Class Dhaka::Grammar
In: ../trunk/lib/dhaka/grammar/grammar.rb
Parent: Object

Abstract base class for grammar specifications.

The following is a grammar specification for simple arithmetic. Precedences are specified as in Yacc - in ascending order of binding strength, with equal-strength symbols on the same level. Production rules are specified for each symbol by specifying the name of the production (used when encoding the Evaluator) and the expansion for that particular production. For example, the production named addition expands the symbol ‘E‘ to the list of symbols [‘E’, ’+’, ‘E’].

 class ArithmeticPrecedenceGrammar < Dhaka::Grammar
   precedences do
     left ['+', '-']
     left ['*', '/']
     nonassoc ['^']

   for_symbol(Dhaka::START_SYMBOL_NAME) do
     expression ['E']

   for_symbol('E') do
     addition ['E', '+', 'E']
     subtraction ['E', '-', 'E']
     multiplication ['E', '*', 'E']
     division ['E', '/', 'E']
     power ['E', '^', 'E']
     literal ['n']
     parenthetized_expression ['(', 'E', ')']
     negated_expression ['-', 'E'], :prec => '*'

In the above grammar, the symbols + and - are declared as being left-associative, meaning that 1 + 2 + 3 is parsed as (1 + 2) + 3 as opposed to 1 + (2 + 3) (right-associativity). The symbol ^ is declared nonassoc which means that expressions such as 2 ^ 3 ^ 4 are not allowed (non-associative). + and - are listed before ^ which means that they bind lower, and an expression such as 2 + 3 ^ 5 will be always be parsed as 2 + (3 ^ 5) and not (2 + 3) ^ 5.


Public Class methods

Used for defining the Production-s for the symbol with name symbol. The block blk is evaluated in the context of a ProductionBuilder.

Returns the set of non-terminal symbols in the grammar.

Used for defining the precedences and associativities of symbols. The block blk is evaluated in the context of a PrecedenceBuilder.

Returns the Production identified by name.

Returns a list of all the Production-s in this grammar.

Returns the grammar symbol identified by name

Returns the set of terminal symbols in the grammar.

Export the grammar to a BNF-like format