This repository has been archived by the owner on Nov 26, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Parser.java
88 lines (78 loc) · 2.44 KB
/
Parser.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
import java.util.LinkedList;
/**
* Class that parses the input string using the built parse table.
*
* @author Logan Blyth, James McCarty, & Robert Rayborn
*
*/
public class Parser
{
public static boolean parse(LinkedList<String> input, ParseTable parseTable)
{
// prepare stack
LinkedList<GrammarRule> stack = new LinkedList<GrammarRule>();
stack.push(parseTable.getDollar());
stack.push(parseTable.getStart());
// set up variables
int tokenNumber = 1;
GrammarRule topRule;
String inputToken;
while (! (stack.isEmpty() && input.isEmpty()) )
{
topRule = stack.peek();
inputToken = input.peek();
// if terminal look up
if(topRule.isTerminal())
{
if(topRule.symbol.equals(inputToken)) // matching input and stack tokens
{
// pop off matching symbols
input.pop();
stack.pop();
// update token number
tokenNumber++;
}
else if(!topRule.equals(EpsilonRule.getEpsilonRule())) // the tokens are mismatched
throw new RuntimeException("\n Parse error at input token " + tokenNumber + ": " +
"Input token " + inputToken +
" does not match with stack token " + topRule.getSymbol() + ".\n " +
currentStackString(stack));
else //the token is epsilon so we should only pop the stack
stack.pop();
}
// if nonterminal add rule to stack
else
{
// get the parse table entry
LinkedList<GrammarRule> expandedRule = parseTable.get( (NonterminalRule) topRule, inputToken);
if(expandedRule == null) // there is no entry in the parse table
throw new RuntimeException("\n Parse error at input token " + tokenNumber + ": " +
"A parse table entry for " + inputToken +
" does not exist for grammar rule "+ topRule.getSymbol() + ".\n " +
currentStackString(stack));
// add the new grammar rules to the stack
stack.pop();
for(int i = expandedRule.size() - 1; i>=0; i--)
{
stack.push(expandedRule.get(i));
}
}
}
// stack and input are both empty
return true;
}
/**\
* Returns a string representing the current stack
* @param list - the stack
* @return - string representation
*/
private static String currentStackString(LinkedList<GrammarRule> list)
{
String ret = " Current Stack: \n ";
for(GrammarRule entry : list)
{
ret += entry.getSymbol() + " \n ";
}
return ret;
}
}