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?
source to share
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\";");
}
}
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 )
source to share