Search code examples
validationgrammarcase-insensitiverulextext

How to make Enum literal case insensitive in Xtext


I have defined an EnumRule like following in my Xtext grammar file:

enum MySpec_directionEnum: left='"left"' | right='"right"' | none='"none"';

With this rule the allowed enum values are "left", "right" and "none" (all in lower case). I want to be able to allow these values in any case(case insensitive). For example I want to also allow the values to be "left" or "Left" or "LEFT" or "LeFt" and so on.

But I just want values of MySpec_directionEnum enum to be case insensitive and not all enums in my grammar file. Is it possible through grammar or some kind of validation?


Solution

  • I think your best option is to replace the enum rule with an ordinary parser rule, like

    MySpec_directionEnum:
        value=STRING;
    

    and check if value is a permitted string (case-insensitive variant of "left", "right" or "none") in the validator:

    @Check
    public void check(MySpec_directionEnum e) {
        String lowercaseValue = e.getValue().toLowerCase();
        if (!lowercaseValue.equals("left")) {
            error("Expected \"left\".", e, 
                ArithmeticsPackage.Literals.MY_SPEC_DIRECTION_ENUM__VALUE,
                validationMessageAcceptor.INSIGNIFICANT_INDEX);
        }
    }