Skip to content

Commit

Permalink
Fix untupling of functions in for comprehensions
Browse files Browse the repository at this point in the history
  • Loading branch information
EugeneFlesselle committed Feb 5, 2024
1 parent 5c628d9 commit 6221361
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 6 deletions.
16 changes: 14 additions & 2 deletions compiler/src/dotty/tools/dotc/ast/Desugar.scala
Original file line number Diff line number Diff line change
Expand Up @@ -1547,10 +1547,22 @@ object desugar {
*
* If `nparams` != 1, expand instead to
*
* (x$1, ..., x$n) => (x$0, ..., x${n-1} @unchecked?) match { cases }
* (x$1, ..., x$n) => (x$1, ..., x$n @unchecked?) match { cases }
*
* Unless there is a single irrefutable case, then can reuse the rhs
*
* { case (a1, ..., an) => rhs }
* ==>
* (a1, ..., an) => rhs
*/
def makeCaseLambda(cases: List[CaseDef], checkMode: MatchCheck, nparams: Int = 1)(using Context): Function = {
val params = (1 to nparams).toList.map(makeSyntheticParameter(_))
val params = cases match
case List(CaseDef(untpd.Tuple(elems), untpd.EmptyTree, rhs)) if elems.sizeIs == nparams =>
patternsToParams(elems) match
case params if params.sizeIs == nparams => params
case _ => (1 to nparams).toList.map(makeSyntheticParameter(_))
case _ => (1 to nparams).toList.map(makeSyntheticParameter(_))

val selector = makeTuple(params.map(p => Ident(p.name)))
Function(params, Match(makeSelector(selector, checkMode), cases))
}
Expand Down
7 changes: 3 additions & 4 deletions compiler/src/dotty/tools/dotc/typer/Typer.scala
Original file line number Diff line number Diff line change
Expand Up @@ -1621,15 +1621,14 @@ class Typer(@constructorOnly nestingLevel: Int = 0) extends Namer
case untpd.Annotated(scrut1, _) => isParamRef(scrut1)
case untpd.Ident(id) => id == params.head.name
fnBody match
case untpd.Match(scrut, untpd.CaseDef(untpd.Tuple(elems), untpd.EmptyTree, rhs) :: Nil)
case untpd.Match(scrut, cases @ untpd.CaseDef(untpd.Tuple(elems), untpd.EmptyTree, rhs) :: Nil)
if scrut.span.isSynthetic && isParamRef(scrut) && elems.hasSameLengthAs(protoFormals) =>
// If `pt` is N-ary function type, convert synthetic lambda
// x$1 => x$1 match case (a1, ..., aN) => e
// to
// (a1, ..., aN) => e
val params1 = desugar.patternsToParams(elems)
if params1.hasSameLengthAs(elems) then
desugared = cpy.Function(tree)(params1, rhs)
desugared = desugar.makeCaseLambda(
cases, desugar.MatchCheck.IrrefutablePatDef, protoFormals.length)
case _ =>

if desugared.isEmpty then
Expand Down
5 changes: 5 additions & 0 deletions tests/pos/i19576.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@

object Test:
val a = Seq(0 -> 1, 2 -> 3)
val c = Seq("A", "B")
val z = for ((beg, end), c) <- a.lazyZip(c) yield c // Error before changes

0 comments on commit 6221361

Please sign in to comment.