-
Notifications
You must be signed in to change notification settings - Fork 0
/
lexer.cpp
103 lines (86 loc) · 2.91 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
#include<bits/stdc++.h>
#include"lexer.h"
#include<fstream>
#include<cctype>
#include"Parser.cpp"
#include"codeGenerator.cpp"
std::vector<lexer> tokenize(std::string& sourcecode){
std::vector<lexer> tokens;
int currentChar=0;
std::string reservedKeyWord[]={"summonsoul","chant"};
while(currentChar<sourcecode.length()){
//if the current character is space or tab , skip it.
if(sourcecode[currentChar]==' ' || sourcecode[currentChar]=='\t'){
currentChar++;
continue;
}
else if(std::isdigit(sourcecode[currentChar])){
//if the current character is a digit
std::string number="";
while(std::isdigit(sourcecode[currentChar])){
number+=sourcecode[currentChar];
currentChar++;
}
tokens.push_back({TokenType::Identifier,number});
continue;
}
else if(sourcecode[currentChar]=='='){
tokens.push_back({TokenType::Assignment,"="});
currentChar++;
continue;
}
else if(sourcecode[currentChar]=='+'){
tokens.push_back({TokenType::Plus,"+"});
currentChar++;
continue;
}
else if(sourcecode[currentChar]=='-'){
tokens.push_back({TokenType::Minus,"-"});
currentChar++;
continue;
}
else if(sourcecode[currentChar]=='*'){
tokens.push_back({TokenType::Multiply,"*"});
currentChar++;
continue;
}
else if(sourcecode[currentChar]=='/'){
tokens.push_back({TokenType::Divide,"/"});
currentChar++;
continue;
}
else if(sourcecode[currentChar]=='('){
tokens.push_back({TokenType::LParen,"("});
currentChar++;
continue;
}
else if(sourcecode[currentChar]==')'){
tokens.push_back({TokenType::RParen,")"});
currentChar++;
continue;
}
else if(isalpha(sourcecode[currentChar])){
//if the current character is a letter
std::string identifier="";
while(isalpha(sourcecode[currentChar]) || std::isdigit(sourcecode[currentChar])){
identifier+=sourcecode[currentChar];
currentChar++;
}
if(std::find(std::begin(reservedKeyWord),std::end(reservedKeyWord),identifier)!=std::end(reservedKeyWord)){
tokens.push_back({TokenType::Keyword,identifier});
}
else{
tokens.push_back({TokenType::Identifier,identifier});
}
continue;
}
else {
if(sourcecode[currentChar]==';'){
tokens.push_back({TokenType::Eol,";"});
currentChar++;
continue;
}
}
}
return tokens;
}