Allow not-immediately-expanded `expand` expressions

Author: zygoloidCreated Sep 25, 2026Updated Sep 30, 2026
Labelsleads question

Summary of issue:

The rules for expand are too restrictive, and also allow cases that have the ambiguity in meaning that we wanted to avoid.

Details:

In #2240, we wanted to add a general expand <tuple expression> expression, but this leads to a problem: for

carbon
fn F(n: i32);
fn G() -> (i32, i32, i32);
... F(expand G());

... we clearly want to call F three times, but intuitions vary as to whether the call to G() would be evaluated once or three times. The consistent behavior would be that ... <stuff> expands all of <stuff> N times, so the expansion would be

carbon
F(G().0);
F(G().1);
F(G().2);

But that seems in some sense wasteful, and during discussion some preferred

carbon
let x: auto = G();
F(x.0);
F(x.1);
F(x.2);

However, that expansion doesn't actually work in general; for example, in:

carbon
... F(if each cond then expand G() else 0);

... how often should G() be invoked? Similarly, in:

carbon
... RegisterCallback(fn => expand G());

... it would be surprising if we invoked G() at all.

The solution we ended up with was to allow expand only when it is immediately expanded with ... within a tuple literal. So:

carbon
(a, ...expand G(), c)

is OK, but

carbon
... F(expand G());

is not. However, this has the same problem we were trying to avoid: it's unclear whether G() is invoked one or three times in the above, and it's unnecessarily restrictive, since it disallows cases where there is no potential ambiguity because the tuple expression has no side effects, such as:

carbon
fn F(t: (i32, i32, i32)) {
  ... F(expand t);
}

Any other information that you want to share?

I suggest resolving this by allowing the cases where the two interpretations of expand mean the same thing: where it doesn't really matter if the expand's operand is evaluated once for each pack expansion or once overall, and it doesn't really matter when it is reached. (It may still subtly matter because it affects things like when a value binding is formed; the semantics we should use are that ... expands everything within it, rather than reordering the operand of expand to before the ....)

In practice, I think this means we should remove the current permission for (...expand e) (for an e with side effects), and instead allow expand e whenever e is a tuple-typed expression with no side effects (either because it's a constant expression or because it happens to have no runtime side effects -- in particular, e can include name references or member accesses, but not function calls). This is harmonious with the restrictions on each, since each x also can't have side effects.

Source: carbon-language/carbon-lang