2011-06-06 41 views
1

在下面的語法定義的情況下,爲什麼在嘗試訪問由規則key創建的節點的val方法時出現錯誤?Treetop中訪問節點的關聯方法

的錯誤消息是

(eval):168:in `val': undefined local variable or method `key' 
for #<Treetop::Runtime::SyntaxNode:0x00000101b1e160> (NameError) 

語法是

grammar Command 
    rule create_command 
    'create' space pair { 
     def val 
     pair.val 
     end 
    } 
    end 

    rule pair 
    key space? '=' space? '"' value '"' { 
     def val 
     { key.val => value.val } 
     end 
    } 
    end 

    rule key 
    [A-Za-z_] [A-Za-z0-9_]* { 
     def val 
     key.to_sym 
     end 
    } 
    end 

    rule value 
    ('\\"'/[^"])+ { 
     def val 
     value.to_s 
     end 
    } 
    end 

    rule space 
    [ \t]+ 
    end 
end 

測試代碼是

require 'treetop' 
Treetop.load "command" 
p = CommandParser.new 
r = p.parse 'create name = "foobar"' 
p r.val 

回答

1

您可以通過訪問text_value規則本身的內容。語法:

grammar Command 

    rule create_command 
    'create' space pair { 
     def val 
     pair.val 
     end 
    } 
    end 

    rule pair 
    key space? '=' space? '"' value '"' { 
     def val 
     { key.val => value.val } 
     end 
    } 
    end 

    rule key 
    [A-Za-z_] [A-Za-z0-9_]* { 
     def val 
     text_value 
     end 
    } 
    end 

    rule value 
    ('\\"'/[^"])+ { 
     def val 
     text_value 
     end 
    } 
    end 

    rule space 
    [ \t]+ 
    end 

end 

其可與待測試:

require 'rubygems' 
require 'treetop' 
require 'polyglot' 
require 'command' 

parser = CommandParser.new 
pair = parser.parse('create name = "foobar"').val 
print pair['name'], "\n" 

和將打印:

foobar

到控制檯。