-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlexer.cpp
More file actions
62 lines (51 loc) · 1.37 KB
/
Copy pathlexer.cpp
File metadata and controls
62 lines (51 loc) · 1.37 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
#include "lexer.h"
#include <stdexcept>
#include <cctype>
#include <iostream>
Lexer::Lexer(const std::string& src) : input(src) {}
char Lexer::peek() {
return (pos < input.size() ? input[pos] : '\0');
}
char Lexer::get() {
return (pos < input.size() ? input[pos++] : '\0');
}
void Lexer::skipWhiteSpace(){
while(isspace(peek())) get();
}
Token Lexer::nextToken() {
skipWhiteSpace();
char c = peek();
if(isdigit(c)) {
std::string num;
while(isdigit(peek())) num += get();
return {TokenType::NUMBER, num};
}
if(isalpha(c)) { // IDENT
std::string ident;
while(isalnum(peek())) ident += get();
return {TokenType::IDENT, ident};
}
switch(c) {
case '+': get(); return {TokenType::PLUS, "+"};
case '-': get(); return {TokenType::MINUS, "-"};
case '*': get(); return {TokenType::MUL, "*"};
case '/': get(); return {TokenType::DIV, "/"};
case '^': get(); return {TokenType::POW, "^"};
case '(': get(); return {TokenType::LPAREN, "("};
case ')': get(); return {TokenType::RPAREN, ")"};
case '\0': return {TokenType::END, "EOF"};
}
throw std::runtime_error(std::string("Unexpected character: ") + c);
}
// int main(){
// std::string input = "2+x^2+5";
// Lexer lex(input);
// do{
// auto current = lex.nextToken();
// std::cout << current.text << std::endl;
// if(current.type == TokenType::END) {
// break;
// }
// }while(true);
// return 0;
// }