CSU-CS-Melange / alpha-language

Forked from Inria gitlab
MIT License
0 stars 0 forks source link

Xtend generation issue #69

Closed lnarmour closed 5 months ago

lnarmour commented 5 months ago

At the time of writing this issue, main pointed to commit 56a0147. All the links here refer to this commit. There is a subtle bug in alpha.codegen.writeC.Common due to the way that xtend generates switch expressions.

Example of a GOOD generated switch expression

Look at the getReductionInitalValue function which switches on the value of the op variable. It is in line 163 in Common.xtend and the generated java code is in line 264 in Common.java. The generated java code uses a switch expression as we’d expect.

Example of BAD generated switch expression

Look at the getMaxValue function which switches on the dataType variable. This is line 174 in Common.xtend and line 296 in the generated Common.java.

The xtend switch expression looks like this:

static def getMaxValue(BaseDataType dataType) {
    return switch dataType {
        case INT: "INT_MAX",
        case LONG: "LONG_MAX",
        case FLOAT: "FLT_MAX",
        case DOUBLE: "DBL_MAX"
        default: throw new Exception("There is no maximum value for type '" + dataType + "'.")
    }.customExpr
}

but the generated code looks like this:

public static CustomExpr getMaxValue(final BaseDataType dataType) {
    try {
      String _switchResult = null;
      boolean _matched = false;
      if (Objects.equal(dataType, BaseDataType.INT)) {
        _matched=true;
        _switchResult = "INT_MAX";
      }
      if (!_matched) {
        _matched=true;    // <-------------------------------- BAD line here
        if (!_matched) {
          if (Objects.equal(dataType, BaseDataType.LONG)) {
            _matched=true;
          }
        }
        if (_matched) {
          _switchResult = "LONG_MAX";
        }
      }
      ...

If execution makes it to the second case, the it returns unconditionally, because _matched is always set to true. I haven’t been to identify why this happens. A workaround is to just use if/else-ifs instead of cases.

lnarmour commented 5 months ago

After looking more, it turns out this behavior is expected. We do not want the “fall through” behavior in the getMaxValue function. The commas just need to be removed.

More info on “fall through” can be found here: https://eclipse.dev/Xtext/xtend/documentation/203_xtend_expressions.html#switch-expression