Search code examples
textx

Unexpected behaviour of numeric value conversion


I have the following rule in textx:

IsLessThanOrEqualToRule:
'is <= ' reference_value_input = FLOAT | INT
;

This rule allows the DSL user to specify a reference numeric value as a float or an integer in the following manner: is <= 1000 or is <= 100.025.

However it seems that depending on the order in which I specify the value types FLOAT and INT, entered numeric values are being converted. This is an unexpected behaviour. Examples:

  1. if I specify rule as .....reference_value_input = FLOAT | INT then integer input values are represented as floats. So, 1000 is represented as 1000.0.
  2. if I specify rule as .....reference_value_input = INT | FLOAT then float input values are represented as integers. So, 1000.112 is represented as 1000.

How do I maintain my numeric type when reading user input? Thank you for all your inputs. Anjan


Solution

  • textX uses PEG which respects the order in which rules are defined. So, if you order your rule as FLOAT | INT, FLOAT will be tried first. This is the problem as FLOAT rule matches INT so INT which follows will never be tried.

    Solution it to use STRICTFLOAT which do not match INT. There is a more general rule called NUMBER which does exactly what you need. So, just write reference_value_input = NUMBER.

    Section on base textX types in the documentation gives a more detailed explanation.