@@ -4992,19 +4992,30 @@ void CodeCompletionCallbacksImpl::doneParsing() {
4992
4992
bool OnRoot = !KPE->getComponents ().front ().isValid ();
4993
4993
Lookup.setIsSwiftKeyPathExpr (OnRoot);
4994
4994
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) {
4999
5012
// KeyPath expr with '?' (e.g. '\Ty.[0].prop?.another').
5000
5013
// Althogh expected type is optional, we should unwrap it because it's
5001
5014
// unwrapped.
5002
- ParsedType = ParsedType ->getOptionalObjectType ();
5015
+ baseType = baseType ->getOptionalObjectType ();
5003
5016
}
5004
5017
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);
5008
5019
break ;
5009
5020
}
5010
5021
0 commit comments