-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParser.java
More file actions
93 lines (75 loc) · 2.43 KB
/
Parser.java
File metadata and controls
93 lines (75 loc) · 2.43 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
//package edu.osu.lisp;
public class Parser {
Tokenizer tokenizer = new Tokenizer();
String expression = "";
public Parser(String expression) {
this.expression = expression;
this.tokenizer.tokenize(this.expression);
}
public SExp input(String token) throws interException {
String nextToken = token;
if (nextToken.equals("")) {
nextToken = tokenizer.ckNextToken();
}
if (nextToken.equals(")")) {
throw new interException("start with )");
}
if (nextToken.equals(".")) {
throw new interException("single dot");
}
if (nextToken.equals("(")) { //Type 1
nextToken = tokenizer.ckNextToken();
if (nextToken.equals(")")) { //corner case:()
return new SExp("NIL");
}
SExp left = input(nextToken);
if (left == null) {
return null;
}
SExp right;
nextToken = tokenizer.ckNextToken();
if (nextToken.equals(".")) { //Type 3
right = input("");
nextToken = tokenizer.ckNextToken();
if (!nextToken.equals(")")) {
throw new interException("missing right parenthesis");
}
}
else {
right = input2(nextToken);
}
return new SExp(left, right);
}
if (nextToken.matches(Patterns.NUMERIC_ATOM) || nextToken.matches(Patterns.DIGIT)) {
return new SExp(Integer.parseInt(nextToken));
}
else if (nextToken.matches(Patterns.LITERAL)){
return new SExp(nextToken);
}
else {
throw new interException("invalid symbol");
}
}
public SExp input2(String token) throws interException {
if (token.equals(")")) {
return new SExp("NIL");
}
SExp left = input(token);
if (left == null) {
return null;
}
SExp right = input2(tokenizer.ckNextToken());
if (right == null) {
return null;
}
return new SExp(left, right);
}
public boolean check() {
try {
tokenizer.ckNextToken();
return false;
} catch (interException ex) {
return ex.getMessage().equals("incomplete expression");
}
}
}