-
Notifications
You must be signed in to change notification settings - Fork 0
/
Scanner.java
105 lines (90 loc) · 2.13 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
104
105
package lox;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static lox.TokenType.*;
class Scanner {
private final String source;
private final List<Token> tokens = new ArrayList<>();
private int start = 0;
private int current = 0;
private int line = 1;
Scanner(String source){
this.source = source;
}
List<Token> scanTokens() {
while (!isAtEnd()){
start = current;
scanToken();
}
tokens.add(new Token(EOF, "", null, line));
return tokens;
}
private void scanToken(){
char c = advance();
switch (c)
case '(': addToken(LEFT_PAREN); break;
case ')': addToken(RIGHT_PAREN); break;
case '{': addToken(LEFT_BRACE); break;
case '}': addToken(RIGHT_BRACE); break;
case ',': addToken(COMMA); break;
case '.': addToken(DOT); break;
case '-': addToken(MINUS); break;
case '+': addToken(PLUS); break;
case ';': addToken(SEMICOLON); break;
case '*': addToken(STAR); break;
case '!':
addToken(match('=') ? BANG_EQUAL : EQUAL);
break;
case '=':
addToken(match('=') ? EQUAL_EQUAL : EQUAL);
break;
case '>':
addToken(match('=') ? GREATER_EQUAL : GREATER);
break;
case '<':
addToken(match('=') ? LESS_EQUAL : LESS);
break;
case '/':
if(match('/'){
while(peek() != "/n" && !isAtEnd()) advance();
} else {
addToken(SLASH);
}
break;
case ' ':
case '\r':
case '\t': break;
case 'n':
line++;
break;
default:
Lox.error(line, "Unexpected character.");
break;
}
}
private boolean match(char expected){
if(isAtEnd()) return false;
if(source.charAt(current)!=expected) return false;
current++;
return true;
}
private char peek(){
if(isAtEnd()) return '\0';
return source.charAt(current);
}
private boolean isAtEnd(){
return current >= source.length();
}
private char advance() {
return source.charAt(current++);
}
private void addToken(TokenType type){
addToken(type, null);
}
private void addToken(TokenType type, Object literal){
String text = source.substring(start, current);
tokens.add(new Token(type, text, literal, line))'
}
}