开发者

Access Associating Methods with Node in Treetop

开发者 https://www.devze.com 2023-03-10 14:10 出处:网络
With the grammar defined as below, why I keep get error while try to access the val method of nodes created by rule key?

With the grammar defined as below, why I keep get error while try to access the val method of nodes created by rule key?

The error message is

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

The grammar is

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

The test code is

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


You can access the contents of the rule itself through text_value. The grammar:

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

which can be tested with:

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

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

and will print:

foobar

to the console.

0

精彩评论

暂无评论...
验证码 换一张
取 消