-
Notifications
You must be signed in to change notification settings - Fork 10.2k
/
ExprContextAnalysis.cpp
1262 lines (1128 loc) · 43.6 KB
/
ExprContextAnalysis.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===--- ExprContextAnalysis.cpp - Expession context analysis -------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "ExprContextAnalysis.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTVisitor.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DeclContext.h"
#include "swift/AST/Expr.h"
#include "swift/AST/GenericSignature.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/LazyResolver.h"
#include "swift/AST/Module.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/SourceFile.h"
#include "swift/AST/Stmt.h"
#include "swift/AST/Type.h"
#include "swift/AST/Types.h"
#include "swift/Basic/SourceManager.h"
#include "swift/IDE/CodeCompletion.h"
#include "swift/Sema/IDETypeChecking.h"
#include "swift/Subsystems.h"
#include "clang/AST/Attr.h"
#include "clang/AST/Decl.h"
#include "llvm/ADT/SmallSet.h"
using namespace swift;
using namespace ide;
//===----------------------------------------------------------------------===//
// typeCheckContextAt(DeclContext, SourceLoc)
//===----------------------------------------------------------------------===//
namespace {
void typeCheckContextImpl(DeclContext *DC, SourceLoc Loc) {
// Nothing to type check in module context.
if (DC->isModuleScopeContext())
return;
typeCheckContextImpl(DC->getParent(), Loc);
// Type-check this context.
switch (DC->getContextKind()) {
case DeclContextKind::AbstractClosureExpr:
case DeclContextKind::Module:
case DeclContextKind::SerializedLocal:
case DeclContextKind::TopLevelCodeDecl:
case DeclContextKind::EnumElementDecl:
case DeclContextKind::GenericTypeDecl:
case DeclContextKind::SubscriptDecl:
// Nothing to do for these.
break;
case DeclContextKind::Initializer:
if (auto *patternInit = dyn_cast<PatternBindingInitializer>(DC)) {
if (auto *PBD = patternInit->getBinding()) {
auto i = patternInit->getBindingIndex();
PBD->getPattern(i)->forEachVariable(
[](VarDecl *VD) { (void)VD->getInterfaceType(); });
if (PBD->getInit(i)) {
if (!PBD->isInitializerChecked(i))
typeCheckPatternBinding(PBD, i);
}
}
}
break;
case DeclContextKind::AbstractFunctionDecl: {
auto *AFD = cast<AbstractFunctionDecl>(DC);
auto &SM = DC->getASTContext().SourceMgr;
auto bodyRange = AFD->getBodySourceRange();
if (SM.rangeContainsTokenLoc(bodyRange, Loc)) {
swift::typeCheckAbstractFunctionBodyAtLoc(AFD, Loc);
} else {
assert(bodyRange.isInvalid() && "The body should not be parsed if the "
"completion happens in the signature");
}
break;
}
case DeclContextKind::ExtensionDecl:
// Make sure the extension has been bound, in case it is in an
// inactive #if or something weird like that.
cast<ExtensionDecl>(DC)->computeExtendedNominal();
break;
case DeclContextKind::FileUnit:
llvm_unreachable("module scope context handled above");
}
}
} // anonymous namespace
void swift::ide::typeCheckContextAt(DeclContext *DC, SourceLoc Loc) {
while (isa<AbstractClosureExpr>(DC))
DC = DC->getParent();
if (auto *TLCD = dyn_cast<TopLevelCodeDecl>(DC)) {
typeCheckTopLevelCodeDecl(TLCD);
} else {
typeCheckContextImpl(DC, Loc);
}
}
//===----------------------------------------------------------------------===//
// findParsedExpr(DeclContext, Expr)
//===----------------------------------------------------------------------===//
namespace {
class ExprFinder : public ASTWalker {
SourceManager &SM;
SourceRange TargetRange;
Expr *FoundExpr = nullptr;
template <typename NodeType> bool isInterstingRange(NodeType *Node) {
return SM.rangeContains(Node->getSourceRange(), TargetRange);
}
bool shouldIgnore(Expr *E) {
// E.g. instanceOfDerived.methodInBaseReturningSelf().#^HERE^#'
// When calling a method in a base class returning 'Self', the call
// expression itself has the type of the base class. That is wrapped with
// CovariantReturnConversionExpr which downcasts it to the derived class.
if (isa<CovariantReturnConversionExpr>(E))
return false;
// E.g. TypeName(#^HERE^#
// In this case, we want the type expression instead of a reference to the
// initializer.
if (isa<ConstructorRefCallExpr>(E))
return true;
// Ignore other implicit expression.
if (E->isImplicit())
return true;
return false;
}
public:
ExprFinder(SourceManager &SM, SourceRange TargetRange)
: SM(SM), TargetRange(TargetRange) {}
Expr *get() const { return FoundExpr; }
std::pair<bool, Expr *> walkToExprPre(Expr *E) override {
if (TargetRange == E->getSourceRange() && !shouldIgnore(E)) {
assert(!FoundExpr && "non-nullptr for found expr");
FoundExpr = E;
return {false, nullptr};
}
return {isInterstingRange(E), E};
}
std::pair<bool, Pattern *> walkToPatternPre(Pattern *P) override {
return {isInterstingRange(P), P};
}
std::pair<bool, Stmt *> walkToStmtPre(Stmt *S) override {
return {isInterstingRange(S), S};
}
bool walkToTypeLocPre(TypeLoc &TL) override { return false; }
bool walkToTypeReprPre(TypeRepr *T) override { return false; }
};
} // anonymous namespace
Expr *swift::ide::findParsedExpr(const DeclContext *DC,
SourceRange TargetRange) {
ExprFinder finder(DC->getASTContext().SourceMgr, TargetRange);
const_cast<DeclContext *>(DC)->walkContext(finder);
return finder.get();
}
//===----------------------------------------------------------------------===//
// removeCodeCompletionExpr(ASTContext, Expr)
//===----------------------------------------------------------------------===//
namespace {
// TODO: Implement other expressions?
class CCExprRemover: public ASTWalker, public ExprVisitor<CCExprRemover, Expr *> {
ASTContext &Ctx;
public:
bool Removed = false;
CCExprRemover(ASTContext &Ctx) : Ctx(Ctx) {}
Expr *visitCallExpr(CallExpr *E) {
SourceLoc lParenLoc, rParenLoc;
SmallVector<Identifier, 2> argLabels;
SmallVector<SourceLoc, 2> argLabelLocs;
SmallVector<Expr *, 2> args;
SmallVector<TrailingClosure, 2> trailingClosures;
bool removing = false;
if (auto paren = dyn_cast<ParenExpr>(E->getArg())) {
if (isa<CodeCompletionExpr>(paren->getSubExpr())) {
lParenLoc = paren->getLParenLoc();
rParenLoc = paren->getRParenLoc();
removing = true;
}
} else if (auto tuple = dyn_cast<TupleExpr>(E->getArg())) {
lParenLoc = tuple->getLParenLoc();
rParenLoc = tuple->getRParenLoc();
assert((!E->getUnlabeledTrailingClosureIndex().hasValue() ||
(tuple->getNumElements() == E->getArgumentLabels().size() &&
tuple->getNumElements() == E->getArgumentLabelLocs().size())) &&
"CallExpr with trailing closure must have the same number of "
"argument labels");
assert(tuple->getNumElements() == E->getArgumentLabels().size());
assert(tuple->getNumElements() == E->getArgumentLabelLocs().size() ||
E->getArgumentLabelLocs().size() == 0);
bool hasArgumentLabelLocs = E->getArgumentLabelLocs().size() > 0;
for (unsigned i = 0, e = tuple->getNumElements(); i != e; ++i) {
if (isa<CodeCompletionExpr>(tuple->getElement(i))) {
removing = true;
continue;
}
if (!E->getUnlabeledTrailingClosureIndex().hasValue() ||
i < *E->getUnlabeledTrailingClosureIndex()) {
// Normal arguments.
argLabels.push_back(E->getArgumentLabels()[i]);
if (hasArgumentLabelLocs)
argLabelLocs.push_back(E->getArgumentLabelLocs()[i]);
args.push_back(tuple->getElement(i));
} else {
// Trailing closure arguments.
trailingClosures.emplace_back(E->getArgumentLabels()[i],
E->getArgumentLabelLocs()[i],
tuple->getElement(i));
}
}
}
if (removing) {
Removed = true;
return CallExpr::create(Ctx, E->getFn(), lParenLoc, args, argLabels,
argLabelLocs, rParenLoc, trailingClosures,
E->isImplicit());
}
return E;
}
Expr *visitExpr(Expr *E) {
return E;
}
std::pair<bool, Expr *> walkToExprPre(Expr *E) override {
if (Removed)
return {false, nullptr};
E = visit(E);
return {!Removed, E};
}
std::pair<bool, Stmt *> walkToStmtPre(Stmt *S) override {
if (Removed)
return {false, nullptr};
return {true, S};
}
bool walkToDeclPre(Decl *D) override {
return !Removed;
}
};
}
bool swift::ide::removeCodeCompletionExpr(ASTContext &Ctx, Expr *&expr) {
CCExprRemover remover(Ctx);
expr = expr->walk(remover);
return remover.Removed;
}
//===----------------------------------------------------------------------===//
// getReturnTypeFromContext(DeclContext)
//===----------------------------------------------------------------------===//
Type swift::ide::getReturnTypeFromContext(const DeclContext *DC) {
if (auto FD = dyn_cast<AbstractFunctionDecl>(DC)) {
auto Ty = FD->getInterfaceType();
if (FD->getDeclContext()->isTypeContext())
Ty = FD->getMethodInterfaceType();
if (auto FT = Ty->getAs<AnyFunctionType>())
return DC->mapTypeIntoContext(FT->getResult());
} else if (auto ACE = dyn_cast<AbstractClosureExpr>(DC)) {
if (ACE->getType() && !ACE->getType()->hasError())
return ACE->getResultType();
if (auto CE = dyn_cast<ClosureExpr>(ACE)) {
if (CE->hasExplicitResultType()) {
if (auto ty = CE->getExplicitResultType()) {
return ty;
}
auto typeLoc = TypeLoc{CE->getExplicitResultTypeRepr()};
if (swift::performTypeLocChecking(DC->getASTContext(),
typeLoc,
/*isSILMode*/ false,
/*isSILType*/ false,
DC->getGenericEnvironmentOfContext(),
const_cast<DeclContext *>(DC),
/*diagnostics*/ false)) {
return Type();
}
return typeLoc.getType();
}
}
}
return Type();
}
//===----------------------------------------------------------------------===//
// ExprContextInfo(DeclContext, SourceRange)
//===----------------------------------------------------------------------===//
namespace {
class ExprParentFinder : public ASTWalker {
friend class ExprContextAnalyzer;
Expr *ChildExpr;
std::function<bool(ParentTy, ParentTy)> Predicate;
bool arePositionsSame(Expr *E1, Expr *E2) {
return E1->getSourceRange().Start == E2->getSourceRange().Start &&
E1->getSourceRange().End == E2->getSourceRange().End;
}
public:
llvm::SmallVector<ParentTy, 5> Ancestors;
ExprParentFinder(Expr *ChildExpr,
std::function<bool(ParentTy, ParentTy)> Predicate)
: ChildExpr(ChildExpr), Predicate(Predicate) {}
std::pair<bool, Expr *> walkToExprPre(Expr *E) override {
// Finish if we found the target. 'ChildExpr' might have been replaced
// with typechecked expression. In that case, match the position.
if (E == ChildExpr || arePositionsSame(E, ChildExpr))
return {false, nullptr};
if (E != ChildExpr && Predicate(E, Parent)) {
Ancestors.push_back(E);
return {true, E};
}
return {true, E};
}
Expr *walkToExprPost(Expr *E) override {
if (Predicate(E, Parent))
Ancestors.pop_back();
return E;
}
std::pair<bool, Stmt *> walkToStmtPre(Stmt *S) override {
if (Predicate(S, Parent))
Ancestors.push_back(S);
return {true, S};
}
Stmt *walkToStmtPost(Stmt *S) override {
if (Predicate(S, Parent))
Ancestors.pop_back();
return S;
}
bool walkToDeclPre(Decl *D) override {
if (Predicate(D, Parent))
Ancestors.push_back(D);
return true;
}
bool walkToDeclPost(Decl *D) override {
if (Predicate(D, Parent))
Ancestors.pop_back();
return true;
}
std::pair<bool, Pattern *> walkToPatternPre(Pattern *P) override {
if (Predicate(P, Parent))
Ancestors.push_back(P);
return {true, P};
}
Pattern *walkToPatternPost(Pattern *P) override {
if (Predicate(P, Parent))
Ancestors.pop_back();
return P;
}
};
/// Collect function (or subscript) members with the given \p name on \p baseTy.
static void collectPossibleCalleesByQualifiedLookup(
DeclContext &DC, Type baseTy, DeclNameRef name,
SmallVectorImpl<FunctionTypeAndDecl> &candidates) {
auto baseInstanceTy = baseTy->getMetatypeInstanceType();
if (!baseInstanceTy->mayHaveMembers())
return;
bool isOnMetaType = baseTy->is<AnyMetatypeType>();
SmallVector<ValueDecl *, 2> decls;
if (!DC.lookupQualified(baseInstanceTy,
name.withoutArgumentLabels(),
NL_QualifiedDefault | NL_ProtocolMembers,
decls))
return;
llvm::DenseMap<std::pair<char, CanType>, size_t> known;
auto *baseNominal = baseInstanceTy->getAnyNominal();
for (auto *VD : decls) {
if ((!isa<AbstractFunctionDecl>(VD) && !isa<SubscriptDecl>(VD)) ||
VD->shouldHideFromEditor())
continue;
if (!isMemberDeclApplied(&DC, baseInstanceTy, VD))
continue;
Type declaredMemberType = VD->getInterfaceType();
if (!declaredMemberType->is<AnyFunctionType>())
continue;
if (VD->getDeclContext()->isTypeContext()) {
if (isa<FuncDecl>(VD)) {
if (!isOnMetaType && VD->isStatic())
continue;
if (isOnMetaType == VD->isStatic())
declaredMemberType =
declaredMemberType->castTo<AnyFunctionType>()->getResult();
} else if (isa<ConstructorDecl>(VD)) {
if (!isOnMetaType)
continue;
declaredMemberType =
declaredMemberType->castTo<AnyFunctionType>()->getResult();
} else if (isa<SubscriptDecl>(VD)) {
if (isOnMetaType != VD->isStatic())
continue;
}
}
auto subs = baseInstanceTy->getMemberSubstitutionMap(
DC.getParentModule(), VD,
VD->getInnermostDeclContext()->getGenericEnvironmentOfContext());
auto fnType = declaredMemberType.subst(subs);
if (!fnType || !fnType->is<AnyFunctionType>())
continue;
// If we are calling on a type alias type, replace the canonicalized type
// in the function type with the type alias.
if (isa<SugarType>(baseInstanceTy.getPointer())) {
auto canBaseTy = baseInstanceTy->getCanonicalType();
fnType = fnType.transform([&](Type t) -> Type {
if (t->getCanonicalType()->isEqual(canBaseTy))
return baseInstanceTy;
return t;
});
}
auto semanticContext = SemanticContextKind::CurrentNominal;
if (baseNominal &&
VD->getDeclContext()->getSelfNominalTypeDecl() != baseNominal)
semanticContext = SemanticContextKind::Super;
FunctionTypeAndDecl entry(fnType->castTo<AnyFunctionType>(), VD,
semanticContext);
// Remember the index of the entry.
auto knownResult = known.insert(
{{VD->isStatic(), fnType->getCanonicalType()}, candidates.size()});
if (knownResult.second) {
candidates.push_back(entry);
continue;
}
auto idx = knownResult.first->second;
if (AvailableAttr::isUnavailable(candidates[idx].Decl) &&
!AvailableAttr::isUnavailable(VD)) {
// Replace the previously found "unavailable" with the "available" one.
candidates[idx] = entry;
}
// Otherwise, skip redundant results.
}
}
/// Collect function (or subscript) members with the given \p name on
/// \p baseExpr expression.
static void collectPossibleCalleesByQualifiedLookup(
DeclContext &DC, Expr *baseExpr, DeclNameRef name,
SmallVectorImpl<FunctionTypeAndDecl> &candidates) {
ConcreteDeclRef ref = nullptr;
// Re-typecheck TypeExpr so it's typechecked without the arguments which may
// affects the inference of the generic arguments.
if (TypeExpr *tyExpr = dyn_cast<TypeExpr>(baseExpr)) {
if (!tyExpr->isImplicit())
tyExpr->setType(nullptr);
}
Type baseTy = baseExpr->getType();
if (!baseTy || baseTy->is<ErrorType>()) {
auto baseTyOpt = getTypeOfCompletionContextExpr(
DC.getASTContext(), &DC, CompletionTypeCheckKind::Normal, baseExpr,
ref);
if (!baseTyOpt)
return;
baseTy = *baseTyOpt;
}
baseTy = baseTy->getWithoutSpecifierType();
// Use metatype for lookup 'super.init' if it's inside constructors.
if (isa<SuperRefExpr>(baseExpr) && isa<ConstructorDecl>(DC) &&
name == DeclNameRef::createConstructor())
baseTy = MetatypeType::get(baseTy);
collectPossibleCalleesByQualifiedLookup(DC, baseTy, name, candidates);
// Add virtual 'subscript<Value>(keyPath: KeyPath<Root, Value>) -> Value'.
if (name.getBaseName() == DeclBaseName::createSubscript() &&
(baseTy->getAnyNominal() || baseTy->is<ArchetypeType>() ||
baseTy->is<TupleType>())) {
auto &Ctx = DC.getASTContext();
auto *kpDecl = Ctx.getKeyPathDecl();
Type kpTy = kpDecl->mapTypeIntoContext(kpDecl->getDeclaredInterfaceType());
Type kpValueTy = kpTy->castTo<BoundGenericType>()->getGenericArgs()[1];
kpTy = BoundGenericType::get(kpDecl, Type(), {baseTy, kpValueTy});
Type fnTy = FunctionType::get(
{AnyFunctionType::Param(kpTy, Ctx.Id_keyPath)}, kpValueTy);
candidates.emplace_back(fnTy->castTo<AnyFunctionType>(), nullptr);
}
}
/// For the given \c callExpr, collect possible callee types and declarations.
static bool collectPossibleCalleesForApply(
DeclContext &DC, ApplyExpr *callExpr,
SmallVectorImpl<FunctionTypeAndDecl> &candidates) {
auto *fnExpr = callExpr->getFn();
if (auto *DRE = dyn_cast<DeclRefExpr>(fnExpr)) {
if (auto *decl = DRE->getDecl()) {
Type declTy = fnExpr->getType();
if ((!declTy || declTy->hasError() || declTy->hasUnresolvedType()) &&
decl->hasInterfaceType()) {
declTy = decl->getInterfaceType();
declTy = decl->getInnermostDeclContext()->mapTypeIntoContext(declTy);
}
if (declTy) {
declTy = declTy->getWithoutSpecifierType();
if (auto *funcTy = declTy->getAs<AnyFunctionType>())
candidates.emplace_back(funcTy, decl);
}
}
} else if (auto *OSRE = dyn_cast<OverloadSetRefExpr>(fnExpr)) {
for (auto *decl : OSRE->getDecls()) {
if (decl->hasInterfaceType()) {
auto declTy = decl->getInterfaceType();
declTy = decl->getInnermostDeclContext()->mapTypeIntoContext(declTy);
if (auto *funcType = declTy->getAs<AnyFunctionType>())
candidates.emplace_back(funcType, decl);
}
}
} else if (auto *UDE = dyn_cast<UnresolvedDotExpr>(fnExpr)) {
collectPossibleCalleesByQualifiedLookup(DC, UDE->getBase(), UDE->getName(),
candidates);
} else if (auto *DSCE = dyn_cast<DotSyntaxCallExpr>(fnExpr)) {
if (auto *DRE = dyn_cast<DeclRefExpr>(DSCE->getFn())) {
collectPossibleCalleesByQualifiedLookup(
DC, DSCE->getArg(), DeclNameRef(DRE->getDecl()->getName()),
candidates);
}
} else if (auto CRCE = dyn_cast<ConstructorRefCallExpr>(fnExpr)) {
collectPossibleCalleesByQualifiedLookup(
DC, CRCE->getArg(), DeclNameRef::createConstructor(), candidates);
}
if (!candidates.empty())
return true;
ConcreteDeclRef refDecl = nullptr;
Type fnType = fnExpr->getType();
if (fnType) {
refDecl = fnExpr->getReferencedDecl();
if (!refDecl)
if (auto apply = dyn_cast<ApplyExpr>(fnExpr))
refDecl = apply->getFn()->getReferencedDecl();
}
if (!fnType) {
auto fnTypeOpt = getTypeOfCompletionContextExpr(
DC.getASTContext(), &DC, CompletionTypeCheckKind::Normal, fnExpr,
refDecl);
if (fnTypeOpt)
fnType = *fnTypeOpt;
}
if (!fnType || fnType->hasUnresolvedType() || fnType->hasError())
return false;
fnType = fnType->getWithoutSpecifierType();
if (auto *AFT = fnType->getAs<AnyFunctionType>()) {
candidates.emplace_back(AFT, refDecl.getDecl());
} else if (auto *AMT = fnType->getAs<AnyMetatypeType>()) {
auto baseTy = AMT->getInstanceType();
if (isa<TypeExpr>(fnExpr) && baseTy->mayHaveMembers()) {
collectPossibleCalleesByQualifiedLookup(
DC, fnExpr, DeclNameRef::createConstructor(), candidates);
}
} else {
// Otherwise, look for `callAsFunction` (SE-0253).
collectPossibleCalleesByQualifiedLookup(
DC, fnExpr, DeclNameRef(DC.getASTContext().Id_callAsFunction),
candidates);
}
return !candidates.empty();
}
/// For the given \c subscriptExpr, collect possible callee types and
/// declarations.
static bool collectPossibleCalleesForSubscript(
DeclContext &DC, SubscriptExpr *subscriptExpr,
SmallVectorImpl<FunctionTypeAndDecl> &candidates) {
if (subscriptExpr->hasDecl()) {
if (auto SD = dyn_cast<SubscriptDecl>(subscriptExpr->getDecl().getDecl())) {
auto declType = SD->getInterfaceType();
declType = declType.subst(subscriptExpr->getDecl().getSubstitutions());
if (auto *funcType = declType->getAs<AnyFunctionType>())
candidates.emplace_back(funcType, SD);
}
} else {
collectPossibleCalleesByQualifiedLookup(DC, subscriptExpr->getBase(),
DeclNameRef::createSubscript(),
candidates);
}
return !candidates.empty();
}
/// For the given \p unresolvedMemberExpr, collect possible callee types and
/// declarations.
static bool collectPossibleCalleesForUnresolvedMember(
DeclContext &DC, UnresolvedMemberExpr *unresolvedMemberExpr,
SmallVectorImpl<FunctionTypeAndDecl> &candidates) {
auto currModule = DC.getParentModule();
// Get the context of the expression itself.
ExprContextInfo contextInfo(&DC, unresolvedMemberExpr);
for (auto expectedTy : contextInfo.getPossibleTypes()) {
if (!expectedTy->mayHaveMembers())
continue;
SmallVector<FunctionTypeAndDecl, 2> members;
collectPossibleCalleesByQualifiedLookup(DC, MetatypeType::get(expectedTy),
unresolvedMemberExpr->getName(),
members);
for (auto member : members) {
if (isReferenceableByImplicitMemberExpr(currModule, &DC, expectedTy,
member.Decl))
candidates.push_back(member);
}
}
return !candidates.empty();
}
/// Get index of \p CCExpr in \p Args. \p Args is usually a \c TupleExpr
/// or \c ParenExpr.
/// \returns \c true if success, \c false if \p CCExpr is not a part of \p Args.
static bool getPositionInArgs(DeclContext &DC, Expr *Args, Expr *CCExpr,
unsigned &Position, bool &HasName) {
if (isa<ParenExpr>(Args)) {
HasName = false;
Position = 0;
return true;
}
auto *tuple = dyn_cast<TupleExpr>(Args);
if (!tuple)
return false;
auto &SM = DC.getASTContext().SourceMgr;
for (unsigned i = 0, n = tuple->getNumElements(); i != n; ++i) {
if (SM.isBeforeInBuffer(tuple->getElement(i)->getEndLoc(),
CCExpr->getStartLoc()))
continue;
HasName = tuple->getElementNameLoc(i).isValid();
Position = i;
return true;
}
return false;
}
/// Given an expression and its context, the analyzer tries to figure out the
/// expected type of the expression by analyzing its context.
class ExprContextAnalyzer {
DeclContext *DC;
Expr *ParsedExpr;
SourceManager &SM;
ASTContext &Context;
// Results populated by Analyze()
SmallVectorImpl<Type> &PossibleTypes;
SmallVectorImpl<PossibleParamInfo> &PossibleParams;
SmallVectorImpl<FunctionTypeAndDecl> &PossibleCallees;
Expr *&AnalyzedExpr;
bool &singleExpressionBody;
void recordPossibleType(Type ty) {
if (!ty || ty->is<ErrorType>())
return;
PossibleTypes.push_back(ty->getRValueType());
}
void recordPossibleParam(const AnyFunctionType::Param *arg, bool isRequired) {
PossibleParams.emplace_back(arg, isRequired);
}
/// Collect context information at call argument position.
bool analyzeApplyExpr(Expr *E) {
// Collect parameter lists for possible func decls.
SmallVector<FunctionTypeAndDecl, 2> Candidates;
Expr *Arg = nullptr;
if (auto *applyExpr = dyn_cast<ApplyExpr>(E)) {
if (!collectPossibleCalleesForApply(*DC, applyExpr, Candidates))
return false;
Arg = applyExpr->getArg();
} else if (auto *subscriptExpr = dyn_cast<SubscriptExpr>(E)) {
if (!collectPossibleCalleesForSubscript(*DC, subscriptExpr, Candidates))
return false;
Arg = subscriptExpr->getIndex();
} else if (auto *unresolvedMemberExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
if (!collectPossibleCalleesForUnresolvedMember(*DC, unresolvedMemberExpr,
Candidates))
return false;
Arg = unresolvedMemberExpr->getArgument();
} else {
llvm_unreachable("unexpected expression kind");
}
assert(!Candidates.empty());
PossibleCallees.assign(Candidates.begin(), Candidates.end());
// Determine the position of code completion token in call argument.
unsigned Position;
bool HasName;
if (!getPositionInArgs(*DC, Arg, ParsedExpr, Position, HasName))
return false;
// Collect possible types (or labels) at the position.
// FIXME: Take variadic and optional parameters into account. We need to do
// something equivalent to 'constraints::matchCallArguments'
{
bool MayNeedName = !HasName && !E->isImplicit() &&
(isa<CallExpr>(E) | isa<SubscriptExpr>(E) ||
isa<UnresolvedMemberExpr>(E));
SmallPtrSet<TypeBase *, 4> seenTypes;
llvm::SmallSet<std::pair<Identifier, TypeBase *>, 4> seenArgs;
for (auto &typeAndDecl : Candidates) {
DeclContext *memberDC = nullptr;
if (typeAndDecl.Decl)
memberDC = typeAndDecl.Decl->getInnermostDeclContext();
auto Params = typeAndDecl.Type->getParams();
ParameterList *paramList = nullptr;
if (auto VD = typeAndDecl.Decl) {
if (auto FD = dyn_cast<AbstractFunctionDecl>(VD))
paramList = FD->getParameters();
else if (auto SD = dyn_cast<SubscriptDecl>(VD))
paramList = SD->getIndices();
if (paramList && paramList->size() != Params.size())
paramList = nullptr;
}
for (auto Pos = Position; Pos < Params.size(); ++Pos) {
const auto ¶mType = Params[Pos];
Type ty = paramType.getPlainType();
if (memberDC && ty->hasTypeParameter())
ty = memberDC->mapTypeIntoContext(ty);
bool canSkip =
paramList && (paramList->get(Pos)->isDefaultArgument() ||
paramList->get(Pos)->isVariadic());
if (paramType.hasLabel() && MayNeedName) {
if (seenArgs.insert({paramType.getLabel(), ty.getPointer()}).second)
recordPossibleParam(¶mType, !canSkip);
} else {
auto argTy = ty;
if (paramType.isInOut())
argTy = InOutType::get(argTy);
if (seenTypes.insert(argTy.getPointer()).second)
recordPossibleType(argTy);
}
if (!canSkip)
break;
}
// If the argument position is out of expeceted number, indicate that
// with optional nullptr param.
if (Position >= Params.size()) {
if (seenArgs.insert({Identifier(), nullptr}).second)
recordPossibleParam(nullptr, /*isRequired=*/false);
}
}
}
return !PossibleTypes.empty() || !PossibleParams.empty();
}
void analyzeExpr(Expr *Parent) {
AnalyzedExpr = Parent;
switch (Parent->getKind()) {
case ExprKind::Call:
case ExprKind::Subscript:
case ExprKind::UnresolvedMember:
case ExprKind::Binary:
case ExprKind::PrefixUnary: {
analyzeApplyExpr(Parent);
break;
}
case ExprKind::Array: {
if (auto type = ParsedExpr->getType()) {
recordPossibleType(type);
break;
}
// Check context types of the array literal expression.
ExprContextInfo arrayCtxtInfo(DC, Parent);
for (auto arrayT : arrayCtxtInfo.getPossibleTypes()) {
if (auto boundGenericT = arrayT->getAs<BoundGenericType>()) {
// let _: [Element] = [#HERE#]
// In this case, 'Element' is the expected type.
if (boundGenericT->getDecl() == Context.getArrayDecl())
recordPossibleType(boundGenericT->getGenericArgs()[0]);
// let _: [Key : Value] = [#HERE#]
// In this case, 'Key' is the expected type.
if (boundGenericT->getDecl() == Context.getDictionaryDecl())
recordPossibleType(boundGenericT->getGenericArgs()[0]);
}
}
break;
}
case ExprKind::Dictionary: {
// Check context types of the dictionary literal expression.
ExprContextInfo dictCtxtInfo(DC, Parent);
for (auto dictT : dictCtxtInfo.getPossibleTypes()) {
if (auto boundGenericT = dictT->getAs<BoundGenericType>()) {
if (boundGenericT->getDecl() == Context.getDictionaryDecl()) {
if (ParsedExpr->isImplicit() && isa<TupleExpr>(ParsedExpr)) {
// let _: [Key : Value] = [#HERE#:]
// let _: [Key : Value] = [#HERE#:val]
// let _: [Key : Value] = [key:#HERE#]
// In this case, this is called by 'ExprKind::Tuple' case. Return
// '(Key,Value)' here, 'ExprKind::Tuple' branch can decide which
// type in the tuple type is the exprected type.
SmallVector<TupleTypeElt, 2> elts;
for (auto genericArg : boundGenericT->getGenericArgs())
elts.emplace_back(genericArg);
recordPossibleType(TupleType::get(elts, DC->getASTContext()));
} else {
// let _: [Key : Value] = [key: val, #HERE#]
// In this case, assume 'Key' is the expected type.
if (boundGenericT->getDecl() == Context.getDictionaryDecl())
recordPossibleType(boundGenericT->getGenericArgs()[0]);
}
}
}
}
break;
}
case ExprKind::If: {
auto *IE = cast<IfExpr>(Parent);
if (IE->isFolded() &&
SM.rangeContains(IE->getCondExpr()->getSourceRange(),
ParsedExpr->getSourceRange())) {
recordPossibleType(Context.getBoolDecl()->getDeclaredInterfaceType());
break;
}
ExprContextInfo ternaryCtxtInfo(DC, Parent);
for (auto ternaryT : ternaryCtxtInfo.getPossibleTypes())
recordPossibleType(ternaryT);
break;
}
case ExprKind::Assign: {
auto *AE = cast<AssignExpr>(Parent);
// Make sure code completion is on the right hand side.
if (SM.isBeforeInBuffer(AE->getEqualLoc(), ParsedExpr->getStartLoc())) {
// The destination is of the expected type.
auto *destExpr = AE->getDest();
if (auto type = destExpr->getType()) {
recordPossibleType(type);
} else if (auto *DRE = dyn_cast<DeclRefExpr>(destExpr)) {
if (auto *decl = DRE->getDecl()) {
if (decl->hasInterfaceType())
recordPossibleType(decl->getDeclContext()->mapTypeIntoContext(
decl->getInterfaceType()));
}
}
}
break;
}
case ExprKind::Tuple: {
TupleType *tupleT = nullptr;
if (Parent->getType() && Parent->getType()->is<TupleType>()) {
tupleT = Parent->getType()->castTo<TupleType>();
} else {
ExprContextInfo tupleCtxtInfo(DC, Parent);
for (auto possibleT : tupleCtxtInfo.getPossibleTypes()) {
if (auto possibleTupleT = possibleT->getAs<TupleType>()) {
tupleT = possibleTupleT;
break;
}
}
if (!tupleT)
return;
}
unsigned Position = 0;
bool HasName;
if (getPositionInArgs(*DC, Parent, ParsedExpr, Position, HasName)) {
// The expected type may have fewer number of elements.
if (Position < tupleT->getNumElements())
recordPossibleType(tupleT->getElementType(Position));
}
break;
}
case ExprKind::Closure: {
auto *CE = cast<ClosureExpr>(Parent);
assert(isSingleExpressionBodyForCodeCompletion(CE->getBody()));
singleExpressionBody = true;
recordPossibleType(getReturnTypeFromContext(CE));
break;
}
default:
llvm_unreachable("Unhandled expression kind.");
}
}
void analyzeStmt(Stmt *Parent) {
switch (Parent->getKind()) {
case StmtKind::Return:
recordPossibleType(getReturnTypeFromContext(DC));
break;
case StmtKind::ForEach:
if (auto SEQ = cast<ForEachStmt>(Parent)->getSequence()) {
if (containsTarget(SEQ)) {
recordPossibleType(
Context.getSequenceDecl()->getDeclaredInterfaceType());
}
}
break;
case StmtKind::RepeatWhile:
case StmtKind::If:
case StmtKind::While:
case StmtKind::Guard:
if (isBoolConditionOf(Parent)) {
recordPossibleType(Context.getBoolDecl()->getDeclaredInterfaceType());
}
break;
default:
llvm_unreachable("Unhandled statement kind.");
}
}
bool isBoolConditionOf(Stmt *parent) {
if (auto *repeat = dyn_cast<RepeatWhileStmt>(parent)) {
return repeat->getCond() && containsTarget(repeat->getCond());
}
if (auto *conditional = dyn_cast<LabeledConditionalStmt>(parent)) {
for (StmtConditionElement cond : conditional->getCond()) {
if (auto *E = cond.getBooleanOrNull()) {
if (containsTarget(E)) {
return true;
}
}
}
}
return false;
}
bool containsTarget(Expr *E) {
assert(E && "expected parent expression");
return SM.rangeContains(E->getSourceRange(), ParsedExpr->getSourceRange());
}
void analyzeDecl(Decl *D) {
switch (D->getKind()) {
case DeclKind::PatternBinding: {
auto PBD = cast<PatternBindingDecl>(D);
for (unsigned I : range(PBD->getNumPatternEntries())) {
if (auto Init = PBD->getInit(I)) {
if (containsTarget(Init)) {
if (PBD->getPattern(I)->hasType()) {
recordPossibleType(PBD->getPattern(I)->getType());
break;
}