Question

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.

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:

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

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). I can't find what is different about its definition, that causes this.

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top