简体   繁体   English

树梢忽略语法中定义的方法

[英]Treetop ignores methods defined in grammar

I'm trying to parse a percentage with treetop. 我正在尝试使用树梢解析百分比。 I wrote the following grammar: 我写了以下语法:

grammar Numerals
  rule percentage
    (decimal "%") {
      def to_f
        decimal.to_f / 100
      end
    }
  end

  rule decimal
    sign [0-9]+ '.' [0-9]* {
      def to_f
        text_value.to_f
      end
    }
  end

  rule sign
    ('+'/'-')? 
  end
end

This matches correctly, but for some reason the to_f method on the root node is missing in the result. 这正确匹配,但是由于某种原因,结果中缺少根节点上的to_f方法。

When I checked the code generated by tt, it had created two modules for the percentage nodes, only one of which was used in the rest of the code: 当我检查tt生成的代码时,它为百分比节点创建了两个模块,其余代码仅使用其中一个:

module Percentage0
  def decimal
    elements[0]
  end
end

module Percentage1
  def to_f
    decimal.to_f / 100
  end
end

Percentage1 never appears anywhere else in the code, while Percentage0 is used on the correct nodes Percentage1永远不会出现在代码中的其他任何地方,而Percentage0用于正确的节点

r0 = instantiate_node(SyntaxNode,input, i0...index, s0)
r0.extend(Percentage0)

On the other hand, the to_f method on decimal works fine (also two modules, but both are used to extend the node). 另一方面, decimalto_f方法也可以正常工作(也有两个模块,但是都用于扩展节点)。 I can't find what is different about its definition, that causes this. 我找不到它的定义有什么不同,这导致了这一点。

I think you just need to remove the parentheses from the root rule. 我认为您只需要从根规则中删除括号即可。

Also, for the decimal rule you should probably use a + instead of a * after the decimal; 另外,对于十进制规则,您应该在小数点后使用+而不是* you'll want at least one number there. 您至少要有一个电话号码。

grammar Numerals
  rule percentage
    decimal "%" {
      def to_f
        decimal.to_f / 100
      end
    }
  end

  rule decimal
    sign [0-9]+ '.' [0-9]+ {
      def to_f
        text_value.to_f
      end
    }
  end

  rule sign
    ('+'/'-')? 
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM