You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by pa...@apache.org on 2026/04/25 09:41:15 UTC

(groovy-website) branch asf-site updated: draft GEP for additional multi-assignment forms

This is an automated email from the ASF dual-hosted git repository.

paulk-asert pushed a commit to branch asf-site
in repository https://gitbox.apache.org/repos/asf/groovy-website.git


The following commit(s) were added to refs/heads/asf-site by this push:
     new e411c33  draft GEP for additional multi-assignment forms
e411c33 is described below

commit e411c33bff359f0726e2efbb0f77a8a7aaee89c0
Author: Paul King <pa...@asert.com.au>
AuthorDate: Sat Apr 25 19:40:58 2026 +1000

    draft GEP for additional multi-assignment forms
---
 site/src/site/wiki/GEP-20.adoc | 472 +++++++++++++++++++++++++++++++++++++++++
 1 file changed, 472 insertions(+)

diff --git a/site/src/site/wiki/GEP-20.adoc b/site/src/site/wiki/GEP-20.adoc
new file mode 100644
index 0000000..d2ef18c
--- /dev/null
+++ b/site/src/site/wiki/GEP-20.adoc
@@ -0,0 +1,472 @@
+= GEP-20: Multi-assignment Destructuring
+
+:icons: font
+
+.Metadata
+****
+[horizontal,options="compact"]
+*Number*:: GEP-20
+*Title*:: Multi-assignment Destructuring
+*Version*:: 1
+*Type*:: Feature
+*Status*:: Draft
+*Leader*:: Paul King
+*Created*:: 2026-04-25
+*Last modification*&#160;:: 2026-04-25
+****
+
+== Abstract
+
+This GEP extends Groovy's parens-form multi-assignment with rest
+bindings (`*t`) at the tail, head, or middle of the declarator list,
+and map-style key destructuring (`name: n`). The extensions are
+strictly additive — every program valid in Groovy 4 / 5 today
+compiles with identical semantics — and each new shape uses an
+unparseable token sequence in the existing grammar, so the proposal
+claims previously-unused syntax rather than reinterpreting any
+existing form.
+
+The proposal targets Groovy 6.x.
+
+== Motivation
+
+Groovy's multi-assignment in `def (...)` has been stable since Groovy
+1.6. Today's grammar supports only positional binding:
+
+[source,groovy]
+----
+def (a, b, c) = list
+def (int x, String y) = pair
+----
+
+Three idioms are common in modern languages but unavailable in Groovy:
+
+* *Tail rest binding*: `def (h, *t) = list` — separate the head from
+  the remainder. Common in functional code (recursive list traversal,
+  pipeline-style processing of streams and iterators).
+* *Map-style destructuring*: `def (name: n, age: a) = person` — extract
+  named properties or map keys directly, without intermediate
+  variables.
+* *Rest in non-tail positions*: `def (*f, last) = list`,
+  `def (l, *m, r) = list` — useful when the boundaries are at the ends
+  rather than the middle.
+
+Adding these to the parens form keeps the grammar familiar (no new
+bracket form, no marker words) while filling the gaps.
+
+=== Design principles
+
+* *Strictly additive* — every program valid in Groovy 5 / 6 compiles
+  with identical semantics. New forms use grammar that fails to parse
+  today.
+
+* *No new keywords or markers* — `def (...)` already declares the
+  names; `var` or other markers add ceremony without disambiguation in
+  declarator position.
+
+* *`_` stays an identifier* — existing idioms like
+  `def (_, y, m) = Calendar.instance` keep working without warning.
+  This proposal introduces no wildcard semantics for `_`.
+
+* *Reuse Groovy's existing tokens* — the rest marker is `*`, matching
+  Groovy's spread operator. The map form uses `key: value` syntax
+  matching Groovy map literals.
+
+* *Sized contracts only when needed* — forms that can be lowered
+  streaming-style (tail rest) accept iterators and unbounded sources
+  via an `iterator()` fallback. Forms that genuinely need to know the
+  RHS size (head rest, middle rest) document the sized-RHS contract
+  and fail fast against non-conforming input.
+
+== Features
+
+=== Existing positional form (recap)
+
+For reference, `def (a, b, c) = rhs` evaluates `rhs` once into a
+synthetic local then assigns each declared variable from
+`rhs.getAt(0)`, `rhs.getAt(1)`, `rhs.getAt(2)`. This is unchanged. Any
+RHS supporting `getAt(int)` continues to work — `List`, `String`,
+arrays, ranges, iterators (via DGM's `getAt(Iterator, int)`), and any
+user-defined class providing the operator.
+
+Type ascriptions on positional bindings (`def (int a, String b)`) are
+likewise unchanged.
+
+=== Tail rest binding
+
+A single `*ident` at the end of the declarator list captures the
+remaining elements:
+
+[source,groovy]
+----
+def (h, *t) = list
+def (a, b, c, *rest) = list
+----
+
+The rest binding is well-defined for any RHS that supports *either*
+`getAt(IntRange)` *or* `iterator()`. The compiler picks one of two
+lowerings:
+
+[source,groovy]
+----
+// Path A — RHS supports getAt(IntRange):
+def __rhs = rhs
+def h = __rhs.getAt(0)
+def t = __rhs.getAt(1..-1)
+
+// Path B — RHS iterable but not range-indexable:
+def __it = rhs.iterator()
+def h = __it.hasNext() ? __it.next() : null
+def t = __it
+----
+
+`t` therefore has the natural type of the RHS:
+
+[cols="2,1,1,2"]
+|===
+|RHS type |`getAt(IntRange)` |Path |Type of `t`
+
+|`List<T>`               |✓ |A |`List<T>`
+|`T[]`                   |✓ |A |`List<T>`
+|`String`                |✓ |A |`String`
+|`Range`                 |✓ |A |`List<Integer>`
+|`Set<T>`                |✗ |B |`Iterator<T>`
+|`Iterable<T>` (custom)  |✗ |B |`Iterator<T>`
+|`Iterator<T>`           |✗ |B |`Iterator<T>` — same instance, advanced
+|`Stream<T>`             |✗ |B |`Iterator<T>`
+|===
+
+Path B is the key enabler for unbounded sources. Given an infinite or
+lazy iterator, `def (h, *t) = source` returns the head and an iterator
+the caller can keep pulling from — there is no materialisation.
+
+==== Type ascriptions on the rest binder
+
+The rest binder may carry a type ascription, mirroring the existing
+positional form:
+
+[source,groovy]
+----
+def (h, List<Integer> *t) = [1, 2, 3, 4]    // Path A — t : List<Integer>
+def (h, Iterator<Integer> *t) = someSet     // Path B — t : Iterator<Integer>
+def (l, List<Integer> *m, r) = list         // typed middle rest
+----
+
+The declared type must be compatible with the path the RHS selects:
+`List<T>` (or a supertype) for Path A, `Iterator<T>` (or a supertype)
+for Path B. Under `@CompileStatic` a mismatch is reported at compile
+time; in dynamic mode it surfaces as a `GroovyCastException` when the
+slice or iterator is coerced. Untyped rest is the recommended
+default; ascribe a type when you want a tighter element type or to
+fail fast if the RHS shape changes.
+
+Edge cases:
+
+* Empty RHS: `def (h, *t) = []` — `h = null`, `t = []` (Path A) or `t`
+  is an exhausted iterator (Path B).
+* Exhausted iterator: `def (h, *t) = exhaustedIter` — `h = null`,
+  `t = exhaustedIter`.
+* RHS that supports neither protocol: compile error under
+  `@CompileStatic`; `MissingMethodException` at runtime in dynamic
+  mode.
+
+=== Rest binding in head and middle positions
+
+A `*ident` in non-tail position requires a sized, indexable RHS:
+
+[source,groovy]
+----
+def (*front, last) = list
+def (l, *middle, r) = list
+def (a, b, *m, y, z) = list
+----
+
+These forms lower via indexed access. Positional slots use `getAt(int)`
+(with negative indices for tail-side fixed slots); the rest slot uses
+`getAt(IntRange)`. The RHS contract is `getAt(int)` plus
+`getAt(IntRange)` — equivalent to "list-like".
+
+[source,groovy]
+----
+// def (l, *m, r) = rhs
+def __rhs = rhs
+def m = __rhs.getAt(1..-2)    // emitted before any negative-index call
+def l = __rhs.getAt(0)
+def r = __rhs.getAt(-1)
+----
+
+The `getAt(IntRange)` call is *emitted before* any negative-index
+`getAt(int)` call. This is load-bearing for safety: DGM's
+`getAt(Iterator, int)` materialises the iterator on negative indices
+(`toList(self)` then index from the end), which would silently hang on
+an infinite source. By emitting the IntRange call first, iterators
+fail fast with `MissingMethodException` (no `getAt(Iterator, IntRange)`
+overload exists in DGM) before any materialisation can happen — the
+same clean failure mode `def (a, b) = 42` already produces today
+against a non-indexable RHS.
+
+Constraints:
+
+* At most one rest binding per parens form. Multiple rest bindings
+  (`def (a, *b, *c, d)`) is a compile error.
+* RHS sizes smaller than the total number of fixed slots are
+  tolerated: `getAt(int)` returns `null` for out-of-bounds positions
+  and the rest slot becomes an empty collection.
+
+=== Map-style destructuring
+
+`key: ident` pairs in the declarator list bind via property access:
+
+[source,groovy]
+----
+def (name: n, age: a) = person
+def (host: h, port: p) = config
+----
+
+Lowering:
+
+[source,groovy]
+----
+def __rhs = person
+def n = __rhs.name
+def a = __rhs.age
+----
+
+The protocol is Groovy's normal property access (`obj.name`), so the
+form works on any RHS responding to the named property via the MOP:
+
+* `Map` values — Groovy's MapMOP makes `m.name` equivalent to
+  `m['name']`.
+* Java beans — calls the getter, e.g. `getName()`.
+* `GroovyObject` — dispatches via `getProperty('name')`.
+* Any user-defined class providing the property by any of the above
+  routes.
+
+Type ascriptions pin or coerce binding types:
+
+[source,groovy]
+----
+def (name: String n, age: int a) = person
+----
+
+Failure modes match expression-position property access:
+
+[cols="2,2,2"]
+|===
+|RHS shape |Property absent |Result
+
+|`Map`                          |Key not in map  |Binding receives `null` (Groovy `Map` returns null for missing keys)
+|Bean / `GroovyObject`          |No matching property |`MissingPropertyException` at runtime
+|Static type lacks the property |—              |Compile error under `@CompileStatic`
+|===
+
+==== Map-key restrictions
+
+`class` is a reserved keyword and so cannot appear as a destructuring
+key — `def (class: c) = m` is a syntax error. Identifiers like
+`metaClass` parse, but `m.metaClass` resolves to the map's MetaClass
+via Groovy's standard MOP, not to a key named `metaClass`. Users
+needing either key fall back to subscript: `def c = m['class']`.
+
+==== Mixing positional and map
+
+Mixing positional and map-style declarators within a single `def (...)`
+is a compile error in 6.x:
+
+[source,groovy]
+----
+def (h, name: n, *t) = obj    // error in 6.x
+----
+
+Disallowing this leaves the option open for a future spec; permitting
+it now would lock in semantics before use cases emerge.
+
+=== `_` and other identifiers
+
+`_` is a regular identifier in all forms, exactly as today:
+
+[source,groovy]
+----
+def (_, y, m) = Calendar.instance      // unchanged
+def (_, *t)   = list                   // _ binds to head
+def (h, *_)   = list                   // _ binds to rest
+def (*_, last) = list                  // _ binds to front
+def (name: _, age: a) = person         // _ binds to person.name
+----
+
+No deprecation warning, no wildcard semantics, no behavioural change.
+
+== Compilation
+
+=== Grammar additions
+
+Two local additions to the multi-assignment production:
+
+* In the declarator list, allow an optional leading `*` on at most one
+  identifier (with optional type ascription).
+* Add a `key: ident` (or `key: Type ident`) alternative to the
+  declarator list, exclusive of positional declarators within a single
+  `def (...)`.
+
+Empty declarator lists (`def () = expr`) remain a syntax error, as
+today. No changes outside the multi-assignment production. No new
+keywords. No reserved identifiers.
+
+=== Lowering summary
+
+[cols="3,3,2"]
+|===
+|Shape |Lowering |RHS contract
+
+|`def (a, b, c) = rhs`
+|Today's lowering, unchanged
+|`getAt(int)`
+
+|`def (h, *t) = rhs` (and `def (a, b, *t) = rhs`, etc.)
+|Path A (`getAt(IntRange)`) or Path B (`iterator()`)
+|`getAt(IntRange)` *or* `iterator()`
+
+|`def (*f, last) = rhs` / `def (l, *m, r) = rhs`
+|`getAt(IntRange)` first, then `getAt(int)` (positive then negative)
+|`getAt(int)` + `getAt(IntRange)`
+
+|`def (k1: v1, k2: v2) = rhs`
+|Property access
+|Property dispatch via MOP
+|===
+
+=== Static type checking
+
+Under `@CompileStatic` and `@TypeChecked`:
+
+* Path A vs Path B for tail rest is decided at compile time from the
+  RHS's declared type.
+* Bindings receive their natural narrowed type. For `List<T>`, the
+  tail rest is `List<T>`; for `Iterator<T>`, the tail rest is
+  `Iterator<T>`; for `Map<String, V>`, map-style bindings are `V`; for
+  beans, bindings are the property's declared type.
+* If neither protocol is available on the RHS's static type, the
+  compiler reports an error.
+
+==== Implicit type of the rest binding
+
+An untyped rest binding (`*t`, `*f`, `*m`) takes the inferred type
+shown in the _Tail rest binding_ table. Head and middle rest are
+restricted to Path A — a non-indexable RHS (Set, Iterator, Stream)
+in those positions is a static type error.
+
+=== Dynamic dispatch
+
+In dynamic mode, Path A vs Path B for tail rest is selected at runtime
+via Groovy's normal method-resolution. Failure modes are runtime
+exceptions (`MissingMethodException`, `MissingPropertyException`)
+consistent with expression-position dispatch — no new failure types
+introduced.
+
+=== RHS evaluation
+
+The RHS expression is evaluated *exactly once* into a synthetic local.
+All bindings derive from that single evaluation. Order of binding
+assignment is left-to-right of declared positions, except that in
+non-tail-rest forms the IntRange call is emitted before any
+negative-index call (see _Rest binding in head and middle positions_).
+
+== Compatibility
+
+=== Backwards compatibility
+
+Every program valid in Groovy 4 / 5 compiles with identical semantics.
+The new shapes use grammar that does not parse today:
+
+[cols="3,1"]
+|===
+|Form |Parses today?
+
+|`def (a, b, c) = list`            |Yes — unchanged
+|`def (int a, String b) = pair`    |Yes — unchanged
+|`def (_, y, m) = list`            |Yes — `_` is an identifier, unchanged
+|`def (h, *t) = list`              |No — claimed by this proposal
+|`def (*f, last) = list`           |No — claimed
+|`def (l, *m, r) = list`           |No — claimed
+|`def (name: n, age: a) = person`  |No — claimed
+|===
+
+No syntactic ambiguity is introduced: `*ident` and `key: ident` in
+declarator position both fail to parse today, so claiming them as new
+grammar does not change the meaning of any existing program.
+
+=== `_` is not deprecated
+
+This proposal explicitly does *not* deprecate `_` as an identifier in
+any context. Existing idioms (`def (_, y, m) = Calendar.instance`,
+`(0..n).each { _ -> ... }`, etc.) continue to compile with no warning.
+
+=== Forward compatibility
+
+The parens form claims grammar that is unparseable today and uses
+tokens (`*`, `key:`) that have no other meaning in declarator position.
+This leaves the unrelated `def [...]` bracket-literal grammar entirely
+free for any future pattern-matching or destructuring proposal that
+wants to use it, with no risk of conflicting reinterpretation.
+
+== Excluded and deferred features
+
+The following forms were considered and intentionally left out of this
+proposal. Some are deferred to a future spec (typically alongside
+GEP-19 pattern matching); others are not planned.
+
+[cols="2,1,3"]
+|===
+|Feature |Status |Rationale
+
+|Bracket form `def [h, *t] = list`
+|Deferred
+|Out of scope for the parens-form additions; would belong with a
+ dedicated bracket-pattern proposal
+
+|`var` markers in declarators
+|Not planned
+|`def (...)` already declares the names; `var` adds ceremony without
+ disambiguation in declarator position
+
+|Wildcard `_` semantics
+|Not planned for parens form
+|Existing identifier semantics preserved; any future wildcard form
+ belongs in a separate grammar (e.g. bracket-form patterns)
+
+|Mixing positional and map-style in one `def (...)`
+|Not planned for 6.x
+|Semantics not obvious; defer pending concrete use cases
+
+|Multiple rest bindings (`def (a, *b, *c, d)`)
+|Not planned
+|Inherently ambiguous; no language ships this
+
+|Nested patterns (e.g. `def (h, [a, b]) = ...`)
+|Deferred
+|Belongs with a bracket-form pattern grammar
+
+|Head/middle rest against a non-indexable RHS
+|Not planned
+|No clean semantics; iterators / streams fail with
+ `MissingMethodException` for `getAt(IntRange)`, by design
+
+|Map destructuring with renaming via the `as` operator (e.g.
+ `def (name as fullName: n) = person`)
+|Deferred
+|`key: ident` already provides the renaming (`def (name: fullName) =
+ person`); a separate `as` form is unnecessary
+
+|Default values (e.g. `def (name: n = 'anon', age: a = 0) = person`)
+|Deferred
+|Useful for map-style destructuring on partial inputs; can be added
+ later without grammar collision
+|===
+
+== References
+
+* https://groovy-lang.org/semantics.html#_multiple_assignment[Groovy multiple assignment (existing semantics)]
+* https://github.com/apache/groovy/blob/master/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java[`DefaultGroovyMethods` — DGM extension methods on `Iterator`, `Iterable`, `List`, etc.]
+* https://docs.python.org/3/reference/simple_stmts.html#assignment-statements[Python: starred targets in assignment]
+* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment[JavaScript: destructuring assignment]
+* link:GEP-19.html[GEP-19: Structural Pattern Matching in switch] — related future work on pattern matching