Chapter 1General 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 ParseTreeBuilder();
   |        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.