-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScanner.java
More file actions
66 lines (63 loc) · 2.57 KB
/
Scanner.java
File metadata and controls
66 lines (63 loc) · 2.57 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
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
public class Scanner{
SymbolTable lexemes;
public Scanner(){
lexemes = new SymbolTable();
}
public ArrayList<IdEntry> scan(String filename){
ArrayList<IdEntry> tokens = new ArrayList<IdEntry>();
try{
BufferedReader br = new BufferedReader(new FileReader(filename));
String line;
int lineNum = 0;
while((line = br.readLine()) != null){
lineNum++;
line = line.trim();
if(line.startsWith("//")) continue; //skip comments
String token = "";
for(int i = 0 ; i < line.length() ; ){
do{
token += line.charAt(i++);
while(token.equals(" ") && i < line.length()){
token = "" + line.charAt(i++);
}
if(i >= line.length()) break; // if i exceeds the length, process the temporary string formed
if(token.startsWith("\"") || token.startsWith("\'")){
while(true){
char nextChar = line.charAt(i++);
token += nextChar;
if(nextChar == token.charAt(0))
break;
}
break;
}
char lookahead = line.charAt(i);
if(lookahead == ' ')
break;
if(lookahead == '.'){
token += lookahead;
i++;
if(i >= line.length()) break;
lookahead = line.charAt(i);
}
boolean currentMatch = lexemes.containsKey(token) || lexemes.hasMatch(token);
if(currentMatch && !lexemes.containsKey(token + lookahead) && !lexemes.hasMatch(token + lookahead))
break;
}while(true);
IdEntry tokenDetails = lexemes.checkToken(token, lineNum);
if(tokenDetails != null) {
tokens.add(tokenDetails);
token = "";
}
}
}
}catch(Exception e){
e.printStackTrace();
}
IdEntry terminal = new IdEntry("$", 1);
tokens.add(terminal);
return tokens;
}
}