Class: Rley::Syntax::Grammar

Inherits:
Object
  • Object
show all
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

Instance Method Summary collapse

Constructor Details

#initialize(theProductions) ⇒ Grammar

Returns a new instance of Grammar.

Parameters:

  • theProductions (Array<Production>)

    productions of the 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

#name2symbolHash{String => GrmSymbol} (readonly)

A Hash that maps symbol names to their grammar symbols

Returns:



32
33
34
# File 'lib/rley/syntax/grammar.rb', line 32

def name2symbol
  @name2symbol
end

#rulesArray<Production> (readonly)

The list of production rules for the language.

Returns:

  • (Array<Production>)

    Array of productions for the grammar.



24
25
26
# File 'lib/rley/syntax/grammar.rb', line 24

def rules
  @rules
end

#start_symbolNonTerminal (readonly)

A non-terminal symbol that represents all the possible strings in the language.

Returns:



20
21
22
# File 'lib/rley/syntax/grammar.rb', line 20

def start_symbol
  @start_symbol
end

#symbolsArray<GrmSymbol> (readonly)

The list of grammar symbols in the language.

Returns:

  • (Array<GrmSymbol>)

    The terminal and non-terminal symbols.



28
29
30
# File 'lib/rley/syntax/grammar.rb', line 28

def symbols
  @symbols
end

Instance Method Details

#non_terminalsArray

Returns The list of non-terminals in the grammar.

Returns:

  • (Array)

    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_productionProduction

Returns The start production of the grammar (i.e. the rule that specifies the syntax for the start symbol.

Returns:

  • (Production)

    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