From 5739ee39de292fe127c103ebdf4d6b65fc399559 Mon Sep 17 00:00:00 2001 From: Yichen Xu Date: Fri, 21 Mar 2025 16:03:19 +0100 Subject: [PATCH] Fix: Prevent GADT reasoning in pattern alternatives --- compiler/src/dotty/tools/dotc/typer/Typer.scala | 2 ++ tests/neg/gadt-alternatives.scala | 9 +++++++++ 2 files changed, 11 insertions(+) create mode 100644 tests/neg/gadt-alternatives.scala diff --git a/compiler/src/dotty/tools/dotc/typer/Typer.scala b/compiler/src/dotty/tools/dotc/typer/Typer.scala index 03782a423fc7..6b7b840e7606 100644 --- a/compiler/src/dotty/tools/dotc/typer/Typer.scala +++ b/compiler/src/dotty/tools/dotc/typer/Typer.scala @@ -2805,8 +2805,10 @@ class Typer(@constructorOnly nestingLevel: Int = 0) extends Namer else assert(ctx.reporter.errorsReported) tree.withType(defn.AnyType) + val savedGadt = nestedCtx.gadt val trees1 = tree.trees.mapconserve(typed(_, pt)(using nestedCtx)) .mapconserve(ensureValueTypeOrWildcard) + nestedCtx.gadtState.restore(savedGadt) // Disable GADT reasoning for pattern alternatives assignType(cpy.Alternative(tree)(trees1), trees1) } diff --git a/tests/neg/gadt-alternatives.scala b/tests/neg/gadt-alternatives.scala new file mode 100644 index 000000000000..034f88ea5f24 --- /dev/null +++ b/tests/neg/gadt-alternatives.scala @@ -0,0 +1,9 @@ +enum Expr[+T]: + case StringVal(x: String) extends Expr[String] + case IntVal(x: Int) extends Expr[Int] + case IntValAlt(x: Int) extends Expr[Int] +import Expr.* +def eval[T](e: Expr[T]): T = e match + case StringVal(_) | IntVal(_) => "42" // error +def eval1[T](e: Expr[T]): T = e match + case IntValAlt(_) | IntVal(_) => 42 // error // limitation