-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlexer.cpp
129 lines (122 loc) · 2.64 KB
/
lexer.cpp
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
int check_letter(char c)
{
if(isalpha(c))
{
return 1;
}
else if(isdigit(c))
{
return 2;
}
else if(ispunct(c))
{
return 3;
}
else
{
return 0;
}
}
void check_state(char c, int &state, string &temp, vector<string> keywords, vector<string> tokens)
{
switch(state)
{
case 2:
for(int i = 0; i < keywords.size(); i++)
{
if(temp == keywords[i])
{
cout << fixed << left << setw(15) << tokens[0] << "\t" << temp << endl;
state = 0;
temp = "";
break;
}
}
if(ispunct(c))
{
if(c == '$')
{
temp += c;
cout << fixed << left << setw(15) << tokens[1] << "\t" << temp << endl;
state = 0;
temp = "";
}
else
{
cout << fixed << left << setw(15) << tokens[1] << "\t" << temp << endl;
temp = "";
state = 4;
check_state(c, state, temp, keywords, tokens);
}
}
break;
case 3:
if(ispunct(c))
{
temp = "";
state = 4;
check_state(c, state, temp, keywords, tokens);
}
else
{
cout << fixed << left << setw(15) << tokens[2] << "\t" << temp << endl;
temp = "";
state = 0;
}
break;
case 4:
cout << fixed << left << setw(15) << tokens[3] << "\t" << c << endl;
state = 0;
break;
}
}
void state_change(char c, int &state, string &temp, vector<string> keywords, vector<string> tokens)
{
int CL = check_letter(c);
switch(CL)
{
case 0:
if(state != 0) { state_change(c, state, temp, keywords, tokens); }
break;
case 1:
if(state == 0 || state == 2){ temp += c; state = 2; }
check_state(c, state, temp, keywords, tokens);
break;
case 2:
if(state == 0 || state == 3) { temp += c; state = 3; }
check_state(c, state, temp, keywords, tokens);
break;
case 3:
if(state == 0 || state == 4) { state = 4; }
check_state(c, state, temp, keywords, tokens);
}
}
int main()
{
char c;
int state = 0; // Initial state
bool change_state = false;
string temp = "";
vector<string> keywords = {"function", "return", "int"};
vector<string> tokens = {"Keyword", "Identifier", "Integer", "Separator", "Operator"};
fstream file;
file.open("test.txt", ios::in);
if(file.is_open())
{
while(file >> c)
{
state_change(c, state, temp, keywords, tokens);
}
}
else
{
cerr << "Cannot open test.txt" << endl;
}
return 0;
}