carbon-lang icon indicating copy to clipboard operation
carbon-lang copied to clipboard

What are the semantics of the parentheses in a match-case statement?

Open CJ-Johnson opened this issue 8 months ago • 2 comments
trafficstars

Summary of issue:

There is tension between the parentheses in the match portion of a match-case and the case portion. We expect both to have parentheses, but the semantics seems to differ. For the match portion, they are (currently) treated as regular parentheses. For the case portion, they are (currently) treated as tuple literals.

Details:

The following code fails to compile:

class C {}
fn F() -> C;
match (F()) {
  // Attempting to perform tuple destructuring on a non-tuple type.
  // Fails to compile.
  case (x: C) => {}
}

It fails because the parens in a case are considered to be a tuple pattern. This is convenient in some cases where you want tuple destructuring at the top level, but it means non-tuple code becomes unrepresentable.

I would really appreciate it if we could unify the semantics of the parens in match-case such that they are both always tuple patterns/literals or both always just parens. In order to support code like this example, we need to treat them the same.

Any other information that you want to share?

No response

CJ-Johnson avatar Mar 12 '25 22:03 CJ-Johnson

Per https://docs.carbon-lang.dev/docs/design/pattern_matching.html#tuple-patterns, (x: C) is treated as having grouping parentheses, not a tuple pattern. To form a tuple pattern or tuple literal, you need either for the parens to be empty or to contain at least one , or ....

zygoloid avatar Mar 26 '25 18:03 zygoloid

My apologies. I was under the impression that the parens were mandatory. But I see they are not, as in https://github.com/carbon-language/carbon-lang/blob/c7a338be59a1037904dbde4fa7f1b0accebad0ac/explorer/data/prelude.carbon#L209 . That is what lead to my confusion. Perhaps this issue can be changed to request that we make them mandatory and thus always parens/never tuple patterns?

CJ-Johnson avatar Mar 27 '25 19:03 CJ-Johnson