Using grammar classes

The classes have mostly the same structure as the XML grammar format, and interpreted as the model of the grammar.

Grammar grammar = new Grammar();

Production A = new Production(new Nonterminal("A"));
Production B = new Production(new Nonterminal("B"));

grammar.addProduction(A);
grammar.addProduction(B);

For the definition the class SymbolList is used.

Terminal a = new Terminal("a");
Nonterminal b = new Nonterminal("b");

SymbolList definition = new SymbolList()
definition.addSymbol(a);
definition.addSymbol(b);

A.setDefinition(definition);

B.getDefinition().addSymbol(b);
B.getDefinition().addSymbol(a);

If you are using precedences and/or associativities, you can use the following code.

A.setPrecedence(a);

grammar.setAssociativity(B, Associativity.RIGHT);

As last step you should always validate your model. You can do this simply by using the validate method. Which returns a list of violations. If this list is empty your grammar is valid.

Violations violations = grammar.validate();

if (violations.getViolationCount()>0)
  throw new IllegalStateException();
by Stephan Michels