Bug Summary

File:build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/lib/Sema/SemaCodeComplete.cpp
Warning:line 3767, column 5
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name SemaCodeComplete.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm -resource-dir /usr/lib/llvm-16/lib/clang/16.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/lib/Sema -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-16/lib/clang/16.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-09-04-125545-48738-1 -x c++ /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/lib/Sema/SemaCodeComplete.cpp
1//===---------------- SemaCodeComplete.cpp - Code Completion ----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the code-completion semantic actions.
10//
11//===----------------------------------------------------------------------===//
12#include "clang/AST/ASTConcept.h"
13#include "clang/AST/Decl.h"
14#include "clang/AST/DeclBase.h"
15#include "clang/AST/DeclCXX.h"
16#include "clang/AST/DeclObjC.h"
17#include "clang/AST/DeclTemplate.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/ExprCXX.h"
20#include "clang/AST/ExprConcepts.h"
21#include "clang/AST/ExprObjC.h"
22#include "clang/AST/NestedNameSpecifier.h"
23#include "clang/AST/QualTypeNames.h"
24#include "clang/AST/RecursiveASTVisitor.h"
25#include "clang/AST/Type.h"
26#include "clang/Basic/AttributeCommonInfo.h"
27#include "clang/Basic/CharInfo.h"
28#include "clang/Basic/OperatorKinds.h"
29#include "clang/Basic/Specifiers.h"
30#include "clang/Lex/HeaderSearch.h"
31#include "clang/Lex/MacroInfo.h"
32#include "clang/Lex/Preprocessor.h"
33#include "clang/Sema/CodeCompleteConsumer.h"
34#include "clang/Sema/DeclSpec.h"
35#include "clang/Sema/Designator.h"
36#include "clang/Sema/Lookup.h"
37#include "clang/Sema/Overload.h"
38#include "clang/Sema/ParsedAttr.h"
39#include "clang/Sema/ParsedTemplate.h"
40#include "clang/Sema/Scope.h"
41#include "clang/Sema/ScopeInfo.h"
42#include "clang/Sema/Sema.h"
43#include "clang/Sema/SemaInternal.h"
44#include "llvm/ADT/ArrayRef.h"
45#include "llvm/ADT/DenseSet.h"
46#include "llvm/ADT/SmallBitVector.h"
47#include "llvm/ADT/SmallPtrSet.h"
48#include "llvm/ADT/SmallString.h"
49#include "llvm/ADT/StringExtras.h"
50#include "llvm/ADT/StringSwitch.h"
51#include "llvm/ADT/Twine.h"
52#include "llvm/ADT/iterator_range.h"
53#include "llvm/Support/Casting.h"
54#include "llvm/Support/Path.h"
55#include "llvm/Support/raw_ostream.h"
56
57#include <list>
58#include <map>
59#include <string>
60#include <vector>
61
62using namespace clang;
63using namespace sema;
64
65namespace {
66/// A container of code-completion results.
67class ResultBuilder {
68public:
69 /// The type of a name-lookup filter, which can be provided to the
70 /// name-lookup routines to specify which declarations should be included in
71 /// the result set (when it returns true) and which declarations should be
72 /// filtered out (returns false).
73 typedef bool (ResultBuilder::*LookupFilter)(const NamedDecl *) const;
74
75 typedef CodeCompletionResult Result;
76
77private:
78 /// The actual results we have found.
79 std::vector<Result> Results;
80
81 /// A record of all of the declarations we have found and placed
82 /// into the result set, used to ensure that no declaration ever gets into
83 /// the result set twice.
84 llvm::SmallPtrSet<const Decl *, 16> AllDeclsFound;
85
86 typedef std::pair<const NamedDecl *, unsigned> DeclIndexPair;
87
88 /// An entry in the shadow map, which is optimized to store
89 /// a single (declaration, index) mapping (the common case) but
90 /// can also store a list of (declaration, index) mappings.
91 class ShadowMapEntry {
92 typedef SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
93
94 /// Contains either the solitary NamedDecl * or a vector
95 /// of (declaration, index) pairs.
96 llvm::PointerUnion<const NamedDecl *, DeclIndexPairVector *> DeclOrVector;
97
98 /// When the entry contains a single declaration, this is
99 /// the index associated with that entry.
100 unsigned SingleDeclIndex;
101
102 public:
103 ShadowMapEntry() : SingleDeclIndex(0) {}
104 ShadowMapEntry(const ShadowMapEntry &) = delete;
105 ShadowMapEntry(ShadowMapEntry &&Move) { *this = std::move(Move); }
106 ShadowMapEntry &operator=(const ShadowMapEntry &) = delete;
107 ShadowMapEntry &operator=(ShadowMapEntry &&Move) {
108 SingleDeclIndex = Move.SingleDeclIndex;
109 DeclOrVector = Move.DeclOrVector;
110 Move.DeclOrVector = nullptr;
111 return *this;
112 }
113
114 void Add(const NamedDecl *ND, unsigned Index) {
115 if (DeclOrVector.isNull()) {
116 // 0 - > 1 elements: just set the single element information.
117 DeclOrVector = ND;
118 SingleDeclIndex = Index;
119 return;
120 }
121
122 if (const NamedDecl *PrevND =
123 DeclOrVector.dyn_cast<const NamedDecl *>()) {
124 // 1 -> 2 elements: create the vector of results and push in the
125 // existing declaration.
126 DeclIndexPairVector *Vec = new DeclIndexPairVector;
127 Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
128 DeclOrVector = Vec;
129 }
130
131 // Add the new element to the end of the vector.
132 DeclOrVector.get<DeclIndexPairVector *>()->push_back(
133 DeclIndexPair(ND, Index));
134 }
135
136 ~ShadowMapEntry() {
137 if (DeclIndexPairVector *Vec =
138 DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
139 delete Vec;
140 DeclOrVector = ((NamedDecl *)nullptr);
141 }
142 }
143
144 // Iteration.
145 class iterator;
146 iterator begin() const;
147 iterator end() const;
148 };
149
150 /// A mapping from declaration names to the declarations that have
151 /// this name within a particular scope and their index within the list of
152 /// results.
153 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
154
155 /// The semantic analysis object for which results are being
156 /// produced.
157 Sema &SemaRef;
158
159 /// The allocator used to allocate new code-completion strings.
160 CodeCompletionAllocator &Allocator;
161
162 CodeCompletionTUInfo &CCTUInfo;
163
164 /// If non-NULL, a filter function used to remove any code-completion
165 /// results that are not desirable.
166 LookupFilter Filter;
167
168 /// Whether we should allow declarations as
169 /// nested-name-specifiers that would otherwise be filtered out.
170 bool AllowNestedNameSpecifiers;
171
172 /// If set, the type that we would prefer our resulting value
173 /// declarations to have.
174 ///
175 /// Closely matching the preferred type gives a boost to a result's
176 /// priority.
177 CanQualType PreferredType;
178
179 /// A list of shadow maps, which is used to model name hiding at
180 /// different levels of, e.g., the inheritance hierarchy.
181 std::list<ShadowMap> ShadowMaps;
182
183 /// Overloaded C++ member functions found by SemaLookup.
184 /// Used to determine when one overload is dominated by another.
185 llvm::DenseMap<std::pair<DeclContext *, /*Name*/uintptr_t>, ShadowMapEntry>
186 OverloadMap;
187
188 /// If we're potentially referring to a C++ member function, the set
189 /// of qualifiers applied to the object type.
190 Qualifiers ObjectTypeQualifiers;
191 /// The kind of the object expression, for rvalue/lvalue overloads.
192 ExprValueKind ObjectKind;
193
194 /// Whether the \p ObjectTypeQualifiers field is active.
195 bool HasObjectTypeQualifiers;
196
197 /// The selector that we prefer.
198 Selector PreferredSelector;
199
200 /// The completion context in which we are gathering results.
201 CodeCompletionContext CompletionContext;
202
203 /// If we are in an instance method definition, the \@implementation
204 /// object.
205 ObjCImplementationDecl *ObjCImplementation;
206
207 void AdjustResultPriorityForDecl(Result &R);
208
209 void MaybeAddConstructorResults(Result R);
210
211public:
212 explicit ResultBuilder(Sema &SemaRef, CodeCompletionAllocator &Allocator,
213 CodeCompletionTUInfo &CCTUInfo,
214 const CodeCompletionContext &CompletionContext,
215 LookupFilter Filter = nullptr)
216 : SemaRef(SemaRef), Allocator(Allocator), CCTUInfo(CCTUInfo),
217 Filter(Filter), AllowNestedNameSpecifiers(false),
218 HasObjectTypeQualifiers(false), CompletionContext(CompletionContext),
219 ObjCImplementation(nullptr) {
220 // If this is an Objective-C instance method definition, dig out the
221 // corresponding implementation.
222 switch (CompletionContext.getKind()) {
223 case CodeCompletionContext::CCC_Expression:
224 case CodeCompletionContext::CCC_ObjCMessageReceiver:
225 case CodeCompletionContext::CCC_ParenthesizedExpression:
226 case CodeCompletionContext::CCC_Statement:
227 case CodeCompletionContext::CCC_Recovery:
228 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
229 if (Method->isInstanceMethod())
230 if (ObjCInterfaceDecl *Interface = Method->getClassInterface())
231 ObjCImplementation = Interface->getImplementation();
232 break;
233
234 default:
235 break;
236 }
237 }
238
239 /// Determine the priority for a reference to the given declaration.
240 unsigned getBasePriority(const NamedDecl *D);
241
242 /// Whether we should include code patterns in the completion
243 /// results.
244 bool includeCodePatterns() const {
245 return SemaRef.CodeCompleter &&
246 SemaRef.CodeCompleter->includeCodePatterns();
247 }
248
249 /// Set the filter used for code-completion results.
250 void setFilter(LookupFilter Filter) { this->Filter = Filter; }
251
252 Result *data() { return Results.empty() ? nullptr : &Results.front(); }
253 unsigned size() const { return Results.size(); }
254 bool empty() const { return Results.empty(); }
255
256 /// Specify the preferred type.
257 void setPreferredType(QualType T) {
258 PreferredType = SemaRef.Context.getCanonicalType(T);
259 }
260
261 /// Set the cv-qualifiers on the object type, for us in filtering
262 /// calls to member functions.
263 ///
264 /// When there are qualifiers in this set, they will be used to filter
265 /// out member functions that aren't available (because there will be a
266 /// cv-qualifier mismatch) or prefer functions with an exact qualifier
267 /// match.
268 void setObjectTypeQualifiers(Qualifiers Quals, ExprValueKind Kind) {
269 ObjectTypeQualifiers = Quals;
270 ObjectKind = Kind;
271 HasObjectTypeQualifiers = true;
272 }
273
274 /// Set the preferred selector.
275 ///
276 /// When an Objective-C method declaration result is added, and that
277 /// method's selector matches this preferred selector, we give that method
278 /// a slight priority boost.
279 void setPreferredSelector(Selector Sel) { PreferredSelector = Sel; }
280
281 /// Retrieve the code-completion context for which results are
282 /// being collected.
283 const CodeCompletionContext &getCompletionContext() const {
284 return CompletionContext;
285 }
286
287 /// Specify whether nested-name-specifiers are allowed.
288 void allowNestedNameSpecifiers(bool Allow = true) {
289 AllowNestedNameSpecifiers = Allow;
290 }
291
292 /// Return the semantic analysis object for which we are collecting
293 /// code completion results.
294 Sema &getSema() const { return SemaRef; }
295
296 /// Retrieve the allocator used to allocate code completion strings.
297 CodeCompletionAllocator &getAllocator() const { return Allocator; }
298
299 CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo; }
300
301 /// Determine whether the given declaration is at all interesting
302 /// as a code-completion result.
303 ///
304 /// \param ND the declaration that we are inspecting.
305 ///
306 /// \param AsNestedNameSpecifier will be set true if this declaration is
307 /// only interesting when it is a nested-name-specifier.
308 bool isInterestingDecl(const NamedDecl *ND,
309 bool &AsNestedNameSpecifier) const;
310
311 /// Check whether the result is hidden by the Hiding declaration.
312 ///
313 /// \returns true if the result is hidden and cannot be found, false if
314 /// the hidden result could still be found. When false, \p R may be
315 /// modified to describe how the result can be found (e.g., via extra
316 /// qualification).
317 bool CheckHiddenResult(Result &R, DeclContext *CurContext,
318 const NamedDecl *Hiding);
319
320 /// Add a new result to this result set (if it isn't already in one
321 /// of the shadow maps), or replace an existing result (for, e.g., a
322 /// redeclaration).
323 ///
324 /// \param R the result to add (if it is unique).
325 ///
326 /// \param CurContext the context in which this result will be named.
327 void MaybeAddResult(Result R, DeclContext *CurContext = nullptr);
328
329 /// Add a new result to this result set, where we already know
330 /// the hiding declaration (if any).
331 ///
332 /// \param R the result to add (if it is unique).
333 ///
334 /// \param CurContext the context in which this result will be named.
335 ///
336 /// \param Hiding the declaration that hides the result.
337 ///
338 /// \param InBaseClass whether the result was found in a base
339 /// class of the searched context.
340 void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
341 bool InBaseClass);
342
343 /// Add a new non-declaration result to this result set.
344 void AddResult(Result R);
345
346 /// Enter into a new scope.
347 void EnterNewScope();
348
349 /// Exit from the current scope.
350 void ExitScope();
351
352 /// Ignore this declaration, if it is seen again.
353 void Ignore(const Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
354
355 /// Add a visited context.
356 void addVisitedContext(DeclContext *Ctx) {
357 CompletionContext.addVisitedContext(Ctx);
358 }
359
360 /// \name Name lookup predicates
361 ///
362 /// These predicates can be passed to the name lookup functions to filter the
363 /// results of name lookup. All of the predicates have the same type, so that
364 ///
365 //@{
366 bool IsOrdinaryName(const NamedDecl *ND) const;
367 bool IsOrdinaryNonTypeName(const NamedDecl *ND) const;
368 bool IsIntegralConstantValue(const NamedDecl *ND) const;
369 bool IsOrdinaryNonValueName(const NamedDecl *ND) const;
370 bool IsNestedNameSpecifier(const NamedDecl *ND) const;
371 bool IsEnum(const NamedDecl *ND) const;
372 bool IsClassOrStruct(const NamedDecl *ND) const;
373 bool IsUnion(const NamedDecl *ND) const;
374 bool IsNamespace(const NamedDecl *ND) const;
375 bool IsNamespaceOrAlias(const NamedDecl *ND) const;
376 bool IsType(const NamedDecl *ND) const;
377 bool IsMember(const NamedDecl *ND) const;
378 bool IsObjCIvar(const NamedDecl *ND) const;
379 bool IsObjCMessageReceiver(const NamedDecl *ND) const;
380 bool IsObjCMessageReceiverOrLambdaCapture(const NamedDecl *ND) const;
381 bool IsObjCCollection(const NamedDecl *ND) const;
382 bool IsImpossibleToSatisfy(const NamedDecl *ND) const;
383 //@}
384};
385} // namespace
386
387void PreferredTypeBuilder::enterReturn(Sema &S, SourceLocation Tok) {
388 if (!Enabled)
389 return;
390 if (isa<BlockDecl>(S.CurContext)) {
391 if (sema::BlockScopeInfo *BSI = S.getCurBlock()) {
392 ComputeType = nullptr;
393 Type = BSI->ReturnType;
394 ExpectedLoc = Tok;
395 }
396 } else if (const auto *Function = dyn_cast<FunctionDecl>(S.CurContext)) {
397 ComputeType = nullptr;
398 Type = Function->getReturnType();
399 ExpectedLoc = Tok;
400 } else if (const auto *Method = dyn_cast<ObjCMethodDecl>(S.CurContext)) {
401 ComputeType = nullptr;
402 Type = Method->getReturnType();
403 ExpectedLoc = Tok;
404 }
405}
406
407void PreferredTypeBuilder::enterVariableInit(SourceLocation Tok, Decl *D) {
408 if (!Enabled)
409 return;
410 auto *VD = llvm::dyn_cast_or_null<ValueDecl>(D);
411 ComputeType = nullptr;
412 Type = VD ? VD->getType() : QualType();
413 ExpectedLoc = Tok;
414}
415
416static QualType getDesignatedType(QualType BaseType, const Designation &Desig);
417
418void PreferredTypeBuilder::enterDesignatedInitializer(SourceLocation Tok,
419 QualType BaseType,
420 const Designation &D) {
421 if (!Enabled)
422 return;
423 ComputeType = nullptr;
424 Type = getDesignatedType(BaseType, D);
425 ExpectedLoc = Tok;
426}
427
428void PreferredTypeBuilder::enterFunctionArgument(
429 SourceLocation Tok, llvm::function_ref<QualType()> ComputeType) {
430 if (!Enabled)
431 return;
432 this->ComputeType = ComputeType;
433 Type = QualType();
434 ExpectedLoc = Tok;
435}
436
437void PreferredTypeBuilder::enterParenExpr(SourceLocation Tok,
438 SourceLocation LParLoc) {
439 if (!Enabled)
440 return;
441 // expected type for parenthesized expression does not change.
442 if (ExpectedLoc == LParLoc)
443 ExpectedLoc = Tok;
444}
445
446static QualType getPreferredTypeOfBinaryRHS(Sema &S, Expr *LHS,
447 tok::TokenKind Op) {
448 if (!LHS)
449 return QualType();
450
451 QualType LHSType = LHS->getType();
452 if (LHSType->isPointerType()) {
453 if (Op == tok::plus || Op == tok::plusequal || Op == tok::minusequal)
454 return S.getASTContext().getPointerDiffType();
455 // Pointer difference is more common than subtracting an int from a pointer.
456 if (Op == tok::minus)
457 return LHSType;
458 }
459
460 switch (Op) {
461 // No way to infer the type of RHS from LHS.
462 case tok::comma:
463 return QualType();
464 // Prefer the type of the left operand for all of these.
465 // Arithmetic operations.
466 case tok::plus:
467 case tok::plusequal:
468 case tok::minus:
469 case tok::minusequal:
470 case tok::percent:
471 case tok::percentequal:
472 case tok::slash:
473 case tok::slashequal:
474 case tok::star:
475 case tok::starequal:
476 // Assignment.
477 case tok::equal:
478 // Comparison operators.
479 case tok::equalequal:
480 case tok::exclaimequal:
481 case tok::less:
482 case tok::lessequal:
483 case tok::greater:
484 case tok::greaterequal:
485 case tok::spaceship:
486 return LHS->getType();
487 // Binary shifts are often overloaded, so don't try to guess those.
488 case tok::greatergreater:
489 case tok::greatergreaterequal:
490 case tok::lessless:
491 case tok::lesslessequal:
492 if (LHSType->isIntegralOrEnumerationType())
493 return S.getASTContext().IntTy;
494 return QualType();
495 // Logical operators, assume we want bool.
496 case tok::ampamp:
497 case tok::pipepipe:
498 case tok::caretcaret:
499 return S.getASTContext().BoolTy;
500 // Operators often used for bit manipulation are typically used with the type
501 // of the left argument.
502 case tok::pipe:
503 case tok::pipeequal:
504 case tok::caret:
505 case tok::caretequal:
506 case tok::amp:
507 case tok::ampequal:
508 if (LHSType->isIntegralOrEnumerationType())
509 return LHSType;
510 return QualType();
511 // RHS should be a pointer to a member of the 'LHS' type, but we can't give
512 // any particular type here.
513 case tok::periodstar:
514 case tok::arrowstar:
515 return QualType();
516 default:
517 // FIXME(ibiryukov): handle the missing op, re-add the assertion.
518 // assert(false && "unhandled binary op");
519 return QualType();
520 }
521}
522
523/// Get preferred type for an argument of an unary expression. \p ContextType is
524/// preferred type of the whole unary expression.
525static QualType getPreferredTypeOfUnaryArg(Sema &S, QualType ContextType,
526 tok::TokenKind Op) {
527 switch (Op) {
528 case tok::exclaim:
529 return S.getASTContext().BoolTy;
530 case tok::amp:
531 if (!ContextType.isNull() && ContextType->isPointerType())
532 return ContextType->getPointeeType();
533 return QualType();
534 case tok::star:
535 if (ContextType.isNull())
536 return QualType();
537 return S.getASTContext().getPointerType(ContextType.getNonReferenceType());
538 case tok::plus:
539 case tok::minus:
540 case tok::tilde:
541 case tok::minusminus:
542 case tok::plusplus:
543 if (ContextType.isNull())
544 return S.getASTContext().IntTy;
545 // leave as is, these operators typically return the same type.
546 return ContextType;
547 case tok::kw___real:
548 case tok::kw___imag:
549 return QualType();
550 default:
551 assert(false && "unhandled unary op")(static_cast <bool> (false && "unhandled unary op"
) ? void (0) : __assert_fail ("false && \"unhandled unary op\""
, "clang/lib/Sema/SemaCodeComplete.cpp", 551, __extension__ __PRETTY_FUNCTION__
))
;
552 return QualType();
553 }
554}
555
556void PreferredTypeBuilder::enterBinary(Sema &S, SourceLocation Tok, Expr *LHS,
557 tok::TokenKind Op) {
558 if (!Enabled)
559 return;
560 ComputeType = nullptr;
561 Type = getPreferredTypeOfBinaryRHS(S, LHS, Op);
562 ExpectedLoc = Tok;
563}
564
565void PreferredTypeBuilder::enterMemAccess(Sema &S, SourceLocation Tok,
566 Expr *Base) {
567 if (!Enabled || !Base)
568 return;
569 // Do we have expected type for Base?
570 if (ExpectedLoc != Base->getBeginLoc())
571 return;
572 // Keep the expected type, only update the location.
573 ExpectedLoc = Tok;
574}
575
576void PreferredTypeBuilder::enterUnary(Sema &S, SourceLocation Tok,
577 tok::TokenKind OpKind,
578 SourceLocation OpLoc) {
579 if (!Enabled)
580 return;
581 ComputeType = nullptr;
582 Type = getPreferredTypeOfUnaryArg(S, this->get(OpLoc), OpKind);
583 ExpectedLoc = Tok;
584}
585
586void PreferredTypeBuilder::enterSubscript(Sema &S, SourceLocation Tok,
587 Expr *LHS) {
588 if (!Enabled)
589 return;
590 ComputeType = nullptr;
591 Type = S.getASTContext().IntTy;
592 ExpectedLoc = Tok;
593}
594
595void PreferredTypeBuilder::enterTypeCast(SourceLocation Tok,
596 QualType CastType) {
597 if (!Enabled)
598 return;
599 ComputeType = nullptr;
600 Type = !CastType.isNull() ? CastType.getCanonicalType() : QualType();
601 ExpectedLoc = Tok;
602}
603
604void PreferredTypeBuilder::enterCondition(Sema &S, SourceLocation Tok) {
605 if (!Enabled)
606 return;
607 ComputeType = nullptr;
608 Type = S.getASTContext().BoolTy;
609 ExpectedLoc = Tok;
610}
611
612class ResultBuilder::ShadowMapEntry::iterator {
613 llvm::PointerUnion<const NamedDecl *, const DeclIndexPair *> DeclOrIterator;
614 unsigned SingleDeclIndex;
615
616public:
617 typedef DeclIndexPair value_type;
618 typedef value_type reference;
619 typedef std::ptrdiff_t difference_type;
620 typedef std::input_iterator_tag iterator_category;
621
622 class pointer {
623 DeclIndexPair Value;
624
625 public:
626 pointer(const DeclIndexPair &Value) : Value(Value) {}
627
628 const DeclIndexPair *operator->() const { return &Value; }
629 };
630
631 iterator() : DeclOrIterator((NamedDecl *)nullptr), SingleDeclIndex(0) {}
632
633 iterator(const NamedDecl *SingleDecl, unsigned Index)
634 : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) {}
635
636 iterator(const DeclIndexPair *Iterator)
637 : DeclOrIterator(Iterator), SingleDeclIndex(0) {}
638
639 iterator &operator++() {
640 if (DeclOrIterator.is<const NamedDecl *>()) {
641 DeclOrIterator = (NamedDecl *)nullptr;
642 SingleDeclIndex = 0;
643 return *this;
644 }
645
646 const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair *>();
647 ++I;
648 DeclOrIterator = I;
649 return *this;
650 }
651
652 /*iterator operator++(int) {
653 iterator tmp(*this);
654 ++(*this);
655 return tmp;
656 }*/
657
658 reference operator*() const {
659 if (const NamedDecl *ND = DeclOrIterator.dyn_cast<const NamedDecl *>())
660 return reference(ND, SingleDeclIndex);
661
662 return *DeclOrIterator.get<const DeclIndexPair *>();
663 }
664
665 pointer operator->() const { return pointer(**this); }
666
667 friend bool operator==(const iterator &X, const iterator &Y) {
668 return X.DeclOrIterator.getOpaqueValue() ==
669 Y.DeclOrIterator.getOpaqueValue() &&
670 X.SingleDeclIndex == Y.SingleDeclIndex;
671 }
672
673 friend bool operator!=(const iterator &X, const iterator &Y) {
674 return !(X == Y);
675 }
676};
677
678ResultBuilder::ShadowMapEntry::iterator
679ResultBuilder::ShadowMapEntry::begin() const {
680 if (DeclOrVector.isNull())
681 return iterator();
682
683 if (const NamedDecl *ND = DeclOrVector.dyn_cast<const NamedDecl *>())
684 return iterator(ND, SingleDeclIndex);
685
686 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
687}
688
689ResultBuilder::ShadowMapEntry::iterator
690ResultBuilder::ShadowMapEntry::end() const {
691 if (DeclOrVector.is<const NamedDecl *>() || DeclOrVector.isNull())
692 return iterator();
693
694 return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
695}
696
697/// Compute the qualification required to get from the current context
698/// (\p CurContext) to the target context (\p TargetContext).
699///
700/// \param Context the AST context in which the qualification will be used.
701///
702/// \param CurContext the context where an entity is being named, which is
703/// typically based on the current scope.
704///
705/// \param TargetContext the context in which the named entity actually
706/// resides.
707///
708/// \returns a nested name specifier that refers into the target context, or
709/// NULL if no qualification is needed.
710static NestedNameSpecifier *
711getRequiredQualification(ASTContext &Context, const DeclContext *CurContext,
712 const DeclContext *TargetContext) {
713 SmallVector<const DeclContext *, 4> TargetParents;
714
715 for (const DeclContext *CommonAncestor = TargetContext;
716 CommonAncestor && !CommonAncestor->Encloses(CurContext);
717 CommonAncestor = CommonAncestor->getLookupParent()) {
718 if (CommonAncestor->isTransparentContext() ||
719 CommonAncestor->isFunctionOrMethod())
720 continue;
721
722 TargetParents.push_back(CommonAncestor);
723 }
724
725 NestedNameSpecifier *Result = nullptr;
726 while (!TargetParents.empty()) {
727 const DeclContext *Parent = TargetParents.pop_back_val();
728
729 if (const auto *Namespace = dyn_cast<NamespaceDecl>(Parent)) {
730 if (!Namespace->getIdentifier())
731 continue;
732
733 Result = NestedNameSpecifier::Create(Context, Result, Namespace);
734 } else if (const auto *TD = dyn_cast<TagDecl>(Parent))
735 Result = NestedNameSpecifier::Create(
736 Context, Result, false, Context.getTypeDeclType(TD).getTypePtr());
737 }
738 return Result;
739}
740
741// Some declarations have reserved names that we don't want to ever show.
742// Filter out names reserved for the implementation if they come from a
743// system header.
744static bool shouldIgnoreDueToReservedName(const NamedDecl *ND, Sema &SemaRef) {
745 ReservedIdentifierStatus Status = ND->isReserved(SemaRef.getLangOpts());
746 // Ignore reserved names for compiler provided decls.
747 if (isReservedInAllContexts(Status) && ND->getLocation().isInvalid())
748 return true;
749
750 // For system headers ignore only double-underscore names.
751 // This allows for system headers providing private symbols with a single
752 // underscore.
753 if (Status == ReservedIdentifierStatus::StartsWithDoubleUnderscore &&
754 SemaRef.SourceMgr.isInSystemHeader(
755 SemaRef.SourceMgr.getSpellingLoc(ND->getLocation())))
756 return true;
757
758 return false;
759}
760
761bool ResultBuilder::isInterestingDecl(const NamedDecl *ND,
762 bool &AsNestedNameSpecifier) const {
763 AsNestedNameSpecifier = false;
764
765 auto *Named = ND;
766 ND = ND->getUnderlyingDecl();
767
768 // Skip unnamed entities.
769 if (!ND->getDeclName())
770 return false;
771
772 // Friend declarations and declarations introduced due to friends are never
773 // added as results.
774 if (ND->getFriendObjectKind() == Decl::FOK_Undeclared)
775 return false;
776
777 // Class template (partial) specializations are never added as results.
778 if (isa<ClassTemplateSpecializationDecl>(ND) ||
779 isa<ClassTemplatePartialSpecializationDecl>(ND))
780 return false;
781
782 // Using declarations themselves are never added as results.
783 if (isa<UsingDecl>(ND))
784 return false;
785
786 if (shouldIgnoreDueToReservedName(ND, SemaRef))
787 return false;
788
789 if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
790 (isa<NamespaceDecl>(ND) && Filter != &ResultBuilder::IsNamespace &&
791 Filter != &ResultBuilder::IsNamespaceOrAlias && Filter != nullptr))
792 AsNestedNameSpecifier = true;
793
794 // Filter out any unwanted results.
795 if (Filter && !(this->*Filter)(Named)) {
796 // Check whether it is interesting as a nested-name-specifier.
797 if (AllowNestedNameSpecifiers && SemaRef.getLangOpts().CPlusPlus &&
798 IsNestedNameSpecifier(ND) &&
799 (Filter != &ResultBuilder::IsMember ||
800 (isa<CXXRecordDecl>(ND) &&
801 cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
802 AsNestedNameSpecifier = true;
803 return true;
804 }
805
806 return false;
807 }
808 // ... then it must be interesting!
809 return true;
810}
811
812bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
813 const NamedDecl *Hiding) {
814 // In C, there is no way to refer to a hidden name.
815 // FIXME: This isn't true; we can find a tag name hidden by an ordinary
816 // name if we introduce the tag type.
817 if (!SemaRef.getLangOpts().CPlusPlus)
818 return true;
819
820 const DeclContext *HiddenCtx =
821 R.Declaration->getDeclContext()->getRedeclContext();
822
823 // There is no way to qualify a name declared in a function or method.
824 if (HiddenCtx->isFunctionOrMethod())
825 return true;
826
827 if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext())
828 return true;
829
830 // We can refer to the result with the appropriate qualification. Do it.
831 R.Hidden = true;
832 R.QualifierIsInformative = false;
833
834 if (!R.Qualifier)
835 R.Qualifier = getRequiredQualification(SemaRef.Context, CurContext,
836 R.Declaration->getDeclContext());
837 return false;
838}
839
840/// A simplified classification of types used to determine whether two
841/// types are "similar enough" when adjusting priorities.
842SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) {
843 switch (T->getTypeClass()) {
844 case Type::Builtin:
845 switch (cast<BuiltinType>(T)->getKind()) {
846 case BuiltinType::Void:
847 return STC_Void;
848
849 case BuiltinType::NullPtr:
850 return STC_Pointer;
851
852 case BuiltinType::Overload:
853 case BuiltinType::Dependent:
854 return STC_Other;
855
856 case BuiltinType::ObjCId:
857 case BuiltinType::ObjCClass:
858 case BuiltinType::ObjCSel:
859 return STC_ObjectiveC;
860
861 default:
862 return STC_Arithmetic;
863 }
864
865 case Type::Complex:
866 return STC_Arithmetic;
867
868 case Type::Pointer:
869 return STC_Pointer;
870
871 case Type::BlockPointer:
872 return STC_Block;
873
874 case Type::LValueReference:
875 case Type::RValueReference:
876 return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
877
878 case Type::ConstantArray:
879 case Type::IncompleteArray:
880 case Type::VariableArray:
881 case Type::DependentSizedArray:
882 return STC_Array;
883
884 case Type::DependentSizedExtVector:
885 case Type::Vector:
886 case Type::ExtVector:
887 return STC_Arithmetic;
888
889 case Type::FunctionProto:
890 case Type::FunctionNoProto:
891 return STC_Function;
892
893 case Type::Record:
894 return STC_Record;
895
896 case Type::Enum:
897 return STC_Arithmetic;
898
899 case Type::ObjCObject:
900 case Type::ObjCInterface:
901 case Type::ObjCObjectPointer:
902 return STC_ObjectiveC;
903
904 default:
905 return STC_Other;
906 }
907}
908
909/// Get the type that a given expression will have if this declaration
910/// is used as an expression in its "typical" code-completion form.
911QualType clang::getDeclUsageType(ASTContext &C, const NamedDecl *ND) {
912 ND = ND->getUnderlyingDecl();
913
914 if (const auto *Type = dyn_cast<TypeDecl>(ND))
915 return C.getTypeDeclType(Type);
916 if (const auto *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
917 return C.getObjCInterfaceType(Iface);
918
919 QualType T;
920 if (const FunctionDecl *Function = ND->getAsFunction())
921 T = Function->getCallResultType();
922 else if (const auto *Method = dyn_cast<ObjCMethodDecl>(ND))
923 T = Method->getSendResultType();
924 else if (const auto *Enumerator = dyn_cast<EnumConstantDecl>(ND))
925 T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
926 else if (const auto *Property = dyn_cast<ObjCPropertyDecl>(ND))
927 T = Property->getType();
928 else if (const auto *Value = dyn_cast<ValueDecl>(ND))
929 T = Value->getType();
930
931 if (T.isNull())
932 return QualType();
933
934 // Dig through references, function pointers, and block pointers to
935 // get down to the likely type of an expression when the entity is
936 // used.
937 do {
938 if (const auto *Ref = T->getAs<ReferenceType>()) {
939 T = Ref->getPointeeType();
940 continue;
941 }
942
943 if (const auto *Pointer = T->getAs<PointerType>()) {
944 if (Pointer->getPointeeType()->isFunctionType()) {
945 T = Pointer->getPointeeType();
946 continue;
947 }
948
949 break;
950 }
951
952 if (const auto *Block = T->getAs<BlockPointerType>()) {
953 T = Block->getPointeeType();
954 continue;
955 }
956
957 if (const auto *Function = T->getAs<FunctionType>()) {
958 T = Function->getReturnType();
959 continue;
960 }
961
962 break;
963 } while (true);
964
965 return T;
966}
967
968unsigned ResultBuilder::getBasePriority(const NamedDecl *ND) {
969 if (!ND)
970 return CCP_Unlikely;
971
972 // Context-based decisions.
973 const DeclContext *LexicalDC = ND->getLexicalDeclContext();
974 if (LexicalDC->isFunctionOrMethod()) {
975 // _cmd is relatively rare
976 if (const auto *ImplicitParam = dyn_cast<ImplicitParamDecl>(ND))
977 if (ImplicitParam->getIdentifier() &&
978 ImplicitParam->getIdentifier()->isStr("_cmd"))
979 return CCP_ObjC_cmd;
980
981 return CCP_LocalDeclaration;
982 }
983
984 const DeclContext *DC = ND->getDeclContext()->getRedeclContext();
985 if (DC->isRecord() || isa<ObjCContainerDecl>(DC)) {
986 // Explicit destructor calls are very rare.
987 if (isa<CXXDestructorDecl>(ND))
988 return CCP_Unlikely;
989 // Explicit operator and conversion function calls are also very rare.
990 auto DeclNameKind = ND->getDeclName().getNameKind();
991 if (DeclNameKind == DeclarationName::CXXOperatorName ||
992 DeclNameKind == DeclarationName::CXXLiteralOperatorName ||
993 DeclNameKind == DeclarationName::CXXConversionFunctionName)
994 return CCP_Unlikely;
995 return CCP_MemberDeclaration;
996 }
997
998 // Content-based decisions.
999 if (isa<EnumConstantDecl>(ND))
1000 return CCP_Constant;
1001
1002 // Use CCP_Type for type declarations unless we're in a statement, Objective-C
1003 // message receiver, or parenthesized expression context. There, it's as
1004 // likely that the user will want to write a type as other declarations.
1005 if ((isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
1006 !(CompletionContext.getKind() == CodeCompletionContext::CCC_Statement ||
1007 CompletionContext.getKind() ==
1008 CodeCompletionContext::CCC_ObjCMessageReceiver ||
1009 CompletionContext.getKind() ==
1010 CodeCompletionContext::CCC_ParenthesizedExpression))
1011 return CCP_Type;
1012
1013 return CCP_Declaration;
1014}
1015
1016void ResultBuilder::AdjustResultPriorityForDecl(Result &R) {
1017 // If this is an Objective-C method declaration whose selector matches our
1018 // preferred selector, give it a priority boost.
1019 if (!PreferredSelector.isNull())
1020 if (const auto *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
1021 if (PreferredSelector == Method->getSelector())
1022 R.Priority += CCD_SelectorMatch;
1023
1024 // If we have a preferred type, adjust the priority for results with exactly-
1025 // matching or nearly-matching types.
1026 if (!PreferredType.isNull()) {
1027 QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
1028 if (!T.isNull()) {
1029 CanQualType TC = SemaRef.Context.getCanonicalType(T);
1030 // Check for exactly-matching types (modulo qualifiers).
1031 if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
1032 R.Priority /= CCF_ExactTypeMatch;
1033 // Check for nearly-matching types, based on classification of each.
1034 else if ((getSimplifiedTypeClass(PreferredType) ==
1035 getSimplifiedTypeClass(TC)) &&
1036 !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
1037 R.Priority /= CCF_SimilarTypeMatch;
1038 }
1039 }
1040}
1041
1042static DeclContext::lookup_result getConstructors(ASTContext &Context,
1043 const CXXRecordDecl *Record) {
1044 QualType RecordTy = Context.getTypeDeclType(Record);
1045 DeclarationName ConstructorName =
1046 Context.DeclarationNames.getCXXConstructorName(
1047 Context.getCanonicalType(RecordTy));
1048 return Record->lookup(ConstructorName);
1049}
1050
1051void ResultBuilder::MaybeAddConstructorResults(Result R) {
1052 if (!SemaRef.getLangOpts().CPlusPlus || !R.Declaration ||
1053 !CompletionContext.wantConstructorResults())
1054 return;
1055
1056 const NamedDecl *D = R.Declaration;
1057 const CXXRecordDecl *Record = nullptr;
1058 if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D))
1059 Record = ClassTemplate->getTemplatedDecl();
1060 else if ((Record = dyn_cast<CXXRecordDecl>(D))) {
1061 // Skip specializations and partial specializations.
1062 if (isa<ClassTemplateSpecializationDecl>(Record))
1063 return;
1064 } else {
1065 // There are no constructors here.
1066 return;
1067 }
1068
1069 Record = Record->getDefinition();
1070 if (!Record)
1071 return;
1072
1073 for (NamedDecl *Ctor : getConstructors(SemaRef.Context, Record)) {
1074 R.Declaration = Ctor;
1075 R.CursorKind = getCursorKindForDecl(R.Declaration);
1076 Results.push_back(R);
1077 }
1078}
1079
1080static bool isConstructor(const Decl *ND) {
1081 if (const auto *Tmpl = dyn_cast<FunctionTemplateDecl>(ND))
1082 ND = Tmpl->getTemplatedDecl();
1083 return isa<CXXConstructorDecl>(ND);
1084}
1085
1086void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
1087 assert(!ShadowMaps.empty() && "Must enter into a results scope")(static_cast <bool> (!ShadowMaps.empty() && "Must enter into a results scope"
) ? void (0) : __assert_fail ("!ShadowMaps.empty() && \"Must enter into a results scope\""
, "clang/lib/Sema/SemaCodeComplete.cpp", 1087, __extension__ __PRETTY_FUNCTION__
))
;
1088
1089 if (R.Kind != Result::RK_Declaration) {
1090 // For non-declaration results, just add the result.
1091 Results.push_back(R);
1092 return;
1093 }
1094
1095 // Look through using declarations.
1096 if (const UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
1097 CodeCompletionResult Result(Using->getTargetDecl(),
1098 getBasePriority(Using->getTargetDecl()),
1099 R.Qualifier, false,
1100 (R.Availability == CXAvailability_Available ||
1101 R.Availability == CXAvailability_Deprecated),
1102 std::move(R.FixIts));
1103 Result.ShadowDecl = Using;
1104 MaybeAddResult(Result, CurContext);
1105 return;
1106 }
1107
1108 const Decl *CanonDecl = R.Declaration->getCanonicalDecl();
1109 unsigned IDNS = CanonDecl->getIdentifierNamespace();
1110
1111 bool AsNestedNameSpecifier = false;
1112 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
1113 return;
1114
1115 // C++ constructors are never found by name lookup.
1116 if (isConstructor(R.Declaration))
1117 return;
1118
1119 ShadowMap &SMap = ShadowMaps.back();
1120 ShadowMapEntry::iterator I, IEnd;
1121 ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
1122 if (NamePos != SMap.end()) {
1123 I = NamePos->second.begin();
1124 IEnd = NamePos->second.end();
1125 }
1126
1127 for (; I != IEnd; ++I) {
1128 const NamedDecl *ND = I->first;
1129 unsigned Index = I->second;
1130 if (ND->getCanonicalDecl() == CanonDecl) {
1131 // This is a redeclaration. Always pick the newer declaration.
1132 Results[Index].Declaration = R.Declaration;
1133
1134 // We're done.
1135 return;
1136 }
1137 }
1138
1139 // This is a new declaration in this scope. However, check whether this
1140 // declaration name is hidden by a similarly-named declaration in an outer
1141 // scope.
1142 std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
1143 --SMEnd;
1144 for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
1145 ShadowMapEntry::iterator I, IEnd;
1146 ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
1147 if (NamePos != SM->end()) {
1148 I = NamePos->second.begin();
1149 IEnd = NamePos->second.end();
1150 }
1151 for (; I != IEnd; ++I) {
1152 // A tag declaration does not hide a non-tag declaration.
1153 if (I->first->hasTagIdentifierNamespace() &&
1154 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
1155 Decl::IDNS_LocalExtern | Decl::IDNS_ObjCProtocol)))
1156 continue;
1157
1158 // Protocols are in distinct namespaces from everything else.
1159 if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol) ||
1160 (IDNS & Decl::IDNS_ObjCProtocol)) &&
1161 I->first->getIdentifierNamespace() != IDNS)
1162 continue;
1163
1164 // The newly-added result is hidden by an entry in the shadow map.
1165 if (CheckHiddenResult(R, CurContext, I->first))
1166 return;
1167
1168 break;
1169 }
1170 }
1171
1172 // Make sure that any given declaration only shows up in the result set once.
1173 if (!AllDeclsFound.insert(CanonDecl).second)
1174 return;
1175
1176 // If the filter is for nested-name-specifiers, then this result starts a
1177 // nested-name-specifier.
1178 if (AsNestedNameSpecifier) {
1179 R.StartsNestedNameSpecifier = true;
1180 R.Priority = CCP_NestedNameSpecifier;
1181 } else
1182 AdjustResultPriorityForDecl(R);
1183
1184 // If this result is supposed to have an informative qualifier, add one.
1185 if (R.QualifierIsInformative && !R.Qualifier &&
1186 !R.StartsNestedNameSpecifier) {
1187 const DeclContext *Ctx = R.Declaration->getDeclContext();
1188 if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
1189 R.Qualifier =
1190 NestedNameSpecifier::Create(SemaRef.Context, nullptr, Namespace);
1191 else if (const TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
1192 R.Qualifier = NestedNameSpecifier::Create(
1193 SemaRef.Context, nullptr, false,
1194 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
1195 else
1196 R.QualifierIsInformative = false;
1197 }
1198
1199 // Insert this result into the set of results and into the current shadow
1200 // map.
1201 SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
1202 Results.push_back(R);
1203
1204 if (!AsNestedNameSpecifier)
1205 MaybeAddConstructorResults(R);
1206}
1207
1208static void setInBaseClass(ResultBuilder::Result &R) {
1209 R.Priority += CCD_InBaseClass;
1210 R.InBaseClass = true;
1211}
1212
1213enum class OverloadCompare { BothViable, Dominates, Dominated };
1214// Will Candidate ever be called on the object, when overloaded with Incumbent?
1215// Returns Dominates if Candidate is always called, Dominated if Incumbent is
1216// always called, BothViable if either may be called depending on arguments.
1217// Precondition: must actually be overloads!
1218static OverloadCompare compareOverloads(const CXXMethodDecl &Candidate,
1219 const CXXMethodDecl &Incumbent,
1220 const Qualifiers &ObjectQuals,
1221 ExprValueKind ObjectKind) {
1222 // Base/derived shadowing is handled elsewhere.
1223 if (Candidate.getDeclContext() != Incumbent.getDeclContext())
1224 return OverloadCompare::BothViable;
1225 if (Candidate.isVariadic() != Incumbent.isVariadic() ||
1226 Candidate.getNumParams() != Incumbent.getNumParams() ||
1227 Candidate.getMinRequiredArguments() !=
1228 Incumbent.getMinRequiredArguments())
1229 return OverloadCompare::BothViable;
1230 for (unsigned I = 0, E = Candidate.getNumParams(); I != E; ++I)
1231 if (Candidate.parameters()[I]->getType().getCanonicalType() !=
1232 Incumbent.parameters()[I]->getType().getCanonicalType())
1233 return OverloadCompare::BothViable;
1234 if (!llvm::empty(Candidate.specific_attrs<EnableIfAttr>()) ||
1235 !llvm::empty(Incumbent.specific_attrs<EnableIfAttr>()))
1236 return OverloadCompare::BothViable;
1237 // At this point, we know calls can't pick one or the other based on
1238 // arguments, so one of the two must win. (Or both fail, handled elsewhere).
1239 RefQualifierKind CandidateRef = Candidate.getRefQualifier();
1240 RefQualifierKind IncumbentRef = Incumbent.getRefQualifier();
1241 if (CandidateRef != IncumbentRef) {
1242 // If the object kind is LValue/RValue, there's one acceptable ref-qualifier
1243 // and it can't be mixed with ref-unqualified overloads (in valid code).
1244
1245 // For xvalue objects, we prefer the rvalue overload even if we have to
1246 // add qualifiers (which is rare, because const&& is rare).
1247 if (ObjectKind == clang::VK_XValue)
1248 return CandidateRef == RQ_RValue ? OverloadCompare::Dominates
1249 : OverloadCompare::Dominated;
1250 }
1251 // Now the ref qualifiers are the same (or we're in some invalid state).
1252 // So make some decision based on the qualifiers.
1253 Qualifiers CandidateQual = Candidate.getMethodQualifiers();
1254 Qualifiers IncumbentQual = Incumbent.getMethodQualifiers();
1255 bool CandidateSuperset = CandidateQual.compatiblyIncludes(IncumbentQual);
1256 bool IncumbentSuperset = IncumbentQual.compatiblyIncludes(CandidateQual);
1257 if (CandidateSuperset == IncumbentSuperset)
1258 return OverloadCompare::BothViable;
1259 return IncumbentSuperset ? OverloadCompare::Dominates
1260 : OverloadCompare::Dominated;
1261}
1262
1263void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
1264 NamedDecl *Hiding, bool InBaseClass = false) {
1265 if (R.Kind != Result::RK_Declaration) {
1266 // For non-declaration results, just add the result.
1267 Results.push_back(R);
1268 return;
1269 }
1270
1271 // Look through using declarations.
1272 if (const auto *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
1273 CodeCompletionResult Result(Using->getTargetDecl(),
1274 getBasePriority(Using->getTargetDecl()),
1275 R.Qualifier, false,
1276 (R.Availability == CXAvailability_Available ||
1277 R.Availability == CXAvailability_Deprecated),
1278 std::move(R.FixIts));
1279 Result.ShadowDecl = Using;
1280 AddResult(Result, CurContext, Hiding);
1281 return;
1282 }
1283
1284 bool AsNestedNameSpecifier = false;
1285 if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
1286 return;
1287
1288 // C++ constructors are never found by name lookup.
1289 if (isConstructor(R.Declaration))
1290 return;
1291
1292 if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
1293 return;
1294
1295 // Make sure that any given declaration only shows up in the result set once.
1296 if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()).second)
1297 return;
1298
1299 // If the filter is for nested-name-specifiers, then this result starts a
1300 // nested-name-specifier.
1301 if (AsNestedNameSpecifier) {
1302 R.StartsNestedNameSpecifier = true;
1303 R.Priority = CCP_NestedNameSpecifier;
1304 } else if (Filter == &ResultBuilder::IsMember && !R.Qualifier &&
1305 InBaseClass &&
1306 isa<CXXRecordDecl>(
1307 R.Declaration->getDeclContext()->getRedeclContext()))
1308 R.QualifierIsInformative = true;
1309
1310 // If this result is supposed to have an informative qualifier, add one.
1311 if (R.QualifierIsInformative && !R.Qualifier &&
1312 !R.StartsNestedNameSpecifier) {
1313 const DeclContext *Ctx = R.Declaration->getDeclContext();
1314 if (const auto *Namespace = dyn_cast<NamespaceDecl>(Ctx))
1315 R.Qualifier =
1316 NestedNameSpecifier::Create(SemaRef.Context, nullptr, Namespace);
1317 else if (const auto *Tag = dyn_cast<TagDecl>(Ctx))
1318 R.Qualifier = NestedNameSpecifier::Create(
1319 SemaRef.Context, nullptr, false,
1320 SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
1321 else
1322 R.QualifierIsInformative = false;
1323 }
1324
1325 // Adjust the priority if this result comes from a base class.
1326 if (InBaseClass)
1327 setInBaseClass(R);
1328
1329 AdjustResultPriorityForDecl(R);
1330
1331 if (HasObjectTypeQualifiers)
1332 if (const auto *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
1333 if (Method->isInstance()) {
1334 Qualifiers MethodQuals = Method->getMethodQualifiers();
1335 if (ObjectTypeQualifiers == MethodQuals)
1336 R.Priority += CCD_ObjectQualifierMatch;
1337 else if (ObjectTypeQualifiers - MethodQuals) {
1338 // The method cannot be invoked, because doing so would drop
1339 // qualifiers.
1340 return;
1341 }
1342 // Detect cases where a ref-qualified method cannot be invoked.
1343 switch (Method->getRefQualifier()) {
1344 case RQ_LValue:
1345 if (ObjectKind != VK_LValue && !MethodQuals.hasConst())
1346 return;
1347 break;
1348 case RQ_RValue:
1349 if (ObjectKind == VK_LValue)
1350 return;
1351 break;
1352 case RQ_None:
1353 break;
1354 }
1355
1356 /// Check whether this dominates another overloaded method, which should
1357 /// be suppressed (or vice versa).
1358 /// Motivating case is const_iterator begin() const vs iterator begin().
1359 auto &OverloadSet = OverloadMap[std::make_pair(
1360 CurContext, Method->getDeclName().getAsOpaqueInteger())];
1361 for (const DeclIndexPair Entry : OverloadSet) {
1362 Result &Incumbent = Results[Entry.second];
1363 switch (compareOverloads(*Method,
1364 *cast<CXXMethodDecl>(Incumbent.Declaration),
1365 ObjectTypeQualifiers, ObjectKind)) {
1366 case OverloadCompare::Dominates:
1367 // Replace the dominated overload with this one.
1368 // FIXME: if the overload dominates multiple incumbents then we
1369 // should remove all. But two overloads is by far the common case.
1370 Incumbent = std::move(R);
1371 return;
1372 case OverloadCompare::Dominated:
1373 // This overload can't be called, drop it.
1374 return;
1375 case OverloadCompare::BothViable:
1376 break;
1377 }
1378 }
1379 OverloadSet.Add(Method, Results.size());
1380 }
1381
1382 // Insert this result into the set of results.
1383 Results.push_back(R);
1384
1385 if (!AsNestedNameSpecifier)
1386 MaybeAddConstructorResults(R);
1387}
1388
1389void ResultBuilder::AddResult(Result R) {
1390 assert(R.Kind != Result::RK_Declaration &&(static_cast <bool> (R.Kind != Result::RK_Declaration &&
"Declaration results need more context") ? void (0) : __assert_fail
("R.Kind != Result::RK_Declaration && \"Declaration results need more context\""
, "clang/lib/Sema/SemaCodeComplete.cpp", 1391, __extension__ __PRETTY_FUNCTION__
))
1391 "Declaration results need more context")(static_cast <bool> (R.Kind != Result::RK_Declaration &&
"Declaration results need more context") ? void (0) : __assert_fail
("R.Kind != Result::RK_Declaration && \"Declaration results need more context\""
, "clang/lib/Sema/SemaCodeComplete.cpp", 1391, __extension__ __PRETTY_FUNCTION__
))
;
1392 Results.push_back(R);
1393}
1394
1395/// Enter into a new scope.
1396void ResultBuilder::EnterNewScope() { ShadowMaps.emplace_back(); }
1397
1398/// Exit from the current scope.
1399void ResultBuilder::ExitScope() {
1400 ShadowMaps.pop_back();
1401}
1402
1403/// Determines whether this given declaration will be found by
1404/// ordinary name lookup.
1405bool ResultBuilder::IsOrdinaryName(const NamedDecl *ND) const {
1406 ND = ND->getUnderlyingDecl();
1407
1408 // If name lookup finds a local extern declaration, then we are in a
1409 // context where it behaves like an ordinary name.
1410 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
1411 if (SemaRef.getLangOpts().CPlusPlus)
1412 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
1413 else if (SemaRef.getLangOpts().ObjC) {
1414 if (isa<ObjCIvarDecl>(ND))
1415 return true;
1416 }
1417
1418 return ND->getIdentifierNamespace() & IDNS;
1419}
1420
1421/// Determines whether this given declaration will be found by
1422/// ordinary name lookup but is not a type name.
1423bool ResultBuilder::IsOrdinaryNonTypeName(const NamedDecl *ND) const {
1424 ND = ND->getUnderlyingDecl();
1425 if (isa<TypeDecl>(ND))
1426 return false;
1427 // Objective-C interfaces names are not filtered by this method because they
1428 // can be used in a class property expression. We can still filter out
1429 // @class declarations though.
1430 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND)) {
1431 if (!ID->getDefinition())
1432 return false;
1433 }
1434
1435 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
1436 if (SemaRef.getLangOpts().CPlusPlus)
1437 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
1438 else if (SemaRef.getLangOpts().ObjC) {
1439 if (isa<ObjCIvarDecl>(ND))
1440 return true;
1441 }
1442
1443 return ND->getIdentifierNamespace() & IDNS;
1444}
1445
1446bool ResultBuilder::IsIntegralConstantValue(const NamedDecl *ND) const {
1447 if (!IsOrdinaryNonTypeName(ND))
1448 return false;
1449
1450 if (const auto *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
1451 if (VD->getType()->isIntegralOrEnumerationType())
1452 return true;
1453
1454 return false;
1455}
1456
1457/// Determines whether this given declaration will be found by
1458/// ordinary name lookup.
1459bool ResultBuilder::IsOrdinaryNonValueName(const NamedDecl *ND) const {
1460 ND = ND->getUnderlyingDecl();
1461
1462 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
1463 if (SemaRef.getLangOpts().CPlusPlus)
1464 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
1465
1466 return (ND->getIdentifierNamespace() & IDNS) && !isa<ValueDecl>(ND) &&
1467 !isa<FunctionTemplateDecl>(ND) && !isa<ObjCPropertyDecl>(ND);
1468}
1469
1470/// Determines whether the given declaration is suitable as the
1471/// start of a C++ nested-name-specifier, e.g., a class or namespace.
1472bool ResultBuilder::IsNestedNameSpecifier(const NamedDecl *ND) const {
1473 // Allow us to find class templates, too.
1474 if (const auto *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1475 ND = ClassTemplate->getTemplatedDecl();
1476
1477 return SemaRef.isAcceptableNestedNameSpecifier(ND);
1478}
1479
1480/// Determines whether the given declaration is an enumeration.
1481bool ResultBuilder::IsEnum(const NamedDecl *ND) const {
1482 return isa<EnumDecl>(ND);
1483}
1484
1485/// Determines whether the given declaration is a class or struct.
1486bool ResultBuilder::IsClassOrStruct(const NamedDecl *ND) const {
1487 // Allow us to find class templates, too.
1488 if (const auto *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1489 ND = ClassTemplate->getTemplatedDecl();
1490
1491 // For purposes of this check, interfaces match too.
1492 if (const auto *RD = dyn_cast<RecordDecl>(ND))
1493 return RD->getTagKind() == TTK_Class || RD->getTagKind() == TTK_Struct ||
1494 RD->getTagKind() == TTK_Interface;
1495
1496 return false;
1497}
1498
1499/// Determines whether the given declaration is a union.
1500bool ResultBuilder::IsUnion(const NamedDecl *ND) const {
1501 // Allow us to find class templates, too.
1502 if (const auto *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
1503 ND = ClassTemplate->getTemplatedDecl();
1504
1505 if (const auto *RD = dyn_cast<RecordDecl>(ND))
1506 return RD->getTagKind() == TTK_Union;
1507
1508 return false;
1509}
1510
1511/// Determines whether the given declaration is a namespace.
1512bool ResultBuilder::IsNamespace(const NamedDecl *ND) const {
1513 return isa<NamespaceDecl>(ND);
1514}
1515
1516/// Determines whether the given declaration is a namespace or
1517/// namespace alias.
1518bool ResultBuilder::IsNamespaceOrAlias(const NamedDecl *ND) const {
1519 return isa<NamespaceDecl>(ND->getUnderlyingDecl());
1520}
1521
1522/// Determines whether the given declaration is a type.
1523bool ResultBuilder::IsType(const NamedDecl *ND) const {
1524 ND = ND->getUnderlyingDecl();
1525 return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
1526}
1527
1528/// Determines which members of a class should be visible via
1529/// "." or "->". Only value declarations, nested name specifiers, and
1530/// using declarations thereof should show up.
1531bool ResultBuilder::IsMember(const NamedDecl *ND) const {
1532 ND = ND->getUnderlyingDecl();
1533 return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
1534 isa<ObjCPropertyDecl>(ND);
1535}
1536
1537static bool isObjCReceiverType(ASTContext &C, QualType T) {
1538 T = C.getCanonicalType(T);
1539 switch (T->getTypeClass()) {
1540 case Type::ObjCObject:
1541 case Type::ObjCInterface:
1542 case Type::ObjCObjectPointer:
1543 return true;
1544
1545 case Type::Builtin:
1546 switch (cast<BuiltinType>(T)->getKind()) {
1547 case BuiltinType::ObjCId:
1548 case BuiltinType::ObjCClass:
1549 case BuiltinType::ObjCSel:
1550 return true;
1551
1552 default:
1553 break;
1554 }
1555 return false;
1556
1557 default:
1558 break;
1559 }
1560
1561 if (!C.getLangOpts().CPlusPlus)
1562 return false;
1563
1564 // FIXME: We could perform more analysis here to determine whether a
1565 // particular class type has any conversions to Objective-C types. For now,
1566 // just accept all class types.
1567 return T->isDependentType() || T->isRecordType();
1568}
1569
1570bool ResultBuilder::IsObjCMessageReceiver(const NamedDecl *ND) const {
1571 QualType T = getDeclUsageType(SemaRef.Context, ND);
1572 if (T.isNull())
1573 return false;
1574
1575 T = SemaRef.Context.getBaseElementType(T);
1576 return isObjCReceiverType(SemaRef.Context, T);
1577}
1578
1579bool ResultBuilder::IsObjCMessageReceiverOrLambdaCapture(
1580 const NamedDecl *ND) const {
1581 if (IsObjCMessageReceiver(ND))
1582 return true;
1583
1584 const auto *Var = dyn_cast<VarDecl>(ND);
1585 if (!Var)
1586 return false;
1587
1588 return Var->hasLocalStorage() && !Var->hasAttr<BlocksAttr>();
1589}
1590
1591bool ResultBuilder::IsObjCCollection(const NamedDecl *ND) const {
1592 if ((SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryName(ND)) ||
1593 (!SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
1594 return false;
1595
1596 QualType T = getDeclUsageType(SemaRef.Context, ND);
1597 if (T.isNull())
1598 return false;
1599
1600 T = SemaRef.Context.getBaseElementType(T);
1601 return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
1602 T->isObjCIdType() ||
1603 (SemaRef.getLangOpts().CPlusPlus && T->isRecordType());
1604}
1605
1606bool ResultBuilder::IsImpossibleToSatisfy(const NamedDecl *ND) const {
1607 return false;
1608}
1609
1610/// Determines whether the given declaration is an Objective-C
1611/// instance variable.
1612bool ResultBuilder::IsObjCIvar(const NamedDecl *ND) const {
1613 return isa<ObjCIvarDecl>(ND);
1614}
1615
1616namespace {
1617
1618/// Visible declaration consumer that adds a code-completion result
1619/// for each visible declaration.
1620class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
1621 ResultBuilder &Results;
1622 DeclContext *InitialLookupCtx;
1623 // NamingClass and BaseType are used for access-checking. See
1624 // Sema::IsSimplyAccessible for details.
1625 CXXRecordDecl *NamingClass;
1626 QualType BaseType;
1627 std::vector<FixItHint> FixIts;
1628
1629public:
1630 CodeCompletionDeclConsumer(
1631 ResultBuilder &Results, DeclContext *InitialLookupCtx,
1632 QualType BaseType = QualType(),
1633 std::vector<FixItHint> FixIts = std::vector<FixItHint>())
1634 : Results(Results), InitialLookupCtx(InitialLookupCtx),
1635 FixIts(std::move(FixIts)) {
1636 NamingClass = llvm::dyn_cast<CXXRecordDecl>(InitialLookupCtx);
1637 // If BaseType was not provided explicitly, emulate implicit 'this->'.
1638 if (BaseType.isNull()) {
1639 auto ThisType = Results.getSema().getCurrentThisType();
1640 if (!ThisType.isNull()) {
1641 assert(ThisType->isPointerType())(static_cast <bool> (ThisType->isPointerType()) ? void
(0) : __assert_fail ("ThisType->isPointerType()", "clang/lib/Sema/SemaCodeComplete.cpp"
, 1641, __extension__ __PRETTY_FUNCTION__))
;
1642 BaseType = ThisType->getPointeeType();
1643 if (!NamingClass)
1644 NamingClass = BaseType->getAsCXXRecordDecl();
1645 }
1646 }
1647 this->BaseType = BaseType;
1648 }
1649
1650 void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
1651 bool InBaseClass) override {
1652 ResultBuilder::Result Result(ND, Results.getBasePriority(ND), nullptr,
1653 false, IsAccessible(ND, Ctx), FixIts);
1654 Results.AddResult(Result, InitialLookupCtx, Hiding, InBaseClass);
1655 }
1656
1657 void EnteredContext(DeclContext *Ctx) override {
1658 Results.addVisitedContext(Ctx);
1659 }
1660
1661private:
1662 bool IsAccessible(NamedDecl *ND, DeclContext *Ctx) {
1663 // Naming class to use for access check. In most cases it was provided
1664 // explicitly (e.g. member access (lhs.foo) or qualified lookup (X::)),
1665 // for unqualified lookup we fallback to the \p Ctx in which we found the
1666 // member.
1667 auto *NamingClass = this->NamingClass;
1668 QualType BaseType = this->BaseType;
1669 if (auto *Cls = llvm::dyn_cast_or_null<CXXRecordDecl>(Ctx)) {
1670 if (!NamingClass)
1671 NamingClass = Cls;
1672 // When we emulate implicit 'this->' in an unqualified lookup, we might
1673 // end up with an invalid naming class. In that case, we avoid emulating
1674 // 'this->' qualifier to satisfy preconditions of the access checking.
1675 if (NamingClass->getCanonicalDecl() != Cls->getCanonicalDecl() &&
1676 !NamingClass->isDerivedFrom(Cls)) {
1677 NamingClass = Cls;
1678 BaseType = QualType();
1679 }
1680 } else {
1681 // The decl was found outside the C++ class, so only ObjC access checks
1682 // apply. Those do not rely on NamingClass and BaseType, so we clear them
1683 // out.
1684 NamingClass = nullptr;
1685 BaseType = QualType();
1686 }
1687 return Results.getSema().IsSimplyAccessible(ND, NamingClass, BaseType);
1688 }
1689};
1690} // namespace
1691
1692/// Add type specifiers for the current language as keyword results.
1693static void AddTypeSpecifierResults(const LangOptions &LangOpts,
1694 ResultBuilder &Results) {
1695 typedef CodeCompletionResult Result;
1696 Results.AddResult(Result("short", CCP_Type));
1697 Results.AddResult(Result("long", CCP_Type));
1698 Results.AddResult(Result("signed", CCP_Type));
1699 Results.AddResult(Result("unsigned", CCP_Type));
1700 Results.AddResult(Result("void", CCP_Type));
1701 Results.AddResult(Result("char", CCP_Type));
1702 Results.AddResult(Result("int", CCP_Type));
1703 Results.AddResult(Result("float", CCP_Type));
1704 Results.AddResult(Result("double", CCP_Type));
1705 Results.AddResult(Result("enum", CCP_Type));
1706 Results.AddResult(Result("struct", CCP_Type));
1707 Results.AddResult(Result("union", CCP_Type));
1708 Results.AddResult(Result("const", CCP_Type));
1709 Results.AddResult(Result("volatile", CCP_Type));
1710
1711 if (LangOpts.C99) {
1712 // C99-specific
1713 Results.AddResult(Result("_Complex", CCP_Type));
1714 Results.AddResult(Result("_Imaginary", CCP_Type));
1715 Results.AddResult(Result("_Bool", CCP_Type));
1716 Results.AddResult(Result("restrict", CCP_Type));
1717 }
1718
1719 CodeCompletionBuilder Builder(Results.getAllocator(),
1720 Results.getCodeCompletionTUInfo());
1721 if (LangOpts.CPlusPlus) {
1722 // C++-specific
1723 Results.AddResult(
1724 Result("bool", CCP_Type + (LangOpts.ObjC ? CCD_bool_in_ObjC : 0)));
1725 Results.AddResult(Result("class", CCP_Type));
1726 Results.AddResult(Result("wchar_t", CCP_Type));
1727
1728 // typename name
1729 Builder.AddTypedTextChunk("typename");
1730 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1731 Builder.AddPlaceholderChunk("name");
1732 Results.AddResult(Result(Builder.TakeString()));
1733
1734 if (LangOpts.CPlusPlus11) {
1735 Results.AddResult(Result("auto", CCP_Type));
1736 Results.AddResult(Result("char16_t", CCP_Type));
1737 Results.AddResult(Result("char32_t", CCP_Type));
1738
1739 Builder.AddTypedTextChunk("decltype");
1740 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1741 Builder.AddPlaceholderChunk("expression");
1742 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1743 Results.AddResult(Result(Builder.TakeString()));
1744 }
1745 } else
1746 Results.AddResult(Result("__auto_type", CCP_Type));
1747
1748 // GNU keywords
1749 if (LangOpts.GNUKeywords) {
1750 // FIXME: Enable when we actually support decimal floating point.
1751 // Results.AddResult(Result("_Decimal32"));
1752 // Results.AddResult(Result("_Decimal64"));
1753 // Results.AddResult(Result("_Decimal128"));
1754
1755 Builder.AddTypedTextChunk("typeof");
1756 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1757 Builder.AddPlaceholderChunk("expression");
1758 Results.AddResult(Result(Builder.TakeString()));
1759
1760 Builder.AddTypedTextChunk("typeof");
1761 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1762 Builder.AddPlaceholderChunk("type");
1763 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1764 Results.AddResult(Result(Builder.TakeString()));
1765 }
1766
1767 // Nullability
1768 Results.AddResult(Result("_Nonnull", CCP_Type));
1769 Results.AddResult(Result("_Null_unspecified", CCP_Type));
1770 Results.AddResult(Result("_Nullable", CCP_Type));
1771}
1772
1773static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
1774 const LangOptions &LangOpts,
1775 ResultBuilder &Results) {
1776 typedef CodeCompletionResult Result;
1777 // Note: we don't suggest either "auto" or "register", because both
1778 // are pointless as storage specifiers. Elsewhere, we suggest "auto"
1779 // in C++0x as a type specifier.
1780 Results.AddResult(Result("extern"));
1781 Results.AddResult(Result("static"));
1782
1783 if (LangOpts.CPlusPlus11) {
1784 CodeCompletionAllocator &Allocator = Results.getAllocator();
1785 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
1786
1787 // alignas
1788 Builder.AddTypedTextChunk("alignas");
1789 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1790 Builder.AddPlaceholderChunk("expression");
1791 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1792 Results.AddResult(Result(Builder.TakeString()));
1793
1794 Results.AddResult(Result("constexpr"));
1795 Results.AddResult(Result("thread_local"));
1796 }
1797}
1798
1799static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
1800 const LangOptions &LangOpts,
1801 ResultBuilder &Results) {
1802 typedef CodeCompletionResult Result;
1803 switch (CCC) {
1804 case Sema::PCC_Class:
1805 case Sema::PCC_MemberTemplate:
1806 if (LangOpts.CPlusPlus) {
1807 Results.AddResult(Result("explicit"));
1808 Results.AddResult(Result("friend"));
1809 Results.AddResult(Result("mutable"));
1810 Results.AddResult(Result("virtual"));
1811 }
1812 [[fallthrough]];
1813
1814 case Sema::PCC_ObjCInterface:
1815 case Sema::PCC_ObjCImplementation:
1816 case Sema::PCC_Namespace:
1817 case Sema::PCC_Template:
1818 if (LangOpts.CPlusPlus || LangOpts.C99)
1819 Results.AddResult(Result("inline"));
1820 break;
1821
1822 case Sema::PCC_ObjCInstanceVariableList:
1823 case Sema::PCC_Expression:
1824 case Sema::PCC_Statement:
1825 case Sema::PCC_ForInit:
1826 case Sema::PCC_Condition:
1827 case Sema::PCC_RecoveryInFunction:
1828 case Sema::PCC_Type:
1829 case Sema::PCC_ParenthesizedExpression:
1830 case Sema::PCC_LocalDeclarationSpecifiers:
1831 break;
1832 }
1833}
1834
1835static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
1836static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
1837static void AddObjCVisibilityResults(const LangOptions &LangOpts,
1838 ResultBuilder &Results, bool NeedAt);
1839static void AddObjCImplementationResults(const LangOptions &LangOpts,
1840 ResultBuilder &Results, bool NeedAt);
1841static void AddObjCInterfaceResults(const LangOptions &LangOpts,
1842 ResultBuilder &Results, bool NeedAt);
1843static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
1844
1845static void AddTypedefResult(ResultBuilder &Results) {
1846 CodeCompletionBuilder Builder(Results.getAllocator(),
1847 Results.getCodeCompletionTUInfo());
1848 Builder.AddTypedTextChunk("typedef");
1849 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1850 Builder.AddPlaceholderChunk("type");
1851 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1852 Builder.AddPlaceholderChunk("name");
1853 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1854 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1855}
1856
1857// using name = type
1858static void AddUsingAliasResult(CodeCompletionBuilder &Builder,
1859 ResultBuilder &Results) {
1860 Builder.AddTypedTextChunk("using");
1861 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
1862 Builder.AddPlaceholderChunk("name");
1863 Builder.AddChunk(CodeCompletionString::CK_Equal);
1864 Builder.AddPlaceholderChunk("type");
1865 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1866 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1867}
1868
1869static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
1870 const LangOptions &LangOpts) {
1871 switch (CCC) {
1872 case Sema::PCC_Namespace:
1873 case Sema::PCC_Class:
1874 case Sema::PCC_ObjCInstanceVariableList:
1875 case Sema::PCC_Template:
1876 case Sema::PCC_MemberTemplate:
1877 case Sema::PCC_Statement:
1878 case Sema::PCC_RecoveryInFunction:
1879 case Sema::PCC_Type:
1880 case Sema::PCC_ParenthesizedExpression:
1881 case Sema::PCC_LocalDeclarationSpecifiers:
1882 return true;
1883
1884 case Sema::PCC_Expression:
1885 case Sema::PCC_Condition:
1886 return LangOpts.CPlusPlus;
1887
1888 case Sema::PCC_ObjCInterface:
1889 case Sema::PCC_ObjCImplementation:
1890 return false;
1891
1892 case Sema::PCC_ForInit:
1893 return LangOpts.CPlusPlus || LangOpts.ObjC || LangOpts.C99;
1894 }
1895
1896 llvm_unreachable("Invalid ParserCompletionContext!")::llvm::llvm_unreachable_internal("Invalid ParserCompletionContext!"
, "clang/lib/Sema/SemaCodeComplete.cpp", 1896)
;
1897}
1898
1899static PrintingPolicy getCompletionPrintingPolicy(const ASTContext &Context,
1900 const Preprocessor &PP) {
1901 PrintingPolicy Policy = Sema::getPrintingPolicy(Context, PP);
1902 Policy.AnonymousTagLocations = false;
1903 Policy.SuppressStrongLifetime = true;
1904 Policy.SuppressUnwrittenScope = true;
1905 Policy.SuppressScope = true;
1906 Policy.CleanUglifiedParameters = true;
1907 return Policy;
1908}
1909
1910/// Retrieve a printing policy suitable for code completion.
1911static PrintingPolicy getCompletionPrintingPolicy(Sema &S) {
1912 return getCompletionPrintingPolicy(S.Context, S.PP);
1913}
1914
1915/// Retrieve the string representation of the given type as a string
1916/// that has the appropriate lifetime for code completion.
1917///
1918/// This routine provides a fast path where we provide constant strings for
1919/// common type names.
1920static const char *GetCompletionTypeString(QualType T, ASTContext &Context,
1921 const PrintingPolicy &Policy,
1922 CodeCompletionAllocator &Allocator) {
1923 if (!T.getLocalQualifiers()) {
1924 // Built-in type names are constant strings.
1925 if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
1926 return BT->getNameAsCString(Policy);
1927
1928 // Anonymous tag types are constant strings.
1929 if (const TagType *TagT = dyn_cast<TagType>(T))
1930 if (TagDecl *Tag = TagT->getDecl())
1931 if (!Tag->hasNameForLinkage()) {
1932 switch (Tag->getTagKind()) {
1933 case TTK_Struct:
1934 return "struct <anonymous>";
1935 case TTK_Interface:
1936 return "__interface <anonymous>";
1937 case TTK_Class:
1938 return "class <anonymous>";
1939 case TTK_Union:
1940 return "union <anonymous>";
1941 case TTK_Enum:
1942 return "enum <anonymous>";
1943 }
1944 }
1945 }
1946
1947 // Slow path: format the type as a string.
1948 std::string Result;
1949 T.getAsStringInternal(Result, Policy);
1950 return Allocator.CopyString(Result);
1951}
1952
1953/// Add a completion for "this", if we're in a member function.
1954static void addThisCompletion(Sema &S, ResultBuilder &Results) {
1955 QualType ThisTy = S.getCurrentThisType();
1956 if (ThisTy.isNull())
1957 return;
1958
1959 CodeCompletionAllocator &Allocator = Results.getAllocator();
1960 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
1961 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
1962 Builder.AddResultTypeChunk(
1963 GetCompletionTypeString(ThisTy, S.Context, Policy, Allocator));
1964 Builder.AddTypedTextChunk("this");
1965 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1966}
1967
1968static void AddStaticAssertResult(CodeCompletionBuilder &Builder,
1969 ResultBuilder &Results,
1970 const LangOptions &LangOpts) {
1971 if (!LangOpts.CPlusPlus11)
1972 return;
1973
1974 Builder.AddTypedTextChunk("static_assert");
1975 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
1976 Builder.AddPlaceholderChunk("expression");
1977 Builder.AddChunk(CodeCompletionString::CK_Comma);
1978 Builder.AddPlaceholderChunk("message");
1979 Builder.AddChunk(CodeCompletionString::CK_RightParen);
1980 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
1981 Results.AddResult(CodeCompletionResult(Builder.TakeString()));
1982}
1983
1984static void AddOverrideResults(ResultBuilder &Results,
1985 const CodeCompletionContext &CCContext,
1986 CodeCompletionBuilder &Builder) {
1987 Sema &S = Results.getSema();
1988 const auto *CR = llvm::dyn_cast<CXXRecordDecl>(S.CurContext);
1989 // If not inside a class/struct/union return empty.
1990 if (!CR)
1991 return;
1992 // First store overrides within current class.
1993 // These are stored by name to make querying fast in the later step.
1994 llvm::StringMap<std::vector<FunctionDecl *>> Overrides;
1995 for (auto *Method : CR->methods()) {
1996 if (!Method->isVirtual() || !Method->getIdentifier())
1997 continue;
1998 Overrides[Method->getName()].push_back(Method);
1999 }
2000
2001 for (const auto &Base : CR->bases()) {
2002 const auto *BR = Base.getType().getTypePtr()->getAsCXXRecordDecl();
2003 if (!BR)
2004 continue;
2005 for (auto *Method : BR->methods()) {
2006 if (!Method->isVirtual() || !Method->getIdentifier())
2007 continue;
2008 const auto it = Overrides.find(Method->getName());
2009 bool IsOverriden = false;
2010 if (it != Overrides.end()) {
2011 for (auto *MD : it->second) {
2012 // If the method in current body is not an overload of this virtual
2013 // function, then it overrides this one.
2014 if (!S.IsOverload(MD, Method, false)) {
2015 IsOverriden = true;
2016 break;
2017 }
2018 }
2019 }
2020 if (!IsOverriden) {
2021 // Generates a new CodeCompletionResult by taking this function and
2022 // converting it into an override declaration with only one chunk in the
2023 // final CodeCompletionString as a TypedTextChunk.
2024 std::string OverrideSignature;
2025 llvm::raw_string_ostream OS(OverrideSignature);
2026 CodeCompletionResult CCR(Method, 0);
2027 PrintingPolicy Policy =
2028 getCompletionPrintingPolicy(S.getASTContext(), S.getPreprocessor());
2029 auto *CCS = CCR.createCodeCompletionStringForOverride(
2030 S.getPreprocessor(), S.getASTContext(), Builder,
2031 /*IncludeBriefComments=*/false, CCContext, Policy);
2032 Results.AddResult(CodeCompletionResult(CCS, Method, CCP_CodePattern));
2033 }
2034 }
2035 }
2036}
2037
2038/// Add language constructs that show up for "ordinary" names.
2039static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC, Scope *S,
2040 Sema &SemaRef, ResultBuilder &Results) {
2041 CodeCompletionAllocator &Allocator = Results.getAllocator();
2042 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
2043
2044 typedef CodeCompletionResult Result;
2045 switch (CCC) {
2046 case Sema::PCC_Namespace:
2047 if (SemaRef.getLangOpts().CPlusPlus) {
2048 if (Results.includeCodePatterns()) {
2049 // namespace <identifier> { declarations }
2050 Builder.AddTypedTextChunk("namespace");
2051 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2052 Builder.AddPlaceholderChunk("identifier");
2053 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2054 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2055 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2056 Builder.AddPlaceholderChunk("declarations");
2057 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2058 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2059 Results.AddResult(Result(Builder.TakeString()));
2060 }
2061
2062 // namespace identifier = identifier ;
2063 Builder.AddTypedTextChunk("namespace");
2064 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2065 Builder.AddPlaceholderChunk("name");
2066 Builder.AddChunk(CodeCompletionString::CK_Equal);
2067 Builder.AddPlaceholderChunk("namespace");
2068 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2069 Results.AddResult(Result(Builder.TakeString()));
2070
2071 // Using directives
2072 Builder.AddTypedTextChunk("using namespace");
2073 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2074 Builder.AddPlaceholderChunk("identifier");
2075 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2076 Results.AddResult(Result(Builder.TakeString()));
2077
2078 // asm(string-literal)
2079 Builder.AddTypedTextChunk("asm");
2080 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2081 Builder.AddPlaceholderChunk("string-literal");
2082 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2083 Results.AddResult(Result(Builder.TakeString()));
2084
2085 if (Results.includeCodePatterns()) {
2086 // Explicit template instantiation
2087 Builder.AddTypedTextChunk("template");
2088 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2089 Builder.AddPlaceholderChunk("declaration");
2090 Results.AddResult(Result(Builder.TakeString()));
2091 } else {
2092 Results.AddResult(Result("template", CodeCompletionResult::RK_Keyword));
2093 }
2094 }
2095
2096 if (SemaRef.getLangOpts().ObjC)
2097 AddObjCTopLevelResults(Results, true);
2098
2099 AddTypedefResult(Results);
2100 [[fallthrough]];
2101
2102 case Sema::PCC_Class:
2103 if (SemaRef.getLangOpts().CPlusPlus) {
2104 // Using declaration
2105 Builder.AddTypedTextChunk("using");
2106 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2107 Builder.AddPlaceholderChunk("qualifier");
2108 Builder.AddTextChunk("::");
2109 Builder.AddPlaceholderChunk("name");
2110 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2111 Results.AddResult(Result(Builder.TakeString()));
2112
2113 if (SemaRef.getLangOpts().CPlusPlus11)
2114 AddUsingAliasResult(Builder, Results);
2115
2116 // using typename qualifier::name (only in a dependent context)
2117 if (SemaRef.CurContext->isDependentContext()) {
2118 Builder.AddTypedTextChunk("using typename");
2119 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2120 Builder.AddPlaceholderChunk("qualifier");
2121 Builder.AddTextChunk("::");
2122 Builder.AddPlaceholderChunk("name");
2123 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2124 Results.AddResult(Result(Builder.TakeString()));
2125 }
2126
2127 AddStaticAssertResult(Builder, Results, SemaRef.getLangOpts());
2128
2129 if (CCC == Sema::PCC_Class) {
2130 AddTypedefResult(Results);
2131
2132 bool IsNotInheritanceScope = !S->isClassInheritanceScope();
2133 // public:
2134 Builder.AddTypedTextChunk("public");
2135 if (IsNotInheritanceScope && Results.includeCodePatterns())
2136 Builder.AddChunk(CodeCompletionString::CK_Colon);
2137 Results.AddResult(Result(Builder.TakeString()));
2138
2139 // protected:
2140 Builder.AddTypedTextChunk("protected");
2141 if (IsNotInheritanceScope && Results.includeCodePatterns())
2142 Builder.AddChunk(CodeCompletionString::CK_Colon);
2143 Results.AddResult(Result(Builder.TakeString()));
2144
2145 // private:
2146 Builder.AddTypedTextChunk("private");
2147 if (IsNotInheritanceScope && Results.includeCodePatterns())
2148 Builder.AddChunk(CodeCompletionString::CK_Colon);
2149 Results.AddResult(Result(Builder.TakeString()));
2150
2151 // FIXME: This adds override results only if we are at the first word of
2152 // the declaration/definition. Also call this from other sides to have
2153 // more use-cases.
2154 AddOverrideResults(Results, CodeCompletionContext::CCC_ClassStructUnion,
2155 Builder);
2156 }
2157 }
2158 [[fallthrough]];
2159
2160 case Sema::PCC_Template:
2161 case Sema::PCC_MemberTemplate:
2162 if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns()) {
2163 // template < parameters >
2164 Builder.AddTypedTextChunk("template");
2165 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2166 Builder.AddPlaceholderChunk("parameters");
2167 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2168 Results.AddResult(Result(Builder.TakeString()));
2169 } else {
2170 Results.AddResult(Result("template", CodeCompletionResult::RK_Keyword));
2171 }
2172
2173 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2174 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2175 break;
2176
2177 case Sema::PCC_ObjCInterface:
2178 AddObjCInterfaceResults(SemaRef.getLangOpts(), Results, true);
2179 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2180 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2181 break;
2182
2183 case Sema::PCC_ObjCImplementation:
2184 AddObjCImplementationResults(SemaRef.getLangOpts(), Results, true);
2185 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2186 AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2187 break;
2188
2189 case Sema::PCC_ObjCInstanceVariableList:
2190 AddObjCVisibilityResults(SemaRef.getLangOpts(), Results, true);
2191 break;
2192
2193 case Sema::PCC_RecoveryInFunction:
2194 case Sema::PCC_Statement: {
2195 if (SemaRef.getLangOpts().CPlusPlus11)
2196 AddUsingAliasResult(Builder, Results);
2197
2198 AddTypedefResult(Results);
2199
2200 if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns() &&
2201 SemaRef.getLangOpts().CXXExceptions) {
2202 Builder.AddTypedTextChunk("try");
2203 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2204 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2205 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2206 Builder.AddPlaceholderChunk("statements");
2207 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2208 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2209 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2210 Builder.AddTextChunk("catch");
2211 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2212 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2213 Builder.AddPlaceholderChunk("declaration");
2214 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2215 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2216 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2217 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2218 Builder.AddPlaceholderChunk("statements");
2219 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2220 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2221 Results.AddResult(Result(Builder.TakeString()));
2222 }
2223 if (SemaRef.getLangOpts().ObjC)
2224 AddObjCStatementResults(Results, true);
2225
2226 if (Results.includeCodePatterns()) {
2227 // if (condition) { statements }
2228 Builder.AddTypedTextChunk("if");
2229 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2230 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2231 if (SemaRef.getLangOpts().CPlusPlus)
2232 Builder.AddPlaceholderChunk("condition");
2233 else
2234 Builder.AddPlaceholderChunk("expression");
2235 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2236 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2237 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2238 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2239 Builder.AddPlaceholderChunk("statements");
2240 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2241 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2242 Results.AddResult(Result(Builder.TakeString()));
2243
2244 // switch (condition) { }
2245 Builder.AddTypedTextChunk("switch");
2246 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2247 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2248 if (SemaRef.getLangOpts().CPlusPlus)
2249 Builder.AddPlaceholderChunk("condition");
2250 else
2251 Builder.AddPlaceholderChunk("expression");
2252 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2253 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2254 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2255 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2256 Builder.AddPlaceholderChunk("cases");
2257 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2258 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2259 Results.AddResult(Result(Builder.TakeString()));
2260 }
2261
2262 // Switch-specific statements.
2263 if (SemaRef.getCurFunction() &&
2264 !SemaRef.getCurFunction()->SwitchStack.empty()) {
2265 // case expression:
2266 Builder.AddTypedTextChunk("case");
2267 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2268 Builder.AddPlaceholderChunk("expression");
2269 Builder.AddChunk(CodeCompletionString::CK_Colon);
2270 Results.AddResult(Result(Builder.TakeString()));
2271
2272 // default:
2273 Builder.AddTypedTextChunk("default");
2274 Builder.AddChunk(CodeCompletionString::CK_Colon);
2275 Results.AddResult(Result(Builder.TakeString()));
2276 }
2277
2278 if (Results.includeCodePatterns()) {
2279 /// while (condition) { statements }
2280 Builder.AddTypedTextChunk("while");
2281 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2282 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2283 if (SemaRef.getLangOpts().CPlusPlus)
2284 Builder.AddPlaceholderChunk("condition");
2285 else
2286 Builder.AddPlaceholderChunk("expression");
2287 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2288 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2289 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2290 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2291 Builder.AddPlaceholderChunk("statements");
2292 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2293 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2294 Results.AddResult(Result(Builder.TakeString()));
2295
2296 // do { statements } while ( expression );
2297 Builder.AddTypedTextChunk("do");
2298 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2299 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2300 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2301 Builder.AddPlaceholderChunk("statements");
2302 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2303 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2304 Builder.AddTextChunk("while");
2305 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2306 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2307 Builder.AddPlaceholderChunk("expression");
2308 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2309 Results.AddResult(Result(Builder.TakeString()));
2310
2311 // for ( for-init-statement ; condition ; expression ) { statements }
2312 Builder.AddTypedTextChunk("for");
2313 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2314 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2315 if (SemaRef.getLangOpts().CPlusPlus || SemaRef.getLangOpts().C99)
2316 Builder.AddPlaceholderChunk("init-statement");
2317 else
2318 Builder.AddPlaceholderChunk("init-expression");
2319 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2320 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2321 Builder.AddPlaceholderChunk("condition");
2322 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2323 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2324 Builder.AddPlaceholderChunk("inc-expression");
2325 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2326 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2327 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2328 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2329 Builder.AddPlaceholderChunk("statements");
2330 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2331 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2332 Results.AddResult(Result(Builder.TakeString()));
2333
2334 if (SemaRef.getLangOpts().CPlusPlus11 || SemaRef.getLangOpts().ObjC) {
2335 // for ( range_declaration (:|in) range_expression ) { statements }
2336 Builder.AddTypedTextChunk("for");
2337 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2338 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2339 Builder.AddPlaceholderChunk("range-declaration");
2340 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2341 if (SemaRef.getLangOpts().ObjC)
2342 Builder.AddTextChunk("in");
2343 else
2344 Builder.AddChunk(CodeCompletionString::CK_Colon);
2345 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2346 Builder.AddPlaceholderChunk("range-expression");
2347 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2348 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2349 Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
2350 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2351 Builder.AddPlaceholderChunk("statements");
2352 Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
2353 Builder.AddChunk(CodeCompletionString::CK_RightBrace);
2354 Results.AddResult(Result(Builder.TakeString()));
2355 }
2356 }
2357
2358 if (S->getContinueParent()) {
2359 // continue ;
2360 Builder.AddTypedTextChunk("continue");
2361 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2362 Results.AddResult(Result(Builder.TakeString()));
2363 }
2364
2365 if (S->getBreakParent()) {
2366 // break ;
2367 Builder.AddTypedTextChunk("break");
2368 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2369 Results.AddResult(Result(Builder.TakeString()));
2370 }
2371
2372 // "return expression ;" or "return ;", depending on the return type.
2373 QualType ReturnType;
2374 if (const auto *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
2375 ReturnType = Function->getReturnType();
2376 else if (const auto *Method = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
2377 ReturnType = Method->getReturnType();
2378 else if (SemaRef.getCurBlock() &&
2379 !SemaRef.getCurBlock()->ReturnType.isNull())
2380 ReturnType = SemaRef.getCurBlock()->ReturnType;;
2381 if (ReturnType.isNull() || ReturnType->isVoidType()) {
2382 Builder.AddTypedTextChunk("return");
2383 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2384 Results.AddResult(Result(Builder.TakeString()));
2385 } else {
2386 assert(!ReturnType.isNull())(static_cast <bool> (!ReturnType.isNull()) ? void (0) :
__assert_fail ("!ReturnType.isNull()", "clang/lib/Sema/SemaCodeComplete.cpp"
, 2386, __extension__ __PRETTY_FUNCTION__))
;
2387 // "return expression ;"
2388 Builder.AddTypedTextChunk("return");
2389 Builder.AddChunk(clang::CodeCompletionString::CK_HorizontalSpace);
2390 Builder.AddPlaceholderChunk("expression");
2391 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2392 Results.AddResult(Result(Builder.TakeString()));
2393 // When boolean, also add 'return true;' and 'return false;'.
2394 if (ReturnType->isBooleanType()) {
2395 Builder.AddTypedTextChunk("return true");
2396 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2397 Results.AddResult(Result(Builder.TakeString()));
2398
2399 Builder.AddTypedTextChunk("return false");
2400 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2401 Results.AddResult(Result(Builder.TakeString()));
2402 }
2403 // For pointers, suggest 'return nullptr' in C++.
2404 if (SemaRef.getLangOpts().CPlusPlus11 &&
2405 (ReturnType->isPointerType() || ReturnType->isMemberPointerType())) {
2406 Builder.AddTypedTextChunk("return nullptr");
2407 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2408 Results.AddResult(Result(Builder.TakeString()));
2409 }
2410 }
2411
2412 // goto identifier ;
2413 Builder.AddTypedTextChunk("goto");
2414 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2415 Builder.AddPlaceholderChunk("label");
2416 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2417 Results.AddResult(Result(Builder.TakeString()));
2418
2419 // Using directives
2420 Builder.AddTypedTextChunk("using namespace");
2421 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2422 Builder.AddPlaceholderChunk("identifier");
2423 Builder.AddChunk(CodeCompletionString::CK_SemiColon);
2424 Results.AddResult(Result(Builder.TakeString()));
2425
2426 AddStaticAssertResult(Builder, Results, SemaRef.getLangOpts());
2427 }
2428 [[fallthrough]];
2429
2430 // Fall through (for statement expressions).
2431 case Sema::PCC_ForInit:
2432 case Sema::PCC_Condition:
2433 AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
2434 // Fall through: conditions and statements can have expressions.
2435 [[fallthrough]];
2436
2437 case Sema::PCC_ParenthesizedExpression:
2438 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
2439 CCC == Sema::PCC_ParenthesizedExpression) {
2440 // (__bridge <type>)<expression>
2441 Builder.AddTypedTextChunk("__bridge");
2442 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2443 Builder.AddPlaceholderChunk("type");
2444 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2445 Builder.AddPlaceholderChunk("expression");
2446 Results.AddResult(Result(Builder.TakeString()));
2447
2448 // (__bridge_transfer <Objective-C type>)<expression>
2449 Builder.AddTypedTextChunk("__bridge_transfer");
2450 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2451 Builder.AddPlaceholderChunk("Objective-C type");
2452 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2453 Builder.AddPlaceholderChunk("expression");
2454 Results.AddResult(Result(Builder.TakeString()));
2455
2456 // (__bridge_retained <CF type>)<expression>
2457 Builder.AddTypedTextChunk("__bridge_retained");
2458 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2459 Builder.AddPlaceholderChunk("CF type");
2460 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2461 Builder.AddPlaceholderChunk("expression");
2462 Results.AddResult(Result(Builder.TakeString()));
2463 }
2464 // Fall through
2465 [[fallthrough]];
2466
2467 case Sema::PCC_Expression: {
2468 if (SemaRef.getLangOpts().CPlusPlus) {
2469 // 'this', if we're in a non-static member function.
2470 addThisCompletion(SemaRef, Results);
2471
2472 // true
2473 Builder.AddResultTypeChunk("bool");
2474 Builder.AddTypedTextChunk("true");
2475 Results.AddResult(Result(Builder.TakeString()));
2476
2477 // false
2478 Builder.AddResultTypeChunk("bool");
2479 Builder.AddTypedTextChunk("false");
2480 Results.AddResult(Result(Builder.TakeString()));
2481
2482 if (SemaRef.getLangOpts().RTTI) {
2483 // dynamic_cast < type-id > ( expression )
2484 Builder.AddTypedTextChunk("dynamic_cast");
2485 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2486 Builder.AddPlaceholderChunk("type");
2487 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2488 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2489 Builder.AddPlaceholderChunk("expression");
2490 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2491 Results.AddResult(Result(Builder.TakeString()));
2492 }
2493
2494 // static_cast < type-id > ( expression )
2495 Builder.AddTypedTextChunk("static_cast");
2496 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2497 Builder.AddPlaceholderChunk("type");
2498 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2499 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2500 Builder.AddPlaceholderChunk("expression");
2501 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2502 Results.AddResult(Result(Builder.TakeString()));
2503
2504 // reinterpret_cast < type-id > ( expression )
2505 Builder.AddTypedTextChunk("reinterpret_cast");
2506 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2507 Builder.AddPlaceholderChunk("type");
2508 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2509 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2510 Builder.AddPlaceholderChunk("expression");
2511 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2512 Results.AddResult(Result(Builder.TakeString()));
2513
2514 // const_cast < type-id > ( expression )
2515 Builder.AddTypedTextChunk("const_cast");
2516 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
2517 Builder.AddPlaceholderChunk("type");
2518 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
2519 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2520 Builder.AddPlaceholderChunk("expression");
2521 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2522 Results.AddResult(Result(Builder.TakeString()));
2523
2524 if (SemaRef.getLangOpts().RTTI) {
2525 // typeid ( expression-or-type )
2526 Builder.AddResultTypeChunk("std::type_info");
2527 Builder.AddTypedTextChunk("typeid");
2528 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2529 Builder.AddPlaceholderChunk("expression-or-type");
2530 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2531 Results.AddResult(Result(Builder.TakeString()));
2532 }
2533
2534 // new T ( ... )
2535 Builder.AddTypedTextChunk("new");
2536 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2537 Builder.AddPlaceholderChunk("type");
2538 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2539 Builder.AddPlaceholderChunk("expressions");
2540 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2541 Results.AddResult(Result(Builder.TakeString()));
2542
2543 // new T [ ] ( ... )
2544 Builder.AddTypedTextChunk("new");
2545 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2546 Builder.AddPlaceholderChunk("type");
2547 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
2548 Builder.AddPlaceholderChunk("size");
2549 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
2550 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2551 Builder.AddPlaceholderChunk("expressions");
2552 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2553 Results.AddResult(Result(Builder.TakeString()));
2554
2555 // delete expression
2556 Builder.AddResultTypeChunk("void");
2557 Builder.AddTypedTextChunk("delete");
2558 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2559 Builder.AddPlaceholderChunk("expression");
2560 Results.AddResult(Result(Builder.TakeString()));
2561
2562 // delete [] expression
2563 Builder.AddResultTypeChunk("void");
2564 Builder.AddTypedTextChunk("delete");
2565 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2566 Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
2567 Builder.AddChunk(CodeCompletionString::CK_RightBracket);
2568 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2569 Builder.AddPlaceholderChunk("expression");
2570 Results.AddResult(Result(Builder.TakeString()));
2571
2572 if (SemaRef.getLangOpts().CXXExceptions) {
2573 // throw expression
2574 Builder.AddResultTypeChunk("void");
2575 Builder.AddTypedTextChunk("throw");
2576 Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
2577 Builder.AddPlaceholderChunk("expression");
2578 Results.AddResult(Result(Builder.TakeString()));
2579 }
2580
2581 // FIXME: Rethrow?
2582
2583 if (SemaRef.getLangOpts().CPlusPlus11) {
2584 // nullptr
2585 Builder.AddResultTypeChunk("std::nullptr_t");
2586 Builder.AddTypedTextChunk("nullptr");
2587 Results.AddResult(Result(Builder.TakeString()));
2588
2589 // alignof
2590 Builder.AddResultTypeChunk("size_t");
2591 Builder.AddTypedTextChunk("alignof");
2592 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2593 Builder.AddPlaceholderChunk("type");
2594 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2595 Results.AddResult(Result(Builder.TakeString()));
2596
2597 // noexcept
2598 Builder.AddResultTypeChunk("bool");
2599 Builder.AddTypedTextChunk("noexcept");
2600 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2601 Builder.AddPlaceholderChunk("expression");
2602 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2603 Results.AddResult(Result(Builder.TakeString()));
2604
2605 // sizeof... expression
2606 Builder.AddResultTypeChunk("size_t");
2607 Builder.AddTypedTextChunk("sizeof...");
2608 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2609 Builder.AddPlaceholderChunk("parameter-pack");
2610 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2611 Results.AddResult(Result(Builder.TakeString()));
2612 }
2613 }
2614
2615 if (SemaRef.getLangOpts().ObjC) {
2616 // Add "super", if we're in an Objective-C class with a superclass.
2617 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
2618 // The interface can be NULL.
2619 if (ObjCInterfaceDecl *ID = Method->getClassInterface())
2620 if (ID->getSuperClass()) {
2621 std::string SuperType;
2622 SuperType = ID->getSuperClass()->getNameAsString();
2623 if (Method->isInstanceMethod())
2624 SuperType += " *";
2625
2626 Builder.AddResultTypeChunk(Allocator.CopyString(SuperType));
2627 Builder.AddTypedTextChunk("super");
2628 Results.AddResult(Result(Builder.TakeString()));
2629 }
2630 }
2631
2632 AddObjCExpressionResults(Results, true);
2633 }
2634
2635 if (SemaRef.getLangOpts().C11) {
2636 // _Alignof
2637 Builder.AddResultTypeChunk("size_t");
2638 if (SemaRef.PP.isMacroDefined("alignof"))
2639 Builder.AddTypedTextChunk("alignof");
2640 else
2641 Builder.AddTypedTextChunk("_Alignof");
2642 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2643 Builder.AddPlaceholderChunk("type");
2644 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2645 Results.AddResult(Result(Builder.TakeString()));
2646 }
2647
2648 // sizeof expression
2649 Builder.AddResultTypeChunk("size_t");
2650 Builder.AddTypedTextChunk("sizeof");
2651 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
2652 Builder.AddPlaceholderChunk("expression-or-type");
2653 Builder.AddChunk(CodeCompletionString::CK_RightParen);
2654 Results.AddResult(Result(Builder.TakeString()));
2655 break;
2656 }
2657
2658 case Sema::PCC_Type:
2659 case Sema::PCC_LocalDeclarationSpecifiers:
2660 break;
2661 }
2662
2663 if (WantTypesInContext(CCC, SemaRef.getLangOpts()))
2664 AddTypeSpecifierResults(SemaRef.getLangOpts(), Results);
2665
2666 if (SemaRef.getLangOpts().CPlusPlus && CCC != Sema::PCC_Type)
2667 Results.AddResult(Result("operator"));
2668}
2669
2670/// If the given declaration has an associated type, add it as a result
2671/// type chunk.
2672static void AddResultTypeChunk(ASTContext &Context,
2673 const PrintingPolicy &Policy,
2674 const NamedDecl *ND, QualType BaseType,
2675 CodeCompletionBuilder &Result) {
2676 if (!ND)
2677 return;
2678
2679 // Skip constructors and conversion functions, which have their return types
2680 // built into their names.
2681 if (isConstructor(ND) || isa<CXXConversionDecl>(ND))
2682 return;
2683
2684 // Determine the type of the declaration (if it has a type).
2685 QualType T;
2686 if (const FunctionDecl *Function = ND->getAsFunction())
2687 T = Function->getReturnType();
2688 else if (const auto *Method = dyn_cast<ObjCMethodDecl>(ND)) {
2689 if (!BaseType.isNull())
2690 T = Method->getSendResultType(BaseType);
2691 else
2692 T = Method->getReturnType();
2693 } else if (const auto *Enumerator = dyn_cast<EnumConstantDecl>(ND)) {
2694 T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
2695 T = clang::TypeName::getFullyQualifiedType(T, Context);
2696 } else if (isa<UnresolvedUsingValueDecl>(ND)) {
2697 /* Do nothing: ignore unresolved using declarations*/
2698 } else if (const auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
2699 if (!BaseType.isNull())
2700 T = Ivar->getUsageType(BaseType);
2701 else
2702 T = Ivar->getType();
2703 } else if (const auto *Value = dyn_cast<ValueDecl>(ND)) {
2704 T = Value->getType();
2705 } else if (const auto *Property = dyn_cast<ObjCPropertyDecl>(ND)) {
2706 if (!BaseType.isNull())
2707 T = Property->getUsageType(BaseType);
2708 else
2709 T = Property->getType();
2710 }
2711
2712 if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
2713 return;
2714
2715 Result.AddResultTypeChunk(
2716 GetCompletionTypeString(T, Context, Policy, Result.getAllocator()));
2717}
2718
2719static void MaybeAddSentinel(Preprocessor &PP,
2720 const NamedDecl *FunctionOrMethod,
2721 CodeCompletionBuilder &Result) {
2722 if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
2723 if (Sentinel->getSentinel() == 0) {
2724 if (PP.getLangOpts().ObjC && PP.isMacroDefined("nil"))
2725 Result.AddTextChunk(", nil");
2726 else if (PP.isMacroDefined("NULL"))
2727 Result.AddTextChunk(", NULL");
2728 else
2729 Result.AddTextChunk(", (void*)0");
2730 }
2731}
2732
2733static std::string formatObjCParamQualifiers(unsigned ObjCQuals,
2734 QualType &Type) {
2735 std::string Result;
2736 if (ObjCQuals & Decl::OBJC_TQ_In)
2737 Result += "in ";
2738 else if (ObjCQuals & Decl::OBJC_TQ_Inout)
2739 Result += "inout ";
2740 else if (ObjCQuals & Decl::OBJC_TQ_Out)
2741 Result += "out ";
2742 if (ObjCQuals & Decl::OBJC_TQ_Bycopy)
2743 Result += "bycopy ";
2744 else if (ObjCQuals & Decl::OBJC_TQ_Byref)
2745 Result += "byref ";
2746 if (ObjCQuals & Decl::OBJC_TQ_Oneway)
2747 Result += "oneway ";
2748 if (ObjCQuals & Decl::OBJC_TQ_CSNullability) {
2749 if (auto nullability = AttributedType::stripOuterNullability(Type)) {
2750 switch (*nullability) {
2751 case NullabilityKind::NonNull:
2752 Result += "nonnull ";
2753 break;
2754
2755 case NullabilityKind::Nullable:
2756 Result += "nullable ";
2757 break;
2758
2759 case NullabilityKind::Unspecified:
2760 Result += "null_unspecified ";
2761 break;
2762
2763 case NullabilityKind::NullableResult:
2764 llvm_unreachable("Not supported as a context-sensitive keyword!")::llvm::llvm_unreachable_internal("Not supported as a context-sensitive keyword!"
, "clang/lib/Sema/SemaCodeComplete.cpp", 2764)
;
2765 break;
2766 }
2767 }
2768 }
2769 return Result;
2770}
2771
2772/// Tries to find the most appropriate type location for an Objective-C
2773/// block placeholder.
2774///
2775/// This function ignores things like typedefs and qualifiers in order to
2776/// present the most relevant and accurate block placeholders in code completion
2777/// results.
2778static void findTypeLocationForBlockDecl(const TypeSourceInfo *TSInfo,
2779 FunctionTypeLoc &Block,
2780 FunctionProtoTypeLoc &BlockProto,
2781 bool SuppressBlock = false) {
2782 if (!TSInfo)
2783 return;
2784 TypeLoc TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
2785 while (true) {
2786 // Look through typedefs.
2787 if (!SuppressBlock) {
2788 if (TypedefTypeLoc TypedefTL = TL.getAsAdjusted<TypedefTypeLoc>()) {
2789 if (TypeSourceInfo *InnerTSInfo =
2790 TypedefTL.getTypedefNameDecl()->getTypeSourceInfo()) {
2791 TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
2792 continue;
2793 }
2794 }
2795
2796 // Look through qualified types
2797 if (QualifiedTypeLoc QualifiedTL = TL.getAs<QualifiedTypeLoc>()) {
2798 TL = QualifiedTL.getUnqualifiedLoc();
2799 continue;
2800 }
2801
2802 if (AttributedTypeLoc AttrTL = TL.getAs<AttributedTypeLoc>()) {
2803 TL = AttrTL.getModifiedLoc();
2804 continue;
2805 }
2806 }
2807
2808 // Try to get the function prototype behind the block pointer type,
2809 // then we're done.
2810 if (BlockPointerTypeLoc BlockPtr = TL.getAs<BlockPointerTypeLoc>()) {
2811 TL = BlockPtr.getPointeeLoc().IgnoreParens();
2812 Block = TL.getAs<FunctionTypeLoc>();
2813 BlockProto = TL.getAs<FunctionProtoTypeLoc>();
2814 }
2815 break;
2816 }
2817}
2818
2819static std::string
2820formatBlockPlaceholder(const PrintingPolicy &Policy, const NamedDecl *BlockDecl,
2821 FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto,
2822 bool SuppressBlockName = false,
2823 bool SuppressBlock = false,
2824 Optional<ArrayRef<QualType>> ObjCSubsts = None);
2825
2826static std::string
2827FormatFunctionParameter(const PrintingPolicy &Policy,
2828 const DeclaratorDecl *Param, bool SuppressName = false,
2829 bool SuppressBlock = false,
2830 Optional<ArrayRef<QualType>> ObjCSubsts = None) {
2831 // Params are unavailable in FunctionTypeLoc if the FunctionType is invalid.
2832 // It would be better to pass in the param Type, which is usually available.
2833 // But this case is rare, so just pretend we fell back to int as elsewhere.
2834 if (!Param)
2835 return "int";
2836 Decl::ObjCDeclQualifier ObjCQual = Decl::OBJC_TQ_None;
2837 if (const auto *PVD = dyn_cast<ParmVarDecl>(Param))
2838 ObjCQual = PVD->getObjCDeclQualifier();
2839 bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
2840 if (Param->getType()->isDependentType() ||
2841 !Param->getType()->isBlockPointerType()) {
2842 // The argument for a dependent or non-block parameter is a placeholder
2843 // containing that parameter's type.
2844 std::string Result;
2845
2846 if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
2847 Result = std::string(Param->getIdentifier()->deuglifiedName());
2848
2849 QualType Type = Param->getType();
2850 if (ObjCSubsts)
2851 Type = Type.substObjCTypeArgs(Param->getASTContext(), *ObjCSubsts,
2852 ObjCSubstitutionContext::Parameter);
2853 if (ObjCMethodParam) {
2854 Result = "(" + formatObjCParamQualifiers(ObjCQual, Type);
2855 Result += Type.getAsString(Policy) + ")";
2856 if (Param->getIdentifier() && !SuppressName)
2857 Result += Param->getIdentifier()->deuglifiedName();
2858 } else {
2859 Type.getAsStringInternal(Result, Policy);
2860 }
2861 return Result;
2862 }
2863
2864 // The argument for a block pointer parameter is a block literal with
2865 // the appropriate type.
2866 FunctionTypeLoc Block;
2867 FunctionProtoTypeLoc BlockProto;
2868 findTypeLocationForBlockDecl(Param->getTypeSourceInfo(), Block, BlockProto,
2869 SuppressBlock);
2870 // Try to retrieve the block type information from the property if this is a
2871 // parameter in a setter.
2872 if (!Block && ObjCMethodParam &&
2873 cast<ObjCMethodDecl>(Param->getDeclContext())->isPropertyAccessor()) {
2874 if (const auto *PD = cast<ObjCMethodDecl>(Param->getDeclContext())
2875 ->findPropertyDecl(/*CheckOverrides=*/false))
2876 findTypeLocationForBlockDecl(PD->getTypeSourceInfo(), Block, BlockProto,
2877 SuppressBlock);
2878 }
2879
2880 if (!Block) {
2881 // We were unable to find a FunctionProtoTypeLoc with parameter names
2882 // for the block; just use the parameter type as a placeholder.
2883 std::string Result;
2884 if (!ObjCMethodParam && Param->getIdentifier())
2885 Result = std::string(Param->getIdentifier()->deuglifiedName());
2886
2887 QualType Type = Param->getType().getUnqualifiedType();
2888
2889 if (ObjCMethodParam) {
2890 Result = Type.getAsString(Policy);
2891 std::string Quals = formatObjCParamQualifiers(ObjCQual, Type);
2892 if (!Quals.empty())
2893 Result = "(" + Quals + " " + Result + ")";
2894 if (Result.back() != ')')
2895 Result += " ";
2896 if (Param->getIdentifier())
2897 Result += Param->getIdentifier()->deuglifiedName();
2898 } else {
2899 Type.getAsStringInternal(Result, Policy);
2900 }
2901
2902 return Result;
2903 }
2904
2905 // We have the function prototype behind the block pointer type, as it was
2906 // written in the source.
2907 return formatBlockPlaceholder(Policy, Param, Block, BlockProto,
2908 /*SuppressBlockName=*/false, SuppressBlock,
2909 ObjCSubsts);
2910}
2911
2912/// Returns a placeholder string that corresponds to an Objective-C block
2913/// declaration.
2914///
2915/// \param BlockDecl A declaration with an Objective-C block type.
2916///
2917/// \param Block The most relevant type location for that block type.
2918///
2919/// \param SuppressBlockName Determines whether or not the name of the block
2920/// declaration is included in the resulting string.
2921static std::string
2922formatBlockPlaceholder(const PrintingPolicy &Policy, const NamedDecl *BlockDecl,
2923 FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto,
2924 bool SuppressBlockName, bool SuppressBlock,
2925 Optional<ArrayRef<QualType>> ObjCSubsts) {
2926 std::string Result;
2927 QualType ResultType = Block.getTypePtr()->getReturnType();
2928 if (ObjCSubsts)
2929 ResultType =
2930 ResultType.substObjCTypeArgs(BlockDecl->getASTContext(), *ObjCSubsts,
2931 ObjCSubstitutionContext::Result);
2932 if (!ResultType->isVoidType() || SuppressBlock)
2933 ResultType.getAsStringInternal(Result, Policy);
2934
2935 // Format the parameter list.
2936 std::string Params;
2937 if (!BlockProto || Block.getNumParams() == 0) {
2938 if (BlockProto && BlockProto.getTypePtr()->isVariadic())
2939 Params = "(...)";
2940 else
2941 Params = "(void)";
2942 } else {
2943 Params += "(";
2944 for (unsigned I = 0, N = Block.getNumParams(); I != N; ++I) {
2945 if (I)
2946 Params += ", ";
2947 Params += FormatFunctionParameter(Policy, Block.getParam(I),
2948 /*SuppressName=*/false,
2949 /*SuppressBlock=*/true, ObjCSubsts);
2950
2951 if (I == N - 1 && BlockProto.getTypePtr()->isVariadic())
2952 Params += ", ...";
2953 }
2954 Params += ")";
2955 }
2956
2957 if (SuppressBlock) {
2958 // Format as a parameter.
2959 Result = Result + " (^";
2960 if (!SuppressBlockName && BlockDecl->getIdentifier())
2961 Result += BlockDecl->getIdentifier()->getName();
2962 Result += ")";
2963 Result += Params;
2964 } else {
2965 // Format as a block literal argument.
2966 Result = '^' + Result;
2967 Result += Params;
2968
2969 if (!SuppressBlockName && BlockDecl->getIdentifier())
2970 Result += BlockDecl->getIdentifier()->getName();
2971 }
2972
2973 return Result;
2974}
2975
2976static std::string GetDefaultValueString(const ParmVarDecl *Param,
2977 const SourceManager &SM,
2978 const LangOptions &LangOpts) {
2979 const SourceRange SrcRange = Param->getDefaultArgRange();
2980 CharSourceRange CharSrcRange = CharSourceRange::getTokenRange(SrcRange);
2981 bool Invalid = CharSrcRange.isInvalid();
2982 if (Invalid)
2983 return "";
2984 StringRef srcText =
2985 Lexer::getSourceText(CharSrcRange, SM, LangOpts, &Invalid);
2986 if (Invalid)
2987 return "";
2988
2989 if (srcText.empty() || srcText == "=") {
2990 // Lexer can't determine the value.
2991 // This happens if the code is incorrect (for example class is forward
2992 // declared).
2993 return "";
2994 }
2995 std::string DefValue(srcText.str());
2996 // FIXME: remove this check if the Lexer::getSourceText value is fixed and
2997 // this value always has (or always does not have) '=' in front of it
2998 if (DefValue.at(0) != '=') {
2999 // If we don't have '=' in front of value.
3000 // Lexer returns built-in types values without '=' and user-defined types
3001 // values with it.
3002 return " = " + DefValue;
3003 }
3004 return " " + DefValue;
3005}
3006
3007/// Add function parameter chunks to the given code completion string.
3008static void AddFunctionParameterChunks(Preprocessor &PP,
3009 const PrintingPolicy &Policy,
3010 const FunctionDecl *Function,
3011 CodeCompletionBuilder &Result,
3012 unsigned Start = 0,
3013 bool InOptional = false) {
3014 bool FirstParameter = true;
3015
3016 for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
3017 const ParmVarDecl *Param = Function->getParamDecl(P);
3018
3019 if (Param->hasDefaultArg() && !InOptional) {
3020 // When we see an optional default argument, put that argument and
3021 // the remaining default arguments into a new, optional string.
3022 CodeCompletionBuilder Opt(Result.getAllocator(),
3023 Result.getCodeCompletionTUInfo());
3024 if (!FirstParameter)
3025 Opt.AddChunk(CodeCompletionString::CK_Comma);
3026 AddFunctionParameterChunks(PP, Policy, Function, Opt, P, true);
3027 Result.AddOptionalChunk(Opt.TakeString());
3028 break;
3029 }
3030
3031 if (FirstParameter)
3032 FirstParameter = false;
3033 else
3034 Result.AddChunk(CodeCompletionString::CK_Comma);
3035
3036 InOptional = false;
3037
3038 // Format the placeholder string.
3039 std::string PlaceholderStr = FormatFunctionParameter(Policy, Param);
3040 if (Param->hasDefaultArg())
3041 PlaceholderStr +=
3042 GetDefaultValueString(Param, PP.getSourceManager(), PP.getLangOpts());
3043
3044 if (Function->isVariadic() && P == N - 1)
3045 PlaceholderStr += ", ...";
3046
3047 // Add the placeholder string.
3048 Result.AddPlaceholderChunk(
3049 Result.getAllocator().CopyString(PlaceholderStr));
3050 }
3051
3052 if (const auto *Proto = Function->getType()->getAs<FunctionProtoType>())
3053 if (Proto->isVariadic()) {
3054 if (Proto->getNumParams() == 0)
3055 Result.AddPlaceholderChunk("...");
3056
3057 MaybeAddSentinel(PP, Function, Result);
3058 }
3059}
3060
3061/// Add template parameter chunks to the given code completion string.
3062static void AddTemplateParameterChunks(
3063 ASTContext &Context, const PrintingPolicy &Policy,
3064 const TemplateDecl *Template, CodeCompletionBuilder &Result,
3065 unsigned MaxParameters = 0, unsigned Start = 0, bool InDefaultArg = false) {
3066 bool FirstParameter = true;
3067
3068 // Prefer to take the template parameter names from the first declaration of
3069 // the template.
3070 Template = cast<TemplateDecl>(Template->getCanonicalDecl());
3071
3072 TemplateParameterList *Params = Template->getTemplateParameters();
3073 TemplateParameterList::iterator PEnd = Params->end();
3074 if (MaxParameters)
3075 PEnd = Params->begin() + MaxParameters;
3076 for (TemplateParameterList::iterator P = Params->begin() + Start; P != PEnd;
3077 ++P) {
3078 bool HasDefaultArg = false;
3079 std::string PlaceholderStr;
3080 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
3081 if (TTP->wasDeclaredWithTypename())
3082 PlaceholderStr = "typename";
3083 else if (const auto *TC = TTP->getTypeConstraint()) {
3084 llvm::raw_string_ostream OS(PlaceholderStr);
3085 TC->print(OS, Policy);
3086 OS.flush();
3087 } else
3088 PlaceholderStr = "class";
3089
3090 if (TTP->getIdentifier()) {
3091 PlaceholderStr += ' ';
3092 PlaceholderStr += TTP->getIdentifier()->deuglifiedName();
3093 }
3094
3095 HasDefaultArg = TTP->hasDefaultArgument();
3096 } else if (NonTypeTemplateParmDecl *NTTP =
3097 dyn_cast<NonTypeTemplateParmDecl>(*P)) {
3098 if (NTTP->getIdentifier())
3099 PlaceholderStr = std::string(NTTP->getIdentifier()->deuglifiedName());
3100 NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
3101 HasDefaultArg = NTTP->hasDefaultArgument();
3102 } else {
3103 assert(isa<TemplateTemplateParmDecl>(*P))(static_cast <bool> (isa<TemplateTemplateParmDecl>
(*P)) ? void (0) : __assert_fail ("isa<TemplateTemplateParmDecl>(*P)"
, "clang/lib/Sema/SemaCodeComplete.cpp", 3103, __extension__ __PRETTY_FUNCTION__
))
;
3104 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
3105
3106 // Since putting the template argument list into the placeholder would
3107 // be very, very long, we just use an abbreviation.
3108 PlaceholderStr = "template<...> class";
3109 if (TTP->getIdentifier()) {
3110 PlaceholderStr += ' ';
3111 PlaceholderStr += TTP->getIdentifier()->deuglifiedName();
3112 }
3113
3114 HasDefaultArg = TTP->hasDefaultArgument();
3115 }
3116
3117 if (HasDefaultArg && !InDefaultArg) {
3118 // When we see an optional default argument, put that argument and
3119 // the remaining default arguments into a new, optional string.
3120 CodeCompletionBuilder Opt(Result.getAllocator(),
3121 Result.getCodeCompletionTUInfo());
3122 if (!FirstParameter)
3123 Opt.AddChunk(CodeCompletionString::CK_Comma);
3124 AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters,
3125 P - Params->begin(), true);
3126 Result.AddOptionalChunk(Opt.TakeString());
3127 break;
3128 }
3129
3130 InDefaultArg = false;
3131
3132 if (FirstParameter)
3133 FirstParameter = false;
3134 else
3135 Result.AddChunk(CodeCompletionString::CK_Comma);
3136
3137 // Add the placeholder string.
3138 Result.AddPlaceholderChunk(
3139 Result.getAllocator().CopyString(PlaceholderStr));
3140 }
3141}
3142
3143/// Add a qualifier to the given code-completion string, if the
3144/// provided nested-name-specifier is non-NULL.
3145static void AddQualifierToCompletionString(CodeCompletionBuilder &Result,
3146 NestedNameSpecifier *Qualifier,
3147 bool QualifierIsInformative,
3148 ASTContext &Context,
3149 const PrintingPolicy &Policy) {
3150 if (!Qualifier)
3151 return;
3152
3153 std::string PrintedNNS;
3154 {
3155 llvm::raw_string_ostream OS(PrintedNNS);
3156 Qualifier->print(OS, Policy);
3157 }
3158 if (QualifierIsInformative)
3159 Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
3160 else
3161 Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
3162}
3163
3164static void
3165AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
3166 const FunctionDecl *Function) {
3167 const auto *Proto = Function->getType()->getAs<FunctionProtoType>();
3168 if (!Proto || !Proto->getMethodQuals())
3169 return;
3170
3171 // FIXME: Add ref-qualifier!
3172
3173 // Handle single qualifiers without copying
3174 if (Proto->getMethodQuals().hasOnlyConst()) {
3175 Result.AddInformativeChunk(" const");
3176 return;
3177 }
3178
3179 if (Proto->getMethodQuals().hasOnlyVolatile()) {
3180 Result.AddInformativeChunk(" volatile");
3181 return;
3182 }
3183
3184 if (Proto->getMethodQuals().hasOnlyRestrict()) {
3185 Result.AddInformativeChunk(" restrict");
3186 return;
3187 }
3188
3189 // Handle multiple qualifiers.
3190 std::string QualsStr;
3191 if (Proto->isConst())
3192 QualsStr += " const";
3193 if (Proto->isVolatile())
3194 QualsStr += " volatile";
3195 if (Proto->isRestrict())
3196 QualsStr += " restrict";
3197 Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
3198}
3199
3200/// Add the name of the given declaration
3201static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy,
3202 const NamedDecl *ND,
3203 CodeCompletionBuilder &Result) {
3204 DeclarationName Name = ND->getDeclName();
3205 if (!Name)
3206 return;
3207
3208 switch (Name.getNameKind()) {
3209 case DeclarationName::CXXOperatorName: {
3210 const char *OperatorName = nullptr;
3211 switch (Name.getCXXOverloadedOperator()) {
3212 case OO_None:
3213 case OO_Conditional:
3214 case NUM_OVERLOADED_OPERATORS:
3215 OperatorName = "operator";
3216 break;
3217
3218#define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \
3219 case OO_##Name: \
3220 OperatorName = "operator" Spelling; \
3221 break;
3222#define OVERLOADED_OPERATOR_MULTI(Name, Spelling, Unary, Binary, MemberOnly)
3223#include "clang/Basic/OperatorKinds.def"
3224
3225 case OO_New:
3226 OperatorName = "operator new";
3227 break;
3228 case OO_Delete:
3229 OperatorName = "operator delete";
3230 break;
3231 case OO_Array_New:
3232 OperatorName = "operator new[]";
3233 break;
3234 case OO_Array_Delete:
3235 OperatorName = "operator delete[]";
3236 break;
3237 case OO_Call:
3238 OperatorName = "operator()";
3239 break;
3240 case OO_Subscript:
3241 OperatorName = "operator[]";
3242 break;
3243 }
3244 Result.AddTypedTextChunk(OperatorName);
3245 break;
3246 }
3247
3248 case DeclarationName::Identifier:
3249 case DeclarationName::CXXConversionFunctionName:
3250 case DeclarationName::CXXDestructorName:
3251 case DeclarationName::CXXLiteralOperatorName:
3252 Result.AddTypedTextChunk(
3253 Result.getAllocator().CopyString(ND->getNameAsString()));
3254 break;
3255
3256 case DeclarationName::CXXDeductionGuideName:
3257 case DeclarationName::CXXUsingDirective:
3258 case DeclarationName::ObjCZeroArgSelector:
3259 case DeclarationName::ObjCOneArgSelector:
3260 case DeclarationName::ObjCMultiArgSelector:
3261 break;
3262
3263 case DeclarationName::CXXConstructorName: {
3264 CXXRecordDecl *Record = nullptr;
3265 QualType Ty = Name.getCXXNameType();
3266 if (const auto *RecordTy = Ty->getAs<RecordType>())
3267 Record = cast<CXXRecordDecl>(RecordTy->getDecl());
3268 else if (const auto *InjectedTy = Ty->getAs<InjectedClassNameType>())
3269 Record = InjectedTy->getDecl();
3270 else {
3271 Result.AddTypedTextChunk(
3272 Result.getAllocator().CopyString(ND->getNameAsString()));
3273 break;
3274 }
3275
3276 Result.AddTypedTextChunk(
3277 Result.getAllocator().CopyString(Record->getNameAsString()));
3278 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
3279 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
3280 AddTemplateParameterChunks(Context, Policy, Template, Result);
3281 Result.AddChunk(CodeCompletionString::CK_RightAngle);
3282 }
3283 break;
3284 }
3285 }
3286}
3287
3288CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString(
3289 Sema &S, const CodeCompletionContext &CCContext,
3290 CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo,
3291 bool IncludeBriefComments) {
3292 return CreateCodeCompletionString(S.Context, S.PP, CCContext, Allocator,
3293 CCTUInfo, IncludeBriefComments);
3294}
3295
3296CodeCompletionString *CodeCompletionResult::CreateCodeCompletionStringForMacro(
3297 Preprocessor &PP, CodeCompletionAllocator &Allocator,
3298 CodeCompletionTUInfo &CCTUInfo) {
3299 assert(Kind == RK_Macro)(static_cast <bool> (Kind == RK_Macro) ? void (0) : __assert_fail
("Kind == RK_Macro", "clang/lib/Sema/SemaCodeComplete.cpp", 3299
, __extension__ __PRETTY_FUNCTION__))
;
3300 CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
3301 const MacroInfo *MI = PP.getMacroInfo(Macro);
3302 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Macro->getName()));
3303
3304 if (!MI || !MI->isFunctionLike())
3305 return Result.TakeString();
3306
3307 // Format a function-like macro with placeholders for the arguments.
3308 Result.AddChunk(CodeCompletionString::CK_LeftParen);
3309 MacroInfo::param_iterator A = MI->param_begin(), AEnd = MI->param_end();
3310
3311 // C99 variadic macros add __VA_ARGS__ at the end. Skip it.
3312 if (MI->isC99Varargs()) {
3313 --AEnd;
3314
3315 if (A == AEnd) {
3316 Result.AddPlaceholderChunk("...");
3317 }
3318 }
3319
3320 for (MacroInfo::param_iterator A = MI->param_begin(); A != AEnd; ++A) {
3321 if (A != MI->param_begin())
3322 Result.AddChunk(CodeCompletionString::CK_Comma);
3323
3324 if (MI->isVariadic() && (A + 1) == AEnd) {
3325 SmallString<32> Arg = (*A)->getName();
3326 if (MI->isC99Varargs())
3327 Arg += ", ...";
3328 else
3329 Arg += "...";
3330 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
3331 break;
3332 }
3333
3334 // Non-variadic macros are simple.
3335 Result.AddPlaceholderChunk(
3336 Result.getAllocator().CopyString((*A)->getName()));
3337 }
3338 Result.AddChunk(CodeCompletionString::CK_RightParen);
3339 return Result.TakeString();
3340}
3341
3342/// If possible, create a new code completion string for the given
3343/// result.
3344///
3345/// \returns Either a new, heap-allocated code completion string describing
3346/// how to use this result, or NULL to indicate that the string or name of the
3347/// result is all that is needed.
3348CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString(
3349 ASTContext &Ctx, Preprocessor &PP, const CodeCompletionContext &CCContext,
3350 CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo,
3351 bool IncludeBriefComments) {
3352 if (Kind == RK_Macro)
3353 return CreateCodeCompletionStringForMacro(PP, Allocator, CCTUInfo);
3354
3355 CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
3356
3357 PrintingPolicy Policy = getCompletionPrintingPolicy(Ctx, PP);
3358 if (Kind == RK_Pattern) {
3359 Pattern->Priority = Priority;
3360 Pattern->Availability = Availability;
3361
3362 if (Declaration) {
3363 Result.addParentContext(Declaration->getDeclContext());
3364 Pattern->ParentName = Result.getParentName();
3365 if (const RawComment *RC =
3366 getPatternCompletionComment(Ctx, Declaration)) {
3367 Result.addBriefComment(RC->getBriefText(Ctx));
3368 Pattern->BriefComment = Result.getBriefComment();
3369 }
3370 }
3371
3372 return Pattern;
3373 }
3374
3375 if (Kind == RK_Keyword) {
3376 Result.AddTypedTextChunk(Keyword);
3377 return Result.TakeString();
3378 }
3379 assert(Kind == RK_Declaration && "Missed a result kind?")(static_cast <bool> (Kind == RK_Declaration && "Missed a result kind?"
) ? void (0) : __assert_fail ("Kind == RK_Declaration && \"Missed a result kind?\""
, "clang/lib/Sema/SemaCodeComplete.cpp", 3379, __extension__ __PRETTY_FUNCTION__
))
;
3380 return createCodeCompletionStringForDecl(
3381 PP, Ctx, Result, IncludeBriefComments, CCContext, Policy);
3382}
3383
3384static void printOverrideString(const CodeCompletionString &CCS,
3385 std::string &BeforeName,
3386 std::string &NameAndSignature) {
3387 bool SeenTypedChunk = false;
3388 for (auto &Chunk : CCS) {
3389 if (Chunk.Kind == CodeCompletionString::CK_Optional) {
3390 assert(SeenTypedChunk && "optional parameter before name")(static_cast <bool> (SeenTypedChunk && "optional parameter before name"
) ? void (0) : __assert_fail ("SeenTypedChunk && \"optional parameter before name\""
, "clang/lib/Sema/SemaCodeComplete.cpp", 3390, __extension__ __PRETTY_FUNCTION__
))
;
3391 // Note that we put all chunks inside into NameAndSignature.
3392 printOverrideString(*Chunk.Optional, NameAndSignature, NameAndSignature);
3393 continue;
3394 }
3395 SeenTypedChunk |= Chunk.Kind == CodeCompletionString::CK_TypedText;
3396 if (SeenTypedChunk)
3397 NameAndSignature += Chunk.Text;
3398 else
3399 BeforeName += Chunk.Text;
3400 }
3401}
3402
3403CodeCompletionString *
3404CodeCompletionResult::createCodeCompletionStringForOverride(
3405 Preprocessor &PP, ASTContext &Ctx, CodeCompletionBuilder &Result,
3406 bool IncludeBriefComments, const CodeCompletionContext &CCContext,
3407 PrintingPolicy &Policy) {
3408 auto *CCS = createCodeCompletionStringForDecl(PP, Ctx, Result,
3409 /*IncludeBriefComments=*/false,
3410 CCContext, Policy);
3411 std::string BeforeName;
3412 std::string NameAndSignature;
3413 // For overrides all chunks go into the result, none are informative.
3414 printOverrideString(*CCS, BeforeName, NameAndSignature);
3415 NameAndSignature += " override";
3416
3417 Result.AddTextChunk(Result.getAllocator().CopyString(BeforeName));
3418 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3419 Result.AddTypedTextChunk(Result.getAllocator().CopyString(NameAndSignature));
3420 return Result.TakeString();
3421}
3422
3423// FIXME: Right now this works well with lambdas. Add support for other functor
3424// types like std::function.
3425static const NamedDecl *extractFunctorCallOperator(const NamedDecl *ND) {
3426 const auto *VD = dyn_cast<VarDecl>(ND);
3427 if (!VD)
3428 return nullptr;
3429 const auto *RecordDecl = VD->getType()->getAsCXXRecordDecl();
3430 if (!RecordDecl || !RecordDecl->isLambda())
3431 return nullptr;
3432 return RecordDecl->getLambdaCallOperator();
3433}
3434
3435CodeCompletionString *CodeCompletionResult::createCodeCompletionStringForDecl(
3436 Preprocessor &PP, ASTContext &Ctx, CodeCompletionBuilder &Result,
3437 bool IncludeBriefComments, const CodeCompletionContext &CCContext,
3438 PrintingPolicy &Policy) {
3439 const NamedDecl *ND = Declaration;
3440 Result.addParentContext(ND->getDeclContext());
3441
3442 if (IncludeBriefComments) {
3443 // Add documentation comment, if it exists.
3444 if (const RawComment *RC = getCompletionComment(Ctx, Declaration)) {
3445 Result.addBriefComment(RC->getBriefText(Ctx));
3446 }
3447 }
3448
3449 if (StartsNestedNameSpecifier) {
3450 Result.AddTypedTextChunk(
3451 Result.getAllocator().CopyString(ND->getNameAsString()));
3452 Result.AddTextChunk("::");
3453 return Result.TakeString();
3454 }
3455
3456 for (const auto *I : ND->specific_attrs<AnnotateAttr>())
3457 Result.AddAnnotation(Result.getAllocator().CopyString(I->getAnnotation()));
3458
3459 auto AddFunctionTypeAndResult = [&](const FunctionDecl *Function) {
3460 AddResultTypeChunk(Ctx, Policy, Function, CCContext.getBaseType(), Result);
3461 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
3462 Ctx, Policy);
3463 AddTypedNameChunk(Ctx, Policy, ND, Result);
3464 Result.AddChunk(CodeCompletionString::CK_LeftParen);
3465 AddFunctionParameterChunks(PP, Policy, Function, Result);
3466 Result.AddChunk(CodeCompletionString::CK_RightParen);
3467 AddFunctionTypeQualsToCompletionString(Result, Function);
3468 };
3469
3470 if (const auto *Function = dyn_cast<FunctionDecl>(ND)) {
3471 AddFunctionTypeAndResult(Function);
3472 return Result.TakeString();
3473 }
3474
3475 if (const auto *CallOperator =
3476 dyn_cast_or_null<FunctionDecl>(extractFunctorCallOperator(ND))) {
3477 AddFunctionTypeAndResult(CallOperator);
3478 return Result.TakeString();
3479 }
3480
3481 AddResultTypeChunk(Ctx, Policy, ND, CCContext.getBaseType(), Result);
3482
3483 if (const FunctionTemplateDecl *FunTmpl =
3484 dyn_cast<FunctionTemplateDecl>(ND)) {
3485 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
3486 Ctx, Policy);
3487 FunctionDecl *Function = FunTmpl->getTemplatedDecl();
3488 AddTypedNameChunk(Ctx, Policy, Function, Result);
3489
3490 // Figure out which template parameters are deduced (or have default
3491 // arguments).
3492 llvm::SmallBitVector Deduced;
3493 Sema::MarkDeducedTemplateParameters(Ctx, FunTmpl, Deduced);
3494 unsigned LastDeducibleArgument;
3495 for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
3496 --LastDeducibleArgument) {
3497 if (!Deduced[LastDeducibleArgument - 1]) {
3498 // C++0x: Figure out if the template argument has a default. If so,
3499 // the user doesn't need to type this argument.
3500 // FIXME: We need to abstract template parameters better!
3501 bool HasDefaultArg = false;
3502 NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
3503 LastDeducibleArgument - 1);
3504 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3505 HasDefaultArg = TTP->hasDefaultArgument();
3506 else if (NonTypeTemplateParmDecl *NTTP =
3507 dyn_cast<NonTypeTemplateParmDecl>(Param))
3508 HasDefaultArg = NTTP->hasDefaultArgument();
3509 else {
3510 assert(isa<TemplateTemplateParmDecl>(Param))(static_cast <bool> (isa<TemplateTemplateParmDecl>
(Param)) ? void (0) : __assert_fail ("isa<TemplateTemplateParmDecl>(Param)"
, "clang/lib/Sema/SemaCodeComplete.cpp", 3510, __extension__ __PRETTY_FUNCTION__
))
;
3511 HasDefaultArg =
3512 cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
3513 }
3514
3515 if (!HasDefaultArg)
3516 break;
3517 }
3518 }
3519
3520 if (LastDeducibleArgument) {
3521 // Some of the function template arguments cannot be deduced from a
3522 // function call, so we introduce an explicit template argument list
3523 // containing all of the arguments up to the first deducible argument.
3524 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
3525 AddTemplateParameterChunks(Ctx, Policy, FunTmpl, Result,
3526 LastDeducibleArgument);
3527 Result.AddChunk(CodeCompletionString::CK_RightAngle);
3528 }
3529
3530 // Add the function parameters
3531 Result.AddChunk(CodeCompletionString::CK_LeftParen);
3532 AddFunctionParameterChunks(PP, Policy, Function, Result);
3533 Result.AddChunk(CodeCompletionString::CK_RightParen);
3534 AddFunctionTypeQualsToCompletionString(Result, Function);
3535 return Result.TakeString();
3536 }
3537
3538 if (const auto *Template = dyn_cast<TemplateDecl>(ND)) {
3539 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
3540 Ctx, Policy);
3541 Result.AddTypedTextChunk(
3542 Result.getAllocator().CopyString(Template->getNameAsString()));
3543 Result.AddChunk(CodeCompletionString::CK_LeftAngle);
3544 AddTemplateParameterChunks(Ctx, Policy, Template, Result);
3545 Result.AddChunk(CodeCompletionString::CK_RightAngle);
3546 return Result.TakeString();
3547 }
3548
3549 if (const auto *Method = dyn_cast<ObjCMethodDecl>(ND)) {
3550 Selector Sel = Method->getSelector();
3551 if (Sel.isUnarySelector()) {
3552 Result.AddTypedTextChunk(
3553 Result.getAllocator().CopyString(Sel.getNameForSlot(0)));
3554 return Result.TakeString();
3555 }
3556
3557 std::string SelName = Sel.getNameForSlot(0).str();
3558 SelName += ':';
3559 if (StartParameter == 0)
3560 Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
3561 else {
3562 Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
3563
3564 // If there is only one parameter, and we're past it, add an empty
3565 // typed-text chunk since there is nothing to type.
3566 if (Method->param_size() == 1)
3567 Result.AddTypedTextChunk("");
3568 }
3569 unsigned Idx = 0;
3570 // The extra Idx < Sel.getNumArgs() check is needed due to legacy C-style
3571 // method parameters.
3572 for (ObjCMethodDecl::param_const_iterator P = Method->param_begin(),
3573 PEnd = Method->param_end();
3574 P != PEnd && Idx < Sel.getNumArgs(); (void)++P, ++Idx) {
3575 if (Idx > 0) {
3576 std::string Keyword;
3577 if (Idx > StartParameter)
3578 Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
3579 if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
3580 Keyword += II->getName();
3581 Keyword += ":";
3582 if (Idx < StartParameter || AllParametersAreInformative)
3583 Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
3584 else
3585 Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
3586 }
3587
3588 // If we're before the starting parameter, skip the placeholder.
3589 if (Idx < StartParameter)
3590 continue;
3591
3592 std::string Arg;
3593 QualType ParamType = (*P)->getType();
3594 Optional<ArrayRef<QualType>> ObjCSubsts;
3595 if (!CCContext.getBaseType().isNull())
3596 ObjCSubsts = CCContext.getBaseType()->getObjCSubstitutions(Method);
3597
3598 if (ParamType->isBlockPointerType() && !DeclaringEntity)
3599 Arg = FormatFunctionParameter(Policy, *P, true,
3600 /*SuppressBlock=*/false, ObjCSubsts);
3601 else {
3602 if (ObjCSubsts)
3603 ParamType = ParamType.substObjCTypeArgs(
3604 Ctx, *ObjCSubsts, ObjCSubstitutionContext::Parameter);
3605 Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier(),
3606 ParamType);
3607 Arg += ParamType.getAsString(Policy) + ")";
3608 if (IdentifierInfo *II = (*P)->getIdentifier())
3609 if (DeclaringEntity || AllParametersAreInformative)
3610 Arg += II->getName();
3611 }
3612
3613 if (Method->isVariadic() && (P + 1) == PEnd)
3614 Arg += ", ...";
3615
3616 if (DeclaringEntity)
3617 Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
3618 else if (AllParametersAreInformative)
3619 Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
3620 else
3621 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
3622 }
3623
3624 if (Method->isVariadic()) {
3625 if (Method->param_size() == 0) {
3626 if (DeclaringEntity)
3627 Result.AddTextChunk(", ...");
3628 else if (AllParametersAreInformative)
3629 Result.AddInformativeChunk(", ...");
3630 else
3631 Result.AddPlaceholderChunk(", ...");
3632 }
3633
3634 MaybeAddSentinel(PP, Method, Result);
3635 }
3636
3637 return Result.TakeString();
3638 }
3639
3640 if (Qualifier)
3641 AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
3642 Ctx, Policy);
3643
3644 Result.AddTypedTextChunk(
3645 Result.getAllocator().CopyString(ND->getNameAsString()));
3646 return Result.TakeString();
3647}
3648
3649const RawComment *clang::getCompletionComment(const ASTContext &Ctx,
3650 const NamedDecl *ND) {
3651 if (!ND)
3652 return nullptr;
3653 if (auto *RC = Ctx.getRawCommentForAnyRedecl(ND))
3654 return RC;
3655
3656 // Try to find comment from a property for ObjC methods.
3657 const auto *M = dyn_cast<ObjCMethodDecl>(ND);
3658 if (!M)
3659 return nullptr;
3660 const ObjCPropertyDecl *PDecl = M->findPropertyDecl();
3661 if (!PDecl)
3662 return nullptr;
3663
3664 return Ctx.getRawCommentForAnyRedecl(PDecl);
3665}
3666
3667const RawComment *clang::getPatternCompletionComment(const ASTContext &Ctx,
3668 const NamedDecl *ND) {
3669 const auto *M = dyn_cast_or_null<ObjCMethodDecl>(ND);
3670 if (!M || !M->isPropertyAccessor())
3671 return nullptr;
3672
3673 // Provide code completion comment for self.GetterName where
3674 // GetterName is the getter method for a property with name
3675 // different from the property name (declared via a property
3676 // getter attribute.
3677 const ObjCPropertyDecl *PDecl = M->findPropertyDecl();
3678 if (!PDecl)
3679 return nullptr;
3680 if (PDecl->getGetterName() == M->getSelector() &&
3681 PDecl->getIdentifier() != M->getIdentifier()) {
3682 if (auto *RC = Ctx.getRawCommentForAnyRedecl(M))
3683 return RC;
3684 if (auto *RC = Ctx.getRawCommentForAnyRedecl(PDecl))
3685 return RC;
3686 }
3687 return nullptr;
3688}
3689
3690const RawComment *clang::getParameterComment(
3691 const ASTContext &Ctx,
3692 const CodeCompleteConsumer::OverloadCandidate &Result, unsigned ArgIndex) {
3693 auto FDecl = Result.getFunction();
3694 if (!FDecl)
3695 return nullptr;
3696 if (ArgIndex < FDecl->getNumParams())
3697 return Ctx.getRawCommentForAnyRedecl(FDecl->getParamDecl(ArgIndex));
3698 return nullptr;
3699}
3700
3701static void AddOverloadAggregateChunks(const RecordDecl *RD,
3702 const PrintingPolicy &Policy,
3703 CodeCompletionBuilder &Result,
3704 unsigned CurrentArg) {
3705 unsigned ChunkIndex = 0;
3706 auto AddChunk = [&](llvm::StringRef Placeholder) {
3707 if (ChunkIndex > 0)
3708 Result.AddChunk(CodeCompletionString::CK_Comma);
3709 const char *Copy = Result.getAllocator().CopyString(Placeholder);
3710 if (ChunkIndex == CurrentArg)
3711 Result.AddCurrentParameterChunk(Copy);
3712 else
3713 Result.AddPlaceholderChunk(Copy);
3714 ++ChunkIndex;
3715 };
3716 // Aggregate initialization has all bases followed by all fields.
3717 // (Bases are not legal in C++11 but in that case we never get here).
3718 if (auto *CRD = llvm::dyn_cast<CXXRecordDecl>(RD)) {
3719 for (const auto &Base : CRD->bases())
3720 AddChunk(Base.getType().getAsString(Policy));
3721 }
3722 for (const auto &Field : RD->fields())
3723 AddChunk(FormatFunctionParameter(Policy, Field));
3724}
3725
3726/// Add function overload parameter chunks to the given code completion
3727/// string.
3728static void AddOverloadParameterChunks(
3729 ASTContext &Context, const PrintingPolicy &Policy,
3730 const FunctionDecl *Function, const FunctionProtoType *Prototype,
3731 FunctionProtoTypeLoc PrototypeLoc, CodeCompletionBuilder &Result,
3732 unsigned CurrentArg, unsigned Start = 0, bool InOptional = false) {
3733 if (!Function
15.1
'Function' is non-null
&& !Prototype) {
3734 Result.AddChunk(CodeCompletionString::CK_CurrentParameter, "...");
3735 return;
3736 }
3737
3738 bool FirstParameter = true;
3739 unsigned NumParams =
3740 Function
15.2
'Function' is non-null
? Function->getNumParams() : Prototype->getNumParams();
16
'?' condition is true
3741
3742 for (unsigned P = Start; P != NumParams; ++P) {
17
Assuming 'P' is not equal to 'NumParams'
3743 if (Function
17.1
'Function' is non-null
&& Function->getParamDecl(P)->hasDefaultArg() && !InOptional) {
18
Assuming the condition is false
3744 // When we see an optional default argument, put that argument and
3745 // the remaining default arguments into a new, optional string.
3746 CodeCompletionBuilder Opt(Result.getAllocator(),
3747 Result.getCodeCompletionTUInfo());
3748 if (!FirstParameter)
3749 Opt.AddChunk(CodeCompletionString::CK_Comma);
3750 // Optional sections are nested.
3751 AddOverloadParameterChunks(Context, Policy, Function, Prototype,
3752 PrototypeLoc, Opt, CurrentArg, P,
3753 /*InOptional=*/true);
3754 Result.AddOptionalChunk(Opt.TakeString());
3755 return;
3756 }
3757
3758 if (FirstParameter
18.1
'FirstParameter' is true
)
19
Taking true branch
3759 FirstParameter = false;
3760 else
3761 Result.AddChunk(CodeCompletionString::CK_Comma);
3762
3763 InOptional = false;
3764
3765 // Format the placeholder string.
3766 std::string Placeholder;
3767 assert(P < Prototype->getNumParams())(static_cast <bool> (P < Prototype->getNumParams(
)) ? void (0) : __assert_fail ("P < Prototype->getNumParams()"
, "clang/lib/Sema/SemaCodeComplete.cpp", 3767, __extension__ __PRETTY_FUNCTION__
))
;
20
Called C++ object pointer is null
3768 if (Function || PrototypeLoc) {
3769 const ParmVarDecl *Param =
3770 Function ? Function->getParamDecl(P) : PrototypeLoc.getParam(P);
3771 Placeholder = FormatFunctionParameter(Policy, Param);
3772 if (Param->hasDefaultArg())
3773 Placeholder += GetDefaultValueString(Param, Context.getSourceManager(),
3774 Context.getLangOpts());
3775 } else {
3776 Placeholder = Prototype->getParamType(P).getAsString(Policy);
3777 }
3778
3779 if (P == CurrentArg)
3780 Result.AddCurrentParameterChunk(
3781 Result.getAllocator().CopyString(Placeholder));
3782 else
3783 Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Placeholder));
3784 }
3785
3786 if (Prototype && Prototype->isVariadic()) {
3787 CodeCompletionBuilder Opt(Result.getAllocator(),
3788 Result.getCodeCompletionTUInfo());
3789 if (!FirstParameter)
3790 Opt.AddChunk(CodeCompletionString::CK_Comma);
3791
3792 if (CurrentArg < NumParams)
3793 Opt.AddPlaceholderChunk("...");
3794 else
3795 Opt.AddCurrentParameterChunk("...");
3796
3797 Result.AddOptionalChunk(Opt.TakeString());
3798 }
3799}
3800
3801static std::string
3802formatTemplateParameterPlaceholder(const NamedDecl *Param, bool &Optional,
3803 const PrintingPolicy &Policy) {
3804 if (const auto *Type = dyn_cast<TemplateTypeParmDecl>(Param)) {
3805 Optional = Type->hasDefaultArgument();
3806 } else if (const auto *NonType = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3807 Optional = NonType->hasDefaultArgument();
3808 } else if (const auto *Template = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3809 Optional = Template->hasDefaultArgument();
3810 }
3811 std::string Result;
3812 llvm::raw_string_ostream OS(Result);
3813 Param->print(OS, Policy);
3814 return Result;
3815}
3816
3817static std::string templateResultType(const TemplateDecl *TD,
3818 const PrintingPolicy &Policy) {
3819 if (const auto *CTD = dyn_cast<ClassTemplateDecl>(TD))
3820 return CTD->getTemplatedDecl()->getKindName().str();
3821 if (const auto *VTD = dyn_cast<VarTemplateDecl>(TD))
3822 return VTD->getTemplatedDecl()->getType().getAsString(Policy);
3823 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(TD))
3824 return FTD->getTemplatedDecl()->getReturnType().getAsString(Policy);
3825 if (isa<TypeAliasTemplateDecl>(TD))
3826 return "type";
3827 if (isa<TemplateTemplateParmDecl>(TD))
3828 return "class";
3829 if (isa<ConceptDecl>(TD))
3830 return "concept";
3831 return "";
3832}
3833
3834static CodeCompletionString *createTemplateSignatureString(
3835 const TemplateDecl *TD, CodeCompletionBuilder &Builder, unsigned CurrentArg,
3836 const PrintingPolicy &Policy) {
3837 llvm::ArrayRef<NamedDecl *> Params = TD->getTemplateParameters()->asArray();
3838 CodeCompletionBuilder OptionalBuilder(Builder.getAllocator(),
3839 Builder.getCodeCompletionTUInfo());
3840 std::string ResultType = templateResultType(TD, Policy);
3841 if (!ResultType.empty())
3842 Builder.AddResultTypeChunk(Builder.getAllocator().CopyString(ResultType));
3843 Builder.AddTextChunk(
3844 Builder.getAllocator().CopyString(TD->getNameAsString()));
3845 Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
3846 // Initially we're writing into the main string. Once we see an optional arg
3847 // (with default), we're writing into the nested optional chunk.
3848 CodeCompletionBuilder *Current = &Builder;
3849 for (unsigned I = 0; I < Params.size(); ++I) {
3850 bool Optional = false;
3851 std::string Placeholder =
3852 formatTemplateParameterPlaceholder(Params[I], Optional, Policy);
3853 if (Optional)
3854 Current = &OptionalBuilder;
3855 if (I > 0)
3856 Current->AddChunk(CodeCompletionString::CK_Comma);
3857 Current->AddChunk(I == CurrentArg
3858 ? CodeCompletionString::CK_CurrentParameter
3859 : CodeCompletionString::CK_Placeholder,
3860 Current->getAllocator().CopyString(Placeholder));
3861 }
3862 // Add the optional chunk to the main string if we ever used it.
3863 if (Current == &OptionalBuilder)
3864 Builder.AddOptionalChunk(OptionalBuilder.TakeString());
3865 Builder.AddChunk(CodeCompletionString::CK_RightAngle);
3866 // For function templates, ResultType was the function's return type.
3867 // Give some clue this is a function. (Don't show the possibly-bulky params).
3868 if (isa<FunctionTemplateDecl>(TD))
3869 Builder.AddInformativeChunk("()");
3870 return Builder.TakeString();
3871}
3872
3873CodeCompletionString *
3874CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
3875 unsigned CurrentArg, Sema &S, CodeCompletionAllocator &Allocator,
3876 CodeCompletionTUInfo &CCTUInfo, bool IncludeBriefComments,
3877 bool Braced) const {
3878 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
3879 // Show signatures of constructors as they are declared:
3880 // vector(int n) rather than vector<string>(int n)
3881 // This is less noisy without being less clear, and avoids tricky cases.
3882 Policy.SuppressTemplateArgsInCXXConstructors = true;
3883
3884 // FIXME: Set priority, availability appropriately.
3885 CodeCompletionBuilder Result(Allocator, CCTUInfo, 1,
3886 CXAvailability_Available);
3887
3888 if (getKind() == CK_Template)
1
Assuming the condition is false
2
Taking false branch
3889 return createTemplateSignatureString(getTemplate(), Result, CurrentArg,
3890 Policy);
3891
3892 FunctionDecl *FDecl = getFunction();
3893 const FunctionProtoType *Proto =
4
'Proto' initialized to a null pointer value
3894 dyn_cast_or_null<FunctionProtoType>(getFunctionType());
3
Assuming null pointer is passed into cast
3895
3896 // First, the name/type of the callee.
3897 if (getKind() == CK_Aggregate) {
5
Assuming the condition is false
6
Taking false branch
3898 Result.AddTextChunk(
3899 Result.getAllocator().CopyString(getAggregate()->getName()));
3900 } else if (FDecl) {
7
Assuming 'FDecl' is non-null
8
Taking true branch
3901 if (IncludeBriefComments) {
9
Assuming 'IncludeBriefComments' is false
10
Taking false branch
3902 if (auto RC = getParameterComment(S.getASTContext(), *this, CurrentArg))
3903 Result.addBriefComment(RC->getBriefText(S.getASTContext()));
3904 }
3905 AddResultTypeChunk(S.Context, Policy, FDecl, QualType(), Result);
3906
3907 std::string Name;
3908 llvm::raw_string_ostream OS(Name);
3909 FDecl->getDeclName().print(OS, Policy);
3910 Result.AddTextChunk(Result.getAllocator().CopyString(OS.str()));
3911 } else {
3912 // Function without a declaration. Just give the return type.
3913 Result.AddResultTypeChunk(Result.getAllocator().CopyString(
3914 getFunctionType()->getReturnType().getAsString(Policy)));
3915 }
3916
3917 // Next, the brackets and parameters.
3918 Result.AddChunk(Braced ? CodeCompletionString::CK_LeftBrace
11
Assuming 'Braced' is false
12
'?' condition is false
3919 : CodeCompletionString::CK_LeftParen);
3920 if (getKind() == CK_Aggregate)
13
Taking false branch
3921 AddOverloadAggregateChunks(getAggregate(), Policy, Result, CurrentArg);
3922 else
3923 AddOverloadParameterChunks(S.getASTContext(), Policy, FDecl, Proto,
14
Passing null pointer value via 4th parameter 'Prototype'
15
Calling 'AddOverloadParameterChunks'
3924 getFunctionProtoTypeLoc(), Result, CurrentArg);
3925 Result.AddChunk(Braced ? CodeCompletionString::CK_RightBrace
3926 : CodeCompletionString::CK_RightParen);
3927
3928 return Result.TakeString();
3929}
3930
3931unsigned clang::getMacroUsagePriority(StringRef MacroName,
3932 const LangOptions &LangOpts,
3933 bool PreferredTypeIsPointer) {
3934 unsigned Priority = CCP_Macro;
3935
3936 // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
3937 if (MacroName.equals("nil") || MacroName.equals("NULL") ||
3938 MacroName.equals("Nil")) {
3939 Priority = CCP_Constant;
3940 if (PreferredTypeIsPointer)
3941 Priority = Priority / CCF_SimilarTypeMatch;
3942 }
3943 // Treat "YES", "NO", "true", and "false" as constants.
3944 else if (MacroName.equals("YES") || MacroName.equals("NO") ||
3945 MacroName.equals("true") || MacroName.equals("false"))
3946 Priority = CCP_Constant;
3947 // Treat "bool" as a type.
3948 else if (MacroName.equals("bool"))
3949 Priority = CCP_Type + (LangOpts.ObjC ? CCD_bool_in_ObjC : 0);
3950
3951 return Priority;
3952}
3953
3954CXCursorKind clang::getCursorKindForDecl(const Decl *D) {
3955 if (!D)
3956 return CXCursor_UnexposedDecl;
3957
3958 switch (D->getKind()) {
3959 case Decl::Enum:
3960 return CXCursor_EnumDecl;
3961 case Decl::EnumConstant:
3962 return CXCursor_EnumConstantDecl;
3963 case Decl::Field:
3964 return CXCursor_FieldDecl;
3965 case Decl::Function:
3966 return CXCursor_FunctionDecl;
3967 case Decl::ObjCCategory:
3968 return CXCursor_ObjCCategoryDecl;
3969 case Decl::ObjCCategoryImpl:
3970 return CXCursor_ObjCCategoryImplDecl;
3971 case Decl::ObjCImplementation:
3972 return CXCursor_ObjCImplementationDecl;
3973
3974 case Decl::ObjCInterface:
3975 return CXCursor_ObjCInterfaceDecl;
3976 case Decl::ObjCIvar:
3977 return CXCursor_ObjCIvarDecl;
3978 case Decl::ObjCMethod:
3979 return cast<ObjCMethodDecl>(D)->isInstanceMethod()
3980 ? CXCursor_ObjCInstanceMethodDecl
3981 : CXCursor_ObjCClassMethodDecl;
3982 case Decl::CXXMethod:
3983 return CXCursor_CXXMethod;
3984 case Decl::CXXConstructor:
3985 return CXCursor_Constructor;
3986 case Decl::CXXDestructor:
3987 return CXCursor_Destructor;
3988 case Decl::CXXConversion:
3989 return CXCursor_ConversionFunction;
3990 case Decl::ObjCProperty:
3991 return CXCursor_ObjCPropertyDecl;
3992 case Decl::ObjCProtocol:
3993 return CXCursor_ObjCProtocolDecl;
3994 case Decl::ParmVar:
3995 return CXCursor_ParmDecl;
3996 case Decl::Typedef:
3997 return CXCursor_TypedefDecl;
3998 case Decl::TypeAlias:
3999 return CXCursor_TypeAliasDecl;
4000 case Decl::TypeAliasTemplate:
4001 return CXCursor_TypeAliasTemplateDecl;
4002 case Decl::Var:
4003 return CXCursor_VarDecl;
4004 case Decl::Namespace:
4005 return CXCursor_Namespace;
4006 case Decl::NamespaceAlias:
4007 return CXCursor_NamespaceAlias;
4008 case Decl::TemplateTypeParm:
4009 return CXCursor_TemplateTypeParameter;
4010 case Decl::NonTypeTemplateParm:
4011 return CXCursor_NonTypeTemplateParameter;
4012 case Decl::TemplateTemplateParm:
4013 return CXCursor_TemplateTemplateParameter;
4014 case Decl::FunctionTemplate:
4015 return CXCursor_FunctionTemplate;
4016 case Decl::ClassTemplate:
4017 return CXCursor_ClassTemplate;
4018 case Decl::AccessSpec:
4019 return CXCursor_CXXAccessSpecifier;
4020 case Decl::ClassTemplatePartialSpecialization:
4021 return CXCursor_ClassTemplatePartialSpecialization;
4022 case Decl::UsingDirective:
4023 return CXCursor_UsingDirective;
4024 case Decl::StaticAssert:
4025 return CXCursor_StaticAssert;
4026 case Decl::Friend:
4027 return CXCursor_FriendDecl;
4028 case Decl::TranslationUnit:
4029 return CXCursor_TranslationUnit;
4030
4031 case Decl::Using:
4032 case Decl::UnresolvedUsingValue:
4033 case Decl::UnresolvedUsingTypename:
4034 return CXCursor_UsingDeclaration;
4035
4036 case Decl::UsingEnum:
4037 return CXCursor_EnumDecl;
4038
4039 case Decl::ObjCPropertyImpl:
4040 switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
4041 case ObjCPropertyImplDecl::Dynamic:
4042 return CXCursor_ObjCDynamicDecl;
4043
4044 case ObjCPropertyImplDecl::Synthesize:
4045 return CXCursor_ObjCSynthesizeDecl;
4046 }
4047 llvm_unreachable("Unexpected Kind!")::llvm::llvm_unreachable_internal("Unexpected Kind!", "clang/lib/Sema/SemaCodeComplete.cpp"
, 4047)
;
4048
4049 case Decl::Import:
4050 return CXCursor_ModuleImportDecl;
4051
4052 case Decl::ObjCTypeParam:
4053 return CXCursor_TemplateTypeParameter;
4054
4055 case Decl::Concept:
4056 return CXCursor_ConceptDecl;
4057
4058 default:
4059 if (const auto *TD = dyn_cast<TagDecl>(D)) {
4060 switch (TD->getTagKind()) {
4061 case TTK_Interface: // fall through
4062 case TTK_Struct:
4063 return CXCursor_StructDecl;
4064 case TTK_Class:
4065 return CXCursor_ClassDecl;
4066 case TTK_Union:
4067 return CXCursor_UnionDecl;
4068 case TTK_Enum:
4069 return CXCursor_EnumDecl;
4070 }
4071 }
4072 }
4073
4074 return CXCursor_UnexposedDecl;
4075}
4076
4077static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
4078 bool LoadExternal, bool IncludeUndefined,
4079 bool TargetTypeIsPointer = false) {
4080 typedef CodeCompletionResult Result;
4081
4082 Results.EnterNewScope();
4083
4084 for (Preprocessor::macro_iterator M = PP.macro_begin(LoadExternal),
4085 MEnd = PP.macro_end(LoadExternal);
4086 M != MEnd; ++M) {
4087 auto MD = PP.getMacroDefinition(M->first);
4088 if (IncludeUndefined || MD) {
4089 MacroInfo *MI = MD.getMacroInfo();
4090 if (MI && MI->isUsedForHeaderGuard())
4091 continue;
4092
4093 Results.AddResult(
4094 Result(M->first, MI,
4095 getMacroUsagePriority(M->first->getName(), PP.getLangOpts(),
4096 TargetTypeIsPointer)));
4097 }
4098 }
4099
4100 Results.ExitScope();
4101}
4102
4103static void AddPrettyFunctionResults(const LangOptions &LangOpts,
4104 ResultBuilder &Results) {
4105 typedef CodeCompletionResult Result;
4106
4107 Results.EnterNewScope();
4108
4109 Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
4110 Results.AddResult(Result("__FUNCTION__", CCP_Constant));
4111 if (LangOpts.C99 || LangOpts.CPlusPlus11)
4112 Results.AddResult(Result("__func__", CCP_Constant));
4113 Results.ExitScope();
4114}
4115
4116static void HandleCodeCompleteResults(Sema *S,
4117 CodeCompleteConsumer *CodeCompleter,
4118 CodeCompletionContext Context,
4119 CodeCompletionResult *Results,
4120 unsigned NumResults) {
4121 if (CodeCompleter)
4122 CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
4123}
4124
4125static CodeCompletionContext
4126mapCodeCompletionContext(Sema &S, Sema::ParserCompletionContext PCC) {
4127 switch (PCC) {
4128 case Sema::PCC_Namespace:
4129 return CodeCompletionContext::CCC_TopLevel;
4130
4131 case Sema::PCC_Class:
4132 return CodeCompletionContext::CCC_ClassStructUnion;
4133
4134 case Sema::PCC_ObjCInterface:
4135 return CodeCompletionContext::CCC_ObjCInterface;
4136
4137 case Sema::PCC_ObjCImplementation:
4138 return CodeCompletionContext::CCC_ObjCImplementation;
4139
4140 case Sema::PCC_ObjCInstanceVariableList:
4141 return CodeCompletionContext::CCC_ObjCIvarList;
4142
4143 case Sema::PCC_Template:
4144 case Sema::PCC_MemberTemplate:
4145 if (S.CurContext->isFileContext())
4146 return CodeCompletionContext::CCC_TopLevel;
4147 if (S.CurContext->isRecord())
4148 return CodeCompletionContext::CCC_ClassStructUnion;
4149 return CodeCompletionContext::CCC_Other;
4150
4151 case Sema::PCC_RecoveryInFunction:
4152 return CodeCompletionContext::CCC_Recovery;
4153
4154 case Sema::PCC_ForInit:
4155 if (S.getLangOpts().CPlusPlus || S.getLangOpts().C99 ||
4156 S.getLangOpts().ObjC)
4157 return CodeCompletionContext::CCC_ParenthesizedExpression;
4158 else
4159 return CodeCompletionContext::CCC_Expression;
4160
4161 case Sema::PCC_Expression:
4162 return CodeCompletionContext::CCC_Expression;
4163 case Sema::PCC_Condition:
4164 return CodeCompletionContext(CodeCompletionContext::CCC_Expression,
4165 S.getASTContext().BoolTy);
4166
4167 case Sema::PCC_Statement:
4168 return CodeCompletionContext::CCC_Statement;
4169
4170 case Sema::PCC_Type:
4171 return CodeCompletionContext::CCC_Type;
4172
4173 case Sema::PCC_ParenthesizedExpression:
4174 return CodeCompletionContext::CCC_ParenthesizedExpression;
4175
4176 case Sema::PCC_LocalDeclarationSpecifiers:
4177 return CodeCompletionContext::CCC_Type;
4178 }
4179
4180 llvm_unreachable("Invalid ParserCompletionContext!")::llvm::llvm_unreachable_internal("Invalid ParserCompletionContext!"
, "clang/lib/Sema/SemaCodeComplete.cpp", 4180)
;
4181}
4182
4183/// If we're in a C++ virtual member function, add completion results
4184/// that invoke the functions we override, since it's common to invoke the
4185/// overridden function as well as adding new functionality.
4186///
4187/// \param S The semantic analysis object for which we are generating results.
4188///
4189/// \param InContext This context in which the nested-name-specifier preceding
4190/// the code-completion point
4191static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
4192 ResultBuilder &Results) {
4193 // Look through blocks.
4194 DeclContext *CurContext = S.CurContext;
4195 while (isa<BlockDecl>(CurContext))
4196 CurContext = CurContext->getParent();
4197
4198 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
4199 if (!Method || !Method->isVirtual())
4200 return;
4201
4202 // We need to have names for all of the parameters, if we're going to
4203 // generate a forwarding call.
4204 for (auto *P : Method->parameters())
4205 if (!P->getDeclName())
4206 return;
4207
4208 PrintingPolicy Policy = getCompletionPrintingPolicy(S);
4209 for (const CXXMethodDecl *Overridden : Method->overridden_methods()) {
4210 CodeCompletionBuilder Builder(Results.getAllocator(),
4211 Results.getCodeCompletionTUInfo());
4212 if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
4213 continue;
4214
4215 // If we need a nested-name-specifier, add one now.
4216 if (!InContext) {
4217 NestedNameSpecifier *NNS = getRequiredQualification(
4218 S.Context, CurContext, Overridden->getDeclContext());
4219 if (NNS) {
4220 std::string Str;
4221 llvm::raw_string_ostream OS(Str);
4222 NNS->print(OS, Policy);
4223 Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
4224 }
4225 } else if (!InContext->Equals(Overridden->getDeclContext()))
4226 continue;
4227
4228 Builder.AddTypedTextChunk(
4229 Results.getAllocator().CopyString(Overridden->getNameAsString()));
4230 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4231 bool FirstParam = true;
4232 for (auto *P : Method->parameters()) {
4233 if (FirstParam)
4234 FirstParam = false;
4235 else
4236 Builder.AddChunk(CodeCompletionString::CK_Comma);
4237
4238 Builder.AddPlaceholderChunk(
4239 Results.getAllocator().CopyString(P->getIdentifier()->getName()));
4240 }
4241 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4242 Results.AddResult(CodeCompletionResult(
4243 Builder.TakeString(), CCP_SuperCompletion, CXCursor_CXXMethod,
4244 CXAvailability_Available, Overridden));
4245 Results.Ignore(Overridden);
4246 }
4247}
4248
4249void Sema::CodeCompleteModuleImport(SourceLocation ImportLoc,
4250 ModuleIdPath Path) {
4251 typedef CodeCompletionResult Result;
4252 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4253 CodeCompleter->getCodeCompletionTUInfo(),
4254 CodeCompletionContext::CCC_Other);
4255 Results.EnterNewScope();
4256
4257 CodeCompletionAllocator &Allocator = Results.getAllocator();
4258 CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
4259 typedef CodeCompletionResult Result;
4260 if (Path.empty()) {
4261 // Enumerate all top-level modules.
4262 SmallVector<Module *, 8> Modules;
4263 PP.getHeaderSearchInfo().collectAllModules(Modules);
4264 for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
4265 Builder.AddTypedTextChunk(
4266 Builder.getAllocator().CopyString(Modules[I]->Name));
4267 Results.AddResult(Result(
4268 Builder.TakeString(), CCP_Declaration, CXCursor_ModuleImportDecl,
4269 Modules[I]->isAvailable() ? CXAvailability_Available
4270 : CXAvailability_NotAvailable));
4271 }
4272 } else if (getLangOpts().Modules) {
4273 // Load the named module.
4274 Module *Mod =
4275 PP.getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
4276 /*IsInclusionDirective=*/false);
4277 // Enumerate submodules.
4278 if (Mod) {
4279 for (Module::submodule_iterator Sub = Mod->submodule_begin(),
4280 SubEnd = Mod->submodule_end();
4281 Sub != SubEnd; ++Sub) {
4282
4283 Builder.AddTypedTextChunk(
4284 Builder.getAllocator().CopyString((*Sub)->Name));
4285 Results.AddResult(Result(
4286 Builder.TakeString(), CCP_Declaration, CXCursor_ModuleImportDecl,
4287 (*Sub)->isAvailable() ? CXAvailability_Available
4288 : CXAvailability_NotAvailable));
4289 }
4290 }
4291 }
4292 Results.ExitScope();
4293 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4294 Results.data(), Results.size());
4295}
4296
4297void Sema::CodeCompleteOrdinaryName(Scope *S,
4298 ParserCompletionContext CompletionContext) {
4299 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4300 CodeCompleter->getCodeCompletionTUInfo(),
4301 mapCodeCompletionContext(*this, CompletionContext));
4302 Results.EnterNewScope();
4303
4304 // Determine how to filter results, e.g., so that the names of
4305 // values (functions, enumerators, function templates, etc.) are
4306 // only allowed where we can have an expression.
4307 switch (CompletionContext) {
4308 case PCC_Namespace:
4309 case PCC_Class:
4310 case PCC_ObjCInterface:
4311 case PCC_ObjCImplementation:
4312 case PCC_ObjCInstanceVariableList:
4313 case PCC_Template:
4314 case PCC_MemberTemplate:
4315 case PCC_Type:
4316 case PCC_LocalDeclarationSpecifiers:
4317 Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
4318 break;
4319
4320 case PCC_Statement:
4321 case PCC_ParenthesizedExpression:
4322 case PCC_Expression:
4323 case PCC_ForInit:
4324 case PCC_Condition:
4325 if (WantTypesInContext(CompletionContext, getLangOpts()))
4326 Results.setFilter(&ResultBuilder::IsOrdinaryName);
4327 else
4328 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
4329
4330 if (getLangOpts().CPlusPlus)
4331 MaybeAddOverrideCalls(*this, /*InContext=*/nullptr, Results);
4332 break;
4333
4334 case PCC_RecoveryInFunction:
4335 // Unfiltered
4336 break;
4337 }
4338
4339 // If we are in a C++ non-static member function, check the qualifiers on
4340 // the member function to filter/prioritize the results list.
4341 auto ThisType = getCurrentThisType();
4342 if (!ThisType.isNull())
4343 Results.setObjectTypeQualifiers(ThisType->getPointeeType().getQualifiers(),
4344 VK_LValue);
4345
4346 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4347 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4348 CodeCompleter->includeGlobals(),
4349 CodeCompleter->loadExternal());
4350
4351 AddOrdinaryNameResults(CompletionContext, S, *this, Results);
4352 Results.ExitScope();
4353
4354 switch (CompletionContext) {
4355 case PCC_ParenthesizedExpression:
4356 case PCC_Expression:
4357 case PCC_Statement:
4358 case PCC_RecoveryInFunction:
4359 if (S->getFnParent())
4360 AddPrettyFunctionResults(getLangOpts(), Results);
4361 break;
4362
4363 case PCC_Namespace:
4364 case PCC_Class:
4365 case PCC_ObjCInterface:
4366 case PCC_ObjCImplementation:
4367 case PCC_ObjCInstanceVariableList:
4368 case PCC_Template:
4369 case PCC_MemberTemplate:
4370 case PCC_ForInit:
4371 case PCC_Condition:
4372 case PCC_Type:
4373 case PCC_LocalDeclarationSpecifiers:
4374 break;
4375 }
4376
4377 if (CodeCompleter->includeMacros())
4378 AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false);
4379
4380 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4381 Results.data(), Results.size());
4382}
4383
4384static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
4385 ParsedType Receiver,
4386 ArrayRef<IdentifierInfo *> SelIdents,
4387 bool AtArgumentExpression, bool IsSuper,
4388 ResultBuilder &Results);
4389
4390void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
4391 bool AllowNonIdentifiers,
4392 bool AllowNestedNameSpecifiers) {
4393 typedef CodeCompletionResult Result;
4394 ResultBuilder Results(
4395 *this, CodeCompleter->getAllocator(),
4396 CodeCompleter->getCodeCompletionTUInfo(),
4397 AllowNestedNameSpecifiers
4398 // FIXME: Try to separate codepath leading here to deduce whether we
4399 // need an existing symbol or a new one.
4400 ? CodeCompletionContext::CCC_SymbolOrNewName
4401 : CodeCompletionContext::CCC_NewName);
4402 Results.EnterNewScope();
4403
4404 // Type qualifiers can come after names.
4405 Results.AddResult(Result("const"));
4406 Results.AddResult(Result("volatile"));
4407 if (getLangOpts().C99)
4408 Results.AddResult(Result("restrict"));
4409
4410 if (getLangOpts().CPlusPlus) {
4411 if (getLangOpts().CPlusPlus11 &&
4412 (DS.getTypeSpecType() == DeclSpec::TST_class ||
4413 DS.getTypeSpecType() == DeclSpec::TST_struct))
4414 Results.AddResult("final");
4415
4416 if (AllowNonIdentifiers) {
4417 Results.AddResult(Result("operator"));
4418 }
4419
4420 // Add nested-name-specifiers.
4421 if (AllowNestedNameSpecifiers) {
4422 Results.allowNestedNameSpecifiers();
4423 Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
4424 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4425 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
4426 CodeCompleter->includeGlobals(),
4427 CodeCompleter->loadExternal());
4428 Results.setFilter(nullptr);
4429 }
4430 }
4431 Results.ExitScope();
4432
4433 // If we're in a context where we might have an expression (rather than a
4434 // declaration), and what we've seen so far is an Objective-C type that could
4435 // be a receiver of a class message, this may be a class message send with
4436 // the initial opening bracket '[' missing. Add appropriate completions.
4437 if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
4438 DS.getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
4439 DS.getTypeSpecType() == DeclSpec::TST_typename &&
4440 DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
4441 DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
4442 !DS.isTypeAltiVecVector() && S &&
4443 (S->getFlags() & Scope::DeclScope) != 0 &&
4444 (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
4445 Scope::FunctionPrototypeScope | Scope::AtCatchScope)) ==
4446 0) {
4447 ParsedType T = DS.getRepAsType();
4448 if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
4449 AddClassMessageCompletions(*this, S, T, None, false, false, Results);
4450 }
4451
4452 // Note that we intentionally suppress macro results here, since we do not
4453 // encourage using macros to produce the names of entities.
4454
4455 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4456 Results.data(), Results.size());
4457}
4458
4459static const char *underscoreAttrScope(llvm::StringRef Scope) {
4460 if (Scope == "clang")
4461 return "_Clang";
4462 if (Scope == "gnu")
4463 return "__gnu__";
4464 return nullptr;
4465}
4466
4467static const char *noUnderscoreAttrScope(llvm::StringRef Scope) {
4468 if (Scope == "_Clang")
4469 return "clang";
4470 if (Scope == "__gnu__")
4471 return "gnu";
4472 return nullptr;
4473}
4474
4475void Sema::CodeCompleteAttribute(AttributeCommonInfo::Syntax Syntax,
4476 AttributeCompletion Completion,
4477 const IdentifierInfo *InScope) {
4478 if (Completion == AttributeCompletion::None)
4479 return;
4480 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
4481 CodeCompleter->getCodeCompletionTUInfo(),
4482 CodeCompletionContext::CCC_Attribute);
4483
4484 // We're going to iterate over the normalized spellings of the attribute.
4485 // These don't include "underscore guarding": the normalized spelling is
4486 // clang::foo but you can also write _Clang::__foo__.
4487 //
4488 // (Clang supports a mix like clang::__foo__ but we won't suggest it: either
4489 // you care about clashing with macros or you don't).
4490 //
4491 // So if we're already in a scope, we determine its canonical spellings
4492 // (for comparison with normalized attr spelling) and remember whether it was
4493 // underscore-guarded (so we know how to spell contained attributes).
4494 llvm::StringRef InScopeName;
4495 bool InScopeUnderscore = false;
4496 if (InScope) {
4497 InScopeName = InScope->getName();
4498 if (const char *NoUnderscore = noUnderscoreAttrScope(InScopeName)) {
4499 InScopeName = NoUnderscore;
4500 InScopeUnderscore = true;
4501 }
4502 }
4503 bool SyntaxSupportsGuards = Syntax == AttributeCommonInfo::AS_GNU ||
4504 Syntax == AttributeCommonInfo::AS_CXX11 ||
4505 Syntax == AttributeCommonInfo::AS_C2x;
4506
4507 llvm::DenseSet<llvm::StringRef> FoundScopes;
4508 auto AddCompletions = [&](const ParsedAttrInfo &A) {
4509 if (A.IsTargetSpecific && !A.existsInTarget(Context.getTargetInfo()))
4510 return;
4511 if (!A.acceptsLangOpts(getLangOpts()))
4512 return;
4513 for (const auto &S : A.Spellings) {
4514 if (S.Syntax != Syntax)
4515 continue;
4516 llvm::StringRef Name = S.NormalizedFullName;
4517 llvm::StringRef Scope;
4518 if ((Syntax == AttributeCommonInfo::AS_CXX11 ||
4519 Syntax == AttributeCommonInfo::AS_C2x)) {
4520 std::tie(Scope, Name) = Name.split("::");
4521 if (Name.empty()) // oops, unscoped
4522 std::swap(Name, Scope);
4523 }
4524
4525 // Do we just want a list of scopes rather than attributes?
4526 if (Completion == AttributeCompletion::Scope) {
4527 // Make sure to emit each scope only once.
4528 if (!Scope.empty() && FoundScopes.insert(Scope).second) {
4529 Results.AddResult(
4530 CodeCompletionResult(Results.getAllocator().CopyString(Scope)));
4531 // Include alternate form (__gnu__ instead of gnu).
4532 if (const char *Scope2 = underscoreAttrScope(Scope))
4533 Results.AddResult(CodeCompletionResult(Scope2));
4534 }
4535 continue;
4536 }
4537
4538 // If a scope was specified, it must match but we don't need to print it.
4539 if (!InScopeName.empty()) {
4540 if (Scope != InScopeName)
4541 continue;
4542 Scope = "";
4543 }
4544
4545 auto Add = [&](llvm::StringRef Scope, llvm::StringRef Name,
4546 bool Underscores) {
4547 CodeCompletionBuilder Builder(Results.getAllocator(),
4548 Results.getCodeCompletionTUInfo());
4549 llvm::SmallString<32> Text;
4550 if (!Scope.empty()) {
4551 Text.append(Scope);
4552 Text.append("::");
4553 }
4554 if (Underscores)
4555 Text.append("__");
4556 Text.append(Name);
4557 if (Underscores)
4558 Text.append("__");
4559 Builder.AddTypedTextChunk(Results.getAllocator().CopyString(Text));
4560
4561 if (!A.ArgNames.empty()) {
4562 Builder.AddChunk(CodeCompletionString::CK_LeftParen, "(");
4563 bool First = true;
4564 for (const char *Arg : A.ArgNames) {
4565 if (!First)
4566 Builder.AddChunk(CodeCompletionString::CK_Comma, ", ");
4567 First = false;
4568 Builder.AddPlaceholderChunk(Arg);
4569 }
4570 Builder.AddChunk(CodeCompletionString::CK_RightParen, ")");
4571 }
4572
4573 Results.AddResult(Builder.TakeString());
4574 };
4575
4576 // Generate the non-underscore-guarded result.
4577 // Note this is (a suffix of) the NormalizedFullName, no need to copy.
4578 // If an underscore-guarded scope was specified, only the
4579 // underscore-guarded attribute name is relevant.
4580 if (!InScopeUnderscore)
4581 Add(Scope, Name, /*Underscores=*/false);
4582
4583 // Generate the underscore-guarded version, for syntaxes that support it.
4584 // We skip this if the scope was already spelled and not guarded, or
4585 // we must spell it and can't guard it.
4586 if (!(InScope && !InScopeUnderscore) && SyntaxSupportsGuards) {
4587 llvm::SmallString<32> Guarded;
4588 if (Scope.empty()) {
4589 Add(Scope, Name, /*Underscores=*/true);
4590 } else {
4591 const char *GuardedScope = underscoreAttrScope(Scope);
4592 if (!GuardedScope)
4593 continue;
4594 Add(GuardedScope, Name, /*Underscores=*/true);
4595 }
4596 }
4597
4598 // It may be nice to include the Kind so we can look up the docs later.
4599 }
4600 };
4601
4602 for (const auto *A : ParsedAttrInfo::getAllBuiltin())
4603 AddCompletions(*A);
4604 for (const auto &Entry : ParsedAttrInfoRegistry::entries())
4605 AddCompletions(*Entry.instantiate());
4606
4607 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4608 Results.data(), Results.size());
4609}
4610
4611struct Sema::CodeCompleteExpressionData {
4612 CodeCompleteExpressionData(QualType PreferredType = QualType(),
4613 bool IsParenthesized = false)
4614 : PreferredType(PreferredType), IntegralConstantExpression(false),
4615 ObjCCollection(false), IsParenthesized(IsParenthesized) {}
4616
4617 QualType PreferredType;
4618 bool IntegralConstantExpression;
4619 bool ObjCCollection;
4620 bool IsParenthesized;
4621 SmallVector<Decl *, 4> IgnoreDecls;
4622};
4623
4624namespace {
4625/// Information that allows to avoid completing redundant enumerators.
4626struct CoveredEnumerators {
4627 llvm::SmallPtrSet<EnumConstantDecl *, 8> Seen;
4628 NestedNameSpecifier *SuggestedQualifier = nullptr;
4629};
4630} // namespace
4631
4632static void AddEnumerators(ResultBuilder &Results, ASTContext &Context,
4633 EnumDecl *Enum, DeclContext *CurContext,
4634 const CoveredEnumerators &Enumerators) {
4635 NestedNameSpecifier *Qualifier = Enumerators.SuggestedQualifier;
4636 if (Context.getLangOpts().CPlusPlus && !Qualifier && Enumerators.Seen.empty()) {
4637 // If there are no prior enumerators in C++, check whether we have to
4638 // qualify the names of the enumerators that we suggest, because they
4639 // may not be visible in this scope.
4640 Qualifier = getRequiredQualification(Context, CurContext, Enum);
4641 }
4642
4643 Results.EnterNewScope();
4644 for (auto *E : Enum->enumerators()) {
4645 if (Enumerators.Seen.count(E))
4646 continue;
4647
4648 CodeCompletionResult R(E, CCP_EnumInCase, Qualifier);
4649 Results.AddResult(R, CurContext, nullptr, false);
4650 }
4651 Results.ExitScope();
4652}
4653
4654/// Try to find a corresponding FunctionProtoType for function-like types (e.g.
4655/// function pointers, std::function, etc).
4656static const FunctionProtoType *TryDeconstructFunctionLike(QualType T) {
4657 assert(!T.isNull())(static_cast <bool> (!T.isNull()) ? void (0) : __assert_fail
("!T.isNull()", "clang/lib/Sema/SemaCodeComplete.cpp", 4657,
__extension__ __PRETTY_FUNCTION__))
;
4658 // Try to extract first template argument from std::function<> and similar.
4659 // Note we only handle the sugared types, they closely match what users wrote.
4660 // We explicitly choose to not handle ClassTemplateSpecializationDecl.
4661 if (auto *Specialization = T->getAs<TemplateSpecializationType>()) {
4662 if (Specialization->getNumArgs() != 1)
4663 return nullptr;
4664 const TemplateArgument &Argument = Specialization->getArg(0);
4665 if (Argument.getKind() != TemplateArgument::Type)
4666 return nullptr;
4667 return Argument.getAsType()->getAs<FunctionProtoType>();
4668 }
4669 // Handle other cases.
4670 if (T->isPointerType())
4671 T = T->getPointeeType();
4672 return T->getAs<FunctionProtoType>();
4673}
4674
4675/// Adds a pattern completion for a lambda expression with the specified
4676/// parameter types and placeholders for parameter names.
4677static void AddLambdaCompletion(ResultBuilder &Results,
4678 llvm::ArrayRef<QualType> Parameters,
4679 const LangOptions &LangOpts) {
4680 if (!Results.includeCodePatterns())
4681 return;
4682 CodeCompletionBuilder Completion(Results.getAllocator(),
4683 Results.getCodeCompletionTUInfo());
4684 // [](<parameters>) {}
4685 Completion.AddChunk(CodeCompletionString::CK_LeftBracket);
4686 Completion.AddPlaceholderChunk("=");
4687 Completion.AddChunk(CodeCompletionString::CK_RightBracket);
4688 if (!Parameters.empty()) {
4689 Completion.AddChunk(CodeCompletionString::CK_LeftParen);
4690 bool First = true;
4691 for (auto Parameter : Parameters) {
4692 if (!First)
4693 Completion.AddChunk(CodeCompletionString::ChunkKind::CK_Comma);
4694 else
4695 First = false;
4696
4697 constexpr llvm::StringLiteral NamePlaceholder = "!#!NAME_GOES_HERE!#!";
4698 std::string Type = std::string(NamePlaceholder);
4699 Parameter.getAsStringInternal(Type, PrintingPolicy(LangOpts));
4700 llvm::StringRef Prefix, Suffix;
4701 std::tie(Prefix, Suffix) = llvm::StringRef(Type).split(NamePlaceholder);
4702 Prefix = Prefix.rtrim();
4703 Suffix = Suffix.ltrim();
4704
4705 Completion.AddTextChunk(Completion.getAllocator().CopyString(Prefix));
4706 Completion.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4707 Completion.AddPlaceholderChunk("parameter");
4708 Completion.AddTextChunk(Completion.getAllocator().CopyString(Suffix));
4709 };
4710 Completion.AddChunk(CodeCompletionString::CK_RightParen);
4711 }
4712 Completion.AddChunk(clang::CodeCompletionString::CK_HorizontalSpace);
4713 Completion.AddChunk(CodeCompletionString::CK_LeftBrace);
4714 Completion.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4715 Completion.AddPlaceholderChunk("body");
4716 Completion.AddChunk(CodeCompletionString::CK_HorizontalSpace);
4717 Completion.AddChunk(CodeCompletionString::CK_RightBrace);
4718
4719 Results.AddResult(Completion.TakeString());
4720}
4721
4722/// Perform code-completion in an expression context when we know what
4723/// type we're looking for.
4724void Sema::CodeCompleteExpression(Scope *S,
4725 const CodeCompleteExpressionData &Data) {
4726 ResultBuilder Results(
4727 *this, CodeCompleter->getAllocator(),
4728 CodeCompleter->getCodeCompletionTUInfo(),
4729 CodeCompletionContext(
4730 Data.IsParenthesized
4731 ? CodeCompletionContext::CCC_ParenthesizedExpression
4732 : CodeCompletionContext::CCC_Expression,
4733 Data.PreferredType));
4734 auto PCC =
4735 Data.IsParenthesized ? PCC_ParenthesizedExpression : PCC_Expression;
4736 if (Data.ObjCCollection)
4737 Results.setFilter(&ResultBuilder::IsObjCCollection);
4738 else if (Data.IntegralConstantExpression)
4739 Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
4740 else if (WantTypesInContext(PCC, getLangOpts()))
4741 Results.setFilter(&ResultBuilder::IsOrdinaryName);
4742 else
4743 Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
4744
4745 if (!Data.PreferredType.isNull())
4746 Results.setPreferredType(Data.PreferredType.getNonReferenceType());
4747
4748 // Ignore any declarations that we were told that we don't care about.
4749 for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
4750 Results.Ignore(Data.IgnoreDecls[I]);
4751
4752 CodeCompletionDeclConsumer Consumer(Results, CurContext);
4753 LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
4754 CodeCompleter->includeGlobals(),
4755 CodeCompleter->loadExternal());
4756
4757 Results.EnterNewScope();
4758 AddOrdinaryNameResults(PCC, S, *this, Results);
4759 Results.ExitScope();
4760
4761 bool PreferredTypeIsPointer = false;
4762 if (!Data.PreferredType.isNull()) {
4763 PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType() ||
4764 Data.PreferredType->isMemberPointerType() ||
4765 Data.PreferredType->isBlockPointerType();
4766 if (Data.PreferredType->isEnumeralType()) {
4767 EnumDecl *Enum = Data.PreferredType->castAs<EnumType>()->getDecl();
4768 if (auto *Def = Enum->getDefinition())
4769 Enum = Def;
4770 // FIXME: collect covered enumerators in cases like:
4771 // if (x == my_enum::one) { ... } else if (x == ^) {}
4772 AddEnumerators(Results, Context, Enum, CurContext, CoveredEnumerators());
4773 }
4774 }
4775
4776 if (S->getFnParent() && !Data.ObjCCollection &&
4777 !Data.IntegralConstantExpression)
4778 AddPrettyFunctionResults(getLangOpts(), Results);
4779
4780 if (CodeCompleter->includeMacros())
4781 AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false,
4782 PreferredTypeIsPointer);
4783
4784 // Complete a lambda expression when preferred type is a function.
4785 if (!Data.PreferredType.isNull() && getLangOpts().CPlusPlus11) {
4786 if (const FunctionProtoType *F =
4787 TryDeconstructFunctionLike(Data.PreferredType))
4788 AddLambdaCompletion(Results, F->getParamTypes(), getLangOpts());
4789 }
4790
4791 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
4792 Results.data(), Results.size());
4793}
4794
4795void Sema::CodeCompleteExpression(Scope *S, QualType PreferredType,
4796 bool IsParenthesized) {
4797 return CodeCompleteExpression(
4798 S, CodeCompleteExpressionData(PreferredType, IsParenthesized));
4799}
4800
4801void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E,
4802 QualType PreferredType) {
4803 if (E.isInvalid())
4804 CodeCompleteExpression(S, PreferredType);
4805 else if (getLangOpts().ObjC)
4806 CodeCompleteObjCInstanceMessage(S, E.get(), None, false);
4807}
4808
4809/// The set of properties that have already been added, referenced by
4810/// property name.
4811typedef llvm::SmallPtrSet<IdentifierInfo *, 16> AddedPropertiesSet;
4812
4813/// Retrieve the container definition, if any?
4814static ObjCContainerDecl *getContainerDef(ObjCContainerDecl *Container) {
4815 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4816 if (Interface->hasDefinition())
4817 return Interface->getDefinition();
4818
4819 return Interface;
4820 }
4821
4822 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4823 if (Protocol->hasDefinition())
4824 return Protocol->getDefinition();
4825
4826 return Protocol;
4827 }
4828 return Container;
4829}
4830
4831/// Adds a block invocation code completion result for the given block
4832/// declaration \p BD.
4833static void AddObjCBlockCall(ASTContext &Context, const PrintingPolicy &Policy,
4834 CodeCompletionBuilder &Builder,
4835 const NamedDecl *BD,
4836 const FunctionTypeLoc &BlockLoc,
4837 const FunctionProtoTypeLoc &BlockProtoLoc) {
4838 Builder.AddResultTypeChunk(
4839 GetCompletionTypeString(BlockLoc.getReturnLoc().getType(), Context,
4840 Policy, Builder.getAllocator()));
4841
4842 AddTypedNameChunk(Context, Policy, BD, Builder);
4843 Builder.AddChunk(CodeCompletionString::CK_LeftParen);
4844
4845 if (BlockProtoLoc && BlockProtoLoc.getTypePtr()->isVariadic()) {
4846 Builder.AddPlaceholderChunk("...");
4847 } else {
4848 for (unsigned I = 0, N = BlockLoc.getNumParams(); I != N; ++I) {
4849 if (I)
4850 Builder.AddChunk(CodeCompletionString::CK_Comma);
4851
4852 // Format the placeholder string.
4853 std::string PlaceholderStr =
4854 FormatFunctionParameter(Policy, BlockLoc.getParam(I));
4855
4856 if (I == N - 1 && BlockProtoLoc &&
4857 BlockProtoLoc.getTypePtr()->isVariadic())
4858 PlaceholderStr += ", ...";
4859
4860 // Add the placeholder string.
4861 Builder.AddPlaceholderChunk(
4862 Builder.getAllocator().CopyString(PlaceholderStr));
4863 }
4864 }
4865
4866 Builder.AddChunk(CodeCompletionString::CK_RightParen);
4867}
4868
4869static void
4870AddObjCProperties(const CodeCompletionContext &CCContext,
4871 ObjCContainerDecl *Container, bool AllowCategories,
4872 bool AllowNullaryMethods, DeclContext *CurContext,
4873 AddedPropertiesSet &AddedProperties, ResultBuilder &Results,
4874 bool IsBaseExprStatement = false,
4875 bool IsClassProperty = false, bool InOriginalClass = true) {
4876 typedef CodeCompletionResult Result;
4877
4878 // Retrieve the definition.
4879 Container = getContainerDef(Container);
4880
4881 // Add properties in this container.
4882 const auto AddProperty = [&](const ObjCPropertyDecl *P) {
4883 if (!AddedProperties.insert(P->getIdentifier()).second)
4884 return;
4885
4886 // FIXME: Provide block invocation completion for non-statement
4887 // expressions.
4888 if (!P->getType().getTypePtr()->isBlockPointerType() ||
4889 !IsBaseExprStatement) {
4890 Result R = Result(P, Results.getBasePriority(P), nullptr);
4891 if (!InOriginalClass)
4892 setInBaseClass(R);
4893 Results.MaybeAddResult(R, CurContext);
4894 return;
4895 }
4896
4897 // Block setter and invocation completion is provided only when we are able
4898 // to find the FunctionProtoTypeLoc with parameter names for the block.
4899 FunctionTypeLoc BlockLoc;
4900 FunctionProtoTypeLoc BlockProtoLoc;
4901 findTypeLocationForBlockDecl(P->getTypeSourceInfo(), BlockLoc,
4902 BlockProtoLoc);
4903 if (!BlockLoc) {
4904 Result R = Result(P, Results.getBasePriority(P), nullptr);
4905 if (!InOriginalClass)
4906 setInBaseClass(R);
4907 Results.MaybeAddResult(R, CurContext);
4908 return;
4909 }
4910
4911 // The default completion result for block properties should be the block
4912 // invocation completion when the base expression is a statement.
4913 CodeCompletionBuilder Builder(Results.getAllocator(),
4914 Results.getCodeCompletionTUInfo());
4915 AddObjCBlockCall(Container->getASTContext(),
4916 getCompletionPrintingPolicy(Results.getSema()), Builder, P,
4917 BlockLoc, BlockProtoLoc);
4918 Result R = Result(Builder.TakeString(), P, Results.getBasePriority(P));
4919 if (!InOriginalClass)
4920 setInBaseClass(R);
4921 Results.MaybeAddResult(R, CurContext);
4922
4923 // Provide additional block setter completion iff the base expression is a
4924 // statement and the block property is mutable.
4925 if (!P->isReadOnly()) {
4926 CodeCompletionBuilder Builder(Results.getAllocator(),
4927 Results.getCodeCompletionTUInfo());
4928 AddResultTypeChunk(Container->getASTContext(),
4929 getCompletionPrintingPolicy(Results.getSema()), P,
4930 CCContext.getBaseType(), Builder);
4931 Builder.AddTypedTextChunk(
4932 Results.getAllocator().CopyString(P->getName()));
4933 Builder.AddChunk(CodeCompletionString::CK_Equal);
4934
4935 std::string PlaceholderStr = formatBlockPlaceholder(
4936 getCompletionPrintingPolicy(Results.getSema()), P, BlockLoc,
4937 BlockProtoLoc, /*SuppressBlockName=*/true);
4938 // Add the placeholder string.
4939 Builder.AddPlaceholderChunk(
4940 Builder.getAllocator().CopyString(PlaceholderStr));
4941
4942 // When completing blocks properties that return void the default
4943 // property completion result should show up before the setter,
4944 // otherwise the setter completion should show up before the default
4945 // property completion, as we normally want to use the result of the
4946 // call.
4947 Result R =
4948 Result(Builder.TakeString(), P,
4949 Results.getBasePriority(P) +
4950 (BlockLoc.getTypePtr()->getReturnType()->isVoidType()
4951 ? CCD_BlockPropertySetter
4952 : -CCD_BlockPropertySetter));
4953 if (!InOriginalClass)
4954 setInBaseClass(R);
4955 Results.MaybeAddResult(R, CurContext);
4956 }
4957 };
4958
4959 if (IsClassProperty) {
4960 for (const auto *P : Container->class_properties())
4961 AddProperty(P);
4962 } else {
4963 for (const auto *P : Container->instance_properties())
4964 AddProperty(P);
4965 }
4966
4967 // Add nullary methods or implicit class properties
4968 if (AllowNullaryMethods) {
4969 ASTContext &Context = Container->getASTContext();
4970 PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
4971 // Adds a method result
4972 const auto AddMethod = [&](const ObjCMethodDecl *M) {
4973 IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0);
4974 if (!Name)
4975 return;
4976 if (!AddedProperties.insert(Name).second)
4977 return;
4978 CodeCompletionBuilder Builder(Results.getAllocator(),
4979 Results.getCodeCompletionTUInfo());
4980 AddResultTypeChunk(Context, Policy, M, CCContext.getBaseType(), Builder);
4981 Builder.AddTypedTextChunk(
4982 Results.getAllocator().CopyString(Name->getName()));
4983 Result R = Result(Builder.TakeString(), M,
4984 CCP_MemberDeclaration + CCD_MethodAsProperty);
4985 if (!InOriginalClass)
4986 setInBaseClass(R);
4987 Results.MaybeAddResult(R, CurContext);
4988 };
4989
4990 if (IsClassProperty) {
4991 for (const auto *M : Container->methods()) {
4992 // Gather the class method that can be used as implicit property
4993 // getters. Methods with arguments or methods that return void aren't
4994 // added to the results as they can't be used as a getter.
4995 if (!M->getSelector().isUnarySelector() ||
4996 M->getReturnType()->isVoidType() || M->isInstanceMethod())
4997 continue;
4998 AddMethod(M);
4999 }
5000 } else {
5001 for (auto *M : Container->methods()) {
5002 if (M->getSelector().isUnarySelector())
5003 AddMethod(M);
5004 }
5005 }
5006 }
5007
5008 // Add properties in referenced protocols.
5009 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
5010 for (auto *P : Protocol->protocols())
5011 AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
5012 CurContext, AddedProperties, Results,
5013 IsBaseExprStatement, IsClassProperty,
5014 /*InOriginalClass*/ false);
5015 } else if (ObjCInterfaceDecl *IFace =
5016 dyn_cast<ObjCInterfaceDecl>(Container)) {
5017 if (AllowCategories) {
5018 // Look through categories.
5019 for (auto *Cat : IFace->known_categories())
5020 AddObjCProperties(CCContext, Cat, AllowCategories, AllowNullaryMethods,
5021 CurContext, AddedProperties, Results,
5022 IsBaseExprStatement, IsClassProperty,
5023 InOriginalClass);
5024 }
5025
5026 // Look through protocols.
5027 for (auto *I : IFace->all_referenced_protocols())
5028 AddObjCProperties(CCContext, I, AllowCategories, AllowNullaryMethods,
5029 CurContext, AddedProperties, Results,
5030 IsBaseExprStatement, IsClassProperty,
5031 /*InOriginalClass*/ false);
5032
5033 // Look in the superclass.
5034 if (IFace->getSuperClass())
5035 AddObjCProperties(CCContext, IFace->getSuperClass(), AllowCategories,
5036 AllowNullaryMethods, CurContext, AddedProperties,
5037 Results, IsBaseExprStatement, IsClassProperty,
5038 /*InOriginalClass*/ false);
5039 } else if (const auto *Category =
5040 dyn_cast<ObjCCategoryDecl>(Container)) {
5041 // Look through protocols.
5042 for (auto *P : Category->protocols())
5043 AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
5044 CurContext, AddedProperties, Results,
5045 IsBaseExprStatement, IsClassProperty,
5046 /*InOriginalClass*/ false);
5047 }
5048}
5049
5050static void AddRecordMembersCompletionResults(
5051 Sema &SemaRef, ResultBuilder &Results, Scope *S, QualType BaseType,
5052 ExprValueKind BaseKind, RecordDecl *RD, Optional<FixItHint> AccessOpFixIt) {
5053 // Indicate that we are performing a member access, and the cv-qualifiers
5054 // for the base object type.
5055 Results.setObjectTypeQualifiers(BaseType.getQualifiers(), BaseKind);
5056
5057 // Access to a C/C++ class, struct, or union.
5058 Results.allowNestedNameSpecifiers();
5059 std::vector<FixItHint> FixIts;
5060 if (AccessOpFixIt)
5061 FixIts.emplace_back(*AccessOpFixIt);
5062 CodeCompletionDeclConsumer Consumer(Results, RD, BaseType, std::move(FixIts));
5063 SemaRef.LookupVisibleDecls(RD, Sema::LookupMemberName, Consumer,
5064 SemaRef.CodeCompleter->includeGlobals(),
5065 /*IncludeDependentBases=*/true,
5066 SemaRef.CodeCompleter->loadExternal());
5067
5068 if (SemaRef.getLangOpts().CPlusPlus) {
5069 if (!Results.empty()) {
5070 // The "template" keyword can follow "->" or "." in the grammar.
5071 // However, we only want to suggest the template keyword if something
5072 // is dependent.
5073 bool IsDependent = BaseType->isDependentType();
5074 if (!IsDependent) {
5075 for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
5076 if (DeclContext *Ctx = DepScope->getEntity()) {
5077 IsDependent = Ctx->isDependentContext();
5078 break;
5079 }
5080 }
5081
5082 if (IsDependent)
5083 Results.AddResult(CodeCompletionResult("template"));
5084 }
5085 }
5086}
5087
5088// Returns the RecordDecl inside the BaseType, falling back to primary template
5089// in case of specializations. Since we might not have a decl for the
5090// instantiation/specialization yet, e.g. dependent code.
5091static RecordDecl *getAsRecordDecl(const QualType BaseType) {
5092 if (auto *RD = BaseType->getAsRecordDecl()) {
5093 if (const auto *CTSD =
5094 llvm::dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
5095 // Template might not be instantiated yet, fall back to primary template
5096 // in such cases.
5097 if (CTSD->getTemplateSpecializationKind() == TSK_Undeclared)
5098 RD = CTSD->getSpecializedTemplate()->getTemplatedDecl();
5099 }
5100 return RD;
5101 }
5102
5103 if (const auto *TST = BaseType->getAs<TemplateSpecializationType>()) {
5104 if (const auto *TD = dyn_cast_or_null<ClassTemplateDecl>(
5105 TST->getTemplateName().getAsTemplateDecl())) {
5106 return TD->getTemplatedDecl();
5107 }
5108 }
5109
5110 return nullptr;
5111}
5112
5113namespace {
5114// Collects completion-relevant information about a concept-constrainted type T.
5115// In particular, examines the constraint expressions to find members of T.
5116//
5117// The design is very simple: we walk down each constraint looking for
5118// expressions of the form T.foo().
5119// If we're extra lucky, the return type is specified.
5120// We don't do any clever handling of && or || in constraint expressions, we
5121// take members from both branches.
5122//
5123// For example, given:
5124// template <class T> concept X = requires (T t, string& s) { t.print(s); };
5125// template <X U> void foo(U u) { u.^ }
5126// We want to suggest the inferred member function 'print(string)'.
5127// We see that u has type U, so X<U> holds.
5128// X<U> requires t.print(s) to be valid, where t has type U (substituted for T).
5129// By looking at the CallExpr we find the signature of print().
5130//
5131// While we tend to know in advance which kind of members (access via . -> ::)
5132// we want, it's simpler just to gather them all and post-filter.
5133//
5134// FIXME: some of this machinery could be used for non-concept type-parms too,
5135// enabling completion for type parameters based on other uses of that param.
5136//
5137// FIXME: there are other cases where a type can be constrained by a concept,
5138// e.g. inside `if constexpr(ConceptSpecializationExpr) { ... }`
5139class ConceptInfo {
5140public:
5141 // Describes a likely member of a type, inferred by concept constraints.
5142 // Offered as a code completion for T. T-> and T:: contexts.
5143 struct Member {
5144 // Always non-null: we only handle members with ordinary identifier names.
5145 const IdentifierInfo *Name = nullptr;
5146 // Set for functions we've seen called.
5147 // We don't have the declared parameter types, only the actual types of
5148 // arguments we've seen. These are still valuable, as it's hard to render
5149 // a useful function completion with neither parameter types nor names!
5150 llvm::Optional<SmallVector<QualType, 1>> ArgTypes;
5151 // Whether this is accessed as T.member, T->member, or T::member.
5152 enum AccessOperator {
5153 Colons,
5154 Arrow,
5155 Dot,
5156 } Operator = Dot;
5157 // What's known about the type of a variable or return type of a function.
5158 const TypeConstraint *ResultType = nullptr;
5159 // FIXME: also track:
5160 // - kind of entity (function/variable/type), to expose structured results
5161 // - template args kinds/types, as a proxy for template params
5162
5163 // For now we simply return these results as "pattern" strings.
5164 CodeCompletionString *render(Sema &S, CodeCompletionAllocator &Alloc,
5165 CodeCompletionTUInfo &Info) const {
5166 CodeCompletionBuilder B(Alloc, Info);
5167 // Result type
5168 if (ResultType) {
5169 std::string AsString;
5170 {
5171 llvm::raw_string_ostream OS(AsString);
5172 QualType ExactType = deduceType(*ResultType);
5173 if (!ExactType.isNull())
5174 ExactType.print(OS, getCompletionPrintingPolicy(S));
5175 else
5176 ResultType->print(OS, getCompletionPrintingPolicy(S));
5177 }
5178 B.AddResultTypeChunk(Alloc.CopyString(AsString));
5179 }
5180 // Member name
5181 B.AddTypedTextChunk(Alloc.CopyString(Name->getName()));
5182 // Function argument list
5183 if (ArgTypes) {
5184 B.AddChunk(clang::CodeCompletionString::CK_LeftParen);
5185 bool First = true;
5186 for (QualType Arg : *ArgTypes) {
5187 if (First)
5188 First = false;
5189 else {
5190 B.AddChunk(clang::CodeCompletionString::CK_Comma);
5191 B.AddChunk(clang::CodeCompletionString::CK_HorizontalSpace);
5192 }
5193 B.AddPlaceholderChunk(Alloc.CopyString(
5194 Arg.getAsString(getCompletionPrintingPolicy(S))));
5195 }
5196 B.AddChunk(clang::CodeCompletionString::CK_RightParen);
5197 }
5198 return B.TakeString();
5199 }
5200 };
5201
5202 // BaseType is the type parameter T to infer members from.
5203 // T must be accessible within S, as we use it to find the template entity
5204 // that T is attached to in order to gather the relevant constraints.
5205 ConceptInfo(const TemplateTypeParmType &BaseType, Scope *S) {
5206 auto *TemplatedEntity = getTemplatedEntity(BaseType.getDecl(), S);
5207 for (const Expr *E : constraintsForTemplatedEntity(TemplatedEntity))
5208 believe(E, &BaseType);
5209 }
5210
5211 std::vector<Member> members() {
5212 std::vector<Member> Results;
5213 for (const auto &E : this->Results)
5214 Results.push_back(E.second);
5215 llvm::sort(Results, [](const Member &L, const Member &R) {
5216 return L.Name->getName() < R.Name->getName();
5217 });
5218 return Results;
5219 }
5220
5221private:
5222 // Infer members of T, given that the expression E (dependent on T) is true.
5223 void believe(const Expr *E, const TemplateTypeParmType *T) {
5224 if (!E || !T)
5225 return;
5226 if (auto *CSE = dyn_cast<ConceptSpecializationExpr>(E)) {
5227 // If the concept is
5228 // template <class A, class B> concept CD = f<A, B>();
5229 // And the concept specialization is
5230 // CD<int, T>
5231 // Then we're substituting T for B, so we want to make f<A, B>() true
5232 // by adding members to B - i.e. believe(f<A, B>(), B);
5233 //
5234 // For simplicity:
5235 // - we don't attempt to substitute int for A
5236 // - when T is used in other ways (like CD<T*>) we ignore it
5237 ConceptDecl *CD = CSE->getNamedConcept();
5238 TemplateParameterList *Params = CD->getTemplateParameters();
5239 unsigned Index = 0;
5240 for (const auto &Arg : CSE->getTemplateArguments()) {
5241 if (Index >= Params->size())
5242 break; // Won't happen in valid code.
5243 if (isApprox(Arg, T)) {
5244 auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Params->getParam(Index));
5245 if (!TTPD)
5246 continue;
5247 // T was used as an argument, and bound to the parameter TT.
5248 auto *TT = cast<TemplateTypeParmType>(TTPD->getTypeForDecl());
5249 // So now we know the constraint as a function of TT is true.
5250 believe(CD->getConstraintExpr(), TT);
5251 // (concepts themselves have no associated constraints to require)
5252 }
5253
5254 ++Index;
5255 }
5256 } else if (auto *BO = dyn_cast<BinaryOperator>(E)) {
5257 // For A && B, we can infer members from both branches.
5258 // For A || B, the union is still more useful than the intersection.
5259 if (BO->getOpcode() == BO_LAnd || BO->getOpcode() == BO_LOr) {
5260 believe(BO->getLHS(), T);
5261 believe(BO->getRHS(), T);
5262 }
5263 } else if (auto *RE = dyn_cast<RequiresExpr>(E)) {
5264 // A requires(){...} lets us infer members from each requirement.
5265 for (const concepts::Requirement *Req : RE->getRequirements()) {
5266 if (!Req->isDependent())
5267 continue; // Can't tell us anything about T.
5268 // Now Req cannot a substitution-error: those aren't dependent.
5269
5270 if (auto *TR = dyn_cast<concepts::TypeRequirement>(Req)) {
5271 // Do a full traversal so we get `foo` from `typename T::foo::bar`.
5272 QualType AssertedType = TR->getType()->getType();
5273 ValidVisitor(this, T).TraverseType(AssertedType);
5274 } else if (auto *ER = dyn_cast<concepts::ExprRequirement>(Req)) {
5275 ValidVisitor Visitor(this, T);
5276 // If we have a type constraint on the value of the expression,
5277 // AND the whole outer expression describes a member, then we'll
5278 // be able to use the constraint to provide the return type.
5279 if (ER->getReturnTypeRequirement().isTypeConstraint()) {
5280 Visitor.OuterType =
5281 ER->getReturnTypeRequirement().getTypeConstraint();
5282 Visitor.OuterExpr = ER->getExpr();
5283 }
5284 Visitor.TraverseStmt(ER->getExpr());
5285 } else if (auto *NR = dyn_cast<concepts::NestedRequirement>(Req)) {
5286 believe(NR->getConstraintExpr(), T);
5287 }
5288 }
5289 }
5290 }
5291
5292 // This visitor infers members of T based on traversing expressions/types
5293 // that involve T. It is invoked with code known to be valid for T.
5294 class ValidVisitor : public RecursiveASTVisitor<ValidVisitor> {
5295 ConceptInfo *Outer;
5296 const TemplateTypeParmType *T;
5297
5298 CallExpr *Caller = nullptr;
5299 Expr *Callee = nullptr;
5300
5301 public:
5302 // If set, OuterExpr is constrained by OuterType.
5303 Expr *OuterExpr = nullptr;
5304 const TypeConstraint *OuterType = nullptr;
5305
5306 ValidVisitor(ConceptInfo *Outer, const TemplateTypeParmType *T)
5307 : Outer(Outer), T(T) {
5308 assert(T)(static_cast <bool> (T) ? void (0) : __assert_fail ("T"
, "clang/lib/Sema/SemaCodeComplete.cpp", 5308, __extension__ __PRETTY_FUNCTION__
))
;
5309 }
5310
5311 // In T.foo or T->foo, `foo` is a member function/variable.
5312 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
5313 const Type *Base = E->getBaseType().getTypePtr();
5314 bool IsArrow = E->isArrow();
5315 if (Base->isPointerType() && IsArrow) {
5316 IsArrow = false;
5317 Base = Base->getPointeeType().getTypePtr();
5318 }
5319 if (isApprox(Base, T))
5320 addValue(E, E->getMember(), IsArrow ? Member::Arrow : Member::Dot);
5321 return true;
5322 }
5323
5324 // In T::foo, `foo` is a static member function/variable.
5325 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
5326 if (E->getQualifier() && isApprox(E->getQualifier()->getAsType(), T))
5327 addValue(E, E->getDeclName(), Member::Colons);
5328 return true;
5329 }
5330
5331 // In T::typename foo, `foo` is a type.
5332 bool VisitDependentNameType(DependentNameType *DNT) {
5333 const auto *Q = DNT->getQualifier();
5334 if (Q && isApprox(Q->getAsType(), T))
5335 addType(DNT->getIdentifier());
5336 return true;
5337 }
5338
5339 // In T::foo::bar, `foo` must be a type.
5340 // VisitNNS() doesn't exist, and TraverseNNS isn't always called :-(
5341 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSL) {
5342 if (NNSL) {
5343 NestedNameSpecifier *NNS = NNSL.getNestedNameSpecifier();
5344 const auto *Q = NNS->getPrefix();
5345 if (Q && isApprox(Q->getAsType(), T))
5346 addType(NNS->getAsIdentifier());
5347 }
5348 // FIXME: also handle T::foo<X>::bar
5349 return RecursiveASTVisitor::TraverseNestedNameSpecifierLoc(NNSL);
5350 }
5351
5352 // FIXME also handle T::foo<X>
5353
5354 // Track the innermost caller/callee relationship so we can tell if a
5355 // nested expr is being called as a function.
5356 bool VisitCallExpr(CallExpr *CE) {
5357 Caller = CE;
5358 Callee = CE->getCallee();
5359 return true;
5360 }
5361
5362 private:
5363 void addResult(Member &&M) {
5364 auto R = Outer->Results.try_emplace(M.Name);
5365 Member &O = R.first->second;
5366 // Overwrite existing if the new member has more info.
5367 // The preference of . vs :: vs -> is fairly arbitrary.
5368 if (/*Inserted*/ R.second ||
5369 std::make_tuple(M.ArgTypes.has_value(), M.ResultType != nullptr,
5370 M.Operator) > std::make_tuple(O.ArgTypes.has_value(),
5371 O.ResultType != nullptr,
5372 O.Operator))
5373 O = std::move(M);
5374 }
5375
5376 void addType(const IdentifierInfo *Name) {
5377 if (!Name)
5378 return;
5379 Member M;
5380 M.Name = Name;
5381 M.Operator = Member::Colons;
5382 addResult(std::move(M));
5383 }
5384
5385 void addValue(Expr *E, DeclarationName Name,
5386 Member::AccessOperator Operator) {
5387 if (!Name.isIdentifier())
5388 return;
5389 Member Result;
5390 Result.Name = Name.getAsIdentifierInfo();
5391 Result.Operator = Operator;
5392 // If this is the callee of an immediately-enclosing CallExpr, then
5393 // treat it as a method, otherwise it's a variable.
5394 if (Caller != nullptr && Callee == E) {
5395 Result.ArgTypes.emplace();
5396 for (const auto *Arg : Caller->arguments())
5397 Result.ArgTypes->push_back(Arg->getType());
5398 if (Caller == OuterExpr) {
5399 Result.ResultType = OuterType;
5400 }
5401 } else {
5402 if (E == OuterExpr)
5403 Result.ResultType = OuterType;
5404 }
5405 addResult(std::move(Result));
5406 }
5407 };
5408
5409 static bool isApprox(const TemplateArgument &Arg, const Type *T) {
5410 return Arg.getKind() == TemplateArgument::Type &&
5411 isApprox(Arg.getAsType().getTypePtr(), T);
5412 }
5413
5414 static bool isApprox(const Type *T1, const Type *T2) {
5415 return T1 && T2 &&
5416 T1->getCanonicalTypeUnqualified() ==
5417 T2->getCanonicalTypeUnqualified();
5418 }
5419
5420 // Returns the DeclContext immediately enclosed by the template parameter
5421 // scope. For primary templates, this is the templated (e.g.) CXXRecordDecl.
5422 // For specializations, this is e.g. ClassTemplatePartialSpecializationDecl.
5423 static DeclContext *getTemplatedEntity(const TemplateTypeParmDecl *D,
5424 Scope *S) {
5425 if (D == nullptr)
5426 return nullptr;
5427 Scope *Inner = nullptr;
5428 while (S) {
5429 if (S->isTemplateParamScope() && S->isDeclScope(D))
5430 return Inner ? Inner->getEntity() : nullptr;
5431 Inner = S;
5432 S = S->getParent();
5433 }
5434 return nullptr;
5435 }
5436
5437 // Gets all the type constraint expressions that might apply to the type
5438 // variables associated with DC (as returned by getTemplatedEntity()).
5439 static SmallVector<const Expr *, 1>
5440 constraintsForTemplatedEntity(DeclContext *DC) {
5441 SmallVector<const Expr *, 1> Result;
5442 if (DC == nullptr)
5443 return Result;
5444 // Primary templates can have constraints.
5445 if (const auto *TD = cast<Decl>(DC)->getDescribedTemplate())
5446 TD->getAssociatedConstraints(Result);
5447 // Partial specializations may have constraints.
5448 if (const auto *CTPSD =
5449 dyn_cast<ClassTemplatePartialSpecializationDecl>(DC))
5450 CTPSD->getAssociatedConstraints(Result);
5451 if (const auto *VTPSD = dyn_cast<VarTemplatePartialSpecializationDecl>(DC))
5452 VTPSD->getAssociatedConstraints(Result);
5453 return Result;
5454 }
5455
5456 // Attempt to find the unique type satisfying a constraint.
5457 // This lets us show e.g. `int` instead of `std::same_as<int>`.
5458 static QualType deduceType(const TypeConstraint &T) {
5459 // Assume a same_as<T> return type constraint is std::same_as or equivalent.
5460 // In this case the return type is T.
5461 DeclarationName DN = T.getNamedConcept()->getDeclName();
5462 if (DN.isIdentifier() && DN.getAsIdentifierInfo()->isStr("same_as"))
5463 if (const auto *Args = T.getTemplateArgsAsWritten())
5464 if (Args->getNumTemplateArgs() == 1) {
5465 const auto &Arg = Args->arguments().front().getArgument();
5466 if (Arg.getKind() == TemplateArgument::Type)
5467 return Arg.getAsType();
5468 }
5469 return {};
5470 }
5471
5472 llvm::DenseMap<const IdentifierInfo *, Member> Results;
5473};
5474
5475// Returns a type for E that yields acceptable member completions.
5476// In particular, when E->getType() is DependentTy, try to guess a likely type.
5477// We accept some lossiness (like dropping parameters).
5478// We only try to handle common expressions on the LHS of MemberExpr.
5479QualType getApproximateType(const Expr *E) {
5480 QualType Unresolved = E->getType();
5481 if (Unresolved.isNull() ||
5482 !Unresolved->isSpecificBuiltinType(BuiltinType::Dependent))
5483 return Unresolved;
5484 E = E->IgnoreParens();
5485 // A call: approximate-resolve callee to a function type, get its return type
5486 if (const CallExpr *CE = llvm::dyn_cast<CallExpr>(E)) {
5487 QualType Callee = getApproximateType(CE->getCallee());
5488 if (Callee.isNull() ||
5489 Callee->isSpecificPlaceholderType(BuiltinType::BoundMember))
5490 Callee = Expr::findBoundMemberType(CE->getCallee());
5491 if (Callee.isNull())
5492 return Unresolved;
5493
5494 if (const auto *FnTypePtr = Callee->getAs<PointerType>()) {
5495 Callee = FnTypePtr->getPointeeType();
5496 } else if (const auto *BPT = Callee->getAs<BlockPointerType>()) {
5497 Callee = BPT->getPointeeType();
5498 }
5499 if (const FunctionType *FnType = Callee->getAs<FunctionType>())
5500 return FnType->getReturnType().getNonReferenceType();
5501
5502 // Unresolved call: try to guess the return type.
5503 if (const auto *OE = llvm::dyn_cast<OverloadExpr>(CE->getCallee())) {
5504 // If all candidates have the same approximate return type, use it.
5505 // Discard references and const to allow more to be "the same".
5506 // (In particular, if there's one candidate + ADL, resolve it).
5507 const Type *Common = nullptr;
5508 for (const auto *D : OE->decls()) {
5509 QualType ReturnType;
5510 if (const auto *FD = llvm::dyn_cast<FunctionDecl>(D))
5511 ReturnType = FD->getReturnType();
5512 else if (const auto *FTD = llvm::dyn_cast<FunctionTemplateDecl>(D))
5513 ReturnType = FTD->getTemplatedDecl()->getReturnType();
5514 if (ReturnType.isNull())
5515 continue;
5516 const Type *Candidate =
5517 ReturnType.getNonReferenceType().getCanonicalType().getTypePtr();
5518 if (Common && Common != Candidate)
5519 return Unresolved; // Multiple candidates.
5520 Common = Candidate;
5521 }
5522 if (Common != nullptr)
5523 return QualType(Common, 0);
5524 }
5525 }
5526 // A dependent member: approximate-resolve the base, then lookup.
5527 if (const auto *CDSME = llvm::dyn_cast<CXXDependentScopeMemberExpr>(E)) {
5528 QualType Base = CDSME->isImplicitAccess()
5529 ? CDSME->getBaseType()
5530 : getApproximateType(CDSME->getBase());
5531 if (CDSME->isArrow() && !Base.isNull())
5532 Base = Base->getPointeeType(); // could handle unique_ptr etc here?
5533 auto *RD =
5534 Base.isNull()
5535 ? nullptr
5536 : llvm::dyn_cast_or_null<CXXRecordDecl>(getAsRecordDecl(Base));
5537 if (RD && RD->isCompleteDefinition()) {
5538 // Look up member heuristically, including in bases.
5539 for (const auto *Member : RD->lookupDependentName(
5540 CDSME->getMember(), [](const NamedDecl *Member) {
5541 return llvm::isa<ValueDecl>(Member);
5542 })) {
5543 return llvm::cast<ValueDecl>(Member)->getType().getNonReferenceType();
5544 }
5545 }
5546 }
5547 return Unresolved;
5548}
5549
5550// If \p Base is ParenListExpr, assume a chain of comma operators and pick the
5551// last expr. We expect other ParenListExprs to be resolved to e.g. constructor
5552// calls before here. (So the ParenListExpr should be nonempty, but check just
5553// in case)
5554Expr *unwrapParenList(Expr *Base) {
5555 if (auto *PLE = llvm::dyn_cast_or_null<ParenListExpr>(Base)) {
5556 if (PLE->getNumExprs() == 0)
5557 return nullptr;
5558 Base = PLE->getExpr(PLE->getNumExprs() - 1);
5559 }
5560 return Base;
5561}
5562
5563} // namespace
5564
5565void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
5566 Expr *OtherOpBase,
5567 SourceLocation OpLoc, bool IsArrow,
5568 bool IsBaseExprStatement,
5569 QualType PreferredType) {
5570 Base = unwrapParenList(Base);
5571 OtherOpBase = unwrapParenList(OtherOpBase);
5572 if (!Base || !CodeCompleter)
5573 return;
5574
5575 ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
5576 if (ConvertedBase.isInvalid())
5577 return;
5578 QualType ConvertedBaseType = getApproximateType(ConvertedBase.get());
5579
5580 enum CodeCompletionContext::Kind contextKind;
5581
5582 if (IsArrow) {
5583 if (const auto *Ptr = ConvertedBaseType->getAs<PointerType>())
5584 ConvertedBaseType = Ptr->getPointeeType();
5585 }
5586
5587 if (IsArrow) {
5588 contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
5589 } else {
5590 if (ConvertedBaseType->isObjCObjectPointerType() ||
5591 ConvertedBaseType->isObjCObjectOrInterfaceType()) {
5592 contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
5593 } else {
5594 contextKind = CodeCompletionContext::CCC_DotMemberAccess;
5595 }
5596 }
5597
5598 CodeCompletionContext CCContext(contextKind, ConvertedBaseType);
5599 CCContext.setPreferredType(PreferredType);
5600 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5601 CodeCompleter->getCodeCompletionTUInfo(), CCContext,
5602 &ResultBuilder::IsMember);
5603
5604 auto DoCompletion = [&](Expr *Base, bool IsArrow,
5605 Optional<FixItHint> AccessOpFixIt) -> bool {
5606 if (!Base)
5607 return false;
5608
5609 ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
5610 if (ConvertedBase.isInvalid())
5611 return false;
5612 Base = ConvertedBase.get();
5613
5614 QualType BaseType = getApproximateType(Base);
5615 if (BaseType.isNull())
5616 return false;
5617 ExprValueKind BaseKind = Base->getValueKind();
5618
5619 if (IsArrow) {
5620 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
5621 BaseType = Ptr->getPointeeType();
5622 BaseKind = VK_LValue;
5623 } else if (BaseType->isObjCObjectPointerType() ||
5624 BaseType->isTemplateTypeParmType()) {
5625 // Both cases (dot/arrow) handled below.
5626 } else {
5627 return false;
5628 }
5629 }
5630
5631 if (RecordDecl *RD = getAsRecordDecl(BaseType)) {
5632 AddRecordMembersCompletionResults(*this, Results, S, BaseType, BaseKind,
5633 RD, std::move(AccessOpFixIt));
5634 } else if (const auto *TTPT =
5635 dyn_cast<TemplateTypeParmType>(BaseType.getTypePtr())) {
5636 auto Operator =
5637 IsArrow ? ConceptInfo::Member::Arrow : ConceptInfo::Member::Dot;
5638 for (const auto &R : ConceptInfo(*TTPT, S).members()) {
5639 if (R.Operator != Operator)
5640 continue;
5641 CodeCompletionResult Result(
5642 R.render(*this, CodeCompleter->getAllocator(),
5643 CodeCompleter->getCodeCompletionTUInfo()));
5644 if (AccessOpFixIt)
5645 Result.FixIts.push_back(*AccessOpFixIt);
5646 Results.AddResult(std::move(Result));
5647 }
5648 } else if (!IsArrow && BaseType->isObjCObjectPointerType()) {
5649 // Objective-C property reference. Bail if we're performing fix-it code
5650 // completion since Objective-C properties are normally backed by ivars,
5651 // most Objective-C fix-its here would have little value.
5652 if (AccessOpFixIt) {
5653 return false;
5654 }
5655 AddedPropertiesSet AddedProperties;
5656
5657 if (const ObjCObjectPointerType *ObjCPtr =
5658 BaseType->getAsObjCInterfacePointerType()) {
5659 // Add property results based on our interface.
5660 assert(ObjCPtr && "Non-NULL pointer guaranteed above!")(static_cast <bool> (ObjCPtr && "Non-NULL pointer guaranteed above!"
) ? void (0) : __assert_fail ("ObjCPtr && \"Non-NULL pointer guaranteed above!\""
, "clang/lib/Sema/SemaCodeComplete.cpp", 5660, __extension__ __PRETTY_FUNCTION__
))
;
5661 AddObjCProperties(CCContext, ObjCPtr->getInterfaceDecl(), true,
5662 /*AllowNullaryMethods=*/true, CurContext,
5663 AddedProperties, Results, IsBaseExprStatement);
5664 }
5665
5666 // Add properties from the protocols in a qualified interface.
5667 for (auto *I : BaseType->castAs<ObjCObjectPointerType>()->quals())
5668 AddObjCProperties(CCContext, I, true, /*AllowNullaryMethods=*/true,
5669 CurContext, AddedProperties, Results,
5670 IsBaseExprStatement, /*IsClassProperty*/ false,
5671 /*InOriginalClass*/ false);
5672 } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
5673 (!IsArrow && BaseType->isObjCObjectType())) {
5674 // Objective-C instance variable access. Bail if we're performing fix-it
5675 // code completion since Objective-C properties are normally backed by
5676 // ivars, most Objective-C fix-its here would have little value.
5677 if (AccessOpFixIt) {
5678 return false;
5679 }
5680 ObjCInterfaceDecl *Class = nullptr;
5681 if (const ObjCObjectPointerType *ObjCPtr =
5682 BaseType->getAs<ObjCObjectPointerType>())
5683 Class = ObjCPtr->getInterfaceDecl();
5684 else
5685 Class = BaseType->castAs<ObjCObjectType>()->getInterface();
5686
5687 // Add all ivars from this class and its superclasses.
5688 if (Class) {
5689 CodeCompletionDeclConsumer Consumer(Results, Class, BaseType);
5690 Results.setFilter(&ResultBuilder::IsObjCIvar);
5691 LookupVisibleDecls(
5692 Class, LookupMemberName, Consumer, CodeCompleter->includeGlobals(),
5693 /*IncludeDependentBases=*/false, CodeCompleter->loadExternal());
5694 }
5695 }
5696
5697 // FIXME: How do we cope with isa?
5698 return true;
5699 };
5700
5701 Results.EnterNewScope();
5702
5703 bool CompletionSucceded = DoCompletion(Base, IsArrow, None);
5704 if (CodeCompleter->includeFixIts()) {
5705 const CharSourceRange OpRange =
5706 CharSourceRange::getTokenRange(OpLoc, OpLoc);
5707 CompletionSucceded |= DoCompletion(
5708 OtherOpBase, !IsArrow,
5709 FixItHint::CreateReplacement(OpRange, IsArrow ? "." : "->"));
5710 }
5711
5712 Results.ExitScope();
5713
5714 if (!CompletionSucceded)
5715 return;
5716
5717 // Hand off the results found for code completion.
5718 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5719 Results.data(), Results.size());
5720}
5721
5722void Sema::CodeCompleteObjCClassPropertyRefExpr(Scope *S,
5723 IdentifierInfo &ClassName,
5724 SourceLocation ClassNameLoc,
5725 bool IsBaseExprStatement) {
5726 IdentifierInfo *ClassNamePtr = &ClassName;
5727 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(ClassNamePtr, ClassNameLoc);
5728 if (!IFace)
5729 return;
5730 CodeCompletionContext CCContext(
5731 CodeCompletionContext::CCC_ObjCPropertyAccess);
5732 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5733 CodeCompleter->getCodeCompletionTUInfo(), CCContext,
5734 &ResultBuilder::IsMember);
5735 Results.EnterNewScope();
5736 AddedPropertiesSet AddedProperties;
5737 AddObjCProperties(CCContext, IFace, true,
5738 /*AllowNullaryMethods=*/true, CurContext, AddedProperties,
5739 Results, IsBaseExprStatement,
5740 /*IsClassProperty=*/true);
5741 Results.ExitScope();
5742 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5743 Results.data(), Results.size());
5744}
5745
5746void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
5747 if (!CodeCompleter)
5748 return;
5749
5750 ResultBuilder::LookupFilter Filter = nullptr;
5751 enum CodeCompletionContext::Kind ContextKind =
5752 CodeCompletionContext::CCC_Other;
5753 switch ((DeclSpec::TST)TagSpec) {
5754 case DeclSpec::TST_enum:
5755 Filter = &ResultBuilder::IsEnum;
5756 ContextKind = CodeCompletionContext::CCC_EnumTag;
5757 break;
5758
5759 case DeclSpec::TST_union:
5760 Filter = &ResultBuilder::IsUnion;
5761 ContextKind = CodeCompletionContext::CCC_UnionTag;
5762 break;
5763
5764 case DeclSpec::TST_struct:
5765 case DeclSpec::TST_class:
5766 case DeclSpec::TST_interface:
5767 Filter = &ResultBuilder::IsClassOrStruct;
5768 ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
5769 break;
5770
5771 default:
5772 llvm_unreachable("Unknown type specifier kind in CodeCompleteTag")::llvm::llvm_unreachable_internal("Unknown type specifier kind in CodeCompleteTag"
, "clang/lib/Sema/SemaCodeComplete.cpp", 5772)
;
5773 }
5774
5775 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5776 CodeCompleter->getCodeCompletionTUInfo(), ContextKind);
5777 CodeCompletionDeclConsumer Consumer(Results, CurContext);
5778
5779 // First pass: look for tags.
5780 Results.setFilter(Filter);
5781 LookupVisibleDecls(S, LookupTagName, Consumer,
5782 CodeCompleter->includeGlobals(),
5783 CodeCompleter->loadExternal());
5784
5785 if (CodeCompleter->includeGlobals()) {
5786 // Second pass: look for nested name specifiers.
5787 Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
5788 LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
5789 CodeCompleter->includeGlobals(),
5790 CodeCompleter->loadExternal());
5791 }
5792
5793 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5794 Results.data(), Results.size());
5795}
5796
5797static void AddTypeQualifierResults(DeclSpec &DS, ResultBuilder &Results,
5798 const LangOptions &LangOpts) {
5799 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
5800 Results.AddResult("const");
5801 if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
5802 Results.AddResult("volatile");
5803 if (LangOpts.C99 && !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
5804 Results.AddResult("restrict");
5805 if (LangOpts.C11 && !(DS.getTypeQualifiers() & DeclSpec::TQ_atomic))
5806 Results.AddResult("_Atomic");
5807 if (LangOpts.MSVCCompat && !(DS.getTypeQualifiers() & DeclSpec::TQ_unaligned))
5808 Results.AddResult("__unaligned");
5809}
5810
5811void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
5812 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5813 CodeCompleter->getCodeCompletionTUInfo(),
5814 CodeCompletionContext::CCC_TypeQualifiers);
5815 Results.EnterNewScope();
5816 AddTypeQualifierResults(DS, Results, LangOpts);
5817 Results.ExitScope();
5818 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5819 Results.data(), Results.size());
5820}
5821
5822void Sema::CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
5823 const VirtSpecifiers *VS) {
5824 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5825 CodeCompleter->getCodeCompletionTUInfo(),
5826 CodeCompletionContext::CCC_TypeQualifiers);
5827 Results.EnterNewScope();
5828 AddTypeQualifierResults(DS, Results, LangOpts);
5829 if (LangOpts.CPlusPlus11) {
5830 Results.AddResult("noexcept");
5831 if (D.getContext() == DeclaratorContext::Member && !D.isCtorOrDtor() &&
5832 !D.isStaticMember()) {
5833 if (!VS || !VS->isFinalSpecified())
5834 Results.AddResult("final");
5835 if (!VS || !VS->isOverrideSpecified())
5836 Results.AddResult("override");
5837 }
5838 }
5839 Results.ExitScope();
5840 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5841 Results.data(), Results.size());
5842}
5843
5844void Sema::CodeCompleteBracketDeclarator(Scope *S) {
5845 CodeCompleteExpression(S, QualType(getASTContext().getSizeType()));
5846}
5847
5848void Sema::CodeCompleteCase(Scope *S) {
5849 if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
5850 return;
5851
5852 SwitchStmt *Switch = getCurFunction()->SwitchStack.back().getPointer();
5853 // Condition expression might be invalid, do not continue in this case.
5854 if (!Switch->getCond())
5855 return;
5856 QualType type = Switch->getCond()->IgnoreImplicit()->getType();
5857 if (!type->isEnumeralType()) {
5858 CodeCompleteExpressionData Data(type);
5859 Data.IntegralConstantExpression = true;
5860 CodeCompleteExpression(S, Data);
5861 return;
5862 }
5863
5864 // Code-complete the cases of a switch statement over an enumeration type
5865 // by providing the list of
5866 EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
5867 if (EnumDecl *Def = Enum->getDefinition())
5868 Enum = Def;
5869
5870 // Determine which enumerators we have already seen in the switch statement.
5871 // FIXME: Ideally, we would also be able to look *past* the code-completion
5872 // token, in case we are code-completing in the middle of the switch and not
5873 // at the end. However, we aren't able to do so at the moment.
5874 CoveredEnumerators Enumerators;
5875 for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
5876 SC = SC->getNextSwitchCase()) {
5877 CaseStmt *Case = dyn_cast<CaseStmt>(SC);
5878 if (!Case)
5879 continue;
5880
5881 Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
5882 if (auto *DRE = dyn_cast<DeclRefExpr>(CaseVal))
5883 if (auto *Enumerator =
5884 dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5885 // We look into the AST of the case statement to determine which
5886 // enumerator was named. Alternatively, we could compute the value of
5887 // the integral constant expression, then compare it against the
5888 // values of each enumerator. However, value-based approach would not
5889 // work as well with C++ templates where enumerators declared within a
5890 // template are type- and value-dependent.
5891 Enumerators.Seen.insert(Enumerator);
5892
5893 // If this is a qualified-id, keep track of the nested-name-specifier
5894 // so that we can reproduce it as part of code completion, e.g.,
5895 //
5896 // switch (TagD.getKind()) {
5897 // case TagDecl::TK_enum:
5898 // break;
5899 // case XXX
5900 //
5901 // At the XXX, our completions are TagDecl::TK_union,
5902 // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
5903 // TK_struct, and TK_class.
5904 Enumerators.SuggestedQualifier = DRE->getQualifier();
5905 }
5906 }
5907
5908 // Add any enumerators that have not yet been mentioned.
5909 ResultBuilder Results(*this, CodeCompleter->getAllocator(),
5910 CodeCompleter->getCodeCompletionTUInfo(),
5911 CodeCompletionContext::CCC_Expression);
5912 AddEnumerators(Results, Context, Enum, CurContext, Enumerators);
5913
5914 if (CodeCompleter->includeMacros()) {
5915 AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false);
5916 }
5917 HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
5918 Results.data(), Results.size());
5919}
5920
5921static bool anyNullArguments(ArrayRef<Expr *> Args) {
5922 if (Args.size() && !Args.data())
5923 return true;
5924
5925 for (unsigned I = 0; I != Args.size(); ++I)
5926 if (!Args[I])
5927 return true;
5928
5929 return false;
5930}
5931
5932typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
5933
5934static void mergeCandidatesWithResults(
5935 Sema &SemaRef, SmallVectorImpl<ResultCandidate> &Results,
5936 OverloadCandidateSet &CandidateSet, SourceLocation Loc, size_t ArgSize) {
5937 // Sort the overload candidate set by placing the best overloads first.
5938 llvm::stable_sort(CandidateSet, [&](const OverloadCandidate &X,
5939 const OverloadCandidate &Y) {
5940 return isBetterOverloadCandidate(SemaRef, X, Y, Loc,
5941 CandidateSet.getKind());
5942 });
5943
5944 // Add the remaining viable overload candidates as code-completion results.
5945 for (OverloadCandidate &Candidate : CandidateSet) {
5946 if (Candidate.Function) {
5947 if (Candidate.Function->isDeleted())
5948 continue;
5949 if (shouldEnforceArgLimit(/*PartialOverloading=*/true,
5950 Candidate.Function) &&
5951 Candidate.Function->getNumParams() <= ArgSize &&
5952 // Having zero args is annoying, normally we don't surface a function
5953 // with 2 params, if you already have 2 params, because you are
5954 // inserting the 3rd now. But with zero, it helps the user to figure
5955 // out there are no overloads that take any arguments. Hence we are
5956 // keeping the overload.
5957 ArgSize > 0)
5958 continue;
5959 }
5960 if (Candidate.Viable)
5961 Results.push_back(ResultCandidate(Candidate.Function));
5962 }
5963}
5964
5965/// Get the type of the Nth parameter from a given set of overload
5966/// candidates.
5967static QualType getParamType(Sema &SemaRef,
5968 ArrayRef<ResultCandidate> Candidates, unsigned N) {
5969
5970 // Given the overloads 'Candidates' for a function call matching all arguments
5971 // up to N, return the type of the Nth parameter if it is the same for all
5972 // overload candidates.
5973 QualType ParamType;
5974 for (auto &Candidate : Candidates) {
5975 QualType CandidateParamType = Candidate.getParamType(N);
5976 if (CandidateParamType.isNull())
5977 continue;
5978 if (ParamType.isNull()) {
5979 ParamType = CandidateParamType;
5980 continue;
5981 }
5982 if (!SemaRef.Context.hasSameUnqualifiedType(
5983 ParamType.getNonReferenceType(),
5984 CandidateParamType.getNonReferenceType()))
5985 // Two conflicting types, give up.
5986 return QualType();
5987 }
5988
5989 return ParamType;
5990}
5991
5992static QualType
5993ProduceSignatureHelp(Sema &SemaRef, MutableArrayRef<ResultCandidate> Candidates,
5994 unsigned CurrentArg, SourceLocation OpenParLoc,
5995 bool Braced) {
5996 if (Candidates.empty())
5997 return QualType();
5998 if (SemaRef.getPreprocessor().isCodeCompletionReached())
5999 SemaRef.CodeCompleter->ProcessOverloadCandidates(
6000 SemaRef, CurrentArg, Candidates.data(), Candidates.size(), OpenParLoc,
6001 Braced);
6002 return getParamType(SemaRef, Candidates, CurrentArg);
6003}
6004
6005// Given a callee expression `Fn`, if the call is through a function pointer,
6006// try to find the declaration of the corresponding function pointer type,
6007// so that we can recover argument names from it.
6008static FunctionProtoTypeLoc GetPrototypeLoc(Expr *Fn) {
6009 TypeLoc Target;
6010 if (const auto *T = Fn->getType().getTypePtr()->getAs<TypedefType>()) {
6011 Target = T->getDecl()->getTypeSourceInfo()->getTypeLoc();
6012
6013 } else if (const auto *DR = dyn_cast<DeclRefExpr>(Fn)) {
6014 const auto *D = DR->getDecl();
6015 if (const auto *const VD = dyn_cast<VarDecl>(D)) {
6016 Target = VD->getTypeSourceInfo()->getTypeLoc();
6017 }
6018 }
6019
6020 if (!Target)
6021 return {};
6022
6023 if (auto P = Target.getAs<PointerTypeLoc>()) {
6024 Target = P.getPointeeLoc();
6025 }
6026
6027 if (auto P = Target.getAs<ParenTypeLoc>()) {