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.
33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/rley/syntax/grammar.rb', line 33 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
30 31 32 |
# File 'lib/rley/syntax/grammar.rb', line 30 def name2symbol @name2symbol end |
#rules ⇒ Array<Production> (readonly)
The list of production rules for the language.
22 23 24 |
# File 'lib/rley/syntax/grammar.rb', line 22 def rules @rules end |
#start_symbol ⇒ NonTerminal (readonly)
A non-terminal symbol that represents all the possible strings in the language.
18 19 20 |
# File 'lib/rley/syntax/grammar.rb', line 18 def start_symbol @start_symbol end |
#symbols ⇒ Array<GrmSymbol> (readonly)
The list of grammar symbols in the language.
26 27 28 |
# File 'lib/rley/syntax/grammar.rb', line 26 def symbols @symbols end |
Instance Method Details
#non_terminals ⇒ Array
Returns The list of non-terminals in the grammar.
49 50 51 |
# File 'lib/rley/syntax/grammar.rb', line 49 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.
55 56 57 |
# File 'lib/rley/syntax/grammar.rb', line 55 def start_production() return rules[0] end |