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