@@ -5004,19 +5004,30 @@ void CodeCompletionCallbacksImpl::doneParsing() {
5004
5004
bool OnRoot = !KPE->getComponents ().front ().isValid ();
5005
5005
Lookup.setIsSwiftKeyPathExpr (OnRoot);
5006
5006
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) {
5011
5024
// KeyPath expr with '?' (e.g. '\Ty.[0].prop?.another').
5012
5025
// Althogh expected type is optional, we should unwrap it because it's
5013
5026
// unwrapped.
5014
- ParsedType = ParsedType ->getOptionalObjectType ();
5027
+ baseType = baseType ->getOptionalObjectType ();
5015
5028
}
5016
5029
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);
5020
5031
break ;
5021
5032
}
5022
5033
0 commit comments