mirosval
mirosval

Reputation: 6822

Xtext assign values during parsing

I'm trying to build a parser that can take a human language expression like twenty five percent and transform it into a number like 25%.

Essentially I have a rule like this:

Number:
    (T1 | T2 | T3 T1) 'percent'?
;

terminal T1: 'zero' | 'one' | 'two' etc....;
terminal T2: 'ten' | 'eleven' | 'twelve' etc...;
terminal T3: 'twenty' | 'thirty' | 'forty' etc...;

And I want to transform it somehow so that when I access Number in Xtend to generate my code it will not be text like twenty five percent but it will be a number.

Is this possible?

Upvotes: 0

Views: 701

Answers (1)

Sebastian Zarnekow
Sebastian Zarnekow

Reputation: 6729

You defined Number as a data type rule that returns a String.

If you use something like

Number returns ecore::EBigDecimal:
  (T1 | T2 | T3 T1) 'percent'?
;

you can define a value converter for your rule Number and convert it to an actual instance of BigDecimal. The callee of the rule Number will see it as a BigDecimal. Please refer to the docs for details on value conversion in Xtext. Please keep in mind that you have to import the Ecore package for that purpose. Take a look at the common terminals and the docs if you have questions about that.

Upvotes: 1

Related Questions