1

val以下のように文法が定義されているのに、ルールによって作成されたノードのメソッドにアクセスしようとするとエラーが発生し続けるのはなぜkeyですか?

エラーメッセージは

(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
4

1 に答える 1

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"

そして印刷します:

foob​​ar

コンソールに。

于 2011-06-07T06:55:25.347 に答える