@@ -5000,19 +5000,30 @@ void CodeCompletionCallbacksImpl::doneParsing() {
5000
5000
bool OnRoot = !KPE->getComponents ().front ().isValid ();
5001
5001
Lookup.setIsSwiftKeyPathExpr (OnRoot);
5002
5002
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) {
5007
5020
// KeyPath expr with '?' (e.g. '\Ty.[0].prop?.another').
5008
5021
// Althogh expected type is optional, we should unwrap it because it's
5009
5022
// unwrapped.
5010
- ParsedType = ParsedType ->getOptionalObjectType ();
5023
+ baseType = baseType ->getOptionalObjectType ();
5011
5024
}
5012
5025
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);
5016
5027
break ;
5017
5028
}
5018
5029
0 commit comments