-
Notifications
You must be signed in to change notification settings - Fork 0
/
Scanner.java
103 lines (82 loc) · 2.38 KB
/
Scanner.java
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
package com.ayomideoyekanmi.explanck.interpreter;
import java.util.ArrayList;
import java.util.List;
/**
* @author: aoyekanmi
* @date: 11/03/2022
*/
public class Scanner {
private final String source;
private final List<Token> tokens = new ArrayList<>();
private int start = 0;
private int current = 0;
Scanner(String source) {
this.source = source;
}
List<Token> scanTokens() {
while (!isAtEnd()) {
start = current;
scanToken();
}
return tokens;
}
private void scanToken() {
char c = peek();
advance();
switch (c) {
// @formatter:off
case '(': add(TokenType.LEFT_PAREN); break;
case ')': add(TokenType.RIGHT_PAREN); break;
case '*': add(TokenType.STAR); break;
case '/': add(TokenType.SLASH); break;
case '+': add(TokenType.PLUS); break;
case '-': add(TokenType.MINUS); break;
case '^': add(TokenType.POWER); break;
// @formatter:on
case ' ':
case '\r':
case '\t':
break;
default:
if (isDigit(c)) {
addNumberToken();
} else {
// We should throw this
Explanck.error("Unexpected character: " + c);
}
}
}
private boolean isAtEnd() {
return current >= source.length();
}
private boolean isDigit(char c) {
return c >= '0' && c <= '9';
}
private char peek() {
if (isAtEnd()) return '\0';
return source.charAt(current);
}
private char peekNext() {
if (current + 1 >= source.length()) return '\0';
return source.charAt(current + 1);
}
private void advance() {
current++;
}
private void add(TokenType type) {
add(type, null);
}
private void add(TokenType type, Object literal) {
tokens.add(new Token(type, literal));
}
private void addNumberToken() {
while (isDigit(peek())) advance();
// Look for fractional part
if (peek() == '.' && isDigit(peekNext())) {
// Consume the '.'
advance();
while (isDigit(peek())) advance();
}
add(TokenType.NUMBER, Double.parseDouble(source.substring(start, current)));
}
}