1. General use

This is just an overview, consult the JavaDoc for more details.

1Grammar grammar = new Grammar();                      
 
NonterminalSymbol S = grammar.getNonterminal("S");    
NonterminalSymbol A = grammar.getNonterminal("A");
5NonterminalSymbol B = grammar.getNonterminal("B");
NonterminalSymbol X = grammar.getNonterminal("X");
NonterminalSymbol Y = grammar.getNonterminal("Y");
 
Rule s1 = new Rule(S, A);         
10grammar.addRule(s1);              
 
grammar.addRule(S, B);                                
grammar.addRule(A, TerminalSymbol.ch('a'), X);        
grammar.addRule(A, TerminalSymbol.ch('b'), X);
15grammar.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.