Class: NonTerminal

Inherits:
Object
  • Object
show all
Defined in:
lib/cofgratx/cfg/non_terminal.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*rules) ⇒ NonTerminal

Returns a new instance of NonTerminal.



4
5
6
7
8
# File 'lib/cofgratx/cfg/non_terminal.rb', line 4

def initialize *rules
  validate_list_of_rules *rules
  @rules = rules.to_a
  @rules.uniq!{|r| [r.rule, r.translation]}
end

Instance Attribute Details

#rulesObject (readonly)

Returns the value of attribute rules.



2
3
4
# File 'lib/cofgratx/cfg/non_terminal.rb', line 2

def rules
  @rules
end

Instance Method Details

#add_rules(*rules) ⇒ Object



10
11
12
13
14
# File 'lib/cofgratx/cfg/non_terminal.rb', line 10

def add_rules *rules
  validate_list_of_rules *rules
  @rules.push *rules
  @rules.uniq!{|r| [r.rule, r.translation]}
end

#extract(string) ⇒ Object



23
24
25
26
27
28
29
30
31
32
# File 'lib/cofgratx/cfg/non_terminal.rb', line 23

def extract string
  matches = @rules.inject([]) do |matches, rule|
    rule_matches = rule.extract string
    matches.concat rule_matches if rule_matches.first[0]
    matches
  end

  return [ [nil, string, [[]]] ] if matches.length == 0
  matches
end

#match?(string) ⇒ Boolean

Returns:

  • (Boolean)


16
17
18
19
20
21
# File 'lib/cofgratx/cfg/non_terminal.rb', line 16

def match? string
  @rules.each do |rule|
    return true if rule.match? string
  end
  false
end

#translate(string) ⇒ Object



34
35
36
37
38
39
40
41
42
43
# File 'lib/cofgratx/cfg/non_terminal.rb', line 34

def translate string
  translations = @rules.inject([]) do |translations, rule|
    rule.translate( string ).each do |translation, remainder|
      translations << [translation, remainder] if translation and remainder
    end
    translations
  end
  return [ [nil, string] ] if translations.length == 0
  translations
end