-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.cpp
More file actions
76 lines (67 loc) · 2.51 KB
/
stack.cpp
File metadata and controls
76 lines (67 loc) · 2.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
//
// Created by daze on 08/06/19.
//
#include <algorithm>
#include <sstream>
#include <cstring>
#include "stack.hh"
void Stack::split(std::string str)
{
std::vector<std::string> vec;
std::istringstream is(str);
std::string res;
while (std::getline(is, res, ' ')) // pushing every split word into a temporary vector
vec.push_back(res);
for (auto i = vec.rbegin(); i != vec.rend(); ++i) // using a reverse iterator to fill the queue in the right order
{
_queue.push_front(*i);
}
}
// return true in case of valid input file, false and a message indicating the error line otherwise
bool Stack::loop()
{
std::string line;
std::istringstream is(_str);
std::getline(is, line, '\n');
int i = 1;
while (!_queue.empty()) // Doing the process all over until the queue is empty - only way to have a valid input file
{
// First step is removing the top element of the stack
std::string front = _queue.front();
//std::cout << "FRONT = " << front << std::endl;
//std::cout << "LINE = " << line << std::endl;
_queue.pop_front();
if (isupper(front[0]) != 0) // Checks if we have a non-terminal or terminal
{
std::string token = _table.find(front, line); // Searching the symbol in the table
if (token != "error" && token != "e") // Checking if token is not empty nor an espilon, represented as "e"
split(token); // Splitting the tokens into individual keywords to push into the queue
else if (token != "e")
{
std::cout << "Symbol Table doesn't recognize this pattern at line " << i << std::endl;
std::cout << "Expected: " << front << std::endl;
std::cout << "Got: " << line << std::endl;
return (false);
}
}
else
{
if (front != line) // if our top element of the stack doesn't match what is on the line, the file is not valid
{
std::cout << "Terminal not recognized at line " << i << std::endl;
std::cout << "Expected: " << front << std::endl;
std::cout << "Got: " << line << std::endl;
return (false);
}
std::getline(is, line, '\n'); // Carrying on the process for the next line in the input file
++i;
}
}
std::cout << "Input file is valid" << std::endl;
return (true); // We return true if we get out of the loop, meaning the stack is empty and the file valid
}
Stack::Stack(std::string str) : _str(str){
// initializing the stack with our first element and endmarker
_queue.push_front("$");
_queue.push_front("CODE");
}