Paul King created GROOVY-12845:
----------------------------------
Summary: Compiler crash: early yield in a return-position arrow
switch with @Ensures or a class @Invariant
Key: GROOVY-12845
URL: https://issues.apache.org/jira/browse/GROOVY-12845
Project: Groovy
Issue Type: Bug
Components: groovy-contracts
Affects Versions: 6.0.1
Reporter: Paul King
A {{yield}} that doesn't end its arm, in an arrow switch in return position,
crashes the compiler if the method has {{@Ensures}} or its class has
{{@Invariant}}.
{code:groovy}
import groovy.contracts.*
class A {
@Ensures({ result > 0 })
int f(int x) {
switch (x) {
case 1 -> { if (x > 0) yield 1; yield 2 }
default -> 3
}
}
}
assert new A().f(1) == 1
{code}
{noformat}
BUG! exception in phase 'class generation' in source unit 'Script1.groovy'
yield lowered for a switch in return position no longer ends with its value and
break
at
org.codehaus.groovy.classgen.ReturnAdder$1.visitBlockStatement(ReturnAdder.java:244)
{noformat}
It happens in dynamic and statically compiled code. With {{@CompileStatic}} or
a {{def}} return type, the phase is 'instruction selection'.
||Same method with||6.0.0||6.0.1 and master||
|{{@Ensures}} or a class {{@Invariant}}|compiles, f(1) is 2 (wrong)|compiler
crash|
|{{@Requires}}, {{@ThrowsIf}} or {{@Decreases}} only|compiles, f(1) is 2
(wrong)|1|
|no contract|compiles, f(1) is 2 (wrong)|1|
|{{@Ensures}}, written as {{return switch (x) ...}}|1|1|
So GROOVY-12478 fixed the wrong value, but not for a method whose returns
groovy-contracts rewrites. Arms whose yields are all in tail position, such as
an {{if}}/{{else}} where both branches yield, are not affected.
h3. Workaround
Write {{return switch (x) ...}}.
h3. Cause
{{ReturnAdder}} visits the method twice. groovy-contracts runs it first, from
{{AssertStatementCreationUtility.getReturnStatements}}. That visit replaces the
value and {{break}} of the lowered yield with a return, but leaves the
{{YieldStatement}} marker on the block. The contract check is then woven around
that return. When the compiler runs {{ReturnAdder}} later,
{{addReturnsForEarlyYields}} finds the marked block again. It no longer ends
with a value and {{break}}, so the {{GroovyBugError}} is thrown.
h3. Possible fix
Remove the marker when the block is converted:
{code:java}
if (doAdd) {
statements.remove(n - 1);
statements.set(n - 2, returnStatement);
block.removeNodeMetaData(YieldStatement.class);
}
{code}
With this change on master, all the crashing forms above compile and return 1,
and a postcondition violated by the early value is reported.
--
This message was sent by Atlassian Jira
(v10.3.26#10030026)