Class: Grammar
- Inherits:
-
Object
- Object
- Grammar
- Defined in:
- lib/cofgratx/cfg/grammar.rb
Instance Attribute Summary collapse
-
#rules ⇒ Object
readonly
Returns the value of attribute rules.
Instance Method Summary collapse
- #add_rules(non_terminal_symbol, *rules) ⇒ Object
- #clear_rule(non_terminal_symbol) ⇒ Object
-
#initialize ⇒ Grammar
constructor
A new instance of Grammar.
- #match?(string, starting_non_terminal) ⇒ Boolean
- #translate(string, starting_non_terminal) ⇒ Object
Constructor Details
#initialize ⇒ Grammar
Returns a new instance of Grammar.
4 5 6 |
# File 'lib/cofgratx/cfg/grammar.rb', line 4 def initialize @rules = { } end |
Instance Attribute Details
#rules ⇒ Object (readonly)
Returns the value of attribute rules.
2 3 4 |
# File 'lib/cofgratx/cfg/grammar.rb', line 2 def rules @rules end |
Instance Method Details
#add_rules(non_terminal_symbol, *rules) ⇒ Object
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
# File 'lib/cofgratx/cfg/grammar.rb', line 8 def add_rules non_terminal_symbol, *rules @rules[non_terminal_symbol.to_sym] ||= NonTerminal.new good_rules = [] rules.each do |rule, translation| 0.upto(rule.size) do |index| if rule[index].class == Symbol rule[index] = (@rules[rule[index]] ||= NonTerminal.new) end end new_rule = Rule.new( rule, translation ) if new_rule.valid_translation? good_rules << Rule.new( rule, translation ) else raise GrammarError.new(new_rule.) end end @rules[non_terminal_symbol.to_sym].add_rules *good_rules end |
#clear_rule(non_terminal_symbol) ⇒ Object
29 30 31 |
# File 'lib/cofgratx/cfg/grammar.rb', line 29 def clear_rule non_terminal_symbol @rules[non_terminal_symbol.to_sym] = NonTerminal.new end |
#match?(string, starting_non_terminal) ⇒ Boolean
33 34 35 36 37 38 |
# File 'lib/cofgratx/cfg/grammar.rb', line 33 def match? string, starting_non_terminal #the grammar only matches if the string has no remainder raise "Unknown initial non terminal: '#{starting_non_terminal}'" unless @rules[starting_non_terminal.to_sym] candidate_matches = @rules[starting_non_terminal.to_sym].extract(string) candidate_matches.select{|m| m[1] == "" and m[0] != nil}.size > 0 end |
#translate(string, starting_non_terminal) ⇒ Object
40 41 42 43 44 |
# File 'lib/cofgratx/cfg/grammar.rb', line 40 def translate string, starting_non_terminal raise "Unknown initial non terminal: '#{starting_non_terminal}'" unless @rules[starting_non_terminal.to_sym] candidate_matches = @rules[starting_non_terminal.to_sym].translate(string) candidate_matches.select{|m| m[1] == "" and m[0] != nil} end |