@@ -1354,20 +1354,41 @@ namespace {
13541354 Type visitDeclRefExpr (DeclRefExpr *E) {
13551355 auto locator = CS.getConstraintLocator (E);
13561356
1357+ auto invalidateReference = [&]() -> Type {
1358+ auto *hole = CS.createTypeVariable (locator, TVO_CanBindToHole);
1359+ (void )CS.recordFix (AllowRefToInvalidDecl::create (CS, locator));
1360+ CS.setType (E, hole);
1361+ return hole;
1362+ };
1363+
13571364 Type knownType;
13581365 if (auto *VD = dyn_cast<VarDecl>(E->getDecl ())) {
13591366 knownType = CS.getTypeIfAvailable (VD);
13601367 if (!knownType)
13611368 knownType = CS.getVarType (VD);
13621369
13631370 if (knownType) {
1371+ // An out-of-scope type variable(s) could appear the type of
1372+ // a declaration only in diagnostic mode when invalid variable
1373+ // declaration is recursively referenced inside of a multi-statement
1374+ // closure located somewhere within its initializer e.g.:
1375+ // `let x = [<call>] { ... print(x) }`. It happens because the
1376+ // variable assumes the result type of its initializer unless
1377+ // its specified explicitly.
1378+ if (isa<ClosureExpr>(CurDC) && knownType->hasTypeVariable ()) {
1379+ if (knownType.findIf ([&](Type type) {
1380+ auto *typeVar = type->getAs <TypeVariableType>();
1381+ if (!typeVar || CS.getFixedType (typeVar))
1382+ return false ;
1383+
1384+ return !CS.isActiveTypeVariable (typeVar);
1385+ }))
1386+ return invalidateReference ();
1387+ }
1388+
13641389 // If the known type has an error, bail out.
13651390 if (knownType->hasError ()) {
1366- auto *hole = CS.createTypeVariable (locator, TVO_CanBindToHole);
1367- (void )CS.recordFix (AllowRefToInvalidDecl::create (CS, locator));
1368- if (!CS.hasType (E))
1369- CS.setType (E, hole);
1370- return hole;
1391+ return invalidateReference ();
13711392 }
13721393
13731394 if (!knownType->hasPlaceholder ()) {
@@ -1384,10 +1405,7 @@ namespace {
13841405 // (in getTypeOfReference) so we can match non-error param types.
13851406 if (!knownType && E->getDecl ()->isInvalid () &&
13861407 !CS.isForCodeCompletion ()) {
1387- auto *hole = CS.createTypeVariable (locator, TVO_CanBindToHole);
1388- (void )CS.recordFix (AllowRefToInvalidDecl::create (CS, locator));
1389- CS.setType (E, hole);
1390- return hole;
1408+ return invalidateReference ();
13911409 }
13921410
13931411 // Create an overload choice referencing this declaration and immediately
0 commit comments