-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlexer.cpp
More file actions
131 lines (108 loc) · 2.65 KB
/
lexer.cpp
File metadata and controls
131 lines (108 loc) · 2.65 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
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
130
131
#include "lexer.h"
#include "word.h"
#include "type.h"
#include "num.h"
#include "real.h"
#include <iostream>
int Lexer::line = 1;
Lexer::Lexer(std::string input){
_input = input;
Lexer::line = 0;
reserve(new Word("if",IF));
reserve(new Word("else",ELSE));
reserve(new Word("while",WHILE));
reserve(new Word("do",DO));
reserve(new Word("break",BREAK));
reserve(Word::word(TRUE));
reserve(Word::word(FALSE));
reserve(Type::Int());
reserve(Type::Float());
reserve(Type::Char());
reserve(Type::Bool());
_currentPos = 0;
peek = ' ';
}
Lexer::~Lexer()
{
}
void Lexer::reserve(Word *w)
{
this->words[w->lexeme()] = w;
}
void Lexer::readch()
{
if(_currentPos < _input.size()){
peek = _input[_currentPos++];
}else{
peek = EOF;
}
// std::cout<<"Current Char:";
// std::cout<<peek<<std::endl;
}
bool Lexer::readch(char c)
{
readch();
if( peek != c) return false;
peek = ' ';
return true;
}
Token* Lexer::scan()
{
for(;;readch()){
if( peek == ' ' || peek == '\t') continue;
else if( peek == '\n') Lexer::line = Lexer::line + 1;
else break;
}
switch (peek)
{
case '&':
if( readch('&') ) return Word::word(AND); else return new Token((Tag)'&');
case '|':
if( readch('|') ) return Word::word(OR); else return new Token((Tag)'|');
case '=':
if( readch('=') ) return Word::word(EQ); else return new Token((Tag)'=');
case '!':
if( readch('=') ) return Word::word(NE); else return new Token((Tag)'!');
case '<':
if( readch('=') ) return Word::word(LE); else return new Token((Tag)'<');
case '>':
if( readch('=') ) return Word::word(GE); else return new Token((Tag)'>');
default:
break;
}
if(isdigit(peek)){
int v = 0;
do{
v = 10*v + peek - '0';
readch();
}while(isdigit(peek));
if(peek != ' ') return new Num(v);
float x = v;
float d = 10;
while(true){
readch();
if(!isdigit(peek)) break;
x = x + (peek-'0')/d;
d = d * 10;
}
return new Real(x);
}
if(isalpha(peek)){
std::string b = "";
do{
b += peek;
readch();
}while(isalpha(peek) || isdigit(peek));
std::string &s = b;
Word *w = words[s];
if(w != NULL){
return w;
}
w = new Word(s,ID);
words[s] = w;
return w;
}
Token *tok = new Token(peek);
peek = ' ';
return tok;
}