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.



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

#name2symbolHash{String => GrmSymbol} (readonly)

A Hash that maps symbol names to their grammar symbols

Returns:



30
31
32
# File 'lib/rley/syntax/grammar.rb', line 30

def name2symbol
  @name2symbol
end

#rulesArray<Production> (readonly)

The list of production rules for the language.

Returns:

  • (Array<Production>)

    Array of productions for the grammar.



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

def rules
  @rules
end

#start_symbolNonTerminal (readonly)

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

Returns:



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

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.



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

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.



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_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.



55
56
57
# File 'lib/rley/syntax/grammar.rb', line 55

def start_production()
  return rules[0]
end