Chapter 1. General use
This is just an overview, consult the JavaDoc for more details.
1 |SourceGrammar grammar = new SourceGrammar(options); ①
|②
|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'));
||
ParserGrammar pgrammar = grammar.getCompiledGrammar(S);
20 |⑧
|HygieneReport report = pgrammar.getHygieneReport();
|if (!report.isClean()) { ⑨
|// TODO: deal with undefined, unused, and unproductive items
|}
25 ||
GearleyParser parser = pgrammar.getParser(options);
|⑩
|GearleyResult result = parser.parse("bx");
|⑪
30 |if (result.succeeded()) {
|ParseForest forest = result.getForest(); ⑫
|ParseTree tree = forest.getTree(); ⑬
|⑭
|// TODO: do something with the tree.
35 ||
if (forest.isAmbiguous()) {
|ParseTreeBuilder builder = new ParseTreeBuilde⑮r();
|forest.getTree(builder);
|long totalParses = builder.getParseCount();
40 |// TODO: deal with multiple parses
|}
|} else {
|// TODO: deal with failure
|}
- ①
Create the ParserOptions.
- ②
Create a SourceGrammar.
- ③
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.
- ⑧
Get a parser grammar from the (current state of) the source grammar.
- ⑨
Hygiene problems with a parser 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.