@@ -4992,19 +4992,30 @@ void CodeCompletionCallbacksImpl::doneParsing() {
49924992 bool OnRoot = !KPE->getComponents ().front ().isValid ();
49934993 Lookup.setIsSwiftKeyPathExpr (OnRoot);
49944994
4995- auto ParsedType = BGT->getGenericArgs ()[1 ];
4996- auto Components = KPE->getComponents ();
4997- if (Components.back ().getKind () ==
4998- KeyPathExpr::Component::Kind::OptionalWrap) {
4995+ Type baseType = BGT->getGenericArgs ()[OnRoot ? 0 : 1 ];
4996+ if (OnRoot && baseType->is <UnresolvedType>()) {
4997+ // Infer the root type of the keypath from the context type.
4998+ ExprContextInfo ContextInfo (CurDeclContext, ParsedExpr);
4999+ for (auto T : ContextInfo.getPossibleTypes ()) {
5000+ if (auto unwrapped = T->getOptionalObjectType ())
5001+ T = unwrapped;
5002+ if (!T->getAnyNominal () || !T->getAnyNominal ()->getKeyPathTypeKind () ||
5003+ T->hasUnresolvedType () || !T->is <BoundGenericType>())
5004+ continue ;
5005+ // Use the first KeyPath context type found.
5006+ baseType = T->castTo <BoundGenericType>()->getGenericArgs ()[0 ];
5007+ break ;
5008+ }
5009+ }
5010+ if (!OnRoot && KPE->getComponents ().back ().getKind () ==
5011+ KeyPathExpr::Component::Kind::OptionalWrap) {
49995012 // KeyPath expr with '?' (e.g. '\Ty.[0].prop?.another').
50005013 // Althogh expected type is optional, we should unwrap it because it's
50015014 // unwrapped.
5002- ParsedType = ParsedType ->getOptionalObjectType ();
5015+ baseType = baseType ->getOptionalObjectType ();
50035016 }
50045017
5005- // The second generic type argument of KeyPath<Root, Value> should be
5006- // the value we pull code completion results from.
5007- Lookup.getValueExprCompletions (ParsedType);
5018+ Lookup.getValueExprCompletions (baseType);
50085019 break ;
50095020 }
50105021
0 commit comments