Skip to content

Fix #23224: Optimize simple tuple extraction #23373

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 25 additions & 7 deletions compiler/src/dotty/tools/dotc/ast/Desugar.scala
Original file line number Diff line number Diff line change
Expand Up @@ -1483,14 +1483,14 @@ object desugar {
|please bind to an identifier and use an alias given.""", bind)
false

def isTuplePattern(arity: Int): Boolean = pat match {
case Tuple(pats) if pats.size == arity =>
pats.forall(isVarPattern)
case _ => false
// The arity of the tuple pattern if it only contains simple variables or wildcards.
val varTuplePatternArity = pat match {
case Tuple(pats) if pats.forall(isVarPattern) => pats.length
case _ => -1
}

val isMatchingTuple: Tree => Boolean = {
case Tuple(es) => isTuplePattern(es.length) && !hasNamedArg(es)
case Tuple(es) => varTuplePatternArity == es.length && !hasNamedArg(es)
case _ => false
}

Expand Down Expand Up @@ -1519,10 +1519,28 @@ object desugar {

val ids = for ((named, _) <- vars) yield Ident(named.name)
val matchExpr =
if (tupleOptimizable) rhs
if tupleOptimizable then rhs
else
val caseDef = CaseDef(pat, EmptyTree, makeTuple(ids).withAttachment(ForArtifact, ()))
val caseDef =
if varTuplePatternArity >= 0 && ids.length > 1 then
// If the pattern contains only simple variables or wildcards,
// we don't need to create a new tuple.
// If there is only one variable (ids.length == 1),
// `makeTuple` will optimize it to `Ident(named)`,
// so we don't need to handle that case here.
val tmpTuple = UniqueName.fresh()
// Replace all variables with wildcards in the pattern
val pat1 = pat match
case Tuple(pats) =>
Tuple(pats.map(pat => Ident(nme.WILDCARD).withSpan(pat.span)))
CaseDef(
Bind(tmpTuple, pat1),
EmptyTree,
Ident(tmpTuple).withAttachment(ForArtifact, ())
)
else CaseDef(pat, EmptyTree, makeTuple(ids).withAttachment(ForArtifact, ()))
Copy link
Preview

Copilot AI Jun 16, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nitpick] This inlined block for simple-variable tuple optimization is fairly large and complex. Extracting it into a named helper method (e.g., makeVarTupleCaseDef) could improve readability and reduce cognitive overhead.

Suggested change
if varTuplePatternArity >= 0 && ids.length > 1 then
// If the pattern contains only simple variables or wildcards,
// we don't need to create a new tuple.
// If there is only one variable (ids.length == 1),
// `makeTuple` will optimize it to `Ident(named)`,
// so we don't need to handle that case here.
val tmpTuple = UniqueName.fresh()
// Replace all variables with wildcards in the pattern
val pat1 = pat match
case Tuple(pats) =>
Tuple(pats.map(pat => Ident(nme.WILDCARD).withSpan(pat.span)))
CaseDef(
Bind(tmpTuple, pat1),
EmptyTree,
Ident(tmpTuple).withAttachment(ForArtifact, ())
)
else CaseDef(pat, EmptyTree, makeTuple(ids).withAttachment(ForArtifact, ()))
makeVarTupleCaseDef(pat, ids, rhs, varTuplePatternArity)

Copilot uses AI. Check for mistakes.

Match(makeSelector(rhs, MatchCheck.IrrefutablePatDef), caseDef :: Nil)

vars match {
case Nil if !mods.is(Lazy) =>
matchExpr
Expand Down
13 changes: 11 additions & 2 deletions compiler/src/dotty/tools/dotc/typer/Typer.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2774,6 +2774,16 @@ class Typer(@constructorOnly nestingLevel: Int = 0) extends Namer
if !isFullyDefined(pt, ForceDegree.all) then
return errorTree(tree, em"expected type of $tree is not fully defined")
val body1 = typed(tree.body, pt)

// If the body is a named tuple pattern, we need to use pt for symbol type,
// because the desugared body is a regular tuple unapply.
def isNamedTuplePattern =
ctx.mode.is(Mode.Pattern)
&& pt.dealias.isNamedTupleType
&& tree.body.match
case untpd.Tuple((_: NamedArg) :: _) => true
case _ => false

body1 match {
case UnApply(fn, Nil, arg :: Nil)
if fn.symbol.exists && (fn.symbol.owner.derivesFrom(defn.TypeTestClass) || fn.symbol.owner == defn.ClassTagClass) && !body1.tpe.isError =>
Expand All @@ -2799,8 +2809,7 @@ class Typer(@constructorOnly nestingLevel: Int = 0) extends Namer
body1.isInstanceOf[RefTree] && !isWildcardArg(body1)
|| body1.isInstanceOf[Literal]
val symTp =
if isStableIdentifierOrLiteral || pt.dealias.isNamedTupleType then pt
// need to combine tuple element types with expected named type
if isStableIdentifierOrLiteral || isNamedTuplePattern then pt
else if isWildcardStarArg(body1)
|| pt == defn.ImplicitScrutineeTypeRef
|| body1.tpe <:< pt // There is some strange interaction with gadt matching.
Expand Down
34 changes: 34 additions & 0 deletions tests/pos/simple-tuple-extract.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@

class Test:
def f1: (Int, Int, Int) = (1, 2, 3)
def f2: (x: Int, y: Int) = (3, 4)

def test1 =
val (a, b, c) = f1
// Desugared to:
// val $2$: (Int, Int, Int) =
// this.f1:(Int, Int, Int) @unchecked match
// {
// case $1$ @ Tuple3.unapply[Int, Int, Int](_, _, _) =>
// $1$:(Int, Int, Int)
// }
// val a: Int = $2$._1
// val b: Int = $2$._2
// val c: Int = $2$._3
a + b + c

def test2 =
val (_, d, e) = f1
e + e

def test3 =
val (_, f, _) = f1
f + f

def test4 =
val (x, y) = f2
x + y

def test5 =
val (_, a) = f2
a + a
Loading