Paul King created GROOVY-12790:
----------------------------------
Summary: A multiple-assignment declaration with a non-literal
right-hand side is dropped, with every later declaration, from a script with an
instance main or a run method
Key: GROOVY-12790
URL: https://issues.apache.org/jira/browse/GROOVY-12790
Project: Groovy
Issue Type: Bug
Components: Compiler
Reporter: Paul King
In a script with no statements other than declarations, plus a {{main}} method
(the JEP 445 style class) or a no-arg {{run}} method, top-level declarations
are turned into fields. A multiple-assignment declaration whose right-hand side
is not a list literal is silently dropped instead, together with every
declaration that follows it.
{code:groovy}
def (a, b) = "xy".toList()
def c = 3
void main() { println "a=$a c=$c" }
{code}
fails with:
{noformat}
groovy.lang.MissingPropertyException: No such property: a for class: M
{noformat}
The generated class's declared fields:
||Script||Fields||
|{{def (a, b) = [1, 2]; def c = 3; void main() {}}}|a, b, c|
|{{def (a, b) = "xy".toList(); def c = 3; void main() {}}}|(none)|
|{{def (a, b) = "xy".toList(); def c = 3; def run() {}}}|(none)|
Neither {{a}}, {{b}} nor {{c}} becomes a field, and the declaration's
right-hand side is never evaluated. There is no compile error or warning.
The cause is the declaration loop in {{ModuleNode.createStatementsClass()}}:
{code:java}
if (!(de.getRightExpression() instanceof ListExpression)) break;
{code}
The {{break}} leaves the loop without setting {{hasUncontainedStatements}}, so
the class is still built from the fields collected so far, and the remaining
declarations are discarded. The loop was added by GROOVY-11118 (5.0.0-alpha-1).
Possible fixes: treat such a declaration as an uncontained statement, which
gives the normal script behaviour; or create the fields and assign them in an
instance initializer, which keeps the plain class.
Reproduced on master at 077ff21217 and on 6.0.0-beta-2, both on JDK 17.0.20.
The same code is on GROOVY_5_0_X, GROOVY_5_1_X and GROOVY_6_0_X, but not on
GROOVY_4_0_X.
--
This message was sent by Atlassian Jira
(v10.3.26#10030026)