Chapter 1. General use
This is just an overview, consult the JavaDoc for more details.
1 |Grammar grammar = new Grammar(); ①
||
NonterminalSymbol S = grammar.getNonterminal("S"); ②
|NonterminalSymbol A = grammar.getNonterminal("A");
5 |NonterminalSymbol B = grammar.getNonterminal("B");
|NonterminalSymbol X = grammar.getNonterminal("X");
|NonterminalSymbol Y = grammar.getNonterminal("Y");
||
Rule s1 = new Rule(S, A); ③
10 |grammar.addRule(s1); ④
||
grammar.addRule(S, B); ⑤
|grammar.addRule(A, TerminalSymbol.ch('a'), X); ⑥
|grammar.addRule(A, TerminalSymbol.ch('b'), X);
15 |grammar.addRule(B, TerminalSymbol.ch('b'), X);
|grammar.addRule(X, TerminalSymbol.ch('x'));
|grammar.addRule(Y, TerminalSymbol.ch('y'));
||
grammar.close(); ⑦
20 ||
HygieneReport report = grammar.checkHygiene(S); ⑧
|if (!report.isClean()) {
|// TODO: deal with undefined,
|// unused, and unproductive items
25 |}
||
EarleyParser parser = grammar.getParser(S); ⑨
||
EarleyResult result = parser.parse("bx"); ⑩
30 ||
if (result.succeeded()) { ⑪
|ParseForest forest = result.getForest(); ⑫
|ParseTree tree = forest.parse(); ⑬
|35 |
// TODO: do something with the tree.
||
if (forest.isAmbiguous()) { ⑭
|long totalParses = forest.getTotalParses();
|// TODO: deal with multiple parses
40 |}
|} else {
|// TODO: deal with failure
|}
- ①
Create a Grammar.
- ②
Use the grammar to create nonterminal symbols.
- ③
Create rules mapping each nonterminal symbol to zero or more other symbols.
- ④
Add the rules to the grammar.
- ⑤
You can also just use the
addRule
method to add the symbols and their mappings directly.- ⑥
Several flavors of TerminalSymbol are supported out-of-the-box and the set of Tokens is extensible.
- ⑦
Close the grammar when you’re finished adding to it. After a grammar is closed, it cannot be modified.
- ⑧
Hygiene problems with a closed grammar will generate warning messages through the logging framework. Hygiene problems include undefined or unused symbols as well as unproductive symbols and rules.
- ⑨
Create a parser.
- ⑩
Parse some input.
- ⑪
Examine the results.
- ⑫
Obtain the forest.
- ⑬
Get the (first) parse tree.
- ⑭
If the parse was ambiguous, you can get additional parse trees.