【问题标题】:Access Associating Methods with Node in Treetop访问关联方法与 Treetop 中的节点
【发布时间】:2011-06-06 16:34:54
【问题描述】:

使用如下定义的语法,为什么我在尝试访问由规则key 创建的节点的val 方法时总是出错?

错误信息是

(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

【问题讨论】:

    标签: ruby parsing dsl treetop


    【解决方案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

    到控制台。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多