forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSemaCodeComplete.cpp
10523 lines (9274 loc) · 404 KB
/
SemaCodeComplete.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
//===---------------- SemaCodeComplete.cpp - Code Completion ----*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines the code-completion semantic actions.
//
//===----------------------------------------------------------------------===//
#include "clang/AST/ASTConcept.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclBase.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/DynamicRecursiveASTVisitor.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/ExprConcepts.h"
#include "clang/AST/ExprObjC.h"
#include "clang/AST/NestedNameSpecifier.h"
#include "clang/AST/OperationKinds.h"
#include "clang/AST/QualTypeNames.h"
#include "clang/AST/Type.h"
#include "clang/Basic/AttributeCommonInfo.h"
#include "clang/Basic/CharInfo.h"
#include "clang/Basic/OperatorKinds.h"
#include "clang/Basic/Specifiers.h"
#include "clang/Lex/HeaderSearch.h"
#include "clang/Lex/MacroInfo.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Sema/CodeCompleteConsumer.h"
#include "clang/Sema/DeclSpec.h"
#include "clang/Sema/Designator.h"
#include "clang/Sema/HeuristicResolver.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/Overload.h"
#include "clang/Sema/ParsedAttr.h"
#include "clang/Sema/ParsedTemplate.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/ScopeInfo.h"
#include "clang/Sema/Sema.h"
#include "clang/Sema/SemaCodeCompletion.h"
#include "clang/Sema/SemaObjC.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/SmallBitVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/ADT/Twine.h"
#include "llvm/ADT/iterator_range.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include <list>
#include <map>
#include <optional>
#include <string>
#include <vector>
using namespace clang;
using namespace sema;
namespace {
/// A container of code-completion results.
class ResultBuilder {
public:
/// The type of a name-lookup filter, which can be provided to the
/// name-lookup routines to specify which declarations should be included in
/// the result set (when it returns true) and which declarations should be
/// filtered out (returns false).
typedef bool (ResultBuilder::*LookupFilter)(const NamedDecl *) const;
typedef CodeCompletionResult Result;
private:
/// The actual results we have found.
std::vector<Result> Results;
/// A record of all of the declarations we have found and placed
/// into the result set, used to ensure that no declaration ever gets into
/// the result set twice.
llvm::SmallPtrSet<const Decl *, 16> AllDeclsFound;
typedef std::pair<const NamedDecl *, unsigned> DeclIndexPair;
/// An entry in the shadow map, which is optimized to store
/// a single (declaration, index) mapping (the common case) but
/// can also store a list of (declaration, index) mappings.
class ShadowMapEntry {
typedef SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
/// Contains either the solitary NamedDecl * or a vector
/// of (declaration, index) pairs.
llvm::PointerUnion<const NamedDecl *, DeclIndexPairVector *> DeclOrVector;
/// When the entry contains a single declaration, this is
/// the index associated with that entry.
unsigned SingleDeclIndex = 0;
public:
ShadowMapEntry() = default;
ShadowMapEntry(const ShadowMapEntry &) = delete;
ShadowMapEntry(ShadowMapEntry &&Move) { *this = std::move(Move); }
ShadowMapEntry &operator=(const ShadowMapEntry &) = delete;
ShadowMapEntry &operator=(ShadowMapEntry &&Move) {
SingleDeclIndex = Move.SingleDeclIndex;
DeclOrVector = Move.DeclOrVector;
Move.DeclOrVector = nullptr;
return *this;
}
void Add(const NamedDecl *ND, unsigned Index) {
if (DeclOrVector.isNull()) {
// 0 - > 1 elements: just set the single element information.
DeclOrVector = ND;
SingleDeclIndex = Index;
return;
}
if (const NamedDecl *PrevND = dyn_cast<const NamedDecl *>(DeclOrVector)) {
// 1 -> 2 elements: create the vector of results and push in the
// existing declaration.
DeclIndexPairVector *Vec = new DeclIndexPairVector;
Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
DeclOrVector = Vec;
}
// Add the new element to the end of the vector.
cast<DeclIndexPairVector *>(DeclOrVector)
->push_back(DeclIndexPair(ND, Index));
}
~ShadowMapEntry() {
if (DeclIndexPairVector *Vec =
dyn_cast_if_present<DeclIndexPairVector *>(DeclOrVector)) {
delete Vec;
DeclOrVector = ((NamedDecl *)nullptr);
}
}
// Iteration.
class iterator;
iterator begin() const;
iterator end() const;
};
/// A mapping from declaration names to the declarations that have
/// this name within a particular scope and their index within the list of
/// results.
typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
/// The semantic analysis object for which results are being
/// produced.
Sema &SemaRef;
/// The allocator used to allocate new code-completion strings.
CodeCompletionAllocator &Allocator;
CodeCompletionTUInfo &CCTUInfo;
/// If non-NULL, a filter function used to remove any code-completion
/// results that are not desirable.
LookupFilter Filter;
/// Whether we should allow declarations as
/// nested-name-specifiers that would otherwise be filtered out.
bool AllowNestedNameSpecifiers;
/// If set, the type that we would prefer our resulting value
/// declarations to have.
///
/// Closely matching the preferred type gives a boost to a result's
/// priority.
CanQualType PreferredType;
/// A list of shadow maps, which is used to model name hiding at
/// different levels of, e.g., the inheritance hierarchy.
std::list<ShadowMap> ShadowMaps;
/// Overloaded C++ member functions found by SemaLookup.
/// Used to determine when one overload is dominated by another.
llvm::DenseMap<std::pair<DeclContext *, /*Name*/uintptr_t>, ShadowMapEntry>
OverloadMap;
/// If we're potentially referring to a C++ member function, the set
/// of qualifiers applied to the object type.
Qualifiers ObjectTypeQualifiers;
/// The kind of the object expression, for rvalue/lvalue overloads.
ExprValueKind ObjectKind;
/// Whether the \p ObjectTypeQualifiers field is active.
bool HasObjectTypeQualifiers;
/// The selector that we prefer.
Selector PreferredSelector;
/// The completion context in which we are gathering results.
CodeCompletionContext CompletionContext;
/// If we are in an instance method definition, the \@implementation
/// object.
ObjCImplementationDecl *ObjCImplementation;
void AdjustResultPriorityForDecl(Result &R);
void MaybeAddConstructorResults(Result R);
public:
explicit ResultBuilder(Sema &SemaRef, CodeCompletionAllocator &Allocator,
CodeCompletionTUInfo &CCTUInfo,
const CodeCompletionContext &CompletionContext,
LookupFilter Filter = nullptr)
: SemaRef(SemaRef), Allocator(Allocator), CCTUInfo(CCTUInfo),
Filter(Filter), AllowNestedNameSpecifiers(false),
HasObjectTypeQualifiers(false), CompletionContext(CompletionContext),
ObjCImplementation(nullptr) {
// If this is an Objective-C instance method definition, dig out the
// corresponding implementation.
switch (CompletionContext.getKind()) {
case CodeCompletionContext::CCC_Expression:
case CodeCompletionContext::CCC_ObjCMessageReceiver:
case CodeCompletionContext::CCC_ParenthesizedExpression:
case CodeCompletionContext::CCC_Statement:
case CodeCompletionContext::CCC_TopLevelOrExpression:
case CodeCompletionContext::CCC_Recovery:
if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
if (Method->isInstanceMethod())
if (ObjCInterfaceDecl *Interface = Method->getClassInterface())
ObjCImplementation = Interface->getImplementation();
break;
default:
break;
}
}
/// Determine the priority for a reference to the given declaration.
unsigned getBasePriority(const NamedDecl *D);
/// Whether we should include code patterns in the completion
/// results.
bool includeCodePatterns() const {
return SemaRef.CodeCompletion().CodeCompleter &&
SemaRef.CodeCompletion().CodeCompleter->includeCodePatterns();
}
/// Set the filter used for code-completion results.
void setFilter(LookupFilter Filter) { this->Filter = Filter; }
Result *data() { return Results.empty() ? nullptr : &Results.front(); }
unsigned size() const { return Results.size(); }
bool empty() const { return Results.empty(); }
/// Specify the preferred type.
void setPreferredType(QualType T) {
PreferredType = SemaRef.Context.getCanonicalType(T);
}
/// Set the cv-qualifiers on the object type, for us in filtering
/// calls to member functions.
///
/// When there are qualifiers in this set, they will be used to filter
/// out member functions that aren't available (because there will be a
/// cv-qualifier mismatch) or prefer functions with an exact qualifier
/// match.
void setObjectTypeQualifiers(Qualifiers Quals, ExprValueKind Kind) {
ObjectTypeQualifiers = Quals;
ObjectKind = Kind;
HasObjectTypeQualifiers = true;
}
/// Set the preferred selector.
///
/// When an Objective-C method declaration result is added, and that
/// method's selector matches this preferred selector, we give that method
/// a slight priority boost.
void setPreferredSelector(Selector Sel) { PreferredSelector = Sel; }
/// Retrieve the code-completion context for which results are
/// being collected.
const CodeCompletionContext &getCompletionContext() const {
return CompletionContext;
}
/// Specify whether nested-name-specifiers are allowed.
void allowNestedNameSpecifiers(bool Allow = true) {
AllowNestedNameSpecifiers = Allow;
}
/// Return the semantic analysis object for which we are collecting
/// code completion results.
Sema &getSema() const { return SemaRef; }
/// Retrieve the allocator used to allocate code completion strings.
CodeCompletionAllocator &getAllocator() const { return Allocator; }
CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo; }
/// Determine whether the given declaration is at all interesting
/// as a code-completion result.
///
/// \param ND the declaration that we are inspecting.
///
/// \param AsNestedNameSpecifier will be set true if this declaration is
/// only interesting when it is a nested-name-specifier.
bool isInterestingDecl(const NamedDecl *ND,
bool &AsNestedNameSpecifier) const;
/// Decide whether or not a use of function Decl can be a call.
///
/// \param ND the function declaration.
///
/// \param BaseExprType the object type in a member access expression,
/// if any.
bool canFunctionBeCalled(const NamedDecl *ND, QualType BaseExprType) const;
/// Decide whether or not a use of member function Decl can be a call.
///
/// \param Method the function declaration.
///
/// \param BaseExprType the object type in a member access expression,
/// if any.
bool canCxxMethodBeCalled(const CXXMethodDecl *Method,
QualType BaseExprType) const;
/// Check whether the result is hidden by the Hiding declaration.
///
/// \returns true if the result is hidden and cannot be found, false if
/// the hidden result could still be found. When false, \p R may be
/// modified to describe how the result can be found (e.g., via extra
/// qualification).
bool CheckHiddenResult(Result &R, DeclContext *CurContext,
const NamedDecl *Hiding);
/// Add a new result to this result set (if it isn't already in one
/// of the shadow maps), or replace an existing result (for, e.g., a
/// redeclaration).
///
/// \param R the result to add (if it is unique).
///
/// \param CurContext the context in which this result will be named.
void MaybeAddResult(Result R, DeclContext *CurContext = nullptr);
/// Add a new result to this result set, where we already know
/// the hiding declaration (if any).
///
/// \param R the result to add (if it is unique).
///
/// \param CurContext the context in which this result will be named.
///
/// \param Hiding the declaration that hides the result.
///
/// \param InBaseClass whether the result was found in a base
/// class of the searched context.
///
/// \param BaseExprType the type of expression that precedes the "." or "->"
/// in a member access expression.
void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
bool InBaseClass, QualType BaseExprType);
/// Add a new non-declaration result to this result set.
void AddResult(Result R);
/// Enter into a new scope.
void EnterNewScope();
/// Exit from the current scope.
void ExitScope();
/// Ignore this declaration, if it is seen again.
void Ignore(const Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
/// Add a visited context.
void addVisitedContext(DeclContext *Ctx) {
CompletionContext.addVisitedContext(Ctx);
}
/// \name Name lookup predicates
///
/// These predicates can be passed to the name lookup functions to filter the
/// results of name lookup. All of the predicates have the same type, so that
///
//@{
bool IsOrdinaryName(const NamedDecl *ND) const;
bool IsOrdinaryNonTypeName(const NamedDecl *ND) const;
bool IsIntegralConstantValue(const NamedDecl *ND) const;
bool IsOrdinaryNonValueName(const NamedDecl *ND) const;
bool IsNestedNameSpecifier(const NamedDecl *ND) const;
bool IsEnum(const NamedDecl *ND) const;
bool IsClassOrStruct(const NamedDecl *ND) const;
bool IsUnion(const NamedDecl *ND) const;
bool IsNamespace(const NamedDecl *ND) const;
bool IsNamespaceOrAlias(const NamedDecl *ND) const;
bool IsType(const NamedDecl *ND) const;
bool IsMember(const NamedDecl *ND) const;
bool IsObjCIvar(const NamedDecl *ND) const;
bool IsObjCMessageReceiver(const NamedDecl *ND) const;
bool IsObjCMessageReceiverOrLambdaCapture(const NamedDecl *ND) const;
bool IsObjCCollection(const NamedDecl *ND) const;
bool IsImpossibleToSatisfy(const NamedDecl *ND) const;
//@}
};
} // namespace
void PreferredTypeBuilder::enterReturn(Sema &S, SourceLocation Tok) {
if (!Enabled)
return;
if (isa<BlockDecl>(S.CurContext)) {
if (sema::BlockScopeInfo *BSI = S.getCurBlock()) {
ComputeType = nullptr;
Type = BSI->ReturnType;
ExpectedLoc = Tok;
}
} else if (const auto *Function = dyn_cast<FunctionDecl>(S.CurContext)) {
ComputeType = nullptr;
Type = Function->getReturnType();
ExpectedLoc = Tok;
} else if (const auto *Method = dyn_cast<ObjCMethodDecl>(S.CurContext)) {
ComputeType = nullptr;
Type = Method->getReturnType();
ExpectedLoc = Tok;
}
}
void PreferredTypeBuilder::enterVariableInit(SourceLocation Tok, Decl *D) {
if (!Enabled)
return;
auto *VD = llvm::dyn_cast_or_null<ValueDecl>(D);
ComputeType = nullptr;
Type = VD ? VD->getType() : QualType();
ExpectedLoc = Tok;
}
static QualType getDesignatedType(QualType BaseType, const Designation &Desig);
void PreferredTypeBuilder::enterDesignatedInitializer(SourceLocation Tok,
QualType BaseType,
const Designation &D) {
if (!Enabled)
return;
ComputeType = nullptr;
Type = getDesignatedType(BaseType, D);
ExpectedLoc = Tok;
}
void PreferredTypeBuilder::enterFunctionArgument(
SourceLocation Tok, llvm::function_ref<QualType()> ComputeType) {
if (!Enabled)
return;
this->ComputeType = ComputeType;
Type = QualType();
ExpectedLoc = Tok;
}
void PreferredTypeBuilder::enterParenExpr(SourceLocation Tok,
SourceLocation LParLoc) {
if (!Enabled)
return;
// expected type for parenthesized expression does not change.
if (ExpectedLoc == LParLoc)
ExpectedLoc = Tok;
}
static QualType getPreferredTypeOfBinaryRHS(Sema &S, Expr *LHS,
tok::TokenKind Op) {
if (!LHS)
return QualType();
QualType LHSType = LHS->getType();
if (LHSType->isPointerType()) {
if (Op == tok::plus || Op == tok::plusequal || Op == tok::minusequal)
return S.getASTContext().getPointerDiffType();
// Pointer difference is more common than subtracting an int from a pointer.
if (Op == tok::minus)
return LHSType;
}
switch (Op) {
// No way to infer the type of RHS from LHS.
case tok::comma:
return QualType();
// Prefer the type of the left operand for all of these.
// Arithmetic operations.
case tok::plus:
case tok::plusequal:
case tok::minus:
case tok::minusequal:
case tok::percent:
case tok::percentequal:
case tok::slash:
case tok::slashequal:
case tok::star:
case tok::starequal:
// Assignment.
case tok::equal:
// Comparison operators.
case tok::equalequal:
case tok::exclaimequal:
case tok::less:
case tok::lessequal:
case tok::greater:
case tok::greaterequal:
case tok::spaceship:
return LHS->getType();
// Binary shifts are often overloaded, so don't try to guess those.
case tok::greatergreater:
case tok::greatergreaterequal:
case tok::lessless:
case tok::lesslessequal:
if (LHSType->isIntegralOrEnumerationType())
return S.getASTContext().IntTy;
return QualType();
// Logical operators, assume we want bool.
case tok::ampamp:
case tok::pipepipe:
return S.getASTContext().BoolTy;
// Operators often used for bit manipulation are typically used with the type
// of the left argument.
case tok::pipe:
case tok::pipeequal:
case tok::caret:
case tok::caretequal:
case tok::amp:
case tok::ampequal:
if (LHSType->isIntegralOrEnumerationType())
return LHSType;
return QualType();
// RHS should be a pointer to a member of the 'LHS' type, but we can't give
// any particular type here.
case tok::periodstar:
case tok::arrowstar:
return QualType();
default:
// FIXME(ibiryukov): handle the missing op, re-add the assertion.
// assert(false && "unhandled binary op");
return QualType();
}
}
/// Get preferred type for an argument of an unary expression. \p ContextType is
/// preferred type of the whole unary expression.
static QualType getPreferredTypeOfUnaryArg(Sema &S, QualType ContextType,
tok::TokenKind Op) {
switch (Op) {
case tok::exclaim:
return S.getASTContext().BoolTy;
case tok::amp:
if (!ContextType.isNull() && ContextType->isPointerType())
return ContextType->getPointeeType();
return QualType();
case tok::star:
if (ContextType.isNull())
return QualType();
return S.getASTContext().getPointerType(ContextType.getNonReferenceType());
case tok::plus:
case tok::minus:
case tok::tilde:
case tok::minusminus:
case tok::plusplus:
if (ContextType.isNull())
return S.getASTContext().IntTy;
// leave as is, these operators typically return the same type.
return ContextType;
case tok::kw___real:
case tok::kw___imag:
return QualType();
default:
assert(false && "unhandled unary op");
return QualType();
}
}
void PreferredTypeBuilder::enterBinary(Sema &S, SourceLocation Tok, Expr *LHS,
tok::TokenKind Op) {
if (!Enabled)
return;
ComputeType = nullptr;
Type = getPreferredTypeOfBinaryRHS(S, LHS, Op);
ExpectedLoc = Tok;
}
void PreferredTypeBuilder::enterMemAccess(Sema &S, SourceLocation Tok,
Expr *Base) {
if (!Enabled || !Base)
return;
// Do we have expected type for Base?
if (ExpectedLoc != Base->getBeginLoc())
return;
// Keep the expected type, only update the location.
ExpectedLoc = Tok;
}
void PreferredTypeBuilder::enterUnary(Sema &S, SourceLocation Tok,
tok::TokenKind OpKind,
SourceLocation OpLoc) {
if (!Enabled)
return;
ComputeType = nullptr;
Type = getPreferredTypeOfUnaryArg(S, this->get(OpLoc), OpKind);
ExpectedLoc = Tok;
}
void PreferredTypeBuilder::enterSubscript(Sema &S, SourceLocation Tok,
Expr *LHS) {
if (!Enabled)
return;
ComputeType = nullptr;
Type = S.getASTContext().IntTy;
ExpectedLoc = Tok;
}
void PreferredTypeBuilder::enterTypeCast(SourceLocation Tok,
QualType CastType) {
if (!Enabled)
return;
ComputeType = nullptr;
Type = !CastType.isNull() ? CastType.getCanonicalType() : QualType();
ExpectedLoc = Tok;
}
void PreferredTypeBuilder::enterCondition(Sema &S, SourceLocation Tok) {
if (!Enabled)
return;
ComputeType = nullptr;
Type = S.getASTContext().BoolTy;
ExpectedLoc = Tok;
}
class ResultBuilder::ShadowMapEntry::iterator {
llvm::PointerUnion<const NamedDecl *, const DeclIndexPair *> DeclOrIterator;
unsigned SingleDeclIndex;
public:
typedef DeclIndexPair value_type;
typedef value_type reference;
typedef std::ptrdiff_t difference_type;
typedef std::input_iterator_tag iterator_category;
class pointer {
DeclIndexPair Value;
public:
pointer(const DeclIndexPair &Value) : Value(Value) {}
const DeclIndexPair *operator->() const { return &Value; }
};
iterator() : DeclOrIterator((NamedDecl *)nullptr), SingleDeclIndex(0) {}
iterator(const NamedDecl *SingleDecl, unsigned Index)
: DeclOrIterator(SingleDecl), SingleDeclIndex(Index) {}
iterator(const DeclIndexPair *Iterator)
: DeclOrIterator(Iterator), SingleDeclIndex(0) {}
iterator &operator++() {
if (isa<const NamedDecl *>(DeclOrIterator)) {
DeclOrIterator = (NamedDecl *)nullptr;
SingleDeclIndex = 0;
return *this;
}
const DeclIndexPair *I = cast<const DeclIndexPair *>(DeclOrIterator);
++I;
DeclOrIterator = I;
return *this;
}
/*iterator operator++(int) {
iterator tmp(*this);
++(*this);
return tmp;
}*/
reference operator*() const {
if (const NamedDecl *ND = dyn_cast<const NamedDecl *>(DeclOrIterator))
return reference(ND, SingleDeclIndex);
return *cast<const DeclIndexPair *>(DeclOrIterator);
}
pointer operator->() const { return pointer(**this); }
friend bool operator==(const iterator &X, const iterator &Y) {
return X.DeclOrIterator.getOpaqueValue() ==
Y.DeclOrIterator.getOpaqueValue() &&
X.SingleDeclIndex == Y.SingleDeclIndex;
}
friend bool operator!=(const iterator &X, const iterator &Y) {
return !(X == Y);
}
};
ResultBuilder::ShadowMapEntry::iterator
ResultBuilder::ShadowMapEntry::begin() const {
if (DeclOrVector.isNull())
return iterator();
if (const NamedDecl *ND = dyn_cast<const NamedDecl *>(DeclOrVector))
return iterator(ND, SingleDeclIndex);
return iterator(cast<DeclIndexPairVector *>(DeclOrVector)->begin());
}
ResultBuilder::ShadowMapEntry::iterator
ResultBuilder::ShadowMapEntry::end() const {
if (isa<const NamedDecl *>(DeclOrVector) || DeclOrVector.isNull())
return iterator();
return iterator(cast<DeclIndexPairVector *>(DeclOrVector)->end());
}
/// Compute the qualification required to get from the current context
/// (\p CurContext) to the target context (\p TargetContext).
///
/// \param Context the AST context in which the qualification will be used.
///
/// \param CurContext the context where an entity is being named, which is
/// typically based on the current scope.
///
/// \param TargetContext the context in which the named entity actually
/// resides.
///
/// \returns a nested name specifier that refers into the target context, or
/// NULL if no qualification is needed.
static NestedNameSpecifier *
getRequiredQualification(ASTContext &Context, const DeclContext *CurContext,
const DeclContext *TargetContext) {
SmallVector<const DeclContext *, 4> TargetParents;
for (const DeclContext *CommonAncestor = TargetContext;
CommonAncestor && !CommonAncestor->Encloses(CurContext);
CommonAncestor = CommonAncestor->getLookupParent()) {
if (CommonAncestor->isTransparentContext() ||
CommonAncestor->isFunctionOrMethod())
continue;
TargetParents.push_back(CommonAncestor);
}
NestedNameSpecifier *Result = nullptr;
while (!TargetParents.empty()) {
const DeclContext *Parent = TargetParents.pop_back_val();
if (const auto *Namespace = dyn_cast<NamespaceDecl>(Parent)) {
if (!Namespace->getIdentifier())
continue;
Result = NestedNameSpecifier::Create(Context, Result, Namespace);
} else if (const auto *TD = dyn_cast<TagDecl>(Parent))
Result = NestedNameSpecifier::Create(
Context, Result, false, Context.getTypeDeclType(TD).getTypePtr());
}
return Result;
}
// Some declarations have reserved names that we don't want to ever show.
// Filter out names reserved for the implementation if they come from a
// system header.
static bool shouldIgnoreDueToReservedName(const NamedDecl *ND, Sema &SemaRef) {
// Debuggers want access to all identifiers, including reserved ones.
if (SemaRef.getLangOpts().DebuggerSupport)
return false;
ReservedIdentifierStatus Status = ND->isReserved(SemaRef.getLangOpts());
// Ignore reserved names for compiler provided decls.
if (isReservedInAllContexts(Status) && ND->getLocation().isInvalid())
return true;
// For system headers ignore only double-underscore names.
// This allows for system headers providing private symbols with a single
// underscore.
if (Status == ReservedIdentifierStatus::StartsWithDoubleUnderscore &&
SemaRef.SourceMgr.isInSystemHeader(
SemaRef.SourceMgr.getSpellingLoc(ND->getLocation())))
return true;
return false;
}
bool ResultBuilder::isInterestingDecl(const NamedDecl *ND,
bool &AsNestedNameSpecifier) const {
AsNestedNameSpecifier = false;
auto *Named = ND;
ND = ND->getUnderlyingDecl();
// Skip unnamed entities.
if (!ND->getDeclName())
return false;
// Friend declarations and declarations introduced due to friends are never
// added as results.
if (ND->getFriendObjectKind() == Decl::FOK_Undeclared)
return false;
// Class template (partial) specializations are never added as results.
if (isa<ClassTemplateSpecializationDecl>(ND) ||
isa<ClassTemplatePartialSpecializationDecl>(ND))
return false;
// Using declarations themselves are never added as results.
if (isa<UsingDecl>(ND))
return false;
if (shouldIgnoreDueToReservedName(ND, SemaRef))
return false;
if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
(isa<NamespaceDecl>(ND) && Filter != &ResultBuilder::IsNamespace &&
Filter != &ResultBuilder::IsNamespaceOrAlias && Filter != nullptr))
AsNestedNameSpecifier = true;
// Filter out any unwanted results.
if (Filter && !(this->*Filter)(Named)) {
// Check whether it is interesting as a nested-name-specifier.
if (AllowNestedNameSpecifiers && SemaRef.getLangOpts().CPlusPlus &&
IsNestedNameSpecifier(ND) &&
(Filter != &ResultBuilder::IsMember ||
(isa<CXXRecordDecl>(ND) &&
cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
AsNestedNameSpecifier = true;
return true;
}
return false;
}
// ... then it must be interesting!
return true;
}
bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
const NamedDecl *Hiding) {
// In C, there is no way to refer to a hidden name.
// FIXME: This isn't true; we can find a tag name hidden by an ordinary
// name if we introduce the tag type.
if (!SemaRef.getLangOpts().CPlusPlus)
return true;
const DeclContext *HiddenCtx =
R.Declaration->getDeclContext()->getRedeclContext();
// There is no way to qualify a name declared in a function or method.
if (HiddenCtx->isFunctionOrMethod())
return true;
if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext())
return true;
// We can refer to the result with the appropriate qualification. Do it.
R.Hidden = true;
R.QualifierIsInformative = false;
if (!R.Qualifier)
R.Qualifier = getRequiredQualification(SemaRef.Context, CurContext,
R.Declaration->getDeclContext());
return false;
}
/// A simplified classification of types used to determine whether two
/// types are "similar enough" when adjusting priorities.
SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) {
switch (T->getTypeClass()) {
case Type::Builtin:
switch (cast<BuiltinType>(T)->getKind()) {
case BuiltinType::Void:
return STC_Void;
case BuiltinType::NullPtr:
return STC_Pointer;
case BuiltinType::Overload:
case BuiltinType::Dependent:
return STC_Other;
case BuiltinType::ObjCId:
case BuiltinType::ObjCClass:
case BuiltinType::ObjCSel:
return STC_ObjectiveC;
default:
return STC_Arithmetic;
}
case Type::Complex:
return STC_Arithmetic;
case Type::Pointer:
return STC_Pointer;
case Type::BlockPointer:
return STC_Block;
case Type::LValueReference:
case Type::RValueReference:
return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
case Type::ConstantArray:
case Type::IncompleteArray:
case Type::VariableArray:
case Type::DependentSizedArray:
return STC_Array;
case Type::DependentSizedExtVector:
case Type::Vector:
case Type::ExtVector:
return STC_Arithmetic;
case Type::FunctionProto:
case Type::FunctionNoProto:
return STC_Function;
case Type::Record:
return STC_Record;
case Type::Enum:
return STC_Arithmetic;
case Type::ObjCObject:
case Type::ObjCInterface:
case Type::ObjCObjectPointer:
return STC_ObjectiveC;
default:
return STC_Other;
}
}
/// Get the type that a given expression will have if this declaration
/// is used as an expression in its "typical" code-completion form.
QualType clang::getDeclUsageType(ASTContext &C, const NamedDecl *ND) {
ND = ND->getUnderlyingDecl();
if (const auto *Type = dyn_cast<TypeDecl>(ND))
return C.getTypeDeclType(Type);
if (const auto *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
return C.getObjCInterfaceType(Iface);
QualType T;
if (const FunctionDecl *Function = ND->getAsFunction())
T = Function->getCallResultType();
else if (const auto *Method = dyn_cast<ObjCMethodDecl>(ND))
T = Method->getSendResultType();
else if (const auto *Enumerator = dyn_cast<EnumConstantDecl>(ND))
T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
else if (const auto *Property = dyn_cast<ObjCPropertyDecl>(ND))
T = Property->getType();
else if (const auto *Value = dyn_cast<ValueDecl>(ND))
T = Value->getType();
if (T.isNull())
return QualType();
// Dig through references, function pointers, and block pointers to
// get down to the likely type of an expression when the entity is
// used.
do {
if (const auto *Ref = T->getAs<ReferenceType>()) {
T = Ref->getPointeeType();
continue;
}
if (const auto *Pointer = T->getAs<PointerType>()) {
if (Pointer->getPointeeType()->isFunctionType()) {
T = Pointer->getPointeeType();
continue;
}
break;
}
if (const auto *Block = T->getAs<BlockPointerType>()) {
T = Block->getPointeeType();
continue;
}
if (const auto *Function = T->getAs<FunctionType>()) {
T = Function->getReturnType();
continue;
}
break;
} while (true);
return T;
}
unsigned ResultBuilder::getBasePriority(const NamedDecl *ND) {
if (!ND)
return CCP_Unlikely;
// Context-based decisions.
const DeclContext *LexicalDC = ND->getLexicalDeclContext();
if (LexicalDC->isFunctionOrMethod()) {