Bug Summary

File:clang/lib/Sema/SemaCodeComplete.cpp
Warning:line 8856, column 9
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 -disable-llvm-verifier -discard-value-names -main-file-name SemaCodeComplete.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -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 -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/Sema -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/llvm/include -D 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-14/lib/clang/14.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 -O2 -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 -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -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-2021-09-04-040900-46481-1 -x c++ /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/lib/Sema/SemaCodeComplete.cpp

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