Class: Rley::Syntax::Grammar
- Inherits:
-
Object
- Object
- Rley::Syntax::Grammar
- Defined in:
- lib/rley/syntax/grammar.rb
Overview
A grammar specifies the syntax of a language. Formally, a grammar has:
- One start symbol,
- One or more other production rules,
- Each production has a rhs that is a sequence of grammar symbols.
- Grammar symbols are categorized into: -terminal symbols -non-terminal symbols
Instance Attribute Summary collapse
-
#name2symbol ⇒ Hash{String => GrmSymbol}
readonly
A Hash that maps symbol names to their grammar symbols.
-
#rules ⇒ Array<Production>
readonly
The list of production rules for the language.
-
#start_symbol ⇒ NonTerminal
readonly
A non-terminal symbol that represents all the possible strings in the language.
-
#symbols ⇒ Array<GrmSymbol>
readonly
The list of grammar symbols in the language.
Instance Method Summary collapse
-
#initialize(theProductions) ⇒ Grammar
constructor
A new instance of Grammar.
-
#non_terminals ⇒ Array
The list of non-terminals in the grammar.
-
#start_production ⇒ Production
The start production of the grammar (i.e. the rule that specifies the syntax for the start symbol..
Constructor Details
#initialize(theProductions) ⇒ Grammar
Returns a new instance of Grammar.
35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/rley/syntax/grammar.rb', line 35 def initialize(theProductions) @rules = [] @symbols = [] @name2symbol = {} valid_productions = validate_productions(theProductions) valid_productions.each do |prod| add_production(prod) name_production(prod) end diagnose # TODO: use topological sorting @start_symbol = valid_productions[0].lhs end |
Instance Attribute Details
#name2symbol ⇒ Hash{String => GrmSymbol} (readonly)
A Hash that maps symbol names to their grammar symbols
32 33 34 |
# File 'lib/rley/syntax/grammar.rb', line 32 def name2symbol @name2symbol end |
#rules ⇒ Array<Production> (readonly)
The list of production rules for the language.
24 25 26 |
# File 'lib/rley/syntax/grammar.rb', line 24 def rules @rules end |
#start_symbol ⇒ NonTerminal (readonly)
A non-terminal symbol that represents all the possible strings in the language.
20 21 22 |
# File 'lib/rley/syntax/grammar.rb', line 20 def start_symbol @start_symbol end |
#symbols ⇒ Array<GrmSymbol> (readonly)
The list of grammar symbols in the language.
28 29 30 |
# File 'lib/rley/syntax/grammar.rb', line 28 def symbols @symbols end |
Instance Method Details
#non_terminals ⇒ Array
Returns The list of non-terminals in the grammar.
51 52 53 |
# File 'lib/rley/syntax/grammar.rb', line 51 def non_terminals @non_terminals ||= symbols.select { |s| s.kind_of?(NonTerminal) } end |
#start_production ⇒ Production
Returns The start production of the grammar (i.e. the rule that specifies the syntax for the start symbol.
57 58 59 |
# File 'lib/rley/syntax/grammar.rb', line 57 def start_production return rules[0] end |