@@ -19,6 +19,7 @@ import config.Feature
1919import util .SrcPos
2020import reporting .*
2121import NameKinds .WildcardParamName
22+ import cc .*
2223
2324object PostTyper {
2425 val name : String = " posttyper"
@@ -279,6 +280,17 @@ class PostTyper extends MacroTransform with InfoTransformer { thisPhase =>
279280 if ! tree.symbol.is(Package ) then tree
280281 else errorTree(tree, em " ${tree.symbol} cannot be used as a type " )
281282
283+ // Cleans up retains annotations in inferred type trees. This is needed because
284+ // during the typer, it is infeasible to correctly infer the capture sets in most
285+ // cases, resulting ill-formed capture sets that could crash the pickler later on.
286+ // See #20035.
287+ private def cleanupRetainsAnnot (symbol : Symbol , tpt : Tree )(using Context ): Tree =
288+ tpt match
289+ case tpt : InferredTypeTree if ! symbol.allOverriddenSymbols.hasNext =>
290+ val tpe1 = cleanupRetains(tpt.tpe)
291+ tpt.withType(tpe1)
292+ case _ => tpt
293+
282294 override def transform (tree : Tree )(using Context ): Tree =
283295 try tree match {
284296 // TODO move CaseDef case lower: keep most probable trees first for performance
@@ -388,7 +400,7 @@ class PostTyper extends MacroTransform with InfoTransformer { thisPhase =>
388400 registerIfHasMacroAnnotations(tree)
389401 checkErasedDef(tree)
390402 Checking .checkPolyFunctionType(tree.tpt)
391- val tree1 = cpy.ValDef (tree)(rhs = normalizeErasedRhs(tree.rhs, tree.symbol))
403+ val tree1 = cpy.ValDef (tree)(tpt = cleanupRetainsAnnot(tree.symbol, tree.tpt), rhs = normalizeErasedRhs(tree.rhs, tree.symbol))
392404 if tree1.removeAttachment(desugar.UntupledParam ).isDefined then
393405 checkStableSelection(tree.rhs)
394406 processValOrDefDef(super .transform(tree1))
@@ -398,7 +410,7 @@ class PostTyper extends MacroTransform with InfoTransformer { thisPhase =>
398410 checkErasedDef(tree)
399411 Checking .checkPolyFunctionType(tree.tpt)
400412 annotateContextResults(tree)
401- val tree1 = cpy.DefDef (tree)(rhs = normalizeErasedRhs(tree.rhs, tree.symbol))
413+ val tree1 = cpy.DefDef (tree)(tpt = cleanupRetainsAnnot(tree.symbol, tree.tpt), rhs = normalizeErasedRhs(tree.rhs, tree.symbol))
402414 processValOrDefDef(superAcc.wrapDefDef(tree1)(super .transform(tree1).asInstanceOf [DefDef ]))
403415 case tree : TypeDef =>
404416 registerIfHasMacroAnnotations(tree)
0 commit comments