Skip to content

Commit dd22105

Browse files
committed
Try to type as an Assign
1 parent ca5f467 commit dd22105

File tree

3 files changed

+25
-6
lines changed

3 files changed

+25
-6
lines changed

compiler/src/dotty/tools/dotc/typer/Typer.scala

+11-6
Original file line numberDiff line numberDiff line change
@@ -3398,7 +3398,7 @@ class Typer(@constructorOnly nestingLevel: Int = 0) extends Namer
33983398
/** Translate tuples of all arities */
33993399
def typedTuple(tree: untpd.Tuple, pt: Type)(using Context): Tree =
34003400
val tree1 = desugar.tuple(tree, pt)
3401-
checkAmbiguousNamedTuple(tree)
3401+
checkAmbiguousNamedTupleAssignment(tree)
34023402
if tree1 ne tree then typed(tree1, pt)
34033403
else
34043404
val arity = tree.trees.length
@@ -3424,14 +3424,19 @@ class Typer(@constructorOnly nestingLevel: Int = 0) extends Namer
34243424
val resTpe = TypeOps.nestedPairs(elemTpes)
34253425
app1.cast(resTpe)
34263426

3427-
def checkAmbiguousNamedTuple(tree: untpd.Tuple)(using Context): Unit =
3427+
/** Checks if `tree` is a named tuple with one element that could be
3428+
* interpreted as an assignment, such as `(x = 1)`. If so, issues a warning.
3429+
*/
3430+
def checkAmbiguousNamedTupleAssignment(tree: untpd.Tuple)(using Context): Unit =
34283431
tree.trees match
34293432
case List(NamedArg(name, value)) =>
3430-
val typedName = typedIdent(untpd.Ident(name), WildcardType)
3431-
val sym = typedName.symbol
3432-
if sym.exists && (sym.is(Flags.Mutable) || sym.setter.exists) then
3433+
val tmpCtx = ctx.fresh.setNewTyperState()
3434+
typedAssign(untpd.Assign(untpd.Ident(name), value), WildcardType)(using tmpCtx)
3435+
if !tmpCtx.reporter.hasErrors then
3436+
// If there are no errors typing the above, then the named tuple is
3437+
// ambiguous and we issue a warning.
34333438
report.migrationWarning(AmbiguousNamedTupleAssignment(name, value), tree.srcPos)
3434-
case _ =>
3439+
case _ => ()
34353440

34363441
/** Retrieve symbol attached to given tree */
34373442
protected def retrieveSym(tree: untpd.Tree)(using Context): Symbol = tree.removeAttachment(SymOfTree) match {

tests/warn/21681c.check

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
-- [E203] Syntax Migration Warning: tests/warn/21681c.scala:6:2 --------------------------------------------------------
2+
6 | (age = 29) // warn
3+
| ^^^^^^^^^^
4+
| Ambiguous syntax: this is interpreted as a named tuple with one element,
5+
| not as an assignment.
6+
|
7+
| To assign a value, use curly braces: `{age = 29}`.

tests/warn/21681c.scala

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
2+
object Test:
3+
def age: Int = ???
4+
def age_=(x: Int): Unit = ()
5+
age = 29
6+
(age = 29) // warn
7+

0 commit comments

Comments
 (0)