Class: Dendroid::Syntax::Rule

Inherits:
Object
  • Object
show all
Defined in:
lib/dendroid/syntax/rule.rb

Overview

A specialization of the Rule class. A choice is a rule with multiple rhs

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(theLhs, alt) ⇒ Rule

Create a Rule instance.



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

def initialize(theLhs, alt)
  @head = valid_head(theLhs)
  @alternatives = valid_alternatives(alt)
end

Instance Attribute Details

#alternativesArray<Dendroid::Syntax::SymbolSeq> (readonly)



13
14
15
# File 'lib/dendroid/syntax/rule.rb', line 13

def alternatives
  @alternatives
end

#headDendroid::Syntax::NonTerminal (readonly) Also known as: lhs



9
10
11
# File 'lib/dendroid/syntax/rule.rb', line 9

def head
  @head
end

Instance Method Details

#==(other) ⇒ Boolean

Equality operator Two production rules are equal when their head and alternatives are equal.



55
56
57
58
59
# File 'lib/dendroid/syntax/rule.rb', line 55

def ==(other)
  return true if equal?(other)

  (head == other.head) && (alternatives == other.alternatives)
end

#empty?Boolean

Predicate method to check whether the rule has at least one empty alternative.



42
43
44
# File 'lib/dendroid/syntax/rule.rb', line 42

def empty?
  alternatives.any?(&:empty?)
end

#nonterminalsArray<Dendroid::Syntax::NonTerminal>

The set of all non-terminal symbols that occur in the rhs.



72
73
74
# File 'lib/dendroid/syntax/rule.rb', line 72

def nonterminals
  rhs_symbols.reject(&:terminal?)
end

#productive?Boolean

Predicate method to check whether the choice rule body is productive. It is productive when at least one of its alternative is productive.



32
33
34
35
36
37
38
# File 'lib/dendroid/syntax/rule.rb', line 32

def productive?
  productive_alts = alternatives.select(&:productive?)
  return false if productive_alts.empty?

  @productive = Set.new(productive_alts)
  head.productive = true
end

#rhsArray<Dendroid::Syntax::SymbolSeq>

Returns an array with the symbol sequence of its alternatives



48
49
50
# File 'lib/dendroid/syntax/rule.rb', line 48

def rhs
  alternatives
end

#rhs_symbolsArray<Dendroid::Syntax::GrmSymbol>

The set of all grammar symbols that occur in the rhs.



63
64
65
66
67
68
# File 'lib/dendroid/syntax/rule.rb', line 63

def rhs_symbols
  symbols = rhs.reduce([]) do |result, alt|
    result.concat(alt.members)
  end
  symbols.uniq
end

#terminalsArray<Dendroid::Syntax::Terminal>

The set of all terminal symbols that occur in the rhs.



78
79
80
# File 'lib/dendroid/syntax/rule.rb', line 78

def terminals
  rhs_symbols.select(&:terminal?)
end

#to_sString

Return the text representation of the choice



25
26
27
# File 'lib/dendroid/syntax/rule.rb', line 25

def to_s
  "#{head} => #{alternatives.join(' | ')}"
end