JavaCC generates dead code

This is my first time using JavaCC and I notice that it generates a lot of dead code. There are many lines that look like (sorry for the spacing, it's automatic):

{if ("" != null) return result;}
    throw new Error("Missing return statement in function");
  }

      

Can this dead code be avoided? It raises dozens of compiler warnings that can hopefully be avoided.

Thank!

Here is a complete minimal example from a .jj file:

Statement UseStatement():
{
    String dbName;
}
{
    <USE> dbName=DbObjectName()
    {
        return new UseStatement(dbName);
    }
}

      

What generates:

final public Statement UseStatement() throws ParseException {String dbName;
    jj_consume_token(USE);
    dbName = DbObjectName();
{if ("" != null) return new UseStatement(dbName);}
    throw new Error("Missing return statement in function");
  }

      

Additionally, JavaCC creates a ParserTokenManager file that throws a TokenMgrError, but the code does not compile. He announces protected int curChar

where he should announce it char

. As a result of this phrase, there are many examples where it is correctly declared char

- are they just people editing the result manually?

+3


source to share


1 answer


I went to the source and to prevent dead code you have to call Options.isLegacyExceptionHandling

.

  // Add if statement to prevent subsequent code generated
  // from being dead code.
  // NB: eclipse now detects 'if (true)' as dead code, so use the more complicated
  // 'if ("" != null)'
  if (inAction  && (Options.isLegacyExceptionHandling()) ) {
    t.image = "{if (\"\" != null) return";
    jumpPatched = true;
  }

      

which then runs:

if (p.isJumpPatched() && !voidReturn) {
  if (isJavaDialect) {
    // TODO :: I don't think we need to throw an Error/Exception to mark that a return statement is missing as the compiler will flag this error automatically
    if (Options.isLegacyExceptionHandling()) {
        codeGenerator.genCodeLine("    throw new "+(Options.isLegacyExceptionHandling() ? "Error" : "RuntimeException")+"(\"Missing return statement in function\");");
    }
  } else {
    codeGenerator.genCodeLine("    throw \"Missing return statement in function\";");
  }
}

      

https://github.com/javacc/javacc/blob/e38cbdb1db7ca8bd66f892859fef88b4876e69ba/src/main/javacc/JavaCC.jj#L2771-L2779



https://github.com/javacc/javacc/blob/2ac628df1f899fdf6acf1f87fad313b6797085f7/src/main/java/org/javacc/parser/ParseEngine.java#L707-L712

Deprecated Exception Handling is a derived option that is false only when JAVA_TEMPLATE_TYPE=modern

. The only way to set it correctly is to include it in a block options

in the .jj file like so:

options {
    JAVA_TEMPLATE_TYPE="modern";
}

      

In theory it is also set using command line options, but at the time of writing it is actually not possible to set a derived option prior to parsing command line arguments ( # 25 )

0


source







All Articles