Class: Dendroid::Syntax::Grammar

Inherits:
Object
  • Object
show all
Defined in:
lib/dendroid/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

Instance Method Summary collapse

Constructor Details

#initialize(terminals) ⇒ Grammar

Constructor.

Parameters:



35
36
37
38
39
# File 'lib/dendroid/syntax/grammar.rb', line 35

def initialize(terminals)
  @symbols = []
  @name2symbol = {}
  add_terminals(terminals)
end

Instance Attribute Details

#name2symbolHash{String => Dendroid::Syntax::GrmSymbol} (readonly)

A Hash that maps symbol names to their grammar symbols

Returns:



26
27
28
# File 'lib/dendroid/syntax/grammar.rb', line 26

def name2symbol
  @name2symbol
end

#nonterm2productionsHash{Dendroid::Syntax::GrmSymbol => Dendroid::Syntax::Rule} (readonly)

TODO: make nonterminal - rules one-to-one A Hash that maps symbol names to their grammar symbols



31
32
33
# File 'lib/dendroid/syntax/grammar.rb', line 31

def nonterm2productions
  @nonterm2productions
end

#rulesArray<Dendroid::Syntax::Rule> (readonly)

The list of production rules for the language.

Returns:



22
23
24
# File 'lib/dendroid/syntax/grammar.rb', line 22

def rules
  @rules
end

#symbolsArray<Dendroid::Syntax::GrmSymbol> (readonly)

The list of grammar symbols in the language.

Returns:



18
19
20
# File 'lib/dendroid/syntax/grammar.rb', line 18

def symbols
  @symbols
end

Instance Method Details

#add_rule(rule) ⇒ Object

Add a rule to the grammar

Parameters:



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/dendroid/syntax/grammar.rb', line 43

def add_rule(rule)
  if @rules.nil?
    @rules = []
    @nonterm2productions = {}
  end
  # TODO: add test for duplicate productions
  if nonterm2productions[rule.head]&.include? rule
    raise StandardError, "Production rule '#{production}' appears more than once in the grammar."
  end

  add_symbol(rule.head)
  rule.nonterminals.each { |nonterm| add_symbol(nonterm) }
  rules << rule
  nonterm2productions[rule.head] = [] unless nonterm2productions.include? rule.head
  nonterm2productions[rule.head] << rule
end

#complete!Object

A event method to notify the grammar that all grammar rules have been entered. The grammar, in turn, reacts by validating the production rules.



69
70
71
72
# File 'lib/dendroid/syntax/grammar.rb', line 69

def complete!
  validate
  analyze
end

#start_symbolDendroid::Syntax::NonTerminal

Return the start symbol for the language



62
63
64
# File 'lib/dendroid/syntax/grammar.rb', line 62

def start_symbol
  rules.first.lhs
end