@@ -5004,19 +5004,30 @@ void CodeCompletionCallbacksImpl::doneParsing() {
50045004 bool OnRoot = !KPE->getComponents ().front ().isValid ();
50055005 Lookup.setIsSwiftKeyPathExpr (OnRoot);
50065006
5007- auto ParsedType = BGT->getGenericArgs ()[1 ];
5008- auto Components = KPE->getComponents ();
5009- if (Components.back ().getKind () ==
5010- KeyPathExpr::Component::Kind::OptionalWrap) {
5007+ Type baseType = BGT->getGenericArgs ()[OnRoot ? 0 : 1 ];
5008+ if (OnRoot && baseType->is <UnresolvedType>()) {
5009+ // Infer the root type of the keypath from the context type.
5010+ ExprContextInfo ContextInfo (CurDeclContext, ParsedExpr);
5011+ for (auto T : ContextInfo.getPossibleTypes ()) {
5012+ if (auto unwrapped = T->getOptionalObjectType ())
5013+ T = unwrapped;
5014+ if (!T->getAnyNominal () || !T->getAnyNominal ()->getKeyPathTypeKind () ||
5015+ T->hasUnresolvedType () || !T->is <BoundGenericType>())
5016+ continue ;
5017+ // Use the first KeyPath context type found.
5018+ baseType = T->castTo <BoundGenericType>()->getGenericArgs ()[0 ];
5019+ break ;
5020+ }
5021+ }
5022+ if (!OnRoot && KPE->getComponents ().back ().getKind () ==
5023+ KeyPathExpr::Component::Kind::OptionalWrap) {
50115024 // KeyPath expr with '?' (e.g. '\Ty.[0].prop?.another').
50125025 // Althogh expected type is optional, we should unwrap it because it's
50135026 // unwrapped.
5014- ParsedType = ParsedType ->getOptionalObjectType ();
5027+ baseType = baseType ->getOptionalObjectType ();
50155028 }
50165029
5017- // The second generic type argument of KeyPath<Root, Value> should be
5018- // the value we pull code completion results from.
5019- Lookup.getValueExprCompletions (ParsedType);
5030+ Lookup.getValueExprCompletions (baseType);
50205031 break ;
50215032 }
50225033
0 commit comments