eclipse-xtext / eclipse-xtext/xtext
Unnecessary casts in ternary operator and if-expressions
Nobody has claimed this yet.
- Dominant language
- Java
- Stars
- 831
- Forks
- 330
- Avg merge
- 3d 7h
- Merged PRs (30d)
- 12
Description
Consider the following function, where MAXIMUM is a static variable of type int:
def isMaxAsInt(int value){
value==MAXIMUM?1:0
}
It compiles to
public int isMaxAsInt(int value){
int _xifexpression = (int) 0; // Unnecesary cast here
if ((value == Foo.MAXIMUM)) {
_xifexpression = 1;
} else {
_xifexpression = 0;
}
return _xifexpression;
}
Explicitly typing the return value does not fix the problem.
This also happens with other primitive types, such as long.
Unsure if this also happens with standard if-expression. EDIT: this does happen with if-expressions.
As a side note, the else branch seems a good target for optimization (in this example), as it serves as a noop.
Example using an if-expression: (Why is an if-expression generated here?)
private static def checkValue(long arg) {
if(arg < 0 || arg > MAXIMUM) throw new IllegalArgumentException(
"value out of range!")
arg
}
compiles to
private static long checkValue(final long arg) {
long _xblockexpression = (long) 0; // Redundant cast here
{
if (((arg < 0) || (arg > Foo.MAXIMUM))) {
throw new IllegalArgumentException(
"value out of range!");
}
_xblockexpression = arg;
}
return _xblockexpression;
}
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the Xtend ternary and if-expression examples and inspecting their generated Java output. Trace the compiler path that initializes _xifexpression or _xblockexpression, then verify that equivalent primitive expressions no longer receive redundant casts while preserving the generated behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- java
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100