File: | build/source/clang/include/clang/AST/NestedNameSpecifier.h |
Warning: | line 386, column 7 Attempt to free released memory |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===---------------- SemaCodeComplete.cpp - Code Completion ----*- C++ -*-===// | |||
2 | // | |||
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | |||
4 | // See https://llvm.org/LICENSE.txt for license information. | |||
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | |||
6 | // | |||
7 | //===----------------------------------------------------------------------===// | |||
8 | // | |||
9 | // This file defines the code-completion semantic actions. | |||
10 | // | |||
11 | //===----------------------------------------------------------------------===// | |||
12 | #include "clang/AST/ASTConcept.h" | |||
13 | #include "clang/AST/Decl.h" | |||
14 | #include "clang/AST/DeclBase.h" | |||
15 | #include "clang/AST/DeclCXX.h" | |||
16 | #include "clang/AST/DeclObjC.h" | |||
17 | #include "clang/AST/DeclTemplate.h" | |||
18 | #include "clang/AST/Expr.h" | |||
19 | #include "clang/AST/ExprCXX.h" | |||
20 | #include "clang/AST/ExprConcepts.h" | |||
21 | #include "clang/AST/ExprObjC.h" | |||
22 | #include "clang/AST/NestedNameSpecifier.h" | |||
23 | #include "clang/AST/QualTypeNames.h" | |||
24 | #include "clang/AST/RecursiveASTVisitor.h" | |||
25 | #include "clang/AST/Type.h" | |||
26 | #include "clang/Basic/AttributeCommonInfo.h" | |||
27 | #include "clang/Basic/CharInfo.h" | |||
28 | #include "clang/Basic/OperatorKinds.h" | |||
29 | #include "clang/Basic/Specifiers.h" | |||
30 | #include "clang/Lex/HeaderSearch.h" | |||
31 | #include "clang/Lex/MacroInfo.h" | |||
32 | #include "clang/Lex/Preprocessor.h" | |||
33 | #include "clang/Sema/CodeCompleteConsumer.h" | |||
34 | #include "clang/Sema/DeclSpec.h" | |||
35 | #include "clang/Sema/Designator.h" | |||
36 | #include "clang/Sema/Lookup.h" | |||
37 | #include "clang/Sema/Overload.h" | |||
38 | #include "clang/Sema/ParsedAttr.h" | |||
39 | #include "clang/Sema/ParsedTemplate.h" | |||
40 | #include "clang/Sema/Scope.h" | |||
41 | #include "clang/Sema/ScopeInfo.h" | |||
42 | #include "clang/Sema/Sema.h" | |||
43 | #include "clang/Sema/SemaInternal.h" | |||
44 | #include "llvm/ADT/ArrayRef.h" | |||
45 | #include "llvm/ADT/DenseSet.h" | |||
46 | #include "llvm/ADT/SmallBitVector.h" | |||
47 | #include "llvm/ADT/SmallPtrSet.h" | |||
48 | #include "llvm/ADT/SmallString.h" | |||
49 | #include "llvm/ADT/StringExtras.h" | |||
50 | #include "llvm/ADT/StringSwitch.h" | |||
51 | #include "llvm/ADT/Twine.h" | |||
52 | #include "llvm/ADT/iterator_range.h" | |||
53 | #include "llvm/Support/Casting.h" | |||
54 | #include "llvm/Support/Path.h" | |||
55 | #include "llvm/Support/raw_ostream.h" | |||
56 | ||||
57 | #include <list> | |||
58 | #include <map> | |||
59 | #include <optional> | |||
60 | #include <string> | |||
61 | #include <vector> | |||
62 | ||||
63 | using namespace clang; | |||
64 | using namespace sema; | |||
65 | ||||
66 | namespace { | |||
67 | /// A container of code-completion results. | |||
68 | class ResultBuilder { | |||
69 | public: | |||
70 | /// The type of a name-lookup filter, which can be provided to the | |||
71 | /// name-lookup routines to specify which declarations should be included in | |||
72 | /// the result set (when it returns true) and which declarations should be | |||
73 | /// filtered out (returns false). | |||
74 | typedef bool (ResultBuilder::*LookupFilter)(const NamedDecl *) const; | |||
75 | ||||
76 | typedef CodeCompletionResult Result; | |||
77 | ||||
78 | private: | |||
79 | /// The actual results we have found. | |||
80 | std::vector<Result> Results; | |||
81 | ||||
82 | /// A record of all of the declarations we have found and placed | |||
83 | /// into the result set, used to ensure that no declaration ever gets into | |||
84 | /// the result set twice. | |||
85 | llvm::SmallPtrSet<const Decl *, 16> AllDeclsFound; | |||
86 | ||||
87 | typedef std::pair<const NamedDecl *, unsigned> DeclIndexPair; | |||
88 | ||||
89 | /// An entry in the shadow map, which is optimized to store | |||
90 | /// a single (declaration, index) mapping (the common case) but | |||
91 | /// can also store a list of (declaration, index) mappings. | |||
92 | class ShadowMapEntry { | |||
93 | typedef SmallVector<DeclIndexPair, 4> DeclIndexPairVector; | |||
94 | ||||
95 | /// Contains either the solitary NamedDecl * or a vector | |||
96 | /// of (declaration, index) pairs. | |||
97 | llvm::PointerUnion<const NamedDecl *, DeclIndexPairVector *> DeclOrVector; | |||
98 | ||||
99 | /// When the entry contains a single declaration, this is | |||
100 | /// the index associated with that entry. | |||
101 | unsigned SingleDeclIndex; | |||
102 | ||||
103 | public: | |||
104 | ShadowMapEntry() : SingleDeclIndex(0) {} | |||
105 | ShadowMapEntry(const ShadowMapEntry &) = delete; | |||
106 | ShadowMapEntry(ShadowMapEntry &&Move) { *this = std::move(Move); } | |||
107 | ShadowMapEntry &operator=(const ShadowMapEntry &) = delete; | |||
108 | ShadowMapEntry &operator=(ShadowMapEntry &&Move) { | |||
109 | SingleDeclIndex = Move.SingleDeclIndex; | |||
110 | DeclOrVector = Move.DeclOrVector; | |||
111 | Move.DeclOrVector = nullptr; | |||
112 | return *this; | |||
113 | } | |||
114 | ||||
115 | void Add(const NamedDecl *ND, unsigned Index) { | |||
116 | if (DeclOrVector.isNull()) { | |||
117 | // 0 - > 1 elements: just set the single element information. | |||
118 | DeclOrVector = ND; | |||
119 | SingleDeclIndex = Index; | |||
120 | return; | |||
121 | } | |||
122 | ||||
123 | if (const NamedDecl *PrevND = | |||
124 | DeclOrVector.dyn_cast<const NamedDecl *>()) { | |||
125 | // 1 -> 2 elements: create the vector of results and push in the | |||
126 | // existing declaration. | |||
127 | DeclIndexPairVector *Vec = new DeclIndexPairVector; | |||
128 | Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex)); | |||
129 | DeclOrVector = Vec; | |||
130 | } | |||
131 | ||||
132 | // Add the new element to the end of the vector. | |||
133 | DeclOrVector.get<DeclIndexPairVector *>()->push_back( | |||
134 | DeclIndexPair(ND, Index)); | |||
135 | } | |||
136 | ||||
137 | ~ShadowMapEntry() { | |||
138 | if (DeclIndexPairVector *Vec = | |||
139 | DeclOrVector.dyn_cast<DeclIndexPairVector *>()) { | |||
140 | delete Vec; | |||
141 | DeclOrVector = ((NamedDecl *)nullptr); | |||
142 | } | |||
143 | } | |||
144 | ||||
145 | // Iteration. | |||
146 | class iterator; | |||
147 | iterator begin() const; | |||
148 | iterator end() const; | |||
149 | }; | |||
150 | ||||
151 | /// A mapping from declaration names to the declarations that have | |||
152 | /// this name within a particular scope and their index within the list of | |||
153 | /// results. | |||
154 | typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap; | |||
155 | ||||
156 | /// The semantic analysis object for which results are being | |||
157 | /// produced. | |||
158 | Sema &SemaRef; | |||
159 | ||||
160 | /// The allocator used to allocate new code-completion strings. | |||
161 | CodeCompletionAllocator &Allocator; | |||
162 | ||||
163 | CodeCompletionTUInfo &CCTUInfo; | |||
164 | ||||
165 | /// If non-NULL, a filter function used to remove any code-completion | |||
166 | /// results that are not desirable. | |||
167 | LookupFilter Filter; | |||
168 | ||||
169 | /// Whether we should allow declarations as | |||
170 | /// nested-name-specifiers that would otherwise be filtered out. | |||
171 | bool AllowNestedNameSpecifiers; | |||
172 | ||||
173 | /// If set, the type that we would prefer our resulting value | |||
174 | /// declarations to have. | |||
175 | /// | |||
176 | /// Closely matching the preferred type gives a boost to a result's | |||
177 | /// priority. | |||
178 | CanQualType PreferredType; | |||
179 | ||||
180 | /// A list of shadow maps, which is used to model name hiding at | |||
181 | /// different levels of, e.g., the inheritance hierarchy. | |||
182 | std::list<ShadowMap> ShadowMaps; | |||
183 | ||||
184 | /// Overloaded C++ member functions found by SemaLookup. | |||
185 | /// Used to determine when one overload is dominated by another. | |||
186 | llvm::DenseMap<std::pair<DeclContext *, /*Name*/uintptr_t>, ShadowMapEntry> | |||
187 | OverloadMap; | |||
188 | ||||
189 | /// If we're potentially referring to a C++ member function, the set | |||
190 | /// of qualifiers applied to the object type. | |||
191 | Qualifiers ObjectTypeQualifiers; | |||
192 | /// The kind of the object expression, for rvalue/lvalue overloads. | |||
193 | ExprValueKind ObjectKind; | |||
194 | ||||
195 | /// Whether the \p ObjectTypeQualifiers field is active. | |||
196 | bool HasObjectTypeQualifiers; | |||
197 | ||||
198 | /// The selector that we prefer. | |||
199 | Selector PreferredSelector; | |||
200 | ||||
201 | /// The completion context in which we are gathering results. | |||
202 | CodeCompletionContext CompletionContext; | |||
203 | ||||
204 | /// If we are in an instance method definition, the \@implementation | |||
205 | /// object. | |||
206 | ObjCImplementationDecl *ObjCImplementation; | |||
207 | ||||
208 | void AdjustResultPriorityForDecl(Result &R); | |||
209 | ||||
210 | void MaybeAddConstructorResults(Result R); | |||
211 | ||||
212 | public: | |||
213 | explicit ResultBuilder(Sema &SemaRef, CodeCompletionAllocator &Allocator, | |||
214 | CodeCompletionTUInfo &CCTUInfo, | |||
215 | const CodeCompletionContext &CompletionContext, | |||
216 | LookupFilter Filter = nullptr) | |||
217 | : SemaRef(SemaRef), Allocator(Allocator), CCTUInfo(CCTUInfo), | |||
218 | Filter(Filter), AllowNestedNameSpecifiers(false), | |||
219 | HasObjectTypeQualifiers(false), CompletionContext(CompletionContext), | |||
220 | ObjCImplementation(nullptr) { | |||
221 | // If this is an Objective-C instance method definition, dig out the | |||
222 | // corresponding implementation. | |||
223 | switch (CompletionContext.getKind()) { | |||
224 | case CodeCompletionContext::CCC_Expression: | |||
225 | case CodeCompletionContext::CCC_ObjCMessageReceiver: | |||
226 | case CodeCompletionContext::CCC_ParenthesizedExpression: | |||
227 | case CodeCompletionContext::CCC_Statement: | |||
228 | case CodeCompletionContext::CCC_Recovery: | |||
229 | if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) | |||
230 | if (Method->isInstanceMethod()) | |||
231 | if (ObjCInterfaceDecl *Interface = Method->getClassInterface()) | |||
232 | ObjCImplementation = Interface->getImplementation(); | |||
233 | break; | |||
234 | ||||
235 | default: | |||
236 | break; | |||
237 | } | |||
238 | } | |||
239 | ||||
240 | /// Determine the priority for a reference to the given declaration. | |||
241 | unsigned getBasePriority(const NamedDecl *D); | |||
242 | ||||
243 | /// Whether we should include code patterns in the completion | |||
244 | /// results. | |||
245 | bool includeCodePatterns() const { | |||
246 | return SemaRef.CodeCompleter && | |||
247 | SemaRef.CodeCompleter->includeCodePatterns(); | |||
248 | } | |||
249 | ||||
250 | /// Set the filter used for code-completion results. | |||
251 | void setFilter(LookupFilter Filter) { this->Filter = Filter; } | |||
252 | ||||
253 | Result *data() { return Results.empty() ? nullptr : &Results.front(); } | |||
254 | unsigned size() const { return Results.size(); } | |||
255 | bool empty() const { return Results.empty(); } | |||
256 | ||||
257 | /// Specify the preferred type. | |||
258 | void setPreferredType(QualType T) { | |||
259 | PreferredType = SemaRef.Context.getCanonicalType(T); | |||
260 | } | |||
261 | ||||
262 | /// Set the cv-qualifiers on the object type, for us in filtering | |||
263 | /// calls to member functions. | |||
264 | /// | |||
265 | /// When there are qualifiers in this set, they will be used to filter | |||
266 | /// out member functions that aren't available (because there will be a | |||
267 | /// cv-qualifier mismatch) or prefer functions with an exact qualifier | |||
268 | /// match. | |||
269 | void setObjectTypeQualifiers(Qualifiers Quals, ExprValueKind Kind) { | |||
270 | ObjectTypeQualifiers = Quals; | |||
271 | ObjectKind = Kind; | |||
272 | HasObjectTypeQualifiers = true; | |||
273 | } | |||
274 | ||||
275 | /// Set the preferred selector. | |||
276 | /// | |||
277 | /// When an Objective-C method declaration result is added, and that | |||
278 | /// method's selector matches this preferred selector, we give that method | |||
279 | /// a slight priority boost. | |||
280 | void setPreferredSelector(Selector Sel) { PreferredSelector = Sel; } | |||
281 | ||||
282 | /// Retrieve the code-completion context for which results are | |||
283 | /// being collected. | |||
284 | const CodeCompletionContext &getCompletionContext() const { | |||
285 | return CompletionContext; | |||
286 | } | |||
287 | ||||
288 | /// Specify whether nested-name-specifiers are allowed. | |||
289 | void allowNestedNameSpecifiers(bool Allow = true) { | |||
290 | AllowNestedNameSpecifiers = Allow; | |||
291 | } | |||
292 | ||||
293 | /// Return the semantic analysis object for which we are collecting | |||
294 | /// code completion results. | |||
295 | Sema &getSema() const { return SemaRef; } | |||
296 | ||||
297 | /// Retrieve the allocator used to allocate code completion strings. | |||
298 | CodeCompletionAllocator &getAllocator() const { return Allocator; } | |||
299 | ||||
300 | CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo; } | |||
301 | ||||
302 | /// Determine whether the given declaration is at all interesting | |||
303 | /// as a code-completion result. | |||
304 | /// | |||
305 | /// \param ND the declaration that we are inspecting. | |||
306 | /// | |||
307 | /// \param AsNestedNameSpecifier will be set true if this declaration is | |||
308 | /// only interesting when it is a nested-name-specifier. | |||
309 | bool isInterestingDecl(const NamedDecl *ND, | |||
310 | bool &AsNestedNameSpecifier) const; | |||
311 | ||||
312 | /// Check whether the result is hidden by the Hiding declaration. | |||
313 | /// | |||
314 | /// \returns true if the result is hidden and cannot be found, false if | |||
315 | /// the hidden result could still be found. When false, \p R may be | |||
316 | /// modified to describe how the result can be found (e.g., via extra | |||
317 | /// qualification). | |||
318 | bool CheckHiddenResult(Result &R, DeclContext *CurContext, | |||
319 | const NamedDecl *Hiding); | |||
320 | ||||
321 | /// Add a new result to this result set (if it isn't already in one | |||
322 | /// of the shadow maps), or replace an existing result (for, e.g., a | |||
323 | /// redeclaration). | |||
324 | /// | |||
325 | /// \param R the result to add (if it is unique). | |||
326 | /// | |||
327 | /// \param CurContext the context in which this result will be named. | |||
328 | void MaybeAddResult(Result R, DeclContext *CurContext = nullptr); | |||
329 | ||||
330 | /// Add a new result to this result set, where we already know | |||
331 | /// the hiding declaration (if any). | |||
332 | /// | |||
333 | /// \param R the result to add (if it is unique). | |||
334 | /// | |||
335 | /// \param CurContext the context in which this result will be named. | |||
336 | /// | |||
337 | /// \param Hiding the declaration that hides the result. | |||
338 | /// | |||
339 | /// \param InBaseClass whether the result was found in a base | |||
340 | /// class of the searched context. | |||
341 | void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding, | |||
342 | bool InBaseClass); | |||
343 | ||||
344 | /// Add a new non-declaration result to this result set. | |||
345 | void AddResult(Result R); | |||
346 | ||||
347 | /// Enter into a new scope. | |||
348 | void EnterNewScope(); | |||
349 | ||||
350 | /// Exit from the current scope. | |||
351 | void ExitScope(); | |||
352 | ||||
353 | /// Ignore this declaration, if it is seen again. | |||
354 | void Ignore(const Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); } | |||
355 | ||||
356 | /// Add a visited context. | |||
357 | void addVisitedContext(DeclContext *Ctx) { | |||
358 | CompletionContext.addVisitedContext(Ctx); | |||
359 | } | |||
360 | ||||
361 | /// \name Name lookup predicates | |||
362 | /// | |||
363 | /// These predicates can be passed to the name lookup functions to filter the | |||
364 | /// results of name lookup. All of the predicates have the same type, so that | |||
365 | /// | |||
366 | //@{ | |||
367 | bool IsOrdinaryName(const NamedDecl *ND) const; | |||
368 | bool IsOrdinaryNonTypeName(const NamedDecl *ND) const; | |||
369 | bool IsIntegralConstantValue(const NamedDecl *ND) const; | |||
370 | bool IsOrdinaryNonValueName(const NamedDecl *ND) const; | |||
371 | bool IsNestedNameSpecifier(const NamedDecl *ND) const; | |||
372 | bool IsEnum(const NamedDecl *ND) const; | |||
373 | bool IsClassOrStruct(const NamedDecl *ND) const; | |||
374 | bool IsUnion(const NamedDecl *ND) const; | |||
375 | bool IsNamespace(const NamedDecl *ND) const; | |||
376 | bool IsNamespaceOrAlias(const NamedDecl *ND) const; | |||
377 | bool IsType(const NamedDecl *ND) const; | |||
378 | bool IsMember(const NamedDecl *ND) const; | |||
379 | bool IsObjCIvar(const NamedDecl *ND) const; | |||
380 | bool IsObjCMessageReceiver(const NamedDecl *ND) const; | |||
381 | bool IsObjCMessageReceiverOrLambdaCapture(const NamedDecl *ND) const; | |||
382 | bool IsObjCCollection(const NamedDecl *ND) const; | |||
383 | bool IsImpossibleToSatisfy(const NamedDecl *ND) const; | |||
384 | //@} | |||
385 | }; | |||
386 | } // namespace | |||
387 | ||||
388 | void PreferredTypeBuilder::enterReturn(Sema &S, SourceLocation Tok) { | |||
389 | if (!Enabled) | |||
390 | return; | |||
391 | if (isa<BlockDecl>(S.CurContext)) { | |||
392 | if (sema::BlockScopeInfo *BSI = S.getCurBlock()) { | |||
393 | ComputeType = nullptr; | |||
394 | Type = BSI->ReturnType; | |||
395 | ExpectedLoc = Tok; | |||
396 | } | |||
397 | } else if (const auto *Function = dyn_cast<FunctionDecl>(S.CurContext)) { | |||
398 | ComputeType = nullptr; | |||
399 | Type = Function->getReturnType(); | |||
400 | ExpectedLoc = Tok; | |||
401 | } else if (const auto *Method = dyn_cast<ObjCMethodDecl>(S.CurContext)) { | |||
402 | ComputeType = nullptr; | |||
403 | Type = Method->getReturnType(); | |||
404 | ExpectedLoc = Tok; | |||
405 | } | |||
406 | } | |||
407 | ||||
408 | void PreferredTypeBuilder::enterVariableInit(SourceLocation Tok, Decl *D) { | |||
409 | if (!Enabled) | |||
410 | return; | |||
411 | auto *VD = llvm::dyn_cast_or_null<ValueDecl>(D); | |||
412 | ComputeType = nullptr; | |||
413 | Type = VD ? VD->getType() : QualType(); | |||
414 | ExpectedLoc = Tok; | |||
415 | } | |||
416 | ||||
417 | static QualType getDesignatedType(QualType BaseType, const Designation &Desig); | |||
418 | ||||
419 | void PreferredTypeBuilder::enterDesignatedInitializer(SourceLocation Tok, | |||
420 | QualType BaseType, | |||
421 | const Designation &D) { | |||
422 | if (!Enabled) | |||
423 | return; | |||
424 | ComputeType = nullptr; | |||
425 | Type = getDesignatedType(BaseType, D); | |||
426 | ExpectedLoc = Tok; | |||
427 | } | |||
428 | ||||
429 | void PreferredTypeBuilder::enterFunctionArgument( | |||
430 | SourceLocation Tok, llvm::function_ref<QualType()> ComputeType) { | |||
431 | if (!Enabled) | |||
432 | return; | |||
433 | this->ComputeType = ComputeType; | |||
434 | Type = QualType(); | |||
435 | ExpectedLoc = Tok; | |||
436 | } | |||
437 | ||||
438 | void PreferredTypeBuilder::enterParenExpr(SourceLocation Tok, | |||
439 | SourceLocation LParLoc) { | |||
440 | if (!Enabled) | |||
441 | return; | |||
442 | // expected type for parenthesized expression does not change. | |||
443 | if (ExpectedLoc == LParLoc) | |||
444 | ExpectedLoc = Tok; | |||
445 | } | |||
446 | ||||
447 | static QualType getPreferredTypeOfBinaryRHS(Sema &S, Expr *LHS, | |||
448 | tok::TokenKind Op) { | |||
449 | if (!LHS) | |||
450 | return QualType(); | |||
451 | ||||
452 | QualType LHSType = LHS->getType(); | |||
453 | if (LHSType->isPointerType()) { | |||
454 | if (Op == tok::plus || Op == tok::plusequal || Op == tok::minusequal) | |||
455 | return S.getASTContext().getPointerDiffType(); | |||
456 | // Pointer difference is more common than subtracting an int from a pointer. | |||
457 | if (Op == tok::minus) | |||
458 | return LHSType; | |||
459 | } | |||
460 | ||||
461 | switch (Op) { | |||
462 | // No way to infer the type of RHS from LHS. | |||
463 | case tok::comma: | |||
464 | return QualType(); | |||
465 | // Prefer the type of the left operand for all of these. | |||
466 | // Arithmetic operations. | |||
467 | case tok::plus: | |||
468 | case tok::plusequal: | |||
469 | case tok::minus: | |||
470 | case tok::minusequal: | |||
471 | case tok::percent: | |||
472 | case tok::percentequal: | |||
473 | case tok::slash: | |||
474 | case tok::slashequal: | |||
475 | case tok::star: | |||
476 | case tok::starequal: | |||
477 | // Assignment. | |||
478 | case tok::equal: | |||
479 | // Comparison operators. | |||
480 | case tok::equalequal: | |||
481 | case tok::exclaimequal: | |||
482 | case tok::less: | |||
483 | case tok::lessequal: | |||
484 | case tok::greater: | |||
485 | case tok::greaterequal: | |||
486 | case tok::spaceship: | |||
487 | return LHS->getType(); | |||
488 | // Binary shifts are often overloaded, so don't try to guess those. | |||
489 | case tok::greatergreater: | |||
490 | case tok::greatergreaterequal: | |||
491 | case tok::lessless: | |||
492 | case tok::lesslessequal: | |||
493 | if (LHSType->isIntegralOrEnumerationType()) | |||
494 | return S.getASTContext().IntTy; | |||
495 | return QualType(); | |||
496 | // Logical operators, assume we want bool. | |||
497 | case tok::ampamp: | |||
498 | case tok::pipepipe: | |||
499 | case tok::caretcaret: | |||
500 | return S.getASTContext().BoolTy; | |||
501 | // Operators often used for bit manipulation are typically used with the type | |||
502 | // of the left argument. | |||
503 | case tok::pipe: | |||
504 | case tok::pipeequal: | |||
505 | case tok::caret: | |||
506 | case tok::caretequal: | |||
507 | case tok::amp: | |||
508 | case tok::ampequal: | |||
509 | if (LHSType->isIntegralOrEnumerationType()) | |||
510 | return LHSType; | |||
511 | return QualType(); | |||
512 | // RHS should be a pointer to a member of the 'LHS' type, but we can't give | |||
513 | // any particular type here. | |||
514 | case tok::periodstar: | |||
515 | case tok::arrowstar: | |||
516 | return QualType(); | |||
517 | default: | |||
518 | // FIXME(ibiryukov): handle the missing op, re-add the assertion. | |||
519 | // assert(false && "unhandled binary op"); | |||
520 | return QualType(); | |||
521 | } | |||
522 | } | |||
523 | ||||
524 | /// Get preferred type for an argument of an unary expression. \p ContextType is | |||
525 | /// preferred type of the whole unary expression. | |||
526 | static QualType getPreferredTypeOfUnaryArg(Sema &S, QualType ContextType, | |||
527 | tok::TokenKind Op) { | |||
528 | switch (Op) { | |||
529 | case tok::exclaim: | |||
530 | return S.getASTContext().BoolTy; | |||
531 | case tok::amp: | |||
532 | if (!ContextType.isNull() && ContextType->isPointerType()) | |||
533 | return ContextType->getPointeeType(); | |||
534 | return QualType(); | |||
535 | case tok::star: | |||
536 | if (ContextType.isNull()) | |||
537 | return QualType(); | |||
538 | return S.getASTContext().getPointerType(ContextType.getNonReferenceType()); | |||
539 | case tok::plus: | |||
540 | case tok::minus: | |||
541 | case tok::tilde: | |||
542 | case tok::minusminus: | |||
543 | case tok::plusplus: | |||
544 | if (ContextType.isNull()) | |||
545 | return S.getASTContext().IntTy; | |||
546 | // leave as is, these operators typically return the same type. | |||
547 | return ContextType; | |||
548 | case tok::kw___real: | |||
549 | case tok::kw___imag: | |||
550 | return QualType(); | |||
551 | default: | |||
552 | assert(false && "unhandled unary op")(static_cast <bool> (false && "unhandled unary op" ) ? void (0) : __assert_fail ("false && \"unhandled unary op\"" , "clang/lib/Sema/SemaCodeComplete.cpp", 552, __extension__ __PRETTY_FUNCTION__ )); | |||
553 | return QualType(); | |||
554 | } | |||
555 | } | |||
556 | ||||
557 | void PreferredTypeBuilder::enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, | |||
558 | tok::TokenKind Op) { | |||
559 | if (!Enabled) | |||
560 | return; | |||
561 | ComputeType = nullptr; | |||
562 | Type = getPreferredTypeOfBinaryRHS(S, LHS, Op); | |||
563 | ExpectedLoc = Tok; | |||
564 | } | |||
565 | ||||
566 | void PreferredTypeBuilder::enterMemAccess(Sema &S, SourceLocation Tok, | |||
567 | Expr *Base) { | |||
568 | if (!Enabled || !Base) | |||
569 | return; | |||
570 | // Do we have expected type for Base? | |||
571 | if (ExpectedLoc != Base->getBeginLoc()) | |||
572 | return; | |||
573 | // Keep the expected type, only update the location. | |||
574 | ExpectedLoc = Tok; | |||
575 | } | |||
576 | ||||
577 | void PreferredTypeBuilder::enterUnary(Sema &S, SourceLocation Tok, | |||
578 | tok::TokenKind OpKind, | |||
579 | SourceLocation OpLoc) { | |||
580 | if (!Enabled) | |||
581 | return; | |||
582 | ComputeType = nullptr; | |||
583 | Type = getPreferredTypeOfUnaryArg(S, this->get(OpLoc), OpKind); | |||
584 | ExpectedLoc = Tok; | |||
585 | } | |||
586 | ||||
587 | void PreferredTypeBuilder::enterSubscript(Sema &S, SourceLocation Tok, | |||
588 | Expr *LHS) { | |||
589 | if (!Enabled) | |||
590 | return; | |||
591 | ComputeType = nullptr; | |||
592 | Type = S.getASTContext().IntTy; | |||
593 | ExpectedLoc = Tok; | |||
594 | } | |||
595 | ||||
596 | void PreferredTypeBuilder::enterTypeCast(SourceLocation Tok, | |||
597 | QualType CastType) { | |||
598 | if (!Enabled) | |||
599 | return; | |||
600 | ComputeType = nullptr; | |||
601 | Type = !CastType.isNull() ? CastType.getCanonicalType() : QualType(); | |||
602 | ExpectedLoc = Tok; | |||
603 | } | |||
604 | ||||
605 | void PreferredTypeBuilder::enterCondition(Sema &S, SourceLocation Tok) { | |||
606 | if (!Enabled) | |||
607 | return; | |||
608 | ComputeType = nullptr; | |||
609 | Type = S.getASTContext().BoolTy; | |||
610 | ExpectedLoc = Tok; | |||
611 | } | |||
612 | ||||
613 | class ResultBuilder::ShadowMapEntry::iterator { | |||
614 | llvm::PointerUnion<const NamedDecl *, const DeclIndexPair *> DeclOrIterator; | |||
615 | unsigned SingleDeclIndex; | |||
616 | ||||
617 | public: | |||
618 | typedef DeclIndexPair value_type; | |||
619 | typedef value_type reference; | |||
620 | typedef std::ptrdiff_t difference_type; | |||
621 | typedef std::input_iterator_tag iterator_category; | |||
622 | ||||
623 | class pointer { | |||
624 | DeclIndexPair Value; | |||
625 | ||||
626 | public: | |||
627 | pointer(const DeclIndexPair &Value) : Value(Value) {} | |||
628 | ||||
629 | const DeclIndexPair *operator->() const { return &Value; } | |||
630 | }; | |||
631 | ||||
632 | iterator() : DeclOrIterator((NamedDecl *)nullptr), SingleDeclIndex(0) {} | |||
633 | ||||
634 | iterator(const NamedDecl *SingleDecl, unsigned Index) | |||
635 | : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) {} | |||
636 | ||||
637 | iterator(const DeclIndexPair *Iterator) | |||
638 | : DeclOrIterator(Iterator), SingleDeclIndex(0) {} | |||
639 | ||||
640 | iterator &operator++() { | |||
641 | if (DeclOrIterator.is<const NamedDecl *>()) { | |||
642 | DeclOrIterator = (NamedDecl *)nullptr; | |||
643 | SingleDeclIndex = 0; | |||
644 | return *this; | |||
645 | } | |||
646 | ||||
647 | const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair *>(); | |||
648 | ++I; | |||
649 | DeclOrIterator = I; | |||
650 | return *this; | |||
651 | } | |||
652 | ||||
653 | /*iterator operator++(int) { | |||
654 | iterator tmp(*this); | |||
655 | ++(*this); | |||
656 | return tmp; | |||
657 | }*/ | |||
658 | ||||
659 | reference operator*() const { | |||
660 | if (const NamedDecl *ND = DeclOrIterator.dyn_cast<const NamedDecl *>()) | |||
661 | return reference(ND, SingleDeclIndex); | |||
662 | ||||
663 | return *DeclOrIterator.get<const DeclIndexPair *>(); | |||
664 | } | |||
665 | ||||
666 | pointer operator->() const { return pointer(**this); } | |||
667 | ||||
668 | friend bool operator==(const iterator &X, const iterator &Y) { | |||
669 | return X.DeclOrIterator.getOpaqueValue() == | |||
670 | Y.DeclOrIterator.getOpaqueValue() && | |||
671 | X.SingleDeclIndex == Y.SingleDeclIndex; | |||
672 | } | |||
673 | ||||
674 | friend bool operator!=(const iterator &X, const iterator &Y) { | |||
675 | return !(X == Y); | |||
676 | } | |||
677 | }; | |||
678 | ||||
679 | ResultBuilder::ShadowMapEntry::iterator | |||
680 | ResultBuilder::ShadowMapEntry::begin() const { | |||
681 | if (DeclOrVector.isNull()) | |||
682 | return iterator(); | |||
683 | ||||
684 | if (const NamedDecl *ND = DeclOrVector.dyn_cast<const NamedDecl *>()) | |||
685 | return iterator(ND, SingleDeclIndex); | |||
686 | ||||
687 | return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin()); | |||
688 | } | |||
689 | ||||
690 | ResultBuilder::ShadowMapEntry::iterator | |||
691 | ResultBuilder::ShadowMapEntry::end() const { | |||
692 | if (DeclOrVector.is<const NamedDecl *>() || DeclOrVector.isNull()) | |||
693 | return iterator(); | |||
694 | ||||
695 | return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end()); | |||
696 | } | |||
697 | ||||
698 | /// Compute the qualification required to get from the current context | |||
699 | /// (\p CurContext) to the target context (\p TargetContext). | |||
700 | /// | |||
701 | /// \param Context the AST context in which the qualification will be used. | |||
702 | /// | |||
703 | /// \param CurContext the context where an entity is being named, which is | |||
704 | /// typically based on the current scope. | |||
705 | /// | |||
706 | /// \param TargetContext the context in which the named entity actually | |||
707 | /// resides. | |||
708 | /// | |||
709 | /// \returns a nested name specifier that refers into the target context, or | |||
710 | /// NULL if no qualification is needed. | |||
711 | static NestedNameSpecifier * | |||
712 | getRequiredQualification(ASTContext &Context, const DeclContext *CurContext, | |||
713 | const DeclContext *TargetContext) { | |||
714 | SmallVector<const DeclContext *, 4> TargetParents; | |||
715 | ||||
716 | for (const DeclContext *CommonAncestor = TargetContext; | |||
717 | CommonAncestor && !CommonAncestor->Encloses(CurContext); | |||
718 | CommonAncestor = CommonAncestor->getLookupParent()) { | |||
719 | if (CommonAncestor->isTransparentContext() || | |||
720 | CommonAncestor->isFunctionOrMethod()) | |||
721 | continue; | |||
722 | ||||
723 | TargetParents.push_back(CommonAncestor); | |||
724 | } | |||
725 | ||||
726 | NestedNameSpecifier *Result = nullptr; | |||
727 | while (!TargetParents.empty()) { | |||
728 | const DeclContext *Parent = TargetParents.pop_back_val(); | |||
729 | ||||
730 | if (const auto *Namespace = dyn_cast<NamespaceDecl>(Parent)) { | |||
731 | if (!Namespace->getIdentifier()) | |||
732 | continue; | |||
733 | ||||
734 | Result = NestedNameSpecifier::Create(Context, Result, Namespace); | |||
735 | } else if (const auto *TD = dyn_cast<TagDecl>(Parent)) | |||
736 | Result = NestedNameSpecifier::Create( | |||
737 | Context, Result, false, Context.getTypeDeclType(TD).getTypePtr()); | |||
738 | } | |||
739 | return Result; | |||
740 | } | |||
741 | ||||
742 | // Some declarations have reserved names that we don't want to ever show. | |||
743 | // Filter out names reserved for the implementation if they come from a | |||
744 | // system header. | |||
745 | static bool shouldIgnoreDueToReservedName(const NamedDecl *ND, Sema &SemaRef) { | |||
746 | ReservedIdentifierStatus Status = ND->isReserved(SemaRef.getLangOpts()); | |||
747 | // Ignore reserved names for compiler provided decls. | |||
748 | if (isReservedInAllContexts(Status) && 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 | ||||
762 | bool 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 | ||||
813 | bool 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. | |||
843 | SimplifiedTypeClass 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. | |||
912 | QualType 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 | ||||
969 | unsigned 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 | ||||
1017 | void 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 | ||||
1043 | static 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 | ||||
1052 | void 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 | ||||
1081 | static 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 | ||||
1087 | void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) { | |||
1088 | assert(!ShadowMaps.empty() && "Must enter into a results scope")(static_cast <bool> (!ShadowMaps.empty() && "Must enter into a results scope" ) ? void (0) : __assert_fail ("!ShadowMaps.empty() && \"Must enter into a results scope\"" , "clang/lib/Sema/SemaCodeComplete.cpp", 1088, __extension__ __PRETTY_FUNCTION__ )); | |||
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, false, | |||
1101 | (R.Availability == CXAvailability_Available || | |||
1102 | R.Availability == CXAvailability_Deprecated), | |||
1103 | std::move(R.FixIts)); | |||
1104 | Result.ShadowDecl = Using; | |||
1105 | MaybeAddResult(Result, CurContext); | |||
1106 | return; | |||
1107 | } | |||
1108 | ||||
1109 | const Decl *CanonDecl = R.Declaration->getCanonicalDecl(); | |||
1110 | unsigned IDNS = CanonDecl->getIdentifierNamespace(); | |||
1111 | ||||
1112 | bool AsNestedNameSpecifier = false; | |||
1113 | if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier)) | |||
1114 | return; | |||
1115 | ||||
1116 | // C++ constructors are never found by name lookup. | |||
1117 | if (isConstructor(R.Declaration)) | |||
1118 | return; | |||
1119 | ||||
1120 | ShadowMap &SMap = ShadowMaps.back(); | |||
1121 | ShadowMapEntry::iterator I, IEnd; | |||
1122 | ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName()); | |||
1123 | if (NamePos != SMap.end()) { | |||
1124 | I = NamePos->second.begin(); | |||
1125 | IEnd = NamePos->second.end(); | |||
1126 | } | |||
1127 | ||||
1128 | for (; I != IEnd; ++I) { | |||
1129 | const NamedDecl *ND = I->first; | |||
1130 | unsigned Index = I->second; | |||
1131 | if (ND->getCanonicalDecl() == CanonDecl) { | |||
1132 | // This is a redeclaration. Always pick the newer declaration. | |||
1133 | Results[Index].Declaration = R.Declaration; | |||
1134 | ||||
1135 | // We're done. | |||
1136 | return; | |||
1137 | } | |||
1138 | } | |||
1139 | ||||
1140 | // This is a new declaration in this scope. However, check whether this | |||
1141 | // declaration name is hidden by a similarly-named declaration in an outer | |||
1142 | // scope. | |||
1143 | std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end(); | |||
1144 | --SMEnd; | |||
1145 | for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) { | |||
1146 | ShadowMapEntry::iterator I, IEnd; | |||
1147 | ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName()); | |||
1148 | if (NamePos != SM->end()) { | |||
1149 | I = NamePos->second.begin(); | |||
1150 | IEnd = NamePos->second.end(); | |||
1151 | } | |||
1152 | for (; I != IEnd; ++I) { | |||
1153 | // A tag declaration does not hide a non-tag declaration. | |||
1154 | if (I->first->hasTagIdentifierNamespace() && | |||
1155 | (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary | | |||
1156 | Decl::IDNS_LocalExtern | Decl::IDNS_ObjCProtocol))) | |||
1157 | continue; | |||
1158 | ||||
1159 | // Protocols are in distinct namespaces from everything else. | |||
1160 | if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol) || | |||
1161 | (IDNS & Decl::IDNS_ObjCProtocol)) && | |||
1162 | I->first->getIdentifierNamespace() != IDNS) | |||
1163 | continue; | |||
1164 | ||||
1165 | // The newly-added result is hidden by an entry in the shadow map. | |||
1166 | if (CheckHiddenResult(R, CurContext, I->first)) | |||
1167 | return; | |||
1168 | ||||
1169 | break; | |||
1170 | } | |||
1171 | } | |||
1172 | ||||
1173 | // Make sure that any given declaration only shows up in the result set once. | |||
1174 | if (!AllDeclsFound.insert(CanonDecl).second) | |||
1175 | return; | |||
1176 | ||||
1177 | // If the filter is for nested-name-specifiers, then this result starts a | |||
1178 | // nested-name-specifier. | |||
1179 | if (AsNestedNameSpecifier) { | |||
1180 | R.StartsNestedNameSpecifier = true; | |||
1181 | R.Priority = CCP_NestedNameSpecifier; | |||
1182 | } else | |||
1183 | AdjustResultPriorityForDecl(R); | |||
1184 | ||||
1185 | // If this result is supposed to have an informative qualifier, add one. | |||
1186 | if (R.QualifierIsInformative && !R.Qualifier && | |||
1187 | !R.StartsNestedNameSpecifier) { | |||
1188 | const DeclContext *Ctx = R.Declaration->getDeclContext(); | |||
1189 | if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx)) | |||
1190 | R.Qualifier = | |||
1191 | NestedNameSpecifier::Create(SemaRef.Context, nullptr, Namespace); | |||
1192 | else if (const TagDecl *Tag = dyn_cast<TagDecl>(Ctx)) | |||
1193 | R.Qualifier = NestedNameSpecifier::Create( | |||
1194 | SemaRef.Context, nullptr, false, | |||
1195 | SemaRef.Context.getTypeDeclType(Tag).getTypePtr()); | |||
1196 | else | |||
1197 | R.QualifierIsInformative = false; | |||
1198 | } | |||
1199 | ||||
1200 | // Insert this result into the set of results and into the current shadow | |||
1201 | // map. | |||
1202 | SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size()); | |||
1203 | Results.push_back(R); | |||
1204 | ||||
1205 | if (!AsNestedNameSpecifier) | |||
1206 | MaybeAddConstructorResults(R); | |||
1207 | } | |||
1208 | ||||
1209 | static void setInBaseClass(ResultBuilder::Result &R) { | |||
1210 | R.Priority += CCD_InBaseClass; | |||
1211 | R.InBaseClass = true; | |||
1212 | } | |||
1213 | ||||
1214 | enum class OverloadCompare { BothViable, Dominates, Dominated }; | |||
1215 | // Will Candidate ever be called on the object, when overloaded with Incumbent? | |||
1216 | // Returns Dominates if Candidate is always called, Dominated if Incumbent is | |||
1217 | // always called, BothViable if either may be called depending on arguments. | |||
1218 | // Precondition: must actually be overloads! | |||
1219 | static OverloadCompare compareOverloads(const CXXMethodDecl &Candidate, | |||
1220 | const CXXMethodDecl &Incumbent, | |||
1221 | const Qualifiers &ObjectQuals, | |||
1222 | ExprValueKind ObjectKind) { | |||
1223 | // Base/derived shadowing is handled elsewhere. | |||
1224 | if (Candidate.getDeclContext() != Incumbent.getDeclContext()) | |||
1225 | return OverloadCompare::BothViable; | |||
1226 | if (Candidate.isVariadic() != Incumbent.isVariadic() || | |||
1227 | Candidate.getNumParams() != Incumbent.getNumParams() || | |||
1228 | Candidate.getMinRequiredArguments() != | |||
1229 | Incumbent.getMinRequiredArguments()) | |||
1230 | return OverloadCompare::BothViable; | |||
1231 | for (unsigned I = 0, E = Candidate.getNumParams(); I != E; ++I) | |||
1232 | if (Candidate.parameters()[I]->getType().getCanonicalType() != | |||
1233 | Incumbent.parameters()[I]->getType().getCanonicalType()) | |||
1234 | return OverloadCompare::BothViable; | |||
1235 | if (!Candidate.specific_attrs<EnableIfAttr>().empty() || | |||
1236 | !Incumbent.specific_attrs<EnableIfAttr>().empty()) | |||
1237 | return OverloadCompare::BothViable; | |||
1238 | // At this point, we know calls can't pick one or the other based on | |||
1239 | // arguments, so one of the two must win. (Or both fail, handled elsewhere). | |||
1240 | RefQualifierKind CandidateRef = Candidate.getRefQualifier(); | |||
1241 | RefQualifierKind IncumbentRef = Incumbent.getRefQualifier(); | |||
1242 | if (CandidateRef != IncumbentRef) { | |||
1243 | // If the object kind is LValue/RValue, there's one acceptable ref-qualifier | |||
1244 | // and it can't be mixed with ref-unqualified overloads (in valid code). | |||
1245 | ||||
1246 | // For xvalue objects, we prefer the rvalue overload even if we have to | |||
1247 | // add qualifiers (which is rare, because const&& is rare). | |||
1248 | if (ObjectKind == clang::VK_XValue) | |||
1249 | return CandidateRef == RQ_RValue ? OverloadCompare::Dominates | |||
1250 | : OverloadCompare::Dominated; | |||
1251 | } | |||
1252 | // Now the ref qualifiers are the same (or we're in some invalid state). | |||
1253 | // So make some decision based on the qualifiers. | |||
1254 | Qualifiers CandidateQual = Candidate.getMethodQualifiers(); | |||
1255 | Qualifiers IncumbentQual = Incumbent.getMethodQualifiers(); | |||
1256 | bool CandidateSuperset = CandidateQual.compatiblyIncludes(IncumbentQual); | |||
1257 | bool IncumbentSuperset = IncumbentQual.compatiblyIncludes(CandidateQual); | |||
1258 | if (CandidateSuperset == IncumbentSuperset) | |||
1259 | return OverloadCompare::BothViable; | |||
1260 | return IncumbentSuperset ? OverloadCompare::Dominates | |||
1261 | : OverloadCompare::Dominated; | |||
1262 | } | |||
1263 | ||||
1264 | void ResultBuilder::AddResult(Result R, DeclContext *CurContext, | |||
1265 | NamedDecl *Hiding, bool InBaseClass = false) { | |||
1266 | if (R.Kind != Result::RK_Declaration) { | |||
1267 | // For non-declaration results, just add the result. | |||
1268 | Results.push_back(R); | |||
1269 | return; | |||
1270 | } | |||
1271 | ||||
1272 | // Look through using declarations. | |||
1273 | if (const auto *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) { | |||
1274 | CodeCompletionResult Result(Using->getTargetDecl(), | |||
1275 | getBasePriority(Using->getTargetDecl()), | |||
1276 | R.Qualifier, false, | |||
1277 | (R.Availability == CXAvailability_Available || | |||
1278 | R.Availability == CXAvailability_Deprecated), | |||
1279 | std::move(R.FixIts)); | |||
1280 | Result.ShadowDecl = Using; | |||
1281 | AddResult(Result, CurContext, Hiding); | |||
1282 | return; | |||
1283 | } | |||
1284 | ||||
1285 | bool AsNestedNameSpecifier = false; | |||
1286 | if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier)) | |||
1287 | return; | |||
1288 | ||||
1289 | // C++ constructors are never found by name lookup. | |||
1290 | if (isConstructor(R.Declaration)) | |||
1291 | return; | |||
1292 | ||||
1293 | if (Hiding && CheckHiddenResult(R, CurContext, Hiding)) | |||
1294 | return; | |||
1295 | ||||
1296 | // Make sure that any given declaration only shows up in the result set once. | |||
1297 | if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()).second) | |||
1298 | return; | |||
1299 | ||||
1300 | // If the filter is for nested-name-specifiers, then this result starts a | |||
1301 | // nested-name-specifier. | |||
1302 | if (AsNestedNameSpecifier) { | |||
1303 | R.StartsNestedNameSpecifier = true; | |||
1304 | R.Priority = CCP_NestedNameSpecifier; | |||
1305 | } else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && | |||
1306 | InBaseClass && | |||
1307 | isa<CXXRecordDecl>( | |||
1308 | R.Declaration->getDeclContext()->getRedeclContext())) | |||
1309 | R.QualifierIsInformative = true; | |||
1310 | ||||
1311 | // If this result is supposed to have an informative qualifier, add one. | |||
1312 | if (R.QualifierIsInformative && !R.Qualifier && | |||
1313 | !R.StartsNestedNameSpecifier) { | |||
1314 | const DeclContext *Ctx = R.Declaration->getDeclContext(); | |||
1315 | if (const auto *Namespace = dyn_cast<NamespaceDecl>(Ctx)) | |||
1316 | R.Qualifier = | |||
1317 | NestedNameSpecifier::Create(SemaRef.Context, nullptr, Namespace); | |||
1318 | else if (const auto *Tag = dyn_cast<TagDecl>(Ctx)) | |||
1319 | R.Qualifier = NestedNameSpecifier::Create( | |||
1320 | SemaRef.Context, nullptr, false, | |||
1321 | SemaRef.Context.getTypeDeclType(Tag).getTypePtr()); | |||
1322 | else | |||
1323 | R.QualifierIsInformative = false; | |||
1324 | } | |||
1325 | ||||
1326 | // Adjust the priority if this result comes from a base class. | |||
1327 | if (InBaseClass) | |||
1328 | setInBaseClass(R); | |||
1329 | ||||
1330 | AdjustResultPriorityForDecl(R); | |||
1331 | ||||
1332 | if (HasObjectTypeQualifiers) | |||
1333 | if (const auto *Method = dyn_cast<CXXMethodDecl>(R.Declaration)) | |||
1334 | if (Method->isInstance()) { | |||
1335 | Qualifiers MethodQuals = Method->getMethodQualifiers(); | |||
1336 | if (ObjectTypeQualifiers == MethodQuals) | |||
1337 | R.Priority += CCD_ObjectQualifierMatch; | |||
1338 | else if (ObjectTypeQualifiers - MethodQuals) { | |||
1339 | // The method cannot be invoked, because doing so would drop | |||
1340 | // qualifiers. | |||
1341 | return; | |||
1342 | } | |||
1343 | // Detect cases where a ref-qualified method cannot be invoked. | |||
1344 | switch (Method->getRefQualifier()) { | |||
1345 | case RQ_LValue: | |||
1346 | if (ObjectKind != VK_LValue && !MethodQuals.hasConst()) | |||
1347 | return; | |||
1348 | break; | |||
1349 | case RQ_RValue: | |||
1350 | if (ObjectKind == VK_LValue) | |||
1351 | return; | |||
1352 | break; | |||
1353 | case RQ_None: | |||
1354 | break; | |||
1355 | } | |||
1356 | ||||
1357 | /// Check whether this dominates another overloaded method, which should | |||
1358 | /// be suppressed (or vice versa). | |||
1359 | /// Motivating case is const_iterator begin() const vs iterator begin(). | |||
1360 | auto &OverloadSet = OverloadMap[std::make_pair( | |||
1361 | CurContext, Method->getDeclName().getAsOpaqueInteger())]; | |||
1362 | for (const DeclIndexPair Entry : OverloadSet) { | |||
1363 | Result &Incumbent = Results[Entry.second]; | |||
1364 | switch (compareOverloads(*Method, | |||
1365 | *cast<CXXMethodDecl>(Incumbent.Declaration), | |||
1366 | ObjectTypeQualifiers, ObjectKind)) { | |||
1367 | case OverloadCompare::Dominates: | |||
1368 | // Replace the dominated overload with this one. | |||
1369 | // FIXME: if the overload dominates multiple incumbents then we | |||
1370 | // should remove all. But two overloads is by far the common case. | |||
1371 | Incumbent = std::move(R); | |||
1372 | return; | |||
1373 | case OverloadCompare::Dominated: | |||
1374 | // This overload can't be called, drop it. | |||
1375 | return; | |||
1376 | case OverloadCompare::BothViable: | |||
1377 | break; | |||
1378 | } | |||
1379 | } | |||
1380 | OverloadSet.Add(Method, Results.size()); | |||
1381 | } | |||
1382 | ||||
1383 | // When completing a non-static member function (and not via | |||
1384 | // dot/arrow member access) and we're not inside that class' scope, | |||
1385 | // it can't be a call. | |||
1386 | if (CompletionContext.getKind() == clang::CodeCompletionContext::CCC_Symbol) { | |||
1387 | const auto *Method = dyn_cast<CXXMethodDecl>(R.getDeclaration()); | |||
1388 | if (Method && !Method->isStatic()) { | |||
1389 | // Find the class scope that we're currently in. | |||
1390 | // We could e.g. be inside a lambda, so walk up the DeclContext until we | |||
1391 | // find a CXXMethodDecl. | |||
1392 | const auto *CurrentClassScope = [&]() -> const CXXRecordDecl * { | |||
1393 | for (DeclContext *Ctx = SemaRef.CurContext; Ctx; | |||
1394 | Ctx = Ctx->getParent()) { | |||
1395 | const auto *CtxMethod = llvm::dyn_cast<CXXMethodDecl>(Ctx); | |||
1396 | if (CtxMethod && !CtxMethod->getParent()->isLambda()) { | |||
1397 | return CtxMethod->getParent(); | |||
1398 | } | |||
1399 | } | |||
1400 | return nullptr; | |||
1401 | }(); | |||
1402 | ||||
1403 | R.FunctionCanBeCall = | |||
1404 | CurrentClassScope && | |||
1405 | (CurrentClassScope == Method->getParent() || | |||
1406 | CurrentClassScope->isDerivedFrom(Method->getParent())); | |||
1407 | } | |||
1408 | } | |||
1409 | ||||
1410 | // Insert this result into the set of results. | |||
1411 | Results.push_back(R); | |||
1412 | ||||
1413 | if (!AsNestedNameSpecifier) | |||
1414 | MaybeAddConstructorResults(R); | |||
1415 | } | |||
1416 | ||||
1417 | void ResultBuilder::AddResult(Result R) { | |||
1418 | assert(R.Kind != Result::RK_Declaration &&(static_cast <bool> (R.Kind != Result::RK_Declaration && "Declaration results need more context") ? void (0) : __assert_fail ("R.Kind != Result::RK_Declaration && \"Declaration results need more context\"" , "clang/lib/Sema/SemaCodeComplete.cpp", 1419, __extension__ __PRETTY_FUNCTION__ )) | |||
1419 | "Declaration results need more context")(static_cast <bool> (R.Kind != Result::RK_Declaration && "Declaration results need more context") ? void (0) : __assert_fail ("R.Kind != Result::RK_Declaration && \"Declaration results need more context\"" , "clang/lib/Sema/SemaCodeComplete.cpp", 1419, __extension__ __PRETTY_FUNCTION__ )); | |||
1420 | Results.push_back(R); | |||
1421 | } | |||
1422 | ||||
1423 | /// Enter into a new scope. | |||
1424 | void ResultBuilder::EnterNewScope() { ShadowMaps.emplace_back(); } | |||
1425 | ||||
1426 | /// Exit from the current scope. | |||
1427 | void ResultBuilder::ExitScope() { | |||
1428 | ShadowMaps.pop_back(); | |||
1429 | } | |||
1430 | ||||
1431 | /// Determines whether this given declaration will be found by | |||
1432 | /// ordinary name lookup. | |||
1433 | bool ResultBuilder::IsOrdinaryName(const NamedDecl *ND) const { | |||
1434 | ND = ND->getUnderlyingDecl(); | |||
1435 | ||||
1436 | // If name lookup finds a local extern declaration, then we are in a | |||
1437 | // context where it behaves like an ordinary name. | |||
1438 | unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern; | |||
1439 | if (SemaRef.getLangOpts().CPlusPlus) | |||
1440 | IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member; | |||
1441 | else if (SemaRef.getLangOpts().ObjC) { | |||
1442 | if (isa<ObjCIvarDecl>(ND)) | |||
1443 | return true; | |||
1444 | } | |||
1445 | ||||
1446 | return ND->getIdentifierNamespace() & IDNS; | |||
1447 | } | |||
1448 | ||||
1449 | /// Determines whether this given declaration will be found by | |||
1450 | /// ordinary name lookup but is not a type name. | |||
1451 | bool ResultBuilder::IsOrdinaryNonTypeName(const NamedDecl *ND) const { | |||
1452 | ND = ND->getUnderlyingDecl(); | |||
1453 | if (isa<TypeDecl>(ND)) | |||
1454 | return false; | |||
1455 | // Objective-C interfaces names are not filtered by this method because they | |||
1456 | // can be used in a class property expression. We can still filter out | |||
1457 | // @class declarations though. | |||
1458 | if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND)) { | |||
1459 | if (!ID->getDefinition()) | |||
1460 | return false; | |||
1461 | } | |||
1462 | ||||
1463 | unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern; | |||
1464 | if (SemaRef.getLangOpts().CPlusPlus) | |||
1465 | IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member; | |||
1466 | else if (SemaRef.getLangOpts().ObjC) { | |||
1467 | if (isa<ObjCIvarDecl>(ND)) | |||
1468 | return true; | |||
1469 | } | |||
1470 | ||||
1471 | return ND->getIdentifierNamespace() & IDNS; | |||
1472 | } | |||
1473 | ||||
1474 | bool ResultBuilder::IsIntegralConstantValue(const NamedDecl *ND) const { | |||
1475 | if (!IsOrdinaryNonTypeName(ND)) | |||
1476 | return false; | |||
1477 | ||||
1478 | if (const auto *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl())) | |||
1479 | if (VD->getType()->isIntegralOrEnumerationType()) | |||
1480 | return true; | |||
1481 | ||||
1482 | return false; | |||
1483 | } | |||
1484 | ||||
1485 | /// Determines whether this given declaration will be found by | |||
1486 | /// ordinary name lookup. | |||
1487 | bool ResultBuilder::IsOrdinaryNonValueName(const NamedDecl *ND) const { | |||
1488 | ND = ND->getUnderlyingDecl(); | |||
1489 | ||||
1490 | unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern; | |||
1491 | if (SemaRef.getLangOpts().CPlusPlus) | |||
1492 | IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace; | |||
1493 | ||||
1494 | return (ND->getIdentifierNamespace() & IDNS) && !isa<ValueDecl>(ND) && | |||
1495 | !isa<FunctionTemplateDecl>(ND) && !isa<ObjCPropertyDecl>(ND); | |||
1496 | } | |||
1497 | ||||
1498 | /// Determines whether the given declaration is suitable as the | |||
1499 | /// start of a C++ nested-name-specifier, e.g., a class or namespace. | |||
1500 | bool ResultBuilder::IsNestedNameSpecifier(const NamedDecl *ND) const { | |||
1501 | // Allow us to find class templates, too. | |||
1502 | if (const auto *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND)) | |||
1503 | ND = ClassTemplate->getTemplatedDecl(); | |||
1504 | ||||
1505 | return SemaRef.isAcceptableNestedNameSpecifier(ND); | |||
1506 | } | |||
1507 | ||||
1508 | /// Determines whether the given declaration is an enumeration. | |||
1509 | bool ResultBuilder::IsEnum(const NamedDecl *ND) const { | |||
1510 | return isa<EnumDecl>(ND); | |||
1511 | } | |||
1512 | ||||
1513 | /// Determines whether the given declaration is a class or struct. | |||
1514 | bool ResultBuilder::IsClassOrStruct(const NamedDecl *ND) const { | |||
1515 | // Allow us to find class templates, too. | |||
1516 | if (const auto *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND)) | |||
1517 | ND = ClassTemplate->getTemplatedDecl(); | |||
1518 | ||||
1519 | // For purposes of this check, interfaces match too. | |||
1520 | if (const auto *RD = dyn_cast<RecordDecl>(ND)) | |||
1521 | return RD->getTagKind() == TTK_Class || RD->getTagKind() == TTK_Struct || | |||
1522 | RD->getTagKind() == TTK_Interface; | |||
1523 | ||||
1524 | return false; | |||
1525 | } | |||
1526 | ||||
1527 | /// Determines whether the given declaration is a union. | |||
1528 | bool ResultBuilder::IsUnion(const NamedDecl *ND) const { | |||
1529 | // Allow us to find class templates, too. | |||
1530 | if (const auto *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND)) | |||
1531 | ND = ClassTemplate->getTemplatedDecl(); | |||
1532 | ||||
1533 | if (const auto *RD = dyn_cast<RecordDecl>(ND)) | |||
1534 | return RD->getTagKind() == TTK_Union; | |||
1535 | ||||
1536 | return false; | |||
1537 | } | |||
1538 | ||||
1539 | /// Determines whether the given declaration is a namespace. | |||
1540 | bool ResultBuilder::IsNamespace(const NamedDecl *ND) const { | |||
1541 | return isa<NamespaceDecl>(ND); | |||
1542 | } | |||
1543 | ||||
1544 | /// Determines whether the given declaration is a namespace or | |||
1545 | /// namespace alias. | |||
1546 | bool ResultBuilder::IsNamespaceOrAlias(const NamedDecl *ND) const { | |||
1547 | return isa<NamespaceDecl>(ND->getUnderlyingDecl()); | |||
1548 | } | |||
1549 | ||||
1550 | /// Determines whether the given declaration is a type. | |||
1551 | bool ResultBuilder::IsType(const NamedDecl *ND) const { | |||
1552 | ND = ND->getUnderlyingDecl(); | |||
1553 | return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); | |||
1554 | } | |||
1555 | ||||
1556 | /// Determines which members of a class should be visible via | |||
1557 | /// "." or "->". Only value declarations, nested name specifiers, and | |||
1558 | /// using declarations thereof should show up. | |||
1559 | bool ResultBuilder::IsMember(const NamedDecl *ND) const { | |||
1560 | ND = ND->getUnderlyingDecl(); | |||
1561 | return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) || | |||
1562 | isa<ObjCPropertyDecl>(ND); | |||
1563 | } | |||
1564 | ||||
1565 | static bool isObjCReceiverType(ASTContext &C, QualType T) { | |||
1566 | T = C.getCanonicalType(T); | |||
1567 | switch (T->getTypeClass()) { | |||
1568 | case Type::ObjCObject: | |||
1569 | case Type::ObjCInterface: | |||
1570 | case Type::ObjCObjectPointer: | |||
1571 | return true; | |||
1572 | ||||
1573 | case Type::Builtin: | |||
1574 | switch (cast<BuiltinType>(T)->getKind()) { | |||
1575 | case BuiltinType::ObjCId: | |||
1576 | case BuiltinType::ObjCClass: | |||
1577 | case BuiltinType::ObjCSel: | |||
1578 | return true; | |||
1579 | ||||
1580 | default: | |||
1581 | break; | |||
1582 | } | |||
1583 | return false; | |||
1584 | ||||
1585 | default: | |||
1586 | break; | |||
1587 | } | |||
1588 | ||||
1589 | if (!C.getLangOpts().CPlusPlus) | |||
1590 | return false; | |||
1591 | ||||
1592 | // FIXME: We could perform more analysis here to determine whether a | |||
1593 | // particular class type has any conversions to Objective-C types. For now, | |||
1594 | // just accept all class types. | |||
1595 | return T->isDependentType() || T->isRecordType(); | |||
1596 | } | |||
1597 | ||||
1598 | bool ResultBuilder::IsObjCMessageReceiver(const NamedDecl *ND) const { | |||
1599 | QualType T = getDeclUsageType(SemaRef.Context, ND); | |||
1600 | if (T.isNull()) | |||
1601 | return false; | |||
1602 | ||||
1603 | T = SemaRef.Context.getBaseElementType(T); | |||
1604 | return isObjCReceiverType(SemaRef.Context, T); | |||
1605 | } | |||
1606 | ||||
1607 | bool ResultBuilder::IsObjCMessageReceiverOrLambdaCapture( | |||
1608 | const NamedDecl *ND) const { | |||
1609 | if (IsObjCMessageReceiver(ND)) | |||
1610 | return true; | |||
1611 | ||||
1612 | const auto *Var = dyn_cast<VarDecl>(ND); | |||
1613 | if (!Var) | |||
1614 | return false; | |||
1615 | ||||
1616 | return Var->hasLocalStorage() && !Var->hasAttr<BlocksAttr>(); | |||
1617 | } | |||
1618 | ||||
1619 | bool ResultBuilder::IsObjCCollection(const NamedDecl *ND) const { | |||
1620 | if ((SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryName(ND)) || | |||
1621 | (!SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryNonTypeName(ND))) | |||
1622 | return false; | |||
1623 | ||||
1624 | QualType T = getDeclUsageType(SemaRef.Context, ND); | |||
1625 | if (T.isNull()) | |||
1626 | return false; | |||
1627 | ||||
1628 | T = SemaRef.Context.getBaseElementType(T); | |||
1629 | return T->isObjCObjectType() || T->isObjCObjectPointerType() || | |||
1630 | T->isObjCIdType() || | |||
1631 | (SemaRef.getLangOpts().CPlusPlus && T->isRecordType()); | |||
1632 | } | |||
1633 | ||||
1634 | bool ResultBuilder::IsImpossibleToSatisfy(const NamedDecl *ND) const { | |||
1635 | return false; | |||
1636 | } | |||
1637 | ||||
1638 | /// Determines whether the given declaration is an Objective-C | |||
1639 | /// instance variable. | |||
1640 | bool ResultBuilder::IsObjCIvar(const NamedDecl *ND) const { | |||
1641 | return isa<ObjCIvarDecl>(ND); | |||
1642 | } | |||
1643 | ||||
1644 | namespace { | |||
1645 | ||||
1646 | /// Visible declaration consumer that adds a code-completion result | |||
1647 | /// for each visible declaration. | |||
1648 | class CodeCompletionDeclConsumer : public VisibleDeclConsumer { | |||
1649 | ResultBuilder &Results; | |||
1650 | DeclContext *InitialLookupCtx; | |||
1651 | // NamingClass and BaseType are used for access-checking. See | |||
1652 | // Sema::IsSimplyAccessible for details. | |||
1653 | CXXRecordDecl *NamingClass; | |||
1654 | QualType BaseType; | |||
1655 | std::vector<FixItHint> FixIts; | |||
1656 | ||||
1657 | public: | |||
1658 | CodeCompletionDeclConsumer( | |||
1659 | ResultBuilder &Results, DeclContext *InitialLookupCtx, | |||
1660 | QualType BaseType = QualType(), | |||
1661 | std::vector<FixItHint> FixIts = std::vector<FixItHint>()) | |||
1662 | : Results(Results), InitialLookupCtx(InitialLookupCtx), | |||
1663 | FixIts(std::move(FixIts)) { | |||
1664 | NamingClass = llvm::dyn_cast<CXXRecordDecl>(InitialLookupCtx); | |||
1665 | // If BaseType was not provided explicitly, emulate implicit 'this->'. | |||
1666 | if (BaseType.isNull()) { | |||
1667 | auto ThisType = Results.getSema().getCurrentThisType(); | |||
1668 | if (!ThisType.isNull()) { | |||
1669 | assert(ThisType->isPointerType())(static_cast <bool> (ThisType->isPointerType()) ? void (0) : __assert_fail ("ThisType->isPointerType()", "clang/lib/Sema/SemaCodeComplete.cpp" , 1669, __extension__ __PRETTY_FUNCTION__)); | |||
1670 | BaseType = ThisType->getPointeeType(); | |||
1671 | if (!NamingClass) | |||
1672 | NamingClass = BaseType->getAsCXXRecordDecl(); | |||
1673 | } | |||
1674 | } | |||
1675 | this->BaseType = BaseType; | |||
1676 | } | |||
1677 | ||||
1678 | void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx, | |||
1679 | bool InBaseClass) override { | |||
1680 | ResultBuilder::Result Result(ND, Results.getBasePriority(ND), nullptr, | |||
1681 | false, IsAccessible(ND, Ctx), FixIts); | |||
1682 | Results.AddResult(Result, InitialLookupCtx, Hiding, InBaseClass); | |||
1683 | } | |||
1684 | ||||
1685 | void EnteredContext(DeclContext *Ctx) override { | |||
1686 | Results.addVisitedContext(Ctx); | |||
1687 | } | |||
1688 | ||||
1689 | private: | |||
1690 | bool IsAccessible(NamedDecl *ND, DeclContext *Ctx) { | |||
1691 | // Naming class to use for access check. In most cases it was provided | |||
1692 | // explicitly (e.g. member access (lhs.foo) or qualified lookup (X::)), | |||
1693 | // for unqualified lookup we fallback to the \p Ctx in which we found the | |||
1694 | // member. | |||
1695 | auto *NamingClass = this->NamingClass; | |||
1696 | QualType BaseType = this->BaseType; | |||
1697 | if (auto *Cls = llvm::dyn_cast_or_null<CXXRecordDecl>(Ctx)) { | |||
1698 | if (!NamingClass) | |||
1699 | NamingClass = Cls; | |||
1700 | // When we emulate implicit 'this->' in an unqualified lookup, we might | |||
1701 | // end up with an invalid naming class. In that case, we avoid emulating | |||
1702 | // 'this->' qualifier to satisfy preconditions of the access checking. | |||
1703 | if (NamingClass->getCanonicalDecl() != Cls->getCanonicalDecl() && | |||
1704 | !NamingClass->isDerivedFrom(Cls)) { | |||
1705 | NamingClass = Cls; | |||
1706 | BaseType = QualType(); | |||
1707 | } | |||
1708 | } else { | |||
1709 | // The decl was found outside the C++ class, so only ObjC access checks | |||
1710 | // apply. Those do not rely on NamingClass and BaseType, so we clear them | |||
1711 | // out. | |||
1712 | NamingClass = nullptr; | |||
1713 | BaseType = QualType(); | |||
1714 | } | |||
1715 | return Results.getSema().IsSimplyAccessible(ND, NamingClass, BaseType); | |||
1716 | } | |||
1717 | }; | |||
1718 | } // namespace | |||
1719 | ||||
1720 | /// Add type specifiers for the current language as keyword results. | |||
1721 | static void AddTypeSpecifierResults(const LangOptions &LangOpts, | |||
1722 | ResultBuilder &Results) { | |||
1723 | typedef CodeCompletionResult Result; | |||
1724 | Results.AddResult(Result("short", CCP_Type)); | |||
1725 | Results.AddResult(Result("long", CCP_Type)); | |||
1726 | Results.AddResult(Result("signed", CCP_Type)); | |||
1727 | Results.AddResult(Result("unsigned", CCP_Type)); | |||
1728 | Results.AddResult(Result("void", CCP_Type)); | |||
1729 | Results.AddResult(Result("char", CCP_Type)); | |||
1730 | Results.AddResult(Result("int", CCP_Type)); | |||
1731 | Results.AddResult(Result("float", CCP_Type)); | |||
1732 | Results.AddResult(Result("double", CCP_Type)); | |||
1733 | Results.AddResult(Result("enum", CCP_Type)); | |||
1734 | Results.AddResult(Result("struct", CCP_Type)); | |||
1735 | Results.AddResult(Result("union", CCP_Type)); | |||
1736 | Results.AddResult(Result("const", CCP_Type)); | |||
1737 | Results.AddResult(Result("volatile", CCP_Type)); | |||
1738 | ||||
1739 | if (LangOpts.C99) { | |||
1740 | // C99-specific | |||
1741 | Results.AddResult(Result("_Complex", CCP_Type)); | |||
1742 | Results.AddResult(Result("_Imaginary", CCP_Type)); | |||
1743 | Results.AddResult(Result("_Bool", CCP_Type)); | |||
1744 | Results.AddResult(Result("restrict", CCP_Type)); | |||
1745 | } | |||
1746 | ||||
1747 | CodeCompletionBuilder Builder(Results.getAllocator(), | |||
1748 | Results.getCodeCompletionTUInfo()); | |||
1749 | if (LangOpts.CPlusPlus) { | |||
1750 | // C++-specific | |||
1751 | Results.AddResult( | |||
1752 | Result("bool", CCP_Type + (LangOpts.ObjC ? CCD_bool_in_ObjC : 0))); | |||
1753 | Results.AddResult(Result("class", CCP_Type)); | |||
1754 | Results.AddResult(Result("wchar_t", CCP_Type)); | |||
1755 | ||||
1756 | // typename name | |||
1757 | Builder.AddTypedTextChunk("typename"); | |||
1758 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
1759 | Builder.AddPlaceholderChunk("name"); | |||
1760 | Results.AddResult(Result(Builder.TakeString())); | |||
1761 | ||||
1762 | if (LangOpts.CPlusPlus11) { | |||
1763 | Results.AddResult(Result("auto", CCP_Type)); | |||
1764 | Results.AddResult(Result("char16_t", CCP_Type)); | |||
1765 | Results.AddResult(Result("char32_t", CCP_Type)); | |||
1766 | ||||
1767 | Builder.AddTypedTextChunk("decltype"); | |||
1768 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
1769 | Builder.AddPlaceholderChunk("expression"); | |||
1770 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
1771 | Results.AddResult(Result(Builder.TakeString())); | |||
1772 | } | |||
1773 | } else | |||
1774 | Results.AddResult(Result("__auto_type", CCP_Type)); | |||
1775 | ||||
1776 | // GNU keywords | |||
1777 | if (LangOpts.GNUKeywords) { | |||
1778 | // FIXME: Enable when we actually support decimal floating point. | |||
1779 | // Results.AddResult(Result("_Decimal32")); | |||
1780 | // Results.AddResult(Result("_Decimal64")); | |||
1781 | // Results.AddResult(Result("_Decimal128")); | |||
1782 | ||||
1783 | Builder.AddTypedTextChunk("typeof"); | |||
1784 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
1785 | Builder.AddPlaceholderChunk("expression"); | |||
1786 | Results.AddResult(Result(Builder.TakeString())); | |||
1787 | ||||
1788 | Builder.AddTypedTextChunk("typeof"); | |||
1789 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
1790 | Builder.AddPlaceholderChunk("type"); | |||
1791 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
1792 | Results.AddResult(Result(Builder.TakeString())); | |||
1793 | } | |||
1794 | ||||
1795 | // Nullability | |||
1796 | Results.AddResult(Result("_Nonnull", CCP_Type)); | |||
1797 | Results.AddResult(Result("_Null_unspecified", CCP_Type)); | |||
1798 | Results.AddResult(Result("_Nullable", CCP_Type)); | |||
1799 | } | |||
1800 | ||||
1801 | static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC, | |||
1802 | const LangOptions &LangOpts, | |||
1803 | ResultBuilder &Results) { | |||
1804 | typedef CodeCompletionResult Result; | |||
1805 | // Note: we don't suggest either "auto" or "register", because both | |||
1806 | // are pointless as storage specifiers. Elsewhere, we suggest "auto" | |||
1807 | // in C++0x as a type specifier. | |||
1808 | Results.AddResult(Result("extern")); | |||
1809 | Results.AddResult(Result("static")); | |||
1810 | ||||
1811 | if (LangOpts.CPlusPlus11) { | |||
1812 | CodeCompletionAllocator &Allocator = Results.getAllocator(); | |||
1813 | CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo()); | |||
1814 | ||||
1815 | // alignas | |||
1816 | Builder.AddTypedTextChunk("alignas"); | |||
1817 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
1818 | Builder.AddPlaceholderChunk("expression"); | |||
1819 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
1820 | Results.AddResult(Result(Builder.TakeString())); | |||
1821 | ||||
1822 | Results.AddResult(Result("constexpr")); | |||
1823 | Results.AddResult(Result("thread_local")); | |||
1824 | } | |||
1825 | } | |||
1826 | ||||
1827 | static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC, | |||
1828 | const LangOptions &LangOpts, | |||
1829 | ResultBuilder &Results) { | |||
1830 | typedef CodeCompletionResult Result; | |||
1831 | switch (CCC) { | |||
1832 | case Sema::PCC_Class: | |||
1833 | case Sema::PCC_MemberTemplate: | |||
1834 | if (LangOpts.CPlusPlus) { | |||
1835 | Results.AddResult(Result("explicit")); | |||
1836 | Results.AddResult(Result("friend")); | |||
1837 | Results.AddResult(Result("mutable")); | |||
1838 | Results.AddResult(Result("virtual")); | |||
1839 | } | |||
1840 | [[fallthrough]]; | |||
1841 | ||||
1842 | case Sema::PCC_ObjCInterface: | |||
1843 | case Sema::PCC_ObjCImplementation: | |||
1844 | case Sema::PCC_Namespace: | |||
1845 | case Sema::PCC_Template: | |||
1846 | if (LangOpts.CPlusPlus || LangOpts.C99) | |||
1847 | Results.AddResult(Result("inline")); | |||
1848 | break; | |||
1849 | ||||
1850 | case Sema::PCC_ObjCInstanceVariableList: | |||
1851 | case Sema::PCC_Expression: | |||
1852 | case Sema::PCC_Statement: | |||
1853 | case Sema::PCC_ForInit: | |||
1854 | case Sema::PCC_Condition: | |||
1855 | case Sema::PCC_RecoveryInFunction: | |||
1856 | case Sema::PCC_Type: | |||
1857 | case Sema::PCC_ParenthesizedExpression: | |||
1858 | case Sema::PCC_LocalDeclarationSpecifiers: | |||
1859 | break; | |||
1860 | } | |||
1861 | } | |||
1862 | ||||
1863 | static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt); | |||
1864 | static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt); | |||
1865 | static void AddObjCVisibilityResults(const LangOptions &LangOpts, | |||
1866 | ResultBuilder &Results, bool NeedAt); | |||
1867 | static void AddObjCImplementationResults(const LangOptions &LangOpts, | |||
1868 | ResultBuilder &Results, bool NeedAt); | |||
1869 | static void AddObjCInterfaceResults(const LangOptions &LangOpts, | |||
1870 | ResultBuilder &Results, bool NeedAt); | |||
1871 | static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt); | |||
1872 | ||||
1873 | static void AddTypedefResult(ResultBuilder &Results) { | |||
1874 | CodeCompletionBuilder Builder(Results.getAllocator(), | |||
1875 | Results.getCodeCompletionTUInfo()); | |||
1876 | Builder.AddTypedTextChunk("typedef"); | |||
1877 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
1878 | Builder.AddPlaceholderChunk("type"); | |||
1879 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
1880 | Builder.AddPlaceholderChunk("name"); | |||
1881 | Builder.AddChunk(CodeCompletionString::CK_SemiColon); | |||
1882 | Results.AddResult(CodeCompletionResult(Builder.TakeString())); | |||
1883 | } | |||
1884 | ||||
1885 | // using name = type | |||
1886 | static void AddUsingAliasResult(CodeCompletionBuilder &Builder, | |||
1887 | ResultBuilder &Results) { | |||
1888 | Builder.AddTypedTextChunk("using"); | |||
1889 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
1890 | Builder.AddPlaceholderChunk("name"); | |||
1891 | Builder.AddChunk(CodeCompletionString::CK_Equal); | |||
1892 | Builder.AddPlaceholderChunk("type"); | |||
1893 | Builder.AddChunk(CodeCompletionString::CK_SemiColon); | |||
1894 | Results.AddResult(CodeCompletionResult(Builder.TakeString())); | |||
1895 | } | |||
1896 | ||||
1897 | static bool WantTypesInContext(Sema::ParserCompletionContext CCC, | |||
1898 | const LangOptions &LangOpts) { | |||
1899 | switch (CCC) { | |||
1900 | case Sema::PCC_Namespace: | |||
1901 | case Sema::PCC_Class: | |||
1902 | case Sema::PCC_ObjCInstanceVariableList: | |||
1903 | case Sema::PCC_Template: | |||
1904 | case Sema::PCC_MemberTemplate: | |||
1905 | case Sema::PCC_Statement: | |||
1906 | case Sema::PCC_RecoveryInFunction: | |||
1907 | case Sema::PCC_Type: | |||
1908 | case Sema::PCC_ParenthesizedExpression: | |||
1909 | case Sema::PCC_LocalDeclarationSpecifiers: | |||
1910 | return true; | |||
1911 | ||||
1912 | case Sema::PCC_Expression: | |||
1913 | case Sema::PCC_Condition: | |||
1914 | return LangOpts.CPlusPlus; | |||
1915 | ||||
1916 | case Sema::PCC_ObjCInterface: | |||
1917 | case Sema::PCC_ObjCImplementation: | |||
1918 | return false; | |||
1919 | ||||
1920 | case Sema::PCC_ForInit: | |||
1921 | return LangOpts.CPlusPlus || LangOpts.ObjC || LangOpts.C99; | |||
1922 | } | |||
1923 | ||||
1924 | llvm_unreachable("Invalid ParserCompletionContext!")::llvm::llvm_unreachable_internal("Invalid ParserCompletionContext!" , "clang/lib/Sema/SemaCodeComplete.cpp", 1924); | |||
1925 | } | |||
1926 | ||||
1927 | static PrintingPolicy getCompletionPrintingPolicy(const ASTContext &Context, | |||
1928 | const Preprocessor &PP) { | |||
1929 | PrintingPolicy Policy = Sema::getPrintingPolicy(Context, PP); | |||
1930 | Policy.AnonymousTagLocations = false; | |||
1931 | Policy.SuppressStrongLifetime = true; | |||
1932 | Policy.SuppressUnwrittenScope = true; | |||
1933 | Policy.SuppressScope = true; | |||
1934 | Policy.CleanUglifiedParameters = true; | |||
1935 | return Policy; | |||
1936 | } | |||
1937 | ||||
1938 | /// Retrieve a printing policy suitable for code completion. | |||
1939 | static PrintingPolicy getCompletionPrintingPolicy(Sema &S) { | |||
1940 | return getCompletionPrintingPolicy(S.Context, S.PP); | |||
1941 | } | |||
1942 | ||||
1943 | /// Retrieve the string representation of the given type as a string | |||
1944 | /// that has the appropriate lifetime for code completion. | |||
1945 | /// | |||
1946 | /// This routine provides a fast path where we provide constant strings for | |||
1947 | /// common type names. | |||
1948 | static const char *GetCompletionTypeString(QualType T, ASTContext &Context, | |||
1949 | const PrintingPolicy &Policy, | |||
1950 | CodeCompletionAllocator &Allocator) { | |||
1951 | if (!T.getLocalQualifiers()) { | |||
1952 | // Built-in type names are constant strings. | |||
1953 | if (const BuiltinType *BT = dyn_cast<BuiltinType>(T)) | |||
1954 | return BT->getNameAsCString(Policy); | |||
1955 | ||||
1956 | // Anonymous tag types are constant strings. | |||
1957 | if (const TagType *TagT = dyn_cast<TagType>(T)) | |||
1958 | if (TagDecl *Tag = TagT->getDecl()) | |||
1959 | if (!Tag->hasNameForLinkage()) { | |||
1960 | switch (Tag->getTagKind()) { | |||
1961 | case TTK_Struct: | |||
1962 | return "struct <anonymous>"; | |||
1963 | case TTK_Interface: | |||
1964 | return "__interface <anonymous>"; | |||
1965 | case TTK_Class: | |||
1966 | return "class <anonymous>"; | |||
1967 | case TTK_Union: | |||
1968 | return "union <anonymous>"; | |||
1969 | case TTK_Enum: | |||
1970 | return "enum <anonymous>"; | |||
1971 | } | |||
1972 | } | |||
1973 | } | |||
1974 | ||||
1975 | // Slow path: format the type as a string. | |||
1976 | std::string Result; | |||
1977 | T.getAsStringInternal(Result, Policy); | |||
1978 | return Allocator.CopyString(Result); | |||
1979 | } | |||
1980 | ||||
1981 | /// Add a completion for "this", if we're in a member function. | |||
1982 | static void addThisCompletion(Sema &S, ResultBuilder &Results) { | |||
1983 | QualType ThisTy = S.getCurrentThisType(); | |||
1984 | if (ThisTy.isNull()) | |||
1985 | return; | |||
1986 | ||||
1987 | CodeCompletionAllocator &Allocator = Results.getAllocator(); | |||
1988 | CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo()); | |||
1989 | PrintingPolicy Policy = getCompletionPrintingPolicy(S); | |||
1990 | Builder.AddResultTypeChunk( | |||
1991 | GetCompletionTypeString(ThisTy, S.Context, Policy, Allocator)); | |||
1992 | Builder.AddTypedTextChunk("this"); | |||
1993 | Results.AddResult(CodeCompletionResult(Builder.TakeString())); | |||
1994 | } | |||
1995 | ||||
1996 | static void AddStaticAssertResult(CodeCompletionBuilder &Builder, | |||
1997 | ResultBuilder &Results, | |||
1998 | const LangOptions &LangOpts) { | |||
1999 | if (!LangOpts.CPlusPlus11) | |||
2000 | return; | |||
2001 | ||||
2002 | Builder.AddTypedTextChunk("static_assert"); | |||
2003 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
2004 | Builder.AddPlaceholderChunk("expression"); | |||
2005 | Builder.AddChunk(CodeCompletionString::CK_Comma); | |||
2006 | Builder.AddPlaceholderChunk("message"); | |||
2007 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
2008 | Builder.AddChunk(CodeCompletionString::CK_SemiColon); | |||
2009 | Results.AddResult(CodeCompletionResult(Builder.TakeString())); | |||
2010 | } | |||
2011 | ||||
2012 | static void AddOverrideResults(ResultBuilder &Results, | |||
2013 | const CodeCompletionContext &CCContext, | |||
2014 | CodeCompletionBuilder &Builder) { | |||
2015 | Sema &S = Results.getSema(); | |||
2016 | const auto *CR = llvm::dyn_cast<CXXRecordDecl>(S.CurContext); | |||
2017 | // If not inside a class/struct/union return empty. | |||
2018 | if (!CR) | |||
2019 | return; | |||
2020 | // First store overrides within current class. | |||
2021 | // These are stored by name to make querying fast in the later step. | |||
2022 | llvm::StringMap<std::vector<FunctionDecl *>> Overrides; | |||
2023 | for (auto *Method : CR->methods()) { | |||
2024 | if (!Method->isVirtual() || !Method->getIdentifier()) | |||
2025 | continue; | |||
2026 | Overrides[Method->getName()].push_back(Method); | |||
2027 | } | |||
2028 | ||||
2029 | for (const auto &Base : CR->bases()) { | |||
2030 | const auto *BR = Base.getType().getTypePtr()->getAsCXXRecordDecl(); | |||
2031 | if (!BR) | |||
2032 | continue; | |||
2033 | for (auto *Method : BR->methods()) { | |||
2034 | if (!Method->isVirtual() || !Method->getIdentifier()) | |||
2035 | continue; | |||
2036 | const auto it = Overrides.find(Method->getName()); | |||
2037 | bool IsOverriden = false; | |||
2038 | if (it != Overrides.end()) { | |||
2039 | for (auto *MD : it->second) { | |||
2040 | // If the method in current body is not an overload of this virtual | |||
2041 | // function, then it overrides this one. | |||
2042 | if (!S.IsOverload(MD, Method, false)) { | |||
2043 | IsOverriden = true; | |||
2044 | break; | |||
2045 | } | |||
2046 | } | |||
2047 | } | |||
2048 | if (!IsOverriden) { | |||
2049 | // Generates a new CodeCompletionResult by taking this function and | |||
2050 | // converting it into an override declaration with only one chunk in the | |||
2051 | // final CodeCompletionString as a TypedTextChunk. | |||
2052 | std::string OverrideSignature; | |||
2053 | llvm::raw_string_ostream OS(OverrideSignature); | |||
2054 | CodeCompletionResult CCR(Method, 0); | |||
2055 | PrintingPolicy Policy = | |||
2056 | getCompletionPrintingPolicy(S.getASTContext(), S.getPreprocessor()); | |||
2057 | auto *CCS = CCR.createCodeCompletionStringForOverride( | |||
2058 | S.getPreprocessor(), S.getASTContext(), Builder, | |||
2059 | /*IncludeBriefComments=*/false, CCContext, Policy); | |||
2060 | Results.AddResult(CodeCompletionResult(CCS, Method, CCP_CodePattern)); | |||
2061 | } | |||
2062 | } | |||
2063 | } | |||
2064 | } | |||
2065 | ||||
2066 | /// Add language constructs that show up for "ordinary" names. | |||
2067 | static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC, Scope *S, | |||
2068 | Sema &SemaRef, ResultBuilder &Results) { | |||
2069 | CodeCompletionAllocator &Allocator = Results.getAllocator(); | |||
2070 | CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo()); | |||
2071 | ||||
2072 | typedef CodeCompletionResult Result; | |||
2073 | switch (CCC) { | |||
2074 | case Sema::PCC_Namespace: | |||
2075 | if (SemaRef.getLangOpts().CPlusPlus) { | |||
2076 | if (Results.includeCodePatterns()) { | |||
2077 | // namespace <identifier> { declarations } | |||
2078 | Builder.AddTypedTextChunk("namespace"); | |||
2079 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
2080 | Builder.AddPlaceholderChunk("identifier"); | |||
2081 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
2082 | Builder.AddChunk(CodeCompletionString::CK_LeftBrace); | |||
2083 | Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); | |||
2084 | Builder.AddPlaceholderChunk("declarations"); | |||
2085 | Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); | |||
2086 | Builder.AddChunk(CodeCompletionString::CK_RightBrace); | |||
2087 | Results.AddResult(Result(Builder.TakeString())); | |||
2088 | } | |||
2089 | ||||
2090 | // namespace identifier = identifier ; | |||
2091 | Builder.AddTypedTextChunk("namespace"); | |||
2092 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
2093 | Builder.AddPlaceholderChunk("name"); | |||
2094 | Builder.AddChunk(CodeCompletionString::CK_Equal); | |||
2095 | Builder.AddPlaceholderChunk("namespace"); | |||
2096 | Builder.AddChunk(CodeCompletionString::CK_SemiColon); | |||
2097 | Results.AddResult(Result(Builder.TakeString())); | |||
2098 | ||||
2099 | // Using directives | |||
2100 | Builder.AddTypedTextChunk("using namespace"); | |||
2101 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
2102 | Builder.AddPlaceholderChunk("identifier"); | |||
2103 | Builder.AddChunk(CodeCompletionString::CK_SemiColon); | |||
2104 | Results.AddResult(Result(Builder.TakeString())); | |||
2105 | ||||
2106 | // asm(string-literal) | |||
2107 | Builder.AddTypedTextChunk("asm"); | |||
2108 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
2109 | Builder.AddPlaceholderChunk("string-literal"); | |||
2110 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
2111 | Results.AddResult(Result(Builder.TakeString())); | |||
2112 | ||||
2113 | if (Results.includeCodePatterns()) { | |||
2114 | // Explicit template instantiation | |||
2115 | Builder.AddTypedTextChunk("template"); | |||
2116 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
2117 | Builder.AddPlaceholderChunk("declaration"); | |||
2118 | Results.AddResult(Result(Builder.TakeString())); | |||
2119 | } else { | |||
2120 | Results.AddResult(Result("template", CodeCompletionResult::RK_Keyword)); | |||
2121 | } | |||
2122 | } | |||
2123 | ||||
2124 | if (SemaRef.getLangOpts().ObjC) | |||
2125 | AddObjCTopLevelResults(Results, true); | |||
2126 | ||||
2127 | AddTypedefResult(Results); | |||
2128 | [[fallthrough]]; | |||
2129 | ||||
2130 | case Sema::PCC_Class: | |||
2131 | if (SemaRef.getLangOpts().CPlusPlus) { | |||
2132 | // Using declaration | |||
2133 | Builder.AddTypedTextChunk("using"); | |||
2134 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
2135 | Builder.AddPlaceholderChunk("qualifier"); | |||
2136 | Builder.AddTextChunk("::"); | |||
2137 | Builder.AddPlaceholderChunk("name"); | |||
2138 | Builder.AddChunk(CodeCompletionString::CK_SemiColon); | |||
2139 | Results.AddResult(Result(Builder.TakeString())); | |||
2140 | ||||
2141 | if (SemaRef.getLangOpts().CPlusPlus11) | |||
2142 | AddUsingAliasResult(Builder, Results); | |||
2143 | ||||
2144 | // using typename qualifier::name (only in a dependent context) | |||
2145 | if (SemaRef.CurContext->isDependentContext()) { | |||
2146 | Builder.AddTypedTextChunk("using typename"); | |||
2147 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
2148 | Builder.AddPlaceholderChunk("qualifier"); | |||
2149 | Builder.AddTextChunk("::"); | |||
2150 | Builder.AddPlaceholderChunk("name"); | |||
2151 | Builder.AddChunk(CodeCompletionString::CK_SemiColon); | |||
2152 | Results.AddResult(Result(Builder.TakeString())); | |||
2153 | } | |||
2154 | ||||
2155 | AddStaticAssertResult(Builder, Results, SemaRef.getLangOpts()); | |||
2156 | ||||
2157 | if (CCC == Sema::PCC_Class) { | |||
2158 | AddTypedefResult(Results); | |||
2159 | ||||
2160 | bool IsNotInheritanceScope = !S->isClassInheritanceScope(); | |||
2161 | // public: | |||
2162 | Builder.AddTypedTextChunk("public"); | |||
2163 | if (IsNotInheritanceScope && Results.includeCodePatterns()) | |||
2164 | Builder.AddChunk(CodeCompletionString::CK_Colon); | |||
2165 | Results.AddResult(Result(Builder.TakeString())); | |||
2166 | ||||
2167 | // protected: | |||
2168 | Builder.AddTypedTextChunk("protected"); | |||
2169 | if (IsNotInheritanceScope && Results.includeCodePatterns()) | |||
2170 | Builder.AddChunk(CodeCompletionString::CK_Colon); | |||
2171 | Results.AddResult(Result(Builder.TakeString())); | |||
2172 | ||||
2173 | // private: | |||
2174 | Builder.AddTypedTextChunk("private"); | |||
2175 | if (IsNotInheritanceScope && Results.includeCodePatterns()) | |||
2176 | Builder.AddChunk(CodeCompletionString::CK_Colon); | |||
2177 | Results.AddResult(Result(Builder.TakeString())); | |||
2178 | ||||
2179 | // FIXME: This adds override results only if we are at the first word of | |||
2180 | // the declaration/definition. Also call this from other sides to have | |||
2181 | // more use-cases. | |||
2182 | AddOverrideResults(Results, CodeCompletionContext::CCC_ClassStructUnion, | |||
2183 | Builder); | |||
2184 | } | |||
2185 | } | |||
2186 | [[fallthrough]]; | |||
2187 | ||||
2188 | case Sema::PCC_Template: | |||
2189 | case Sema::PCC_MemberTemplate: | |||
2190 | if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns()) { | |||
2191 | // template < parameters > | |||
2192 | Builder.AddTypedTextChunk("template"); | |||
2193 | Builder.AddChunk(CodeCompletionString::CK_LeftAngle); | |||
2194 | Builder.AddPlaceholderChunk("parameters"); | |||
2195 | Builder.AddChunk(CodeCompletionString::CK_RightAngle); | |||
2196 | Results.AddResult(Result(Builder.TakeString())); | |||
2197 | } else { | |||
2198 | Results.AddResult(Result("template", CodeCompletionResult::RK_Keyword)); | |||
2199 | } | |||
2200 | ||||
2201 | AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results); | |||
2202 | AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results); | |||
2203 | break; | |||
2204 | ||||
2205 | case Sema::PCC_ObjCInterface: | |||
2206 | AddObjCInterfaceResults(SemaRef.getLangOpts(), Results, true); | |||
2207 | AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results); | |||
2208 | AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results); | |||
2209 | break; | |||
2210 | ||||
2211 | case Sema::PCC_ObjCImplementation: | |||
2212 | AddObjCImplementationResults(SemaRef.getLangOpts(), Results, true); | |||
2213 | AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results); | |||
2214 | AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results); | |||
2215 | break; | |||
2216 | ||||
2217 | case Sema::PCC_ObjCInstanceVariableList: | |||
2218 | AddObjCVisibilityResults(SemaRef.getLangOpts(), Results, true); | |||
2219 | break; | |||
2220 | ||||
2221 | case Sema::PCC_RecoveryInFunction: | |||
2222 | case Sema::PCC_Statement: { | |||
2223 | if (SemaRef.getLangOpts().CPlusPlus11) | |||
2224 | AddUsingAliasResult(Builder, Results); | |||
2225 | ||||
2226 | AddTypedefResult(Results); | |||
2227 | ||||
2228 | if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns() && | |||
2229 | SemaRef.getLangOpts().CXXExceptions) { | |||
2230 | Builder.AddTypedTextChunk("try"); | |||
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 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
2238 | Builder.AddTextChunk("catch"); | |||
2239 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
2240 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
2241 | Builder.AddPlaceholderChunk("declaration"); | |||
2242 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
2243 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
2244 | Builder.AddChunk(CodeCompletionString::CK_LeftBrace); | |||
2245 | Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); | |||
2246 | Builder.AddPlaceholderChunk("statements"); | |||
2247 | Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); | |||
2248 | Builder.AddChunk(CodeCompletionString::CK_RightBrace); | |||
2249 | Results.AddResult(Result(Builder.TakeString())); | |||
2250 | } | |||
2251 | if (SemaRef.getLangOpts().ObjC) | |||
2252 | AddObjCStatementResults(Results, true); | |||
2253 | ||||
2254 | if (Results.includeCodePatterns()) { | |||
2255 | // if (condition) { statements } | |||
2256 | Builder.AddTypedTextChunk("if"); | |||
2257 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
2258 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
2259 | if (SemaRef.getLangOpts().CPlusPlus) | |||
2260 | Builder.AddPlaceholderChunk("condition"); | |||
2261 | else | |||
2262 | Builder.AddPlaceholderChunk("expression"); | |||
2263 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
2264 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
2265 | Builder.AddChunk(CodeCompletionString::CK_LeftBrace); | |||
2266 | Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); | |||
2267 | Builder.AddPlaceholderChunk("statements"); | |||
2268 | Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); | |||
2269 | Builder.AddChunk(CodeCompletionString::CK_RightBrace); | |||
2270 | Results.AddResult(Result(Builder.TakeString())); | |||
2271 | ||||
2272 | // switch (condition) { } | |||
2273 | Builder.AddTypedTextChunk("switch"); | |||
2274 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
2275 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
2276 | if (SemaRef.getLangOpts().CPlusPlus) | |||
2277 | Builder.AddPlaceholderChunk("condition"); | |||
2278 | else | |||
2279 | Builder.AddPlaceholderChunk("expression"); | |||
2280 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
2281 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
2282 | Builder.AddChunk(CodeCompletionString::CK_LeftBrace); | |||
2283 | Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); | |||
2284 | Builder.AddPlaceholderChunk("cases"); | |||
2285 | Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); | |||
2286 | Builder.AddChunk(CodeCompletionString::CK_RightBrace); | |||
2287 | Results.AddResult(Result(Builder.TakeString())); | |||
2288 | } | |||
2289 | ||||
2290 | // Switch-specific statements. | |||
2291 | if (SemaRef.getCurFunction() && | |||
2292 | !SemaRef.getCurFunction()->SwitchStack.empty()) { | |||
2293 | // case expression: | |||
2294 | Builder.AddTypedTextChunk("case"); | |||
2295 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
2296 | Builder.AddPlaceholderChunk("expression"); | |||
2297 | Builder.AddChunk(CodeCompletionString::CK_Colon); | |||
2298 | Results.AddResult(Result(Builder.TakeString())); | |||
2299 | ||||
2300 | // default: | |||
2301 | Builder.AddTypedTextChunk("default"); | |||
2302 | Builder.AddChunk(CodeCompletionString::CK_Colon); | |||
2303 | Results.AddResult(Result(Builder.TakeString())); | |||
2304 | } | |||
2305 | ||||
2306 | if (Results.includeCodePatterns()) { | |||
2307 | /// while (condition) { statements } | |||
2308 | Builder.AddTypedTextChunk("while"); | |||
2309 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
2310 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
2311 | if (SemaRef.getLangOpts().CPlusPlus) | |||
2312 | Builder.AddPlaceholderChunk("condition"); | |||
2313 | else | |||
2314 | Builder.AddPlaceholderChunk("expression"); | |||
2315 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
2316 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
2317 | Builder.AddChunk(CodeCompletionString::CK_LeftBrace); | |||
2318 | Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); | |||
2319 | Builder.AddPlaceholderChunk("statements"); | |||
2320 | Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); | |||
2321 | Builder.AddChunk(CodeCompletionString::CK_RightBrace); | |||
2322 | Results.AddResult(Result(Builder.TakeString())); | |||
2323 | ||||
2324 | // do { statements } while ( expression ); | |||
2325 | Builder.AddTypedTextChunk("do"); | |||
2326 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
2327 | Builder.AddChunk(CodeCompletionString::CK_LeftBrace); | |||
2328 | Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); | |||
2329 | Builder.AddPlaceholderChunk("statements"); | |||
2330 | Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); | |||
2331 | Builder.AddChunk(CodeCompletionString::CK_RightBrace); | |||
2332 | Builder.AddTextChunk("while"); | |||
2333 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
2334 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
2335 | Builder.AddPlaceholderChunk("expression"); | |||
2336 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
2337 | Results.AddResult(Result(Builder.TakeString())); | |||
2338 | ||||
2339 | // for ( for-init-statement ; condition ; expression ) { statements } | |||
2340 | Builder.AddTypedTextChunk("for"); | |||
2341 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
2342 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
2343 | if (SemaRef.getLangOpts().CPlusPlus || SemaRef.getLangOpts().C99) | |||
2344 | Builder.AddPlaceholderChunk("init-statement"); | |||
2345 | else | |||
2346 | Builder.AddPlaceholderChunk("init-expression"); | |||
2347 | Builder.AddChunk(CodeCompletionString::CK_SemiColon); | |||
2348 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
2349 | Builder.AddPlaceholderChunk("condition"); | |||
2350 | Builder.AddChunk(CodeCompletionString::CK_SemiColon); | |||
2351 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
2352 | Builder.AddPlaceholderChunk("inc-expression"); | |||
2353 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
2354 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
2355 | Builder.AddChunk(CodeCompletionString::CK_LeftBrace); | |||
2356 | Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); | |||
2357 | Builder.AddPlaceholderChunk("statements"); | |||
2358 | Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); | |||
2359 | Builder.AddChunk(CodeCompletionString::CK_RightBrace); | |||
2360 | Results.AddResult(Result(Builder.TakeString())); | |||
2361 | ||||
2362 | if (SemaRef.getLangOpts().CPlusPlus11 || SemaRef.getLangOpts().ObjC) { | |||
2363 | // for ( range_declaration (:|in) range_expression ) { statements } | |||
2364 | Builder.AddTypedTextChunk("for"); | |||
2365 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
2366 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
2367 | Builder.AddPlaceholderChunk("range-declaration"); | |||
2368 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
2369 | if (SemaRef.getLangOpts().ObjC) | |||
2370 | Builder.AddTextChunk("in"); | |||
2371 | else | |||
2372 | Builder.AddChunk(CodeCompletionString::CK_Colon); | |||
2373 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
2374 | Builder.AddPlaceholderChunk("range-expression"); | |||
2375 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
2376 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
2377 | Builder.AddChunk(CodeCompletionString::CK_LeftBrace); | |||
2378 | Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); | |||
2379 | Builder.AddPlaceholderChunk("statements"); | |||
2380 | Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); | |||
2381 | Builder.AddChunk(CodeCompletionString::CK_RightBrace); | |||
2382 | Results.AddResult(Result(Builder.TakeString())); | |||
2383 | } | |||
2384 | } | |||
2385 | ||||
2386 | if (S->getContinueParent()) { | |||
2387 | // continue ; | |||
2388 | Builder.AddTypedTextChunk("continue"); | |||
2389 | Builder.AddChunk(CodeCompletionString::CK_SemiColon); | |||
2390 | Results.AddResult(Result(Builder.TakeString())); | |||
2391 | } | |||
2392 | ||||
2393 | if (S->getBreakParent()) { | |||
2394 | // break ; | |||
2395 | Builder.AddTypedTextChunk("break"); | |||
2396 | Builder.AddChunk(CodeCompletionString::CK_SemiColon); | |||
2397 | Results.AddResult(Result(Builder.TakeString())); | |||
2398 | } | |||
2399 | ||||
2400 | // "return expression ;" or "return ;", depending on the return type. | |||
2401 | QualType ReturnType; | |||
2402 | if (const auto *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext)) | |||
2403 | ReturnType = Function->getReturnType(); | |||
2404 | else if (const auto *Method = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext)) | |||
2405 | ReturnType = Method->getReturnType(); | |||
2406 | else if (SemaRef.getCurBlock() && | |||
2407 | !SemaRef.getCurBlock()->ReturnType.isNull()) | |||
2408 | ReturnType = SemaRef.getCurBlock()->ReturnType;; | |||
2409 | if (ReturnType.isNull() || ReturnType->isVoidType()) { | |||
2410 | Builder.AddTypedTextChunk("return"); | |||
2411 | Builder.AddChunk(CodeCompletionString::CK_SemiColon); | |||
2412 | Results.AddResult(Result(Builder.TakeString())); | |||
2413 | } else { | |||
2414 | assert(!ReturnType.isNull())(static_cast <bool> (!ReturnType.isNull()) ? void (0) : __assert_fail ("!ReturnType.isNull()", "clang/lib/Sema/SemaCodeComplete.cpp" , 2414, __extension__ __PRETTY_FUNCTION__)); | |||
2415 | // "return expression ;" | |||
2416 | Builder.AddTypedTextChunk("return"); | |||
2417 | Builder.AddChunk(clang::CodeCompletionString::CK_HorizontalSpace); | |||
2418 | Builder.AddPlaceholderChunk("expression"); | |||
2419 | Builder.AddChunk(CodeCompletionString::CK_SemiColon); | |||
2420 | Results.AddResult(Result(Builder.TakeString())); | |||
2421 | // When boolean, also add 'return true;' and 'return false;'. | |||
2422 | if (ReturnType->isBooleanType()) { | |||
2423 | Builder.AddTypedTextChunk("return true"); | |||
2424 | Builder.AddChunk(CodeCompletionString::CK_SemiColon); | |||
2425 | Results.AddResult(Result(Builder.TakeString())); | |||
2426 | ||||
2427 | Builder.AddTypedTextChunk("return false"); | |||
2428 | Builder.AddChunk(CodeCompletionString::CK_SemiColon); | |||
2429 | Results.AddResult(Result(Builder.TakeString())); | |||
2430 | } | |||
2431 | // For pointers, suggest 'return nullptr' in C++. | |||
2432 | if (SemaRef.getLangOpts().CPlusPlus11 && | |||
2433 | (ReturnType->isPointerType() || ReturnType->isMemberPointerType())) { | |||
2434 | Builder.AddTypedTextChunk("return nullptr"); | |||
2435 | Builder.AddChunk(CodeCompletionString::CK_SemiColon); | |||
2436 | Results.AddResult(Result(Builder.TakeString())); | |||
2437 | } | |||
2438 | } | |||
2439 | ||||
2440 | // goto identifier ; | |||
2441 | Builder.AddTypedTextChunk("goto"); | |||
2442 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
2443 | Builder.AddPlaceholderChunk("label"); | |||
2444 | Builder.AddChunk(CodeCompletionString::CK_SemiColon); | |||
2445 | Results.AddResult(Result(Builder.TakeString())); | |||
2446 | ||||
2447 | // Using directives | |||
2448 | Builder.AddTypedTextChunk("using namespace"); | |||
2449 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
2450 | Builder.AddPlaceholderChunk("identifier"); | |||
2451 | Builder.AddChunk(CodeCompletionString::CK_SemiColon); | |||
2452 | Results.AddResult(Result(Builder.TakeString())); | |||
2453 | ||||
2454 | AddStaticAssertResult(Builder, Results, SemaRef.getLangOpts()); | |||
2455 | } | |||
2456 | [[fallthrough]]; | |||
2457 | ||||
2458 | // Fall through (for statement expressions). | |||
2459 | case Sema::PCC_ForInit: | |||
2460 | case Sema::PCC_Condition: | |||
2461 | AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results); | |||
2462 | // Fall through: conditions and statements can have expressions. | |||
2463 | [[fallthrough]]; | |||
2464 | ||||
2465 | case Sema::PCC_ParenthesizedExpression: | |||
2466 | if (SemaRef.getLangOpts().ObjCAutoRefCount && | |||
2467 | CCC == Sema::PCC_ParenthesizedExpression) { | |||
2468 | // (__bridge <type>)<expression> | |||
2469 | Builder.AddTypedTextChunk("__bridge"); | |||
2470 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
2471 | Builder.AddPlaceholderChunk("type"); | |||
2472 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
2473 | Builder.AddPlaceholderChunk("expression"); | |||
2474 | Results.AddResult(Result(Builder.TakeString())); | |||
2475 | ||||
2476 | // (__bridge_transfer <Objective-C type>)<expression> | |||
2477 | Builder.AddTypedTextChunk("__bridge_transfer"); | |||
2478 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
2479 | Builder.AddPlaceholderChunk("Objective-C type"); | |||
2480 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
2481 | Builder.AddPlaceholderChunk("expression"); | |||
2482 | Results.AddResult(Result(Builder.TakeString())); | |||
2483 | ||||
2484 | // (__bridge_retained <CF type>)<expression> | |||
2485 | Builder.AddTypedTextChunk("__bridge_retained"); | |||
2486 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
2487 | Builder.AddPlaceholderChunk("CF type"); | |||
2488 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
2489 | Builder.AddPlaceholderChunk("expression"); | |||
2490 | Results.AddResult(Result(Builder.TakeString())); | |||
2491 | } | |||
2492 | // Fall through | |||
2493 | [[fallthrough]]; | |||
2494 | ||||
2495 | case Sema::PCC_Expression: { | |||
2496 | if (SemaRef.getLangOpts().CPlusPlus) { | |||
2497 | // 'this', if we're in a non-static member function. | |||
2498 | addThisCompletion(SemaRef, Results); | |||
2499 | ||||
2500 | // true | |||
2501 | Builder.AddResultTypeChunk("bool"); | |||
2502 | Builder.AddTypedTextChunk("true"); | |||
2503 | Results.AddResult(Result(Builder.TakeString())); | |||
2504 | ||||
2505 | // false | |||
2506 | Builder.AddResultTypeChunk("bool"); | |||
2507 | Builder.AddTypedTextChunk("false"); | |||
2508 | Results.AddResult(Result(Builder.TakeString())); | |||
2509 | ||||
2510 | if (SemaRef.getLangOpts().RTTI) { | |||
2511 | // dynamic_cast < type-id > ( expression ) | |||
2512 | Builder.AddTypedTextChunk("dynamic_cast"); | |||
2513 | Builder.AddChunk(CodeCompletionString::CK_LeftAngle); | |||
2514 | Builder.AddPlaceholderChunk("type"); | |||
2515 | Builder.AddChunk(CodeCompletionString::CK_RightAngle); | |||
2516 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
2517 | Builder.AddPlaceholderChunk("expression"); | |||
2518 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
2519 | Results.AddResult(Result(Builder.TakeString())); | |||
2520 | } | |||
2521 | ||||
2522 | // static_cast < type-id > ( expression ) | |||
2523 | Builder.AddTypedTextChunk("static_cast"); | |||
2524 | Builder.AddChunk(CodeCompletionString::CK_LeftAngle); | |||
2525 | Builder.AddPlaceholderChunk("type"); | |||
2526 | Builder.AddChunk(CodeCompletionString::CK_RightAngle); | |||
2527 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
2528 | Builder.AddPlaceholderChunk("expression"); | |||
2529 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
2530 | Results.AddResult(Result(Builder.TakeString())); | |||
2531 | ||||
2532 | // reinterpret_cast < type-id > ( expression ) | |||
2533 | Builder.AddTypedTextChunk("reinterpret_cast"); | |||
2534 | Builder.AddChunk(CodeCompletionString::CK_LeftAngle); | |||
2535 | Builder.AddPlaceholderChunk("type"); | |||
2536 | Builder.AddChunk(CodeCompletionString::CK_RightAngle); | |||
2537 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
2538 | Builder.AddPlaceholderChunk("expression"); | |||
2539 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
2540 | Results.AddResult(Result(Builder.TakeString())); | |||
2541 | ||||
2542 | // const_cast < type-id > ( expression ) | |||
2543 | Builder.AddTypedTextChunk("const_cast"); | |||
2544 | Builder.AddChunk(CodeCompletionString::CK_LeftAngle); | |||
2545 | Builder.AddPlaceholderChunk("type"); | |||
2546 | Builder.AddChunk(CodeCompletionString::CK_RightAngle); | |||
2547 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
2548 | Builder.AddPlaceholderChunk("expression"); | |||
2549 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
2550 | Results.AddResult(Result(Builder.TakeString())); | |||
2551 | ||||
2552 | if (SemaRef.getLangOpts().RTTI) { | |||
2553 | // typeid ( expression-or-type ) | |||
2554 | Builder.AddResultTypeChunk("std::type_info"); | |||
2555 | Builder.AddTypedTextChunk("typeid"); | |||
2556 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
2557 | Builder.AddPlaceholderChunk("expression-or-type"); | |||
2558 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
2559 | Results.AddResult(Result(Builder.TakeString())); | |||
2560 | } | |||
2561 | ||||
2562 | // new T ( ... ) | |||
2563 | Builder.AddTypedTextChunk("new"); | |||
2564 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
2565 | Builder.AddPlaceholderChunk("type"); | |||
2566 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
2567 | Builder.AddPlaceholderChunk("expressions"); | |||
2568 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
2569 | Results.AddResult(Result(Builder.TakeString())); | |||
2570 | ||||
2571 | // new T [ ] ( ... ) | |||
2572 | Builder.AddTypedTextChunk("new"); | |||
2573 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
2574 | Builder.AddPlaceholderChunk("type"); | |||
2575 | Builder.AddChunk(CodeCompletionString::CK_LeftBracket); | |||
2576 | Builder.AddPlaceholderChunk("size"); | |||
2577 | Builder.AddChunk(CodeCompletionString::CK_RightBracket); | |||
2578 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
2579 | Builder.AddPlaceholderChunk("expressions"); | |||
2580 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
2581 | Results.AddResult(Result(Builder.TakeString())); | |||
2582 | ||||
2583 | // delete expression | |||
2584 | Builder.AddResultTypeChunk("void"); | |||
2585 | Builder.AddTypedTextChunk("delete"); | |||
2586 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
2587 | Builder.AddPlaceholderChunk("expression"); | |||
2588 | Results.AddResult(Result(Builder.TakeString())); | |||
2589 | ||||
2590 | // delete [] expression | |||
2591 | Builder.AddResultTypeChunk("void"); | |||
2592 | Builder.AddTypedTextChunk("delete"); | |||
2593 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
2594 | Builder.AddChunk(CodeCompletionString::CK_LeftBracket); | |||
2595 | Builder.AddChunk(CodeCompletionString::CK_RightBracket); | |||
2596 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
2597 | Builder.AddPlaceholderChunk("expression"); | |||
2598 | Results.AddResult(Result(Builder.TakeString())); | |||
2599 | ||||
2600 | if (SemaRef.getLangOpts().CXXExceptions) { | |||
2601 | // throw expression | |||
2602 | Builder.AddResultTypeChunk("void"); | |||
2603 | Builder.AddTypedTextChunk("throw"); | |||
2604 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
2605 | Builder.AddPlaceholderChunk("expression"); | |||
2606 | Results.AddResult(Result(Builder.TakeString())); | |||
2607 | } | |||
2608 | ||||
2609 | // FIXME: Rethrow? | |||
2610 | ||||
2611 | if (SemaRef.getLangOpts().CPlusPlus11) { | |||
2612 | // nullptr | |||
2613 | Builder.AddResultTypeChunk("std::nullptr_t"); | |||
2614 | Builder.AddTypedTextChunk("nullptr"); | |||
2615 | Results.AddResult(Result(Builder.TakeString())); | |||
2616 | ||||
2617 | // alignof | |||
2618 | Builder.AddResultTypeChunk("size_t"); | |||
2619 | Builder.AddTypedTextChunk("alignof"); | |||
2620 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
2621 | Builder.AddPlaceholderChunk("type"); | |||
2622 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
2623 | Results.AddResult(Result(Builder.TakeString())); | |||
2624 | ||||
2625 | // noexcept | |||
2626 | Builder.AddResultTypeChunk("bool"); | |||
2627 | Builder.AddTypedTextChunk("noexcept"); | |||
2628 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
2629 | Builder.AddPlaceholderChunk("expression"); | |||
2630 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
2631 | Results.AddResult(Result(Builder.TakeString())); | |||
2632 | ||||
2633 | // sizeof... expression | |||
2634 | Builder.AddResultTypeChunk("size_t"); | |||
2635 | Builder.AddTypedTextChunk("sizeof..."); | |||
2636 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
2637 | Builder.AddPlaceholderChunk("parameter-pack"); | |||
2638 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
2639 | Results.AddResult(Result(Builder.TakeString())); | |||
2640 | } | |||
2641 | } | |||
2642 | ||||
2643 | if (SemaRef.getLangOpts().ObjC) { | |||
2644 | // Add "super", if we're in an Objective-C class with a superclass. | |||
2645 | if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) { | |||
2646 | // The interface can be NULL. | |||
2647 | if (ObjCInterfaceDecl *ID = Method->getClassInterface()) | |||
2648 | if (ID->getSuperClass()) { | |||
2649 | std::string SuperType; | |||
2650 | SuperType = ID->getSuperClass()->getNameAsString(); | |||
2651 | if (Method->isInstanceMethod()) | |||
2652 | SuperType += " *"; | |||
2653 | ||||
2654 | Builder.AddResultTypeChunk(Allocator.CopyString(SuperType)); | |||
2655 | Builder.AddTypedTextChunk("super"); | |||
2656 | Results.AddResult(Result(Builder.TakeString())); | |||
2657 | } | |||
2658 | } | |||
2659 | ||||
2660 | AddObjCExpressionResults(Results, true); | |||
2661 | } | |||
2662 | ||||
2663 | if (SemaRef.getLangOpts().C11) { | |||
2664 | // _Alignof | |||
2665 | Builder.AddResultTypeChunk("size_t"); | |||
2666 | if (SemaRef.PP.isMacroDefined("alignof")) | |||
2667 | Builder.AddTypedTextChunk("alignof"); | |||
2668 | else | |||
2669 | Builder.AddTypedTextChunk("_Alignof"); | |||
2670 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
2671 | Builder.AddPlaceholderChunk("type"); | |||
2672 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
2673 | Results.AddResult(Result(Builder.TakeString())); | |||
2674 | } | |||
2675 | ||||
2676 | if (SemaRef.getLangOpts().C2x) { | |||
2677 | // nullptr | |||
2678 | Builder.AddResultTypeChunk("nullptr_t"); | |||
2679 | Builder.AddTypedTextChunk("nullptr"); | |||
2680 | Results.AddResult(Result(Builder.TakeString())); | |||
2681 | } | |||
2682 | ||||
2683 | // sizeof expression | |||
2684 | Builder.AddResultTypeChunk("size_t"); | |||
2685 | Builder.AddTypedTextChunk("sizeof"); | |||
2686 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
2687 | Builder.AddPlaceholderChunk("expression-or-type"); | |||
2688 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
2689 | Results.AddResult(Result(Builder.TakeString())); | |||
2690 | break; | |||
2691 | } | |||
2692 | ||||
2693 | case Sema::PCC_Type: | |||
2694 | case Sema::PCC_LocalDeclarationSpecifiers: | |||
2695 | break; | |||
2696 | } | |||
2697 | ||||
2698 | if (WantTypesInContext(CCC, SemaRef.getLangOpts())) | |||
2699 | AddTypeSpecifierResults(SemaRef.getLangOpts(), Results); | |||
2700 | ||||
2701 | if (SemaRef.getLangOpts().CPlusPlus && CCC != Sema::PCC_Type) | |||
2702 | Results.AddResult(Result("operator")); | |||
2703 | } | |||
2704 | ||||
2705 | /// If the given declaration has an associated type, add it as a result | |||
2706 | /// type chunk. | |||
2707 | static void AddResultTypeChunk(ASTContext &Context, | |||
2708 | const PrintingPolicy &Policy, | |||
2709 | const NamedDecl *ND, QualType BaseType, | |||
2710 | CodeCompletionBuilder &Result) { | |||
2711 | if (!ND) | |||
2712 | return; | |||
2713 | ||||
2714 | // Skip constructors and conversion functions, which have their return types | |||
2715 | // built into their names. | |||
2716 | if (isConstructor(ND) || isa<CXXConversionDecl>(ND)) | |||
2717 | return; | |||
2718 | ||||
2719 | // Determine the type of the declaration (if it has a type). | |||
2720 | QualType T; | |||
2721 | if (const FunctionDecl *Function = ND->getAsFunction()) | |||
2722 | T = Function->getReturnType(); | |||
2723 | else if (const auto *Method = dyn_cast<ObjCMethodDecl>(ND)) { | |||
2724 | if (!BaseType.isNull()) | |||
2725 | T = Method->getSendResultType(BaseType); | |||
2726 | else | |||
2727 | T = Method->getReturnType(); | |||
2728 | } else if (const auto *Enumerator = dyn_cast<EnumConstantDecl>(ND)) { | |||
2729 | T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext())); | |||
2730 | T = clang::TypeName::getFullyQualifiedType(T, Context); | |||
2731 | } else if (isa<UnresolvedUsingValueDecl>(ND)) { | |||
2732 | /* Do nothing: ignore unresolved using declarations*/ | |||
2733 | } else if (const auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) { | |||
2734 | if (!BaseType.isNull()) | |||
2735 | T = Ivar->getUsageType(BaseType); | |||
2736 | else | |||
2737 | T = Ivar->getType(); | |||
2738 | } else if (const auto *Value = dyn_cast<ValueDecl>(ND)) { | |||
2739 | T = Value->getType(); | |||
2740 | } else if (const auto *Property = dyn_cast<ObjCPropertyDecl>(ND)) { | |||
2741 | if (!BaseType.isNull()) | |||
2742 | T = Property->getUsageType(BaseType); | |||
2743 | else | |||
2744 | T = Property->getType(); | |||
2745 | } | |||
2746 | ||||
2747 | if (T.isNull() || Context.hasSameType(T, Context.DependentTy)) | |||
2748 | return; | |||
2749 | ||||
2750 | Result.AddResultTypeChunk( | |||
2751 | GetCompletionTypeString(T, Context, Policy, Result.getAllocator())); | |||
2752 | } | |||
2753 | ||||
2754 | static void MaybeAddSentinel(Preprocessor &PP, | |||
2755 | const NamedDecl *FunctionOrMethod, | |||
2756 | CodeCompletionBuilder &Result) { | |||
2757 | if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>()) | |||
2758 | if (Sentinel->getSentinel() == 0) { | |||
2759 | if (PP.getLangOpts().ObjC && PP.isMacroDefined("nil")) | |||
2760 | Result.AddTextChunk(", nil"); | |||
2761 | else if (PP.isMacroDefined("NULL")) | |||
2762 | Result.AddTextChunk(", NULL"); | |||
2763 | else | |||
2764 | Result.AddTextChunk(", (void*)0"); | |||
2765 | } | |||
2766 | } | |||
2767 | ||||
2768 | static std::string formatObjCParamQualifiers(unsigned ObjCQuals, | |||
2769 | QualType &Type) { | |||
2770 | std::string Result; | |||
2771 | if (ObjCQuals & Decl::OBJC_TQ_In) | |||
2772 | Result += "in "; | |||
2773 | else if (ObjCQuals & Decl::OBJC_TQ_Inout) | |||
2774 | Result += "inout "; | |||
2775 | else if (ObjCQuals & Decl::OBJC_TQ_Out) | |||
2776 | Result += "out "; | |||
2777 | if (ObjCQuals & Decl::OBJC_TQ_Bycopy) | |||
2778 | Result += "bycopy "; | |||
2779 | else if (ObjCQuals & Decl::OBJC_TQ_Byref) | |||
2780 | Result += "byref "; | |||
2781 | if (ObjCQuals & Decl::OBJC_TQ_Oneway) | |||
2782 | Result += "oneway "; | |||
2783 | if (ObjCQuals & Decl::OBJC_TQ_CSNullability) { | |||
2784 | if (auto nullability = AttributedType::stripOuterNullability(Type)) { | |||
2785 | switch (*nullability) { | |||
2786 | case NullabilityKind::NonNull: | |||
2787 | Result += "nonnull "; | |||
2788 | break; | |||
2789 | ||||
2790 | case NullabilityKind::Nullable: | |||
2791 | Result += "nullable "; | |||
2792 | break; | |||
2793 | ||||
2794 | case NullabilityKind::Unspecified: | |||
2795 | Result += "null_unspecified "; | |||
2796 | break; | |||
2797 | ||||
2798 | case NullabilityKind::NullableResult: | |||
2799 | llvm_unreachable("Not supported as a context-sensitive keyword!")::llvm::llvm_unreachable_internal("Not supported as a context-sensitive keyword!" , "clang/lib/Sema/SemaCodeComplete.cpp", 2799); | |||
2800 | break; | |||
2801 | } | |||
2802 | } | |||
2803 | } | |||
2804 | return Result; | |||
2805 | } | |||
2806 | ||||
2807 | /// Tries to find the most appropriate type location for an Objective-C | |||
2808 | /// block placeholder. | |||
2809 | /// | |||
2810 | /// This function ignores things like typedefs and qualifiers in order to | |||
2811 | /// present the most relevant and accurate block placeholders in code completion | |||
2812 | /// results. | |||
2813 | static void findTypeLocationForBlockDecl(const TypeSourceInfo *TSInfo, | |||
2814 | FunctionTypeLoc &Block, | |||
2815 | FunctionProtoTypeLoc &BlockProto, | |||
2816 | bool SuppressBlock = false) { | |||
2817 | if (!TSInfo) | |||
2818 | return; | |||
2819 | TypeLoc TL = TSInfo->getTypeLoc().getUnqualifiedLoc(); | |||
2820 | while (true) { | |||
2821 | // Look through typedefs. | |||
2822 | if (!SuppressBlock) { | |||
2823 | if (TypedefTypeLoc TypedefTL = TL.getAsAdjusted<TypedefTypeLoc>()) { | |||
2824 | if (TypeSourceInfo *InnerTSInfo = | |||
2825 | TypedefTL.getTypedefNameDecl()->getTypeSourceInfo()) { | |||
2826 | TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc(); | |||
2827 | continue; | |||
2828 | } | |||
2829 | } | |||
2830 | ||||
2831 | // Look through qualified types | |||
2832 | if (QualifiedTypeLoc QualifiedTL = TL.getAs<QualifiedTypeLoc>()) { | |||
2833 | TL = QualifiedTL.getUnqualifiedLoc(); | |||
2834 | continue; | |||
2835 | } | |||
2836 | ||||
2837 | if (AttributedTypeLoc AttrTL = TL.getAs<AttributedTypeLoc>()) { | |||
2838 | TL = AttrTL.getModifiedLoc(); | |||
2839 | continue; | |||
2840 | } | |||
2841 | } | |||
2842 | ||||
2843 | // Try to get the function prototype behind the block pointer type, | |||
2844 | // then we're done. | |||
2845 | if (BlockPointerTypeLoc BlockPtr = TL.getAs<BlockPointerTypeLoc>()) { | |||
2846 | TL = BlockPtr.getPointeeLoc().IgnoreParens(); | |||
2847 | Block = TL.getAs<FunctionTypeLoc>(); | |||
2848 | BlockProto = TL.getAs<FunctionProtoTypeLoc>(); | |||
2849 | } | |||
2850 | break; | |||
2851 | } | |||
2852 | } | |||
2853 | ||||
2854 | static std::string formatBlockPlaceholder( | |||
2855 | const PrintingPolicy &Policy, const NamedDecl *BlockDecl, | |||
2856 | FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto, | |||
2857 | bool SuppressBlockName = false, bool SuppressBlock = false, | |||
2858 | std::optional<ArrayRef<QualType>> ObjCSubsts = std::nullopt); | |||
2859 | ||||
2860 | static std::string FormatFunctionParameter( | |||
2861 | const PrintingPolicy &Policy, const DeclaratorDecl *Param, | |||
2862 | bool SuppressName = false, bool SuppressBlock = false, | |||
2863 | std::optional<ArrayRef<QualType>> ObjCSubsts = std::nullopt) { | |||
2864 | // Params are unavailable in FunctionTypeLoc if the FunctionType is invalid. | |||
2865 | // It would be better to pass in the param Type, which is usually available. | |||
2866 | // But this case is rare, so just pretend we fell back to int as elsewhere. | |||
2867 | if (!Param) | |||
2868 | return "int"; | |||
2869 | Decl::ObjCDeclQualifier ObjCQual = Decl::OBJC_TQ_None; | |||
2870 | if (const auto *PVD = dyn_cast<ParmVarDecl>(Param)) | |||
2871 | ObjCQual = PVD->getObjCDeclQualifier(); | |||
2872 | bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext()); | |||
2873 | if (Param->getType()->isDependentType() || | |||
2874 | !Param->getType()->isBlockPointerType()) { | |||
2875 | // The argument for a dependent or non-block parameter is a placeholder | |||
2876 | // containing that parameter's type. | |||
2877 | std::string Result; | |||
2878 | ||||
2879 | if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName) | |||
2880 | Result = std::string(Param->getIdentifier()->deuglifiedName()); | |||
2881 | ||||
2882 | QualType Type = Param->getType(); | |||
2883 | if (ObjCSubsts) | |||
2884 | Type = Type.substObjCTypeArgs(Param->getASTContext(), *ObjCSubsts, | |||
2885 | ObjCSubstitutionContext::Parameter); | |||
2886 | if (ObjCMethodParam) { | |||
2887 | Result = "(" + formatObjCParamQualifiers(ObjCQual, Type); | |||
2888 | Result += Type.getAsString(Policy) + ")"; | |||
2889 | if (Param->getIdentifier() && !SuppressName) | |||
2890 | Result += Param->getIdentifier()->deuglifiedName(); | |||
2891 | } else { | |||
2892 | Type.getAsStringInternal(Result, Policy); | |||
2893 | } | |||
2894 | return Result; | |||
2895 | } | |||
2896 | ||||
2897 | // The argument for a block pointer parameter is a block literal with | |||
2898 | // the appropriate type. | |||
2899 | FunctionTypeLoc Block; | |||
2900 | FunctionProtoTypeLoc BlockProto; | |||
2901 | findTypeLocationForBlockDecl(Param->getTypeSourceInfo(), Block, BlockProto, | |||
2902 | SuppressBlock); | |||
2903 | // Try to retrieve the block type information from the property if this is a | |||
2904 | // parameter in a setter. | |||
2905 | if (!Block && ObjCMethodParam && | |||
2906 | cast<ObjCMethodDecl>(Param->getDeclContext())->isPropertyAccessor()) { | |||
2907 | if (const auto *PD = cast<ObjCMethodDecl>(Param->getDeclContext()) | |||
2908 | ->findPropertyDecl(/*CheckOverrides=*/false)) | |||
2909 | findTypeLocationForBlockDecl(PD->getTypeSourceInfo(), Block, BlockProto, | |||
2910 | SuppressBlock); | |||
2911 | } | |||
2912 | ||||
2913 | if (!Block) { | |||
2914 | // We were unable to find a FunctionProtoTypeLoc with parameter names | |||
2915 | // for the block; just use the parameter type as a placeholder. | |||
2916 | std::string Result; | |||
2917 | if (!ObjCMethodParam && Param->getIdentifier()) | |||
2918 | Result = std::string(Param->getIdentifier()->deuglifiedName()); | |||
2919 | ||||
2920 | QualType Type = Param->getType().getUnqualifiedType(); | |||
2921 | ||||
2922 | if (ObjCMethodParam) { | |||
2923 | Result = Type.getAsString(Policy); | |||
2924 | std::string Quals = formatObjCParamQualifiers(ObjCQual, Type); | |||
2925 | if (!Quals.empty()) | |||
2926 | Result = "(" + Quals + " " + Result + ")"; | |||
2927 | if (Result.back() != ')') | |||
2928 | Result += " "; | |||
2929 | if (Param->getIdentifier()) | |||
2930 | Result += Param->getIdentifier()->deuglifiedName(); | |||
2931 | } else { | |||
2932 | Type.getAsStringInternal(Result, Policy); | |||
2933 | } | |||
2934 | ||||
2935 | return Result; | |||
2936 | } | |||
2937 | ||||
2938 | // We have the function prototype behind the block pointer type, as it was | |||
2939 | // written in the source. | |||
2940 | return formatBlockPlaceholder(Policy, Param, Block, BlockProto, | |||
2941 | /*SuppressBlockName=*/false, SuppressBlock, | |||
2942 | ObjCSubsts); | |||
2943 | } | |||
2944 | ||||
2945 | /// Returns a placeholder string that corresponds to an Objective-C block | |||
2946 | /// declaration. | |||
2947 | /// | |||
2948 | /// \param BlockDecl A declaration with an Objective-C block type. | |||
2949 | /// | |||
2950 | /// \param Block The most relevant type location for that block type. | |||
2951 | /// | |||
2952 | /// \param SuppressBlockName Determines whether or not the name of the block | |||
2953 | /// declaration is included in the resulting string. | |||
2954 | static std::string | |||
2955 | formatBlockPlaceholder(const PrintingPolicy &Policy, const NamedDecl *BlockDecl, | |||
2956 | FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto, | |||
2957 | bool SuppressBlockName, bool SuppressBlock, | |||
2958 | std::optional<ArrayRef<QualType>> ObjCSubsts) { | |||
2959 | std::string Result; | |||
2960 | QualType ResultType = Block.getTypePtr()->getReturnType(); | |||
2961 | if (ObjCSubsts) | |||
2962 | ResultType = | |||
2963 | ResultType.substObjCTypeArgs(BlockDecl->getASTContext(), *ObjCSubsts, | |||
2964 | ObjCSubstitutionContext::Result); | |||
2965 | if (!ResultType->isVoidType() || SuppressBlock) | |||
2966 | ResultType.getAsStringInternal(Result, Policy); | |||
2967 | ||||
2968 | // Format the parameter list. | |||
2969 | std::string Params; | |||
2970 | if (!BlockProto || Block.getNumParams() == 0) { | |||
2971 | if (BlockProto && BlockProto.getTypePtr()->isVariadic()) | |||
2972 | Params = "(...)"; | |||
2973 | else | |||
2974 | Params = "(void)"; | |||
2975 | } else { | |||
2976 | Params += "("; | |||
2977 | for (unsigned I = 0, N = Block.getNumParams(); I != N; ++I) { | |||
2978 | if (I) | |||
2979 | Params += ", "; | |||
2980 | Params += FormatFunctionParameter(Policy, Block.getParam(I), | |||
2981 | /*SuppressName=*/false, | |||
2982 | /*SuppressBlock=*/true, ObjCSubsts); | |||
2983 | ||||
2984 | if (I == N - 1 && BlockProto.getTypePtr()->isVariadic()) | |||
2985 | Params += ", ..."; | |||
2986 | } | |||
2987 | Params += ")"; | |||
2988 | } | |||
2989 | ||||
2990 | if (SuppressBlock) { | |||
2991 | // Format as a parameter. | |||
2992 | Result = Result + " (^"; | |||
2993 | if (!SuppressBlockName && BlockDecl->getIdentifier()) | |||
2994 | Result += BlockDecl->getIdentifier()->getName(); | |||
2995 | Result += ")"; | |||
2996 | Result += Params; | |||
2997 | } else { | |||
2998 | // Format as a block literal argument. | |||
2999 | Result = '^' + Result; | |||
3000 | Result += Params; | |||
3001 | ||||
3002 | if (!SuppressBlockName && BlockDecl->getIdentifier()) | |||
3003 | Result += BlockDecl->getIdentifier()->getName(); | |||
3004 | } | |||
3005 | ||||
3006 | return Result; | |||
3007 | } | |||
3008 | ||||
3009 | static std::string GetDefaultValueString(const ParmVarDecl *Param, | |||
3010 | const SourceManager &SM, | |||
3011 | const LangOptions &LangOpts) { | |||
3012 | const SourceRange SrcRange = Param->getDefaultArgRange(); | |||
3013 | CharSourceRange CharSrcRange = CharSourceRange::getTokenRange(SrcRange); | |||
3014 | bool Invalid = CharSrcRange.isInvalid(); | |||
3015 | if (Invalid) | |||
3016 | return ""; | |||
3017 | StringRef srcText = | |||
3018 | Lexer::getSourceText(CharSrcRange, SM, LangOpts, &Invalid); | |||
3019 | if (Invalid) | |||
3020 | return ""; | |||
3021 | ||||
3022 | if (srcText.empty() || srcText == "=") { | |||
3023 | // Lexer can't determine the value. | |||
3024 | // This happens if the code is incorrect (for example class is forward | |||
3025 | // declared). | |||
3026 | return ""; | |||
3027 | } | |||
3028 | std::string DefValue(srcText.str()); | |||
3029 | // FIXME: remove this check if the Lexer::getSourceText value is fixed and | |||
3030 | // this value always has (or always does not have) '=' in front of it | |||
3031 | if (DefValue.at(0) != '=') { | |||
3032 | // If we don't have '=' in front of value. | |||
3033 | // Lexer returns built-in types values without '=' and user-defined types | |||
3034 | // values with it. | |||
3035 | return " = " + DefValue; | |||
3036 | } | |||
3037 | return " " + DefValue; | |||
3038 | } | |||
3039 | ||||
3040 | /// Add function parameter chunks to the given code completion string. | |||
3041 | static void AddFunctionParameterChunks(Preprocessor &PP, | |||
3042 | const PrintingPolicy &Policy, | |||
3043 | const FunctionDecl *Function, | |||
3044 | CodeCompletionBuilder &Result, | |||
3045 | unsigned Start = 0, | |||
3046 | bool InOptional = false) { | |||
3047 | bool FirstParameter = true; | |||
3048 | ||||
3049 | for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) { | |||
3050 | const ParmVarDecl *Param = Function->getParamDecl(P); | |||
3051 | ||||
3052 | if (Param->hasDefaultArg() && !InOptional) { | |||
3053 | // When we see an optional default argument, put that argument and | |||
3054 | // the remaining default arguments into a new, optional string. | |||
3055 | CodeCompletionBuilder Opt(Result.getAllocator(), | |||
3056 | Result.getCodeCompletionTUInfo()); | |||
3057 | if (!FirstParameter) | |||
3058 | Opt.AddChunk(CodeCompletionString::CK_Comma); | |||
3059 | AddFunctionParameterChunks(PP, Policy, Function, Opt, P, true); | |||
3060 | Result.AddOptionalChunk(Opt.TakeString()); | |||
3061 | break; | |||
3062 | } | |||
3063 | ||||
3064 | if (FirstParameter) | |||
3065 | FirstParameter = false; | |||
3066 | else | |||
3067 | Result.AddChunk(CodeCompletionString::CK_Comma); | |||
3068 | ||||
3069 | InOptional = false; | |||
3070 | ||||
3071 | // Format the placeholder string. | |||
3072 | std::string PlaceholderStr = FormatFunctionParameter(Policy, Param); | |||
3073 | if (Param->hasDefaultArg()) | |||
3074 | PlaceholderStr += | |||
3075 | GetDefaultValueString(Param, PP.getSourceManager(), PP.getLangOpts()); | |||
3076 | ||||
3077 | if (Function->isVariadic() && P == N - 1) | |||
3078 | PlaceholderStr += ", ..."; | |||
3079 | ||||
3080 | // Add the placeholder string. | |||
3081 | Result.AddPlaceholderChunk( | |||
3082 | Result.getAllocator().CopyString(PlaceholderStr)); | |||
3083 | } | |||
3084 | ||||
3085 | if (const auto *Proto = Function->getType()->getAs<FunctionProtoType>()) | |||
3086 | if (Proto->isVariadic()) { | |||
3087 | if (Proto->getNumParams() == 0) | |||
3088 | Result.AddPlaceholderChunk("..."); | |||
3089 | ||||
3090 | MaybeAddSentinel(PP, Function, Result); | |||
3091 | } | |||
3092 | } | |||
3093 | ||||
3094 | /// Add template parameter chunks to the given code completion string. | |||
3095 | static void AddTemplateParameterChunks( | |||
3096 | ASTContext &Context, const PrintingPolicy &Policy, | |||
3097 | const TemplateDecl *Template, CodeCompletionBuilder &Result, | |||
3098 | unsigned MaxParameters = 0, unsigned Start = 0, bool InDefaultArg = false) { | |||
3099 | bool FirstParameter = true; | |||
3100 | ||||
3101 | // Prefer to take the template parameter names from the first declaration of | |||
3102 | // the template. | |||
3103 | Template = cast<TemplateDecl>(Template->getCanonicalDecl()); | |||
3104 | ||||
3105 | TemplateParameterList *Params = Template->getTemplateParameters(); | |||
3106 | TemplateParameterList::iterator PEnd = Params->end(); | |||
3107 | if (MaxParameters) | |||
3108 | PEnd = Params->begin() + MaxParameters; | |||
3109 | for (TemplateParameterList::iterator P = Params->begin() + Start; P != PEnd; | |||
3110 | ++P) { | |||
3111 | bool HasDefaultArg = false; | |||
3112 | std::string PlaceholderStr; | |||
3113 | if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { | |||
3114 | if (TTP->wasDeclaredWithTypename()) | |||
3115 | PlaceholderStr = "typename"; | |||
3116 | else if (const auto *TC = TTP->getTypeConstraint()) { | |||
3117 | llvm::raw_string_ostream OS(PlaceholderStr); | |||
3118 | TC->print(OS, Policy); | |||
3119 | OS.flush(); | |||
3120 | } else | |||
3121 | PlaceholderStr = "class"; | |||
3122 | ||||
3123 | if (TTP->getIdentifier()) { | |||
3124 | PlaceholderStr += ' '; | |||
3125 | PlaceholderStr += TTP->getIdentifier()->deuglifiedName(); | |||
3126 | } | |||
3127 | ||||
3128 | HasDefaultArg = TTP->hasDefaultArgument(); | |||
3129 | } else if (NonTypeTemplateParmDecl *NTTP = | |||
3130 | dyn_cast<NonTypeTemplateParmDecl>(*P)) { | |||
3131 | if (NTTP->getIdentifier()) | |||
3132 | PlaceholderStr = std::string(NTTP->getIdentifier()->deuglifiedName()); | |||
3133 | NTTP->getType().getAsStringInternal(PlaceholderStr, Policy); | |||
3134 | HasDefaultArg = NTTP->hasDefaultArgument(); | |||
3135 | } else { | |||
3136 | assert(isa<TemplateTemplateParmDecl>(*P))(static_cast <bool> (isa<TemplateTemplateParmDecl> (*P)) ? void (0) : __assert_fail ("isa<TemplateTemplateParmDecl>(*P)" , "clang/lib/Sema/SemaCodeComplete.cpp", 3136, __extension__ __PRETTY_FUNCTION__ )); | |||
3137 | TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P); | |||
3138 | ||||
3139 | // Since putting the template argument list into the placeholder would | |||
3140 | // be very, very long, we just use an abbreviation. | |||
3141 | PlaceholderStr = "template<...> class"; | |||
3142 | if (TTP->getIdentifier()) { | |||
3143 | PlaceholderStr += ' '; | |||
3144 | PlaceholderStr += TTP->getIdentifier()->deuglifiedName(); | |||
3145 | } | |||
3146 | ||||
3147 | HasDefaultArg = TTP->hasDefaultArgument(); | |||
3148 | } | |||
3149 | ||||
3150 | if (HasDefaultArg && !InDefaultArg) { | |||
3151 | // When we see an optional default argument, put that argument and | |||
3152 | // the remaining default arguments into a new, optional string. | |||
3153 | CodeCompletionBuilder Opt(Result.getAllocator(), | |||
3154 | Result.getCodeCompletionTUInfo()); | |||
3155 | if (!FirstParameter) | |||
3156 | Opt.AddChunk(CodeCompletionString::CK_Comma); | |||
3157 | AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters, | |||
3158 | P - Params->begin(), true); | |||
3159 | Result.AddOptionalChunk(Opt.TakeString()); | |||
3160 | break; | |||
3161 | } | |||
3162 | ||||
3163 | InDefaultArg = false; | |||
3164 | ||||
3165 | if (FirstParameter) | |||
3166 | FirstParameter = false; | |||
3167 | else | |||
3168 | Result.AddChunk(CodeCompletionString::CK_Comma); | |||
3169 | ||||
3170 | // Add the placeholder string. | |||
3171 | Result.AddPlaceholderChunk( | |||
3172 | Result.getAllocator().CopyString(PlaceholderStr)); | |||
3173 | } | |||
3174 | } | |||
3175 | ||||
3176 | /// Add a qualifier to the given code-completion string, if the | |||
3177 | /// provided nested-name-specifier is non-NULL. | |||
3178 | static void AddQualifierToCompletionString(CodeCompletionBuilder &Result, | |||
3179 | NestedNameSpecifier *Qualifier, | |||
3180 | bool QualifierIsInformative, | |||
3181 | ASTContext &Context, | |||
3182 | const PrintingPolicy &Policy) { | |||
3183 | if (!Qualifier) | |||
3184 | return; | |||
3185 | ||||
3186 | std::string PrintedNNS; | |||
3187 | { | |||
3188 | llvm::raw_string_ostream OS(PrintedNNS); | |||
3189 | Qualifier->print(OS, Policy); | |||
3190 | } | |||
3191 | if (QualifierIsInformative) | |||
3192 | Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS)); | |||
3193 | else | |||
3194 | Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS)); | |||
3195 | } | |||
3196 | ||||
3197 | static void | |||
3198 | AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result, | |||
3199 | const FunctionDecl *Function) { | |||
3200 | const auto *Proto = Function->getType()->getAs<FunctionProtoType>(); | |||
3201 | if (!Proto || !Proto->getMethodQuals()) | |||
3202 | return; | |||
3203 | ||||
3204 | // FIXME: Add ref-qualifier! | |||
3205 | ||||
3206 | // Handle single qualifiers without copying | |||
3207 | if (Proto->getMethodQuals().hasOnlyConst()) { | |||
3208 | Result.AddInformativeChunk(" const"); | |||
3209 | return; | |||
3210 | } | |||
3211 | ||||
3212 | if (Proto->getMethodQuals().hasOnlyVolatile()) { | |||
3213 | Result.AddInformativeChunk(" volatile"); | |||
3214 | return; | |||
3215 | } | |||
3216 | ||||
3217 | if (Proto->getMethodQuals().hasOnlyRestrict()) { | |||
3218 | Result.AddInformativeChunk(" restrict"); | |||
3219 | return; | |||
3220 | } | |||
3221 | ||||
3222 | // Handle multiple qualifiers. | |||
3223 | std::string QualsStr; | |||
3224 | if (Proto->isConst()) | |||
3225 | QualsStr += " const"; | |||
3226 | if (Proto->isVolatile()) | |||
3227 | QualsStr += " volatile"; | |||
3228 | if (Proto->isRestrict()) | |||
3229 | QualsStr += " restrict"; | |||
3230 | Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr)); | |||
3231 | } | |||
3232 | ||||
3233 | /// Add the name of the given declaration | |||
3234 | static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy, | |||
3235 | const NamedDecl *ND, | |||
3236 | CodeCompletionBuilder &Result) { | |||
3237 | DeclarationName Name = ND->getDeclName(); | |||
3238 | if (!Name) | |||
3239 | return; | |||
3240 | ||||
3241 | switch (Name.getNameKind()) { | |||
3242 | case DeclarationName::CXXOperatorName: { | |||
3243 | const char *OperatorName = nullptr; | |||
3244 | switch (Name.getCXXOverloadedOperator()) { | |||
3245 | case OO_None: | |||
3246 | case OO_Conditional: | |||
3247 | case NUM_OVERLOADED_OPERATORS: | |||
3248 | OperatorName = "operator"; | |||
3249 | break; | |||
3250 | ||||
3251 | #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \ | |||
3252 | case OO_##Name: \ | |||
3253 | OperatorName = "operator" Spelling; \ | |||
3254 | break; | |||
3255 | #define OVERLOADED_OPERATOR_MULTI(Name, Spelling, Unary, Binary, MemberOnly) | |||
3256 | #include "clang/Basic/OperatorKinds.def" | |||
3257 | ||||
3258 | case OO_New: | |||
3259 | OperatorName = "operator new"; | |||
3260 | break; | |||
3261 | case OO_Delete: | |||
3262 | OperatorName = "operator delete"; | |||
3263 | break; | |||
3264 | case OO_Array_New: | |||
3265 | OperatorName = "operator new[]"; | |||
3266 | break; | |||
3267 | case OO_Array_Delete: | |||
3268 | OperatorName = "operator delete[]"; | |||
3269 | break; | |||
3270 | case OO_Call: | |||
3271 | OperatorName = "operator()"; | |||
3272 | break; | |||
3273 | case OO_Subscript: | |||
3274 | OperatorName = "operator[]"; | |||
3275 | break; | |||
3276 | } | |||
3277 | Result.AddTypedTextChunk(OperatorName); | |||
3278 | break; | |||
3279 | } | |||
3280 | ||||
3281 | case DeclarationName::Identifier: | |||
3282 | case DeclarationName::CXXConversionFunctionName: | |||
3283 | case DeclarationName::CXXDestructorName: | |||
3284 | case DeclarationName::CXXLiteralOperatorName: | |||
3285 | Result.AddTypedTextChunk( | |||
3286 | Result.getAllocator().CopyString(ND->getNameAsString())); | |||
3287 | break; | |||
3288 | ||||
3289 | case DeclarationName::CXXDeductionGuideName: | |||
3290 | case DeclarationName::CXXUsingDirective: | |||
3291 | case DeclarationName::ObjCZeroArgSelector: | |||
3292 | case DeclarationName::ObjCOneArgSelector: | |||
3293 | case DeclarationName::ObjCMultiArgSelector: | |||
3294 | break; | |||
3295 | ||||
3296 | case DeclarationName::CXXConstructorName: { | |||
3297 | CXXRecordDecl *Record = nullptr; | |||
3298 | QualType Ty = Name.getCXXNameType(); | |||
3299 | if (const auto *RecordTy = Ty->getAs<RecordType>()) | |||
3300 | Record = cast<CXXRecordDecl>(RecordTy->getDecl()); | |||
3301 | else if (const auto *InjectedTy = Ty->getAs<InjectedClassNameType>()) | |||
3302 | Record = InjectedTy->getDecl(); | |||
3303 | else { | |||
3304 | Result.AddTypedTextChunk( | |||
3305 | Result.getAllocator().CopyString(ND->getNameAsString())); | |||
3306 | break; | |||
3307 | } | |||
3308 | ||||
3309 | Result.AddTypedTextChunk( | |||
3310 | Result.getAllocator().CopyString(Record->getNameAsString())); | |||
3311 | if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) { | |||
3312 | Result.AddChunk(CodeCompletionString::CK_LeftAngle); | |||
3313 | AddTemplateParameterChunks(Context, Policy, Template, Result); | |||
3314 | Result.AddChunk(CodeCompletionString::CK_RightAngle); | |||
3315 | } | |||
3316 | break; | |||
3317 | } | |||
3318 | } | |||
3319 | } | |||
3320 | ||||
3321 | CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString( | |||
3322 | Sema &S, const CodeCompletionContext &CCContext, | |||
3323 | CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo, | |||
3324 | bool IncludeBriefComments) { | |||
3325 | return CreateCodeCompletionString(S.Context, S.PP, CCContext, Allocator, | |||
3326 | CCTUInfo, IncludeBriefComments); | |||
3327 | } | |||
3328 | ||||
3329 | CodeCompletionString *CodeCompletionResult::CreateCodeCompletionStringForMacro( | |||
3330 | Preprocessor &PP, CodeCompletionAllocator &Allocator, | |||
3331 | CodeCompletionTUInfo &CCTUInfo) { | |||
3332 | assert(Kind == RK_Macro)(static_cast <bool> (Kind == RK_Macro) ? void (0) : __assert_fail ("Kind == RK_Macro", "clang/lib/Sema/SemaCodeComplete.cpp", 3332 , __extension__ __PRETTY_FUNCTION__)); | |||
3333 | CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability); | |||
3334 | const MacroInfo *MI = PP.getMacroInfo(Macro); | |||
3335 | Result.AddTypedTextChunk(Result.getAllocator().CopyString(Macro->getName())); | |||
3336 | ||||
3337 | if (!MI || !MI->isFunctionLike()) | |||
3338 | return Result.TakeString(); | |||
3339 | ||||
3340 | // Format a function-like macro with placeholders for the arguments. | |||
3341 | Result.AddChunk(CodeCompletionString::CK_LeftParen); | |||
3342 | MacroInfo::param_iterator A = MI->param_begin(), AEnd = MI->param_end(); | |||
3343 | ||||
3344 | // C99 variadic macros add __VA_ARGS__ at the end. Skip it. | |||
3345 | if (MI->isC99Varargs()) { | |||
3346 | --AEnd; | |||
3347 | ||||
3348 | if (A == AEnd) { | |||
3349 | Result.AddPlaceholderChunk("..."); | |||
3350 | } | |||
3351 | } | |||
3352 | ||||
3353 | for (MacroInfo::param_iterator A = MI->param_begin(); A != AEnd; ++A) { | |||
3354 | if (A != MI->param_begin()) | |||
3355 | Result.AddChunk(CodeCompletionString::CK_Comma); | |||
3356 | ||||
3357 | if (MI->isVariadic() && (A + 1) == AEnd) { | |||
3358 | SmallString<32> Arg = (*A)->getName(); | |||
3359 | if (MI->isC99Varargs()) | |||
3360 | Arg += ", ..."; | |||
3361 | else | |||
3362 | Arg += "..."; | |||
3363 | Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg)); | |||
3364 | break; | |||
3365 | } | |||
3366 | ||||
3367 | // Non-variadic macros are simple. | |||
3368 | Result.AddPlaceholderChunk( | |||
3369 | Result.getAllocator().CopyString((*A)->getName())); | |||
3370 | } | |||
3371 | Result.AddChunk(CodeCompletionString::CK_RightParen); | |||
3372 | return Result.TakeString(); | |||
3373 | } | |||
3374 | ||||
3375 | /// If possible, create a new code completion string for the given | |||
3376 | /// result. | |||
3377 | /// | |||
3378 | /// \returns Either a new, heap-allocated code completion string describing | |||
3379 | /// how to use this result, or NULL to indicate that the string or name of the | |||
3380 | /// result is all that is needed. | |||
3381 | CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString( | |||
3382 | ASTContext &Ctx, Preprocessor &PP, const CodeCompletionContext &CCContext, | |||
3383 | CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo, | |||
3384 | bool IncludeBriefComments) { | |||
3385 | if (Kind == RK_Macro) | |||
3386 | return CreateCodeCompletionStringForMacro(PP, Allocator, CCTUInfo); | |||
3387 | ||||
3388 | CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability); | |||
3389 | ||||
3390 | PrintingPolicy Policy = getCompletionPrintingPolicy(Ctx, PP); | |||
3391 | if (Kind == RK_Pattern) { | |||
3392 | Pattern->Priority = Priority; | |||
3393 | Pattern->Availability = Availability; | |||
3394 | ||||
3395 | if (Declaration) { | |||
3396 | Result.addParentContext(Declaration->getDeclContext()); | |||
3397 | Pattern->ParentName = Result.getParentName(); | |||
3398 | if (const RawComment *RC = | |||
3399 | getPatternCompletionComment(Ctx, Declaration)) { | |||
3400 | Result.addBriefComment(RC->getBriefText(Ctx)); | |||
3401 | Pattern->BriefComment = Result.getBriefComment(); | |||
3402 | } | |||
3403 | } | |||
3404 | ||||
3405 | return Pattern; | |||
3406 | } | |||
3407 | ||||
3408 | if (Kind == RK_Keyword) { | |||
3409 | Result.AddTypedTextChunk(Keyword); | |||
3410 | return Result.TakeString(); | |||
3411 | } | |||
3412 | assert(Kind == RK_Declaration && "Missed a result kind?")(static_cast <bool> (Kind == RK_Declaration && "Missed a result kind?" ) ? void (0) : __assert_fail ("Kind == RK_Declaration && \"Missed a result kind?\"" , "clang/lib/Sema/SemaCodeComplete.cpp", 3412, __extension__ __PRETTY_FUNCTION__ )); | |||
3413 | return createCodeCompletionStringForDecl( | |||
3414 | PP, Ctx, Result, IncludeBriefComments, CCContext, Policy); | |||
3415 | } | |||
3416 | ||||
3417 | static void printOverrideString(const CodeCompletionString &CCS, | |||
3418 | std::string &BeforeName, | |||
3419 | std::string &NameAndSignature) { | |||
3420 | bool SeenTypedChunk = false; | |||
3421 | for (auto &Chunk : CCS) { | |||
3422 | if (Chunk.Kind == CodeCompletionString::CK_Optional) { | |||
3423 | assert(SeenTypedChunk && "optional parameter before name")(static_cast <bool> (SeenTypedChunk && "optional parameter before name" ) ? void (0) : __assert_fail ("SeenTypedChunk && \"optional parameter before name\"" , "clang/lib/Sema/SemaCodeComplete.cpp", 3423, __extension__ __PRETTY_FUNCTION__ )); | |||
3424 | // Note that we put all chunks inside into NameAndSignature. | |||
3425 | printOverrideString(*Chunk.Optional, NameAndSignature, NameAndSignature); | |||
3426 | continue; | |||
3427 | } | |||
3428 | SeenTypedChunk |= Chunk.Kind == CodeCompletionString::CK_TypedText; | |||
3429 | if (SeenTypedChunk) | |||
3430 | NameAndSignature += Chunk.Text; | |||
3431 | else | |||
3432 | BeforeName += Chunk.Text; | |||
3433 | } | |||
3434 | } | |||
3435 | ||||
3436 | CodeCompletionString * | |||
3437 | CodeCompletionResult::createCodeCompletionStringForOverride( | |||
3438 | Preprocessor &PP, ASTContext &Ctx, CodeCompletionBuilder &Result, | |||
3439 | bool IncludeBriefComments, const CodeCompletionContext &CCContext, | |||
3440 | PrintingPolicy &Policy) { | |||
3441 | auto *CCS = createCodeCompletionStringForDecl(PP, Ctx, Result, | |||
3442 | /*IncludeBriefComments=*/false, | |||
3443 | CCContext, Policy); | |||
3444 | std::string BeforeName; | |||
3445 | std::string NameAndSignature; | |||
3446 | // For overrides all chunks go into the result, none are informative. | |||
3447 | printOverrideString(*CCS, BeforeName, NameAndSignature); | |||
3448 | NameAndSignature += " override"; | |||
3449 | ||||
3450 | Result.AddTextChunk(Result.getAllocator().CopyString(BeforeName)); | |||
3451 | Result.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
3452 | Result.AddTypedTextChunk(Result.getAllocator().CopyString(NameAndSignature)); | |||
3453 | return Result.TakeString(); | |||
3454 | } | |||
3455 | ||||
3456 | // FIXME: Right now this works well with lambdas. Add support for other functor | |||
3457 | // types like std::function. | |||
3458 | static const NamedDecl *extractFunctorCallOperator(const NamedDecl *ND) { | |||
3459 | const auto *VD = dyn_cast<VarDecl>(ND); | |||
3460 | if (!VD) | |||
3461 | return nullptr; | |||
3462 | const auto *RecordDecl = VD->getType()->getAsCXXRecordDecl(); | |||
3463 | if (!RecordDecl || !RecordDecl->isLambda()) | |||
3464 | return nullptr; | |||
3465 | return RecordDecl->getLambdaCallOperator(); | |||
3466 | } | |||
3467 | ||||
3468 | CodeCompletionString *CodeCompletionResult::createCodeCompletionStringForDecl( | |||
3469 | Preprocessor &PP, ASTContext &Ctx, CodeCompletionBuilder &Result, | |||
3470 | bool IncludeBriefComments, const CodeCompletionContext &CCContext, | |||
3471 | PrintingPolicy &Policy) { | |||
3472 | const NamedDecl *ND = Declaration; | |||
3473 | Result.addParentContext(ND->getDeclContext()); | |||
3474 | ||||
3475 | if (IncludeBriefComments) { | |||
3476 | // Add documentation comment, if it exists. | |||
3477 | if (const RawComment *RC = getCompletionComment(Ctx, Declaration)) { | |||
3478 | Result.addBriefComment(RC->getBriefText(Ctx)); | |||
3479 | } | |||
3480 | } | |||
3481 | ||||
3482 | if (StartsNestedNameSpecifier) { | |||
3483 | Result.AddTypedTextChunk( | |||
3484 | Result.getAllocator().CopyString(ND->getNameAsString())); | |||
3485 | Result.AddTextChunk("::"); | |||
3486 | return Result.TakeString(); | |||
3487 | } | |||
3488 | ||||
3489 | for (const auto *I : ND->specific_attrs<AnnotateAttr>()) | |||
3490 | Result.AddAnnotation(Result.getAllocator().CopyString(I->getAnnotation())); | |||
3491 | ||||
3492 | auto AddFunctionTypeAndResult = [&](const FunctionDecl *Function) { | |||
3493 | AddResultTypeChunk(Ctx, Policy, Function, CCContext.getBaseType(), Result); | |||
3494 | AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative, | |||
3495 | Ctx, Policy); | |||
3496 | AddTypedNameChunk(Ctx, Policy, ND, Result); | |||
3497 | Result.AddChunk(CodeCompletionString::CK_LeftParen); | |||
3498 | AddFunctionParameterChunks(PP, Policy, Function, Result); | |||
3499 | Result.AddChunk(CodeCompletionString::CK_RightParen); | |||
3500 | AddFunctionTypeQualsToCompletionString(Result, Function); | |||
3501 | }; | |||
3502 | ||||
3503 | if (const auto *Function = dyn_cast<FunctionDecl>(ND)) { | |||
3504 | AddFunctionTypeAndResult(Function); | |||
3505 | return Result.TakeString(); | |||
3506 | } | |||
3507 | ||||
3508 | if (const auto *CallOperator = | |||
3509 | dyn_cast_or_null<FunctionDecl>(extractFunctorCallOperator(ND))) { | |||
3510 | AddFunctionTypeAndResult(CallOperator); | |||
3511 | return Result.TakeString(); | |||
3512 | } | |||
3513 | ||||
3514 | AddResultTypeChunk(Ctx, Policy, ND, CCContext.getBaseType(), Result); | |||
3515 | ||||
3516 | if (const FunctionTemplateDecl *FunTmpl = | |||
3517 | dyn_cast<FunctionTemplateDecl>(ND)) { | |||
3518 | AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative, | |||
3519 | Ctx, Policy); | |||
3520 | FunctionDecl *Function = FunTmpl->getTemplatedDecl(); | |||
3521 | AddTypedNameChunk(Ctx, Policy, Function, Result); | |||
3522 | ||||
3523 | // Figure out which template parameters are deduced (or have default | |||
3524 | // arguments). | |||
3525 | llvm::SmallBitVector Deduced; | |||
3526 | Sema::MarkDeducedTemplateParameters(Ctx, FunTmpl, Deduced); | |||
3527 | unsigned LastDeducibleArgument; | |||
3528 | for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0; | |||
3529 | --LastDeducibleArgument) { | |||
3530 | if (!Deduced[LastDeducibleArgument - 1]) { | |||
3531 | // C++0x: Figure out if the template argument has a default. If so, | |||
3532 | // the user doesn't need to type this argument. | |||
3533 | // FIXME: We need to abstract template parameters better! | |||
3534 | bool HasDefaultArg = false; | |||
3535 | NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam( | |||
3536 | LastDeducibleArgument - 1); | |||
3537 | if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) | |||
3538 | HasDefaultArg = TTP->hasDefaultArgument(); | |||
3539 | else if (NonTypeTemplateParmDecl *NTTP = | |||
3540 | dyn_cast<NonTypeTemplateParmDecl>(Param)) | |||
3541 | HasDefaultArg = NTTP->hasDefaultArgument(); | |||
3542 | else { | |||
3543 | assert(isa<TemplateTemplateParmDecl>(Param))(static_cast <bool> (isa<TemplateTemplateParmDecl> (Param)) ? void (0) : __assert_fail ("isa<TemplateTemplateParmDecl>(Param)" , "clang/lib/Sema/SemaCodeComplete.cpp", 3543, __extension__ __PRETTY_FUNCTION__ )); | |||
3544 | HasDefaultArg = | |||
3545 | cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument(); | |||
3546 | } | |||
3547 | ||||
3548 | if (!HasDefaultArg) | |||
3549 | break; | |||
3550 | } | |||
3551 | } | |||
3552 | ||||
3553 | if (LastDeducibleArgument) { | |||
3554 | // Some of the function template arguments cannot be deduced from a | |||
3555 | // function call, so we introduce an explicit template argument list | |||
3556 | // containing all of the arguments up to the first deducible argument. | |||
3557 | Result.AddChunk(CodeCompletionString::CK_LeftAngle); | |||
3558 | AddTemplateParameterChunks(Ctx, Policy, FunTmpl, Result, | |||
3559 | LastDeducibleArgument); | |||
3560 | Result.AddChunk(CodeCompletionString::CK_RightAngle); | |||
3561 | } | |||
3562 | ||||
3563 | // Add the function parameters | |||
3564 | Result.AddChunk(CodeCompletionString::CK_LeftParen); | |||
3565 | AddFunctionParameterChunks(PP, Policy, Function, Result); | |||
3566 | Result.AddChunk(CodeCompletionString::CK_RightParen); | |||
3567 | AddFunctionTypeQualsToCompletionString(Result, Function); | |||
3568 | return Result.TakeString(); | |||
3569 | } | |||
3570 | ||||
3571 | if (const auto *Template = dyn_cast<TemplateDecl>(ND)) { | |||
3572 | AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative, | |||
3573 | Ctx, Policy); | |||
3574 | Result.AddTypedTextChunk( | |||
3575 | Result.getAllocator().CopyString(Template->getNameAsString())); | |||
3576 | Result.AddChunk(CodeCompletionString::CK_LeftAngle); | |||
3577 | AddTemplateParameterChunks(Ctx, Policy, Template, Result); | |||
3578 | Result.AddChunk(CodeCompletionString::CK_RightAngle); | |||
3579 | return Result.TakeString(); | |||
3580 | } | |||
3581 | ||||
3582 | if (const auto *Method = dyn_cast<ObjCMethodDecl>(ND)) { | |||
3583 | Selector Sel = Method->getSelector(); | |||
3584 | if (Sel.isUnarySelector()) { | |||
3585 | Result.AddTypedTextChunk( | |||
3586 | Result.getAllocator().CopyString(Sel.getNameForSlot(0))); | |||
3587 | return Result.TakeString(); | |||
3588 | } | |||
3589 | ||||
3590 | std::string SelName = Sel.getNameForSlot(0).str(); | |||
3591 | SelName += ':'; | |||
3592 | if (StartParameter == 0) | |||
3593 | Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName)); | |||
3594 | else { | |||
3595 | Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName)); | |||
3596 | ||||
3597 | // If there is only one parameter, and we're past it, add an empty | |||
3598 | // typed-text chunk since there is nothing to type. | |||
3599 | if (Method->param_size() == 1) | |||
3600 | Result.AddTypedTextChunk(""); | |||
3601 | } | |||
3602 | unsigned Idx = 0; | |||
3603 | // The extra Idx < Sel.getNumArgs() check is needed due to legacy C-style | |||
3604 | // method parameters. | |||
3605 | for (ObjCMethodDecl::param_const_iterator P = Method->param_begin(), | |||
3606 | PEnd = Method->param_end(); | |||
3607 | P != PEnd && Idx < Sel.getNumArgs(); (void)++P, ++Idx) { | |||
3608 | if (Idx > 0) { | |||
3609 | std::string Keyword; | |||
3610 | if (Idx > StartParameter) | |||
3611 | Result.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
3612 | if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx)) | |||
3613 | Keyword += II->getName(); | |||
3614 | Keyword += ":"; | |||
3615 | if (Idx < StartParameter || AllParametersAreInformative) | |||
3616 | Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword)); | |||
3617 | else | |||
3618 | Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword)); | |||
3619 | } | |||
3620 | ||||
3621 | // If we're before the starting parameter, skip the placeholder. | |||
3622 | if (Idx < StartParameter) | |||
3623 | continue; | |||
3624 | ||||
3625 | std::string Arg; | |||
3626 | QualType ParamType = (*P)->getType(); | |||
3627 | std::optional<ArrayRef<QualType>> ObjCSubsts; | |||
3628 | if (!CCContext.getBaseType().isNull()) | |||
3629 | ObjCSubsts = CCContext.getBaseType()->getObjCSubstitutions(Method); | |||
3630 | ||||
3631 | if (ParamType->isBlockPointerType() && !DeclaringEntity) | |||
3632 | Arg = FormatFunctionParameter(Policy, *P, true, | |||
3633 | /*SuppressBlock=*/false, ObjCSubsts); | |||
3634 | else { | |||
3635 | if (ObjCSubsts) | |||
3636 | ParamType = ParamType.substObjCTypeArgs( | |||
3637 | Ctx, *ObjCSubsts, ObjCSubstitutionContext::Parameter); | |||
3638 | Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier(), | |||
3639 | ParamType); | |||
3640 | Arg += ParamType.getAsString(Policy) + ")"; | |||
3641 | if (IdentifierInfo *II = (*P)->getIdentifier()) | |||
3642 | if (DeclaringEntity || AllParametersAreInformative) | |||
3643 | Arg += II->getName(); | |||
3644 | } | |||
3645 | ||||
3646 | if (Method->isVariadic() && (P + 1) == PEnd) | |||
3647 | Arg += ", ..."; | |||
3648 | ||||
3649 | if (DeclaringEntity) | |||
3650 | Result.AddTextChunk(Result.getAllocator().CopyString(Arg)); | |||
3651 | else if (AllParametersAreInformative) | |||
3652 | Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg)); | |||
3653 | else | |||
3654 | Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg)); | |||
3655 | } | |||
3656 | ||||
3657 | if (Method->isVariadic()) { | |||
3658 | if (Method->param_size() == 0) { | |||
3659 | if (DeclaringEntity) | |||
3660 | Result.AddTextChunk(", ..."); | |||
3661 | else if (AllParametersAreInformative) | |||
3662 | Result.AddInformativeChunk(", ..."); | |||
3663 | else | |||
3664 | Result.AddPlaceholderChunk(", ..."); | |||
3665 | } | |||
3666 | ||||
3667 | MaybeAddSentinel(PP, Method, Result); | |||
3668 | } | |||
3669 | ||||
3670 | return Result.TakeString(); | |||
3671 | } | |||
3672 | ||||
3673 | if (Qualifier) | |||
3674 | AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative, | |||
3675 | Ctx, Policy); | |||
3676 | ||||
3677 | Result.AddTypedTextChunk( | |||
3678 | Result.getAllocator().CopyString(ND->getNameAsString())); | |||
3679 | return Result.TakeString(); | |||
3680 | } | |||
3681 | ||||
3682 | const RawComment *clang::getCompletionComment(const ASTContext &Ctx, | |||
3683 | const NamedDecl *ND) { | |||
3684 | if (!ND) | |||
3685 | return nullptr; | |||
3686 | if (auto *RC = Ctx.getRawCommentForAnyRedecl(ND)) | |||
3687 | return RC; | |||
3688 | ||||
3689 | // Try to find comment from a property for ObjC methods. | |||
3690 | const auto *M = dyn_cast<ObjCMethodDecl>(ND); | |||
3691 | if (!M) | |||
3692 | return nullptr; | |||
3693 | const ObjCPropertyDecl *PDecl = M->findPropertyDecl(); | |||
3694 | if (!PDecl) | |||
3695 | return nullptr; | |||
3696 | ||||
3697 | return Ctx.getRawCommentForAnyRedecl(PDecl); | |||
3698 | } | |||
3699 | ||||
3700 | const RawComment *clang::getPatternCompletionComment(const ASTContext &Ctx, | |||
3701 | const NamedDecl *ND) { | |||
3702 | const auto *M = dyn_cast_or_null<ObjCMethodDecl>(ND); | |||
3703 | if (!M || !M->isPropertyAccessor()) | |||
3704 | return nullptr; | |||
3705 | ||||
3706 | // Provide code completion comment for self.GetterName where | |||
3707 | // GetterName is the getter method for a property with name | |||
3708 | // different from the property name (declared via a property | |||
3709 | // getter attribute. | |||
3710 | const ObjCPropertyDecl *PDecl = M->findPropertyDecl(); | |||
3711 | if (!PDecl) | |||
3712 | return nullptr; | |||
3713 | if (PDecl->getGetterName() == M->getSelector() && | |||
3714 | PDecl->getIdentifier() != M->getIdentifier()) { | |||
3715 | if (auto *RC = Ctx.getRawCommentForAnyRedecl(M)) | |||
3716 | return RC; | |||
3717 | if (auto *RC = Ctx.getRawCommentForAnyRedecl(PDecl)) | |||
3718 | return RC; | |||
3719 | } | |||
3720 | return nullptr; | |||
3721 | } | |||
3722 | ||||
3723 | const RawComment *clang::getParameterComment( | |||
3724 | const ASTContext &Ctx, | |||
3725 | const CodeCompleteConsumer::OverloadCandidate &Result, unsigned ArgIndex) { | |||
3726 | auto FDecl = Result.getFunction(); | |||
3727 | if (!FDecl) | |||
3728 | return nullptr; | |||
3729 | if (ArgIndex < FDecl->getNumParams()) | |||
3730 | return Ctx.getRawCommentForAnyRedecl(FDecl->getParamDecl(ArgIndex)); | |||
3731 | return nullptr; | |||
3732 | } | |||
3733 | ||||
3734 | static void AddOverloadAggregateChunks(const RecordDecl *RD, | |||
3735 | const PrintingPolicy &Policy, | |||
3736 | CodeCompletionBuilder &Result, | |||
3737 | unsigned CurrentArg) { | |||
3738 | unsigned ChunkIndex = 0; | |||
3739 | auto AddChunk = [&](llvm::StringRef Placeholder) { | |||
3740 | if (ChunkIndex > 0) | |||
3741 | Result.AddChunk(CodeCompletionString::CK_Comma); | |||
3742 | const char *Copy = Result.getAllocator().CopyString(Placeholder); | |||
3743 | if (ChunkIndex == CurrentArg) | |||
3744 | Result.AddCurrentParameterChunk(Copy); | |||
3745 | else | |||
3746 | Result.AddPlaceholderChunk(Copy); | |||
3747 | ++ChunkIndex; | |||
3748 | }; | |||
3749 | // Aggregate initialization has all bases followed by all fields. | |||
3750 | // (Bases are not legal in C++11 but in that case we never get here). | |||
3751 | if (auto *CRD = llvm::dyn_cast<CXXRecordDecl>(RD)) { | |||
3752 | for (const auto &Base : CRD->bases()) | |||
3753 | AddChunk(Base.getType().getAsString(Policy)); | |||
3754 | } | |||
3755 | for (const auto &Field : RD->fields()) | |||
3756 | AddChunk(FormatFunctionParameter(Policy, Field)); | |||
3757 | } | |||
3758 | ||||
3759 | /// Add function overload parameter chunks to the given code completion | |||
3760 | /// string. | |||
3761 | static void AddOverloadParameterChunks( | |||
3762 | ASTContext &Context, const PrintingPolicy &Policy, | |||
3763 | const FunctionDecl *Function, const FunctionProtoType *Prototype, | |||
3764 | FunctionProtoTypeLoc PrototypeLoc, CodeCompletionBuilder &Result, | |||
3765 | unsigned CurrentArg, unsigned Start = 0, bool InOptional = false) { | |||
3766 | if (!Function && !Prototype) { | |||
3767 | Result.AddChunk(CodeCompletionString::CK_CurrentParameter, "..."); | |||
3768 | return; | |||
3769 | } | |||
3770 | ||||
3771 | bool FirstParameter = true; | |||
3772 | unsigned NumParams = | |||
3773 | Function ? Function->getNumParams() : Prototype->getNumParams(); | |||
3774 | ||||
3775 | for (unsigned P = Start; P != NumParams; ++P) { | |||
3776 | if (Function && Function->getParamDecl(P)->hasDefaultArg() && !InOptional) { | |||
3777 | // When we see an optional default argument, put that argument and | |||
3778 | // the remaining default arguments into a new, optional string. | |||
3779 | CodeCompletionBuilder Opt(Result.getAllocator(), | |||
3780 | Result.getCodeCompletionTUInfo()); | |||
3781 | if (!FirstParameter) | |||
3782 | Opt.AddChunk(CodeCompletionString::CK_Comma); | |||
3783 | // Optional sections are nested. | |||
3784 | AddOverloadParameterChunks(Context, Policy, Function, Prototype, | |||
3785 | PrototypeLoc, Opt, CurrentArg, P, | |||
3786 | /*InOptional=*/true); | |||
3787 | Result.AddOptionalChunk(Opt.TakeString()); | |||
3788 | return; | |||
3789 | } | |||
3790 | ||||
3791 | if (FirstParameter) | |||
3792 | FirstParameter = false; | |||
3793 | else | |||
3794 | Result.AddChunk(CodeCompletionString::CK_Comma); | |||
3795 | ||||
3796 | InOptional = false; | |||
3797 | ||||
3798 | // Format the placeholder string. | |||
3799 | std::string Placeholder; | |||
3800 | assert(P < Prototype->getNumParams())(static_cast <bool> (P < Prototype->getNumParams( )) ? void (0) : __assert_fail ("P < Prototype->getNumParams()" , "clang/lib/Sema/SemaCodeComplete.cpp", 3800, __extension__ __PRETTY_FUNCTION__ )); | |||
3801 | if (Function || PrototypeLoc) { | |||
3802 | const ParmVarDecl *Param = | |||
3803 | Function ? Function->getParamDecl(P) : PrototypeLoc.getParam(P); | |||
3804 | Placeholder = FormatFunctionParameter(Policy, Param); | |||
3805 | if (Param->hasDefaultArg()) | |||
3806 | Placeholder += GetDefaultValueString(Param, Context.getSourceManager(), | |||
3807 | Context.getLangOpts()); | |||
3808 | } else { | |||
3809 | Placeholder = Prototype->getParamType(P).getAsString(Policy); | |||
3810 | } | |||
3811 | ||||
3812 | if (P == CurrentArg) | |||
3813 | Result.AddCurrentParameterChunk( | |||
3814 | Result.getAllocator().CopyString(Placeholder)); | |||
3815 | else | |||
3816 | Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Placeholder)); | |||
3817 | } | |||
3818 | ||||
3819 | if (Prototype && Prototype->isVariadic()) { | |||
3820 | CodeCompletionBuilder Opt(Result.getAllocator(), | |||
3821 | Result.getCodeCompletionTUInfo()); | |||
3822 | if (!FirstParameter) | |||
3823 | Opt.AddChunk(CodeCompletionString::CK_Comma); | |||
3824 | ||||
3825 | if (CurrentArg < NumParams) | |||
3826 | Opt.AddPlaceholderChunk("..."); | |||
3827 | else | |||
3828 | Opt.AddCurrentParameterChunk("..."); | |||
3829 | ||||
3830 | Result.AddOptionalChunk(Opt.TakeString()); | |||
3831 | } | |||
3832 | } | |||
3833 | ||||
3834 | static std::string | |||
3835 | formatTemplateParameterPlaceholder(const NamedDecl *Param, bool &Optional, | |||
3836 | const PrintingPolicy &Policy) { | |||
3837 | if (const auto *Type = dyn_cast<TemplateTypeParmDecl>(Param)) { | |||
3838 | Optional = Type->hasDefaultArgument(); | |||
3839 | } else if (const auto *NonType = dyn_cast<NonTypeTemplateParmDecl>(Param)) { | |||
3840 | Optional = NonType->hasDefaultArgument(); | |||
3841 | } else if (const auto *Template = dyn_cast<TemplateTemplateParmDecl>(Param)) { | |||
3842 | Optional = Template->hasDefaultArgument(); | |||
3843 | } | |||
3844 | std::string Result; | |||
3845 | llvm::raw_string_ostream OS(Result); | |||
3846 | Param->print(OS, Policy); | |||
3847 | return Result; | |||
3848 | } | |||
3849 | ||||
3850 | static std::string templateResultType(const TemplateDecl *TD, | |||
3851 | const PrintingPolicy &Policy) { | |||
3852 | if (const auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) | |||
3853 | return CTD->getTemplatedDecl()->getKindName().str(); | |||
3854 | if (const auto *VTD = dyn_cast<VarTemplateDecl>(TD)) | |||
3855 | return VTD->getTemplatedDecl()->getType().getAsString(Policy); | |||
3856 | if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(TD)) | |||
3857 | return FTD->getTemplatedDecl()->getReturnType().getAsString(Policy); | |||
3858 | if (isa<TypeAliasTemplateDecl>(TD)) | |||
3859 | return "type"; | |||
3860 | if (isa<TemplateTemplateParmDecl>(TD)) | |||
3861 | return "class"; | |||
3862 | if (isa<ConceptDecl>(TD)) | |||
3863 | return "concept"; | |||
3864 | return ""; | |||
3865 | } | |||
3866 | ||||
3867 | static CodeCompletionString *createTemplateSignatureString( | |||
3868 | const TemplateDecl *TD, CodeCompletionBuilder &Builder, unsigned CurrentArg, | |||
3869 | const PrintingPolicy &Policy) { | |||
3870 | llvm::ArrayRef<NamedDecl *> Params = TD->getTemplateParameters()->asArray(); | |||
3871 | CodeCompletionBuilder OptionalBuilder(Builder.getAllocator(), | |||
3872 | Builder.getCodeCompletionTUInfo()); | |||
3873 | std::string ResultType = templateResultType(TD, Policy); | |||
3874 | if (!ResultType.empty()) | |||
3875 | Builder.AddResultTypeChunk(Builder.getAllocator().CopyString(ResultType)); | |||
3876 | Builder.AddTextChunk( | |||
3877 | Builder.getAllocator().CopyString(TD->getNameAsString())); | |||
3878 | Builder.AddChunk(CodeCompletionString::CK_LeftAngle); | |||
3879 | // Initially we're writing into the main string. Once we see an optional arg | |||
3880 | // (with default), we're writing into the nested optional chunk. | |||
3881 | CodeCompletionBuilder *Current = &Builder; | |||
3882 | for (unsigned I = 0; I < Params.size(); ++I) { | |||
3883 | bool Optional = false; | |||
3884 | std::string Placeholder = | |||
3885 | formatTemplateParameterPlaceholder(Params[I], Optional, Policy); | |||
3886 | if (Optional) | |||
3887 | Current = &OptionalBuilder; | |||
3888 | if (I > 0) | |||
3889 | Current->AddChunk(CodeCompletionString::CK_Comma); | |||
3890 | Current->AddChunk(I == CurrentArg | |||
3891 | ? CodeCompletionString::CK_CurrentParameter | |||
3892 | : CodeCompletionString::CK_Placeholder, | |||
3893 | Current->getAllocator().CopyString(Placeholder)); | |||
3894 | } | |||
3895 | // Add the optional chunk to the main string if we ever used it. | |||
3896 | if (Current == &OptionalBuilder) | |||
3897 | Builder.AddOptionalChunk(OptionalBuilder.TakeString()); | |||
3898 | Builder.AddChunk(CodeCompletionString::CK_RightAngle); | |||
3899 | // For function templates, ResultType was the function's return type. | |||
3900 | // Give some clue this is a function. (Don't show the possibly-bulky params). | |||
3901 | if (isa<FunctionTemplateDecl>(TD)) | |||
3902 | Builder.AddInformativeChunk("()"); | |||
3903 | return Builder.TakeString(); | |||
3904 | } | |||
3905 | ||||
3906 | CodeCompletionString * | |||
3907 | CodeCompleteConsumer::OverloadCandidate::CreateSignatureString( | |||
3908 | unsigned CurrentArg, Sema &S, CodeCompletionAllocator &Allocator, | |||
3909 | CodeCompletionTUInfo &CCTUInfo, bool IncludeBriefComments, | |||
3910 | bool Braced) const { | |||
3911 | PrintingPolicy Policy = getCompletionPrintingPolicy(S); | |||
3912 | // Show signatures of constructors as they are declared: | |||
3913 | // vector(int n) rather than vector<string>(int n) | |||
3914 | // This is less noisy without being less clear, and avoids tricky cases. | |||
3915 | Policy.SuppressTemplateArgsInCXXConstructors = true; | |||
3916 | ||||
3917 | // FIXME: Set priority, availability appropriately. | |||
3918 | CodeCompletionBuilder Result(Allocator, CCTUInfo, 1, | |||
3919 | CXAvailability_Available); | |||
3920 | ||||
3921 | if (getKind() == CK_Template) | |||
3922 | return createTemplateSignatureString(getTemplate(), Result, CurrentArg, | |||
3923 | Policy); | |||
3924 | ||||
3925 | FunctionDecl *FDecl = getFunction(); | |||
3926 | const FunctionProtoType *Proto = | |||
3927 | dyn_cast_or_null<FunctionProtoType>(getFunctionType()); | |||
3928 | ||||
3929 | // First, the name/type of the callee. | |||
3930 | if (getKind() == CK_Aggregate) { | |||
3931 | Result.AddTextChunk( | |||
3932 | Result.getAllocator().CopyString(getAggregate()->getName())); | |||
3933 | } else if (FDecl) { | |||
3934 | if (IncludeBriefComments) { | |||
3935 | if (auto RC = getParameterComment(S.getASTContext(), *this, CurrentArg)) | |||
3936 | Result.addBriefComment(RC->getBriefText(S.getASTContext())); | |||
3937 | } | |||
3938 | AddResultTypeChunk(S.Context, Policy, FDecl, QualType(), Result); | |||
3939 | ||||
3940 | std::string Name; | |||
3941 | llvm::raw_string_ostream OS(Name); | |||
3942 | FDecl->getDeclName().print(OS, Policy); | |||
3943 | Result.AddTextChunk(Result.getAllocator().CopyString(OS.str())); | |||
3944 | } else { | |||
3945 | // Function without a declaration. Just give the return type. | |||
3946 | Result.AddResultTypeChunk(Result.getAllocator().CopyString( | |||
3947 | getFunctionType()->getReturnType().getAsString(Policy))); | |||
3948 | } | |||
3949 | ||||
3950 | // Next, the brackets and parameters. | |||
3951 | Result.AddChunk(Braced ? CodeCompletionString::CK_LeftBrace | |||
3952 | : CodeCompletionString::CK_LeftParen); | |||
3953 | if (getKind() == CK_Aggregate) | |||
3954 | AddOverloadAggregateChunks(getAggregate(), Policy, Result, CurrentArg); | |||
3955 | else | |||
3956 | AddOverloadParameterChunks(S.getASTContext(), Policy, FDecl, Proto, | |||
3957 | getFunctionProtoTypeLoc(), Result, CurrentArg); | |||
3958 | Result.AddChunk(Braced ? CodeCompletionString::CK_RightBrace | |||
3959 | : CodeCompletionString::CK_RightParen); | |||
3960 | ||||
3961 | return Result.TakeString(); | |||
3962 | } | |||
3963 | ||||
3964 | unsigned clang::getMacroUsagePriority(StringRef MacroName, | |||
3965 | const LangOptions &LangOpts, | |||
3966 | bool PreferredTypeIsPointer) { | |||
3967 | unsigned Priority = CCP_Macro; | |||
3968 | ||||
3969 | // Treat the "nil", "Nil" and "NULL" macros as null pointer constants. | |||
3970 | if (MacroName.equals("nil") || MacroName.equals("NULL") || | |||
3971 | MacroName.equals("Nil")) { | |||
3972 | Priority = CCP_Constant; | |||
3973 | if (PreferredTypeIsPointer) | |||
3974 | Priority = Priority / CCF_SimilarTypeMatch; | |||
3975 | } | |||
3976 | // Treat "YES", "NO", "true", and "false" as constants. | |||
3977 | else if (MacroName.equals("YES") || MacroName.equals("NO") || | |||
3978 | MacroName.equals("true") || MacroName.equals("false")) | |||
3979 | Priority = CCP_Constant; | |||
3980 | // Treat "bool" as a type. | |||
3981 | else if (MacroName.equals("bool")) | |||
3982 | Priority = CCP_Type + (LangOpts.ObjC ? CCD_bool_in_ObjC : 0); | |||
3983 | ||||
3984 | return Priority; | |||
3985 | } | |||
3986 | ||||
3987 | CXCursorKind clang::getCursorKindForDecl(const Decl *D) { | |||
3988 | if (!D) | |||
3989 | return CXCursor_UnexposedDecl; | |||
3990 | ||||
3991 | switch (D->getKind()) { | |||
3992 | case Decl::Enum: | |||
3993 | return CXCursor_EnumDecl; | |||
3994 | case Decl::EnumConstant: | |||
3995 | return CXCursor_EnumConstantDecl; | |||
3996 | case Decl::Field: | |||
3997 | return CXCursor_FieldDecl; | |||
3998 | case Decl::Function: | |||
3999 | return CXCursor_FunctionDecl; | |||
4000 | case Decl::ObjCCategory: | |||
4001 | return CXCursor_ObjCCategoryDecl; | |||
4002 | case Decl::ObjCCategoryImpl: | |||
4003 | return CXCursor_ObjCCategoryImplDecl; | |||
4004 | case Decl::ObjCImplementation: | |||
4005 | return CXCursor_ObjCImplementationDecl; | |||
4006 | ||||
4007 | case Decl::ObjCInterface: | |||
4008 | return CXCursor_ObjCInterfaceDecl; | |||
4009 | case Decl::ObjCIvar: | |||
4010 | return CXCursor_ObjCIvarDecl; | |||
4011 | case Decl::ObjCMethod: | |||
4012 | return cast<ObjCMethodDecl>(D)->isInstanceMethod() | |||
4013 | ? CXCursor_ObjCInstanceMethodDecl | |||
4014 | : CXCursor_ObjCClassMethodDecl; | |||
4015 | case Decl::CXXMethod: | |||
4016 | return CXCursor_CXXMethod; | |||
4017 | case Decl::CXXConstructor: | |||
4018 | return CXCursor_Constructor; | |||
4019 | case Decl::CXXDestructor: | |||
4020 | return CXCursor_Destructor; | |||
4021 | case Decl::CXXConversion: | |||
4022 | return CXCursor_ConversionFunction; | |||
4023 | case Decl::ObjCProperty: | |||
4024 | return CXCursor_ObjCPropertyDecl; | |||
4025 | case Decl::ObjCProtocol: | |||
4026 | return CXCursor_ObjCProtocolDecl; | |||
4027 | case Decl::ParmVar: | |||
4028 | return CXCursor_ParmDecl; | |||
4029 | case Decl::Typedef: | |||
4030 | return CXCursor_TypedefDecl; | |||
4031 | case Decl::TypeAlias: | |||
4032 | return CXCursor_TypeAliasDecl; | |||
4033 | case Decl::TypeAliasTemplate: | |||
4034 | return CXCursor_TypeAliasTemplateDecl; | |||
4035 | case Decl::Var: | |||
4036 | return CXCursor_VarDecl; | |||
4037 | case Decl::Namespace: | |||
4038 | return CXCursor_Namespace; | |||
4039 | case Decl::NamespaceAlias: | |||
4040 | return CXCursor_NamespaceAlias; | |||
4041 | case Decl::TemplateTypeParm: | |||
4042 | return CXCursor_TemplateTypeParameter; | |||
4043 | case Decl::NonTypeTemplateParm: | |||
4044 | return CXCursor_NonTypeTemplateParameter; | |||
4045 | case Decl::TemplateTemplateParm: | |||
4046 | return CXCursor_TemplateTemplateParameter; | |||
4047 | case Decl::FunctionTemplate: | |||
4048 | return CXCursor_FunctionTemplate; | |||
4049 | case Decl::ClassTemplate: | |||
4050 | return CXCursor_ClassTemplate; | |||
4051 | case Decl::AccessSpec: | |||
4052 | return CXCursor_CXXAccessSpecifier; | |||
4053 | case Decl::ClassTemplatePartialSpecialization: | |||
4054 | return CXCursor_ClassTemplatePartialSpecialization; | |||
4055 | case Decl::UsingDirective: | |||
4056 | return CXCursor_UsingDirective; | |||
4057 | case Decl::StaticAssert: | |||
4058 | return CXCursor_StaticAssert; | |||
4059 | case Decl::Friend: | |||
4060 | return CXCursor_FriendDecl; | |||
4061 | case Decl::TranslationUnit: | |||
4062 | return CXCursor_TranslationUnit; | |||
4063 | ||||
4064 | case Decl::Using: | |||
4065 | case Decl::UnresolvedUsingValue: | |||
4066 | case Decl::UnresolvedUsingTypename: | |||
4067 | return CXCursor_UsingDeclaration; | |||
4068 | ||||
4069 | case Decl::UsingEnum: | |||
4070 | return CXCursor_EnumDecl; | |||
4071 | ||||
4072 | case Decl::ObjCPropertyImpl: | |||
4073 | switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) { | |||
4074 | case ObjCPropertyImplDecl::Dynamic: | |||
4075 | return CXCursor_ObjCDynamicDecl; | |||
4076 | ||||
4077 | case ObjCPropertyImplDecl::Synthesize: | |||
4078 | return CXCursor_ObjCSynthesizeDecl; | |||
4079 | } | |||
4080 | llvm_unreachable("Unexpected Kind!")::llvm::llvm_unreachable_internal("Unexpected Kind!", "clang/lib/Sema/SemaCodeComplete.cpp" , 4080); | |||
4081 | ||||
4082 | case Decl::Import: | |||
4083 | return CXCursor_ModuleImportDecl; | |||
4084 | ||||
4085 | case Decl::ObjCTypeParam: | |||
4086 | return CXCursor_TemplateTypeParameter; | |||
4087 | ||||
4088 | case Decl::Concept: | |||
4089 | return CXCursor_ConceptDecl; | |||
4090 | ||||
4091 | default: | |||
4092 | if (const auto *TD = dyn_cast<TagDecl>(D)) { | |||
4093 | switch (TD->getTagKind()) { | |||
4094 | case TTK_Interface: // fall through | |||
4095 | case TTK_Struct: | |||
4096 | return CXCursor_StructDecl; | |||
4097 | case TTK_Class: | |||
4098 | return CXCursor_ClassDecl; | |||
4099 | case TTK_Union: | |||
4100 | return CXCursor_UnionDecl; | |||
4101 | case TTK_Enum: | |||
4102 | return CXCursor_EnumDecl; | |||
4103 | } | |||
4104 | } | |||
4105 | } | |||
4106 | ||||
4107 | return CXCursor_UnexposedDecl; | |||
4108 | } | |||
4109 | ||||
4110 | static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results, | |||
4111 | bool LoadExternal, bool IncludeUndefined, | |||
4112 | bool TargetTypeIsPointer = false) { | |||
4113 | typedef CodeCompletionResult Result; | |||
4114 | ||||
4115 | Results.EnterNewScope(); | |||
4116 | ||||
4117 | for (Preprocessor::macro_iterator M = PP.macro_begin(LoadExternal), | |||
4118 | MEnd = PP.macro_end(LoadExternal); | |||
4119 | M != MEnd; ++M) { | |||
4120 | auto MD = PP.getMacroDefinition(M->first); | |||
4121 | if (IncludeUndefined || MD) { | |||
4122 | MacroInfo *MI = MD.getMacroInfo(); | |||
4123 | if (MI && MI->isUsedForHeaderGuard()) | |||
4124 | continue; | |||
4125 | ||||
4126 | Results.AddResult( | |||
4127 | Result(M->first, MI, | |||
4128 | getMacroUsagePriority(M->first->getName(), PP.getLangOpts(), | |||
4129 | TargetTypeIsPointer))); | |||
4130 | } | |||
4131 | } | |||
4132 | ||||
4133 | Results.ExitScope(); | |||
4134 | } | |||
4135 | ||||
4136 | static void AddPrettyFunctionResults(const LangOptions &LangOpts, | |||
4137 | ResultBuilder &Results) { | |||
4138 | typedef CodeCompletionResult Result; | |||
4139 | ||||
4140 | Results.EnterNewScope(); | |||
4141 | ||||
4142 | Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant)); | |||
4143 | Results.AddResult(Result("__FUNCTION__", CCP_Constant)); | |||
4144 | if (LangOpts.C99 || LangOpts.CPlusPlus11) | |||
4145 | Results.AddResult(Result("__func__", CCP_Constant)); | |||
4146 | Results.ExitScope(); | |||
4147 | } | |||
4148 | ||||
4149 | static void HandleCodeCompleteResults(Sema *S, | |||
4150 | CodeCompleteConsumer *CodeCompleter, | |||
4151 | const CodeCompletionContext &Context, | |||
4152 | CodeCompletionResult *Results, | |||
4153 | unsigned NumResults) { | |||
4154 | if (CodeCompleter) | |||
4155 | CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults); | |||
4156 | } | |||
4157 | ||||
4158 | static CodeCompletionContext | |||
4159 | mapCodeCompletionContext(Sema &S, Sema::ParserCompletionContext PCC) { | |||
4160 | switch (PCC) { | |||
4161 | case Sema::PCC_Namespace: | |||
4162 | return CodeCompletionContext::CCC_TopLevel; | |||
4163 | ||||
4164 | case Sema::PCC_Class: | |||
4165 | return CodeCompletionContext::CCC_ClassStructUnion; | |||
4166 | ||||
4167 | case Sema::PCC_ObjCInterface: | |||
4168 | return CodeCompletionContext::CCC_ObjCInterface; | |||
4169 | ||||
4170 | case Sema::PCC_ObjCImplementation: | |||
4171 | return CodeCompletionContext::CCC_ObjCImplementation; | |||
4172 | ||||
4173 | case Sema::PCC_ObjCInstanceVariableList: | |||
4174 | return CodeCompletionContext::CCC_ObjCIvarList; | |||
4175 | ||||
4176 | case Sema::PCC_Template: | |||
4177 | case Sema::PCC_MemberTemplate: | |||
4178 | if (S.CurContext->isFileContext()) | |||
4179 | return CodeCompletionContext::CCC_TopLevel; | |||
4180 | if (S.CurContext->isRecord()) | |||
4181 | return CodeCompletionContext::CCC_ClassStructUnion; | |||
4182 | return CodeCompletionContext::CCC_Other; | |||
4183 | ||||
4184 | case Sema::PCC_RecoveryInFunction: | |||
4185 | return CodeCompletionContext::CCC_Recovery; | |||
4186 | ||||
4187 | case Sema::PCC_ForInit: | |||
4188 | if (S.getLangOpts().CPlusPlus || S.getLangOpts().C99 || | |||
4189 | S.getLangOpts().ObjC) | |||
4190 | return CodeCompletionContext::CCC_ParenthesizedExpression; | |||
4191 | else | |||
4192 | return CodeCompletionContext::CCC_Expression; | |||
4193 | ||||
4194 | case Sema::PCC_Expression: | |||
4195 | return CodeCompletionContext::CCC_Expression; | |||
4196 | case Sema::PCC_Condition: | |||
4197 | return CodeCompletionContext(CodeCompletionContext::CCC_Expression, | |||
4198 | S.getASTContext().BoolTy); | |||
4199 | ||||
4200 | case Sema::PCC_Statement: | |||
4201 | return CodeCompletionContext::CCC_Statement; | |||
4202 | ||||
4203 | case Sema::PCC_Type: | |||
4204 | return CodeCompletionContext::CCC_Type; | |||
4205 | ||||
4206 | case Sema::PCC_ParenthesizedExpression: | |||
4207 | return CodeCompletionContext::CCC_ParenthesizedExpression; | |||
4208 | ||||
4209 | case Sema::PCC_LocalDeclarationSpecifiers: | |||
4210 | return CodeCompletionContext::CCC_Type; | |||
4211 | } | |||
4212 | ||||
4213 | llvm_unreachable("Invalid ParserCompletionContext!")::llvm::llvm_unreachable_internal("Invalid ParserCompletionContext!" , "clang/lib/Sema/SemaCodeComplete.cpp", 4213); | |||
4214 | } | |||
4215 | ||||
4216 | /// If we're in a C++ virtual member function, add completion results | |||
4217 | /// that invoke the functions we override, since it's common to invoke the | |||
4218 | /// overridden function as well as adding new functionality. | |||
4219 | /// | |||
4220 | /// \param S The semantic analysis object for which we are generating results. | |||
4221 | /// | |||
4222 | /// \param InContext This context in which the nested-name-specifier preceding | |||
4223 | /// the code-completion point | |||
4224 | static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext, | |||
4225 | ResultBuilder &Results) { | |||
4226 | // Look through blocks. | |||
4227 | DeclContext *CurContext = S.CurContext; | |||
4228 | while (isa<BlockDecl>(CurContext)) | |||
4229 | CurContext = CurContext->getParent(); | |||
4230 | ||||
4231 | CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext); | |||
4232 | if (!Method || !Method->isVirtual()) | |||
4233 | return; | |||
4234 | ||||
4235 | // We need to have names for all of the parameters, if we're going to | |||
4236 | // generate a forwarding call. | |||
4237 | for (auto *P : Method->parameters()) | |||
4238 | if (!P->getDeclName()) | |||
4239 | return; | |||
4240 | ||||
4241 | PrintingPolicy Policy = getCompletionPrintingPolicy(S); | |||
4242 | for (const CXXMethodDecl *Overridden : Method->overridden_methods()) { | |||
4243 | CodeCompletionBuilder Builder(Results.getAllocator(), | |||
4244 | Results.getCodeCompletionTUInfo()); | |||
4245 | if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl()) | |||
4246 | continue; | |||
4247 | ||||
4248 | // If we need a nested-name-specifier, add one now. | |||
4249 | if (!InContext) { | |||
4250 | NestedNameSpecifier *NNS = getRequiredQualification( | |||
4251 | S.Context, CurContext, Overridden->getDeclContext()); | |||
4252 | if (NNS) { | |||
4253 | std::string Str; | |||
4254 | llvm::raw_string_ostream OS(Str); | |||
4255 | NNS->print(OS, Policy); | |||
4256 | Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str())); | |||
4257 | } | |||
4258 | } else if (!InContext->Equals(Overridden->getDeclContext())) | |||
4259 | continue; | |||
4260 | ||||
4261 | Builder.AddTypedTextChunk( | |||
4262 | Results.getAllocator().CopyString(Overridden->getNameAsString())); | |||
4263 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
4264 | bool FirstParam = true; | |||
4265 | for (auto *P : Method->parameters()) { | |||
4266 | if (FirstParam) | |||
4267 | FirstParam = false; | |||
4268 | else | |||
4269 | Builder.AddChunk(CodeCompletionString::CK_Comma); | |||
4270 | ||||
4271 | Builder.AddPlaceholderChunk( | |||
4272 | Results.getAllocator().CopyString(P->getIdentifier()->getName())); | |||
4273 | } | |||
4274 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
4275 | Results.AddResult(CodeCompletionResult( | |||
4276 | Builder.TakeString(), CCP_SuperCompletion, CXCursor_CXXMethod, | |||
4277 | CXAvailability_Available, Overridden)); | |||
4278 | Results.Ignore(Overridden); | |||
4279 | } | |||
4280 | } | |||
4281 | ||||
4282 | void Sema::CodeCompleteModuleImport(SourceLocation ImportLoc, | |||
4283 | ModuleIdPath Path) { | |||
4284 | typedef CodeCompletionResult Result; | |||
4285 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
4286 | CodeCompleter->getCodeCompletionTUInfo(), | |||
4287 | CodeCompletionContext::CCC_Other); | |||
4288 | Results.EnterNewScope(); | |||
4289 | ||||
4290 | CodeCompletionAllocator &Allocator = Results.getAllocator(); | |||
4291 | CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo()); | |||
4292 | typedef CodeCompletionResult Result; | |||
4293 | if (Path.empty()) { | |||
4294 | // Enumerate all top-level modules. | |||
4295 | SmallVector<Module *, 8> Modules; | |||
4296 | PP.getHeaderSearchInfo().collectAllModules(Modules); | |||
4297 | for (unsigned I = 0, N = Modules.size(); I != N; ++I) { | |||
4298 | Builder.AddTypedTextChunk( | |||
4299 | Builder.getAllocator().CopyString(Modules[I]->Name)); | |||
4300 | Results.AddResult(Result( | |||
4301 | Builder.TakeString(), CCP_Declaration, CXCursor_ModuleImportDecl, | |||
4302 | Modules[I]->isAvailable() ? CXAvailability_Available | |||
4303 | : CXAvailability_NotAvailable)); | |||
4304 | } | |||
4305 | } else if (getLangOpts().Modules) { | |||
4306 | // Load the named module. | |||
4307 | Module *Mod = | |||
4308 | PP.getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, | |||
4309 | /*IsInclusionDirective=*/false); | |||
4310 | // Enumerate submodules. | |||
4311 | if (Mod) { | |||
4312 | for (auto *Submodule : Mod->submodules()) { | |||
4313 | Builder.AddTypedTextChunk( | |||
4314 | Builder.getAllocator().CopyString(Submodule->Name)); | |||
4315 | Results.AddResult(Result( | |||
4316 | Builder.TakeString(), CCP_Declaration, CXCursor_ModuleImportDecl, | |||
4317 | Submodule->isAvailable() ? CXAvailability_Available | |||
4318 | : CXAvailability_NotAvailable)); | |||
4319 | } | |||
4320 | } | |||
4321 | } | |||
4322 | Results.ExitScope(); | |||
4323 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
4324 | Results.data(), Results.size()); | |||
4325 | } | |||
4326 | ||||
4327 | void Sema::CodeCompleteOrdinaryName(Scope *S, | |||
4328 | ParserCompletionContext CompletionContext) { | |||
4329 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
4330 | CodeCompleter->getCodeCompletionTUInfo(), | |||
4331 | mapCodeCompletionContext(*this, CompletionContext)); | |||
4332 | Results.EnterNewScope(); | |||
4333 | ||||
4334 | // Determine how to filter results, e.g., so that the names of | |||
4335 | // values (functions, enumerators, function templates, etc.) are | |||
4336 | // only allowed where we can have an expression. | |||
4337 | switch (CompletionContext) { | |||
4338 | case PCC_Namespace: | |||
4339 | case PCC_Class: | |||
4340 | case PCC_ObjCInterface: | |||
4341 | case PCC_ObjCImplementation: | |||
4342 | case PCC_ObjCInstanceVariableList: | |||
4343 | case PCC_Template: | |||
4344 | case PCC_MemberTemplate: | |||
4345 | case PCC_Type: | |||
4346 | case PCC_LocalDeclarationSpecifiers: | |||
4347 | Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName); | |||
4348 | break; | |||
4349 | ||||
4350 | case PCC_Statement: | |||
4351 | case PCC_ParenthesizedExpression: | |||
4352 | case PCC_Expression: | |||
4353 | case PCC_ForInit: | |||
4354 | case PCC_Condition: | |||
4355 | if (WantTypesInContext(CompletionContext, getLangOpts())) | |||
4356 | Results.setFilter(&ResultBuilder::IsOrdinaryName); | |||
4357 | else | |||
4358 | Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName); | |||
4359 | ||||
4360 | if (getLangOpts().CPlusPlus) | |||
4361 | MaybeAddOverrideCalls(*this, /*InContext=*/nullptr, Results); | |||
4362 | break; | |||
4363 | ||||
4364 | case PCC_RecoveryInFunction: | |||
4365 | // Unfiltered | |||
4366 | break; | |||
4367 | } | |||
4368 | ||||
4369 | // If we are in a C++ non-static member function, check the qualifiers on | |||
4370 | // the member function to filter/prioritize the results list. | |||
4371 | auto ThisType = getCurrentThisType(); | |||
4372 | if (!ThisType.isNull()) | |||
4373 | Results.setObjectTypeQualifiers(ThisType->getPointeeType().getQualifiers(), | |||
4374 | VK_LValue); | |||
4375 | ||||
4376 | CodeCompletionDeclConsumer Consumer(Results, CurContext); | |||
4377 | LookupVisibleDecls(S, LookupOrdinaryName, Consumer, | |||
4378 | CodeCompleter->includeGlobals(), | |||
4379 | CodeCompleter->loadExternal()); | |||
4380 | ||||
4381 | AddOrdinaryNameResults(CompletionContext, S, *this, Results); | |||
4382 | Results.ExitScope(); | |||
4383 | ||||
4384 | switch (CompletionContext) { | |||
4385 | case PCC_ParenthesizedExpression: | |||
4386 | case PCC_Expression: | |||
4387 | case PCC_Statement: | |||
4388 | case PCC_RecoveryInFunction: | |||
4389 | if (S->getFnParent()) | |||
4390 | AddPrettyFunctionResults(getLangOpts(), Results); | |||
4391 | break; | |||
4392 | ||||
4393 | case PCC_Namespace: | |||
4394 | case PCC_Class: | |||
4395 | case PCC_ObjCInterface: | |||
4396 | case PCC_ObjCImplementation: | |||
4397 | case PCC_ObjCInstanceVariableList: | |||
4398 | case PCC_Template: | |||
4399 | case PCC_MemberTemplate: | |||
4400 | case PCC_ForInit: | |||
4401 | case PCC_Condition: | |||
4402 | case PCC_Type: | |||
4403 | case PCC_LocalDeclarationSpecifiers: | |||
4404 | break; | |||
4405 | } | |||
4406 | ||||
4407 | if (CodeCompleter->includeMacros()) | |||
4408 | AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false); | |||
4409 | ||||
4410 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
4411 | Results.data(), Results.size()); | |||
4412 | } | |||
4413 | ||||
4414 | static void AddClassMessageCompletions(Sema &SemaRef, Scope *S, | |||
4415 | ParsedType Receiver, | |||
4416 | ArrayRef<IdentifierInfo *> SelIdents, | |||
4417 | bool AtArgumentExpression, bool IsSuper, | |||
4418 | ResultBuilder &Results); | |||
4419 | ||||
4420 | void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, | |||
4421 | bool AllowNonIdentifiers, | |||
4422 | bool AllowNestedNameSpecifiers) { | |||
4423 | typedef CodeCompletionResult Result; | |||
4424 | ResultBuilder Results( | |||
4425 | *this, CodeCompleter->getAllocator(), | |||
4426 | CodeCompleter->getCodeCompletionTUInfo(), | |||
4427 | AllowNestedNameSpecifiers | |||
4428 | // FIXME: Try to separate codepath leading here to deduce whether we | |||
4429 | // need an existing symbol or a new one. | |||
4430 | ? CodeCompletionContext::CCC_SymbolOrNewName | |||
4431 | : CodeCompletionContext::CCC_NewName); | |||
4432 | Results.EnterNewScope(); | |||
4433 | ||||
4434 | // Type qualifiers can come after names. | |||
4435 | Results.AddResult(Result("const")); | |||
4436 | Results.AddResult(Result("volatile")); | |||
4437 | if (getLangOpts().C99) | |||
4438 | Results.AddResult(Result("restrict")); | |||
4439 | ||||
4440 | if (getLangOpts().CPlusPlus) { | |||
4441 | if (getLangOpts().CPlusPlus11 && | |||
4442 | (DS.getTypeSpecType() == DeclSpec::TST_class || | |||
4443 | DS.getTypeSpecType() == DeclSpec::TST_struct)) | |||
4444 | Results.AddResult("final"); | |||
4445 | ||||
4446 | if (AllowNonIdentifiers) { | |||
4447 | Results.AddResult(Result("operator")); | |||
4448 | } | |||
4449 | ||||
4450 | // Add nested-name-specifiers. | |||
4451 | if (AllowNestedNameSpecifiers) { | |||
4452 | Results.allowNestedNameSpecifiers(); | |||
4453 | Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy); | |||
4454 | CodeCompletionDeclConsumer Consumer(Results, CurContext); | |||
4455 | LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer, | |||
4456 | CodeCompleter->includeGlobals(), | |||
4457 | CodeCompleter->loadExternal()); | |||
4458 | Results.setFilter(nullptr); | |||
4459 | } | |||
4460 | } | |||
4461 | Results.ExitScope(); | |||
4462 | ||||
4463 | // If we're in a context where we might have an expression (rather than a | |||
4464 | // declaration), and what we've seen so far is an Objective-C type that could | |||
4465 | // be a receiver of a class message, this may be a class message send with | |||
4466 | // the initial opening bracket '[' missing. Add appropriate completions. | |||
4467 | if (AllowNonIdentifiers && !AllowNestedNameSpecifiers && | |||
4468 | DS.getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier && | |||
4469 | DS.getTypeSpecType() == DeclSpec::TST_typename && | |||
4470 | DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified && | |||
4471 | DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && | |||
4472 | !DS.isTypeAltiVecVector() && S && | |||
4473 | (S->getFlags() & Scope::DeclScope) != 0 && | |||
4474 | (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope | | |||
4475 | Scope::FunctionPrototypeScope | Scope::AtCatchScope)) == | |||
4476 | 0) { | |||
4477 | ParsedType T = DS.getRepAsType(); | |||
4478 | if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType()) | |||
4479 | AddClassMessageCompletions(*this, S, T, std::nullopt, false, false, | |||
4480 | Results); | |||
4481 | } | |||
4482 | ||||
4483 | // Note that we intentionally suppress macro results here, since we do not | |||
4484 | // encourage using macros to produce the names of entities. | |||
4485 | ||||
4486 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
4487 | Results.data(), Results.size()); | |||
4488 | } | |||
4489 | ||||
4490 | static const char *underscoreAttrScope(llvm::StringRef Scope) { | |||
4491 | if (Scope == "clang") | |||
4492 | return "_Clang"; | |||
4493 | if (Scope == "gnu") | |||
4494 | return "__gnu__"; | |||
4495 | return nullptr; | |||
4496 | } | |||
4497 | ||||
4498 | static const char *noUnderscoreAttrScope(llvm::StringRef Scope) { | |||
4499 | if (Scope == "_Clang") | |||
4500 | return "clang"; | |||
4501 | if (Scope == "__gnu__") | |||
4502 | return "gnu"; | |||
4503 | return nullptr; | |||
4504 | } | |||
4505 | ||||
4506 | void Sema::CodeCompleteAttribute(AttributeCommonInfo::Syntax Syntax, | |||
4507 | AttributeCompletion Completion, | |||
4508 | const IdentifierInfo *InScope) { | |||
4509 | if (Completion == AttributeCompletion::None) | |||
4510 | return; | |||
4511 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
4512 | CodeCompleter->getCodeCompletionTUInfo(), | |||
4513 | CodeCompletionContext::CCC_Attribute); | |||
4514 | ||||
4515 | // We're going to iterate over the normalized spellings of the attribute. | |||
4516 | // These don't include "underscore guarding": the normalized spelling is | |||
4517 | // clang::foo but you can also write _Clang::__foo__. | |||
4518 | // | |||
4519 | // (Clang supports a mix like clang::__foo__ but we won't suggest it: either | |||
4520 | // you care about clashing with macros or you don't). | |||
4521 | // | |||
4522 | // So if we're already in a scope, we determine its canonical spellings | |||
4523 | // (for comparison with normalized attr spelling) and remember whether it was | |||
4524 | // underscore-guarded (so we know how to spell contained attributes). | |||
4525 | llvm::StringRef InScopeName; | |||
4526 | bool InScopeUnderscore = false; | |||
4527 | if (InScope) { | |||
4528 | InScopeName = InScope->getName(); | |||
4529 | if (const char *NoUnderscore = noUnderscoreAttrScope(InScopeName)) { | |||
4530 | InScopeName = NoUnderscore; | |||
4531 | InScopeUnderscore = true; | |||
4532 | } | |||
4533 | } | |||
4534 | bool SyntaxSupportsGuards = Syntax == AttributeCommonInfo::AS_GNU || | |||
4535 | Syntax == AttributeCommonInfo::AS_CXX11 || | |||
4536 | Syntax == AttributeCommonInfo::AS_C2x; | |||
4537 | ||||
4538 | llvm::DenseSet<llvm::StringRef> FoundScopes; | |||
4539 | auto AddCompletions = [&](const ParsedAttrInfo &A) { | |||
4540 | if (A.IsTargetSpecific && !A.existsInTarget(Context.getTargetInfo())) | |||
4541 | return; | |||
4542 | if (!A.acceptsLangOpts(getLangOpts())) | |||
4543 | return; | |||
4544 | for (const auto &S : A.Spellings) { | |||
4545 | if (S.Syntax != Syntax) | |||
4546 | continue; | |||
4547 | llvm::StringRef Name = S.NormalizedFullName; | |||
4548 | llvm::StringRef Scope; | |||
4549 | if ((Syntax == AttributeCommonInfo::AS_CXX11 || | |||
4550 | Syntax == AttributeCommonInfo::AS_C2x)) { | |||
4551 | std::tie(Scope, Name) = Name.split("::"); | |||
4552 | if (Name.empty()) // oops, unscoped | |||
4553 | std::swap(Name, Scope); | |||
4554 | } | |||
4555 | ||||
4556 | // Do we just want a list of scopes rather than attributes? | |||
4557 | if (Completion == AttributeCompletion::Scope) { | |||
4558 | // Make sure to emit each scope only once. | |||
4559 | if (!Scope.empty() && FoundScopes.insert(Scope).second) { | |||
4560 | Results.AddResult( | |||
4561 | CodeCompletionResult(Results.getAllocator().CopyString(Scope))); | |||
4562 | // Include alternate form (__gnu__ instead of gnu). | |||
4563 | if (const char *Scope2 = underscoreAttrScope(Scope)) | |||
4564 | Results.AddResult(CodeCompletionResult(Scope2)); | |||
4565 | } | |||
4566 | continue; | |||
4567 | } | |||
4568 | ||||
4569 | // If a scope was specified, it must match but we don't need to print it. | |||
4570 | if (!InScopeName.empty()) { | |||
4571 | if (Scope != InScopeName) | |||
4572 | continue; | |||
4573 | Scope = ""; | |||
4574 | } | |||
4575 | ||||
4576 | auto Add = [&](llvm::StringRef Scope, llvm::StringRef Name, | |||
4577 | bool Underscores) { | |||
4578 | CodeCompletionBuilder Builder(Results.getAllocator(), | |||
4579 | Results.getCodeCompletionTUInfo()); | |||
4580 | llvm::SmallString<32> Text; | |||
4581 | if (!Scope.empty()) { | |||
4582 | Text.append(Scope); | |||
4583 | Text.append("::"); | |||
4584 | } | |||
4585 | if (Underscores) | |||
4586 | Text.append("__"); | |||
4587 | Text.append(Name); | |||
4588 | if (Underscores) | |||
4589 | Text.append("__"); | |||
4590 | Builder.AddTypedTextChunk(Results.getAllocator().CopyString(Text)); | |||
4591 | ||||
4592 | if (!A.ArgNames.empty()) { | |||
4593 | Builder.AddChunk(CodeCompletionString::CK_LeftParen, "("); | |||
4594 | bool First = true; | |||
4595 | for (const char *Arg : A.ArgNames) { | |||
4596 | if (!First) | |||
4597 | Builder.AddChunk(CodeCompletionString::CK_Comma, ", "); | |||
4598 | First = false; | |||
4599 | Builder.AddPlaceholderChunk(Arg); | |||
4600 | } | |||
4601 | Builder.AddChunk(CodeCompletionString::CK_RightParen, ")"); | |||
4602 | } | |||
4603 | ||||
4604 | Results.AddResult(Builder.TakeString()); | |||
4605 | }; | |||
4606 | ||||
4607 | // Generate the non-underscore-guarded result. | |||
4608 | // Note this is (a suffix of) the NormalizedFullName, no need to copy. | |||
4609 | // If an underscore-guarded scope was specified, only the | |||
4610 | // underscore-guarded attribute name is relevant. | |||
4611 | if (!InScopeUnderscore) | |||
4612 | Add(Scope, Name, /*Underscores=*/false); | |||
4613 | ||||
4614 | // Generate the underscore-guarded version, for syntaxes that support it. | |||
4615 | // We skip this if the scope was already spelled and not guarded, or | |||
4616 | // we must spell it and can't guard it. | |||
4617 | if (!(InScope && !InScopeUnderscore) && SyntaxSupportsGuards) { | |||
4618 | llvm::SmallString<32> Guarded; | |||
4619 | if (Scope.empty()) { | |||
4620 | Add(Scope, Name, /*Underscores=*/true); | |||
4621 | } else { | |||
4622 | const char *GuardedScope = underscoreAttrScope(Scope); | |||
4623 | if (!GuardedScope) | |||
4624 | continue; | |||
4625 | Add(GuardedScope, Name, /*Underscores=*/true); | |||
4626 | } | |||
4627 | } | |||
4628 | ||||
4629 | // It may be nice to include the Kind so we can look up the docs later. | |||
4630 | } | |||
4631 | }; | |||
4632 | ||||
4633 | for (const auto *A : ParsedAttrInfo::getAllBuiltin()) | |||
4634 | AddCompletions(*A); | |||
4635 | for (const auto &Entry : ParsedAttrInfoRegistry::entries()) | |||
4636 | AddCompletions(*Entry.instantiate()); | |||
4637 | ||||
4638 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
4639 | Results.data(), Results.size()); | |||
4640 | } | |||
4641 | ||||
4642 | struct Sema::CodeCompleteExpressionData { | |||
4643 | CodeCompleteExpressionData(QualType PreferredType = QualType(), | |||
4644 | bool IsParenthesized = false) | |||
4645 | : PreferredType(PreferredType), IntegralConstantExpression(false), | |||
4646 | ObjCCollection(false), IsParenthesized(IsParenthesized) {} | |||
4647 | ||||
4648 | QualType PreferredType; | |||
4649 | bool IntegralConstantExpression; | |||
4650 | bool ObjCCollection; | |||
4651 | bool IsParenthesized; | |||
4652 | SmallVector<Decl *, 4> IgnoreDecls; | |||
4653 | }; | |||
4654 | ||||
4655 | namespace { | |||
4656 | /// Information that allows to avoid completing redundant enumerators. | |||
4657 | struct CoveredEnumerators { | |||
4658 | llvm::SmallPtrSet<EnumConstantDecl *, 8> Seen; | |||
4659 | NestedNameSpecifier *SuggestedQualifier = nullptr; | |||
4660 | }; | |||
4661 | } // namespace | |||
4662 | ||||
4663 | static void AddEnumerators(ResultBuilder &Results, ASTContext &Context, | |||
4664 | EnumDecl *Enum, DeclContext *CurContext, | |||
4665 | const CoveredEnumerators &Enumerators) { | |||
4666 | NestedNameSpecifier *Qualifier = Enumerators.SuggestedQualifier; | |||
4667 | if (Context.getLangOpts().CPlusPlus && !Qualifier && Enumerators.Seen.empty()) { | |||
4668 | // If there are no prior enumerators in C++, check whether we have to | |||
4669 | // qualify the names of the enumerators that we suggest, because they | |||
4670 | // may not be visible in this scope. | |||
4671 | Qualifier = getRequiredQualification(Context, CurContext, Enum); | |||
4672 | } | |||
4673 | ||||
4674 | Results.EnterNewScope(); | |||
4675 | for (auto *E : Enum->enumerators()) { | |||
4676 | if (Enumerators.Seen.count(E)) | |||
4677 | continue; | |||
4678 | ||||
4679 | CodeCompletionResult R(E, CCP_EnumInCase, Qualifier); | |||
4680 | Results.AddResult(R, CurContext, nullptr, false); | |||
4681 | } | |||
4682 | Results.ExitScope(); | |||
4683 | } | |||
4684 | ||||
4685 | /// Try to find a corresponding FunctionProtoType for function-like types (e.g. | |||
4686 | /// function pointers, std::function, etc). | |||
4687 | static const FunctionProtoType *TryDeconstructFunctionLike(QualType T) { | |||
4688 | assert(!T.isNull())(static_cast <bool> (!T.isNull()) ? void (0) : __assert_fail ("!T.isNull()", "clang/lib/Sema/SemaCodeComplete.cpp", 4688, __extension__ __PRETTY_FUNCTION__)); | |||
4689 | // Try to extract first template argument from std::function<> and similar. | |||
4690 | // Note we only handle the sugared types, they closely match what users wrote. | |||
4691 | // We explicitly choose to not handle ClassTemplateSpecializationDecl. | |||
4692 | if (auto *Specialization = T->getAs<TemplateSpecializationType>()) { | |||
4693 | if (Specialization->template_arguments().size() != 1) | |||
4694 | return nullptr; | |||
4695 | const TemplateArgument &Argument = Specialization->template_arguments()[0]; | |||
4696 | if (Argument.getKind() != TemplateArgument::Type) | |||
4697 | return nullptr; | |||
4698 | return Argument.getAsType()->getAs<FunctionProtoType>(); | |||
4699 | } | |||
4700 | // Handle other cases. | |||
4701 | if (T->isPointerType()) | |||
4702 | T = T->getPointeeType(); | |||
4703 | return T->getAs<FunctionProtoType>(); | |||
4704 | } | |||
4705 | ||||
4706 | /// Adds a pattern completion for a lambda expression with the specified | |||
4707 | /// parameter types and placeholders for parameter names. | |||
4708 | static void AddLambdaCompletion(ResultBuilder &Results, | |||
4709 | llvm::ArrayRef<QualType> Parameters, | |||
4710 | const LangOptions &LangOpts) { | |||
4711 | if (!Results.includeCodePatterns()) | |||
4712 | return; | |||
4713 | CodeCompletionBuilder Completion(Results.getAllocator(), | |||
4714 | Results.getCodeCompletionTUInfo()); | |||
4715 | // [](<parameters>) {} | |||
4716 | Completion.AddChunk(CodeCompletionString::CK_LeftBracket); | |||
4717 | Completion.AddPlaceholderChunk("="); | |||
4718 | Completion.AddChunk(CodeCompletionString::CK_RightBracket); | |||
4719 | if (!Parameters.empty()) { | |||
4720 | Completion.AddChunk(CodeCompletionString::CK_LeftParen); | |||
4721 | bool First = true; | |||
4722 | for (auto Parameter : Parameters) { | |||
4723 | if (!First) | |||
4724 | Completion.AddChunk(CodeCompletionString::ChunkKind::CK_Comma); | |||
4725 | else | |||
4726 | First = false; | |||
4727 | ||||
4728 | constexpr llvm::StringLiteral NamePlaceholder = "!#!NAME_GOES_HERE!#!"; | |||
4729 | std::string Type = std::string(NamePlaceholder); | |||
4730 | Parameter.getAsStringInternal(Type, PrintingPolicy(LangOpts)); | |||
4731 | llvm::StringRef Prefix, Suffix; | |||
4732 | std::tie(Prefix, Suffix) = llvm::StringRef(Type).split(NamePlaceholder); | |||
4733 | Prefix = Prefix.rtrim(); | |||
4734 | Suffix = Suffix.ltrim(); | |||
4735 | ||||
4736 | Completion.AddTextChunk(Completion.getAllocator().CopyString(Prefix)); | |||
4737 | Completion.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
4738 | Completion.AddPlaceholderChunk("parameter"); | |||
4739 | Completion.AddTextChunk(Completion.getAllocator().CopyString(Suffix)); | |||
4740 | }; | |||
4741 | Completion.AddChunk(CodeCompletionString::CK_RightParen); | |||
4742 | } | |||
4743 | Completion.AddChunk(clang::CodeCompletionString::CK_HorizontalSpace); | |||
4744 | Completion.AddChunk(CodeCompletionString::CK_LeftBrace); | |||
4745 | Completion.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
4746 | Completion.AddPlaceholderChunk("body"); | |||
4747 | Completion.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
4748 | Completion.AddChunk(CodeCompletionString::CK_RightBrace); | |||
4749 | ||||
4750 | Results.AddResult(Completion.TakeString()); | |||
4751 | } | |||
4752 | ||||
4753 | /// Perform code-completion in an expression context when we know what | |||
4754 | /// type we're looking for. | |||
4755 | void Sema::CodeCompleteExpression(Scope *S, | |||
4756 | const CodeCompleteExpressionData &Data) { | |||
4757 | ResultBuilder Results( | |||
4758 | *this, CodeCompleter->getAllocator(), | |||
4759 | CodeCompleter->getCodeCompletionTUInfo(), | |||
4760 | CodeCompletionContext( | |||
4761 | Data.IsParenthesized | |||
4762 | ? CodeCompletionContext::CCC_ParenthesizedExpression | |||
4763 | : CodeCompletionContext::CCC_Expression, | |||
4764 | Data.PreferredType)); | |||
4765 | auto PCC = | |||
4766 | Data.IsParenthesized ? PCC_ParenthesizedExpression : PCC_Expression; | |||
4767 | if (Data.ObjCCollection) | |||
4768 | Results.setFilter(&ResultBuilder::IsObjCCollection); | |||
4769 | else if (Data.IntegralConstantExpression) | |||
4770 | Results.setFilter(&ResultBuilder::IsIntegralConstantValue); | |||
4771 | else if (WantTypesInContext(PCC, getLangOpts())) | |||
4772 | Results.setFilter(&ResultBuilder::IsOrdinaryName); | |||
4773 | else | |||
4774 | Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName); | |||
4775 | ||||
4776 | if (!Data.PreferredType.isNull()) | |||
4777 | Results.setPreferredType(Data.PreferredType.getNonReferenceType()); | |||
4778 | ||||
4779 | // Ignore any declarations that we were told that we don't care about. | |||
4780 | for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I) | |||
4781 | Results.Ignore(Data.IgnoreDecls[I]); | |||
4782 | ||||
4783 | CodeCompletionDeclConsumer Consumer(Results, CurContext); | |||
4784 | LookupVisibleDecls(S, LookupOrdinaryName, Consumer, | |||
4785 | CodeCompleter->includeGlobals(), | |||
4786 | CodeCompleter->loadExternal()); | |||
4787 | ||||
4788 | Results.EnterNewScope(); | |||
4789 | AddOrdinaryNameResults(PCC, S, *this, Results); | |||
4790 | Results.ExitScope(); | |||
4791 | ||||
4792 | bool PreferredTypeIsPointer = false; | |||
4793 | if (!Data.PreferredType.isNull()) { | |||
4794 | PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType() || | |||
4795 | Data.PreferredType->isMemberPointerType() || | |||
4796 | Data.PreferredType->isBlockPointerType(); | |||
4797 | if (Data.PreferredType->isEnumeralType()) { | |||
4798 | EnumDecl *Enum = Data.PreferredType->castAs<EnumType>()->getDecl(); | |||
4799 | if (auto *Def = Enum->getDefinition()) | |||
4800 | Enum = Def; | |||
4801 | // FIXME: collect covered enumerators in cases like: | |||
4802 | // if (x == my_enum::one) { ... } else if (x == ^) {} | |||
4803 | AddEnumerators(Results, Context, Enum, CurContext, CoveredEnumerators()); | |||
4804 | } | |||
4805 | } | |||
4806 | ||||
4807 | if (S->getFnParent() && !Data.ObjCCollection && | |||
4808 | !Data.IntegralConstantExpression) | |||
4809 | AddPrettyFunctionResults(getLangOpts(), Results); | |||
4810 | ||||
4811 | if (CodeCompleter->includeMacros()) | |||
4812 | AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false, | |||
4813 | PreferredTypeIsPointer); | |||
4814 | ||||
4815 | // Complete a lambda expression when preferred type is a function. | |||
4816 | if (!Data.PreferredType.isNull() && getLangOpts().CPlusPlus11) { | |||
4817 | if (const FunctionProtoType *F = | |||
4818 | TryDeconstructFunctionLike(Data.PreferredType)) | |||
4819 | AddLambdaCompletion(Results, F->getParamTypes(), getLangOpts()); | |||
4820 | } | |||
4821 | ||||
4822 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
4823 | Results.data(), Results.size()); | |||
4824 | } | |||
4825 | ||||
4826 | void Sema::CodeCompleteExpression(Scope *S, QualType PreferredType, | |||
4827 | bool IsParenthesized) { | |||
4828 | return CodeCompleteExpression( | |||
4829 | S, CodeCompleteExpressionData(PreferredType, IsParenthesized)); | |||
4830 | } | |||
4831 | ||||
4832 | void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E, | |||
4833 | QualType PreferredType) { | |||
4834 | if (E.isInvalid()) | |||
4835 | CodeCompleteExpression(S, PreferredType); | |||
4836 | else if (getLangOpts().ObjC) | |||
4837 | CodeCompleteObjCInstanceMessage(S, E.get(), std::nullopt, false); | |||
4838 | } | |||
4839 | ||||
4840 | /// The set of properties that have already been added, referenced by | |||
4841 | /// property name. | |||
4842 | typedef llvm::SmallPtrSet<IdentifierInfo *, 16> AddedPropertiesSet; | |||
4843 | ||||
4844 | /// Retrieve the container definition, if any? | |||
4845 | static ObjCContainerDecl *getContainerDef(ObjCContainerDecl *Container) { | |||
4846 | if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) { | |||
4847 | if (Interface->hasDefinition()) | |||
4848 | return Interface->getDefinition(); | |||
4849 | ||||
4850 | return Interface; | |||
4851 | } | |||
4852 | ||||
4853 | if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { | |||
4854 | if (Protocol->hasDefinition()) | |||
4855 | return Protocol->getDefinition(); | |||
4856 | ||||
4857 | return Protocol; | |||
4858 | } | |||
4859 | return Container; | |||
4860 | } | |||
4861 | ||||
4862 | /// Adds a block invocation code completion result for the given block | |||
4863 | /// declaration \p BD. | |||
4864 | static void AddObjCBlockCall(ASTContext &Context, const PrintingPolicy &Policy, | |||
4865 | CodeCompletionBuilder &Builder, | |||
4866 | const NamedDecl *BD, | |||
4867 | const FunctionTypeLoc &BlockLoc, | |||
4868 | const FunctionProtoTypeLoc &BlockProtoLoc) { | |||
4869 | Builder.AddResultTypeChunk( | |||
4870 | GetCompletionTypeString(BlockLoc.getReturnLoc().getType(), Context, | |||
4871 | Policy, Builder.getAllocator())); | |||
4872 | ||||
4873 | AddTypedNameChunk(Context, Policy, BD, Builder); | |||
4874 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
4875 | ||||
4876 | if (BlockProtoLoc && BlockProtoLoc.getTypePtr()->isVariadic()) { | |||
4877 | Builder.AddPlaceholderChunk("..."); | |||
4878 | } else { | |||
4879 | for (unsigned I = 0, N = BlockLoc.getNumParams(); I != N; ++I) { | |||
4880 | if (I) | |||
4881 | Builder.AddChunk(CodeCompletionString::CK_Comma); | |||
4882 | ||||
4883 | // Format the placeholder string. | |||
4884 | std::string PlaceholderStr = | |||
4885 | FormatFunctionParameter(Policy, BlockLoc.getParam(I)); | |||
4886 | ||||
4887 | if (I == N - 1 && BlockProtoLoc && | |||
4888 | BlockProtoLoc.getTypePtr()->isVariadic()) | |||
4889 | PlaceholderStr += ", ..."; | |||
4890 | ||||
4891 | // Add the placeholder string. | |||
4892 | Builder.AddPlaceholderChunk( | |||
4893 | Builder.getAllocator().CopyString(PlaceholderStr)); | |||
4894 | } | |||
4895 | } | |||
4896 | ||||
4897 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
4898 | } | |||
4899 | ||||
4900 | static void | |||
4901 | AddObjCProperties(const CodeCompletionContext &CCContext, | |||
4902 | ObjCContainerDecl *Container, bool AllowCategories, | |||
4903 | bool AllowNullaryMethods, DeclContext *CurContext, | |||
4904 | AddedPropertiesSet &AddedProperties, ResultBuilder &Results, | |||
4905 | bool IsBaseExprStatement = false, | |||
4906 | bool IsClassProperty = false, bool InOriginalClass = true) { | |||
4907 | typedef CodeCompletionResult Result; | |||
4908 | ||||
4909 | // Retrieve the definition. | |||
4910 | Container = getContainerDef(Container); | |||
4911 | ||||
4912 | // Add properties in this container. | |||
4913 | const auto AddProperty = [&](const ObjCPropertyDecl *P) { | |||
4914 | if (!AddedProperties.insert(P->getIdentifier()).second) | |||
4915 | return; | |||
4916 | ||||
4917 | // FIXME: Provide block invocation completion for non-statement | |||
4918 | // expressions. | |||
4919 | if (!P->getType().getTypePtr()->isBlockPointerType() || | |||
4920 | !IsBaseExprStatement) { | |||
4921 | Result R = Result(P, Results.getBasePriority(P), nullptr); | |||
4922 | if (!InOriginalClass) | |||
4923 | setInBaseClass(R); | |||
4924 | Results.MaybeAddResult(R, CurContext); | |||
4925 | return; | |||
4926 | } | |||
4927 | ||||
4928 | // Block setter and invocation completion is provided only when we are able | |||
4929 | // to find the FunctionProtoTypeLoc with parameter names for the block. | |||
4930 | FunctionTypeLoc BlockLoc; | |||
4931 | FunctionProtoTypeLoc BlockProtoLoc; | |||
4932 | findTypeLocationForBlockDecl(P->getTypeSourceInfo(), BlockLoc, | |||
4933 | BlockProtoLoc); | |||
4934 | if (!BlockLoc) { | |||
4935 | Result R = Result(P, Results.getBasePriority(P), nullptr); | |||
4936 | if (!InOriginalClass) | |||
4937 | setInBaseClass(R); | |||
4938 | Results.MaybeAddResult(R, CurContext); | |||
4939 | return; | |||
4940 | } | |||
4941 | ||||
4942 | // The default completion result for block properties should be the block | |||
4943 | // invocation completion when the base expression is a statement. | |||
4944 | CodeCompletionBuilder Builder(Results.getAllocator(), | |||
4945 | Results.getCodeCompletionTUInfo()); | |||
4946 | AddObjCBlockCall(Container->getASTContext(), | |||
4947 | getCompletionPrintingPolicy(Results.getSema()), Builder, P, | |||
4948 | BlockLoc, BlockProtoLoc); | |||
4949 | Result R = Result(Builder.TakeString(), P, Results.getBasePriority(P)); | |||
4950 | if (!InOriginalClass) | |||
4951 | setInBaseClass(R); | |||
4952 | Results.MaybeAddResult(R, CurContext); | |||
4953 | ||||
4954 | // Provide additional block setter completion iff the base expression is a | |||
4955 | // statement and the block property is mutable. | |||
4956 | if (!P->isReadOnly()) { | |||
4957 | CodeCompletionBuilder Builder(Results.getAllocator(), | |||
4958 | Results.getCodeCompletionTUInfo()); | |||
4959 | AddResultTypeChunk(Container->getASTContext(), | |||
4960 | getCompletionPrintingPolicy(Results.getSema()), P, | |||
4961 | CCContext.getBaseType(), Builder); | |||
4962 | Builder.AddTypedTextChunk( | |||
4963 | Results.getAllocator().CopyString(P->getName())); | |||
4964 | Builder.AddChunk(CodeCompletionString::CK_Equal); | |||
4965 | ||||
4966 | std::string PlaceholderStr = formatBlockPlaceholder( | |||
4967 | getCompletionPrintingPolicy(Results.getSema()), P, BlockLoc, | |||
4968 | BlockProtoLoc, /*SuppressBlockName=*/true); | |||
4969 | // Add the placeholder string. | |||
4970 | Builder.AddPlaceholderChunk( | |||
4971 | Builder.getAllocator().CopyString(PlaceholderStr)); | |||
4972 | ||||
4973 | // When completing blocks properties that return void the default | |||
4974 | // property completion result should show up before the setter, | |||
4975 | // otherwise the setter completion should show up before the default | |||
4976 | // property completion, as we normally want to use the result of the | |||
4977 | // call. | |||
4978 | Result R = | |||
4979 | Result(Builder.TakeString(), P, | |||
4980 | Results.getBasePriority(P) + | |||
4981 | (BlockLoc.getTypePtr()->getReturnType()->isVoidType() | |||
4982 | ? CCD_BlockPropertySetter | |||
4983 | : -CCD_BlockPropertySetter)); | |||
4984 | if (!InOriginalClass) | |||
4985 | setInBaseClass(R); | |||
4986 | Results.MaybeAddResult(R, CurContext); | |||
4987 | } | |||
4988 | }; | |||
4989 | ||||
4990 | if (IsClassProperty) { | |||
4991 | for (const auto *P : Container->class_properties()) | |||
4992 | AddProperty(P); | |||
4993 | } else { | |||
4994 | for (const auto *P : Container->instance_properties()) | |||
4995 | AddProperty(P); | |||
4996 | } | |||
4997 | ||||
4998 | // Add nullary methods or implicit class properties | |||
4999 | if (AllowNullaryMethods) { | |||
5000 | ASTContext &Context = Container->getASTContext(); | |||
5001 | PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema()); | |||
5002 | // Adds a method result | |||
5003 | const auto AddMethod = [&](const ObjCMethodDecl *M) { | |||
5004 | IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0); | |||
5005 | if (!Name) | |||
5006 | return; | |||
5007 | if (!AddedProperties.insert(Name).second) | |||
5008 | return; | |||
5009 | CodeCompletionBuilder Builder(Results.getAllocator(), | |||
5010 | Results.getCodeCompletionTUInfo()); | |||
5011 | AddResultTypeChunk(Context, Policy, M, CCContext.getBaseType(), Builder); | |||
5012 | Builder.AddTypedTextChunk( | |||
5013 | Results.getAllocator().CopyString(Name->getName())); | |||
5014 | Result R = Result(Builder.TakeString(), M, | |||
5015 | CCP_MemberDeclaration + CCD_MethodAsProperty); | |||
5016 | if (!InOriginalClass) | |||
5017 | setInBaseClass(R); | |||
5018 | Results.MaybeAddResult(R, CurContext); | |||
5019 | }; | |||
5020 | ||||
5021 | if (IsClassProperty) { | |||
5022 | for (const auto *M : Container->methods()) { | |||
5023 | // Gather the class method that can be used as implicit property | |||
5024 | // getters. Methods with arguments or methods that return void aren't | |||
5025 | // added to the results as they can't be used as a getter. | |||
5026 | if (!M->getSelector().isUnarySelector() || | |||
5027 | M->getReturnType()->isVoidType() || M->isInstanceMethod()) | |||
5028 | continue; | |||
5029 | AddMethod(M); | |||
5030 | } | |||
5031 | } else { | |||
5032 | for (auto *M : Container->methods()) { | |||
5033 | if (M->getSelector().isUnarySelector()) | |||
5034 | AddMethod(M); | |||
5035 | } | |||
5036 | } | |||
5037 | } | |||
5038 | ||||
5039 | // Add properties in referenced protocols. | |||
5040 | if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { | |||
5041 | for (auto *P : Protocol->protocols()) | |||
5042 | AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods, | |||
5043 | CurContext, AddedProperties, Results, | |||
5044 | IsBaseExprStatement, IsClassProperty, | |||
5045 | /*InOriginalClass*/ false); | |||
5046 | } else if (ObjCInterfaceDecl *IFace = | |||
5047 | dyn_cast<ObjCInterfaceDecl>(Container)) { | |||
5048 | if (AllowCategories) { | |||
5049 | // Look through categories. | |||
5050 | for (auto *Cat : IFace->known_categories()) | |||
5051 | AddObjCProperties(CCContext, Cat, AllowCategories, AllowNullaryMethods, | |||
5052 | CurContext, AddedProperties, Results, | |||
5053 | IsBaseExprStatement, IsClassProperty, | |||
5054 | InOriginalClass); | |||
5055 | } | |||
5056 | ||||
5057 | // Look through protocols. | |||
5058 | for (auto *I : IFace->all_referenced_protocols()) | |||
5059 | AddObjCProperties(CCContext, I, AllowCategories, AllowNullaryMethods, | |||
5060 | CurContext, AddedProperties, Results, | |||
5061 | IsBaseExprStatement, IsClassProperty, | |||
5062 | /*InOriginalClass*/ false); | |||
5063 | ||||
5064 | // Look in the superclass. | |||
5065 | if (IFace->getSuperClass()) | |||
5066 | AddObjCProperties(CCContext, IFace->getSuperClass(), AllowCategories, | |||
5067 | AllowNullaryMethods, CurContext, AddedProperties, | |||
5068 | Results, IsBaseExprStatement, IsClassProperty, | |||
5069 | /*InOriginalClass*/ false); | |||
5070 | } else if (const auto *Category = | |||
5071 | dyn_cast<ObjCCategoryDecl>(Container)) { | |||
5072 | // Look through protocols. | |||
5073 | for (auto *P : Category->protocols()) | |||
5074 | AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods, | |||
5075 | CurContext, AddedProperties, Results, | |||
5076 | IsBaseExprStatement, IsClassProperty, | |||
5077 | /*InOriginalClass*/ false); | |||
5078 | } | |||
5079 | } | |||
5080 | ||||
5081 | static void | |||
5082 | AddRecordMembersCompletionResults(Sema &SemaRef, ResultBuilder &Results, | |||
5083 | Scope *S, QualType BaseType, | |||
5084 | ExprValueKind BaseKind, RecordDecl *RD, | |||
5085 | std::optional<FixItHint> AccessOpFixIt) { | |||
5086 | // Indicate that we are performing a member access, and the cv-qualifiers | |||
5087 | // for the base object type. | |||
5088 | Results.setObjectTypeQualifiers(BaseType.getQualifiers(), BaseKind); | |||
5089 | ||||
5090 | // Access to a C/C++ class, struct, or union. | |||
5091 | Results.allowNestedNameSpecifiers(); | |||
5092 | std::vector<FixItHint> FixIts; | |||
5093 | if (AccessOpFixIt) | |||
5094 | FixIts.emplace_back(*AccessOpFixIt); | |||
5095 | CodeCompletionDeclConsumer Consumer(Results, RD, BaseType, std::move(FixIts)); | |||
5096 | SemaRef.LookupVisibleDecls(RD, Sema::LookupMemberName, Consumer, | |||
5097 | SemaRef.CodeCompleter->includeGlobals(), | |||
5098 | /*IncludeDependentBases=*/true, | |||
5099 | SemaRef.CodeCompleter->loadExternal()); | |||
5100 | ||||
5101 | if (SemaRef.getLangOpts().CPlusPlus) { | |||
5102 | if (!Results.empty()) { | |||
5103 | // The "template" keyword can follow "->" or "." in the grammar. | |||
5104 | // However, we only want to suggest the template keyword if something | |||
5105 | // is dependent. | |||
5106 | bool IsDependent = BaseType->isDependentType(); | |||
5107 | if (!IsDependent) { | |||
5108 | for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent()) | |||
5109 | if (DeclContext *Ctx = DepScope->getEntity()) { | |||
5110 | IsDependent = Ctx->isDependentContext(); | |||
5111 | break; | |||
5112 | } | |||
5113 | } | |||
5114 | ||||
5115 | if (IsDependent) | |||
5116 | Results.AddResult(CodeCompletionResult("template")); | |||
5117 | } | |||
5118 | } | |||
5119 | } | |||
5120 | ||||
5121 | // Returns the RecordDecl inside the BaseType, falling back to primary template | |||
5122 | // in case of specializations. Since we might not have a decl for the | |||
5123 | // instantiation/specialization yet, e.g. dependent code. | |||
5124 | static RecordDecl *getAsRecordDecl(QualType BaseType) { | |||
5125 | BaseType = BaseType.getNonReferenceType(); | |||
5126 | if (auto *RD = BaseType->getAsRecordDecl()) { | |||
5127 | if (const auto *CTSD = | |||
5128 | llvm::dyn_cast<ClassTemplateSpecializationDecl>(RD)) { | |||
5129 | // Template might not be instantiated yet, fall back to primary template | |||
5130 | // in such cases. | |||
5131 | if (CTSD->getTemplateSpecializationKind() == TSK_Undeclared) | |||
5132 | RD = CTSD->getSpecializedTemplate()->getTemplatedDecl(); | |||
5133 | } | |||
5134 | return RD; | |||
5135 | } | |||
5136 | ||||
5137 | if (const auto *TST = BaseType->getAs<TemplateSpecializationType>()) { | |||
5138 | if (const auto *TD = dyn_cast_or_null<ClassTemplateDecl>( | |||
5139 | TST->getTemplateName().getAsTemplateDecl())) { | |||
5140 | return TD->getTemplatedDecl(); | |||
5141 | } | |||
5142 | } | |||
5143 | ||||
5144 | return nullptr; | |||
5145 | } | |||
5146 | ||||
5147 | namespace { | |||
5148 | // Collects completion-relevant information about a concept-constrainted type T. | |||
5149 | // In particular, examines the constraint expressions to find members of T. | |||
5150 | // | |||
5151 | // The design is very simple: we walk down each constraint looking for | |||
5152 | // expressions of the form T.foo(). | |||
5153 | // If we're extra lucky, the return type is specified. | |||
5154 | // We don't do any clever handling of && or || in constraint expressions, we | |||
5155 | // take members from both branches. | |||
5156 | // | |||
5157 | // For example, given: | |||
5158 | // template <class T> concept X = requires (T t, string& s) { t.print(s); }; | |||
5159 | // template <X U> void foo(U u) { u.^ } | |||
5160 | // We want to suggest the inferred member function 'print(string)'. | |||
5161 | // We see that u has type U, so X<U> holds. | |||
5162 | // X<U> requires t.print(s) to be valid, where t has type U (substituted for T). | |||
5163 | // By looking at the CallExpr we find the signature of print(). | |||
5164 | // | |||
5165 | // While we tend to know in advance which kind of members (access via . -> ::) | |||
5166 | // we want, it's simpler just to gather them all and post-filter. | |||
5167 | // | |||
5168 | // FIXME: some of this machinery could be used for non-concept type-parms too, | |||
5169 | // enabling completion for type parameters based on other uses of that param. | |||
5170 | // | |||
5171 | // FIXME: there are other cases where a type can be constrained by a concept, | |||
5172 | // e.g. inside `if constexpr(ConceptSpecializationExpr) { ... }` | |||
5173 | class ConceptInfo { | |||
5174 | public: | |||
5175 | // Describes a likely member of a type, inferred by concept constraints. | |||
5176 | // Offered as a code completion for T. T-> and T:: contexts. | |||
5177 | struct Member { | |||
5178 | // Always non-null: we only handle members with ordinary identifier names. | |||
5179 | const IdentifierInfo *Name = nullptr; | |||
5180 | // Set for functions we've seen called. | |||
5181 | // We don't have the declared parameter types, only the actual types of | |||
5182 | // arguments we've seen. These are still valuable, as it's hard to render | |||
5183 | // a useful function completion with neither parameter types nor names! | |||
5184 | std::optional<SmallVector<QualType, 1>> ArgTypes; | |||
5185 | // Whether this is accessed as T.member, T->member, or T::member. | |||
5186 | enum AccessOperator { | |||
5187 | Colons, | |||
5188 | Arrow, | |||
5189 | Dot, | |||
5190 | } Operator = Dot; | |||
5191 | // What's known about the type of a variable or return type of a function. | |||
5192 | const TypeConstraint *ResultType = nullptr; | |||
5193 | // FIXME: also track: | |||
5194 | // - kind of entity (function/variable/type), to expose structured results | |||
5195 | // - template args kinds/types, as a proxy for template params | |||
5196 | ||||
5197 | // For now we simply return these results as "pattern" strings. | |||
5198 | CodeCompletionString *render(Sema &S, CodeCompletionAllocator &Alloc, | |||
5199 | CodeCompletionTUInfo &Info) const { | |||
5200 | CodeCompletionBuilder B(Alloc, Info); | |||
5201 | // Result type | |||
5202 | if (ResultType) { | |||
5203 | std::string AsString; | |||
5204 | { | |||
5205 | llvm::raw_string_ostream OS(AsString); | |||
5206 | QualType ExactType = deduceType(*ResultType); | |||
5207 | if (!ExactType.isNull()) | |||
5208 | ExactType.print(OS, getCompletionPrintingPolicy(S)); | |||
5209 | else | |||
5210 | ResultType->print(OS, getCompletionPrintingPolicy(S)); | |||
5211 | } | |||
5212 | B.AddResultTypeChunk(Alloc.CopyString(AsString)); | |||
5213 | } | |||
5214 | // Member name | |||
5215 | B.AddTypedTextChunk(Alloc.CopyString(Name->getName())); | |||
5216 | // Function argument list | |||
5217 | if (ArgTypes) { | |||
5218 | B.AddChunk(clang::CodeCompletionString::CK_LeftParen); | |||
5219 | bool First = true; | |||
5220 | for (QualType Arg : *ArgTypes) { | |||
5221 | if (First) | |||
5222 | First = false; | |||
5223 | else { | |||
5224 | B.AddChunk(clang::CodeCompletionString::CK_Comma); | |||
5225 | B.AddChunk(clang::CodeCompletionString::CK_HorizontalSpace); | |||
5226 | } | |||
5227 | B.AddPlaceholderChunk(Alloc.CopyString( | |||
5228 | Arg.getAsString(getCompletionPrintingPolicy(S)))); | |||
5229 | } | |||
5230 | B.AddChunk(clang::CodeCompletionString::CK_RightParen); | |||
5231 | } | |||
5232 | return B.TakeString(); | |||
5233 | } | |||
5234 | }; | |||
5235 | ||||
5236 | // BaseType is the type parameter T to infer members from. | |||
5237 | // T must be accessible within S, as we use it to find the template entity | |||
5238 | // that T is attached to in order to gather the relevant constraints. | |||
5239 | ConceptInfo(const TemplateTypeParmType &BaseType, Scope *S) { | |||
5240 | auto *TemplatedEntity = getTemplatedEntity(BaseType.getDecl(), S); | |||
5241 | for (const Expr *E : constraintsForTemplatedEntity(TemplatedEntity)) | |||
5242 | believe(E, &BaseType); | |||
5243 | } | |||
5244 | ||||
5245 | std::vector<Member> members() { | |||
5246 | std::vector<Member> Results; | |||
5247 | for (const auto &E : this->Results) | |||
5248 | Results.push_back(E.second); | |||
5249 | llvm::sort(Results, [](const Member &L, const Member &R) { | |||
5250 | return L.Name->getName() < R.Name->getName(); | |||
5251 | }); | |||
5252 | return Results; | |||
5253 | } | |||
5254 | ||||
5255 | private: | |||
5256 | // Infer members of T, given that the expression E (dependent on T) is true. | |||
5257 | void believe(const Expr *E, const TemplateTypeParmType *T) { | |||
5258 | if (!E || !T) | |||
5259 | return; | |||
5260 | if (auto *CSE = dyn_cast<ConceptSpecializationExpr>(E)) { | |||
5261 | // If the concept is | |||
5262 | // template <class A, class B> concept CD = f<A, B>(); | |||
5263 | // And the concept specialization is | |||
5264 | // CD<int, T> | |||
5265 | // Then we're substituting T for B, so we want to make f<A, B>() true | |||
5266 | // by adding members to B - i.e. believe(f<A, B>(), B); | |||
5267 | // | |||
5268 | // For simplicity: | |||
5269 | // - we don't attempt to substitute int for A | |||
5270 | // - when T is used in other ways (like CD<T*>) we ignore it | |||
5271 | ConceptDecl *CD = CSE->getNamedConcept(); | |||
5272 | TemplateParameterList *Params = CD->getTemplateParameters(); | |||
5273 | unsigned Index = 0; | |||
5274 | for (const auto &Arg : CSE->getTemplateArguments()) { | |||
5275 | if (Index >= Params->size()) | |||
5276 | break; // Won't happen in valid code. | |||
5277 | if (isApprox(Arg, T)) { | |||
5278 | auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Params->getParam(Index)); | |||
5279 | if (!TTPD) | |||
5280 | continue; | |||
5281 | // T was used as an argument, and bound to the parameter TT. | |||
5282 | auto *TT = cast<TemplateTypeParmType>(TTPD->getTypeForDecl()); | |||
5283 | // So now we know the constraint as a function of TT is true. | |||
5284 | believe(CD->getConstraintExpr(), TT); | |||
5285 | // (concepts themselves have no associated constraints to require) | |||
5286 | } | |||
5287 | ||||
5288 | ++Index; | |||
5289 | } | |||
5290 | } else if (auto *BO = dyn_cast<BinaryOperator>(E)) { | |||
5291 | // For A && B, we can infer members from both branches. | |||
5292 | // For A || B, the union is still more useful than the intersection. | |||
5293 | if (BO->getOpcode() == BO_LAnd || BO->getOpcode() == BO_LOr) { | |||
5294 | believe(BO->getLHS(), T); | |||
5295 | believe(BO->getRHS(), T); | |||
5296 | } | |||
5297 | } else if (auto *RE = dyn_cast<RequiresExpr>(E)) { | |||
5298 | // A requires(){...} lets us infer members from each requirement. | |||
5299 | for (const concepts::Requirement *Req : RE->getRequirements()) { | |||
5300 | if (!Req->isDependent()) | |||
5301 | continue; // Can't tell us anything about T. | |||
5302 | // Now Req cannot a substitution-error: those aren't dependent. | |||
5303 | ||||
5304 | if (auto *TR = dyn_cast<concepts::TypeRequirement>(Req)) { | |||
5305 | // Do a full traversal so we get `foo` from `typename T::foo::bar`. | |||
5306 | QualType AssertedType = TR->getType()->getType(); | |||
5307 | ValidVisitor(this, T).TraverseType(AssertedType); | |||
5308 | } else if (auto *ER = dyn_cast<concepts::ExprRequirement>(Req)) { | |||
5309 | ValidVisitor Visitor(this, T); | |||
5310 | // If we have a type constraint on the value of the expression, | |||
5311 | // AND the whole outer expression describes a member, then we'll | |||
5312 | // be able to use the constraint to provide the return type. | |||
5313 | if (ER->getReturnTypeRequirement().isTypeConstraint()) { | |||
5314 | Visitor.OuterType = | |||
5315 | ER->getReturnTypeRequirement().getTypeConstraint(); | |||
5316 | Visitor.OuterExpr = ER->getExpr(); | |||
5317 | } | |||
5318 | Visitor.TraverseStmt(ER->getExpr()); | |||
5319 | } else if (auto *NR = dyn_cast<concepts::NestedRequirement>(Req)) { | |||
5320 | believe(NR->getConstraintExpr(), T); | |||
5321 | } | |||
5322 | } | |||
5323 | } | |||
5324 | } | |||
5325 | ||||
5326 | // This visitor infers members of T based on traversing expressions/types | |||
5327 | // that involve T. It is invoked with code known to be valid for T. | |||
5328 | class ValidVisitor : public RecursiveASTVisitor<ValidVisitor> { | |||
5329 | ConceptInfo *Outer; | |||
5330 | const TemplateTypeParmType *T; | |||
5331 | ||||
5332 | CallExpr *Caller = nullptr; | |||
5333 | Expr *Callee = nullptr; | |||
5334 | ||||
5335 | public: | |||
5336 | // If set, OuterExpr is constrained by OuterType. | |||
5337 | Expr *OuterExpr = nullptr; | |||
5338 | const TypeConstraint *OuterType = nullptr; | |||
5339 | ||||
5340 | ValidVisitor(ConceptInfo *Outer, const TemplateTypeParmType *T) | |||
5341 | : Outer(Outer), T(T) { | |||
5342 | assert(T)(static_cast <bool> (T) ? void (0) : __assert_fail ("T" , "clang/lib/Sema/SemaCodeComplete.cpp", 5342, __extension__ __PRETTY_FUNCTION__ )); | |||
5343 | } | |||
5344 | ||||
5345 | // In T.foo or T->foo, `foo` is a member function/variable. | |||
5346 | bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) { | |||
5347 | const Type *Base = E->getBaseType().getTypePtr(); | |||
5348 | bool IsArrow = E->isArrow(); | |||
5349 | if (Base->isPointerType() && IsArrow) { | |||
5350 | IsArrow = false; | |||
5351 | Base = Base->getPointeeType().getTypePtr(); | |||
5352 | } | |||
5353 | if (isApprox(Base, T)) | |||
5354 | addValue(E, E->getMember(), IsArrow ? Member::Arrow : Member::Dot); | |||
5355 | return true; | |||
5356 | } | |||
5357 | ||||
5358 | // In T::foo, `foo` is a static member function/variable. | |||
5359 | bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) { | |||
5360 | if (E->getQualifier() && isApprox(E->getQualifier()->getAsType(), T)) | |||
5361 | addValue(E, E->getDeclName(), Member::Colons); | |||
5362 | return true; | |||
5363 | } | |||
5364 | ||||
5365 | // In T::typename foo, `foo` is a type. | |||
5366 | bool VisitDependentNameType(DependentNameType *DNT) { | |||
5367 | const auto *Q = DNT->getQualifier(); | |||
5368 | if (Q && isApprox(Q->getAsType(), T)) | |||
5369 | addType(DNT->getIdentifier()); | |||
5370 | return true; | |||
5371 | } | |||
5372 | ||||
5373 | // In T::foo::bar, `foo` must be a type. | |||
5374 | // VisitNNS() doesn't exist, and TraverseNNS isn't always called :-( | |||
5375 | bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSL) { | |||
5376 | if (NNSL) { | |||
5377 | NestedNameSpecifier *NNS = NNSL.getNestedNameSpecifier(); | |||
5378 | const auto *Q = NNS->getPrefix(); | |||
5379 | if (Q && isApprox(Q->getAsType(), T)) | |||
5380 | addType(NNS->getAsIdentifier()); | |||
5381 | } | |||
5382 | // FIXME: also handle T::foo<X>::bar | |||
5383 | return RecursiveASTVisitor::TraverseNestedNameSpecifierLoc(NNSL); | |||
5384 | } | |||
5385 | ||||
5386 | // FIXME also handle T::foo<X> | |||
5387 | ||||
5388 | // Track the innermost caller/callee relationship so we can tell if a | |||
5389 | // nested expr is being called as a function. | |||
5390 | bool VisitCallExpr(CallExpr *CE) { | |||
5391 | Caller = CE; | |||
5392 | Callee = CE->getCallee(); | |||
5393 | return true; | |||
5394 | } | |||
5395 | ||||
5396 | private: | |||
5397 | void addResult(Member &&M) { | |||
5398 | auto R = Outer->Results.try_emplace(M.Name); | |||
5399 | Member &O = R.first->second; | |||
5400 | // Overwrite existing if the new member has more info. | |||
5401 | // The preference of . vs :: vs -> is fairly arbitrary. | |||
5402 | if (/*Inserted*/ R.second || | |||
5403 | std::make_tuple(M.ArgTypes.has_value(), M.ResultType != nullptr, | |||
5404 | M.Operator) > std::make_tuple(O.ArgTypes.has_value(), | |||
5405 | O.ResultType != nullptr, | |||
5406 | O.Operator)) | |||
5407 | O = std::move(M); | |||
5408 | } | |||
5409 | ||||
5410 | void addType(const IdentifierInfo *Name) { | |||
5411 | if (!Name) | |||
5412 | return; | |||
5413 | Member M; | |||
5414 | M.Name = Name; | |||
5415 | M.Operator = Member::Colons; | |||
5416 | addResult(std::move(M)); | |||
5417 | } | |||
5418 | ||||
5419 | void addValue(Expr *E, DeclarationName Name, | |||
5420 | Member::AccessOperator Operator) { | |||
5421 | if (!Name.isIdentifier()) | |||
5422 | return; | |||
5423 | Member Result; | |||
5424 | Result.Name = Name.getAsIdentifierInfo(); | |||
5425 | Result.Operator = Operator; | |||
5426 | // If this is the callee of an immediately-enclosing CallExpr, then | |||
5427 | // treat it as a method, otherwise it's a variable. | |||
5428 | if (Caller != nullptr && Callee == E) { | |||
5429 | Result.ArgTypes.emplace(); | |||
5430 | for (const auto *Arg : Caller->arguments()) | |||
5431 | Result.ArgTypes->push_back(Arg->getType()); | |||
5432 | if (Caller == OuterExpr) { | |||
5433 | Result.ResultType = OuterType; | |||
5434 | } | |||
5435 | } else { | |||
5436 | if (E == OuterExpr) | |||
5437 | Result.ResultType = OuterType; | |||
5438 | } | |||
5439 | addResult(std::move(Result)); | |||
5440 | } | |||
5441 | }; | |||
5442 | ||||
5443 | static bool isApprox(const TemplateArgument &Arg, const Type *T) { | |||
5444 | return Arg.getKind() == TemplateArgument::Type && | |||
5445 | isApprox(Arg.getAsType().getTypePtr(), T); | |||
5446 | } | |||
5447 | ||||
5448 | static bool isApprox(const Type *T1, const Type *T2) { | |||
5449 | return T1 && T2 && | |||
5450 | T1->getCanonicalTypeUnqualified() == | |||
5451 | T2->getCanonicalTypeUnqualified(); | |||
5452 | } | |||
5453 | ||||
5454 | // Returns the DeclContext immediately enclosed by the template parameter | |||
5455 | // scope. For primary templates, this is the templated (e.g.) CXXRecordDecl. | |||
5456 | // For specializations, this is e.g. ClassTemplatePartialSpecializationDecl. | |||
5457 | static DeclContext *getTemplatedEntity(const TemplateTypeParmDecl *D, | |||
5458 | Scope *S) { | |||
5459 | if (D == nullptr) | |||
5460 | return nullptr; | |||
5461 | Scope *Inner = nullptr; | |||
5462 | while (S) { | |||
5463 | if (S->isTemplateParamScope() && S->isDeclScope(D)) | |||
5464 | return Inner ? Inner->getEntity() : nullptr; | |||
5465 | Inner = S; | |||
5466 | S = S->getParent(); | |||
5467 | } | |||
5468 | return nullptr; | |||
5469 | } | |||
5470 | ||||
5471 | // Gets all the type constraint expressions that might apply to the type | |||
5472 | // variables associated with DC (as returned by getTemplatedEntity()). | |||
5473 | static SmallVector<const Expr *, 1> | |||
5474 | constraintsForTemplatedEntity(DeclContext *DC) { | |||
5475 | SmallVector<const Expr *, 1> Result; | |||
5476 | if (DC == nullptr) | |||
5477 | return Result; | |||
5478 | // Primary templates can have constraints. | |||
5479 | if (const auto *TD = cast<Decl>(DC)->getDescribedTemplate()) | |||
5480 | TD->getAssociatedConstraints(Result); | |||
5481 | // Partial specializations may have constraints. | |||
5482 | if (const auto *CTPSD = | |||
5483 | dyn_cast<ClassTemplatePartialSpecializationDecl>(DC)) | |||
5484 | CTPSD->getAssociatedConstraints(Result); | |||
5485 | if (const auto *VTPSD = dyn_cast<VarTemplatePartialSpecializationDecl>(DC)) | |||
5486 | VTPSD->getAssociatedConstraints(Result); | |||
5487 | return Result; | |||
5488 | } | |||
5489 | ||||
5490 | // Attempt to find the unique type satisfying a constraint. | |||
5491 | // This lets us show e.g. `int` instead of `std::same_as<int>`. | |||
5492 | static QualType deduceType(const TypeConstraint &T) { | |||
5493 | // Assume a same_as<T> return type constraint is std::same_as or equivalent. | |||
5494 | // In this case the return type is T. | |||
5495 | DeclarationName DN = T.getNamedConcept()->getDeclName(); | |||
5496 | if (DN.isIdentifier() && DN.getAsIdentifierInfo()->isStr("same_as")) | |||
5497 | if (const auto *Args = T.getTemplateArgsAsWritten()) | |||
5498 | if (Args->getNumTemplateArgs() == 1) { | |||
5499 | const auto &Arg = Args->arguments().front().getArgument(); | |||
5500 | if (Arg.getKind() == TemplateArgument::Type) | |||
5501 | return Arg.getAsType(); | |||
5502 | } | |||
5503 | return {}; | |||
5504 | } | |||
5505 | ||||
5506 | llvm::DenseMap<const IdentifierInfo *, Member> Results; | |||
5507 | }; | |||
5508 | ||||
5509 | // Returns a type for E that yields acceptable member completions. | |||
5510 | // In particular, when E->getType() is DependentTy, try to guess a likely type. | |||
5511 | // We accept some lossiness (like dropping parameters). | |||
5512 | // We only try to handle common expressions on the LHS of MemberExpr. | |||
5513 | QualType getApproximateType(const Expr *E) { | |||
5514 | if (E->getType().isNull()) | |||
5515 | return QualType(); | |||
5516 | E = E->IgnoreParenImpCasts(); | |||
5517 | QualType Unresolved = E->getType(); | |||
5518 | // We only resolve DependentTy, or undeduced autos (including auto* etc). | |||
5519 | if (!Unresolved->isSpecificBuiltinType(BuiltinType::Dependent)) { | |||
5520 | AutoType *Auto = Unresolved->getContainedAutoType(); | |||
5521 | if (!Auto || !Auto->isUndeducedAutoType()) | |||
5522 | return Unresolved; | |||
5523 | } | |||
5524 | // A call: approximate-resolve callee to a function type, get its return type | |||
5525 | if (const CallExpr *CE = llvm::dyn_cast<CallExpr>(E)) { | |||
5526 | QualType Callee = getApproximateType(CE->getCallee()); | |||
5527 | if (Callee.isNull() || | |||
5528 | Callee->isSpecificPlaceholderType(BuiltinType::BoundMember)) | |||
5529 | Callee = Expr::findBoundMemberType(CE->getCallee()); | |||
5530 | if (Callee.isNull()) | |||
5531 | return Unresolved; | |||
5532 | ||||
5533 | if (const auto *FnTypePtr = Callee->getAs<PointerType>()) { | |||
5534 | Callee = FnTypePtr->getPointeeType(); | |||
5535 | } else if (const auto *BPT = Callee->getAs<BlockPointerType>()) { | |||
5536 | Callee = BPT->getPointeeType(); | |||
5537 | } | |||
5538 | if (const FunctionType *FnType = Callee->getAs<FunctionType>()) | |||
5539 | return FnType->getReturnType().getNonReferenceType(); | |||
5540 | ||||
5541 | // Unresolved call: try to guess the return type. | |||
5542 | if (const auto *OE = llvm::dyn_cast<OverloadExpr>(CE->getCallee())) { | |||
5543 | // If all candidates have the same approximate return type, use it. | |||
5544 | // Discard references and const to allow more to be "the same". | |||
5545 | // (In particular, if there's one candidate + ADL, resolve it). | |||
5546 | const Type *Common = nullptr; | |||
5547 | for (const auto *D : OE->decls()) { | |||
5548 | QualType ReturnType; | |||
5549 | if (const auto *FD = llvm::dyn_cast<FunctionDecl>(D)) | |||
5550 | ReturnType = FD->getReturnType(); | |||
5551 | else if (const auto *FTD = llvm::dyn_cast<FunctionTemplateDecl>(D)) | |||
5552 | ReturnType = FTD->getTemplatedDecl()->getReturnType(); | |||
5553 | if (ReturnType.isNull()) | |||
5554 | continue; | |||
5555 | const Type *Candidate = | |||
5556 | ReturnType.getNonReferenceType().getCanonicalType().getTypePtr(); | |||
5557 | if (Common && Common != Candidate) | |||
5558 | return Unresolved; // Multiple candidates. | |||
5559 | Common = Candidate; | |||
5560 | } | |||
5561 | if (Common != nullptr) | |||
5562 | return QualType(Common, 0); | |||
5563 | } | |||
5564 | } | |||
5565 | // A dependent member: approximate-resolve the base, then lookup. | |||
5566 | if (const auto *CDSME = llvm::dyn_cast<CXXDependentScopeMemberExpr>(E)) { | |||
5567 | QualType Base = CDSME->isImplicitAccess() | |||
5568 | ? CDSME->getBaseType() | |||
5569 | : getApproximateType(CDSME->getBase()); | |||
5570 | if (CDSME->isArrow() && !Base.isNull()) | |||
5571 | Base = Base->getPointeeType(); // could handle unique_ptr etc here? | |||
5572 | auto *RD = | |||
5573 | Base.isNull() | |||
5574 | ? nullptr | |||
5575 | : llvm::dyn_cast_or_null<CXXRecordDecl>(getAsRecordDecl(Base)); | |||
5576 | if (RD && RD->isCompleteDefinition()) { | |||
5577 | // Look up member heuristically, including in bases. | |||
5578 | for (const auto *Member : RD->lookupDependentName( | |||
5579 | CDSME->getMember(), [](const NamedDecl *Member) { | |||
5580 | return llvm::isa<ValueDecl>(Member); | |||
5581 | })) { | |||
5582 | return llvm::cast<ValueDecl>(Member)->getType().getNonReferenceType(); | |||
5583 | } | |||
5584 | } | |||
5585 | } | |||
5586 | // A reference to an `auto` variable: approximate-resolve its initializer. | |||
5587 | if (const auto *DRE = llvm::dyn_cast<DeclRefExpr>(E)) { | |||
5588 | if (const auto *VD = llvm::dyn_cast<VarDecl>(DRE->getDecl())) { | |||
5589 | if (VD->hasInit()) | |||
5590 | return getApproximateType(VD->getInit()); | |||
5591 | } | |||
5592 | } | |||
5593 | return Unresolved; | |||
5594 | } | |||
5595 | ||||
5596 | // If \p Base is ParenListExpr, assume a chain of comma operators and pick the | |||
5597 | // last expr. We expect other ParenListExprs to be resolved to e.g. constructor | |||
5598 | // calls before here. (So the ParenListExpr should be nonempty, but check just | |||
5599 | // in case) | |||
5600 | Expr *unwrapParenList(Expr *Base) { | |||
5601 | if (auto *PLE = llvm::dyn_cast_or_null<ParenListExpr>(Base)) { | |||
5602 | if (PLE->getNumExprs() == 0) | |||
5603 | return nullptr; | |||
5604 | Base = PLE->getExpr(PLE->getNumExprs() - 1); | |||
5605 | } | |||
5606 | return Base; | |||
5607 | } | |||
5608 | ||||
5609 | } // namespace | |||
5610 | ||||
5611 | void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, | |||
5612 | Expr *OtherOpBase, | |||
5613 | SourceLocation OpLoc, bool IsArrow, | |||
5614 | bool IsBaseExprStatement, | |||
5615 | QualType PreferredType) { | |||
5616 | Base = unwrapParenList(Base); | |||
5617 | OtherOpBase = unwrapParenList(OtherOpBase); | |||
5618 | if (!Base || !CodeCompleter) | |||
5619 | return; | |||
5620 | ||||
5621 | ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow); | |||
5622 | if (ConvertedBase.isInvalid()) | |||
5623 | return; | |||
5624 | QualType ConvertedBaseType = getApproximateType(ConvertedBase.get()); | |||
5625 | ||||
5626 | enum CodeCompletionContext::Kind contextKind; | |||
5627 | ||||
5628 | if (IsArrow) { | |||
5629 | if (const auto *Ptr = ConvertedBaseType->getAs<PointerType>()) | |||
5630 | ConvertedBaseType = Ptr->getPointeeType(); | |||
5631 | } | |||
5632 | ||||
5633 | if (IsArrow) { | |||
5634 | contextKind = CodeCompletionContext::CCC_ArrowMemberAccess; | |||
5635 | } else { | |||
5636 | if (ConvertedBaseType->isObjCObjectPointerType() || | |||
5637 | ConvertedBaseType->isObjCObjectOrInterfaceType()) { | |||
5638 | contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess; | |||
5639 | } else { | |||
5640 | contextKind = CodeCompletionContext::CCC_DotMemberAccess; | |||
5641 | } | |||
5642 | } | |||
5643 | ||||
5644 | CodeCompletionContext CCContext(contextKind, ConvertedBaseType); | |||
5645 | CCContext.setPreferredType(PreferredType); | |||
5646 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
5647 | CodeCompleter->getCodeCompletionTUInfo(), CCContext, | |||
5648 | &ResultBuilder::IsMember); | |||
5649 | ||||
5650 | auto DoCompletion = [&](Expr *Base, bool IsArrow, | |||
5651 | std::optional<FixItHint> AccessOpFixIt) -> bool { | |||
5652 | if (!Base) | |||
5653 | return false; | |||
5654 | ||||
5655 | ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow); | |||
5656 | if (ConvertedBase.isInvalid()) | |||
5657 | return false; | |||
5658 | Base = ConvertedBase.get(); | |||
5659 | ||||
5660 | QualType BaseType = getApproximateType(Base); | |||
5661 | if (BaseType.isNull()) | |||
5662 | return false; | |||
5663 | ExprValueKind BaseKind = Base->getValueKind(); | |||
5664 | ||||
5665 | if (IsArrow) { | |||
5666 | if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { | |||
5667 | BaseType = Ptr->getPointeeType(); | |||
5668 | BaseKind = VK_LValue; | |||
5669 | } else if (BaseType->isObjCObjectPointerType() || | |||
5670 | BaseType->isTemplateTypeParmType()) { | |||
5671 | // Both cases (dot/arrow) handled below. | |||
5672 | } else { | |||
5673 | return false; | |||
5674 | } | |||
5675 | } | |||
5676 | ||||
5677 | if (RecordDecl *RD = getAsRecordDecl(BaseType)) { | |||
5678 | AddRecordMembersCompletionResults(*this, Results, S, BaseType, BaseKind, | |||
5679 | RD, std::move(AccessOpFixIt)); | |||
5680 | } else if (const auto *TTPT = | |||
5681 | dyn_cast<TemplateTypeParmType>(BaseType.getTypePtr())) { | |||
5682 | auto Operator = | |||
5683 | IsArrow ? ConceptInfo::Member::Arrow : ConceptInfo::Member::Dot; | |||
5684 | for (const auto &R : ConceptInfo(*TTPT, S).members()) { | |||
5685 | if (R.Operator != Operator) | |||
5686 | continue; | |||
5687 | CodeCompletionResult Result( | |||
5688 | R.render(*this, CodeCompleter->getAllocator(), | |||
5689 | CodeCompleter->getCodeCompletionTUInfo())); | |||
5690 | if (AccessOpFixIt) | |||
5691 | Result.FixIts.push_back(*AccessOpFixIt); | |||
5692 | Results.AddResult(std::move(Result)); | |||
5693 | } | |||
5694 | } else if (!IsArrow && BaseType->isObjCObjectPointerType()) { | |||
5695 | // Objective-C property reference. Bail if we're performing fix-it code | |||
5696 | // completion since Objective-C properties are normally backed by ivars, | |||
5697 | // most Objective-C fix-its here would have little value. | |||
5698 | if (AccessOpFixIt) { | |||
5699 | return false; | |||
5700 | } | |||
5701 | AddedPropertiesSet AddedProperties; | |||
5702 | ||||
5703 | if (const ObjCObjectPointerType *ObjCPtr = | |||
5704 | BaseType->getAsObjCInterfacePointerType()) { | |||
5705 | // Add property results based on our interface. | |||
5706 | assert(ObjCPtr && "Non-NULL pointer guaranteed above!")(static_cast <bool> (ObjCPtr && "Non-NULL pointer guaranteed above!" ) ? void (0) : __assert_fail ("ObjCPtr && \"Non-NULL pointer guaranteed above!\"" , "clang/lib/Sema/SemaCodeComplete.cpp", 5706, __extension__ __PRETTY_FUNCTION__ )); | |||
5707 | AddObjCProperties(CCContext, ObjCPtr->getInterfaceDecl(), true, | |||
5708 | /*AllowNullaryMethods=*/true, CurContext, | |||
5709 | AddedProperties, Results, IsBaseExprStatement); | |||
5710 | } | |||
5711 | ||||
5712 | // Add properties from the protocols in a qualified interface. | |||
5713 | for (auto *I : BaseType->castAs<ObjCObjectPointerType>()->quals()) | |||
5714 | AddObjCProperties(CCContext, I, true, /*AllowNullaryMethods=*/true, | |||
5715 | CurContext, AddedProperties, Results, | |||
5716 | IsBaseExprStatement, /*IsClassProperty*/ false, | |||
5717 | /*InOriginalClass*/ false); | |||
5718 | } else if ((IsArrow && BaseType->isObjCObjectPointerType()) || | |||
5719 | (!IsArrow && BaseType->isObjCObjectType())) { | |||
5720 | // Objective-C instance variable access. Bail if we're performing fix-it | |||
5721 | // code completion since Objective-C properties are normally backed by | |||
5722 | // ivars, most Objective-C fix-its here would have little value. | |||
5723 | if (AccessOpFixIt) { | |||
5724 | return false; | |||
5725 | } | |||
5726 | ObjCInterfaceDecl *Class = nullptr; | |||
5727 | if (const ObjCObjectPointerType *ObjCPtr = | |||
5728 | BaseType->getAs<ObjCObjectPointerType>()) | |||
5729 | Class = ObjCPtr->getInterfaceDecl(); | |||
5730 | else | |||
5731 | Class = BaseType->castAs<ObjCObjectType>()->getInterface(); | |||
5732 | ||||
5733 | // Add all ivars from this class and its superclasses. | |||
5734 | if (Class) { | |||
5735 | CodeCompletionDeclConsumer Consumer(Results, Class, BaseType); | |||
5736 | Results.setFilter(&ResultBuilder::IsObjCIvar); | |||
5737 | LookupVisibleDecls( | |||
5738 | Class, LookupMemberName, Consumer, CodeCompleter->includeGlobals(), | |||
5739 | /*IncludeDependentBases=*/false, CodeCompleter->loadExternal()); | |||
5740 | } | |||
5741 | } | |||
5742 | ||||
5743 | // FIXME: How do we cope with isa? | |||
5744 | return true; | |||
5745 | }; | |||
5746 | ||||
5747 | Results.EnterNewScope(); | |||
5748 | ||||
5749 | bool CompletionSucceded = DoCompletion(Base, IsArrow, std::nullopt); | |||
5750 | if (CodeCompleter->includeFixIts()) { | |||
5751 | const CharSourceRange OpRange = | |||
5752 | CharSourceRange::getTokenRange(OpLoc, OpLoc); | |||
5753 | CompletionSucceded |= DoCompletion( | |||
5754 | OtherOpBase, !IsArrow, | |||
5755 | FixItHint::CreateReplacement(OpRange, IsArrow ? "." : "->")); | |||
5756 | } | |||
5757 | ||||
5758 | Results.ExitScope(); | |||
5759 | ||||
5760 | if (!CompletionSucceded) | |||
5761 | return; | |||
5762 | ||||
5763 | // Hand off the results found for code completion. | |||
5764 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
5765 | Results.data(), Results.size()); | |||
5766 | } | |||
5767 | ||||
5768 | void Sema::CodeCompleteObjCClassPropertyRefExpr(Scope *S, | |||
5769 | IdentifierInfo &ClassName, | |||
5770 | SourceLocation ClassNameLoc, | |||
5771 | bool IsBaseExprStatement) { | |||
5772 | IdentifierInfo *ClassNamePtr = &ClassName; | |||
5773 | ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(ClassNamePtr, ClassNameLoc); | |||
5774 | if (!IFace) | |||
5775 | return; | |||
5776 | CodeCompletionContext CCContext( | |||
5777 | CodeCompletionContext::CCC_ObjCPropertyAccess); | |||
5778 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
5779 | CodeCompleter->getCodeCompletionTUInfo(), CCContext, | |||
5780 | &ResultBuilder::IsMember); | |||
5781 | Results.EnterNewScope(); | |||
5782 | AddedPropertiesSet AddedProperties; | |||
5783 | AddObjCProperties(CCContext, IFace, true, | |||
5784 | /*AllowNullaryMethods=*/true, CurContext, AddedProperties, | |||
5785 | Results, IsBaseExprStatement, | |||
5786 | /*IsClassProperty=*/true); | |||
5787 | Results.ExitScope(); | |||
5788 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
5789 | Results.data(), Results.size()); | |||
5790 | } | |||
5791 | ||||
5792 | void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) { | |||
5793 | if (!CodeCompleter) | |||
5794 | return; | |||
5795 | ||||
5796 | ResultBuilder::LookupFilter Filter = nullptr; | |||
5797 | enum CodeCompletionContext::Kind ContextKind = | |||
5798 | CodeCompletionContext::CCC_Other; | |||
5799 | switch ((DeclSpec::TST)TagSpec) { | |||
5800 | case DeclSpec::TST_enum: | |||
5801 | Filter = &ResultBuilder::IsEnum; | |||
5802 | ContextKind = CodeCompletionContext::CCC_EnumTag; | |||
5803 | break; | |||
5804 | ||||
5805 | case DeclSpec::TST_union: | |||
5806 | Filter = &ResultBuilder::IsUnion; | |||
5807 | ContextKind = CodeCompletionContext::CCC_UnionTag; | |||
5808 | break; | |||
5809 | ||||
5810 | case DeclSpec::TST_struct: | |||
5811 | case DeclSpec::TST_class: | |||
5812 | case DeclSpec::TST_interface: | |||
5813 | Filter = &ResultBuilder::IsClassOrStruct; | |||
5814 | ContextKind = CodeCompletionContext::CCC_ClassOrStructTag; | |||
5815 | break; | |||
5816 | ||||
5817 | default: | |||
5818 | llvm_unreachable("Unknown type specifier kind in CodeCompleteTag")::llvm::llvm_unreachable_internal("Unknown type specifier kind in CodeCompleteTag" , "clang/lib/Sema/SemaCodeComplete.cpp", 5818); | |||
5819 | } | |||
5820 | ||||
5821 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
5822 | CodeCompleter->getCodeCompletionTUInfo(), ContextKind); | |||
5823 | CodeCompletionDeclConsumer Consumer(Results, CurContext); | |||
5824 | ||||
5825 | // First pass: look for tags. | |||
5826 | Results.setFilter(Filter); | |||
5827 | LookupVisibleDecls(S, LookupTagName, Consumer, | |||
5828 | CodeCompleter->includeGlobals(), | |||
5829 | CodeCompleter->loadExternal()); | |||
5830 | ||||
5831 | if (CodeCompleter->includeGlobals()) { | |||
5832 | // Second pass: look for nested name specifiers. | |||
5833 | Results.setFilter(&ResultBuilder::IsNestedNameSpecifier); | |||
5834 | LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer, | |||
5835 | CodeCompleter->includeGlobals(), | |||
5836 | CodeCompleter->loadExternal()); | |||
5837 | } | |||
5838 | ||||
5839 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
5840 | Results.data(), Results.size()); | |||
5841 | } | |||
5842 | ||||
5843 | static void AddTypeQualifierResults(DeclSpec &DS, ResultBuilder &Results, | |||
5844 | const LangOptions &LangOpts) { | |||
5845 | if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const)) | |||
5846 | Results.AddResult("const"); | |||
5847 | if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile)) | |||
5848 | Results.AddResult("volatile"); | |||
5849 | if (LangOpts.C99 && !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict)) | |||
5850 | Results.AddResult("restrict"); | |||
5851 | if (LangOpts.C11 && !(DS.getTypeQualifiers() & DeclSpec::TQ_atomic)) | |||
5852 | Results.AddResult("_Atomic"); | |||
5853 | if (LangOpts.MSVCCompat && !(DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)) | |||
5854 | Results.AddResult("__unaligned"); | |||
5855 | } | |||
5856 | ||||
5857 | void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) { | |||
5858 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
5859 | CodeCompleter->getCodeCompletionTUInfo(), | |||
5860 | CodeCompletionContext::CCC_TypeQualifiers); | |||
5861 | Results.EnterNewScope(); | |||
5862 | AddTypeQualifierResults(DS, Results, LangOpts); | |||
5863 | Results.ExitScope(); | |||
5864 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
5865 | Results.data(), Results.size()); | |||
5866 | } | |||
5867 | ||||
5868 | void Sema::CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D, | |||
5869 | const VirtSpecifiers *VS) { | |||
5870 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
5871 | CodeCompleter->getCodeCompletionTUInfo(), | |||
5872 | CodeCompletionContext::CCC_TypeQualifiers); | |||
5873 | Results.EnterNewScope(); | |||
5874 | AddTypeQualifierResults(DS, Results, LangOpts); | |||
5875 | if (LangOpts.CPlusPlus11) { | |||
5876 | Results.AddResult("noexcept"); | |||
5877 | if (D.getContext() == DeclaratorContext::Member && !D.isCtorOrDtor() && | |||
5878 | !D.isStaticMember()) { | |||
5879 | if (!VS || !VS->isFinalSpecified()) | |||
5880 | Results.AddResult("final"); | |||
5881 | if (!VS || !VS->isOverrideSpecified()) | |||
5882 | Results.AddResult("override"); | |||
5883 | } | |||
5884 | } | |||
5885 | Results.ExitScope(); | |||
5886 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
5887 | Results.data(), Results.size()); | |||
5888 | } | |||
5889 | ||||
5890 | void Sema::CodeCompleteBracketDeclarator(Scope *S) { | |||
5891 | CodeCompleteExpression(S, QualType(getASTContext().getSizeType())); | |||
5892 | } | |||
5893 | ||||
5894 | void Sema::CodeCompleteCase(Scope *S) { | |||
5895 | if (getCurFunction()->SwitchStack.empty() || !CodeCompleter) | |||
5896 | return; | |||
5897 | ||||
5898 | SwitchStmt *Switch = getCurFunction()->SwitchStack.back().getPointer(); | |||
5899 | // Condition expression might be invalid, do not continue in this case. | |||
5900 | if (!Switch->getCond()) | |||
5901 | return; | |||
5902 | QualType type = Switch->getCond()->IgnoreImplicit()->getType(); | |||
5903 | if (!type->isEnumeralType()) { | |||
5904 | CodeCompleteExpressionData Data(type); | |||
5905 | Data.IntegralConstantExpression = true; | |||
5906 | CodeCompleteExpression(S, Data); | |||
5907 | return; | |||
5908 | } | |||
5909 | ||||
5910 | // Code-complete the cases of a switch statement over an enumeration type | |||
5911 | // by providing the list of | |||
5912 | EnumDecl *Enum = type->castAs<EnumType>()->getDecl(); | |||
5913 | if (EnumDecl *Def = Enum->getDefinition()) | |||
5914 | Enum = Def; | |||
5915 | ||||
5916 | // Determine which enumerators we have already seen in the switch statement. | |||
5917 | // FIXME: Ideally, we would also be able to look *past* the code-completion | |||
5918 | // token, in case we are code-completing in the middle of the switch and not | |||
5919 | // at the end. However, we aren't able to do so at the moment. | |||
5920 | CoveredEnumerators Enumerators; | |||
5921 | for (SwitchCase *SC = Switch->getSwitchCaseList(); SC; | |||
5922 | SC = SC->getNextSwitchCase()) { | |||
5923 | CaseStmt *Case = dyn_cast<CaseStmt>(SC); | |||
5924 | if (!Case) | |||
5925 | continue; | |||
5926 | ||||
5927 | Expr *CaseVal = Case->getLHS()->IgnoreParenCasts(); | |||
5928 | if (auto *DRE = dyn_cast<DeclRefExpr>(CaseVal)) | |||
5929 | if (auto *Enumerator = | |||
5930 | dyn_cast<EnumConstantDecl>(DRE->getDecl())) { | |||
5931 | // We look into the AST of the case statement to determine which | |||
5932 | // enumerator was named. Alternatively, we could compute the value of | |||
5933 | // the integral constant expression, then compare it against the | |||
5934 | // values of each enumerator. However, value-based approach would not | |||
5935 | // work as well with C++ templates where enumerators declared within a | |||
5936 | // template are type- and value-dependent. | |||
5937 | Enumerators.Seen.insert(Enumerator); | |||
5938 | ||||
5939 | // If this is a qualified-id, keep track of the nested-name-specifier | |||
5940 | // so that we can reproduce it as part of code completion, e.g., | |||
5941 | // | |||
5942 | // switch (TagD.getKind()) { | |||
5943 | // case TagDecl::TK_enum: | |||
5944 | // break; | |||
5945 | // case XXX | |||
5946 | // | |||
5947 | // At the XXX, our completions are TagDecl::TK_union, | |||
5948 | // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union, | |||
5949 | // TK_struct, and TK_class. | |||
5950 | Enumerators.SuggestedQualifier = DRE->getQualifier(); | |||
5951 | } | |||
5952 | } | |||
5953 | ||||
5954 | // Add any enumerators that have not yet been mentioned. | |||
5955 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
5956 | CodeCompleter->getCodeCompletionTUInfo(), | |||
5957 | CodeCompletionContext::CCC_Expression); | |||
5958 | AddEnumerators(Results, Context, Enum, CurContext, Enumerators); | |||
5959 | ||||
5960 | if (CodeCompleter->includeMacros()) { | |||
5961 | AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false); | |||
5962 | } | |||
5963 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
5964 | Results.data(), Results.size()); | |||
5965 | } | |||
5966 | ||||
5967 | static bool anyNullArguments(ArrayRef<Expr *> Args) { | |||
5968 | if (Args.size() && !Args.data()) | |||
5969 | return true; | |||
5970 | ||||
5971 | for (unsigned I = 0; I != Args.size(); ++I) | |||
5972 | if (!Args[I]) | |||
5973 | return true; | |||
5974 | ||||
5975 | return false; | |||
5976 | } | |||
5977 | ||||
5978 | typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate; | |||
5979 | ||||
5980 | static void mergeCandidatesWithResults( | |||
5981 | Sema &SemaRef, SmallVectorImpl<ResultCandidate> &Results, | |||
5982 | OverloadCandidateSet &CandidateSet, SourceLocation Loc, size_t ArgSize) { | |||
5983 | // Sort the overload candidate set by placing the best overloads first. | |||
5984 | llvm::stable_sort(CandidateSet, [&](const OverloadCandidate &X, | |||
5985 | const OverloadCandidate &Y) { | |||
5986 | return isBetterOverloadCandidate(SemaRef, X, Y, Loc, | |||
5987 | CandidateSet.getKind()); | |||
5988 | }); | |||
5989 | ||||
5990 | // Add the remaining viable overload candidates as code-completion results. | |||
5991 | for (OverloadCandidate &Candidate : CandidateSet) { | |||
5992 | if (Candidate.Function) { | |||
5993 | if (Candidate.Function->isDeleted()) | |||
5994 | continue; | |||
5995 | if (shouldEnforceArgLimit(/*PartialOverloading=*/true, | |||
5996 | Candidate.Function) && | |||
5997 | Candidate.Function->getNumParams() <= ArgSize && | |||
5998 | // Having zero args is annoying, normally we don't surface a function | |||
5999 | // with 2 params, if you already have 2 params, because you are | |||
6000 | // inserting the 3rd now. But with zero, it helps the user to figure | |||
6001 | // out there are no overloads that take any arguments. Hence we are | |||
6002 | // keeping the overload. | |||
6003 | ArgSize > 0) | |||
6004 | continue; | |||
6005 | } | |||
6006 | if (Candidate.Viable) | |||
6007 | Results.push_back(ResultCandidate(Candidate.Function)); | |||
6008 | } | |||
6009 | } | |||
6010 | ||||
6011 | /// Get the type of the Nth parameter from a given set of overload | |||
6012 | /// candidates. | |||
6013 | static QualType getParamType(Sema &SemaRef, | |||
6014 | ArrayRef<ResultCandidate> Candidates, unsigned N) { | |||
6015 | ||||
6016 | // Given the overloads 'Candidates' for a function call matching all arguments | |||
6017 | // up to N, return the type of the Nth parameter if it is the same for all | |||
6018 | // overload candidates. | |||
6019 | QualType ParamType; | |||
6020 | for (auto &Candidate : Candidates) { | |||
6021 | QualType CandidateParamType = Candidate.getParamType(N); | |||
6022 | if (CandidateParamType.isNull()) | |||
6023 | continue; | |||
6024 | if (ParamType.isNull()) { | |||
6025 | ParamType = CandidateParamType; | |||
6026 | continue; | |||
6027 | } | |||
6028 | if (!SemaRef.Context.hasSameUnqualifiedType( | |||
6029 | ParamType.getNonReferenceType(), | |||
6030 | CandidateParamType.getNonReferenceType())) | |||
6031 | // Two conflicting types, give up. | |||
6032 | return QualType(); | |||
6033 | } | |||
6034 | ||||
6035 | return ParamType; | |||
6036 | } | |||
6037 | ||||
6038 | static QualType | |||
6039 | ProduceSignatureHelp(Sema &SemaRef, MutableArrayRef<ResultCandidate> Candidates, | |||
6040 | unsigned CurrentArg, SourceLocation OpenParLoc, | |||
6041 | bool Braced) { | |||
6042 | if (Candidates.empty()) | |||
6043 | return QualType(); | |||
6044 | if (SemaRef.getPreprocessor().isCodeCompletionReached()) | |||
6045 | SemaRef.CodeCompleter->ProcessOverloadCandidates( | |||
6046 | SemaRef, CurrentArg, Candidates.data(), Candidates.size(), OpenParLoc, | |||
6047 | Braced); | |||
6048 | return getParamType(SemaRef, Candidates, CurrentArg); | |||
6049 | } | |||
6050 | ||||
6051 | // Given a callee expression `Fn`, if the call is through a function pointer, | |||
6052 | // try to find the declaration of the corresponding function pointer type, | |||
6053 | // so that we can recover argument names from it. | |||
6054 | static FunctionProtoTypeLoc GetPrototypeLoc(Expr *Fn) { | |||
6055 | TypeLoc Target; | |||
6056 | if (const auto *T = Fn->getType().getTypePtr()->getAs<TypedefType>()) { | |||
6057 | Target = T->getDecl()->getTypeSourceInfo()->getTypeLoc(); | |||
6058 | ||||
6059 | } else if (const auto *DR = dyn_cast<DeclRefExpr>(Fn)) { | |||
6060 | const auto *D = DR->getDecl(); | |||
6061 | if (const auto *const VD = dyn_cast<VarDecl>(D)) { | |||
6062 | Target = VD->getTypeSourceInfo()->getTypeLoc(); | |||
6063 | } | |||
6064 | } | |||
6065 | ||||
6066 | if (!Target) | |||
6067 | return {}; | |||
6068 | ||||
6069 | if (auto P = Target.getAs<PointerTypeLoc>()) { | |||
6070 | Target = P.getPointeeLoc(); | |||
6071 | } | |||
6072 | ||||
6073 | if (auto P = Target.getAs<ParenTypeLoc>()) { | |||
6074 | Target = P.getInnerLoc(); | |||
6075 | } | |||
6076 | ||||
6077 | if (auto F = Target.getAs<FunctionProtoTypeLoc>()) { | |||
6078 | return F; | |||
6079 | } | |||
6080 | ||||
6081 | return {}; | |||
6082 | } | |||
6083 | ||||
6084 | QualType Sema::ProduceCallSignatureHelp(Expr *Fn, ArrayRef<Expr *> Args, | |||
6085 | SourceLocation OpenParLoc) { | |||
6086 | Fn = unwrapParenList(Fn); | |||
6087 | if (!CodeCompleter || !Fn) | |||
6088 | return QualType(); | |||
6089 | ||||
6090 | // FIXME: Provide support for variadic template functions. | |||
6091 | // Ignore type-dependent call expressions entirely. | |||
6092 | if (Fn->isTypeDependent() || anyNullArguments(Args)) | |||
6093 | return QualType(); | |||
6094 | // In presence of dependent args we surface all possible signatures using the | |||
6095 | // non-dependent args in the prefix. Afterwards we do a post filtering to make | |||
6096 | // sure provided candidates satisfy parameter count restrictions. | |||
6097 | auto ArgsWithoutDependentTypes = | |||
6098 | Args.take_while([](Expr *Arg) { return !Arg->isTypeDependent(); }); | |||
6099 | ||||
6100 | SmallVector<ResultCandidate, 8> Results; | |||
6101 | ||||
6102 | Expr *NakedFn = Fn->IgnoreParenCasts(); | |||
6103 | // Build an overload candidate set based on the functions we find. | |||
6104 | SourceLocation Loc = Fn->getExprLoc(); | |||
6105 | OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); | |||
6106 | ||||
6107 | if (auto ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn)) { | |||
6108 | AddOverloadedCallCandidates(ULE, ArgsWithoutDependentTypes, CandidateSet, | |||
6109 | /*PartialOverloading=*/true); | |||
6110 | } else if (auto UME = dyn_cast<UnresolvedMemberExpr>(NakedFn)) { | |||
6111 | TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; | |||
6112 | if (UME->hasExplicitTemplateArgs()) { | |||
6113 | UME->copyTemplateArgumentsInto(TemplateArgsBuffer); | |||
6114 | TemplateArgs = &TemplateArgsBuffer; | |||
6115 | } | |||
6116 | ||||
6117 | // Add the base as first argument (use a nullptr if the base is implicit). | |||
6118 | SmallVector<Expr *, 12> ArgExprs( | |||
6119 | 1, UME->isImplicitAccess() ? nullptr : UME->getBase()); | |||
6120 | ArgExprs.append(ArgsWithoutDependentTypes.begin(), | |||
6121 | ArgsWithoutDependentTypes.end()); | |||
6122 | UnresolvedSet<8> Decls; | |||
6123 | Decls.append(UME->decls_begin(), UME->decls_end()); | |||
6124 | const bool FirstArgumentIsBase = !UME->isImplicitAccess() && UME->getBase(); | |||
6125 | AddFunctionCandidates(Decls, ArgExprs, CandidateSet, TemplateArgs, | |||
6126 | /*SuppressUserConversions=*/false, | |||
6127 | /*PartialOverloading=*/true, FirstArgumentIsBase); | |||
6128 | } else { | |||
6129 | FunctionDecl *FD = nullptr; | |||
6130 | if (auto *MCE = dyn_cast<MemberExpr>(NakedFn)) | |||
6131 | FD = dyn_cast<FunctionDecl>(MCE->getMemberDecl()); | |||
6132 | else if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) | |||
6133 | FD = dyn_cast<FunctionDecl>(DRE->getDecl()); | |||
6134 | if (FD) { // We check whether it's a resolved function declaration. | |||
6135 | if (!getLangOpts().CPlusPlus || | |||
6136 | !FD->getType()->getAs<FunctionProtoType>()) | |||
6137 | Results.push_back(ResultCandidate(FD)); | |||
6138 | else | |||
6139 | AddOverloadCandidate(FD, DeclAccessPair::make(FD, FD->getAccess()), | |||
6140 | ArgsWithoutDependentTypes, CandidateSet, | |||
6141 | /*SuppressUserConversions=*/false, | |||
6142 | /*PartialOverloading=*/true); | |||
6143 | ||||
6144 | } else if (auto DC = NakedFn->getType()->getAsCXXRecordDecl()) { | |||
6145 | // If expression's type is CXXRecordDecl, it may overload the function | |||
6146 | // call operator, so we check if it does and add them as candidates. | |||
6147 | // A complete type is needed to lookup for member function call operators. | |||
6148 | if (isCompleteType(Loc, NakedFn->getType())) { | |||
6149 | DeclarationName OpName = | |||
6150 | Context.DeclarationNames.getCXXOperatorName(OO_Call); | |||
6151 | LookupResult R(*this, OpName, Loc, LookupOrdinaryName); | |||
6152 | LookupQualifiedName(R, DC); | |||
6153 | R.suppressDiagnostics(); | |||
6154 | SmallVector<Expr *, 12> ArgExprs(1, NakedFn); | |||
6155 | ArgExprs.append(ArgsWithoutDependentTypes.begin(), | |||
6156 | ArgsWithoutDependentTypes.end()); | |||
6157 | AddFunctionCandidates(R.asUnresolvedSet(), ArgExprs, CandidateSet, | |||
6158 | /*ExplicitArgs=*/nullptr, | |||
6159 | /*SuppressUserConversions=*/false, | |||
6160 | /*PartialOverloading=*/true); | |||
6161 | } | |||
6162 | } else { | |||
6163 | // Lastly we check whether expression's type is function pointer or | |||
6164 | // function. | |||
6165 | ||||
6166 | FunctionProtoTypeLoc P = GetPrototypeLoc(NakedFn); | |||
6167 | QualType T = NakedFn->getType(); | |||
6168 | if (!T->getPointeeType().isNull()) | |||
6169 | T = T->getPointeeType(); | |||
6170 | ||||
6171 | if (auto FP = T->getAs<FunctionProtoType>()) { | |||
6172 | if (!TooManyArguments(FP->getNumParams(), | |||
6173 | ArgsWithoutDependentTypes.size(), | |||
6174 | /*PartialOverloading=*/true) || | |||
6175 | FP->isVariadic()) { | |||
6176 | if (P) { | |||
6177 | Results.push_back(ResultCandidate(P)); | |||
6178 | } else { | |||
6179 | Results.push_back(ResultCandidate(FP)); | |||
6180 | } | |||
6181 | } | |||
6182 | } else if (auto FT = T->getAs<FunctionType>()) | |||
6183 | // No prototype and declaration, it may be a K & R style function. | |||
6184 | Results.push_back(ResultCandidate(FT)); | |||
6185 | } | |||
6186 | } | |||
6187 | mergeCandidatesWithResults(*this, Results, CandidateSet, Loc, Args.size()); | |||
6188 | QualType ParamType = ProduceSignatureHelp(*this, Results, Args.size(), | |||
6189 | OpenParLoc, /*Braced=*/false); | |||
6190 | return !CandidateSet.empty() ? ParamType : QualType(); | |||
6191 | } | |||
6192 | ||||
6193 | // Determine which param to continue aggregate initialization from after | |||
6194 | // a designated initializer. | |||
6195 | // | |||
6196 | // Given struct S { int a,b,c,d,e; }: | |||
6197 | // after `S{.b=1,` we want to suggest c to continue | |||
6198 | // after `S{.b=1, 2,` we continue with d (this is legal C and ext in C++) | |||
6199 | // after `S{.b=1, .a=2,` we continue with b (this is legal C and ext in C++) | |||
6200 | // | |||
6201 | // Possible outcomes: | |||
6202 | // - we saw a designator for a field, and continue from the returned index. | |||
6203 | // Only aggregate initialization is allowed. | |||
6204 | // - we saw a designator, but it was complex or we couldn't find the field. | |||
6205 | // Only aggregate initialization is possible, but we can't assist with it. | |||
6206 | // Returns an out-of-range index. | |||
6207 | // - we saw no designators, just positional arguments. | |||
6208 | // Returns std::nullopt. | |||
6209 | static std::optional<unsigned> | |||
6210 | getNextAggregateIndexAfterDesignatedInit(const ResultCandidate &Aggregate, | |||
6211 | ArrayRef<Expr *> Args) { | |||
6212 | static constexpr unsigned Invalid = std::numeric_limits<unsigned>::max(); | |||
6213 | assert(Aggregate.getKind() == ResultCandidate::CK_Aggregate)(static_cast <bool> (Aggregate.getKind() == ResultCandidate ::CK_Aggregate) ? void (0) : __assert_fail ("Aggregate.getKind() == ResultCandidate::CK_Aggregate" , "clang/lib/Sema/SemaCodeComplete.cpp", 6213, __extension__ __PRETTY_FUNCTION__ )); | |||
6214 | ||||
6215 | // Look for designated initializers. | |||
6216 | // They're in their syntactic form, not yet resolved to fields. | |||
6217 | const IdentifierInfo *DesignatedFieldName = nullptr; | |||
6218 | unsigned ArgsAfterDesignator = 0; | |||
6219 | for (const Expr *Arg : Args) { | |||
6220 | if (const auto *DIE = dyn_cast<DesignatedInitExpr>(Arg)) { | |||
6221 | if (DIE->size() == 1 && DIE->getDesignator(0)->isFieldDesignator()) { | |||
6222 | DesignatedFieldName = DIE->getDesignator(0)->getFieldName(); | |||
6223 | ArgsAfterDesignator = 0; | |||
6224 | } else { | |||
6225 | return Invalid; // Complicated designator. | |||
6226 | } | |||
6227 | } else if (isa<DesignatedInitUpdateExpr>(Arg)) { | |||
6228 | return Invalid; // Unsupported. | |||
6229 | } else { | |||
6230 | ++ArgsAfterDesignator; | |||
6231 | } | |||
6232 | } | |||
6233 | if (!DesignatedFieldName) | |||
6234 | return std::nullopt; | |||
6235 | ||||
6236 | // Find the index within the class's fields. | |||
6237 | // (Probing getParamDecl() directly would be quadratic in number of fields). | |||
6238 | unsigned DesignatedIndex = 0; | |||
6239 | const FieldDecl *DesignatedField = nullptr; | |||
6240 | for (const auto *Field : Aggregate.getAggregate()->fields()) { | |||
6241 | if (Field->getIdentifier() == DesignatedFieldName) { | |||
6242 | DesignatedField = Field; | |||
6243 | break; | |||
6244 | } | |||
6245 | ++DesignatedIndex; | |||
6246 | } | |||
6247 | if (!DesignatedField) | |||
6248 | return Invalid; // Designator referred to a missing field, give up. | |||
6249 | ||||
6250 | // Find the index within the aggregate (which may have leading bases). | |||
6251 | unsigned AggregateSize = Aggregate.getNumParams(); | |||
6252 | while (DesignatedIndex < AggregateSize && | |||
6253 | Aggregate.getParamDecl(DesignatedIndex) != DesignatedField) | |||
6254 | ++DesignatedIndex; | |||
6255 | ||||
6256 | // Continue from the index after the last named field. | |||
6257 | return DesignatedIndex + ArgsAfterDesignator + 1; | |||
6258 | } | |||
6259 | ||||
6260 | QualType Sema::ProduceConstructorSignatureHelp(QualType Type, | |||
6261 | SourceLocation Loc, | |||
6262 | ArrayRef<Expr *> Args, | |||
6263 | SourceLocation OpenParLoc, | |||
6264 | bool Braced) { | |||
6265 | if (!CodeCompleter) | |||
6266 | return QualType(); | |||
6267 | SmallVector<ResultCandidate, 8> Results; | |||
6268 | ||||
6269 | // A complete type is needed to lookup for constructors. | |||
6270 | RecordDecl *RD = | |||
6271 | isCompleteType(Loc, Type) ? Type->getAsRecordDecl() : nullptr; | |||
6272 | if (!RD) | |||
6273 | return Type; | |||
6274 | CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD); | |||
6275 | ||||
6276 | // Consider aggregate initialization. | |||
6277 | // We don't check that types so far are correct. | |||
6278 | // We also don't handle C99/C++17 brace-elision, we assume init-list elements | |||
6279 | // are 1:1 with fields. | |||
6280 | // FIXME: it would be nice to support "unwrapping" aggregates that contain | |||
6281 | // a single subaggregate, like std::array<T, N> -> T __elements[N]. | |||
6282 | if (Braced && !RD->isUnion() && | |||
6283 | (!LangOpts.CPlusPlus || (CRD && CRD->isAggregate()))) { | |||
6284 | ResultCandidate AggregateSig(RD); | |||
6285 | unsigned AggregateSize = AggregateSig.getNumParams(); | |||
6286 | ||||
6287 | if (auto NextIndex = | |||
6288 | getNextAggregateIndexAfterDesignatedInit(AggregateSig, Args)) { | |||
6289 | // A designator was used, only aggregate init is possible. | |||
6290 | if (*NextIndex >= AggregateSize) | |||
6291 | return Type; | |||
6292 | Results.push_back(AggregateSig); | |||
6293 | return ProduceSignatureHelp(*this, Results, *NextIndex, OpenParLoc, | |||
6294 | Braced); | |||
6295 | } | |||
6296 | ||||
6297 | // Describe aggregate initialization, but also constructors below. | |||
6298 | if (Args.size() < AggregateSize) | |||
6299 | Results.push_back(AggregateSig); | |||
6300 | } | |||
6301 | ||||
6302 | // FIXME: Provide support for member initializers. | |||
6303 | // FIXME: Provide support for variadic template constructors. | |||
6304 | ||||
6305 | if (CRD) { | |||
6306 | OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); | |||
6307 | for (NamedDecl *C : LookupConstructors(CRD)) { | |||
6308 | if (auto *FD = dyn_cast<FunctionDecl>(C)) { | |||
6309 | // FIXME: we can't yet provide correct signature help for initializer | |||
6310 | // list constructors, so skip them entirely. | |||
6311 | if (Braced && LangOpts.CPlusPlus && isInitListConstructor(FD)) | |||
6312 | continue; | |||
6313 | AddOverloadCandidate(FD, DeclAccessPair::make(FD, C->getAccess()), Args, | |||
6314 | CandidateSet, | |||
6315 | /*SuppressUserConversions=*/false, | |||
6316 | /*PartialOverloading=*/true, | |||
6317 | /*AllowExplicit*/ true); | |||
6318 | } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(C)) { | |||
6319 | if (Braced && LangOpts.CPlusPlus && | |||
6320 | isInitListConstructor(FTD->getTemplatedDecl())) | |||
6321 | continue; | |||
6322 | ||||
6323 | AddTemplateOverloadCandidate( | |||
6324 | FTD, DeclAccessPair::make(FTD, C->getAccess()), | |||
6325 | /*ExplicitTemplateArgs=*/nullptr, Args, CandidateSet, | |||
6326 | /*SuppressUserConversions=*/false, | |||
6327 | /*PartialOverloading=*/true); | |||
6328 | } | |||
6329 | } | |||
6330 | mergeCandidatesWithResults(*this, Results, CandidateSet, Loc, Args.size()); | |||
6331 | } | |||
6332 | ||||
6333 | return ProduceSignatureHelp(*this, Results, Args.size(), OpenParLoc, Braced); | |||
6334 | } | |||
6335 | ||||
6336 | QualType Sema::ProduceCtorInitMemberSignatureHelp( | |||
6337 | Decl *ConstructorDecl, CXXScopeSpec SS, ParsedType TemplateTypeTy, | |||
6338 | ArrayRef<Expr *> ArgExprs, IdentifierInfo *II, SourceLocation OpenParLoc, | |||
6339 | bool Braced) { | |||
6340 | if (!CodeCompleter) | |||
6341 | return QualType(); | |||
6342 | ||||
6343 | CXXConstructorDecl *Constructor = | |||
6344 | dyn_cast<CXXConstructorDecl>(ConstructorDecl); | |||
6345 | if (!Constructor) | |||
6346 | return QualType(); | |||
6347 | // FIXME: Add support for Base class constructors as well. | |||
6348 | if (ValueDecl *MemberDecl = tryLookupCtorInitMemberDecl( | |||
6349 | Constructor->getParent(), SS, TemplateTypeTy, II)) | |||
6350 | return ProduceConstructorSignatureHelp(MemberDecl->getType(), | |||
6351 | MemberDecl->getLocation(), ArgExprs, | |||
6352 | OpenParLoc, Braced); | |||
6353 | return QualType(); | |||
6354 | } | |||
6355 | ||||
6356 | static bool argMatchesTemplateParams(const ParsedTemplateArgument &Arg, | |||
6357 | unsigned Index, | |||
6358 | const TemplateParameterList &Params) { | |||
6359 | const NamedDecl *Param; | |||
6360 | if (Index < Params.size()) | |||
6361 | Param = Params.getParam(Index); | |||
6362 | else if (Params.hasParameterPack()) | |||
6363 | Param = Params.asArray().back(); | |||
6364 | else | |||
6365 | return false; // too many args | |||
6366 | ||||
6367 | switch (Arg.getKind()) { | |||
6368 | case ParsedTemplateArgument::Type: | |||
6369 | return llvm::isa<TemplateTypeParmDecl>(Param); // constraints not checked | |||
6370 | case ParsedTemplateArgument::NonType: | |||
6371 | return llvm::isa<NonTypeTemplateParmDecl>(Param); // type not checked | |||
6372 | case ParsedTemplateArgument::Template: | |||
6373 | return llvm::isa<TemplateTemplateParmDecl>(Param); // signature not checked | |||
6374 | } | |||
6375 | llvm_unreachable("Unhandled switch case")::llvm::llvm_unreachable_internal("Unhandled switch case", "clang/lib/Sema/SemaCodeComplete.cpp" , 6375); | |||
6376 | } | |||
6377 | ||||
6378 | QualType Sema::ProduceTemplateArgumentSignatureHelp( | |||
6379 | TemplateTy ParsedTemplate, ArrayRef<ParsedTemplateArgument> Args, | |||
6380 | SourceLocation LAngleLoc) { | |||
6381 | if (!CodeCompleter || !ParsedTemplate) | |||
6382 | return QualType(); | |||
6383 | ||||
6384 | SmallVector<ResultCandidate, 8> Results; | |||
6385 | auto Consider = [&](const TemplateDecl *TD) { | |||
6386 | // Only add if the existing args are compatible with the template. | |||
6387 | bool Matches = true; | |||
6388 | for (unsigned I = 0; I < Args.size(); ++I) { | |||
6389 | if (!argMatchesTemplateParams(Args[I], I, *TD->getTemplateParameters())) { | |||
6390 | Matches = false; | |||
6391 | break; | |||
6392 | } | |||
6393 | } | |||
6394 | if (Matches) | |||
6395 | Results.emplace_back(TD); | |||
6396 | }; | |||
6397 | ||||
6398 | TemplateName Template = ParsedTemplate.get(); | |||
6399 | if (const auto *TD = Template.getAsTemplateDecl()) { | |||
6400 | Consider(TD); | |||
6401 | } else if (const auto *OTS = Template.getAsOverloadedTemplate()) { | |||
6402 | for (const NamedDecl *ND : *OTS) | |||
6403 | if (const auto *TD = llvm::dyn_cast<TemplateDecl>(ND)) | |||
6404 | Consider(TD); | |||
6405 | } | |||
6406 | return ProduceSignatureHelp(*this, Results, Args.size(), LAngleLoc, | |||
6407 | /*Braced=*/false); | |||
6408 | } | |||
6409 | ||||
6410 | static QualType getDesignatedType(QualType BaseType, const Designation &Desig) { | |||
6411 | for (unsigned I = 0; I < Desig.getNumDesignators(); ++I) { | |||
6412 | if (BaseType.isNull()) | |||
6413 | break; | |||
6414 | QualType NextType; | |||
6415 | const auto &D = Desig.getDesignator(I); | |||
6416 | if (D.isArrayDesignator() || D.isArrayRangeDesignator()) { | |||
6417 | if (BaseType->isArrayType()) | |||
6418 | NextType = BaseType->getAsArrayTypeUnsafe()->getElementType(); | |||
6419 | } else { | |||
6420 | assert(D.isFieldDesignator())(static_cast <bool> (D.isFieldDesignator()) ? void (0) : __assert_fail ("D.isFieldDesignator()", "clang/lib/Sema/SemaCodeComplete.cpp" , 6420, __extension__ __PRETTY_FUNCTION__)); | |||
6421 | auto *RD = getAsRecordDecl(BaseType); | |||
6422 | if (RD && RD->isCompleteDefinition()) { | |||
6423 | for (const auto *Member : RD->lookup(D.getFieldDecl())) | |||
6424 | if (const FieldDecl *FD = llvm::dyn_cast<FieldDecl>(Member)) { | |||
6425 | NextType = FD->getType(); | |||
6426 | break; | |||
6427 | } | |||
6428 | } | |||
6429 | } | |||
6430 | BaseType = NextType; | |||
6431 | } | |||
6432 | return BaseType; | |||
6433 | } | |||
6434 | ||||
6435 | void Sema::CodeCompleteDesignator(QualType BaseType, | |||
6436 | llvm::ArrayRef<Expr *> InitExprs, | |||
6437 | const Designation &D) { | |||
6438 | BaseType = getDesignatedType(BaseType, D); | |||
6439 | if (BaseType.isNull()) | |||
6440 | return; | |||
6441 | const auto *RD = getAsRecordDecl(BaseType); | |||
6442 | if (!RD || RD->fields().empty()) | |||
6443 | return; | |||
6444 | ||||
6445 | CodeCompletionContext CCC(CodeCompletionContext::CCC_DotMemberAccess, | |||
6446 | BaseType); | |||
6447 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
6448 | CodeCompleter->getCodeCompletionTUInfo(), CCC); | |||
6449 | ||||
6450 | Results.EnterNewScope(); | |||
6451 | for (const Decl *D : RD->decls()) { | |||
6452 | const FieldDecl *FD; | |||
6453 | if (auto *IFD = dyn_cast<IndirectFieldDecl>(D)) | |||
6454 | FD = IFD->getAnonField(); | |||
6455 | else if (auto *DFD = dyn_cast<FieldDecl>(D)) | |||
6456 | FD = DFD; | |||
6457 | else | |||
6458 | continue; | |||
6459 | ||||
6460 | // FIXME: Make use of previous designators to mark any fields before those | |||
6461 | // inaccessible, and also compute the next initializer priority. | |||
6462 | ResultBuilder::Result Result(FD, Results.getBasePriority(FD)); | |||
6463 | Results.AddResult(Result, CurContext, /*Hiding=*/nullptr); | |||
6464 | } | |||
6465 | Results.ExitScope(); | |||
6466 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
6467 | Results.data(), Results.size()); | |||
6468 | } | |||
6469 | ||||
6470 | void Sema::CodeCompleteInitializer(Scope *S, Decl *D) { | |||
6471 | ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D); | |||
6472 | if (!VD) { | |||
6473 | CodeCompleteOrdinaryName(S, PCC_Expression); | |||
6474 | return; | |||
6475 | } | |||
6476 | ||||
6477 | CodeCompleteExpressionData Data; | |||
6478 | Data.PreferredType = VD->getType(); | |||
6479 | // Ignore VD to avoid completing the variable itself, e.g. in 'int foo = ^'. | |||
6480 | Data.IgnoreDecls.push_back(VD); | |||
6481 | ||||
6482 | CodeCompleteExpression(S, Data); | |||
6483 | } | |||
6484 | ||||
6485 | void Sema::CodeCompleteAfterIf(Scope *S, bool IsBracedThen) { | |||
6486 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
6487 | CodeCompleter->getCodeCompletionTUInfo(), | |||
6488 | mapCodeCompletionContext(*this, PCC_Statement)); | |||
6489 | Results.setFilter(&ResultBuilder::IsOrdinaryName); | |||
6490 | Results.EnterNewScope(); | |||
6491 | ||||
6492 | CodeCompletionDeclConsumer Consumer(Results, CurContext); | |||
6493 | LookupVisibleDecls(S, LookupOrdinaryName, Consumer, | |||
6494 | CodeCompleter->includeGlobals(), | |||
6495 | CodeCompleter->loadExternal()); | |||
6496 | ||||
6497 | AddOrdinaryNameResults(PCC_Statement, S, *this, Results); | |||
6498 | ||||
6499 | // "else" block | |||
6500 | CodeCompletionBuilder Builder(Results.getAllocator(), | |||
6501 | Results.getCodeCompletionTUInfo()); | |||
6502 | ||||
6503 | auto AddElseBodyPattern = [&] { | |||
6504 | if (IsBracedThen) { | |||
6505 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
6506 | Builder.AddChunk(CodeCompletionString::CK_LeftBrace); | |||
6507 | Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); | |||
6508 | Builder.AddPlaceholderChunk("statements"); | |||
6509 | Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); | |||
6510 | Builder.AddChunk(CodeCompletionString::CK_RightBrace); | |||
6511 | } else { | |||
6512 | Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); | |||
6513 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
6514 | Builder.AddPlaceholderChunk("statement"); | |||
6515 | Builder.AddChunk(CodeCompletionString::CK_SemiColon); | |||
6516 | } | |||
6517 | }; | |||
6518 | Builder.AddTypedTextChunk("else"); | |||
6519 | if (Results.includeCodePatterns()) | |||
6520 | AddElseBodyPattern(); | |||
6521 | Results.AddResult(Builder.TakeString()); | |||
6522 | ||||
6523 | // "else if" block | |||
6524 | Builder.AddTypedTextChunk("else if"); | |||
6525 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
6526 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
6527 | if (getLangOpts().CPlusPlus) | |||
6528 | Builder.AddPlaceholderChunk("condition"); | |||
6529 | else | |||
6530 | Builder.AddPlaceholderChunk("expression"); | |||
6531 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
6532 | if (Results.includeCodePatterns()) { | |||
6533 | AddElseBodyPattern(); | |||
6534 | } | |||
6535 | Results.AddResult(Builder.TakeString()); | |||
6536 | ||||
6537 | Results.ExitScope(); | |||
6538 | ||||
6539 | if (S->getFnParent()) | |||
6540 | AddPrettyFunctionResults(getLangOpts(), Results); | |||
6541 | ||||
6542 | if (CodeCompleter->includeMacros()) | |||
6543 | AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false); | |||
6544 | ||||
6545 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
6546 | Results.data(), Results.size()); | |||
6547 | } | |||
6548 | ||||
6549 | void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, | |||
6550 | bool EnteringContext, | |||
6551 | bool IsUsingDeclaration, QualType BaseType, | |||
6552 | QualType PreferredType) { | |||
6553 | if (SS.isEmpty() || !CodeCompleter) | |||
6554 | return; | |||
6555 | ||||
6556 | CodeCompletionContext CC(CodeCompletionContext::CCC_Symbol, PreferredType); | |||
6557 | CC.setIsUsingDeclaration(IsUsingDeclaration); | |||
6558 | CC.setCXXScopeSpecifier(SS); | |||
6559 | ||||
6560 | // We want to keep the scope specifier even if it's invalid (e.g. the scope | |||
6561 | // "a::b::" is not corresponding to any context/namespace in the AST), since | |||
6562 | // it can be useful for global code completion which have information about | |||
6563 | // contexts/symbols that are not in the AST. | |||
6564 | if (SS.isInvalid()) { | |||
6565 | // As SS is invalid, we try to collect accessible contexts from the current | |||
6566 | // scope with a dummy lookup so that the completion consumer can try to | |||
6567 | // guess what the specified scope is. | |||
6568 | ResultBuilder DummyResults(*this, CodeCompleter->getAllocator(), | |||
6569 | CodeCompleter->getCodeCompletionTUInfo(), CC); | |||
6570 | if (!PreferredType.isNull()) | |||
6571 | DummyResults.setPreferredType(PreferredType); | |||
6572 | if (S->getEntity()) { | |||
6573 | CodeCompletionDeclConsumer Consumer(DummyResults, S->getEntity(), | |||
6574 | BaseType); | |||
6575 | LookupVisibleDecls(S, LookupOrdinaryName, Consumer, | |||
6576 | /*IncludeGlobalScope=*/false, | |||
6577 | /*LoadExternal=*/false); | |||
6578 | } | |||
6579 | HandleCodeCompleteResults(this, CodeCompleter, | |||
6580 | DummyResults.getCompletionContext(), nullptr, 0); | |||
6581 | return; | |||
6582 | } | |||
6583 | // Always pretend to enter a context to ensure that a dependent type | |||
6584 | // resolves to a dependent record. | |||
6585 | DeclContext *Ctx = computeDeclContext(SS, /*EnteringContext=*/true); | |||
6586 | ||||
6587 | // Try to instantiate any non-dependent declaration contexts before | |||
6588 | // we look in them. Bail out if we fail. | |||
6589 | NestedNameSpecifier *NNS = SS.getScopeRep(); | |||
6590 | if (NNS != nullptr && SS.isValid() && !NNS->isDependent()) { | |||
6591 | if (Ctx == nullptr || RequireCompleteDeclContext(SS, Ctx)) | |||
6592 | return; | |||
6593 | } | |||
6594 | ||||
6595 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
6596 | CodeCompleter->getCodeCompletionTUInfo(), CC); | |||
6597 | if (!PreferredType.isNull()) | |||
6598 | Results.setPreferredType(PreferredType); | |||
6599 | Results.EnterNewScope(); | |||
6600 | ||||
6601 | // The "template" keyword can follow "::" in the grammar, but only | |||
6602 | // put it into the grammar if the nested-name-specifier is dependent. | |||
6603 | // FIXME: results is always empty, this appears to be dead. | |||
6604 | if (!Results.empty() && NNS->isDependent()) | |||
6605 | Results.AddResult("template"); | |||
6606 | ||||
6607 | // If the scope is a concept-constrained type parameter, infer nested | |||
6608 | // members based on the constraints. | |||
6609 | if (const auto *TTPT = | |||
6610 | dyn_cast_or_null<TemplateTypeParmType>(NNS->getAsType())) { | |||
6611 | for (const auto &R : ConceptInfo(*TTPT, S).members()) { | |||
6612 | if (R.Operator != ConceptInfo::Member::Colons) | |||
6613 | continue; | |||
6614 | Results.AddResult(CodeCompletionResult( | |||
6615 | R.render(*this, CodeCompleter->getAllocator(), | |||
6616 | CodeCompleter->getCodeCompletionTUInfo()))); | |||
6617 | } | |||
6618 | } | |||
6619 | ||||
6620 | // Add calls to overridden virtual functions, if there are any. | |||
6621 | // | |||
6622 | // FIXME: This isn't wonderful, because we don't know whether we're actually | |||
6623 | // in a context that permits expressions. This is a general issue with | |||
6624 | // qualified-id completions. | |||
6625 | if (Ctx && !EnteringContext) | |||
6626 | MaybeAddOverrideCalls(*this, Ctx, Results); | |||
6627 | Results.ExitScope(); | |||
6628 | ||||
6629 | if (Ctx && | |||
6630 | (CodeCompleter->includeNamespaceLevelDecls() || !Ctx->isFileContext())) { | |||
6631 | CodeCompletionDeclConsumer Consumer(Results, Ctx, BaseType); | |||
6632 | LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer, | |||
6633 | /*IncludeGlobalScope=*/true, | |||
6634 | /*IncludeDependentBases=*/true, | |||
6635 | CodeCompleter->loadExternal()); | |||
6636 | } | |||
6637 | ||||
6638 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
6639 | Results.data(), Results.size()); | |||
6640 | } | |||
6641 | ||||
6642 | void Sema::CodeCompleteUsing(Scope *S) { | |||
6643 | if (!CodeCompleter) | |||
6644 | return; | |||
6645 | ||||
6646 | // This can be both a using alias or using declaration, in the former we | |||
6647 | // expect a new name and a symbol in the latter case. | |||
6648 | CodeCompletionContext Context(CodeCompletionContext::CCC_SymbolOrNewName); | |||
6649 | Context.setIsUsingDeclaration(true); | |||
6650 | ||||
6651 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
6652 | CodeCompleter->getCodeCompletionTUInfo(), Context, | |||
6653 | &ResultBuilder::IsNestedNameSpecifier); | |||
6654 | Results.EnterNewScope(); | |||
6655 | ||||
6656 | // If we aren't in class scope, we could see the "namespace" keyword. | |||
6657 | if (!S->isClassScope()) | |||
6658 | Results.AddResult(CodeCompletionResult("namespace")); | |||
6659 | ||||
6660 | // After "using", we can see anything that would start a | |||
6661 | // nested-name-specifier. | |||
6662 | CodeCompletionDeclConsumer Consumer(Results, CurContext); | |||
6663 | LookupVisibleDecls(S, LookupOrdinaryName, Consumer, | |||
6664 | CodeCompleter->includeGlobals(), | |||
6665 | CodeCompleter->loadExternal()); | |||
6666 | Results.ExitScope(); | |||
6667 | ||||
6668 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
6669 | Results.data(), Results.size()); | |||
6670 | } | |||
6671 | ||||
6672 | void Sema::CodeCompleteUsingDirective(Scope *S) { | |||
6673 | if (!CodeCompleter) | |||
6674 | return; | |||
6675 | ||||
6676 | // After "using namespace", we expect to see a namespace name or namespace | |||
6677 | // alias. | |||
6678 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
6679 | CodeCompleter->getCodeCompletionTUInfo(), | |||
6680 | CodeCompletionContext::CCC_Namespace, | |||
6681 | &ResultBuilder::IsNamespaceOrAlias); | |||
6682 | Results.EnterNewScope(); | |||
6683 | CodeCompletionDeclConsumer Consumer(Results, CurContext); | |||
6684 | LookupVisibleDecls(S, LookupOrdinaryName, Consumer, | |||
6685 | CodeCompleter->includeGlobals(), | |||
6686 | CodeCompleter->loadExternal()); | |||
6687 | Results.ExitScope(); | |||
6688 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
6689 | Results.data(), Results.size()); | |||
6690 | } | |||
6691 | ||||
6692 | void Sema::CodeCompleteNamespaceDecl(Scope *S) { | |||
6693 | if (!CodeCompleter) | |||
6694 | return; | |||
6695 | ||||
6696 | DeclContext *Ctx = S->getEntity(); | |||
6697 | if (!S->getParent()) | |||
6698 | Ctx = Context.getTranslationUnitDecl(); | |||
6699 | ||||
6700 | bool SuppressedGlobalResults = | |||
6701 | Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx); | |||
6702 | ||||
6703 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
6704 | CodeCompleter->getCodeCompletionTUInfo(), | |||
6705 | SuppressedGlobalResults | |||
6706 | ? CodeCompletionContext::CCC_Namespace | |||
6707 | : CodeCompletionContext::CCC_Other, | |||
6708 | &ResultBuilder::IsNamespace); | |||
6709 | ||||
6710 | if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) { | |||
6711 | // We only want to see those namespaces that have already been defined | |||
6712 | // within this scope, because its likely that the user is creating an | |||
6713 | // extended namespace declaration. Keep track of the most recent | |||
6714 | // definition of each namespace. | |||
6715 | std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest; | |||
6716 | for (DeclContext::specific_decl_iterator<NamespaceDecl> | |||
6717 | NS(Ctx->decls_begin()), | |||
6718 | NSEnd(Ctx->decls_end()); | |||
6719 | NS != NSEnd; ++NS) | |||
6720 | OrigToLatest[NS->getOriginalNamespace()] = *NS; | |||
6721 | ||||
6722 | // Add the most recent definition (or extended definition) of each | |||
6723 | // namespace to the list of results. | |||
6724 | Results.EnterNewScope(); | |||
6725 | for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator | |||
6726 | NS = OrigToLatest.begin(), | |||
6727 | NSEnd = OrigToLatest.end(); | |||
6728 | NS != NSEnd; ++NS) | |||
6729 | Results.AddResult( | |||
6730 | CodeCompletionResult(NS->second, Results.getBasePriority(NS->second), | |||
6731 | nullptr), | |||
6732 | CurContext, nullptr, false); | |||
6733 | Results.ExitScope(); | |||
6734 | } | |||
6735 | ||||
6736 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
6737 | Results.data(), Results.size()); | |||
6738 | } | |||
6739 | ||||
6740 | void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) { | |||
6741 | if (!CodeCompleter) | |||
6742 | return; | |||
6743 | ||||
6744 | // After "namespace", we expect to see a namespace or alias. | |||
6745 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
6746 | CodeCompleter->getCodeCompletionTUInfo(), | |||
6747 | CodeCompletionContext::CCC_Namespace, | |||
6748 | &ResultBuilder::IsNamespaceOrAlias); | |||
6749 | CodeCompletionDeclConsumer Consumer(Results, CurContext); | |||
6750 | LookupVisibleDecls(S, LookupOrdinaryName, Consumer, | |||
6751 | CodeCompleter->includeGlobals(), | |||
6752 | CodeCompleter->loadExternal()); | |||
6753 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
6754 | Results.data(), Results.size()); | |||
6755 | } | |||
6756 | ||||
6757 | void Sema::CodeCompleteOperatorName(Scope *S) { | |||
6758 | if (!CodeCompleter) | |||
6759 | return; | |||
6760 | ||||
6761 | typedef CodeCompletionResult Result; | |||
6762 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
6763 | CodeCompleter->getCodeCompletionTUInfo(), | |||
6764 | CodeCompletionContext::CCC_Type, | |||
6765 | &ResultBuilder::IsType); | |||
6766 | Results.EnterNewScope(); | |||
6767 | ||||
6768 | // Add the names of overloadable operators. Note that OO_Conditional is not | |||
6769 | // actually overloadable. | |||
6770 | #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \ | |||
6771 | if (OO_##Name != OO_Conditional) \ | |||
6772 | Results.AddResult(Result(Spelling)); | |||
6773 | #include "clang/Basic/OperatorKinds.def" | |||
6774 | ||||
6775 | // Add any type names visible from the current scope | |||
6776 | Results.allowNestedNameSpecifiers(); | |||
6777 | CodeCompletionDeclConsumer Consumer(Results, CurContext); | |||
6778 | LookupVisibleDecls(S, LookupOrdinaryName, Consumer, | |||
6779 | CodeCompleter->includeGlobals(), | |||
6780 | CodeCompleter->loadExternal()); | |||
6781 | ||||
6782 | // Add any type specifiers | |||
6783 | AddTypeSpecifierResults(getLangOpts(), Results); | |||
6784 | Results.ExitScope(); | |||
6785 | ||||
6786 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
6787 | Results.data(), Results.size()); | |||
6788 | } | |||
6789 | ||||
6790 | void Sema::CodeCompleteConstructorInitializer( | |||
6791 | Decl *ConstructorD, ArrayRef<CXXCtorInitializer *> Initializers) { | |||
6792 | if (!ConstructorD) | |||
6793 | return; | |||
6794 | ||||
6795 | AdjustDeclIfTemplate(ConstructorD); | |||
6796 | ||||
6797 | auto *Constructor = dyn_cast<CXXConstructorDecl>(ConstructorD); | |||
6798 | if (!Constructor) | |||
6799 | return; | |||
6800 | ||||
6801 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
6802 | CodeCompleter->getCodeCompletionTUInfo(), | |||
6803 | CodeCompletionContext::CCC_Symbol); | |||
6804 | Results.EnterNewScope(); | |||
6805 | ||||
6806 | // Fill in any already-initialized fields or base classes. | |||
6807 | llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields; | |||
6808 | llvm::SmallPtrSet<CanQualType, 4> InitializedBases; | |||
6809 | for (unsigned I = 0, E = Initializers.size(); I != E; ++I) { | |||
6810 | if (Initializers[I]->isBaseInitializer()) | |||
6811 | InitializedBases.insert(Context.getCanonicalType( | |||
6812 | QualType(Initializers[I]->getBaseClass(), 0))); | |||
6813 | else | |||
6814 | InitializedFields.insert( | |||
6815 | cast<FieldDecl>(Initializers[I]->getAnyMember())); | |||
6816 | } | |||
6817 | ||||
6818 | // Add completions for base classes. | |||
6819 | PrintingPolicy Policy = getCompletionPrintingPolicy(*this); | |||
6820 | bool SawLastInitializer = Initializers.empty(); | |||
6821 | CXXRecordDecl *ClassDecl = Constructor->getParent(); | |||
6822 | ||||
6823 | auto GenerateCCS = [&](const NamedDecl *ND, const char *Name) { | |||
6824 | CodeCompletionBuilder Builder(Results.getAllocator(), | |||
6825 | Results.getCodeCompletionTUInfo()); | |||
6826 | Builder.AddTypedTextChunk(Name); | |||
6827 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
6828 | if (const auto *Function = dyn_cast<FunctionDecl>(ND)) | |||
6829 | AddFunctionParameterChunks(PP, Policy, Function, Builder); | |||
6830 | else if (const auto *FunTemplDecl = dyn_cast<FunctionTemplateDecl>(ND)) | |||
6831 | AddFunctionParameterChunks(PP, Policy, FunTemplDecl->getTemplatedDecl(), | |||
6832 | Builder); | |||
6833 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
6834 | return Builder.TakeString(); | |||
6835 | }; | |||
6836 | auto AddDefaultCtorInit = [&](const char *Name, const char *Type, | |||
6837 | const NamedDecl *ND) { | |||
6838 | CodeCompletionBuilder Builder(Results.getAllocator(), | |||
6839 | Results.getCodeCompletionTUInfo()); | |||
6840 | Builder.AddTypedTextChunk(Name); | |||
6841 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
6842 | Builder.AddPlaceholderChunk(Type); | |||
6843 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
6844 | if (ND) { | |||
6845 | auto CCR = CodeCompletionResult( | |||
6846 | Builder.TakeString(), ND, | |||
6847 | SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration); | |||
6848 | if (isa<FieldDecl>(ND)) | |||
6849 | CCR.CursorKind = CXCursor_MemberRef; | |||
6850 | return Results.AddResult(CCR); | |||
6851 | } | |||
6852 | return Results.AddResult(CodeCompletionResult( | |||
6853 | Builder.TakeString(), | |||
6854 | SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration)); | |||
6855 | }; | |||
6856 | auto AddCtorsWithName = [&](const CXXRecordDecl *RD, unsigned int Priority, | |||
6857 | const char *Name, const FieldDecl *FD) { | |||
6858 | if (!RD) | |||
6859 | return AddDefaultCtorInit(Name, | |||
6860 | FD ? Results.getAllocator().CopyString( | |||
6861 | FD->getType().getAsString(Policy)) | |||
6862 | : Name, | |||
6863 | FD); | |||
6864 | auto Ctors = getConstructors(Context, RD); | |||
6865 | if (Ctors.begin() == Ctors.end()) | |||
6866 | return AddDefaultCtorInit(Name, Name, RD); | |||
6867 | for (const NamedDecl *Ctor : Ctors) { | |||
6868 | auto CCR = CodeCompletionResult(GenerateCCS(Ctor, Name), RD, Priority); | |||
6869 | CCR.CursorKind = getCursorKindForDecl(Ctor); | |||
6870 | Results.AddResult(CCR); | |||
6871 | } | |||
6872 | }; | |||
6873 | auto AddBase = [&](const CXXBaseSpecifier &Base) { | |||
6874 | const char *BaseName = | |||
6875 | Results.getAllocator().CopyString(Base.getType().getAsString(Policy)); | |||
6876 | const auto *RD = Base.getType()->getAsCXXRecordDecl(); | |||
6877 | AddCtorsWithName( | |||
6878 | RD, SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration, | |||
6879 | BaseName, nullptr); | |||
6880 | }; | |||
6881 | auto AddField = [&](const FieldDecl *FD) { | |||
6882 | const char *FieldName = | |||
6883 | Results.getAllocator().CopyString(FD->getIdentifier()->getName()); | |||
6884 | const CXXRecordDecl *RD = FD->getType()->getAsCXXRecordDecl(); | |||
6885 | AddCtorsWithName( | |||
6886 | RD, SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration, | |||
6887 | FieldName, FD); | |||
6888 | }; | |||
6889 | ||||
6890 | for (const auto &Base : ClassDecl->bases()) { | |||
6891 | if (!InitializedBases.insert(Context.getCanonicalType(Base.getType())) | |||
6892 | .second) { | |||
6893 | SawLastInitializer = | |||
6894 | !Initializers.empty() && Initializers.back()->isBaseInitializer() && | |||
6895 | Context.hasSameUnqualifiedType( | |||
6896 | Base.getType(), QualType(Initializers.back()->getBaseClass(), 0)); | |||
6897 | continue; | |||
6898 | } | |||
6899 | ||||
6900 | AddBase(Base); | |||
6901 | SawLastInitializer = false; | |||
6902 | } | |||
6903 | ||||
6904 | // Add completions for virtual base classes. | |||
6905 | for (const auto &Base : ClassDecl->vbases()) { | |||
6906 | if (!InitializedBases.insert(Context.getCanonicalType(Base.getType())) | |||
6907 | .second) { | |||
6908 | SawLastInitializer = | |||
6909 | !Initializers.empty() && Initializers.back()->isBaseInitializer() && | |||
6910 | Context.hasSameUnqualifiedType( | |||
6911 | Base.getType(), QualType(Initializers.back()->getBaseClass(), 0)); | |||
6912 | continue; | |||
6913 | } | |||
6914 | ||||
6915 | AddBase(Base); | |||
6916 | SawLastInitializer = false; | |||
6917 | } | |||
6918 | ||||
6919 | // Add completions for members. | |||
6920 | for (auto *Field : ClassDecl->fields()) { | |||
6921 | if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl())) | |||
6922 | .second) { | |||
6923 | SawLastInitializer = !Initializers.empty() && | |||
6924 | Initializers.back()->isAnyMemberInitializer() && | |||
6925 | Initializers.back()->getAnyMember() == Field; | |||
6926 | continue; | |||
6927 | } | |||
6928 | ||||
6929 | if (!Field->getDeclName()) | |||
6930 | continue; | |||
6931 | ||||
6932 | AddField(Field); | |||
6933 | SawLastInitializer = false; | |||
6934 | } | |||
6935 | Results.ExitScope(); | |||
6936 | ||||
6937 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
6938 | Results.data(), Results.size()); | |||
6939 | } | |||
6940 | ||||
6941 | /// Determine whether this scope denotes a namespace. | |||
6942 | static bool isNamespaceScope(Scope *S) { | |||
6943 | DeclContext *DC = S->getEntity(); | |||
6944 | if (!DC) | |||
6945 | return false; | |||
6946 | ||||
6947 | return DC->isFileContext(); | |||
6948 | } | |||
6949 | ||||
6950 | void Sema::CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro, | |||
6951 | bool AfterAmpersand) { | |||
6952 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
6953 | CodeCompleter->getCodeCompletionTUInfo(), | |||
6954 | CodeCompletionContext::CCC_Other); | |||
6955 | Results.EnterNewScope(); | |||
6956 | ||||
6957 | // Note what has already been captured. | |||
6958 | llvm::SmallPtrSet<IdentifierInfo *, 4> Known; | |||
6959 | bool IncludedThis = false; | |||
6960 | for (const auto &C : Intro.Captures) { | |||
6961 | if (C.Kind == LCK_This) { | |||
6962 | IncludedThis = true; | |||
6963 | continue; | |||
6964 | } | |||
6965 | ||||
6966 | Known.insert(C.Id); | |||
6967 | } | |||
6968 | ||||
6969 | // Look for other capturable variables. | |||
6970 | for (; S && !isNamespaceScope(S); S = S->getParent()) { | |||
6971 | for (const auto *D : S->decls()) { | |||
6972 | const auto *Var = dyn_cast<VarDecl>(D); | |||
6973 | if (!Var || !Var->hasLocalStorage() || Var->hasAttr<BlocksAttr>()) | |||
6974 | continue; | |||
6975 | ||||
6976 | if (Known.insert(Var->getIdentifier()).second) | |||
6977 | Results.AddResult(CodeCompletionResult(Var, CCP_LocalDeclaration), | |||
6978 | CurContext, nullptr, false); | |||
6979 | } | |||
6980 | } | |||
6981 | ||||
6982 | // Add 'this', if it would be valid. | |||
6983 | if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy) | |||
6984 | addThisCompletion(*this, Results); | |||
6985 | ||||
6986 | Results.ExitScope(); | |||
6987 | ||||
6988 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
6989 | Results.data(), Results.size()); | |||
6990 | } | |||
6991 | ||||
6992 | void Sema::CodeCompleteAfterFunctionEquals(Declarator &D) { | |||
6993 | if (!LangOpts.CPlusPlus11) | |||
6994 | return; | |||
6995 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
6996 | CodeCompleter->getCodeCompletionTUInfo(), | |||
6997 | CodeCompletionContext::CCC_Other); | |||
6998 | auto ShouldAddDefault = [&D, this]() { | |||
6999 | if (!D.isFunctionDeclarator()) | |||
7000 | return false; | |||
7001 | auto &Id = D.getName(); | |||
7002 | if (Id.getKind() == UnqualifiedIdKind::IK_DestructorName) | |||
7003 | return true; | |||
7004 | // FIXME(liuhui): Ideally, we should check the constructor parameter list to | |||
7005 | // verify that it is the default, copy or move constructor? | |||
7006 | if (Id.getKind() == UnqualifiedIdKind::IK_ConstructorName && | |||
7007 | D.getFunctionTypeInfo().NumParams <= 1) | |||
7008 | return true; | |||
7009 | if (Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId) { | |||
7010 | auto Op = Id.OperatorFunctionId.Operator; | |||
7011 | // FIXME(liuhui): Ideally, we should check the function parameter list to | |||
7012 | // verify that it is the copy or move assignment? | |||
7013 | if (Op == OverloadedOperatorKind::OO_Equal) | |||
7014 | return true; | |||
7015 | if (LangOpts.CPlusPlus20 && | |||
7016 | (Op == OverloadedOperatorKind::OO_EqualEqual || | |||
7017 | Op == OverloadedOperatorKind::OO_ExclaimEqual || | |||
7018 | Op == OverloadedOperatorKind::OO_Less || | |||
7019 | Op == OverloadedOperatorKind::OO_LessEqual || | |||
7020 | Op == OverloadedOperatorKind::OO_Greater || | |||
7021 | Op == OverloadedOperatorKind::OO_GreaterEqual || | |||
7022 | Op == OverloadedOperatorKind::OO_Spaceship)) | |||
7023 | return true; | |||
7024 | } | |||
7025 | return false; | |||
7026 | }; | |||
7027 | ||||
7028 | Results.EnterNewScope(); | |||
7029 | if (ShouldAddDefault()) | |||
7030 | Results.AddResult("default"); | |||
7031 | // FIXME(liuhui): Ideally, we should only provide `delete` completion for the | |||
7032 | // first function declaration. | |||
7033 | Results.AddResult("delete"); | |||
7034 | Results.ExitScope(); | |||
7035 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
7036 | Results.data(), Results.size()); | |||
7037 | } | |||
7038 | ||||
7039 | /// Macro that optionally prepends an "@" to the string literal passed in via | |||
7040 | /// Keyword, depending on whether NeedAt is true or false. | |||
7041 | #define OBJC_AT_KEYWORD_NAME(NeedAt, Keyword)((NeedAt) ? "@" Keyword : Keyword) ((NeedAt) ? "@" Keyword : Keyword) | |||
7042 | ||||
7043 | static void AddObjCImplementationResults(const LangOptions &LangOpts, | |||
7044 | ResultBuilder &Results, bool NeedAt) { | |||
7045 | typedef CodeCompletionResult Result; | |||
7046 | // Since we have an implementation, we can end it. | |||
7047 | Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "end")((NeedAt) ? "@" "end" : "end"))); | |||
7048 | ||||
7049 | CodeCompletionBuilder Builder(Results.getAllocator(), | |||
7050 | Results.getCodeCompletionTUInfo()); | |||
7051 | if (LangOpts.ObjC) { | |||
7052 | // @dynamic | |||
7053 | Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "dynamic")((NeedAt) ? "@" "dynamic" : "dynamic")); | |||
7054 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
7055 | Builder.AddPlaceholderChunk("property"); | |||
7056 | Results.AddResult(Result(Builder.TakeString())); | |||
7057 | ||||
7058 | // @synthesize | |||
7059 | Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "synthesize")((NeedAt) ? "@" "synthesize" : "synthesize")); | |||
7060 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
7061 | Builder.AddPlaceholderChunk("property"); | |||
7062 | Results.AddResult(Result(Builder.TakeString())); | |||
7063 | } | |||
7064 | } | |||
7065 | ||||
7066 | static void AddObjCInterfaceResults(const LangOptions &LangOpts, | |||
7067 | ResultBuilder &Results, bool NeedAt) { | |||
7068 | typedef CodeCompletionResult Result; | |||
7069 | ||||
7070 | // Since we have an interface or protocol, we can end it. | |||
7071 | Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "end")((NeedAt) ? "@" "end" : "end"))); | |||
7072 | ||||
7073 | if (LangOpts.ObjC) { | |||
7074 | // @property | |||
7075 | Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "property")((NeedAt) ? "@" "property" : "property"))); | |||
7076 | ||||
7077 | // @required | |||
7078 | Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "required")((NeedAt) ? "@" "required" : "required"))); | |||
7079 | ||||
7080 | // @optional | |||
7081 | Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "optional")((NeedAt) ? "@" "optional" : "optional"))); | |||
7082 | } | |||
7083 | } | |||
7084 | ||||
7085 | static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) { | |||
7086 | typedef CodeCompletionResult Result; | |||
7087 | CodeCompletionBuilder Builder(Results.getAllocator(), | |||
7088 | Results.getCodeCompletionTUInfo()); | |||
7089 | ||||
7090 | // @class name ; | |||
7091 | Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "class")((NeedAt) ? "@" "class" : "class")); | |||
7092 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
7093 | Builder.AddPlaceholderChunk("name"); | |||
7094 | Results.AddResult(Result(Builder.TakeString())); | |||
7095 | ||||
7096 | if (Results.includeCodePatterns()) { | |||
7097 | // @interface name | |||
7098 | // FIXME: Could introduce the whole pattern, including superclasses and | |||
7099 | // such. | |||
7100 | Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "interface")((NeedAt) ? "@" "interface" : "interface")); | |||
7101 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
7102 | Builder.AddPlaceholderChunk("class"); | |||
7103 | Results.AddResult(Result(Builder.TakeString())); | |||
7104 | ||||
7105 | // @protocol name | |||
7106 | Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "protocol")((NeedAt) ? "@" "protocol" : "protocol")); | |||
7107 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
7108 | Builder.AddPlaceholderChunk("protocol"); | |||
7109 | Results.AddResult(Result(Builder.TakeString())); | |||
7110 | ||||
7111 | // @implementation name | |||
7112 | Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "implementation")((NeedAt) ? "@" "implementation" : "implementation")); | |||
7113 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
7114 | Builder.AddPlaceholderChunk("class"); | |||
7115 | Results.AddResult(Result(Builder.TakeString())); | |||
7116 | } | |||
7117 | ||||
7118 | // @compatibility_alias name | |||
7119 | Builder.AddTypedTextChunk( | |||
7120 | OBJC_AT_KEYWORD_NAME(NeedAt, "compatibility_alias")((NeedAt) ? "@" "compatibility_alias" : "compatibility_alias" )); | |||
7121 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
7122 | Builder.AddPlaceholderChunk("alias"); | |||
7123 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
7124 | Builder.AddPlaceholderChunk("class"); | |||
7125 | Results.AddResult(Result(Builder.TakeString())); | |||
7126 | ||||
7127 | if (Results.getSema().getLangOpts().Modules) { | |||
7128 | // @import name | |||
7129 | Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "import")((NeedAt) ? "@" "import" : "import")); | |||
7130 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
7131 | Builder.AddPlaceholderChunk("module"); | |||
7132 | Results.AddResult(Result(Builder.TakeString())); | |||
7133 | } | |||
7134 | } | |||
7135 | ||||
7136 | void Sema::CodeCompleteObjCAtDirective(Scope *S) { | |||
7137 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
7138 | CodeCompleter->getCodeCompletionTUInfo(), | |||
7139 | CodeCompletionContext::CCC_Other); | |||
7140 | Results.EnterNewScope(); | |||
7141 | if (isa<ObjCImplDecl>(CurContext)) | |||
7142 | AddObjCImplementationResults(getLangOpts(), Results, false); | |||
7143 | else if (CurContext->isObjCContainer()) | |||
7144 | AddObjCInterfaceResults(getLangOpts(), Results, false); | |||
7145 | else | |||
7146 | AddObjCTopLevelResults(Results, false); | |||
7147 | Results.ExitScope(); | |||
7148 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
7149 | Results.data(), Results.size()); | |||
7150 | } | |||
7151 | ||||
7152 | static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) { | |||
7153 | typedef CodeCompletionResult Result; | |||
7154 | CodeCompletionBuilder Builder(Results.getAllocator(), | |||
7155 | Results.getCodeCompletionTUInfo()); | |||
7156 | ||||
7157 | // @encode ( type-name ) | |||
7158 | const char *EncodeType = "char[]"; | |||
7159 | if (Results.getSema().getLangOpts().CPlusPlus || | |||
7160 | Results.getSema().getLangOpts().ConstStrings) | |||
7161 | EncodeType = "const char[]"; | |||
7162 | Builder.AddResultTypeChunk(EncodeType); | |||
7163 | Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "encode")((NeedAt) ? "@" "encode" : "encode")); | |||
7164 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
7165 | Builder.AddPlaceholderChunk("type-name"); | |||
7166 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
7167 | Results.AddResult(Result(Builder.TakeString())); | |||
7168 | ||||
7169 | // @protocol ( protocol-name ) | |||
7170 | Builder.AddResultTypeChunk("Protocol *"); | |||
7171 | Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "protocol")((NeedAt) ? "@" "protocol" : "protocol")); | |||
7172 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
7173 | Builder.AddPlaceholderChunk("protocol-name"); | |||
7174 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
7175 | Results.AddResult(Result(Builder.TakeString())); | |||
7176 | ||||
7177 | // @selector ( selector ) | |||
7178 | Builder.AddResultTypeChunk("SEL"); | |||
7179 | Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "selector")((NeedAt) ? "@" "selector" : "selector")); | |||
7180 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
7181 | Builder.AddPlaceholderChunk("selector"); | |||
7182 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
7183 | Results.AddResult(Result(Builder.TakeString())); | |||
7184 | ||||
7185 | // @"string" | |||
7186 | Builder.AddResultTypeChunk("NSString *"); | |||
7187 | Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "\"")((NeedAt) ? "@" "\"" : "\"")); | |||
7188 | Builder.AddPlaceholderChunk("string"); | |||
7189 | Builder.AddTextChunk("\""); | |||
7190 | Results.AddResult(Result(Builder.TakeString())); | |||
7191 | ||||
7192 | // @[objects, ...] | |||
7193 | Builder.AddResultTypeChunk("NSArray *"); | |||
7194 | Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "[")((NeedAt) ? "@" "[" : "[")); | |||
7195 | Builder.AddPlaceholderChunk("objects, ..."); | |||
7196 | Builder.AddChunk(CodeCompletionString::CK_RightBracket); | |||
7197 | Results.AddResult(Result(Builder.TakeString())); | |||
7198 | ||||
7199 | // @{key : object, ...} | |||
7200 | Builder.AddResultTypeChunk("NSDictionary *"); | |||
7201 | Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "{")((NeedAt) ? "@" "{" : "{")); | |||
7202 | Builder.AddPlaceholderChunk("key"); | |||
7203 | Builder.AddChunk(CodeCompletionString::CK_Colon); | |||
7204 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
7205 | Builder.AddPlaceholderChunk("object, ..."); | |||
7206 | Builder.AddChunk(CodeCompletionString::CK_RightBrace); | |||
7207 | Results.AddResult(Result(Builder.TakeString())); | |||
7208 | ||||
7209 | // @(expression) | |||
7210 | Builder.AddResultTypeChunk("id"); | |||
7211 | Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "(")((NeedAt) ? "@" "(" : "(")); | |||
7212 | Builder.AddPlaceholderChunk("expression"); | |||
7213 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
7214 | Results.AddResult(Result(Builder.TakeString())); | |||
7215 | } | |||
7216 | ||||
7217 | static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) { | |||
7218 | typedef CodeCompletionResult Result; | |||
7219 | CodeCompletionBuilder Builder(Results.getAllocator(), | |||
7220 | Results.getCodeCompletionTUInfo()); | |||
7221 | ||||
7222 | if (Results.includeCodePatterns()) { | |||
7223 | // @try { statements } @catch ( declaration ) { statements } @finally | |||
7224 | // { statements } | |||
7225 | Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "try")((NeedAt) ? "@" "try" : "try")); | |||
7226 | Builder.AddChunk(CodeCompletionString::CK_LeftBrace); | |||
7227 | Builder.AddPlaceholderChunk("statements"); | |||
7228 | Builder.AddChunk(CodeCompletionString::CK_RightBrace); | |||
7229 | Builder.AddTextChunk("@catch"); | |||
7230 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
7231 | Builder.AddPlaceholderChunk("parameter"); | |||
7232 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
7233 | Builder.AddChunk(CodeCompletionString::CK_LeftBrace); | |||
7234 | Builder.AddPlaceholderChunk("statements"); | |||
7235 | Builder.AddChunk(CodeCompletionString::CK_RightBrace); | |||
7236 | Builder.AddTextChunk("@finally"); | |||
7237 | Builder.AddChunk(CodeCompletionString::CK_LeftBrace); | |||
7238 | Builder.AddPlaceholderChunk("statements"); | |||
7239 | Builder.AddChunk(CodeCompletionString::CK_RightBrace); | |||
7240 | Results.AddResult(Result(Builder.TakeString())); | |||
7241 | } | |||
7242 | ||||
7243 | // @throw | |||
7244 | Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "throw")((NeedAt) ? "@" "throw" : "throw")); | |||
7245 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
7246 | Builder.AddPlaceholderChunk("expression"); | |||
7247 | Results.AddResult(Result(Builder.TakeString())); | |||
7248 | ||||
7249 | if (Results.includeCodePatterns()) { | |||
7250 | // @synchronized ( expression ) { statements } | |||
7251 | Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "synchronized")((NeedAt) ? "@" "synchronized" : "synchronized")); | |||
7252 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
7253 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
7254 | Builder.AddPlaceholderChunk("expression"); | |||
7255 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
7256 | Builder.AddChunk(CodeCompletionString::CK_LeftBrace); | |||
7257 | Builder.AddPlaceholderChunk("statements"); | |||
7258 | Builder.AddChunk(CodeCompletionString::CK_RightBrace); | |||
7259 | Results.AddResult(Result(Builder.TakeString())); | |||
7260 | } | |||
7261 | } | |||
7262 | ||||
7263 | static void AddObjCVisibilityResults(const LangOptions &LangOpts, | |||
7264 | ResultBuilder &Results, bool NeedAt) { | |||
7265 | typedef CodeCompletionResult Result; | |||
7266 | Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "private")((NeedAt) ? "@" "private" : "private"))); | |||
7267 | Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "protected")((NeedAt) ? "@" "protected" : "protected"))); | |||
7268 | Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "public")((NeedAt) ? "@" "public" : "public"))); | |||
7269 | if (LangOpts.ObjC) | |||
7270 | Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "package")((NeedAt) ? "@" "package" : "package"))); | |||
7271 | } | |||
7272 | ||||
7273 | void Sema::CodeCompleteObjCAtVisibility(Scope *S) { | |||
7274 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
7275 | CodeCompleter->getCodeCompletionTUInfo(), | |||
7276 | CodeCompletionContext::CCC_Other); | |||
7277 | Results.EnterNewScope(); | |||
7278 | AddObjCVisibilityResults(getLangOpts(), Results, false); | |||
7279 | Results.ExitScope(); | |||
7280 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
7281 | Results.data(), Results.size()); | |||
7282 | } | |||
7283 | ||||
7284 | void Sema::CodeCompleteObjCAtStatement(Scope *S) { | |||
7285 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
7286 | CodeCompleter->getCodeCompletionTUInfo(), | |||
7287 | CodeCompletionContext::CCC_Other); | |||
7288 | Results.EnterNewScope(); | |||
7289 | AddObjCStatementResults(Results, false); | |||
7290 | AddObjCExpressionResults(Results, false); | |||
7291 | Results.ExitScope(); | |||
7292 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
7293 | Results.data(), Results.size()); | |||
7294 | } | |||
7295 | ||||
7296 | void Sema::CodeCompleteObjCAtExpression(Scope *S) { | |||
7297 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
7298 | CodeCompleter->getCodeCompletionTUInfo(), | |||
7299 | CodeCompletionContext::CCC_Other); | |||
7300 | Results.EnterNewScope(); | |||
7301 | AddObjCExpressionResults(Results, false); | |||
7302 | Results.ExitScope(); | |||
7303 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
7304 | Results.data(), Results.size()); | |||
7305 | } | |||
7306 | ||||
7307 | /// Determine whether the addition of the given flag to an Objective-C | |||
7308 | /// property's attributes will cause a conflict. | |||
7309 | static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) { | |||
7310 | // Check if we've already added this flag. | |||
7311 | if (Attributes & NewFlag) | |||
7312 | return true; | |||
7313 | ||||
7314 | Attributes |= NewFlag; | |||
7315 | ||||
7316 | // Check for collisions with "readonly". | |||
7317 | if ((Attributes & ObjCPropertyAttribute::kind_readonly) && | |||
7318 | (Attributes & ObjCPropertyAttribute::kind_readwrite)) | |||
7319 | return true; | |||
7320 | ||||
7321 | // Check for more than one of { assign, copy, retain, strong, weak }. | |||
7322 | unsigned AssignCopyRetMask = | |||
7323 | Attributes & | |||
7324 | (ObjCPropertyAttribute::kind_assign | | |||
7325 | ObjCPropertyAttribute::kind_unsafe_unretained | | |||
7326 | ObjCPropertyAttribute::kind_copy | ObjCPropertyAttribute::kind_retain | | |||
7327 | ObjCPropertyAttribute::kind_strong | ObjCPropertyAttribute::kind_weak); | |||
7328 | if (AssignCopyRetMask && | |||
7329 | AssignCopyRetMask != ObjCPropertyAttribute::kind_assign && | |||
7330 | AssignCopyRetMask != ObjCPropertyAttribute::kind_unsafe_unretained && | |||
7331 | AssignCopyRetMask != ObjCPropertyAttribute::kind_copy && | |||
7332 | AssignCopyRetMask != ObjCPropertyAttribute::kind_retain && | |||
7333 | AssignCopyRetMask != ObjCPropertyAttribute::kind_strong && | |||
7334 | AssignCopyRetMask != ObjCPropertyAttribute::kind_weak) | |||
7335 | return true; | |||
7336 | ||||
7337 | return false; | |||
7338 | } | |||
7339 | ||||
7340 | void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) { | |||
7341 | if (!CodeCompleter) | |||
7342 | return; | |||
7343 | ||||
7344 | unsigned Attributes = ODS.getPropertyAttributes(); | |||
7345 | ||||
7346 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
7347 | CodeCompleter->getCodeCompletionTUInfo(), | |||
7348 | CodeCompletionContext::CCC_Other); | |||
7349 | Results.EnterNewScope(); | |||
7350 | if (!ObjCPropertyFlagConflicts(Attributes, | |||
7351 | ObjCPropertyAttribute::kind_readonly)) | |||
7352 | Results.AddResult(CodeCompletionResult("readonly")); | |||
7353 | if (!ObjCPropertyFlagConflicts(Attributes, | |||
7354 | ObjCPropertyAttribute::kind_assign)) | |||
7355 | Results.AddResult(CodeCompletionResult("assign")); | |||
7356 | if (!ObjCPropertyFlagConflicts(Attributes, | |||
7357 | ObjCPropertyAttribute::kind_unsafe_unretained)) | |||
7358 | Results.AddResult(CodeCompletionResult("unsafe_unretained")); | |||
7359 | if (!ObjCPropertyFlagConflicts(Attributes, | |||
7360 | ObjCPropertyAttribute::kind_readwrite)) | |||
7361 | Results.AddResult(CodeCompletionResult("readwrite")); | |||
7362 | if (!ObjCPropertyFlagConflicts(Attributes, | |||
7363 | ObjCPropertyAttribute::kind_retain)) | |||
7364 | Results.AddResult(CodeCompletionResult("retain")); | |||
7365 | if (!ObjCPropertyFlagConflicts(Attributes, | |||
7366 | ObjCPropertyAttribute::kind_strong)) | |||
7367 | Results.AddResult(CodeCompletionResult("strong")); | |||
7368 | if (!ObjCPropertyFlagConflicts(Attributes, ObjCPropertyAttribute::kind_copy)) | |||
7369 | Results.AddResult(CodeCompletionResult("copy")); | |||
7370 | if (!ObjCPropertyFlagConflicts(Attributes, | |||
7371 | ObjCPropertyAttribute::kind_nonatomic)) | |||
7372 | Results.AddResult(CodeCompletionResult("nonatomic")); | |||
7373 | if (!ObjCPropertyFlagConflicts(Attributes, | |||
7374 | ObjCPropertyAttribute::kind_atomic)) | |||
7375 | Results.AddResult(CodeCompletionResult("atomic")); | |||
7376 | ||||
7377 | // Only suggest "weak" if we're compiling for ARC-with-weak-references or GC. | |||
7378 | if (getLangOpts().ObjCWeak || getLangOpts().getGC() != LangOptions::NonGC) | |||
7379 | if (!ObjCPropertyFlagConflicts(Attributes, | |||
7380 | ObjCPropertyAttribute::kind_weak)) | |||
7381 | Results.AddResult(CodeCompletionResult("weak")); | |||
7382 | ||||
7383 | if (!ObjCPropertyFlagConflicts(Attributes, | |||
7384 | ObjCPropertyAttribute::kind_setter)) { | |||
7385 | CodeCompletionBuilder Setter(Results.getAllocator(), | |||
7386 | Results.getCodeCompletionTUInfo()); | |||
7387 | Setter.AddTypedTextChunk("setter"); | |||
7388 | Setter.AddTextChunk("="); | |||
7389 | Setter.AddPlaceholderChunk("method"); | |||
7390 | Results.AddResult(CodeCompletionResult(Setter.TakeString())); | |||
7391 | } | |||
7392 | if (!ObjCPropertyFlagConflicts(Attributes, | |||
7393 | ObjCPropertyAttribute::kind_getter)) { | |||
7394 | CodeCompletionBuilder Getter(Results.getAllocator(), | |||
7395 | Results.getCodeCompletionTUInfo()); | |||
7396 | Getter.AddTypedTextChunk("getter"); | |||
7397 | Getter.AddTextChunk("="); | |||
7398 | Getter.AddPlaceholderChunk("method"); | |||
7399 | Results.AddResult(CodeCompletionResult(Getter.TakeString())); | |||
7400 | } | |||
7401 | if (!ObjCPropertyFlagConflicts(Attributes, | |||
7402 | ObjCPropertyAttribute::kind_nullability)) { | |||
7403 | Results.AddResult(CodeCompletionResult("nonnull")); | |||
7404 | Results.AddResult(CodeCompletionResult("nullable")); | |||
7405 | Results.AddResult(CodeCompletionResult("null_unspecified")); | |||
7406 | Results.AddResult(CodeCompletionResult("null_resettable")); | |||
7407 | } | |||
7408 | Results.ExitScope(); | |||
7409 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
7410 | Results.data(), Results.size()); | |||
7411 | } | |||
7412 | ||||
7413 | /// Describes the kind of Objective-C method that we want to find | |||
7414 | /// via code completion. | |||
7415 | enum ObjCMethodKind { | |||
7416 | MK_Any, ///< Any kind of method, provided it means other specified criteria. | |||
7417 | MK_ZeroArgSelector, ///< Zero-argument (unary) selector. | |||
7418 | MK_OneArgSelector ///< One-argument selector. | |||
7419 | }; | |||
7420 | ||||
7421 | static bool isAcceptableObjCSelector(Selector Sel, ObjCMethodKind WantKind, | |||
7422 | ArrayRef<IdentifierInfo *> SelIdents, | |||
7423 | bool AllowSameLength = true) { | |||
7424 | unsigned NumSelIdents = SelIdents.size(); | |||
7425 | if (NumSelIdents > Sel.getNumArgs()) | |||
7426 | return false; | |||
7427 | ||||
7428 | switch (WantKind) { | |||
7429 | case MK_Any: | |||
7430 | break; | |||
7431 | case MK_ZeroArgSelector: | |||
7432 | return Sel.isUnarySelector(); | |||
7433 | case MK_OneArgSelector: | |||
7434 | return Sel.getNumArgs() == 1; | |||
7435 | } | |||
7436 | ||||
7437 | if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs()) | |||
7438 | return false; | |||
7439 | ||||
7440 | for (unsigned I = 0; I != NumSelIdents; ++I) | |||
7441 | if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I)) | |||
7442 | return false; | |||
7443 | ||||
7444 | return true; | |||
7445 | } | |||
7446 | ||||
7447 | static bool isAcceptableObjCMethod(ObjCMethodDecl *Method, | |||
7448 | ObjCMethodKind WantKind, | |||
7449 | ArrayRef<IdentifierInfo *> SelIdents, | |||
7450 | bool AllowSameLength = true) { | |||
7451 | return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents, | |||
7452 | AllowSameLength); | |||
7453 | } | |||
7454 | ||||
7455 | /// A set of selectors, which is used to avoid introducing multiple | |||
7456 | /// completions with the same selector into the result set. | |||
7457 | typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet; | |||
7458 | ||||
7459 | /// Add all of the Objective-C methods in the given Objective-C | |||
7460 | /// container to the set of results. | |||
7461 | /// | |||
7462 | /// The container will be a class, protocol, category, or implementation of | |||
7463 | /// any of the above. This mether will recurse to include methods from | |||
7464 | /// the superclasses of classes along with their categories, protocols, and | |||
7465 | /// implementations. | |||
7466 | /// | |||
7467 | /// \param Container the container in which we'll look to find methods. | |||
7468 | /// | |||
7469 | /// \param WantInstanceMethods Whether to add instance methods (only); if | |||
7470 | /// false, this routine will add factory methods (only). | |||
7471 | /// | |||
7472 | /// \param CurContext the context in which we're performing the lookup that | |||
7473 | /// finds methods. | |||
7474 | /// | |||
7475 | /// \param AllowSameLength Whether we allow a method to be added to the list | |||
7476 | /// when it has the same number of parameters as we have selector identifiers. | |||
7477 | /// | |||
7478 | /// \param Results the structure into which we'll add results. | |||
7479 | static void AddObjCMethods(ObjCContainerDecl *Container, | |||
7480 | bool WantInstanceMethods, ObjCMethodKind WantKind, | |||
7481 | ArrayRef<IdentifierInfo *> SelIdents, | |||
7482 | DeclContext *CurContext, | |||
7483 | VisitedSelectorSet &Selectors, bool AllowSameLength, | |||
7484 | ResultBuilder &Results, bool InOriginalClass = true, | |||
7485 | bool IsRootClass = false) { | |||
7486 | typedef CodeCompletionResult Result; | |||
7487 | Container = getContainerDef(Container); | |||
7488 | ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container); | |||
7489 | IsRootClass = IsRootClass || (IFace && !IFace->getSuperClass()); | |||
7490 | for (ObjCMethodDecl *M : Container->methods()) { | |||
7491 | // The instance methods on the root class can be messaged via the | |||
7492 | // metaclass. | |||
7493 | if (M->isInstanceMethod() == WantInstanceMethods || | |||
7494 | (IsRootClass && !WantInstanceMethods)) { | |||
7495 | // Check whether the selector identifiers we've been given are a | |||
7496 | // subset of the identifiers for this particular method. | |||
7497 | if (!isAcceptableObjCMethod(M, WantKind, SelIdents, AllowSameLength)) | |||
7498 | continue; | |||
7499 | ||||
7500 | if (!Selectors.insert(M->getSelector()).second) | |||
7501 | continue; | |||
7502 | ||||
7503 | Result R = Result(M, Results.getBasePriority(M), nullptr); | |||
7504 | R.StartParameter = SelIdents.size(); | |||
7505 | R.AllParametersAreInformative = (WantKind != MK_Any); | |||
7506 | if (!InOriginalClass) | |||
7507 | setInBaseClass(R); | |||
7508 | Results.MaybeAddResult(R, CurContext); | |||
7509 | } | |||
7510 | } | |||
7511 | ||||
7512 | // Visit the protocols of protocols. | |||
7513 | if (const auto *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { | |||
7514 | if (Protocol->hasDefinition()) { | |||
7515 | const ObjCList<ObjCProtocolDecl> &Protocols = | |||
7516 | Protocol->getReferencedProtocols(); | |||
7517 | for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), | |||
7518 | E = Protocols.end(); | |||
7519 | I != E; ++I) | |||
7520 | AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext, | |||
7521 | Selectors, AllowSameLength, Results, false, IsRootClass); | |||
7522 | } | |||
7523 | } | |||
7524 | ||||
7525 | if (!IFace || !IFace->hasDefinition()) | |||
7526 | return; | |||
7527 | ||||
7528 | // Add methods in protocols. | |||
7529 | for (ObjCProtocolDecl *I : IFace->protocols()) | |||
7530 | AddObjCMethods(I, WantInstanceMethods, WantKind, SelIdents, CurContext, | |||
7531 | Selectors, AllowSameLength, Results, false, IsRootClass); | |||
7532 | ||||
7533 | // Add methods in categories. | |||
7534 | for (ObjCCategoryDecl *CatDecl : IFace->known_categories()) { | |||
7535 | AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents, | |||
7536 | CurContext, Selectors, AllowSameLength, Results, | |||
7537 | InOriginalClass, IsRootClass); | |||
7538 | ||||
7539 | // Add a categories protocol methods. | |||
7540 | const ObjCList<ObjCProtocolDecl> &Protocols = | |||
7541 | CatDecl->getReferencedProtocols(); | |||
7542 | for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), | |||
7543 | E = Protocols.end(); | |||
7544 | I != E; ++I) | |||
7545 | AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext, | |||
7546 | Selectors, AllowSameLength, Results, false, IsRootClass); | |||
7547 | ||||
7548 | // Add methods in category implementations. | |||
7549 | if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation()) | |||
7550 | AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext, | |||
7551 | Selectors, AllowSameLength, Results, InOriginalClass, | |||
7552 | IsRootClass); | |||
7553 | } | |||
7554 | ||||
7555 | // Add methods in superclass. | |||
7556 | // Avoid passing in IsRootClass since root classes won't have super classes. | |||
7557 | if (IFace->getSuperClass()) | |||
7558 | AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind, | |||
7559 | SelIdents, CurContext, Selectors, AllowSameLength, Results, | |||
7560 | /*IsRootClass=*/false); | |||
7561 | ||||
7562 | // Add methods in our implementation, if any. | |||
7563 | if (ObjCImplementationDecl *Impl = IFace->getImplementation()) | |||
7564 | AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext, | |||
7565 | Selectors, AllowSameLength, Results, InOriginalClass, | |||
7566 | IsRootClass); | |||
7567 | } | |||
7568 | ||||
7569 | void Sema::CodeCompleteObjCPropertyGetter(Scope *S) { | |||
7570 | // Try to find the interface where getters might live. | |||
7571 | ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext); | |||
7572 | if (!Class) { | |||
7573 | if (ObjCCategoryDecl *Category = | |||
7574 | dyn_cast_or_null<ObjCCategoryDecl>(CurContext)) | |||
7575 | Class = Category->getClassInterface(); | |||
7576 | ||||
7577 | if (!Class) | |||
7578 | return; | |||
7579 | } | |||
7580 | ||||
7581 | // Find all of the potential getters. | |||
7582 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
7583 | CodeCompleter->getCodeCompletionTUInfo(), | |||
7584 | CodeCompletionContext::CCC_Other); | |||
7585 | Results.EnterNewScope(); | |||
7586 | ||||
7587 | VisitedSelectorSet Selectors; | |||
7588 | AddObjCMethods(Class, true, MK_ZeroArgSelector, std::nullopt, CurContext, | |||
7589 | Selectors, | |||
7590 | /*AllowSameLength=*/true, Results); | |||
7591 | Results.ExitScope(); | |||
7592 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
7593 | Results.data(), Results.size()); | |||
7594 | } | |||
7595 | ||||
7596 | void Sema::CodeCompleteObjCPropertySetter(Scope *S) { | |||
7597 | // Try to find the interface where setters might live. | |||
7598 | ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext); | |||
7599 | if (!Class) { | |||
7600 | if (ObjCCategoryDecl *Category = | |||
7601 | dyn_cast_or_null<ObjCCategoryDecl>(CurContext)) | |||
7602 | Class = Category->getClassInterface(); | |||
7603 | ||||
7604 | if (!Class) | |||
7605 | return; | |||
7606 | } | |||
7607 | ||||
7608 | // Find all of the potential getters. | |||
7609 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
7610 | CodeCompleter->getCodeCompletionTUInfo(), | |||
7611 | CodeCompletionContext::CCC_Other); | |||
7612 | Results.EnterNewScope(); | |||
7613 | ||||
7614 | VisitedSelectorSet Selectors; | |||
7615 | AddObjCMethods(Class, true, MK_OneArgSelector, std::nullopt, CurContext, | |||
7616 | Selectors, | |||
7617 | /*AllowSameLength=*/true, Results); | |||
7618 | ||||
7619 | Results.ExitScope(); | |||
7620 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
7621 | Results.data(), Results.size()); | |||
7622 | } | |||
7623 | ||||
7624 | void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, | |||
7625 | bool IsParameter) { | |||
7626 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
7627 | CodeCompleter->getCodeCompletionTUInfo(), | |||
7628 | CodeCompletionContext::CCC_Type); | |||
7629 | Results.EnterNewScope(); | |||
7630 | ||||
7631 | // Add context-sensitive, Objective-C parameter-passing keywords. | |||
7632 | bool AddedInOut = false; | |||
7633 | if ((DS.getObjCDeclQualifier() & | |||
7634 | (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) { | |||
7635 | Results.AddResult("in"); | |||
7636 | Results.AddResult("inout"); | |||
7637 | AddedInOut = true; | |||
7638 | } | |||
7639 | if ((DS.getObjCDeclQualifier() & | |||
7640 | (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) { | |||
7641 | Results.AddResult("out"); | |||
7642 | if (!AddedInOut) | |||
7643 | Results.AddResult("inout"); | |||
7644 | } | |||
7645 | if ((DS.getObjCDeclQualifier() & | |||
7646 | (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref | | |||
7647 | ObjCDeclSpec::DQ_Oneway)) == 0) { | |||
7648 | Results.AddResult("bycopy"); | |||
7649 | Results.AddResult("byref"); | |||
7650 | Results.AddResult("oneway"); | |||
7651 | } | |||
7652 | if ((DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability) == 0) { | |||
7653 | Results.AddResult("nonnull"); | |||
7654 | Results.AddResult("nullable"); | |||
7655 | Results.AddResult("null_unspecified"); | |||
7656 | } | |||
7657 | ||||
7658 | // If we're completing the return type of an Objective-C method and the | |||
7659 | // identifier IBAction refers to a macro, provide a completion item for | |||
7660 | // an action, e.g., | |||
7661 | // IBAction)<#selector#>:(id)sender | |||
7662 | if (DS.getObjCDeclQualifier() == 0 && !IsParameter && | |||
7663 | PP.isMacroDefined("IBAction")) { | |||
7664 | CodeCompletionBuilder Builder(Results.getAllocator(), | |||
7665 | Results.getCodeCompletionTUInfo(), | |||
7666 | CCP_CodePattern, CXAvailability_Available); | |||
7667 | Builder.AddTypedTextChunk("IBAction"); | |||
7668 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
7669 | Builder.AddPlaceholderChunk("selector"); | |||
7670 | Builder.AddChunk(CodeCompletionString::CK_Colon); | |||
7671 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
7672 | Builder.AddTextChunk("id"); | |||
7673 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
7674 | Builder.AddTextChunk("sender"); | |||
7675 | Results.AddResult(CodeCompletionResult(Builder.TakeString())); | |||
7676 | } | |||
7677 | ||||
7678 | // If we're completing the return type, provide 'instancetype'. | |||
7679 | if (!IsParameter) { | |||
7680 | Results.AddResult(CodeCompletionResult("instancetype")); | |||
7681 | } | |||
7682 | ||||
7683 | // Add various builtin type names and specifiers. | |||
7684 | AddOrdinaryNameResults(PCC_Type, S, *this, Results); | |||
7685 | Results.ExitScope(); | |||
7686 | ||||
7687 | // Add the various type names | |||
7688 | Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName); | |||
7689 | CodeCompletionDeclConsumer Consumer(Results, CurContext); | |||
7690 | LookupVisibleDecls(S, LookupOrdinaryName, Consumer, | |||
7691 | CodeCompleter->includeGlobals(), | |||
7692 | CodeCompleter->loadExternal()); | |||
7693 | ||||
7694 | if (CodeCompleter->includeMacros()) | |||
7695 | AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false); | |||
7696 | ||||
7697 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
7698 | Results.data(), Results.size()); | |||
7699 | } | |||
7700 | ||||
7701 | /// When we have an expression with type "id", we may assume | |||
7702 | /// that it has some more-specific class type based on knowledge of | |||
7703 | /// common uses of Objective-C. This routine returns that class type, | |||
7704 | /// or NULL if no better result could be determined. | |||
7705 | static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) { | |||
7706 | auto *Msg = dyn_cast_or_null<ObjCMessageExpr>(E); | |||
7707 | if (!Msg) | |||
7708 | return nullptr; | |||
7709 | ||||
7710 | Selector Sel = Msg->getSelector(); | |||
7711 | if (Sel.isNull()) | |||
7712 | return nullptr; | |||
7713 | ||||
7714 | IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0); | |||
7715 | if (!Id) | |||
7716 | return nullptr; | |||
7717 | ||||
7718 | ObjCMethodDecl *Method = Msg->getMethodDecl(); | |||
7719 | if (!Method) | |||
7720 | return nullptr; | |||
7721 | ||||
7722 | // Determine the class that we're sending the message to. | |||
7723 | ObjCInterfaceDecl *IFace = nullptr; | |||
7724 | switch (Msg->getReceiverKind()) { | |||
7725 | case ObjCMessageExpr::Class: | |||
7726 | if (const ObjCObjectType *ObjType = | |||
7727 | Msg->getClassReceiver()->getAs<ObjCObjectType>()) | |||
7728 | IFace = ObjType->getInterface(); | |||
7729 | break; | |||
7730 | ||||
7731 | case ObjCMessageExpr::Instance: { | |||
7732 | QualType T = Msg->getInstanceReceiver()->getType(); | |||
7733 | if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>()) | |||
7734 | IFace = Ptr->getInterfaceDecl(); | |||
7735 | break; | |||
7736 | } | |||
7737 | ||||
7738 | case ObjCMessageExpr::SuperInstance: | |||
7739 | case ObjCMessageExpr::SuperClass: | |||
7740 | break; | |||
7741 | } | |||
7742 | ||||
7743 | if (!IFace) | |||
7744 | return nullptr; | |||
7745 | ||||
7746 | ObjCInterfaceDecl *Super = IFace->getSuperClass(); | |||
7747 | if (Method->isInstanceMethod()) | |||
7748 | return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName()) | |||
7749 | .Case("retain", IFace) | |||
7750 | .Case("strong", IFace) | |||
7751 | .Case("autorelease", IFace) | |||
7752 | .Case("copy", IFace) | |||
7753 | .Case("copyWithZone", IFace) | |||
7754 | .Case("mutableCopy", IFace) | |||
7755 | .Case("mutableCopyWithZone", IFace) | |||
7756 | .Case("awakeFromCoder", IFace) | |||
7757 | .Case("replacementObjectFromCoder", IFace) | |||
7758 | .Case("class", IFace) | |||
7759 | .Case("classForCoder", IFace) | |||
7760 | .Case("superclass", Super) | |||
7761 | .Default(nullptr); | |||
7762 | ||||
7763 | return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName()) | |||
7764 | .Case("new", IFace) | |||
7765 | .Case("alloc", IFace) | |||
7766 | .Case("allocWithZone", IFace) | |||
7767 | .Case("class", IFace) | |||
7768 | .Case("superclass", Super) | |||
7769 | .Default(nullptr); | |||
7770 | } | |||
7771 | ||||
7772 | // Add a special completion for a message send to "super", which fills in the | |||
7773 | // most likely case of forwarding all of our arguments to the superclass | |||
7774 | // function. | |||
7775 | /// | |||
7776 | /// \param S The semantic analysis object. | |||
7777 | /// | |||
7778 | /// \param NeedSuperKeyword Whether we need to prefix this completion with | |||
7779 | /// the "super" keyword. Otherwise, we just need to provide the arguments. | |||
7780 | /// | |||
7781 | /// \param SelIdents The identifiers in the selector that have already been | |||
7782 | /// provided as arguments for a send to "super". | |||
7783 | /// | |||
7784 | /// \param Results The set of results to augment. | |||
7785 | /// | |||
7786 | /// \returns the Objective-C method declaration that would be invoked by | |||
7787 | /// this "super" completion. If NULL, no completion was added. | |||
7788 | static ObjCMethodDecl * | |||
7789 | AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword, | |||
7790 | ArrayRef<IdentifierInfo *> SelIdents, | |||
7791 | ResultBuilder &Results) { | |||
7792 | ObjCMethodDecl *CurMethod = S.getCurMethodDecl(); | |||
7793 | if (!CurMethod) | |||
7794 | return nullptr; | |||
7795 | ||||
7796 | ObjCInterfaceDecl *Class = CurMethod->getClassInterface(); | |||
7797 | if (!Class) | |||
7798 | return nullptr; | |||
7799 | ||||
7800 | // Try to find a superclass method with the same selector. | |||
7801 | ObjCMethodDecl *SuperMethod = nullptr; | |||
7802 | while ((Class = Class->getSuperClass()) && !SuperMethod) { | |||
7803 | // Check in the class | |||
7804 | SuperMethod = Class->getMethod(CurMethod->getSelector(), | |||
7805 | CurMethod->isInstanceMethod()); | |||
7806 | ||||
7807 | // Check in categories or class extensions. | |||
7808 | if (!SuperMethod) { | |||
7809 | for (const auto *Cat : Class->known_categories()) { | |||
7810 | if ((SuperMethod = Cat->getMethod(CurMethod->getSelector(), | |||
7811 | CurMethod->isInstanceMethod()))) | |||
7812 | break; | |||
7813 | } | |||
7814 | } | |||
7815 | } | |||
7816 | ||||
7817 | if (!SuperMethod) | |||
7818 | return nullptr; | |||
7819 | ||||
7820 | // Check whether the superclass method has the same signature. | |||
7821 | if (CurMethod->param_size() != SuperMethod->param_size() || | |||
7822 | CurMethod->isVariadic() != SuperMethod->isVariadic()) | |||
7823 | return nullptr; | |||
7824 | ||||
7825 | for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(), | |||
7826 | CurPEnd = CurMethod->param_end(), | |||
7827 | SuperP = SuperMethod->param_begin(); | |||
7828 | CurP != CurPEnd; ++CurP, ++SuperP) { | |||
7829 | // Make sure the parameter types are compatible. | |||
7830 | if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(), | |||
7831 | (*SuperP)->getType())) | |||
7832 | return nullptr; | |||
7833 | ||||
7834 | // Make sure we have a parameter name to forward! | |||
7835 | if (!(*CurP)->getIdentifier()) | |||
7836 | return nullptr; | |||
7837 | } | |||
7838 | ||||
7839 | // We have a superclass method. Now, form the send-to-super completion. | |||
7840 | CodeCompletionBuilder Builder(Results.getAllocator(), | |||
7841 | Results.getCodeCompletionTUInfo()); | |||
7842 | ||||
7843 | // Give this completion a return type. | |||
7844 | AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod, | |||
7845 | Results.getCompletionContext().getBaseType(), Builder); | |||
7846 | ||||
7847 | // If we need the "super" keyword, add it (plus some spacing). | |||
7848 | if (NeedSuperKeyword) { | |||
7849 | Builder.AddTypedTextChunk("super"); | |||
7850 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
7851 | } | |||
7852 | ||||
7853 | Selector Sel = CurMethod->getSelector(); | |||
7854 | if (Sel.isUnarySelector()) { | |||
7855 | if (NeedSuperKeyword) | |||
7856 | Builder.AddTextChunk( | |||
7857 | Builder.getAllocator().CopyString(Sel.getNameForSlot(0))); | |||
7858 | else | |||
7859 | Builder.AddTypedTextChunk( | |||
7860 | Builder.getAllocator().CopyString(Sel.getNameForSlot(0))); | |||
7861 | } else { | |||
7862 | ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(); | |||
7863 | for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) { | |||
7864 | if (I > SelIdents.size()) | |||
7865 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
7866 | ||||
7867 | if (I < SelIdents.size()) | |||
7868 | Builder.AddInformativeChunk( | |||
7869 | Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":")); | |||
7870 | else if (NeedSuperKeyword || I > SelIdents.size()) { | |||
7871 | Builder.AddTextChunk( | |||
7872 | Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":")); | |||
7873 | Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString( | |||
7874 | (*CurP)->getIdentifier()->getName())); | |||
7875 | } else { | |||
7876 | Builder.AddTypedTextChunk( | |||
7877 | Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":")); | |||
7878 | Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString( | |||
7879 | (*CurP)->getIdentifier()->getName())); | |||
7880 | } | |||
7881 | } | |||
7882 | } | |||
7883 | ||||
7884 | Results.AddResult(CodeCompletionResult(Builder.TakeString(), SuperMethod, | |||
7885 | CCP_SuperCompletion)); | |||
7886 | return SuperMethod; | |||
7887 | } | |||
7888 | ||||
7889 | void Sema::CodeCompleteObjCMessageReceiver(Scope *S) { | |||
7890 | typedef CodeCompletionResult Result; | |||
7891 | ResultBuilder Results( | |||
7892 | *this, CodeCompleter->getAllocator(), | |||
7893 | CodeCompleter->getCodeCompletionTUInfo(), | |||
7894 | CodeCompletionContext::CCC_ObjCMessageReceiver, | |||
7895 | getLangOpts().CPlusPlus11 | |||
7896 | ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture | |||
7897 | : &ResultBuilder::IsObjCMessageReceiver); | |||
7898 | ||||
7899 | CodeCompletionDeclConsumer Consumer(Results, CurContext); | |||
7900 | Results.EnterNewScope(); | |||
7901 | LookupVisibleDecls(S, LookupOrdinaryName, Consumer, | |||
7902 | CodeCompleter->includeGlobals(), | |||
7903 | CodeCompleter->loadExternal()); | |||
7904 | ||||
7905 | // If we are in an Objective-C method inside a class that has a superclass, | |||
7906 | // add "super" as an option. | |||
7907 | if (ObjCMethodDecl *Method = getCurMethodDecl()) | |||
7908 | if (ObjCInterfaceDecl *Iface = Method->getClassInterface()) | |||
7909 | if (Iface->getSuperClass()) { | |||
7910 | Results.AddResult(Result("super")); | |||
7911 | ||||
7912 | AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, std::nullopt, | |||
7913 | Results); | |||
7914 | } | |||
7915 | ||||
7916 | if (getLangOpts().CPlusPlus11) | |||
7917 | addThisCompletion(*this, Results); | |||
7918 | ||||
7919 | Results.ExitScope(); | |||
7920 | ||||
7921 | if (CodeCompleter->includeMacros()) | |||
7922 | AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false); | |||
7923 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
7924 | Results.data(), Results.size()); | |||
7925 | } | |||
7926 | ||||
7927 | void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, | |||
7928 | ArrayRef<IdentifierInfo *> SelIdents, | |||
7929 | bool AtArgumentExpression) { | |||
7930 | ObjCInterfaceDecl *CDecl = nullptr; | |||
7931 | if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) { | |||
7932 | // Figure out which interface we're in. | |||
7933 | CDecl = CurMethod->getClassInterface(); | |||
7934 | if (!CDecl) | |||
7935 | return; | |||
7936 | ||||
7937 | // Find the superclass of this class. | |||
7938 | CDecl = CDecl->getSuperClass(); | |||
7939 | if (!CDecl) | |||
7940 | return; | |||
7941 | ||||
7942 | if (CurMethod->isInstanceMethod()) { | |||
7943 | // We are inside an instance method, which means that the message | |||
7944 | // send [super ...] is actually calling an instance method on the | |||
7945 | // current object. | |||
7946 | return CodeCompleteObjCInstanceMessage(S, nullptr, SelIdents, | |||
7947 | AtArgumentExpression, CDecl); | |||
7948 | } | |||
7949 | ||||
7950 | // Fall through to send to the superclass in CDecl. | |||
7951 | } else { | |||
7952 | // "super" may be the name of a type or variable. Figure out which | |||
7953 | // it is. | |||
7954 | IdentifierInfo *Super = getSuperIdentifier(); | |||
7955 | NamedDecl *ND = LookupSingleName(S, Super, SuperLoc, LookupOrdinaryName); | |||
7956 | if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) { | |||
7957 | // "super" names an interface. Use it. | |||
7958 | } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) { | |||
7959 | if (const ObjCObjectType *Iface = | |||
7960 | Context.getTypeDeclType(TD)->getAs<ObjCObjectType>()) | |||
7961 | CDecl = Iface->getInterface(); | |||
7962 | } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) { | |||
7963 | // "super" names an unresolved type; we can't be more specific. | |||
7964 | } else { | |||
7965 | // Assume that "super" names some kind of value and parse that way. | |||
7966 | CXXScopeSpec SS; | |||
7967 | SourceLocation TemplateKWLoc; | |||
7968 | UnqualifiedId id; | |||
7969 | id.setIdentifier(Super, SuperLoc); | |||
7970 | ExprResult SuperExpr = ActOnIdExpression(S, SS, TemplateKWLoc, id, | |||
7971 | /*HasTrailingLParen=*/false, | |||
7972 | /*IsAddressOfOperand=*/false); | |||
7973 | return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(), | |||
7974 | SelIdents, AtArgumentExpression); | |||
7975 | } | |||
7976 | ||||
7977 | // Fall through | |||
7978 | } | |||
7979 | ||||
7980 | ParsedType Receiver; | |||
7981 | if (CDecl) | |||
7982 | Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl)); | |||
7983 | return CodeCompleteObjCClassMessage(S, Receiver, SelIdents, | |||
7984 | AtArgumentExpression, | |||
7985 | /*IsSuper=*/true); | |||
7986 | } | |||
7987 | ||||
7988 | /// Given a set of code-completion results for the argument of a message | |||
7989 | /// send, determine the preferred type (if any) for that argument expression. | |||
7990 | static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results, | |||
7991 | unsigned NumSelIdents) { | |||
7992 | typedef CodeCompletionResult Result; | |||
7993 | ASTContext &Context = Results.getSema().Context; | |||
7994 | ||||
7995 | QualType PreferredType; | |||
7996 | unsigned BestPriority = CCP_Unlikely * 2; | |||
7997 | Result *ResultsData = Results.data(); | |||
7998 | for (unsigned I = 0, N = Results.size(); I != N; ++I) { | |||
7999 | Result &R = ResultsData[I]; | |||
8000 | if (R.Kind == Result::RK_Declaration && | |||
8001 | isa<ObjCMethodDecl>(R.Declaration)) { | |||
8002 | if (R.Priority <= BestPriority) { | |||
8003 | const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration); | |||
8004 | if (NumSelIdents <= Method->param_size()) { | |||
8005 | QualType MyPreferredType = | |||
8006 | Method->parameters()[NumSelIdents - 1]->getType(); | |||
8007 | if (R.Priority < BestPriority || PreferredType.isNull()) { | |||
8008 | BestPriority = R.Priority; | |||
8009 | PreferredType = MyPreferredType; | |||
8010 | } else if (!Context.hasSameUnqualifiedType(PreferredType, | |||
8011 | MyPreferredType)) { | |||
8012 | PreferredType = QualType(); | |||
8013 | } | |||
8014 | } | |||
8015 | } | |||
8016 | } | |||
8017 | } | |||
8018 | ||||
8019 | return PreferredType; | |||
8020 | } | |||
8021 | ||||
8022 | static void AddClassMessageCompletions(Sema &SemaRef, Scope *S, | |||
8023 | ParsedType Receiver, | |||
8024 | ArrayRef<IdentifierInfo *> SelIdents, | |||
8025 | bool AtArgumentExpression, bool IsSuper, | |||
8026 | ResultBuilder &Results) { | |||
8027 | typedef CodeCompletionResult Result; | |||
8028 | ObjCInterfaceDecl *CDecl = nullptr; | |||
8029 | ||||
8030 | // If the given name refers to an interface type, retrieve the | |||
8031 | // corresponding declaration. | |||
8032 | if (Receiver) { | |||
8033 | QualType T = SemaRef.GetTypeFromParser(Receiver, nullptr); | |||
8034 | if (!T.isNull()) | |||
8035 | if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>()) | |||
8036 | CDecl = Interface->getInterface(); | |||
8037 | } | |||
8038 | ||||
8039 | // Add all of the factory methods in this Objective-C class, its protocols, | |||
8040 | // superclasses, categories, implementation, etc. | |||
8041 | Results.EnterNewScope(); | |||
8042 | ||||
8043 | // If this is a send-to-super, try to add the special "super" send | |||
8044 | // completion. | |||
8045 | if (IsSuper) { | |||
8046 | if (ObjCMethodDecl *SuperMethod = | |||
8047 | AddSuperSendCompletion(SemaRef, false, SelIdents, Results)) | |||
8048 | Results.Ignore(SuperMethod); | |||
8049 | } | |||
8050 | ||||
8051 | // If we're inside an Objective-C method definition, prefer its selector to | |||
8052 | // others. | |||
8053 | if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl()) | |||
8054 | Results.setPreferredSelector(CurMethod->getSelector()); | |||
8055 | ||||
8056 | VisitedSelectorSet Selectors; | |||
8057 | if (CDecl) | |||
8058 | AddObjCMethods(CDecl, false, MK_Any, SelIdents, SemaRef.CurContext, | |||
8059 | Selectors, AtArgumentExpression, Results); | |||
8060 | else { | |||
8061 | // We're messaging "id" as a type; provide all class/factory methods. | |||
8062 | ||||
8063 | // If we have an external source, load the entire class method | |||
8064 | // pool from the AST file. | |||
8065 | if (SemaRef.getExternalSource()) { | |||
8066 | for (uint32_t I = 0, | |||
8067 | N = SemaRef.getExternalSource()->GetNumExternalSelectors(); | |||
8068 | I != N; ++I) { | |||
8069 | Selector Sel = SemaRef.getExternalSource()->GetExternalSelector(I); | |||
8070 | if (Sel.isNull() || SemaRef.MethodPool.count(Sel)) | |||
8071 | continue; | |||
8072 | ||||
8073 | SemaRef.ReadMethodPool(Sel); | |||
8074 | } | |||
8075 | } | |||
8076 | ||||
8077 | for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(), | |||
8078 | MEnd = SemaRef.MethodPool.end(); | |||
8079 | M != MEnd; ++M) { | |||
8080 | for (ObjCMethodList *MethList = &M->second.second; | |||
8081 | MethList && MethList->getMethod(); MethList = MethList->getNext()) { | |||
8082 | if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents)) | |||
8083 | continue; | |||
8084 | ||||
8085 | Result R(MethList->getMethod(), | |||
8086 | Results.getBasePriority(MethList->getMethod()), nullptr); | |||
8087 | R.StartParameter = SelIdents.size(); | |||
8088 | R.AllParametersAreInformative = false; | |||
8089 | Results.MaybeAddResult(R, SemaRef.CurContext); | |||
8090 | } | |||
8091 | } | |||
8092 | } | |||
8093 | ||||
8094 | Results.ExitScope(); | |||
8095 | } | |||
8096 | ||||
8097 | void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, | |||
8098 | ArrayRef<IdentifierInfo *> SelIdents, | |||
8099 | bool AtArgumentExpression, | |||
8100 | bool IsSuper) { | |||
8101 | ||||
8102 | QualType T = this->GetTypeFromParser(Receiver); | |||
8103 | ||||
8104 | ResultBuilder Results( | |||
8105 | *this, CodeCompleter->getAllocator(), | |||
8106 | CodeCompleter->getCodeCompletionTUInfo(), | |||
8107 | CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage, T, | |||
8108 | SelIdents)); | |||
8109 | ||||
8110 | AddClassMessageCompletions(*this, S, Receiver, SelIdents, | |||
8111 | AtArgumentExpression, IsSuper, Results); | |||
8112 | ||||
8113 | // If we're actually at the argument expression (rather than prior to the | |||
8114 | // selector), we're actually performing code completion for an expression. | |||
8115 | // Determine whether we have a single, best method. If so, we can | |||
8116 | // code-complete the expression using the corresponding parameter type as | |||
8117 | // our preferred type, improving completion results. | |||
8118 | if (AtArgumentExpression) { | |||
8119 | QualType PreferredType = | |||
8120 | getPreferredArgumentTypeForMessageSend(Results, SelIdents.size()); | |||
8121 | if (PreferredType.isNull()) | |||
8122 | CodeCompleteOrdinaryName(S, PCC_Expression); | |||
8123 | else | |||
8124 | CodeCompleteExpression(S, PreferredType); | |||
8125 | return; | |||
8126 | } | |||
8127 | ||||
8128 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
8129 | Results.data(), Results.size()); | |||
8130 | } | |||
8131 | ||||
8132 | void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, | |||
8133 | ArrayRef<IdentifierInfo *> SelIdents, | |||
8134 | bool AtArgumentExpression, | |||
8135 | ObjCInterfaceDecl *Super) { | |||
8136 | typedef CodeCompletionResult Result; | |||
8137 | ||||
8138 | Expr *RecExpr = static_cast<Expr *>(Receiver); | |||
8139 | ||||
8140 | // If necessary, apply function/array conversion to the receiver. | |||
8141 | // C99 6.7.5.3p[7,8]. | |||
8142 | if (RecExpr) { | |||
8143 | ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr); | |||
8144 | if (Conv.isInvalid()) // conversion failed. bail. | |||
8145 | return; | |||
8146 | RecExpr = Conv.get(); | |||
8147 | } | |||
8148 | QualType ReceiverType = RecExpr | |||
8149 | ? RecExpr->getType() | |||
8150 | : Super ? Context.getObjCObjectPointerType( | |||
8151 | Context.getObjCInterfaceType(Super)) | |||
8152 | : Context.getObjCIdType(); | |||
8153 | ||||
8154 | // If we're messaging an expression with type "id" or "Class", check | |||
8155 | // whether we know something special about the receiver that allows | |||
8156 | // us to assume a more-specific receiver type. | |||
8157 | if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType()) { | |||
8158 | if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) { | |||
8159 | if (ReceiverType->isObjCClassType()) | |||
8160 | return CodeCompleteObjCClassMessage( | |||
8161 | S, ParsedType::make(Context.getObjCInterfaceType(IFace)), SelIdents, | |||
8162 | AtArgumentExpression, Super); | |||
8163 | ||||
8164 | ReceiverType = | |||
8165 | Context.getObjCObjectPointerType(Context.getObjCInterfaceType(IFace)); | |||
8166 | } | |||
8167 | } else if (RecExpr && getLangOpts().CPlusPlus) { | |||
8168 | ExprResult Conv = PerformContextuallyConvertToObjCPointer(RecExpr); | |||
8169 | if (Conv.isUsable()) { | |||
8170 | RecExpr = Conv.get(); | |||
8171 | ReceiverType = RecExpr->getType(); | |||
8172 | } | |||
8173 | } | |||
8174 | ||||
8175 | // Build the set of methods we can see. | |||
8176 | ResultBuilder Results( | |||
8177 | *this, CodeCompleter->getAllocator(), | |||
8178 | CodeCompleter->getCodeCompletionTUInfo(), | |||
8179 | CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage, | |||
8180 | ReceiverType, SelIdents)); | |||
8181 | ||||
8182 | Results.EnterNewScope(); | |||
8183 | ||||
8184 | // If this is a send-to-super, try to add the special "super" send | |||
8185 | // completion. | |||
8186 | if (Super) { | |||
8187 | if (ObjCMethodDecl *SuperMethod = | |||
8188 | AddSuperSendCompletion(*this, false, SelIdents, Results)) | |||
8189 | Results.Ignore(SuperMethod); | |||
8190 | } | |||
8191 | ||||
8192 | // If we're inside an Objective-C method definition, prefer its selector to | |||
8193 | // others. | |||
8194 | if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) | |||
8195 | Results.setPreferredSelector(CurMethod->getSelector()); | |||
8196 | ||||
8197 | // Keep track of the selectors we've already added. | |||
8198 | VisitedSelectorSet Selectors; | |||
8199 | ||||
8200 | // Handle messages to Class. This really isn't a message to an instance | |||
8201 | // method, so we treat it the same way we would treat a message send to a | |||
8202 | // class method. | |||
8203 | if (ReceiverType->isObjCClassType() || | |||
8204 | ReceiverType->isObjCQualifiedClassType()) { | |||
8205 | if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) { | |||
8206 | if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface()) | |||
8207 | AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, CurContext, | |||
8208 | Selectors, AtArgumentExpression, Results); | |||
8209 | } | |||
8210 | } | |||
8211 | // Handle messages to a qualified ID ("id<foo>"). | |||
8212 | else if (const ObjCObjectPointerType *QualID = | |||
8213 | ReceiverType->getAsObjCQualifiedIdType()) { | |||
8214 | // Search protocols for instance methods. | |||
8215 | for (auto *I : QualID->quals()) | |||
8216 | AddObjCMethods(I, true, MK_Any, SelIdents, CurContext, Selectors, | |||
8217 | AtArgumentExpression, Results); | |||
8218 | } | |||
8219 | // Handle messages to a pointer to interface type. | |||
8220 | else if (const ObjCObjectPointerType *IFacePtr = | |||
8221 | ReceiverType->getAsObjCInterfacePointerType()) { | |||
8222 | // Search the class, its superclasses, etc., for instance methods. | |||
8223 | AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents, | |||
8224 | CurContext, Selectors, AtArgumentExpression, Results); | |||
8225 | ||||
8226 | // Search protocols for instance methods. | |||
8227 | for (auto *I : IFacePtr->quals()) | |||
8228 | AddObjCMethods(I, true, MK_Any, SelIdents, CurContext, Selectors, | |||
8229 | AtArgumentExpression, Results); | |||
8230 | } | |||
8231 | // Handle messages to "id". | |||
8232 | else if (ReceiverType->isObjCIdType()) { | |||
8233 | // We're messaging "id", so provide all instance methods we know | |||
8234 | // about as code-completion results. | |||
8235 | ||||
8236 | // If we have an external source, load the entire class method | |||
8237 | // pool from the AST file. | |||
8238 | if (ExternalSource) { | |||
8239 | for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); | |||
8240 | I != N; ++I) { | |||
8241 | Selector Sel = ExternalSource->GetExternalSelector(I); | |||
8242 | if (Sel.isNull() || MethodPool.count(Sel)) | |||
8243 | continue; | |||
8244 | ||||
8245 | ReadMethodPool(Sel); | |||
8246 | } | |||
8247 | } | |||
8248 | ||||
8249 | for (GlobalMethodPool::iterator M = MethodPool.begin(), | |||
8250 | MEnd = MethodPool.end(); | |||
8251 | M != MEnd; ++M) { | |||
8252 | for (ObjCMethodList *MethList = &M->second.first; | |||
8253 | MethList && MethList->getMethod(); MethList = MethList->getNext()) { | |||
8254 | if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents)) | |||
8255 | continue; | |||
8256 | ||||
8257 | if (!Selectors.insert(MethList->getMethod()->getSelector()).second) | |||
8258 | continue; | |||
8259 | ||||
8260 | Result R(MethList->getMethod(), | |||
8261 | Results.getBasePriority(MethList->getMethod()), nullptr); | |||
8262 | R.StartParameter = SelIdents.size(); | |||
8263 | R.AllParametersAreInformative = false; | |||
8264 | Results.MaybeAddResult(R, CurContext); | |||
8265 | } | |||
8266 | } | |||
8267 | } | |||
8268 | Results.ExitScope(); | |||
8269 | ||||
8270 | // If we're actually at the argument expression (rather than prior to the | |||
8271 | // selector), we're actually performing code completion for an expression. | |||
8272 | // Determine whether we have a single, best method. If so, we can | |||
8273 | // code-complete the expression using the corresponding parameter type as | |||
8274 | // our preferred type, improving completion results. | |||
8275 | if (AtArgumentExpression) { | |||
8276 | QualType PreferredType = | |||
8277 | getPreferredArgumentTypeForMessageSend(Results, SelIdents.size()); | |||
8278 | if (PreferredType.isNull()) | |||
8279 | CodeCompleteOrdinaryName(S, PCC_Expression); | |||
8280 | else | |||
8281 | CodeCompleteExpression(S, PreferredType); | |||
8282 | return; | |||
8283 | } | |||
8284 | ||||
8285 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
8286 | Results.data(), Results.size()); | |||
8287 | } | |||
8288 | ||||
8289 | void Sema::CodeCompleteObjCForCollection(Scope *S, | |||
8290 | DeclGroupPtrTy IterationVar) { | |||
8291 | CodeCompleteExpressionData Data; | |||
8292 | Data.ObjCCollection = true; | |||
8293 | ||||
8294 | if (IterationVar.getAsOpaquePtr()) { | |||
8295 | DeclGroupRef DG = IterationVar.get(); | |||
8296 | for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) { | |||
8297 | if (*I) | |||
8298 | Data.IgnoreDecls.push_back(*I); | |||
8299 | } | |||
8300 | } | |||
8301 | ||||
8302 | CodeCompleteExpression(S, Data); | |||
8303 | } | |||
8304 | ||||
8305 | void Sema::CodeCompleteObjCSelector(Scope *S, | |||
8306 | ArrayRef<IdentifierInfo *> SelIdents) { | |||
8307 | // If we have an external source, load the entire class method | |||
8308 | // pool from the AST file. | |||
8309 | if (ExternalSource) { | |||
8310 | for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); I != N; | |||
8311 | ++I) { | |||
8312 | Selector Sel = ExternalSource->GetExternalSelector(I); | |||
8313 | if (Sel.isNull() || MethodPool.count(Sel)) | |||
8314 | continue; | |||
8315 | ||||
8316 | ReadMethodPool(Sel); | |||
8317 | } | |||
8318 | } | |||
8319 | ||||
8320 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
8321 | CodeCompleter->getCodeCompletionTUInfo(), | |||
8322 | CodeCompletionContext::CCC_SelectorName); | |||
8323 | Results.EnterNewScope(); | |||
8324 | for (GlobalMethodPool::iterator M = MethodPool.begin(), | |||
8325 | MEnd = MethodPool.end(); | |||
8326 | M != MEnd; ++M) { | |||
8327 | ||||
8328 | Selector Sel = M->first; | |||
8329 | if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents)) | |||
8330 | continue; | |||
8331 | ||||
8332 | CodeCompletionBuilder Builder(Results.getAllocator(), | |||
8333 | Results.getCodeCompletionTUInfo()); | |||
8334 | if (Sel.isUnarySelector()) { | |||
8335 | Builder.AddTypedTextChunk( | |||
8336 | Builder.getAllocator().CopyString(Sel.getNameForSlot(0))); | |||
8337 | Results.AddResult(Builder.TakeString()); | |||
8338 | continue; | |||
8339 | } | |||
8340 | ||||
8341 | std::string Accumulator; | |||
8342 | for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) { | |||
8343 | if (I == SelIdents.size()) { | |||
8344 | if (!Accumulator.empty()) { | |||
8345 | Builder.AddInformativeChunk( | |||
8346 | Builder.getAllocator().CopyString(Accumulator)); | |||
8347 | Accumulator.clear(); | |||
8348 | } | |||
8349 | } | |||
8350 | ||||
8351 | Accumulator += Sel.getNameForSlot(I); | |||
8352 | Accumulator += ':'; | |||
8353 | } | |||
8354 | Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(Accumulator)); | |||
8355 | Results.AddResult(Builder.TakeString()); | |||
8356 | } | |||
8357 | Results.ExitScope(); | |||
8358 | ||||
8359 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
8360 | Results.data(), Results.size()); | |||
8361 | } | |||
8362 | ||||
8363 | /// Add all of the protocol declarations that we find in the given | |||
8364 | /// (translation unit) context. | |||
8365 | static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext, | |||
8366 | bool OnlyForwardDeclarations, | |||
8367 | ResultBuilder &Results) { | |||
8368 | typedef CodeCompletionResult Result; | |||
8369 | ||||
8370 | for (const auto *D : Ctx->decls()) { | |||
8371 | // Record any protocols we find. | |||
8372 | if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(D)) | |||
8373 | if (!OnlyForwardDeclarations || !Proto->hasDefinition()) | |||
8374 | Results.AddResult( | |||
8375 | Result(Proto, Results.getBasePriority(Proto), nullptr), CurContext, | |||
8376 | nullptr, false); | |||
8377 | } | |||
8378 | } | |||
8379 | ||||
8380 | void Sema::CodeCompleteObjCProtocolReferences( | |||
8381 | ArrayRef<IdentifierLocPair> Protocols) { | |||
8382 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
8383 | CodeCompleter->getCodeCompletionTUInfo(), | |||
8384 | CodeCompletionContext::CCC_ObjCProtocolName); | |||
8385 | ||||
8386 | if (CodeCompleter->includeGlobals()) { | |||
8387 | Results.EnterNewScope(); | |||
8388 | ||||
8389 | // Tell the result set to ignore all of the protocols we have | |||
8390 | // already seen. | |||
8391 | // FIXME: This doesn't work when caching code-completion results. | |||
8392 | for (const IdentifierLocPair &Pair : Protocols) | |||
8393 | if (ObjCProtocolDecl *Protocol = LookupProtocol(Pair.first, Pair.second)) | |||
8394 | Results.Ignore(Protocol); | |||
8395 | ||||
8396 | // Add all protocols. | |||
8397 | AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false, | |||
8398 | Results); | |||
8399 | ||||
8400 | Results.ExitScope(); | |||
8401 | } | |||
8402 | ||||
8403 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
8404 | Results.data(), Results.size()); | |||
8405 | } | |||
8406 | ||||
8407 | void Sema::CodeCompleteObjCProtocolDecl(Scope *) { | |||
8408 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
8409 | CodeCompleter->getCodeCompletionTUInfo(), | |||
8410 | CodeCompletionContext::CCC_ObjCProtocolName); | |||
8411 | ||||
8412 | if (CodeCompleter->includeGlobals()) { | |||
8413 | Results.EnterNewScope(); | |||
8414 | ||||
8415 | // Add all protocols. | |||
8416 | AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true, | |||
8417 | Results); | |||
8418 | ||||
8419 | Results.ExitScope(); | |||
8420 | } | |||
8421 | ||||
8422 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
8423 | Results.data(), Results.size()); | |||
8424 | } | |||
8425 | ||||
8426 | /// Add all of the Objective-C interface declarations that we find in | |||
8427 | /// the given (translation unit) context. | |||
8428 | static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext, | |||
8429 | bool OnlyForwardDeclarations, | |||
8430 | bool OnlyUnimplemented, | |||
8431 | ResultBuilder &Results) { | |||
8432 | typedef CodeCompletionResult Result; | |||
8433 | ||||
8434 | for (const auto *D : Ctx->decls()) { | |||
8435 | // Record any interfaces we find. | |||
8436 | if (const auto *Class = dyn_cast<ObjCInterfaceDecl>(D)) | |||
8437 | if ((!OnlyForwardDeclarations || !Class->hasDefinition()) && | |||
8438 | (!OnlyUnimplemented || !Class->getImplementation())) | |||
8439 | Results.AddResult( | |||
8440 | Result(Class, Results.getBasePriority(Class), nullptr), CurContext, | |||
8441 | nullptr, false); | |||
8442 | } | |||
8443 | } | |||
8444 | ||||
8445 | void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) { | |||
8446 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
8447 | CodeCompleter->getCodeCompletionTUInfo(), | |||
8448 | CodeCompletionContext::CCC_ObjCInterfaceName); | |||
8449 | Results.EnterNewScope(); | |||
8450 | ||||
8451 | if (CodeCompleter->includeGlobals()) { | |||
8452 | // Add all classes. | |||
8453 | AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false, | |||
8454 | false, Results); | |||
8455 | } | |||
8456 | ||||
8457 | Results.ExitScope(); | |||
8458 | ||||
8459 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
8460 | Results.data(), Results.size()); | |||
8461 | } | |||
8462 | ||||
8463 | void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName, | |||
8464 | SourceLocation ClassNameLoc) { | |||
8465 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
8466 | CodeCompleter->getCodeCompletionTUInfo(), | |||
8467 | CodeCompletionContext::CCC_ObjCInterfaceName); | |||
8468 | Results.EnterNewScope(); | |||
8469 | ||||
8470 | // Make sure that we ignore the class we're currently defining. | |||
8471 | NamedDecl *CurClass = | |||
8472 | LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName); | |||
8473 | if (CurClass && isa<ObjCInterfaceDecl>(CurClass)) | |||
8474 | Results.Ignore(CurClass); | |||
8475 | ||||
8476 | if (CodeCompleter->includeGlobals()) { | |||
8477 | // Add all classes. | |||
8478 | AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false, | |||
8479 | false, Results); | |||
8480 | } | |||
8481 | ||||
8482 | Results.ExitScope(); | |||
8483 | ||||
8484 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
8485 | Results.data(), Results.size()); | |||
8486 | } | |||
8487 | ||||
8488 | void Sema::CodeCompleteObjCImplementationDecl(Scope *S) { | |||
8489 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
8490 | CodeCompleter->getCodeCompletionTUInfo(), | |||
8491 | CodeCompletionContext::CCC_ObjCImplementation); | |||
8492 | Results.EnterNewScope(); | |||
8493 | ||||
8494 | if (CodeCompleter->includeGlobals()) { | |||
8495 | // Add all unimplemented classes. | |||
8496 | AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false, | |||
8497 | true, Results); | |||
8498 | } | |||
8499 | ||||
8500 | Results.ExitScope(); | |||
8501 | ||||
8502 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
8503 | Results.data(), Results.size()); | |||
8504 | } | |||
8505 | ||||
8506 | void Sema::CodeCompleteObjCInterfaceCategory(Scope *S, | |||
8507 | IdentifierInfo *ClassName, | |||
8508 | SourceLocation ClassNameLoc) { | |||
8509 | typedef CodeCompletionResult Result; | |||
8510 | ||||
8511 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
8512 | CodeCompleter->getCodeCompletionTUInfo(), | |||
8513 | CodeCompletionContext::CCC_ObjCCategoryName); | |||
8514 | ||||
8515 | // Ignore any categories we find that have already been implemented by this | |||
8516 | // interface. | |||
8517 | llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames; | |||
8518 | NamedDecl *CurClass = | |||
8519 | LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName); | |||
8520 | if (ObjCInterfaceDecl *Class = | |||
8521 | dyn_cast_or_null<ObjCInterfaceDecl>(CurClass)) { | |||
8522 | for (const auto *Cat : Class->visible_categories()) | |||
8523 | CategoryNames.insert(Cat->getIdentifier()); | |||
8524 | } | |||
8525 | ||||
8526 | // Add all of the categories we know about. | |||
8527 | Results.EnterNewScope(); | |||
8528 | TranslationUnitDecl *TU = Context.getTranslationUnitDecl(); | |||
8529 | for (const auto *D : TU->decls()) | |||
8530 | if (const auto *Category = dyn_cast<ObjCCategoryDecl>(D)) | |||
8531 | if (CategoryNames.insert(Category->getIdentifier()).second) | |||
8532 | Results.AddResult( | |||
8533 | Result(Category, Results.getBasePriority(Category), nullptr), | |||
8534 | CurContext, nullptr, false); | |||
8535 | Results.ExitScope(); | |||
8536 | ||||
8537 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
8538 | Results.data(), Results.size()); | |||
8539 | } | |||
8540 | ||||
8541 | void Sema::CodeCompleteObjCImplementationCategory(Scope *S, | |||
8542 | IdentifierInfo *ClassName, | |||
8543 | SourceLocation ClassNameLoc) { | |||
8544 | typedef CodeCompletionResult Result; | |||
8545 | ||||
8546 | // Find the corresponding interface. If we couldn't find the interface, the | |||
8547 | // program itself is ill-formed. However, we'll try to be helpful still by | |||
8548 | // providing the list of all of the categories we know about. | |||
8549 | NamedDecl *CurClass = | |||
8550 | LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName); | |||
8551 | ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass); | |||
8552 | if (!Class) | |||
8553 | return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc); | |||
8554 | ||||
8555 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
8556 | CodeCompleter->getCodeCompletionTUInfo(), | |||
8557 | CodeCompletionContext::CCC_ObjCCategoryName); | |||
8558 | ||||
8559 | // Add all of the categories that have corresponding interface | |||
8560 | // declarations in this class and any of its superclasses, except for | |||
8561 | // already-implemented categories in the class itself. | |||
8562 | llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames; | |||
8563 | Results.EnterNewScope(); | |||
8564 | bool IgnoreImplemented = true; | |||
8565 | while (Class) { | |||
8566 | for (const auto *Cat : Class->visible_categories()) { | |||
8567 | if ((!IgnoreImplemented || !Cat->getImplementation()) && | |||
8568 | CategoryNames.insert(Cat->getIdentifier()).second) | |||
8569 | Results.AddResult(Result(Cat, Results.getBasePriority(Cat), nullptr), | |||
8570 | CurContext, nullptr, false); | |||
8571 | } | |||
8572 | ||||
8573 | Class = Class->getSuperClass(); | |||
8574 | IgnoreImplemented = false; | |||
8575 | } | |||
8576 | Results.ExitScope(); | |||
8577 | ||||
8578 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
8579 | Results.data(), Results.size()); | |||
8580 | } | |||
8581 | ||||
8582 | void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) { | |||
8583 | CodeCompletionContext CCContext(CodeCompletionContext::CCC_Other); | |||
8584 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
8585 | CodeCompleter->getCodeCompletionTUInfo(), CCContext); | |||
8586 | ||||
8587 | // Figure out where this @synthesize lives. | |||
8588 | ObjCContainerDecl *Container = | |||
8589 | dyn_cast_or_null<ObjCContainerDecl>(CurContext); | |||
8590 | if (!Container || (!isa<ObjCImplementationDecl>(Container) && | |||
8591 | !isa<ObjCCategoryImplDecl>(Container))) | |||
8592 | return; | |||
8593 | ||||
8594 | // Ignore any properties that have already been implemented. | |||
8595 | Container = getContainerDef(Container); | |||
8596 | for (const auto *D : Container->decls()) | |||
8597 | if (const auto *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(D)) | |||
8598 | Results.Ignore(PropertyImpl->getPropertyDecl()); | |||
8599 | ||||
8600 | // Add any properties that we find. | |||
8601 | AddedPropertiesSet AddedProperties; | |||
8602 | Results.EnterNewScope(); | |||
8603 | if (ObjCImplementationDecl *ClassImpl = | |||
8604 | dyn_cast<ObjCImplementationDecl>(Container)) | |||
8605 | AddObjCProperties(CCContext, ClassImpl->getClassInterface(), false, | |||
8606 | /*AllowNullaryMethods=*/false, CurContext, | |||
8607 | AddedProperties, Results); | |||
8608 | else | |||
8609 | AddObjCProperties(CCContext, | |||
8610 | cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(), | |||
8611 | false, /*AllowNullaryMethods=*/false, CurContext, | |||
8612 | AddedProperties, Results); | |||
8613 | Results.ExitScope(); | |||
8614 | ||||
8615 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
8616 | Results.data(), Results.size()); | |||
8617 | } | |||
8618 | ||||
8619 | void Sema::CodeCompleteObjCPropertySynthesizeIvar( | |||
8620 | Scope *S, IdentifierInfo *PropertyName) { | |||
8621 | typedef CodeCompletionResult Result; | |||
8622 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
8623 | CodeCompleter->getCodeCompletionTUInfo(), | |||
8624 | CodeCompletionContext::CCC_Other); | |||
8625 | ||||
8626 | // Figure out where this @synthesize lives. | |||
8627 | ObjCContainerDecl *Container = | |||
8628 | dyn_cast_or_null<ObjCContainerDecl>(CurContext); | |||
8629 | if (!Container || (!isa<ObjCImplementationDecl>(Container) && | |||
8630 | !isa<ObjCCategoryImplDecl>(Container))) | |||
8631 | return; | |||
8632 | ||||
8633 | // Figure out which interface we're looking into. | |||
8634 | ObjCInterfaceDecl *Class = nullptr; | |||
8635 | if (ObjCImplementationDecl *ClassImpl = | |||
8636 | dyn_cast<ObjCImplementationDecl>(Container)) | |||
8637 | Class = ClassImpl->getClassInterface(); | |||
8638 | else | |||
8639 | Class = cast<ObjCCategoryImplDecl>(Container) | |||
8640 | ->getCategoryDecl() | |||
8641 | ->getClassInterface(); | |||
8642 | ||||
8643 | // Determine the type of the property we're synthesizing. | |||
8644 | QualType PropertyType = Context.getObjCIdType(); | |||
8645 | if (Class) { | |||
8646 | if (ObjCPropertyDecl *Property = Class->FindPropertyDeclaration( | |||
8647 | PropertyName, ObjCPropertyQueryKind::OBJC_PR_query_instance)) { | |||
8648 | PropertyType = | |||
8649 | Property->getType().getNonReferenceType().getUnqualifiedType(); | |||
8650 | ||||
8651 | // Give preference to ivars | |||
8652 | Results.setPreferredType(PropertyType); | |||
8653 | } | |||
8654 | } | |||
8655 | ||||
8656 | // Add all of the instance variables in this class and its superclasses. | |||
8657 | Results.EnterNewScope(); | |||
8658 | bool SawSimilarlyNamedIvar = false; | |||
8659 | std::string NameWithPrefix; | |||
8660 | NameWithPrefix += '_'; | |||
8661 | NameWithPrefix += PropertyName->getName(); | |||
8662 | std::string NameWithSuffix = PropertyName->getName().str(); | |||
8663 | NameWithSuffix += '_'; | |||
8664 | for (; Class; Class = Class->getSuperClass()) { | |||
8665 | for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar; | |||
8666 | Ivar = Ivar->getNextIvar()) { | |||
8667 | Results.AddResult(Result(Ivar, Results.getBasePriority(Ivar), nullptr), | |||
8668 | CurContext, nullptr, false); | |||
8669 | ||||
8670 | // Determine whether we've seen an ivar with a name similar to the | |||
8671 | // property. | |||
8672 | if ((PropertyName == Ivar->getIdentifier() || | |||
8673 | NameWithPrefix == Ivar->getName() || | |||
8674 | NameWithSuffix == Ivar->getName())) { | |||
8675 | SawSimilarlyNamedIvar = true; | |||
8676 | ||||
8677 | // Reduce the priority of this result by one, to give it a slight | |||
8678 | // advantage over other results whose names don't match so closely. | |||
8679 | if (Results.size() && | |||
8680 | Results.data()[Results.size() - 1].Kind == | |||
8681 | CodeCompletionResult::RK_Declaration && | |||
8682 | Results.data()[Results.size() - 1].Declaration == Ivar) | |||
8683 | Results.data()[Results.size() - 1].Priority--; | |||
8684 | } | |||
8685 | } | |||
8686 | } | |||
8687 | ||||
8688 | if (!SawSimilarlyNamedIvar) { | |||
8689 | // Create ivar result _propName, that the user can use to synthesize | |||
8690 | // an ivar of the appropriate type. | |||
8691 | unsigned Priority = CCP_MemberDeclaration + 1; | |||
8692 | typedef CodeCompletionResult Result; | |||
8693 | CodeCompletionAllocator &Allocator = Results.getAllocator(); | |||
8694 | CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo(), | |||
8695 | Priority, CXAvailability_Available); | |||
8696 | ||||
8697 | PrintingPolicy Policy = getCompletionPrintingPolicy(*this); | |||
8698 | Builder.AddResultTypeChunk( | |||
8699 | GetCompletionTypeString(PropertyType, Context, Policy, Allocator)); | |||
8700 | Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix)); | |||
8701 | Results.AddResult( | |||
8702 | Result(Builder.TakeString(), Priority, CXCursor_ObjCIvarDecl)); | |||
8703 | } | |||
8704 | ||||
8705 | Results.ExitScope(); | |||
8706 | ||||
8707 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
8708 | Results.data(), Results.size()); | |||
8709 | } | |||
8710 | ||||
8711 | // Mapping from selectors to the methods that implement that selector, along | |||
8712 | // with the "in original class" flag. | |||
8713 | typedef llvm::DenseMap<Selector, | |||
8714 | llvm::PointerIntPair<ObjCMethodDecl *, 1, bool>> | |||
8715 | KnownMethodsMap; | |||
8716 | ||||
8717 | /// Find all of the methods that reside in the given container | |||
8718 | /// (and its superclasses, protocols, etc.) that meet the given | |||
8719 | /// criteria. Insert those methods into the map of known methods, | |||
8720 | /// indexed by selector so they can be easily found. | |||
8721 | static void FindImplementableMethods(ASTContext &Context, | |||
8722 | ObjCContainerDecl *Container, | |||
8723 | std::optional<bool> WantInstanceMethods, | |||
8724 | QualType ReturnType, | |||
8725 | KnownMethodsMap &KnownMethods, | |||
8726 | bool InOriginalClass = true) { | |||
8727 | if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) { | |||
8728 | // Make sure we have a definition; that's what we'll walk. | |||
8729 | if (!IFace->hasDefinition()) | |||
8730 | return; | |||
8731 | ||||
8732 | IFace = IFace->getDefinition(); | |||
8733 | Container = IFace; | |||
8734 | ||||
8735 | const ObjCList<ObjCProtocolDecl> &Protocols = | |||
8736 | IFace->getReferencedProtocols(); | |||
8737 | for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), | |||
8738 | E = Protocols.end(); | |||
8739 | I != E; ++I) | |||
8740 | FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, | |||
8741 | KnownMethods, InOriginalClass); | |||
8742 | ||||
8743 | // Add methods from any class extensions and categories. | |||
8744 | for (auto *Cat : IFace->visible_categories()) { | |||
8745 | FindImplementableMethods(Context, Cat, WantInstanceMethods, ReturnType, | |||
8746 | KnownMethods, false); | |||
8747 | } | |||
8748 | ||||
8749 | // Visit the superclass. | |||
8750 | if (IFace->getSuperClass()) | |||
8751 | FindImplementableMethods(Context, IFace->getSuperClass(), | |||
8752 | WantInstanceMethods, ReturnType, KnownMethods, | |||
8753 | false); | |||
8754 | } | |||
8755 | ||||
8756 | if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) { | |||
8757 | // Recurse into protocols. | |||
8758 | const ObjCList<ObjCProtocolDecl> &Protocols = | |||
8759 | Category->getReferencedProtocols(); | |||
8760 | for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), | |||
8761 | E = Protocols.end(); | |||
8762 | I != E; ++I) | |||
8763 | FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, | |||
8764 | KnownMethods, InOriginalClass); | |||
8765 | ||||
8766 | // If this category is the original class, jump to the interface. | |||
8767 | if (InOriginalClass && Category->getClassInterface()) | |||
8768 | FindImplementableMethods(Context, Category->getClassInterface(), | |||
8769 | WantInstanceMethods, ReturnType, KnownMethods, | |||
8770 | false); | |||
8771 | } | |||
8772 | ||||
8773 | if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) { | |||
8774 | // Make sure we have a definition; that's what we'll walk. | |||
8775 | if (!Protocol->hasDefinition()) | |||
8776 | return; | |||
8777 | Protocol = Protocol->getDefinition(); | |||
8778 | Container = Protocol; | |||
8779 | ||||
8780 | // Recurse into protocols. | |||
8781 | const ObjCList<ObjCProtocolDecl> &Protocols = | |||
8782 | Protocol->getReferencedProtocols(); | |||
8783 | for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), | |||
8784 | E = Protocols.end(); | |||
8785 | I != E; ++I) | |||
8786 | FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, | |||
8787 | KnownMethods, false); | |||
8788 | } | |||
8789 | ||||
8790 | // Add methods in this container. This operation occurs last because | |||
8791 | // we want the methods from this container to override any methods | |||
8792 | // we've previously seen with the same selector. | |||
8793 | for (auto *M : Container->methods()) { | |||
8794 | if (!WantInstanceMethods || M->isInstanceMethod() == *WantInstanceMethods) { | |||
8795 | if (!ReturnType.isNull() && | |||
8796 | !Context.hasSameUnqualifiedType(ReturnType, M->getReturnType())) | |||
8797 | continue; | |||
8798 | ||||
8799 | KnownMethods[M->getSelector()] = | |||
8800 | KnownMethodsMap::mapped_type(M, InOriginalClass); | |||
8801 | } | |||
8802 | } | |||
8803 | } | |||
8804 | ||||
8805 | /// Add the parenthesized return or parameter type chunk to a code | |||
8806 | /// completion string. | |||
8807 | static void AddObjCPassingTypeChunk(QualType Type, unsigned ObjCDeclQuals, | |||
8808 | ASTContext &Context, | |||
8809 | const PrintingPolicy &Policy, | |||
8810 | CodeCompletionBuilder &Builder) { | |||
8811 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
8812 | std::string Quals = formatObjCParamQualifiers(ObjCDeclQuals, Type); | |||
8813 | if (!Quals.empty()) | |||
8814 | Builder.AddTextChunk(Builder.getAllocator().CopyString(Quals)); | |||
8815 | Builder.AddTextChunk( | |||
8816 | GetCompletionTypeString(Type, Context, Policy, Builder.getAllocator())); | |||
8817 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
8818 | } | |||
8819 | ||||
8820 | /// Determine whether the given class is or inherits from a class by | |||
8821 | /// the given name. | |||
8822 | static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class, StringRef Name) { | |||
8823 | if (!Class) | |||
8824 | return false; | |||
8825 | ||||
8826 | if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name) | |||
8827 | return true; | |||
8828 | ||||
8829 | return InheritsFromClassNamed(Class->getSuperClass(), Name); | |||
8830 | } | |||
8831 | ||||
8832 | /// Add code completions for Objective-C Key-Value Coding (KVC) and | |||
8833 | /// Key-Value Observing (KVO). | |||
8834 | static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, | |||
8835 | bool IsInstanceMethod, | |||
8836 | QualType ReturnType, ASTContext &Context, | |||
8837 | VisitedSelectorSet &KnownSelectors, | |||
8838 | ResultBuilder &Results) { | |||
8839 | IdentifierInfo *PropName = Property->getIdentifier(); | |||
8840 | if (!PropName || PropName->getLength() == 0) | |||
8841 | return; | |||
8842 | ||||
8843 | PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema()); | |||
8844 | ||||
8845 | // Builder that will create each code completion. | |||
8846 | typedef CodeCompletionResult Result; | |||
8847 | CodeCompletionAllocator &Allocator = Results.getAllocator(); | |||
8848 | CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo()); | |||
8849 | ||||
8850 | // The selector table. | |||
8851 | SelectorTable &Selectors = Context.Selectors; | |||
8852 | ||||
8853 | // The property name, copied into the code completion allocation region | |||
8854 | // on demand. | |||
8855 | struct KeyHolder { | |||
8856 | CodeCompletionAllocator &Allocator; | |||
8857 | StringRef Key; | |||
8858 | const char *CopiedKey; | |||
8859 | ||||
8860 | KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key) | |||
8861 | : Allocator(Allocator), Key(Key), CopiedKey(nullptr) {} | |||
8862 | ||||
8863 | operator const char *() { | |||
8864 | if (CopiedKey) | |||
8865 | return CopiedKey; | |||
8866 | ||||
8867 | return CopiedKey = Allocator.CopyString(Key); | |||
8868 | } | |||
8869 | } Key(Allocator, PropName->getName()); | |||
8870 | ||||
8871 | // The uppercased name of the property name. | |||
8872 | std::string UpperKey = std::string(PropName->getName()); | |||
8873 | if (!UpperKey.empty()) | |||
8874 | UpperKey[0] = toUppercase(UpperKey[0]); | |||
8875 | ||||
8876 | bool ReturnTypeMatchesProperty = | |||
8877 | ReturnType.isNull() || | |||
8878 | Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(), | |||
8879 | Property->getType()); | |||
8880 | bool ReturnTypeMatchesVoid = ReturnType.isNull() || ReturnType->isVoidType(); | |||
8881 | ||||
8882 | // Add the normal accessor -(type)key. | |||
8883 | if (IsInstanceMethod && | |||
8884 | KnownSelectors.insert(Selectors.getNullarySelector(PropName)).second && | |||
8885 | ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) { | |||
8886 | if (ReturnType.isNull()) | |||
8887 | AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0, Context, Policy, | |||
8888 | Builder); | |||
8889 | ||||
8890 | Builder.AddTypedTextChunk(Key); | |||
8891 | Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, | |||
8892 | CXCursor_ObjCInstanceMethodDecl)); | |||
8893 | } | |||
8894 | ||||
8895 | // If we have an integral or boolean property (or the user has provided | |||
8896 | // an integral or boolean return type), add the accessor -(type)isKey. | |||
8897 | if (IsInstanceMethod && | |||
8898 | ((!ReturnType.isNull() && | |||
8899 | (ReturnType->isIntegerType() || ReturnType->isBooleanType())) || | |||
8900 | (ReturnType.isNull() && (Property->getType()->isIntegerType() || | |||
8901 | Property->getType()->isBooleanType())))) { | |||
8902 | std::string SelectorName = (Twine("is") + UpperKey).str(); | |||
8903 | IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); | |||
8904 | if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) | |||
8905 | .second) { | |||
8906 | if (ReturnType.isNull()) { | |||
8907 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
8908 | Builder.AddTextChunk("BOOL"); | |||
8909 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
8910 | } | |||
8911 | ||||
8912 | Builder.AddTypedTextChunk(Allocator.CopyString(SelectorId->getName())); | |||
8913 | Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, | |||
8914 | CXCursor_ObjCInstanceMethodDecl)); | |||
8915 | } | |||
8916 | } | |||
8917 | ||||
8918 | // Add the normal mutator. | |||
8919 | if (IsInstanceMethod && ReturnTypeMatchesVoid && | |||
8920 | !Property->getSetterMethodDecl()) { | |||
8921 | std::string SelectorName = (Twine("set") + UpperKey).str(); | |||
8922 | IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); | |||
8923 | if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { | |||
8924 | if (ReturnType.isNull()) { | |||
8925 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
8926 | Builder.AddTextChunk("void"); | |||
8927 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
8928 | } | |||
8929 | ||||
8930 | Builder.AddTypedTextChunk( | |||
8931 | Allocator.CopyString(SelectorId->getName() + ":")); | |||
8932 | AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0, Context, Policy, | |||
8933 | Builder); | |||
8934 | Builder.AddTextChunk(Key); | |||
8935 | Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, | |||
8936 | CXCursor_ObjCInstanceMethodDecl)); | |||
8937 | } | |||
8938 | } | |||
8939 | ||||
8940 | // Indexed and unordered accessors | |||
8941 | unsigned IndexedGetterPriority = CCP_CodePattern; | |||
8942 | unsigned IndexedSetterPriority = CCP_CodePattern; | |||
8943 | unsigned UnorderedGetterPriority = CCP_CodePattern; | |||
8944 | unsigned UnorderedSetterPriority = CCP_CodePattern; | |||
8945 | if (const auto *ObjCPointer = | |||
8946 | Property->getType()->getAs<ObjCObjectPointerType>()) { | |||
8947 | if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) { | |||
8948 | // If this interface type is not provably derived from a known | |||
8949 | // collection, penalize the corresponding completions. | |||
8950 | if (!InheritsFromClassNamed(IFace, "NSMutableArray")) { | |||
8951 | IndexedSetterPriority += CCD_ProbablyNotObjCCollection; | |||
8952 | if (!InheritsFromClassNamed(IFace, "NSArray")) | |||
8953 | IndexedGetterPriority += CCD_ProbablyNotObjCCollection; | |||
8954 | } | |||
8955 | ||||
8956 | if (!InheritsFromClassNamed(IFace, "NSMutableSet")) { | |||
8957 | UnorderedSetterPriority += CCD_ProbablyNotObjCCollection; | |||
8958 | if (!InheritsFromClassNamed(IFace, "NSSet")) | |||
8959 | UnorderedGetterPriority += CCD_ProbablyNotObjCCollection; | |||
8960 | } | |||
8961 | } | |||
8962 | } else { | |||
8963 | IndexedGetterPriority += CCD_ProbablyNotObjCCollection; | |||
8964 | IndexedSetterPriority += CCD_ProbablyNotObjCCollection; | |||
8965 | UnorderedGetterPriority += CCD_ProbablyNotObjCCollection; | |||
8966 | UnorderedSetterPriority += CCD_ProbablyNotObjCCollection; | |||
8967 | } | |||
8968 | ||||
8969 | // Add -(NSUInteger)countOf<key> | |||
8970 | if (IsInstanceMethod && | |||
8971 | (ReturnType.isNull() || ReturnType->isIntegerType())) { | |||
8972 | std::string SelectorName = (Twine("countOf") + UpperKey).str(); | |||
8973 | IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); | |||
8974 | if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) | |||
8975 | .second) { | |||
8976 | if (ReturnType.isNull()) { | |||
8977 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
8978 | Builder.AddTextChunk("NSUInteger"); | |||
8979 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
8980 | } | |||
8981 | ||||
8982 | Builder.AddTypedTextChunk(Allocator.CopyString(SelectorId->getName())); | |||
8983 | Results.AddResult( | |||
8984 | Result(Builder.TakeString(), | |||
8985 | std::min(IndexedGetterPriority, UnorderedGetterPriority), | |||
8986 | CXCursor_ObjCInstanceMethodDecl)); | |||
8987 | } | |||
8988 | } | |||
8989 | ||||
8990 | // Indexed getters | |||
8991 | // Add -(id)objectInKeyAtIndex:(NSUInteger)index | |||
8992 | if (IsInstanceMethod && | |||
8993 | (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) { | |||
8994 | std::string SelectorName = (Twine("objectIn") + UpperKey + "AtIndex").str(); | |||
8995 | IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); | |||
8996 | if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { | |||
8997 | if (ReturnType.isNull()) { | |||
8998 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
8999 | Builder.AddTextChunk("id"); | |||
9000 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
9001 | } | |||
9002 | ||||
9003 | Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); | |||
9004 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
9005 | Builder.AddTextChunk("NSUInteger"); | |||
9006 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
9007 | Builder.AddTextChunk("index"); | |||
9008 | Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority, | |||
9009 | CXCursor_ObjCInstanceMethodDecl)); | |||
9010 | } | |||
9011 | } | |||
9012 | ||||
9013 | // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes | |||
9014 | if (IsInstanceMethod && | |||
9015 | (ReturnType.isNull() || | |||
9016 | (ReturnType->isObjCObjectPointerType() && | |||
9017 | ReturnType->castAs<ObjCObjectPointerType>()->getInterfaceDecl() && | |||
9018 | ReturnType->castAs<ObjCObjectPointerType>() | |||
9019 | ->getInterfaceDecl() | |||
9020 | ->getName() == "NSArray"))) { | |||
9021 | std::string SelectorName = (Twine(Property->getName()) + "AtIndexes").str(); | |||
9022 | IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); | |||
9023 | if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { | |||
9024 | if (ReturnType.isNull()) { | |||
9025 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
9026 | Builder.AddTextChunk("NSArray *"); | |||
9027 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
9028 | } | |||
9029 | ||||
9030 | Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); | |||
9031 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
9032 | Builder.AddTextChunk("NSIndexSet *"); | |||
9033 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
9034 | Builder.AddTextChunk("indexes"); | |||
9035 | Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority, | |||
9036 | CXCursor_ObjCInstanceMethodDecl)); | |||
9037 | } | |||
9038 | } | |||
9039 | ||||
9040 | // Add -(void)getKey:(type **)buffer range:(NSRange)inRange | |||
9041 | if (IsInstanceMethod && ReturnTypeMatchesVoid) { | |||
9042 | std::string SelectorName = (Twine("get") + UpperKey).str(); | |||
9043 | IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName), | |||
9044 | &Context.Idents.get("range")}; | |||
9045 | ||||
9046 | if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { | |||
9047 | if (ReturnType.isNull()) { | |||
9048 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
9049 | Builder.AddTextChunk("void"); | |||
9050 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
9051 | } | |||
9052 | ||||
9053 | Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); | |||
9054 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
9055 | Builder.AddPlaceholderChunk("object-type"); | |||
9056 | Builder.AddTextChunk(" **"); | |||
9057 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
9058 | Builder.AddTextChunk("buffer"); | |||
9059 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
9060 | Builder.AddTypedTextChunk("range:"); | |||
9061 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
9062 | Builder.AddTextChunk("NSRange"); | |||
9063 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
9064 | Builder.AddTextChunk("inRange"); | |||
9065 | Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority, | |||
9066 | CXCursor_ObjCInstanceMethodDecl)); | |||
9067 | } | |||
9068 | } | |||
9069 | ||||
9070 | // Mutable indexed accessors | |||
9071 | ||||
9072 | // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index | |||
9073 | if (IsInstanceMethod && ReturnTypeMatchesVoid) { | |||
9074 | std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str(); | |||
9075 | IdentifierInfo *SelectorIds[2] = {&Context.Idents.get("insertObject"), | |||
9076 | &Context.Idents.get(SelectorName)}; | |||
9077 | ||||
9078 | if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { | |||
9079 | if (ReturnType.isNull()) { | |||
9080 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
9081 | Builder.AddTextChunk("void"); | |||
9082 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
9083 | } | |||
9084 | ||||
9085 | Builder.AddTypedTextChunk("insertObject:"); | |||
9086 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
9087 | Builder.AddPlaceholderChunk("object-type"); | |||
9088 | Builder.AddTextChunk(" *"); | |||
9089 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
9090 | Builder.AddTextChunk("object"); | |||
9091 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
9092 | Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); | |||
9093 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
9094 | Builder.AddPlaceholderChunk("NSUInteger"); | |||
9095 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
9096 | Builder.AddTextChunk("index"); | |||
9097 | Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, | |||
9098 | CXCursor_ObjCInstanceMethodDecl)); | |||
9099 | } | |||
9100 | } | |||
9101 | ||||
9102 | // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes | |||
9103 | if (IsInstanceMethod && ReturnTypeMatchesVoid) { | |||
9104 | std::string SelectorName = (Twine("insert") + UpperKey).str(); | |||
9105 | IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName), | |||
9106 | &Context.Idents.get("atIndexes")}; | |||
9107 | ||||
9108 | if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { | |||
9109 | if (ReturnType.isNull()) { | |||
9110 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
9111 | Builder.AddTextChunk("void"); | |||
9112 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
9113 | } | |||
9114 | ||||
9115 | Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); | |||
9116 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
9117 | Builder.AddTextChunk("NSArray *"); | |||
9118 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
9119 | Builder.AddTextChunk("array"); | |||
9120 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
9121 | Builder.AddTypedTextChunk("atIndexes:"); | |||
9122 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
9123 | Builder.AddPlaceholderChunk("NSIndexSet *"); | |||
9124 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
9125 | Builder.AddTextChunk("indexes"); | |||
9126 | Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, | |||
9127 | CXCursor_ObjCInstanceMethodDecl)); | |||
9128 | } | |||
9129 | } | |||
9130 | ||||
9131 | // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index | |||
9132 | if (IsInstanceMethod && ReturnTypeMatchesVoid) { | |||
9133 | std::string SelectorName = | |||
9134 | (Twine("removeObjectFrom") + UpperKey + "AtIndex").str(); | |||
9135 | IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); | |||
9136 | if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { | |||
9137 | if (ReturnType.isNull()) { | |||
9138 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
9139 | Builder.AddTextChunk("void"); | |||
9140 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
9141 | } | |||
9142 | ||||
9143 | Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); | |||
9144 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
9145 | Builder.AddTextChunk("NSUInteger"); | |||
9146 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
9147 | Builder.AddTextChunk("index"); | |||
9148 | Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, | |||
9149 | CXCursor_ObjCInstanceMethodDecl)); | |||
9150 | } | |||
9151 | } | |||
9152 | ||||
9153 | // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes | |||
9154 | if (IsInstanceMethod && ReturnTypeMatchesVoid) { | |||
9155 | std::string SelectorName = (Twine("remove") + UpperKey + "AtIndexes").str(); | |||
9156 | IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); | |||
9157 | if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { | |||
9158 | if (ReturnType.isNull()) { | |||
9159 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
9160 | Builder.AddTextChunk("void"); | |||
9161 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
9162 | } | |||
9163 | ||||
9164 | Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); | |||
9165 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
9166 | Builder.AddTextChunk("NSIndexSet *"); | |||
9167 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
9168 | Builder.AddTextChunk("indexes"); | |||
9169 | Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, | |||
9170 | CXCursor_ObjCInstanceMethodDecl)); | |||
9171 | } | |||
9172 | } | |||
9173 | ||||
9174 | // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object | |||
9175 | if (IsInstanceMethod && ReturnTypeMatchesVoid) { | |||
9176 | std::string SelectorName = | |||
9177 | (Twine("replaceObjectIn") + UpperKey + "AtIndex").str(); | |||
9178 | IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName), | |||
9179 | &Context.Idents.get("withObject")}; | |||
9180 | ||||
9181 | if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { | |||
9182 | if (ReturnType.isNull()) { | |||
9183 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
9184 | Builder.AddTextChunk("void"); | |||
9185 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
9186 | } | |||
9187 | ||||
9188 | Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); | |||
9189 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
9190 | Builder.AddPlaceholderChunk("NSUInteger"); | |||
9191 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
9192 | Builder.AddTextChunk("index"); | |||
9193 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
9194 | Builder.AddTypedTextChunk("withObject:"); | |||
9195 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
9196 | Builder.AddTextChunk("id"); | |||
9197 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
9198 | Builder.AddTextChunk("object"); | |||
9199 | Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, | |||
9200 | CXCursor_ObjCInstanceMethodDecl)); | |||
9201 | } | |||
9202 | } | |||
9203 | ||||
9204 | // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array | |||
9205 | if (IsInstanceMethod && ReturnTypeMatchesVoid) { | |||
9206 | std::string SelectorName1 = | |||
9207 | (Twine("replace") + UpperKey + "AtIndexes").str(); | |||
9208 | std::string SelectorName2 = (Twine("with") + UpperKey).str(); | |||
9209 | IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName1), | |||
9210 | &Context.Idents.get(SelectorName2)}; | |||
9211 | ||||
9212 | if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) { | |||
9213 | if (ReturnType.isNull()) { | |||
9214 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
9215 | Builder.AddTextChunk("void"); | |||
9216 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
9217 | } | |||
9218 | ||||
9219 | Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":")); | |||
9220 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
9221 | Builder.AddPlaceholderChunk("NSIndexSet *"); | |||
9222 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
9223 | Builder.AddTextChunk("indexes"); | |||
9224 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
9225 | Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":")); | |||
9226 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
9227 | Builder.AddTextChunk("NSArray *"); | |||
9228 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
9229 | Builder.AddTextChunk("array"); | |||
9230 | Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority, | |||
9231 | CXCursor_ObjCInstanceMethodDecl)); | |||
9232 | } | |||
9233 | } | |||
9234 | ||||
9235 | // Unordered getters | |||
9236 | // - (NSEnumerator *)enumeratorOfKey | |||
9237 | if (IsInstanceMethod && | |||
9238 | (ReturnType.isNull() || | |||
9239 | (ReturnType->isObjCObjectPointerType() && | |||
9240 | ReturnType->castAs<ObjCObjectPointerType>()->getInterfaceDecl() && | |||
9241 | ReturnType->castAs<ObjCObjectPointerType>() | |||
9242 | ->getInterfaceDecl() | |||
9243 | ->getName() == "NSEnumerator"))) { | |||
9244 | std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str(); | |||
9245 | IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); | |||
9246 | if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) | |||
9247 | .second) { | |||
9248 | if (ReturnType.isNull()) { | |||
9249 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
9250 | Builder.AddTextChunk("NSEnumerator *"); | |||
9251 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
9252 | } | |||
9253 | ||||
9254 | Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName)); | |||
9255 | Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority, | |||
9256 | CXCursor_ObjCInstanceMethodDecl)); | |||
9257 | } | |||
9258 | } | |||
9259 | ||||
9260 | // - (type *)memberOfKey:(type *)object | |||
9261 | if (IsInstanceMethod && | |||
9262 | (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) { | |||
9263 | std::string SelectorName = (Twine("memberOf") + UpperKey).str(); | |||
9264 | IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); | |||
9265 | if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { | |||
9266 | if (ReturnType.isNull()) { | |||
9267 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
9268 | Builder.AddPlaceholderChunk("object-type"); | |||
9269 | Builder.AddTextChunk(" *"); | |||
9270 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
9271 | } | |||
9272 | ||||
9273 | Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); | |||
9274 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
9275 | if (ReturnType.isNull()) { | |||
9276 | Builder.AddPlaceholderChunk("object-type"); | |||
9277 | Builder.AddTextChunk(" *"); | |||
9278 | } else { | |||
9279 | Builder.AddTextChunk(GetCompletionTypeString( | |||
9280 | ReturnType, Context, Policy, Builder.getAllocator())); | |||
9281 | } | |||
9282 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
9283 | Builder.AddTextChunk("object"); | |||
9284 | Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority, | |||
9285 | CXCursor_ObjCInstanceMethodDecl)); | |||
9286 | } | |||
9287 | } | |||
9288 | ||||
9289 | // Mutable unordered accessors | |||
9290 | // - (void)addKeyObject:(type *)object | |||
9291 | if (IsInstanceMethod && ReturnTypeMatchesVoid) { | |||
9292 | std::string SelectorName = | |||
9293 | (Twine("add") + UpperKey + Twine("Object")).str(); | |||
9294 | IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); | |||
9295 | if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { | |||
9296 | if (ReturnType.isNull()) { | |||
9297 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
9298 | Builder.AddTextChunk("void"); | |||
9299 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
9300 | } | |||
9301 | ||||
9302 | Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); | |||
9303 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
9304 | Builder.AddPlaceholderChunk("object-type"); | |||
9305 | Builder.AddTextChunk(" *"); | |||
9306 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
9307 | Builder.AddTextChunk("object"); | |||
9308 | Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, | |||
9309 | CXCursor_ObjCInstanceMethodDecl)); | |||
9310 | } | |||
9311 | } | |||
9312 | ||||
9313 | // - (void)addKey:(NSSet *)objects | |||
9314 | if (IsInstanceMethod && ReturnTypeMatchesVoid) { | |||
9315 | std::string SelectorName = (Twine("add") + UpperKey).str(); | |||
9316 | IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); | |||
9317 | if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { | |||
9318 | if (ReturnType.isNull()) { | |||
9319 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
9320 | Builder.AddTextChunk("void"); | |||
9321 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
9322 | } | |||
9323 | ||||
9324 | Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); | |||
9325 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
9326 | Builder.AddTextChunk("NSSet *"); | |||
9327 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
9328 | Builder.AddTextChunk("objects"); | |||
9329 | Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, | |||
9330 | CXCursor_ObjCInstanceMethodDecl)); | |||
9331 | } | |||
9332 | } | |||
9333 | ||||
9334 | // - (void)removeKeyObject:(type *)object | |||
9335 | if (IsInstanceMethod && ReturnTypeMatchesVoid) { | |||
9336 | std::string SelectorName = | |||
9337 | (Twine("remove") + UpperKey + Twine("Object")).str(); | |||
9338 | IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); | |||
9339 | if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { | |||
9340 | if (ReturnType.isNull()) { | |||
9341 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
9342 | Builder.AddTextChunk("void"); | |||
9343 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
9344 | } | |||
9345 | ||||
9346 | Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); | |||
9347 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
9348 | Builder.AddPlaceholderChunk("object-type"); | |||
9349 | Builder.AddTextChunk(" *"); | |||
9350 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
9351 | Builder.AddTextChunk("object"); | |||
9352 | Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, | |||
9353 | CXCursor_ObjCInstanceMethodDecl)); | |||
9354 | } | |||
9355 | } | |||
9356 | ||||
9357 | // - (void)removeKey:(NSSet *)objects | |||
9358 | if (IsInstanceMethod && ReturnTypeMatchesVoid) { | |||
9359 | std::string SelectorName = (Twine("remove") + UpperKey).str(); | |||
9360 | IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); | |||
9361 | if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { | |||
9362 | if (ReturnType.isNull()) { | |||
9363 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
9364 | Builder.AddTextChunk("void"); | |||
9365 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
9366 | } | |||
9367 | ||||
9368 | Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); | |||
9369 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
9370 | Builder.AddTextChunk("NSSet *"); | |||
9371 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
9372 | Builder.AddTextChunk("objects"); | |||
9373 | Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, | |||
9374 | CXCursor_ObjCInstanceMethodDecl)); | |||
9375 | } | |||
9376 | } | |||
9377 | ||||
9378 | // - (void)intersectKey:(NSSet *)objects | |||
9379 | if (IsInstanceMethod && ReturnTypeMatchesVoid) { | |||
9380 | std::string SelectorName = (Twine("intersect") + UpperKey).str(); | |||
9381 | IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); | |||
9382 | if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) { | |||
9383 | if (ReturnType.isNull()) { | |||
9384 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
9385 | Builder.AddTextChunk("void"); | |||
9386 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
9387 | } | |||
9388 | ||||
9389 | Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":")); | |||
9390 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
9391 | Builder.AddTextChunk("NSSet *"); | |||
9392 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
9393 | Builder.AddTextChunk("objects"); | |||
9394 | Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority, | |||
9395 | CXCursor_ObjCInstanceMethodDecl)); | |||
9396 | } | |||
9397 | } | |||
9398 | ||||
9399 | // Key-Value Observing | |||
9400 | // + (NSSet *)keyPathsForValuesAffectingKey | |||
9401 | if (!IsInstanceMethod && | |||
9402 | (ReturnType.isNull() || | |||
9403 | (ReturnType->isObjCObjectPointerType() && | |||
9404 | ReturnType->castAs<ObjCObjectPointerType>()->getInterfaceDecl() && | |||
9405 | ReturnType->castAs<ObjCObjectPointerType>() | |||
9406 | ->getInterfaceDecl() | |||
9407 | ->getName() == "NSSet"))) { | |||
9408 | std::string SelectorName = | |||
9409 | (Twine("keyPathsForValuesAffecting") + UpperKey).str(); | |||
9410 | IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); | |||
9411 | if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) | |||
9412 | .second) { | |||
9413 | if (ReturnType.isNull()) { | |||
9414 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
9415 | Builder.AddTextChunk("NSSet<NSString *> *"); | |||
9416 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
9417 | } | |||
9418 | ||||
9419 | Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName)); | |||
9420 | Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, | |||
9421 | CXCursor_ObjCClassMethodDecl)); | |||
9422 | } | |||
9423 | } | |||
9424 | ||||
9425 | // + (BOOL)automaticallyNotifiesObserversForKey | |||
9426 | if (!IsInstanceMethod && | |||
9427 | (ReturnType.isNull() || ReturnType->isIntegerType() || | |||
9428 | ReturnType->isBooleanType())) { | |||
9429 | std::string SelectorName = | |||
9430 | (Twine("automaticallyNotifiesObserversOf") + UpperKey).str(); | |||
9431 | IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName); | |||
9432 | if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId)) | |||
9433 | .second) { | |||
9434 | if (ReturnType.isNull()) { | |||
9435 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
9436 | Builder.AddTextChunk("BOOL"); | |||
9437 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
9438 | } | |||
9439 | ||||
9440 | Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName)); | |||
9441 | Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern, | |||
9442 | CXCursor_ObjCClassMethodDecl)); | |||
9443 | } | |||
9444 | } | |||
9445 | } | |||
9446 | ||||
9447 | void Sema::CodeCompleteObjCMethodDecl(Scope *S, | |||
9448 | std::optional<bool> IsInstanceMethod, | |||
9449 | ParsedType ReturnTy) { | |||
9450 | // Determine the return type of the method we're declaring, if | |||
9451 | // provided. | |||
9452 | QualType ReturnType = GetTypeFromParser(ReturnTy); | |||
9453 | Decl *IDecl = nullptr; | |||
9454 | if (CurContext->isObjCContainer()) { | |||
9455 | ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext); | |||
9456 | IDecl = OCD; | |||
9457 | } | |||
9458 | // Determine where we should start searching for methods. | |||
9459 | ObjCContainerDecl *SearchDecl = nullptr; | |||
9460 | bool IsInImplementation = false; | |||
9461 | if (Decl *D = IDecl) { | |||
9462 | if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) { | |||
9463 | SearchDecl = Impl->getClassInterface(); | |||
9464 | IsInImplementation = true; | |||
9465 | } else if (ObjCCategoryImplDecl *CatImpl = | |||
9466 | dyn_cast<ObjCCategoryImplDecl>(D)) { | |||
9467 | SearchDecl = CatImpl->getCategoryDecl(); | |||
9468 | IsInImplementation = true; | |||
9469 | } else | |||
9470 | SearchDecl = dyn_cast<ObjCContainerDecl>(D); | |||
9471 | } | |||
9472 | ||||
9473 | if (!SearchDecl && S) { | |||
9474 | if (DeclContext *DC = S->getEntity()) | |||
9475 | SearchDecl = dyn_cast<ObjCContainerDecl>(DC); | |||
9476 | } | |||
9477 | ||||
9478 | if (!SearchDecl) { | |||
9479 | HandleCodeCompleteResults(this, CodeCompleter, | |||
9480 | CodeCompletionContext::CCC_Other, nullptr, 0); | |||
9481 | return; | |||
9482 | } | |||
9483 | ||||
9484 | // Find all of the methods that we could declare/implement here. | |||
9485 | KnownMethodsMap KnownMethods; | |||
9486 | FindImplementableMethods(Context, SearchDecl, IsInstanceMethod, ReturnType, | |||
9487 | KnownMethods); | |||
9488 | ||||
9489 | // Add declarations or definitions for each of the known methods. | |||
9490 | typedef CodeCompletionResult Result; | |||
9491 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
9492 | CodeCompleter->getCodeCompletionTUInfo(), | |||
9493 | CodeCompletionContext::CCC_Other); | |||
9494 | Results.EnterNewScope(); | |||
9495 | PrintingPolicy Policy = getCompletionPrintingPolicy(*this); | |||
9496 | for (KnownMethodsMap::iterator M = KnownMethods.begin(), | |||
9497 | MEnd = KnownMethods.end(); | |||
9498 | M != MEnd; ++M) { | |||
9499 | ObjCMethodDecl *Method = M->second.getPointer(); | |||
9500 | CodeCompletionBuilder Builder(Results.getAllocator(), | |||
9501 | Results.getCodeCompletionTUInfo()); | |||
9502 | ||||
9503 | // Add the '-'/'+' prefix if it wasn't provided yet. | |||
9504 | if (!IsInstanceMethod) { | |||
9505 | Builder.AddTextChunk(Method->isInstanceMethod() ? "-" : "+"); | |||
9506 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
9507 | } | |||
9508 | ||||
9509 | // If the result type was not already provided, add it to the | |||
9510 | // pattern as (type). | |||
9511 | if (ReturnType.isNull()) { | |||
9512 | QualType ResTy = Method->getSendResultType().stripObjCKindOfType(Context); | |||
9513 | AttributedType::stripOuterNullability(ResTy); | |||
9514 | AddObjCPassingTypeChunk(ResTy, Method->getObjCDeclQualifier(), Context, | |||
9515 | Policy, Builder); | |||
9516 | } | |||
9517 | ||||
9518 | Selector Sel = Method->getSelector(); | |||
9519 | ||||
9520 | if (Sel.isUnarySelector()) { | |||
9521 | // Unary selectors have no arguments. | |||
9522 | Builder.AddTypedTextChunk( | |||
9523 | Builder.getAllocator().CopyString(Sel.getNameForSlot(0))); | |||
9524 | } else { | |||
9525 | // Add all parameters to the pattern. | |||
9526 | unsigned I = 0; | |||
9527 | for (ObjCMethodDecl::param_iterator P = Method->param_begin(), | |||
9528 | PEnd = Method->param_end(); | |||
9529 | P != PEnd; (void)++P, ++I) { | |||
9530 | // Add the part of the selector name. | |||
9531 | if (I == 0) | |||
9532 | Builder.AddTypedTextChunk( | |||
9533 | Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":")); | |||
9534 | else if (I < Sel.getNumArgs()) { | |||
9535 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
9536 | Builder.AddTypedTextChunk( | |||
9537 | Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":")); | |||
9538 | } else | |||
9539 | break; | |||
9540 | ||||
9541 | // Add the parameter type. | |||
9542 | QualType ParamType; | |||
9543 | if ((*P)->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) | |||
9544 | ParamType = (*P)->getType(); | |||
9545 | else | |||
9546 | ParamType = (*P)->getOriginalType(); | |||
9547 | ParamType = ParamType.substObjCTypeArgs( | |||
9548 | Context, {}, ObjCSubstitutionContext::Parameter); | |||
9549 | AttributedType::stripOuterNullability(ParamType); | |||
9550 | AddObjCPassingTypeChunk(ParamType, (*P)->getObjCDeclQualifier(), | |||
9551 | Context, Policy, Builder); | |||
9552 | ||||
9553 | if (IdentifierInfo *Id = (*P)->getIdentifier()) | |||
9554 | Builder.AddTextChunk( | |||
9555 | Builder.getAllocator().CopyString(Id->getName())); | |||
9556 | } | |||
9557 | } | |||
9558 | ||||
9559 | if (Method->isVariadic()) { | |||
9560 | if (Method->param_size() > 0) | |||
9561 | Builder.AddChunk(CodeCompletionString::CK_Comma); | |||
9562 | Builder.AddTextChunk("..."); | |||
9563 | } | |||
9564 | ||||
9565 | if (IsInImplementation && Results.includeCodePatterns()) { | |||
9566 | // We will be defining the method here, so add a compound statement. | |||
9567 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
9568 | Builder.AddChunk(CodeCompletionString::CK_LeftBrace); | |||
9569 | Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); | |||
9570 | if (!Method->getReturnType()->isVoidType()) { | |||
9571 | // If the result type is not void, add a return clause. | |||
9572 | Builder.AddTextChunk("return"); | |||
9573 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
9574 | Builder.AddPlaceholderChunk("expression"); | |||
9575 | Builder.AddChunk(CodeCompletionString::CK_SemiColon); | |||
9576 | } else | |||
9577 | Builder.AddPlaceholderChunk("statements"); | |||
9578 | ||||
9579 | Builder.AddChunk(CodeCompletionString::CK_VerticalSpace); | |||
9580 | Builder.AddChunk(CodeCompletionString::CK_RightBrace); | |||
9581 | } | |||
9582 | ||||
9583 | unsigned Priority = CCP_CodePattern; | |||
9584 | auto R = Result(Builder.TakeString(), Method, Priority); | |||
9585 | if (!M->second.getInt()) | |||
9586 | setInBaseClass(R); | |||
9587 | Results.AddResult(std::move(R)); | |||
9588 | } | |||
9589 | ||||
9590 | // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of | |||
9591 | // the properties in this class and its categories. | |||
9592 | if (Context.getLangOpts().ObjC) { | |||
9593 | SmallVector<ObjCContainerDecl *, 4> Containers; | |||
9594 | Containers.push_back(SearchDecl); | |||
9595 | ||||
9596 | VisitedSelectorSet KnownSelectors; | |||
9597 | for (KnownMethodsMap::iterator M = KnownMethods.begin(), | |||
9598 | MEnd = KnownMethods.end(); | |||
9599 | M != MEnd; ++M) | |||
9600 | KnownSelectors.insert(M->first); | |||
9601 | ||||
9602 | ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl); | |||
9603 | if (!IFace) | |||
9604 | if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl)) | |||
9605 | IFace = Category->getClassInterface(); | |||
9606 | ||||
9607 | if (IFace) | |||
9608 | llvm::append_range(Containers, IFace->visible_categories()); | |||
9609 | ||||
9610 | if (IsInstanceMethod) { | |||
9611 | for (unsigned I = 0, N = Containers.size(); I != N; ++I) | |||
9612 | for (auto *P : Containers[I]->instance_properties()) | |||
9613 | AddObjCKeyValueCompletions(P, *IsInstanceMethod, ReturnType, Context, | |||
9614 | KnownSelectors, Results); | |||
9615 | } | |||
9616 | } | |||
9617 | ||||
9618 | Results.ExitScope(); | |||
9619 | ||||
9620 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
9621 | Results.data(), Results.size()); | |||
9622 | } | |||
9623 | ||||
9624 | void Sema::CodeCompleteObjCMethodDeclSelector( | |||
9625 | Scope *S, bool IsInstanceMethod, bool AtParameterName, ParsedType ReturnTy, | |||
9626 | ArrayRef<IdentifierInfo *> SelIdents) { | |||
9627 | // If we have an external source, load the entire class method | |||
9628 | // pool from the AST file. | |||
9629 | if (ExternalSource) { | |||
9630 | for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); I != N; | |||
9631 | ++I) { | |||
9632 | Selector Sel = ExternalSource->GetExternalSelector(I); | |||
9633 | if (Sel.isNull() || MethodPool.count(Sel)) | |||
9634 | continue; | |||
9635 | ||||
9636 | ReadMethodPool(Sel); | |||
9637 | } | |||
9638 | } | |||
9639 | ||||
9640 | // Build the set of methods we can see. | |||
9641 | typedef CodeCompletionResult Result; | |||
9642 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
9643 | CodeCompleter->getCodeCompletionTUInfo(), | |||
9644 | CodeCompletionContext::CCC_Other); | |||
9645 | ||||
9646 | if (ReturnTy) | |||
9647 | Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType()); | |||
9648 | ||||
9649 | Results.EnterNewScope(); | |||
9650 | for (GlobalMethodPool::iterator M = MethodPool.begin(), | |||
9651 | MEnd = MethodPool.end(); | |||
9652 | M != MEnd; ++M) { | |||
9653 | for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first | |||
9654 | : &M->second.second; | |||
9655 | MethList && MethList->getMethod(); MethList = MethList->getNext()) { | |||
9656 | if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents)) | |||
9657 | continue; | |||
9658 | ||||
9659 | if (AtParameterName) { | |||
9660 | // Suggest parameter names we've seen before. | |||
9661 | unsigned NumSelIdents = SelIdents.size(); | |||
9662 | if (NumSelIdents && | |||
9663 | NumSelIdents <= MethList->getMethod()->param_size()) { | |||
9664 | ParmVarDecl *Param = | |||
9665 | MethList->getMethod()->parameters()[NumSelIdents - 1]; | |||
9666 | if (Param->getIdentifier()) { | |||
9667 | CodeCompletionBuilder Builder(Results.getAllocator(), | |||
9668 | Results.getCodeCompletionTUInfo()); | |||
9669 | Builder.AddTypedTextChunk(Builder.getAllocator().CopyString( | |||
9670 | Param->getIdentifier()->getName())); | |||
9671 | Results.AddResult(Builder.TakeString()); | |||
9672 | } | |||
9673 | } | |||
9674 | ||||
9675 | continue; | |||
9676 | } | |||
9677 | ||||
9678 | Result R(MethList->getMethod(), | |||
9679 | Results.getBasePriority(MethList->getMethod()), nullptr); | |||
9680 | R.StartParameter = SelIdents.size(); | |||
9681 | R.AllParametersAreInformative = false; | |||
9682 | R.DeclaringEntity = true; | |||
9683 | Results.MaybeAddResult(R, CurContext); | |||
9684 | } | |||
9685 | } | |||
9686 | ||||
9687 | Results.ExitScope(); | |||
9688 | ||||
9689 | if (!AtParameterName && !SelIdents.empty() && | |||
9690 | SelIdents.front()->getName().startswith("init")) { | |||
9691 | for (const auto &M : PP.macros()) { | |||
9692 | if (M.first->getName() != "NS_DESIGNATED_INITIALIZER") | |||
9693 | continue; | |||
9694 | Results.EnterNewScope(); | |||
9695 | CodeCompletionBuilder Builder(Results.getAllocator(), | |||
9696 | Results.getCodeCompletionTUInfo()); | |||
9697 | Builder.AddTypedTextChunk( | |||
9698 | Builder.getAllocator().CopyString(M.first->getName())); | |||
9699 | Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_Macro, | |||
9700 | CXCursor_MacroDefinition)); | |||
9701 | Results.ExitScope(); | |||
9702 | } | |||
9703 | } | |||
9704 | ||||
9705 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
9706 | Results.data(), Results.size()); | |||
9707 | } | |||
9708 | ||||
9709 | void Sema::CodeCompletePreprocessorDirective(bool InConditional) { | |||
9710 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
9711 | CodeCompleter->getCodeCompletionTUInfo(), | |||
9712 | CodeCompletionContext::CCC_PreprocessorDirective); | |||
9713 | Results.EnterNewScope(); | |||
9714 | ||||
9715 | // #if <condition> | |||
9716 | CodeCompletionBuilder Builder(Results.getAllocator(), | |||
9717 | Results.getCodeCompletionTUInfo()); | |||
9718 | Builder.AddTypedTextChunk("if"); | |||
9719 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
9720 | Builder.AddPlaceholderChunk("condition"); | |||
9721 | Results.AddResult(Builder.TakeString()); | |||
9722 | ||||
9723 | // #ifdef <macro> | |||
9724 | Builder.AddTypedTextChunk("ifdef"); | |||
9725 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
9726 | Builder.AddPlaceholderChunk("macro"); | |||
9727 | Results.AddResult(Builder.TakeString()); | |||
9728 | ||||
9729 | // #ifndef <macro> | |||
9730 | Builder.AddTypedTextChunk("ifndef"); | |||
9731 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
9732 | Builder.AddPlaceholderChunk("macro"); | |||
9733 | Results.AddResult(Builder.TakeString()); | |||
9734 | ||||
9735 | if (InConditional) { | |||
9736 | // #elif <condition> | |||
9737 | Builder.AddTypedTextChunk("elif"); | |||
9738 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
9739 | Builder.AddPlaceholderChunk("condition"); | |||
9740 | Results.AddResult(Builder.TakeString()); | |||
9741 | ||||
9742 | // #elifdef <macro> | |||
9743 | Builder.AddTypedTextChunk("elifdef"); | |||
9744 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
9745 | Builder.AddPlaceholderChunk("macro"); | |||
9746 | Results.AddResult(Builder.TakeString()); | |||
9747 | ||||
9748 | // #elifndef <macro> | |||
9749 | Builder.AddTypedTextChunk("elifndef"); | |||
9750 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
9751 | Builder.AddPlaceholderChunk("macro"); | |||
9752 | Results.AddResult(Builder.TakeString()); | |||
9753 | ||||
9754 | // #else | |||
9755 | Builder.AddTypedTextChunk("else"); | |||
9756 | Results.AddResult(Builder.TakeString()); | |||
9757 | ||||
9758 | // #endif | |||
9759 | Builder.AddTypedTextChunk("endif"); | |||
9760 | Results.AddResult(Builder.TakeString()); | |||
9761 | } | |||
9762 | ||||
9763 | // #include "header" | |||
9764 | Builder.AddTypedTextChunk("include"); | |||
9765 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
9766 | Builder.AddTextChunk("\""); | |||
9767 | Builder.AddPlaceholderChunk("header"); | |||
9768 | Builder.AddTextChunk("\""); | |||
9769 | Results.AddResult(Builder.TakeString()); | |||
9770 | ||||
9771 | // #include <header> | |||
9772 | Builder.AddTypedTextChunk("include"); | |||
9773 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
9774 | Builder.AddTextChunk("<"); | |||
9775 | Builder.AddPlaceholderChunk("header"); | |||
9776 | Builder.AddTextChunk(">"); | |||
9777 | Results.AddResult(Builder.TakeString()); | |||
9778 | ||||
9779 | // #define <macro> | |||
9780 | Builder.AddTypedTextChunk("define"); | |||
9781 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
9782 | Builder.AddPlaceholderChunk("macro"); | |||
9783 | Results.AddResult(Builder.TakeString()); | |||
9784 | ||||
9785 | // #define <macro>(<args>) | |||
9786 | Builder.AddTypedTextChunk("define"); | |||
9787 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
9788 | Builder.AddPlaceholderChunk("macro"); | |||
9789 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
9790 | Builder.AddPlaceholderChunk("args"); | |||
9791 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
9792 | Results.AddResult(Builder.TakeString()); | |||
9793 | ||||
9794 | // #undef <macro> | |||
9795 | Builder.AddTypedTextChunk("undef"); | |||
9796 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
9797 | Builder.AddPlaceholderChunk("macro"); | |||
9798 | Results.AddResult(Builder.TakeString()); | |||
9799 | ||||
9800 | // #line <number> | |||
9801 | Builder.AddTypedTextChunk("line"); | |||
9802 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
9803 | Builder.AddPlaceholderChunk("number"); | |||
9804 | Results.AddResult(Builder.TakeString()); | |||
9805 | ||||
9806 | // #line <number> "filename" | |||
9807 | Builder.AddTypedTextChunk("line"); | |||
9808 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
9809 | Builder.AddPlaceholderChunk("number"); | |||
9810 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
9811 | Builder.AddTextChunk("\""); | |||
9812 | Builder.AddPlaceholderChunk("filename"); | |||
9813 | Builder.AddTextChunk("\""); | |||
9814 | Results.AddResult(Builder.TakeString()); | |||
9815 | ||||
9816 | // #error <message> | |||
9817 | Builder.AddTypedTextChunk("error"); | |||
9818 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
9819 | Builder.AddPlaceholderChunk("message"); | |||
9820 | Results.AddResult(Builder.TakeString()); | |||
9821 | ||||
9822 | // #pragma <arguments> | |||
9823 | Builder.AddTypedTextChunk("pragma"); | |||
9824 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
9825 | Builder.AddPlaceholderChunk("arguments"); | |||
9826 | Results.AddResult(Builder.TakeString()); | |||
9827 | ||||
9828 | if (getLangOpts().ObjC) { | |||
9829 | // #import "header" | |||
9830 | Builder.AddTypedTextChunk("import"); | |||
9831 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
9832 | Builder.AddTextChunk("\""); | |||
9833 | Builder.AddPlaceholderChunk("header"); | |||
9834 | Builder.AddTextChunk("\""); | |||
9835 | Results.AddResult(Builder.TakeString()); | |||
9836 | ||||
9837 | // #import <header> | |||
9838 | Builder.AddTypedTextChunk("import"); | |||
9839 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
9840 | Builder.AddTextChunk("<"); | |||
9841 | Builder.AddPlaceholderChunk("header"); | |||
9842 | Builder.AddTextChunk(">"); | |||
9843 | Results.AddResult(Builder.TakeString()); | |||
9844 | } | |||
9845 | ||||
9846 | // #include_next "header" | |||
9847 | Builder.AddTypedTextChunk("include_next"); | |||
9848 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
9849 | Builder.AddTextChunk("\""); | |||
9850 | Builder.AddPlaceholderChunk("header"); | |||
9851 | Builder.AddTextChunk("\""); | |||
9852 | Results.AddResult(Builder.TakeString()); | |||
9853 | ||||
9854 | // #include_next <header> | |||
9855 | Builder.AddTypedTextChunk("include_next"); | |||
9856 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
9857 | Builder.AddTextChunk("<"); | |||
9858 | Builder.AddPlaceholderChunk("header"); | |||
9859 | Builder.AddTextChunk(">"); | |||
9860 | Results.AddResult(Builder.TakeString()); | |||
9861 | ||||
9862 | // #warning <message> | |||
9863 | Builder.AddTypedTextChunk("warning"); | |||
9864 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
9865 | Builder.AddPlaceholderChunk("message"); | |||
9866 | Results.AddResult(Builder.TakeString()); | |||
9867 | ||||
9868 | // Note: #ident and #sccs are such crazy anachronisms that we don't provide | |||
9869 | // completions for them. And __include_macros is a Clang-internal extension | |||
9870 | // that we don't want to encourage anyone to use. | |||
9871 | ||||
9872 | // FIXME: we don't support #assert or #unassert, so don't suggest them. | |||
9873 | Results.ExitScope(); | |||
9874 | ||||
9875 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
9876 | Results.data(), Results.size()); | |||
9877 | } | |||
9878 | ||||
9879 | void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) { | |||
9880 | CodeCompleteOrdinaryName(S, S->getFnParent() ? Sema::PCC_RecoveryInFunction | |||
9881 | : Sema::PCC_Namespace); | |||
9882 | } | |||
9883 | ||||
9884 | void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) { | |||
9885 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
9886 | CodeCompleter->getCodeCompletionTUInfo(), | |||
9887 | IsDefinition ? CodeCompletionContext::CCC_MacroName | |||
9888 | : CodeCompletionContext::CCC_MacroNameUse); | |||
9889 | if (!IsDefinition && CodeCompleter->includeMacros()) { | |||
9890 | // Add just the names of macros, not their arguments. | |||
9891 | CodeCompletionBuilder Builder(Results.getAllocator(), | |||
9892 | Results.getCodeCompletionTUInfo()); | |||
9893 | Results.EnterNewScope(); | |||
9894 | for (Preprocessor::macro_iterator M = PP.macro_begin(), | |||
9895 | MEnd = PP.macro_end(); | |||
9896 | M != MEnd; ++M) { | |||
9897 | Builder.AddTypedTextChunk( | |||
9898 | Builder.getAllocator().CopyString(M->first->getName())); | |||
9899 | Results.AddResult(CodeCompletionResult( | |||
9900 | Builder.TakeString(), CCP_CodePattern, CXCursor_MacroDefinition)); | |||
9901 | } | |||
9902 | Results.ExitScope(); | |||
9903 | } else if (IsDefinition) { | |||
9904 | // FIXME: Can we detect when the user just wrote an include guard above? | |||
9905 | } | |||
9906 | ||||
9907 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
9908 | Results.data(), Results.size()); | |||
9909 | } | |||
9910 | ||||
9911 | void Sema::CodeCompletePreprocessorExpression() { | |||
9912 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
9913 | CodeCompleter->getCodeCompletionTUInfo(), | |||
9914 | CodeCompletionContext::CCC_PreprocessorExpression); | |||
9915 | ||||
9916 | if (CodeCompleter->includeMacros()) | |||
9917 | AddMacroResults(PP, Results, CodeCompleter->loadExternal(), true); | |||
9918 | ||||
9919 | // defined (<macro>) | |||
9920 | Results.EnterNewScope(); | |||
9921 | CodeCompletionBuilder Builder(Results.getAllocator(), | |||
9922 | Results.getCodeCompletionTUInfo()); | |||
9923 | Builder.AddTypedTextChunk("defined"); | |||
9924 | Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace); | |||
9925 | Builder.AddChunk(CodeCompletionString::CK_LeftParen); | |||
9926 | Builder.AddPlaceholderChunk("macro"); | |||
9927 | Builder.AddChunk(CodeCompletionString::CK_RightParen); | |||
9928 | Results.AddResult(Builder.TakeString()); | |||
9929 | Results.ExitScope(); | |||
9930 | ||||
9931 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
9932 | Results.data(), Results.size()); | |||
9933 | } | |||
9934 | ||||
9935 | void Sema::CodeCompletePreprocessorMacroArgument(Scope *S, | |||
9936 | IdentifierInfo *Macro, | |||
9937 | MacroInfo *MacroInfo, | |||
9938 | unsigned Argument) { | |||
9939 | // FIXME: In the future, we could provide "overload" results, much like we | |||
9940 | // do for function calls. | |||
9941 | ||||
9942 | // Now just ignore this. There will be another code-completion callback | |||
9943 | // for the expanded tokens. | |||
9944 | } | |||
9945 | ||||
9946 | // This handles completion inside an #include filename, e.g. #include <foo/ba | |||
9947 | // We look for the directory "foo" under each directory on the include path, | |||
9948 | // list its files, and reassemble the appropriate #include. | |||
9949 | void Sema::CodeCompleteIncludedFile(llvm::StringRef Dir, bool Angled) { | |||
9950 | // RelDir should use /, but unescaped \ is possible on windows! | |||
9951 | // Our completions will normalize to / for simplicity, this case is rare. | |||
9952 | std::string RelDir = llvm::sys::path::convert_to_slash(Dir); | |||
9953 | // We need the native slashes for the actual file system interactions. | |||
9954 | SmallString<128> NativeRelDir = StringRef(RelDir); | |||
9955 | llvm::sys::path::native(NativeRelDir); | |||
9956 | llvm::vfs::FileSystem &FS = | |||
9957 | getSourceManager().getFileManager().getVirtualFileSystem(); | |||
9958 | ||||
9959 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
9960 | CodeCompleter->getCodeCompletionTUInfo(), | |||
9961 | CodeCompletionContext::CCC_IncludedFile); | |||
9962 | llvm::DenseSet<StringRef> SeenResults; // To deduplicate results. | |||
9963 | ||||
9964 | // Helper: adds one file or directory completion result. | |||
9965 | auto AddCompletion = [&](StringRef Filename, bool IsDirectory) { | |||
9966 | SmallString<64> TypedChunk = Filename; | |||
9967 | // Directory completion is up to the slash, e.g. <sys/ | |||
9968 | TypedChunk.push_back(IsDirectory ? '/' : Angled ? '>' : '"'); | |||
9969 | auto R = SeenResults.insert(TypedChunk); | |||
9970 | if (R.second) { // New completion | |||
9971 | const char *InternedTyped = Results.getAllocator().CopyString(TypedChunk); | |||
9972 | *R.first = InternedTyped; // Avoid dangling StringRef. | |||
9973 | CodeCompletionBuilder Builder(CodeCompleter->getAllocator(), | |||
9974 | CodeCompleter->getCodeCompletionTUInfo()); | |||
9975 | Builder.AddTypedTextChunk(InternedTyped); | |||
9976 | // The result is a "Pattern", which is pretty opaque. | |||
9977 | // We may want to include the real filename to allow smart ranking. | |||
9978 | Results.AddResult(CodeCompletionResult(Builder.TakeString())); | |||
9979 | } | |||
9980 | }; | |||
9981 | ||||
9982 | // Helper: scans IncludeDir for nice files, and adds results for each. | |||
9983 | auto AddFilesFromIncludeDir = [&](StringRef IncludeDir, | |||
9984 | bool IsSystem, | |||
9985 | DirectoryLookup::LookupType_t LookupType) { | |||
9986 | llvm::SmallString<128> Dir = IncludeDir; | |||
9987 | if (!NativeRelDir.empty()) { | |||
9988 | if (LookupType == DirectoryLookup::LT_Framework) { | |||
9989 | // For a framework dir, #include <Foo/Bar/> actually maps to | |||
9990 | // a path of Foo.framework/Headers/Bar/. | |||
9991 | auto Begin = llvm::sys::path::begin(NativeRelDir); | |||
9992 | auto End = llvm::sys::path::end(NativeRelDir); | |||
9993 | ||||
9994 | llvm::sys::path::append(Dir, *Begin + ".framework", "Headers"); | |||
9995 | llvm::sys::path::append(Dir, ++Begin, End); | |||
9996 | } else { | |||
9997 | llvm::sys::path::append(Dir, NativeRelDir); | |||
9998 | } | |||
9999 | } | |||
10000 | ||||
10001 | const StringRef &Dirname = llvm::sys::path::filename(Dir); | |||
10002 | const bool isQt = Dirname.startswith("Qt") || Dirname == "ActiveQt"; | |||
10003 | const bool ExtensionlessHeaders = | |||
10004 | IsSystem || isQt || Dir.endswith(".framework/Headers"); | |||
10005 | std::error_code EC; | |||
10006 | unsigned Count = 0; | |||
10007 | for (auto It = FS.dir_begin(Dir, EC); | |||
10008 | !EC && It != llvm::vfs::directory_iterator(); It.increment(EC)) { | |||
10009 | if (++Count == 2500) // If we happen to hit a huge directory, | |||
10010 | break; // bail out early so we're not too slow. | |||
10011 | StringRef Filename = llvm::sys::path::filename(It->path()); | |||
10012 | ||||
10013 | // To know whether a symlink should be treated as file or a directory, we | |||
10014 | // have to stat it. This should be cheap enough as there shouldn't be many | |||
10015 | // symlinks. | |||
10016 | llvm::sys::fs::file_type Type = It->type(); | |||
10017 | if (Type == llvm::sys::fs::file_type::symlink_file) { | |||
10018 | if (auto FileStatus = FS.status(It->path())) | |||
10019 | Type = FileStatus->getType(); | |||
10020 | } | |||
10021 | switch (Type) { | |||
10022 | case llvm::sys::fs::file_type::directory_file: | |||
10023 | // All entries in a framework directory must have a ".framework" suffix, | |||
10024 | // but the suffix does not appear in the source code's include/import. | |||
10025 | if (LookupType == DirectoryLookup::LT_Framework && | |||
10026 | NativeRelDir.empty() && !Filename.consume_back(".framework")) | |||
10027 | break; | |||
10028 | ||||
10029 | AddCompletion(Filename, /*IsDirectory=*/true); | |||
10030 | break; | |||
10031 | case llvm::sys::fs::file_type::regular_file: { | |||
10032 | // Only files that really look like headers. (Except in special dirs). | |||
10033 | const bool IsHeader = Filename.endswith_insensitive(".h") || | |||
10034 | Filename.endswith_insensitive(".hh") || | |||
10035 | Filename.endswith_insensitive(".hpp") || | |||
10036 | Filename.endswith_insensitive(".hxx") || | |||
10037 | Filename.endswith_insensitive(".inc") || | |||
10038 | (ExtensionlessHeaders && !Filename.contains('.')); | |||
10039 | if (!IsHeader) | |||
10040 | break; | |||
10041 | AddCompletion(Filename, /*IsDirectory=*/false); | |||
10042 | break; | |||
10043 | } | |||
10044 | default: | |||
10045 | break; | |||
10046 | } | |||
10047 | } | |||
10048 | }; | |||
10049 | ||||
10050 | // Helper: adds results relative to IncludeDir, if possible. | |||
10051 | auto AddFilesFromDirLookup = [&](const DirectoryLookup &IncludeDir, | |||
10052 | bool IsSystem) { | |||
10053 | switch (IncludeDir.getLookupType()) { | |||
10054 | case DirectoryLookup::LT_HeaderMap: | |||
10055 | // header maps are not (currently) enumerable. | |||
10056 | break; | |||
10057 | case DirectoryLookup::LT_NormalDir: | |||
10058 | AddFilesFromIncludeDir(IncludeDir.getDir()->getName(), IsSystem, | |||
10059 | DirectoryLookup::LT_NormalDir); | |||
10060 | break; | |||
10061 | case DirectoryLookup::LT_Framework: | |||
10062 | AddFilesFromIncludeDir(IncludeDir.getFrameworkDir()->getName(), IsSystem, | |||
10063 | DirectoryLookup::LT_Framework); | |||
10064 | break; | |||
10065 | } | |||
10066 | }; | |||
10067 | ||||
10068 | // Finally with all our helpers, we can scan the include path. | |||
10069 | // Do this in standard order so deduplication keeps the right file. | |||
10070 | // (In case we decide to add more details to the results later). | |||
10071 | const auto &S = PP.getHeaderSearchInfo(); | |||
10072 | using llvm::make_range; | |||
10073 | if (!Angled) { | |||
10074 | // The current directory is on the include path for "quoted" includes. | |||
10075 | const FileEntry *CurFile = PP.getCurrentFileLexer()->getFileEntry(); | |||
10076 | if (CurFile && CurFile->getDir()) | |||
10077 | AddFilesFromIncludeDir(CurFile->getDir()->getName(), false, | |||
10078 | DirectoryLookup::LT_NormalDir); | |||
10079 | for (const auto &D : make_range(S.quoted_dir_begin(), S.quoted_dir_end())) | |||
10080 | AddFilesFromDirLookup(D, false); | |||
10081 | } | |||
10082 | for (const auto &D : make_range(S.angled_dir_begin(), S.angled_dir_end())) | |||
10083 | AddFilesFromDirLookup(D, false); | |||
10084 | for (const auto &D : make_range(S.system_dir_begin(), S.system_dir_end())) | |||
10085 | AddFilesFromDirLookup(D, true); | |||
10086 | ||||
10087 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
10088 | Results.data(), Results.size()); | |||
10089 | } | |||
10090 | ||||
10091 | void Sema::CodeCompleteNaturalLanguage() { | |||
10092 | HandleCodeCompleteResults(this, CodeCompleter, | |||
10093 | CodeCompletionContext::CCC_NaturalLanguage, nullptr, | |||
10094 | 0); | |||
10095 | } | |||
10096 | ||||
10097 | void Sema::CodeCompleteAvailabilityPlatformName() { | |||
10098 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), | |||
10099 | CodeCompleter->getCodeCompletionTUInfo(), | |||
10100 | CodeCompletionContext::CCC_Other); | |||
10101 | Results.EnterNewScope(); | |||
10102 | static const char *Platforms[] = {"macOS", "iOS", "watchOS", "tvOS"}; | |||
10103 | for (const char *Platform : llvm::ArrayRef(Platforms)) { | |||
10104 | Results.AddResult(CodeCompletionResult(Platform)); | |||
10105 | Results.AddResult(CodeCompletionResult(Results.getAllocator().CopyString( | |||
10106 | Twine(Platform) + "ApplicationExtension"))); | |||
10107 | } | |||
10108 | Results.ExitScope(); | |||
10109 | HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(), | |||
10110 | Results.data(), Results.size()); | |||
10111 | } | |||
10112 | ||||
10113 | void Sema::GatherGlobalCodeCompletions( | |||
10114 | CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo, | |||
10115 | SmallVectorImpl<CodeCompletionResult> &Results) { | |||
10116 | ResultBuilder Builder(*this, Allocator, CCTUInfo, | |||
10117 | CodeCompletionContext::CCC_Recovery); | |||
| ||||
10118 | if (!CodeCompleter || CodeCompleter->includeGlobals()) { | |||
10119 | CodeCompletionDeclConsumer Consumer(Builder, | |||
10120 | Context.getTranslationUnitDecl()); | |||
10121 | LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName, | |||
10122 | Consumer, | |||
10123 | !CodeCompleter || CodeCompleter->loadExternal()); | |||
10124 | } | |||
10125 | ||||
10126 | if (!CodeCompleter || CodeCompleter->includeMacros()) | |||
10127 | AddMacroResults(PP, Builder, | |||
10128 | !CodeCompleter || CodeCompleter->loadExternal(), true); | |||
10129 | ||||
10130 | Results.clear(); | |||
10131 | Results.insert(Results.end(), Builder.data(), | |||
10132 | Builder.data() + Builder.size()); | |||
10133 | } |
1 | //===- CodeCompleteConsumer.h - Code Completion Interface -------*- 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 CodeCompleteConsumer class. |
10 | // |
11 | //===----------------------------------------------------------------------===// |
12 | |
13 | #ifndef LLVM_CLANG_SEMA_CODECOMPLETECONSUMER_H |
14 | #define LLVM_CLANG_SEMA_CODECOMPLETECONSUMER_H |
15 | |
16 | #include "clang-c/Index.h" |
17 | #include "clang/AST/Type.h" |
18 | #include "clang/Basic/LLVM.h" |
19 | #include "clang/Lex/MacroInfo.h" |
20 | #include "clang/Sema/CodeCompleteOptions.h" |
21 | #include "clang/Sema/DeclSpec.h" |
22 | #include "llvm/ADT/ArrayRef.h" |
23 | #include "llvm/ADT/DenseMap.h" |
24 | #include "llvm/ADT/SmallPtrSet.h" |
25 | #include "llvm/ADT/SmallVector.h" |
26 | #include "llvm/ADT/StringRef.h" |
27 | #include "llvm/Support/Allocator.h" |
28 | #include "llvm/Support/type_traits.h" |
29 | #include <cassert> |
30 | #include <memory> |
31 | #include <optional> |
32 | #include <string> |
33 | #include <utility> |
34 | |
35 | namespace clang { |
36 | |
37 | class ASTContext; |
38 | class Decl; |
39 | class DeclContext; |
40 | class FunctionDecl; |
41 | class FunctionTemplateDecl; |
42 | class IdentifierInfo; |
43 | class LangOptions; |
44 | class NamedDecl; |
45 | class NestedNameSpecifier; |
46 | class Preprocessor; |
47 | class RawComment; |
48 | class Sema; |
49 | class UsingShadowDecl; |
50 | |
51 | /// Default priority values for code-completion results based |
52 | /// on their kind. |
53 | enum { |
54 | /// Priority for the next initialization in a constructor initializer |
55 | /// list. |
56 | CCP_NextInitializer = 7, |
57 | |
58 | /// Priority for an enumeration constant inside a switch whose |
59 | /// condition is of the enumeration type. |
60 | CCP_EnumInCase = 7, |
61 | |
62 | /// Priority for a send-to-super completion. |
63 | CCP_SuperCompletion = 20, |
64 | |
65 | /// Priority for a declaration that is in the local scope. |
66 | CCP_LocalDeclaration = 34, |
67 | |
68 | /// Priority for a member declaration found from the current |
69 | /// method or member function. |
70 | CCP_MemberDeclaration = 35, |
71 | |
72 | /// Priority for a language keyword (that isn't any of the other |
73 | /// categories). |
74 | CCP_Keyword = 40, |
75 | |
76 | /// Priority for a code pattern. |
77 | CCP_CodePattern = 40, |
78 | |
79 | /// Priority for a non-type declaration. |
80 | CCP_Declaration = 50, |
81 | |
82 | /// Priority for a type. |
83 | CCP_Type = CCP_Declaration, |
84 | |
85 | /// Priority for a constant value (e.g., enumerator). |
86 | CCP_Constant = 65, |
87 | |
88 | /// Priority for a preprocessor macro. |
89 | CCP_Macro = 70, |
90 | |
91 | /// Priority for a nested-name-specifier. |
92 | CCP_NestedNameSpecifier = 75, |
93 | |
94 | /// Priority for a result that isn't likely to be what the user wants, |
95 | /// but is included for completeness. |
96 | CCP_Unlikely = 80, |
97 | |
98 | /// Priority for the Objective-C "_cmd" implicit parameter. |
99 | CCP_ObjC_cmd = CCP_Unlikely |
100 | }; |
101 | |
102 | /// Priority value deltas that are added to code-completion results |
103 | /// based on the context of the result. |
104 | enum { |
105 | /// The result is in a base class. |
106 | CCD_InBaseClass = 2, |
107 | |
108 | /// The result is a C++ non-static member function whose qualifiers |
109 | /// exactly match the object type on which the member function can be called. |
110 | CCD_ObjectQualifierMatch = -1, |
111 | |
112 | /// The selector of the given message exactly matches the selector |
113 | /// of the current method, which might imply that some kind of delegation |
114 | /// is occurring. |
115 | CCD_SelectorMatch = -3, |
116 | |
117 | /// Adjustment to the "bool" type in Objective-C, where the typedef |
118 | /// "BOOL" is preferred. |
119 | CCD_bool_in_ObjC = 1, |
120 | |
121 | /// Adjustment for KVC code pattern priorities when it doesn't look |
122 | /// like the |
123 | CCD_ProbablyNotObjCCollection = 15, |
124 | |
125 | /// An Objective-C method being used as a property. |
126 | CCD_MethodAsProperty = 2, |
127 | |
128 | /// An Objective-C block property completed as a setter with a |
129 | /// block placeholder. |
130 | CCD_BlockPropertySetter = 3 |
131 | }; |
132 | |
133 | /// Priority value factors by which we will divide or multiply the |
134 | /// priority of a code-completion result. |
135 | enum { |
136 | /// Divide by this factor when a code-completion result's type exactly |
137 | /// matches the type we expect. |
138 | CCF_ExactTypeMatch = 4, |
139 | |
140 | /// Divide by this factor when a code-completion result's type is |
141 | /// similar to the type we expect (e.g., both arithmetic types, both |
142 | /// Objective-C object pointer types). |
143 | CCF_SimilarTypeMatch = 2 |
144 | }; |
145 | |
146 | /// A simplified classification of types used when determining |
147 | /// "similar" types for code completion. |
148 | enum SimplifiedTypeClass { |
149 | STC_Arithmetic, |
150 | STC_Array, |
151 | STC_Block, |
152 | STC_Function, |
153 | STC_ObjectiveC, |
154 | STC_Other, |
155 | STC_Pointer, |
156 | STC_Record, |
157 | STC_Void |
158 | }; |
159 | |
160 | /// Determine the simplified type class of the given canonical type. |
161 | SimplifiedTypeClass getSimplifiedTypeClass(CanQualType T); |
162 | |
163 | /// Determine the type that this declaration will have if it is used |
164 | /// as a type or in an expression. |
165 | QualType getDeclUsageType(ASTContext &C, const NamedDecl *ND); |
166 | |
167 | /// Determine the priority to be given to a macro code completion result |
168 | /// with the given name. |
169 | /// |
170 | /// \param MacroName The name of the macro. |
171 | /// |
172 | /// \param LangOpts Options describing the current language dialect. |
173 | /// |
174 | /// \param PreferredTypeIsPointer Whether the preferred type for the context |
175 | /// of this macro is a pointer type. |
176 | unsigned getMacroUsagePriority(StringRef MacroName, |
177 | const LangOptions &LangOpts, |
178 | bool PreferredTypeIsPointer = false); |
179 | |
180 | /// Determine the libclang cursor kind associated with the given |
181 | /// declaration. |
182 | CXCursorKind getCursorKindForDecl(const Decl *D); |
183 | |
184 | /// The context in which code completion occurred, so that the |
185 | /// code-completion consumer can process the results accordingly. |
186 | class CodeCompletionContext { |
187 | public: |
188 | enum Kind { |
189 | /// An unspecified code-completion context. |
190 | CCC_Other, |
191 | |
192 | /// An unspecified code-completion context where we should also add |
193 | /// macro completions. |
194 | CCC_OtherWithMacros, |
195 | |
196 | /// Code completion occurred within a "top-level" completion context, |
197 | /// e.g., at namespace or global scope. |
198 | CCC_TopLevel, |
199 | |
200 | /// Code completion occurred within an Objective-C interface, |
201 | /// protocol, or category interface. |
202 | CCC_ObjCInterface, |
203 | |
204 | /// Code completion occurred within an Objective-C implementation |
205 | /// or category implementation. |
206 | CCC_ObjCImplementation, |
207 | |
208 | /// Code completion occurred within the instance variable list of |
209 | /// an Objective-C interface, implementation, or category implementation. |
210 | CCC_ObjCIvarList, |
211 | |
212 | /// Code completion occurred within a class, struct, or union. |
213 | CCC_ClassStructUnion, |
214 | |
215 | /// Code completion occurred where a statement (or declaration) is |
216 | /// expected in a function, method, or block. |
217 | CCC_Statement, |
218 | |
219 | /// Code completion occurred where an expression is expected. |
220 | CCC_Expression, |
221 | |
222 | /// Code completion occurred where an Objective-C message receiver |
223 | /// is expected. |
224 | CCC_ObjCMessageReceiver, |
225 | |
226 | /// Code completion occurred on the right-hand side of a member |
227 | /// access expression using the dot operator. |
228 | /// |
229 | /// The results of this completion are the members of the type being |
230 | /// accessed. The type itself is available via |
231 | /// \c CodeCompletionContext::getType(). |
232 | CCC_DotMemberAccess, |
233 | |
234 | /// Code completion occurred on the right-hand side of a member |
235 | /// access expression using the arrow operator. |
236 | /// |
237 | /// The results of this completion are the members of the type being |
238 | /// accessed. The type itself is available via |
239 | /// \c CodeCompletionContext::getType(). |
240 | CCC_ArrowMemberAccess, |
241 | |
242 | /// Code completion occurred on the right-hand side of an Objective-C |
243 | /// property access expression. |
244 | /// |
245 | /// The results of this completion are the members of the type being |
246 | /// accessed. The type itself is available via |
247 | /// \c CodeCompletionContext::getType(). |
248 | CCC_ObjCPropertyAccess, |
249 | |
250 | /// Code completion occurred after the "enum" keyword, to indicate |
251 | /// an enumeration name. |
252 | CCC_EnumTag, |
253 | |
254 | /// Code completion occurred after the "union" keyword, to indicate |
255 | /// a union name. |
256 | CCC_UnionTag, |
257 | |
258 | /// Code completion occurred after the "struct" or "class" keyword, |
259 | /// to indicate a struct or class name. |
260 | CCC_ClassOrStructTag, |
261 | |
262 | /// Code completion occurred where a protocol name is expected. |
263 | CCC_ObjCProtocolName, |
264 | |
265 | /// Code completion occurred where a namespace or namespace alias |
266 | /// is expected. |
267 | CCC_Namespace, |
268 | |
269 | /// Code completion occurred where a type name is expected. |
270 | CCC_Type, |
271 | |
272 | /// Code completion occurred where a new name is expected. |
273 | CCC_NewName, |
274 | |
275 | /// Code completion occurred where both a new name and an existing symbol is |
276 | /// permissible. |
277 | CCC_SymbolOrNewName, |
278 | |
279 | /// Code completion occurred where an existing name(such as type, function |
280 | /// or variable) is expected. |
281 | CCC_Symbol, |
282 | |
283 | /// Code completion occurred where an macro is being defined. |
284 | CCC_MacroName, |
285 | |
286 | /// Code completion occurred where a macro name is expected |
287 | /// (without any arguments, in the case of a function-like macro). |
288 | CCC_MacroNameUse, |
289 | |
290 | /// Code completion occurred within a preprocessor expression. |
291 | CCC_PreprocessorExpression, |
292 | |
293 | /// Code completion occurred where a preprocessor directive is |
294 | /// expected. |
295 | CCC_PreprocessorDirective, |
296 | |
297 | /// Code completion occurred in a context where natural language is |
298 | /// expected, e.g., a comment or string literal. |
299 | /// |
300 | /// This context usually implies that no completions should be added, |
301 | /// unless they come from an appropriate natural-language dictionary. |
302 | CCC_NaturalLanguage, |
303 | |
304 | /// Code completion for a selector, as in an \@selector expression. |
305 | CCC_SelectorName, |
306 | |
307 | /// Code completion within a type-qualifier list. |
308 | CCC_TypeQualifiers, |
309 | |
310 | /// Code completion in a parenthesized expression, which means that |
311 | /// we may also have types here in C and Objective-C (as well as in C++). |
312 | CCC_ParenthesizedExpression, |
313 | |
314 | /// Code completion where an Objective-C instance message is |
315 | /// expected. |
316 | CCC_ObjCInstanceMessage, |
317 | |
318 | /// Code completion where an Objective-C class message is expected. |
319 | CCC_ObjCClassMessage, |
320 | |
321 | /// Code completion where the name of an Objective-C class is |
322 | /// expected. |
323 | CCC_ObjCInterfaceName, |
324 | |
325 | /// Code completion where an Objective-C category name is expected. |
326 | CCC_ObjCCategoryName, |
327 | |
328 | /// Code completion inside the filename part of a #include directive. |
329 | CCC_IncludedFile, |
330 | |
331 | /// Code completion of an attribute name. |
332 | CCC_Attribute, |
333 | |
334 | /// An unknown context, in which we are recovering from a parsing |
335 | /// error and don't know which completions we should give. |
336 | CCC_Recovery |
337 | }; |
338 | |
339 | using VisitedContextSet = llvm::SmallPtrSet<DeclContext *, 8>; |
340 | |
341 | private: |
342 | Kind CCKind; |
343 | |
344 | /// Indicates whether we are completing a name of a using declaration, e.g. |
345 | /// using ^; |
346 | /// using a::^; |
347 | bool IsUsingDeclaration; |
348 | |
349 | /// The type that would prefer to see at this point (e.g., the type |
350 | /// of an initializer or function parameter). |
351 | QualType PreferredType; |
352 | |
353 | /// The type of the base object in a member access expression. |
354 | QualType BaseType; |
355 | |
356 | /// The identifiers for Objective-C selector parts. |
357 | ArrayRef<IdentifierInfo *> SelIdents; |
358 | |
359 | /// The scope specifier that comes before the completion token e.g. |
360 | /// "a::b::" |
361 | std::optional<CXXScopeSpec> ScopeSpecifier; |
362 | |
363 | /// A set of declaration contexts visited by Sema when doing lookup for |
364 | /// code completion. |
365 | VisitedContextSet VisitedContexts; |
366 | |
367 | public: |
368 | /// Construct a new code-completion context of the given kind. |
369 | CodeCompletionContext(Kind CCKind) |
370 | : CCKind(CCKind), IsUsingDeclaration(false), SelIdents(std::nullopt) {} |
371 | |
372 | /// Construct a new code-completion context of the given kind. |
373 | CodeCompletionContext(Kind CCKind, QualType T, |
374 | ArrayRef<IdentifierInfo *> SelIdents = std::nullopt) |
375 | : CCKind(CCKind), IsUsingDeclaration(false), SelIdents(SelIdents) { |
376 | if (CCKind == CCC_DotMemberAccess || CCKind == CCC_ArrowMemberAccess || |
377 | CCKind == CCC_ObjCPropertyAccess || CCKind == CCC_ObjCClassMessage || |
378 | CCKind == CCC_ObjCInstanceMessage) |
379 | BaseType = T; |
380 | else |
381 | PreferredType = T; |
382 | } |
383 | |
384 | bool isUsingDeclaration() const { return IsUsingDeclaration; } |
385 | void setIsUsingDeclaration(bool V) { IsUsingDeclaration = V; } |
386 | |
387 | /// Retrieve the kind of code-completion context. |
388 | Kind getKind() const { return CCKind; } |
389 | |
390 | /// Retrieve the type that this expression would prefer to have, e.g., |
391 | /// if the expression is a variable initializer or a function argument, the |
392 | /// type of the corresponding variable or function parameter. |
393 | QualType getPreferredType() const { return PreferredType; } |
394 | void setPreferredType(QualType T) { PreferredType = T; } |
395 | |
396 | /// Retrieve the type of the base object in a member-access |
397 | /// expression. |
398 | QualType getBaseType() const { return BaseType; } |
399 | |
400 | /// Retrieve the Objective-C selector identifiers. |
401 | ArrayRef<IdentifierInfo *> getSelIdents() const { return SelIdents; } |
402 | |
403 | /// Determines whether we want C++ constructors as results within this |
404 | /// context. |
405 | bool wantConstructorResults() const; |
406 | |
407 | /// Sets the scope specifier that comes before the completion token. |
408 | /// This is expected to be set in code completions on qualfied specifiers |
409 | /// (e.g. "a::b::"). |
410 | void setCXXScopeSpecifier(CXXScopeSpec SS) { |
411 | this->ScopeSpecifier = std::move(SS); |
412 | } |
413 | |
414 | /// Adds a visited context. |
415 | void addVisitedContext(DeclContext *Ctx) { |
416 | VisitedContexts.insert(Ctx); |
417 | } |
418 | |
419 | /// Retrieves all visited contexts. |
420 | const VisitedContextSet &getVisitedContexts() const { |
421 | return VisitedContexts; |
422 | } |
423 | |
424 | std::optional<const CXXScopeSpec *> getCXXScopeSpecifier() { |
425 | if (ScopeSpecifier) |
426 | return &*ScopeSpecifier; |
427 | return std::nullopt; |
428 | } |
429 | }; |
430 | |
431 | /// Get string representation of \p Kind, useful for debugging. |
432 | llvm::StringRef getCompletionKindString(CodeCompletionContext::Kind Kind); |
433 | |
434 | /// A "string" used to describe how code completion can |
435 | /// be performed for an entity. |
436 | /// |
437 | /// A code completion string typically shows how a particular entity can be |
438 | /// used. For example, the code completion string for a function would show |
439 | /// the syntax to call it, including the parentheses, placeholders for the |
440 | /// arguments, etc. |
441 | class CodeCompletionString { |
442 | public: |
443 | /// The different kinds of "chunks" that can occur within a code |
444 | /// completion string. |
445 | enum ChunkKind { |
446 | /// The piece of text that the user is expected to type to |
447 | /// match the code-completion string, typically a keyword or the name of a |
448 | /// declarator or macro. |
449 | CK_TypedText, |
450 | |
451 | /// A piece of text that should be placed in the buffer, e.g., |
452 | /// parentheses or a comma in a function call. |
453 | CK_Text, |
454 | |
455 | /// A code completion string that is entirely optional. For example, |
456 | /// an optional code completion string that describes the default arguments |
457 | /// in a function call. |
458 | CK_Optional, |
459 | |
460 | /// A string that acts as a placeholder for, e.g., a function |
461 | /// call argument. |
462 | CK_Placeholder, |
463 | |
464 | /// A piece of text that describes something about the result but |
465 | /// should not be inserted into the buffer. |
466 | CK_Informative, |
467 | /// A piece of text that describes the type of an entity or, for |
468 | /// functions and methods, the return type. |
469 | CK_ResultType, |
470 | |
471 | /// A piece of text that describes the parameter that corresponds |
472 | /// to the code-completion location within a function call, message send, |
473 | /// macro invocation, etc. |
474 | CK_CurrentParameter, |
475 | |
476 | /// A left parenthesis ('('). |
477 | CK_LeftParen, |
478 | |
479 | /// A right parenthesis (')'). |
480 | CK_RightParen, |
481 | |
482 | /// A left bracket ('['). |
483 | CK_LeftBracket, |
484 | |
485 | /// A right bracket (']'). |
486 | CK_RightBracket, |
487 | |
488 | /// A left brace ('{'). |
489 | CK_LeftBrace, |
490 | |
491 | /// A right brace ('}'). |
492 | CK_RightBrace, |
493 | |
494 | /// A left angle bracket ('<'). |
495 | CK_LeftAngle, |
496 | |
497 | /// A right angle bracket ('>'). |
498 | CK_RightAngle, |
499 | |
500 | /// A comma separator (','). |
501 | CK_Comma, |
502 | |
503 | /// A colon (':'). |
504 | CK_Colon, |
505 | |
506 | /// A semicolon (';'). |
507 | CK_SemiColon, |
508 | |
509 | /// An '=' sign. |
510 | CK_Equal, |
511 | |
512 | /// Horizontal whitespace (' '). |
513 | CK_HorizontalSpace, |
514 | |
515 | /// Vertical whitespace ('\\n' or '\\r\\n', depending on the |
516 | /// platform). |
517 | CK_VerticalSpace |
518 | }; |
519 | |
520 | /// One piece of the code completion string. |
521 | struct Chunk { |
522 | /// The kind of data stored in this piece of the code completion |
523 | /// string. |
524 | ChunkKind Kind = CK_Text; |
525 | |
526 | union { |
527 | /// The text string associated with a CK_Text, CK_Placeholder, |
528 | /// CK_Informative, or CK_Comma chunk. |
529 | /// The string is owned by the chunk and will be deallocated |
530 | /// (with delete[]) when the chunk is destroyed. |
531 | const char *Text; |
532 | |
533 | /// The code completion string associated with a CK_Optional chunk. |
534 | /// The optional code completion string is owned by the chunk, and will |
535 | /// be deallocated (with delete) when the chunk is destroyed. |
536 | CodeCompletionString *Optional; |
537 | }; |
538 | |
539 | Chunk() : Text(nullptr) {} |
540 | |
541 | explicit Chunk(ChunkKind Kind, const char *Text = ""); |
542 | |
543 | /// Create a new text chunk. |
544 | static Chunk CreateText(const char *Text); |
545 | |
546 | /// Create a new optional chunk. |
547 | static Chunk CreateOptional(CodeCompletionString *Optional); |
548 | |
549 | /// Create a new placeholder chunk. |
550 | static Chunk CreatePlaceholder(const char *Placeholder); |
551 | |
552 | /// Create a new informative chunk. |
553 | static Chunk CreateInformative(const char *Informative); |
554 | |
555 | /// Create a new result type chunk. |
556 | static Chunk CreateResultType(const char *ResultType); |
557 | |
558 | /// Create a new current-parameter chunk. |
559 | static Chunk CreateCurrentParameter(const char *CurrentParameter); |
560 | }; |
561 | |
562 | private: |
563 | friend class CodeCompletionBuilder; |
564 | friend class CodeCompletionResult; |
565 | |
566 | /// The number of chunks stored in this string. |
567 | unsigned NumChunks : 16; |
568 | |
569 | /// The number of annotations for this code-completion result. |
570 | unsigned NumAnnotations : 16; |
571 | |
572 | /// The priority of this code-completion string. |
573 | unsigned Priority : 16; |
574 | |
575 | /// The availability of this code-completion result. |
576 | unsigned Availability : 2; |
577 | |
578 | /// The name of the parent context. |
579 | StringRef ParentName; |
580 | |
581 | /// A brief documentation comment attached to the declaration of |
582 | /// entity being completed by this result. |
583 | const char *BriefComment; |
584 | |
585 | CodeCompletionString(const Chunk *Chunks, unsigned NumChunks, |
586 | unsigned Priority, CXAvailabilityKind Availability, |
587 | const char **Annotations, unsigned NumAnnotations, |
588 | StringRef ParentName, |
589 | const char *BriefComment); |
590 | ~CodeCompletionString() = default; |
591 | |
592 | public: |
593 | CodeCompletionString(const CodeCompletionString &) = delete; |
594 | CodeCompletionString &operator=(const CodeCompletionString &) = delete; |
595 | |
596 | using iterator = const Chunk *; |
597 | |
598 | iterator begin() const { return reinterpret_cast<const Chunk *>(this + 1); } |
599 | iterator end() const { return begin() + NumChunks; } |
600 | bool empty() const { return NumChunks == 0; } |
601 | unsigned size() const { return NumChunks; } |
602 | |
603 | const Chunk &operator[](unsigned I) const { |
604 | assert(I < size() && "Chunk index out-of-range")(static_cast <bool> (I < size() && "Chunk index out-of-range" ) ? void (0) : __assert_fail ("I < size() && \"Chunk index out-of-range\"" , "clang/include/clang/Sema/CodeCompleteConsumer.h", 604, __extension__ __PRETTY_FUNCTION__)); |
605 | return begin()[I]; |
606 | } |
607 | |
608 | /// Returns the text in the first TypedText chunk. |
609 | const char *getTypedText() const; |
610 | |
611 | /// Returns the combined text from all TypedText chunks. |
612 | std::string getAllTypedText() const; |
613 | |
614 | /// Retrieve the priority of this code completion result. |
615 | unsigned getPriority() const { return Priority; } |
616 | |
617 | /// Retrieve the availability of this code completion result. |
618 | unsigned getAvailability() const { return Availability; } |
619 | |
620 | /// Retrieve the number of annotations for this code completion result. |
621 | unsigned getAnnotationCount() const; |
622 | |
623 | /// Retrieve the annotation string specified by \c AnnotationNr. |
624 | const char *getAnnotation(unsigned AnnotationNr) const; |
625 | |
626 | /// Retrieve the name of the parent context. |
627 | StringRef getParentContextName() const { |
628 | return ParentName; |
629 | } |
630 | |
631 | const char *getBriefComment() const { |
632 | return BriefComment; |
633 | } |
634 | |
635 | /// Retrieve a string representation of the code completion string, |
636 | /// which is mainly useful for debugging. |
637 | std::string getAsString() const; |
638 | }; |
639 | |
640 | /// An allocator used specifically for the purpose of code completion. |
641 | class CodeCompletionAllocator : public llvm::BumpPtrAllocator { |
642 | public: |
643 | /// Copy the given string into this allocator. |
644 | const char *CopyString(const Twine &String); |
645 | }; |
646 | |
647 | /// Allocator for a cached set of global code completions. |
648 | class GlobalCodeCompletionAllocator : public CodeCompletionAllocator {}; |
649 | |
650 | class CodeCompletionTUInfo { |
651 | llvm::DenseMap<const DeclContext *, StringRef> ParentNames; |
652 | std::shared_ptr<GlobalCodeCompletionAllocator> AllocatorRef; |
653 | |
654 | public: |
655 | explicit CodeCompletionTUInfo( |
656 | std::shared_ptr<GlobalCodeCompletionAllocator> Allocator) |
657 | : AllocatorRef(std::move(Allocator)) {} |
658 | |
659 | std::shared_ptr<GlobalCodeCompletionAllocator> getAllocatorRef() const { |
660 | return AllocatorRef; |
661 | } |
662 | |
663 | CodeCompletionAllocator &getAllocator() const { |
664 | assert(AllocatorRef)(static_cast <bool> (AllocatorRef) ? void (0) : __assert_fail ("AllocatorRef", "clang/include/clang/Sema/CodeCompleteConsumer.h" , 664, __extension__ __PRETTY_FUNCTION__)); |
665 | return *AllocatorRef; |
666 | } |
667 | |
668 | StringRef getParentName(const DeclContext *DC); |
669 | }; |
670 | |
671 | } // namespace clang |
672 | |
673 | namespace clang { |
674 | |
675 | /// A builder class used to construct new code-completion strings. |
676 | class CodeCompletionBuilder { |
677 | public: |
678 | using Chunk = CodeCompletionString::Chunk; |
679 | |
680 | private: |
681 | CodeCompletionAllocator &Allocator; |
682 | CodeCompletionTUInfo &CCTUInfo; |
683 | unsigned Priority = 0; |
684 | CXAvailabilityKind Availability = CXAvailability_Available; |
685 | StringRef ParentName; |
686 | const char *BriefComment = nullptr; |
687 | |
688 | /// The chunks stored in this string. |
689 | SmallVector<Chunk, 4> Chunks; |
690 | |
691 | SmallVector<const char *, 2> Annotations; |
692 | |
693 | public: |
694 | CodeCompletionBuilder(CodeCompletionAllocator &Allocator, |
695 | CodeCompletionTUInfo &CCTUInfo) |
696 | : Allocator(Allocator), CCTUInfo(CCTUInfo) {} |
697 | |
698 | CodeCompletionBuilder(CodeCompletionAllocator &Allocator, |
699 | CodeCompletionTUInfo &CCTUInfo, |
700 | unsigned Priority, CXAvailabilityKind Availability) |
701 | : Allocator(Allocator), CCTUInfo(CCTUInfo), Priority(Priority), |
702 | Availability(Availability) {} |
703 | |
704 | /// Retrieve the allocator into which the code completion |
705 | /// strings should be allocated. |
706 | CodeCompletionAllocator &getAllocator() const { return Allocator; } |
707 | |
708 | CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo; } |
709 | |
710 | /// Take the resulting completion string. |
711 | /// |
712 | /// This operation can only be performed once. |
713 | CodeCompletionString *TakeString(); |
714 | |
715 | /// Add a new typed-text chunk. |
716 | void AddTypedTextChunk(const char *Text); |
717 | |
718 | /// Add a new text chunk. |
719 | void AddTextChunk(const char *Text); |
720 | |
721 | /// Add a new optional chunk. |
722 | void AddOptionalChunk(CodeCompletionString *Optional); |
723 | |
724 | /// Add a new placeholder chunk. |
725 | void AddPlaceholderChunk(const char *Placeholder); |
726 | |
727 | /// Add a new informative chunk. |
728 | void AddInformativeChunk(const char *Text); |
729 | |
730 | /// Add a new result-type chunk. |
731 | void AddResultTypeChunk(const char *ResultType); |
732 | |
733 | /// Add a new current-parameter chunk. |
734 | void AddCurrentParameterChunk(const char *CurrentParameter); |
735 | |
736 | /// Add a new chunk. |
737 | void AddChunk(CodeCompletionString::ChunkKind CK, const char *Text = ""); |
738 | |
739 | void AddAnnotation(const char *A) { Annotations.push_back(A); } |
740 | |
741 | /// Add the parent context information to this code completion. |
742 | void addParentContext(const DeclContext *DC); |
743 | |
744 | const char *getBriefComment() const { return BriefComment; } |
745 | void addBriefComment(StringRef Comment); |
746 | |
747 | StringRef getParentName() const { return ParentName; } |
748 | }; |
749 | |
750 | /// Captures a result of code completion. |
751 | class CodeCompletionResult { |
752 | public: |
753 | /// Describes the kind of result generated. |
754 | enum ResultKind { |
755 | /// Refers to a declaration. |
756 | RK_Declaration = 0, |
757 | |
758 | /// Refers to a keyword or symbol. |
759 | RK_Keyword, |
760 | |
761 | /// Refers to a macro. |
762 | RK_Macro, |
763 | |
764 | /// Refers to a precomputed pattern. |
765 | RK_Pattern |
766 | }; |
767 | |
768 | /// When Kind == RK_Declaration or RK_Pattern, the declaration we are |
769 | /// referring to. In the latter case, the declaration might be NULL. |
770 | const NamedDecl *Declaration = nullptr; |
771 | |
772 | union { |
773 | /// When Kind == RK_Keyword, the string representing the keyword |
774 | /// or symbol's spelling. |
775 | const char *Keyword; |
776 | |
777 | /// When Kind == RK_Pattern, the code-completion string that |
778 | /// describes the completion text to insert. |
779 | CodeCompletionString *Pattern; |
780 | |
781 | /// When Kind == RK_Macro, the identifier that refers to a macro. |
782 | const IdentifierInfo *Macro; |
783 | }; |
784 | |
785 | /// The priority of this particular code-completion result. |
786 | unsigned Priority; |
787 | |
788 | /// Specifies which parameter (of a function, Objective-C method, |
789 | /// macro, etc.) we should start with when formatting the result. |
790 | unsigned StartParameter = 0; |
791 | |
792 | /// The kind of result stored here. |
793 | ResultKind Kind; |
794 | |
795 | /// The cursor kind that describes this result. |
796 | CXCursorKind CursorKind; |
797 | |
798 | /// The availability of this result. |
799 | CXAvailabilityKind Availability = CXAvailability_Available; |
800 | |
801 | /// Fix-its that *must* be applied before inserting the text for the |
802 | /// corresponding completion. |
803 | /// |
804 | /// By default, CodeCompletionBuilder only returns completions with empty |
805 | /// fix-its. Extra completions with non-empty fix-its should be explicitly |
806 | /// requested by setting CompletionOptions::IncludeFixIts. |
807 | /// |
808 | /// For the clients to be able to compute position of the cursor after |
809 | /// applying fix-its, the following conditions are guaranteed to hold for |
810 | /// RemoveRange of the stored fix-its: |
811 | /// - Ranges in the fix-its are guaranteed to never contain the completion |
812 | /// point (or identifier under completion point, if any) inside them, except |
813 | /// at the start or at the end of the range. |
814 | /// - If a fix-it range starts or ends with completion point (or starts or |
815 | /// ends after the identifier under completion point), it will contain at |
816 | /// least one character. It allows to unambiguously recompute completion |
817 | /// point after applying the fix-it. |
818 | /// |
819 | /// The intuition is that provided fix-its change code around the identifier |
820 | /// we complete, but are not allowed to touch the identifier itself or the |
821 | /// completion point. One example of completions with corrections are the ones |
822 | /// replacing '.' with '->' and vice versa: |
823 | /// |
824 | /// std::unique_ptr<std::vector<int>> vec_ptr; |
825 | /// In 'vec_ptr.^', one of the completions is 'push_back', it requires |
826 | /// replacing '.' with '->'. |
827 | /// In 'vec_ptr->^', one of the completions is 'release', it requires |
828 | /// replacing '->' with '.'. |
829 | std::vector<FixItHint> FixIts; |
830 | |
831 | /// Whether this result is hidden by another name. |
832 | bool Hidden : 1; |
833 | |
834 | /// Whether this is a class member from base class. |
835 | bool InBaseClass : 1; |
836 | |
837 | /// Whether this result was found via lookup into a base class. |
838 | bool QualifierIsInformative : 1; |
839 | |
840 | /// Whether this declaration is the beginning of a |
841 | /// nested-name-specifier and, therefore, should be followed by '::'. |
842 | bool StartsNestedNameSpecifier : 1; |
843 | |
844 | /// Whether all parameters (of a function, Objective-C |
845 | /// method, etc.) should be considered "informative". |
846 | bool AllParametersAreInformative : 1; |
847 | |
848 | /// Whether we're completing a declaration of the given entity, |
849 | /// rather than a use of that entity. |
850 | bool DeclaringEntity : 1; |
851 | |
852 | /// When completing a function, whether it can be a call. This will usually be |
853 | /// true, but we have some heuristics, e.g. when a pointer to a non-static |
854 | /// member function is completed outside of that class' scope, it can never |
855 | /// be a call. |
856 | bool FunctionCanBeCall : 1; |
857 | |
858 | /// If the result should have a nested-name-specifier, this is it. |
859 | /// When \c QualifierIsInformative, the nested-name-specifier is |
860 | /// informative rather than required. |
861 | NestedNameSpecifier *Qualifier = nullptr; |
862 | |
863 | /// If this Decl was unshadowed by using declaration, this can store a |
864 | /// pointer to the UsingShadowDecl which was used in the unshadowing process. |
865 | /// This information can be used to uprank CodeCompletionResults / which have |
866 | /// corresponding `using decl::qualified::name;` nearby. |
867 | const UsingShadowDecl *ShadowDecl = nullptr; |
868 | |
869 | /// If the result is RK_Macro, this can store the information about the macro |
870 | /// definition. This should be set in most cases but can be missing when |
871 | /// the macro has been undefined. |
872 | const MacroInfo *MacroDefInfo = nullptr; |
873 | |
874 | /// Build a result that refers to a declaration. |
875 | CodeCompletionResult(const NamedDecl *Declaration, unsigned Priority, |
876 | NestedNameSpecifier *Qualifier = nullptr, |
877 | bool QualifierIsInformative = false, |
878 | bool Accessible = true, |
879 | std::vector<FixItHint> FixIts = std::vector<FixItHint>()) |
880 | : Declaration(Declaration), Priority(Priority), Kind(RK_Declaration), |
881 | FixIts(std::move(FixIts)), Hidden(false), InBaseClass(false), |
882 | QualifierIsInformative(QualifierIsInformative), |
883 | StartsNestedNameSpecifier(false), AllParametersAreInformative(false), |
884 | DeclaringEntity(false), FunctionCanBeCall(true), Qualifier(Qualifier) { |
885 | // FIXME: Add assert to check FixIts range requirements. |
886 | computeCursorKindAndAvailability(Accessible); |
887 | } |
888 | |
889 | /// Build a result that refers to a keyword or symbol. |
890 | CodeCompletionResult(const char *Keyword, unsigned Priority = CCP_Keyword) |
891 | : Keyword(Keyword), Priority(Priority), Kind(RK_Keyword), |
892 | CursorKind(CXCursor_NotImplemented), Hidden(false), InBaseClass(false), |
893 | QualifierIsInformative(false), StartsNestedNameSpecifier(false), |
894 | AllParametersAreInformative(false), DeclaringEntity(false), |
895 | FunctionCanBeCall(true) {} |
896 | |
897 | /// Build a result that refers to a macro. |
898 | CodeCompletionResult(const IdentifierInfo *Macro, |
899 | const MacroInfo *MI = nullptr, |
900 | unsigned Priority = CCP_Macro) |
901 | : Macro(Macro), Priority(Priority), Kind(RK_Macro), |
902 | CursorKind(CXCursor_MacroDefinition), Hidden(false), InBaseClass(false), |
903 | QualifierIsInformative(false), StartsNestedNameSpecifier(false), |
904 | AllParametersAreInformative(false), DeclaringEntity(false), |
905 | FunctionCanBeCall(true), MacroDefInfo(MI) {} |
906 | |
907 | /// Build a result that refers to a pattern. |
908 | CodeCompletionResult( |
909 | CodeCompletionString *Pattern, unsigned Priority = CCP_CodePattern, |
910 | CXCursorKind CursorKind = CXCursor_NotImplemented, |
911 | CXAvailabilityKind Availability = CXAvailability_Available, |
912 | const NamedDecl *D = nullptr) |
913 | : Declaration(D), Pattern(Pattern), Priority(Priority), Kind(RK_Pattern), |
914 | CursorKind(CursorKind), Availability(Availability), Hidden(false), |
915 | InBaseClass(false), QualifierIsInformative(false), |
916 | StartsNestedNameSpecifier(false), AllParametersAreInformative(false), |
917 | DeclaringEntity(false), FunctionCanBeCall(true) {} |
918 | |
919 | /// Build a result that refers to a pattern with an associated |
920 | /// declaration. |
921 | CodeCompletionResult(CodeCompletionString *Pattern, const NamedDecl *D, |
922 | unsigned Priority) |
923 | : Declaration(D), Pattern(Pattern), Priority(Priority), Kind(RK_Pattern), |
924 | Hidden(false), InBaseClass(false), QualifierIsInformative(false), |
925 | StartsNestedNameSpecifier(false), AllParametersAreInformative(false), |
926 | DeclaringEntity(false), FunctionCanBeCall(true) { |
927 | computeCursorKindAndAvailability(); |
928 | } |
929 | |
930 | /// Retrieve the declaration stored in this result. This might be nullptr if |
931 | /// Kind is RK_Pattern. |
932 | const NamedDecl *getDeclaration() const { |
933 | assert(((Kind == RK_Declaration) || (Kind == RK_Pattern)) &&(static_cast <bool> (((Kind == RK_Declaration) || (Kind == RK_Pattern)) && "Not a declaration or pattern result" ) ? void (0) : __assert_fail ("((Kind == RK_Declaration) || (Kind == RK_Pattern)) && \"Not a declaration or pattern result\"" , "clang/include/clang/Sema/CodeCompleteConsumer.h", 934, __extension__ __PRETTY_FUNCTION__)) |
934 | "Not a declaration or pattern result")(static_cast <bool> (((Kind == RK_Declaration) || (Kind == RK_Pattern)) && "Not a declaration or pattern result" ) ? void (0) : __assert_fail ("((Kind == RK_Declaration) || (Kind == RK_Pattern)) && \"Not a declaration or pattern result\"" , "clang/include/clang/Sema/CodeCompleteConsumer.h", 934, __extension__ __PRETTY_FUNCTION__)); |
935 | return Declaration; |
936 | } |
937 | |
938 | /// Retrieve the keyword stored in this result. |
939 | const char *getKeyword() const { |
940 | assert(Kind == RK_Keyword && "Not a keyword result")(static_cast <bool> (Kind == RK_Keyword && "Not a keyword result" ) ? void (0) : __assert_fail ("Kind == RK_Keyword && \"Not a keyword result\"" , "clang/include/clang/Sema/CodeCompleteConsumer.h", 940, __extension__ __PRETTY_FUNCTION__)); |
941 | return Keyword; |
942 | } |
943 | |
944 | /// Create a new code-completion string that describes how to insert |
945 | /// this result into a program. |
946 | /// |
947 | /// \param S The semantic analysis that created the result. |
948 | /// |
949 | /// \param Allocator The allocator that will be used to allocate the |
950 | /// string itself. |
951 | CodeCompletionString *CreateCodeCompletionString(Sema &S, |
952 | const CodeCompletionContext &CCContext, |
953 | CodeCompletionAllocator &Allocator, |
954 | CodeCompletionTUInfo &CCTUInfo, |
955 | bool IncludeBriefComments); |
956 | CodeCompletionString *CreateCodeCompletionString(ASTContext &Ctx, |
957 | Preprocessor &PP, |
958 | const CodeCompletionContext &CCContext, |
959 | CodeCompletionAllocator &Allocator, |
960 | CodeCompletionTUInfo &CCTUInfo, |
961 | bool IncludeBriefComments); |
962 | /// Creates a new code-completion string for the macro result. Similar to the |
963 | /// above overloads, except this only requires preprocessor information. |
964 | /// The result kind must be `RK_Macro`. |
965 | CodeCompletionString * |
966 | CreateCodeCompletionStringForMacro(Preprocessor &PP, |
967 | CodeCompletionAllocator &Allocator, |
968 | CodeCompletionTUInfo &CCTUInfo); |
969 | |
970 | CodeCompletionString *createCodeCompletionStringForDecl( |
971 | Preprocessor &PP, ASTContext &Ctx, CodeCompletionBuilder &Result, |
972 | bool IncludeBriefComments, const CodeCompletionContext &CCContext, |
973 | PrintingPolicy &Policy); |
974 | |
975 | CodeCompletionString *createCodeCompletionStringForOverride( |
976 | Preprocessor &PP, ASTContext &Ctx, CodeCompletionBuilder &Result, |
977 | bool IncludeBriefComments, const CodeCompletionContext &CCContext, |
978 | PrintingPolicy &Policy); |
979 | |
980 | /// Retrieve the name that should be used to order a result. |
981 | /// |
982 | /// If the name needs to be constructed as a string, that string will be |
983 | /// saved into Saved and the returned StringRef will refer to it. |
984 | StringRef getOrderedName(std::string &Saved) const; |
985 | |
986 | private: |
987 | void computeCursorKindAndAvailability(bool Accessible = true); |
988 | }; |
989 | |
990 | bool operator<(const CodeCompletionResult &X, const CodeCompletionResult &Y); |
991 | |
992 | inline bool operator>(const CodeCompletionResult &X, |
993 | const CodeCompletionResult &Y) { |
994 | return Y < X; |
995 | } |
996 | |
997 | inline bool operator<=(const CodeCompletionResult &X, |
998 | const CodeCompletionResult &Y) { |
999 | return !(Y < X); |
1000 | } |
1001 | |
1002 | inline bool operator>=(const CodeCompletionResult &X, |
1003 | const CodeCompletionResult &Y) { |
1004 | return !(X < Y); |
1005 | } |
1006 | |
1007 | /// Abstract interface for a consumer of code-completion |
1008 | /// information. |
1009 | class CodeCompleteConsumer { |
1010 | protected: |
1011 | const CodeCompleteOptions CodeCompleteOpts; |
1012 | |
1013 | public: |
1014 | class OverloadCandidate { |
1015 | public: |
1016 | /// Describes the type of overload candidate. |
1017 | enum CandidateKind { |
1018 | /// The candidate is a function declaration. |
1019 | CK_Function, |
1020 | |
1021 | /// The candidate is a function template, arguments are being completed. |
1022 | CK_FunctionTemplate, |
1023 | |
1024 | /// The "candidate" is actually a variable, expression, or block |
1025 | /// for which we only have a function prototype. |
1026 | CK_FunctionType, |
1027 | |
1028 | /// The candidate is a variable or expression of function type |
1029 | /// for which we have the location of the prototype declaration. |
1030 | CK_FunctionProtoTypeLoc, |
1031 | |
1032 | /// The candidate is a template, template arguments are being completed. |
1033 | CK_Template, |
1034 | |
1035 | /// The candidate is aggregate initialization of a record type. |
1036 | CK_Aggregate, |
1037 | }; |
1038 | |
1039 | private: |
1040 | /// The kind of overload candidate. |
1041 | CandidateKind Kind; |
1042 | |
1043 | union { |
1044 | /// The function overload candidate, available when |
1045 | /// Kind == CK_Function. |
1046 | FunctionDecl *Function; |
1047 | |
1048 | /// The function template overload candidate, available when |
1049 | /// Kind == CK_FunctionTemplate. |
1050 | FunctionTemplateDecl *FunctionTemplate; |
1051 | |
1052 | /// The function type that describes the entity being called, |
1053 | /// when Kind == CK_FunctionType. |
1054 | const FunctionType *Type; |
1055 | |
1056 | /// The location of the function prototype that describes the entity being |
1057 | /// called, when Kind == CK_FunctionProtoTypeLoc. |
1058 | FunctionProtoTypeLoc ProtoTypeLoc; |
1059 | |
1060 | /// The template overload candidate, available when |
1061 | /// Kind == CK_Template. |
1062 | const TemplateDecl *Template; |
1063 | |
1064 | /// The class being aggregate-initialized, |
1065 | /// when Kind == CK_Aggregate |
1066 | const RecordDecl *AggregateType; |
1067 | }; |
1068 | |
1069 | public: |
1070 | OverloadCandidate(FunctionDecl *Function) |
1071 | : Kind(CK_Function), Function(Function) { |
1072 | assert(Function != nullptr)(static_cast <bool> (Function != nullptr) ? void (0) : __assert_fail ("Function != nullptr", "clang/include/clang/Sema/CodeCompleteConsumer.h" , 1072, __extension__ __PRETTY_FUNCTION__)); |
1073 | } |
1074 | |
1075 | OverloadCandidate(FunctionTemplateDecl *FunctionTemplateDecl) |
1076 | : Kind(CK_FunctionTemplate), FunctionTemplate(FunctionTemplateDecl) { |
1077 | assert(FunctionTemplateDecl != nullptr)(static_cast <bool> (FunctionTemplateDecl != nullptr) ? void (0) : __assert_fail ("FunctionTemplateDecl != nullptr", "clang/include/clang/Sema/CodeCompleteConsumer.h", 1077, __extension__ __PRETTY_FUNCTION__)); |
1078 | } |
1079 | |
1080 | OverloadCandidate(const FunctionType *Type) |
1081 | : Kind(CK_FunctionType), Type(Type) { |
1082 | assert(Type != nullptr)(static_cast <bool> (Type != nullptr) ? void (0) : __assert_fail ("Type != nullptr", "clang/include/clang/Sema/CodeCompleteConsumer.h" , 1082, __extension__ __PRETTY_FUNCTION__)); |
1083 | } |
1084 | |
1085 | OverloadCandidate(FunctionProtoTypeLoc Prototype) |
1086 | : Kind(CK_FunctionProtoTypeLoc), ProtoTypeLoc(Prototype) { |
1087 | assert(!Prototype.isNull())(static_cast <bool> (!Prototype.isNull()) ? void (0) : __assert_fail ("!Prototype.isNull()", "clang/include/clang/Sema/CodeCompleteConsumer.h" , 1087, __extension__ __PRETTY_FUNCTION__)); |
1088 | } |
1089 | |
1090 | OverloadCandidate(const RecordDecl *Aggregate) |
1091 | : Kind(CK_Aggregate), AggregateType(Aggregate) { |
1092 | assert(Aggregate != nullptr)(static_cast <bool> (Aggregate != nullptr) ? void (0) : __assert_fail ("Aggregate != nullptr", "clang/include/clang/Sema/CodeCompleteConsumer.h" , 1092, __extension__ __PRETTY_FUNCTION__)); |
1093 | } |
1094 | |
1095 | OverloadCandidate(const TemplateDecl *Template) |
1096 | : Kind(CK_Template), Template(Template) {} |
1097 | |
1098 | /// Determine the kind of overload candidate. |
1099 | CandidateKind getKind() const { return Kind; } |
1100 | |
1101 | /// Retrieve the function overload candidate or the templated |
1102 | /// function declaration for a function template. |
1103 | FunctionDecl *getFunction() const; |
1104 | |
1105 | /// Retrieve the function template overload candidate. |
1106 | FunctionTemplateDecl *getFunctionTemplate() const { |
1107 | assert(getKind() == CK_FunctionTemplate && "Not a function template")(static_cast <bool> (getKind() == CK_FunctionTemplate && "Not a function template") ? void (0) : __assert_fail ("getKind() == CK_FunctionTemplate && \"Not a function template\"" , "clang/include/clang/Sema/CodeCompleteConsumer.h", 1107, __extension__ __PRETTY_FUNCTION__)); |
1108 | return FunctionTemplate; |
1109 | } |
1110 | |
1111 | /// Retrieve the function type of the entity, regardless of how the |
1112 | /// function is stored. |
1113 | const FunctionType *getFunctionType() const; |
1114 | |
1115 | /// Retrieve the function ProtoTypeLoc candidate. |
1116 | /// This can be called for any Kind, but returns null for kinds |
1117 | /// other than CK_FunctionProtoTypeLoc. |
1118 | const FunctionProtoTypeLoc getFunctionProtoTypeLoc() const; |
1119 | |
1120 | const TemplateDecl *getTemplate() const { |
1121 | assert(getKind() == CK_Template && "Not a template")(static_cast <bool> (getKind() == CK_Template && "Not a template") ? void (0) : __assert_fail ("getKind() == CK_Template && \"Not a template\"" , "clang/include/clang/Sema/CodeCompleteConsumer.h", 1121, __extension__ __PRETTY_FUNCTION__)); |
1122 | return Template; |
1123 | } |
1124 | |
1125 | /// Retrieve the aggregate type being initialized. |
1126 | const RecordDecl *getAggregate() const { |
1127 | assert(getKind() == CK_Aggregate)(static_cast <bool> (getKind() == CK_Aggregate) ? void ( 0) : __assert_fail ("getKind() == CK_Aggregate", "clang/include/clang/Sema/CodeCompleteConsumer.h" , 1127, __extension__ __PRETTY_FUNCTION__)); |
1128 | return AggregateType; |
1129 | } |
1130 | |
1131 | /// Get the number of parameters in this signature. |
1132 | unsigned getNumParams() const; |
1133 | |
1134 | /// Get the type of the Nth parameter. |
1135 | /// Returns null if the type is unknown or N is out of range. |
1136 | QualType getParamType(unsigned N) const; |
1137 | |
1138 | /// Get the declaration of the Nth parameter. |
1139 | /// Returns null if the decl is unknown or N is out of range. |
1140 | const NamedDecl *getParamDecl(unsigned N) const; |
1141 | |
1142 | /// Create a new code-completion string that describes the function |
1143 | /// signature of this overload candidate. |
1144 | CodeCompletionString * |
1145 | CreateSignatureString(unsigned CurrentArg, Sema &S, |
1146 | CodeCompletionAllocator &Allocator, |
1147 | CodeCompletionTUInfo &CCTUInfo, |
1148 | bool IncludeBriefComments, bool Braced) const; |
1149 | }; |
1150 | |
1151 | CodeCompleteConsumer(const CodeCompleteOptions &CodeCompleteOpts) |
1152 | : CodeCompleteOpts(CodeCompleteOpts) {} |
1153 | |
1154 | /// Whether the code-completion consumer wants to see macros. |
1155 | bool includeMacros() const { |
1156 | return CodeCompleteOpts.IncludeMacros; |
1157 | } |
1158 | |
1159 | /// Whether the code-completion consumer wants to see code patterns. |
1160 | bool includeCodePatterns() const { |
1161 | return CodeCompleteOpts.IncludeCodePatterns; |
1162 | } |
1163 | |
1164 | /// Whether to include global (top-level) declaration results. |
1165 | bool includeGlobals() const { return CodeCompleteOpts.IncludeGlobals; } |
1166 | |
1167 | /// Whether to include declarations in namespace contexts (including |
1168 | /// the global namespace). If this is false, `includeGlobals()` will be |
1169 | /// ignored. |
1170 | bool includeNamespaceLevelDecls() const { |
1171 | return CodeCompleteOpts.IncludeNamespaceLevelDecls; |
1172 | } |
1173 | |
1174 | /// Whether to include brief documentation comments within the set of |
1175 | /// code completions returned. |
1176 | bool includeBriefComments() const { |
1177 | return CodeCompleteOpts.IncludeBriefComments; |
1178 | } |
1179 | |
1180 | /// Whether to include completion items with small fix-its, e.g. change |
1181 | /// '.' to '->' on member access, etc. |
1182 | bool includeFixIts() const { return CodeCompleteOpts.IncludeFixIts; } |
1183 | |
1184 | /// Hint whether to load data from the external AST in order to provide |
1185 | /// full results. If false, declarations from the preamble may be omitted. |
1186 | bool loadExternal() const { |
1187 | return CodeCompleteOpts.LoadExternal; |
1188 | } |
1189 | |
1190 | /// Deregisters and destroys this code-completion consumer. |
1191 | virtual ~CodeCompleteConsumer(); |
1192 | |
1193 | /// \name Code-completion filtering |
1194 | /// Check if the result should be filtered out. |
1195 | virtual bool isResultFilteredOut(StringRef Filter, |
1196 | CodeCompletionResult Results) { |
1197 | return false; |
1198 | } |
1199 | |
1200 | /// \name Code-completion callbacks |
1201 | //@{ |
1202 | /// Process the finalized code-completion results. |
1203 | virtual void ProcessCodeCompleteResults(Sema &S, |
1204 | CodeCompletionContext Context, |
1205 | CodeCompletionResult *Results, |
1206 | unsigned NumResults) {} |
1207 | |
1208 | /// \param S the semantic-analyzer object for which code-completion is being |
1209 | /// done. |
1210 | /// |
1211 | /// \param CurrentArg the index of the current argument. |
1212 | /// |
1213 | /// \param Candidates an array of overload candidates. |
1214 | /// |
1215 | /// \param NumCandidates the number of overload candidates |
1216 | /// |
1217 | /// \param OpenParLoc location of the opening parenthesis of the argument |
1218 | /// list. |
1219 | virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg, |
1220 | OverloadCandidate *Candidates, |
1221 | unsigned NumCandidates, |
1222 | SourceLocation OpenParLoc, |
1223 | bool Braced) {} |
1224 | //@} |
1225 | |
1226 | /// Retrieve the allocator that will be used to allocate |
1227 | /// code completion strings. |
1228 | virtual CodeCompletionAllocator &getAllocator() = 0; |
1229 | |
1230 | virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() = 0; |
1231 | }; |
1232 | |
1233 | /// Get the documentation comment used to produce |
1234 | /// CodeCompletionString::BriefComment for RK_Declaration. |
1235 | const RawComment *getCompletionComment(const ASTContext &Ctx, |
1236 | const NamedDecl *Decl); |
1237 | |
1238 | /// Get the documentation comment used to produce |
1239 | /// CodeCompletionString::BriefComment for RK_Pattern. |
1240 | const RawComment *getPatternCompletionComment(const ASTContext &Ctx, |
1241 | const NamedDecl *Decl); |
1242 | |
1243 | /// Get the documentation comment used to produce |
1244 | /// CodeCompletionString::BriefComment for OverloadCandidate. |
1245 | const RawComment * |
1246 | getParameterComment(const ASTContext &Ctx, |
1247 | const CodeCompleteConsumer::OverloadCandidate &Result, |
1248 | unsigned ArgIndex); |
1249 | |
1250 | /// A simple code-completion consumer that prints the results it |
1251 | /// receives in a simple format. |
1252 | class PrintingCodeCompleteConsumer : public CodeCompleteConsumer { |
1253 | /// The raw output stream. |
1254 | raw_ostream &OS; |
1255 | |
1256 | CodeCompletionTUInfo CCTUInfo; |
1257 | |
1258 | public: |
1259 | /// Create a new printing code-completion consumer that prints its |
1260 | /// results to the given raw output stream. |
1261 | PrintingCodeCompleteConsumer(const CodeCompleteOptions &CodeCompleteOpts, |
1262 | raw_ostream &OS) |
1263 | : CodeCompleteConsumer(CodeCompleteOpts), OS(OS), |
1264 | CCTUInfo(std::make_shared<GlobalCodeCompletionAllocator>()) {} |
1265 | |
1266 | /// Prints the finalized code-completion results. |
1267 | void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context, |
1268 | CodeCompletionResult *Results, |
1269 | unsigned NumResults) override; |
1270 | |
1271 | void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg, |
1272 | OverloadCandidate *Candidates, |
1273 | unsigned NumCandidates, |
1274 | SourceLocation OpenParLoc, |
1275 | bool Braced) override; |
1276 | |
1277 | bool isResultFilteredOut(StringRef Filter, CodeCompletionResult Results) override; |
1278 | |
1279 | CodeCompletionAllocator &getAllocator() override { |
1280 | return CCTUInfo.getAllocator(); |
1281 | } |
1282 | |
1283 | CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; } |
1284 | }; |
1285 | |
1286 | } // namespace clang |
1287 | |
1288 | #endif // LLVM_CLANG_SEMA_CODECOMPLETECONSUMER_H |
1 | // <optional> -*- C++ -*- |
2 | |
3 | // Copyright (C) 2013-2020 Free Software Foundation, Inc. |
4 | // |
5 | // This file is part of the GNU ISO C++ Library. This library is free |
6 | // software; you can redistribute it and/or modify it under the |
7 | // terms of the GNU General Public License as published by the |
8 | // Free Software Foundation; either version 3, or (at your option) |
9 | // any later version. |
10 | |
11 | // This library is distributed in the hope that it will be useful, |
12 | // but WITHOUT ANY WARRANTY; without even the implied warranty of |
13 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
14 | // GNU General Public License for more details. |
15 | |
16 | // Under Section 7 of GPL version 3, you are granted additional |
17 | // permissions described in the GCC Runtime Library Exception, version |
18 | // 3.1, as published by the Free Software Foundation. |
19 | |
20 | // You should have received a copy of the GNU General Public License and |
21 | // a copy of the GCC Runtime Library Exception along with this program; |
22 | // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see |
23 | // <http://www.gnu.org/licenses/>. |
24 | |
25 | /** @file include/optional |
26 | * This is a Standard C++ Library header. |
27 | */ |
28 | |
29 | #ifndef _GLIBCXX_OPTIONAL1 |
30 | #define _GLIBCXX_OPTIONAL1 1 |
31 | |
32 | #pragma GCC system_header |
33 | |
34 | #if __cplusplus201703L >= 201703L |
35 | |
36 | #include <utility> |
37 | #include <type_traits> |
38 | #include <exception> |
39 | #include <new> |
40 | #include <initializer_list> |
41 | #include <bits/exception_defines.h> |
42 | #include <bits/functional_hash.h> |
43 | #include <bits/enable_special_members.h> |
44 | #if __cplusplus201703L > 201703L |
45 | # include <compare> |
46 | #endif |
47 | |
48 | namespace std _GLIBCXX_VISIBILITY(default)__attribute__ ((__visibility__ ("default"))) |
49 | { |
50 | _GLIBCXX_BEGIN_NAMESPACE_VERSION |
51 | |
52 | /** |
53 | * @addtogroup utilities |
54 | * @{ |
55 | */ |
56 | |
57 | #define __cpp_lib_optional201606L 201606L |
58 | |
59 | template<typename _Tp> |
60 | class optional; |
61 | |
62 | /// Tag type to disengage optional objects. |
63 | struct nullopt_t |
64 | { |
65 | // Do not user-declare default constructor at all for |
66 | // optional_value = {} syntax to work. |
67 | // nullopt_t() = delete; |
68 | |
69 | // Used for constructing nullopt. |
70 | enum class _Construct { _Token }; |
71 | |
72 | // Must be constexpr for nullopt_t to be literal. |
73 | explicit constexpr nullopt_t(_Construct) { } |
74 | }; |
75 | |
76 | /// Tag to disengage optional objects. |
77 | inline constexpr nullopt_t nullopt { nullopt_t::_Construct::_Token }; |
78 | |
79 | /** |
80 | * @brief Exception class thrown when a disengaged optional object is |
81 | * dereferenced. |
82 | * @ingroup exceptions |
83 | */ |
84 | class bad_optional_access : public exception |
85 | { |
86 | public: |
87 | bad_optional_access() { } |
88 | |
89 | virtual const char* what() const noexcept override |
90 | { return "bad optional access"; } |
91 | |
92 | virtual ~bad_optional_access() noexcept = default; |
93 | }; |
94 | |
95 | void |
96 | __throw_bad_optional_access() |
97 | __attribute__((__noreturn__)); |
98 | |
99 | // XXX Does not belong here. |
100 | inline void |
101 | __throw_bad_optional_access() |
102 | { _GLIBCXX_THROW_OR_ABORT(bad_optional_access())(__builtin_abort()); } |
103 | |
104 | // This class template manages construction/destruction of |
105 | // the contained value for a std::optional. |
106 | template <typename _Tp> |
107 | struct _Optional_payload_base |
108 | { |
109 | using _Stored_type = remove_const_t<_Tp>; |
110 | |
111 | _Optional_payload_base() = default; |
112 | ~_Optional_payload_base() = default; |
113 | |
114 | template<typename... _Args> |
115 | constexpr |
116 | _Optional_payload_base(in_place_t __tag, _Args&&... __args) |
117 | : _M_payload(__tag, std::forward<_Args>(__args)...), |
118 | _M_engaged(true) |
119 | { } |
120 | |
121 | template<typename _Up, typename... _Args> |
122 | constexpr |
123 | _Optional_payload_base(std::initializer_list<_Up> __il, |
124 | _Args&&... __args) |
125 | : _M_payload(__il, std::forward<_Args>(__args)...), |
126 | _M_engaged(true) |
127 | { } |
128 | |
129 | // Constructor used by _Optional_base copy constructor when the |
130 | // contained value is not trivially copy constructible. |
131 | constexpr |
132 | _Optional_payload_base(bool __engaged, |
133 | const _Optional_payload_base& __other) |
134 | { |
135 | if (__other._M_engaged) |
136 | this->_M_construct(__other._M_get()); |
137 | } |
138 | |
139 | // Constructor used by _Optional_base move constructor when the |
140 | // contained value is not trivially move constructible. |
141 | constexpr |
142 | _Optional_payload_base(bool __engaged, |
143 | _Optional_payload_base&& __other) |
144 | { |
145 | if (__other._M_engaged) |
146 | this->_M_construct(std::move(__other._M_get())); |
147 | } |
148 | |
149 | // Copy constructor is only used to when the contained value is |
150 | // trivially copy constructible. |
151 | _Optional_payload_base(const _Optional_payload_base&) = default; |
152 | |
153 | // Move constructor is only used to when the contained value is |
154 | // trivially copy constructible. |
155 | _Optional_payload_base(_Optional_payload_base&&) = default; |
156 | |
157 | _Optional_payload_base& |
158 | operator=(const _Optional_payload_base&) = default; |
159 | |
160 | _Optional_payload_base& |
161 | operator=(_Optional_payload_base&&) = default; |
162 | |
163 | // used to perform non-trivial copy assignment. |
164 | constexpr void |
165 | _M_copy_assign(const _Optional_payload_base& __other) |
166 | { |
167 | if (this->_M_engaged && __other._M_engaged) |
168 | this->_M_get() = __other._M_get(); |
169 | else |
170 | { |
171 | if (__other._M_engaged) |
172 | this->_M_construct(__other._M_get()); |
173 | else |
174 | this->_M_reset(); |
175 | } |
176 | } |
177 | |
178 | // used to perform non-trivial move assignment. |
179 | constexpr void |
180 | _M_move_assign(_Optional_payload_base&& __other) |
181 | noexcept(__and_v<is_nothrow_move_constructible<_Tp>, |
182 | is_nothrow_move_assignable<_Tp>>) |
183 | { |
184 | if (this->_M_engaged && __other._M_engaged) |
185 | this->_M_get() = std::move(__other._M_get()); |
186 | else |
187 | { |
188 | if (__other._M_engaged) |
189 | this->_M_construct(std::move(__other._M_get())); |
190 | else |
191 | this->_M_reset(); |
192 | } |
193 | } |
194 | |
195 | struct _Empty_byte { }; |
196 | |
197 | template<typename _Up, bool = is_trivially_destructible_v<_Up>> |
198 | union _Storage |
199 | { |
200 | constexpr _Storage() noexcept : _M_empty() { } |
201 | |
202 | template<typename... _Args> |
203 | constexpr |
204 | _Storage(in_place_t, _Args&&... __args) |
205 | : _M_value(std::forward<_Args>(__args)...) |
206 | { } |
207 | |
208 | template<typename _Vp, typename... _Args> |
209 | constexpr |
210 | _Storage(std::initializer_list<_Vp> __il, _Args&&... __args) |
211 | : _M_value(__il, std::forward<_Args>(__args)...) |
212 | { } |
213 | |
214 | _Empty_byte _M_empty; |
215 | _Up _M_value; |
216 | }; |
217 | |
218 | template<typename _Up> |
219 | union _Storage<_Up, false> |
220 | { |
221 | constexpr _Storage() noexcept : _M_empty() { } |
222 | |
223 | template<typename... _Args> |
224 | constexpr |
225 | _Storage(in_place_t, _Args&&... __args) |
226 | : _M_value(std::forward<_Args>(__args)...) |
227 | { } |
228 | |
229 | template<typename _Vp, typename... _Args> |
230 | constexpr |
231 | _Storage(std::initializer_list<_Vp> __il, _Args&&... __args) |
232 | : _M_value(__il, std::forward<_Args>(__args)...) |
233 | { } |
234 | |
235 | // User-provided destructor is needed when _Up has non-trivial dtor. |
236 | ~_Storage() { } |
237 | |
238 | _Empty_byte _M_empty; |
239 | _Up _M_value; |
240 | }; |
241 | |
242 | _Storage<_Stored_type> _M_payload; |
243 | |
244 | bool _M_engaged = false; |
245 | |
246 | template<typename... _Args> |
247 | void |
248 | _M_construct(_Args&&... __args) |
249 | noexcept(is_nothrow_constructible_v<_Stored_type, _Args...>) |
250 | { |
251 | ::new ((void *) std::__addressof(this->_M_payload)) |
252 | _Stored_type(std::forward<_Args>(__args)...); |
253 | this->_M_engaged = true; |
254 | } |
255 | |
256 | constexpr void |
257 | _M_destroy() noexcept |
258 | { |
259 | _M_engaged = false; |
260 | _M_payload._M_value.~_Stored_type(); |
261 | } |
262 | |
263 | // The _M_get() operations have _M_engaged as a precondition. |
264 | // They exist to access the contained value with the appropriate |
265 | // const-qualification, because _M_payload has had the const removed. |
266 | |
267 | constexpr _Tp& |
268 | _M_get() noexcept |
269 | { return this->_M_payload._M_value; } |
270 | |
271 | constexpr const _Tp& |
272 | _M_get() const noexcept |
273 | { return this->_M_payload._M_value; } |
274 | |
275 | // _M_reset is a 'safe' operation with no precondition. |
276 | constexpr void |
277 | _M_reset() noexcept |
278 | { |
279 | if (this->_M_engaged) |
280 | _M_destroy(); |
281 | } |
282 | }; |
283 | |
284 | // Class template that manages the payload for optionals. |
285 | template <typename _Tp, |
286 | bool /*_HasTrivialDestructor*/ = |
287 | is_trivially_destructible_v<_Tp>, |
288 | bool /*_HasTrivialCopy */ = |
289 | is_trivially_copy_assignable_v<_Tp> |
290 | && is_trivially_copy_constructible_v<_Tp>, |
291 | bool /*_HasTrivialMove */ = |
292 | is_trivially_move_assignable_v<_Tp> |
293 | && is_trivially_move_constructible_v<_Tp>> |
294 | struct _Optional_payload; |
295 | |
296 | // Payload for potentially-constexpr optionals (trivial copy/move/destroy). |
297 | template <typename _Tp> |
298 | struct _Optional_payload<_Tp, true, true, true> |
299 | : _Optional_payload_base<_Tp> |
300 | { |
301 | using _Optional_payload_base<_Tp>::_Optional_payload_base; |
302 | |
303 | _Optional_payload() = default; |
304 | }; |
305 | |
306 | // Payload for optionals with non-trivial copy construction/assignment. |
307 | template <typename _Tp> |
308 | struct _Optional_payload<_Tp, true, false, true> |
309 | : _Optional_payload_base<_Tp> |
310 | { |
311 | using _Optional_payload_base<_Tp>::_Optional_payload_base; |
312 | |
313 | _Optional_payload() = default; |
314 | ~_Optional_payload() = default; |
315 | _Optional_payload(const _Optional_payload&) = default; |
316 | _Optional_payload(_Optional_payload&&) = default; |
317 | _Optional_payload& operator=(_Optional_payload&&) = default; |
318 | |
319 | // Non-trivial copy assignment. |
320 | constexpr |
321 | _Optional_payload& |
322 | operator=(const _Optional_payload& __other) |
323 | { |
324 | this->_M_copy_assign(__other); |
325 | return *this; |
326 | } |
327 | }; |
328 | |
329 | // Payload for optionals with non-trivial move construction/assignment. |
330 | template <typename _Tp> |
331 | struct _Optional_payload<_Tp, true, true, false> |
332 | : _Optional_payload_base<_Tp> |
333 | { |
334 | using _Optional_payload_base<_Tp>::_Optional_payload_base; |
335 | |
336 | _Optional_payload() = default; |
337 | ~_Optional_payload() = default; |
338 | _Optional_payload(const _Optional_payload&) = default; |
339 | _Optional_payload(_Optional_payload&&) = default; |
340 | _Optional_payload& operator=(const _Optional_payload&) = default; |
341 | |
342 | // Non-trivial move assignment. |
343 | constexpr |
344 | _Optional_payload& |
345 | operator=(_Optional_payload&& __other) |
346 | noexcept(__and_v<is_nothrow_move_constructible<_Tp>, |
347 | is_nothrow_move_assignable<_Tp>>) |
348 | { |
349 | this->_M_move_assign(std::move(__other)); |
350 | return *this; |
351 | } |
352 | }; |
353 | |
354 | // Payload for optionals with non-trivial copy and move assignment. |
355 | template <typename _Tp> |
356 | struct _Optional_payload<_Tp, true, false, false> |
357 | : _Optional_payload_base<_Tp> |
358 | { |
359 | using _Optional_payload_base<_Tp>::_Optional_payload_base; |
360 | |
361 | _Optional_payload() = default; |
362 | ~_Optional_payload() = default; |
363 | _Optional_payload(const _Optional_payload&) = default; |
364 | _Optional_payload(_Optional_payload&&) = default; |
365 | |
366 | // Non-trivial copy assignment. |
367 | constexpr |
368 | _Optional_payload& |
369 | operator=(const _Optional_payload& __other) |
370 | { |
371 | this->_M_copy_assign(__other); |
372 | return *this; |
373 | } |
374 | |
375 | // Non-trivial move assignment. |
376 | constexpr |
377 | _Optional_payload& |
378 | operator=(_Optional_payload&& __other) |
379 | noexcept(__and_v<is_nothrow_move_constructible<_Tp>, |
380 | is_nothrow_move_assignable<_Tp>>) |
381 | { |
382 | this->_M_move_assign(std::move(__other)); |
383 | return *this; |
384 | } |
385 | }; |
386 | |
387 | // Payload for optionals with non-trivial destructors. |
388 | template <typename _Tp, bool _Copy, bool _Move> |
389 | struct _Optional_payload<_Tp, false, _Copy, _Move> |
390 | : _Optional_payload<_Tp, true, false, false> |
391 | { |
392 | // Base class implements all the constructors and assignment operators: |
393 | using _Optional_payload<_Tp, true, false, false>::_Optional_payload; |
394 | _Optional_payload() = default; |
395 | _Optional_payload(const _Optional_payload&) = default; |
396 | _Optional_payload(_Optional_payload&&) = default; |
397 | _Optional_payload& operator=(const _Optional_payload&) = default; |
398 | _Optional_payload& operator=(_Optional_payload&&) = default; |
399 | |
400 | // Destructor needs to destroy the contained value: |
401 | ~_Optional_payload() { this->_M_reset(); } |
402 | }; |
403 | |
404 | // Common base class for _Optional_base<T> to avoid repeating these |
405 | // member functions in each specialization. |
406 | template<typename _Tp, typename _Dp> |
407 | class _Optional_base_impl |
408 | { |
409 | protected: |
410 | using _Stored_type = remove_const_t<_Tp>; |
411 | |
412 | // The _M_construct operation has !_M_engaged as a precondition |
413 | // while _M_destruct has _M_engaged as a precondition. |
414 | template<typename... _Args> |
415 | void |
416 | _M_construct(_Args&&... __args) |
417 | noexcept(is_nothrow_constructible_v<_Stored_type, _Args...>) |
418 | { |
419 | ::new |
420 | (std::__addressof(static_cast<_Dp*>(this)->_M_payload._M_payload)) |
421 | _Stored_type(std::forward<_Args>(__args)...); |
422 | static_cast<_Dp*>(this)->_M_payload._M_engaged = true; |
423 | } |
424 | |
425 | void |
426 | _M_destruct() noexcept |
427 | { static_cast<_Dp*>(this)->_M_payload._M_destroy(); } |
428 | |
429 | // _M_reset is a 'safe' operation with no precondition. |
430 | constexpr void |
431 | _M_reset() noexcept |
432 | { static_cast<_Dp*>(this)->_M_payload._M_reset(); } |
433 | |
434 | constexpr bool _M_is_engaged() const noexcept |
435 | { return static_cast<const _Dp*>(this)->_M_payload._M_engaged; } |
436 | |
437 | // The _M_get operations have _M_engaged as a precondition. |
438 | constexpr _Tp& |
439 | _M_get() noexcept |
440 | { |
441 | __glibcxx_assert(this->_M_is_engaged())do { if (! (this->_M_is_engaged())) std::__replacement_assert ("/usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/optional" , 441, __PRETTY_FUNCTION__, "this->_M_is_engaged()"); } while (false); |
442 | return static_cast<_Dp*>(this)->_M_payload._M_get(); |
443 | } |
444 | |
445 | constexpr const _Tp& |
446 | _M_get() const noexcept |
447 | { |
448 | __glibcxx_assert(this->_M_is_engaged())do { if (! (this->_M_is_engaged())) std::__replacement_assert ("/usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/optional" , 448, __PRETTY_FUNCTION__, "this->_M_is_engaged()"); } while (false); |
449 | return static_cast<const _Dp*>(this)->_M_payload._M_get(); |
450 | } |
451 | }; |
452 | |
453 | /** |
454 | * @brief Class template that provides copy/move constructors of optional. |
455 | * |
456 | * Such a separate base class template is necessary in order to |
457 | * conditionally make copy/move constructors trivial. |
458 | * |
459 | * When the contained value is trivially copy/move constructible, |
460 | * the copy/move constructors of _Optional_base will invoke the |
461 | * trivial copy/move constructor of _Optional_payload. Otherwise, |
462 | * they will invoke _Optional_payload(bool, const _Optional_payload&) |
463 | * or _Optional_payload(bool, _Optional_payload&&) to initialize |
464 | * the contained value, if copying/moving an engaged optional. |
465 | * |
466 | * Whether the other special members are trivial is determined by the |
467 | * _Optional_payload<_Tp> specialization used for the _M_payload member. |
468 | * |
469 | * @see optional, _Enable_special_members |
470 | */ |
471 | template<typename _Tp, |
472 | bool = is_trivially_copy_constructible_v<_Tp>, |
473 | bool = is_trivially_move_constructible_v<_Tp>> |
474 | struct _Optional_base |
475 | : _Optional_base_impl<_Tp, _Optional_base<_Tp>> |
476 | { |
477 | // Constructors for disengaged optionals. |
478 | constexpr _Optional_base() = default; |
479 | |
480 | // Constructors for engaged optionals. |
481 | template<typename... _Args, |
482 | enable_if_t<is_constructible_v<_Tp, _Args&&...>, bool> = false> |
483 | constexpr explicit _Optional_base(in_place_t, _Args&&... __args) |
484 | : _M_payload(in_place, |
485 | std::forward<_Args>(__args)...) { } |
486 | |
487 | template<typename _Up, typename... _Args, |
488 | enable_if_t<is_constructible_v<_Tp, |
489 | initializer_list<_Up>&, |
490 | _Args&&...>, bool> = false> |
491 | constexpr explicit _Optional_base(in_place_t, |
492 | initializer_list<_Up> __il, |
493 | _Args&&... __args) |
494 | : _M_payload(in_place, |
495 | __il, std::forward<_Args>(__args)...) |
496 | { } |
497 | |
498 | // Copy and move constructors. |
499 | constexpr _Optional_base(const _Optional_base& __other) |
500 | : _M_payload(__other._M_payload._M_engaged, |
501 | __other._M_payload) |
502 | { } |
503 | |
504 | constexpr _Optional_base(_Optional_base&& __other) |
505 | noexcept(is_nothrow_move_constructible_v<_Tp>) |
506 | : _M_payload(__other._M_payload._M_engaged, |
507 | std::move(__other._M_payload)) |
508 | { } |
509 | |
510 | // Assignment operators. |
511 | _Optional_base& operator=(const _Optional_base&) = default; |
512 | _Optional_base& operator=(_Optional_base&&) = default; |
513 | |
514 | _Optional_payload<_Tp> _M_payload; |
515 | }; |
516 | |
517 | template<typename _Tp> |
518 | struct _Optional_base<_Tp, false, true> |
519 | : _Optional_base_impl<_Tp, _Optional_base<_Tp>> |
520 | { |
521 | // Constructors for disengaged optionals. |
522 | constexpr _Optional_base() = default; |
523 | |
524 | // Constructors for engaged optionals. |
525 | template<typename... _Args, |
526 | enable_if_t<is_constructible_v<_Tp, _Args&&...>, bool> = false> |
527 | constexpr explicit _Optional_base(in_place_t, _Args&&... __args) |
528 | : _M_payload(in_place, |
529 | std::forward<_Args>(__args)...) { } |
530 | |
531 | template<typename _Up, typename... _Args, |
532 | enable_if_t<is_constructible_v<_Tp, |
533 | initializer_list<_Up>&, |
534 | _Args&&...>, bool> = false> |
535 | constexpr explicit _Optional_base(in_place_t, |
536 | initializer_list<_Up> __il, |
537 | _Args&&... __args) |
538 | : _M_payload(in_place, |
539 | __il, std::forward<_Args>(__args)...) |
540 | { } |
541 | |
542 | // Copy and move constructors. |
543 | constexpr _Optional_base(const _Optional_base& __other) |
544 | : _M_payload(__other._M_payload._M_engaged, |
545 | __other._M_payload) |
546 | { } |
547 | |
548 | constexpr _Optional_base(_Optional_base&& __other) = default; |
549 | |
550 | // Assignment operators. |
551 | _Optional_base& operator=(const _Optional_base&) = default; |
552 | _Optional_base& operator=(_Optional_base&&) = default; |
553 | |
554 | _Optional_payload<_Tp> _M_payload; |
555 | }; |
556 | |
557 | template<typename _Tp> |
558 | struct _Optional_base<_Tp, true, false> |
559 | : _Optional_base_impl<_Tp, _Optional_base<_Tp>> |
560 | { |
561 | // Constructors for disengaged optionals. |
562 | constexpr _Optional_base() = default; |
563 | |
564 | // Constructors for engaged optionals. |
565 | template<typename... _Args, |
566 | enable_if_t<is_constructible_v<_Tp, _Args&&...>, bool> = false> |
567 | constexpr explicit _Optional_base(in_place_t, _Args&&... __args) |
568 | : _M_payload(in_place, |
569 | std::forward<_Args>(__args)...) { } |
570 | |
571 | template<typename _Up, typename... _Args, |
572 | enable_if_t<is_constructible_v<_Tp, |
573 | initializer_list<_Up>&, |
574 | _Args&&...>, bool> = false> |
575 | constexpr explicit _Optional_base(in_place_t, |
576 | initializer_list<_Up> __il, |
577 | _Args&&... __args) |
578 | : _M_payload(in_place, |
579 | __il, std::forward<_Args>(__args)...) |
580 | { } |
581 | |
582 | // Copy and move constructors. |
583 | constexpr _Optional_base(const _Optional_base& __other) = default; |
584 | |
585 | constexpr _Optional_base(_Optional_base&& __other) |
586 | noexcept(is_nothrow_move_constructible_v<_Tp>) |
587 | : _M_payload(__other._M_payload._M_engaged, |
588 | std::move(__other._M_payload)) |
589 | { } |
590 | |
591 | // Assignment operators. |
592 | _Optional_base& operator=(const _Optional_base&) = default; |
593 | _Optional_base& operator=(_Optional_base&&) = default; |
594 | |
595 | _Optional_payload<_Tp> _M_payload; |
596 | }; |
597 | |
598 | template<typename _Tp> |
599 | struct _Optional_base<_Tp, true, true> |
600 | : _Optional_base_impl<_Tp, _Optional_base<_Tp>> |
601 | { |
602 | // Constructors for disengaged optionals. |
603 | constexpr _Optional_base() = default; |
604 | |
605 | // Constructors for engaged optionals. |
606 | template<typename... _Args, |
607 | enable_if_t<is_constructible_v<_Tp, _Args&&...>, bool> = false> |
608 | constexpr explicit _Optional_base(in_place_t, _Args&&... __args) |
609 | : _M_payload(in_place, |
610 | std::forward<_Args>(__args)...) { } |
611 | |
612 | template<typename _Up, typename... _Args, |
613 | enable_if_t<is_constructible_v<_Tp, |
614 | initializer_list<_Up>&, |
615 | _Args&&...>, bool> = false> |
616 | constexpr explicit _Optional_base(in_place_t, |
617 | initializer_list<_Up> __il, |
618 | _Args&&... __args) |
619 | : _M_payload(in_place, |
620 | __il, std::forward<_Args>(__args)...) |
621 | { } |
622 | |
623 | // Copy and move constructors. |
624 | constexpr _Optional_base(const _Optional_base& __other) = default; |
625 | constexpr _Optional_base(_Optional_base&& __other) = default; |
626 | |
627 | // Assignment operators. |
628 | _Optional_base& operator=(const _Optional_base&) = default; |
629 | _Optional_base& operator=(_Optional_base&&) = default; |
630 | |
631 | _Optional_payload<_Tp> _M_payload; |
632 | }; |
633 | |
634 | template<typename _Tp> |
635 | class optional; |
636 | |
637 | template<typename _Tp, typename _Up> |
638 | using __converts_from_optional = |
639 | __or_<is_constructible<_Tp, const optional<_Up>&>, |
640 | is_constructible<_Tp, optional<_Up>&>, |
641 | is_constructible<_Tp, const optional<_Up>&&>, |
642 | is_constructible<_Tp, optional<_Up>&&>, |
643 | is_convertible<const optional<_Up>&, _Tp>, |
644 | is_convertible<optional<_Up>&, _Tp>, |
645 | is_convertible<const optional<_Up>&&, _Tp>, |
646 | is_convertible<optional<_Up>&&, _Tp>>; |
647 | |
648 | template<typename _Tp, typename _Up> |
649 | using __assigns_from_optional = |
650 | __or_<is_assignable<_Tp&, const optional<_Up>&>, |
651 | is_assignable<_Tp&, optional<_Up>&>, |
652 | is_assignable<_Tp&, const optional<_Up>&&>, |
653 | is_assignable<_Tp&, optional<_Up>&&>>; |
654 | |
655 | /** |
656 | * @brief Class template for optional values. |
657 | */ |
658 | template<typename _Tp> |
659 | class optional |
660 | : private _Optional_base<_Tp>, |
661 | private _Enable_copy_move< |
662 | // Copy constructor. |
663 | is_copy_constructible_v<_Tp>, |
664 | // Copy assignment. |
665 | __and_v<is_copy_constructible<_Tp>, is_copy_assignable<_Tp>>, |
666 | // Move constructor. |
667 | is_move_constructible_v<_Tp>, |
668 | // Move assignment. |
669 | __and_v<is_move_constructible<_Tp>, is_move_assignable<_Tp>>, |
670 | // Unique tag type. |
671 | optional<_Tp>> |
672 | { |
673 | static_assert(!is_same_v<remove_cv_t<_Tp>, nullopt_t>); |
674 | static_assert(!is_same_v<remove_cv_t<_Tp>, in_place_t>); |
675 | static_assert(!is_reference_v<_Tp>); |
676 | |
677 | private: |
678 | using _Base = _Optional_base<_Tp>; |
679 | |
680 | // SFINAE helpers |
681 | template<typename _Up> |
682 | using __not_self = __not_<is_same<optional, __remove_cvref_t<_Up>>>; |
683 | template<typename _Up> |
684 | using __not_tag = __not_<is_same<in_place_t, __remove_cvref_t<_Up>>>; |
685 | template<typename... _Cond> |
686 | using _Requires = enable_if_t<__and_v<_Cond...>, bool>; |
687 | |
688 | public: |
689 | using value_type = _Tp; |
690 | |
691 | constexpr optional() = default; |
692 | |
693 | constexpr optional(nullopt_t) noexcept { } |
694 | |
695 | // Converting constructors for engaged optionals. |
696 | template<typename _Up = _Tp, |
697 | _Requires<__not_self<_Up>, __not_tag<_Up>, |
698 | is_constructible<_Tp, _Up&&>, |
699 | is_convertible<_Up&&, _Tp>> = true> |
700 | constexpr |
701 | optional(_Up&& __t) |
702 | : _Base(std::in_place, std::forward<_Up>(__t)) { } |
703 | |
704 | template<typename _Up = _Tp, |
705 | _Requires<__not_self<_Up>, __not_tag<_Up>, |
706 | is_constructible<_Tp, _Up&&>, |
707 | __not_<is_convertible<_Up&&, _Tp>>> = false> |
708 | explicit constexpr |
709 | optional(_Up&& __t) |
710 | : _Base(std::in_place, std::forward<_Up>(__t)) { } |
711 | |
712 | template<typename _Up, |
713 | _Requires<__not_<is_same<_Tp, _Up>>, |
714 | is_constructible<_Tp, const _Up&>, |
715 | is_convertible<const _Up&, _Tp>, |
716 | __not_<__converts_from_optional<_Tp, _Up>>> = true> |
717 | constexpr |
718 | optional(const optional<_Up>& __t) |
719 | { |
720 | if (__t) |
721 | emplace(*__t); |
722 | } |
723 | |
724 | template<typename _Up, |
725 | _Requires<__not_<is_same<_Tp, _Up>>, |
726 | is_constructible<_Tp, const _Up&>, |
727 | __not_<is_convertible<const _Up&, _Tp>>, |
728 | __not_<__converts_from_optional<_Tp, _Up>>> = false> |
729 | explicit constexpr |
730 | optional(const optional<_Up>& __t) |
731 | { |
732 | if (__t) |
733 | emplace(*__t); |
734 | } |
735 | |
736 | template <typename _Up, |
737 | _Requires<__not_<is_same<_Tp, _Up>>, |
738 | is_constructible<_Tp, _Up&&>, |
739 | is_convertible<_Up&&, _Tp>, |
740 | __not_<__converts_from_optional<_Tp, _Up>>> = true> |
741 | constexpr |
742 | optional(optional<_Up>&& __t) |
743 | { |
744 | if (__t) |
745 | emplace(std::move(*__t)); |
746 | } |
747 | |
748 | template <typename _Up, |
749 | _Requires<__not_<is_same<_Tp, _Up>>, |
750 | is_constructible<_Tp, _Up&&>, |
751 | __not_<is_convertible<_Up&&, _Tp>>, |
752 | __not_<__converts_from_optional<_Tp, _Up>>> = false> |
753 | explicit constexpr |
754 | optional(optional<_Up>&& __t) |
755 | { |
756 | if (__t) |
757 | emplace(std::move(*__t)); |
758 | } |
759 | |
760 | template<typename... _Args, |
761 | _Requires<is_constructible<_Tp, _Args&&...>> = false> |
762 | explicit constexpr |
763 | optional(in_place_t, _Args&&... __args) |
764 | : _Base(std::in_place, std::forward<_Args>(__args)...) { } |
765 | |
766 | template<typename _Up, typename... _Args, |
767 | _Requires<is_constructible<_Tp, |
768 | initializer_list<_Up>&, |
769 | _Args&&...>> = false> |
770 | explicit constexpr |
771 | optional(in_place_t, initializer_list<_Up> __il, _Args&&... __args) |
772 | : _Base(std::in_place, __il, std::forward<_Args>(__args)...) { } |
773 | |
774 | // Assignment operators. |
775 | optional& |
776 | operator=(nullopt_t) noexcept |
777 | { |
778 | this->_M_reset(); |
779 | return *this; |
780 | } |
781 | |
782 | template<typename _Up = _Tp> |
783 | enable_if_t<__and_v<__not_self<_Up>, |
784 | __not_<__and_<is_scalar<_Tp>, |
785 | is_same<_Tp, decay_t<_Up>>>>, |
786 | is_constructible<_Tp, _Up>, |
787 | is_assignable<_Tp&, _Up>>, |
788 | optional&> |
789 | operator=(_Up&& __u) |
790 | { |
791 | if (this->_M_is_engaged()) |
792 | this->_M_get() = std::forward<_Up>(__u); |
793 | else |
794 | this->_M_construct(std::forward<_Up>(__u)); |
795 | |
796 | return *this; |
797 | } |
798 | |
799 | template<typename _Up> |
800 | enable_if_t<__and_v<__not_<is_same<_Tp, _Up>>, |
801 | is_constructible<_Tp, const _Up&>, |
802 | is_assignable<_Tp&, _Up>, |
803 | __not_<__converts_from_optional<_Tp, _Up>>, |
804 | __not_<__assigns_from_optional<_Tp, _Up>>>, |
805 | optional&> |
806 | operator=(const optional<_Up>& __u) |
807 | { |
808 | if (__u) |
809 | { |
810 | if (this->_M_is_engaged()) |
811 | this->_M_get() = *__u; |
812 | else |
813 | this->_M_construct(*__u); |
814 | } |
815 | else |
816 | { |
817 | this->_M_reset(); |
818 | } |
819 | return *this; |
820 | } |
821 | |
822 | template<typename _Up> |
823 | enable_if_t<__and_v<__not_<is_same<_Tp, _Up>>, |
824 | is_constructible<_Tp, _Up>, |
825 | is_assignable<_Tp&, _Up>, |
826 | __not_<__converts_from_optional<_Tp, _Up>>, |
827 | __not_<__assigns_from_optional<_Tp, _Up>>>, |
828 | optional&> |
829 | operator=(optional<_Up>&& __u) |
830 | { |
831 | if (__u) |
832 | { |
833 | if (this->_M_is_engaged()) |
834 | this->_M_get() = std::move(*__u); |
835 | else |
836 | this->_M_construct(std::move(*__u)); |
837 | } |
838 | else |
839 | { |
840 | this->_M_reset(); |
841 | } |
842 | |
843 | return *this; |
844 | } |
845 | |
846 | template<typename... _Args> |
847 | enable_if_t<is_constructible_v<_Tp, _Args&&...>, _Tp&> |
848 | emplace(_Args&&... __args) |
849 | { |
850 | this->_M_reset(); |
851 | this->_M_construct(std::forward<_Args>(__args)...); |
852 | return this->_M_get(); |
853 | } |
854 | |
855 | template<typename _Up, typename... _Args> |
856 | enable_if_t<is_constructible_v<_Tp, initializer_list<_Up>&, |
857 | _Args&&...>, _Tp&> |
858 | emplace(initializer_list<_Up> __il, _Args&&... __args) |
859 | { |
860 | this->_M_reset(); |
861 | this->_M_construct(__il, std::forward<_Args>(__args)...); |
862 | return this->_M_get(); |
863 | } |
864 | |
865 | // Destructor is implicit, implemented in _Optional_base. |
866 | |
867 | // Swap. |
868 | void |
869 | swap(optional& __other) |
870 | noexcept(is_nothrow_move_constructible_v<_Tp> |
871 | && is_nothrow_swappable_v<_Tp>) |
872 | { |
873 | using std::swap; |
874 | |
875 | if (this->_M_is_engaged() && __other._M_is_engaged()) |
876 | swap(this->_M_get(), __other._M_get()); |
877 | else if (this->_M_is_engaged()) |
878 | { |
879 | __other._M_construct(std::move(this->_M_get())); |
880 | this->_M_destruct(); |
881 | } |
882 | else if (__other._M_is_engaged()) |
883 | { |
884 | this->_M_construct(std::move(__other._M_get())); |
885 | __other._M_destruct(); |
886 | } |
887 | } |
888 | |
889 | // Observers. |
890 | constexpr const _Tp* |
891 | operator->() const |
892 | { return std::__addressof(this->_M_get()); } |
893 | |
894 | constexpr _Tp* |
895 | operator->() |
896 | { return std::__addressof(this->_M_get()); } |
897 | |
898 | constexpr const _Tp& |
899 | operator*() const& |
900 | { return this->_M_get(); } |
901 | |
902 | constexpr _Tp& |
903 | operator*()& |
904 | { return this->_M_get(); } |
905 | |
906 | constexpr _Tp&& |
907 | operator*()&& |
908 | { return std::move(this->_M_get()); } |
909 | |
910 | constexpr const _Tp&& |
911 | operator*() const&& |
912 | { return std::move(this->_M_get()); } |
913 | |
914 | constexpr explicit operator bool() const noexcept |
915 | { return this->_M_is_engaged(); } |
916 | |
917 | constexpr bool has_value() const noexcept |
918 | { return this->_M_is_engaged(); } |
919 | |
920 | constexpr const _Tp& |
921 | value() const& |
922 | { |
923 | return this->_M_is_engaged() |
924 | ? this->_M_get() |
925 | : (__throw_bad_optional_access(), this->_M_get()); |
926 | } |
927 | |
928 | constexpr _Tp& |
929 | value()& |
930 | { |
931 | return this->_M_is_engaged() |
932 | ? this->_M_get() |
933 | : (__throw_bad_optional_access(), this->_M_get()); |
934 | } |
935 | |
936 | constexpr _Tp&& |
937 | value()&& |
938 | { |
939 | return this->_M_is_engaged() |
940 | ? std::move(this->_M_get()) |
941 | : (__throw_bad_optional_access(), std::move(this->_M_get())); |
942 | } |
943 | |
944 | constexpr const _Tp&& |
945 | value() const&& |
946 | { |
947 | return this->_M_is_engaged() |
948 | ? std::move(this->_M_get()) |
949 | : (__throw_bad_optional_access(), std::move(this->_M_get())); |
950 | } |
951 | |
952 | template<typename _Up> |
953 | constexpr _Tp |
954 | value_or(_Up&& __u) const& |
955 | { |
956 | static_assert(is_copy_constructible_v<_Tp>); |
957 | static_assert(is_convertible_v<_Up&&, _Tp>); |
958 | |
959 | return this->_M_is_engaged() |
960 | ? this->_M_get() : static_cast<_Tp>(std::forward<_Up>(__u)); |
961 | } |
962 | |
963 | template<typename _Up> |
964 | constexpr _Tp |
965 | value_or(_Up&& __u) && |
966 | { |
967 | static_assert(is_move_constructible_v<_Tp>); |
968 | static_assert(is_convertible_v<_Up&&, _Tp>); |
969 | |
970 | return this->_M_is_engaged() |
971 | ? std::move(this->_M_get()) |
972 | : static_cast<_Tp>(std::forward<_Up>(__u)); |
973 | } |
974 | |
975 | void reset() noexcept { this->_M_reset(); } |
976 | }; |
977 | |
978 | template<typename _Tp> |
979 | using __optional_relop_t = |
980 | enable_if_t<is_convertible<_Tp, bool>::value, bool>; |
981 | |
982 | template<typename _Tp, typename _Up> |
983 | using __optional_eq_t = __optional_relop_t< |
984 | decltype(std::declval<const _Tp&>() == std::declval<const _Up&>()) |
985 | >; |
986 | |
987 | template<typename _Tp, typename _Up> |
988 | using __optional_ne_t = __optional_relop_t< |
989 | decltype(std::declval<const _Tp&>() != std::declval<const _Up&>()) |
990 | >; |
991 | |
992 | template<typename _Tp, typename _Up> |
993 | using __optional_lt_t = __optional_relop_t< |
994 | decltype(std::declval<const _Tp&>() < std::declval<const _Up&>()) |
995 | >; |
996 | |
997 | template<typename _Tp, typename _Up> |
998 | using __optional_gt_t = __optional_relop_t< |
999 | decltype(std::declval<const _Tp&>() > std::declval<const _Up&>()) |
1000 | >; |
1001 | |
1002 | template<typename _Tp, typename _Up> |
1003 | using __optional_le_t = __optional_relop_t< |
1004 | decltype(std::declval<const _Tp&>() <= std::declval<const _Up&>()) |
1005 | >; |
1006 | |
1007 | template<typename _Tp, typename _Up> |
1008 | using __optional_ge_t = __optional_relop_t< |
1009 | decltype(std::declval<const _Tp&>() >= std::declval<const _Up&>()) |
1010 | >; |
1011 | |
1012 | // Comparisons between optional values. |
1013 | template<typename _Tp, typename _Up> |
1014 | constexpr auto |
1015 | operator==(const optional<_Tp>& __lhs, const optional<_Up>& __rhs) |
1016 | -> __optional_eq_t<_Tp, _Up> |
1017 | { |
1018 | return static_cast<bool>(__lhs) == static_cast<bool>(__rhs) |
1019 | && (!__lhs || *__lhs == *__rhs); |
1020 | } |
1021 | |
1022 | template<typename _Tp, typename _Up> |
1023 | constexpr auto |
1024 | operator!=(const optional<_Tp>& __lhs, const optional<_Up>& __rhs) |
1025 | -> __optional_ne_t<_Tp, _Up> |
1026 | { |
1027 | return static_cast<bool>(__lhs) != static_cast<bool>(__rhs) |
1028 | || (static_cast<bool>(__lhs) && *__lhs != *__rhs); |
1029 | } |
1030 | |
1031 | template<typename _Tp, typename _Up> |
1032 | constexpr auto |
1033 | operator<(const optional<_Tp>& __lhs, const optional<_Up>& __rhs) |
1034 | -> __optional_lt_t<_Tp, _Up> |
1035 | { |
1036 | return static_cast<bool>(__rhs) && (!__lhs || *__lhs < *__rhs); |
1037 | } |
1038 | |
1039 | template<typename _Tp, typename _Up> |
1040 | constexpr auto |
1041 | operator>(const optional<_Tp>& __lhs, const optional<_Up>& __rhs) |
1042 | -> __optional_gt_t<_Tp, _Up> |
1043 | { |
1044 | return static_cast<bool>(__lhs) && (!__rhs || *__lhs > *__rhs); |
1045 | } |
1046 | |
1047 | template<typename _Tp, typename _Up> |
1048 | constexpr auto |
1049 | operator<=(const optional<_Tp>& __lhs, const optional<_Up>& __rhs) |
1050 | -> __optional_le_t<_Tp, _Up> |
1051 | { |
1052 | return !__lhs || (static_cast<bool>(__rhs) && *__lhs <= *__rhs); |
1053 | } |
1054 | |
1055 | template<typename _Tp, typename _Up> |
1056 | constexpr auto |
1057 | operator>=(const optional<_Tp>& __lhs, const optional<_Up>& __rhs) |
1058 | -> __optional_ge_t<_Tp, _Up> |
1059 | { |
1060 | return !__rhs || (static_cast<bool>(__lhs) && *__lhs >= *__rhs); |
1061 | } |
1062 | |
1063 | #ifdef __cpp_lib_three_way_comparison |
1064 | template<typename _Tp, three_way_comparable_with<_Tp> _Up> |
1065 | constexpr compare_three_way_result_t<_Tp, _Up> |
1066 | operator<=>(const optional<_Tp>& __x, const optional<_Up>& __y) |
1067 | { |
1068 | return __x && __y ? *__x <=> *__y : bool(__x) <=> bool(__y); |
1069 | } |
1070 | #endif |
1071 | |
1072 | // Comparisons with nullopt. |
1073 | template<typename _Tp> |
1074 | constexpr bool |
1075 | operator==(const optional<_Tp>& __lhs, nullopt_t) noexcept |
1076 | { return !__lhs; } |
1077 | |
1078 | #ifdef __cpp_lib_three_way_comparison |
1079 | template<typename _Tp> |
1080 | constexpr strong_ordering |
1081 | operator<=>(const optional<_Tp>& __x, nullopt_t) noexcept |
1082 | { return bool(__x) <=> false; } |
1083 | #else |
1084 | template<typename _Tp> |
1085 | constexpr bool |
1086 | operator==(nullopt_t, const optional<_Tp>& __rhs) noexcept |
1087 | { return !__rhs; } |
1088 | |
1089 | template<typename _Tp> |
1090 | constexpr bool |
1091 | operator!=(const optional<_Tp>& __lhs, nullopt_t) noexcept |
1092 | { return static_cast<bool>(__lhs); } |
1093 | |
1094 | template<typename _Tp> |
1095 | constexpr bool |
1096 | operator!=(nullopt_t, const optional<_Tp>& __rhs) noexcept |
1097 | { return static_cast<bool>(__rhs); } |
1098 | |
1099 | template<typename _Tp> |
1100 | constexpr bool |
1101 | operator<(const optional<_Tp>& /* __lhs */, nullopt_t) noexcept |
1102 | { return false; } |
1103 | |
1104 | template<typename _Tp> |
1105 | constexpr bool |
1106 | operator<(nullopt_t, const optional<_Tp>& __rhs) noexcept |
1107 | { return static_cast<bool>(__rhs); } |
1108 | |
1109 | template<typename _Tp> |
1110 | constexpr bool |
1111 | operator>(const optional<_Tp>& __lhs, nullopt_t) noexcept |
1112 | { return static_cast<bool>(__lhs); } |
1113 | |
1114 | template<typename _Tp> |
1115 | constexpr bool |
1116 | operator>(nullopt_t, const optional<_Tp>& /* __rhs */) noexcept |
1117 | { return false; } |
1118 | |
1119 | template<typename _Tp> |
1120 | constexpr bool |
1121 | operator<=(const optional<_Tp>& __lhs, nullopt_t) noexcept |
1122 | { return !__lhs; } |
1123 | |
1124 | template<typename _Tp> |
1125 | constexpr bool |
1126 | operator<=(nullopt_t, const optional<_Tp>& /* __rhs */) noexcept |
1127 | { return true; } |
1128 | |
1129 | template<typename _Tp> |
1130 | constexpr bool |
1131 | operator>=(const optional<_Tp>& /* __lhs */, nullopt_t) noexcept |
1132 | { return true; } |
1133 | |
1134 | template<typename _Tp> |
1135 | constexpr bool |
1136 | operator>=(nullopt_t, const optional<_Tp>& __rhs) noexcept |
1137 | { return !__rhs; } |
1138 | #endif // three-way-comparison |
1139 | |
1140 | // Comparisons with value type. |
1141 | template<typename _Tp, typename _Up> |
1142 | constexpr auto |
1143 | operator==(const optional<_Tp>& __lhs, const _Up& __rhs) |
1144 | -> __optional_eq_t<_Tp, _Up> |
1145 | { return __lhs && *__lhs == __rhs; } |
1146 | |
1147 | template<typename _Tp, typename _Up> |
1148 | constexpr auto |
1149 | operator==(const _Up& __lhs, const optional<_Tp>& __rhs) |
1150 | -> __optional_eq_t<_Up, _Tp> |
1151 | { return __rhs && __lhs == *__rhs; } |
1152 | |
1153 | template<typename _Tp, typename _Up> |
1154 | constexpr auto |
1155 | operator!=(const optional<_Tp>& __lhs, const _Up& __rhs) |
1156 | -> __optional_ne_t<_Tp, _Up> |
1157 | { return !__lhs || *__lhs != __rhs; } |
1158 | |
1159 | template<typename _Tp, typename _Up> |
1160 | constexpr auto |
1161 | operator!=(const _Up& __lhs, const optional<_Tp>& __rhs) |
1162 | -> __optional_ne_t<_Up, _Tp> |
1163 | { return !__rhs || __lhs != *__rhs; } |
1164 | |
1165 | template<typename _Tp, typename _Up> |
1166 | constexpr auto |
1167 | operator<(const optional<_Tp>& __lhs, const _Up& __rhs) |
1168 | -> __optional_lt_t<_Tp, _Up> |
1169 | { return !__lhs || *__lhs < __rhs; } |
1170 | |
1171 | template<typename _Tp, typename _Up> |
1172 | constexpr auto |
1173 | operator<(const _Up& __lhs, const optional<_Tp>& __rhs) |
1174 | -> __optional_lt_t<_Up, _Tp> |
1175 | { return __rhs && __lhs < *__rhs; } |
1176 | |
1177 | template<typename _Tp, typename _Up> |
1178 | constexpr auto |
1179 | operator>(const optional<_Tp>& __lhs, const _Up& __rhs) |
1180 | -> __optional_gt_t<_Tp, _Up> |
1181 | { return __lhs && *__lhs > __rhs; } |
1182 | |
1183 | template<typename _Tp, typename _Up> |
1184 | constexpr auto |
1185 | operator>(const _Up& __lhs, const optional<_Tp>& __rhs) |
1186 | -> __optional_gt_t<_Up, _Tp> |
1187 | { return !__rhs || __lhs > *__rhs; } |
1188 | |
1189 | template<typename _Tp, typename _Up> |
1190 | constexpr auto |
1191 | operator<=(const optional<_Tp>& __lhs, const _Up& __rhs) |
1192 | -> __optional_le_t<_Tp, _Up> |
1193 | { return !__lhs || *__lhs <= __rhs; } |
1194 | |
1195 | template<typename _Tp, typename _Up> |
1196 | constexpr auto |
1197 | operator<=(const _Up& __lhs, const optional<_Tp>& __rhs) |
1198 | -> __optional_le_t<_Up, _Tp> |
1199 | { return __rhs && __lhs <= *__rhs; } |
1200 | |
1201 | template<typename _Tp, typename _Up> |
1202 | constexpr auto |
1203 | operator>=(const optional<_Tp>& __lhs, const _Up& __rhs) |
1204 | -> __optional_ge_t<_Tp, _Up> |
1205 | { return __lhs && *__lhs >= __rhs; } |
1206 | |
1207 | template<typename _Tp, typename _Up> |
1208 | constexpr auto |
1209 | operator>=(const _Up& __lhs, const optional<_Tp>& __rhs) |
1210 | -> __optional_ge_t<_Up, _Tp> |
1211 | { return !__rhs || __lhs >= *__rhs; } |
1212 | |
1213 | #ifdef __cpp_lib_three_way_comparison |
1214 | template<typename _Tp, typename _Up> |
1215 | constexpr compare_three_way_result_t<_Tp, _Up> |
1216 | operator<=>(const optional<_Tp>& __x, const _Up& __v) |
1217 | { return bool(__x) ? *__x <=> __v : strong_ordering::less; } |
1218 | #endif |
1219 | |
1220 | // Swap and creation functions. |
1221 | |
1222 | // _GLIBCXX_RESOLVE_LIB_DEFECTS |
1223 | // 2748. swappable traits for optionals |
1224 | template<typename _Tp> |
1225 | inline enable_if_t<is_move_constructible_v<_Tp> && is_swappable_v<_Tp>> |
1226 | swap(optional<_Tp>& __lhs, optional<_Tp>& __rhs) |
1227 | noexcept(noexcept(__lhs.swap(__rhs))) |
1228 | { __lhs.swap(__rhs); } |
1229 | |
1230 | template<typename _Tp> |
1231 | enable_if_t<!(is_move_constructible_v<_Tp> && is_swappable_v<_Tp>)> |
1232 | swap(optional<_Tp>&, optional<_Tp>&) = delete; |
1233 | |
1234 | template<typename _Tp> |
1235 | constexpr optional<decay_t<_Tp>> |
1236 | make_optional(_Tp&& __t) |
1237 | { return optional<decay_t<_Tp>> { std::forward<_Tp>(__t) }; } |
1238 | |
1239 | template<typename _Tp, typename ..._Args> |
1240 | constexpr optional<_Tp> |
1241 | make_optional(_Args&&... __args) |
1242 | { return optional<_Tp> { in_place, std::forward<_Args>(__args)... }; } |
1243 | |
1244 | template<typename _Tp, typename _Up, typename ..._Args> |
1245 | constexpr optional<_Tp> |
1246 | make_optional(initializer_list<_Up> __il, _Args&&... __args) |
1247 | { return optional<_Tp> { in_place, __il, std::forward<_Args>(__args)... }; } |
1248 | |
1249 | // Hash. |
1250 | |
1251 | template<typename _Tp, typename _Up = remove_const_t<_Tp>, |
1252 | bool = __poison_hash<_Up>::__enable_hash_call> |
1253 | struct __optional_hash_call_base |
1254 | { |
1255 | size_t |
1256 | operator()(const optional<_Tp>& __t) const |
1257 | noexcept(noexcept(hash<_Up>{}(*__t))) |
1258 | { |
1259 | // We pick an arbitrary hash for disengaged optionals which hopefully |
1260 | // usual values of _Tp won't typically hash to. |
1261 | constexpr size_t __magic_disengaged_hash = static_cast<size_t>(-3333); |
1262 | return __t ? hash<_Up>{}(*__t) : __magic_disengaged_hash; |
1263 | } |
1264 | }; |
1265 | |
1266 | template<typename _Tp, typename _Up> |
1267 | struct __optional_hash_call_base<_Tp, _Up, false> {}; |
1268 | |
1269 | template<typename _Tp> |
1270 | struct hash<optional<_Tp>> |
1271 | : private __poison_hash<remove_const_t<_Tp>>, |
1272 | public __optional_hash_call_base<_Tp> |
1273 | { |
1274 | using result_type [[__deprecated__]] = size_t; |
1275 | using argument_type [[__deprecated__]] = optional<_Tp>; |
1276 | }; |
1277 | |
1278 | template<typename _Tp> |
1279 | struct __is_fast_hash<hash<optional<_Tp>>> : __is_fast_hash<hash<_Tp>> |
1280 | { }; |
1281 | |
1282 | /// @} |
1283 | |
1284 | #if __cpp_deduction_guides201703L >= 201606 |
1285 | template <typename _Tp> optional(_Tp) -> optional<_Tp>; |
1286 | #endif |
1287 | |
1288 | _GLIBCXX_END_NAMESPACE_VERSION |
1289 | } // namespace std |
1290 | |
1291 | #endif // C++17 |
1292 | |
1293 | #endif // _GLIBCXX_OPTIONAL |
1 | //===--- DeclSpec.h - Parsed declaration specifiers -------------*- 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 | /// \file |
10 | /// This file defines the classes used to store parsed information about |
11 | /// declaration-specifiers and declarators. |
12 | /// |
13 | /// \verbatim |
14 | /// static const int volatile x, *y, *(*(*z)[10])(const void *x); |
15 | /// ------------------------- - -- --------------------------- |
16 | /// declaration-specifiers \ | / |
17 | /// declarators |
18 | /// \endverbatim |
19 | /// |
20 | //===----------------------------------------------------------------------===// |
21 | |
22 | #ifndef LLVM_CLANG_SEMA_DECLSPEC_H |
23 | #define LLVM_CLANG_SEMA_DECLSPEC_H |
24 | |
25 | #include "clang/AST/DeclCXX.h" |
26 | #include "clang/AST/DeclObjCCommon.h" |
27 | #include "clang/AST/NestedNameSpecifier.h" |
28 | #include "clang/Basic/ExceptionSpecificationType.h" |
29 | #include "clang/Basic/Lambda.h" |
30 | #include "clang/Basic/OperatorKinds.h" |
31 | #include "clang/Basic/Specifiers.h" |
32 | #include "clang/Lex/Token.h" |
33 | #include "clang/Sema/Ownership.h" |
34 | #include "clang/Sema/ParsedAttr.h" |
35 | #include "llvm/ADT/STLExtras.h" |
36 | #include "llvm/ADT/SmallVector.h" |
37 | #include "llvm/Support/Compiler.h" |
38 | #include "llvm/Support/ErrorHandling.h" |
39 | |
40 | namespace clang { |
41 | class ASTContext; |
42 | class CXXRecordDecl; |
43 | class TypeLoc; |
44 | class LangOptions; |
45 | class IdentifierInfo; |
46 | class NamespaceAliasDecl; |
47 | class NamespaceDecl; |
48 | class ObjCDeclSpec; |
49 | class Sema; |
50 | class Declarator; |
51 | struct TemplateIdAnnotation; |
52 | |
53 | /// Represents a C++ nested-name-specifier or a global scope specifier. |
54 | /// |
55 | /// These can be in 3 states: |
56 | /// 1) Not present, identified by isEmpty() |
57 | /// 2) Present, identified by isNotEmpty() |
58 | /// 2.a) Valid, identified by isValid() |
59 | /// 2.b) Invalid, identified by isInvalid(). |
60 | /// |
61 | /// isSet() is deprecated because it mostly corresponded to "valid" but was |
62 | /// often used as if it meant "present". |
63 | /// |
64 | /// The actual scope is described by getScopeRep(). |
65 | /// |
66 | /// If the kind of getScopeRep() is TypeSpec then TemplateParamLists may be empty |
67 | /// or contain the template parameter lists attached to the current declaration. |
68 | /// Consider the following example: |
69 | /// template <class T> void SomeType<T>::some_method() {} |
70 | /// If CXXScopeSpec refers to SomeType<T> then TemplateParamLists will contain |
71 | /// a single element referring to template <class T>. |
72 | |
73 | class CXXScopeSpec { |
74 | SourceRange Range; |
75 | NestedNameSpecifierLocBuilder Builder; |
76 | ArrayRef<TemplateParameterList *> TemplateParamLists; |
77 | |
78 | public: |
79 | SourceRange getRange() const { return Range; } |
80 | void setRange(SourceRange R) { Range = R; } |
81 | void setBeginLoc(SourceLocation Loc) { Range.setBegin(Loc); } |
82 | void setEndLoc(SourceLocation Loc) { Range.setEnd(Loc); } |
83 | SourceLocation getBeginLoc() const { return Range.getBegin(); } |
84 | SourceLocation getEndLoc() const { return Range.getEnd(); } |
85 | |
86 | void setTemplateParamLists(ArrayRef<TemplateParameterList *> L) { |
87 | TemplateParamLists = L; |
88 | } |
89 | ArrayRef<TemplateParameterList *> getTemplateParamLists() const { |
90 | return TemplateParamLists; |
91 | } |
92 | |
93 | /// Retrieve the representation of the nested-name-specifier. |
94 | NestedNameSpecifier *getScopeRep() const { |
95 | return Builder.getRepresentation(); |
96 | } |
97 | |
98 | /// Extend the current nested-name-specifier by another |
99 | /// nested-name-specifier component of the form 'type::'. |
100 | /// |
101 | /// \param Context The AST context in which this nested-name-specifier |
102 | /// resides. |
103 | /// |
104 | /// \param TemplateKWLoc The location of the 'template' keyword, if present. |
105 | /// |
106 | /// \param TL The TypeLoc that describes the type preceding the '::'. |
107 | /// |
108 | /// \param ColonColonLoc The location of the trailing '::'. |
109 | void Extend(ASTContext &Context, SourceLocation TemplateKWLoc, TypeLoc TL, |
110 | SourceLocation ColonColonLoc); |
111 | |
112 | /// Extend the current nested-name-specifier by another |
113 | /// nested-name-specifier component of the form 'identifier::'. |
114 | /// |
115 | /// \param Context The AST context in which this nested-name-specifier |
116 | /// resides. |
117 | /// |
118 | /// \param Identifier The identifier. |
119 | /// |
120 | /// \param IdentifierLoc The location of the identifier. |
121 | /// |
122 | /// \param ColonColonLoc The location of the trailing '::'. |
123 | void Extend(ASTContext &Context, IdentifierInfo *Identifier, |
124 | SourceLocation IdentifierLoc, SourceLocation ColonColonLoc); |
125 | |
126 | /// Extend the current nested-name-specifier by another |
127 | /// nested-name-specifier component of the form 'namespace::'. |
128 | /// |
129 | /// \param Context The AST context in which this nested-name-specifier |
130 | /// resides. |
131 | /// |
132 | /// \param Namespace The namespace. |
133 | /// |
134 | /// \param NamespaceLoc The location of the namespace name. |
135 | /// |
136 | /// \param ColonColonLoc The location of the trailing '::'. |
137 | void Extend(ASTContext &Context, NamespaceDecl *Namespace, |
138 | SourceLocation NamespaceLoc, SourceLocation ColonColonLoc); |
139 | |
140 | /// Extend the current nested-name-specifier by another |
141 | /// nested-name-specifier component of the form 'namespace-alias::'. |
142 | /// |
143 | /// \param Context The AST context in which this nested-name-specifier |
144 | /// resides. |
145 | /// |
146 | /// \param Alias The namespace alias. |
147 | /// |
148 | /// \param AliasLoc The location of the namespace alias |
149 | /// name. |
150 | /// |
151 | /// \param ColonColonLoc The location of the trailing '::'. |
152 | void Extend(ASTContext &Context, NamespaceAliasDecl *Alias, |
153 | SourceLocation AliasLoc, SourceLocation ColonColonLoc); |
154 | |
155 | /// Turn this (empty) nested-name-specifier into the global |
156 | /// nested-name-specifier '::'. |
157 | void MakeGlobal(ASTContext &Context, SourceLocation ColonColonLoc); |
158 | |
159 | /// Turns this (empty) nested-name-specifier into '__super' |
160 | /// nested-name-specifier. |
161 | /// |
162 | /// \param Context The AST context in which this nested-name-specifier |
163 | /// resides. |
164 | /// |
165 | /// \param RD The declaration of the class in which nested-name-specifier |
166 | /// appeared. |
167 | /// |
168 | /// \param SuperLoc The location of the '__super' keyword. |
169 | /// name. |
170 | /// |
171 | /// \param ColonColonLoc The location of the trailing '::'. |
172 | void MakeSuper(ASTContext &Context, CXXRecordDecl *RD, |
173 | SourceLocation SuperLoc, SourceLocation ColonColonLoc); |
174 | |
175 | /// Make a new nested-name-specifier from incomplete source-location |
176 | /// information. |
177 | /// |
178 | /// FIXME: This routine should be used very, very rarely, in cases where we |
179 | /// need to synthesize a nested-name-specifier. Most code should instead use |
180 | /// \c Adopt() with a proper \c NestedNameSpecifierLoc. |
181 | void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, |
182 | SourceRange R); |
183 | |
184 | /// Adopt an existing nested-name-specifier (with source-range |
185 | /// information). |
186 | void Adopt(NestedNameSpecifierLoc Other); |
187 | |
188 | /// Retrieve a nested-name-specifier with location information, copied |
189 | /// into the given AST context. |
190 | /// |
191 | /// \param Context The context into which this nested-name-specifier will be |
192 | /// copied. |
193 | NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const; |
194 | |
195 | /// Retrieve the location of the name in the last qualifier |
196 | /// in this nested name specifier. |
197 | /// |
198 | /// For example, the location of \c bar |
199 | /// in |
200 | /// \verbatim |
201 | /// \::foo::bar<0>:: |
202 | /// ^~~ |
203 | /// \endverbatim |
204 | SourceLocation getLastQualifierNameLoc() const; |
205 | |
206 | /// No scope specifier. |
207 | bool isEmpty() const { return Range.isInvalid() && getScopeRep() == nullptr; } |
208 | /// A scope specifier is present, but may be valid or invalid. |
209 | bool isNotEmpty() const { return !isEmpty(); } |
210 | |
211 | /// An error occurred during parsing of the scope specifier. |
212 | bool isInvalid() const { return Range.isValid() && getScopeRep() == nullptr; } |
213 | /// A scope specifier is present, and it refers to a real scope. |
214 | bool isValid() const { return getScopeRep() != nullptr; } |
215 | |
216 | /// Indicate that this nested-name-specifier is invalid. |
217 | void SetInvalid(SourceRange R) { |
218 | assert(R.isValid() && "Must have a valid source range")(static_cast <bool> (R.isValid() && "Must have a valid source range" ) ? void (0) : __assert_fail ("R.isValid() && \"Must have a valid source range\"" , "clang/include/clang/Sema/DeclSpec.h", 218, __extension__ __PRETTY_FUNCTION__ )); |
219 | if (Range.getBegin().isInvalid()) |
220 | Range.setBegin(R.getBegin()); |
221 | Range.setEnd(R.getEnd()); |
222 | Builder.Clear(); |
223 | } |
224 | |
225 | /// Deprecated. Some call sites intend isNotEmpty() while others intend |
226 | /// isValid(). |
227 | bool isSet() const { return getScopeRep() != nullptr; } |
228 | |
229 | void clear() { |
230 | Range = SourceRange(); |
231 | Builder.Clear(); |
232 | } |
233 | |
234 | /// Retrieve the data associated with the source-location information. |
235 | char *location_data() const { return Builder.getBuffer().first; } |
236 | |
237 | /// Retrieve the size of the data associated with source-location |
238 | /// information. |
239 | unsigned location_size() const { return Builder.getBuffer().second; } |
240 | }; |
241 | |
242 | /// Captures information about "declaration specifiers". |
243 | /// |
244 | /// "Declaration specifiers" encompasses storage-class-specifiers, |
245 | /// type-specifiers, type-qualifiers, and function-specifiers. |
246 | class DeclSpec { |
247 | public: |
248 | /// storage-class-specifier |
249 | /// \note The order of these enumerators is important for diagnostics. |
250 | enum SCS { |
251 | SCS_unspecified = 0, |
252 | SCS_typedef, |
253 | SCS_extern, |
254 | SCS_static, |
255 | SCS_auto, |
256 | SCS_register, |
257 | SCS_private_extern, |
258 | SCS_mutable |
259 | }; |
260 | |
261 | // Import thread storage class specifier enumeration and constants. |
262 | // These can be combined with SCS_extern and SCS_static. |
263 | typedef ThreadStorageClassSpecifier TSCS; |
264 | static const TSCS TSCS_unspecified = clang::TSCS_unspecified; |
265 | static const TSCS TSCS___thread = clang::TSCS___thread; |
266 | static const TSCS TSCS_thread_local = clang::TSCS_thread_local; |
267 | static const TSCS TSCS__Thread_local = clang::TSCS__Thread_local; |
268 | |
269 | enum TSC { |
270 | TSC_unspecified, |
271 | TSC_imaginary, |
272 | TSC_complex |
273 | }; |
274 | |
275 | // Import type specifier type enumeration and constants. |
276 | typedef TypeSpecifierType TST; |
277 | static const TST TST_unspecified = clang::TST_unspecified; |
278 | static const TST TST_void = clang::TST_void; |
279 | static const TST TST_char = clang::TST_char; |
280 | static const TST TST_wchar = clang::TST_wchar; |
281 | static const TST TST_char8 = clang::TST_char8; |
282 | static const TST TST_char16 = clang::TST_char16; |
283 | static const TST TST_char32 = clang::TST_char32; |
284 | static const TST TST_int = clang::TST_int; |
285 | static const TST TST_int128 = clang::TST_int128; |
286 | static const TST TST_bitint = clang::TST_bitint; |
287 | static const TST TST_half = clang::TST_half; |
288 | static const TST TST_BFloat16 = clang::TST_BFloat16; |
289 | static const TST TST_float = clang::TST_float; |
290 | static const TST TST_double = clang::TST_double; |
291 | static const TST TST_float16 = clang::TST_Float16; |
292 | static const TST TST_accum = clang::TST_Accum; |
293 | static const TST TST_fract = clang::TST_Fract; |
294 | static const TST TST_float128 = clang::TST_float128; |
295 | static const TST TST_ibm128 = clang::TST_ibm128; |
296 | static const TST TST_bool = clang::TST_bool; |
297 | static const TST TST_decimal32 = clang::TST_decimal32; |
298 | static const TST TST_decimal64 = clang::TST_decimal64; |
299 | static const TST TST_decimal128 = clang::TST_decimal128; |
300 | static const TST TST_enum = clang::TST_enum; |
301 | static const TST TST_union = clang::TST_union; |
302 | static const TST TST_struct = clang::TST_struct; |
303 | static const TST TST_interface = clang::TST_interface; |
304 | static const TST TST_class = clang::TST_class; |
305 | static const TST TST_typename = clang::TST_typename; |
306 | static const TST TST_typeofType = clang::TST_typeofType; |
307 | static const TST TST_typeofExpr = clang::TST_typeofExpr; |
308 | static const TST TST_typeof_unqualType = clang::TST_typeof_unqualType; |
309 | static const TST TST_typeof_unqualExpr = clang::TST_typeof_unqualExpr; |
310 | static const TST TST_decltype = clang::TST_decltype; |
311 | static const TST TST_decltype_auto = clang::TST_decltype_auto; |
312 | #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) \ |
313 | static const TST TST_##Trait = clang::TST_##Trait; |
314 | #include "clang/Basic/TransformTypeTraits.def" |
315 | static const TST TST_auto = clang::TST_auto; |
316 | static const TST TST_auto_type = clang::TST_auto_type; |
317 | static const TST TST_unknown_anytype = clang::TST_unknown_anytype; |
318 | static const TST TST_atomic = clang::TST_atomic; |
319 | #define GENERIC_IMAGE_TYPE(ImgType, Id) \ |
320 | static const TST TST_##ImgType##_t = clang::TST_##ImgType##_t; |
321 | #include "clang/Basic/OpenCLImageTypes.def" |
322 | static const TST TST_error = clang::TST_error; |
323 | |
324 | // type-qualifiers |
325 | enum TQ { // NOTE: These flags must be kept in sync with Qualifiers::TQ. |
326 | TQ_unspecified = 0, |
327 | TQ_const = 1, |
328 | TQ_restrict = 2, |
329 | TQ_volatile = 4, |
330 | TQ_unaligned = 8, |
331 | // This has no corresponding Qualifiers::TQ value, because it's not treated |
332 | // as a qualifier in our type system. |
333 | TQ_atomic = 16 |
334 | }; |
335 | |
336 | /// ParsedSpecifiers - Flags to query which specifiers were applied. This is |
337 | /// returned by getParsedSpecifiers. |
338 | enum ParsedSpecifiers { |
339 | PQ_None = 0, |
340 | PQ_StorageClassSpecifier = 1, |
341 | PQ_TypeSpecifier = 2, |
342 | PQ_TypeQualifier = 4, |
343 | PQ_FunctionSpecifier = 8 |
344 | // FIXME: Attributes should be included here. |
345 | }; |
346 | |
347 | enum FriendSpecified : bool { |
348 | No, |
349 | Yes, |
350 | }; |
351 | |
352 | private: |
353 | // storage-class-specifier |
354 | /*SCS*/unsigned StorageClassSpec : 3; |
355 | /*TSCS*/unsigned ThreadStorageClassSpec : 2; |
356 | unsigned SCS_extern_in_linkage_spec : 1; |
357 | |
358 | // type-specifier |
359 | /*TypeSpecifierWidth*/ unsigned TypeSpecWidth : 2; |
360 | /*TSC*/unsigned TypeSpecComplex : 2; |
361 | /*TSS*/unsigned TypeSpecSign : 2; |
362 | /*TST*/unsigned TypeSpecType : 7; |
363 | unsigned TypeAltiVecVector : 1; |
364 | unsigned TypeAltiVecPixel : 1; |
365 | unsigned TypeAltiVecBool : 1; |
366 | unsigned TypeSpecOwned : 1; |
367 | unsigned TypeSpecPipe : 1; |
368 | unsigned TypeSpecSat : 1; |
369 | unsigned ConstrainedAuto : 1; |
370 | |
371 | // type-qualifiers |
372 | unsigned TypeQualifiers : 5; // Bitwise OR of TQ. |
373 | |
374 | // function-specifier |
375 | unsigned FS_inline_specified : 1; |
376 | unsigned FS_forceinline_specified: 1; |
377 | unsigned FS_virtual_specified : 1; |
378 | unsigned FS_noreturn_specified : 1; |
379 | |
380 | // friend-specifier |
381 | unsigned Friend_specified : 1; |
382 | |
383 | // constexpr-specifier |
384 | unsigned ConstexprSpecifier : 2; |
385 | |
386 | union { |
387 | UnionParsedType TypeRep; |
388 | Decl *DeclRep; |
389 | Expr *ExprRep; |
390 | TemplateIdAnnotation *TemplateIdRep; |
391 | }; |
392 | |
393 | /// ExplicitSpecifier - Store information about explicit spicifer. |
394 | ExplicitSpecifier FS_explicit_specifier; |
395 | |
396 | // attributes. |
397 | ParsedAttributes Attrs; |
398 | |
399 | // Scope specifier for the type spec, if applicable. |
400 | CXXScopeSpec TypeScope; |
401 | |
402 | // SourceLocation info. These are null if the item wasn't specified or if |
403 | // the setting was synthesized. |
404 | SourceRange Range; |
405 | |
406 | SourceLocation StorageClassSpecLoc, ThreadStorageClassSpecLoc; |
407 | SourceRange TSWRange; |
408 | SourceLocation TSCLoc, TSSLoc, TSTLoc, AltiVecLoc, TSSatLoc; |
409 | /// TSTNameLoc - If TypeSpecType is any of class, enum, struct, union, |
410 | /// typename, then this is the location of the named type (if present); |
411 | /// otherwise, it is the same as TSTLoc. Hence, the pair TSTLoc and |
412 | /// TSTNameLoc provides source range info for tag types. |
413 | SourceLocation TSTNameLoc; |
414 | SourceRange TypeofParensRange; |
415 | SourceLocation TQ_constLoc, TQ_restrictLoc, TQ_volatileLoc, TQ_atomicLoc, |
416 | TQ_unalignedLoc; |
417 | SourceLocation FS_inlineLoc, FS_virtualLoc, FS_explicitLoc, FS_noreturnLoc; |
418 | SourceLocation FS_explicitCloseParenLoc; |
419 | SourceLocation FS_forceinlineLoc; |
420 | SourceLocation FriendLoc, ModulePrivateLoc, ConstexprLoc; |
421 | SourceLocation TQ_pipeLoc; |
422 | |
423 | WrittenBuiltinSpecs writtenBS; |
424 | void SaveWrittenBuiltinSpecs(); |
425 | |
426 | ObjCDeclSpec *ObjCQualifiers; |
427 | |
428 | static bool isTypeRep(TST T) { |
429 | return T == TST_atomic || T == TST_typename || T == TST_typeofType || |
430 | T == TST_typeof_unqualType || isTransformTypeTrait(T); |
431 | } |
432 | static bool isExprRep(TST T) { |
433 | return T == TST_typeofExpr || T == TST_typeof_unqualExpr || |
434 | T == TST_decltype || T == TST_bitint; |
435 | } |
436 | static bool isTemplateIdRep(TST T) { |
437 | return (T == TST_auto || T == TST_decltype_auto); |
438 | } |
439 | |
440 | DeclSpec(const DeclSpec &) = delete; |
441 | void operator=(const DeclSpec &) = delete; |
442 | public: |
443 | static bool isDeclRep(TST T) { |
444 | return (T == TST_enum || T == TST_struct || |
445 | T == TST_interface || T == TST_union || |
446 | T == TST_class); |
447 | } |
448 | static bool isTransformTypeTrait(TST T) { |
449 | constexpr std::array<TST, 16> Traits = { |
450 | #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) TST_##Trait, |
451 | #include "clang/Basic/TransformTypeTraits.def" |
452 | }; |
453 | |
454 | return T >= Traits.front() && T <= Traits.back(); |
455 | } |
456 | |
457 | DeclSpec(AttributeFactory &attrFactory) |
458 | : StorageClassSpec(SCS_unspecified), |
459 | ThreadStorageClassSpec(TSCS_unspecified), |
460 | SCS_extern_in_linkage_spec(false), |
461 | TypeSpecWidth(static_cast<unsigned>(TypeSpecifierWidth::Unspecified)), |
462 | TypeSpecComplex(TSC_unspecified), |
463 | TypeSpecSign(static_cast<unsigned>(TypeSpecifierSign::Unspecified)), |
464 | TypeSpecType(TST_unspecified), TypeAltiVecVector(false), |
465 | TypeAltiVecPixel(false), TypeAltiVecBool(false), TypeSpecOwned(false), |
466 | TypeSpecPipe(false), TypeSpecSat(false), ConstrainedAuto(false), |
467 | TypeQualifiers(TQ_unspecified), FS_inline_specified(false), |
468 | FS_forceinline_specified(false), FS_virtual_specified(false), |
469 | FS_noreturn_specified(false), Friend_specified(false), |
470 | ConstexprSpecifier( |
471 | static_cast<unsigned>(ConstexprSpecKind::Unspecified)), |
472 | Attrs(attrFactory), writtenBS(), ObjCQualifiers(nullptr) {} |
473 | |
474 | // storage-class-specifier |
475 | SCS getStorageClassSpec() const { return (SCS)StorageClassSpec; } |
476 | TSCS getThreadStorageClassSpec() const { |
477 | return (TSCS)ThreadStorageClassSpec; |
478 | } |
479 | bool isExternInLinkageSpec() const { return SCS_extern_in_linkage_spec; } |
480 | void setExternInLinkageSpec(bool Value) { |
481 | SCS_extern_in_linkage_spec = Value; |
482 | } |
483 | |
484 | SourceLocation getStorageClassSpecLoc() const { return StorageClassSpecLoc; } |
485 | SourceLocation getThreadStorageClassSpecLoc() const { |
486 | return ThreadStorageClassSpecLoc; |
487 | } |
488 | |
489 | void ClearStorageClassSpecs() { |
490 | StorageClassSpec = DeclSpec::SCS_unspecified; |
491 | ThreadStorageClassSpec = DeclSpec::TSCS_unspecified; |
492 | SCS_extern_in_linkage_spec = false; |
493 | StorageClassSpecLoc = SourceLocation(); |
494 | ThreadStorageClassSpecLoc = SourceLocation(); |
495 | } |
496 | |
497 | void ClearTypeSpecType() { |
498 | TypeSpecType = DeclSpec::TST_unspecified; |
499 | TypeSpecOwned = false; |
500 | TSTLoc = SourceLocation(); |
501 | } |
502 | |
503 | // type-specifier |
504 | TypeSpecifierWidth getTypeSpecWidth() const { |
505 | return static_cast<TypeSpecifierWidth>(TypeSpecWidth); |
506 | } |
507 | TSC getTypeSpecComplex() const { return (TSC)TypeSpecComplex; } |
508 | TypeSpecifierSign getTypeSpecSign() const { |
509 | return static_cast<TypeSpecifierSign>(TypeSpecSign); |
510 | } |
511 | TST getTypeSpecType() const { return (TST)TypeSpecType; } |
512 | bool isTypeAltiVecVector() const { return TypeAltiVecVector; } |
513 | bool isTypeAltiVecPixel() const { return TypeAltiVecPixel; } |
514 | bool isTypeAltiVecBool() const { return TypeAltiVecBool; } |
515 | bool isTypeSpecOwned() const { return TypeSpecOwned; } |
516 | bool isTypeRep() const { return isTypeRep((TST) TypeSpecType); } |
517 | bool isTypeSpecPipe() const { return TypeSpecPipe; } |
518 | bool isTypeSpecSat() const { return TypeSpecSat; } |
519 | bool isConstrainedAuto() const { return ConstrainedAuto; } |
520 | |
521 | ParsedType getRepAsType() const { |
522 | assert(isTypeRep((TST) TypeSpecType) && "DeclSpec does not store a type")(static_cast <bool> (isTypeRep((TST) TypeSpecType) && "DeclSpec does not store a type") ? void (0) : __assert_fail ("isTypeRep((TST) TypeSpecType) && \"DeclSpec does not store a type\"" , "clang/include/clang/Sema/DeclSpec.h", 522, __extension__ __PRETTY_FUNCTION__ )); |
523 | return TypeRep; |
524 | } |
525 | Decl *getRepAsDecl() const { |
526 | assert(isDeclRep((TST) TypeSpecType) && "DeclSpec does not store a decl")(static_cast <bool> (isDeclRep((TST) TypeSpecType) && "DeclSpec does not store a decl") ? void (0) : __assert_fail ("isDeclRep((TST) TypeSpecType) && \"DeclSpec does not store a decl\"" , "clang/include/clang/Sema/DeclSpec.h", 526, __extension__ __PRETTY_FUNCTION__ )); |
527 | return DeclRep; |
528 | } |
529 | Expr *getRepAsExpr() const { |
530 | assert(isExprRep((TST) TypeSpecType) && "DeclSpec does not store an expr")(static_cast <bool> (isExprRep((TST) TypeSpecType) && "DeclSpec does not store an expr") ? void (0) : __assert_fail ("isExprRep((TST) TypeSpecType) && \"DeclSpec does not store an expr\"" , "clang/include/clang/Sema/DeclSpec.h", 530, __extension__ __PRETTY_FUNCTION__ )); |
531 | return ExprRep; |
532 | } |
533 | TemplateIdAnnotation *getRepAsTemplateId() const { |
534 | assert(isTemplateIdRep((TST) TypeSpecType) &&(static_cast <bool> (isTemplateIdRep((TST) TypeSpecType ) && "DeclSpec does not store a template id") ? void ( 0) : __assert_fail ("isTemplateIdRep((TST) TypeSpecType) && \"DeclSpec does not store a template id\"" , "clang/include/clang/Sema/DeclSpec.h", 535, __extension__ __PRETTY_FUNCTION__ )) |
535 | "DeclSpec does not store a template id")(static_cast <bool> (isTemplateIdRep((TST) TypeSpecType ) && "DeclSpec does not store a template id") ? void ( 0) : __assert_fail ("isTemplateIdRep((TST) TypeSpecType) && \"DeclSpec does not store a template id\"" , "clang/include/clang/Sema/DeclSpec.h", 535, __extension__ __PRETTY_FUNCTION__ )); |
536 | return TemplateIdRep; |
537 | } |
538 | CXXScopeSpec &getTypeSpecScope() { return TypeScope; } |
539 | const CXXScopeSpec &getTypeSpecScope() const { return TypeScope; } |
540 | |
541 | SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) { return Range; } |
542 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getBegin(); } |
543 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getEnd(); } |
544 | |
545 | SourceLocation getTypeSpecWidthLoc() const { return TSWRange.getBegin(); } |
546 | SourceRange getTypeSpecWidthRange() const { return TSWRange; } |
547 | SourceLocation getTypeSpecComplexLoc() const { return TSCLoc; } |
548 | SourceLocation getTypeSpecSignLoc() const { return TSSLoc; } |
549 | SourceLocation getTypeSpecTypeLoc() const { return TSTLoc; } |
550 | SourceLocation getAltiVecLoc() const { return AltiVecLoc; } |
551 | SourceLocation getTypeSpecSatLoc() const { return TSSatLoc; } |
552 | |
553 | SourceLocation getTypeSpecTypeNameLoc() const { |
554 | assert(isDeclRep((TST)TypeSpecType) || isTypeRep((TST)TypeSpecType) ||(static_cast <bool> (isDeclRep((TST)TypeSpecType) || isTypeRep ((TST)TypeSpecType) || isExprRep((TST)TypeSpecType)) ? void ( 0) : __assert_fail ("isDeclRep((TST)TypeSpecType) || isTypeRep((TST)TypeSpecType) || isExprRep((TST)TypeSpecType)" , "clang/include/clang/Sema/DeclSpec.h", 555, __extension__ __PRETTY_FUNCTION__ )) |
555 | isExprRep((TST)TypeSpecType))(static_cast <bool> (isDeclRep((TST)TypeSpecType) || isTypeRep ((TST)TypeSpecType) || isExprRep((TST)TypeSpecType)) ? void ( 0) : __assert_fail ("isDeclRep((TST)TypeSpecType) || isTypeRep((TST)TypeSpecType) || isExprRep((TST)TypeSpecType)" , "clang/include/clang/Sema/DeclSpec.h", 555, __extension__ __PRETTY_FUNCTION__ )); |
556 | return TSTNameLoc; |
557 | } |
558 | |
559 | SourceRange getTypeofParensRange() const { return TypeofParensRange; } |
560 | void setTypeArgumentRange(SourceRange range) { TypeofParensRange = range; } |
561 | |
562 | bool hasAutoTypeSpec() const { |
563 | return (TypeSpecType == TST_auto || TypeSpecType == TST_auto_type || |
564 | TypeSpecType == TST_decltype_auto); |
565 | } |
566 | |
567 | bool hasTagDefinition() const; |
568 | |
569 | /// Turn a type-specifier-type into a string like "_Bool" or "union". |
570 | static const char *getSpecifierName(DeclSpec::TST T, |
571 | const PrintingPolicy &Policy); |
572 | static const char *getSpecifierName(DeclSpec::TQ Q); |
573 | static const char *getSpecifierName(TypeSpecifierSign S); |
574 | static const char *getSpecifierName(DeclSpec::TSC C); |
575 | static const char *getSpecifierName(TypeSpecifierWidth W); |
576 | static const char *getSpecifierName(DeclSpec::SCS S); |
577 | static const char *getSpecifierName(DeclSpec::TSCS S); |
578 | static const char *getSpecifierName(ConstexprSpecKind C); |
579 | |
580 | // type-qualifiers |
581 | |
582 | /// getTypeQualifiers - Return a set of TQs. |
583 | unsigned getTypeQualifiers() const { return TypeQualifiers; } |
584 | SourceLocation getConstSpecLoc() const { return TQ_constLoc; } |
585 | SourceLocation getRestrictSpecLoc() const { return TQ_restrictLoc; } |
586 | SourceLocation getVolatileSpecLoc() const { return TQ_volatileLoc; } |
587 | SourceLocation getAtomicSpecLoc() const { return TQ_atomicLoc; } |
588 | SourceLocation getUnalignedSpecLoc() const { return TQ_unalignedLoc; } |
589 | SourceLocation getPipeLoc() const { return TQ_pipeLoc; } |
590 | |
591 | /// Clear out all of the type qualifiers. |
592 | void ClearTypeQualifiers() { |
593 | TypeQualifiers = 0; |
594 | TQ_constLoc = SourceLocation(); |
595 | TQ_restrictLoc = SourceLocation(); |
596 | TQ_volatileLoc = SourceLocation(); |
597 | TQ_atomicLoc = SourceLocation(); |
598 | TQ_unalignedLoc = SourceLocation(); |
599 | TQ_pipeLoc = SourceLocation(); |
600 | } |
601 | |
602 | // function-specifier |
603 | bool isInlineSpecified() const { |
604 | return FS_inline_specified | FS_forceinline_specified; |
605 | } |
606 | SourceLocation getInlineSpecLoc() const { |
607 | return FS_inline_specified ? FS_inlineLoc : FS_forceinlineLoc; |
608 | } |
609 | |
610 | ExplicitSpecifier getExplicitSpecifier() const { |
611 | return FS_explicit_specifier; |
612 | } |
613 | |
614 | bool isVirtualSpecified() const { return FS_virtual_specified; } |
615 | SourceLocation getVirtualSpecLoc() const { return FS_virtualLoc; } |
616 | |
617 | bool hasExplicitSpecifier() const { |
618 | return FS_explicit_specifier.isSpecified(); |
619 | } |
620 | SourceLocation getExplicitSpecLoc() const { return FS_explicitLoc; } |
621 | SourceRange getExplicitSpecRange() const { |
622 | return FS_explicit_specifier.getExpr() |
623 | ? SourceRange(FS_explicitLoc, FS_explicitCloseParenLoc) |
624 | : SourceRange(FS_explicitLoc); |
625 | } |
626 | |
627 | bool isNoreturnSpecified() const { return FS_noreturn_specified; } |
628 | SourceLocation getNoreturnSpecLoc() const { return FS_noreturnLoc; } |
629 | |
630 | void ClearFunctionSpecs() { |
631 | FS_inline_specified = false; |
632 | FS_inlineLoc = SourceLocation(); |
633 | FS_forceinline_specified = false; |
634 | FS_forceinlineLoc = SourceLocation(); |
635 | FS_virtual_specified = false; |
636 | FS_virtualLoc = SourceLocation(); |
637 | FS_explicit_specifier = ExplicitSpecifier(); |
638 | FS_explicitLoc = SourceLocation(); |
639 | FS_explicitCloseParenLoc = SourceLocation(); |
640 | FS_noreturn_specified = false; |
641 | FS_noreturnLoc = SourceLocation(); |
642 | } |
643 | |
644 | /// This method calls the passed in handler on each CVRU qual being |
645 | /// set. |
646 | /// Handle - a handler to be invoked. |
647 | void forEachCVRUQualifier( |
648 | llvm::function_ref<void(TQ, StringRef, SourceLocation)> Handle); |
649 | |
650 | /// This method calls the passed in handler on each qual being |
651 | /// set. |
652 | /// Handle - a handler to be invoked. |
653 | void forEachQualifier( |
654 | llvm::function_ref<void(TQ, StringRef, SourceLocation)> Handle); |
655 | |
656 | /// Return true if any type-specifier has been found. |
657 | bool hasTypeSpecifier() const { |
658 | return getTypeSpecType() != DeclSpec::TST_unspecified || |
659 | getTypeSpecWidth() != TypeSpecifierWidth::Unspecified || |
660 | getTypeSpecComplex() != DeclSpec::TSC_unspecified || |
661 | getTypeSpecSign() != TypeSpecifierSign::Unspecified; |
662 | } |
663 | |
664 | /// Return a bitmask of which flavors of specifiers this |
665 | /// DeclSpec includes. |
666 | unsigned getParsedSpecifiers() const; |
667 | |
668 | /// isEmpty - Return true if this declaration specifier is completely empty: |
669 | /// no tokens were parsed in the production of it. |
670 | bool isEmpty() const { |
671 | return getParsedSpecifiers() == DeclSpec::PQ_None; |
672 | } |
673 | |
674 | void SetRangeStart(SourceLocation Loc) { Range.setBegin(Loc); } |
675 | void SetRangeEnd(SourceLocation Loc) { Range.setEnd(Loc); } |
676 | |
677 | /// These methods set the specified attribute of the DeclSpec and |
678 | /// return false if there was no error. If an error occurs (for |
679 | /// example, if we tried to set "auto" on a spec with "extern" |
680 | /// already set), they return true and set PrevSpec and DiagID |
681 | /// such that |
682 | /// Diag(Loc, DiagID) << PrevSpec; |
683 | /// will yield a useful result. |
684 | /// |
685 | /// TODO: use a more general approach that still allows these |
686 | /// diagnostics to be ignored when desired. |
687 | bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc, |
688 | const char *&PrevSpec, unsigned &DiagID, |
689 | const PrintingPolicy &Policy); |
690 | bool SetStorageClassSpecThread(TSCS TSC, SourceLocation Loc, |
691 | const char *&PrevSpec, unsigned &DiagID); |
692 | bool SetTypeSpecWidth(TypeSpecifierWidth W, SourceLocation Loc, |
693 | const char *&PrevSpec, unsigned &DiagID, |
694 | const PrintingPolicy &Policy); |
695 | bool SetTypeSpecComplex(TSC C, SourceLocation Loc, const char *&PrevSpec, |
696 | unsigned &DiagID); |
697 | bool SetTypeSpecSign(TypeSpecifierSign S, SourceLocation Loc, |
698 | const char *&PrevSpec, unsigned &DiagID); |
699 | bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, |
700 | unsigned &DiagID, const PrintingPolicy &Policy); |
701 | bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, |
702 | unsigned &DiagID, ParsedType Rep, |
703 | const PrintingPolicy &Policy); |
704 | bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, |
705 | unsigned &DiagID, TypeResult Rep, |
706 | const PrintingPolicy &Policy) { |
707 | if (Rep.isInvalid()) |
708 | return SetTypeSpecError(); |
709 | return SetTypeSpecType(T, Loc, PrevSpec, DiagID, Rep.get(), Policy); |
710 | } |
711 | bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, |
712 | unsigned &DiagID, Decl *Rep, bool Owned, |
713 | const PrintingPolicy &Policy); |
714 | bool SetTypeSpecType(TST T, SourceLocation TagKwLoc, |
715 | SourceLocation TagNameLoc, const char *&PrevSpec, |
716 | unsigned &DiagID, ParsedType Rep, |
717 | const PrintingPolicy &Policy); |
718 | bool SetTypeSpecType(TST T, SourceLocation TagKwLoc, |
719 | SourceLocation TagNameLoc, const char *&PrevSpec, |
720 | unsigned &DiagID, Decl *Rep, bool Owned, |
721 | const PrintingPolicy &Policy); |
722 | bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, |
723 | unsigned &DiagID, TemplateIdAnnotation *Rep, |
724 | const PrintingPolicy &Policy); |
725 | |
726 | bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, |
727 | unsigned &DiagID, Expr *Rep, |
728 | const PrintingPolicy &policy); |
729 | bool SetTypeAltiVecVector(bool isAltiVecVector, SourceLocation Loc, |
730 | const char *&PrevSpec, unsigned &DiagID, |
731 | const PrintingPolicy &Policy); |
732 | bool SetTypeAltiVecPixel(bool isAltiVecPixel, SourceLocation Loc, |
733 | const char *&PrevSpec, unsigned &DiagID, |
734 | const PrintingPolicy &Policy); |
735 | bool SetTypeAltiVecBool(bool isAltiVecBool, SourceLocation Loc, |
736 | const char *&PrevSpec, unsigned &DiagID, |
737 | const PrintingPolicy &Policy); |
738 | bool SetTypePipe(bool isPipe, SourceLocation Loc, |
739 | const char *&PrevSpec, unsigned &DiagID, |
740 | const PrintingPolicy &Policy); |
741 | bool SetBitIntType(SourceLocation KWLoc, Expr *BitWidth, |
742 | const char *&PrevSpec, unsigned &DiagID, |
743 | const PrintingPolicy &Policy); |
744 | bool SetTypeSpecSat(SourceLocation Loc, const char *&PrevSpec, |
745 | unsigned &DiagID); |
746 | bool SetTypeSpecError(); |
747 | void UpdateDeclRep(Decl *Rep) { |
748 | assert(isDeclRep((TST) TypeSpecType))(static_cast <bool> (isDeclRep((TST) TypeSpecType)) ? void (0) : __assert_fail ("isDeclRep((TST) TypeSpecType)", "clang/include/clang/Sema/DeclSpec.h" , 748, __extension__ __PRETTY_FUNCTION__)); |
749 | DeclRep = Rep; |
750 | } |
751 | void UpdateTypeRep(ParsedType Rep) { |
752 | assert(isTypeRep((TST) TypeSpecType))(static_cast <bool> (isTypeRep((TST) TypeSpecType)) ? void (0) : __assert_fail ("isTypeRep((TST) TypeSpecType)", "clang/include/clang/Sema/DeclSpec.h" , 752, __extension__ __PRETTY_FUNCTION__)); |
753 | TypeRep = Rep; |
754 | } |
755 | void UpdateExprRep(Expr *Rep) { |
756 | assert(isExprRep((TST) TypeSpecType))(static_cast <bool> (isExprRep((TST) TypeSpecType)) ? void (0) : __assert_fail ("isExprRep((TST) TypeSpecType)", "clang/include/clang/Sema/DeclSpec.h" , 756, __extension__ __PRETTY_FUNCTION__)); |
757 | ExprRep = Rep; |
758 | } |
759 | |
760 | bool SetTypeQual(TQ T, SourceLocation Loc); |
761 | |
762 | bool SetTypeQual(TQ T, SourceLocation Loc, const char *&PrevSpec, |
763 | unsigned &DiagID, const LangOptions &Lang); |
764 | |
765 | bool setFunctionSpecInline(SourceLocation Loc, const char *&PrevSpec, |
766 | unsigned &DiagID); |
767 | bool setFunctionSpecForceInline(SourceLocation Loc, const char *&PrevSpec, |
768 | unsigned &DiagID); |
769 | bool setFunctionSpecVirtual(SourceLocation Loc, const char *&PrevSpec, |
770 | unsigned &DiagID); |
771 | bool setFunctionSpecExplicit(SourceLocation Loc, const char *&PrevSpec, |
772 | unsigned &DiagID, ExplicitSpecifier ExplicitSpec, |
773 | SourceLocation CloseParenLoc); |
774 | bool setFunctionSpecNoreturn(SourceLocation Loc, const char *&PrevSpec, |
775 | unsigned &DiagID); |
776 | |
777 | bool SetFriendSpec(SourceLocation Loc, const char *&PrevSpec, |
778 | unsigned &DiagID); |
779 | bool setModulePrivateSpec(SourceLocation Loc, const char *&PrevSpec, |
780 | unsigned &DiagID); |
781 | bool SetConstexprSpec(ConstexprSpecKind ConstexprKind, SourceLocation Loc, |
782 | const char *&PrevSpec, unsigned &DiagID); |
783 | |
784 | FriendSpecified isFriendSpecified() const { |
785 | return static_cast<FriendSpecified>(Friend_specified); |
786 | } |
787 | |
788 | SourceLocation getFriendSpecLoc() const { return FriendLoc; } |
789 | |
790 | bool isModulePrivateSpecified() const { return ModulePrivateLoc.isValid(); } |
791 | SourceLocation getModulePrivateSpecLoc() const { return ModulePrivateLoc; } |
792 | |
793 | ConstexprSpecKind getConstexprSpecifier() const { |
794 | return ConstexprSpecKind(ConstexprSpecifier); |
795 | } |
796 | |
797 | SourceLocation getConstexprSpecLoc() const { return ConstexprLoc; } |
798 | bool hasConstexprSpecifier() const { |
799 | return getConstexprSpecifier() != ConstexprSpecKind::Unspecified; |
800 | } |
801 | |
802 | void ClearConstexprSpec() { |
803 | ConstexprSpecifier = static_cast<unsigned>(ConstexprSpecKind::Unspecified); |
804 | ConstexprLoc = SourceLocation(); |
805 | } |
806 | |
807 | AttributePool &getAttributePool() const { |
808 | return Attrs.getPool(); |
809 | } |
810 | |
811 | /// Concatenates two attribute lists. |
812 | /// |
813 | /// The GCC attribute syntax allows for the following: |
814 | /// |
815 | /// \code |
816 | /// short __attribute__(( unused, deprecated )) |
817 | /// int __attribute__(( may_alias, aligned(16) )) var; |
818 | /// \endcode |
819 | /// |
820 | /// This declares 4 attributes using 2 lists. The following syntax is |
821 | /// also allowed and equivalent to the previous declaration. |
822 | /// |
823 | /// \code |
824 | /// short __attribute__((unused)) __attribute__((deprecated)) |
825 | /// int __attribute__((may_alias)) __attribute__((aligned(16))) var; |
826 | /// \endcode |
827 | /// |
828 | void addAttributes(const ParsedAttributesView &AL) { |
829 | Attrs.addAll(AL.begin(), AL.end()); |
830 | } |
831 | |
832 | bool hasAttributes() const { return !Attrs.empty(); } |
833 | |
834 | ParsedAttributes &getAttributes() { return Attrs; } |
835 | const ParsedAttributes &getAttributes() const { return Attrs; } |
836 | |
837 | void takeAttributesFrom(ParsedAttributes &attrs) { |
838 | Attrs.takeAllFrom(attrs); |
839 | } |
840 | |
841 | /// Finish - This does final analysis of the declspec, issuing diagnostics for |
842 | /// things like "_Imaginary" (lacking an FP type). After calling this method, |
843 | /// DeclSpec is guaranteed self-consistent, even if an error occurred. |
844 | void Finish(Sema &S, const PrintingPolicy &Policy); |
845 | |
846 | const WrittenBuiltinSpecs& getWrittenBuiltinSpecs() const { |
847 | return writtenBS; |
848 | } |
849 | |
850 | ObjCDeclSpec *getObjCQualifiers() const { return ObjCQualifiers; } |
851 | void setObjCQualifiers(ObjCDeclSpec *quals) { ObjCQualifiers = quals; } |
852 | |
853 | /// Checks if this DeclSpec can stand alone, without a Declarator. |
854 | /// |
855 | /// Only tag declspecs can stand alone. |
856 | bool isMissingDeclaratorOk(); |
857 | }; |
858 | |
859 | /// Captures information about "declaration specifiers" specific to |
860 | /// Objective-C. |
861 | class ObjCDeclSpec { |
862 | public: |
863 | /// ObjCDeclQualifier - Qualifier used on types in method |
864 | /// declarations. Not all combinations are sensible. Parameters |
865 | /// can be one of { in, out, inout } with one of { bycopy, byref }. |
866 | /// Returns can either be { oneway } or not. |
867 | /// |
868 | /// This should be kept in sync with Decl::ObjCDeclQualifier. |
869 | enum ObjCDeclQualifier { |
870 | DQ_None = 0x0, |
871 | DQ_In = 0x1, |
872 | DQ_Inout = 0x2, |
873 | DQ_Out = 0x4, |
874 | DQ_Bycopy = 0x8, |
875 | DQ_Byref = 0x10, |
876 | DQ_Oneway = 0x20, |
877 | DQ_CSNullability = 0x40 |
878 | }; |
879 | |
880 | ObjCDeclSpec() |
881 | : objcDeclQualifier(DQ_None), |
882 | PropertyAttributes(ObjCPropertyAttribute::kind_noattr), Nullability(0), |
883 | GetterName(nullptr), SetterName(nullptr) {} |
884 | |
885 | ObjCDeclQualifier getObjCDeclQualifier() const { |
886 | return (ObjCDeclQualifier)objcDeclQualifier; |
887 | } |
888 | void setObjCDeclQualifier(ObjCDeclQualifier DQVal) { |
889 | objcDeclQualifier = (ObjCDeclQualifier) (objcDeclQualifier | DQVal); |
890 | } |
891 | void clearObjCDeclQualifier(ObjCDeclQualifier DQVal) { |
892 | objcDeclQualifier = (ObjCDeclQualifier) (objcDeclQualifier & ~DQVal); |
893 | } |
894 | |
895 | ObjCPropertyAttribute::Kind getPropertyAttributes() const { |
896 | return ObjCPropertyAttribute::Kind(PropertyAttributes); |
897 | } |
898 | void setPropertyAttributes(ObjCPropertyAttribute::Kind PRVal) { |
899 | PropertyAttributes = |
900 | (ObjCPropertyAttribute::Kind)(PropertyAttributes | PRVal); |
901 | } |
902 | |
903 | NullabilityKind getNullability() const { |
904 | assert((static_cast <bool> (((getObjCDeclQualifier() & DQ_CSNullability ) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability )) && "Objective-C declspec doesn't have nullability" ) ? void (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Objective-C declspec doesn't have nullability\"" , "clang/include/clang/Sema/DeclSpec.h", 907, __extension__ __PRETTY_FUNCTION__ )) |
905 | ((getObjCDeclQualifier() & DQ_CSNullability) ||(static_cast <bool> (((getObjCDeclQualifier() & DQ_CSNullability ) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability )) && "Objective-C declspec doesn't have nullability" ) ? void (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Objective-C declspec doesn't have nullability\"" , "clang/include/clang/Sema/DeclSpec.h", 907, __extension__ __PRETTY_FUNCTION__ )) |
906 | (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) &&(static_cast <bool> (((getObjCDeclQualifier() & DQ_CSNullability ) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability )) && "Objective-C declspec doesn't have nullability" ) ? void (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Objective-C declspec doesn't have nullability\"" , "clang/include/clang/Sema/DeclSpec.h", 907, __extension__ __PRETTY_FUNCTION__ )) |
907 | "Objective-C declspec doesn't have nullability")(static_cast <bool> (((getObjCDeclQualifier() & DQ_CSNullability ) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability )) && "Objective-C declspec doesn't have nullability" ) ? void (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Objective-C declspec doesn't have nullability\"" , "clang/include/clang/Sema/DeclSpec.h", 907, __extension__ __PRETTY_FUNCTION__ )); |
908 | return static_cast<NullabilityKind>(Nullability); |
909 | } |
910 | |
911 | SourceLocation getNullabilityLoc() const { |
912 | assert((static_cast <bool> (((getObjCDeclQualifier() & DQ_CSNullability ) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability )) && "Objective-C declspec doesn't have nullability" ) ? void (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Objective-C declspec doesn't have nullability\"" , "clang/include/clang/Sema/DeclSpec.h", 915, __extension__ __PRETTY_FUNCTION__ )) |
913 | ((getObjCDeclQualifier() & DQ_CSNullability) ||(static_cast <bool> (((getObjCDeclQualifier() & DQ_CSNullability ) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability )) && "Objective-C declspec doesn't have nullability" ) ? void (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Objective-C declspec doesn't have nullability\"" , "clang/include/clang/Sema/DeclSpec.h", 915, __extension__ __PRETTY_FUNCTION__ )) |
914 | (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) &&(static_cast <bool> (((getObjCDeclQualifier() & DQ_CSNullability ) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability )) && "Objective-C declspec doesn't have nullability" ) ? void (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Objective-C declspec doesn't have nullability\"" , "clang/include/clang/Sema/DeclSpec.h", 915, __extension__ __PRETTY_FUNCTION__ )) |
915 | "Objective-C declspec doesn't have nullability")(static_cast <bool> (((getObjCDeclQualifier() & DQ_CSNullability ) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability )) && "Objective-C declspec doesn't have nullability" ) ? void (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Objective-C declspec doesn't have nullability\"" , "clang/include/clang/Sema/DeclSpec.h", 915, __extension__ __PRETTY_FUNCTION__ )); |
916 | return NullabilityLoc; |
917 | } |
918 | |
919 | void setNullability(SourceLocation loc, NullabilityKind kind) { |
920 | assert((static_cast <bool> (((getObjCDeclQualifier() & DQ_CSNullability ) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability )) && "Set the nullability declspec or property attribute first" ) ? void (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Set the nullability declspec or property attribute first\"" , "clang/include/clang/Sema/DeclSpec.h", 923, __extension__ __PRETTY_FUNCTION__ )) |
921 | ((getObjCDeclQualifier() & DQ_CSNullability) ||(static_cast <bool> (((getObjCDeclQualifier() & DQ_CSNullability ) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability )) && "Set the nullability declspec or property attribute first" ) ? void (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Set the nullability declspec or property attribute first\"" , "clang/include/clang/Sema/DeclSpec.h", 923, __extension__ __PRETTY_FUNCTION__ )) |
922 | (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) &&(static_cast <bool> (((getObjCDeclQualifier() & DQ_CSNullability ) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability )) && "Set the nullability declspec or property attribute first" ) ? void (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Set the nullability declspec or property attribute first\"" , "clang/include/clang/Sema/DeclSpec.h", 923, __extension__ __PRETTY_FUNCTION__ )) |
923 | "Set the nullability declspec or property attribute first")(static_cast <bool> (((getObjCDeclQualifier() & DQ_CSNullability ) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability )) && "Set the nullability declspec or property attribute first" ) ? void (0) : __assert_fail ("((getObjCDeclQualifier() & DQ_CSNullability) || (getPropertyAttributes() & ObjCPropertyAttribute::kind_nullability)) && \"Set the nullability declspec or property attribute first\"" , "clang/include/clang/Sema/DeclSpec.h", 923, __extension__ __PRETTY_FUNCTION__ )); |
924 | Nullability = static_cast<unsigned>(kind); |
925 | NullabilityLoc = loc; |
926 | } |
927 | |
928 | const IdentifierInfo *getGetterName() const { return GetterName; } |
929 | IdentifierInfo *getGetterName() { return GetterName; } |
930 | SourceLocation getGetterNameLoc() const { return GetterNameLoc; } |
931 | void setGetterName(IdentifierInfo *name, SourceLocation loc) { |
932 | GetterName = name; |
933 | GetterNameLoc = loc; |
934 | } |
935 | |
936 | const IdentifierInfo *getSetterName() const { return SetterName; } |
937 | IdentifierInfo *getSetterName() { return SetterName; } |
938 | SourceLocation getSetterNameLoc() const { return SetterNameLoc; } |
939 | void setSetterName(IdentifierInfo *name, SourceLocation loc) { |
940 | SetterName = name; |
941 | SetterNameLoc = loc; |
942 | } |
943 | |
944 | private: |
945 | // FIXME: These two are unrelated and mutually exclusive. So perhaps |
946 | // we can put them in a union to reflect their mutual exclusivity |
947 | // (space saving is negligible). |
948 | unsigned objcDeclQualifier : 7; |
949 | |
950 | // NOTE: VC++ treats enums as signed, avoid using ObjCPropertyAttribute::Kind |
951 | unsigned PropertyAttributes : NumObjCPropertyAttrsBits; |
952 | |
953 | unsigned Nullability : 2; |
954 | |
955 | SourceLocation NullabilityLoc; |
956 | |
957 | IdentifierInfo *GetterName; // getter name or NULL if no getter |
958 | IdentifierInfo *SetterName; // setter name or NULL if no setter |
959 | SourceLocation GetterNameLoc; // location of the getter attribute's value |
960 | SourceLocation SetterNameLoc; // location of the setter attribute's value |
961 | |
962 | }; |
963 | |
964 | /// Describes the kind of unqualified-id parsed. |
965 | enum class UnqualifiedIdKind { |
966 | /// An identifier. |
967 | IK_Identifier, |
968 | /// An overloaded operator name, e.g., operator+. |
969 | IK_OperatorFunctionId, |
970 | /// A conversion function name, e.g., operator int. |
971 | IK_ConversionFunctionId, |
972 | /// A user-defined literal name, e.g., operator "" _i. |
973 | IK_LiteralOperatorId, |
974 | /// A constructor name. |
975 | IK_ConstructorName, |
976 | /// A constructor named via a template-id. |
977 | IK_ConstructorTemplateId, |
978 | /// A destructor name. |
979 | IK_DestructorName, |
980 | /// A template-id, e.g., f<int>. |
981 | IK_TemplateId, |
982 | /// An implicit 'self' parameter |
983 | IK_ImplicitSelfParam, |
984 | /// A deduction-guide name (a template-name) |
985 | IK_DeductionGuideName |
986 | }; |
987 | |
988 | /// Represents a C++ unqualified-id that has been parsed. |
989 | class UnqualifiedId { |
990 | private: |
991 | UnqualifiedId(const UnqualifiedId &Other) = delete; |
992 | const UnqualifiedId &operator=(const UnqualifiedId &) = delete; |
993 | |
994 | /// Describes the kind of unqualified-id parsed. |
995 | UnqualifiedIdKind Kind; |
996 | |
997 | public: |
998 | struct OFI { |
999 | /// The kind of overloaded operator. |
1000 | OverloadedOperatorKind Operator; |
1001 | |
1002 | /// The source locations of the individual tokens that name |
1003 | /// the operator, e.g., the "new", "[", and "]" tokens in |
1004 | /// operator new []. |
1005 | /// |
1006 | /// Different operators have different numbers of tokens in their name, |
1007 | /// up to three. Any remaining source locations in this array will be |
1008 | /// set to an invalid value for operators with fewer than three tokens. |
1009 | SourceLocation SymbolLocations[3]; |
1010 | }; |
1011 | |
1012 | /// Anonymous union that holds extra data associated with the |
1013 | /// parsed unqualified-id. |
1014 | union { |
1015 | /// When Kind == IK_Identifier, the parsed identifier, or when |
1016 | /// Kind == IK_UserLiteralId, the identifier suffix. |
1017 | IdentifierInfo *Identifier; |
1018 | |
1019 | /// When Kind == IK_OperatorFunctionId, the overloaded operator |
1020 | /// that we parsed. |
1021 | struct OFI OperatorFunctionId; |
1022 | |
1023 | /// When Kind == IK_ConversionFunctionId, the type that the |
1024 | /// conversion function names. |
1025 | UnionParsedType ConversionFunctionId; |
1026 | |
1027 | /// When Kind == IK_ConstructorName, the class-name of the type |
1028 | /// whose constructor is being referenced. |
1029 | UnionParsedType ConstructorName; |
1030 | |
1031 | /// When Kind == IK_DestructorName, the type referred to by the |
1032 | /// class-name. |
1033 | UnionParsedType DestructorName; |
1034 | |
1035 | /// When Kind == IK_DeductionGuideName, the parsed template-name. |
1036 | UnionParsedTemplateTy TemplateName; |
1037 | |
1038 | /// When Kind == IK_TemplateId or IK_ConstructorTemplateId, |
1039 | /// the template-id annotation that contains the template name and |
1040 | /// template arguments. |
1041 | TemplateIdAnnotation *TemplateId; |
1042 | }; |
1043 | |
1044 | /// The location of the first token that describes this unqualified-id, |
1045 | /// which will be the location of the identifier, "operator" keyword, |
1046 | /// tilde (for a destructor), or the template name of a template-id. |
1047 | SourceLocation StartLocation; |
1048 | |
1049 | /// The location of the last token that describes this unqualified-id. |
1050 | SourceLocation EndLocation; |
1051 | |
1052 | UnqualifiedId() |
1053 | : Kind(UnqualifiedIdKind::IK_Identifier), Identifier(nullptr) {} |
1054 | |
1055 | /// Clear out this unqualified-id, setting it to default (invalid) |
1056 | /// state. |
1057 | void clear() { |
1058 | Kind = UnqualifiedIdKind::IK_Identifier; |
1059 | Identifier = nullptr; |
1060 | StartLocation = SourceLocation(); |
1061 | EndLocation = SourceLocation(); |
1062 | } |
1063 | |
1064 | /// Determine whether this unqualified-id refers to a valid name. |
1065 | bool isValid() const { return StartLocation.isValid(); } |
1066 | |
1067 | /// Determine whether this unqualified-id refers to an invalid name. |
1068 | bool isInvalid() const { return !isValid(); } |
1069 | |
1070 | /// Determine what kind of name we have. |
1071 | UnqualifiedIdKind getKind() const { return Kind; } |
1072 | |
1073 | /// Specify that this unqualified-id was parsed as an identifier. |
1074 | /// |
1075 | /// \param Id the parsed identifier. |
1076 | /// \param IdLoc the location of the parsed identifier. |
1077 | void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc) { |
1078 | Kind = UnqualifiedIdKind::IK_Identifier; |
1079 | Identifier = const_cast<IdentifierInfo *>(Id); |
1080 | StartLocation = EndLocation = IdLoc; |
1081 | } |
1082 | |
1083 | /// Specify that this unqualified-id was parsed as an |
1084 | /// operator-function-id. |
1085 | /// |
1086 | /// \param OperatorLoc the location of the 'operator' keyword. |
1087 | /// |
1088 | /// \param Op the overloaded operator. |
1089 | /// |
1090 | /// \param SymbolLocations the locations of the individual operator symbols |
1091 | /// in the operator. |
1092 | void setOperatorFunctionId(SourceLocation OperatorLoc, |
1093 | OverloadedOperatorKind Op, |
1094 | SourceLocation SymbolLocations[3]); |
1095 | |
1096 | /// Specify that this unqualified-id was parsed as a |
1097 | /// conversion-function-id. |
1098 | /// |
1099 | /// \param OperatorLoc the location of the 'operator' keyword. |
1100 | /// |
1101 | /// \param Ty the type to which this conversion function is converting. |
1102 | /// |
1103 | /// \param EndLoc the location of the last token that makes up the type name. |
1104 | void setConversionFunctionId(SourceLocation OperatorLoc, |
1105 | ParsedType Ty, |
1106 | SourceLocation EndLoc) { |
1107 | Kind = UnqualifiedIdKind::IK_ConversionFunctionId; |
1108 | StartLocation = OperatorLoc; |
1109 | EndLocation = EndLoc; |
1110 | ConversionFunctionId = Ty; |
1111 | } |
1112 | |
1113 | /// Specific that this unqualified-id was parsed as a |
1114 | /// literal-operator-id. |
1115 | /// |
1116 | /// \param Id the parsed identifier. |
1117 | /// |
1118 | /// \param OpLoc the location of the 'operator' keyword. |
1119 | /// |
1120 | /// \param IdLoc the location of the identifier. |
1121 | void setLiteralOperatorId(const IdentifierInfo *Id, SourceLocation OpLoc, |
1122 | SourceLocation IdLoc) { |
1123 | Kind = UnqualifiedIdKind::IK_LiteralOperatorId; |
1124 | Identifier = const_cast<IdentifierInfo *>(Id); |
1125 | StartLocation = OpLoc; |
1126 | EndLocation = IdLoc; |
1127 | } |
1128 | |
1129 | /// Specify that this unqualified-id was parsed as a constructor name. |
1130 | /// |
1131 | /// \param ClassType the class type referred to by the constructor name. |
1132 | /// |
1133 | /// \param ClassNameLoc the location of the class name. |
1134 | /// |
1135 | /// \param EndLoc the location of the last token that makes up the type name. |
1136 | void setConstructorName(ParsedType ClassType, |
1137 | SourceLocation ClassNameLoc, |
1138 | SourceLocation EndLoc) { |
1139 | Kind = UnqualifiedIdKind::IK_ConstructorName; |
1140 | StartLocation = ClassNameLoc; |
1141 | EndLocation = EndLoc; |
1142 | ConstructorName = ClassType; |
1143 | } |
1144 | |
1145 | /// Specify that this unqualified-id was parsed as a |
1146 | /// template-id that names a constructor. |
1147 | /// |
1148 | /// \param TemplateId the template-id annotation that describes the parsed |
1149 | /// template-id. This UnqualifiedId instance will take ownership of the |
1150 | /// \p TemplateId and will free it on destruction. |
1151 | void setConstructorTemplateId(TemplateIdAnnotation *TemplateId); |
1152 | |
1153 | /// Specify that this unqualified-id was parsed as a destructor name. |
1154 | /// |
1155 | /// \param TildeLoc the location of the '~' that introduces the destructor |
1156 | /// name. |
1157 | /// |
1158 | /// \param ClassType the name of the class referred to by the destructor name. |
1159 | void setDestructorName(SourceLocation TildeLoc, |
1160 | ParsedType ClassType, |
1161 | SourceLocation EndLoc) { |
1162 | Kind = UnqualifiedIdKind::IK_DestructorName; |
1163 | StartLocation = TildeLoc; |
1164 | EndLocation = EndLoc; |
1165 | DestructorName = ClassType; |
1166 | } |
1167 | |
1168 | /// Specify that this unqualified-id was parsed as a template-id. |
1169 | /// |
1170 | /// \param TemplateId the template-id annotation that describes the parsed |
1171 | /// template-id. This UnqualifiedId instance will take ownership of the |
1172 | /// \p TemplateId and will free it on destruction. |
1173 | void setTemplateId(TemplateIdAnnotation *TemplateId); |
1174 | |
1175 | /// Specify that this unqualified-id was parsed as a template-name for |
1176 | /// a deduction-guide. |
1177 | /// |
1178 | /// \param Template The parsed template-name. |
1179 | /// \param TemplateLoc The location of the parsed template-name. |
1180 | void setDeductionGuideName(ParsedTemplateTy Template, |
1181 | SourceLocation TemplateLoc) { |
1182 | Kind = UnqualifiedIdKind::IK_DeductionGuideName; |
1183 | TemplateName = Template; |
1184 | StartLocation = EndLocation = TemplateLoc; |
1185 | } |
1186 | |
1187 | /// Specify that this unqualified-id is an implicit 'self' |
1188 | /// parameter. |
1189 | /// |
1190 | /// \param Id the identifier. |
1191 | void setImplicitSelfParam(const IdentifierInfo *Id) { |
1192 | Kind = UnqualifiedIdKind::IK_ImplicitSelfParam; |
1193 | Identifier = const_cast<IdentifierInfo *>(Id); |
1194 | StartLocation = EndLocation = SourceLocation(); |
1195 | } |
1196 | |
1197 | /// Return the source range that covers this unqualified-id. |
1198 | SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) { |
1199 | return SourceRange(StartLocation, EndLocation); |
1200 | } |
1201 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return StartLocation; } |
1202 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return EndLocation; } |
1203 | }; |
1204 | |
1205 | /// A set of tokens that has been cached for later parsing. |
1206 | typedef SmallVector<Token, 4> CachedTokens; |
1207 | |
1208 | /// One instance of this struct is used for each type in a |
1209 | /// declarator that is parsed. |
1210 | /// |
1211 | /// This is intended to be a small value object. |
1212 | struct DeclaratorChunk { |
1213 | DeclaratorChunk() {}; |
1214 | |
1215 | enum { |
1216 | Pointer, Reference, Array, Function, BlockPointer, MemberPointer, Paren, Pipe |
1217 | } Kind; |
1218 | |
1219 | /// Loc - The place where this type was defined. |
1220 | SourceLocation Loc; |
1221 | /// EndLoc - If valid, the place where this chunck ends. |
1222 | SourceLocation EndLoc; |
1223 | |
1224 | SourceRange getSourceRange() const { |
1225 | if (EndLoc.isInvalid()) |
1226 | return SourceRange(Loc, Loc); |
1227 | return SourceRange(Loc, EndLoc); |
1228 | } |
1229 | |
1230 | ParsedAttributesView AttrList; |
1231 | |
1232 | struct PointerTypeInfo { |
1233 | /// The type qualifiers: const/volatile/restrict/unaligned/atomic. |
1234 | unsigned TypeQuals : 5; |
1235 | |
1236 | /// The location of the const-qualifier, if any. |
1237 | SourceLocation ConstQualLoc; |
1238 | |
1239 | /// The location of the volatile-qualifier, if any. |
1240 | SourceLocation VolatileQualLoc; |
1241 | |
1242 | /// The location of the restrict-qualifier, if any. |
1243 | SourceLocation RestrictQualLoc; |
1244 | |
1245 | /// The location of the _Atomic-qualifier, if any. |
1246 | SourceLocation AtomicQualLoc; |
1247 | |
1248 | /// The location of the __unaligned-qualifier, if any. |
1249 | SourceLocation UnalignedQualLoc; |
1250 | |
1251 | void destroy() { |
1252 | } |
1253 | }; |
1254 | |
1255 | struct ReferenceTypeInfo { |
1256 | /// The type qualifier: restrict. [GNU] C++ extension |
1257 | bool HasRestrict : 1; |
1258 | /// True if this is an lvalue reference, false if it's an rvalue reference. |
1259 | bool LValueRef : 1; |
1260 | void destroy() { |
1261 | } |
1262 | }; |
1263 | |
1264 | struct ArrayTypeInfo { |
1265 | /// The type qualifiers for the array: |
1266 | /// const/volatile/restrict/__unaligned/_Atomic. |
1267 | unsigned TypeQuals : 5; |
1268 | |
1269 | /// True if this dimension included the 'static' keyword. |
1270 | unsigned hasStatic : 1; |
1271 | |
1272 | /// True if this dimension was [*]. In this case, NumElts is null. |
1273 | unsigned isStar : 1; |
1274 | |
1275 | /// This is the size of the array, or null if [] or [*] was specified. |
1276 | /// Since the parser is multi-purpose, and we don't want to impose a root |
1277 | /// expression class on all clients, NumElts is untyped. |
1278 | Expr *NumElts; |
1279 | |
1280 | void destroy() {} |
1281 | }; |
1282 | |
1283 | /// ParamInfo - An array of paraminfo objects is allocated whenever a function |
1284 | /// declarator is parsed. There are two interesting styles of parameters |
1285 | /// here: |
1286 | /// K&R-style identifier lists and parameter type lists. K&R-style identifier |
1287 | /// lists will have information about the identifier, but no type information. |
1288 | /// Parameter type lists will have type info (if the actions module provides |
1289 | /// it), but may have null identifier info: e.g. for 'void foo(int X, int)'. |
1290 | struct ParamInfo { |
1291 | IdentifierInfo *Ident; |
1292 | SourceLocation IdentLoc; |
1293 | Decl *Param; |
1294 | |
1295 | /// DefaultArgTokens - When the parameter's default argument |
1296 | /// cannot be parsed immediately (because it occurs within the |
1297 | /// declaration of a member function), it will be stored here as a |
1298 | /// sequence of tokens to be parsed once the class definition is |
1299 | /// complete. Non-NULL indicates that there is a default argument. |
1300 | std::unique_ptr<CachedTokens> DefaultArgTokens; |
1301 | |
1302 | ParamInfo() = default; |
1303 | ParamInfo(IdentifierInfo *ident, SourceLocation iloc, |
1304 | Decl *param, |
1305 | std::unique_ptr<CachedTokens> DefArgTokens = nullptr) |
1306 | : Ident(ident), IdentLoc(iloc), Param(param), |
1307 | DefaultArgTokens(std::move(DefArgTokens)) {} |
1308 | }; |
1309 | |
1310 | struct TypeAndRange { |
1311 | ParsedType Ty; |
1312 | SourceRange Range; |
1313 | }; |
1314 | |
1315 | struct FunctionTypeInfo { |
1316 | /// hasPrototype - This is true if the function had at least one typed |
1317 | /// parameter. If the function is () or (a,b,c), then it has no prototype, |
1318 | /// and is treated as a K&R-style function. |
1319 | unsigned hasPrototype : 1; |
1320 | |
1321 | /// isVariadic - If this function has a prototype, and if that |
1322 | /// proto ends with ',...)', this is true. When true, EllipsisLoc |
1323 | /// contains the location of the ellipsis. |
1324 | unsigned isVariadic : 1; |
1325 | |
1326 | /// Can this declaration be a constructor-style initializer? |
1327 | unsigned isAmbiguous : 1; |
1328 | |
1329 | /// Whether the ref-qualifier (if any) is an lvalue reference. |
1330 | /// Otherwise, it's an rvalue reference. |
1331 | unsigned RefQualifierIsLValueRef : 1; |
1332 | |
1333 | /// ExceptionSpecType - An ExceptionSpecificationType value. |
1334 | unsigned ExceptionSpecType : 4; |
1335 | |
1336 | /// DeleteParams - If this is true, we need to delete[] Params. |
1337 | unsigned DeleteParams : 1; |
1338 | |
1339 | /// HasTrailingReturnType - If this is true, a trailing return type was |
1340 | /// specified. |
1341 | unsigned HasTrailingReturnType : 1; |
1342 | |
1343 | /// The location of the left parenthesis in the source. |
1344 | SourceLocation LParenLoc; |
1345 | |
1346 | /// When isVariadic is true, the location of the ellipsis in the source. |
1347 | SourceLocation EllipsisLoc; |
1348 | |
1349 | /// The location of the right parenthesis in the source. |
1350 | SourceLocation RParenLoc; |
1351 | |
1352 | /// NumParams - This is the number of formal parameters specified by the |
1353 | /// declarator. |
1354 | unsigned NumParams; |
1355 | |
1356 | /// NumExceptionsOrDecls - This is the number of types in the |
1357 | /// dynamic-exception-decl, if the function has one. In C, this is the |
1358 | /// number of declarations in the function prototype. |
1359 | unsigned NumExceptionsOrDecls; |
1360 | |
1361 | /// The location of the ref-qualifier, if any. |
1362 | /// |
1363 | /// If this is an invalid location, there is no ref-qualifier. |
1364 | SourceLocation RefQualifierLoc; |
1365 | |
1366 | /// The location of the 'mutable' qualifer in a lambda-declarator, if |
1367 | /// any. |
1368 | SourceLocation MutableLoc; |
1369 | |
1370 | /// The beginning location of the exception specification, if any. |
1371 | SourceLocation ExceptionSpecLocBeg; |
1372 | |
1373 | /// The end location of the exception specification, if any. |
1374 | SourceLocation ExceptionSpecLocEnd; |
1375 | |
1376 | /// Params - This is a pointer to a new[]'d array of ParamInfo objects that |
1377 | /// describe the parameters specified by this function declarator. null if |
1378 | /// there are no parameters specified. |
1379 | ParamInfo *Params; |
1380 | |
1381 | /// DeclSpec for the function with the qualifier related info. |
1382 | DeclSpec *MethodQualifiers; |
1383 | |
1384 | /// AttributeFactory for the MethodQualifiers. |
1385 | AttributeFactory *QualAttrFactory; |
1386 | |
1387 | union { |
1388 | /// Pointer to a new[]'d array of TypeAndRange objects that |
1389 | /// contain the types in the function's dynamic exception specification |
1390 | /// and their locations, if there is one. |
1391 | TypeAndRange *Exceptions; |
1392 | |
1393 | /// Pointer to the expression in the noexcept-specifier of this |
1394 | /// function, if it has one. |
1395 | Expr *NoexceptExpr; |
1396 | |
1397 | /// Pointer to the cached tokens for an exception-specification |
1398 | /// that has not yet been parsed. |
1399 | CachedTokens *ExceptionSpecTokens; |
1400 | |
1401 | /// Pointer to a new[]'d array of declarations that need to be available |
1402 | /// for lookup inside the function body, if one exists. Does not exist in |
1403 | /// C++. |
1404 | NamedDecl **DeclsInPrototype; |
1405 | }; |
1406 | |
1407 | /// If HasTrailingReturnType is true, this is the trailing return |
1408 | /// type specified. |
1409 | UnionParsedType TrailingReturnType; |
1410 | |
1411 | /// If HasTrailingReturnType is true, this is the location of the trailing |
1412 | /// return type. |
1413 | SourceLocation TrailingReturnTypeLoc; |
1414 | |
1415 | /// Reset the parameter list to having zero parameters. |
1416 | /// |
1417 | /// This is used in various places for error recovery. |
1418 | void freeParams() { |
1419 | for (unsigned I = 0; I < NumParams; ++I) |
1420 | Params[I].DefaultArgTokens.reset(); |
1421 | if (DeleteParams) { |
1422 | delete[] Params; |
1423 | DeleteParams = false; |
1424 | } |
1425 | NumParams = 0; |
1426 | } |
1427 | |
1428 | void destroy() { |
1429 | freeParams(); |
1430 | delete QualAttrFactory; |
1431 | delete MethodQualifiers; |
1432 | switch (getExceptionSpecType()) { |
1433 | default: |
1434 | break; |
1435 | case EST_Dynamic: |
1436 | delete[] Exceptions; |
1437 | break; |
1438 | case EST_Unparsed: |
1439 | delete ExceptionSpecTokens; |
1440 | break; |
1441 | case EST_None: |
1442 | if (NumExceptionsOrDecls != 0) |
1443 | delete[] DeclsInPrototype; |
1444 | break; |
1445 | } |
1446 | } |
1447 | |
1448 | DeclSpec &getOrCreateMethodQualifiers() { |
1449 | if (!MethodQualifiers) { |
1450 | QualAttrFactory = new AttributeFactory(); |
1451 | MethodQualifiers = new DeclSpec(*QualAttrFactory); |
1452 | } |
1453 | return *MethodQualifiers; |
1454 | } |
1455 | |
1456 | /// isKNRPrototype - Return true if this is a K&R style identifier list, |
1457 | /// like "void foo(a,b,c)". In a function definition, this will be followed |
1458 | /// by the parameter type definitions. |
1459 | bool isKNRPrototype() const { return !hasPrototype && NumParams != 0; } |
1460 | |
1461 | SourceLocation getLParenLoc() const { return LParenLoc; } |
1462 | |
1463 | SourceLocation getEllipsisLoc() const { return EllipsisLoc; } |
1464 | |
1465 | SourceLocation getRParenLoc() const { return RParenLoc; } |
1466 | |
1467 | SourceLocation getExceptionSpecLocBeg() const { |
1468 | return ExceptionSpecLocBeg; |
1469 | } |
1470 | |
1471 | SourceLocation getExceptionSpecLocEnd() const { |
1472 | return ExceptionSpecLocEnd; |
1473 | } |
1474 | |
1475 | SourceRange getExceptionSpecRange() const { |
1476 | return SourceRange(getExceptionSpecLocBeg(), getExceptionSpecLocEnd()); |
1477 | } |
1478 | |
1479 | /// Retrieve the location of the ref-qualifier, if any. |
1480 | SourceLocation getRefQualifierLoc() const { return RefQualifierLoc; } |
1481 | |
1482 | /// Retrieve the location of the 'const' qualifier. |
1483 | SourceLocation getConstQualifierLoc() const { |
1484 | assert(MethodQualifiers)(static_cast <bool> (MethodQualifiers) ? void (0) : __assert_fail ("MethodQualifiers", "clang/include/clang/Sema/DeclSpec.h", 1484 , __extension__ __PRETTY_FUNCTION__)); |
1485 | return MethodQualifiers->getConstSpecLoc(); |
1486 | } |
1487 | |
1488 | /// Retrieve the location of the 'volatile' qualifier. |
1489 | SourceLocation getVolatileQualifierLoc() const { |
1490 | assert(MethodQualifiers)(static_cast <bool> (MethodQualifiers) ? void (0) : __assert_fail ("MethodQualifiers", "clang/include/clang/Sema/DeclSpec.h", 1490 , __extension__ __PRETTY_FUNCTION__)); |
1491 | return MethodQualifiers->getVolatileSpecLoc(); |
1492 | } |
1493 | |
1494 | /// Retrieve the location of the 'restrict' qualifier. |
1495 | SourceLocation getRestrictQualifierLoc() const { |
1496 | assert(MethodQualifiers)(static_cast <bool> (MethodQualifiers) ? void (0) : __assert_fail ("MethodQualifiers", "clang/include/clang/Sema/DeclSpec.h", 1496 , __extension__ __PRETTY_FUNCTION__)); |
1497 | return MethodQualifiers->getRestrictSpecLoc(); |
1498 | } |
1499 | |
1500 | /// Retrieve the location of the 'mutable' qualifier, if any. |
1501 | SourceLocation getMutableLoc() const { return MutableLoc; } |
1502 | |
1503 | /// Determine whether this function declaration contains a |
1504 | /// ref-qualifier. |
1505 | bool hasRefQualifier() const { return getRefQualifierLoc().isValid(); } |
1506 | |
1507 | /// Determine whether this lambda-declarator contains a 'mutable' |
1508 | /// qualifier. |
1509 | bool hasMutableQualifier() const { return getMutableLoc().isValid(); } |
1510 | |
1511 | /// Determine whether this method has qualifiers. |
1512 | bool hasMethodTypeQualifiers() const { |
1513 | return MethodQualifiers && (MethodQualifiers->getTypeQualifiers() || |
1514 | MethodQualifiers->getAttributes().size()); |
1515 | } |
1516 | |
1517 | /// Get the type of exception specification this function has. |
1518 | ExceptionSpecificationType getExceptionSpecType() const { |
1519 | return static_cast<ExceptionSpecificationType>(ExceptionSpecType); |
1520 | } |
1521 | |
1522 | /// Get the number of dynamic exception specifications. |
1523 | unsigned getNumExceptions() const { |
1524 | assert(ExceptionSpecType != EST_None)(static_cast <bool> (ExceptionSpecType != EST_None) ? void (0) : __assert_fail ("ExceptionSpecType != EST_None", "clang/include/clang/Sema/DeclSpec.h" , 1524, __extension__ __PRETTY_FUNCTION__)); |
1525 | return NumExceptionsOrDecls; |
1526 | } |
1527 | |
1528 | /// Get the non-parameter decls defined within this function |
1529 | /// prototype. Typically these are tag declarations. |
1530 | ArrayRef<NamedDecl *> getDeclsInPrototype() const { |
1531 | assert(ExceptionSpecType == EST_None)(static_cast <bool> (ExceptionSpecType == EST_None) ? void (0) : __assert_fail ("ExceptionSpecType == EST_None", "clang/include/clang/Sema/DeclSpec.h" , 1531, __extension__ __PRETTY_FUNCTION__)); |
1532 | return llvm::ArrayRef(DeclsInPrototype, NumExceptionsOrDecls); |
1533 | } |
1534 | |
1535 | /// Determine whether this function declarator had a |
1536 | /// trailing-return-type. |
1537 | bool hasTrailingReturnType() const { return HasTrailingReturnType; } |
1538 | |
1539 | /// Get the trailing-return-type for this function declarator. |
1540 | ParsedType getTrailingReturnType() const { |
1541 | assert(HasTrailingReturnType)(static_cast <bool> (HasTrailingReturnType) ? void (0) : __assert_fail ("HasTrailingReturnType", "clang/include/clang/Sema/DeclSpec.h" , 1541, __extension__ __PRETTY_FUNCTION__)); |
1542 | return TrailingReturnType; |
1543 | } |
1544 | |
1545 | /// Get the trailing-return-type location for this function declarator. |
1546 | SourceLocation getTrailingReturnTypeLoc() const { |
1547 | assert(HasTrailingReturnType)(static_cast <bool> (HasTrailingReturnType) ? void (0) : __assert_fail ("HasTrailingReturnType", "clang/include/clang/Sema/DeclSpec.h" , 1547, __extension__ __PRETTY_FUNCTION__)); |
1548 | return TrailingReturnTypeLoc; |
1549 | } |
1550 | }; |
1551 | |
1552 | struct BlockPointerTypeInfo { |
1553 | /// For now, sema will catch these as invalid. |
1554 | /// The type qualifiers: const/volatile/restrict/__unaligned/_Atomic. |
1555 | unsigned TypeQuals : 5; |
1556 | |
1557 | void destroy() { |
1558 | } |
1559 | }; |
1560 | |
1561 | struct MemberPointerTypeInfo { |
1562 | /// The type qualifiers: const/volatile/restrict/__unaligned/_Atomic. |
1563 | unsigned TypeQuals : 5; |
1564 | /// Location of the '*' token. |
1565 | SourceLocation StarLoc; |
1566 | // CXXScopeSpec has a constructor, so it can't be a direct member. |
1567 | // So we need some pointer-aligned storage and a bit of trickery. |
1568 | alignas(CXXScopeSpec) char ScopeMem[sizeof(CXXScopeSpec)]; |
1569 | CXXScopeSpec &Scope() { |
1570 | return *reinterpret_cast<CXXScopeSpec *>(ScopeMem); |
1571 | } |
1572 | const CXXScopeSpec &Scope() const { |
1573 | return *reinterpret_cast<const CXXScopeSpec *>(ScopeMem); |
1574 | } |
1575 | void destroy() { |
1576 | Scope().~CXXScopeSpec(); |
1577 | } |
1578 | }; |
1579 | |
1580 | struct PipeTypeInfo { |
1581 | /// The access writes. |
1582 | unsigned AccessWrites : 3; |
1583 | |
1584 | void destroy() {} |
1585 | }; |
1586 | |
1587 | union { |
1588 | PointerTypeInfo Ptr; |
1589 | ReferenceTypeInfo Ref; |
1590 | ArrayTypeInfo Arr; |
1591 | FunctionTypeInfo Fun; |
1592 | BlockPointerTypeInfo Cls; |
1593 | MemberPointerTypeInfo Mem; |
1594 | PipeTypeInfo PipeInfo; |
1595 | }; |
1596 | |
1597 | void destroy() { |
1598 | switch (Kind) { |
1599 | case DeclaratorChunk::Function: return Fun.destroy(); |
1600 | case DeclaratorChunk::Pointer: return Ptr.destroy(); |
1601 | case DeclaratorChunk::BlockPointer: return Cls.destroy(); |
1602 | case DeclaratorChunk::Reference: return Ref.destroy(); |
1603 | case DeclaratorChunk::Array: return Arr.destroy(); |
1604 | case DeclaratorChunk::MemberPointer: return Mem.destroy(); |
1605 | case DeclaratorChunk::Paren: return; |
1606 | case DeclaratorChunk::Pipe: return PipeInfo.destroy(); |
1607 | } |
1608 | } |
1609 | |
1610 | /// If there are attributes applied to this declaratorchunk, return |
1611 | /// them. |
1612 | const ParsedAttributesView &getAttrs() const { return AttrList; } |
1613 | ParsedAttributesView &getAttrs() { return AttrList; } |
1614 | |
1615 | /// Return a DeclaratorChunk for a pointer. |
1616 | static DeclaratorChunk getPointer(unsigned TypeQuals, SourceLocation Loc, |
1617 | SourceLocation ConstQualLoc, |
1618 | SourceLocation VolatileQualLoc, |
1619 | SourceLocation RestrictQualLoc, |
1620 | SourceLocation AtomicQualLoc, |
1621 | SourceLocation UnalignedQualLoc) { |
1622 | DeclaratorChunk I; |
1623 | I.Kind = Pointer; |
1624 | I.Loc = Loc; |
1625 | new (&I.Ptr) PointerTypeInfo; |
1626 | I.Ptr.TypeQuals = TypeQuals; |
1627 | I.Ptr.ConstQualLoc = ConstQualLoc; |
1628 | I.Ptr.VolatileQualLoc = VolatileQualLoc; |
1629 | I.Ptr.RestrictQualLoc = RestrictQualLoc; |
1630 | I.Ptr.AtomicQualLoc = AtomicQualLoc; |
1631 | I.Ptr.UnalignedQualLoc = UnalignedQualLoc; |
1632 | return I; |
1633 | } |
1634 | |
1635 | /// Return a DeclaratorChunk for a reference. |
1636 | static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc, |
1637 | bool lvalue) { |
1638 | DeclaratorChunk I; |
1639 | I.Kind = Reference; |
1640 | I.Loc = Loc; |
1641 | I.Ref.HasRestrict = (TypeQuals & DeclSpec::TQ_restrict) != 0; |
1642 | I.Ref.LValueRef = lvalue; |
1643 | return I; |
1644 | } |
1645 | |
1646 | /// Return a DeclaratorChunk for an array. |
1647 | static DeclaratorChunk getArray(unsigned TypeQuals, |
1648 | bool isStatic, bool isStar, Expr *NumElts, |
1649 | SourceLocation LBLoc, SourceLocation RBLoc) { |
1650 | DeclaratorChunk I; |
1651 | I.Kind = Array; |
1652 | I.Loc = LBLoc; |
1653 | I.EndLoc = RBLoc; |
1654 | I.Arr.TypeQuals = TypeQuals; |
1655 | I.Arr.hasStatic = isStatic; |
1656 | I.Arr.isStar = isStar; |
1657 | I.Arr.NumElts = NumElts; |
1658 | return I; |
1659 | } |
1660 | |
1661 | /// DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function. |
1662 | /// "TheDeclarator" is the declarator that this will be added to. |
1663 | static DeclaratorChunk getFunction(bool HasProto, |
1664 | bool IsAmbiguous, |
1665 | SourceLocation LParenLoc, |
1666 | ParamInfo *Params, unsigned NumParams, |
1667 | SourceLocation EllipsisLoc, |
1668 | SourceLocation RParenLoc, |
1669 | bool RefQualifierIsLvalueRef, |
1670 | SourceLocation RefQualifierLoc, |
1671 | SourceLocation MutableLoc, |
1672 | ExceptionSpecificationType ESpecType, |
1673 | SourceRange ESpecRange, |
1674 | ParsedType *Exceptions, |
1675 | SourceRange *ExceptionRanges, |
1676 | unsigned NumExceptions, |
1677 | Expr *NoexceptExpr, |
1678 | CachedTokens *ExceptionSpecTokens, |
1679 | ArrayRef<NamedDecl *> DeclsInPrototype, |
1680 | SourceLocation LocalRangeBegin, |
1681 | SourceLocation LocalRangeEnd, |
1682 | Declarator &TheDeclarator, |
1683 | TypeResult TrailingReturnType = |
1684 | TypeResult(), |
1685 | SourceLocation TrailingReturnTypeLoc = |
1686 | SourceLocation(), |
1687 | DeclSpec *MethodQualifiers = nullptr); |
1688 | |
1689 | /// Return a DeclaratorChunk for a block. |
1690 | static DeclaratorChunk getBlockPointer(unsigned TypeQuals, |
1691 | SourceLocation Loc) { |
1692 | DeclaratorChunk I; |
1693 | I.Kind = BlockPointer; |
1694 | I.Loc = Loc; |
1695 | I.Cls.TypeQuals = TypeQuals; |
1696 | return I; |
1697 | } |
1698 | |
1699 | /// Return a DeclaratorChunk for a block. |
1700 | static DeclaratorChunk getPipe(unsigned TypeQuals, |
1701 | SourceLocation Loc) { |
1702 | DeclaratorChunk I; |
1703 | I.Kind = Pipe; |
1704 | I.Loc = Loc; |
1705 | I.Cls.TypeQuals = TypeQuals; |
1706 | return I; |
1707 | } |
1708 | |
1709 | static DeclaratorChunk getMemberPointer(const CXXScopeSpec &SS, |
1710 | unsigned TypeQuals, |
1711 | SourceLocation StarLoc, |
1712 | SourceLocation EndLoc) { |
1713 | DeclaratorChunk I; |
1714 | I.Kind = MemberPointer; |
1715 | I.Loc = SS.getBeginLoc(); |
1716 | I.EndLoc = EndLoc; |
1717 | new (&I.Mem) MemberPointerTypeInfo; |
1718 | I.Mem.StarLoc = StarLoc; |
1719 | I.Mem.TypeQuals = TypeQuals; |
1720 | new (I.Mem.ScopeMem) CXXScopeSpec(SS); |
1721 | return I; |
1722 | } |
1723 | |
1724 | /// Return a DeclaratorChunk for a paren. |
1725 | static DeclaratorChunk getParen(SourceLocation LParenLoc, |
1726 | SourceLocation RParenLoc) { |
1727 | DeclaratorChunk I; |
1728 | I.Kind = Paren; |
1729 | I.Loc = LParenLoc; |
1730 | I.EndLoc = RParenLoc; |
1731 | return I; |
1732 | } |
1733 | |
1734 | bool isParen() const { |
1735 | return Kind == Paren; |
1736 | } |
1737 | }; |
1738 | |
1739 | /// A parsed C++17 decomposition declarator of the form |
1740 | /// '[' identifier-list ']' |
1741 | class DecompositionDeclarator { |
1742 | public: |
1743 | struct Binding { |
1744 | IdentifierInfo *Name; |
1745 | SourceLocation NameLoc; |
1746 | }; |
1747 | |
1748 | private: |
1749 | /// The locations of the '[' and ']' tokens. |
1750 | SourceLocation LSquareLoc, RSquareLoc; |
1751 | |
1752 | /// The bindings. |
1753 | Binding *Bindings; |
1754 | unsigned NumBindings : 31; |
1755 | unsigned DeleteBindings : 1; |
1756 | |
1757 | friend class Declarator; |
1758 | |
1759 | public: |
1760 | DecompositionDeclarator() |
1761 | : Bindings(nullptr), NumBindings(0), DeleteBindings(false) {} |
1762 | DecompositionDeclarator(const DecompositionDeclarator &G) = delete; |
1763 | DecompositionDeclarator &operator=(const DecompositionDeclarator &G) = delete; |
1764 | ~DecompositionDeclarator() { |
1765 | if (DeleteBindings) |
1766 | delete[] Bindings; |
1767 | } |
1768 | |
1769 | void clear() { |
1770 | LSquareLoc = RSquareLoc = SourceLocation(); |
1771 | if (DeleteBindings) |
1772 | delete[] Bindings; |
1773 | Bindings = nullptr; |
1774 | NumBindings = 0; |
1775 | DeleteBindings = false; |
1776 | } |
1777 | |
1778 | ArrayRef<Binding> bindings() const { |
1779 | return llvm::ArrayRef(Bindings, NumBindings); |
1780 | } |
1781 | |
1782 | bool isSet() const { return LSquareLoc.isValid(); } |
1783 | |
1784 | SourceLocation getLSquareLoc() const { return LSquareLoc; } |
1785 | SourceLocation getRSquareLoc() const { return RSquareLoc; } |
1786 | SourceRange getSourceRange() const { |
1787 | return SourceRange(LSquareLoc, RSquareLoc); |
1788 | } |
1789 | }; |
1790 | |
1791 | /// Described the kind of function definition (if any) provided for |
1792 | /// a function. |
1793 | enum class FunctionDefinitionKind { |
1794 | Declaration, |
1795 | Definition, |
1796 | Defaulted, |
1797 | Deleted |
1798 | }; |
1799 | |
1800 | enum class DeclaratorContext { |
1801 | File, // File scope declaration. |
1802 | Prototype, // Within a function prototype. |
1803 | ObjCResult, // An ObjC method result type. |
1804 | ObjCParameter, // An ObjC method parameter type. |
1805 | KNRTypeList, // K&R type definition list for formals. |
1806 | TypeName, // Abstract declarator for types. |
1807 | FunctionalCast, // Type in a C++ functional cast expression. |
1808 | Member, // Struct/Union field. |
1809 | Block, // Declaration within a block in a function. |
1810 | ForInit, // Declaration within first part of a for loop. |
1811 | SelectionInit, // Declaration within optional init stmt of if/switch. |
1812 | Condition, // Condition declaration in a C++ if/switch/while/for. |
1813 | TemplateParam, // Within a template parameter list. |
1814 | CXXNew, // C++ new-expression. |
1815 | CXXCatch, // C++ catch exception-declaration |
1816 | ObjCCatch, // Objective-C catch exception-declaration |
1817 | BlockLiteral, // Block literal declarator. |
1818 | LambdaExpr, // Lambda-expression declarator. |
1819 | LambdaExprParameter, // Lambda-expression parameter declarator. |
1820 | ConversionId, // C++ conversion-type-id. |
1821 | TrailingReturn, // C++11 trailing-type-specifier. |
1822 | TrailingReturnVar, // C++11 trailing-type-specifier for variable. |
1823 | TemplateArg, // Any template argument (in template argument list). |
1824 | TemplateTypeArg, // Template type argument (in default argument). |
1825 | AliasDecl, // C++11 alias-declaration. |
1826 | AliasTemplate, // C++11 alias-declaration template. |
1827 | RequiresExpr, // C++2a requires-expression. |
1828 | Association // C11 _Generic selection expression association. |
1829 | }; |
1830 | |
1831 | // Describes whether the current context is a context where an implicit |
1832 | // typename is allowed (C++2a [temp.res]p5]). |
1833 | enum class ImplicitTypenameContext { |
1834 | No, |
1835 | Yes, |
1836 | }; |
1837 | |
1838 | /// Information about one declarator, including the parsed type |
1839 | /// information and the identifier. |
1840 | /// |
1841 | /// When the declarator is fully formed, this is turned into the appropriate |
1842 | /// Decl object. |
1843 | /// |
1844 | /// Declarators come in two types: normal declarators and abstract declarators. |
1845 | /// Abstract declarators are used when parsing types, and don't have an |
1846 | /// identifier. Normal declarators do have ID's. |
1847 | /// |
1848 | /// Instances of this class should be a transient object that lives on the |
1849 | /// stack, not objects that are allocated in large quantities on the heap. |
1850 | class Declarator { |
1851 | |
1852 | private: |
1853 | const DeclSpec &DS; |
1854 | CXXScopeSpec SS; |
1855 | UnqualifiedId Name; |
1856 | SourceRange Range; |
1857 | |
1858 | /// Where we are parsing this declarator. |
1859 | DeclaratorContext Context; |
1860 | |
1861 | /// The C++17 structured binding, if any. This is an alternative to a Name. |
1862 | DecompositionDeclarator BindingGroup; |
1863 | |
1864 | /// DeclTypeInfo - This holds each type that the declarator includes as it is |
1865 | /// parsed. This is pushed from the identifier out, which means that element |
1866 | /// #0 will be the most closely bound to the identifier, and |
1867 | /// DeclTypeInfo.back() will be the least closely bound. |
1868 | SmallVector<DeclaratorChunk, 8> DeclTypeInfo; |
1869 | |
1870 | /// InvalidType - Set by Sema::GetTypeForDeclarator(). |
1871 | unsigned InvalidType : 1; |
1872 | |
1873 | /// GroupingParens - Set by Parser::ParseParenDeclarator(). |
1874 | unsigned GroupingParens : 1; |
1875 | |
1876 | /// FunctionDefinition - Is this Declarator for a function or member |
1877 | /// definition and, if so, what kind? |
1878 | /// |
1879 | /// Actually a FunctionDefinitionKind. |
1880 | unsigned FunctionDefinition : 2; |
1881 | |
1882 | /// Is this Declarator a redeclaration? |
1883 | unsigned Redeclaration : 1; |
1884 | |
1885 | /// true if the declaration is preceded by \c __extension__. |
1886 | unsigned Extension : 1; |
1887 | |
1888 | /// Indicates whether this is an Objective-C instance variable. |
1889 | unsigned ObjCIvar : 1; |
1890 | |
1891 | /// Indicates whether this is an Objective-C 'weak' property. |
1892 | unsigned ObjCWeakProperty : 1; |
1893 | |
1894 | /// Indicates whether the InlineParams / InlineBindings storage has been used. |
1895 | unsigned InlineStorageUsed : 1; |
1896 | |
1897 | /// Indicates whether this declarator has an initializer. |
1898 | unsigned HasInitializer : 1; |
1899 | |
1900 | /// Attributes attached to the declarator. |
1901 | ParsedAttributes Attrs; |
1902 | |
1903 | /// Attributes attached to the declaration. See also documentation for the |
1904 | /// corresponding constructor parameter. |
1905 | const ParsedAttributesView &DeclarationAttrs; |
1906 | |
1907 | /// The asm label, if specified. |
1908 | Expr *AsmLabel; |
1909 | |
1910 | /// \brief The constraint-expression specified by the trailing |
1911 | /// requires-clause, or null if no such clause was specified. |
1912 | Expr *TrailingRequiresClause; |
1913 | |
1914 | /// If this declarator declares a template, its template parameter lists. |
1915 | ArrayRef<TemplateParameterList *> TemplateParameterLists; |
1916 | |
1917 | /// If the declarator declares an abbreviated function template, the innermost |
1918 | /// template parameter list containing the invented and explicit template |
1919 | /// parameters (if any). |
1920 | TemplateParameterList *InventedTemplateParameterList; |
1921 | |
1922 | #ifndef _MSC_VER |
1923 | union { |
1924 | #endif |
1925 | /// InlineParams - This is a local array used for the first function decl |
1926 | /// chunk to avoid going to the heap for the common case when we have one |
1927 | /// function chunk in the declarator. |
1928 | DeclaratorChunk::ParamInfo InlineParams[16]; |
1929 | DecompositionDeclarator::Binding InlineBindings[16]; |
1930 | #ifndef _MSC_VER |
1931 | }; |
1932 | #endif |
1933 | |
1934 | /// If this is the second or subsequent declarator in this declaration, |
1935 | /// the location of the comma before this declarator. |
1936 | SourceLocation CommaLoc; |
1937 | |
1938 | /// If provided, the source location of the ellipsis used to describe |
1939 | /// this declarator as a parameter pack. |
1940 | SourceLocation EllipsisLoc; |
1941 | |
1942 | friend struct DeclaratorChunk; |
1943 | |
1944 | public: |
1945 | /// `DS` and `DeclarationAttrs` must outlive the `Declarator`. In particular, |
1946 | /// take care not to pass temporary objects for these parameters. |
1947 | /// |
1948 | /// `DeclarationAttrs` contains [[]] attributes from the |
1949 | /// attribute-specifier-seq at the beginning of a declaration, which appertain |
1950 | /// to the declared entity itself. Attributes with other syntax (e.g. GNU) |
1951 | /// should not be placed in this attribute list; if they occur at the |
1952 | /// beginning of a declaration, they apply to the `DeclSpec` and should be |
1953 | /// attached to that instead. |
1954 | /// |
1955 | /// Here is an example of an attribute associated with a declaration: |
1956 | /// |
1957 | /// [[deprecated]] int x, y; |
1958 | /// |
1959 | /// This attribute appertains to all of the entities declared in the |
1960 | /// declaration, i.e. `x` and `y` in this case. |
1961 | Declarator(const DeclSpec &DS, const ParsedAttributesView &DeclarationAttrs, |
1962 | DeclaratorContext C) |
1963 | : DS(DS), Range(DS.getSourceRange()), Context(C), |
1964 | InvalidType(DS.getTypeSpecType() == DeclSpec::TST_error), |
1965 | GroupingParens(false), FunctionDefinition(static_cast<unsigned>( |
1966 | FunctionDefinitionKind::Declaration)), |
1967 | Redeclaration(false), Extension(false), ObjCIvar(false), |
1968 | ObjCWeakProperty(false), InlineStorageUsed(false), |
1969 | HasInitializer(false), Attrs(DS.getAttributePool().getFactory()), |
1970 | DeclarationAttrs(DeclarationAttrs), AsmLabel(nullptr), |
1971 | TrailingRequiresClause(nullptr), |
1972 | InventedTemplateParameterList(nullptr) { |
1973 | assert(llvm::all_of(DeclarationAttrs,(static_cast <bool> (llvm::all_of(DeclarationAttrs, []( const ParsedAttr &AL) { return AL.isStandardAttributeSyntax (); }) && "DeclarationAttrs may only contain [[]] attributes" ) ? void (0) : __assert_fail ("llvm::all_of(DeclarationAttrs, [](const ParsedAttr &AL) { return AL.isStandardAttributeSyntax(); }) && \"DeclarationAttrs may only contain [[]] attributes\"" , "clang/include/clang/Sema/DeclSpec.h", 1977, __extension__ __PRETTY_FUNCTION__ )) |
1974 | [](const ParsedAttr &AL) {(static_cast <bool> (llvm::all_of(DeclarationAttrs, []( const ParsedAttr &AL) { return AL.isStandardAttributeSyntax (); }) && "DeclarationAttrs may only contain [[]] attributes" ) ? void (0) : __assert_fail ("llvm::all_of(DeclarationAttrs, [](const ParsedAttr &AL) { return AL.isStandardAttributeSyntax(); }) && \"DeclarationAttrs may only contain [[]] attributes\"" , "clang/include/clang/Sema/DeclSpec.h", 1977, __extension__ __PRETTY_FUNCTION__ )) |
1975 | return AL.isStandardAttributeSyntax();(static_cast <bool> (llvm::all_of(DeclarationAttrs, []( const ParsedAttr &AL) { return AL.isStandardAttributeSyntax (); }) && "DeclarationAttrs may only contain [[]] attributes" ) ? void (0) : __assert_fail ("llvm::all_of(DeclarationAttrs, [](const ParsedAttr &AL) { return AL.isStandardAttributeSyntax(); }) && \"DeclarationAttrs may only contain [[]] attributes\"" , "clang/include/clang/Sema/DeclSpec.h", 1977, __extension__ __PRETTY_FUNCTION__ )) |
1976 | }) &&(static_cast <bool> (llvm::all_of(DeclarationAttrs, []( const ParsedAttr &AL) { return AL.isStandardAttributeSyntax (); }) && "DeclarationAttrs may only contain [[]] attributes" ) ? void (0) : __assert_fail ("llvm::all_of(DeclarationAttrs, [](const ParsedAttr &AL) { return AL.isStandardAttributeSyntax(); }) && \"DeclarationAttrs may only contain [[]] attributes\"" , "clang/include/clang/Sema/DeclSpec.h", 1977, __extension__ __PRETTY_FUNCTION__ )) |
1977 | "DeclarationAttrs may only contain [[]] attributes")(static_cast <bool> (llvm::all_of(DeclarationAttrs, []( const ParsedAttr &AL) { return AL.isStandardAttributeSyntax (); }) && "DeclarationAttrs may only contain [[]] attributes" ) ? void (0) : __assert_fail ("llvm::all_of(DeclarationAttrs, [](const ParsedAttr &AL) { return AL.isStandardAttributeSyntax(); }) && \"DeclarationAttrs may only contain [[]] attributes\"" , "clang/include/clang/Sema/DeclSpec.h", 1977, __extension__ __PRETTY_FUNCTION__ )); |
1978 | } |
1979 | |
1980 | ~Declarator() { |
1981 | clear(); |
1982 | } |
1983 | /// getDeclSpec - Return the declaration-specifier that this declarator was |
1984 | /// declared with. |
1985 | const DeclSpec &getDeclSpec() const { return DS; } |
1986 | |
1987 | /// getMutableDeclSpec - Return a non-const version of the DeclSpec. This |
1988 | /// should be used with extreme care: declspecs can often be shared between |
1989 | /// multiple declarators, so mutating the DeclSpec affects all of the |
1990 | /// Declarators. This should only be done when the declspec is known to not |
1991 | /// be shared or when in error recovery etc. |
1992 | DeclSpec &getMutableDeclSpec() { return const_cast<DeclSpec &>(DS); } |
1993 | |
1994 | AttributePool &getAttributePool() const { |
1995 | return Attrs.getPool(); |
1996 | } |
1997 | |
1998 | /// getCXXScopeSpec - Return the C++ scope specifier (global scope or |
1999 | /// nested-name-specifier) that is part of the declarator-id. |
2000 | const CXXScopeSpec &getCXXScopeSpec() const { return SS; } |
2001 | CXXScopeSpec &getCXXScopeSpec() { return SS; } |
2002 | |
2003 | /// Retrieve the name specified by this declarator. |
2004 | UnqualifiedId &getName() { return Name; } |
2005 | |
2006 | const DecompositionDeclarator &getDecompositionDeclarator() const { |
2007 | return BindingGroup; |
2008 | } |
2009 | |
2010 | DeclaratorContext getContext() const { return Context; } |
2011 | |
2012 | bool isPrototypeContext() const { |
2013 | return (Context == DeclaratorContext::Prototype || |
2014 | Context == DeclaratorContext::ObjCParameter || |
2015 | Context == DeclaratorContext::ObjCResult || |
2016 | Context == DeclaratorContext::LambdaExprParameter); |
2017 | } |
2018 | |
2019 | /// Get the source range that spans this declarator. |
2020 | SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) { return Range; } |
2021 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getBegin(); } |
2022 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getEnd(); } |
2023 | |
2024 | void SetSourceRange(SourceRange R) { Range = R; } |
2025 | /// SetRangeBegin - Set the start of the source range to Loc, unless it's |
2026 | /// invalid. |
2027 | void SetRangeBegin(SourceLocation Loc) { |
2028 | if (!Loc.isInvalid()) |
2029 | Range.setBegin(Loc); |
2030 | } |
2031 | /// SetRangeEnd - Set the end of the source range to Loc, unless it's invalid. |
2032 | void SetRangeEnd(SourceLocation Loc) { |
2033 | if (!Loc.isInvalid()) |
2034 | Range.setEnd(Loc); |
2035 | } |
2036 | /// ExtendWithDeclSpec - Extend the declarator source range to include the |
2037 | /// given declspec, unless its location is invalid. Adopts the range start if |
2038 | /// the current range start is invalid. |
2039 | void ExtendWithDeclSpec(const DeclSpec &DS) { |
2040 | SourceRange SR = DS.getSourceRange(); |
2041 | if (Range.getBegin().isInvalid()) |
2042 | Range.setBegin(SR.getBegin()); |
2043 | if (!SR.getEnd().isInvalid()) |
2044 | Range.setEnd(SR.getEnd()); |
2045 | } |
2046 | |
2047 | /// Reset the contents of this Declarator. |
2048 | void clear() { |
2049 | SS.clear(); |
2050 | Name.clear(); |
2051 | Range = DS.getSourceRange(); |
2052 | BindingGroup.clear(); |
2053 | |
2054 | for (unsigned i = 0, e = DeclTypeInfo.size(); i != e; ++i) |
2055 | DeclTypeInfo[i].destroy(); |
2056 | DeclTypeInfo.clear(); |
2057 | Attrs.clear(); |
2058 | AsmLabel = nullptr; |
2059 | InlineStorageUsed = false; |
2060 | HasInitializer = false; |
2061 | ObjCIvar = false; |
2062 | ObjCWeakProperty = false; |
2063 | CommaLoc = SourceLocation(); |
2064 | EllipsisLoc = SourceLocation(); |
2065 | } |
2066 | |
2067 | /// mayOmitIdentifier - Return true if the identifier is either optional or |
2068 | /// not allowed. This is true for typenames, prototypes, and template |
2069 | /// parameter lists. |
2070 | bool mayOmitIdentifier() const { |
2071 | switch (Context) { |
2072 | case DeclaratorContext::File: |
2073 | case DeclaratorContext::KNRTypeList: |
2074 | case DeclaratorContext::Member: |
2075 | case DeclaratorContext::Block: |
2076 | case DeclaratorContext::ForInit: |
2077 | case DeclaratorContext::SelectionInit: |
2078 | case DeclaratorContext::Condition: |
2079 | return false; |
2080 | |
2081 | case DeclaratorContext::TypeName: |
2082 | case DeclaratorContext::FunctionalCast: |
2083 | case DeclaratorContext::AliasDecl: |
2084 | case DeclaratorContext::AliasTemplate: |
2085 | case DeclaratorContext::Prototype: |
2086 | case DeclaratorContext::LambdaExprParameter: |
2087 | case DeclaratorContext::ObjCParameter: |
2088 | case DeclaratorContext::ObjCResult: |
2089 | case DeclaratorContext::TemplateParam: |
2090 | case DeclaratorContext::CXXNew: |
2091 | case DeclaratorContext::CXXCatch: |
2092 | case DeclaratorContext::ObjCCatch: |
2093 | case DeclaratorContext::BlockLiteral: |
2094 | case DeclaratorContext::LambdaExpr: |
2095 | case DeclaratorContext::ConversionId: |
2096 | case DeclaratorContext::TemplateArg: |
2097 | case DeclaratorContext::TemplateTypeArg: |
2098 | case DeclaratorContext::TrailingReturn: |
2099 | case DeclaratorContext::TrailingReturnVar: |
2100 | case DeclaratorContext::RequiresExpr: |
2101 | case DeclaratorContext::Association: |
2102 | return true; |
2103 | } |
2104 | llvm_unreachable("unknown context kind!")::llvm::llvm_unreachable_internal("unknown context kind!", "clang/include/clang/Sema/DeclSpec.h" , 2104); |
2105 | } |
2106 | |
2107 | /// mayHaveIdentifier - Return true if the identifier is either optional or |
2108 | /// required. This is true for normal declarators and prototypes, but not |
2109 | /// typenames. |
2110 | bool mayHaveIdentifier() const { |
2111 | switch (Context) { |
2112 | case DeclaratorContext::File: |
2113 | case DeclaratorContext::KNRTypeList: |
2114 | case DeclaratorContext::Member: |
2115 | case DeclaratorContext::Block: |
2116 | case DeclaratorContext::ForInit: |
2117 | case DeclaratorContext::SelectionInit: |
2118 | case DeclaratorContext::Condition: |
2119 | case DeclaratorContext::Prototype: |
2120 | case DeclaratorContext::LambdaExprParameter: |
2121 | case DeclaratorContext::TemplateParam: |
2122 | case DeclaratorContext::CXXCatch: |
2123 | case DeclaratorContext::ObjCCatch: |
2124 | case DeclaratorContext::RequiresExpr: |
2125 | return true; |
2126 | |
2127 | case DeclaratorContext::TypeName: |
2128 | case DeclaratorContext::FunctionalCast: |
2129 | case DeclaratorContext::CXXNew: |
2130 | case DeclaratorContext::AliasDecl: |
2131 | case DeclaratorContext::AliasTemplate: |
2132 | case DeclaratorContext::ObjCParameter: |
2133 | case DeclaratorContext::ObjCResult: |
2134 | case DeclaratorContext::BlockLiteral: |
2135 | case DeclaratorContext::LambdaExpr: |
2136 | case DeclaratorContext::ConversionId: |
2137 | case DeclaratorContext::TemplateArg: |
2138 | case DeclaratorContext::TemplateTypeArg: |
2139 | case DeclaratorContext::TrailingReturn: |
2140 | case DeclaratorContext::TrailingReturnVar: |
2141 | case DeclaratorContext::Association: |
2142 | return false; |
2143 | } |
2144 | llvm_unreachable("unknown context kind!")::llvm::llvm_unreachable_internal("unknown context kind!", "clang/include/clang/Sema/DeclSpec.h" , 2144); |
2145 | } |
2146 | |
2147 | /// Return true if the context permits a C++17 decomposition declarator. |
2148 | bool mayHaveDecompositionDeclarator() const { |
2149 | switch (Context) { |
2150 | case DeclaratorContext::File: |
2151 | // FIXME: It's not clear that the proposal meant to allow file-scope |
2152 | // structured bindings, but it does. |
2153 | case DeclaratorContext::Block: |
2154 | case DeclaratorContext::ForInit: |
2155 | case DeclaratorContext::SelectionInit: |
2156 | case DeclaratorContext::Condition: |
2157 | return true; |
2158 | |
2159 | case DeclaratorContext::Member: |
2160 | case DeclaratorContext::Prototype: |
2161 | case DeclaratorContext::TemplateParam: |
2162 | case DeclaratorContext::RequiresExpr: |
2163 | // Maybe one day... |
2164 | return false; |
2165 | |
2166 | // These contexts don't allow any kind of non-abstract declarator. |
2167 | case DeclaratorContext::KNRTypeList: |
2168 | case DeclaratorContext::TypeName: |
2169 | case DeclaratorContext::FunctionalCast: |
2170 | case DeclaratorContext::AliasDecl: |
2171 | case DeclaratorContext::AliasTemplate: |
2172 | case DeclaratorContext::LambdaExprParameter: |
2173 | case DeclaratorContext::ObjCParameter: |
2174 | case DeclaratorContext::ObjCResult: |
2175 | case DeclaratorContext::CXXNew: |
2176 | case DeclaratorContext::CXXCatch: |
2177 | case DeclaratorContext::ObjCCatch: |
2178 | case DeclaratorContext::BlockLiteral: |
2179 | case DeclaratorContext::LambdaExpr: |
2180 | case DeclaratorContext::ConversionId: |
2181 | case DeclaratorContext::TemplateArg: |
2182 | case DeclaratorContext::TemplateTypeArg: |
2183 | case DeclaratorContext::TrailingReturn: |
2184 | case DeclaratorContext::TrailingReturnVar: |
2185 | case DeclaratorContext::Association: |
2186 | return false; |
2187 | } |
2188 | llvm_unreachable("unknown context kind!")::llvm::llvm_unreachable_internal("unknown context kind!", "clang/include/clang/Sema/DeclSpec.h" , 2188); |
2189 | } |
2190 | |
2191 | /// mayBeFollowedByCXXDirectInit - Return true if the declarator can be |
2192 | /// followed by a C++ direct initializer, e.g. "int x(1);". |
2193 | bool mayBeFollowedByCXXDirectInit() const { |
2194 | if (hasGroupingParens()) return false; |
2195 | |
2196 | if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) |
2197 | return false; |
2198 | |
2199 | if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern && |
2200 | Context != DeclaratorContext::File) |
2201 | return false; |
2202 | |
2203 | // Special names can't have direct initializers. |
2204 | if (Name.getKind() != UnqualifiedIdKind::IK_Identifier) |
2205 | return false; |
2206 | |
2207 | switch (Context) { |
2208 | case DeclaratorContext::File: |
2209 | case DeclaratorContext::Block: |
2210 | case DeclaratorContext::ForInit: |
2211 | case DeclaratorContext::SelectionInit: |
2212 | case DeclaratorContext::TrailingReturnVar: |
2213 | return true; |
2214 | |
2215 | case DeclaratorContext::Condition: |
2216 | // This may not be followed by a direct initializer, but it can't be a |
2217 | // function declaration either, and we'd prefer to perform a tentative |
2218 | // parse in order to produce the right diagnostic. |
2219 | return true; |
2220 | |
2221 | case DeclaratorContext::KNRTypeList: |
2222 | case DeclaratorContext::Member: |
2223 | case DeclaratorContext::Prototype: |
2224 | case DeclaratorContext::LambdaExprParameter: |
2225 | case DeclaratorContext::ObjCParameter: |
2226 | case DeclaratorContext::ObjCResult: |
2227 | case DeclaratorContext::TemplateParam: |
2228 | case DeclaratorContext::CXXCatch: |
2229 | case DeclaratorContext::ObjCCatch: |
2230 | case DeclaratorContext::TypeName: |
2231 | case DeclaratorContext::FunctionalCast: // FIXME |
2232 | case DeclaratorContext::CXXNew: |
2233 | case DeclaratorContext::AliasDecl: |
2234 | case DeclaratorContext::AliasTemplate: |
2235 | case DeclaratorContext::BlockLiteral: |
2236 | case DeclaratorContext::LambdaExpr: |
2237 | case DeclaratorContext::ConversionId: |
2238 | case DeclaratorContext::TemplateArg: |
2239 | case DeclaratorContext::TemplateTypeArg: |
2240 | case DeclaratorContext::TrailingReturn: |
2241 | case DeclaratorContext::RequiresExpr: |
2242 | case DeclaratorContext::Association: |
2243 | return false; |
2244 | } |
2245 | llvm_unreachable("unknown context kind!")::llvm::llvm_unreachable_internal("unknown context kind!", "clang/include/clang/Sema/DeclSpec.h" , 2245); |
2246 | } |
2247 | |
2248 | /// isPastIdentifier - Return true if we have parsed beyond the point where |
2249 | /// the name would appear. (This may happen even if we haven't actually parsed |
2250 | /// a name, perhaps because this context doesn't require one.) |
2251 | bool isPastIdentifier() const { return Name.isValid(); } |
2252 | |
2253 | /// hasName - Whether this declarator has a name, which might be an |
2254 | /// identifier (accessible via getIdentifier()) or some kind of |
2255 | /// special C++ name (constructor, destructor, etc.), or a structured |
2256 | /// binding (which is not exactly a name, but occupies the same position). |
2257 | bool hasName() const { |
2258 | return Name.getKind() != UnqualifiedIdKind::IK_Identifier || |
2259 | Name.Identifier || isDecompositionDeclarator(); |
2260 | } |
2261 | |
2262 | /// Return whether this declarator is a decomposition declarator. |
2263 | bool isDecompositionDeclarator() const { |
2264 | return BindingGroup.isSet(); |
2265 | } |
2266 | |
2267 | IdentifierInfo *getIdentifier() const { |
2268 | if (Name.getKind() == UnqualifiedIdKind::IK_Identifier) |
2269 | return Name.Identifier; |
2270 | |
2271 | return nullptr; |
2272 | } |
2273 | SourceLocation getIdentifierLoc() const { return Name.StartLocation; } |
2274 | |
2275 | /// Set the name of this declarator to be the given identifier. |
2276 | void SetIdentifier(IdentifierInfo *Id, SourceLocation IdLoc) { |
2277 | Name.setIdentifier(Id, IdLoc); |
2278 | } |
2279 | |
2280 | /// Set the decomposition bindings for this declarator. |
2281 | void |
2282 | setDecompositionBindings(SourceLocation LSquareLoc, |
2283 | ArrayRef<DecompositionDeclarator::Binding> Bindings, |
2284 | SourceLocation RSquareLoc); |
2285 | |
2286 | /// AddTypeInfo - Add a chunk to this declarator. Also extend the range to |
2287 | /// EndLoc, which should be the last token of the chunk. |
2288 | /// This function takes attrs by R-Value reference because it takes ownership |
2289 | /// of those attributes from the parameter. |
2290 | void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &&attrs, |
2291 | SourceLocation EndLoc) { |
2292 | DeclTypeInfo.push_back(TI); |
2293 | DeclTypeInfo.back().getAttrs().addAll(attrs.begin(), attrs.end()); |
2294 | getAttributePool().takeAllFrom(attrs.getPool()); |
2295 | |
2296 | if (!EndLoc.isInvalid()) |
2297 | SetRangeEnd(EndLoc); |
2298 | } |
2299 | |
2300 | /// AddTypeInfo - Add a chunk to this declarator. Also extend the range to |
2301 | /// EndLoc, which should be the last token of the chunk. |
2302 | void AddTypeInfo(const DeclaratorChunk &TI, SourceLocation EndLoc) { |
2303 | DeclTypeInfo.push_back(TI); |
2304 | |
2305 | if (!EndLoc.isInvalid()) |
2306 | SetRangeEnd(EndLoc); |
2307 | } |
2308 | |
2309 | /// Add a new innermost chunk to this declarator. |
2310 | void AddInnermostTypeInfo(const DeclaratorChunk &TI) { |
2311 | DeclTypeInfo.insert(DeclTypeInfo.begin(), TI); |
2312 | } |
2313 | |
2314 | /// Return the number of types applied to this declarator. |
2315 | unsigned getNumTypeObjects() const { return DeclTypeInfo.size(); } |
2316 | |
2317 | /// Return the specified TypeInfo from this declarator. TypeInfo #0 is |
2318 | /// closest to the identifier. |
2319 | const DeclaratorChunk &getTypeObject(unsigned i) const { |
2320 | assert(i < DeclTypeInfo.size() && "Invalid type chunk")(static_cast <bool> (i < DeclTypeInfo.size() && "Invalid type chunk") ? void (0) : __assert_fail ("i < DeclTypeInfo.size() && \"Invalid type chunk\"" , "clang/include/clang/Sema/DeclSpec.h", 2320, __extension__ __PRETTY_FUNCTION__ )); |
2321 | return DeclTypeInfo[i]; |
2322 | } |
2323 | DeclaratorChunk &getTypeObject(unsigned i) { |
2324 | assert(i < DeclTypeInfo.size() && "Invalid type chunk")(static_cast <bool> (i < DeclTypeInfo.size() && "Invalid type chunk") ? void (0) : __assert_fail ("i < DeclTypeInfo.size() && \"Invalid type chunk\"" , "clang/include/clang/Sema/DeclSpec.h", 2324, __extension__ __PRETTY_FUNCTION__ )); |
2325 | return DeclTypeInfo[i]; |
2326 | } |
2327 | |
2328 | typedef SmallVectorImpl<DeclaratorChunk>::const_iterator type_object_iterator; |
2329 | typedef llvm::iterator_range<type_object_iterator> type_object_range; |
2330 | |
2331 | /// Returns the range of type objects, from the identifier outwards. |
2332 | type_object_range type_objects() const { |
2333 | return type_object_range(DeclTypeInfo.begin(), DeclTypeInfo.end()); |
2334 | } |
2335 | |
2336 | void DropFirstTypeObject() { |
2337 | assert(!DeclTypeInfo.empty() && "No type chunks to drop.")(static_cast <bool> (!DeclTypeInfo.empty() && "No type chunks to drop." ) ? void (0) : __assert_fail ("!DeclTypeInfo.empty() && \"No type chunks to drop.\"" , "clang/include/clang/Sema/DeclSpec.h", 2337, __extension__ __PRETTY_FUNCTION__ )); |
2338 | DeclTypeInfo.front().destroy(); |
2339 | DeclTypeInfo.erase(DeclTypeInfo.begin()); |
2340 | } |
2341 | |
2342 | /// Return the innermost (closest to the declarator) chunk of this |
2343 | /// declarator that is not a parens chunk, or null if there are no |
2344 | /// non-parens chunks. |
2345 | const DeclaratorChunk *getInnermostNonParenChunk() const { |
2346 | for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) { |
2347 | if (!DeclTypeInfo[i].isParen()) |
2348 | return &DeclTypeInfo[i]; |
2349 | } |
2350 | return nullptr; |
2351 | } |
2352 | |
2353 | /// Return the outermost (furthest from the declarator) chunk of |
2354 | /// this declarator that is not a parens chunk, or null if there are |
2355 | /// no non-parens chunks. |
2356 | const DeclaratorChunk *getOutermostNonParenChunk() const { |
2357 | for (unsigned i = DeclTypeInfo.size(), i_end = 0; i != i_end; --i) { |
2358 | if (!DeclTypeInfo[i-1].isParen()) |
2359 | return &DeclTypeInfo[i-1]; |
2360 | } |
2361 | return nullptr; |
2362 | } |
2363 | |
2364 | /// isArrayOfUnknownBound - This method returns true if the declarator |
2365 | /// is a declarator for an array of unknown bound (looking through |
2366 | /// parentheses). |
2367 | bool isArrayOfUnknownBound() const { |
2368 | const DeclaratorChunk *chunk = getInnermostNonParenChunk(); |
2369 | return (chunk && chunk->Kind == DeclaratorChunk::Array && |
2370 | !chunk->Arr.NumElts); |
2371 | } |
2372 | |
2373 | /// isFunctionDeclarator - This method returns true if the declarator |
2374 | /// is a function declarator (looking through parentheses). |
2375 | /// If true is returned, then the reference type parameter idx is |
2376 | /// assigned with the index of the declaration chunk. |
2377 | bool isFunctionDeclarator(unsigned& idx) const { |
2378 | for (unsigned i = 0, i_end = DeclTypeInfo.size(); i < i_end; ++i) { |
2379 | switch (DeclTypeInfo[i].Kind) { |
2380 | case DeclaratorChunk::Function: |
2381 | idx = i; |
2382 | return true; |
2383 | case DeclaratorChunk::Paren: |
2384 | continue; |
2385 | case DeclaratorChunk::Pointer: |
2386 | case DeclaratorChunk::Reference: |
2387 | case DeclaratorChunk::Array: |
2388 | case DeclaratorChunk::BlockPointer: |
2389 | case DeclaratorChunk::MemberPointer: |
2390 | case DeclaratorChunk::Pipe: |
2391 | return false; |
2392 | } |
2393 | llvm_unreachable("Invalid type chunk")::llvm::llvm_unreachable_internal("Invalid type chunk", "clang/include/clang/Sema/DeclSpec.h" , 2393); |
2394 | } |
2395 | return false; |
2396 | } |
2397 | |
2398 | /// isFunctionDeclarator - Once this declarator is fully parsed and formed, |
2399 | /// this method returns true if the identifier is a function declarator |
2400 | /// (looking through parentheses). |
2401 | bool isFunctionDeclarator() const { |
2402 | unsigned index; |
2403 | return isFunctionDeclarator(index); |
2404 | } |
2405 | |
2406 | /// getFunctionTypeInfo - Retrieves the function type info object |
2407 | /// (looking through parentheses). |
2408 | DeclaratorChunk::FunctionTypeInfo &getFunctionTypeInfo() { |
2409 | assert(isFunctionDeclarator() && "Not a function declarator!")(static_cast <bool> (isFunctionDeclarator() && "Not a function declarator!" ) ? void (0) : __assert_fail ("isFunctionDeclarator() && \"Not a function declarator!\"" , "clang/include/clang/Sema/DeclSpec.h", 2409, __extension__ __PRETTY_FUNCTION__ )); |
2410 | unsigned index = 0; |
2411 | isFunctionDeclarator(index); |
2412 | return DeclTypeInfo[index].Fun; |
2413 | } |
2414 | |
2415 | /// getFunctionTypeInfo - Retrieves the function type info object |
2416 | /// (looking through parentheses). |
2417 | const DeclaratorChunk::FunctionTypeInfo &getFunctionTypeInfo() const { |
2418 | return const_cast<Declarator*>(this)->getFunctionTypeInfo(); |
2419 | } |
2420 | |
2421 | /// Determine whether the declaration that will be produced from |
2422 | /// this declaration will be a function. |
2423 | /// |
2424 | /// A declaration can declare a function even if the declarator itself |
2425 | /// isn't a function declarator, if the type specifier refers to a function |
2426 | /// type. This routine checks for both cases. |
2427 | bool isDeclarationOfFunction() const; |
2428 | |
2429 | /// Return true if this declaration appears in a context where a |
2430 | /// function declarator would be a function declaration. |
2431 | bool isFunctionDeclarationContext() const { |
2432 | if (getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) |
2433 | return false; |
2434 | |
2435 | switch (Context) { |
2436 | case DeclaratorContext::File: |
2437 | case DeclaratorContext::Member: |
2438 | case DeclaratorContext::Block: |
2439 | case DeclaratorContext::ForInit: |
2440 | case DeclaratorContext::SelectionInit: |
2441 | return true; |
2442 | |
2443 | case DeclaratorContext::Condition: |
2444 | case DeclaratorContext::KNRTypeList: |
2445 | case DeclaratorContext::TypeName: |
2446 | case DeclaratorContext::FunctionalCast: |
2447 | case DeclaratorContext::AliasDecl: |
2448 | case DeclaratorContext::AliasTemplate: |
2449 | case DeclaratorContext::Prototype: |
2450 | case DeclaratorContext::LambdaExprParameter: |
2451 | case DeclaratorContext::ObjCParameter: |
2452 | case DeclaratorContext::ObjCResult: |
2453 | case DeclaratorContext::TemplateParam: |
2454 | case DeclaratorContext::CXXNew: |
2455 | case DeclaratorContext::CXXCatch: |
2456 | case DeclaratorContext::ObjCCatch: |
2457 | case DeclaratorContext::BlockLiteral: |
2458 | case DeclaratorContext::LambdaExpr: |
2459 | case DeclaratorContext::ConversionId: |
2460 | case DeclaratorContext::TemplateArg: |
2461 | case DeclaratorContext::TemplateTypeArg: |
2462 | case DeclaratorContext::TrailingReturn: |
2463 | case DeclaratorContext::TrailingReturnVar: |
2464 | case DeclaratorContext::RequiresExpr: |
2465 | case DeclaratorContext::Association: |
2466 | return false; |
2467 | } |
2468 | llvm_unreachable("unknown context kind!")::llvm::llvm_unreachable_internal("unknown context kind!", "clang/include/clang/Sema/DeclSpec.h" , 2468); |
2469 | } |
2470 | |
2471 | /// Determine whether this declaration appears in a context where an |
2472 | /// expression could appear. |
2473 | bool isExpressionContext() const { |
2474 | switch (Context) { |
2475 | case DeclaratorContext::File: |
2476 | case DeclaratorContext::KNRTypeList: |
2477 | case DeclaratorContext::Member: |
2478 | |
2479 | // FIXME: sizeof(...) permits an expression. |
2480 | case DeclaratorContext::TypeName: |
2481 | |
2482 | case DeclaratorContext::FunctionalCast: |
2483 | case DeclaratorContext::AliasDecl: |
2484 | case DeclaratorContext::AliasTemplate: |
2485 | case DeclaratorContext::Prototype: |
2486 | case DeclaratorContext::LambdaExprParameter: |
2487 | case DeclaratorContext::ObjCParameter: |
2488 | case DeclaratorContext::ObjCResult: |
2489 | case DeclaratorContext::TemplateParam: |
2490 | case DeclaratorContext::CXXNew: |
2491 | case DeclaratorContext::CXXCatch: |
2492 | case DeclaratorContext::ObjCCatch: |
2493 | case DeclaratorContext::BlockLiteral: |
2494 | case DeclaratorContext::LambdaExpr: |
2495 | case DeclaratorContext::ConversionId: |
2496 | case DeclaratorContext::TrailingReturn: |
2497 | case DeclaratorContext::TrailingReturnVar: |
2498 | case DeclaratorContext::TemplateTypeArg: |
2499 | case DeclaratorContext::RequiresExpr: |
2500 | case DeclaratorContext::Association: |
2501 | return false; |
2502 | |
2503 | case DeclaratorContext::Block: |
2504 | case DeclaratorContext::ForInit: |
2505 | case DeclaratorContext::SelectionInit: |
2506 | case DeclaratorContext::Condition: |
2507 | case DeclaratorContext::TemplateArg: |
2508 | return true; |
2509 | } |
2510 | |
2511 | llvm_unreachable("unknown context kind!")::llvm::llvm_unreachable_internal("unknown context kind!", "clang/include/clang/Sema/DeclSpec.h" , 2511); |
2512 | } |
2513 | |
2514 | /// Return true if a function declarator at this position would be a |
2515 | /// function declaration. |
2516 | bool isFunctionDeclaratorAFunctionDeclaration() const { |
2517 | if (!isFunctionDeclarationContext()) |
2518 | return false; |
2519 | |
2520 | for (unsigned I = 0, N = getNumTypeObjects(); I != N; ++I) |
2521 | if (getTypeObject(I).Kind != DeclaratorChunk::Paren) |
2522 | return false; |
2523 | |
2524 | return true; |
2525 | } |
2526 | |
2527 | /// Determine whether a trailing return type was written (at any |
2528 | /// level) within this declarator. |
2529 | bool hasTrailingReturnType() const { |
2530 | for (const auto &Chunk : type_objects()) |
2531 | if (Chunk.Kind == DeclaratorChunk::Function && |
2532 | Chunk.Fun.hasTrailingReturnType()) |
2533 | return true; |
2534 | return false; |
2535 | } |
2536 | /// Get the trailing return type appearing (at any level) within this |
2537 | /// declarator. |
2538 | ParsedType getTrailingReturnType() const { |
2539 | for (const auto &Chunk : type_objects()) |
2540 | if (Chunk.Kind == DeclaratorChunk::Function && |
2541 | Chunk.Fun.hasTrailingReturnType()) |
2542 | return Chunk.Fun.getTrailingReturnType(); |
2543 | return ParsedType(); |
2544 | } |
2545 | |
2546 | /// \brief Sets a trailing requires clause for this declarator. |
2547 | void setTrailingRequiresClause(Expr *TRC) { |
2548 | TrailingRequiresClause = TRC; |
2549 | |
2550 | SetRangeEnd(TRC->getEndLoc()); |
2551 | } |
2552 | |
2553 | /// \brief Sets a trailing requires clause for this declarator. |
2554 | Expr *getTrailingRequiresClause() { |
2555 | return TrailingRequiresClause; |
2556 | } |
2557 | |
2558 | /// \brief Determine whether a trailing requires clause was written in this |
2559 | /// declarator. |
2560 | bool hasTrailingRequiresClause() const { |
2561 | return TrailingRequiresClause != nullptr; |
2562 | } |
2563 | |
2564 | /// Sets the template parameter lists that preceded the declarator. |
2565 | void setTemplateParameterLists(ArrayRef<TemplateParameterList *> TPLs) { |
2566 | TemplateParameterLists = TPLs; |
2567 | } |
2568 | |
2569 | /// The template parameter lists that preceded the declarator. |
2570 | ArrayRef<TemplateParameterList *> getTemplateParameterLists() const { |
2571 | return TemplateParameterLists; |
2572 | } |
2573 | |
2574 | /// Sets the template parameter list generated from the explicit template |
2575 | /// parameters along with any invented template parameters from |
2576 | /// placeholder-typed parameters. |
2577 | void setInventedTemplateParameterList(TemplateParameterList *Invented) { |
2578 | InventedTemplateParameterList = Invented; |
2579 | } |
2580 | |
2581 | /// The template parameter list generated from the explicit template |
2582 | /// parameters along with any invented template parameters from |
2583 | /// placeholder-typed parameters, if there were any such parameters. |
2584 | TemplateParameterList * getInventedTemplateParameterList() const { |
2585 | return InventedTemplateParameterList; |
2586 | } |
2587 | |
2588 | /// takeAttributes - Takes attributes from the given parsed-attributes |
2589 | /// set and add them to this declarator. |
2590 | /// |
2591 | /// These examples both add 3 attributes to "var": |
2592 | /// short int var __attribute__((aligned(16),common,deprecated)); |
2593 | /// short int x, __attribute__((aligned(16)) var |
2594 | /// __attribute__((common,deprecated)); |
2595 | /// |
2596 | /// Also extends the range of the declarator. |
2597 | void takeAttributes(ParsedAttributes &attrs) { |
2598 | Attrs.takeAllFrom(attrs); |
2599 | |
2600 | if (attrs.Range.getEnd().isValid()) |
2601 | SetRangeEnd(attrs.Range.getEnd()); |
2602 | } |
2603 | |
2604 | const ParsedAttributes &getAttributes() const { return Attrs; } |
2605 | ParsedAttributes &getAttributes() { return Attrs; } |
2606 | |
2607 | const ParsedAttributesView &getDeclarationAttributes() const { |
2608 | return DeclarationAttrs; |
2609 | } |
2610 | |
2611 | /// hasAttributes - do we contain any attributes? |
2612 | bool hasAttributes() const { |
2613 | if (!getAttributes().empty() || !getDeclarationAttributes().empty() || |
2614 | getDeclSpec().hasAttributes()) |
2615 | return true; |
2616 | for (unsigned i = 0, e = getNumTypeObjects(); i != e; ++i) |
2617 | if (!getTypeObject(i).getAttrs().empty()) |
2618 | return true; |
2619 | return false; |
2620 | } |
2621 | |
2622 | /// Return a source range list of C++11 attributes associated |
2623 | /// with the declarator. |
2624 | void getCXX11AttributeRanges(SmallVectorImpl<SourceRange> &Ranges) { |
2625 | for (const ParsedAttr &AL : Attrs) |
2626 | if (AL.isCXX11Attribute()) |
2627 | Ranges.push_back(AL.getRange()); |
2628 | } |
2629 | |
2630 | void setAsmLabel(Expr *E) { AsmLabel = E; } |
2631 | Expr *getAsmLabel() const { return AsmLabel; } |
2632 | |
2633 | void setExtension(bool Val = true) { Extension = Val; } |
2634 | bool getExtension() const { return Extension; } |
2635 | |
2636 | void setObjCIvar(bool Val = true) { ObjCIvar = Val; } |
2637 | bool isObjCIvar() const { return ObjCIvar; } |
2638 | |
2639 | void setObjCWeakProperty(bool Val = true) { ObjCWeakProperty = Val; } |
2640 | bool isObjCWeakProperty() const { return ObjCWeakProperty; } |
2641 | |
2642 | void setInvalidType(bool Val = true) { InvalidType = Val; } |
2643 | bool isInvalidType() const { |
2644 | return InvalidType || DS.getTypeSpecType() == DeclSpec::TST_error; |
2645 | } |
2646 | |
2647 | void setGroupingParens(bool flag) { GroupingParens = flag; } |
2648 | bool hasGroupingParens() const { return GroupingParens; } |
2649 | |
2650 | bool isFirstDeclarator() const { return !CommaLoc.isValid(); } |
2651 | SourceLocation getCommaLoc() const { return CommaLoc; } |
2652 | void setCommaLoc(SourceLocation CL) { CommaLoc = CL; } |
2653 | |
2654 | bool hasEllipsis() const { return EllipsisLoc.isValid(); } |
2655 | SourceLocation getEllipsisLoc() const { return EllipsisLoc; } |
2656 | void setEllipsisLoc(SourceLocation EL) { EllipsisLoc = EL; } |
2657 | |
2658 | void setFunctionDefinitionKind(FunctionDefinitionKind Val) { |
2659 | FunctionDefinition = static_cast<unsigned>(Val); |
2660 | } |
2661 | |
2662 | bool isFunctionDefinition() const { |
2663 | return getFunctionDefinitionKind() != FunctionDefinitionKind::Declaration; |
2664 | } |
2665 | |
2666 | FunctionDefinitionKind getFunctionDefinitionKind() const { |
2667 | return (FunctionDefinitionKind)FunctionDefinition; |
2668 | } |
2669 | |
2670 | void setHasInitializer(bool Val = true) { HasInitializer = Val; } |
2671 | bool hasInitializer() const { return HasInitializer; } |
2672 | |
2673 | /// Returns true if this declares a real member and not a friend. |
2674 | bool isFirstDeclarationOfMember() { |
2675 | return getContext() == DeclaratorContext::Member && |
2676 | !getDeclSpec().isFriendSpecified(); |
2677 | } |
2678 | |
2679 | /// Returns true if this declares a static member. This cannot be called on a |
2680 | /// declarator outside of a MemberContext because we won't know until |
2681 | /// redeclaration time if the decl is static. |
2682 | bool isStaticMember(); |
2683 | |
2684 | /// Returns true if this declares a constructor or a destructor. |
2685 | bool isCtorOrDtor(); |
2686 | |
2687 | void setRedeclaration(bool Val) { Redeclaration = Val; } |
2688 | bool isRedeclaration() const { return Redeclaration; } |
2689 | }; |
2690 | |
2691 | /// This little struct is used to capture information about |
2692 | /// structure field declarators, which is basically just a bitfield size. |
2693 | struct FieldDeclarator { |
2694 | Declarator D; |
2695 | Expr *BitfieldSize; |
2696 | explicit FieldDeclarator(const DeclSpec &DS, |
2697 | const ParsedAttributes &DeclarationAttrs) |
2698 | : D(DS, DeclarationAttrs, DeclaratorContext::Member), |
2699 | BitfieldSize(nullptr) {} |
2700 | }; |
2701 | |
2702 | /// Represents a C++11 virt-specifier-seq. |
2703 | class VirtSpecifiers { |
2704 | public: |
2705 | enum Specifier { |
2706 | VS_None = 0, |
2707 | VS_Override = 1, |
2708 | VS_Final = 2, |
2709 | VS_Sealed = 4, |
2710 | // Represents the __final keyword, which is legal for gcc in pre-C++11 mode. |
2711 | VS_GNU_Final = 8, |
2712 | VS_Abstract = 16 |
2713 | }; |
2714 | |
2715 | VirtSpecifiers() : Specifiers(0), LastSpecifier(VS_None) { } |
2716 | |
2717 | bool SetSpecifier(Specifier VS, SourceLocation Loc, |
2718 | const char *&PrevSpec); |
2719 | |
2720 | bool isUnset() const { return Specifiers == 0; } |
2721 | |
2722 | bool isOverrideSpecified() const { return Specifiers & VS_Override; } |
2723 | SourceLocation getOverrideLoc() const { return VS_overrideLoc; } |
2724 | |
2725 | bool isFinalSpecified() const { return Specifiers & (VS_Final | VS_Sealed | VS_GNU_Final); } |
2726 | bool isFinalSpelledSealed() const { return Specifiers & VS_Sealed; } |
2727 | SourceLocation getFinalLoc() const { return VS_finalLoc; } |
2728 | SourceLocation getAbstractLoc() const { return VS_abstractLoc; } |
2729 | |
2730 | void clear() { Specifiers = 0; } |
2731 | |
2732 | static const char *getSpecifierName(Specifier VS); |
2733 | |
2734 | SourceLocation getFirstLocation() const { return FirstLocation; } |
2735 | SourceLocation getLastLocation() const { return LastLocation; } |
2736 | Specifier getLastSpecifier() const { return LastSpecifier; } |
2737 | |
2738 | private: |
2739 | unsigned Specifiers; |
2740 | Specifier LastSpecifier; |
2741 | |
2742 | SourceLocation VS_overrideLoc, VS_finalLoc, VS_abstractLoc; |
2743 | SourceLocation FirstLocation; |
2744 | SourceLocation LastLocation; |
2745 | }; |
2746 | |
2747 | enum class LambdaCaptureInitKind { |
2748 | NoInit, //!< [a] |
2749 | CopyInit, //!< [a = b], [a = {b}] |
2750 | DirectInit, //!< [a(b)] |
2751 | ListInit //!< [a{b}] |
2752 | }; |
2753 | |
2754 | /// Represents a complete lambda introducer. |
2755 | struct LambdaIntroducer { |
2756 | /// An individual capture in a lambda introducer. |
2757 | struct LambdaCapture { |
2758 | LambdaCaptureKind Kind; |
2759 | SourceLocation Loc; |
2760 | IdentifierInfo *Id; |
2761 | SourceLocation EllipsisLoc; |
2762 | LambdaCaptureInitKind InitKind; |
2763 | ExprResult Init; |
2764 | ParsedType InitCaptureType; |
2765 | SourceRange ExplicitRange; |
2766 | |
2767 | LambdaCapture(LambdaCaptureKind Kind, SourceLocation Loc, |
2768 | IdentifierInfo *Id, SourceLocation EllipsisLoc, |
2769 | LambdaCaptureInitKind InitKind, ExprResult Init, |
2770 | ParsedType InitCaptureType, |
2771 | SourceRange ExplicitRange) |
2772 | : Kind(Kind), Loc(Loc), Id(Id), EllipsisLoc(EllipsisLoc), |
2773 | InitKind(InitKind), Init(Init), InitCaptureType(InitCaptureType), |
2774 | ExplicitRange(ExplicitRange) {} |
2775 | }; |
2776 | |
2777 | SourceRange Range; |
2778 | SourceLocation DefaultLoc; |
2779 | LambdaCaptureDefault Default; |
2780 | SmallVector<LambdaCapture, 4> Captures; |
2781 | |
2782 | LambdaIntroducer() |
2783 | : Default(LCD_None) {} |
2784 | |
2785 | bool hasLambdaCapture() const { |
2786 | return Captures.size() > 0 || Default != LCD_None; |
2787 | } |
2788 | |
2789 | /// Append a capture in a lambda introducer. |
2790 | void addCapture(LambdaCaptureKind Kind, |
2791 | SourceLocation Loc, |
2792 | IdentifierInfo* Id, |
2793 | SourceLocation EllipsisLoc, |
2794 | LambdaCaptureInitKind InitKind, |
2795 | ExprResult Init, |
2796 | ParsedType InitCaptureType, |
2797 | SourceRange ExplicitRange) { |
2798 | Captures.push_back(LambdaCapture(Kind, Loc, Id, EllipsisLoc, InitKind, Init, |
2799 | InitCaptureType, ExplicitRange)); |
2800 | } |
2801 | }; |
2802 | |
2803 | struct InventedTemplateParameterInfo { |
2804 | /// The number of parameters in the template parameter list that were |
2805 | /// explicitly specified by the user, as opposed to being invented by use |
2806 | /// of an auto parameter. |
2807 | unsigned NumExplicitTemplateParams = 0; |
2808 | |
2809 | /// If this is a generic lambda or abbreviated function template, use this |
2810 | /// as the depth of each 'auto' parameter, during initial AST construction. |
2811 | unsigned AutoTemplateParameterDepth = 0; |
2812 | |
2813 | /// Store the list of the template parameters for a generic lambda or an |
2814 | /// abbreviated function template. |
2815 | /// If this is a generic lambda or abbreviated function template, this holds |
2816 | /// the explicit template parameters followed by the auto parameters |
2817 | /// converted into TemplateTypeParmDecls. |
2818 | /// It can be used to construct the generic lambda or abbreviated template's |
2819 | /// template parameter list during initial AST construction. |
2820 | SmallVector<NamedDecl*, 4> TemplateParams; |
2821 | }; |
2822 | |
2823 | } // end namespace clang |
2824 | |
2825 | #endif // LLVM_CLANG_SEMA_DECLSPEC_H |
1 | //===- NestedNameSpecifier.h - C++ nested name specifiers -------*- 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 NestedNameSpecifier class, which represents | ||||||||||
10 | // a C++ nested-name-specifier. | ||||||||||
11 | // | ||||||||||
12 | //===----------------------------------------------------------------------===// | ||||||||||
13 | |||||||||||
14 | #ifndef LLVM_CLANG_AST_NESTEDNAMESPECIFIER_H | ||||||||||
15 | #define LLVM_CLANG_AST_NESTEDNAMESPECIFIER_H | ||||||||||
16 | |||||||||||
17 | #include "clang/AST/DependenceFlags.h" | ||||||||||
18 | #include "clang/Basic/Diagnostic.h" | ||||||||||
19 | #include "clang/Basic/SourceLocation.h" | ||||||||||
20 | #include "llvm/ADT/DenseMapInfo.h" | ||||||||||
21 | #include "llvm/ADT/FoldingSet.h" | ||||||||||
22 | #include "llvm/ADT/PointerIntPair.h" | ||||||||||
23 | #include "llvm/Support/Compiler.h" | ||||||||||
24 | #include <cstdint> | ||||||||||
25 | #include <cstdlib> | ||||||||||
26 | #include <utility> | ||||||||||
27 | |||||||||||
28 | namespace clang { | ||||||||||
29 | |||||||||||
30 | class ASTContext; | ||||||||||
31 | class CXXRecordDecl; | ||||||||||
32 | class IdentifierInfo; | ||||||||||
33 | class LangOptions; | ||||||||||
34 | class NamespaceAliasDecl; | ||||||||||
35 | class NamespaceDecl; | ||||||||||
36 | struct PrintingPolicy; | ||||||||||
37 | class Type; | ||||||||||
38 | class TypeLoc; | ||||||||||
39 | |||||||||||
40 | /// Represents a C++ nested name specifier, such as | ||||||||||
41 | /// "\::std::vector<int>::". | ||||||||||
42 | /// | ||||||||||
43 | /// C++ nested name specifiers are the prefixes to qualified | ||||||||||
44 | /// names. For example, "foo::" in "foo::x" is a nested name | ||||||||||
45 | /// specifier. Nested name specifiers are made up of a sequence of | ||||||||||
46 | /// specifiers, each of which can be a namespace, type, identifier | ||||||||||
47 | /// (for dependent names), decltype specifier, or the global specifier ('::'). | ||||||||||
48 | /// The last two specifiers can only appear at the start of a | ||||||||||
49 | /// nested-namespace-specifier. | ||||||||||
50 | class NestedNameSpecifier : public llvm::FoldingSetNode { | ||||||||||
51 | /// Enumeration describing | ||||||||||
52 | enum StoredSpecifierKind { | ||||||||||
53 | StoredIdentifier = 0, | ||||||||||
54 | StoredDecl = 1, | ||||||||||
55 | StoredTypeSpec = 2, | ||||||||||
56 | StoredTypeSpecWithTemplate = 3 | ||||||||||
57 | }; | ||||||||||
58 | |||||||||||
59 | /// The nested name specifier that precedes this nested name | ||||||||||
60 | /// specifier. | ||||||||||
61 | /// | ||||||||||
62 | /// The pointer is the nested-name-specifier that precedes this | ||||||||||
63 | /// one. The integer stores one of the first four values of type | ||||||||||
64 | /// SpecifierKind. | ||||||||||
65 | llvm::PointerIntPair<NestedNameSpecifier *, 2, StoredSpecifierKind> Prefix; | ||||||||||
66 | |||||||||||
67 | /// The last component in the nested name specifier, which | ||||||||||
68 | /// can be an identifier, a declaration, or a type. | ||||||||||
69 | /// | ||||||||||
70 | /// When the pointer is NULL, this specifier represents the global | ||||||||||
71 | /// specifier '::'. Otherwise, the pointer is one of | ||||||||||
72 | /// IdentifierInfo*, Namespace*, or Type*, depending on the kind of | ||||||||||
73 | /// specifier as encoded within the prefix. | ||||||||||
74 | void* Specifier = nullptr; | ||||||||||
75 | |||||||||||
76 | public: | ||||||||||
77 | /// The kind of specifier that completes this nested name | ||||||||||
78 | /// specifier. | ||||||||||
79 | enum SpecifierKind { | ||||||||||
80 | /// An identifier, stored as an IdentifierInfo*. | ||||||||||
81 | Identifier, | ||||||||||
82 | |||||||||||
83 | /// A namespace, stored as a NamespaceDecl*. | ||||||||||
84 | Namespace, | ||||||||||
85 | |||||||||||
86 | /// A namespace alias, stored as a NamespaceAliasDecl*. | ||||||||||
87 | NamespaceAlias, | ||||||||||
88 | |||||||||||
89 | /// A type, stored as a Type*. | ||||||||||
90 | TypeSpec, | ||||||||||
91 | |||||||||||
92 | /// A type that was preceded by the 'template' keyword, | ||||||||||
93 | /// stored as a Type*. | ||||||||||
94 | TypeSpecWithTemplate, | ||||||||||
95 | |||||||||||
96 | /// The global specifier '::'. There is no stored value. | ||||||||||
97 | Global, | ||||||||||
98 | |||||||||||
99 | /// Microsoft's '__super' specifier, stored as a CXXRecordDecl* of | ||||||||||
100 | /// the class it appeared in. | ||||||||||
101 | Super | ||||||||||
102 | }; | ||||||||||
103 | |||||||||||
104 | private: | ||||||||||
105 | /// Builds the global specifier. | ||||||||||
106 | NestedNameSpecifier() : Prefix(nullptr, StoredIdentifier) {} | ||||||||||
107 | |||||||||||
108 | /// Copy constructor used internally to clone nested name | ||||||||||
109 | /// specifiers. | ||||||||||
110 | NestedNameSpecifier(const NestedNameSpecifier &Other) = default; | ||||||||||
111 | |||||||||||
112 | /// Either find or insert the given nested name specifier | ||||||||||
113 | /// mockup in the given context. | ||||||||||
114 | static NestedNameSpecifier *FindOrInsert(const ASTContext &Context, | ||||||||||
115 | const NestedNameSpecifier &Mockup); | ||||||||||
116 | |||||||||||
117 | public: | ||||||||||
118 | NestedNameSpecifier &operator=(const NestedNameSpecifier &) = delete; | ||||||||||
119 | |||||||||||
120 | /// Builds a specifier combining a prefix and an identifier. | ||||||||||
121 | /// | ||||||||||
122 | /// The prefix must be dependent, since nested name specifiers | ||||||||||
123 | /// referencing an identifier are only permitted when the identifier | ||||||||||
124 | /// cannot be resolved. | ||||||||||
125 | static NestedNameSpecifier *Create(const ASTContext &Context, | ||||||||||
126 | NestedNameSpecifier *Prefix, | ||||||||||
127 | IdentifierInfo *II); | ||||||||||
128 | |||||||||||
129 | /// Builds a nested name specifier that names a namespace. | ||||||||||
130 | static NestedNameSpecifier *Create(const ASTContext &Context, | ||||||||||
131 | NestedNameSpecifier *Prefix, | ||||||||||
132 | const NamespaceDecl *NS); | ||||||||||
133 | |||||||||||
134 | /// Builds a nested name specifier that names a namespace alias. | ||||||||||
135 | static NestedNameSpecifier *Create(const ASTContext &Context, | ||||||||||
136 | NestedNameSpecifier *Prefix, | ||||||||||
137 | NamespaceAliasDecl *Alias); | ||||||||||
138 | |||||||||||
139 | /// Builds a nested name specifier that names a type. | ||||||||||
140 | static NestedNameSpecifier *Create(const ASTContext &Context, | ||||||||||
141 | NestedNameSpecifier *Prefix, | ||||||||||
142 | bool Template, const Type *T); | ||||||||||
143 | |||||||||||
144 | /// Builds a specifier that consists of just an identifier. | ||||||||||
145 | /// | ||||||||||
146 | /// The nested-name-specifier is assumed to be dependent, but has no | ||||||||||
147 | /// prefix because the prefix is implied by something outside of the | ||||||||||
148 | /// nested name specifier, e.g., in "x->Base::f", the "x" has a dependent | ||||||||||
149 | /// type. | ||||||||||
150 | static NestedNameSpecifier *Create(const ASTContext &Context, | ||||||||||
151 | IdentifierInfo *II); | ||||||||||
152 | |||||||||||
153 | /// Returns the nested name specifier representing the global | ||||||||||
154 | /// scope. | ||||||||||
155 | static NestedNameSpecifier *GlobalSpecifier(const ASTContext &Context); | ||||||||||
156 | |||||||||||
157 | /// Returns the nested name specifier representing the __super scope | ||||||||||
158 | /// for the given CXXRecordDecl. | ||||||||||
159 | static NestedNameSpecifier *SuperSpecifier(const ASTContext &Context, | ||||||||||
160 | CXXRecordDecl *RD); | ||||||||||
161 | |||||||||||
162 | /// Return the prefix of this nested name specifier. | ||||||||||
163 | /// | ||||||||||
164 | /// The prefix contains all of the parts of the nested name | ||||||||||
165 | /// specifier that precede this current specifier. For example, for a | ||||||||||
166 | /// nested name specifier that represents "foo::bar::", the current | ||||||||||
167 | /// specifier will contain "bar::" and the prefix will contain | ||||||||||
168 | /// "foo::". | ||||||||||
169 | NestedNameSpecifier *getPrefix() const { return Prefix.getPointer(); } | ||||||||||
170 | |||||||||||
171 | /// Determine what kind of nested name specifier is stored. | ||||||||||
172 | SpecifierKind getKind() const; | ||||||||||
173 | |||||||||||
174 | /// Retrieve the identifier stored in this nested name | ||||||||||
175 | /// specifier. | ||||||||||
176 | IdentifierInfo *getAsIdentifier() const { | ||||||||||
177 | if (Prefix.getInt() == StoredIdentifier) | ||||||||||
178 | return (IdentifierInfo *)Specifier; | ||||||||||
179 | |||||||||||
180 | return nullptr; | ||||||||||
181 | } | ||||||||||
182 | |||||||||||
183 | /// Retrieve the namespace stored in this nested name | ||||||||||
184 | /// specifier. | ||||||||||
185 | NamespaceDecl *getAsNamespace() const; | ||||||||||
186 | |||||||||||
187 | /// Retrieve the namespace alias stored in this nested name | ||||||||||
188 | /// specifier. | ||||||||||
189 | NamespaceAliasDecl *getAsNamespaceAlias() const; | ||||||||||
190 | |||||||||||
191 | /// Retrieve the record declaration stored in this nested name | ||||||||||
192 | /// specifier. | ||||||||||
193 | CXXRecordDecl *getAsRecordDecl() const; | ||||||||||
194 | |||||||||||
195 | /// Retrieve the type stored in this nested name specifier. | ||||||||||
196 | const Type *getAsType() const { | ||||||||||
197 | if (Prefix.getInt() == StoredTypeSpec || | ||||||||||
198 | Prefix.getInt() == StoredTypeSpecWithTemplate) | ||||||||||
199 | return (const Type *)Specifier; | ||||||||||
200 | |||||||||||
201 | return nullptr; | ||||||||||
202 | } | ||||||||||
203 | |||||||||||
204 | NestedNameSpecifierDependence getDependence() const; | ||||||||||
205 | |||||||||||
206 | /// Whether this nested name specifier refers to a dependent | ||||||||||
207 | /// type or not. | ||||||||||
208 | bool isDependent() const; | ||||||||||
209 | |||||||||||
210 | /// Whether this nested name specifier involves a template | ||||||||||
211 | /// parameter. | ||||||||||
212 | bool isInstantiationDependent() const; | ||||||||||
213 | |||||||||||
214 | /// Whether this nested-name-specifier contains an unexpanded | ||||||||||
215 | /// parameter pack (for C++11 variadic templates). | ||||||||||
216 | bool containsUnexpandedParameterPack() const; | ||||||||||
217 | |||||||||||
218 | /// Whether this nested name specifier contains an error. | ||||||||||
219 | bool containsErrors() const; | ||||||||||
220 | |||||||||||
221 | /// Print this nested name specifier to the given output stream. If | ||||||||||
222 | /// `ResolveTemplateArguments` is true, we'll print actual types, e.g. | ||||||||||
223 | /// `ns::SomeTemplate<int, MyClass>` instead of | ||||||||||
224 | /// `ns::SomeTemplate<Container::value_type, T>`. | ||||||||||
225 | void print(raw_ostream &OS, const PrintingPolicy &Policy, | ||||||||||
226 | bool ResolveTemplateArguments = false) const; | ||||||||||
227 | |||||||||||
228 | void Profile(llvm::FoldingSetNodeID &ID) const { | ||||||||||
229 | ID.AddPointer(Prefix.getOpaqueValue()); | ||||||||||
230 | ID.AddPointer(Specifier); | ||||||||||
231 | } | ||||||||||
232 | |||||||||||
233 | /// Dump the nested name specifier to standard output to aid | ||||||||||
234 | /// in debugging. | ||||||||||
235 | void dump(const LangOptions &LO) const; | ||||||||||
236 | void dump() const; | ||||||||||
237 | void dump(llvm::raw_ostream &OS) const; | ||||||||||
238 | void dump(llvm::raw_ostream &OS, const LangOptions &LO) const; | ||||||||||
239 | }; | ||||||||||
240 | |||||||||||
241 | /// A C++ nested-name-specifier augmented with source location | ||||||||||
242 | /// information. | ||||||||||
243 | class NestedNameSpecifierLoc { | ||||||||||
244 | NestedNameSpecifier *Qualifier = nullptr; | ||||||||||
245 | void *Data = nullptr; | ||||||||||
246 | |||||||||||
247 | /// Determines the data length for the last component in the | ||||||||||
248 | /// given nested-name-specifier. | ||||||||||
249 | static unsigned getLocalDataLength(NestedNameSpecifier *Qualifier); | ||||||||||
250 | |||||||||||
251 | /// Determines the data length for the entire | ||||||||||
252 | /// nested-name-specifier. | ||||||||||
253 | static unsigned getDataLength(NestedNameSpecifier *Qualifier); | ||||||||||
254 | |||||||||||
255 | public: | ||||||||||
256 | /// Construct an empty nested-name-specifier. | ||||||||||
257 | NestedNameSpecifierLoc() = default; | ||||||||||
258 | |||||||||||
259 | /// Construct a nested-name-specifier with source location information | ||||||||||
260 | /// from | ||||||||||
261 | NestedNameSpecifierLoc(NestedNameSpecifier *Qualifier, void *Data) | ||||||||||
262 | : Qualifier(Qualifier), Data(Data) {} | ||||||||||
263 | |||||||||||
264 | /// Evaluates true when this nested-name-specifier location is | ||||||||||
265 | /// non-empty. | ||||||||||
266 | explicit operator bool() const { return Qualifier; } | ||||||||||
267 | |||||||||||
268 | /// Evaluates true when this nested-name-specifier location is | ||||||||||
269 | /// empty. | ||||||||||
270 | bool hasQualifier() const { return Qualifier; } | ||||||||||
271 | |||||||||||
272 | /// Retrieve the nested-name-specifier to which this instance | ||||||||||
273 | /// refers. | ||||||||||
274 | NestedNameSpecifier *getNestedNameSpecifier() const { | ||||||||||
275 | return Qualifier; | ||||||||||
276 | } | ||||||||||
277 | |||||||||||
278 | /// Retrieve the opaque pointer that refers to source-location data. | ||||||||||
279 | void *getOpaqueData() const { return Data; } | ||||||||||
280 | |||||||||||
281 | /// Retrieve the source range covering the entirety of this | ||||||||||
282 | /// nested-name-specifier. | ||||||||||
283 | /// | ||||||||||
284 | /// For example, if this instance refers to a nested-name-specifier | ||||||||||
285 | /// \c \::std::vector<int>::, the returned source range would cover | ||||||||||
286 | /// from the initial '::' to the last '::'. | ||||||||||
287 | SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)); | ||||||||||
288 | |||||||||||
289 | /// Retrieve the source range covering just the last part of | ||||||||||
290 | /// this nested-name-specifier, not including the prefix. | ||||||||||
291 | /// | ||||||||||
292 | /// For example, if this instance refers to a nested-name-specifier | ||||||||||
293 | /// \c \::std::vector<int>::, the returned source range would cover | ||||||||||
294 | /// from "vector" to the last '::'. | ||||||||||
295 | SourceRange getLocalSourceRange() const; | ||||||||||
296 | |||||||||||
297 | /// Retrieve the location of the beginning of this | ||||||||||
298 | /// nested-name-specifier. | ||||||||||
299 | SourceLocation getBeginLoc() const { | ||||||||||
300 | return getSourceRange().getBegin(); | ||||||||||
301 | } | ||||||||||
302 | |||||||||||
303 | /// Retrieve the location of the end of this | ||||||||||
304 | /// nested-name-specifier. | ||||||||||
305 | SourceLocation getEndLoc() const { | ||||||||||
306 | return getSourceRange().getEnd(); | ||||||||||
307 | } | ||||||||||
308 | |||||||||||
309 | /// Retrieve the location of the beginning of this | ||||||||||
310 | /// component of the nested-name-specifier. | ||||||||||
311 | SourceLocation getLocalBeginLoc() const { | ||||||||||
312 | return getLocalSourceRange().getBegin(); | ||||||||||
313 | } | ||||||||||
314 | |||||||||||
315 | /// Retrieve the location of the end of this component of the | ||||||||||
316 | /// nested-name-specifier. | ||||||||||
317 | SourceLocation getLocalEndLoc() const { | ||||||||||
318 | return getLocalSourceRange().getEnd(); | ||||||||||
319 | } | ||||||||||
320 | |||||||||||
321 | /// Return the prefix of this nested-name-specifier. | ||||||||||
322 | /// | ||||||||||
323 | /// For example, if this instance refers to a nested-name-specifier | ||||||||||
324 | /// \c \::std::vector<int>::, the prefix is \c \::std::. Note that the | ||||||||||
325 | /// returned prefix may be empty, if this is the first component of | ||||||||||
326 | /// the nested-name-specifier. | ||||||||||
327 | NestedNameSpecifierLoc getPrefix() const { | ||||||||||
328 | if (!Qualifier) | ||||||||||
329 | return *this; | ||||||||||
330 | |||||||||||
331 | return NestedNameSpecifierLoc(Qualifier->getPrefix(), Data); | ||||||||||
332 | } | ||||||||||
333 | |||||||||||
334 | /// For a nested-name-specifier that refers to a type, | ||||||||||
335 | /// retrieve the type with source-location information. | ||||||||||
336 | TypeLoc getTypeLoc() const; | ||||||||||
337 | |||||||||||
338 | /// Determines the data length for the entire | ||||||||||
339 | /// nested-name-specifier. | ||||||||||
340 | unsigned getDataLength() const { return getDataLength(Qualifier); } | ||||||||||
341 | |||||||||||
342 | friend bool operator==(NestedNameSpecifierLoc X, | ||||||||||
343 | NestedNameSpecifierLoc Y) { | ||||||||||
344 | return X.Qualifier == Y.Qualifier && X.Data == Y.Data; | ||||||||||
345 | } | ||||||||||
346 | |||||||||||
347 | friend bool operator!=(NestedNameSpecifierLoc X, | ||||||||||
348 | NestedNameSpecifierLoc Y) { | ||||||||||
349 | return !(X == Y); | ||||||||||
350 | } | ||||||||||
351 | }; | ||||||||||
352 | |||||||||||
353 | /// Class that aids in the construction of nested-name-specifiers along | ||||||||||
354 | /// with source-location information for all of the components of the | ||||||||||
355 | /// nested-name-specifier. | ||||||||||
356 | class NestedNameSpecifierLocBuilder { | ||||||||||
357 | /// The current representation of the nested-name-specifier we're | ||||||||||
358 | /// building. | ||||||||||
359 | NestedNameSpecifier *Representation = nullptr; | ||||||||||
360 | |||||||||||
361 | /// Buffer used to store source-location information for the | ||||||||||
362 | /// nested-name-specifier. | ||||||||||
363 | /// | ||||||||||
364 | /// Note that we explicitly manage the buffer (rather than using a | ||||||||||
365 | /// SmallVector) because \c Declarator expects it to be possible to memcpy() | ||||||||||
366 | /// a \c CXXScopeSpec, and CXXScopeSpec uses a NestedNameSpecifierLocBuilder. | ||||||||||
367 | char *Buffer = nullptr; | ||||||||||
368 | |||||||||||
369 | /// The size of the buffer used to store source-location information | ||||||||||
370 | /// for the nested-name-specifier. | ||||||||||
371 | unsigned BufferSize = 0; | ||||||||||
372 | |||||||||||
373 | /// The capacity of the buffer used to store source-location | ||||||||||
374 | /// information for the nested-name-specifier. | ||||||||||
375 | unsigned BufferCapacity = 0; | ||||||||||
376 | |||||||||||
377 | public: | ||||||||||
378 | NestedNameSpecifierLocBuilder() = default; | ||||||||||
379 | NestedNameSpecifierLocBuilder(const NestedNameSpecifierLocBuilder &Other); | ||||||||||
380 | |||||||||||
381 | NestedNameSpecifierLocBuilder & | ||||||||||
382 | operator=(const NestedNameSpecifierLocBuilder &Other); | ||||||||||
383 | |||||||||||
384 | ~NestedNameSpecifierLocBuilder() { | ||||||||||
385 | if (BufferCapacity
| ||||||||||
386 | free(Buffer); | ||||||||||
| |||||||||||
387 | } | ||||||||||
388 | |||||||||||
389 | /// Retrieve the representation of the nested-name-specifier. | ||||||||||
390 | NestedNameSpecifier *getRepresentation() const { return Representation; } | ||||||||||
391 | |||||||||||
392 | /// Extend the current nested-name-specifier by another | ||||||||||
393 | /// nested-name-specifier component of the form 'type::'. | ||||||||||
394 | /// | ||||||||||
395 | /// \param Context The AST context in which this nested-name-specifier | ||||||||||
396 | /// resides. | ||||||||||
397 | /// | ||||||||||
398 | /// \param TemplateKWLoc The location of the 'template' keyword, if present. | ||||||||||
399 | /// | ||||||||||
400 | /// \param TL The TypeLoc that describes the type preceding the '::'. | ||||||||||
401 | /// | ||||||||||
402 | /// \param ColonColonLoc The location of the trailing '::'. | ||||||||||
403 | void Extend(ASTContext &Context, SourceLocation TemplateKWLoc, TypeLoc TL, | ||||||||||
404 | SourceLocation ColonColonLoc); | ||||||||||
405 | |||||||||||
406 | /// Extend the current nested-name-specifier by another | ||||||||||
407 | /// nested-name-specifier component of the form 'identifier::'. | ||||||||||
408 | /// | ||||||||||
409 | /// \param Context The AST context in which this nested-name-specifier | ||||||||||
410 | /// resides. | ||||||||||
411 | /// | ||||||||||
412 | /// \param Identifier The identifier. | ||||||||||
413 | /// | ||||||||||
414 | /// \param IdentifierLoc The location of the identifier. | ||||||||||
415 | /// | ||||||||||
416 | /// \param ColonColonLoc The location of the trailing '::'. | ||||||||||
417 | void Extend(ASTContext &Context, IdentifierInfo *Identifier, | ||||||||||
418 | SourceLocation IdentifierLoc, SourceLocation ColonColonLoc); | ||||||||||
419 | |||||||||||
420 | /// Extend the current nested-name-specifier by another | ||||||||||
421 | /// nested-name-specifier component of the form 'namespace::'. | ||||||||||
422 | /// | ||||||||||
423 | /// \param Context The AST context in which this nested-name-specifier | ||||||||||
424 | /// resides. | ||||||||||
425 | /// | ||||||||||
426 | /// \param Namespace The namespace. | ||||||||||
427 | /// | ||||||||||
428 | /// \param NamespaceLoc The location of the namespace name. | ||||||||||
429 | /// | ||||||||||
430 | /// \param ColonColonLoc The location of the trailing '::'. | ||||||||||
431 | void Extend(ASTContext &Context, NamespaceDecl *Namespace, | ||||||||||
432 | SourceLocation NamespaceLoc, SourceLocation ColonColonLoc); | ||||||||||
433 | |||||||||||
434 | /// Extend the current nested-name-specifier by another | ||||||||||
435 | /// nested-name-specifier component of the form 'namespace-alias::'. | ||||||||||
436 | /// | ||||||||||
437 | /// \param Context The AST context in which this nested-name-specifier | ||||||||||
438 | /// resides. | ||||||||||
439 | /// | ||||||||||
440 | /// \param Alias The namespace alias. | ||||||||||
441 | /// | ||||||||||
442 | /// \param AliasLoc The location of the namespace alias | ||||||||||
443 | /// name. | ||||||||||
444 | /// | ||||||||||
445 | /// \param ColonColonLoc The location of the trailing '::'. | ||||||||||
446 | void Extend(ASTContext &Context, NamespaceAliasDecl *Alias, | ||||||||||
447 | SourceLocation AliasLoc, SourceLocation ColonColonLoc); | ||||||||||
448 | |||||||||||
449 | /// Turn this (empty) nested-name-specifier into the global | ||||||||||
450 | /// nested-name-specifier '::'. | ||||||||||
451 | void MakeGlobal(ASTContext &Context, SourceLocation ColonColonLoc); | ||||||||||
452 | |||||||||||
453 | /// Turns this (empty) nested-name-specifier into '__super' | ||||||||||
454 | /// nested-name-specifier. | ||||||||||
455 | /// | ||||||||||
456 | /// \param Context The AST context in which this nested-name-specifier | ||||||||||
457 | /// resides. | ||||||||||
458 | /// | ||||||||||
459 | /// \param RD The declaration of the class in which nested-name-specifier | ||||||||||
460 | /// appeared. | ||||||||||
461 | /// | ||||||||||
462 | /// \param SuperLoc The location of the '__super' keyword. | ||||||||||
463 | /// name. | ||||||||||
464 | /// | ||||||||||
465 | /// \param ColonColonLoc The location of the trailing '::'. | ||||||||||
466 | void MakeSuper(ASTContext &Context, CXXRecordDecl *RD, | ||||||||||
467 | SourceLocation SuperLoc, SourceLocation ColonColonLoc); | ||||||||||
468 | |||||||||||
469 | /// Make a new nested-name-specifier from incomplete source-location | ||||||||||
470 | /// information. | ||||||||||
471 | /// | ||||||||||
472 | /// This routine should be used very, very rarely, in cases where we | ||||||||||
473 | /// need to synthesize a nested-name-specifier. Most code should instead use | ||||||||||
474 | /// \c Adopt() with a proper \c NestedNameSpecifierLoc. | ||||||||||
475 | void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, | ||||||||||
476 | SourceRange R); | ||||||||||
477 | |||||||||||
478 | /// Adopt an existing nested-name-specifier (with source-range | ||||||||||
479 | /// information). | ||||||||||
480 | void Adopt(NestedNameSpecifierLoc Other); | ||||||||||
481 | |||||||||||
482 | /// Retrieve the source range covered by this nested-name-specifier. | ||||||||||
483 | SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) { | ||||||||||
484 | return NestedNameSpecifierLoc(Representation, Buffer).getSourceRange(); | ||||||||||
485 | } | ||||||||||
486 | |||||||||||
487 | /// Retrieve a nested-name-specifier with location information, | ||||||||||
488 | /// copied into the given AST context. | ||||||||||
489 | /// | ||||||||||
490 | /// \param Context The context into which this nested-name-specifier will be | ||||||||||
491 | /// copied. | ||||||||||
492 | NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const; | ||||||||||
493 | |||||||||||
494 | /// Retrieve a nested-name-specifier with location | ||||||||||
495 | /// information based on the information in this builder. | ||||||||||
496 | /// | ||||||||||
497 | /// This loc will contain references to the builder's internal data and may | ||||||||||
498 | /// be invalidated by any change to the builder. | ||||||||||
499 | NestedNameSpecifierLoc getTemporary() const { | ||||||||||
500 | return NestedNameSpecifierLoc(Representation, Buffer); | ||||||||||
501 | } | ||||||||||
502 | |||||||||||
503 | /// Clear out this builder, and prepare it to build another | ||||||||||
504 | /// nested-name-specifier with source-location information. | ||||||||||
505 | void Clear() { | ||||||||||
506 | Representation = nullptr; | ||||||||||
507 | BufferSize = 0; | ||||||||||
508 | } | ||||||||||
509 | |||||||||||
510 | /// Retrieve the underlying buffer. | ||||||||||
511 | /// | ||||||||||
512 | /// \returns A pair containing a pointer to the buffer of source-location | ||||||||||
513 | /// data and the size of the source-location data that resides in that | ||||||||||
514 | /// buffer. | ||||||||||
515 | std::pair<char *, unsigned> getBuffer() const { | ||||||||||
516 | return std::make_pair(Buffer, BufferSize); | ||||||||||
517 | } | ||||||||||
518 | }; | ||||||||||
519 | |||||||||||
520 | /// Insertion operator for diagnostics. This allows sending | ||||||||||
521 | /// NestedNameSpecifiers into a diagnostic with <<. | ||||||||||
522 | inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB, | ||||||||||
523 | NestedNameSpecifier *NNS) { | ||||||||||
524 | DB.AddTaggedVal(reinterpret_cast<uint64_t>(NNS), | ||||||||||
525 | DiagnosticsEngine::ak_nestednamespec); | ||||||||||
526 | return DB; | ||||||||||
527 | } | ||||||||||
528 | |||||||||||
529 | } // namespace clang | ||||||||||
530 | |||||||||||
531 | namespace llvm { | ||||||||||
532 | |||||||||||
533 | template <> struct DenseMapInfo<clang::NestedNameSpecifierLoc> { | ||||||||||
534 | using FirstInfo = DenseMapInfo<clang::NestedNameSpecifier *>; | ||||||||||
535 | using SecondInfo = DenseMapInfo<void *>; | ||||||||||
536 | |||||||||||
537 | static clang::NestedNameSpecifierLoc getEmptyKey() { | ||||||||||
538 | return clang::NestedNameSpecifierLoc(FirstInfo::getEmptyKey(), | ||||||||||
539 | SecondInfo::getEmptyKey()); | ||||||||||
540 | } | ||||||||||
541 | |||||||||||
542 | static clang::NestedNameSpecifierLoc getTombstoneKey() { | ||||||||||
543 | return clang::NestedNameSpecifierLoc(FirstInfo::getTombstoneKey(), | ||||||||||
544 | SecondInfo::getTombstoneKey()); | ||||||||||
545 | } | ||||||||||
546 | |||||||||||
547 | static unsigned getHashValue(const clang::NestedNameSpecifierLoc &PairVal) { | ||||||||||
548 | return hash_combine( | ||||||||||
549 | FirstInfo::getHashValue(PairVal.getNestedNameSpecifier()), | ||||||||||
550 | SecondInfo::getHashValue(PairVal.getOpaqueData())); | ||||||||||
551 | } | ||||||||||
552 | |||||||||||
553 | static bool isEqual(const clang::NestedNameSpecifierLoc &LHS, | ||||||||||
554 | const clang::NestedNameSpecifierLoc &RHS) { | ||||||||||
555 | return LHS == RHS; | ||||||||||
556 | } | ||||||||||
557 | }; | ||||||||||
558 | } // namespace llvm | ||||||||||
559 | |||||||||||
560 | #endif // LLVM_CLANG_AST_NESTEDNAMESPECIFIER_H |