@@ -4110,11 +4110,8 @@ object Types {
41104110 *
41114111 * @param origin The parameter that's tracked by the type variable.
41124112 * @param creatorState The typer state in which the variable was created.
4113- *
4114- * `owningTree` and `owner` are used to determine whether a type-variable can be instantiated
4115- * at some given point. See `Inferencing#interpolateUndetVars`.
41164113 */
4117- final class TypeVar (private var _origin : TypeParamRef , creatorState : TyperState ) extends CachedProxyType with ValueType {
4114+ final class TypeVar (private var _origin : TypeParamRef , creatorState : TyperState , level : Int ) extends CachedProxyType with ValueType {
41184115
41194116 def origin : TypeParamRef = _origin
41204117
@@ -4150,14 +4147,34 @@ object Types {
41504147 /** Is the variable already instantiated? */
41514148 def isInstantiated (implicit ctx : Context ): Boolean = instanceOpt.exists
41524149
4150+ def hygienic (tp : Type )(using Context ): Type =
4151+ val problemSyms = new TypeAccumulator [Set [Symbol ]]:
4152+ def apply (syms : Set [Symbol ], t : Type ): Set [Symbol ] = t match
4153+ case ref @ TermRef (NoPrefix , _)
4154+ if ref.symbol.maybeOwner.ownersIterator.length > level =>
4155+ syms + ref.symbol
4156+ case _ =>
4157+ foldOver(syms, t)
4158+ val problems = problemSyms(Set .empty, tp)
4159+ if problems.isEmpty then tp
4160+ else
4161+ val htp = ctx.typer.avoid(tp, problems.toList)
4162+ val msg = i " Inaccessible variables captured by instance for $this. \n $tp was fixed to $htp"
4163+ typr.println(msg)
4164+ val bound = ctx.typeComparer.fullUpperBound(origin)
4165+ if ! (htp <:< bound) then
4166+ throw new TypeError (s " $msg, \n but this does not conform to upper bound $bound" )
4167+ htp
4168+
41534169 /** Instantiate variable with given type */
41544170 def instantiateWith (tp : Type )(implicit ctx : Context ): Type = {
41554171 assert(tp ne this , s " self instantiation of ${tp.show}, constraint = ${ctx.typerState.constraint.show}" )
4156- typr.println(s " instantiating ${this .show} with ${tp.show}" )
4172+ val htp = hygienic(tp)
4173+ typr.println(s " instantiating ${this .show} with ${htp.show}" )
41574174 if ((ctx.typerState eq owningState.get) && ! ctx.typeComparer.subtypeCheckInProgress)
4158- inst = tp
4159- ctx.typerState.constraint = ctx.typerState.constraint.replace(origin, tp )
4160- tp
4175+ inst = htp
4176+ ctx.typerState.constraint = ctx.typerState.constraint.replace(origin, htp )
4177+ htp
41614178 }
41624179
41634180 /** Instantiate variable from the constraints over its `origin`.
0 commit comments