-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLexer.cpp
More file actions
79 lines (65 loc) · 1.62 KB
/
Lexer.cpp
File metadata and controls
79 lines (65 loc) · 1.62 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
77
78
79
#include "Lexer.h"
using namespace Lexer;
/*
Tokenizer to split arithmetic operations into tokens.
Given an input string, it separates numbers and identifiers.
Produces manageable tokens for further processing.
*/
std::vector<Token> Lexer::Tokenize(std::string Input) {
std::vector<Token> Tokens;
std::string Stack;
bool IsQuotationMarkPresent = 0;
bool WasQuotationMarkPresent = 0;
bool FirstChar = 1;
bool IsNegative = 0;
for (int i = 0; i < Input.length(); i++) {
char currentChar = Input.at(i);
if (currentChar == '\"')
{
IsQuotationMarkPresent = !IsQuotationMarkPresent;
if (!IsQuotationMarkPresent) WasQuotationMarkPresent = 1;
}
if (WasQuotationMarkPresent) {
Tokens.push_back({ TokenType::IDENTIFIER, Stack });
return Tokens;
}
if (!IsQuotationMarkPresent) {
if (currentChar == '-') {
IsNegative = !IsNegative;
}
if (isspace(currentChar)) {
if (isdigit(Stack[0])) {
Tokens.push_back({ TokenType::NUMBER, (IsNegative ? "-"+Stack : Stack) });
}
else {
Tokens.push_back({ TokenType::IDENTIFIER, Stack });
}
Stack = "";
continue;
}
if (isdigit(currentChar)) {
Stack += currentChar;
}
if (isalpha(currentChar)) {
Stack += currentChar;
}
if (i == Input.length() - 1) {
if (isdigit(Stack[0])) {
Tokens.push_back({ TokenType::NUMBER, (IsNegative ? "-" + Stack : Stack) });
}
else {
Tokens.push_back({ TokenType::IDENTIFIER, Stack });
}
}
}
else {
if (!FirstChar) {
Stack += currentChar;
}
else {
FirstChar = 0;
}
}
}
return Tokens;
}