Skip to content
Permalink
Browse files
GROOVY-10580: Conditionally initialized final variables considered …
…maybe uninitialized
  • Loading branch information
paulk-asert committed Apr 14, 2022
1 parent d8890e9 commit 99e99c256d135419f49c7fc7fb7fb28ab1cc9b9c
Showing 2 changed files with 35 additions and 1 deletion.
@@ -290,13 +290,19 @@ public void visitIfElse(final IfStatement ifElse) {
allVars.addAll(curState.keySet());
allVars.addAll(ifState.keySet());
allVars.addAll(elseState.keySet());
boolean ifReturning = returningBlock(ifElse.getIfBlock());
boolean elseReturning = returningBlock(ifElse.getElseBlock());
for (Variable var : allVars) {
VariableState beforeValue = curState.get(var);
if (beforeValue != null) {
VariableState ifValue = ifState.get(var);
VariableState elseValue = elseState.get(var);
if (ifValue == elseValue) {
if (ifValue == elseValue || (elseReturning && !ifReturning)) {
curState.put(var, ifValue);
} else if (ifReturning && !elseReturning) {
curState.put(var, elseValue);
} else if (ifReturning) {
curState.put(var, beforeValue);
} else {
curState.put(var, beforeValue == VariableState.is_uninitialized ? VariableState.is_ambiguous : VariableState.is_var);
}
@@ -534,6 +534,34 @@ class FinalVariableAnalyzerTest extends GroovyTestCase {
'''
}

// GROOVY-10580
void testFinalVarIfElseStatementReturningBranch() {
assertScript '''
final int i
final boolean a = true
if (a) {
i = 1
} else {
throw new IllegalStateException('a is false')
}
def result = i
assert result == 1
def evalJ() {
final int j
final boolean b = true
if (!b) {
return null
} else {
j = 2
}
def result = j
return result
}
assert evalJ() == 2
'''
}

@CompileStatic
private static class AssertionFinalVariableAnalyzer extends FinalVariableAnalyzer {

0 comments on commit 99e99c2

Please sign in to comment.