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/OperationKinds.h" |
24 | #include "clang/AST/QualTypeNames.h" |
25 | #include "clang/AST/RecursiveASTVisitor.h" |
26 | #include "clang/AST/Type.h" |
27 | #include "clang/Basic/AttributeCommonInfo.h" |
28 | #include "clang/Basic/CharInfo.h" |
29 | #include "clang/Basic/OperatorKinds.h" |
30 | #include "clang/Basic/Specifiers.h" |
31 | #include "clang/Lex/HeaderSearch.h" |
32 | #include "clang/Lex/MacroInfo.h" |
33 | #include "clang/Lex/Preprocessor.h" |
34 | #include "clang/Sema/CodeCompleteConsumer.h" |
35 | #include "clang/Sema/DeclSpec.h" |
36 | #include "clang/Sema/Designator.h" |
37 | #include "clang/Sema/Lookup.h" |
38 | #include "clang/Sema/Overload.h" |
39 | #include "clang/Sema/ParsedAttr.h" |
40 | #include "clang/Sema/ParsedTemplate.h" |
41 | #include "clang/Sema/Scope.h" |
42 | #include "clang/Sema/ScopeInfo.h" |
43 | #include "clang/Sema/Sema.h" |
44 | #include "clang/Sema/SemaInternal.h" |
45 | #include "llvm/ADT/ArrayRef.h" |
46 | #include "llvm/ADT/DenseSet.h" |
47 | #include "llvm/ADT/SmallBitVector.h" |
48 | #include "llvm/ADT/SmallPtrSet.h" |
49 | #include "llvm/ADT/SmallString.h" |
50 | #include "llvm/ADT/StringExtras.h" |
51 | #include "llvm/ADT/StringSwitch.h" |
52 | #include "llvm/ADT/Twine.h" |
53 | #include "llvm/ADT/iterator_range.h" |
54 | #include "llvm/Support/Casting.h" |
55 | #include "llvm/Support/Path.h" |
56 | #include "llvm/Support/raw_ostream.h" |
57 | |
58 | #include <list> |
59 | #include <map> |
60 | #include <optional> |
61 | #include <string> |
62 | #include <vector> |
63 | |
64 | using namespace clang; |
65 | using namespace sema; |
66 | |
67 | namespace { |
68 | /// A container of code-completion results. |
69 | class ResultBuilder { |
70 | public: |
71 | /// The type of a name-lookup filter, which can be provided to the |
72 | /// name-lookup routines to specify which declarations should be included in |
73 | /// the result set (when it returns true) and which declarations should be |
74 | /// filtered out (returns false). |
75 | typedef bool (ResultBuilder::*LookupFilter)(const NamedDecl *) const; |
76 | |
77 | typedef CodeCompletionResult Result; |
78 | |
79 | private: |
80 | /// The actual results we have found. |
81 | std::vector<Result> Results; |
82 | |
83 | /// A record of all of the declarations we have found and placed |
84 | /// into the result set, used to ensure that no declaration ever gets into |
85 | /// the result set twice. |
86 | llvm::SmallPtrSet<const Decl *, 16> AllDeclsFound; |
87 | |
88 | typedef std::pair<const NamedDecl *, unsigned> DeclIndexPair; |
89 | |
90 | /// An entry in the shadow map, which is optimized to store |
91 | /// a single (declaration, index) mapping (the common case) but |
92 | /// can also store a list of (declaration, index) mappings. |
93 | class ShadowMapEntry { |
94 | typedef SmallVector<DeclIndexPair, 4> DeclIndexPairVector; |
95 | |
96 | /// Contains either the solitary NamedDecl * or a vector |
97 | /// of (declaration, index) pairs. |
98 | llvm::PointerUnion<const NamedDecl *, DeclIndexPairVector *> DeclOrVector; |
99 | |
100 | /// When the entry contains a single declaration, this is |
101 | /// the index associated with that entry. |
102 | unsigned SingleDeclIndex = 0; |
103 | |
104 | public: |
105 | ShadowMapEntry() = default; |
106 | ShadowMapEntry(const ShadowMapEntry &) = delete; |
107 | ShadowMapEntry(ShadowMapEntry &&Move) { *this = std::move(Move); } |
108 | ShadowMapEntry &operator=(const ShadowMapEntry &) = delete; |
109 | ShadowMapEntry &operator=(ShadowMapEntry &&Move) { |
110 | SingleDeclIndex = Move.SingleDeclIndex; |
111 | DeclOrVector = Move.DeclOrVector; |
112 | Move.DeclOrVector = nullptr; |
113 | return *this; |
114 | } |
115 | |
116 | void Add(const NamedDecl *ND, unsigned Index) { |
117 | if (DeclOrVector.isNull()) { |
118 | // 0 - > 1 elements: just set the single element information. |
119 | DeclOrVector = ND; |
120 | SingleDeclIndex = Index; |
121 | return; |
122 | } |
123 | |
124 | if (const NamedDecl *PrevND = |
125 | DeclOrVector.dyn_cast<const NamedDecl *>()) { |
126 | // 1 -> 2 elements: create the vector of results and push in the |
127 | // existing declaration. |
128 | DeclIndexPairVector *Vec = new DeclIndexPairVector; |
129 | Vec->push_back(Elt: DeclIndexPair(PrevND, SingleDeclIndex)); |
130 | DeclOrVector = Vec; |
131 | } |
132 | |
133 | // Add the new element to the end of the vector. |
134 | DeclOrVector.get<DeclIndexPairVector *>()->push_back( |
135 | Elt: DeclIndexPair(ND, Index)); |
136 | } |
137 | |
138 | ~ShadowMapEntry() { |
139 | if (DeclIndexPairVector *Vec = |
140 | DeclOrVector.dyn_cast<DeclIndexPairVector *>()) { |
141 | delete Vec; |
142 | DeclOrVector = ((NamedDecl *)nullptr); |
143 | } |
144 | } |
145 | |
146 | // Iteration. |
147 | class iterator; |
148 | iterator begin() const; |
149 | iterator end() const; |
150 | }; |
151 | |
152 | /// A mapping from declaration names to the declarations that have |
153 | /// this name within a particular scope and their index within the list of |
154 | /// results. |
155 | typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap; |
156 | |
157 | /// The semantic analysis object for which results are being |
158 | /// produced. |
159 | Sema &SemaRef; |
160 | |
161 | /// The allocator used to allocate new code-completion strings. |
162 | CodeCompletionAllocator &Allocator; |
163 | |
164 | CodeCompletionTUInfo &CCTUInfo; |
165 | |
166 | /// If non-NULL, a filter function used to remove any code-completion |
167 | /// results that are not desirable. |
168 | LookupFilter Filter; |
169 | |
170 | /// Whether we should allow declarations as |
171 | /// nested-name-specifiers that would otherwise be filtered out. |
172 | bool AllowNestedNameSpecifiers; |
173 | |
174 | /// If set, the type that we would prefer our resulting value |
175 | /// declarations to have. |
176 | /// |
177 | /// Closely matching the preferred type gives a boost to a result's |
178 | /// priority. |
179 | CanQualType PreferredType; |
180 | |
181 | /// A list of shadow maps, which is used to model name hiding at |
182 | /// different levels of, e.g., the inheritance hierarchy. |
183 | std::list<ShadowMap> ShadowMaps; |
184 | |
185 | /// Overloaded C++ member functions found by SemaLookup. |
186 | /// Used to determine when one overload is dominated by another. |
187 | llvm::DenseMap<std::pair<DeclContext *, /*Name*/uintptr_t>, ShadowMapEntry> |
188 | OverloadMap; |
189 | |
190 | /// If we're potentially referring to a C++ member function, the set |
191 | /// of qualifiers applied to the object type. |
192 | Qualifiers ObjectTypeQualifiers; |
193 | /// The kind of the object expression, for rvalue/lvalue overloads. |
194 | ExprValueKind ObjectKind; |
195 | |
196 | /// Whether the \p ObjectTypeQualifiers field is active. |
197 | bool HasObjectTypeQualifiers; |
198 | |
199 | /// The selector that we prefer. |
200 | Selector PreferredSelector; |
201 | |
202 | /// The completion context in which we are gathering results. |
203 | CodeCompletionContext CompletionContext; |
204 | |
205 | /// If we are in an instance method definition, the \@implementation |
206 | /// object. |
207 | ObjCImplementationDecl *ObjCImplementation; |
208 | |
209 | void AdjustResultPriorityForDecl(Result &R); |
210 | |
211 | void MaybeAddConstructorResults(Result R); |
212 | |
213 | public: |
214 | explicit ResultBuilder(Sema &SemaRef, CodeCompletionAllocator &Allocator, |
215 | CodeCompletionTUInfo &CCTUInfo, |
216 | const CodeCompletionContext &CompletionContext, |
217 | LookupFilter Filter = nullptr) |
218 | : SemaRef(SemaRef), Allocator(Allocator), CCTUInfo(CCTUInfo), |
219 | Filter(Filter), AllowNestedNameSpecifiers(false), |
220 | HasObjectTypeQualifiers(false), CompletionContext(CompletionContext), |
221 | ObjCImplementation(nullptr) { |
222 | // If this is an Objective-C instance method definition, dig out the |
223 | // corresponding implementation. |
224 | switch (CompletionContext.getKind()) { |
225 | case CodeCompletionContext::CCC_Expression: |
226 | case CodeCompletionContext::CCC_ObjCMessageReceiver: |
227 | case CodeCompletionContext::CCC_ParenthesizedExpression: |
228 | case CodeCompletionContext::CCC_Statement: |
229 | case CodeCompletionContext::CCC_TopLevelOrExpression: |
230 | case CodeCompletionContext::CCC_Recovery: |
231 | if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) |
232 | if (Method->isInstanceMethod()) |
233 | if (ObjCInterfaceDecl *Interface = Method->getClassInterface()) |
234 | ObjCImplementation = Interface->getImplementation(); |
235 | break; |
236 | |
237 | default: |
238 | break; |
239 | } |
240 | } |
241 | |
242 | /// Determine the priority for a reference to the given declaration. |
243 | unsigned getBasePriority(const NamedDecl *D); |
244 | |
245 | /// Whether we should include code patterns in the completion |
246 | /// results. |
247 | bool includeCodePatterns() const { |
248 | return SemaRef.CodeCompleter && |
249 | SemaRef.CodeCompleter->includeCodePatterns(); |
250 | } |
251 | |
252 | /// Set the filter used for code-completion results. |
253 | void setFilter(LookupFilter Filter) { this->Filter = Filter; } |
254 | |
255 | Result *data() { return Results.empty() ? nullptr : &Results.front(); } |
256 | unsigned size() const { return Results.size(); } |
257 | bool empty() const { return Results.empty(); } |
258 | |
259 | /// Specify the preferred type. |
260 | void setPreferredType(QualType T) { |
261 | PreferredType = SemaRef.Context.getCanonicalType(T); |
262 | } |
263 | |
264 | /// Set the cv-qualifiers on the object type, for us in filtering |
265 | /// calls to member functions. |
266 | /// |
267 | /// When there are qualifiers in this set, they will be used to filter |
268 | /// out member functions that aren't available (because there will be a |
269 | /// cv-qualifier mismatch) or prefer functions with an exact qualifier |
270 | /// match. |
271 | void setObjectTypeQualifiers(Qualifiers Quals, ExprValueKind Kind) { |
272 | ObjectTypeQualifiers = Quals; |
273 | ObjectKind = Kind; |
274 | HasObjectTypeQualifiers = true; |
275 | } |
276 | |
277 | /// Set the preferred selector. |
278 | /// |
279 | /// When an Objective-C method declaration result is added, and that |
280 | /// method's selector matches this preferred selector, we give that method |
281 | /// a slight priority boost. |
282 | void setPreferredSelector(Selector Sel) { PreferredSelector = Sel; } |
283 | |
284 | /// Retrieve the code-completion context for which results are |
285 | /// being collected. |
286 | const CodeCompletionContext &getCompletionContext() const { |
287 | return CompletionContext; |
288 | } |
289 | |
290 | /// Specify whether nested-name-specifiers are allowed. |
291 | void allowNestedNameSpecifiers(bool Allow = true) { |
292 | AllowNestedNameSpecifiers = Allow; |
293 | } |
294 | |
295 | /// Return the semantic analysis object for which we are collecting |
296 | /// code completion results. |
297 | Sema &getSema() const { return SemaRef; } |
298 | |
299 | /// Retrieve the allocator used to allocate code completion strings. |
300 | CodeCompletionAllocator &getAllocator() const { return Allocator; } |
301 | |
302 | CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo; } |
303 | |
304 | /// Determine whether the given declaration is at all interesting |
305 | /// as a code-completion result. |
306 | /// |
307 | /// \param ND the declaration that we are inspecting. |
308 | /// |
309 | /// \param AsNestedNameSpecifier will be set true if this declaration is |
310 | /// only interesting when it is a nested-name-specifier. |
311 | bool isInterestingDecl(const NamedDecl *ND, |
312 | bool &AsNestedNameSpecifier) const; |
313 | |
314 | /// Decide whether or not a use of function Decl can be a call. |
315 | /// |
316 | /// \param ND the function declaration. |
317 | /// |
318 | /// \param BaseExprType the object type in a member access expression, |
319 | /// if any. |
320 | bool canFunctionBeCalled(const NamedDecl *ND, QualType BaseExprType) const; |
321 | |
322 | /// Decide whether or not a use of member function Decl can be a call. |
323 | /// |
324 | /// \param Method the function declaration. |
325 | /// |
326 | /// \param BaseExprType the object type in a member access expression, |
327 | /// if any. |
328 | bool canCxxMethodBeCalled(const CXXMethodDecl *Method, |
329 | QualType BaseExprType) const; |
330 | |
331 | /// Check whether the result is hidden by the Hiding declaration. |
332 | /// |
333 | /// \returns true if the result is hidden and cannot be found, false if |
334 | /// the hidden result could still be found. When false, \p R may be |
335 | /// modified to describe how the result can be found (e.g., via extra |
336 | /// qualification). |
337 | bool CheckHiddenResult(Result &R, DeclContext *CurContext, |
338 | const NamedDecl *Hiding); |
339 | |
340 | /// Add a new result to this result set (if it isn't already in one |
341 | /// of the shadow maps), or replace an existing result (for, e.g., a |
342 | /// redeclaration). |
343 | /// |
344 | /// \param R the result to add (if it is unique). |
345 | /// |
346 | /// \param CurContext the context in which this result will be named. |
347 | void MaybeAddResult(Result R, DeclContext *CurContext = nullptr); |
348 | |
349 | /// Add a new result to this result set, where we already know |
350 | /// the hiding declaration (if any). |
351 | /// |
352 | /// \param R the result to add (if it is unique). |
353 | /// |
354 | /// \param CurContext the context in which this result will be named. |
355 | /// |
356 | /// \param Hiding the declaration that hides the result. |
357 | /// |
358 | /// \param InBaseClass whether the result was found in a base |
359 | /// class of the searched context. |
360 | /// |
361 | /// \param BaseExprType the type of expression that precedes the "." or "->" |
362 | /// in a member access expression. |
363 | void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding, |
364 | bool InBaseClass, QualType BaseExprType); |
365 | |
366 | /// Add a new non-declaration result to this result set. |
367 | void AddResult(Result R); |
368 | |
369 | /// Enter into a new scope. |
370 | void EnterNewScope(); |
371 | |
372 | /// Exit from the current scope. |
373 | void ExitScope(); |
374 | |
375 | /// Ignore this declaration, if it is seen again. |
376 | void Ignore(const Decl *D) { AllDeclsFound.insert(Ptr: D->getCanonicalDecl()); } |
377 | |
378 | /// Add a visited context. |
379 | void addVisitedContext(DeclContext *Ctx) { |
380 | CompletionContext.addVisitedContext(Ctx); |
381 | } |
382 | |
383 | /// \name Name lookup predicates |
384 | /// |
385 | /// These predicates can be passed to the name lookup functions to filter the |
386 | /// results of name lookup. All of the predicates have the same type, so that |
387 | /// |
388 | //@{ |
389 | bool IsOrdinaryName(const NamedDecl *ND) const; |
390 | bool IsOrdinaryNonTypeName(const NamedDecl *ND) const; |
391 | bool IsIntegralConstantValue(const NamedDecl *ND) const; |
392 | bool IsOrdinaryNonValueName(const NamedDecl *ND) const; |
393 | bool IsNestedNameSpecifier(const NamedDecl *ND) const; |
394 | bool IsEnum(const NamedDecl *ND) const; |
395 | bool IsClassOrStruct(const NamedDecl *ND) const; |
396 | bool IsUnion(const NamedDecl *ND) const; |
397 | bool IsNamespace(const NamedDecl *ND) const; |
398 | bool IsNamespaceOrAlias(const NamedDecl *ND) const; |
399 | bool IsType(const NamedDecl *ND) const; |
400 | bool IsMember(const NamedDecl *ND) const; |
401 | bool IsObjCIvar(const NamedDecl *ND) const; |
402 | bool IsObjCMessageReceiver(const NamedDecl *ND) const; |
403 | bool IsObjCMessageReceiverOrLambdaCapture(const NamedDecl *ND) const; |
404 | bool IsObjCCollection(const NamedDecl *ND) const; |
405 | bool IsImpossibleToSatisfy(const NamedDecl *ND) const; |
406 | //@} |
407 | }; |
408 | } // namespace |
409 | |
410 | void PreferredTypeBuilder::enterReturn(Sema &S, SourceLocation Tok) { |
411 | if (!Enabled) |
412 | return; |
413 | if (isa<BlockDecl>(Val: S.CurContext)) { |
414 | if (sema::BlockScopeInfo *BSI = S.getCurBlock()) { |
415 | ComputeType = nullptr; |
416 | Type = BSI->ReturnType; |
417 | ExpectedLoc = Tok; |
418 | } |
419 | } else if (const auto *Function = dyn_cast<FunctionDecl>(Val: S.CurContext)) { |
420 | ComputeType = nullptr; |
421 | Type = Function->getReturnType(); |
422 | ExpectedLoc = Tok; |
423 | } else if (const auto *Method = dyn_cast<ObjCMethodDecl>(Val: S.CurContext)) { |
424 | ComputeType = nullptr; |
425 | Type = Method->getReturnType(); |
426 | ExpectedLoc = Tok; |
427 | } |
428 | } |
429 | |
430 | void PreferredTypeBuilder::enterVariableInit(SourceLocation Tok, Decl *D) { |
431 | if (!Enabled) |
432 | return; |
433 | auto *VD = llvm::dyn_cast_or_null<ValueDecl>(Val: D); |
434 | ComputeType = nullptr; |
435 | Type = VD ? VD->getType() : QualType(); |
436 | ExpectedLoc = Tok; |
437 | } |
438 | |
439 | static QualType getDesignatedType(QualType BaseType, const Designation &Desig); |
440 | |
441 | void PreferredTypeBuilder::enterDesignatedInitializer(SourceLocation Tok, |
442 | QualType BaseType, |
443 | const Designation &D) { |
444 | if (!Enabled) |
445 | return; |
446 | ComputeType = nullptr; |
447 | Type = getDesignatedType(BaseType, D); |
448 | ExpectedLoc = Tok; |
449 | } |
450 | |
451 | void PreferredTypeBuilder::enterFunctionArgument( |
452 | SourceLocation Tok, llvm::function_ref<QualType()> ComputeType) { |
453 | if (!Enabled) |
454 | return; |
455 | this->ComputeType = ComputeType; |
456 | Type = QualType(); |
457 | ExpectedLoc = Tok; |
458 | } |
459 | |
460 | void PreferredTypeBuilder::enterParenExpr(SourceLocation Tok, |
461 | SourceLocation LParLoc) { |
462 | if (!Enabled) |
463 | return; |
464 | // expected type for parenthesized expression does not change. |
465 | if (ExpectedLoc == LParLoc) |
466 | ExpectedLoc = Tok; |
467 | } |
468 | |
469 | static QualType getPreferredTypeOfBinaryRHS(Sema &S, Expr *LHS, |
470 | tok::TokenKind Op) { |
471 | if (!LHS) |
472 | return QualType(); |
473 | |
474 | QualType LHSType = LHS->getType(); |
475 | if (LHSType->isPointerType()) { |
476 | if (Op == tok::plus || Op == tok::plusequal || Op == tok::minusequal) |
477 | return S.getASTContext().getPointerDiffType(); |
478 | // Pointer difference is more common than subtracting an int from a pointer. |
479 | if (Op == tok::minus) |
480 | return LHSType; |
481 | } |
482 | |
483 | switch (Op) { |
484 | // No way to infer the type of RHS from LHS. |
485 | case tok::comma: |
486 | return QualType(); |
487 | // Prefer the type of the left operand for all of these. |
488 | // Arithmetic operations. |
489 | case tok::plus: |
490 | case tok::plusequal: |
491 | case tok::minus: |
492 | case tok::minusequal: |
493 | case tok::percent: |
494 | case tok::percentequal: |
495 | case tok::slash: |
496 | case tok::slashequal: |
497 | case tok::star: |
498 | case tok::starequal: |
499 | // Assignment. |
500 | case tok::equal: |
501 | // Comparison operators. |
502 | case tok::equalequal: |
503 | case tok::exclaimequal: |
504 | case tok::less: |
505 | case tok::lessequal: |
506 | case tok::greater: |
507 | case tok::greaterequal: |
508 | case tok::spaceship: |
509 | return LHS->getType(); |
510 | // Binary shifts are often overloaded, so don't try to guess those. |
511 | case tok::greatergreater: |
512 | case tok::greatergreaterequal: |
513 | case tok::lessless: |
514 | case tok::lesslessequal: |
515 | if (LHSType->isIntegralOrEnumerationType()) |
516 | return S.getASTContext().IntTy; |
517 | return QualType(); |
518 | // Logical operators, assume we want bool. |
519 | case tok::ampamp: |
520 | case tok::pipepipe: |
521 | case tok::caretcaret: |
522 | return S.getASTContext().BoolTy; |
523 | // Operators often used for bit manipulation are typically used with the type |
524 | // of the left argument. |
525 | case tok::pipe: |
526 | case tok::pipeequal: |
527 | case tok::caret: |
528 | case tok::caretequal: |
529 | case tok::amp: |
530 | case tok::ampequal: |
531 | if (LHSType->isIntegralOrEnumerationType()) |
532 | return LHSType; |
533 | return QualType(); |
534 | // RHS should be a pointer to a member of the 'LHS' type, but we can't give |
535 | // any particular type here. |
536 | case tok::periodstar: |
537 | case tok::arrowstar: |
538 | return QualType(); |
539 | default: |
540 | // FIXME(ibiryukov): handle the missing op, re-add the assertion. |
541 | // assert(false && "unhandled binary op"); |
542 | return QualType(); |
543 | } |
544 | } |
545 | |
546 | /// Get preferred type for an argument of an unary expression. \p ContextType is |
547 | /// preferred type of the whole unary expression. |
548 | static QualType getPreferredTypeOfUnaryArg(Sema &S, QualType ContextType, |
549 | tok::TokenKind Op) { |
550 | switch (Op) { |
551 | case tok::exclaim: |
552 | return S.getASTContext().BoolTy; |
553 | case tok::amp: |
554 | if (!ContextType.isNull() && ContextType->isPointerType()) |
555 | return ContextType->getPointeeType(); |
556 | return QualType(); |
557 | case tok::star: |
558 | if (ContextType.isNull()) |
559 | return QualType(); |
560 | return S.getASTContext().getPointerType(T: ContextType.getNonReferenceType()); |
561 | case tok::plus: |
562 | case tok::minus: |
563 | case tok::tilde: |
564 | case tok::minusminus: |
565 | case tok::plusplus: |
566 | if (ContextType.isNull()) |
567 | return S.getASTContext().IntTy; |
568 | // leave as is, these operators typically return the same type. |
569 | return ContextType; |
570 | case tok::kw___real: |
571 | case tok::kw___imag: |
572 | return QualType(); |
573 | default: |
574 | assert(false && "unhandled unary op" ); |
575 | return QualType(); |
576 | } |
577 | } |
578 | |
579 | void PreferredTypeBuilder::enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, |
580 | tok::TokenKind Op) { |
581 | if (!Enabled) |
582 | return; |
583 | ComputeType = nullptr; |
584 | Type = getPreferredTypeOfBinaryRHS(S, LHS, Op); |
585 | ExpectedLoc = Tok; |
586 | } |
587 | |
588 | void PreferredTypeBuilder::enterMemAccess(Sema &S, SourceLocation Tok, |
589 | Expr *Base) { |
590 | if (!Enabled || !Base) |
591 | return; |
592 | // Do we have expected type for Base? |
593 | if (ExpectedLoc != Base->getBeginLoc()) |
594 | return; |
595 | // Keep the expected type, only update the location. |
596 | ExpectedLoc = Tok; |
597 | } |
598 | |
599 | void PreferredTypeBuilder::enterUnary(Sema &S, SourceLocation Tok, |
600 | tok::TokenKind OpKind, |
601 | SourceLocation OpLoc) { |
602 | if (!Enabled) |
603 | return; |
604 | ComputeType = nullptr; |
605 | Type = getPreferredTypeOfUnaryArg(S, this->get(OpLoc), OpKind); |
606 | ExpectedLoc = Tok; |
607 | } |
608 | |
609 | void PreferredTypeBuilder::enterSubscript(Sema &S, SourceLocation Tok, |
610 | Expr *LHS) { |
611 | if (!Enabled) |
612 | return; |
613 | ComputeType = nullptr; |
614 | Type = S.getASTContext().IntTy; |
615 | ExpectedLoc = Tok; |
616 | } |
617 | |
618 | void PreferredTypeBuilder::enterTypeCast(SourceLocation Tok, |
619 | QualType CastType) { |
620 | if (!Enabled) |
621 | return; |
622 | ComputeType = nullptr; |
623 | Type = !CastType.isNull() ? CastType.getCanonicalType() : QualType(); |
624 | ExpectedLoc = Tok; |
625 | } |
626 | |
627 | void PreferredTypeBuilder::enterCondition(Sema &S, SourceLocation Tok) { |
628 | if (!Enabled) |
629 | return; |
630 | ComputeType = nullptr; |
631 | Type = S.getASTContext().BoolTy; |
632 | ExpectedLoc = Tok; |
633 | } |
634 | |
635 | class ResultBuilder::ShadowMapEntry::iterator { |
636 | llvm::PointerUnion<const NamedDecl *, const DeclIndexPair *> DeclOrIterator; |
637 | unsigned SingleDeclIndex; |
638 | |
639 | public: |
640 | typedef DeclIndexPair value_type; |
641 | typedef value_type reference; |
642 | typedef std::ptrdiff_t difference_type; |
643 | typedef std::input_iterator_tag iterator_category; |
644 | |
645 | class pointer { |
646 | DeclIndexPair Value; |
647 | |
648 | public: |
649 | pointer(const DeclIndexPair &Value) : Value(Value) {} |
650 | |
651 | const DeclIndexPair *operator->() const { return &Value; } |
652 | }; |
653 | |
654 | iterator() : DeclOrIterator((NamedDecl *)nullptr), SingleDeclIndex(0) {} |
655 | |
656 | iterator(const NamedDecl *SingleDecl, unsigned Index) |
657 | : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) {} |
658 | |
659 | iterator(const DeclIndexPair *Iterator) |
660 | : DeclOrIterator(Iterator), SingleDeclIndex(0) {} |
661 | |
662 | iterator &operator++() { |
663 | if (DeclOrIterator.is<const NamedDecl *>()) { |
664 | DeclOrIterator = (NamedDecl *)nullptr; |
665 | SingleDeclIndex = 0; |
666 | return *this; |
667 | } |
668 | |
669 | const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair *>(); |
670 | ++I; |
671 | DeclOrIterator = I; |
672 | return *this; |
673 | } |
674 | |
675 | /*iterator operator++(int) { |
676 | iterator tmp(*this); |
677 | ++(*this); |
678 | return tmp; |
679 | }*/ |
680 | |
681 | reference operator*() const { |
682 | if (const NamedDecl *ND = DeclOrIterator.dyn_cast<const NamedDecl *>()) |
683 | return reference(ND, SingleDeclIndex); |
684 | |
685 | return *DeclOrIterator.get<const DeclIndexPair *>(); |
686 | } |
687 | |
688 | pointer operator->() const { return pointer(**this); } |
689 | |
690 | friend bool operator==(const iterator &X, const iterator &Y) { |
691 | return X.DeclOrIterator.getOpaqueValue() == |
692 | Y.DeclOrIterator.getOpaqueValue() && |
693 | X.SingleDeclIndex == Y.SingleDeclIndex; |
694 | } |
695 | |
696 | friend bool operator!=(const iterator &X, const iterator &Y) { |
697 | return !(X == Y); |
698 | } |
699 | }; |
700 | |
701 | ResultBuilder::ShadowMapEntry::iterator |
702 | ResultBuilder::ShadowMapEntry::begin() const { |
703 | if (DeclOrVector.isNull()) |
704 | return iterator(); |
705 | |
706 | if (const NamedDecl *ND = DeclOrVector.dyn_cast<const NamedDecl *>()) |
707 | return iterator(ND, SingleDeclIndex); |
708 | |
709 | return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin()); |
710 | } |
711 | |
712 | ResultBuilder::ShadowMapEntry::iterator |
713 | ResultBuilder::ShadowMapEntry::end() const { |
714 | if (DeclOrVector.is<const NamedDecl *>() || DeclOrVector.isNull()) |
715 | return iterator(); |
716 | |
717 | return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end()); |
718 | } |
719 | |
720 | /// Compute the qualification required to get from the current context |
721 | /// (\p CurContext) to the target context (\p TargetContext). |
722 | /// |
723 | /// \param Context the AST context in which the qualification will be used. |
724 | /// |
725 | /// \param CurContext the context where an entity is being named, which is |
726 | /// typically based on the current scope. |
727 | /// |
728 | /// \param TargetContext the context in which the named entity actually |
729 | /// resides. |
730 | /// |
731 | /// \returns a nested name specifier that refers into the target context, or |
732 | /// NULL if no qualification is needed. |
733 | static NestedNameSpecifier * |
734 | getRequiredQualification(ASTContext &Context, const DeclContext *CurContext, |
735 | const DeclContext *TargetContext) { |
736 | SmallVector<const DeclContext *, 4> TargetParents; |
737 | |
738 | for (const DeclContext *CommonAncestor = TargetContext; |
739 | CommonAncestor && !CommonAncestor->Encloses(DC: CurContext); |
740 | CommonAncestor = CommonAncestor->getLookupParent()) { |
741 | if (CommonAncestor->isTransparentContext() || |
742 | CommonAncestor->isFunctionOrMethod()) |
743 | continue; |
744 | |
745 | TargetParents.push_back(Elt: CommonAncestor); |
746 | } |
747 | |
748 | NestedNameSpecifier *Result = nullptr; |
749 | while (!TargetParents.empty()) { |
750 | const DeclContext *Parent = TargetParents.pop_back_val(); |
751 | |
752 | if (const auto *Namespace = dyn_cast<NamespaceDecl>(Val: Parent)) { |
753 | if (!Namespace->getIdentifier()) |
754 | continue; |
755 | |
756 | Result = NestedNameSpecifier::Create(Context, Prefix: Result, NS: Namespace); |
757 | } else if (const auto *TD = dyn_cast<TagDecl>(Val: Parent)) |
758 | Result = NestedNameSpecifier::Create( |
759 | Context, Prefix: Result, Template: false, T: Context.getTypeDeclType(TD).getTypePtr()); |
760 | } |
761 | return Result; |
762 | } |
763 | |
764 | // Some declarations have reserved names that we don't want to ever show. |
765 | // Filter out names reserved for the implementation if they come from a |
766 | // system header. |
767 | static bool shouldIgnoreDueToReservedName(const NamedDecl *ND, Sema &SemaRef) { |
768 | // Debuggers want access to all identifiers, including reserved ones. |
769 | if (SemaRef.getLangOpts().DebuggerSupport) |
770 | return false; |
771 | |
772 | ReservedIdentifierStatus Status = ND->isReserved(LangOpts: SemaRef.getLangOpts()); |
773 | // Ignore reserved names for compiler provided decls. |
774 | if (isReservedInAllContexts(Status) && ND->getLocation().isInvalid()) |
775 | return true; |
776 | |
777 | // For system headers ignore only double-underscore names. |
778 | // This allows for system headers providing private symbols with a single |
779 | // underscore. |
780 | if (Status == ReservedIdentifierStatus::StartsWithDoubleUnderscore && |
781 | SemaRef.SourceMgr.isInSystemHeader( |
782 | Loc: SemaRef.SourceMgr.getSpellingLoc(Loc: ND->getLocation()))) |
783 | return true; |
784 | |
785 | return false; |
786 | } |
787 | |
788 | bool ResultBuilder::isInterestingDecl(const NamedDecl *ND, |
789 | bool &AsNestedNameSpecifier) const { |
790 | AsNestedNameSpecifier = false; |
791 | |
792 | auto *Named = ND; |
793 | ND = ND->getUnderlyingDecl(); |
794 | |
795 | // Skip unnamed entities. |
796 | if (!ND->getDeclName()) |
797 | return false; |
798 | |
799 | // Friend declarations and declarations introduced due to friends are never |
800 | // added as results. |
801 | if (ND->getFriendObjectKind() == Decl::FOK_Undeclared) |
802 | return false; |
803 | |
804 | // Class template (partial) specializations are never added as results. |
805 | if (isa<ClassTemplateSpecializationDecl>(Val: ND) || |
806 | isa<ClassTemplatePartialSpecializationDecl>(Val: ND)) |
807 | return false; |
808 | |
809 | // Using declarations themselves are never added as results. |
810 | if (isa<UsingDecl>(Val: ND)) |
811 | return false; |
812 | |
813 | if (shouldIgnoreDueToReservedName(ND, SemaRef)) |
814 | return false; |
815 | |
816 | if (Filter == &ResultBuilder::IsNestedNameSpecifier || |
817 | (isa<NamespaceDecl>(Val: ND) && Filter != &ResultBuilder::IsNamespace && |
818 | Filter != &ResultBuilder::IsNamespaceOrAlias && Filter != nullptr)) |
819 | AsNestedNameSpecifier = true; |
820 | |
821 | // Filter out any unwanted results. |
822 | if (Filter && !(this->*Filter)(Named)) { |
823 | // Check whether it is interesting as a nested-name-specifier. |
824 | if (AllowNestedNameSpecifiers && SemaRef.getLangOpts().CPlusPlus && |
825 | IsNestedNameSpecifier(ND) && |
826 | (Filter != &ResultBuilder::IsMember || |
827 | (isa<CXXRecordDecl>(Val: ND) && |
828 | cast<CXXRecordDecl>(Val: ND)->isInjectedClassName()))) { |
829 | AsNestedNameSpecifier = true; |
830 | return true; |
831 | } |
832 | |
833 | return false; |
834 | } |
835 | // ... then it must be interesting! |
836 | return true; |
837 | } |
838 | |
839 | bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext, |
840 | const NamedDecl *Hiding) { |
841 | // In C, there is no way to refer to a hidden name. |
842 | // FIXME: This isn't true; we can find a tag name hidden by an ordinary |
843 | // name if we introduce the tag type. |
844 | if (!SemaRef.getLangOpts().CPlusPlus) |
845 | return true; |
846 | |
847 | const DeclContext *HiddenCtx = |
848 | R.Declaration->getDeclContext()->getRedeclContext(); |
849 | |
850 | // There is no way to qualify a name declared in a function or method. |
851 | if (HiddenCtx->isFunctionOrMethod()) |
852 | return true; |
853 | |
854 | if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext()) |
855 | return true; |
856 | |
857 | // We can refer to the result with the appropriate qualification. Do it. |
858 | R.Hidden = true; |
859 | R.QualifierIsInformative = false; |
860 | |
861 | if (!R.Qualifier) |
862 | R.Qualifier = getRequiredQualification(SemaRef.Context, CurContext, |
863 | R.Declaration->getDeclContext()); |
864 | return false; |
865 | } |
866 | |
867 | /// A simplified classification of types used to determine whether two |
868 | /// types are "similar enough" when adjusting priorities. |
869 | SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) { |
870 | switch (T->getTypeClass()) { |
871 | case Type::Builtin: |
872 | switch (cast<BuiltinType>(Val&: T)->getKind()) { |
873 | case BuiltinType::Void: |
874 | return STC_Void; |
875 | |
876 | case BuiltinType::NullPtr: |
877 | return STC_Pointer; |
878 | |
879 | case BuiltinType::Overload: |
880 | case BuiltinType::Dependent: |
881 | return STC_Other; |
882 | |
883 | case BuiltinType::ObjCId: |
884 | case BuiltinType::ObjCClass: |
885 | case BuiltinType::ObjCSel: |
886 | return STC_ObjectiveC; |
887 | |
888 | default: |
889 | return STC_Arithmetic; |
890 | } |
891 | |
892 | case Type::Complex: |
893 | return STC_Arithmetic; |
894 | |
895 | case Type::Pointer: |
896 | return STC_Pointer; |
897 | |
898 | case Type::BlockPointer: |
899 | return STC_Block; |
900 | |
901 | case Type::LValueReference: |
902 | case Type::RValueReference: |
903 | return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType()); |
904 | |
905 | case Type::ConstantArray: |
906 | case Type::IncompleteArray: |
907 | case Type::VariableArray: |
908 | case Type::DependentSizedArray: |
909 | return STC_Array; |
910 | |
911 | case Type::DependentSizedExtVector: |
912 | case Type::Vector: |
913 | case Type::ExtVector: |
914 | return STC_Arithmetic; |
915 | |
916 | case Type::FunctionProto: |
917 | case Type::FunctionNoProto: |
918 | return STC_Function; |
919 | |
920 | case Type::Record: |
921 | return STC_Record; |
922 | |
923 | case Type::Enum: |
924 | return STC_Arithmetic; |
925 | |
926 | case Type::ObjCObject: |
927 | case Type::ObjCInterface: |
928 | case Type::ObjCObjectPointer: |
929 | return STC_ObjectiveC; |
930 | |
931 | default: |
932 | return STC_Other; |
933 | } |
934 | } |
935 | |
936 | /// Get the type that a given expression will have if this declaration |
937 | /// is used as an expression in its "typical" code-completion form. |
938 | QualType clang::getDeclUsageType(ASTContext &C, const NamedDecl *ND) { |
939 | ND = ND->getUnderlyingDecl(); |
940 | |
941 | if (const auto *Type = dyn_cast<TypeDecl>(Val: ND)) |
942 | return C.getTypeDeclType(Decl: Type); |
943 | if (const auto *Iface = dyn_cast<ObjCInterfaceDecl>(Val: ND)) |
944 | return C.getObjCInterfaceType(Decl: Iface); |
945 | |
946 | QualType T; |
947 | if (const FunctionDecl *Function = ND->getAsFunction()) |
948 | T = Function->getCallResultType(); |
949 | else if (const auto *Method = dyn_cast<ObjCMethodDecl>(Val: ND)) |
950 | T = Method->getSendResultType(); |
951 | else if (const auto *Enumerator = dyn_cast<EnumConstantDecl>(Val: ND)) |
952 | T = C.getTypeDeclType(Decl: cast<EnumDecl>(Enumerator->getDeclContext())); |
953 | else if (const auto *Property = dyn_cast<ObjCPropertyDecl>(Val: ND)) |
954 | T = Property->getType(); |
955 | else if (const auto *Value = dyn_cast<ValueDecl>(Val: ND)) |
956 | T = Value->getType(); |
957 | |
958 | if (T.isNull()) |
959 | return QualType(); |
960 | |
961 | // Dig through references, function pointers, and block pointers to |
962 | // get down to the likely type of an expression when the entity is |
963 | // used. |
964 | do { |
965 | if (const auto *Ref = T->getAs<ReferenceType>()) { |
966 | T = Ref->getPointeeType(); |
967 | continue; |
968 | } |
969 | |
970 | if (const auto *Pointer = T->getAs<PointerType>()) { |
971 | if (Pointer->getPointeeType()->isFunctionType()) { |
972 | T = Pointer->getPointeeType(); |
973 | continue; |
974 | } |
975 | |
976 | break; |
977 | } |
978 | |
979 | if (const auto *Block = T->getAs<BlockPointerType>()) { |
980 | T = Block->getPointeeType(); |
981 | continue; |
982 | } |
983 | |
984 | if (const auto *Function = T->getAs<FunctionType>()) { |
985 | T = Function->getReturnType(); |
986 | continue; |
987 | } |
988 | |
989 | break; |
990 | } while (true); |
991 | |
992 | return T; |
993 | } |
994 | |
995 | unsigned ResultBuilder::getBasePriority(const NamedDecl *ND) { |
996 | if (!ND) |
997 | return CCP_Unlikely; |
998 | |
999 | // Context-based decisions. |
1000 | const DeclContext *LexicalDC = ND->getLexicalDeclContext(); |
1001 | if (LexicalDC->isFunctionOrMethod()) { |
1002 | // _cmd is relatively rare |
1003 | if (const auto *ImplicitParam = dyn_cast<ImplicitParamDecl>(Val: ND)) |
1004 | if (ImplicitParam->getIdentifier() && |
1005 | ImplicitParam->getIdentifier()->isStr("_cmd" )) |
1006 | return CCP_ObjC_cmd; |
1007 | |
1008 | return CCP_LocalDeclaration; |
1009 | } |
1010 | |
1011 | const DeclContext *DC = ND->getDeclContext()->getRedeclContext(); |
1012 | if (DC->isRecord() || isa<ObjCContainerDecl>(Val: DC)) { |
1013 | // Explicit destructor calls are very rare. |
1014 | if (isa<CXXDestructorDecl>(Val: ND)) |
1015 | return CCP_Unlikely; |
1016 | // Explicit operator and conversion function calls are also very rare. |
1017 | auto DeclNameKind = ND->getDeclName().getNameKind(); |
1018 | if (DeclNameKind == DeclarationName::CXXOperatorName || |
1019 | DeclNameKind == DeclarationName::CXXLiteralOperatorName || |
1020 | DeclNameKind == DeclarationName::CXXConversionFunctionName) |
1021 | return CCP_Unlikely; |
1022 | return CCP_MemberDeclaration; |
1023 | } |
1024 | |
1025 | // Content-based decisions. |
1026 | if (isa<EnumConstantDecl>(Val: ND)) |
1027 | return CCP_Constant; |
1028 | |
1029 | // Use CCP_Type for type declarations unless we're in a statement, Objective-C |
1030 | // message receiver, or parenthesized expression context. There, it's as |
1031 | // likely that the user will want to write a type as other declarations. |
1032 | if ((isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) && |
1033 | !(CompletionContext.getKind() == CodeCompletionContext::CCC_Statement || |
1034 | CompletionContext.getKind() == |
1035 | CodeCompletionContext::CCC_ObjCMessageReceiver || |
1036 | CompletionContext.getKind() == |
1037 | CodeCompletionContext::CCC_ParenthesizedExpression)) |
1038 | return CCP_Type; |
1039 | |
1040 | return CCP_Declaration; |
1041 | } |
1042 | |
1043 | void ResultBuilder::AdjustResultPriorityForDecl(Result &R) { |
1044 | // If this is an Objective-C method declaration whose selector matches our |
1045 | // preferred selector, give it a priority boost. |
1046 | if (!PreferredSelector.isNull()) |
1047 | if (const auto *Method = dyn_cast<ObjCMethodDecl>(Val: R.Declaration)) |
1048 | if (PreferredSelector == Method->getSelector()) |
1049 | R.Priority += CCD_SelectorMatch; |
1050 | |
1051 | // If we have a preferred type, adjust the priority for results with exactly- |
1052 | // matching or nearly-matching types. |
1053 | if (!PreferredType.isNull()) { |
1054 | QualType T = getDeclUsageType(C&: SemaRef.Context, ND: R.Declaration); |
1055 | if (!T.isNull()) { |
1056 | CanQualType TC = SemaRef.Context.getCanonicalType(T); |
1057 | // Check for exactly-matching types (modulo qualifiers). |
1058 | if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC)) |
1059 | R.Priority /= CCF_ExactTypeMatch; |
1060 | // Check for nearly-matching types, based on classification of each. |
1061 | else if ((getSimplifiedTypeClass(PreferredType) == |
1062 | getSimplifiedTypeClass(TC)) && |
1063 | !(PreferredType->isEnumeralType() && TC->isEnumeralType())) |
1064 | R.Priority /= CCF_SimilarTypeMatch; |
1065 | } |
1066 | } |
1067 | } |
1068 | |
1069 | static DeclContext::lookup_result getConstructors(ASTContext &Context, |
1070 | const CXXRecordDecl *Record) { |
1071 | QualType RecordTy = Context.getTypeDeclType(Record); |
1072 | DeclarationName ConstructorName = |
1073 | Context.DeclarationNames.getCXXConstructorName( |
1074 | Ty: Context.getCanonicalType(T: RecordTy)); |
1075 | return Record->lookup(ConstructorName); |
1076 | } |
1077 | |
1078 | void ResultBuilder::MaybeAddConstructorResults(Result R) { |
1079 | if (!SemaRef.getLangOpts().CPlusPlus || !R.Declaration || |
1080 | !CompletionContext.wantConstructorResults()) |
1081 | return; |
1082 | |
1083 | const NamedDecl *D = R.Declaration; |
1084 | const CXXRecordDecl *Record = nullptr; |
1085 | if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(Val: D)) |
1086 | Record = ClassTemplate->getTemplatedDecl(); |
1087 | else if ((Record = dyn_cast<CXXRecordDecl>(Val: D))) { |
1088 | // Skip specializations and partial specializations. |
1089 | if (isa<ClassTemplateSpecializationDecl>(Val: Record)) |
1090 | return; |
1091 | } else { |
1092 | // There are no constructors here. |
1093 | return; |
1094 | } |
1095 | |
1096 | Record = Record->getDefinition(); |
1097 | if (!Record) |
1098 | return; |
1099 | |
1100 | for (NamedDecl *Ctor : getConstructors(Context&: SemaRef.Context, Record)) { |
1101 | R.Declaration = Ctor; |
1102 | R.CursorKind = getCursorKindForDecl(R.Declaration); |
1103 | Results.push_back(x: R); |
1104 | } |
1105 | } |
1106 | |
1107 | static bool isConstructor(const Decl *ND) { |
1108 | if (const auto *Tmpl = dyn_cast<FunctionTemplateDecl>(Val: ND)) |
1109 | ND = Tmpl->getTemplatedDecl(); |
1110 | return isa<CXXConstructorDecl>(Val: ND); |
1111 | } |
1112 | |
1113 | void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) { |
1114 | assert(!ShadowMaps.empty() && "Must enter into a results scope" ); |
1115 | |
1116 | if (R.Kind != Result::RK_Declaration) { |
1117 | // For non-declaration results, just add the result. |
1118 | Results.push_back(x: R); |
1119 | return; |
1120 | } |
1121 | |
1122 | // Look through using declarations. |
1123 | if (const UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(Val: R.Declaration)) { |
1124 | CodeCompletionResult Result(Using->getTargetDecl(), |
1125 | getBasePriority(ND: Using->getTargetDecl()), |
1126 | R.Qualifier, false, |
1127 | (R.Availability == CXAvailability_Available || |
1128 | R.Availability == CXAvailability_Deprecated), |
1129 | std::move(R.FixIts)); |
1130 | Result.ShadowDecl = Using; |
1131 | MaybeAddResult(R: Result, CurContext); |
1132 | return; |
1133 | } |
1134 | |
1135 | const Decl *CanonDecl = R.Declaration->getCanonicalDecl(); |
1136 | unsigned IDNS = CanonDecl->getIdentifierNamespace(); |
1137 | |
1138 | bool AsNestedNameSpecifier = false; |
1139 | if (!isInterestingDecl(ND: R.Declaration, AsNestedNameSpecifier)) |
1140 | return; |
1141 | |
1142 | // C++ constructors are never found by name lookup. |
1143 | if (isConstructor(R.Declaration)) |
1144 | return; |
1145 | |
1146 | ShadowMap &SMap = ShadowMaps.back(); |
1147 | ShadowMapEntry::iterator I, IEnd; |
1148 | ShadowMap::iterator NamePos = SMap.find(Val: R.Declaration->getDeclName()); |
1149 | if (NamePos != SMap.end()) { |
1150 | I = NamePos->second.begin(); |
1151 | IEnd = NamePos->second.end(); |
1152 | } |
1153 | |
1154 | for (; I != IEnd; ++I) { |
1155 | const NamedDecl *ND = I->first; |
1156 | unsigned Index = I->second; |
1157 | if (ND->getCanonicalDecl() == CanonDecl) { |
1158 | // This is a redeclaration. Always pick the newer declaration. |
1159 | Results[Index].Declaration = R.Declaration; |
1160 | |
1161 | // We're done. |
1162 | return; |
1163 | } |
1164 | } |
1165 | |
1166 | // This is a new declaration in this scope. However, check whether this |
1167 | // declaration name is hidden by a similarly-named declaration in an outer |
1168 | // scope. |
1169 | std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end(); |
1170 | --SMEnd; |
1171 | for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) { |
1172 | ShadowMapEntry::iterator I, IEnd; |
1173 | ShadowMap::iterator NamePos = SM->find(Val: R.Declaration->getDeclName()); |
1174 | if (NamePos != SM->end()) { |
1175 | I = NamePos->second.begin(); |
1176 | IEnd = NamePos->second.end(); |
1177 | } |
1178 | for (; I != IEnd; ++I) { |
1179 | // A tag declaration does not hide a non-tag declaration. |
1180 | if (I->first->hasTagIdentifierNamespace() && |
1181 | (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary | |
1182 | Decl::IDNS_LocalExtern | Decl::IDNS_ObjCProtocol))) |
1183 | continue; |
1184 | |
1185 | // Protocols are in distinct namespaces from everything else. |
1186 | if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol) || |
1187 | (IDNS & Decl::IDNS_ObjCProtocol)) && |
1188 | I->first->getIdentifierNamespace() != IDNS) |
1189 | continue; |
1190 | |
1191 | // The newly-added result is hidden by an entry in the shadow map. |
1192 | if (CheckHiddenResult(R, CurContext, Hiding: I->first)) |
1193 | return; |
1194 | |
1195 | break; |
1196 | } |
1197 | } |
1198 | |
1199 | // Make sure that any given declaration only shows up in the result set once. |
1200 | if (!AllDeclsFound.insert(Ptr: CanonDecl).second) |
1201 | return; |
1202 | |
1203 | // If the filter is for nested-name-specifiers, then this result starts a |
1204 | // nested-name-specifier. |
1205 | if (AsNestedNameSpecifier) { |
1206 | R.StartsNestedNameSpecifier = true; |
1207 | R.Priority = CCP_NestedNameSpecifier; |
1208 | } else |
1209 | AdjustResultPriorityForDecl(R); |
1210 | |
1211 | // If this result is supposed to have an informative qualifier, add one. |
1212 | if (R.QualifierIsInformative && !R.Qualifier && |
1213 | !R.StartsNestedNameSpecifier) { |
1214 | const DeclContext *Ctx = R.Declaration->getDeclContext(); |
1215 | if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Val: Ctx)) |
1216 | R.Qualifier = |
1217 | NestedNameSpecifier::Create(Context: SemaRef.Context, Prefix: nullptr, NS: Namespace); |
1218 | else if (const TagDecl *Tag = dyn_cast<TagDecl>(Val: Ctx)) |
1219 | R.Qualifier = NestedNameSpecifier::Create( |
1220 | Context: SemaRef.Context, Prefix: nullptr, Template: false, |
1221 | T: SemaRef.Context.getTypeDeclType(Tag).getTypePtr()); |
1222 | else |
1223 | R.QualifierIsInformative = false; |
1224 | } |
1225 | |
1226 | // Insert this result into the set of results and into the current shadow |
1227 | // map. |
1228 | SMap[R.Declaration->getDeclName()].Add(ND: R.Declaration, Index: Results.size()); |
1229 | Results.push_back(x: R); |
1230 | |
1231 | if (!AsNestedNameSpecifier) |
1232 | MaybeAddConstructorResults(R); |
1233 | } |
1234 | |
1235 | static void setInBaseClass(ResultBuilder::Result &R) { |
1236 | R.Priority += CCD_InBaseClass; |
1237 | R.InBaseClass = true; |
1238 | } |
1239 | |
1240 | enum class OverloadCompare { BothViable, Dominates, Dominated }; |
1241 | // Will Candidate ever be called on the object, when overloaded with Incumbent? |
1242 | // Returns Dominates if Candidate is always called, Dominated if Incumbent is |
1243 | // always called, BothViable if either may be called depending on arguments. |
1244 | // Precondition: must actually be overloads! |
1245 | static OverloadCompare compareOverloads(const CXXMethodDecl &Candidate, |
1246 | const CXXMethodDecl &Incumbent, |
1247 | const Qualifiers &ObjectQuals, |
1248 | ExprValueKind ObjectKind) { |
1249 | // Base/derived shadowing is handled elsewhere. |
1250 | if (Candidate.getDeclContext() != Incumbent.getDeclContext()) |
1251 | return OverloadCompare::BothViable; |
1252 | if (Candidate.isVariadic() != Incumbent.isVariadic() || |
1253 | Candidate.getNumParams() != Incumbent.getNumParams() || |
1254 | Candidate.getMinRequiredArguments() != |
1255 | Incumbent.getMinRequiredArguments()) |
1256 | return OverloadCompare::BothViable; |
1257 | for (unsigned I = 0, E = Candidate.getNumParams(); I != E; ++I) |
1258 | if (Candidate.parameters()[I]->getType().getCanonicalType() != |
1259 | Incumbent.parameters()[I]->getType().getCanonicalType()) |
1260 | return OverloadCompare::BothViable; |
1261 | if (!Candidate.specific_attrs<EnableIfAttr>().empty() || |
1262 | !Incumbent.specific_attrs<EnableIfAttr>().empty()) |
1263 | return OverloadCompare::BothViable; |
1264 | // At this point, we know calls can't pick one or the other based on |
1265 | // arguments, so one of the two must win. (Or both fail, handled elsewhere). |
1266 | RefQualifierKind CandidateRef = Candidate.getRefQualifier(); |
1267 | RefQualifierKind IncumbentRef = Incumbent.getRefQualifier(); |
1268 | if (CandidateRef != IncumbentRef) { |
1269 | // If the object kind is LValue/RValue, there's one acceptable ref-qualifier |
1270 | // and it can't be mixed with ref-unqualified overloads (in valid code). |
1271 | |
1272 | // For xvalue objects, we prefer the rvalue overload even if we have to |
1273 | // add qualifiers (which is rare, because const&& is rare). |
1274 | if (ObjectKind == clang::VK_XValue) |
1275 | return CandidateRef == RQ_RValue ? OverloadCompare::Dominates |
1276 | : OverloadCompare::Dominated; |
1277 | } |
1278 | // Now the ref qualifiers are the same (or we're in some invalid state). |
1279 | // So make some decision based on the qualifiers. |
1280 | Qualifiers CandidateQual = Candidate.getMethodQualifiers(); |
1281 | Qualifiers IncumbentQual = Incumbent.getMethodQualifiers(); |
1282 | bool CandidateSuperset = CandidateQual.compatiblyIncludes(other: IncumbentQual); |
1283 | bool IncumbentSuperset = IncumbentQual.compatiblyIncludes(other: CandidateQual); |
1284 | if (CandidateSuperset == IncumbentSuperset) |
1285 | return OverloadCompare::BothViable; |
1286 | return IncumbentSuperset ? OverloadCompare::Dominates |
1287 | : OverloadCompare::Dominated; |
1288 | } |
1289 | |
1290 | bool ResultBuilder::canCxxMethodBeCalled(const CXXMethodDecl *Method, |
1291 | QualType BaseExprType) const { |
1292 | // Find the class scope that we're currently in. |
1293 | // We could e.g. be inside a lambda, so walk up the DeclContext until we |
1294 | // find a CXXMethodDecl. |
1295 | DeclContext *CurContext = SemaRef.CurContext; |
1296 | const auto *CurrentClassScope = [&]() -> const CXXRecordDecl * { |
1297 | for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getParent()) { |
1298 | const auto *CtxMethod = llvm::dyn_cast<CXXMethodDecl>(Val: Ctx); |
1299 | if (CtxMethod && !CtxMethod->getParent()->isLambda()) { |
1300 | return CtxMethod->getParent(); |
1301 | } |
1302 | } |
1303 | return nullptr; |
1304 | }(); |
1305 | |
1306 | // If we're not inside the scope of the method's class, it can't be a call. |
1307 | bool FunctionCanBeCall = |
1308 | CurrentClassScope && |
1309 | (CurrentClassScope == Method->getParent() || |
1310 | CurrentClassScope->isDerivedFrom(Base: Method->getParent())); |
1311 | |
1312 | // We skip the following calculation for exceptions if it's already true. |
1313 | if (FunctionCanBeCall) |
1314 | return true; |
1315 | |
1316 | // Exception: foo->FooBase::bar() or foo->Foo::bar() *is* a call. |
1317 | if (const CXXRecordDecl *MaybeDerived = |
1318 | BaseExprType.isNull() ? nullptr |
1319 | : BaseExprType->getAsCXXRecordDecl()) { |
1320 | auto *MaybeBase = Method->getParent(); |
1321 | FunctionCanBeCall = |
1322 | MaybeDerived == MaybeBase || MaybeDerived->isDerivedFrom(Base: MaybeBase); |
1323 | } |
1324 | |
1325 | return FunctionCanBeCall; |
1326 | } |
1327 | |
1328 | bool ResultBuilder::canFunctionBeCalled(const NamedDecl *ND, |
1329 | QualType BaseExprType) const { |
1330 | // We apply heuristics only to CCC_Symbol: |
1331 | // * CCC_{Arrow,Dot}MemberAccess reflect member access expressions: |
1332 | // f.method() and f->method(). These are always calls. |
1333 | // * A qualified name to a member function may *not* be a call. We have to |
1334 | // subdivide the cases: For example, f.Base::method(), which is regarded as |
1335 | // CCC_Symbol, should be a call. |
1336 | // * Non-member functions and static member functions are always considered |
1337 | // calls. |
1338 | if (CompletionContext.getKind() == clang::CodeCompletionContext::CCC_Symbol) { |
1339 | if (const auto *FuncTmpl = dyn_cast<FunctionTemplateDecl>(Val: ND)) { |
1340 | ND = FuncTmpl->getTemplatedDecl(); |
1341 | } |
1342 | const auto *Method = dyn_cast<CXXMethodDecl>(Val: ND); |
1343 | if (Method && !Method->isStatic()) { |
1344 | return canCxxMethodBeCalled(Method, BaseExprType); |
1345 | } |
1346 | } |
1347 | return true; |
1348 | } |
1349 | |
1350 | void ResultBuilder::AddResult(Result R, DeclContext *CurContext, |
1351 | NamedDecl *Hiding, bool InBaseClass = false, |
1352 | QualType BaseExprType = QualType()) { |
1353 | if (R.Kind != Result::RK_Declaration) { |
1354 | // For non-declaration results, just add the result. |
1355 | Results.push_back(x: R); |
1356 | return; |
1357 | } |
1358 | |
1359 | // Look through using declarations. |
1360 | if (const auto *Using = dyn_cast<UsingShadowDecl>(Val: R.Declaration)) { |
1361 | CodeCompletionResult Result(Using->getTargetDecl(), |
1362 | getBasePriority(ND: Using->getTargetDecl()), |
1363 | R.Qualifier, false, |
1364 | (R.Availability == CXAvailability_Available || |
1365 | R.Availability == CXAvailability_Deprecated), |
1366 | std::move(R.FixIts)); |
1367 | Result.ShadowDecl = Using; |
1368 | AddResult(R: Result, CurContext, Hiding, /*InBaseClass=*/false, |
1369 | /*BaseExprType=*/BaseExprType); |
1370 | return; |
1371 | } |
1372 | |
1373 | bool AsNestedNameSpecifier = false; |
1374 | if (!isInterestingDecl(ND: R.Declaration, AsNestedNameSpecifier)) |
1375 | return; |
1376 | |
1377 | // C++ constructors are never found by name lookup. |
1378 | if (isConstructor(R.Declaration)) |
1379 | return; |
1380 | |
1381 | if (Hiding && CheckHiddenResult(R, CurContext, Hiding)) |
1382 | return; |
1383 | |
1384 | // Make sure that any given declaration only shows up in the result set once. |
1385 | if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()).second) |
1386 | return; |
1387 | |
1388 | // If the filter is for nested-name-specifiers, then this result starts a |
1389 | // nested-name-specifier. |
1390 | if (AsNestedNameSpecifier) { |
1391 | R.StartsNestedNameSpecifier = true; |
1392 | R.Priority = CCP_NestedNameSpecifier; |
1393 | } else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && |
1394 | InBaseClass && |
1395 | isa<CXXRecordDecl>( |
1396 | R.Declaration->getDeclContext()->getRedeclContext())) |
1397 | R.QualifierIsInformative = true; |
1398 | |
1399 | // If this result is supposed to have an informative qualifier, add one. |
1400 | if (R.QualifierIsInformative && !R.Qualifier && |
1401 | !R.StartsNestedNameSpecifier) { |
1402 | const DeclContext *Ctx = R.Declaration->getDeclContext(); |
1403 | if (const auto *Namespace = dyn_cast<NamespaceDecl>(Ctx)) |
1404 | R.Qualifier = |
1405 | NestedNameSpecifier::Create(SemaRef.Context, nullptr, Namespace); |
1406 | else if (const auto *Tag = dyn_cast<TagDecl>(Ctx)) |
1407 | R.Qualifier = NestedNameSpecifier::Create( |
1408 | SemaRef.Context, nullptr, false, |
1409 | SemaRef.Context.getTypeDeclType(Decl: Tag).getTypePtr()); |
1410 | else |
1411 | R.QualifierIsInformative = false; |
1412 | } |
1413 | |
1414 | // Adjust the priority if this result comes from a base class. |
1415 | if (InBaseClass) |
1416 | setInBaseClass(R); |
1417 | |
1418 | AdjustResultPriorityForDecl(R); |
1419 | |
1420 | if (HasObjectTypeQualifiers) |
1421 | if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: R.Declaration)) |
1422 | if (Method->isInstance()) { |
1423 | Qualifiers MethodQuals = Method->getMethodQualifiers(); |
1424 | if (ObjectTypeQualifiers == MethodQuals) |
1425 | R.Priority += CCD_ObjectQualifierMatch; |
1426 | else if (ObjectTypeQualifiers - MethodQuals) { |
1427 | // The method cannot be invoked, because doing so would drop |
1428 | // qualifiers. |
1429 | return; |
1430 | } |
1431 | // Detect cases where a ref-qualified method cannot be invoked. |
1432 | switch (Method->getRefQualifier()) { |
1433 | case RQ_LValue: |
1434 | if (ObjectKind != VK_LValue && !MethodQuals.hasConst()) |
1435 | return; |
1436 | break; |
1437 | case RQ_RValue: |
1438 | if (ObjectKind == VK_LValue) |
1439 | return; |
1440 | break; |
1441 | case RQ_None: |
1442 | break; |
1443 | } |
1444 | |
1445 | /// Check whether this dominates another overloaded method, which should |
1446 | /// be suppressed (or vice versa). |
1447 | /// Motivating case is const_iterator begin() const vs iterator begin(). |
1448 | auto &OverloadSet = OverloadMap[std::make_pair( |
1449 | CurContext, Method->getDeclName().getAsOpaqueInteger())]; |
1450 | for (const DeclIndexPair Entry : OverloadSet) { |
1451 | Result &Incumbent = Results[Entry.second]; |
1452 | switch (compareOverloads(*Method, |
1453 | *cast<CXXMethodDecl>(Incumbent.Declaration), |
1454 | ObjectTypeQualifiers, ObjectKind)) { |
1455 | case OverloadCompare::Dominates: |
1456 | // Replace the dominated overload with this one. |
1457 | // FIXME: if the overload dominates multiple incumbents then we |
1458 | // should remove all. But two overloads is by far the common case. |
1459 | Incumbent = std::move(R); |
1460 | return; |
1461 | case OverloadCompare::Dominated: |
1462 | // This overload can't be called, drop it. |
1463 | return; |
1464 | case OverloadCompare::BothViable: |
1465 | break; |
1466 | } |
1467 | } |
1468 | OverloadSet.Add(Method, Results.size()); |
1469 | } |
1470 | |
1471 | R.FunctionCanBeCall = canFunctionBeCalled(ND: R.getDeclaration(), BaseExprType); |
1472 | |
1473 | // Insert this result into the set of results. |
1474 | Results.push_back(x: R); |
1475 | |
1476 | if (!AsNestedNameSpecifier) |
1477 | MaybeAddConstructorResults(R); |
1478 | } |
1479 | |
1480 | void ResultBuilder::AddResult(Result R) { |
1481 | assert(R.Kind != Result::RK_Declaration && |
1482 | "Declaration results need more context" ); |
1483 | Results.push_back(x: R); |
1484 | } |
1485 | |
1486 | /// Enter into a new scope. |
1487 | void ResultBuilder::EnterNewScope() { ShadowMaps.emplace_back(); } |
1488 | |
1489 | /// Exit from the current scope. |
1490 | void ResultBuilder::ExitScope() { |
1491 | ShadowMaps.pop_back(); |
1492 | } |
1493 | |
1494 | /// Determines whether this given declaration will be found by |
1495 | /// ordinary name lookup. |
1496 | bool ResultBuilder::IsOrdinaryName(const NamedDecl *ND) const { |
1497 | ND = ND->getUnderlyingDecl(); |
1498 | |
1499 | // If name lookup finds a local extern declaration, then we are in a |
1500 | // context where it behaves like an ordinary name. |
1501 | unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern; |
1502 | if (SemaRef.getLangOpts().CPlusPlus) |
1503 | IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member; |
1504 | else if (SemaRef.getLangOpts().ObjC) { |
1505 | if (isa<ObjCIvarDecl>(Val: ND)) |
1506 | return true; |
1507 | } |
1508 | |
1509 | return ND->getIdentifierNamespace() & IDNS; |
1510 | } |
1511 | |
1512 | /// Determines whether this given declaration will be found by |
1513 | /// ordinary name lookup but is not a type name. |
1514 | bool ResultBuilder::IsOrdinaryNonTypeName(const NamedDecl *ND) const { |
1515 | ND = ND->getUnderlyingDecl(); |
1516 | if (isa<TypeDecl>(Val: ND)) |
1517 | return false; |
1518 | // Objective-C interfaces names are not filtered by this method because they |
1519 | // can be used in a class property expression. We can still filter out |
1520 | // @class declarations though. |
1521 | if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(Val: ND)) { |
1522 | if (!ID->getDefinition()) |
1523 | return false; |
1524 | } |
1525 | |
1526 | unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern; |
1527 | if (SemaRef.getLangOpts().CPlusPlus) |
1528 | IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member; |
1529 | else if (SemaRef.getLangOpts().ObjC) { |
1530 | if (isa<ObjCIvarDecl>(Val: ND)) |
1531 | return true; |
1532 | } |
1533 | |
1534 | return ND->getIdentifierNamespace() & IDNS; |
1535 | } |
1536 | |
1537 | bool ResultBuilder::IsIntegralConstantValue(const NamedDecl *ND) const { |
1538 | if (!IsOrdinaryNonTypeName(ND)) |
1539 | return false; |
1540 | |
1541 | if (const auto *VD = dyn_cast<ValueDecl>(Val: ND->getUnderlyingDecl())) |
1542 | if (VD->getType()->isIntegralOrEnumerationType()) |
1543 | return true; |
1544 | |
1545 | return false; |
1546 | } |
1547 | |
1548 | /// Determines whether this given declaration will be found by |
1549 | /// ordinary name lookup. |
1550 | bool ResultBuilder::IsOrdinaryNonValueName(const NamedDecl *ND) const { |
1551 | ND = ND->getUnderlyingDecl(); |
1552 | |
1553 | unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern; |
1554 | if (SemaRef.getLangOpts().CPlusPlus) |
1555 | IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace; |
1556 | |
1557 | return (ND->getIdentifierNamespace() & IDNS) && !isa<ValueDecl>(Val: ND) && |
1558 | !isa<FunctionTemplateDecl>(Val: ND) && !isa<ObjCPropertyDecl>(Val: ND); |
1559 | } |
1560 | |
1561 | /// Determines whether the given declaration is suitable as the |
1562 | /// start of a C++ nested-name-specifier, e.g., a class or namespace. |
1563 | bool ResultBuilder::IsNestedNameSpecifier(const NamedDecl *ND) const { |
1564 | // Allow us to find class templates, too. |
1565 | if (const auto *ClassTemplate = dyn_cast<ClassTemplateDecl>(Val: ND)) |
1566 | ND = ClassTemplate->getTemplatedDecl(); |
1567 | |
1568 | return SemaRef.isAcceptableNestedNameSpecifier(SD: ND); |
1569 | } |
1570 | |
1571 | /// Determines whether the given declaration is an enumeration. |
1572 | bool ResultBuilder::IsEnum(const NamedDecl *ND) const { |
1573 | return isa<EnumDecl>(Val: ND); |
1574 | } |
1575 | |
1576 | /// Determines whether the given declaration is a class or struct. |
1577 | bool ResultBuilder::IsClassOrStruct(const NamedDecl *ND) const { |
1578 | // Allow us to find class templates, too. |
1579 | if (const auto *ClassTemplate = dyn_cast<ClassTemplateDecl>(Val: ND)) |
1580 | ND = ClassTemplate->getTemplatedDecl(); |
1581 | |
1582 | // For purposes of this check, interfaces match too. |
1583 | if (const auto *RD = dyn_cast<RecordDecl>(Val: ND)) |
1584 | return RD->getTagKind() == TagTypeKind::Class || |
1585 | RD->getTagKind() == TagTypeKind::Struct || |
1586 | RD->getTagKind() == TagTypeKind::Interface; |
1587 | |
1588 | return false; |
1589 | } |
1590 | |
1591 | /// Determines whether the given declaration is a union. |
1592 | bool ResultBuilder::IsUnion(const NamedDecl *ND) const { |
1593 | // Allow us to find class templates, too. |
1594 | if (const auto *ClassTemplate = dyn_cast<ClassTemplateDecl>(Val: ND)) |
1595 | ND = ClassTemplate->getTemplatedDecl(); |
1596 | |
1597 | if (const auto *RD = dyn_cast<RecordDecl>(Val: ND)) |
1598 | return RD->getTagKind() == TagTypeKind::Union; |
1599 | |
1600 | return false; |
1601 | } |
1602 | |
1603 | /// Determines whether the given declaration is a namespace. |
1604 | bool ResultBuilder::IsNamespace(const NamedDecl *ND) const { |
1605 | return isa<NamespaceDecl>(Val: ND); |
1606 | } |
1607 | |
1608 | /// Determines whether the given declaration is a namespace or |
1609 | /// namespace alias. |
1610 | bool ResultBuilder::IsNamespaceOrAlias(const NamedDecl *ND) const { |
1611 | return isa<NamespaceDecl>(Val: ND->getUnderlyingDecl()); |
1612 | } |
1613 | |
1614 | /// Determines whether the given declaration is a type. |
1615 | bool ResultBuilder::IsType(const NamedDecl *ND) const { |
1616 | ND = ND->getUnderlyingDecl(); |
1617 | return isa<TypeDecl>(Val: ND) || isa<ObjCInterfaceDecl>(Val: ND); |
1618 | } |
1619 | |
1620 | /// Determines which members of a class should be visible via |
1621 | /// "." or "->". Only value declarations, nested name specifiers, and |
1622 | /// using declarations thereof should show up. |
1623 | bool ResultBuilder::IsMember(const NamedDecl *ND) const { |
1624 | ND = ND->getUnderlyingDecl(); |
1625 | return isa<ValueDecl>(Val: ND) || isa<FunctionTemplateDecl>(Val: ND) || |
1626 | isa<ObjCPropertyDecl>(Val: ND); |
1627 | } |
1628 | |
1629 | static bool isObjCReceiverType(ASTContext &C, QualType T) { |
1630 | T = C.getCanonicalType(T); |
1631 | switch (T->getTypeClass()) { |
1632 | case Type::ObjCObject: |
1633 | case Type::ObjCInterface: |
1634 | case Type::ObjCObjectPointer: |
1635 | return true; |
1636 | |
1637 | case Type::Builtin: |
1638 | switch (cast<BuiltinType>(Val&: T)->getKind()) { |
1639 | case BuiltinType::ObjCId: |
1640 | case BuiltinType::ObjCClass: |
1641 | case BuiltinType::ObjCSel: |
1642 | return true; |
1643 | |
1644 | default: |
1645 | break; |
1646 | } |
1647 | return false; |
1648 | |
1649 | default: |
1650 | break; |
1651 | } |
1652 | |
1653 | if (!C.getLangOpts().CPlusPlus) |
1654 | return false; |
1655 | |
1656 | // FIXME: We could perform more analysis here to determine whether a |
1657 | // particular class type has any conversions to Objective-C types. For now, |
1658 | // just accept all class types. |
1659 | return T->isDependentType() || T->isRecordType(); |
1660 | } |
1661 | |
1662 | bool ResultBuilder::IsObjCMessageReceiver(const NamedDecl *ND) const { |
1663 | QualType T = getDeclUsageType(C&: SemaRef.Context, ND); |
1664 | if (T.isNull()) |
1665 | return false; |
1666 | |
1667 | T = SemaRef.Context.getBaseElementType(QT: T); |
1668 | return isObjCReceiverType(C&: SemaRef.Context, T); |
1669 | } |
1670 | |
1671 | bool ResultBuilder::IsObjCMessageReceiverOrLambdaCapture( |
1672 | const NamedDecl *ND) const { |
1673 | if (IsObjCMessageReceiver(ND)) |
1674 | return true; |
1675 | |
1676 | const auto *Var = dyn_cast<VarDecl>(Val: ND); |
1677 | if (!Var) |
1678 | return false; |
1679 | |
1680 | return Var->hasLocalStorage() && !Var->hasAttr<BlocksAttr>(); |
1681 | } |
1682 | |
1683 | bool ResultBuilder::IsObjCCollection(const NamedDecl *ND) const { |
1684 | if ((SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryName(ND)) || |
1685 | (!SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryNonTypeName(ND))) |
1686 | return false; |
1687 | |
1688 | QualType T = getDeclUsageType(C&: SemaRef.Context, ND); |
1689 | if (T.isNull()) |
1690 | return false; |
1691 | |
1692 | T = SemaRef.Context.getBaseElementType(QT: T); |
1693 | return T->isObjCObjectType() || T->isObjCObjectPointerType() || |
1694 | T->isObjCIdType() || |
1695 | (SemaRef.getLangOpts().CPlusPlus && T->isRecordType()); |
1696 | } |
1697 | |
1698 | bool ResultBuilder::IsImpossibleToSatisfy(const NamedDecl *ND) const { |
1699 | return false; |
1700 | } |
1701 | |
1702 | /// Determines whether the given declaration is an Objective-C |
1703 | /// instance variable. |
1704 | bool ResultBuilder::IsObjCIvar(const NamedDecl *ND) const { |
1705 | return isa<ObjCIvarDecl>(Val: ND); |
1706 | } |
1707 | |
1708 | namespace { |
1709 | |
1710 | /// Visible declaration consumer that adds a code-completion result |
1711 | /// for each visible declaration. |
1712 | class CodeCompletionDeclConsumer : public VisibleDeclConsumer { |
1713 | ResultBuilder &Results; |
1714 | DeclContext *InitialLookupCtx; |
1715 | // NamingClass and BaseType are used for access-checking. See |
1716 | // Sema::IsSimplyAccessible for details. |
1717 | CXXRecordDecl *NamingClass; |
1718 | QualType BaseType; |
1719 | std::vector<FixItHint> FixIts; |
1720 | |
1721 | public: |
1722 | CodeCompletionDeclConsumer( |
1723 | ResultBuilder &Results, DeclContext *InitialLookupCtx, |
1724 | QualType BaseType = QualType(), |
1725 | std::vector<FixItHint> FixIts = std::vector<FixItHint>()) |
1726 | : Results(Results), InitialLookupCtx(InitialLookupCtx), |
1727 | FixIts(std::move(FixIts)) { |
1728 | NamingClass = llvm::dyn_cast<CXXRecordDecl>(Val: InitialLookupCtx); |
1729 | // If BaseType was not provided explicitly, emulate implicit 'this->'. |
1730 | if (BaseType.isNull()) { |
1731 | auto ThisType = Results.getSema().getCurrentThisType(); |
1732 | if (!ThisType.isNull()) { |
1733 | assert(ThisType->isPointerType()); |
1734 | BaseType = ThisType->getPointeeType(); |
1735 | if (!NamingClass) |
1736 | NamingClass = BaseType->getAsCXXRecordDecl(); |
1737 | } |
1738 | } |
1739 | this->BaseType = BaseType; |
1740 | } |
1741 | |
1742 | void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx, |
1743 | bool InBaseClass) override { |
1744 | ResultBuilder::Result Result(ND, Results.getBasePriority(ND), nullptr, |
1745 | false, IsAccessible(ND, Ctx), FixIts); |
1746 | Results.AddResult(Result, InitialLookupCtx, Hiding, InBaseClass, BaseType); |
1747 | } |
1748 | |
1749 | void EnteredContext(DeclContext *Ctx) override { |
1750 | Results.addVisitedContext(Ctx); |
1751 | } |
1752 | |
1753 | private: |
1754 | bool IsAccessible(NamedDecl *ND, DeclContext *Ctx) { |
1755 | // Naming class to use for access check. In most cases it was provided |
1756 | // explicitly (e.g. member access (lhs.foo) or qualified lookup (X::)), |
1757 | // for unqualified lookup we fallback to the \p Ctx in which we found the |
1758 | // member. |
1759 | auto *NamingClass = this->NamingClass; |
1760 | QualType BaseType = this->BaseType; |
1761 | if (auto *Cls = llvm::dyn_cast_or_null<CXXRecordDecl>(Val: Ctx)) { |
1762 | if (!NamingClass) |
1763 | NamingClass = Cls; |
1764 | // When we emulate implicit 'this->' in an unqualified lookup, we might |
1765 | // end up with an invalid naming class. In that case, we avoid emulating |
1766 | // 'this->' qualifier to satisfy preconditions of the access checking. |
1767 | if (NamingClass->getCanonicalDecl() != Cls->getCanonicalDecl() && |
1768 | !NamingClass->isDerivedFrom(Base: Cls)) { |
1769 | NamingClass = Cls; |
1770 | BaseType = QualType(); |
1771 | } |
1772 | } else { |
1773 | // The decl was found outside the C++ class, so only ObjC access checks |
1774 | // apply. Those do not rely on NamingClass and BaseType, so we clear them |
1775 | // out. |
1776 | NamingClass = nullptr; |
1777 | BaseType = QualType(); |
1778 | } |
1779 | return Results.getSema().IsSimplyAccessible(Decl: ND, NamingClass, BaseType); |
1780 | } |
1781 | }; |
1782 | } // namespace |
1783 | |
1784 | /// Add type specifiers for the current language as keyword results. |
1785 | static void AddTypeSpecifierResults(const LangOptions &LangOpts, |
1786 | ResultBuilder &Results) { |
1787 | typedef CodeCompletionResult Result; |
1788 | Results.AddResult(R: Result("short" , CCP_Type)); |
1789 | Results.AddResult(R: Result("long" , CCP_Type)); |
1790 | Results.AddResult(R: Result("signed" , CCP_Type)); |
1791 | Results.AddResult(R: Result("unsigned" , CCP_Type)); |
1792 | Results.AddResult(R: Result("void" , CCP_Type)); |
1793 | Results.AddResult(R: Result("char" , CCP_Type)); |
1794 | Results.AddResult(R: Result("int" , CCP_Type)); |
1795 | Results.AddResult(R: Result("float" , CCP_Type)); |
1796 | Results.AddResult(R: Result("double" , CCP_Type)); |
1797 | Results.AddResult(R: Result("enum" , CCP_Type)); |
1798 | Results.AddResult(R: Result("struct" , CCP_Type)); |
1799 | Results.AddResult(R: Result("union" , CCP_Type)); |
1800 | Results.AddResult(R: Result("const" , CCP_Type)); |
1801 | Results.AddResult(R: Result("volatile" , CCP_Type)); |
1802 | |
1803 | if (LangOpts.C99) { |
1804 | // C99-specific |
1805 | Results.AddResult(R: Result("_Complex" , CCP_Type)); |
1806 | Results.AddResult(R: Result("_Imaginary" , CCP_Type)); |
1807 | Results.AddResult(R: Result("_Bool" , CCP_Type)); |
1808 | Results.AddResult(R: Result("restrict" , CCP_Type)); |
1809 | } |
1810 | |
1811 | CodeCompletionBuilder Builder(Results.getAllocator(), |
1812 | Results.getCodeCompletionTUInfo()); |
1813 | if (LangOpts.CPlusPlus) { |
1814 | // C++-specific |
1815 | Results.AddResult( |
1816 | R: Result("bool" , CCP_Type + (LangOpts.ObjC ? CCD_bool_in_ObjC : 0))); |
1817 | Results.AddResult(R: Result("class" , CCP_Type)); |
1818 | Results.AddResult(R: Result("wchar_t" , CCP_Type)); |
1819 | |
1820 | // typename name |
1821 | Builder.AddTypedTextChunk(Text: "typename" ); |
1822 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
1823 | Builder.AddPlaceholderChunk(Placeholder: "name" ); |
1824 | Results.AddResult(R: Result(Builder.TakeString())); |
1825 | |
1826 | if (LangOpts.CPlusPlus11) { |
1827 | Results.AddResult(R: Result("auto" , CCP_Type)); |
1828 | Results.AddResult(R: Result("char16_t" , CCP_Type)); |
1829 | Results.AddResult(R: Result("char32_t" , CCP_Type)); |
1830 | |
1831 | Builder.AddTypedTextChunk(Text: "decltype" ); |
1832 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
1833 | Builder.AddPlaceholderChunk(Placeholder: "expression" ); |
1834 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
1835 | Results.AddResult(R: Result(Builder.TakeString())); |
1836 | } |
1837 | } else |
1838 | Results.AddResult(R: Result("__auto_type" , CCP_Type)); |
1839 | |
1840 | // GNU keywords |
1841 | if (LangOpts.GNUKeywords) { |
1842 | // FIXME: Enable when we actually support decimal floating point. |
1843 | // Results.AddResult(Result("_Decimal32")); |
1844 | // Results.AddResult(Result("_Decimal64")); |
1845 | // Results.AddResult(Result("_Decimal128")); |
1846 | |
1847 | Builder.AddTypedTextChunk(Text: "typeof" ); |
1848 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
1849 | Builder.AddPlaceholderChunk(Placeholder: "expression" ); |
1850 | Results.AddResult(R: Result(Builder.TakeString())); |
1851 | |
1852 | Builder.AddTypedTextChunk(Text: "typeof" ); |
1853 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
1854 | Builder.AddPlaceholderChunk(Placeholder: "type" ); |
1855 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
1856 | Results.AddResult(R: Result(Builder.TakeString())); |
1857 | } |
1858 | |
1859 | // Nullability |
1860 | Results.AddResult(R: Result("_Nonnull" , CCP_Type)); |
1861 | Results.AddResult(R: Result("_Null_unspecified" , CCP_Type)); |
1862 | Results.AddResult(R: Result("_Nullable" , CCP_Type)); |
1863 | } |
1864 | |
1865 | static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC, |
1866 | const LangOptions &LangOpts, |
1867 | ResultBuilder &Results) { |
1868 | typedef CodeCompletionResult Result; |
1869 | // Note: we don't suggest either "auto" or "register", because both |
1870 | // are pointless as storage specifiers. Elsewhere, we suggest "auto" |
1871 | // in C++0x as a type specifier. |
1872 | Results.AddResult(R: Result("extern" )); |
1873 | Results.AddResult(R: Result("static" )); |
1874 | |
1875 | if (LangOpts.CPlusPlus11) { |
1876 | CodeCompletionAllocator &Allocator = Results.getAllocator(); |
1877 | CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo()); |
1878 | |
1879 | // alignas |
1880 | Builder.AddTypedTextChunk(Text: "alignas" ); |
1881 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
1882 | Builder.AddPlaceholderChunk(Placeholder: "expression" ); |
1883 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
1884 | Results.AddResult(R: Result(Builder.TakeString())); |
1885 | |
1886 | Results.AddResult(R: Result("constexpr" )); |
1887 | Results.AddResult(R: Result("thread_local" )); |
1888 | } |
1889 | } |
1890 | |
1891 | static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC, |
1892 | const LangOptions &LangOpts, |
1893 | ResultBuilder &Results) { |
1894 | typedef CodeCompletionResult Result; |
1895 | switch (CCC) { |
1896 | case Sema::PCC_Class: |
1897 | case Sema::PCC_MemberTemplate: |
1898 | if (LangOpts.CPlusPlus) { |
1899 | Results.AddResult(R: Result("explicit" )); |
1900 | Results.AddResult(R: Result("friend" )); |
1901 | Results.AddResult(R: Result("mutable" )); |
1902 | Results.AddResult(R: Result("virtual" )); |
1903 | } |
1904 | [[fallthrough]]; |
1905 | |
1906 | case Sema::PCC_ObjCInterface: |
1907 | case Sema::PCC_ObjCImplementation: |
1908 | case Sema::PCC_Namespace: |
1909 | case Sema::PCC_Template: |
1910 | if (LangOpts.CPlusPlus || LangOpts.C99) |
1911 | Results.AddResult(R: Result("inline" )); |
1912 | break; |
1913 | |
1914 | case Sema::PCC_ObjCInstanceVariableList: |
1915 | case Sema::PCC_Expression: |
1916 | case Sema::PCC_Statement: |
1917 | case Sema::PCC_TopLevelOrExpression: |
1918 | case Sema::PCC_ForInit: |
1919 | case Sema::PCC_Condition: |
1920 | case Sema::PCC_RecoveryInFunction: |
1921 | case Sema::PCC_Type: |
1922 | case Sema::PCC_ParenthesizedExpression: |
1923 | case Sema::PCC_LocalDeclarationSpecifiers: |
1924 | break; |
1925 | } |
1926 | } |
1927 | |
1928 | static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt); |
1929 | static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt); |
1930 | static void AddObjCVisibilityResults(const LangOptions &LangOpts, |
1931 | ResultBuilder &Results, bool NeedAt); |
1932 | static void AddObjCImplementationResults(const LangOptions &LangOpts, |
1933 | ResultBuilder &Results, bool NeedAt); |
1934 | static void AddObjCInterfaceResults(const LangOptions &LangOpts, |
1935 | ResultBuilder &Results, bool NeedAt); |
1936 | static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt); |
1937 | |
1938 | static void AddTypedefResult(ResultBuilder &Results) { |
1939 | CodeCompletionBuilder Builder(Results.getAllocator(), |
1940 | Results.getCodeCompletionTUInfo()); |
1941 | Builder.AddTypedTextChunk(Text: "typedef" ); |
1942 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
1943 | Builder.AddPlaceholderChunk(Placeholder: "type" ); |
1944 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
1945 | Builder.AddPlaceholderChunk(Placeholder: "name" ); |
1946 | Builder.AddChunk(CK: CodeCompletionString::CK_SemiColon); |
1947 | Results.AddResult(R: CodeCompletionResult(Builder.TakeString())); |
1948 | } |
1949 | |
1950 | // using name = type |
1951 | static void AddUsingAliasResult(CodeCompletionBuilder &Builder, |
1952 | ResultBuilder &Results) { |
1953 | Builder.AddTypedTextChunk(Text: "using" ); |
1954 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
1955 | Builder.AddPlaceholderChunk(Placeholder: "name" ); |
1956 | Builder.AddChunk(CK: CodeCompletionString::CK_Equal); |
1957 | Builder.AddPlaceholderChunk(Placeholder: "type" ); |
1958 | Builder.AddChunk(CK: CodeCompletionString::CK_SemiColon); |
1959 | Results.AddResult(R: CodeCompletionResult(Builder.TakeString())); |
1960 | } |
1961 | |
1962 | static bool WantTypesInContext(Sema::ParserCompletionContext CCC, |
1963 | const LangOptions &LangOpts) { |
1964 | switch (CCC) { |
1965 | case Sema::PCC_Namespace: |
1966 | case Sema::PCC_Class: |
1967 | case Sema::PCC_ObjCInstanceVariableList: |
1968 | case Sema::PCC_Template: |
1969 | case Sema::PCC_MemberTemplate: |
1970 | case Sema::PCC_Statement: |
1971 | case Sema::PCC_RecoveryInFunction: |
1972 | case Sema::PCC_Type: |
1973 | case Sema::PCC_ParenthesizedExpression: |
1974 | case Sema::PCC_LocalDeclarationSpecifiers: |
1975 | case Sema::PCC_TopLevelOrExpression: |
1976 | return true; |
1977 | |
1978 | case Sema::PCC_Expression: |
1979 | case Sema::PCC_Condition: |
1980 | return LangOpts.CPlusPlus; |
1981 | |
1982 | case Sema::PCC_ObjCInterface: |
1983 | case Sema::PCC_ObjCImplementation: |
1984 | return false; |
1985 | |
1986 | case Sema::PCC_ForInit: |
1987 | return LangOpts.CPlusPlus || LangOpts.ObjC || LangOpts.C99; |
1988 | } |
1989 | |
1990 | llvm_unreachable("Invalid ParserCompletionContext!" ); |
1991 | } |
1992 | |
1993 | static PrintingPolicy getCompletionPrintingPolicy(const ASTContext &Context, |
1994 | const Preprocessor &PP) { |
1995 | PrintingPolicy Policy = Sema::getPrintingPolicy(Ctx: Context, PP); |
1996 | Policy.AnonymousTagLocations = false; |
1997 | Policy.SuppressStrongLifetime = true; |
1998 | Policy.SuppressUnwrittenScope = true; |
1999 | Policy.SuppressScope = true; |
2000 | Policy.CleanUglifiedParameters = true; |
2001 | return Policy; |
2002 | } |
2003 | |
2004 | /// Retrieve a printing policy suitable for code completion. |
2005 | static PrintingPolicy getCompletionPrintingPolicy(Sema &S) { |
2006 | return getCompletionPrintingPolicy(Context: S.Context, PP: S.PP); |
2007 | } |
2008 | |
2009 | /// Retrieve the string representation of the given type as a string |
2010 | /// that has the appropriate lifetime for code completion. |
2011 | /// |
2012 | /// This routine provides a fast path where we provide constant strings for |
2013 | /// common type names. |
2014 | static const char *GetCompletionTypeString(QualType T, ASTContext &Context, |
2015 | const PrintingPolicy &Policy, |
2016 | CodeCompletionAllocator &Allocator) { |
2017 | if (!T.getLocalQualifiers()) { |
2018 | // Built-in type names are constant strings. |
2019 | if (const BuiltinType *BT = dyn_cast<BuiltinType>(Val&: T)) |
2020 | return BT->getNameAsCString(Policy); |
2021 | |
2022 | // Anonymous tag types are constant strings. |
2023 | if (const TagType *TagT = dyn_cast<TagType>(Val&: T)) |
2024 | if (TagDecl *Tag = TagT->getDecl()) |
2025 | if (!Tag->hasNameForLinkage()) { |
2026 | switch (Tag->getTagKind()) { |
2027 | case TagTypeKind::Struct: |
2028 | return "struct <anonymous>" ; |
2029 | case TagTypeKind::Interface: |
2030 | return "__interface <anonymous>" ; |
2031 | case TagTypeKind::Class: |
2032 | return "class <anonymous>" ; |
2033 | case TagTypeKind::Union: |
2034 | return "union <anonymous>" ; |
2035 | case TagTypeKind::Enum: |
2036 | return "enum <anonymous>" ; |
2037 | } |
2038 | } |
2039 | } |
2040 | |
2041 | // Slow path: format the type as a string. |
2042 | std::string Result; |
2043 | T.getAsStringInternal(Str&: Result, Policy); |
2044 | return Allocator.CopyString(String: Result); |
2045 | } |
2046 | |
2047 | /// Add a completion for "this", if we're in a member function. |
2048 | static void addThisCompletion(Sema &S, ResultBuilder &Results) { |
2049 | QualType ThisTy = S.getCurrentThisType(); |
2050 | if (ThisTy.isNull()) |
2051 | return; |
2052 | |
2053 | CodeCompletionAllocator &Allocator = Results.getAllocator(); |
2054 | CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo()); |
2055 | PrintingPolicy Policy = getCompletionPrintingPolicy(S); |
2056 | Builder.AddResultTypeChunk( |
2057 | ResultType: GetCompletionTypeString(T: ThisTy, Context&: S.Context, Policy, Allocator)); |
2058 | Builder.AddTypedTextChunk(Text: "this" ); |
2059 | Results.AddResult(R: CodeCompletionResult(Builder.TakeString())); |
2060 | } |
2061 | |
2062 | static void AddStaticAssertResult(CodeCompletionBuilder &Builder, |
2063 | ResultBuilder &Results, |
2064 | const LangOptions &LangOpts) { |
2065 | if (!LangOpts.CPlusPlus11) |
2066 | return; |
2067 | |
2068 | Builder.AddTypedTextChunk(Text: "static_assert" ); |
2069 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
2070 | Builder.AddPlaceholderChunk(Placeholder: "expression" ); |
2071 | Builder.AddChunk(CK: CodeCompletionString::CK_Comma); |
2072 | Builder.AddPlaceholderChunk(Placeholder: "message" ); |
2073 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
2074 | Builder.AddChunk(CK: CodeCompletionString::CK_SemiColon); |
2075 | Results.AddResult(R: CodeCompletionResult(Builder.TakeString())); |
2076 | } |
2077 | |
2078 | static void AddOverrideResults(ResultBuilder &Results, |
2079 | const CodeCompletionContext &CCContext, |
2080 | CodeCompletionBuilder &Builder) { |
2081 | Sema &S = Results.getSema(); |
2082 | const auto *CR = llvm::dyn_cast<CXXRecordDecl>(Val: S.CurContext); |
2083 | // If not inside a class/struct/union return empty. |
2084 | if (!CR) |
2085 | return; |
2086 | // First store overrides within current class. |
2087 | // These are stored by name to make querying fast in the later step. |
2088 | llvm::StringMap<std::vector<FunctionDecl *>> Overrides; |
2089 | for (auto *Method : CR->methods()) { |
2090 | if (!Method->isVirtual() || !Method->getIdentifier()) |
2091 | continue; |
2092 | Overrides[Method->getName()].push_back(Method); |
2093 | } |
2094 | |
2095 | for (const auto &Base : CR->bases()) { |
2096 | const auto *BR = Base.getType().getTypePtr()->getAsCXXRecordDecl(); |
2097 | if (!BR) |
2098 | continue; |
2099 | for (auto *Method : BR->methods()) { |
2100 | if (!Method->isVirtual() || !Method->getIdentifier()) |
2101 | continue; |
2102 | const auto it = Overrides.find(Method->getName()); |
2103 | bool IsOverriden = false; |
2104 | if (it != Overrides.end()) { |
2105 | for (auto *MD : it->second) { |
2106 | // If the method in current body is not an overload of this virtual |
2107 | // function, then it overrides this one. |
2108 | if (!S.IsOverload(MD, Method, false)) { |
2109 | IsOverriden = true; |
2110 | break; |
2111 | } |
2112 | } |
2113 | } |
2114 | if (!IsOverriden) { |
2115 | // Generates a new CodeCompletionResult by taking this function and |
2116 | // converting it into an override declaration with only one chunk in the |
2117 | // final CodeCompletionString as a TypedTextChunk. |
2118 | std::string OverrideSignature; |
2119 | llvm::raw_string_ostream OS(OverrideSignature); |
2120 | CodeCompletionResult CCR(Method, 0); |
2121 | PrintingPolicy Policy = |
2122 | getCompletionPrintingPolicy(Context: S.getASTContext(), PP: S.getPreprocessor()); |
2123 | auto *CCS = CCR.createCodeCompletionStringForOverride( |
2124 | PP&: S.getPreprocessor(), Ctx&: S.getASTContext(), Result&: Builder, |
2125 | /*IncludeBriefComments=*/false, CCContext, Policy); |
2126 | Results.AddResult(R: CodeCompletionResult(CCS, Method, CCP_CodePattern)); |
2127 | } |
2128 | } |
2129 | } |
2130 | } |
2131 | |
2132 | /// Add language constructs that show up for "ordinary" names. |
2133 | static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC, Scope *S, |
2134 | Sema &SemaRef, ResultBuilder &Results) { |
2135 | CodeCompletionAllocator &Allocator = Results.getAllocator(); |
2136 | CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo()); |
2137 | |
2138 | typedef CodeCompletionResult Result; |
2139 | switch (CCC) { |
2140 | case Sema::PCC_Namespace: |
2141 | if (SemaRef.getLangOpts().CPlusPlus) { |
2142 | if (Results.includeCodePatterns()) { |
2143 | // namespace <identifier> { declarations } |
2144 | Builder.AddTypedTextChunk(Text: "namespace" ); |
2145 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
2146 | Builder.AddPlaceholderChunk(Placeholder: "identifier" ); |
2147 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
2148 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftBrace); |
2149 | Builder.AddChunk(CK: CodeCompletionString::CK_VerticalSpace); |
2150 | Builder.AddPlaceholderChunk(Placeholder: "declarations" ); |
2151 | Builder.AddChunk(CK: CodeCompletionString::CK_VerticalSpace); |
2152 | Builder.AddChunk(CK: CodeCompletionString::CK_RightBrace); |
2153 | Results.AddResult(R: Result(Builder.TakeString())); |
2154 | } |
2155 | |
2156 | // namespace identifier = identifier ; |
2157 | Builder.AddTypedTextChunk(Text: "namespace" ); |
2158 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
2159 | Builder.AddPlaceholderChunk(Placeholder: "name" ); |
2160 | Builder.AddChunk(CK: CodeCompletionString::CK_Equal); |
2161 | Builder.AddPlaceholderChunk(Placeholder: "namespace" ); |
2162 | Builder.AddChunk(CK: CodeCompletionString::CK_SemiColon); |
2163 | Results.AddResult(R: Result(Builder.TakeString())); |
2164 | |
2165 | // Using directives |
2166 | Builder.AddTypedTextChunk(Text: "using namespace" ); |
2167 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
2168 | Builder.AddPlaceholderChunk(Placeholder: "identifier" ); |
2169 | Builder.AddChunk(CK: CodeCompletionString::CK_SemiColon); |
2170 | Results.AddResult(R: Result(Builder.TakeString())); |
2171 | |
2172 | // asm(string-literal) |
2173 | Builder.AddTypedTextChunk(Text: "asm" ); |
2174 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
2175 | Builder.AddPlaceholderChunk(Placeholder: "string-literal" ); |
2176 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
2177 | Results.AddResult(R: Result(Builder.TakeString())); |
2178 | |
2179 | if (Results.includeCodePatterns()) { |
2180 | // Explicit template instantiation |
2181 | Builder.AddTypedTextChunk(Text: "template" ); |
2182 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
2183 | Builder.AddPlaceholderChunk(Placeholder: "declaration" ); |
2184 | Results.AddResult(R: Result(Builder.TakeString())); |
2185 | } else { |
2186 | Results.AddResult(R: Result("template" , CodeCompletionResult::RK_Keyword)); |
2187 | } |
2188 | } |
2189 | |
2190 | if (SemaRef.getLangOpts().ObjC) |
2191 | AddObjCTopLevelResults(Results, NeedAt: true); |
2192 | |
2193 | AddTypedefResult(Results); |
2194 | [[fallthrough]]; |
2195 | |
2196 | case Sema::PCC_Class: |
2197 | if (SemaRef.getLangOpts().CPlusPlus) { |
2198 | // Using declaration |
2199 | Builder.AddTypedTextChunk(Text: "using" ); |
2200 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
2201 | Builder.AddPlaceholderChunk(Placeholder: "qualifier" ); |
2202 | Builder.AddTextChunk(Text: "::" ); |
2203 | Builder.AddPlaceholderChunk(Placeholder: "name" ); |
2204 | Builder.AddChunk(CK: CodeCompletionString::CK_SemiColon); |
2205 | Results.AddResult(R: Result(Builder.TakeString())); |
2206 | |
2207 | if (SemaRef.getLangOpts().CPlusPlus11) |
2208 | AddUsingAliasResult(Builder, Results); |
2209 | |
2210 | // using typename qualifier::name (only in a dependent context) |
2211 | if (SemaRef.CurContext->isDependentContext()) { |
2212 | Builder.AddTypedTextChunk(Text: "using typename" ); |
2213 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
2214 | Builder.AddPlaceholderChunk(Placeholder: "qualifier" ); |
2215 | Builder.AddTextChunk(Text: "::" ); |
2216 | Builder.AddPlaceholderChunk(Placeholder: "name" ); |
2217 | Builder.AddChunk(CK: CodeCompletionString::CK_SemiColon); |
2218 | Results.AddResult(R: Result(Builder.TakeString())); |
2219 | } |
2220 | |
2221 | AddStaticAssertResult(Builder, Results, LangOpts: SemaRef.getLangOpts()); |
2222 | |
2223 | if (CCC == Sema::PCC_Class) { |
2224 | AddTypedefResult(Results); |
2225 | |
2226 | bool IsNotInheritanceScope = !S->isClassInheritanceScope(); |
2227 | // public: |
2228 | Builder.AddTypedTextChunk(Text: "public" ); |
2229 | if (IsNotInheritanceScope && Results.includeCodePatterns()) |
2230 | Builder.AddChunk(CK: CodeCompletionString::CK_Colon); |
2231 | Results.AddResult(R: Result(Builder.TakeString())); |
2232 | |
2233 | // protected: |
2234 | Builder.AddTypedTextChunk(Text: "protected" ); |
2235 | if (IsNotInheritanceScope && Results.includeCodePatterns()) |
2236 | Builder.AddChunk(CK: CodeCompletionString::CK_Colon); |
2237 | Results.AddResult(R: Result(Builder.TakeString())); |
2238 | |
2239 | // private: |
2240 | Builder.AddTypedTextChunk(Text: "private" ); |
2241 | if (IsNotInheritanceScope && Results.includeCodePatterns()) |
2242 | Builder.AddChunk(CK: CodeCompletionString::CK_Colon); |
2243 | Results.AddResult(R: Result(Builder.TakeString())); |
2244 | |
2245 | // FIXME: This adds override results only if we are at the first word of |
2246 | // the declaration/definition. Also call this from other sides to have |
2247 | // more use-cases. |
2248 | AddOverrideResults(Results, CCContext: CodeCompletionContext::CCC_ClassStructUnion, |
2249 | Builder); |
2250 | } |
2251 | } |
2252 | [[fallthrough]]; |
2253 | |
2254 | case Sema::PCC_Template: |
2255 | case Sema::PCC_MemberTemplate: |
2256 | if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns()) { |
2257 | // template < parameters > |
2258 | Builder.AddTypedTextChunk(Text: "template" ); |
2259 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftAngle); |
2260 | Builder.AddPlaceholderChunk(Placeholder: "parameters" ); |
2261 | Builder.AddChunk(CK: CodeCompletionString::CK_RightAngle); |
2262 | Results.AddResult(R: Result(Builder.TakeString())); |
2263 | } else { |
2264 | Results.AddResult(R: Result("template" , CodeCompletionResult::RK_Keyword)); |
2265 | } |
2266 | |
2267 | AddStorageSpecifiers(CCC, LangOpts: SemaRef.getLangOpts(), Results); |
2268 | AddFunctionSpecifiers(CCC, LangOpts: SemaRef.getLangOpts(), Results); |
2269 | break; |
2270 | |
2271 | case Sema::PCC_ObjCInterface: |
2272 | AddObjCInterfaceResults(LangOpts: SemaRef.getLangOpts(), Results, NeedAt: true); |
2273 | AddStorageSpecifiers(CCC, LangOpts: SemaRef.getLangOpts(), Results); |
2274 | AddFunctionSpecifiers(CCC, LangOpts: SemaRef.getLangOpts(), Results); |
2275 | break; |
2276 | |
2277 | case Sema::PCC_ObjCImplementation: |
2278 | AddObjCImplementationResults(LangOpts: SemaRef.getLangOpts(), Results, NeedAt: true); |
2279 | AddStorageSpecifiers(CCC, LangOpts: SemaRef.getLangOpts(), Results); |
2280 | AddFunctionSpecifiers(CCC, LangOpts: SemaRef.getLangOpts(), Results); |
2281 | break; |
2282 | |
2283 | case Sema::PCC_ObjCInstanceVariableList: |
2284 | AddObjCVisibilityResults(LangOpts: SemaRef.getLangOpts(), Results, NeedAt: true); |
2285 | break; |
2286 | |
2287 | case Sema::PCC_RecoveryInFunction: |
2288 | case Sema::PCC_TopLevelOrExpression: |
2289 | case Sema::PCC_Statement: { |
2290 | if (SemaRef.getLangOpts().CPlusPlus11) |
2291 | AddUsingAliasResult(Builder, Results); |
2292 | |
2293 | AddTypedefResult(Results); |
2294 | |
2295 | if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns() && |
2296 | SemaRef.getLangOpts().CXXExceptions) { |
2297 | Builder.AddTypedTextChunk(Text: "try" ); |
2298 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
2299 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftBrace); |
2300 | Builder.AddChunk(CK: CodeCompletionString::CK_VerticalSpace); |
2301 | Builder.AddPlaceholderChunk(Placeholder: "statements" ); |
2302 | Builder.AddChunk(CK: CodeCompletionString::CK_VerticalSpace); |
2303 | Builder.AddChunk(CK: CodeCompletionString::CK_RightBrace); |
2304 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
2305 | Builder.AddTextChunk(Text: "catch" ); |
2306 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
2307 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
2308 | Builder.AddPlaceholderChunk(Placeholder: "declaration" ); |
2309 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
2310 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
2311 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftBrace); |
2312 | Builder.AddChunk(CK: CodeCompletionString::CK_VerticalSpace); |
2313 | Builder.AddPlaceholderChunk(Placeholder: "statements" ); |
2314 | Builder.AddChunk(CK: CodeCompletionString::CK_VerticalSpace); |
2315 | Builder.AddChunk(CK: CodeCompletionString::CK_RightBrace); |
2316 | Results.AddResult(R: Result(Builder.TakeString())); |
2317 | } |
2318 | if (SemaRef.getLangOpts().ObjC) |
2319 | AddObjCStatementResults(Results, NeedAt: true); |
2320 | |
2321 | if (Results.includeCodePatterns()) { |
2322 | // if (condition) { statements } |
2323 | Builder.AddTypedTextChunk(Text: "if" ); |
2324 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
2325 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
2326 | if (SemaRef.getLangOpts().CPlusPlus) |
2327 | Builder.AddPlaceholderChunk(Placeholder: "condition" ); |
2328 | else |
2329 | Builder.AddPlaceholderChunk(Placeholder: "expression" ); |
2330 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
2331 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
2332 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftBrace); |
2333 | Builder.AddChunk(CK: CodeCompletionString::CK_VerticalSpace); |
2334 | Builder.AddPlaceholderChunk(Placeholder: "statements" ); |
2335 | Builder.AddChunk(CK: CodeCompletionString::CK_VerticalSpace); |
2336 | Builder.AddChunk(CK: CodeCompletionString::CK_RightBrace); |
2337 | Results.AddResult(R: Result(Builder.TakeString())); |
2338 | |
2339 | // switch (condition) { } |
2340 | Builder.AddTypedTextChunk(Text: "switch" ); |
2341 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
2342 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
2343 | if (SemaRef.getLangOpts().CPlusPlus) |
2344 | Builder.AddPlaceholderChunk(Placeholder: "condition" ); |
2345 | else |
2346 | Builder.AddPlaceholderChunk(Placeholder: "expression" ); |
2347 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
2348 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
2349 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftBrace); |
2350 | Builder.AddChunk(CK: CodeCompletionString::CK_VerticalSpace); |
2351 | Builder.AddPlaceholderChunk(Placeholder: "cases" ); |
2352 | Builder.AddChunk(CK: CodeCompletionString::CK_VerticalSpace); |
2353 | Builder.AddChunk(CK: CodeCompletionString::CK_RightBrace); |
2354 | Results.AddResult(R: Result(Builder.TakeString())); |
2355 | } |
2356 | |
2357 | // Switch-specific statements. |
2358 | if (SemaRef.getCurFunction() && |
2359 | !SemaRef.getCurFunction()->SwitchStack.empty()) { |
2360 | // case expression: |
2361 | Builder.AddTypedTextChunk(Text: "case" ); |
2362 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
2363 | Builder.AddPlaceholderChunk(Placeholder: "expression" ); |
2364 | Builder.AddChunk(CK: CodeCompletionString::CK_Colon); |
2365 | Results.AddResult(R: Result(Builder.TakeString())); |
2366 | |
2367 | // default: |
2368 | Builder.AddTypedTextChunk(Text: "default" ); |
2369 | Builder.AddChunk(CK: CodeCompletionString::CK_Colon); |
2370 | Results.AddResult(R: Result(Builder.TakeString())); |
2371 | } |
2372 | |
2373 | if (Results.includeCodePatterns()) { |
2374 | /// while (condition) { statements } |
2375 | Builder.AddTypedTextChunk(Text: "while" ); |
2376 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
2377 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
2378 | if (SemaRef.getLangOpts().CPlusPlus) |
2379 | Builder.AddPlaceholderChunk(Placeholder: "condition" ); |
2380 | else |
2381 | Builder.AddPlaceholderChunk(Placeholder: "expression" ); |
2382 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
2383 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
2384 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftBrace); |
2385 | Builder.AddChunk(CK: CodeCompletionString::CK_VerticalSpace); |
2386 | Builder.AddPlaceholderChunk(Placeholder: "statements" ); |
2387 | Builder.AddChunk(CK: CodeCompletionString::CK_VerticalSpace); |
2388 | Builder.AddChunk(CK: CodeCompletionString::CK_RightBrace); |
2389 | Results.AddResult(R: Result(Builder.TakeString())); |
2390 | |
2391 | // do { statements } while ( expression ); |
2392 | Builder.AddTypedTextChunk(Text: "do" ); |
2393 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
2394 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftBrace); |
2395 | Builder.AddChunk(CK: CodeCompletionString::CK_VerticalSpace); |
2396 | Builder.AddPlaceholderChunk(Placeholder: "statements" ); |
2397 | Builder.AddChunk(CK: CodeCompletionString::CK_VerticalSpace); |
2398 | Builder.AddChunk(CK: CodeCompletionString::CK_RightBrace); |
2399 | Builder.AddTextChunk(Text: "while" ); |
2400 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
2401 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
2402 | Builder.AddPlaceholderChunk(Placeholder: "expression" ); |
2403 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
2404 | Results.AddResult(R: Result(Builder.TakeString())); |
2405 | |
2406 | // for ( for-init-statement ; condition ; expression ) { statements } |
2407 | Builder.AddTypedTextChunk(Text: "for" ); |
2408 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
2409 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
2410 | if (SemaRef.getLangOpts().CPlusPlus || SemaRef.getLangOpts().C99) |
2411 | Builder.AddPlaceholderChunk(Placeholder: "init-statement" ); |
2412 | else |
2413 | Builder.AddPlaceholderChunk(Placeholder: "init-expression" ); |
2414 | Builder.AddChunk(CK: CodeCompletionString::CK_SemiColon); |
2415 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
2416 | Builder.AddPlaceholderChunk(Placeholder: "condition" ); |
2417 | Builder.AddChunk(CK: CodeCompletionString::CK_SemiColon); |
2418 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
2419 | Builder.AddPlaceholderChunk(Placeholder: "inc-expression" ); |
2420 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
2421 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
2422 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftBrace); |
2423 | Builder.AddChunk(CK: CodeCompletionString::CK_VerticalSpace); |
2424 | Builder.AddPlaceholderChunk(Placeholder: "statements" ); |
2425 | Builder.AddChunk(CK: CodeCompletionString::CK_VerticalSpace); |
2426 | Builder.AddChunk(CK: CodeCompletionString::CK_RightBrace); |
2427 | Results.AddResult(R: Result(Builder.TakeString())); |
2428 | |
2429 | if (SemaRef.getLangOpts().CPlusPlus11 || SemaRef.getLangOpts().ObjC) { |
2430 | // for ( range_declaration (:|in) range_expression ) { statements } |
2431 | Builder.AddTypedTextChunk(Text: "for" ); |
2432 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
2433 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
2434 | Builder.AddPlaceholderChunk(Placeholder: "range-declaration" ); |
2435 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
2436 | if (SemaRef.getLangOpts().ObjC) |
2437 | Builder.AddTextChunk(Text: "in" ); |
2438 | else |
2439 | Builder.AddChunk(CK: CodeCompletionString::CK_Colon); |
2440 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
2441 | Builder.AddPlaceholderChunk(Placeholder: "range-expression" ); |
2442 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
2443 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
2444 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftBrace); |
2445 | Builder.AddChunk(CK: CodeCompletionString::CK_VerticalSpace); |
2446 | Builder.AddPlaceholderChunk(Placeholder: "statements" ); |
2447 | Builder.AddChunk(CK: CodeCompletionString::CK_VerticalSpace); |
2448 | Builder.AddChunk(CK: CodeCompletionString::CK_RightBrace); |
2449 | Results.AddResult(R: Result(Builder.TakeString())); |
2450 | } |
2451 | } |
2452 | |
2453 | if (S->getContinueParent()) { |
2454 | // continue ; |
2455 | Builder.AddTypedTextChunk(Text: "continue" ); |
2456 | Builder.AddChunk(CK: CodeCompletionString::CK_SemiColon); |
2457 | Results.AddResult(R: Result(Builder.TakeString())); |
2458 | } |
2459 | |
2460 | if (S->getBreakParent()) { |
2461 | // break ; |
2462 | Builder.AddTypedTextChunk(Text: "break" ); |
2463 | Builder.AddChunk(CK: CodeCompletionString::CK_SemiColon); |
2464 | Results.AddResult(R: Result(Builder.TakeString())); |
2465 | } |
2466 | |
2467 | // "return expression ;" or "return ;", depending on the return type. |
2468 | QualType ReturnType; |
2469 | if (const auto *Function = dyn_cast<FunctionDecl>(Val: SemaRef.CurContext)) |
2470 | ReturnType = Function->getReturnType(); |
2471 | else if (const auto *Method = dyn_cast<ObjCMethodDecl>(Val: SemaRef.CurContext)) |
2472 | ReturnType = Method->getReturnType(); |
2473 | else if (SemaRef.getCurBlock() && |
2474 | !SemaRef.getCurBlock()->ReturnType.isNull()) |
2475 | ReturnType = SemaRef.getCurBlock()->ReturnType;; |
2476 | if (ReturnType.isNull() || ReturnType->isVoidType()) { |
2477 | Builder.AddTypedTextChunk(Text: "return" ); |
2478 | Builder.AddChunk(CK: CodeCompletionString::CK_SemiColon); |
2479 | Results.AddResult(R: Result(Builder.TakeString())); |
2480 | } else { |
2481 | assert(!ReturnType.isNull()); |
2482 | // "return expression ;" |
2483 | Builder.AddTypedTextChunk(Text: "return" ); |
2484 | Builder.AddChunk(CK: clang::CodeCompletionString::CK_HorizontalSpace); |
2485 | Builder.AddPlaceholderChunk(Placeholder: "expression" ); |
2486 | Builder.AddChunk(CK: CodeCompletionString::CK_SemiColon); |
2487 | Results.AddResult(R: Result(Builder.TakeString())); |
2488 | // When boolean, also add 'return true;' and 'return false;'. |
2489 | if (ReturnType->isBooleanType()) { |
2490 | Builder.AddTypedTextChunk(Text: "return true" ); |
2491 | Builder.AddChunk(CK: CodeCompletionString::CK_SemiColon); |
2492 | Results.AddResult(R: Result(Builder.TakeString())); |
2493 | |
2494 | Builder.AddTypedTextChunk(Text: "return false" ); |
2495 | Builder.AddChunk(CK: CodeCompletionString::CK_SemiColon); |
2496 | Results.AddResult(R: Result(Builder.TakeString())); |
2497 | } |
2498 | // For pointers, suggest 'return nullptr' in C++. |
2499 | if (SemaRef.getLangOpts().CPlusPlus11 && |
2500 | (ReturnType->isPointerType() || ReturnType->isMemberPointerType())) { |
2501 | Builder.AddTypedTextChunk(Text: "return nullptr" ); |
2502 | Builder.AddChunk(CK: CodeCompletionString::CK_SemiColon); |
2503 | Results.AddResult(R: Result(Builder.TakeString())); |
2504 | } |
2505 | } |
2506 | |
2507 | // goto identifier ; |
2508 | Builder.AddTypedTextChunk(Text: "goto" ); |
2509 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
2510 | Builder.AddPlaceholderChunk(Placeholder: "label" ); |
2511 | Builder.AddChunk(CK: CodeCompletionString::CK_SemiColon); |
2512 | Results.AddResult(R: Result(Builder.TakeString())); |
2513 | |
2514 | // Using directives |
2515 | Builder.AddTypedTextChunk(Text: "using namespace" ); |
2516 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
2517 | Builder.AddPlaceholderChunk(Placeholder: "identifier" ); |
2518 | Builder.AddChunk(CK: CodeCompletionString::CK_SemiColon); |
2519 | Results.AddResult(R: Result(Builder.TakeString())); |
2520 | |
2521 | AddStaticAssertResult(Builder, Results, LangOpts: SemaRef.getLangOpts()); |
2522 | } |
2523 | [[fallthrough]]; |
2524 | |
2525 | // Fall through (for statement expressions). |
2526 | case Sema::PCC_ForInit: |
2527 | case Sema::PCC_Condition: |
2528 | AddStorageSpecifiers(CCC, LangOpts: SemaRef.getLangOpts(), Results); |
2529 | // Fall through: conditions and statements can have expressions. |
2530 | [[fallthrough]]; |
2531 | |
2532 | case Sema::PCC_ParenthesizedExpression: |
2533 | if (SemaRef.getLangOpts().ObjCAutoRefCount && |
2534 | CCC == Sema::PCC_ParenthesizedExpression) { |
2535 | // (__bridge <type>)<expression> |
2536 | Builder.AddTypedTextChunk(Text: "__bridge" ); |
2537 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
2538 | Builder.AddPlaceholderChunk(Placeholder: "type" ); |
2539 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
2540 | Builder.AddPlaceholderChunk(Placeholder: "expression" ); |
2541 | Results.AddResult(R: Result(Builder.TakeString())); |
2542 | |
2543 | // (__bridge_transfer <Objective-C type>)<expression> |
2544 | Builder.AddTypedTextChunk(Text: "__bridge_transfer" ); |
2545 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
2546 | Builder.AddPlaceholderChunk(Placeholder: "Objective-C type" ); |
2547 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
2548 | Builder.AddPlaceholderChunk(Placeholder: "expression" ); |
2549 | Results.AddResult(R: Result(Builder.TakeString())); |
2550 | |
2551 | // (__bridge_retained <CF type>)<expression> |
2552 | Builder.AddTypedTextChunk(Text: "__bridge_retained" ); |
2553 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
2554 | Builder.AddPlaceholderChunk(Placeholder: "CF type" ); |
2555 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
2556 | Builder.AddPlaceholderChunk(Placeholder: "expression" ); |
2557 | Results.AddResult(R: Result(Builder.TakeString())); |
2558 | } |
2559 | // Fall through |
2560 | [[fallthrough]]; |
2561 | |
2562 | case Sema::PCC_Expression: { |
2563 | if (SemaRef.getLangOpts().CPlusPlus) { |
2564 | // 'this', if we're in a non-static member function. |
2565 | addThisCompletion(S&: SemaRef, Results); |
2566 | |
2567 | // true |
2568 | Builder.AddResultTypeChunk(ResultType: "bool" ); |
2569 | Builder.AddTypedTextChunk(Text: "true" ); |
2570 | Results.AddResult(R: Result(Builder.TakeString())); |
2571 | |
2572 | // false |
2573 | Builder.AddResultTypeChunk(ResultType: "bool" ); |
2574 | Builder.AddTypedTextChunk(Text: "false" ); |
2575 | Results.AddResult(R: Result(Builder.TakeString())); |
2576 | |
2577 | if (SemaRef.getLangOpts().RTTI) { |
2578 | // dynamic_cast < type-id > ( expression ) |
2579 | Builder.AddTypedTextChunk(Text: "dynamic_cast" ); |
2580 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftAngle); |
2581 | Builder.AddPlaceholderChunk(Placeholder: "type" ); |
2582 | Builder.AddChunk(CK: CodeCompletionString::CK_RightAngle); |
2583 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
2584 | Builder.AddPlaceholderChunk(Placeholder: "expression" ); |
2585 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
2586 | Results.AddResult(R: Result(Builder.TakeString())); |
2587 | } |
2588 | |
2589 | // static_cast < type-id > ( expression ) |
2590 | Builder.AddTypedTextChunk(Text: "static_cast" ); |
2591 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftAngle); |
2592 | Builder.AddPlaceholderChunk(Placeholder: "type" ); |
2593 | Builder.AddChunk(CK: CodeCompletionString::CK_RightAngle); |
2594 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
2595 | Builder.AddPlaceholderChunk(Placeholder: "expression" ); |
2596 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
2597 | Results.AddResult(R: Result(Builder.TakeString())); |
2598 | |
2599 | // reinterpret_cast < type-id > ( expression ) |
2600 | Builder.AddTypedTextChunk(Text: "reinterpret_cast" ); |
2601 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftAngle); |
2602 | Builder.AddPlaceholderChunk(Placeholder: "type" ); |
2603 | Builder.AddChunk(CK: CodeCompletionString::CK_RightAngle); |
2604 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
2605 | Builder.AddPlaceholderChunk(Placeholder: "expression" ); |
2606 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
2607 | Results.AddResult(R: Result(Builder.TakeString())); |
2608 | |
2609 | // const_cast < type-id > ( expression ) |
2610 | Builder.AddTypedTextChunk(Text: "const_cast" ); |
2611 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftAngle); |
2612 | Builder.AddPlaceholderChunk(Placeholder: "type" ); |
2613 | Builder.AddChunk(CK: CodeCompletionString::CK_RightAngle); |
2614 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
2615 | Builder.AddPlaceholderChunk(Placeholder: "expression" ); |
2616 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
2617 | Results.AddResult(R: Result(Builder.TakeString())); |
2618 | |
2619 | if (SemaRef.getLangOpts().RTTI) { |
2620 | // typeid ( expression-or-type ) |
2621 | Builder.AddResultTypeChunk(ResultType: "std::type_info" ); |
2622 | Builder.AddTypedTextChunk(Text: "typeid" ); |
2623 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
2624 | Builder.AddPlaceholderChunk(Placeholder: "expression-or-type" ); |
2625 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
2626 | Results.AddResult(R: Result(Builder.TakeString())); |
2627 | } |
2628 | |
2629 | // new T ( ... ) |
2630 | Builder.AddTypedTextChunk(Text: "new" ); |
2631 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
2632 | Builder.AddPlaceholderChunk(Placeholder: "type" ); |
2633 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
2634 | Builder.AddPlaceholderChunk(Placeholder: "expressions" ); |
2635 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
2636 | Results.AddResult(R: Result(Builder.TakeString())); |
2637 | |
2638 | // new T [ ] ( ... ) |
2639 | Builder.AddTypedTextChunk(Text: "new" ); |
2640 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
2641 | Builder.AddPlaceholderChunk(Placeholder: "type" ); |
2642 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftBracket); |
2643 | Builder.AddPlaceholderChunk(Placeholder: "size" ); |
2644 | Builder.AddChunk(CK: CodeCompletionString::CK_RightBracket); |
2645 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
2646 | Builder.AddPlaceholderChunk(Placeholder: "expressions" ); |
2647 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
2648 | Results.AddResult(R: Result(Builder.TakeString())); |
2649 | |
2650 | // delete expression |
2651 | Builder.AddResultTypeChunk(ResultType: "void" ); |
2652 | Builder.AddTypedTextChunk(Text: "delete" ); |
2653 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
2654 | Builder.AddPlaceholderChunk(Placeholder: "expression" ); |
2655 | Results.AddResult(R: Result(Builder.TakeString())); |
2656 | |
2657 | // delete [] expression |
2658 | Builder.AddResultTypeChunk(ResultType: "void" ); |
2659 | Builder.AddTypedTextChunk(Text: "delete" ); |
2660 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
2661 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftBracket); |
2662 | Builder.AddChunk(CK: CodeCompletionString::CK_RightBracket); |
2663 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
2664 | Builder.AddPlaceholderChunk(Placeholder: "expression" ); |
2665 | Results.AddResult(R: Result(Builder.TakeString())); |
2666 | |
2667 | if (SemaRef.getLangOpts().CXXExceptions) { |
2668 | // throw expression |
2669 | Builder.AddResultTypeChunk(ResultType: "void" ); |
2670 | Builder.AddTypedTextChunk(Text: "throw" ); |
2671 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
2672 | Builder.AddPlaceholderChunk(Placeholder: "expression" ); |
2673 | Results.AddResult(R: Result(Builder.TakeString())); |
2674 | } |
2675 | |
2676 | // FIXME: Rethrow? |
2677 | |
2678 | if (SemaRef.getLangOpts().CPlusPlus11) { |
2679 | // nullptr |
2680 | Builder.AddResultTypeChunk(ResultType: "std::nullptr_t" ); |
2681 | Builder.AddTypedTextChunk(Text: "nullptr" ); |
2682 | Results.AddResult(R: Result(Builder.TakeString())); |
2683 | |
2684 | // alignof |
2685 | Builder.AddResultTypeChunk(ResultType: "size_t" ); |
2686 | Builder.AddTypedTextChunk(Text: "alignof" ); |
2687 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
2688 | Builder.AddPlaceholderChunk(Placeholder: "type" ); |
2689 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
2690 | Results.AddResult(R: Result(Builder.TakeString())); |
2691 | |
2692 | // noexcept |
2693 | Builder.AddResultTypeChunk(ResultType: "bool" ); |
2694 | Builder.AddTypedTextChunk(Text: "noexcept" ); |
2695 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
2696 | Builder.AddPlaceholderChunk(Placeholder: "expression" ); |
2697 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
2698 | Results.AddResult(R: Result(Builder.TakeString())); |
2699 | |
2700 | // sizeof... expression |
2701 | Builder.AddResultTypeChunk(ResultType: "size_t" ); |
2702 | Builder.AddTypedTextChunk(Text: "sizeof..." ); |
2703 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
2704 | Builder.AddPlaceholderChunk(Placeholder: "parameter-pack" ); |
2705 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
2706 | Results.AddResult(R: Result(Builder.TakeString())); |
2707 | } |
2708 | } |
2709 | |
2710 | if (SemaRef.getLangOpts().ObjC) { |
2711 | // Add "super", if we're in an Objective-C class with a superclass. |
2712 | if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) { |
2713 | // The interface can be NULL. |
2714 | if (ObjCInterfaceDecl *ID = Method->getClassInterface()) |
2715 | if (ID->getSuperClass()) { |
2716 | std::string SuperType; |
2717 | SuperType = ID->getSuperClass()->getNameAsString(); |
2718 | if (Method->isInstanceMethod()) |
2719 | SuperType += " *" ; |
2720 | |
2721 | Builder.AddResultTypeChunk(ResultType: Allocator.CopyString(String: SuperType)); |
2722 | Builder.AddTypedTextChunk(Text: "super" ); |
2723 | Results.AddResult(R: Result(Builder.TakeString())); |
2724 | } |
2725 | } |
2726 | |
2727 | AddObjCExpressionResults(Results, NeedAt: true); |
2728 | } |
2729 | |
2730 | if (SemaRef.getLangOpts().C11) { |
2731 | // _Alignof |
2732 | Builder.AddResultTypeChunk(ResultType: "size_t" ); |
2733 | if (SemaRef.PP.isMacroDefined(Id: "alignof" )) |
2734 | Builder.AddTypedTextChunk(Text: "alignof" ); |
2735 | else |
2736 | Builder.AddTypedTextChunk(Text: "_Alignof" ); |
2737 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
2738 | Builder.AddPlaceholderChunk(Placeholder: "type" ); |
2739 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
2740 | Results.AddResult(R: Result(Builder.TakeString())); |
2741 | } |
2742 | |
2743 | if (SemaRef.getLangOpts().C23) { |
2744 | // nullptr |
2745 | Builder.AddResultTypeChunk(ResultType: "nullptr_t" ); |
2746 | Builder.AddTypedTextChunk(Text: "nullptr" ); |
2747 | Results.AddResult(R: Result(Builder.TakeString())); |
2748 | } |
2749 | |
2750 | // sizeof expression |
2751 | Builder.AddResultTypeChunk(ResultType: "size_t" ); |
2752 | Builder.AddTypedTextChunk(Text: "sizeof" ); |
2753 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
2754 | Builder.AddPlaceholderChunk(Placeholder: "expression-or-type" ); |
2755 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
2756 | Results.AddResult(R: Result(Builder.TakeString())); |
2757 | break; |
2758 | } |
2759 | |
2760 | case Sema::PCC_Type: |
2761 | case Sema::PCC_LocalDeclarationSpecifiers: |
2762 | break; |
2763 | } |
2764 | |
2765 | if (WantTypesInContext(CCC, LangOpts: SemaRef.getLangOpts())) |
2766 | AddTypeSpecifierResults(LangOpts: SemaRef.getLangOpts(), Results); |
2767 | |
2768 | if (SemaRef.getLangOpts().CPlusPlus && CCC != Sema::PCC_Type) |
2769 | Results.AddResult(R: Result("operator" )); |
2770 | } |
2771 | |
2772 | /// If the given declaration has an associated type, add it as a result |
2773 | /// type chunk. |
2774 | static void AddResultTypeChunk(ASTContext &Context, |
2775 | const PrintingPolicy &Policy, |
2776 | const NamedDecl *ND, QualType BaseType, |
2777 | CodeCompletionBuilder &Result) { |
2778 | if (!ND) |
2779 | return; |
2780 | |
2781 | // Skip constructors and conversion functions, which have their return types |
2782 | // built into their names. |
2783 | if (isConstructor(ND) || isa<CXXConversionDecl>(Val: ND)) |
2784 | return; |
2785 | |
2786 | // Determine the type of the declaration (if it has a type). |
2787 | QualType T; |
2788 | if (const FunctionDecl *Function = ND->getAsFunction()) |
2789 | T = Function->getReturnType(); |
2790 | else if (const auto *Method = dyn_cast<ObjCMethodDecl>(Val: ND)) { |
2791 | if (!BaseType.isNull()) |
2792 | T = Method->getSendResultType(receiverType: BaseType); |
2793 | else |
2794 | T = Method->getReturnType(); |
2795 | } else if (const auto *Enumerator = dyn_cast<EnumConstantDecl>(Val: ND)) { |
2796 | T = Context.getTypeDeclType(Decl: cast<TypeDecl>(Enumerator->getDeclContext())); |
2797 | T = clang::TypeName::getFullyQualifiedType(QT: T, Ctx: Context); |
2798 | } else if (isa<UnresolvedUsingValueDecl>(Val: ND)) { |
2799 | /* Do nothing: ignore unresolved using declarations*/ |
2800 | } else if (const auto *Ivar = dyn_cast<ObjCIvarDecl>(Val: ND)) { |
2801 | if (!BaseType.isNull()) |
2802 | T = Ivar->getUsageType(objectType: BaseType); |
2803 | else |
2804 | T = Ivar->getType(); |
2805 | } else if (const auto *Value = dyn_cast<ValueDecl>(Val: ND)) { |
2806 | T = Value->getType(); |
2807 | } else if (const auto *Property = dyn_cast<ObjCPropertyDecl>(Val: ND)) { |
2808 | if (!BaseType.isNull()) |
2809 | T = Property->getUsageType(objectType: BaseType); |
2810 | else |
2811 | T = Property->getType(); |
2812 | } |
2813 | |
2814 | if (T.isNull() || Context.hasSameType(T, Context.DependentTy)) |
2815 | return; |
2816 | |
2817 | Result.AddResultTypeChunk( |
2818 | ResultType: GetCompletionTypeString(T, Context, Policy, Allocator&: Result.getAllocator())); |
2819 | } |
2820 | |
2821 | static void MaybeAddSentinel(Preprocessor &PP, |
2822 | const NamedDecl *FunctionOrMethod, |
2823 | CodeCompletionBuilder &Result) { |
2824 | if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>()) |
2825 | if (Sentinel->getSentinel() == 0) { |
2826 | if (PP.getLangOpts().ObjC && PP.isMacroDefined(Id: "nil" )) |
2827 | Result.AddTextChunk(Text: ", nil" ); |
2828 | else if (PP.isMacroDefined(Id: "NULL" )) |
2829 | Result.AddTextChunk(Text: ", NULL" ); |
2830 | else |
2831 | Result.AddTextChunk(Text: ", (void*)0" ); |
2832 | } |
2833 | } |
2834 | |
2835 | static std::string formatObjCParamQualifiers(unsigned ObjCQuals, |
2836 | QualType &Type) { |
2837 | std::string Result; |
2838 | if (ObjCQuals & Decl::OBJC_TQ_In) |
2839 | Result += "in " ; |
2840 | else if (ObjCQuals & Decl::OBJC_TQ_Inout) |
2841 | Result += "inout " ; |
2842 | else if (ObjCQuals & Decl::OBJC_TQ_Out) |
2843 | Result += "out " ; |
2844 | if (ObjCQuals & Decl::OBJC_TQ_Bycopy) |
2845 | Result += "bycopy " ; |
2846 | else if (ObjCQuals & Decl::OBJC_TQ_Byref) |
2847 | Result += "byref " ; |
2848 | if (ObjCQuals & Decl::OBJC_TQ_Oneway) |
2849 | Result += "oneway " ; |
2850 | if (ObjCQuals & Decl::OBJC_TQ_CSNullability) { |
2851 | if (auto nullability = AttributedType::stripOuterNullability(T&: Type)) { |
2852 | switch (*nullability) { |
2853 | case NullabilityKind::NonNull: |
2854 | Result += "nonnull " ; |
2855 | break; |
2856 | |
2857 | case NullabilityKind::Nullable: |
2858 | Result += "nullable " ; |
2859 | break; |
2860 | |
2861 | case NullabilityKind::Unspecified: |
2862 | Result += "null_unspecified " ; |
2863 | break; |
2864 | |
2865 | case NullabilityKind::NullableResult: |
2866 | llvm_unreachable("Not supported as a context-sensitive keyword!" ); |
2867 | break; |
2868 | } |
2869 | } |
2870 | } |
2871 | return Result; |
2872 | } |
2873 | |
2874 | /// Tries to find the most appropriate type location for an Objective-C |
2875 | /// block placeholder. |
2876 | /// |
2877 | /// This function ignores things like typedefs and qualifiers in order to |
2878 | /// present the most relevant and accurate block placeholders in code completion |
2879 | /// results. |
2880 | static void findTypeLocationForBlockDecl(const TypeSourceInfo *TSInfo, |
2881 | FunctionTypeLoc &Block, |
2882 | FunctionProtoTypeLoc &BlockProto, |
2883 | bool SuppressBlock = false) { |
2884 | if (!TSInfo) |
2885 | return; |
2886 | TypeLoc TL = TSInfo->getTypeLoc().getUnqualifiedLoc(); |
2887 | while (true) { |
2888 | // Look through typedefs. |
2889 | if (!SuppressBlock) { |
2890 | if (TypedefTypeLoc TypedefTL = TL.getAsAdjusted<TypedefTypeLoc>()) { |
2891 | if (TypeSourceInfo *InnerTSInfo = |
2892 | TypedefTL.getTypedefNameDecl()->getTypeSourceInfo()) { |
2893 | TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc(); |
2894 | continue; |
2895 | } |
2896 | } |
2897 | |
2898 | // Look through qualified types |
2899 | if (QualifiedTypeLoc QualifiedTL = TL.getAs<QualifiedTypeLoc>()) { |
2900 | TL = QualifiedTL.getUnqualifiedLoc(); |
2901 | continue; |
2902 | } |
2903 | |
2904 | if (AttributedTypeLoc AttrTL = TL.getAs<AttributedTypeLoc>()) { |
2905 | TL = AttrTL.getModifiedLoc(); |
2906 | continue; |
2907 | } |
2908 | } |
2909 | |
2910 | // Try to get the function prototype behind the block pointer type, |
2911 | // then we're done. |
2912 | if (BlockPointerTypeLoc BlockPtr = TL.getAs<BlockPointerTypeLoc>()) { |
2913 | TL = BlockPtr.getPointeeLoc().IgnoreParens(); |
2914 | Block = TL.getAs<FunctionTypeLoc>(); |
2915 | BlockProto = TL.getAs<FunctionProtoTypeLoc>(); |
2916 | } |
2917 | break; |
2918 | } |
2919 | } |
2920 | |
2921 | static std::string formatBlockPlaceholder( |
2922 | const PrintingPolicy &Policy, const NamedDecl *BlockDecl, |
2923 | FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto, |
2924 | bool SuppressBlockName = false, bool SuppressBlock = false, |
2925 | std::optional<ArrayRef<QualType>> ObjCSubsts = std::nullopt); |
2926 | |
2927 | static std::string FormatFunctionParameter( |
2928 | const PrintingPolicy &Policy, const DeclaratorDecl *Param, |
2929 | bool SuppressName = false, bool SuppressBlock = false, |
2930 | std::optional<ArrayRef<QualType>> ObjCSubsts = std::nullopt) { |
2931 | // Params are unavailable in FunctionTypeLoc if the FunctionType is invalid. |
2932 | // It would be better to pass in the param Type, which is usually available. |
2933 | // But this case is rare, so just pretend we fell back to int as elsewhere. |
2934 | if (!Param) |
2935 | return "int" ; |
2936 | Decl::ObjCDeclQualifier ObjCQual = Decl::OBJC_TQ_None; |
2937 | if (const auto *PVD = dyn_cast<ParmVarDecl>(Val: Param)) |
2938 | ObjCQual = PVD->getObjCDeclQualifier(); |
2939 | bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext()); |
2940 | if (Param->getType()->isDependentType() || |
2941 | !Param->getType()->isBlockPointerType()) { |
2942 | // The argument for a dependent or non-block parameter is a placeholder |
2943 | // containing that parameter's type. |
2944 | std::string Result; |
2945 | |
2946 | if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName) |
2947 | Result = std::string(Param->getIdentifier()->deuglifiedName()); |
2948 | |
2949 | QualType Type = Param->getType(); |
2950 | if (ObjCSubsts) |
2951 | Type = Type.substObjCTypeArgs(ctx&: Param->getASTContext(), typeArgs: *ObjCSubsts, |
2952 | context: ObjCSubstitutionContext::Parameter); |
2953 | if (ObjCMethodParam) { |
2954 | Result = "(" + formatObjCParamQualifiers(ObjCQuals: ObjCQual, Type); |
2955 | Result += Type.getAsString(Policy) + ")" ; |
2956 | if (Param->getIdentifier() && !SuppressName) |
2957 | Result += Param->getIdentifier()->deuglifiedName(); |
2958 | } else { |
2959 | Type.getAsStringInternal(Str&: Result, Policy); |
2960 | } |
2961 | return Result; |
2962 | } |
2963 | |
2964 | // The argument for a block pointer parameter is a block literal with |
2965 | // the appropriate type. |
2966 | FunctionTypeLoc Block; |
2967 | FunctionProtoTypeLoc BlockProto; |
2968 | findTypeLocationForBlockDecl(TSInfo: Param->getTypeSourceInfo(), Block, BlockProto, |
2969 | SuppressBlock); |
2970 | // Try to retrieve the block type information from the property if this is a |
2971 | // parameter in a setter. |
2972 | if (!Block && ObjCMethodParam && |
2973 | cast<ObjCMethodDecl>(Param->getDeclContext())->isPropertyAccessor()) { |
2974 | if (const auto *PD = cast<ObjCMethodDecl>(Param->getDeclContext()) |
2975 | ->findPropertyDecl(/*CheckOverrides=*/false)) |
2976 | findTypeLocationForBlockDecl(PD->getTypeSourceInfo(), Block, BlockProto, |
2977 | SuppressBlock); |
2978 | } |
2979 | |
2980 | if (!Block) { |
2981 | // We were unable to find a FunctionProtoTypeLoc with parameter names |
2982 | // for the block; just use the parameter type as a placeholder. |
2983 | std::string Result; |
2984 | if (!ObjCMethodParam && Param->getIdentifier()) |
2985 | Result = std::string(Param->getIdentifier()->deuglifiedName()); |
2986 | |
2987 | QualType Type = Param->getType().getUnqualifiedType(); |
2988 | |
2989 | if (ObjCMethodParam) { |
2990 | Result = Type.getAsString(Policy); |
2991 | std::string Quals = formatObjCParamQualifiers(ObjCQuals: ObjCQual, Type); |
2992 | if (!Quals.empty()) |
2993 | Result = "(" + Quals + " " + Result + ")" ; |
2994 | if (Result.back() != ')') |
2995 | Result += " " ; |
2996 | if (Param->getIdentifier()) |
2997 | Result += Param->getIdentifier()->deuglifiedName(); |
2998 | } else { |
2999 | Type.getAsStringInternal(Str&: Result, Policy); |
3000 | } |
3001 | |
3002 | return Result; |
3003 | } |
3004 | |
3005 | // We have the function prototype behind the block pointer type, as it was |
3006 | // written in the source. |
3007 | return formatBlockPlaceholder(Policy, Param, Block, BlockProto, |
3008 | /*SuppressBlockName=*/false, SuppressBlock, |
3009 | ObjCSubsts); |
3010 | } |
3011 | |
3012 | /// Returns a placeholder string that corresponds to an Objective-C block |
3013 | /// declaration. |
3014 | /// |
3015 | /// \param BlockDecl A declaration with an Objective-C block type. |
3016 | /// |
3017 | /// \param Block The most relevant type location for that block type. |
3018 | /// |
3019 | /// \param SuppressBlockName Determines whether or not the name of the block |
3020 | /// declaration is included in the resulting string. |
3021 | static std::string |
3022 | formatBlockPlaceholder(const PrintingPolicy &Policy, const NamedDecl *BlockDecl, |
3023 | FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto, |
3024 | bool SuppressBlockName, bool SuppressBlock, |
3025 | std::optional<ArrayRef<QualType>> ObjCSubsts) { |
3026 | std::string Result; |
3027 | QualType ResultType = Block.getTypePtr()->getReturnType(); |
3028 | if (ObjCSubsts) |
3029 | ResultType = |
3030 | ResultType.substObjCTypeArgs(ctx&: BlockDecl->getASTContext(), typeArgs: *ObjCSubsts, |
3031 | context: ObjCSubstitutionContext::Result); |
3032 | if (!ResultType->isVoidType() || SuppressBlock) |
3033 | ResultType.getAsStringInternal(Str&: Result, Policy); |
3034 | |
3035 | // Format the parameter list. |
3036 | std::string Params; |
3037 | if (!BlockProto || Block.getNumParams() == 0) { |
3038 | if (BlockProto && BlockProto.getTypePtr()->isVariadic()) |
3039 | Params = "(...)" ; |
3040 | else |
3041 | Params = "(void)" ; |
3042 | } else { |
3043 | Params += "(" ; |
3044 | for (unsigned I = 0, N = Block.getNumParams(); I != N; ++I) { |
3045 | if (I) |
3046 | Params += ", " ; |
3047 | Params += FormatFunctionParameter(Policy, Block.getParam(i: I), |
3048 | /*SuppressName=*/false, |
3049 | /*SuppressBlock=*/true, ObjCSubsts); |
3050 | |
3051 | if (I == N - 1 && BlockProto.getTypePtr()->isVariadic()) |
3052 | Params += ", ..." ; |
3053 | } |
3054 | Params += ")" ; |
3055 | } |
3056 | |
3057 | if (SuppressBlock) { |
3058 | // Format as a parameter. |
3059 | Result = Result + " (^" ; |
3060 | if (!SuppressBlockName && BlockDecl->getIdentifier()) |
3061 | Result += BlockDecl->getIdentifier()->getName(); |
3062 | Result += ")" ; |
3063 | Result += Params; |
3064 | } else { |
3065 | // Format as a block literal argument. |
3066 | Result = '^' + Result; |
3067 | Result += Params; |
3068 | |
3069 | if (!SuppressBlockName && BlockDecl->getIdentifier()) |
3070 | Result += BlockDecl->getIdentifier()->getName(); |
3071 | } |
3072 | |
3073 | return Result; |
3074 | } |
3075 | |
3076 | static std::string GetDefaultValueString(const ParmVarDecl *Param, |
3077 | const SourceManager &SM, |
3078 | const LangOptions &LangOpts) { |
3079 | const SourceRange SrcRange = Param->getDefaultArgRange(); |
3080 | CharSourceRange CharSrcRange = CharSourceRange::getTokenRange(R: SrcRange); |
3081 | bool Invalid = CharSrcRange.isInvalid(); |
3082 | if (Invalid) |
3083 | return "" ; |
3084 | StringRef srcText = |
3085 | Lexer::getSourceText(Range: CharSrcRange, SM, LangOpts, Invalid: &Invalid); |
3086 | if (Invalid) |
3087 | return "" ; |
3088 | |
3089 | if (srcText.empty() || srcText == "=" ) { |
3090 | // Lexer can't determine the value. |
3091 | // This happens if the code is incorrect (for example class is forward |
3092 | // declared). |
3093 | return "" ; |
3094 | } |
3095 | std::string DefValue(srcText.str()); |
3096 | // FIXME: remove this check if the Lexer::getSourceText value is fixed and |
3097 | // this value always has (or always does not have) '=' in front of it |
3098 | if (DefValue.at(n: 0) != '=') { |
3099 | // If we don't have '=' in front of value. |
3100 | // Lexer returns built-in types values without '=' and user-defined types |
3101 | // values with it. |
3102 | return " = " + DefValue; |
3103 | } |
3104 | return " " + DefValue; |
3105 | } |
3106 | |
3107 | /// Add function parameter chunks to the given code completion string. |
3108 | static void AddFunctionParameterChunks(Preprocessor &PP, |
3109 | const PrintingPolicy &Policy, |
3110 | const FunctionDecl *Function, |
3111 | CodeCompletionBuilder &Result, |
3112 | unsigned Start = 0, |
3113 | bool InOptional = false) { |
3114 | bool FirstParameter = true; |
3115 | |
3116 | for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) { |
3117 | const ParmVarDecl *Param = Function->getParamDecl(i: P); |
3118 | |
3119 | if (Param->hasDefaultArg() && !InOptional) { |
3120 | // When we see an optional default argument, put that argument and |
3121 | // the remaining default arguments into a new, optional string. |
3122 | CodeCompletionBuilder Opt(Result.getAllocator(), |
3123 | Result.getCodeCompletionTUInfo()); |
3124 | if (!FirstParameter) |
3125 | Opt.AddChunk(CK: CodeCompletionString::CK_Comma); |
3126 | AddFunctionParameterChunks(PP, Policy, Function, Result&: Opt, Start: P, InOptional: true); |
3127 | Result.AddOptionalChunk(Optional: Opt.TakeString()); |
3128 | break; |
3129 | } |
3130 | |
3131 | if (FirstParameter) |
3132 | FirstParameter = false; |
3133 | else |
3134 | Result.AddChunk(CK: CodeCompletionString::CK_Comma); |
3135 | |
3136 | InOptional = false; |
3137 | |
3138 | // Format the placeholder string. |
3139 | std::string PlaceholderStr = FormatFunctionParameter(Policy, Param); |
3140 | if (Param->hasDefaultArg()) |
3141 | PlaceholderStr += |
3142 | GetDefaultValueString(Param, SM: PP.getSourceManager(), LangOpts: PP.getLangOpts()); |
3143 | |
3144 | if (Function->isVariadic() && P == N - 1) |
3145 | PlaceholderStr += ", ..." ; |
3146 | |
3147 | // Add the placeholder string. |
3148 | Result.AddPlaceholderChunk( |
3149 | Placeholder: Result.getAllocator().CopyString(String: PlaceholderStr)); |
3150 | } |
3151 | |
3152 | if (const auto *Proto = Function->getType()->getAs<FunctionProtoType>()) |
3153 | if (Proto->isVariadic()) { |
3154 | if (Proto->getNumParams() == 0) |
3155 | Result.AddPlaceholderChunk(Placeholder: "..." ); |
3156 | |
3157 | MaybeAddSentinel(PP, Function, Result); |
3158 | } |
3159 | } |
3160 | |
3161 | /// Add template parameter chunks to the given code completion string. |
3162 | static void AddTemplateParameterChunks( |
3163 | ASTContext &Context, const PrintingPolicy &Policy, |
3164 | const TemplateDecl *Template, CodeCompletionBuilder &Result, |
3165 | unsigned MaxParameters = 0, unsigned Start = 0, bool InDefaultArg = false) { |
3166 | bool FirstParameter = true; |
3167 | |
3168 | // Prefer to take the template parameter names from the first declaration of |
3169 | // the template. |
3170 | Template = cast<TemplateDecl>(Template->getCanonicalDecl()); |
3171 | |
3172 | TemplateParameterList *Params = Template->getTemplateParameters(); |
3173 | TemplateParameterList::iterator PEnd = Params->end(); |
3174 | if (MaxParameters) |
3175 | PEnd = Params->begin() + MaxParameters; |
3176 | for (TemplateParameterList::iterator P = Params->begin() + Start; P != PEnd; |
3177 | ++P) { |
3178 | bool HasDefaultArg = false; |
3179 | std::string PlaceholderStr; |
3180 | if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: *P)) { |
3181 | if (TTP->wasDeclaredWithTypename()) |
3182 | PlaceholderStr = "typename" ; |
3183 | else if (const auto *TC = TTP->getTypeConstraint()) { |
3184 | llvm::raw_string_ostream OS(PlaceholderStr); |
3185 | TC->print(OS, Policy); |
3186 | OS.flush(); |
3187 | } else |
3188 | PlaceholderStr = "class" ; |
3189 | |
3190 | if (TTP->getIdentifier()) { |
3191 | PlaceholderStr += ' '; |
3192 | PlaceholderStr += TTP->getIdentifier()->deuglifiedName(); |
3193 | } |
3194 | |
3195 | HasDefaultArg = TTP->hasDefaultArgument(); |
3196 | } else if (NonTypeTemplateParmDecl *NTTP = |
3197 | dyn_cast<NonTypeTemplateParmDecl>(Val: *P)) { |
3198 | if (NTTP->getIdentifier()) |
3199 | PlaceholderStr = std::string(NTTP->getIdentifier()->deuglifiedName()); |
3200 | NTTP->getType().getAsStringInternal(PlaceholderStr, Policy); |
3201 | HasDefaultArg = NTTP->hasDefaultArgument(); |
3202 | } else { |
3203 | assert(isa<TemplateTemplateParmDecl>(*P)); |
3204 | TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Val: *P); |
3205 | |
3206 | // Since putting the template argument list into the placeholder would |
3207 | // be very, very long, we just use an abbreviation. |
3208 | PlaceholderStr = "template<...> class" ; |
3209 | if (TTP->getIdentifier()) { |
3210 | PlaceholderStr += ' '; |
3211 | PlaceholderStr += TTP->getIdentifier()->deuglifiedName(); |
3212 | } |
3213 | |
3214 | HasDefaultArg = TTP->hasDefaultArgument(); |
3215 | } |
3216 | |
3217 | if (HasDefaultArg && !InDefaultArg) { |
3218 | // When we see an optional default argument, put that argument and |
3219 | // the remaining default arguments into a new, optional string. |
3220 | CodeCompletionBuilder Opt(Result.getAllocator(), |
3221 | Result.getCodeCompletionTUInfo()); |
3222 | if (!FirstParameter) |
3223 | Opt.AddChunk(CK: CodeCompletionString::CK_Comma); |
3224 | AddTemplateParameterChunks(Context, Policy, Template, Result&: Opt, MaxParameters, |
3225 | Start: P - Params->begin(), InDefaultArg: true); |
3226 | Result.AddOptionalChunk(Optional: Opt.TakeString()); |
3227 | break; |
3228 | } |
3229 | |
3230 | InDefaultArg = false; |
3231 | |
3232 | if (FirstParameter) |
3233 | FirstParameter = false; |
3234 | else |
3235 | Result.AddChunk(CK: CodeCompletionString::CK_Comma); |
3236 | |
3237 | // Add the placeholder string. |
3238 | Result.AddPlaceholderChunk( |
3239 | Placeholder: Result.getAllocator().CopyString(String: PlaceholderStr)); |
3240 | } |
3241 | } |
3242 | |
3243 | /// Add a qualifier to the given code-completion string, if the |
3244 | /// provided nested-name-specifier is non-NULL. |
3245 | static void AddQualifierToCompletionString(CodeCompletionBuilder &Result, |
3246 | NestedNameSpecifier *Qualifier, |
3247 | bool QualifierIsInformative, |
3248 | ASTContext &Context, |
3249 | const PrintingPolicy &Policy) { |
3250 | if (!Qualifier) |
3251 | return; |
3252 | |
3253 | std::string PrintedNNS; |
3254 | { |
3255 | llvm::raw_string_ostream OS(PrintedNNS); |
3256 | Qualifier->print(OS, Policy); |
3257 | } |
3258 | if (QualifierIsInformative) |
3259 | Result.AddInformativeChunk(Text: Result.getAllocator().CopyString(String: PrintedNNS)); |
3260 | else |
3261 | Result.AddTextChunk(Text: Result.getAllocator().CopyString(String: PrintedNNS)); |
3262 | } |
3263 | |
3264 | static void |
3265 | AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result, |
3266 | const FunctionDecl *Function) { |
3267 | const auto *Proto = Function->getType()->getAs<FunctionProtoType>(); |
3268 | if (!Proto || !Proto->getMethodQuals()) |
3269 | return; |
3270 | |
3271 | // FIXME: Add ref-qualifier! |
3272 | |
3273 | // Handle single qualifiers without copying |
3274 | if (Proto->getMethodQuals().hasOnlyConst()) { |
3275 | Result.AddInformativeChunk(Text: " const" ); |
3276 | return; |
3277 | } |
3278 | |
3279 | if (Proto->getMethodQuals().hasOnlyVolatile()) { |
3280 | Result.AddInformativeChunk(Text: " volatile" ); |
3281 | return; |
3282 | } |
3283 | |
3284 | if (Proto->getMethodQuals().hasOnlyRestrict()) { |
3285 | Result.AddInformativeChunk(Text: " restrict" ); |
3286 | return; |
3287 | } |
3288 | |
3289 | // Handle multiple qualifiers. |
3290 | std::string QualsStr; |
3291 | if (Proto->isConst()) |
3292 | QualsStr += " const" ; |
3293 | if (Proto->isVolatile()) |
3294 | QualsStr += " volatile" ; |
3295 | if (Proto->isRestrict()) |
3296 | QualsStr += " restrict" ; |
3297 | Result.AddInformativeChunk(Text: Result.getAllocator().CopyString(String: QualsStr)); |
3298 | } |
3299 | |
3300 | /// Add the name of the given declaration |
3301 | static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy, |
3302 | const NamedDecl *ND, |
3303 | CodeCompletionBuilder &Result) { |
3304 | DeclarationName Name = ND->getDeclName(); |
3305 | if (!Name) |
3306 | return; |
3307 | |
3308 | switch (Name.getNameKind()) { |
3309 | case DeclarationName::CXXOperatorName: { |
3310 | const char *OperatorName = nullptr; |
3311 | switch (Name.getCXXOverloadedOperator()) { |
3312 | case OO_None: |
3313 | case OO_Conditional: |
3314 | case NUM_OVERLOADED_OPERATORS: |
3315 | OperatorName = "operator" ; |
3316 | break; |
3317 | |
3318 | #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \ |
3319 | case OO_##Name: \ |
3320 | OperatorName = "operator" Spelling; \ |
3321 | break; |
3322 | #define OVERLOADED_OPERATOR_MULTI(Name, Spelling, Unary, Binary, MemberOnly) |
3323 | #include "clang/Basic/OperatorKinds.def" |
3324 | |
3325 | case OO_New: |
3326 | OperatorName = "operator new" ; |
3327 | break; |
3328 | case OO_Delete: |
3329 | OperatorName = "operator delete" ; |
3330 | break; |
3331 | case OO_Array_New: |
3332 | OperatorName = "operator new[]" ; |
3333 | break; |
3334 | case OO_Array_Delete: |
3335 | OperatorName = "operator delete[]" ; |
3336 | break; |
3337 | case OO_Call: |
3338 | OperatorName = "operator()" ; |
3339 | break; |
3340 | case OO_Subscript: |
3341 | OperatorName = "operator[]" ; |
3342 | break; |
3343 | } |
3344 | Result.AddTypedTextChunk(Text: OperatorName); |
3345 | break; |
3346 | } |
3347 | |
3348 | case DeclarationName::Identifier: |
3349 | case DeclarationName::CXXConversionFunctionName: |
3350 | case DeclarationName::CXXDestructorName: |
3351 | case DeclarationName::CXXLiteralOperatorName: |
3352 | Result.AddTypedTextChunk( |
3353 | Text: Result.getAllocator().CopyString(String: ND->getNameAsString())); |
3354 | break; |
3355 | |
3356 | case DeclarationName::CXXDeductionGuideName: |
3357 | case DeclarationName::CXXUsingDirective: |
3358 | case DeclarationName::ObjCZeroArgSelector: |
3359 | case DeclarationName::ObjCOneArgSelector: |
3360 | case DeclarationName::ObjCMultiArgSelector: |
3361 | break; |
3362 | |
3363 | case DeclarationName::CXXConstructorName: { |
3364 | CXXRecordDecl *Record = nullptr; |
3365 | QualType Ty = Name.getCXXNameType(); |
3366 | if (const auto *RecordTy = Ty->getAs<RecordType>()) |
3367 | Record = cast<CXXRecordDecl>(Val: RecordTy->getDecl()); |
3368 | else if (const auto *InjectedTy = Ty->getAs<InjectedClassNameType>()) |
3369 | Record = InjectedTy->getDecl(); |
3370 | else { |
3371 | Result.AddTypedTextChunk( |
3372 | Text: Result.getAllocator().CopyString(String: ND->getNameAsString())); |
3373 | break; |
3374 | } |
3375 | |
3376 | Result.AddTypedTextChunk( |
3377 | Text: Result.getAllocator().CopyString(String: Record->getNameAsString())); |
3378 | if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) { |
3379 | Result.AddChunk(CK: CodeCompletionString::CK_LeftAngle); |
3380 | AddTemplateParameterChunks(Context, Policy, Template, Result); |
3381 | Result.AddChunk(CK: CodeCompletionString::CK_RightAngle); |
3382 | } |
3383 | break; |
3384 | } |
3385 | } |
3386 | } |
3387 | |
3388 | CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString( |
3389 | Sema &S, const CodeCompletionContext &CCContext, |
3390 | CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo, |
3391 | bool ) { |
3392 | return CreateCodeCompletionString(Ctx&: S.Context, PP&: S.PP, CCContext, Allocator, |
3393 | CCTUInfo, IncludeBriefComments); |
3394 | } |
3395 | |
3396 | CodeCompletionString *CodeCompletionResult::CreateCodeCompletionStringForMacro( |
3397 | Preprocessor &PP, CodeCompletionAllocator &Allocator, |
3398 | CodeCompletionTUInfo &CCTUInfo) { |
3399 | assert(Kind == RK_Macro); |
3400 | CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability); |
3401 | const MacroInfo *MI = PP.getMacroInfo(II: Macro); |
3402 | Result.AddTypedTextChunk(Text: Result.getAllocator().CopyString(String: Macro->getName())); |
3403 | |
3404 | if (!MI || !MI->isFunctionLike()) |
3405 | return Result.TakeString(); |
3406 | |
3407 | // Format a function-like macro with placeholders for the arguments. |
3408 | Result.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
3409 | MacroInfo::param_iterator A = MI->param_begin(), AEnd = MI->param_end(); |
3410 | |
3411 | // C99 variadic macros add __VA_ARGS__ at the end. Skip it. |
3412 | if (MI->isC99Varargs()) { |
3413 | --AEnd; |
3414 | |
3415 | if (A == AEnd) { |
3416 | Result.AddPlaceholderChunk(Placeholder: "..." ); |
3417 | } |
3418 | } |
3419 | |
3420 | for (MacroInfo::param_iterator A = MI->param_begin(); A != AEnd; ++A) { |
3421 | if (A != MI->param_begin()) |
3422 | Result.AddChunk(CK: CodeCompletionString::CK_Comma); |
3423 | |
3424 | if (MI->isVariadic() && (A + 1) == AEnd) { |
3425 | SmallString<32> Arg = (*A)->getName(); |
3426 | if (MI->isC99Varargs()) |
3427 | Arg += ", ..." ; |
3428 | else |
3429 | Arg += "..." ; |
3430 | Result.AddPlaceholderChunk(Placeholder: Result.getAllocator().CopyString(String: Arg)); |
3431 | break; |
3432 | } |
3433 | |
3434 | // Non-variadic macros are simple. |
3435 | Result.AddPlaceholderChunk( |
3436 | Placeholder: Result.getAllocator().CopyString(String: (*A)->getName())); |
3437 | } |
3438 | Result.AddChunk(CK: CodeCompletionString::CK_RightParen); |
3439 | return Result.TakeString(); |
3440 | } |
3441 | |
3442 | /// If possible, create a new code completion string for the given |
3443 | /// result. |
3444 | /// |
3445 | /// \returns Either a new, heap-allocated code completion string describing |
3446 | /// how to use this result, or NULL to indicate that the string or name of the |
3447 | /// result is all that is needed. |
3448 | CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString( |
3449 | ASTContext &Ctx, Preprocessor &PP, const CodeCompletionContext &CCContext, |
3450 | CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo, |
3451 | bool ) { |
3452 | if (Kind == RK_Macro) |
3453 | return CreateCodeCompletionStringForMacro(PP, Allocator, CCTUInfo); |
3454 | |
3455 | CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability); |
3456 | |
3457 | PrintingPolicy Policy = getCompletionPrintingPolicy(Context: Ctx, PP); |
3458 | if (Kind == RK_Pattern) { |
3459 | Pattern->Priority = Priority; |
3460 | Pattern->Availability = Availability; |
3461 | |
3462 | if (Declaration) { |
3463 | Result.addParentContext(DC: Declaration->getDeclContext()); |
3464 | Pattern->ParentName = Result.getParentName(); |
3465 | if (const RawComment *RC = |
3466 | getPatternCompletionComment(Ctx, Decl: Declaration)) { |
3467 | Result.addBriefComment(Comment: RC->getBriefText(Context: Ctx)); |
3468 | Pattern->BriefComment = Result.getBriefComment(); |
3469 | } |
3470 | } |
3471 | |
3472 | return Pattern; |
3473 | } |
3474 | |
3475 | if (Kind == RK_Keyword) { |
3476 | Result.AddTypedTextChunk(Text: Keyword); |
3477 | return Result.TakeString(); |
3478 | } |
3479 | assert(Kind == RK_Declaration && "Missed a result kind?" ); |
3480 | return createCodeCompletionStringForDecl( |
3481 | PP, Ctx, Result, IncludeBriefComments, CCContext, Policy); |
3482 | } |
3483 | |
3484 | static void printOverrideString(const CodeCompletionString &CCS, |
3485 | std::string &BeforeName, |
3486 | std::string &NameAndSignature) { |
3487 | bool SeenTypedChunk = false; |
3488 | for (auto &Chunk : CCS) { |
3489 | if (Chunk.Kind == CodeCompletionString::CK_Optional) { |
3490 | assert(SeenTypedChunk && "optional parameter before name" ); |
3491 | // Note that we put all chunks inside into NameAndSignature. |
3492 | printOverrideString(CCS: *Chunk.Optional, BeforeName&: NameAndSignature, NameAndSignature); |
3493 | continue; |
3494 | } |
3495 | SeenTypedChunk |= Chunk.Kind == CodeCompletionString::CK_TypedText; |
3496 | if (SeenTypedChunk) |
3497 | NameAndSignature += Chunk.Text; |
3498 | else |
3499 | BeforeName += Chunk.Text; |
3500 | } |
3501 | } |
3502 | |
3503 | CodeCompletionString * |
3504 | CodeCompletionResult::createCodeCompletionStringForOverride( |
3505 | Preprocessor &PP, ASTContext &Ctx, CodeCompletionBuilder &Result, |
3506 | bool , const CodeCompletionContext &CCContext, |
3507 | PrintingPolicy &Policy) { |
3508 | auto *CCS = createCodeCompletionStringForDecl(PP, Ctx, Result, |
3509 | /*IncludeBriefComments=*/false, |
3510 | CCContext, Policy); |
3511 | std::string BeforeName; |
3512 | std::string NameAndSignature; |
3513 | // For overrides all chunks go into the result, none are informative. |
3514 | printOverrideString(CCS: *CCS, BeforeName, NameAndSignature); |
3515 | NameAndSignature += " override" ; |
3516 | |
3517 | Result.AddTextChunk(Text: Result.getAllocator().CopyString(String: BeforeName)); |
3518 | Result.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
3519 | Result.AddTypedTextChunk(Text: Result.getAllocator().CopyString(String: NameAndSignature)); |
3520 | return Result.TakeString(); |
3521 | } |
3522 | |
3523 | // FIXME: Right now this works well with lambdas. Add support for other functor |
3524 | // types like std::function. |
3525 | static const NamedDecl *(const NamedDecl *ND) { |
3526 | const auto *VD = dyn_cast<VarDecl>(Val: ND); |
3527 | if (!VD) |
3528 | return nullptr; |
3529 | const auto *RecordDecl = VD->getType()->getAsCXXRecordDecl(); |
3530 | if (!RecordDecl || !RecordDecl->isLambda()) |
3531 | return nullptr; |
3532 | return RecordDecl->getLambdaCallOperator(); |
3533 | } |
3534 | |
3535 | CodeCompletionString *CodeCompletionResult::createCodeCompletionStringForDecl( |
3536 | Preprocessor &PP, ASTContext &Ctx, CodeCompletionBuilder &Result, |
3537 | bool , const CodeCompletionContext &CCContext, |
3538 | PrintingPolicy &Policy) { |
3539 | const NamedDecl *ND = Declaration; |
3540 | Result.addParentContext(DC: ND->getDeclContext()); |
3541 | |
3542 | if (IncludeBriefComments) { |
3543 | // Add documentation comment, if it exists. |
3544 | if (const RawComment *RC = getCompletionComment(Ctx, Decl: Declaration)) { |
3545 | Result.addBriefComment(Comment: RC->getBriefText(Context: Ctx)); |
3546 | } |
3547 | } |
3548 | |
3549 | if (StartsNestedNameSpecifier) { |
3550 | Result.AddTypedTextChunk( |
3551 | Text: Result.getAllocator().CopyString(String: ND->getNameAsString())); |
3552 | Result.AddTextChunk(Text: "::" ); |
3553 | return Result.TakeString(); |
3554 | } |
3555 | |
3556 | for (const auto *I : ND->specific_attrs<AnnotateAttr>()) |
3557 | Result.AddAnnotation(Result.getAllocator().CopyString(I->getAnnotation())); |
3558 | |
3559 | auto AddFunctionTypeAndResult = [&](const FunctionDecl *Function) { |
3560 | AddResultTypeChunk(Ctx, Policy, Function, CCContext.getBaseType(), Result); |
3561 | AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative, |
3562 | Context&: Ctx, Policy); |
3563 | AddTypedNameChunk(Context&: Ctx, Policy, ND, Result); |
3564 | Result.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
3565 | AddFunctionParameterChunks(PP, Policy, Function, Result); |
3566 | Result.AddChunk(CK: CodeCompletionString::CK_RightParen); |
3567 | AddFunctionTypeQualsToCompletionString(Result, Function); |
3568 | }; |
3569 | |
3570 | if (const auto *Function = dyn_cast<FunctionDecl>(Val: ND)) { |
3571 | AddFunctionTypeAndResult(Function); |
3572 | return Result.TakeString(); |
3573 | } |
3574 | |
3575 | if (const auto *CallOperator = |
3576 | dyn_cast_or_null<FunctionDecl>(Val: extractFunctorCallOperator(ND))) { |
3577 | AddFunctionTypeAndResult(CallOperator); |
3578 | return Result.TakeString(); |
3579 | } |
3580 | |
3581 | AddResultTypeChunk(Context&: Ctx, Policy, ND, BaseType: CCContext.getBaseType(), Result); |
3582 | |
3583 | if (const FunctionTemplateDecl *FunTmpl = |
3584 | dyn_cast<FunctionTemplateDecl>(Val: ND)) { |
3585 | AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative, |
3586 | Context&: Ctx, Policy); |
3587 | FunctionDecl *Function = FunTmpl->getTemplatedDecl(); |
3588 | AddTypedNameChunk(Ctx, Policy, Function, Result); |
3589 | |
3590 | // Figure out which template parameters are deduced (or have default |
3591 | // arguments). |
3592 | // Note that we're creating a non-empty bit vector so that we can go |
3593 | // through the loop below to omit default template parameters for non-call |
3594 | // cases. |
3595 | llvm::SmallBitVector Deduced(FunTmpl->getTemplateParameters()->size()); |
3596 | // Avoid running it if this is not a call: We should emit *all* template |
3597 | // parameters. |
3598 | if (FunctionCanBeCall) |
3599 | Sema::MarkDeducedTemplateParameters(Ctx, FunctionTemplate: FunTmpl, Deduced); |
3600 | unsigned LastDeducibleArgument; |
3601 | for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0; |
3602 | --LastDeducibleArgument) { |
3603 | if (!Deduced[LastDeducibleArgument - 1]) { |
3604 | // C++0x: Figure out if the template argument has a default. If so, |
3605 | // the user doesn't need to type this argument. |
3606 | // FIXME: We need to abstract template parameters better! |
3607 | bool HasDefaultArg = false; |
3608 | NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam( |
3609 | LastDeducibleArgument - 1); |
3610 | if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: Param)) |
3611 | HasDefaultArg = TTP->hasDefaultArgument(); |
3612 | else if (NonTypeTemplateParmDecl *NTTP = |
3613 | dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) |
3614 | HasDefaultArg = NTTP->hasDefaultArgument(); |
3615 | else { |
3616 | assert(isa<TemplateTemplateParmDecl>(Param)); |
3617 | HasDefaultArg = |
3618 | cast<TemplateTemplateParmDecl>(Val: Param)->hasDefaultArgument(); |
3619 | } |
3620 | |
3621 | if (!HasDefaultArg) |
3622 | break; |
3623 | } |
3624 | } |
3625 | |
3626 | if (LastDeducibleArgument || !FunctionCanBeCall) { |
3627 | // Some of the function template arguments cannot be deduced from a |
3628 | // function call, so we introduce an explicit template argument list |
3629 | // containing all of the arguments up to the first deducible argument. |
3630 | // |
3631 | // Or, if this isn't a call, emit all the template arguments |
3632 | // to disambiguate the (potential) overloads. |
3633 | // |
3634 | // FIXME: Detect cases where the function parameters can be deduced from |
3635 | // the surrounding context, as per [temp.deduct.funcaddr]. |
3636 | // e.g., |
3637 | // template <class T> void foo(T); |
3638 | // void (*f)(int) = foo; |
3639 | Result.AddChunk(CK: CodeCompletionString::CK_LeftAngle); |
3640 | AddTemplateParameterChunks(Ctx, Policy, FunTmpl, Result, |
3641 | LastDeducibleArgument); |
3642 | Result.AddChunk(CK: CodeCompletionString::CK_RightAngle); |
3643 | } |
3644 | |
3645 | // Add the function parameters |
3646 | Result.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
3647 | AddFunctionParameterChunks(PP, Policy, Function, Result); |
3648 | Result.AddChunk(CK: CodeCompletionString::CK_RightParen); |
3649 | AddFunctionTypeQualsToCompletionString(Result, Function); |
3650 | return Result.TakeString(); |
3651 | } |
3652 | |
3653 | if (const auto *Template = dyn_cast<TemplateDecl>(Val: ND)) { |
3654 | AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative, |
3655 | Context&: Ctx, Policy); |
3656 | Result.AddTypedTextChunk( |
3657 | Text: Result.getAllocator().CopyString(String: Template->getNameAsString())); |
3658 | Result.AddChunk(CK: CodeCompletionString::CK_LeftAngle); |
3659 | AddTemplateParameterChunks(Context&: Ctx, Policy, Template, Result); |
3660 | Result.AddChunk(CK: CodeCompletionString::CK_RightAngle); |
3661 | return Result.TakeString(); |
3662 | } |
3663 | |
3664 | if (const auto *Method = dyn_cast<ObjCMethodDecl>(Val: ND)) { |
3665 | Selector Sel = Method->getSelector(); |
3666 | if (Sel.isUnarySelector()) { |
3667 | Result.AddTypedTextChunk( |
3668 | Text: Result.getAllocator().CopyString(String: Sel.getNameForSlot(argIndex: 0))); |
3669 | return Result.TakeString(); |
3670 | } |
3671 | |
3672 | std::string SelName = Sel.getNameForSlot(argIndex: 0).str(); |
3673 | SelName += ':'; |
3674 | if (StartParameter == 0) |
3675 | Result.AddTypedTextChunk(Text: Result.getAllocator().CopyString(String: SelName)); |
3676 | else { |
3677 | Result.AddInformativeChunk(Text: Result.getAllocator().CopyString(String: SelName)); |
3678 | |
3679 | // If there is only one parameter, and we're past it, add an empty |
3680 | // typed-text chunk since there is nothing to type. |
3681 | if (Method->param_size() == 1) |
3682 | Result.AddTypedTextChunk(Text: "" ); |
3683 | } |
3684 | unsigned Idx = 0; |
3685 | // The extra Idx < Sel.getNumArgs() check is needed due to legacy C-style |
3686 | // method parameters. |
3687 | for (ObjCMethodDecl::param_const_iterator P = Method->param_begin(), |
3688 | PEnd = Method->param_end(); |
3689 | P != PEnd && Idx < Sel.getNumArgs(); (void)++P, ++Idx) { |
3690 | if (Idx > 0) { |
3691 | std::string Keyword; |
3692 | if (Idx > StartParameter) |
3693 | Result.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
3694 | if (const IdentifierInfo *II = Sel.getIdentifierInfoForSlot(argIndex: Idx)) |
3695 | Keyword += II->getName(); |
3696 | Keyword += ":" ; |
3697 | if (Idx < StartParameter || AllParametersAreInformative) |
3698 | Result.AddInformativeChunk(Text: Result.getAllocator().CopyString(String: Keyword)); |
3699 | else |
3700 | Result.AddTypedTextChunk(Text: Result.getAllocator().CopyString(String: Keyword)); |
3701 | } |
3702 | |
3703 | // If we're before the starting parameter, skip the placeholder. |
3704 | if (Idx < StartParameter) |
3705 | continue; |
3706 | |
3707 | std::string Arg; |
3708 | QualType ParamType = (*P)->getType(); |
3709 | std::optional<ArrayRef<QualType>> ObjCSubsts; |
3710 | if (!CCContext.getBaseType().isNull()) |
3711 | ObjCSubsts = CCContext.getBaseType()->getObjCSubstitutions(Method); |
3712 | |
3713 | if (ParamType->isBlockPointerType() && !DeclaringEntity) |
3714 | Arg = FormatFunctionParameter(Policy, *P, true, |
3715 | /*SuppressBlock=*/false, ObjCSubsts); |
3716 | else { |
3717 | if (ObjCSubsts) |
3718 | ParamType = ParamType.substObjCTypeArgs( |
3719 | ctx&: Ctx, typeArgs: *ObjCSubsts, context: ObjCSubstitutionContext::Parameter); |
3720 | Arg = "(" + formatObjCParamQualifiers(ObjCQuals: (*P)->getObjCDeclQualifier(), |
3721 | Type&: ParamType); |
3722 | Arg += ParamType.getAsString(Policy) + ")" ; |
3723 | if (const IdentifierInfo *II = (*P)->getIdentifier()) |
3724 | if (DeclaringEntity || AllParametersAreInformative) |
3725 | Arg += II->getName(); |
3726 | } |
3727 | |
3728 | if (Method->isVariadic() && (P + 1) == PEnd) |
3729 | Arg += ", ..." ; |
3730 | |
3731 | if (DeclaringEntity) |
3732 | Result.AddTextChunk(Text: Result.getAllocator().CopyString(String: Arg)); |
3733 | else if (AllParametersAreInformative) |
3734 | Result.AddInformativeChunk(Text: Result.getAllocator().CopyString(String: Arg)); |
3735 | else |
3736 | Result.AddPlaceholderChunk(Placeholder: Result.getAllocator().CopyString(String: Arg)); |
3737 | } |
3738 | |
3739 | if (Method->isVariadic()) { |
3740 | if (Method->param_size() == 0) { |
3741 | if (DeclaringEntity) |
3742 | Result.AddTextChunk(Text: ", ..." ); |
3743 | else if (AllParametersAreInformative) |
3744 | Result.AddInformativeChunk(Text: ", ..." ); |
3745 | else |
3746 | Result.AddPlaceholderChunk(Placeholder: ", ..." ); |
3747 | } |
3748 | |
3749 | MaybeAddSentinel(PP, Method, Result); |
3750 | } |
3751 | |
3752 | return Result.TakeString(); |
3753 | } |
3754 | |
3755 | if (Qualifier) |
3756 | AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative, |
3757 | Context&: Ctx, Policy); |
3758 | |
3759 | Result.AddTypedTextChunk( |
3760 | Text: Result.getAllocator().CopyString(String: ND->getNameAsString())); |
3761 | return Result.TakeString(); |
3762 | } |
3763 | |
3764 | const RawComment *clang::(const ASTContext &Ctx, |
3765 | const NamedDecl *ND) { |
3766 | if (!ND) |
3767 | return nullptr; |
3768 | if (auto *RC = Ctx.getRawCommentForAnyRedecl(ND)) |
3769 | return RC; |
3770 | |
3771 | // Try to find comment from a property for ObjC methods. |
3772 | const auto *M = dyn_cast<ObjCMethodDecl>(Val: ND); |
3773 | if (!M) |
3774 | return nullptr; |
3775 | const ObjCPropertyDecl *PDecl = M->findPropertyDecl(); |
3776 | if (!PDecl) |
3777 | return nullptr; |
3778 | |
3779 | return Ctx.getRawCommentForAnyRedecl(PDecl); |
3780 | } |
3781 | |
3782 | const RawComment *clang::(const ASTContext &Ctx, |
3783 | const NamedDecl *ND) { |
3784 | const auto *M = dyn_cast_or_null<ObjCMethodDecl>(Val: ND); |
3785 | if (!M || !M->isPropertyAccessor()) |
3786 | return nullptr; |
3787 | |
3788 | // Provide code completion comment for self.GetterName where |
3789 | // GetterName is the getter method for a property with name |
3790 | // different from the property name (declared via a property |
3791 | // getter attribute. |
3792 | const ObjCPropertyDecl *PDecl = M->findPropertyDecl(); |
3793 | if (!PDecl) |
3794 | return nullptr; |
3795 | if (PDecl->getGetterName() == M->getSelector() && |
3796 | PDecl->getIdentifier() != M->getIdentifier()) { |
3797 | if (auto *RC = Ctx.getRawCommentForAnyRedecl(M)) |
3798 | return RC; |
3799 | if (auto *RC = Ctx.getRawCommentForAnyRedecl(PDecl)) |
3800 | return RC; |
3801 | } |
3802 | return nullptr; |
3803 | } |
3804 | |
3805 | const RawComment *clang::getParameterComment( |
3806 | const ASTContext &Ctx, |
3807 | const CodeCompleteConsumer::OverloadCandidate &Result, unsigned ArgIndex) { |
3808 | auto FDecl = Result.getFunction(); |
3809 | if (!FDecl) |
3810 | return nullptr; |
3811 | if (ArgIndex < FDecl->getNumParams()) |
3812 | return Ctx.getRawCommentForAnyRedecl(FDecl->getParamDecl(i: ArgIndex)); |
3813 | return nullptr; |
3814 | } |
3815 | |
3816 | static void AddOverloadAggregateChunks(const RecordDecl *RD, |
3817 | const PrintingPolicy &Policy, |
3818 | CodeCompletionBuilder &Result, |
3819 | unsigned CurrentArg) { |
3820 | unsigned ChunkIndex = 0; |
3821 | auto AddChunk = [&](llvm::StringRef Placeholder) { |
3822 | if (ChunkIndex > 0) |
3823 | Result.AddChunk(CK: CodeCompletionString::CK_Comma); |
3824 | const char *Copy = Result.getAllocator().CopyString(String: Placeholder); |
3825 | if (ChunkIndex == CurrentArg) |
3826 | Result.AddCurrentParameterChunk(CurrentParameter: Copy); |
3827 | else |
3828 | Result.AddPlaceholderChunk(Placeholder: Copy); |
3829 | ++ChunkIndex; |
3830 | }; |
3831 | // Aggregate initialization has all bases followed by all fields. |
3832 | // (Bases are not legal in C++11 but in that case we never get here). |
3833 | if (auto *CRD = llvm::dyn_cast<CXXRecordDecl>(Val: RD)) { |
3834 | for (const auto &Base : CRD->bases()) |
3835 | AddChunk(Base.getType().getAsString(Policy)); |
3836 | } |
3837 | for (const auto &Field : RD->fields()) |
3838 | AddChunk(FormatFunctionParameter(Policy, Field)); |
3839 | } |
3840 | |
3841 | /// Add function overload parameter chunks to the given code completion |
3842 | /// string. |
3843 | static void AddOverloadParameterChunks( |
3844 | ASTContext &Context, const PrintingPolicy &Policy, |
3845 | const FunctionDecl *Function, const FunctionProtoType *Prototype, |
3846 | FunctionProtoTypeLoc PrototypeLoc, CodeCompletionBuilder &Result, |
3847 | unsigned CurrentArg, unsigned Start = 0, bool InOptional = false) { |
3848 | if (!Function && !Prototype) { |
3849 | Result.AddChunk(CK: CodeCompletionString::CK_CurrentParameter, Text: "..." ); |
3850 | return; |
3851 | } |
3852 | |
3853 | bool FirstParameter = true; |
3854 | unsigned NumParams = |
3855 | Function ? Function->getNumParams() : Prototype->getNumParams(); |
3856 | |
3857 | for (unsigned P = Start; P != NumParams; ++P) { |
3858 | if (Function && Function->getParamDecl(i: P)->hasDefaultArg() && !InOptional) { |
3859 | // When we see an optional default argument, put that argument and |
3860 | // the remaining default arguments into a new, optional string. |
3861 | CodeCompletionBuilder Opt(Result.getAllocator(), |
3862 | Result.getCodeCompletionTUInfo()); |
3863 | if (!FirstParameter) |
3864 | Opt.AddChunk(CK: CodeCompletionString::CK_Comma); |
3865 | // Optional sections are nested. |
3866 | AddOverloadParameterChunks(Context, Policy, Function, Prototype, |
3867 | PrototypeLoc, Result&: Opt, CurrentArg, Start: P, |
3868 | /*InOptional=*/true); |
3869 | Result.AddOptionalChunk(Optional: Opt.TakeString()); |
3870 | return; |
3871 | } |
3872 | |
3873 | if (FirstParameter) |
3874 | FirstParameter = false; |
3875 | else |
3876 | Result.AddChunk(CK: CodeCompletionString::CK_Comma); |
3877 | |
3878 | InOptional = false; |
3879 | |
3880 | // Format the placeholder string. |
3881 | std::string Placeholder; |
3882 | assert(P < Prototype->getNumParams()); |
3883 | if (Function || PrototypeLoc) { |
3884 | const ParmVarDecl *Param = |
3885 | Function ? Function->getParamDecl(i: P) : PrototypeLoc.getParam(P); |
3886 | Placeholder = FormatFunctionParameter(Policy, Param); |
3887 | if (Param->hasDefaultArg()) |
3888 | Placeholder += GetDefaultValueString(Param, SM: Context.getSourceManager(), |
3889 | LangOpts: Context.getLangOpts()); |
3890 | } else { |
3891 | Placeholder = Prototype->getParamType(i: P).getAsString(Policy); |
3892 | } |
3893 | |
3894 | if (P == CurrentArg) |
3895 | Result.AddCurrentParameterChunk( |
3896 | CurrentParameter: Result.getAllocator().CopyString(String: Placeholder)); |
3897 | else |
3898 | Result.AddPlaceholderChunk(Placeholder: Result.getAllocator().CopyString(String: Placeholder)); |
3899 | } |
3900 | |
3901 | if (Prototype && Prototype->isVariadic()) { |
3902 | CodeCompletionBuilder Opt(Result.getAllocator(), |
3903 | Result.getCodeCompletionTUInfo()); |
3904 | if (!FirstParameter) |
3905 | Opt.AddChunk(CK: CodeCompletionString::CK_Comma); |
3906 | |
3907 | if (CurrentArg < NumParams) |
3908 | Opt.AddPlaceholderChunk(Placeholder: "..." ); |
3909 | else |
3910 | Opt.AddCurrentParameterChunk(CurrentParameter: "..." ); |
3911 | |
3912 | Result.AddOptionalChunk(Optional: Opt.TakeString()); |
3913 | } |
3914 | } |
3915 | |
3916 | static std::string |
3917 | formatTemplateParameterPlaceholder(const NamedDecl *Param, bool &Optional, |
3918 | const PrintingPolicy &Policy) { |
3919 | if (const auto *Type = dyn_cast<TemplateTypeParmDecl>(Val: Param)) { |
3920 | Optional = Type->hasDefaultArgument(); |
3921 | } else if (const auto *NonType = dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) { |
3922 | Optional = NonType->hasDefaultArgument(); |
3923 | } else if (const auto *Template = dyn_cast<TemplateTemplateParmDecl>(Val: Param)) { |
3924 | Optional = Template->hasDefaultArgument(); |
3925 | } |
3926 | std::string Result; |
3927 | llvm::raw_string_ostream OS(Result); |
3928 | Param->print(OS, Policy); |
3929 | return Result; |
3930 | } |
3931 | |
3932 | static std::string templateResultType(const TemplateDecl *TD, |
3933 | const PrintingPolicy &Policy) { |
3934 | if (const auto *CTD = dyn_cast<ClassTemplateDecl>(Val: TD)) |
3935 | return CTD->getTemplatedDecl()->getKindName().str(); |
3936 | if (const auto *VTD = dyn_cast<VarTemplateDecl>(Val: TD)) |
3937 | return VTD->getTemplatedDecl()->getType().getAsString(Policy); |
3938 | if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: TD)) |
3939 | return FTD->getTemplatedDecl()->getReturnType().getAsString(Policy); |
3940 | if (isa<TypeAliasTemplateDecl>(Val: TD)) |
3941 | return "type" ; |
3942 | if (isa<TemplateTemplateParmDecl>(Val: TD)) |
3943 | return "class" ; |
3944 | if (isa<ConceptDecl>(Val: TD)) |
3945 | return "concept" ; |
3946 | return "" ; |
3947 | } |
3948 | |
3949 | static CodeCompletionString *createTemplateSignatureString( |
3950 | const TemplateDecl *TD, CodeCompletionBuilder &Builder, unsigned CurrentArg, |
3951 | const PrintingPolicy &Policy) { |
3952 | llvm::ArrayRef<NamedDecl *> Params = TD->getTemplateParameters()->asArray(); |
3953 | CodeCompletionBuilder OptionalBuilder(Builder.getAllocator(), |
3954 | Builder.getCodeCompletionTUInfo()); |
3955 | std::string ResultType = templateResultType(TD, Policy); |
3956 | if (!ResultType.empty()) |
3957 | Builder.AddResultTypeChunk(ResultType: Builder.getAllocator().CopyString(String: ResultType)); |
3958 | Builder.AddTextChunk( |
3959 | Text: Builder.getAllocator().CopyString(String: TD->getNameAsString())); |
3960 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftAngle); |
3961 | // Initially we're writing into the main string. Once we see an optional arg |
3962 | // (with default), we're writing into the nested optional chunk. |
3963 | CodeCompletionBuilder *Current = &Builder; |
3964 | for (unsigned I = 0; I < Params.size(); ++I) { |
3965 | bool Optional = false; |
3966 | std::string Placeholder = |
3967 | formatTemplateParameterPlaceholder(Param: Params[I], Optional, Policy); |
3968 | if (Optional) |
3969 | Current = &OptionalBuilder; |
3970 | if (I > 0) |
3971 | Current->AddChunk(CK: CodeCompletionString::CK_Comma); |
3972 | Current->AddChunk(CK: I == CurrentArg |
3973 | ? CodeCompletionString::CK_CurrentParameter |
3974 | : CodeCompletionString::CK_Placeholder, |
3975 | Text: Current->getAllocator().CopyString(String: Placeholder)); |
3976 | } |
3977 | // Add the optional chunk to the main string if we ever used it. |
3978 | if (Current == &OptionalBuilder) |
3979 | Builder.AddOptionalChunk(Optional: OptionalBuilder.TakeString()); |
3980 | Builder.AddChunk(CK: CodeCompletionString::CK_RightAngle); |
3981 | // For function templates, ResultType was the function's return type. |
3982 | // Give some clue this is a function. (Don't show the possibly-bulky params). |
3983 | if (isa<FunctionTemplateDecl>(Val: TD)) |
3984 | Builder.AddInformativeChunk(Text: "()" ); |
3985 | return Builder.TakeString(); |
3986 | } |
3987 | |
3988 | CodeCompletionString * |
3989 | CodeCompleteConsumer::OverloadCandidate::CreateSignatureString( |
3990 | unsigned CurrentArg, Sema &S, CodeCompletionAllocator &Allocator, |
3991 | CodeCompletionTUInfo &CCTUInfo, bool , |
3992 | bool Braced) const { |
3993 | PrintingPolicy Policy = getCompletionPrintingPolicy(S); |
3994 | // Show signatures of constructors as they are declared: |
3995 | // vector(int n) rather than vector<string>(int n) |
3996 | // This is less noisy without being less clear, and avoids tricky cases. |
3997 | Policy.SuppressTemplateArgsInCXXConstructors = true; |
3998 | |
3999 | // FIXME: Set priority, availability appropriately. |
4000 | CodeCompletionBuilder Result(Allocator, CCTUInfo, 1, |
4001 | CXAvailability_Available); |
4002 | |
4003 | if (getKind() == CK_Template) |
4004 | return createTemplateSignatureString(TD: getTemplate(), Builder&: Result, CurrentArg, |
4005 | Policy); |
4006 | |
4007 | FunctionDecl *FDecl = getFunction(); |
4008 | const FunctionProtoType *Proto = |
4009 | dyn_cast_or_null<FunctionProtoType>(Val: getFunctionType()); |
4010 | |
4011 | // First, the name/type of the callee. |
4012 | if (getKind() == CK_Aggregate) { |
4013 | Result.AddTextChunk( |
4014 | Text: Result.getAllocator().CopyString(String: getAggregate()->getName())); |
4015 | } else if (FDecl) { |
4016 | if (IncludeBriefComments) { |
4017 | if (auto RC = getParameterComment(Ctx: S.getASTContext(), Result: *this, ArgIndex: CurrentArg)) |
4018 | Result.addBriefComment(Comment: RC->getBriefText(Context: S.getASTContext())); |
4019 | } |
4020 | AddResultTypeChunk(S.Context, Policy, FDecl, QualType(), Result); |
4021 | |
4022 | std::string Name; |
4023 | llvm::raw_string_ostream OS(Name); |
4024 | FDecl->getDeclName().print(OS, Policy); |
4025 | Result.AddTextChunk(Text: Result.getAllocator().CopyString(String: OS.str())); |
4026 | } else { |
4027 | // Function without a declaration. Just give the return type. |
4028 | Result.AddResultTypeChunk(ResultType: Result.getAllocator().CopyString( |
4029 | String: getFunctionType()->getReturnType().getAsString(Policy))); |
4030 | } |
4031 | |
4032 | // Next, the brackets and parameters. |
4033 | Result.AddChunk(CK: Braced ? CodeCompletionString::CK_LeftBrace |
4034 | : CodeCompletionString::CK_LeftParen); |
4035 | if (getKind() == CK_Aggregate) |
4036 | AddOverloadAggregateChunks(RD: getAggregate(), Policy, Result, CurrentArg); |
4037 | else |
4038 | AddOverloadParameterChunks(Context&: S.getASTContext(), Policy, Function: FDecl, Prototype: Proto, |
4039 | PrototypeLoc: getFunctionProtoTypeLoc(), Result, CurrentArg); |
4040 | Result.AddChunk(CK: Braced ? CodeCompletionString::CK_RightBrace |
4041 | : CodeCompletionString::CK_RightParen); |
4042 | |
4043 | return Result.TakeString(); |
4044 | } |
4045 | |
4046 | unsigned clang::getMacroUsagePriority(StringRef MacroName, |
4047 | const LangOptions &LangOpts, |
4048 | bool PreferredTypeIsPointer) { |
4049 | unsigned Priority = CCP_Macro; |
4050 | |
4051 | // Treat the "nil", "Nil" and "NULL" macros as null pointer constants. |
4052 | if (MacroName.equals(RHS: "nil" ) || MacroName.equals(RHS: "NULL" ) || |
4053 | MacroName.equals(RHS: "Nil" )) { |
4054 | Priority = CCP_Constant; |
4055 | if (PreferredTypeIsPointer) |
4056 | Priority = Priority / CCF_SimilarTypeMatch; |
4057 | } |
4058 | // Treat "YES", "NO", "true", and "false" as constants. |
4059 | else if (MacroName.equals(RHS: "YES" ) || MacroName.equals(RHS: "NO" ) || |
4060 | MacroName.equals(RHS: "true" ) || MacroName.equals(RHS: "false" )) |
4061 | Priority = CCP_Constant; |
4062 | // Treat "bool" as a type. |
4063 | else if (MacroName.equals(RHS: "bool" )) |
4064 | Priority = CCP_Type + (LangOpts.ObjC ? CCD_bool_in_ObjC : 0); |
4065 | |
4066 | return Priority; |
4067 | } |
4068 | |
4069 | CXCursorKind clang::getCursorKindForDecl(const Decl *D) { |
4070 | if (!D) |
4071 | return CXCursor_UnexposedDecl; |
4072 | |
4073 | switch (D->getKind()) { |
4074 | case Decl::Enum: |
4075 | return CXCursor_EnumDecl; |
4076 | case Decl::EnumConstant: |
4077 | return CXCursor_EnumConstantDecl; |
4078 | case Decl::Field: |
4079 | return CXCursor_FieldDecl; |
4080 | case Decl::Function: |
4081 | return CXCursor_FunctionDecl; |
4082 | case Decl::ObjCCategory: |
4083 | return CXCursor_ObjCCategoryDecl; |
4084 | case Decl::ObjCCategoryImpl: |
4085 | return CXCursor_ObjCCategoryImplDecl; |
4086 | case Decl::ObjCImplementation: |
4087 | return CXCursor_ObjCImplementationDecl; |
4088 | |
4089 | case Decl::ObjCInterface: |
4090 | return CXCursor_ObjCInterfaceDecl; |
4091 | case Decl::ObjCIvar: |
4092 | return CXCursor_ObjCIvarDecl; |
4093 | case Decl::ObjCMethod: |
4094 | return cast<ObjCMethodDecl>(Val: D)->isInstanceMethod() |
4095 | ? CXCursor_ObjCInstanceMethodDecl |
4096 | : CXCursor_ObjCClassMethodDecl; |
4097 | case Decl::CXXMethod: |
4098 | return CXCursor_CXXMethod; |
4099 | case Decl::CXXConstructor: |
4100 | return CXCursor_Constructor; |
4101 | case Decl::CXXDestructor: |
4102 | return CXCursor_Destructor; |
4103 | case Decl::CXXConversion: |
4104 | return CXCursor_ConversionFunction; |
4105 | case Decl::ObjCProperty: |
4106 | return CXCursor_ObjCPropertyDecl; |
4107 | case Decl::ObjCProtocol: |
4108 | return CXCursor_ObjCProtocolDecl; |
4109 | case Decl::ParmVar: |
4110 | return CXCursor_ParmDecl; |
4111 | case Decl::Typedef: |
4112 | return CXCursor_TypedefDecl; |
4113 | case Decl::TypeAlias: |
4114 | return CXCursor_TypeAliasDecl; |
4115 | case Decl::TypeAliasTemplate: |
4116 | return CXCursor_TypeAliasTemplateDecl; |
4117 | case Decl::Var: |
4118 | return CXCursor_VarDecl; |
4119 | case Decl::Namespace: |
4120 | return CXCursor_Namespace; |
4121 | case Decl::NamespaceAlias: |
4122 | return CXCursor_NamespaceAlias; |
4123 | case Decl::TemplateTypeParm: |
4124 | return CXCursor_TemplateTypeParameter; |
4125 | case Decl::NonTypeTemplateParm: |
4126 | return CXCursor_NonTypeTemplateParameter; |
4127 | case Decl::TemplateTemplateParm: |
4128 | return CXCursor_TemplateTemplateParameter; |
4129 | case Decl::FunctionTemplate: |
4130 | return CXCursor_FunctionTemplate; |
4131 | case Decl::ClassTemplate: |
4132 | return CXCursor_ClassTemplate; |
4133 | case Decl::AccessSpec: |
4134 | return CXCursor_CXXAccessSpecifier; |
4135 | case Decl::ClassTemplatePartialSpecialization: |
4136 | return CXCursor_ClassTemplatePartialSpecialization; |
4137 | case Decl::UsingDirective: |
4138 | return CXCursor_UsingDirective; |
4139 | case Decl::StaticAssert: |
4140 | return CXCursor_StaticAssert; |
4141 | case Decl::Friend: |
4142 | return CXCursor_FriendDecl; |
4143 | case Decl::TranslationUnit: |
4144 | return CXCursor_TranslationUnit; |
4145 | |
4146 | case Decl::Using: |
4147 | case Decl::UnresolvedUsingValue: |
4148 | case Decl::UnresolvedUsingTypename: |
4149 | return CXCursor_UsingDeclaration; |
4150 | |
4151 | case Decl::UsingEnum: |
4152 | return CXCursor_EnumDecl; |
4153 | |
4154 | case Decl::ObjCPropertyImpl: |
4155 | switch (cast<ObjCPropertyImplDecl>(Val: D)->getPropertyImplementation()) { |
4156 | case ObjCPropertyImplDecl::Dynamic: |
4157 | return CXCursor_ObjCDynamicDecl; |
4158 | |
4159 | case ObjCPropertyImplDecl::Synthesize: |
4160 | return CXCursor_ObjCSynthesizeDecl; |
4161 | } |
4162 | llvm_unreachable("Unexpected Kind!" ); |
4163 | |
4164 | case Decl::Import: |
4165 | return CXCursor_ModuleImportDecl; |
4166 | |
4167 | case Decl::ObjCTypeParam: |
4168 | return CXCursor_TemplateTypeParameter; |
4169 | |
4170 | case Decl::Concept: |
4171 | return CXCursor_ConceptDecl; |
4172 | |
4173 | case Decl::LinkageSpec: |
4174 | return CXCursor_LinkageSpec; |
4175 | |
4176 | default: |
4177 | if (const auto *TD = dyn_cast<TagDecl>(Val: D)) { |
4178 | switch (TD->getTagKind()) { |
4179 | case TagTypeKind::Interface: // fall through |
4180 | case TagTypeKind::Struct: |
4181 | return CXCursor_StructDecl; |
4182 | case TagTypeKind::Class: |
4183 | return CXCursor_ClassDecl; |
4184 | case TagTypeKind::Union: |
4185 | return CXCursor_UnionDecl; |
4186 | case TagTypeKind::Enum: |
4187 | return CXCursor_EnumDecl; |
4188 | } |
4189 | } |
4190 | } |
4191 | |
4192 | return CXCursor_UnexposedDecl; |
4193 | } |
4194 | |
4195 | static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results, |
4196 | bool LoadExternal, bool IncludeUndefined, |
4197 | bool TargetTypeIsPointer = false) { |
4198 | typedef CodeCompletionResult Result; |
4199 | |
4200 | Results.EnterNewScope(); |
4201 | |
4202 | for (Preprocessor::macro_iterator M = PP.macro_begin(IncludeExternalMacros: LoadExternal), |
4203 | MEnd = PP.macro_end(IncludeExternalMacros: LoadExternal); |
4204 | M != MEnd; ++M) { |
4205 | auto MD = PP.getMacroDefinition(II: M->first); |
4206 | if (IncludeUndefined || MD) { |
4207 | MacroInfo *MI = MD.getMacroInfo(); |
4208 | if (MI && MI->isUsedForHeaderGuard()) |
4209 | continue; |
4210 | |
4211 | Results.AddResult( |
4212 | R: Result(M->first, MI, |
4213 | getMacroUsagePriority(MacroName: M->first->getName(), LangOpts: PP.getLangOpts(), |
4214 | PreferredTypeIsPointer: TargetTypeIsPointer))); |
4215 | } |
4216 | } |
4217 | |
4218 | Results.ExitScope(); |
4219 | } |
4220 | |
4221 | static void AddPrettyFunctionResults(const LangOptions &LangOpts, |
4222 | ResultBuilder &Results) { |
4223 | typedef CodeCompletionResult Result; |
4224 | |
4225 | Results.EnterNewScope(); |
4226 | |
4227 | Results.AddResult(R: Result("__PRETTY_FUNCTION__" , CCP_Constant)); |
4228 | Results.AddResult(R: Result("__FUNCTION__" , CCP_Constant)); |
4229 | if (LangOpts.C99 || LangOpts.CPlusPlus11) |
4230 | Results.AddResult(R: Result("__func__" , CCP_Constant)); |
4231 | Results.ExitScope(); |
4232 | } |
4233 | |
4234 | static void HandleCodeCompleteResults(Sema *S, |
4235 | CodeCompleteConsumer *CodeCompleter, |
4236 | const CodeCompletionContext &Context, |
4237 | CodeCompletionResult *Results, |
4238 | unsigned NumResults) { |
4239 | if (CodeCompleter) |
4240 | CodeCompleter->ProcessCodeCompleteResults(S&: *S, Context, Results, NumResults); |
4241 | } |
4242 | |
4243 | static CodeCompletionContext |
4244 | mapCodeCompletionContext(Sema &S, Sema::ParserCompletionContext PCC) { |
4245 | switch (PCC) { |
4246 | case Sema::PCC_Namespace: |
4247 | return CodeCompletionContext::CCC_TopLevel; |
4248 | |
4249 | case Sema::PCC_Class: |
4250 | return CodeCompletionContext::CCC_ClassStructUnion; |
4251 | |
4252 | case Sema::PCC_ObjCInterface: |
4253 | return CodeCompletionContext::CCC_ObjCInterface; |
4254 | |
4255 | case Sema::PCC_ObjCImplementation: |
4256 | return CodeCompletionContext::CCC_ObjCImplementation; |
4257 | |
4258 | case Sema::PCC_ObjCInstanceVariableList: |
4259 | return CodeCompletionContext::CCC_ObjCIvarList; |
4260 | |
4261 | case Sema::PCC_Template: |
4262 | case Sema::PCC_MemberTemplate: |
4263 | if (S.CurContext->isFileContext()) |
4264 | return CodeCompletionContext::CCC_TopLevel; |
4265 | if (S.CurContext->isRecord()) |
4266 | return CodeCompletionContext::CCC_ClassStructUnion; |
4267 | return CodeCompletionContext::CCC_Other; |
4268 | |
4269 | case Sema::PCC_RecoveryInFunction: |
4270 | return CodeCompletionContext::CCC_Recovery; |
4271 | |
4272 | case Sema::PCC_ForInit: |
4273 | if (S.getLangOpts().CPlusPlus || S.getLangOpts().C99 || |
4274 | S.getLangOpts().ObjC) |
4275 | return CodeCompletionContext::CCC_ParenthesizedExpression; |
4276 | else |
4277 | return CodeCompletionContext::CCC_Expression; |
4278 | |
4279 | case Sema::PCC_Expression: |
4280 | return CodeCompletionContext::CCC_Expression; |
4281 | case Sema::PCC_Condition: |
4282 | return CodeCompletionContext(CodeCompletionContext::CCC_Expression, |
4283 | S.getASTContext().BoolTy); |
4284 | |
4285 | case Sema::PCC_Statement: |
4286 | return CodeCompletionContext::CCC_Statement; |
4287 | |
4288 | case Sema::PCC_Type: |
4289 | return CodeCompletionContext::CCC_Type; |
4290 | |
4291 | case Sema::PCC_ParenthesizedExpression: |
4292 | return CodeCompletionContext::CCC_ParenthesizedExpression; |
4293 | |
4294 | case Sema::PCC_LocalDeclarationSpecifiers: |
4295 | return CodeCompletionContext::CCC_Type; |
4296 | case Sema::PCC_TopLevelOrExpression: |
4297 | return CodeCompletionContext::CCC_TopLevelOrExpression; |
4298 | } |
4299 | |
4300 | llvm_unreachable("Invalid ParserCompletionContext!" ); |
4301 | } |
4302 | |
4303 | /// If we're in a C++ virtual member function, add completion results |
4304 | /// that invoke the functions we override, since it's common to invoke the |
4305 | /// overridden function as well as adding new functionality. |
4306 | /// |
4307 | /// \param S The semantic analysis object for which we are generating results. |
4308 | /// |
4309 | /// \param InContext This context in which the nested-name-specifier preceding |
4310 | /// the code-completion point |
4311 | static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext, |
4312 | ResultBuilder &Results) { |
4313 | // Look through blocks. |
4314 | DeclContext *CurContext = S.CurContext; |
4315 | while (isa<BlockDecl>(Val: CurContext)) |
4316 | CurContext = CurContext->getParent(); |
4317 | |
4318 | CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: CurContext); |
4319 | if (!Method || !Method->isVirtual()) |
4320 | return; |
4321 | |
4322 | // We need to have names for all of the parameters, if we're going to |
4323 | // generate a forwarding call. |
4324 | for (auto *P : Method->parameters()) |
4325 | if (!P->getDeclName()) |
4326 | return; |
4327 | |
4328 | PrintingPolicy Policy = getCompletionPrintingPolicy(S); |
4329 | for (const CXXMethodDecl *Overridden : Method->overridden_methods()) { |
4330 | CodeCompletionBuilder Builder(Results.getAllocator(), |
4331 | Results.getCodeCompletionTUInfo()); |
4332 | if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl()) |
4333 | continue; |
4334 | |
4335 | // If we need a nested-name-specifier, add one now. |
4336 | if (!InContext) { |
4337 | NestedNameSpecifier *NNS = getRequiredQualification( |
4338 | S.Context, CurContext, Overridden->getDeclContext()); |
4339 | if (NNS) { |
4340 | std::string Str; |
4341 | llvm::raw_string_ostream OS(Str); |
4342 | NNS->print(OS, Policy); |
4343 | Builder.AddTextChunk(Text: Results.getAllocator().CopyString(String: OS.str())); |
4344 | } |
4345 | } else if (!InContext->Equals(DC: Overridden->getDeclContext())) |
4346 | continue; |
4347 | |
4348 | Builder.AddTypedTextChunk( |
4349 | Text: Results.getAllocator().CopyString(String: Overridden->getNameAsString())); |
4350 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
4351 | bool FirstParam = true; |
4352 | for (auto *P : Method->parameters()) { |
4353 | if (FirstParam) |
4354 | FirstParam = false; |
4355 | else |
4356 | Builder.AddChunk(CodeCompletionString::CK_Comma); |
4357 | |
4358 | Builder.AddPlaceholderChunk( |
4359 | Results.getAllocator().CopyString(P->getIdentifier()->getName())); |
4360 | } |
4361 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
4362 | Results.AddResult(R: CodeCompletionResult( |
4363 | Builder.TakeString(), CCP_SuperCompletion, CXCursor_CXXMethod, |
4364 | CXAvailability_Available, Overridden)); |
4365 | Results.Ignore(Overridden); |
4366 | } |
4367 | } |
4368 | |
4369 | void Sema::CodeCompleteModuleImport(SourceLocation ImportLoc, |
4370 | ModuleIdPath Path) { |
4371 | typedef CodeCompletionResult Result; |
4372 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
4373 | CodeCompleter->getCodeCompletionTUInfo(), |
4374 | CodeCompletionContext::CCC_Other); |
4375 | Results.EnterNewScope(); |
4376 | |
4377 | CodeCompletionAllocator &Allocator = Results.getAllocator(); |
4378 | CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo()); |
4379 | typedef CodeCompletionResult Result; |
4380 | if (Path.empty()) { |
4381 | // Enumerate all top-level modules. |
4382 | SmallVector<Module *, 8> Modules; |
4383 | PP.getHeaderSearchInfo().collectAllModules(Modules); |
4384 | for (unsigned I = 0, N = Modules.size(); I != N; ++I) { |
4385 | Builder.AddTypedTextChunk( |
4386 | Text: Builder.getAllocator().CopyString(String: Modules[I]->Name)); |
4387 | Results.AddResult(R: Result( |
4388 | Builder.TakeString(), CCP_Declaration, CXCursor_ModuleImportDecl, |
4389 | Modules[I]->isAvailable() ? CXAvailability_Available |
4390 | : CXAvailability_NotAvailable)); |
4391 | } |
4392 | } else if (getLangOpts().Modules) { |
4393 | // Load the named module. |
4394 | Module *Mod = |
4395 | PP.getModuleLoader().loadModule(ImportLoc, Path, Visibility: Module::AllVisible, |
4396 | /*IsInclusionDirective=*/false); |
4397 | // Enumerate submodules. |
4398 | if (Mod) { |
4399 | for (auto *Submodule : Mod->submodules()) { |
4400 | Builder.AddTypedTextChunk( |
4401 | Text: Builder.getAllocator().CopyString(String: Submodule->Name)); |
4402 | Results.AddResult(R: Result( |
4403 | Builder.TakeString(), CCP_Declaration, CXCursor_ModuleImportDecl, |
4404 | Submodule->isAvailable() ? CXAvailability_Available |
4405 | : CXAvailability_NotAvailable)); |
4406 | } |
4407 | } |
4408 | } |
4409 | Results.ExitScope(); |
4410 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
4411 | Results: Results.data(), NumResults: Results.size()); |
4412 | } |
4413 | |
4414 | void Sema::CodeCompleteOrdinaryName(Scope *S, |
4415 | ParserCompletionContext CompletionContext) { |
4416 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
4417 | CodeCompleter->getCodeCompletionTUInfo(), |
4418 | mapCodeCompletionContext(S&: *this, PCC: CompletionContext)); |
4419 | Results.EnterNewScope(); |
4420 | |
4421 | // Determine how to filter results, e.g., so that the names of |
4422 | // values (functions, enumerators, function templates, etc.) are |
4423 | // only allowed where we can have an expression. |
4424 | switch (CompletionContext) { |
4425 | case PCC_Namespace: |
4426 | case PCC_Class: |
4427 | case PCC_ObjCInterface: |
4428 | case PCC_ObjCImplementation: |
4429 | case PCC_ObjCInstanceVariableList: |
4430 | case PCC_Template: |
4431 | case PCC_MemberTemplate: |
4432 | case PCC_Type: |
4433 | case PCC_LocalDeclarationSpecifiers: |
4434 | Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName); |
4435 | break; |
4436 | |
4437 | case PCC_Statement: |
4438 | case PCC_TopLevelOrExpression: |
4439 | case PCC_ParenthesizedExpression: |
4440 | case PCC_Expression: |
4441 | case PCC_ForInit: |
4442 | case PCC_Condition: |
4443 | if (WantTypesInContext(CCC: CompletionContext, LangOpts: getLangOpts())) |
4444 | Results.setFilter(&ResultBuilder::IsOrdinaryName); |
4445 | else |
4446 | Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName); |
4447 | |
4448 | if (getLangOpts().CPlusPlus) |
4449 | MaybeAddOverrideCalls(S&: *this, /*InContext=*/nullptr, Results); |
4450 | break; |
4451 | |
4452 | case PCC_RecoveryInFunction: |
4453 | // Unfiltered |
4454 | break; |
4455 | } |
4456 | |
4457 | // If we are in a C++ non-static member function, check the qualifiers on |
4458 | // the member function to filter/prioritize the results list. |
4459 | auto ThisType = getCurrentThisType(); |
4460 | if (!ThisType.isNull()) |
4461 | Results.setObjectTypeQualifiers(Quals: ThisType->getPointeeType().getQualifiers(), |
4462 | Kind: VK_LValue); |
4463 | |
4464 | CodeCompletionDeclConsumer Consumer(Results, CurContext); |
4465 | LookupVisibleDecls(S, LookupOrdinaryName, Consumer, |
4466 | CodeCompleter->includeGlobals(), |
4467 | CodeCompleter->loadExternal()); |
4468 | |
4469 | AddOrdinaryNameResults(CCC: CompletionContext, S, SemaRef&: *this, Results); |
4470 | Results.ExitScope(); |
4471 | |
4472 | switch (CompletionContext) { |
4473 | case PCC_ParenthesizedExpression: |
4474 | case PCC_Expression: |
4475 | case PCC_Statement: |
4476 | case PCC_TopLevelOrExpression: |
4477 | case PCC_RecoveryInFunction: |
4478 | if (S->getFnParent()) |
4479 | AddPrettyFunctionResults(LangOpts: getLangOpts(), Results); |
4480 | break; |
4481 | |
4482 | case PCC_Namespace: |
4483 | case PCC_Class: |
4484 | case PCC_ObjCInterface: |
4485 | case PCC_ObjCImplementation: |
4486 | case PCC_ObjCInstanceVariableList: |
4487 | case PCC_Template: |
4488 | case PCC_MemberTemplate: |
4489 | case PCC_ForInit: |
4490 | case PCC_Condition: |
4491 | case PCC_Type: |
4492 | case PCC_LocalDeclarationSpecifiers: |
4493 | break; |
4494 | } |
4495 | |
4496 | if (CodeCompleter->includeMacros()) |
4497 | AddMacroResults(PP, Results, LoadExternal: CodeCompleter->loadExternal(), IncludeUndefined: false); |
4498 | |
4499 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
4500 | Results: Results.data(), NumResults: Results.size()); |
4501 | } |
4502 | |
4503 | static void |
4504 | AddClassMessageCompletions(Sema &SemaRef, Scope *S, ParsedType Receiver, |
4505 | ArrayRef<const IdentifierInfo *> SelIdents, |
4506 | bool AtArgumentExpression, bool IsSuper, |
4507 | ResultBuilder &Results); |
4508 | |
4509 | void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, |
4510 | bool AllowNonIdentifiers, |
4511 | bool AllowNestedNameSpecifiers) { |
4512 | typedef CodeCompletionResult Result; |
4513 | ResultBuilder Results( |
4514 | *this, CodeCompleter->getAllocator(), |
4515 | CodeCompleter->getCodeCompletionTUInfo(), |
4516 | AllowNestedNameSpecifiers |
4517 | // FIXME: Try to separate codepath leading here to deduce whether we |
4518 | // need an existing symbol or a new one. |
4519 | ? CodeCompletionContext::CCC_SymbolOrNewName |
4520 | : CodeCompletionContext::CCC_NewName); |
4521 | Results.EnterNewScope(); |
4522 | |
4523 | // Type qualifiers can come after names. |
4524 | Results.AddResult(R: Result("const" )); |
4525 | Results.AddResult(R: Result("volatile" )); |
4526 | if (getLangOpts().C99) |
4527 | Results.AddResult(R: Result("restrict" )); |
4528 | |
4529 | if (getLangOpts().CPlusPlus) { |
4530 | if (getLangOpts().CPlusPlus11 && |
4531 | (DS.getTypeSpecType() == DeclSpec::TST_class || |
4532 | DS.getTypeSpecType() == DeclSpec::TST_struct)) |
4533 | Results.AddResult(R: "final" ); |
4534 | |
4535 | if (AllowNonIdentifiers) { |
4536 | Results.AddResult(R: Result("operator" )); |
4537 | } |
4538 | |
4539 | // Add nested-name-specifiers. |
4540 | if (AllowNestedNameSpecifiers) { |
4541 | Results.allowNestedNameSpecifiers(); |
4542 | Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy); |
4543 | CodeCompletionDeclConsumer Consumer(Results, CurContext); |
4544 | LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer, |
4545 | CodeCompleter->includeGlobals(), |
4546 | CodeCompleter->loadExternal()); |
4547 | Results.setFilter(nullptr); |
4548 | } |
4549 | } |
4550 | Results.ExitScope(); |
4551 | |
4552 | // If we're in a context where we might have an expression (rather than a |
4553 | // declaration), and what we've seen so far is an Objective-C type that could |
4554 | // be a receiver of a class message, this may be a class message send with |
4555 | // the initial opening bracket '[' missing. Add appropriate completions. |
4556 | if (AllowNonIdentifiers && !AllowNestedNameSpecifiers && |
4557 | DS.getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier && |
4558 | DS.getTypeSpecType() == DeclSpec::TST_typename && |
4559 | DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified && |
4560 | DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified && |
4561 | !DS.isTypeAltiVecVector() && S && |
4562 | (S->getFlags() & Scope::DeclScope) != 0 && |
4563 | (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope | |
4564 | Scope::FunctionPrototypeScope | Scope::AtCatchScope)) == |
4565 | 0) { |
4566 | ParsedType T = DS.getRepAsType(); |
4567 | if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType()) |
4568 | AddClassMessageCompletions(SemaRef&: *this, S, Receiver: T, SelIdents: std::nullopt, AtArgumentExpression: false, IsSuper: false, |
4569 | Results); |
4570 | } |
4571 | |
4572 | // Note that we intentionally suppress macro results here, since we do not |
4573 | // encourage using macros to produce the names of entities. |
4574 | |
4575 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
4576 | Results: Results.data(), NumResults: Results.size()); |
4577 | } |
4578 | |
4579 | static const char *underscoreAttrScope(llvm::StringRef Scope) { |
4580 | if (Scope == "clang" ) |
4581 | return "_Clang" ; |
4582 | if (Scope == "gnu" ) |
4583 | return "__gnu__" ; |
4584 | return nullptr; |
4585 | } |
4586 | |
4587 | static const char *noUnderscoreAttrScope(llvm::StringRef Scope) { |
4588 | if (Scope == "_Clang" ) |
4589 | return "clang" ; |
4590 | if (Scope == "__gnu__" ) |
4591 | return "gnu" ; |
4592 | return nullptr; |
4593 | } |
4594 | |
4595 | void Sema::CodeCompleteAttribute(AttributeCommonInfo::Syntax Syntax, |
4596 | AttributeCompletion Completion, |
4597 | const IdentifierInfo *InScope) { |
4598 | if (Completion == AttributeCompletion::None) |
4599 | return; |
4600 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
4601 | CodeCompleter->getCodeCompletionTUInfo(), |
4602 | CodeCompletionContext::CCC_Attribute); |
4603 | |
4604 | // We're going to iterate over the normalized spellings of the attribute. |
4605 | // These don't include "underscore guarding": the normalized spelling is |
4606 | // clang::foo but you can also write _Clang::__foo__. |
4607 | // |
4608 | // (Clang supports a mix like clang::__foo__ but we won't suggest it: either |
4609 | // you care about clashing with macros or you don't). |
4610 | // |
4611 | // So if we're already in a scope, we determine its canonical spellings |
4612 | // (for comparison with normalized attr spelling) and remember whether it was |
4613 | // underscore-guarded (so we know how to spell contained attributes). |
4614 | llvm::StringRef InScopeName; |
4615 | bool InScopeUnderscore = false; |
4616 | if (InScope) { |
4617 | InScopeName = InScope->getName(); |
4618 | if (const char *NoUnderscore = noUnderscoreAttrScope(Scope: InScopeName)) { |
4619 | InScopeName = NoUnderscore; |
4620 | InScopeUnderscore = true; |
4621 | } |
4622 | } |
4623 | bool SyntaxSupportsGuards = Syntax == AttributeCommonInfo::AS_GNU || |
4624 | Syntax == AttributeCommonInfo::AS_CXX11 || |
4625 | Syntax == AttributeCommonInfo::AS_C23; |
4626 | |
4627 | llvm::DenseSet<llvm::StringRef> FoundScopes; |
4628 | auto AddCompletions = [&](const ParsedAttrInfo &A) { |
4629 | if (A.IsTargetSpecific && !A.existsInTarget(Target: Context.getTargetInfo())) |
4630 | return; |
4631 | if (!A.acceptsLangOpts(LO: getLangOpts())) |
4632 | return; |
4633 | for (const auto &S : A.Spellings) { |
4634 | if (S.Syntax != Syntax) |
4635 | continue; |
4636 | llvm::StringRef Name = S.NormalizedFullName; |
4637 | llvm::StringRef Scope; |
4638 | if ((Syntax == AttributeCommonInfo::AS_CXX11 || |
4639 | Syntax == AttributeCommonInfo::AS_C23)) { |
4640 | std::tie(args&: Scope, args&: Name) = Name.split(Separator: "::" ); |
4641 | if (Name.empty()) // oops, unscoped |
4642 | std::swap(a&: Name, b&: Scope); |
4643 | } |
4644 | |
4645 | // Do we just want a list of scopes rather than attributes? |
4646 | if (Completion == AttributeCompletion::Scope) { |
4647 | // Make sure to emit each scope only once. |
4648 | if (!Scope.empty() && FoundScopes.insert(V: Scope).second) { |
4649 | Results.AddResult( |
4650 | R: CodeCompletionResult(Results.getAllocator().CopyString(String: Scope))); |
4651 | // Include alternate form (__gnu__ instead of gnu). |
4652 | if (const char *Scope2 = underscoreAttrScope(Scope)) |
4653 | Results.AddResult(R: CodeCompletionResult(Scope2)); |
4654 | } |
4655 | continue; |
4656 | } |
4657 | |
4658 | // If a scope was specified, it must match but we don't need to print it. |
4659 | if (!InScopeName.empty()) { |
4660 | if (Scope != InScopeName) |
4661 | continue; |
4662 | Scope = "" ; |
4663 | } |
4664 | |
4665 | auto Add = [&](llvm::StringRef Scope, llvm::StringRef Name, |
4666 | bool Underscores) { |
4667 | CodeCompletionBuilder Builder(Results.getAllocator(), |
4668 | Results.getCodeCompletionTUInfo()); |
4669 | llvm::SmallString<32> Text; |
4670 | if (!Scope.empty()) { |
4671 | Text.append(RHS: Scope); |
4672 | Text.append(RHS: "::" ); |
4673 | } |
4674 | if (Underscores) |
4675 | Text.append(RHS: "__" ); |
4676 | Text.append(RHS: Name); |
4677 | if (Underscores) |
4678 | Text.append(RHS: "__" ); |
4679 | Builder.AddTypedTextChunk(Text: Results.getAllocator().CopyString(String: Text)); |
4680 | |
4681 | if (!A.ArgNames.empty()) { |
4682 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen, Text: "(" ); |
4683 | bool First = true; |
4684 | for (const char *Arg : A.ArgNames) { |
4685 | if (!First) |
4686 | Builder.AddChunk(CK: CodeCompletionString::CK_Comma, Text: ", " ); |
4687 | First = false; |
4688 | Builder.AddPlaceholderChunk(Placeholder: Arg); |
4689 | } |
4690 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen, Text: ")" ); |
4691 | } |
4692 | |
4693 | Results.AddResult(R: Builder.TakeString()); |
4694 | }; |
4695 | |
4696 | // Generate the non-underscore-guarded result. |
4697 | // Note this is (a suffix of) the NormalizedFullName, no need to copy. |
4698 | // If an underscore-guarded scope was specified, only the |
4699 | // underscore-guarded attribute name is relevant. |
4700 | if (!InScopeUnderscore) |
4701 | Add(Scope, Name, /*Underscores=*/false); |
4702 | |
4703 | // Generate the underscore-guarded version, for syntaxes that support it. |
4704 | // We skip this if the scope was already spelled and not guarded, or |
4705 | // we must spell it and can't guard it. |
4706 | if (!(InScope && !InScopeUnderscore) && SyntaxSupportsGuards) { |
4707 | llvm::SmallString<32> Guarded; |
4708 | if (Scope.empty()) { |
4709 | Add(Scope, Name, /*Underscores=*/true); |
4710 | } else { |
4711 | const char *GuardedScope = underscoreAttrScope(Scope); |
4712 | if (!GuardedScope) |
4713 | continue; |
4714 | Add(GuardedScope, Name, /*Underscores=*/true); |
4715 | } |
4716 | } |
4717 | |
4718 | // It may be nice to include the Kind so we can look up the docs later. |
4719 | } |
4720 | }; |
4721 | |
4722 | for (const auto *A : ParsedAttrInfo::getAllBuiltin()) |
4723 | AddCompletions(*A); |
4724 | for (const auto &Entry : ParsedAttrInfoRegistry::entries()) |
4725 | AddCompletions(*Entry.instantiate()); |
4726 | |
4727 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
4728 | Results: Results.data(), NumResults: Results.size()); |
4729 | } |
4730 | |
4731 | struct Sema::CodeCompleteExpressionData { |
4732 | CodeCompleteExpressionData(QualType PreferredType = QualType(), |
4733 | bool IsParenthesized = false) |
4734 | : PreferredType(PreferredType), IntegralConstantExpression(false), |
4735 | ObjCCollection(false), IsParenthesized(IsParenthesized) {} |
4736 | |
4737 | QualType PreferredType; |
4738 | bool IntegralConstantExpression; |
4739 | bool ObjCCollection; |
4740 | bool IsParenthesized; |
4741 | SmallVector<Decl *, 4> IgnoreDecls; |
4742 | }; |
4743 | |
4744 | namespace { |
4745 | /// Information that allows to avoid completing redundant enumerators. |
4746 | struct CoveredEnumerators { |
4747 | llvm::SmallPtrSet<EnumConstantDecl *, 8> Seen; |
4748 | NestedNameSpecifier *SuggestedQualifier = nullptr; |
4749 | }; |
4750 | } // namespace |
4751 | |
4752 | static void AddEnumerators(ResultBuilder &Results, ASTContext &Context, |
4753 | EnumDecl *Enum, DeclContext *CurContext, |
4754 | const CoveredEnumerators &Enumerators) { |
4755 | NestedNameSpecifier *Qualifier = Enumerators.SuggestedQualifier; |
4756 | if (Context.getLangOpts().CPlusPlus && !Qualifier && Enumerators.Seen.empty()) { |
4757 | // If there are no prior enumerators in C++, check whether we have to |
4758 | // qualify the names of the enumerators that we suggest, because they |
4759 | // may not be visible in this scope. |
4760 | Qualifier = getRequiredQualification(Context, CurContext, Enum); |
4761 | } |
4762 | |
4763 | Results.EnterNewScope(); |
4764 | for (auto *E : Enum->enumerators()) { |
4765 | if (Enumerators.Seen.count(Ptr: E)) |
4766 | continue; |
4767 | |
4768 | CodeCompletionResult R(E, CCP_EnumInCase, Qualifier); |
4769 | Results.AddResult(R, CurContext, Hiding: nullptr, InBaseClass: false); |
4770 | } |
4771 | Results.ExitScope(); |
4772 | } |
4773 | |
4774 | /// Try to find a corresponding FunctionProtoType for function-like types (e.g. |
4775 | /// function pointers, std::function, etc). |
4776 | static const FunctionProtoType *TryDeconstructFunctionLike(QualType T) { |
4777 | assert(!T.isNull()); |
4778 | // Try to extract first template argument from std::function<> and similar. |
4779 | // Note we only handle the sugared types, they closely match what users wrote. |
4780 | // We explicitly choose to not handle ClassTemplateSpecializationDecl. |
4781 | if (auto *Specialization = T->getAs<TemplateSpecializationType>()) { |
4782 | if (Specialization->template_arguments().size() != 1) |
4783 | return nullptr; |
4784 | const TemplateArgument &Argument = Specialization->template_arguments()[0]; |
4785 | if (Argument.getKind() != TemplateArgument::Type) |
4786 | return nullptr; |
4787 | return Argument.getAsType()->getAs<FunctionProtoType>(); |
4788 | } |
4789 | // Handle other cases. |
4790 | if (T->isPointerType()) |
4791 | T = T->getPointeeType(); |
4792 | return T->getAs<FunctionProtoType>(); |
4793 | } |
4794 | |
4795 | /// Adds a pattern completion for a lambda expression with the specified |
4796 | /// parameter types and placeholders for parameter names. |
4797 | static void AddLambdaCompletion(ResultBuilder &Results, |
4798 | llvm::ArrayRef<QualType> Parameters, |
4799 | const LangOptions &LangOpts) { |
4800 | if (!Results.includeCodePatterns()) |
4801 | return; |
4802 | CodeCompletionBuilder Completion(Results.getAllocator(), |
4803 | Results.getCodeCompletionTUInfo()); |
4804 | // [](<parameters>) {} |
4805 | Completion.AddChunk(CK: CodeCompletionString::CK_LeftBracket); |
4806 | Completion.AddPlaceholderChunk(Placeholder: "=" ); |
4807 | Completion.AddChunk(CK: CodeCompletionString::CK_RightBracket); |
4808 | if (!Parameters.empty()) { |
4809 | Completion.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
4810 | bool First = true; |
4811 | for (auto Parameter : Parameters) { |
4812 | if (!First) |
4813 | Completion.AddChunk(CK: CodeCompletionString::ChunkKind::CK_Comma); |
4814 | else |
4815 | First = false; |
4816 | |
4817 | constexpr llvm::StringLiteral NamePlaceholder = "!#!NAME_GOES_HERE!#!" ; |
4818 | std::string Type = std::string(NamePlaceholder); |
4819 | Parameter.getAsStringInternal(Str&: Type, Policy: PrintingPolicy(LangOpts)); |
4820 | llvm::StringRef Prefix, Suffix; |
4821 | std::tie(args&: Prefix, args&: Suffix) = llvm::StringRef(Type).split(Separator: NamePlaceholder); |
4822 | Prefix = Prefix.rtrim(); |
4823 | Suffix = Suffix.ltrim(); |
4824 | |
4825 | Completion.AddTextChunk(Text: Completion.getAllocator().CopyString(String: Prefix)); |
4826 | Completion.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
4827 | Completion.AddPlaceholderChunk(Placeholder: "parameter" ); |
4828 | Completion.AddTextChunk(Text: Completion.getAllocator().CopyString(String: Suffix)); |
4829 | }; |
4830 | Completion.AddChunk(CK: CodeCompletionString::CK_RightParen); |
4831 | } |
4832 | Completion.AddChunk(CK: clang::CodeCompletionString::CK_HorizontalSpace); |
4833 | Completion.AddChunk(CK: CodeCompletionString::CK_LeftBrace); |
4834 | Completion.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
4835 | Completion.AddPlaceholderChunk(Placeholder: "body" ); |
4836 | Completion.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
4837 | Completion.AddChunk(CK: CodeCompletionString::CK_RightBrace); |
4838 | |
4839 | Results.AddResult(R: Completion.TakeString()); |
4840 | } |
4841 | |
4842 | /// Perform code-completion in an expression context when we know what |
4843 | /// type we're looking for. |
4844 | void Sema::CodeCompleteExpression(Scope *S, |
4845 | const CodeCompleteExpressionData &Data) { |
4846 | ResultBuilder Results( |
4847 | *this, CodeCompleter->getAllocator(), |
4848 | CodeCompleter->getCodeCompletionTUInfo(), |
4849 | CodeCompletionContext( |
4850 | Data.IsParenthesized |
4851 | ? CodeCompletionContext::CCC_ParenthesizedExpression |
4852 | : CodeCompletionContext::CCC_Expression, |
4853 | Data.PreferredType)); |
4854 | auto PCC = |
4855 | Data.IsParenthesized ? PCC_ParenthesizedExpression : PCC_Expression; |
4856 | if (Data.ObjCCollection) |
4857 | Results.setFilter(&ResultBuilder::IsObjCCollection); |
4858 | else if (Data.IntegralConstantExpression) |
4859 | Results.setFilter(&ResultBuilder::IsIntegralConstantValue); |
4860 | else if (WantTypesInContext(CCC: PCC, LangOpts: getLangOpts())) |
4861 | Results.setFilter(&ResultBuilder::IsOrdinaryName); |
4862 | else |
4863 | Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName); |
4864 | |
4865 | if (!Data.PreferredType.isNull()) |
4866 | Results.setPreferredType(Data.PreferredType.getNonReferenceType()); |
4867 | |
4868 | // Ignore any declarations that we were told that we don't care about. |
4869 | for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I) |
4870 | Results.Ignore(D: Data.IgnoreDecls[I]); |
4871 | |
4872 | CodeCompletionDeclConsumer Consumer(Results, CurContext); |
4873 | LookupVisibleDecls(S, LookupOrdinaryName, Consumer, |
4874 | CodeCompleter->includeGlobals(), |
4875 | CodeCompleter->loadExternal()); |
4876 | |
4877 | Results.EnterNewScope(); |
4878 | AddOrdinaryNameResults(CCC: PCC, S, SemaRef&: *this, Results); |
4879 | Results.ExitScope(); |
4880 | |
4881 | bool PreferredTypeIsPointer = false; |
4882 | if (!Data.PreferredType.isNull()) { |
4883 | PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType() || |
4884 | Data.PreferredType->isMemberPointerType() || |
4885 | Data.PreferredType->isBlockPointerType(); |
4886 | if (Data.PreferredType->isEnumeralType()) { |
4887 | EnumDecl *Enum = Data.PreferredType->castAs<EnumType>()->getDecl(); |
4888 | if (auto *Def = Enum->getDefinition()) |
4889 | Enum = Def; |
4890 | // FIXME: collect covered enumerators in cases like: |
4891 | // if (x == my_enum::one) { ... } else if (x == ^) {} |
4892 | AddEnumerators(Results, Context, Enum, CurContext, Enumerators: CoveredEnumerators()); |
4893 | } |
4894 | } |
4895 | |
4896 | if (S->getFnParent() && !Data.ObjCCollection && |
4897 | !Data.IntegralConstantExpression) |
4898 | AddPrettyFunctionResults(LangOpts: getLangOpts(), Results); |
4899 | |
4900 | if (CodeCompleter->includeMacros()) |
4901 | AddMacroResults(PP, Results, LoadExternal: CodeCompleter->loadExternal(), IncludeUndefined: false, |
4902 | TargetTypeIsPointer: PreferredTypeIsPointer); |
4903 | |
4904 | // Complete a lambda expression when preferred type is a function. |
4905 | if (!Data.PreferredType.isNull() && getLangOpts().CPlusPlus11) { |
4906 | if (const FunctionProtoType *F = |
4907 | TryDeconstructFunctionLike(Data.PreferredType)) |
4908 | AddLambdaCompletion(Results, Parameters: F->getParamTypes(), LangOpts: getLangOpts()); |
4909 | } |
4910 | |
4911 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
4912 | Results: Results.data(), NumResults: Results.size()); |
4913 | } |
4914 | |
4915 | void Sema::CodeCompleteExpression(Scope *S, QualType PreferredType, |
4916 | bool IsParenthesized) { |
4917 | return CodeCompleteExpression( |
4918 | S, Data: CodeCompleteExpressionData(PreferredType, IsParenthesized)); |
4919 | } |
4920 | |
4921 | void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E, |
4922 | QualType PreferredType) { |
4923 | if (E.isInvalid()) |
4924 | CodeCompleteExpression(S, PreferredType); |
4925 | else if (getLangOpts().ObjC) |
4926 | CodeCompleteObjCInstanceMessage(S, Receiver: E.get(), SelIdents: std::nullopt, AtArgumentExpression: false); |
4927 | } |
4928 | |
4929 | /// The set of properties that have already been added, referenced by |
4930 | /// property name. |
4931 | typedef llvm::SmallPtrSet<const IdentifierInfo *, 16> AddedPropertiesSet; |
4932 | |
4933 | /// Retrieve the container definition, if any? |
4934 | static ObjCContainerDecl *getContainerDef(ObjCContainerDecl *Container) { |
4935 | if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Val: Container)) { |
4936 | if (Interface->hasDefinition()) |
4937 | return Interface->getDefinition(); |
4938 | |
4939 | return Interface; |
4940 | } |
4941 | |
4942 | if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Val: Container)) { |
4943 | if (Protocol->hasDefinition()) |
4944 | return Protocol->getDefinition(); |
4945 | |
4946 | return Protocol; |
4947 | } |
4948 | return Container; |
4949 | } |
4950 | |
4951 | /// Adds a block invocation code completion result for the given block |
4952 | /// declaration \p BD. |
4953 | static void AddObjCBlockCall(ASTContext &Context, const PrintingPolicy &Policy, |
4954 | CodeCompletionBuilder &Builder, |
4955 | const NamedDecl *BD, |
4956 | const FunctionTypeLoc &BlockLoc, |
4957 | const FunctionProtoTypeLoc &BlockProtoLoc) { |
4958 | Builder.AddResultTypeChunk( |
4959 | ResultType: GetCompletionTypeString(T: BlockLoc.getReturnLoc().getType(), Context, |
4960 | Policy, Allocator&: Builder.getAllocator())); |
4961 | |
4962 | AddTypedNameChunk(Context, Policy, ND: BD, Result&: Builder); |
4963 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
4964 | |
4965 | if (BlockProtoLoc && BlockProtoLoc.getTypePtr()->isVariadic()) { |
4966 | Builder.AddPlaceholderChunk(Placeholder: "..." ); |
4967 | } else { |
4968 | for (unsigned I = 0, N = BlockLoc.getNumParams(); I != N; ++I) { |
4969 | if (I) |
4970 | Builder.AddChunk(CK: CodeCompletionString::CK_Comma); |
4971 | |
4972 | // Format the placeholder string. |
4973 | std::string PlaceholderStr = |
4974 | FormatFunctionParameter(Policy, BlockLoc.getParam(i: I)); |
4975 | |
4976 | if (I == N - 1 && BlockProtoLoc && |
4977 | BlockProtoLoc.getTypePtr()->isVariadic()) |
4978 | PlaceholderStr += ", ..." ; |
4979 | |
4980 | // Add the placeholder string. |
4981 | Builder.AddPlaceholderChunk( |
4982 | Placeholder: Builder.getAllocator().CopyString(String: PlaceholderStr)); |
4983 | } |
4984 | } |
4985 | |
4986 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
4987 | } |
4988 | |
4989 | static void |
4990 | AddObjCProperties(const CodeCompletionContext &CCContext, |
4991 | ObjCContainerDecl *Container, bool AllowCategories, |
4992 | bool AllowNullaryMethods, DeclContext *CurContext, |
4993 | AddedPropertiesSet &AddedProperties, ResultBuilder &Results, |
4994 | bool IsBaseExprStatement = false, |
4995 | bool IsClassProperty = false, bool InOriginalClass = true) { |
4996 | typedef CodeCompletionResult Result; |
4997 | |
4998 | // Retrieve the definition. |
4999 | Container = getContainerDef(Container); |
5000 | |
5001 | // Add properties in this container. |
5002 | const auto AddProperty = [&](const ObjCPropertyDecl *P) { |
5003 | if (!AddedProperties.insert(P->getIdentifier()).second) |
5004 | return; |
5005 | |
5006 | // FIXME: Provide block invocation completion for non-statement |
5007 | // expressions. |
5008 | if (!P->getType().getTypePtr()->isBlockPointerType() || |
5009 | !IsBaseExprStatement) { |
5010 | Result R = Result(P, Results.getBasePriority(P), nullptr); |
5011 | if (!InOriginalClass) |
5012 | setInBaseClass(R); |
5013 | Results.MaybeAddResult(R, CurContext); |
5014 | return; |
5015 | } |
5016 | |
5017 | // Block setter and invocation completion is provided only when we are able |
5018 | // to find the FunctionProtoTypeLoc with parameter names for the block. |
5019 | FunctionTypeLoc BlockLoc; |
5020 | FunctionProtoTypeLoc BlockProtoLoc; |
5021 | findTypeLocationForBlockDecl(TSInfo: P->getTypeSourceInfo(), Block&: BlockLoc, |
5022 | BlockProto&: BlockProtoLoc); |
5023 | if (!BlockLoc) { |
5024 | Result R = Result(P, Results.getBasePriority(P), nullptr); |
5025 | if (!InOriginalClass) |
5026 | setInBaseClass(R); |
5027 | Results.MaybeAddResult(R, CurContext); |
5028 | return; |
5029 | } |
5030 | |
5031 | // The default completion result for block properties should be the block |
5032 | // invocation completion when the base expression is a statement. |
5033 | CodeCompletionBuilder Builder(Results.getAllocator(), |
5034 | Results.getCodeCompletionTUInfo()); |
5035 | AddObjCBlockCall(Container->getASTContext(), |
5036 | getCompletionPrintingPolicy(S&: Results.getSema()), Builder, P, |
5037 | BlockLoc, BlockProtoLoc); |
5038 | Result R = Result(Builder.TakeString(), P, Results.getBasePriority(P)); |
5039 | if (!InOriginalClass) |
5040 | setInBaseClass(R); |
5041 | Results.MaybeAddResult(R, CurContext); |
5042 | |
5043 | // Provide additional block setter completion iff the base expression is a |
5044 | // statement and the block property is mutable. |
5045 | if (!P->isReadOnly()) { |
5046 | CodeCompletionBuilder Builder(Results.getAllocator(), |
5047 | Results.getCodeCompletionTUInfo()); |
5048 | AddResultTypeChunk(Container->getASTContext(), |
5049 | getCompletionPrintingPolicy(S&: Results.getSema()), P, |
5050 | CCContext.getBaseType(), Builder); |
5051 | Builder.AddTypedTextChunk( |
5052 | Text: Results.getAllocator().CopyString(String: P->getName())); |
5053 | Builder.AddChunk(CK: CodeCompletionString::CK_Equal); |
5054 | |
5055 | std::string PlaceholderStr = formatBlockPlaceholder( |
5056 | getCompletionPrintingPolicy(S&: Results.getSema()), P, BlockLoc, |
5057 | BlockProtoLoc, /*SuppressBlockName=*/true); |
5058 | // Add the placeholder string. |
5059 | Builder.AddPlaceholderChunk( |
5060 | Placeholder: Builder.getAllocator().CopyString(String: PlaceholderStr)); |
5061 | |
5062 | // When completing blocks properties that return void the default |
5063 | // property completion result should show up before the setter, |
5064 | // otherwise the setter completion should show up before the default |
5065 | // property completion, as we normally want to use the result of the |
5066 | // call. |
5067 | Result R = |
5068 | Result(Builder.TakeString(), P, |
5069 | Results.getBasePriority(P) + |
5070 | (BlockLoc.getTypePtr()->getReturnType()->isVoidType() |
5071 | ? CCD_BlockPropertySetter |
5072 | : -CCD_BlockPropertySetter)); |
5073 | if (!InOriginalClass) |
5074 | setInBaseClass(R); |
5075 | Results.MaybeAddResult(R, CurContext); |
5076 | } |
5077 | }; |
5078 | |
5079 | if (IsClassProperty) { |
5080 | for (const auto *P : Container->class_properties()) |
5081 | AddProperty(P); |
5082 | } else { |
5083 | for (const auto *P : Container->instance_properties()) |
5084 | AddProperty(P); |
5085 | } |
5086 | |
5087 | // Add nullary methods or implicit class properties |
5088 | if (AllowNullaryMethods) { |
5089 | ASTContext &Context = Container->getASTContext(); |
5090 | PrintingPolicy Policy = getCompletionPrintingPolicy(S&: Results.getSema()); |
5091 | // Adds a method result |
5092 | const auto AddMethod = [&](const ObjCMethodDecl *M) { |
5093 | const IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(argIndex: 0); |
5094 | if (!Name) |
5095 | return; |
5096 | if (!AddedProperties.insert(Ptr: Name).second) |
5097 | return; |
5098 | CodeCompletionBuilder Builder(Results.getAllocator(), |
5099 | Results.getCodeCompletionTUInfo()); |
5100 | AddResultTypeChunk(Context, Policy, M, CCContext.getBaseType(), Builder); |
5101 | Builder.AddTypedTextChunk( |
5102 | Text: Results.getAllocator().CopyString(String: Name->getName())); |
5103 | Result R = Result(Builder.TakeString(), M, |
5104 | CCP_MemberDeclaration + CCD_MethodAsProperty); |
5105 | if (!InOriginalClass) |
5106 | setInBaseClass(R); |
5107 | Results.MaybeAddResult(R, CurContext); |
5108 | }; |
5109 | |
5110 | if (IsClassProperty) { |
5111 | for (const auto *M : Container->methods()) { |
5112 | // Gather the class method that can be used as implicit property |
5113 | // getters. Methods with arguments or methods that return void aren't |
5114 | // added to the results as they can't be used as a getter. |
5115 | if (!M->getSelector().isUnarySelector() || |
5116 | M->getReturnType()->isVoidType() || M->isInstanceMethod()) |
5117 | continue; |
5118 | AddMethod(M); |
5119 | } |
5120 | } else { |
5121 | for (auto *M : Container->methods()) { |
5122 | if (M->getSelector().isUnarySelector()) |
5123 | AddMethod(M); |
5124 | } |
5125 | } |
5126 | } |
5127 | |
5128 | // Add properties in referenced protocols. |
5129 | if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Val: Container)) { |
5130 | for (auto *P : Protocol->protocols()) |
5131 | AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods, |
5132 | CurContext, AddedProperties, Results, |
5133 | IsBaseExprStatement, IsClassProperty, |
5134 | /*InOriginalClass*/ false); |
5135 | } else if (ObjCInterfaceDecl *IFace = |
5136 | dyn_cast<ObjCInterfaceDecl>(Val: Container)) { |
5137 | if (AllowCategories) { |
5138 | // Look through categories. |
5139 | for (auto *Cat : IFace->known_categories()) |
5140 | AddObjCProperties(CCContext, Cat, AllowCategories, AllowNullaryMethods, |
5141 | CurContext, AddedProperties, Results, |
5142 | IsBaseExprStatement, IsClassProperty, |
5143 | InOriginalClass); |
5144 | } |
5145 | |
5146 | // Look through protocols. |
5147 | for (auto *I : IFace->all_referenced_protocols()) |
5148 | AddObjCProperties(CCContext, I, AllowCategories, AllowNullaryMethods, |
5149 | CurContext, AddedProperties, Results, |
5150 | IsBaseExprStatement, IsClassProperty, |
5151 | /*InOriginalClass*/ false); |
5152 | |
5153 | // Look in the superclass. |
5154 | if (IFace->getSuperClass()) |
5155 | AddObjCProperties(CCContext, IFace->getSuperClass(), AllowCategories, |
5156 | AllowNullaryMethods, CurContext, AddedProperties, |
5157 | Results, IsBaseExprStatement, IsClassProperty, |
5158 | /*InOriginalClass*/ false); |
5159 | } else if (const auto *Category = |
5160 | dyn_cast<ObjCCategoryDecl>(Val: Container)) { |
5161 | // Look through protocols. |
5162 | for (auto *P : Category->protocols()) |
5163 | AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods, |
5164 | CurContext, AddedProperties, Results, |
5165 | IsBaseExprStatement, IsClassProperty, |
5166 | /*InOriginalClass*/ false); |
5167 | } |
5168 | } |
5169 | |
5170 | static void |
5171 | AddRecordMembersCompletionResults(Sema &SemaRef, ResultBuilder &Results, |
5172 | Scope *S, QualType BaseType, |
5173 | ExprValueKind BaseKind, RecordDecl *RD, |
5174 | std::optional<FixItHint> AccessOpFixIt) { |
5175 | // Indicate that we are performing a member access, and the cv-qualifiers |
5176 | // for the base object type. |
5177 | Results.setObjectTypeQualifiers(Quals: BaseType.getQualifiers(), Kind: BaseKind); |
5178 | |
5179 | // Access to a C/C++ class, struct, or union. |
5180 | Results.allowNestedNameSpecifiers(); |
5181 | std::vector<FixItHint> FixIts; |
5182 | if (AccessOpFixIt) |
5183 | FixIts.emplace_back(args&: *AccessOpFixIt); |
5184 | CodeCompletionDeclConsumer Consumer(Results, RD, BaseType, std::move(FixIts)); |
5185 | SemaRef.LookupVisibleDecls(RD, Sema::LookupMemberName, Consumer, |
5186 | SemaRef.CodeCompleter->includeGlobals(), |
5187 | /*IncludeDependentBases=*/true, |
5188 | SemaRef.CodeCompleter->loadExternal()); |
5189 | |
5190 | if (SemaRef.getLangOpts().CPlusPlus) { |
5191 | if (!Results.empty()) { |
5192 | // The "template" keyword can follow "->" or "." in the grammar. |
5193 | // However, we only want to suggest the template keyword if something |
5194 | // is dependent. |
5195 | bool IsDependent = BaseType->isDependentType(); |
5196 | if (!IsDependent) { |
5197 | for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent()) |
5198 | if (DeclContext *Ctx = DepScope->getEntity()) { |
5199 | IsDependent = Ctx->isDependentContext(); |
5200 | break; |
5201 | } |
5202 | } |
5203 | |
5204 | if (IsDependent) |
5205 | Results.AddResult(R: CodeCompletionResult("template" )); |
5206 | } |
5207 | } |
5208 | } |
5209 | |
5210 | // Returns the RecordDecl inside the BaseType, falling back to primary template |
5211 | // in case of specializations. Since we might not have a decl for the |
5212 | // instantiation/specialization yet, e.g. dependent code. |
5213 | static RecordDecl *getAsRecordDecl(QualType BaseType) { |
5214 | BaseType = BaseType.getNonReferenceType(); |
5215 | if (auto *RD = BaseType->getAsRecordDecl()) { |
5216 | if (const auto *CTSD = |
5217 | llvm::dyn_cast<ClassTemplateSpecializationDecl>(Val: RD)) { |
5218 | // Template might not be instantiated yet, fall back to primary template |
5219 | // in such cases. |
5220 | if (CTSD->getTemplateSpecializationKind() == TSK_Undeclared) |
5221 | RD = CTSD->getSpecializedTemplate()->getTemplatedDecl(); |
5222 | } |
5223 | return RD; |
5224 | } |
5225 | |
5226 | if (const auto *TST = BaseType->getAs<TemplateSpecializationType>()) { |
5227 | if (const auto *TD = dyn_cast_or_null<ClassTemplateDecl>( |
5228 | Val: TST->getTemplateName().getAsTemplateDecl())) { |
5229 | return TD->getTemplatedDecl(); |
5230 | } |
5231 | } |
5232 | |
5233 | return nullptr; |
5234 | } |
5235 | |
5236 | namespace { |
5237 | // Collects completion-relevant information about a concept-constrainted type T. |
5238 | // In particular, examines the constraint expressions to find members of T. |
5239 | // |
5240 | // The design is very simple: we walk down each constraint looking for |
5241 | // expressions of the form T.foo(). |
5242 | // If we're extra lucky, the return type is specified. |
5243 | // We don't do any clever handling of && or || in constraint expressions, we |
5244 | // take members from both branches. |
5245 | // |
5246 | // For example, given: |
5247 | // template <class T> concept X = requires (T t, string& s) { t.print(s); }; |
5248 | // template <X U> void foo(U u) { u.^ } |
5249 | // We want to suggest the inferred member function 'print(string)'. |
5250 | // We see that u has type U, so X<U> holds. |
5251 | // X<U> requires t.print(s) to be valid, where t has type U (substituted for T). |
5252 | // By looking at the CallExpr we find the signature of print(). |
5253 | // |
5254 | // While we tend to know in advance which kind of members (access via . -> ::) |
5255 | // we want, it's simpler just to gather them all and post-filter. |
5256 | // |
5257 | // FIXME: some of this machinery could be used for non-concept type-parms too, |
5258 | // enabling completion for type parameters based on other uses of that param. |
5259 | // |
5260 | // FIXME: there are other cases where a type can be constrained by a concept, |
5261 | // e.g. inside `if constexpr(ConceptSpecializationExpr) { ... }` |
5262 | class ConceptInfo { |
5263 | public: |
5264 | // Describes a likely member of a type, inferred by concept constraints. |
5265 | // Offered as a code completion for T. T-> and T:: contexts. |
5266 | struct Member { |
5267 | // Always non-null: we only handle members with ordinary identifier names. |
5268 | const IdentifierInfo *Name = nullptr; |
5269 | // Set for functions we've seen called. |
5270 | // We don't have the declared parameter types, only the actual types of |
5271 | // arguments we've seen. These are still valuable, as it's hard to render |
5272 | // a useful function completion with neither parameter types nor names! |
5273 | std::optional<SmallVector<QualType, 1>> ArgTypes; |
5274 | // Whether this is accessed as T.member, T->member, or T::member. |
5275 | enum AccessOperator { |
5276 | Colons, |
5277 | Arrow, |
5278 | Dot, |
5279 | } Operator = Dot; |
5280 | // What's known about the type of a variable or return type of a function. |
5281 | const TypeConstraint *ResultType = nullptr; |
5282 | // FIXME: also track: |
5283 | // - kind of entity (function/variable/type), to expose structured results |
5284 | // - template args kinds/types, as a proxy for template params |
5285 | |
5286 | // For now we simply return these results as "pattern" strings. |
5287 | CodeCompletionString *render(Sema &S, CodeCompletionAllocator &Alloc, |
5288 | CodeCompletionTUInfo &Info) const { |
5289 | CodeCompletionBuilder B(Alloc, Info); |
5290 | // Result type |
5291 | if (ResultType) { |
5292 | std::string AsString; |
5293 | { |
5294 | llvm::raw_string_ostream OS(AsString); |
5295 | QualType ExactType = deduceType(T: *ResultType); |
5296 | if (!ExactType.isNull()) |
5297 | ExactType.print(OS, Policy: getCompletionPrintingPolicy(S)); |
5298 | else |
5299 | ResultType->print(OS, Policy: getCompletionPrintingPolicy(S)); |
5300 | } |
5301 | B.AddResultTypeChunk(ResultType: Alloc.CopyString(String: AsString)); |
5302 | } |
5303 | // Member name |
5304 | B.AddTypedTextChunk(Text: Alloc.CopyString(String: Name->getName())); |
5305 | // Function argument list |
5306 | if (ArgTypes) { |
5307 | B.AddChunk(CK: clang::CodeCompletionString::CK_LeftParen); |
5308 | bool First = true; |
5309 | for (QualType Arg : *ArgTypes) { |
5310 | if (First) |
5311 | First = false; |
5312 | else { |
5313 | B.AddChunk(CK: clang::CodeCompletionString::CK_Comma); |
5314 | B.AddChunk(CK: clang::CodeCompletionString::CK_HorizontalSpace); |
5315 | } |
5316 | B.AddPlaceholderChunk(Placeholder: Alloc.CopyString( |
5317 | String: Arg.getAsString(Policy: getCompletionPrintingPolicy(S)))); |
5318 | } |
5319 | B.AddChunk(CK: clang::CodeCompletionString::CK_RightParen); |
5320 | } |
5321 | return B.TakeString(); |
5322 | } |
5323 | }; |
5324 | |
5325 | // BaseType is the type parameter T to infer members from. |
5326 | // T must be accessible within S, as we use it to find the template entity |
5327 | // that T is attached to in order to gather the relevant constraints. |
5328 | ConceptInfo(const TemplateTypeParmType &BaseType, Scope *S) { |
5329 | auto *TemplatedEntity = getTemplatedEntity(D: BaseType.getDecl(), S); |
5330 | for (const Expr *E : constraintsForTemplatedEntity(DC: TemplatedEntity)) |
5331 | believe(E, T: &BaseType); |
5332 | } |
5333 | |
5334 | std::vector<Member> members() { |
5335 | std::vector<Member> Results; |
5336 | for (const auto &E : this->Results) |
5337 | Results.push_back(x: E.second); |
5338 | llvm::sort(C&: Results, Comp: [](const Member &L, const Member &R) { |
5339 | return L.Name->getName() < R.Name->getName(); |
5340 | }); |
5341 | return Results; |
5342 | } |
5343 | |
5344 | private: |
5345 | // Infer members of T, given that the expression E (dependent on T) is true. |
5346 | void believe(const Expr *E, const TemplateTypeParmType *T) { |
5347 | if (!E || !T) |
5348 | return; |
5349 | if (auto *CSE = dyn_cast<ConceptSpecializationExpr>(Val: E)) { |
5350 | // If the concept is |
5351 | // template <class A, class B> concept CD = f<A, B>(); |
5352 | // And the concept specialization is |
5353 | // CD<int, T> |
5354 | // Then we're substituting T for B, so we want to make f<A, B>() true |
5355 | // by adding members to B - i.e. believe(f<A, B>(), B); |
5356 | // |
5357 | // For simplicity: |
5358 | // - we don't attempt to substitute int for A |
5359 | // - when T is used in other ways (like CD<T*>) we ignore it |
5360 | ConceptDecl *CD = CSE->getNamedConcept(); |
5361 | TemplateParameterList *Params = CD->getTemplateParameters(); |
5362 | unsigned Index = 0; |
5363 | for (const auto &Arg : CSE->getTemplateArguments()) { |
5364 | if (Index >= Params->size()) |
5365 | break; // Won't happen in valid code. |
5366 | if (isApprox(Arg, T)) { |
5367 | auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Val: Params->getParam(Idx: Index)); |
5368 | if (!TTPD) |
5369 | continue; |
5370 | // T was used as an argument, and bound to the parameter TT. |
5371 | auto *TT = cast<TemplateTypeParmType>(TTPD->getTypeForDecl()); |
5372 | // So now we know the constraint as a function of TT is true. |
5373 | believe(E: CD->getConstraintExpr(), T: TT); |
5374 | // (concepts themselves have no associated constraints to require) |
5375 | } |
5376 | |
5377 | ++Index; |
5378 | } |
5379 | } else if (auto *BO = dyn_cast<BinaryOperator>(Val: E)) { |
5380 | // For A && B, we can infer members from both branches. |
5381 | // For A || B, the union is still more useful than the intersection. |
5382 | if (BO->getOpcode() == BO_LAnd || BO->getOpcode() == BO_LOr) { |
5383 | believe(E: BO->getLHS(), T); |
5384 | believe(E: BO->getRHS(), T); |
5385 | } |
5386 | } else if (auto *RE = dyn_cast<RequiresExpr>(Val: E)) { |
5387 | // A requires(){...} lets us infer members from each requirement. |
5388 | for (const concepts::Requirement *Req : RE->getRequirements()) { |
5389 | if (!Req->isDependent()) |
5390 | continue; // Can't tell us anything about T. |
5391 | // Now Req cannot a substitution-error: those aren't dependent. |
5392 | |
5393 | if (auto *TR = dyn_cast<concepts::TypeRequirement>(Val: Req)) { |
5394 | // Do a full traversal so we get `foo` from `typename T::foo::bar`. |
5395 | QualType AssertedType = TR->getType()->getType(); |
5396 | ValidVisitor(this, T).TraverseType(T: AssertedType); |
5397 | } else if (auto *ER = dyn_cast<concepts::ExprRequirement>(Val: Req)) { |
5398 | ValidVisitor Visitor(this, T); |
5399 | // If we have a type constraint on the value of the expression, |
5400 | // AND the whole outer expression describes a member, then we'll |
5401 | // be able to use the constraint to provide the return type. |
5402 | if (ER->getReturnTypeRequirement().isTypeConstraint()) { |
5403 | Visitor.OuterType = |
5404 | ER->getReturnTypeRequirement().getTypeConstraint(); |
5405 | Visitor.OuterExpr = ER->getExpr(); |
5406 | } |
5407 | Visitor.TraverseStmt(ER->getExpr()); |
5408 | } else if (auto *NR = dyn_cast<concepts::NestedRequirement>(Val: Req)) { |
5409 | believe(E: NR->getConstraintExpr(), T); |
5410 | } |
5411 | } |
5412 | } |
5413 | } |
5414 | |
5415 | // This visitor infers members of T based on traversing expressions/types |
5416 | // that involve T. It is invoked with code known to be valid for T. |
5417 | class ValidVisitor : public RecursiveASTVisitor<ValidVisitor> { |
5418 | ConceptInfo *Outer; |
5419 | const TemplateTypeParmType *T; |
5420 | |
5421 | CallExpr *Caller = nullptr; |
5422 | Expr *Callee = nullptr; |
5423 | |
5424 | public: |
5425 | // If set, OuterExpr is constrained by OuterType. |
5426 | Expr *OuterExpr = nullptr; |
5427 | const TypeConstraint *OuterType = nullptr; |
5428 | |
5429 | ValidVisitor(ConceptInfo *Outer, const TemplateTypeParmType *T) |
5430 | : Outer(Outer), T(T) { |
5431 | assert(T); |
5432 | } |
5433 | |
5434 | // In T.foo or T->foo, `foo` is a member function/variable. |
5435 | bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) { |
5436 | const Type *Base = E->getBaseType().getTypePtr(); |
5437 | bool IsArrow = E->isArrow(); |
5438 | if (Base->isPointerType() && IsArrow) { |
5439 | IsArrow = false; |
5440 | Base = Base->getPointeeType().getTypePtr(); |
5441 | } |
5442 | if (isApprox(Base, T)) |
5443 | addValue(E, E->getMember(), IsArrow ? Member::Arrow : Member::Dot); |
5444 | return true; |
5445 | } |
5446 | |
5447 | // In T::foo, `foo` is a static member function/variable. |
5448 | bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) { |
5449 | if (E->getQualifier() && isApprox(E->getQualifier()->getAsType(), T)) |
5450 | addValue(E, E->getDeclName(), Member::Colons); |
5451 | return true; |
5452 | } |
5453 | |
5454 | // In T::typename foo, `foo` is a type. |
5455 | bool VisitDependentNameType(DependentNameType *DNT) { |
5456 | const auto *Q = DNT->getQualifier(); |
5457 | if (Q && isApprox(Q->getAsType(), T)) |
5458 | addType(Name: DNT->getIdentifier()); |
5459 | return true; |
5460 | } |
5461 | |
5462 | // In T::foo::bar, `foo` must be a type. |
5463 | // VisitNNS() doesn't exist, and TraverseNNS isn't always called :-( |
5464 | bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSL) { |
5465 | if (NNSL) { |
5466 | NestedNameSpecifier *NNS = NNSL.getNestedNameSpecifier(); |
5467 | const auto *Q = NNS->getPrefix(); |
5468 | if (Q && isApprox(Q->getAsType(), T)) |
5469 | addType(Name: NNS->getAsIdentifier()); |
5470 | } |
5471 | // FIXME: also handle T::foo<X>::bar |
5472 | return RecursiveASTVisitor::TraverseNestedNameSpecifierLoc(NNS: NNSL); |
5473 | } |
5474 | |
5475 | // FIXME also handle T::foo<X> |
5476 | |
5477 | // Track the innermost caller/callee relationship so we can tell if a |
5478 | // nested expr is being called as a function. |
5479 | bool VisitCallExpr(CallExpr *CE) { |
5480 | Caller = CE; |
5481 | Callee = CE->getCallee(); |
5482 | return true; |
5483 | } |
5484 | |
5485 | private: |
5486 | void addResult(Member &&M) { |
5487 | auto R = Outer->Results.try_emplace(Key: M.Name); |
5488 | Member &O = R.first->second; |
5489 | // Overwrite existing if the new member has more info. |
5490 | // The preference of . vs :: vs -> is fairly arbitrary. |
5491 | if (/*Inserted*/ R.second || |
5492 | std::make_tuple(args: M.ArgTypes.has_value(), args: M.ResultType != nullptr, |
5493 | args&: M.Operator) > std::make_tuple(args: O.ArgTypes.has_value(), |
5494 | args: O.ResultType != nullptr, |
5495 | args&: O.Operator)) |
5496 | O = std::move(M); |
5497 | } |
5498 | |
5499 | void addType(const IdentifierInfo *Name) { |
5500 | if (!Name) |
5501 | return; |
5502 | Member M; |
5503 | M.Name = Name; |
5504 | M.Operator = Member::Colons; |
5505 | addResult(M: std::move(M)); |
5506 | } |
5507 | |
5508 | void addValue(Expr *E, DeclarationName Name, |
5509 | Member::AccessOperator Operator) { |
5510 | if (!Name.isIdentifier()) |
5511 | return; |
5512 | Member Result; |
5513 | Result.Name = Name.getAsIdentifierInfo(); |
5514 | Result.Operator = Operator; |
5515 | // If this is the callee of an immediately-enclosing CallExpr, then |
5516 | // treat it as a method, otherwise it's a variable. |
5517 | if (Caller != nullptr && Callee == E) { |
5518 | Result.ArgTypes.emplace(); |
5519 | for (const auto *Arg : Caller->arguments()) |
5520 | Result.ArgTypes->push_back(Elt: Arg->getType()); |
5521 | if (Caller == OuterExpr) { |
5522 | Result.ResultType = OuterType; |
5523 | } |
5524 | } else { |
5525 | if (E == OuterExpr) |
5526 | Result.ResultType = OuterType; |
5527 | } |
5528 | addResult(M: std::move(Result)); |
5529 | } |
5530 | }; |
5531 | |
5532 | static bool isApprox(const TemplateArgument &Arg, const Type *T) { |
5533 | return Arg.getKind() == TemplateArgument::Type && |
5534 | isApprox(T1: Arg.getAsType().getTypePtr(), T2: T); |
5535 | } |
5536 | |
5537 | static bool isApprox(const Type *T1, const Type *T2) { |
5538 | return T1 && T2 && |
5539 | T1->getCanonicalTypeUnqualified() == |
5540 | T2->getCanonicalTypeUnqualified(); |
5541 | } |
5542 | |
5543 | // Returns the DeclContext immediately enclosed by the template parameter |
5544 | // scope. For primary templates, this is the templated (e.g.) CXXRecordDecl. |
5545 | // For specializations, this is e.g. ClassTemplatePartialSpecializationDecl. |
5546 | static DeclContext *getTemplatedEntity(const TemplateTypeParmDecl *D, |
5547 | Scope *S) { |
5548 | if (D == nullptr) |
5549 | return nullptr; |
5550 | Scope *Inner = nullptr; |
5551 | while (S) { |
5552 | if (S->isTemplateParamScope() && S->isDeclScope(D)) |
5553 | return Inner ? Inner->getEntity() : nullptr; |
5554 | Inner = S; |
5555 | S = S->getParent(); |
5556 | } |
5557 | return nullptr; |
5558 | } |
5559 | |
5560 | // Gets all the type constraint expressions that might apply to the type |
5561 | // variables associated with DC (as returned by getTemplatedEntity()). |
5562 | static SmallVector<const Expr *, 1> |
5563 | constraintsForTemplatedEntity(DeclContext *DC) { |
5564 | SmallVector<const Expr *, 1> Result; |
5565 | if (DC == nullptr) |
5566 | return Result; |
5567 | // Primary templates can have constraints. |
5568 | if (const auto *TD = cast<Decl>(Val: DC)->getDescribedTemplate()) |
5569 | TD->getAssociatedConstraints(AC&: Result); |
5570 | // Partial specializations may have constraints. |
5571 | if (const auto *CTPSD = |
5572 | dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: DC)) |
5573 | CTPSD->getAssociatedConstraints(AC&: Result); |
5574 | if (const auto *VTPSD = dyn_cast<VarTemplatePartialSpecializationDecl>(Val: DC)) |
5575 | VTPSD->getAssociatedConstraints(AC&: Result); |
5576 | return Result; |
5577 | } |
5578 | |
5579 | // Attempt to find the unique type satisfying a constraint. |
5580 | // This lets us show e.g. `int` instead of `std::same_as<int>`. |
5581 | static QualType deduceType(const TypeConstraint &T) { |
5582 | // Assume a same_as<T> return type constraint is std::same_as or equivalent. |
5583 | // In this case the return type is T. |
5584 | DeclarationName DN = T.getNamedConcept()->getDeclName(); |
5585 | if (DN.isIdentifier() && DN.getAsIdentifierInfo()->isStr(Str: "same_as" )) |
5586 | if (const auto *Args = T.getTemplateArgsAsWritten()) |
5587 | if (Args->getNumTemplateArgs() == 1) { |
5588 | const auto &Arg = Args->arguments().front().getArgument(); |
5589 | if (Arg.getKind() == TemplateArgument::Type) |
5590 | return Arg.getAsType(); |
5591 | } |
5592 | return {}; |
5593 | } |
5594 | |
5595 | llvm::DenseMap<const IdentifierInfo *, Member> Results; |
5596 | }; |
5597 | |
5598 | // Returns a type for E that yields acceptable member completions. |
5599 | // In particular, when E->getType() is DependentTy, try to guess a likely type. |
5600 | // We accept some lossiness (like dropping parameters). |
5601 | // We only try to handle common expressions on the LHS of MemberExpr. |
5602 | QualType getApproximateType(const Expr *E) { |
5603 | if (E->getType().isNull()) |
5604 | return QualType(); |
5605 | E = E->IgnoreParenImpCasts(); |
5606 | QualType Unresolved = E->getType(); |
5607 | // We only resolve DependentTy, or undeduced autos (including auto* etc). |
5608 | if (!Unresolved->isSpecificBuiltinType(K: BuiltinType::Dependent)) { |
5609 | AutoType *Auto = Unresolved->getContainedAutoType(); |
5610 | if (!Auto || !Auto->isUndeducedAutoType()) |
5611 | return Unresolved; |
5612 | } |
5613 | // A call: approximate-resolve callee to a function type, get its return type |
5614 | if (const CallExpr *CE = llvm::dyn_cast<CallExpr>(Val: E)) { |
5615 | QualType Callee = getApproximateType(E: CE->getCallee()); |
5616 | if (Callee.isNull() || |
5617 | Callee->isSpecificPlaceholderType(K: BuiltinType::BoundMember)) |
5618 | Callee = Expr::findBoundMemberType(expr: CE->getCallee()); |
5619 | if (Callee.isNull()) |
5620 | return Unresolved; |
5621 | |
5622 | if (const auto *FnTypePtr = Callee->getAs<PointerType>()) { |
5623 | Callee = FnTypePtr->getPointeeType(); |
5624 | } else if (const auto *BPT = Callee->getAs<BlockPointerType>()) { |
5625 | Callee = BPT->getPointeeType(); |
5626 | } |
5627 | if (const FunctionType *FnType = Callee->getAs<FunctionType>()) |
5628 | return FnType->getReturnType().getNonReferenceType(); |
5629 | |
5630 | // Unresolved call: try to guess the return type. |
5631 | if (const auto *OE = llvm::dyn_cast<OverloadExpr>(Val: CE->getCallee())) { |
5632 | // If all candidates have the same approximate return type, use it. |
5633 | // Discard references and const to allow more to be "the same". |
5634 | // (In particular, if there's one candidate + ADL, resolve it). |
5635 | const Type *Common = nullptr; |
5636 | for (const auto *D : OE->decls()) { |
5637 | QualType ReturnType; |
5638 | if (const auto *FD = llvm::dyn_cast<FunctionDecl>(Val: D)) |
5639 | ReturnType = FD->getReturnType(); |
5640 | else if (const auto *FTD = llvm::dyn_cast<FunctionTemplateDecl>(Val: D)) |
5641 | ReturnType = FTD->getTemplatedDecl()->getReturnType(); |
5642 | if (ReturnType.isNull()) |
5643 | continue; |
5644 | const Type *Candidate = |
5645 | ReturnType.getNonReferenceType().getCanonicalType().getTypePtr(); |
5646 | if (Common && Common != Candidate) |
5647 | return Unresolved; // Multiple candidates. |
5648 | Common = Candidate; |
5649 | } |
5650 | if (Common != nullptr) |
5651 | return QualType(Common, 0); |
5652 | } |
5653 | } |
5654 | // A dependent member: approximate-resolve the base, then lookup. |
5655 | if (const auto *CDSME = llvm::dyn_cast<CXXDependentScopeMemberExpr>(Val: E)) { |
5656 | QualType Base = CDSME->isImplicitAccess() |
5657 | ? CDSME->getBaseType() |
5658 | : getApproximateType(E: CDSME->getBase()); |
5659 | if (CDSME->isArrow() && !Base.isNull()) |
5660 | Base = Base->getPointeeType(); // could handle unique_ptr etc here? |
5661 | auto *RD = |
5662 | Base.isNull() |
5663 | ? nullptr |
5664 | : llvm::dyn_cast_or_null<CXXRecordDecl>(Val: getAsRecordDecl(BaseType: Base)); |
5665 | if (RD && RD->isCompleteDefinition()) { |
5666 | // Look up member heuristically, including in bases. |
5667 | for (const auto *Member : RD->lookupDependentName( |
5668 | Name: CDSME->getMember(), Filter: [](const NamedDecl *Member) { |
5669 | return llvm::isa<ValueDecl>(Val: Member); |
5670 | })) { |
5671 | return llvm::cast<ValueDecl>(Val: Member)->getType().getNonReferenceType(); |
5672 | } |
5673 | } |
5674 | } |
5675 | // A reference to an `auto` variable: approximate-resolve its initializer. |
5676 | if (const auto *DRE = llvm::dyn_cast<DeclRefExpr>(Val: E)) { |
5677 | if (const auto *VD = llvm::dyn_cast<VarDecl>(Val: DRE->getDecl())) { |
5678 | if (VD->hasInit()) |
5679 | return getApproximateType(E: VD->getInit()); |
5680 | } |
5681 | } |
5682 | if (const auto *UO = llvm::dyn_cast<UnaryOperator>(Val: E)) { |
5683 | if (UO->getOpcode() == UnaryOperatorKind::UO_Deref) |
5684 | return UO->getSubExpr()->getType()->getPointeeType(); |
5685 | } |
5686 | return Unresolved; |
5687 | } |
5688 | |
5689 | // If \p Base is ParenListExpr, assume a chain of comma operators and pick the |
5690 | // last expr. We expect other ParenListExprs to be resolved to e.g. constructor |
5691 | // calls before here. (So the ParenListExpr should be nonempty, but check just |
5692 | // in case) |
5693 | Expr *unwrapParenList(Expr *Base) { |
5694 | if (auto *PLE = llvm::dyn_cast_or_null<ParenListExpr>(Val: Base)) { |
5695 | if (PLE->getNumExprs() == 0) |
5696 | return nullptr; |
5697 | Base = PLE->getExpr(Init: PLE->getNumExprs() - 1); |
5698 | } |
5699 | return Base; |
5700 | } |
5701 | |
5702 | } // namespace |
5703 | |
5704 | void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, |
5705 | Expr *OtherOpBase, |
5706 | SourceLocation OpLoc, bool IsArrow, |
5707 | bool IsBaseExprStatement, |
5708 | QualType PreferredType) { |
5709 | Base = unwrapParenList(Base); |
5710 | OtherOpBase = unwrapParenList(Base: OtherOpBase); |
5711 | if (!Base || !CodeCompleter) |
5712 | return; |
5713 | |
5714 | ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow); |
5715 | if (ConvertedBase.isInvalid()) |
5716 | return; |
5717 | QualType ConvertedBaseType = getApproximateType(E: ConvertedBase.get()); |
5718 | |
5719 | enum CodeCompletionContext::Kind contextKind; |
5720 | |
5721 | if (IsArrow) { |
5722 | if (const auto *Ptr = ConvertedBaseType->getAs<PointerType>()) |
5723 | ConvertedBaseType = Ptr->getPointeeType(); |
5724 | } |
5725 | |
5726 | if (IsArrow) { |
5727 | contextKind = CodeCompletionContext::CCC_ArrowMemberAccess; |
5728 | } else { |
5729 | if (ConvertedBaseType->isObjCObjectPointerType() || |
5730 | ConvertedBaseType->isObjCObjectOrInterfaceType()) { |
5731 | contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess; |
5732 | } else { |
5733 | contextKind = CodeCompletionContext::CCC_DotMemberAccess; |
5734 | } |
5735 | } |
5736 | |
5737 | CodeCompletionContext CCContext(contextKind, ConvertedBaseType); |
5738 | CCContext.setPreferredType(PreferredType); |
5739 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
5740 | CodeCompleter->getCodeCompletionTUInfo(), CCContext, |
5741 | &ResultBuilder::IsMember); |
5742 | |
5743 | auto DoCompletion = [&](Expr *Base, bool IsArrow, |
5744 | std::optional<FixItHint> AccessOpFixIt) -> bool { |
5745 | if (!Base) |
5746 | return false; |
5747 | |
5748 | ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow); |
5749 | if (ConvertedBase.isInvalid()) |
5750 | return false; |
5751 | Base = ConvertedBase.get(); |
5752 | |
5753 | QualType BaseType = getApproximateType(E: Base); |
5754 | if (BaseType.isNull()) |
5755 | return false; |
5756 | ExprValueKind BaseKind = Base->getValueKind(); |
5757 | |
5758 | if (IsArrow) { |
5759 | if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { |
5760 | BaseType = Ptr->getPointeeType(); |
5761 | BaseKind = VK_LValue; |
5762 | } else if (BaseType->isObjCObjectPointerType() || |
5763 | BaseType->isTemplateTypeParmType()) { |
5764 | // Both cases (dot/arrow) handled below. |
5765 | } else { |
5766 | return false; |
5767 | } |
5768 | } |
5769 | |
5770 | if (RecordDecl *RD = getAsRecordDecl(BaseType)) { |
5771 | AddRecordMembersCompletionResults(SemaRef&: *this, Results, S, BaseType, BaseKind, |
5772 | RD, AccessOpFixIt: std::move(AccessOpFixIt)); |
5773 | } else if (const auto *TTPT = |
5774 | dyn_cast<TemplateTypeParmType>(Val: BaseType.getTypePtr())) { |
5775 | auto Operator = |
5776 | IsArrow ? ConceptInfo::Member::Arrow : ConceptInfo::Member::Dot; |
5777 | for (const auto &R : ConceptInfo(*TTPT, S).members()) { |
5778 | if (R.Operator != Operator) |
5779 | continue; |
5780 | CodeCompletionResult Result( |
5781 | R.render(S&: *this, Alloc&: CodeCompleter->getAllocator(), |
5782 | Info&: CodeCompleter->getCodeCompletionTUInfo())); |
5783 | if (AccessOpFixIt) |
5784 | Result.FixIts.push_back(x: *AccessOpFixIt); |
5785 | Results.AddResult(R: std::move(Result)); |
5786 | } |
5787 | } else if (!IsArrow && BaseType->isObjCObjectPointerType()) { |
5788 | // Objective-C property reference. Bail if we're performing fix-it code |
5789 | // completion since Objective-C properties are normally backed by ivars, |
5790 | // most Objective-C fix-its here would have little value. |
5791 | if (AccessOpFixIt) { |
5792 | return false; |
5793 | } |
5794 | AddedPropertiesSet AddedProperties; |
5795 | |
5796 | if (const ObjCObjectPointerType *ObjCPtr = |
5797 | BaseType->getAsObjCInterfacePointerType()) { |
5798 | // Add property results based on our interface. |
5799 | assert(ObjCPtr && "Non-NULL pointer guaranteed above!" ); |
5800 | AddObjCProperties(CCContext, ObjCPtr->getInterfaceDecl(), true, |
5801 | /*AllowNullaryMethods=*/true, CurContext, |
5802 | AddedProperties, Results, IsBaseExprStatement); |
5803 | } |
5804 | |
5805 | // Add properties from the protocols in a qualified interface. |
5806 | for (auto *I : BaseType->castAs<ObjCObjectPointerType>()->quals()) |
5807 | AddObjCProperties(CCContext, I, true, /*AllowNullaryMethods=*/true, |
5808 | CurContext, AddedProperties, Results, |
5809 | IsBaseExprStatement, /*IsClassProperty*/ false, |
5810 | /*InOriginalClass*/ false); |
5811 | } else if ((IsArrow && BaseType->isObjCObjectPointerType()) || |
5812 | (!IsArrow && BaseType->isObjCObjectType())) { |
5813 | // Objective-C instance variable access. Bail if we're performing fix-it |
5814 | // code completion since Objective-C properties are normally backed by |
5815 | // ivars, most Objective-C fix-its here would have little value. |
5816 | if (AccessOpFixIt) { |
5817 | return false; |
5818 | } |
5819 | ObjCInterfaceDecl *Class = nullptr; |
5820 | if (const ObjCObjectPointerType *ObjCPtr = |
5821 | BaseType->getAs<ObjCObjectPointerType>()) |
5822 | Class = ObjCPtr->getInterfaceDecl(); |
5823 | else |
5824 | Class = BaseType->castAs<ObjCObjectType>()->getInterface(); |
5825 | |
5826 | // Add all ivars from this class and its superclasses. |
5827 | if (Class) { |
5828 | CodeCompletionDeclConsumer Consumer(Results, Class, BaseType); |
5829 | Results.setFilter(&ResultBuilder::IsObjCIvar); |
5830 | LookupVisibleDecls( |
5831 | Class, LookupMemberName, Consumer, CodeCompleter->includeGlobals(), |
5832 | /*IncludeDependentBases=*/false, CodeCompleter->loadExternal()); |
5833 | } |
5834 | } |
5835 | |
5836 | // FIXME: How do we cope with isa? |
5837 | return true; |
5838 | }; |
5839 | |
5840 | Results.EnterNewScope(); |
5841 | |
5842 | bool CompletionSucceded = DoCompletion(Base, IsArrow, std::nullopt); |
5843 | if (CodeCompleter->includeFixIts()) { |
5844 | const CharSourceRange OpRange = |
5845 | CharSourceRange::getTokenRange(B: OpLoc, E: OpLoc); |
5846 | CompletionSucceded |= DoCompletion( |
5847 | OtherOpBase, !IsArrow, |
5848 | FixItHint::CreateReplacement(RemoveRange: OpRange, Code: IsArrow ? "." : "->" )); |
5849 | } |
5850 | |
5851 | Results.ExitScope(); |
5852 | |
5853 | if (!CompletionSucceded) |
5854 | return; |
5855 | |
5856 | // Hand off the results found for code completion. |
5857 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
5858 | Results: Results.data(), NumResults: Results.size()); |
5859 | } |
5860 | |
5861 | void Sema::CodeCompleteObjCClassPropertyRefExpr(Scope *S, |
5862 | const IdentifierInfo &ClassName, |
5863 | SourceLocation ClassNameLoc, |
5864 | bool IsBaseExprStatement) { |
5865 | const IdentifierInfo *ClassNamePtr = &ClassName; |
5866 | ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(Id&: ClassNamePtr, IdLoc: ClassNameLoc); |
5867 | if (!IFace) |
5868 | return; |
5869 | CodeCompletionContext CCContext( |
5870 | CodeCompletionContext::CCC_ObjCPropertyAccess); |
5871 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
5872 | CodeCompleter->getCodeCompletionTUInfo(), CCContext, |
5873 | &ResultBuilder::IsMember); |
5874 | Results.EnterNewScope(); |
5875 | AddedPropertiesSet AddedProperties; |
5876 | AddObjCProperties(CCContext, IFace, true, |
5877 | /*AllowNullaryMethods=*/true, CurContext, AddedProperties, |
5878 | Results, IsBaseExprStatement, |
5879 | /*IsClassProperty=*/true); |
5880 | Results.ExitScope(); |
5881 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
5882 | Results: Results.data(), NumResults: Results.size()); |
5883 | } |
5884 | |
5885 | void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) { |
5886 | if (!CodeCompleter) |
5887 | return; |
5888 | |
5889 | ResultBuilder::LookupFilter Filter = nullptr; |
5890 | enum CodeCompletionContext::Kind ContextKind = |
5891 | CodeCompletionContext::CCC_Other; |
5892 | switch ((DeclSpec::TST)TagSpec) { |
5893 | case DeclSpec::TST_enum: |
5894 | Filter = &ResultBuilder::IsEnum; |
5895 | ContextKind = CodeCompletionContext::CCC_EnumTag; |
5896 | break; |
5897 | |
5898 | case DeclSpec::TST_union: |
5899 | Filter = &ResultBuilder::IsUnion; |
5900 | ContextKind = CodeCompletionContext::CCC_UnionTag; |
5901 | break; |
5902 | |
5903 | case DeclSpec::TST_struct: |
5904 | case DeclSpec::TST_class: |
5905 | case DeclSpec::TST_interface: |
5906 | Filter = &ResultBuilder::IsClassOrStruct; |
5907 | ContextKind = CodeCompletionContext::CCC_ClassOrStructTag; |
5908 | break; |
5909 | |
5910 | default: |
5911 | llvm_unreachable("Unknown type specifier kind in CodeCompleteTag" ); |
5912 | } |
5913 | |
5914 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
5915 | CodeCompleter->getCodeCompletionTUInfo(), ContextKind); |
5916 | CodeCompletionDeclConsumer Consumer(Results, CurContext); |
5917 | |
5918 | // First pass: look for tags. |
5919 | Results.setFilter(Filter); |
5920 | LookupVisibleDecls(S, LookupTagName, Consumer, |
5921 | CodeCompleter->includeGlobals(), |
5922 | CodeCompleter->loadExternal()); |
5923 | |
5924 | if (CodeCompleter->includeGlobals()) { |
5925 | // Second pass: look for nested name specifiers. |
5926 | Results.setFilter(&ResultBuilder::IsNestedNameSpecifier); |
5927 | LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer, |
5928 | CodeCompleter->includeGlobals(), |
5929 | CodeCompleter->loadExternal()); |
5930 | } |
5931 | |
5932 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
5933 | Results: Results.data(), NumResults: Results.size()); |
5934 | } |
5935 | |
5936 | static void AddTypeQualifierResults(DeclSpec &DS, ResultBuilder &Results, |
5937 | const LangOptions &LangOpts) { |
5938 | if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const)) |
5939 | Results.AddResult(R: "const" ); |
5940 | if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile)) |
5941 | Results.AddResult(R: "volatile" ); |
5942 | if (LangOpts.C99 && !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict)) |
5943 | Results.AddResult(R: "restrict" ); |
5944 | if (LangOpts.C11 && !(DS.getTypeQualifiers() & DeclSpec::TQ_atomic)) |
5945 | Results.AddResult(R: "_Atomic" ); |
5946 | if (LangOpts.MSVCCompat && !(DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)) |
5947 | Results.AddResult(R: "__unaligned" ); |
5948 | } |
5949 | |
5950 | void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) { |
5951 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
5952 | CodeCompleter->getCodeCompletionTUInfo(), |
5953 | CodeCompletionContext::CCC_TypeQualifiers); |
5954 | Results.EnterNewScope(); |
5955 | AddTypeQualifierResults(DS, Results, LangOpts); |
5956 | Results.ExitScope(); |
5957 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
5958 | Results: Results.data(), NumResults: Results.size()); |
5959 | } |
5960 | |
5961 | void Sema::CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D, |
5962 | const VirtSpecifiers *VS) { |
5963 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
5964 | CodeCompleter->getCodeCompletionTUInfo(), |
5965 | CodeCompletionContext::CCC_TypeQualifiers); |
5966 | Results.EnterNewScope(); |
5967 | AddTypeQualifierResults(DS, Results, LangOpts); |
5968 | if (LangOpts.CPlusPlus11) { |
5969 | Results.AddResult(R: "noexcept" ); |
5970 | if (D.getContext() == DeclaratorContext::Member && !D.isCtorOrDtor() && |
5971 | !D.isStaticMember()) { |
5972 | if (!VS || !VS->isFinalSpecified()) |
5973 | Results.AddResult(R: "final" ); |
5974 | if (!VS || !VS->isOverrideSpecified()) |
5975 | Results.AddResult(R: "override" ); |
5976 | } |
5977 | } |
5978 | Results.ExitScope(); |
5979 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
5980 | Results: Results.data(), NumResults: Results.size()); |
5981 | } |
5982 | |
5983 | void Sema::CodeCompleteBracketDeclarator(Scope *S) { |
5984 | CodeCompleteExpression(S, PreferredType: QualType(getASTContext().getSizeType())); |
5985 | } |
5986 | |
5987 | void Sema::CodeCompleteCase(Scope *S) { |
5988 | if (getCurFunction()->SwitchStack.empty() || !CodeCompleter) |
5989 | return; |
5990 | |
5991 | SwitchStmt *Switch = getCurFunction()->SwitchStack.back().getPointer(); |
5992 | // Condition expression might be invalid, do not continue in this case. |
5993 | if (!Switch->getCond()) |
5994 | return; |
5995 | QualType type = Switch->getCond()->IgnoreImplicit()->getType(); |
5996 | if (!type->isEnumeralType()) { |
5997 | CodeCompleteExpressionData Data(type); |
5998 | Data.IntegralConstantExpression = true; |
5999 | CodeCompleteExpression(S, Data); |
6000 | return; |
6001 | } |
6002 | |
6003 | // Code-complete the cases of a switch statement over an enumeration type |
6004 | // by providing the list of |
6005 | EnumDecl *Enum = type->castAs<EnumType>()->getDecl(); |
6006 | if (EnumDecl *Def = Enum->getDefinition()) |
6007 | Enum = Def; |
6008 | |
6009 | // Determine which enumerators we have already seen in the switch statement. |
6010 | // FIXME: Ideally, we would also be able to look *past* the code-completion |
6011 | // token, in case we are code-completing in the middle of the switch and not |
6012 | // at the end. However, we aren't able to do so at the moment. |
6013 | CoveredEnumerators Enumerators; |
6014 | for (SwitchCase *SC = Switch->getSwitchCaseList(); SC; |
6015 | SC = SC->getNextSwitchCase()) { |
6016 | CaseStmt *Case = dyn_cast<CaseStmt>(Val: SC); |
6017 | if (!Case) |
6018 | continue; |
6019 | |
6020 | Expr *CaseVal = Case->getLHS()->IgnoreParenCasts(); |
6021 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: CaseVal)) |
6022 | if (auto *Enumerator = |
6023 | dyn_cast<EnumConstantDecl>(Val: DRE->getDecl())) { |
6024 | // We look into the AST of the case statement to determine which |
6025 | // enumerator was named. Alternatively, we could compute the value of |
6026 | // the integral constant expression, then compare it against the |
6027 | // values of each enumerator. However, value-based approach would not |
6028 | // work as well with C++ templates where enumerators declared within a |
6029 | // template are type- and value-dependent. |
6030 | Enumerators.Seen.insert(Ptr: Enumerator); |
6031 | |
6032 | // If this is a qualified-id, keep track of the nested-name-specifier |
6033 | // so that we can reproduce it as part of code completion, e.g., |
6034 | // |
6035 | // switch (TagD.getKind()) { |
6036 | // case TagDecl::TK_enum: |
6037 | // break; |
6038 | // case XXX |
6039 | // |
6040 | // At the XXX, our completions are TagDecl::TK_union, |
6041 | // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union, |
6042 | // TK_struct, and TK_class. |
6043 | Enumerators.SuggestedQualifier = DRE->getQualifier(); |
6044 | } |
6045 | } |
6046 | |
6047 | // Add any enumerators that have not yet been mentioned. |
6048 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
6049 | CodeCompleter->getCodeCompletionTUInfo(), |
6050 | CodeCompletionContext::CCC_Expression); |
6051 | AddEnumerators(Results, Context, Enum, CurContext, Enumerators); |
6052 | |
6053 | if (CodeCompleter->includeMacros()) { |
6054 | AddMacroResults(PP, Results, LoadExternal: CodeCompleter->loadExternal(), IncludeUndefined: false); |
6055 | } |
6056 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
6057 | Results: Results.data(), NumResults: Results.size()); |
6058 | } |
6059 | |
6060 | static bool anyNullArguments(ArrayRef<Expr *> Args) { |
6061 | if (Args.size() && !Args.data()) |
6062 | return true; |
6063 | |
6064 | for (unsigned I = 0; I != Args.size(); ++I) |
6065 | if (!Args[I]) |
6066 | return true; |
6067 | |
6068 | return false; |
6069 | } |
6070 | |
6071 | typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate; |
6072 | |
6073 | static void mergeCandidatesWithResults( |
6074 | Sema &SemaRef, SmallVectorImpl<ResultCandidate> &Results, |
6075 | OverloadCandidateSet &CandidateSet, SourceLocation Loc, size_t ArgSize) { |
6076 | // Sort the overload candidate set by placing the best overloads first. |
6077 | llvm::stable_sort(Range&: CandidateSet, C: [&](const OverloadCandidate &X, |
6078 | const OverloadCandidate &Y) { |
6079 | return isBetterOverloadCandidate(S&: SemaRef, Cand1: X, Cand2: Y, Loc, |
6080 | Kind: CandidateSet.getKind()); |
6081 | }); |
6082 | |
6083 | // Add the remaining viable overload candidates as code-completion results. |
6084 | for (OverloadCandidate &Candidate : CandidateSet) { |
6085 | if (Candidate.Function) { |
6086 | if (Candidate.Function->isDeleted()) |
6087 | continue; |
6088 | if (shouldEnforceArgLimit(/*PartialOverloading=*/true, |
6089 | Function: Candidate.Function) && |
6090 | Candidate.Function->getNumParams() <= ArgSize && |
6091 | // Having zero args is annoying, normally we don't surface a function |
6092 | // with 2 params, if you already have 2 params, because you are |
6093 | // inserting the 3rd now. But with zero, it helps the user to figure |
6094 | // out there are no overloads that take any arguments. Hence we are |
6095 | // keeping the overload. |
6096 | ArgSize > 0) |
6097 | continue; |
6098 | } |
6099 | if (Candidate.Viable) |
6100 | Results.push_back(Elt: ResultCandidate(Candidate.Function)); |
6101 | } |
6102 | } |
6103 | |
6104 | /// Get the type of the Nth parameter from a given set of overload |
6105 | /// candidates. |
6106 | static QualType getParamType(Sema &SemaRef, |
6107 | ArrayRef<ResultCandidate> Candidates, unsigned N) { |
6108 | |
6109 | // Given the overloads 'Candidates' for a function call matching all arguments |
6110 | // up to N, return the type of the Nth parameter if it is the same for all |
6111 | // overload candidates. |
6112 | QualType ParamType; |
6113 | for (auto &Candidate : Candidates) { |
6114 | QualType CandidateParamType = Candidate.getParamType(N); |
6115 | if (CandidateParamType.isNull()) |
6116 | continue; |
6117 | if (ParamType.isNull()) { |
6118 | ParamType = CandidateParamType; |
6119 | continue; |
6120 | } |
6121 | if (!SemaRef.Context.hasSameUnqualifiedType( |
6122 | T1: ParamType.getNonReferenceType(), |
6123 | T2: CandidateParamType.getNonReferenceType())) |
6124 | // Two conflicting types, give up. |
6125 | return QualType(); |
6126 | } |
6127 | |
6128 | return ParamType; |
6129 | } |
6130 | |
6131 | static QualType |
6132 | ProduceSignatureHelp(Sema &SemaRef, MutableArrayRef<ResultCandidate> Candidates, |
6133 | unsigned CurrentArg, SourceLocation OpenParLoc, |
6134 | bool Braced) { |
6135 | if (Candidates.empty()) |
6136 | return QualType(); |
6137 | if (SemaRef.getPreprocessor().isCodeCompletionReached()) |
6138 | SemaRef.CodeCompleter->ProcessOverloadCandidates( |
6139 | S&: SemaRef, CurrentArg, Candidates: Candidates.data(), NumCandidates: Candidates.size(), OpenParLoc, |
6140 | Braced); |
6141 | return getParamType(SemaRef, Candidates, N: CurrentArg); |
6142 | } |
6143 | |
6144 | // Given a callee expression `Fn`, if the call is through a function pointer, |
6145 | // try to find the declaration of the corresponding function pointer type, |
6146 | // so that we can recover argument names from it. |
6147 | static FunctionProtoTypeLoc GetPrototypeLoc(Expr *Fn) { |
6148 | TypeLoc Target; |
6149 | |
6150 | if (const auto *T = Fn->getType().getTypePtr()->getAs<TypedefType>()) { |
6151 | Target = T->getDecl()->getTypeSourceInfo()->getTypeLoc(); |
6152 | |
6153 | } else if (const auto *DR = dyn_cast<DeclRefExpr>(Val: Fn)) { |
6154 | const auto *D = DR->getDecl(); |
6155 | if (const auto *const VD = dyn_cast<VarDecl>(Val: D)) { |
6156 | Target = VD->getTypeSourceInfo()->getTypeLoc(); |
6157 | } |
6158 | } else if (const auto *ME = dyn_cast<MemberExpr>(Val: Fn)) { |
6159 | const auto *MD = ME->getMemberDecl(); |
6160 | if (const auto *FD = dyn_cast<FieldDecl>(Val: MD)) { |
6161 | Target = FD->getTypeSourceInfo()->getTypeLoc(); |
6162 | } |
6163 | } |
6164 | |
6165 | if (!Target) |
6166 | return {}; |
6167 | |
6168 | // Unwrap types that may be wrapping the function type |
6169 | while (true) { |
6170 | if (auto P = Target.getAs<PointerTypeLoc>()) { |
6171 | Target = P.getPointeeLoc(); |
6172 | continue; |
6173 | } |
6174 | if (auto A = Target.getAs<AttributedTypeLoc>()) { |
6175 | Target = A.getModifiedLoc(); |
6176 | continue; |
6177 | } |
6178 | if (auto P = Target.getAs<ParenTypeLoc>()) { |
6179 | Target = P.getInnerLoc(); |
6180 | continue; |
6181 | } |
6182 | break; |
6183 | } |
6184 | |
6185 | if (auto F = Target.getAs<FunctionProtoTypeLoc>()) { |
6186 | return F; |
6187 | } |
6188 | |
6189 | return {}; |
6190 | } |
6191 | |
6192 | QualType Sema::ProduceCallSignatureHelp(Expr *Fn, ArrayRef<Expr *> Args, |
6193 | SourceLocation OpenParLoc) { |
6194 | Fn = unwrapParenList(Base: Fn); |
6195 | if (!CodeCompleter || !Fn) |
6196 | return QualType(); |
6197 | |
6198 | // FIXME: Provide support for variadic template functions. |
6199 | // Ignore type-dependent call expressions entirely. |
6200 | if (Fn->isTypeDependent() || anyNullArguments(Args)) |
6201 | return QualType(); |
6202 | // In presence of dependent args we surface all possible signatures using the |
6203 | // non-dependent args in the prefix. Afterwards we do a post filtering to make |
6204 | // sure provided candidates satisfy parameter count restrictions. |
6205 | auto ArgsWithoutDependentTypes = |
6206 | Args.take_while(Pred: [](Expr *Arg) { return !Arg->isTypeDependent(); }); |
6207 | |
6208 | SmallVector<ResultCandidate, 8> Results; |
6209 | |
6210 | Expr *NakedFn = Fn->IgnoreParenCasts(); |
6211 | // Build an overload candidate set based on the functions we find. |
6212 | SourceLocation Loc = Fn->getExprLoc(); |
6213 | OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); |
6214 | |
6215 | if (auto ULE = dyn_cast<UnresolvedLookupExpr>(Val: NakedFn)) { |
6216 | AddOverloadedCallCandidates(ULE, Args: ArgsWithoutDependentTypes, CandidateSet, |
6217 | /*PartialOverloading=*/true); |
6218 | } else if (auto UME = dyn_cast<UnresolvedMemberExpr>(Val: NakedFn)) { |
6219 | TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; |
6220 | if (UME->hasExplicitTemplateArgs()) { |
6221 | UME->copyTemplateArgumentsInto(TemplateArgsBuffer); |
6222 | TemplateArgs = &TemplateArgsBuffer; |
6223 | } |
6224 | |
6225 | // Add the base as first argument (use a nullptr if the base is implicit). |
6226 | SmallVector<Expr *, 12> ArgExprs( |
6227 | 1, UME->isImplicitAccess() ? nullptr : UME->getBase()); |
6228 | ArgExprs.append(in_start: ArgsWithoutDependentTypes.begin(), |
6229 | in_end: ArgsWithoutDependentTypes.end()); |
6230 | UnresolvedSet<8> Decls; |
6231 | Decls.append(I: UME->decls_begin(), E: UME->decls_end()); |
6232 | const bool FirstArgumentIsBase = !UME->isImplicitAccess() && UME->getBase(); |
6233 | AddFunctionCandidates(Functions: Decls, Args: ArgExprs, CandidateSet, ExplicitTemplateArgs: TemplateArgs, |
6234 | /*SuppressUserConversions=*/false, |
6235 | /*PartialOverloading=*/true, FirstArgumentIsBase); |
6236 | } else { |
6237 | FunctionDecl *FD = nullptr; |
6238 | if (auto *MCE = dyn_cast<MemberExpr>(Val: NakedFn)) |
6239 | FD = dyn_cast<FunctionDecl>(Val: MCE->getMemberDecl()); |
6240 | else if (auto *DRE = dyn_cast<DeclRefExpr>(Val: NakedFn)) |
6241 | FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl()); |
6242 | if (FD) { // We check whether it's a resolved function declaration. |
6243 | if (!getLangOpts().CPlusPlus || |
6244 | !FD->getType()->getAs<FunctionProtoType>()) |
6245 | Results.push_back(Elt: ResultCandidate(FD)); |
6246 | else |
6247 | AddOverloadCandidate(Function: FD, FoundDecl: DeclAccessPair::make(D: FD, AS: FD->getAccess()), |
6248 | Args: ArgsWithoutDependentTypes, CandidateSet, |
6249 | /*SuppressUserConversions=*/false, |
6250 | /*PartialOverloading=*/true); |
6251 | |
6252 | } else if (auto DC = NakedFn->getType()->getAsCXXRecordDecl()) { |
6253 | // If expression's type is CXXRecordDecl, it may overload the function |
6254 | // call operator, so we check if it does and add them as candidates. |
6255 | // A complete type is needed to lookup for member function call operators. |
6256 | if (isCompleteType(Loc, T: NakedFn->getType())) { |
6257 | DeclarationName OpName = |
6258 | Context.DeclarationNames.getCXXOperatorName(Op: OO_Call); |
6259 | LookupResult R(*this, OpName, Loc, LookupOrdinaryName); |
6260 | LookupQualifiedName(R, DC); |
6261 | R.suppressDiagnostics(); |
6262 | SmallVector<Expr *, 12> ArgExprs(1, NakedFn); |
6263 | ArgExprs.append(in_start: ArgsWithoutDependentTypes.begin(), |
6264 | in_end: ArgsWithoutDependentTypes.end()); |
6265 | AddFunctionCandidates(Functions: R.asUnresolvedSet(), Args: ArgExprs, CandidateSet, |
6266 | /*ExplicitArgs=*/ExplicitTemplateArgs: nullptr, |
6267 | /*SuppressUserConversions=*/false, |
6268 | /*PartialOverloading=*/true); |
6269 | } |
6270 | } else { |
6271 | // Lastly we check whether expression's type is function pointer or |
6272 | // function. |
6273 | |
6274 | FunctionProtoTypeLoc P = GetPrototypeLoc(Fn: NakedFn); |
6275 | QualType T = NakedFn->getType(); |
6276 | if (!T->getPointeeType().isNull()) |
6277 | T = T->getPointeeType(); |
6278 | |
6279 | if (auto FP = T->getAs<FunctionProtoType>()) { |
6280 | if (!TooManyArguments(NumParams: FP->getNumParams(), |
6281 | NumArgs: ArgsWithoutDependentTypes.size(), |
6282 | /*PartialOverloading=*/true) || |
6283 | FP->isVariadic()) { |
6284 | if (P) { |
6285 | Results.push_back(Elt: ResultCandidate(P)); |
6286 | } else { |
6287 | Results.push_back(Elt: ResultCandidate(FP)); |
6288 | } |
6289 | } |
6290 | } else if (auto FT = T->getAs<FunctionType>()) |
6291 | // No prototype and declaration, it may be a K & R style function. |
6292 | Results.push_back(Elt: ResultCandidate(FT)); |
6293 | } |
6294 | } |
6295 | mergeCandidatesWithResults(SemaRef&: *this, Results, CandidateSet, Loc, ArgSize: Args.size()); |
6296 | QualType ParamType = ProduceSignatureHelp(SemaRef&: *this, Candidates: Results, CurrentArg: Args.size(), |
6297 | OpenParLoc, /*Braced=*/false); |
6298 | return !CandidateSet.empty() ? ParamType : QualType(); |
6299 | } |
6300 | |
6301 | // Determine which param to continue aggregate initialization from after |
6302 | // a designated initializer. |
6303 | // |
6304 | // Given struct S { int a,b,c,d,e; }: |
6305 | // after `S{.b=1,` we want to suggest c to continue |
6306 | // after `S{.b=1, 2,` we continue with d (this is legal C and ext in C++) |
6307 | // after `S{.b=1, .a=2,` we continue with b (this is legal C and ext in C++) |
6308 | // |
6309 | // Possible outcomes: |
6310 | // - we saw a designator for a field, and continue from the returned index. |
6311 | // Only aggregate initialization is allowed. |
6312 | // - we saw a designator, but it was complex or we couldn't find the field. |
6313 | // Only aggregate initialization is possible, but we can't assist with it. |
6314 | // Returns an out-of-range index. |
6315 | // - we saw no designators, just positional arguments. |
6316 | // Returns std::nullopt. |
6317 | static std::optional<unsigned> |
6318 | getNextAggregateIndexAfterDesignatedInit(const ResultCandidate &Aggregate, |
6319 | ArrayRef<Expr *> Args) { |
6320 | static constexpr unsigned Invalid = std::numeric_limits<unsigned>::max(); |
6321 | assert(Aggregate.getKind() == ResultCandidate::CK_Aggregate); |
6322 | |
6323 | // Look for designated initializers. |
6324 | // They're in their syntactic form, not yet resolved to fields. |
6325 | const IdentifierInfo *DesignatedFieldName = nullptr; |
6326 | unsigned ArgsAfterDesignator = 0; |
6327 | for (const Expr *Arg : Args) { |
6328 | if (const auto *DIE = dyn_cast<DesignatedInitExpr>(Val: Arg)) { |
6329 | if (DIE->size() == 1 && DIE->getDesignator(Idx: 0)->isFieldDesignator()) { |
6330 | DesignatedFieldName = DIE->getDesignator(Idx: 0)->getFieldName(); |
6331 | ArgsAfterDesignator = 0; |
6332 | } else { |
6333 | return Invalid; // Complicated designator. |
6334 | } |
6335 | } else if (isa<DesignatedInitUpdateExpr>(Val: Arg)) { |
6336 | return Invalid; // Unsupported. |
6337 | } else { |
6338 | ++ArgsAfterDesignator; |
6339 | } |
6340 | } |
6341 | if (!DesignatedFieldName) |
6342 | return std::nullopt; |
6343 | |
6344 | // Find the index within the class's fields. |
6345 | // (Probing getParamDecl() directly would be quadratic in number of fields). |
6346 | unsigned DesignatedIndex = 0; |
6347 | const FieldDecl *DesignatedField = nullptr; |
6348 | for (const auto *Field : Aggregate.getAggregate()->fields()) { |
6349 | if (Field->getIdentifier() == DesignatedFieldName) { |
6350 | DesignatedField = Field; |
6351 | break; |
6352 | } |
6353 | ++DesignatedIndex; |
6354 | } |
6355 | if (!DesignatedField) |
6356 | return Invalid; // Designator referred to a missing field, give up. |
6357 | |
6358 | // Find the index within the aggregate (which may have leading bases). |
6359 | unsigned AggregateSize = Aggregate.getNumParams(); |
6360 | while (DesignatedIndex < AggregateSize && |
6361 | Aggregate.getParamDecl(N: DesignatedIndex) != DesignatedField) |
6362 | ++DesignatedIndex; |
6363 | |
6364 | // Continue from the index after the last named field. |
6365 | return DesignatedIndex + ArgsAfterDesignator + 1; |
6366 | } |
6367 | |
6368 | QualType Sema::ProduceConstructorSignatureHelp(QualType Type, |
6369 | SourceLocation Loc, |
6370 | ArrayRef<Expr *> Args, |
6371 | SourceLocation OpenParLoc, |
6372 | bool Braced) { |
6373 | if (!CodeCompleter) |
6374 | return QualType(); |
6375 | SmallVector<ResultCandidate, 8> Results; |
6376 | |
6377 | // A complete type is needed to lookup for constructors. |
6378 | RecordDecl *RD = |
6379 | isCompleteType(Loc, T: Type) ? Type->getAsRecordDecl() : nullptr; |
6380 | if (!RD) |
6381 | return Type; |
6382 | CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(Val: RD); |
6383 | |
6384 | // Consider aggregate initialization. |
6385 | // We don't check that types so far are correct. |
6386 | // We also don't handle C99/C++17 brace-elision, we assume init-list elements |
6387 | // are 1:1 with fields. |
6388 | // FIXME: it would be nice to support "unwrapping" aggregates that contain |
6389 | // a single subaggregate, like std::array<T, N> -> T __elements[N]. |
6390 | if (Braced && !RD->isUnion() && |
6391 | (!LangOpts.CPlusPlus || (CRD && CRD->isAggregate()))) { |
6392 | ResultCandidate AggregateSig(RD); |
6393 | unsigned AggregateSize = AggregateSig.getNumParams(); |
6394 | |
6395 | if (auto NextIndex = |
6396 | getNextAggregateIndexAfterDesignatedInit(Aggregate: AggregateSig, Args)) { |
6397 | // A designator was used, only aggregate init is possible. |
6398 | if (*NextIndex >= AggregateSize) |
6399 | return Type; |
6400 | Results.push_back(Elt: AggregateSig); |
6401 | return ProduceSignatureHelp(SemaRef&: *this, Candidates: Results, CurrentArg: *NextIndex, OpenParLoc, |
6402 | Braced); |
6403 | } |
6404 | |
6405 | // Describe aggregate initialization, but also constructors below. |
6406 | if (Args.size() < AggregateSize) |
6407 | Results.push_back(Elt: AggregateSig); |
6408 | } |
6409 | |
6410 | // FIXME: Provide support for member initializers. |
6411 | // FIXME: Provide support for variadic template constructors. |
6412 | |
6413 | if (CRD) { |
6414 | OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); |
6415 | for (NamedDecl *C : LookupConstructors(Class: CRD)) { |
6416 | if (auto *FD = dyn_cast<FunctionDecl>(Val: C)) { |
6417 | // FIXME: we can't yet provide correct signature help for initializer |
6418 | // list constructors, so skip them entirely. |
6419 | if (Braced && LangOpts.CPlusPlus && isInitListConstructor(Ctor: FD)) |
6420 | continue; |
6421 | AddOverloadCandidate(Function: FD, FoundDecl: DeclAccessPair::make(D: FD, AS: C->getAccess()), Args, |
6422 | CandidateSet, |
6423 | /*SuppressUserConversions=*/false, |
6424 | /*PartialOverloading=*/true, |
6425 | /*AllowExplicit*/ true); |
6426 | } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: C)) { |
6427 | if (Braced && LangOpts.CPlusPlus && |
6428 | isInitListConstructor(Ctor: FTD->getTemplatedDecl())) |
6429 | continue; |
6430 | |
6431 | AddTemplateOverloadCandidate( |
6432 | FunctionTemplate: FTD, FoundDecl: DeclAccessPair::make(D: FTD, AS: C->getAccess()), |
6433 | /*ExplicitTemplateArgs=*/nullptr, Args, CandidateSet, |
6434 | /*SuppressUserConversions=*/false, |
6435 | /*PartialOverloading=*/true); |
6436 | } |
6437 | } |
6438 | mergeCandidatesWithResults(SemaRef&: *this, Results, CandidateSet, Loc, ArgSize: Args.size()); |
6439 | } |
6440 | |
6441 | return ProduceSignatureHelp(SemaRef&: *this, Candidates: Results, CurrentArg: Args.size(), OpenParLoc, Braced); |
6442 | } |
6443 | |
6444 | QualType Sema::ProduceCtorInitMemberSignatureHelp( |
6445 | Decl *ConstructorDecl, CXXScopeSpec SS, ParsedType TemplateTypeTy, |
6446 | ArrayRef<Expr *> ArgExprs, IdentifierInfo *II, SourceLocation OpenParLoc, |
6447 | bool Braced) { |
6448 | if (!CodeCompleter) |
6449 | return QualType(); |
6450 | |
6451 | CXXConstructorDecl *Constructor = |
6452 | dyn_cast<CXXConstructorDecl>(Val: ConstructorDecl); |
6453 | if (!Constructor) |
6454 | return QualType(); |
6455 | // FIXME: Add support for Base class constructors as well. |
6456 | if (ValueDecl *MemberDecl = tryLookupCtorInitMemberDecl( |
6457 | ClassDecl: Constructor->getParent(), SS, TemplateTypeTy, MemberOrBase: II)) |
6458 | return ProduceConstructorSignatureHelp(Type: MemberDecl->getType(), |
6459 | Loc: MemberDecl->getLocation(), Args: ArgExprs, |
6460 | OpenParLoc, Braced); |
6461 | return QualType(); |
6462 | } |
6463 | |
6464 | static bool argMatchesTemplateParams(const ParsedTemplateArgument &Arg, |
6465 | unsigned Index, |
6466 | const TemplateParameterList &Params) { |
6467 | const NamedDecl *Param; |
6468 | if (Index < Params.size()) |
6469 | Param = Params.getParam(Idx: Index); |
6470 | else if (Params.hasParameterPack()) |
6471 | Param = Params.asArray().back(); |
6472 | else |
6473 | return false; // too many args |
6474 | |
6475 | switch (Arg.getKind()) { |
6476 | case ParsedTemplateArgument::Type: |
6477 | return llvm::isa<TemplateTypeParmDecl>(Val: Param); // constraints not checked |
6478 | case ParsedTemplateArgument::NonType: |
6479 | return llvm::isa<NonTypeTemplateParmDecl>(Val: Param); // type not checked |
6480 | case ParsedTemplateArgument::Template: |
6481 | return llvm::isa<TemplateTemplateParmDecl>(Val: Param); // signature not checked |
6482 | } |
6483 | llvm_unreachable("Unhandled switch case" ); |
6484 | } |
6485 | |
6486 | QualType Sema::ProduceTemplateArgumentSignatureHelp( |
6487 | TemplateTy ParsedTemplate, ArrayRef<ParsedTemplateArgument> Args, |
6488 | SourceLocation LAngleLoc) { |
6489 | if (!CodeCompleter || !ParsedTemplate) |
6490 | return QualType(); |
6491 | |
6492 | SmallVector<ResultCandidate, 8> Results; |
6493 | auto Consider = [&](const TemplateDecl *TD) { |
6494 | // Only add if the existing args are compatible with the template. |
6495 | bool Matches = true; |
6496 | for (unsigned I = 0; I < Args.size(); ++I) { |
6497 | if (!argMatchesTemplateParams(Arg: Args[I], Index: I, Params: *TD->getTemplateParameters())) { |
6498 | Matches = false; |
6499 | break; |
6500 | } |
6501 | } |
6502 | if (Matches) |
6503 | Results.emplace_back(Args&: TD); |
6504 | }; |
6505 | |
6506 | TemplateName Template = ParsedTemplate.get(); |
6507 | if (const auto *TD = Template.getAsTemplateDecl()) { |
6508 | Consider(TD); |
6509 | } else if (const auto *OTS = Template.getAsOverloadedTemplate()) { |
6510 | for (const NamedDecl *ND : *OTS) |
6511 | if (const auto *TD = llvm::dyn_cast<TemplateDecl>(Val: ND)) |
6512 | Consider(TD); |
6513 | } |
6514 | return ProduceSignatureHelp(SemaRef&: *this, Candidates: Results, CurrentArg: Args.size(), OpenParLoc: LAngleLoc, |
6515 | /*Braced=*/false); |
6516 | } |
6517 | |
6518 | static QualType getDesignatedType(QualType BaseType, const Designation &Desig) { |
6519 | for (unsigned I = 0; I < Desig.getNumDesignators(); ++I) { |
6520 | if (BaseType.isNull()) |
6521 | break; |
6522 | QualType NextType; |
6523 | const auto &D = Desig.getDesignator(Idx: I); |
6524 | if (D.isArrayDesignator() || D.isArrayRangeDesignator()) { |
6525 | if (BaseType->isArrayType()) |
6526 | NextType = BaseType->getAsArrayTypeUnsafe()->getElementType(); |
6527 | } else { |
6528 | assert(D.isFieldDesignator()); |
6529 | auto *RD = getAsRecordDecl(BaseType); |
6530 | if (RD && RD->isCompleteDefinition()) { |
6531 | for (const auto *Member : RD->lookup(D.getFieldDecl())) |
6532 | if (const FieldDecl *FD = llvm::dyn_cast<FieldDecl>(Member)) { |
6533 | NextType = FD->getType(); |
6534 | break; |
6535 | } |
6536 | } |
6537 | } |
6538 | BaseType = NextType; |
6539 | } |
6540 | return BaseType; |
6541 | } |
6542 | |
6543 | void Sema::CodeCompleteDesignator(QualType BaseType, |
6544 | llvm::ArrayRef<Expr *> InitExprs, |
6545 | const Designation &D) { |
6546 | BaseType = getDesignatedType(BaseType, Desig: D); |
6547 | if (BaseType.isNull()) |
6548 | return; |
6549 | const auto *RD = getAsRecordDecl(BaseType); |
6550 | if (!RD || RD->fields().empty()) |
6551 | return; |
6552 | |
6553 | CodeCompletionContext CCC(CodeCompletionContext::CCC_DotMemberAccess, |
6554 | BaseType); |
6555 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
6556 | CodeCompleter->getCodeCompletionTUInfo(), CCC); |
6557 | |
6558 | Results.EnterNewScope(); |
6559 | for (const Decl *D : RD->decls()) { |
6560 | const FieldDecl *FD; |
6561 | if (auto *IFD = dyn_cast<IndirectFieldDecl>(D)) |
6562 | FD = IFD->getAnonField(); |
6563 | else if (auto *DFD = dyn_cast<FieldDecl>(D)) |
6564 | FD = DFD; |
6565 | else |
6566 | continue; |
6567 | |
6568 | // FIXME: Make use of previous designators to mark any fields before those |
6569 | // inaccessible, and also compute the next initializer priority. |
6570 | ResultBuilder::Result Result(FD, Results.getBasePriority(FD)); |
6571 | Results.AddResult(Result, CurContext, /*Hiding=*/nullptr); |
6572 | } |
6573 | Results.ExitScope(); |
6574 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
6575 | Results: Results.data(), NumResults: Results.size()); |
6576 | } |
6577 | |
6578 | void Sema::CodeCompleteInitializer(Scope *S, Decl *D) { |
6579 | ValueDecl *VD = dyn_cast_or_null<ValueDecl>(Val: D); |
6580 | if (!VD) { |
6581 | CodeCompleteOrdinaryName(S, CompletionContext: PCC_Expression); |
6582 | return; |
6583 | } |
6584 | |
6585 | CodeCompleteExpressionData Data; |
6586 | Data.PreferredType = VD->getType(); |
6587 | // Ignore VD to avoid completing the variable itself, e.g. in 'int foo = ^'. |
6588 | Data.IgnoreDecls.push_back(VD); |
6589 | |
6590 | CodeCompleteExpression(S, Data); |
6591 | } |
6592 | |
6593 | void Sema::CodeCompleteAfterIf(Scope *S, bool IsBracedThen) { |
6594 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
6595 | CodeCompleter->getCodeCompletionTUInfo(), |
6596 | mapCodeCompletionContext(S&: *this, PCC: PCC_Statement)); |
6597 | Results.setFilter(&ResultBuilder::IsOrdinaryName); |
6598 | Results.EnterNewScope(); |
6599 | |
6600 | CodeCompletionDeclConsumer Consumer(Results, CurContext); |
6601 | LookupVisibleDecls(S, LookupOrdinaryName, Consumer, |
6602 | CodeCompleter->includeGlobals(), |
6603 | CodeCompleter->loadExternal()); |
6604 | |
6605 | AddOrdinaryNameResults(CCC: PCC_Statement, S, SemaRef&: *this, Results); |
6606 | |
6607 | // "else" block |
6608 | CodeCompletionBuilder Builder(Results.getAllocator(), |
6609 | Results.getCodeCompletionTUInfo()); |
6610 | |
6611 | auto AddElseBodyPattern = [&] { |
6612 | if (IsBracedThen) { |
6613 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
6614 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftBrace); |
6615 | Builder.AddChunk(CK: CodeCompletionString::CK_VerticalSpace); |
6616 | Builder.AddPlaceholderChunk(Placeholder: "statements" ); |
6617 | Builder.AddChunk(CK: CodeCompletionString::CK_VerticalSpace); |
6618 | Builder.AddChunk(CK: CodeCompletionString::CK_RightBrace); |
6619 | } else { |
6620 | Builder.AddChunk(CK: CodeCompletionString::CK_VerticalSpace); |
6621 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
6622 | Builder.AddPlaceholderChunk(Placeholder: "statement" ); |
6623 | Builder.AddChunk(CK: CodeCompletionString::CK_SemiColon); |
6624 | } |
6625 | }; |
6626 | Builder.AddTypedTextChunk(Text: "else" ); |
6627 | if (Results.includeCodePatterns()) |
6628 | AddElseBodyPattern(); |
6629 | Results.AddResult(R: Builder.TakeString()); |
6630 | |
6631 | // "else if" block |
6632 | Builder.AddTypedTextChunk(Text: "else if" ); |
6633 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
6634 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
6635 | if (getLangOpts().CPlusPlus) |
6636 | Builder.AddPlaceholderChunk(Placeholder: "condition" ); |
6637 | else |
6638 | Builder.AddPlaceholderChunk(Placeholder: "expression" ); |
6639 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
6640 | if (Results.includeCodePatterns()) { |
6641 | AddElseBodyPattern(); |
6642 | } |
6643 | Results.AddResult(R: Builder.TakeString()); |
6644 | |
6645 | Results.ExitScope(); |
6646 | |
6647 | if (S->getFnParent()) |
6648 | AddPrettyFunctionResults(LangOpts: getLangOpts(), Results); |
6649 | |
6650 | if (CodeCompleter->includeMacros()) |
6651 | AddMacroResults(PP, Results, LoadExternal: CodeCompleter->loadExternal(), IncludeUndefined: false); |
6652 | |
6653 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
6654 | Results: Results.data(), NumResults: Results.size()); |
6655 | } |
6656 | |
6657 | void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, |
6658 | bool EnteringContext, |
6659 | bool IsUsingDeclaration, QualType BaseType, |
6660 | QualType PreferredType) { |
6661 | if (SS.isEmpty() || !CodeCompleter) |
6662 | return; |
6663 | |
6664 | CodeCompletionContext CC(CodeCompletionContext::CCC_Symbol, PreferredType); |
6665 | CC.setIsUsingDeclaration(IsUsingDeclaration); |
6666 | CC.setCXXScopeSpecifier(SS); |
6667 | |
6668 | // We want to keep the scope specifier even if it's invalid (e.g. the scope |
6669 | // "a::b::" is not corresponding to any context/namespace in the AST), since |
6670 | // it can be useful for global code completion which have information about |
6671 | // contexts/symbols that are not in the AST. |
6672 | if (SS.isInvalid()) { |
6673 | // As SS is invalid, we try to collect accessible contexts from the current |
6674 | // scope with a dummy lookup so that the completion consumer can try to |
6675 | // guess what the specified scope is. |
6676 | ResultBuilder DummyResults(*this, CodeCompleter->getAllocator(), |
6677 | CodeCompleter->getCodeCompletionTUInfo(), CC); |
6678 | if (!PreferredType.isNull()) |
6679 | DummyResults.setPreferredType(PreferredType); |
6680 | if (S->getEntity()) { |
6681 | CodeCompletionDeclConsumer Consumer(DummyResults, S->getEntity(), |
6682 | BaseType); |
6683 | LookupVisibleDecls(S, LookupOrdinaryName, Consumer, |
6684 | /*IncludeGlobalScope=*/false, |
6685 | /*LoadExternal=*/false); |
6686 | } |
6687 | HandleCodeCompleteResults(S: this, CodeCompleter, |
6688 | Context: DummyResults.getCompletionContext(), Results: nullptr, NumResults: 0); |
6689 | return; |
6690 | } |
6691 | // Always pretend to enter a context to ensure that a dependent type |
6692 | // resolves to a dependent record. |
6693 | DeclContext *Ctx = computeDeclContext(SS, /*EnteringContext=*/true); |
6694 | |
6695 | // Try to instantiate any non-dependent declaration contexts before |
6696 | // we look in them. Bail out if we fail. |
6697 | NestedNameSpecifier *NNS = SS.getScopeRep(); |
6698 | if (NNS != nullptr && SS.isValid() && !NNS->isDependent()) { |
6699 | if (Ctx == nullptr || RequireCompleteDeclContext(SS, DC: Ctx)) |
6700 | return; |
6701 | } |
6702 | |
6703 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
6704 | CodeCompleter->getCodeCompletionTUInfo(), CC); |
6705 | if (!PreferredType.isNull()) |
6706 | Results.setPreferredType(PreferredType); |
6707 | Results.EnterNewScope(); |
6708 | |
6709 | // The "template" keyword can follow "::" in the grammar, but only |
6710 | // put it into the grammar if the nested-name-specifier is dependent. |
6711 | // FIXME: results is always empty, this appears to be dead. |
6712 | if (!Results.empty() && NNS && NNS->isDependent()) |
6713 | Results.AddResult(R: "template" ); |
6714 | |
6715 | // If the scope is a concept-constrained type parameter, infer nested |
6716 | // members based on the constraints. |
6717 | if (const auto *TTPT = |
6718 | dyn_cast_or_null<TemplateTypeParmType>(Val: NNS->getAsType())) { |
6719 | for (const auto &R : ConceptInfo(*TTPT, S).members()) { |
6720 | if (R.Operator != ConceptInfo::Member::Colons) |
6721 | continue; |
6722 | Results.AddResult(R: CodeCompletionResult( |
6723 | R.render(S&: *this, Alloc&: CodeCompleter->getAllocator(), |
6724 | Info&: CodeCompleter->getCodeCompletionTUInfo()))); |
6725 | } |
6726 | } |
6727 | |
6728 | // Add calls to overridden virtual functions, if there are any. |
6729 | // |
6730 | // FIXME: This isn't wonderful, because we don't know whether we're actually |
6731 | // in a context that permits expressions. This is a general issue with |
6732 | // qualified-id completions. |
6733 | if (Ctx && !EnteringContext) |
6734 | MaybeAddOverrideCalls(S&: *this, InContext: Ctx, Results); |
6735 | Results.ExitScope(); |
6736 | |
6737 | if (Ctx && |
6738 | (CodeCompleter->includeNamespaceLevelDecls() || !Ctx->isFileContext())) { |
6739 | CodeCompletionDeclConsumer Consumer(Results, Ctx, BaseType); |
6740 | LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer, |
6741 | /*IncludeGlobalScope=*/true, |
6742 | /*IncludeDependentBases=*/true, |
6743 | CodeCompleter->loadExternal()); |
6744 | } |
6745 | |
6746 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
6747 | Results: Results.data(), NumResults: Results.size()); |
6748 | } |
6749 | |
6750 | void Sema::CodeCompleteUsing(Scope *S) { |
6751 | if (!CodeCompleter) |
6752 | return; |
6753 | |
6754 | // This can be both a using alias or using declaration, in the former we |
6755 | // expect a new name and a symbol in the latter case. |
6756 | CodeCompletionContext Context(CodeCompletionContext::CCC_SymbolOrNewName); |
6757 | Context.setIsUsingDeclaration(true); |
6758 | |
6759 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
6760 | CodeCompleter->getCodeCompletionTUInfo(), Context, |
6761 | &ResultBuilder::IsNestedNameSpecifier); |
6762 | Results.EnterNewScope(); |
6763 | |
6764 | // If we aren't in class scope, we could see the "namespace" keyword. |
6765 | if (!S->isClassScope()) |
6766 | Results.AddResult(R: CodeCompletionResult("namespace" )); |
6767 | |
6768 | // After "using", we can see anything that would start a |
6769 | // nested-name-specifier. |
6770 | CodeCompletionDeclConsumer Consumer(Results, CurContext); |
6771 | LookupVisibleDecls(S, LookupOrdinaryName, Consumer, |
6772 | CodeCompleter->includeGlobals(), |
6773 | CodeCompleter->loadExternal()); |
6774 | Results.ExitScope(); |
6775 | |
6776 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
6777 | Results: Results.data(), NumResults: Results.size()); |
6778 | } |
6779 | |
6780 | void Sema::CodeCompleteUsingDirective(Scope *S) { |
6781 | if (!CodeCompleter) |
6782 | return; |
6783 | |
6784 | // After "using namespace", we expect to see a namespace name or namespace |
6785 | // alias. |
6786 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
6787 | CodeCompleter->getCodeCompletionTUInfo(), |
6788 | CodeCompletionContext::CCC_Namespace, |
6789 | &ResultBuilder::IsNamespaceOrAlias); |
6790 | Results.EnterNewScope(); |
6791 | CodeCompletionDeclConsumer Consumer(Results, CurContext); |
6792 | LookupVisibleDecls(S, LookupOrdinaryName, Consumer, |
6793 | CodeCompleter->includeGlobals(), |
6794 | CodeCompleter->loadExternal()); |
6795 | Results.ExitScope(); |
6796 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
6797 | Results: Results.data(), NumResults: Results.size()); |
6798 | } |
6799 | |
6800 | void Sema::CodeCompleteNamespaceDecl(Scope *S) { |
6801 | if (!CodeCompleter) |
6802 | return; |
6803 | |
6804 | DeclContext *Ctx = S->getEntity(); |
6805 | if (!S->getParent()) |
6806 | Ctx = Context.getTranslationUnitDecl(); |
6807 | |
6808 | bool SuppressedGlobalResults = |
6809 | Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Val: Ctx); |
6810 | |
6811 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
6812 | CodeCompleter->getCodeCompletionTUInfo(), |
6813 | SuppressedGlobalResults |
6814 | ? CodeCompletionContext::CCC_Namespace |
6815 | : CodeCompletionContext::CCC_Other, |
6816 | &ResultBuilder::IsNamespace); |
6817 | |
6818 | if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) { |
6819 | // We only want to see those namespaces that have already been defined |
6820 | // within this scope, because its likely that the user is creating an |
6821 | // extended namespace declaration. Keep track of the most recent |
6822 | // definition of each namespace. |
6823 | std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest; |
6824 | for (DeclContext::specific_decl_iterator<NamespaceDecl> |
6825 | NS(Ctx->decls_begin()), |
6826 | NSEnd(Ctx->decls_end()); |
6827 | NS != NSEnd; ++NS) |
6828 | OrigToLatest[NS->getOriginalNamespace()] = *NS; |
6829 | |
6830 | // Add the most recent definition (or extended definition) of each |
6831 | // namespace to the list of results. |
6832 | Results.EnterNewScope(); |
6833 | for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator |
6834 | NS = OrigToLatest.begin(), |
6835 | NSEnd = OrigToLatest.end(); |
6836 | NS != NSEnd; ++NS) |
6837 | Results.AddResult( |
6838 | R: CodeCompletionResult(NS->second, Results.getBasePriority(NS->second), |
6839 | nullptr), |
6840 | CurContext, Hiding: nullptr, InBaseClass: false); |
6841 | Results.ExitScope(); |
6842 | } |
6843 | |
6844 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
6845 | Results: Results.data(), NumResults: Results.size()); |
6846 | } |
6847 | |
6848 | void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) { |
6849 | if (!CodeCompleter) |
6850 | return; |
6851 | |
6852 | // After "namespace", we expect to see a namespace or alias. |
6853 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
6854 | CodeCompleter->getCodeCompletionTUInfo(), |
6855 | CodeCompletionContext::CCC_Namespace, |
6856 | &ResultBuilder::IsNamespaceOrAlias); |
6857 | CodeCompletionDeclConsumer Consumer(Results, CurContext); |
6858 | LookupVisibleDecls(S, LookupOrdinaryName, Consumer, |
6859 | CodeCompleter->includeGlobals(), |
6860 | CodeCompleter->loadExternal()); |
6861 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
6862 | Results: Results.data(), NumResults: Results.size()); |
6863 | } |
6864 | |
6865 | void Sema::CodeCompleteOperatorName(Scope *S) { |
6866 | if (!CodeCompleter) |
6867 | return; |
6868 | |
6869 | typedef CodeCompletionResult Result; |
6870 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
6871 | CodeCompleter->getCodeCompletionTUInfo(), |
6872 | CodeCompletionContext::CCC_Type, |
6873 | &ResultBuilder::IsType); |
6874 | Results.EnterNewScope(); |
6875 | |
6876 | // Add the names of overloadable operators. Note that OO_Conditional is not |
6877 | // actually overloadable. |
6878 | #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \ |
6879 | if (OO_##Name != OO_Conditional) \ |
6880 | Results.AddResult(Result(Spelling)); |
6881 | #include "clang/Basic/OperatorKinds.def" |
6882 | |
6883 | // Add any type names visible from the current scope |
6884 | Results.allowNestedNameSpecifiers(); |
6885 | CodeCompletionDeclConsumer Consumer(Results, CurContext); |
6886 | LookupVisibleDecls(S, LookupOrdinaryName, Consumer, |
6887 | CodeCompleter->includeGlobals(), |
6888 | CodeCompleter->loadExternal()); |
6889 | |
6890 | // Add any type specifiers |
6891 | AddTypeSpecifierResults(LangOpts: getLangOpts(), Results); |
6892 | Results.ExitScope(); |
6893 | |
6894 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
6895 | Results: Results.data(), NumResults: Results.size()); |
6896 | } |
6897 | |
6898 | void Sema::CodeCompleteConstructorInitializer( |
6899 | Decl *ConstructorD, ArrayRef<CXXCtorInitializer *> Initializers) { |
6900 | if (!ConstructorD) |
6901 | return; |
6902 | |
6903 | AdjustDeclIfTemplate(Decl&: ConstructorD); |
6904 | |
6905 | auto *Constructor = dyn_cast<CXXConstructorDecl>(Val: ConstructorD); |
6906 | if (!Constructor) |
6907 | return; |
6908 | |
6909 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
6910 | CodeCompleter->getCodeCompletionTUInfo(), |
6911 | CodeCompletionContext::CCC_Symbol); |
6912 | Results.EnterNewScope(); |
6913 | |
6914 | // Fill in any already-initialized fields or base classes. |
6915 | llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields; |
6916 | llvm::SmallPtrSet<CanQualType, 4> InitializedBases; |
6917 | for (unsigned I = 0, E = Initializers.size(); I != E; ++I) { |
6918 | if (Initializers[I]->isBaseInitializer()) |
6919 | InitializedBases.insert(Ptr: Context.getCanonicalType( |
6920 | T: QualType(Initializers[I]->getBaseClass(), 0))); |
6921 | else |
6922 | InitializedFields.insert( |
6923 | Ptr: cast<FieldDecl>(Val: Initializers[I]->getAnyMember())); |
6924 | } |
6925 | |
6926 | // Add completions for base classes. |
6927 | PrintingPolicy Policy = getCompletionPrintingPolicy(S&: *this); |
6928 | bool SawLastInitializer = Initializers.empty(); |
6929 | CXXRecordDecl *ClassDecl = Constructor->getParent(); |
6930 | |
6931 | auto GenerateCCS = [&](const NamedDecl *ND, const char *Name) { |
6932 | CodeCompletionBuilder Builder(Results.getAllocator(), |
6933 | Results.getCodeCompletionTUInfo()); |
6934 | Builder.AddTypedTextChunk(Text: Name); |
6935 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
6936 | if (const auto *Function = dyn_cast<FunctionDecl>(Val: ND)) |
6937 | AddFunctionParameterChunks(PP, Policy, Function, Result&: Builder); |
6938 | else if (const auto *FunTemplDecl = dyn_cast<FunctionTemplateDecl>(Val: ND)) |
6939 | AddFunctionParameterChunks(PP, Policy, Function: FunTemplDecl->getTemplatedDecl(), |
6940 | Result&: Builder); |
6941 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
6942 | return Builder.TakeString(); |
6943 | }; |
6944 | auto AddDefaultCtorInit = [&](const char *Name, const char *Type, |
6945 | const NamedDecl *ND) { |
6946 | CodeCompletionBuilder Builder(Results.getAllocator(), |
6947 | Results.getCodeCompletionTUInfo()); |
6948 | Builder.AddTypedTextChunk(Text: Name); |
6949 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
6950 | Builder.AddPlaceholderChunk(Placeholder: Type); |
6951 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
6952 | if (ND) { |
6953 | auto CCR = CodeCompletionResult( |
6954 | Builder.TakeString(), ND, |
6955 | SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration); |
6956 | if (isa<FieldDecl>(Val: ND)) |
6957 | CCR.CursorKind = CXCursor_MemberRef; |
6958 | return Results.AddResult(R: CCR); |
6959 | } |
6960 | return Results.AddResult(R: CodeCompletionResult( |
6961 | Builder.TakeString(), |
6962 | SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration)); |
6963 | }; |
6964 | auto AddCtorsWithName = [&](const CXXRecordDecl *RD, unsigned int Priority, |
6965 | const char *Name, const FieldDecl *FD) { |
6966 | if (!RD) |
6967 | return AddDefaultCtorInit(Name, |
6968 | FD ? Results.getAllocator().CopyString( |
6969 | FD->getType().getAsString(Policy)) |
6970 | : Name, |
6971 | FD); |
6972 | auto Ctors = getConstructors(Context, Record: RD); |
6973 | if (Ctors.begin() == Ctors.end()) |
6974 | return AddDefaultCtorInit(Name, Name, RD); |
6975 | for (const NamedDecl *Ctor : Ctors) { |
6976 | auto CCR = CodeCompletionResult(GenerateCCS(Ctor, Name), RD, Priority); |
6977 | CCR.CursorKind = getCursorKindForDecl(Ctor); |
6978 | Results.AddResult(CCR); |
6979 | } |
6980 | }; |
6981 | auto AddBase = [&](const CXXBaseSpecifier &Base) { |
6982 | const char *BaseName = |
6983 | Results.getAllocator().CopyString(String: Base.getType().getAsString(Policy)); |
6984 | const auto *RD = Base.getType()->getAsCXXRecordDecl(); |
6985 | AddCtorsWithName( |
6986 | RD, SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration, |
6987 | BaseName, nullptr); |
6988 | }; |
6989 | auto AddField = [&](const FieldDecl *FD) { |
6990 | const char *FieldName = |
6991 | Results.getAllocator().CopyString(String: FD->getIdentifier()->getName()); |
6992 | const CXXRecordDecl *RD = FD->getType()->getAsCXXRecordDecl(); |
6993 | AddCtorsWithName( |
6994 | RD, SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration, |
6995 | FieldName, FD); |
6996 | }; |
6997 | |
6998 | for (const auto &Base : ClassDecl->bases()) { |
6999 | if (!InitializedBases.insert(Context.getCanonicalType(Base.getType())) |
7000 | .second) { |
7001 | SawLastInitializer = |
7002 | !Initializers.empty() && Initializers.back()->isBaseInitializer() && |
7003 | Context.hasSameUnqualifiedType( |
7004 | Base.getType(), QualType(Initializers.back()->getBaseClass(), 0)); |
7005 | continue; |
7006 | } |
7007 | |
7008 | AddBase(Base); |
7009 | SawLastInitializer = false; |
7010 | } |
7011 | |
7012 | // Add completions for virtual base classes. |
7013 | for (const auto &Base : ClassDecl->vbases()) { |
7014 | if (!InitializedBases.insert(Context.getCanonicalType(Base.getType())) |
7015 | .second) { |
7016 | SawLastInitializer = |
7017 | !Initializers.empty() && Initializers.back()->isBaseInitializer() && |
7018 | Context.hasSameUnqualifiedType( |
7019 | Base.getType(), QualType(Initializers.back()->getBaseClass(), 0)); |
7020 | continue; |
7021 | } |
7022 | |
7023 | AddBase(Base); |
7024 | SawLastInitializer = false; |
7025 | } |
7026 | |
7027 | // Add completions for members. |
7028 | for (auto *Field : ClassDecl->fields()) { |
7029 | if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl())) |
7030 | .second) { |
7031 | SawLastInitializer = !Initializers.empty() && |
7032 | Initializers.back()->isAnyMemberInitializer() && |
7033 | Initializers.back()->getAnyMember() == Field; |
7034 | continue; |
7035 | } |
7036 | |
7037 | if (!Field->getDeclName()) |
7038 | continue; |
7039 | |
7040 | AddField(Field); |
7041 | SawLastInitializer = false; |
7042 | } |
7043 | Results.ExitScope(); |
7044 | |
7045 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
7046 | Results: Results.data(), NumResults: Results.size()); |
7047 | } |
7048 | |
7049 | /// Determine whether this scope denotes a namespace. |
7050 | static bool isNamespaceScope(Scope *S) { |
7051 | DeclContext *DC = S->getEntity(); |
7052 | if (!DC) |
7053 | return false; |
7054 | |
7055 | return DC->isFileContext(); |
7056 | } |
7057 | |
7058 | void Sema::CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro, |
7059 | bool AfterAmpersand) { |
7060 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
7061 | CodeCompleter->getCodeCompletionTUInfo(), |
7062 | CodeCompletionContext::CCC_Other); |
7063 | Results.EnterNewScope(); |
7064 | |
7065 | // Note what has already been captured. |
7066 | llvm::SmallPtrSet<IdentifierInfo *, 4> Known; |
7067 | bool IncludedThis = false; |
7068 | for (const auto &C : Intro.Captures) { |
7069 | if (C.Kind == LCK_This) { |
7070 | IncludedThis = true; |
7071 | continue; |
7072 | } |
7073 | |
7074 | Known.insert(Ptr: C.Id); |
7075 | } |
7076 | |
7077 | // Look for other capturable variables. |
7078 | for (; S && !isNamespaceScope(S); S = S->getParent()) { |
7079 | for (const auto *D : S->decls()) { |
7080 | const auto *Var = dyn_cast<VarDecl>(Val: D); |
7081 | if (!Var || !Var->hasLocalStorage() || Var->hasAttr<BlocksAttr>()) |
7082 | continue; |
7083 | |
7084 | if (Known.insert(Var->getIdentifier()).second) |
7085 | Results.AddResult(R: CodeCompletionResult(Var, CCP_LocalDeclaration), |
7086 | CurContext, Hiding: nullptr, InBaseClass: false); |
7087 | } |
7088 | } |
7089 | |
7090 | // Add 'this', if it would be valid. |
7091 | if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy) |
7092 | addThisCompletion(S&: *this, Results); |
7093 | |
7094 | Results.ExitScope(); |
7095 | |
7096 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
7097 | Results: Results.data(), NumResults: Results.size()); |
7098 | } |
7099 | |
7100 | void Sema::CodeCompleteAfterFunctionEquals(Declarator &D) { |
7101 | if (!LangOpts.CPlusPlus11) |
7102 | return; |
7103 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
7104 | CodeCompleter->getCodeCompletionTUInfo(), |
7105 | CodeCompletionContext::CCC_Other); |
7106 | auto ShouldAddDefault = [&D, this]() { |
7107 | if (!D.isFunctionDeclarator()) |
7108 | return false; |
7109 | auto &Id = D.getName(); |
7110 | if (Id.getKind() == UnqualifiedIdKind::IK_DestructorName) |
7111 | return true; |
7112 | // FIXME(liuhui): Ideally, we should check the constructor parameter list to |
7113 | // verify that it is the default, copy or move constructor? |
7114 | if (Id.getKind() == UnqualifiedIdKind::IK_ConstructorName && |
7115 | D.getFunctionTypeInfo().NumParams <= 1) |
7116 | return true; |
7117 | if (Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId) { |
7118 | auto Op = Id.OperatorFunctionId.Operator; |
7119 | // FIXME(liuhui): Ideally, we should check the function parameter list to |
7120 | // verify that it is the copy or move assignment? |
7121 | if (Op == OverloadedOperatorKind::OO_Equal) |
7122 | return true; |
7123 | if (LangOpts.CPlusPlus20 && |
7124 | (Op == OverloadedOperatorKind::OO_EqualEqual || |
7125 | Op == OverloadedOperatorKind::OO_ExclaimEqual || |
7126 | Op == OverloadedOperatorKind::OO_Less || |
7127 | Op == OverloadedOperatorKind::OO_LessEqual || |
7128 | Op == OverloadedOperatorKind::OO_Greater || |
7129 | Op == OverloadedOperatorKind::OO_GreaterEqual || |
7130 | Op == OverloadedOperatorKind::OO_Spaceship)) |
7131 | return true; |
7132 | } |
7133 | return false; |
7134 | }; |
7135 | |
7136 | Results.EnterNewScope(); |
7137 | if (ShouldAddDefault()) |
7138 | Results.AddResult(R: "default" ); |
7139 | // FIXME(liuhui): Ideally, we should only provide `delete` completion for the |
7140 | // first function declaration. |
7141 | Results.AddResult(R: "delete" ); |
7142 | Results.ExitScope(); |
7143 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
7144 | Results: Results.data(), NumResults: Results.size()); |
7145 | } |
7146 | |
7147 | /// Macro that optionally prepends an "@" to the string literal passed in via |
7148 | /// Keyword, depending on whether NeedAt is true or false. |
7149 | #define OBJC_AT_KEYWORD_NAME(NeedAt, Keyword) ((NeedAt) ? "@" Keyword : Keyword) |
7150 | |
7151 | static void AddObjCImplementationResults(const LangOptions &LangOpts, |
7152 | ResultBuilder &Results, bool NeedAt) { |
7153 | typedef CodeCompletionResult Result; |
7154 | // Since we have an implementation, we can end it. |
7155 | Results.AddResult(R: Result(OBJC_AT_KEYWORD_NAME(NeedAt, "end" ))); |
7156 | |
7157 | CodeCompletionBuilder Builder(Results.getAllocator(), |
7158 | Results.getCodeCompletionTUInfo()); |
7159 | if (LangOpts.ObjC) { |
7160 | // @dynamic |
7161 | Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "dynamic" )); |
7162 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
7163 | Builder.AddPlaceholderChunk(Placeholder: "property" ); |
7164 | Results.AddResult(R: Result(Builder.TakeString())); |
7165 | |
7166 | // @synthesize |
7167 | Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "synthesize" )); |
7168 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
7169 | Builder.AddPlaceholderChunk(Placeholder: "property" ); |
7170 | Results.AddResult(R: Result(Builder.TakeString())); |
7171 | } |
7172 | } |
7173 | |
7174 | static void AddObjCInterfaceResults(const LangOptions &LangOpts, |
7175 | ResultBuilder &Results, bool NeedAt) { |
7176 | typedef CodeCompletionResult Result; |
7177 | |
7178 | // Since we have an interface or protocol, we can end it. |
7179 | Results.AddResult(R: Result(OBJC_AT_KEYWORD_NAME(NeedAt, "end" ))); |
7180 | |
7181 | if (LangOpts.ObjC) { |
7182 | // @property |
7183 | Results.AddResult(R: Result(OBJC_AT_KEYWORD_NAME(NeedAt, "property" ))); |
7184 | |
7185 | // @required |
7186 | Results.AddResult(R: Result(OBJC_AT_KEYWORD_NAME(NeedAt, "required" ))); |
7187 | |
7188 | // @optional |
7189 | Results.AddResult(R: Result(OBJC_AT_KEYWORD_NAME(NeedAt, "optional" ))); |
7190 | } |
7191 | } |
7192 | |
7193 | static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) { |
7194 | typedef CodeCompletionResult Result; |
7195 | CodeCompletionBuilder Builder(Results.getAllocator(), |
7196 | Results.getCodeCompletionTUInfo()); |
7197 | |
7198 | // @class name ; |
7199 | Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "class" )); |
7200 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
7201 | Builder.AddPlaceholderChunk(Placeholder: "name" ); |
7202 | Results.AddResult(R: Result(Builder.TakeString())); |
7203 | |
7204 | if (Results.includeCodePatterns()) { |
7205 | // @interface name |
7206 | // FIXME: Could introduce the whole pattern, including superclasses and |
7207 | // such. |
7208 | Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "interface" )); |
7209 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
7210 | Builder.AddPlaceholderChunk(Placeholder: "class" ); |
7211 | Results.AddResult(R: Result(Builder.TakeString())); |
7212 | |
7213 | // @protocol name |
7214 | Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "protocol" )); |
7215 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
7216 | Builder.AddPlaceholderChunk(Placeholder: "protocol" ); |
7217 | Results.AddResult(R: Result(Builder.TakeString())); |
7218 | |
7219 | // @implementation name |
7220 | Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "implementation" )); |
7221 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
7222 | Builder.AddPlaceholderChunk(Placeholder: "class" ); |
7223 | Results.AddResult(R: Result(Builder.TakeString())); |
7224 | } |
7225 | |
7226 | // @compatibility_alias name |
7227 | Builder.AddTypedTextChunk( |
7228 | OBJC_AT_KEYWORD_NAME(NeedAt, "compatibility_alias" )); |
7229 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
7230 | Builder.AddPlaceholderChunk(Placeholder: "alias" ); |
7231 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
7232 | Builder.AddPlaceholderChunk(Placeholder: "class" ); |
7233 | Results.AddResult(R: Result(Builder.TakeString())); |
7234 | |
7235 | if (Results.getSema().getLangOpts().Modules) { |
7236 | // @import name |
7237 | Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "import" )); |
7238 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
7239 | Builder.AddPlaceholderChunk(Placeholder: "module" ); |
7240 | Results.AddResult(R: Result(Builder.TakeString())); |
7241 | } |
7242 | } |
7243 | |
7244 | void Sema::CodeCompleteObjCAtDirective(Scope *S) { |
7245 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
7246 | CodeCompleter->getCodeCompletionTUInfo(), |
7247 | CodeCompletionContext::CCC_Other); |
7248 | Results.EnterNewScope(); |
7249 | if (isa<ObjCImplDecl>(Val: CurContext)) |
7250 | AddObjCImplementationResults(LangOpts: getLangOpts(), Results, NeedAt: false); |
7251 | else if (CurContext->isObjCContainer()) |
7252 | AddObjCInterfaceResults(LangOpts: getLangOpts(), Results, NeedAt: false); |
7253 | else |
7254 | AddObjCTopLevelResults(Results, NeedAt: false); |
7255 | Results.ExitScope(); |
7256 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
7257 | Results: Results.data(), NumResults: Results.size()); |
7258 | } |
7259 | |
7260 | static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) { |
7261 | typedef CodeCompletionResult Result; |
7262 | CodeCompletionBuilder Builder(Results.getAllocator(), |
7263 | Results.getCodeCompletionTUInfo()); |
7264 | |
7265 | // @encode ( type-name ) |
7266 | const char *EncodeType = "char[]" ; |
7267 | if (Results.getSema().getLangOpts().CPlusPlus || |
7268 | Results.getSema().getLangOpts().ConstStrings) |
7269 | EncodeType = "const char[]" ; |
7270 | Builder.AddResultTypeChunk(ResultType: EncodeType); |
7271 | Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "encode" )); |
7272 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
7273 | Builder.AddPlaceholderChunk(Placeholder: "type-name" ); |
7274 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
7275 | Results.AddResult(R: Result(Builder.TakeString())); |
7276 | |
7277 | // @protocol ( protocol-name ) |
7278 | Builder.AddResultTypeChunk(ResultType: "Protocol *" ); |
7279 | Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "protocol" )); |
7280 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
7281 | Builder.AddPlaceholderChunk(Placeholder: "protocol-name" ); |
7282 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
7283 | Results.AddResult(R: Result(Builder.TakeString())); |
7284 | |
7285 | // @selector ( selector ) |
7286 | Builder.AddResultTypeChunk(ResultType: "SEL" ); |
7287 | Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "selector" )); |
7288 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
7289 | Builder.AddPlaceholderChunk(Placeholder: "selector" ); |
7290 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
7291 | Results.AddResult(R: Result(Builder.TakeString())); |
7292 | |
7293 | // @"string" |
7294 | Builder.AddResultTypeChunk(ResultType: "NSString *" ); |
7295 | Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "\"" )); |
7296 | Builder.AddPlaceholderChunk(Placeholder: "string" ); |
7297 | Builder.AddTextChunk(Text: "\"" ); |
7298 | Results.AddResult(R: Result(Builder.TakeString())); |
7299 | |
7300 | // @[objects, ...] |
7301 | Builder.AddResultTypeChunk(ResultType: "NSArray *" ); |
7302 | Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "[" )); |
7303 | Builder.AddPlaceholderChunk(Placeholder: "objects, ..." ); |
7304 | Builder.AddChunk(CK: CodeCompletionString::CK_RightBracket); |
7305 | Results.AddResult(R: Result(Builder.TakeString())); |
7306 | |
7307 | // @{key : object, ...} |
7308 | Builder.AddResultTypeChunk(ResultType: "NSDictionary *" ); |
7309 | Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "{" )); |
7310 | Builder.AddPlaceholderChunk(Placeholder: "key" ); |
7311 | Builder.AddChunk(CK: CodeCompletionString::CK_Colon); |
7312 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
7313 | Builder.AddPlaceholderChunk(Placeholder: "object, ..." ); |
7314 | Builder.AddChunk(CK: CodeCompletionString::CK_RightBrace); |
7315 | Results.AddResult(R: Result(Builder.TakeString())); |
7316 | |
7317 | // @(expression) |
7318 | Builder.AddResultTypeChunk(ResultType: "id" ); |
7319 | Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "(" )); |
7320 | Builder.AddPlaceholderChunk(Placeholder: "expression" ); |
7321 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
7322 | Results.AddResult(R: Result(Builder.TakeString())); |
7323 | } |
7324 | |
7325 | static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) { |
7326 | typedef CodeCompletionResult Result; |
7327 | CodeCompletionBuilder Builder(Results.getAllocator(), |
7328 | Results.getCodeCompletionTUInfo()); |
7329 | |
7330 | if (Results.includeCodePatterns()) { |
7331 | // @try { statements } @catch ( declaration ) { statements } @finally |
7332 | // { statements } |
7333 | Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "try" )); |
7334 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftBrace); |
7335 | Builder.AddPlaceholderChunk(Placeholder: "statements" ); |
7336 | Builder.AddChunk(CK: CodeCompletionString::CK_RightBrace); |
7337 | Builder.AddTextChunk(Text: "@catch" ); |
7338 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
7339 | Builder.AddPlaceholderChunk(Placeholder: "parameter" ); |
7340 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
7341 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftBrace); |
7342 | Builder.AddPlaceholderChunk(Placeholder: "statements" ); |
7343 | Builder.AddChunk(CK: CodeCompletionString::CK_RightBrace); |
7344 | Builder.AddTextChunk(Text: "@finally" ); |
7345 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftBrace); |
7346 | Builder.AddPlaceholderChunk(Placeholder: "statements" ); |
7347 | Builder.AddChunk(CK: CodeCompletionString::CK_RightBrace); |
7348 | Results.AddResult(R: Result(Builder.TakeString())); |
7349 | } |
7350 | |
7351 | // @throw |
7352 | Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "throw" )); |
7353 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
7354 | Builder.AddPlaceholderChunk(Placeholder: "expression" ); |
7355 | Results.AddResult(R: Result(Builder.TakeString())); |
7356 | |
7357 | if (Results.includeCodePatterns()) { |
7358 | // @synchronized ( expression ) { statements } |
7359 | Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "synchronized" )); |
7360 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
7361 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
7362 | Builder.AddPlaceholderChunk(Placeholder: "expression" ); |
7363 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
7364 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftBrace); |
7365 | Builder.AddPlaceholderChunk(Placeholder: "statements" ); |
7366 | Builder.AddChunk(CK: CodeCompletionString::CK_RightBrace); |
7367 | Results.AddResult(R: Result(Builder.TakeString())); |
7368 | } |
7369 | } |
7370 | |
7371 | static void AddObjCVisibilityResults(const LangOptions &LangOpts, |
7372 | ResultBuilder &Results, bool NeedAt) { |
7373 | typedef CodeCompletionResult Result; |
7374 | Results.AddResult(R: Result(OBJC_AT_KEYWORD_NAME(NeedAt, "private" ))); |
7375 | Results.AddResult(R: Result(OBJC_AT_KEYWORD_NAME(NeedAt, "protected" ))); |
7376 | Results.AddResult(R: Result(OBJC_AT_KEYWORD_NAME(NeedAt, "public" ))); |
7377 | if (LangOpts.ObjC) |
7378 | Results.AddResult(R: Result(OBJC_AT_KEYWORD_NAME(NeedAt, "package" ))); |
7379 | } |
7380 | |
7381 | void Sema::CodeCompleteObjCAtVisibility(Scope *S) { |
7382 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
7383 | CodeCompleter->getCodeCompletionTUInfo(), |
7384 | CodeCompletionContext::CCC_Other); |
7385 | Results.EnterNewScope(); |
7386 | AddObjCVisibilityResults(LangOpts: getLangOpts(), Results, NeedAt: false); |
7387 | Results.ExitScope(); |
7388 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
7389 | Results: Results.data(), NumResults: Results.size()); |
7390 | } |
7391 | |
7392 | void Sema::CodeCompleteObjCAtStatement(Scope *S) { |
7393 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
7394 | CodeCompleter->getCodeCompletionTUInfo(), |
7395 | CodeCompletionContext::CCC_Other); |
7396 | Results.EnterNewScope(); |
7397 | AddObjCStatementResults(Results, NeedAt: false); |
7398 | AddObjCExpressionResults(Results, NeedAt: false); |
7399 | Results.ExitScope(); |
7400 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
7401 | Results: Results.data(), NumResults: Results.size()); |
7402 | } |
7403 | |
7404 | void Sema::CodeCompleteObjCAtExpression(Scope *S) { |
7405 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
7406 | CodeCompleter->getCodeCompletionTUInfo(), |
7407 | CodeCompletionContext::CCC_Other); |
7408 | Results.EnterNewScope(); |
7409 | AddObjCExpressionResults(Results, NeedAt: false); |
7410 | Results.ExitScope(); |
7411 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
7412 | Results: Results.data(), NumResults: Results.size()); |
7413 | } |
7414 | |
7415 | /// Determine whether the addition of the given flag to an Objective-C |
7416 | /// property's attributes will cause a conflict. |
7417 | static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) { |
7418 | // Check if we've already added this flag. |
7419 | if (Attributes & NewFlag) |
7420 | return true; |
7421 | |
7422 | Attributes |= NewFlag; |
7423 | |
7424 | // Check for collisions with "readonly". |
7425 | if ((Attributes & ObjCPropertyAttribute::kind_readonly) && |
7426 | (Attributes & ObjCPropertyAttribute::kind_readwrite)) |
7427 | return true; |
7428 | |
7429 | // Check for more than one of { assign, copy, retain, strong, weak }. |
7430 | unsigned AssignCopyRetMask = |
7431 | Attributes & |
7432 | (ObjCPropertyAttribute::kind_assign | |
7433 | ObjCPropertyAttribute::kind_unsafe_unretained | |
7434 | ObjCPropertyAttribute::kind_copy | ObjCPropertyAttribute::kind_retain | |
7435 | ObjCPropertyAttribute::kind_strong | ObjCPropertyAttribute::kind_weak); |
7436 | if (AssignCopyRetMask && |
7437 | AssignCopyRetMask != ObjCPropertyAttribute::kind_assign && |
7438 | AssignCopyRetMask != ObjCPropertyAttribute::kind_unsafe_unretained && |
7439 | AssignCopyRetMask != ObjCPropertyAttribute::kind_copy && |
7440 | AssignCopyRetMask != ObjCPropertyAttribute::kind_retain && |
7441 | AssignCopyRetMask != ObjCPropertyAttribute::kind_strong && |
7442 | AssignCopyRetMask != ObjCPropertyAttribute::kind_weak) |
7443 | return true; |
7444 | |
7445 | return false; |
7446 | } |
7447 | |
7448 | void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) { |
7449 | if (!CodeCompleter) |
7450 | return; |
7451 | |
7452 | unsigned Attributes = ODS.getPropertyAttributes(); |
7453 | |
7454 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
7455 | CodeCompleter->getCodeCompletionTUInfo(), |
7456 | CodeCompletionContext::CCC_Other); |
7457 | Results.EnterNewScope(); |
7458 | if (!ObjCPropertyFlagConflicts(Attributes, |
7459 | NewFlag: ObjCPropertyAttribute::kind_readonly)) |
7460 | Results.AddResult(R: CodeCompletionResult("readonly" )); |
7461 | if (!ObjCPropertyFlagConflicts(Attributes, |
7462 | NewFlag: ObjCPropertyAttribute::kind_assign)) |
7463 | Results.AddResult(R: CodeCompletionResult("assign" )); |
7464 | if (!ObjCPropertyFlagConflicts(Attributes, |
7465 | NewFlag: ObjCPropertyAttribute::kind_unsafe_unretained)) |
7466 | Results.AddResult(R: CodeCompletionResult("unsafe_unretained" )); |
7467 | if (!ObjCPropertyFlagConflicts(Attributes, |
7468 | NewFlag: ObjCPropertyAttribute::kind_readwrite)) |
7469 | Results.AddResult(R: CodeCompletionResult("readwrite" )); |
7470 | if (!ObjCPropertyFlagConflicts(Attributes, |
7471 | NewFlag: ObjCPropertyAttribute::kind_retain)) |
7472 | Results.AddResult(R: CodeCompletionResult("retain" )); |
7473 | if (!ObjCPropertyFlagConflicts(Attributes, |
7474 | NewFlag: ObjCPropertyAttribute::kind_strong)) |
7475 | Results.AddResult(R: CodeCompletionResult("strong" )); |
7476 | if (!ObjCPropertyFlagConflicts(Attributes, NewFlag: ObjCPropertyAttribute::kind_copy)) |
7477 | Results.AddResult(R: CodeCompletionResult("copy" )); |
7478 | if (!ObjCPropertyFlagConflicts(Attributes, |
7479 | NewFlag: ObjCPropertyAttribute::kind_nonatomic)) |
7480 | Results.AddResult(R: CodeCompletionResult("nonatomic" )); |
7481 | if (!ObjCPropertyFlagConflicts(Attributes, |
7482 | NewFlag: ObjCPropertyAttribute::kind_atomic)) |
7483 | Results.AddResult(R: CodeCompletionResult("atomic" )); |
7484 | |
7485 | // Only suggest "weak" if we're compiling for ARC-with-weak-references or GC. |
7486 | if (getLangOpts().ObjCWeak || getLangOpts().getGC() != LangOptions::NonGC) |
7487 | if (!ObjCPropertyFlagConflicts(Attributes, |
7488 | NewFlag: ObjCPropertyAttribute::kind_weak)) |
7489 | Results.AddResult(R: CodeCompletionResult("weak" )); |
7490 | |
7491 | if (!ObjCPropertyFlagConflicts(Attributes, |
7492 | NewFlag: ObjCPropertyAttribute::kind_setter)) { |
7493 | CodeCompletionBuilder Setter(Results.getAllocator(), |
7494 | Results.getCodeCompletionTUInfo()); |
7495 | Setter.AddTypedTextChunk(Text: "setter" ); |
7496 | Setter.AddTextChunk(Text: "=" ); |
7497 | Setter.AddPlaceholderChunk(Placeholder: "method" ); |
7498 | Results.AddResult(R: CodeCompletionResult(Setter.TakeString())); |
7499 | } |
7500 | if (!ObjCPropertyFlagConflicts(Attributes, |
7501 | NewFlag: ObjCPropertyAttribute::kind_getter)) { |
7502 | CodeCompletionBuilder Getter(Results.getAllocator(), |
7503 | Results.getCodeCompletionTUInfo()); |
7504 | Getter.AddTypedTextChunk(Text: "getter" ); |
7505 | Getter.AddTextChunk(Text: "=" ); |
7506 | Getter.AddPlaceholderChunk(Placeholder: "method" ); |
7507 | Results.AddResult(R: CodeCompletionResult(Getter.TakeString())); |
7508 | } |
7509 | if (!ObjCPropertyFlagConflicts(Attributes, |
7510 | NewFlag: ObjCPropertyAttribute::kind_nullability)) { |
7511 | Results.AddResult(R: CodeCompletionResult("nonnull" )); |
7512 | Results.AddResult(R: CodeCompletionResult("nullable" )); |
7513 | Results.AddResult(R: CodeCompletionResult("null_unspecified" )); |
7514 | Results.AddResult(R: CodeCompletionResult("null_resettable" )); |
7515 | } |
7516 | Results.ExitScope(); |
7517 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
7518 | Results: Results.data(), NumResults: Results.size()); |
7519 | } |
7520 | |
7521 | /// Describes the kind of Objective-C method that we want to find |
7522 | /// via code completion. |
7523 | enum ObjCMethodKind { |
7524 | MK_Any, ///< Any kind of method, provided it means other specified criteria. |
7525 | MK_ZeroArgSelector, ///< Zero-argument (unary) selector. |
7526 | MK_OneArgSelector ///< One-argument selector. |
7527 | }; |
7528 | |
7529 | static bool isAcceptableObjCSelector(Selector Sel, ObjCMethodKind WantKind, |
7530 | ArrayRef<const IdentifierInfo *> SelIdents, |
7531 | bool AllowSameLength = true) { |
7532 | unsigned NumSelIdents = SelIdents.size(); |
7533 | if (NumSelIdents > Sel.getNumArgs()) |
7534 | return false; |
7535 | |
7536 | switch (WantKind) { |
7537 | case MK_Any: |
7538 | break; |
7539 | case MK_ZeroArgSelector: |
7540 | return Sel.isUnarySelector(); |
7541 | case MK_OneArgSelector: |
7542 | return Sel.getNumArgs() == 1; |
7543 | } |
7544 | |
7545 | if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs()) |
7546 | return false; |
7547 | |
7548 | for (unsigned I = 0; I != NumSelIdents; ++I) |
7549 | if (SelIdents[I] != Sel.getIdentifierInfoForSlot(argIndex: I)) |
7550 | return false; |
7551 | |
7552 | return true; |
7553 | } |
7554 | |
7555 | static bool isAcceptableObjCMethod(ObjCMethodDecl *Method, |
7556 | ObjCMethodKind WantKind, |
7557 | ArrayRef<const IdentifierInfo *> SelIdents, |
7558 | bool AllowSameLength = true) { |
7559 | return isAcceptableObjCSelector(Sel: Method->getSelector(), WantKind, SelIdents, |
7560 | AllowSameLength); |
7561 | } |
7562 | |
7563 | /// A set of selectors, which is used to avoid introducing multiple |
7564 | /// completions with the same selector into the result set. |
7565 | typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet; |
7566 | |
7567 | /// Add all of the Objective-C methods in the given Objective-C |
7568 | /// container to the set of results. |
7569 | /// |
7570 | /// The container will be a class, protocol, category, or implementation of |
7571 | /// any of the above. This mether will recurse to include methods from |
7572 | /// the superclasses of classes along with their categories, protocols, and |
7573 | /// implementations. |
7574 | /// |
7575 | /// \param Container the container in which we'll look to find methods. |
7576 | /// |
7577 | /// \param WantInstanceMethods Whether to add instance methods (only); if |
7578 | /// false, this routine will add factory methods (only). |
7579 | /// |
7580 | /// \param CurContext the context in which we're performing the lookup that |
7581 | /// finds methods. |
7582 | /// |
7583 | /// \param AllowSameLength Whether we allow a method to be added to the list |
7584 | /// when it has the same number of parameters as we have selector identifiers. |
7585 | /// |
7586 | /// \param Results the structure into which we'll add results. |
7587 | static void AddObjCMethods(ObjCContainerDecl *Container, |
7588 | bool WantInstanceMethods, ObjCMethodKind WantKind, |
7589 | ArrayRef<const IdentifierInfo *> SelIdents, |
7590 | DeclContext *CurContext, |
7591 | VisitedSelectorSet &Selectors, bool AllowSameLength, |
7592 | ResultBuilder &Results, bool InOriginalClass = true, |
7593 | bool IsRootClass = false) { |
7594 | typedef CodeCompletionResult Result; |
7595 | Container = getContainerDef(Container); |
7596 | ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Val: Container); |
7597 | IsRootClass = IsRootClass || (IFace && !IFace->getSuperClass()); |
7598 | for (ObjCMethodDecl *M : Container->methods()) { |
7599 | // The instance methods on the root class can be messaged via the |
7600 | // metaclass. |
7601 | if (M->isInstanceMethod() == WantInstanceMethods || |
7602 | (IsRootClass && !WantInstanceMethods)) { |
7603 | // Check whether the selector identifiers we've been given are a |
7604 | // subset of the identifiers for this particular method. |
7605 | if (!isAcceptableObjCMethod(Method: M, WantKind, SelIdents, AllowSameLength)) |
7606 | continue; |
7607 | |
7608 | if (!Selectors.insert(Ptr: M->getSelector()).second) |
7609 | continue; |
7610 | |
7611 | Result R = Result(M, Results.getBasePriority(M), nullptr); |
7612 | R.StartParameter = SelIdents.size(); |
7613 | R.AllParametersAreInformative = (WantKind != MK_Any); |
7614 | if (!InOriginalClass) |
7615 | setInBaseClass(R); |
7616 | Results.MaybeAddResult(R, CurContext); |
7617 | } |
7618 | } |
7619 | |
7620 | // Visit the protocols of protocols. |
7621 | if (const auto *Protocol = dyn_cast<ObjCProtocolDecl>(Val: Container)) { |
7622 | if (Protocol->hasDefinition()) { |
7623 | const ObjCList<ObjCProtocolDecl> &Protocols = |
7624 | Protocol->getReferencedProtocols(); |
7625 | for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), |
7626 | E = Protocols.end(); |
7627 | I != E; ++I) |
7628 | AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext, |
7629 | Selectors, AllowSameLength, Results, false, IsRootClass); |
7630 | } |
7631 | } |
7632 | |
7633 | if (!IFace || !IFace->hasDefinition()) |
7634 | return; |
7635 | |
7636 | // Add methods in protocols. |
7637 | for (ObjCProtocolDecl *I : IFace->protocols()) |
7638 | AddObjCMethods(I, WantInstanceMethods, WantKind, SelIdents, CurContext, |
7639 | Selectors, AllowSameLength, Results, false, IsRootClass); |
7640 | |
7641 | // Add methods in categories. |
7642 | for (ObjCCategoryDecl *CatDecl : IFace->known_categories()) { |
7643 | AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents, |
7644 | CurContext, Selectors, AllowSameLength, Results, |
7645 | InOriginalClass, IsRootClass); |
7646 | |
7647 | // Add a categories protocol methods. |
7648 | const ObjCList<ObjCProtocolDecl> &Protocols = |
7649 | CatDecl->getReferencedProtocols(); |
7650 | for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), |
7651 | E = Protocols.end(); |
7652 | I != E; ++I) |
7653 | AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext, |
7654 | Selectors, AllowSameLength, Results, false, IsRootClass); |
7655 | |
7656 | // Add methods in category implementations. |
7657 | if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation()) |
7658 | AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext, |
7659 | Selectors, AllowSameLength, Results, InOriginalClass, |
7660 | IsRootClass); |
7661 | } |
7662 | |
7663 | // Add methods in superclass. |
7664 | // Avoid passing in IsRootClass since root classes won't have super classes. |
7665 | if (IFace->getSuperClass()) |
7666 | AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind, |
7667 | SelIdents, CurContext, Selectors, AllowSameLength, Results, |
7668 | /*IsRootClass=*/false); |
7669 | |
7670 | // Add methods in our implementation, if any. |
7671 | if (ObjCImplementationDecl *Impl = IFace->getImplementation()) |
7672 | AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext, |
7673 | Selectors, AllowSameLength, Results, InOriginalClass, |
7674 | IsRootClass); |
7675 | } |
7676 | |
7677 | void Sema::CodeCompleteObjCPropertyGetter(Scope *S) { |
7678 | // Try to find the interface where getters might live. |
7679 | ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(Val: CurContext); |
7680 | if (!Class) { |
7681 | if (ObjCCategoryDecl *Category = |
7682 | dyn_cast_or_null<ObjCCategoryDecl>(Val: CurContext)) |
7683 | Class = Category->getClassInterface(); |
7684 | |
7685 | if (!Class) |
7686 | return; |
7687 | } |
7688 | |
7689 | // Find all of the potential getters. |
7690 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
7691 | CodeCompleter->getCodeCompletionTUInfo(), |
7692 | CodeCompletionContext::CCC_Other); |
7693 | Results.EnterNewScope(); |
7694 | |
7695 | VisitedSelectorSet Selectors; |
7696 | AddObjCMethods(Class, true, MK_ZeroArgSelector, std::nullopt, CurContext, |
7697 | Selectors, |
7698 | /*AllowSameLength=*/true, Results); |
7699 | Results.ExitScope(); |
7700 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
7701 | Results: Results.data(), NumResults: Results.size()); |
7702 | } |
7703 | |
7704 | void Sema::CodeCompleteObjCPropertySetter(Scope *S) { |
7705 | // Try to find the interface where setters might live. |
7706 | ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(Val: CurContext); |
7707 | if (!Class) { |
7708 | if (ObjCCategoryDecl *Category = |
7709 | dyn_cast_or_null<ObjCCategoryDecl>(Val: CurContext)) |
7710 | Class = Category->getClassInterface(); |
7711 | |
7712 | if (!Class) |
7713 | return; |
7714 | } |
7715 | |
7716 | // Find all of the potential getters. |
7717 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
7718 | CodeCompleter->getCodeCompletionTUInfo(), |
7719 | CodeCompletionContext::CCC_Other); |
7720 | Results.EnterNewScope(); |
7721 | |
7722 | VisitedSelectorSet Selectors; |
7723 | AddObjCMethods(Class, true, MK_OneArgSelector, std::nullopt, CurContext, |
7724 | Selectors, |
7725 | /*AllowSameLength=*/true, Results); |
7726 | |
7727 | Results.ExitScope(); |
7728 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
7729 | Results: Results.data(), NumResults: Results.size()); |
7730 | } |
7731 | |
7732 | void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, |
7733 | bool IsParameter) { |
7734 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
7735 | CodeCompleter->getCodeCompletionTUInfo(), |
7736 | CodeCompletionContext::CCC_Type); |
7737 | Results.EnterNewScope(); |
7738 | |
7739 | // Add context-sensitive, Objective-C parameter-passing keywords. |
7740 | bool AddedInOut = false; |
7741 | if ((DS.getObjCDeclQualifier() & |
7742 | (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) { |
7743 | Results.AddResult(R: "in" ); |
7744 | Results.AddResult(R: "inout" ); |
7745 | AddedInOut = true; |
7746 | } |
7747 | if ((DS.getObjCDeclQualifier() & |
7748 | (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) { |
7749 | Results.AddResult(R: "out" ); |
7750 | if (!AddedInOut) |
7751 | Results.AddResult(R: "inout" ); |
7752 | } |
7753 | if ((DS.getObjCDeclQualifier() & |
7754 | (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref | |
7755 | ObjCDeclSpec::DQ_Oneway)) == 0) { |
7756 | Results.AddResult(R: "bycopy" ); |
7757 | Results.AddResult(R: "byref" ); |
7758 | Results.AddResult(R: "oneway" ); |
7759 | } |
7760 | if ((DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability) == 0) { |
7761 | Results.AddResult(R: "nonnull" ); |
7762 | Results.AddResult(R: "nullable" ); |
7763 | Results.AddResult(R: "null_unspecified" ); |
7764 | } |
7765 | |
7766 | // If we're completing the return type of an Objective-C method and the |
7767 | // identifier IBAction refers to a macro, provide a completion item for |
7768 | // an action, e.g., |
7769 | // IBAction)<#selector#>:(id)sender |
7770 | if (DS.getObjCDeclQualifier() == 0 && !IsParameter && |
7771 | PP.isMacroDefined(Id: "IBAction" )) { |
7772 | CodeCompletionBuilder Builder(Results.getAllocator(), |
7773 | Results.getCodeCompletionTUInfo(), |
7774 | CCP_CodePattern, CXAvailability_Available); |
7775 | Builder.AddTypedTextChunk(Text: "IBAction" ); |
7776 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
7777 | Builder.AddPlaceholderChunk(Placeholder: "selector" ); |
7778 | Builder.AddChunk(CK: CodeCompletionString::CK_Colon); |
7779 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
7780 | Builder.AddTextChunk(Text: "id" ); |
7781 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
7782 | Builder.AddTextChunk(Text: "sender" ); |
7783 | Results.AddResult(R: CodeCompletionResult(Builder.TakeString())); |
7784 | } |
7785 | |
7786 | // If we're completing the return type, provide 'instancetype'. |
7787 | if (!IsParameter) { |
7788 | Results.AddResult(R: CodeCompletionResult("instancetype" )); |
7789 | } |
7790 | |
7791 | // Add various builtin type names and specifiers. |
7792 | AddOrdinaryNameResults(CCC: PCC_Type, S, SemaRef&: *this, Results); |
7793 | Results.ExitScope(); |
7794 | |
7795 | // Add the various type names |
7796 | Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName); |
7797 | CodeCompletionDeclConsumer Consumer(Results, CurContext); |
7798 | LookupVisibleDecls(S, LookupOrdinaryName, Consumer, |
7799 | CodeCompleter->includeGlobals(), |
7800 | CodeCompleter->loadExternal()); |
7801 | |
7802 | if (CodeCompleter->includeMacros()) |
7803 | AddMacroResults(PP, Results, LoadExternal: CodeCompleter->loadExternal(), IncludeUndefined: false); |
7804 | |
7805 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
7806 | Results: Results.data(), NumResults: Results.size()); |
7807 | } |
7808 | |
7809 | /// When we have an expression with type "id", we may assume |
7810 | /// that it has some more-specific class type based on knowledge of |
7811 | /// common uses of Objective-C. This routine returns that class type, |
7812 | /// or NULL if no better result could be determined. |
7813 | static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) { |
7814 | auto *Msg = dyn_cast_or_null<ObjCMessageExpr>(Val: E); |
7815 | if (!Msg) |
7816 | return nullptr; |
7817 | |
7818 | Selector Sel = Msg->getSelector(); |
7819 | if (Sel.isNull()) |
7820 | return nullptr; |
7821 | |
7822 | const IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(argIndex: 0); |
7823 | if (!Id) |
7824 | return nullptr; |
7825 | |
7826 | ObjCMethodDecl *Method = Msg->getMethodDecl(); |
7827 | if (!Method) |
7828 | return nullptr; |
7829 | |
7830 | // Determine the class that we're sending the message to. |
7831 | ObjCInterfaceDecl *IFace = nullptr; |
7832 | switch (Msg->getReceiverKind()) { |
7833 | case ObjCMessageExpr::Class: |
7834 | if (const ObjCObjectType *ObjType = |
7835 | Msg->getClassReceiver()->getAs<ObjCObjectType>()) |
7836 | IFace = ObjType->getInterface(); |
7837 | break; |
7838 | |
7839 | case ObjCMessageExpr::Instance: { |
7840 | QualType T = Msg->getInstanceReceiver()->getType(); |
7841 | if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>()) |
7842 | IFace = Ptr->getInterfaceDecl(); |
7843 | break; |
7844 | } |
7845 | |
7846 | case ObjCMessageExpr::SuperInstance: |
7847 | case ObjCMessageExpr::SuperClass: |
7848 | break; |
7849 | } |
7850 | |
7851 | if (!IFace) |
7852 | return nullptr; |
7853 | |
7854 | ObjCInterfaceDecl *Super = IFace->getSuperClass(); |
7855 | if (Method->isInstanceMethod()) |
7856 | return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName()) |
7857 | .Case(S: "retain" , Value: IFace) |
7858 | .Case(S: "strong" , Value: IFace) |
7859 | .Case(S: "autorelease" , Value: IFace) |
7860 | .Case(S: "copy" , Value: IFace) |
7861 | .Case(S: "copyWithZone" , Value: IFace) |
7862 | .Case(S: "mutableCopy" , Value: IFace) |
7863 | .Case(S: "mutableCopyWithZone" , Value: IFace) |
7864 | .Case(S: "awakeFromCoder" , Value: IFace) |
7865 | .Case(S: "replacementObjectFromCoder" , Value: IFace) |
7866 | .Case(S: "class" , Value: IFace) |
7867 | .Case(S: "classForCoder" , Value: IFace) |
7868 | .Case(S: "superclass" , Value: Super) |
7869 | .Default(Value: nullptr); |
7870 | |
7871 | return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName()) |
7872 | .Case(S: "new" , Value: IFace) |
7873 | .Case(S: "alloc" , Value: IFace) |
7874 | .Case(S: "allocWithZone" , Value: IFace) |
7875 | .Case(S: "class" , Value: IFace) |
7876 | .Case(S: "superclass" , Value: Super) |
7877 | .Default(Value: nullptr); |
7878 | } |
7879 | |
7880 | // Add a special completion for a message send to "super", which fills in the |
7881 | // most likely case of forwarding all of our arguments to the superclass |
7882 | // function. |
7883 | /// |
7884 | /// \param S The semantic analysis object. |
7885 | /// |
7886 | /// \param NeedSuperKeyword Whether we need to prefix this completion with |
7887 | /// the "super" keyword. Otherwise, we just need to provide the arguments. |
7888 | /// |
7889 | /// \param SelIdents The identifiers in the selector that have already been |
7890 | /// provided as arguments for a send to "super". |
7891 | /// |
7892 | /// \param Results The set of results to augment. |
7893 | /// |
7894 | /// \returns the Objective-C method declaration that would be invoked by |
7895 | /// this "super" completion. If NULL, no completion was added. |
7896 | static ObjCMethodDecl * |
7897 | AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword, |
7898 | ArrayRef<const IdentifierInfo *> SelIdents, |
7899 | ResultBuilder &Results) { |
7900 | ObjCMethodDecl *CurMethod = S.getCurMethodDecl(); |
7901 | if (!CurMethod) |
7902 | return nullptr; |
7903 | |
7904 | ObjCInterfaceDecl *Class = CurMethod->getClassInterface(); |
7905 | if (!Class) |
7906 | return nullptr; |
7907 | |
7908 | // Try to find a superclass method with the same selector. |
7909 | ObjCMethodDecl *SuperMethod = nullptr; |
7910 | while ((Class = Class->getSuperClass()) && !SuperMethod) { |
7911 | // Check in the class |
7912 | SuperMethod = Class->getMethod(CurMethod->getSelector(), |
7913 | CurMethod->isInstanceMethod()); |
7914 | |
7915 | // Check in categories or class extensions. |
7916 | if (!SuperMethod) { |
7917 | for (const auto *Cat : Class->known_categories()) { |
7918 | if ((SuperMethod = Cat->getMethod(CurMethod->getSelector(), |
7919 | CurMethod->isInstanceMethod()))) |
7920 | break; |
7921 | } |
7922 | } |
7923 | } |
7924 | |
7925 | if (!SuperMethod) |
7926 | return nullptr; |
7927 | |
7928 | // Check whether the superclass method has the same signature. |
7929 | if (CurMethod->param_size() != SuperMethod->param_size() || |
7930 | CurMethod->isVariadic() != SuperMethod->isVariadic()) |
7931 | return nullptr; |
7932 | |
7933 | for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(), |
7934 | CurPEnd = CurMethod->param_end(), |
7935 | SuperP = SuperMethod->param_begin(); |
7936 | CurP != CurPEnd; ++CurP, ++SuperP) { |
7937 | // Make sure the parameter types are compatible. |
7938 | if (!S.Context.hasSameUnqualifiedType(T1: (*CurP)->getType(), |
7939 | T2: (*SuperP)->getType())) |
7940 | return nullptr; |
7941 | |
7942 | // Make sure we have a parameter name to forward! |
7943 | if (!(*CurP)->getIdentifier()) |
7944 | return nullptr; |
7945 | } |
7946 | |
7947 | // We have a superclass method. Now, form the send-to-super completion. |
7948 | CodeCompletionBuilder Builder(Results.getAllocator(), |
7949 | Results.getCodeCompletionTUInfo()); |
7950 | |
7951 | // Give this completion a return type. |
7952 | AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod, |
7953 | Results.getCompletionContext().getBaseType(), Builder); |
7954 | |
7955 | // If we need the "super" keyword, add it (plus some spacing). |
7956 | if (NeedSuperKeyword) { |
7957 | Builder.AddTypedTextChunk(Text: "super" ); |
7958 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
7959 | } |
7960 | |
7961 | Selector Sel = CurMethod->getSelector(); |
7962 | if (Sel.isUnarySelector()) { |
7963 | if (NeedSuperKeyword) |
7964 | Builder.AddTextChunk( |
7965 | Text: Builder.getAllocator().CopyString(String: Sel.getNameForSlot(argIndex: 0))); |
7966 | else |
7967 | Builder.AddTypedTextChunk( |
7968 | Text: Builder.getAllocator().CopyString(String: Sel.getNameForSlot(argIndex: 0))); |
7969 | } else { |
7970 | ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(); |
7971 | for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) { |
7972 | if (I > SelIdents.size()) |
7973 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
7974 | |
7975 | if (I < SelIdents.size()) |
7976 | Builder.AddInformativeChunk( |
7977 | Text: Builder.getAllocator().CopyString(String: Sel.getNameForSlot(argIndex: I) + ":" )); |
7978 | else if (NeedSuperKeyword || I > SelIdents.size()) { |
7979 | Builder.AddTextChunk( |
7980 | Text: Builder.getAllocator().CopyString(String: Sel.getNameForSlot(argIndex: I) + ":" )); |
7981 | Builder.AddPlaceholderChunk(Placeholder: Builder.getAllocator().CopyString( |
7982 | String: (*CurP)->getIdentifier()->getName())); |
7983 | } else { |
7984 | Builder.AddTypedTextChunk( |
7985 | Text: Builder.getAllocator().CopyString(String: Sel.getNameForSlot(argIndex: I) + ":" )); |
7986 | Builder.AddPlaceholderChunk(Placeholder: Builder.getAllocator().CopyString( |
7987 | String: (*CurP)->getIdentifier()->getName())); |
7988 | } |
7989 | } |
7990 | } |
7991 | |
7992 | Results.AddResult(R: CodeCompletionResult(Builder.TakeString(), SuperMethod, |
7993 | CCP_SuperCompletion)); |
7994 | return SuperMethod; |
7995 | } |
7996 | |
7997 | void Sema::CodeCompleteObjCMessageReceiver(Scope *S) { |
7998 | typedef CodeCompletionResult Result; |
7999 | ResultBuilder Results( |
8000 | *this, CodeCompleter->getAllocator(), |
8001 | CodeCompleter->getCodeCompletionTUInfo(), |
8002 | CodeCompletionContext::CCC_ObjCMessageReceiver, |
8003 | getLangOpts().CPlusPlus11 |
8004 | ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture |
8005 | : &ResultBuilder::IsObjCMessageReceiver); |
8006 | |
8007 | CodeCompletionDeclConsumer Consumer(Results, CurContext); |
8008 | Results.EnterNewScope(); |
8009 | LookupVisibleDecls(S, LookupOrdinaryName, Consumer, |
8010 | CodeCompleter->includeGlobals(), |
8011 | CodeCompleter->loadExternal()); |
8012 | |
8013 | // If we are in an Objective-C method inside a class that has a superclass, |
8014 | // add "super" as an option. |
8015 | if (ObjCMethodDecl *Method = getCurMethodDecl()) |
8016 | if (ObjCInterfaceDecl *Iface = Method->getClassInterface()) |
8017 | if (Iface->getSuperClass()) { |
8018 | Results.AddResult(R: Result("super" )); |
8019 | |
8020 | AddSuperSendCompletion(S&: *this, /*NeedSuperKeyword=*/true, SelIdents: std::nullopt, |
8021 | Results); |
8022 | } |
8023 | |
8024 | if (getLangOpts().CPlusPlus11) |
8025 | addThisCompletion(S&: *this, Results); |
8026 | |
8027 | Results.ExitScope(); |
8028 | |
8029 | if (CodeCompleter->includeMacros()) |
8030 | AddMacroResults(PP, Results, LoadExternal: CodeCompleter->loadExternal(), IncludeUndefined: false); |
8031 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
8032 | Results: Results.data(), NumResults: Results.size()); |
8033 | } |
8034 | |
8035 | void Sema::CodeCompleteObjCSuperMessage( |
8036 | Scope *S, SourceLocation SuperLoc, |
8037 | ArrayRef<const IdentifierInfo *> SelIdents, bool AtArgumentExpression) { |
8038 | ObjCInterfaceDecl *CDecl = nullptr; |
8039 | if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) { |
8040 | // Figure out which interface we're in. |
8041 | CDecl = CurMethod->getClassInterface(); |
8042 | if (!CDecl) |
8043 | return; |
8044 | |
8045 | // Find the superclass of this class. |
8046 | CDecl = CDecl->getSuperClass(); |
8047 | if (!CDecl) |
8048 | return; |
8049 | |
8050 | if (CurMethod->isInstanceMethod()) { |
8051 | // We are inside an instance method, which means that the message |
8052 | // send [super ...] is actually calling an instance method on the |
8053 | // current object. |
8054 | return CodeCompleteObjCInstanceMessage(S, Receiver: nullptr, SelIdents, |
8055 | AtArgumentExpression, Super: CDecl); |
8056 | } |
8057 | |
8058 | // Fall through to send to the superclass in CDecl. |
8059 | } else { |
8060 | // "super" may be the name of a type or variable. Figure out which |
8061 | // it is. |
8062 | const IdentifierInfo *Super = getSuperIdentifier(); |
8063 | NamedDecl *ND = LookupSingleName(S, Name: Super, Loc: SuperLoc, NameKind: LookupOrdinaryName); |
8064 | if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(Val: ND))) { |
8065 | // "super" names an interface. Use it. |
8066 | } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(Val: ND)) { |
8067 | if (const ObjCObjectType *Iface = |
8068 | Context.getTypeDeclType(Decl: TD)->getAs<ObjCObjectType>()) |
8069 | CDecl = Iface->getInterface(); |
8070 | } else if (ND && isa<UnresolvedUsingTypenameDecl>(Val: ND)) { |
8071 | // "super" names an unresolved type; we can't be more specific. |
8072 | } else { |
8073 | // Assume that "super" names some kind of value and parse that way. |
8074 | CXXScopeSpec SS; |
8075 | SourceLocation TemplateKWLoc; |
8076 | UnqualifiedId id; |
8077 | id.setIdentifier(Id: Super, IdLoc: SuperLoc); |
8078 | ExprResult SuperExpr = ActOnIdExpression(S, SS, TemplateKWLoc, Id&: id, |
8079 | /*HasTrailingLParen=*/false, |
8080 | /*IsAddressOfOperand=*/false); |
8081 | return CodeCompleteObjCInstanceMessage(S, Receiver: (Expr *)SuperExpr.get(), |
8082 | SelIdents, AtArgumentExpression); |
8083 | } |
8084 | |
8085 | // Fall through |
8086 | } |
8087 | |
8088 | ParsedType Receiver; |
8089 | if (CDecl) |
8090 | Receiver = ParsedType::make(P: Context.getObjCInterfaceType(Decl: CDecl)); |
8091 | return CodeCompleteObjCClassMessage(S, Receiver, SelIdents, |
8092 | AtArgumentExpression, |
8093 | /*IsSuper=*/true); |
8094 | } |
8095 | |
8096 | /// Given a set of code-completion results for the argument of a message |
8097 | /// send, determine the preferred type (if any) for that argument expression. |
8098 | static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results, |
8099 | unsigned NumSelIdents) { |
8100 | typedef CodeCompletionResult Result; |
8101 | ASTContext &Context = Results.getSema().Context; |
8102 | |
8103 | QualType PreferredType; |
8104 | unsigned BestPriority = CCP_Unlikely * 2; |
8105 | Result *ResultsData = Results.data(); |
8106 | for (unsigned I = 0, N = Results.size(); I != N; ++I) { |
8107 | Result &R = ResultsData[I]; |
8108 | if (R.Kind == Result::RK_Declaration && |
8109 | isa<ObjCMethodDecl>(Val: R.Declaration)) { |
8110 | if (R.Priority <= BestPriority) { |
8111 | const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(Val: R.Declaration); |
8112 | if (NumSelIdents <= Method->param_size()) { |
8113 | QualType MyPreferredType = |
8114 | Method->parameters()[NumSelIdents - 1]->getType(); |
8115 | if (R.Priority < BestPriority || PreferredType.isNull()) { |
8116 | BestPriority = R.Priority; |
8117 | PreferredType = MyPreferredType; |
8118 | } else if (!Context.hasSameUnqualifiedType(T1: PreferredType, |
8119 | T2: MyPreferredType)) { |
8120 | PreferredType = QualType(); |
8121 | } |
8122 | } |
8123 | } |
8124 | } |
8125 | } |
8126 | |
8127 | return PreferredType; |
8128 | } |
8129 | |
8130 | static void |
8131 | AddClassMessageCompletions(Sema &SemaRef, Scope *S, ParsedType Receiver, |
8132 | ArrayRef<const IdentifierInfo *> SelIdents, |
8133 | bool AtArgumentExpression, bool IsSuper, |
8134 | ResultBuilder &Results) { |
8135 | typedef CodeCompletionResult Result; |
8136 | ObjCInterfaceDecl *CDecl = nullptr; |
8137 | |
8138 | // If the given name refers to an interface type, retrieve the |
8139 | // corresponding declaration. |
8140 | if (Receiver) { |
8141 | QualType T = SemaRef.GetTypeFromParser(Ty: Receiver, TInfo: nullptr); |
8142 | if (!T.isNull()) |
8143 | if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>()) |
8144 | CDecl = Interface->getInterface(); |
8145 | } |
8146 | |
8147 | // Add all of the factory methods in this Objective-C class, its protocols, |
8148 | // superclasses, categories, implementation, etc. |
8149 | Results.EnterNewScope(); |
8150 | |
8151 | // If this is a send-to-super, try to add the special "super" send |
8152 | // completion. |
8153 | if (IsSuper) { |
8154 | if (ObjCMethodDecl *SuperMethod = |
8155 | AddSuperSendCompletion(S&: SemaRef, NeedSuperKeyword: false, SelIdents, Results)) |
8156 | Results.Ignore(SuperMethod); |
8157 | } |
8158 | |
8159 | // If we're inside an Objective-C method definition, prefer its selector to |
8160 | // others. |
8161 | if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl()) |
8162 | Results.setPreferredSelector(CurMethod->getSelector()); |
8163 | |
8164 | VisitedSelectorSet Selectors; |
8165 | if (CDecl) |
8166 | AddObjCMethods(CDecl, false, MK_Any, SelIdents, SemaRef.CurContext, |
8167 | Selectors, AtArgumentExpression, Results); |
8168 | else { |
8169 | // We're messaging "id" as a type; provide all class/factory methods. |
8170 | |
8171 | // If we have an external source, load the entire class method |
8172 | // pool from the AST file. |
8173 | if (SemaRef.getExternalSource()) { |
8174 | for (uint32_t I = 0, |
8175 | N = SemaRef.getExternalSource()->GetNumExternalSelectors(); |
8176 | I != N; ++I) { |
8177 | Selector Sel = SemaRef.getExternalSource()->GetExternalSelector(ID: I); |
8178 | if (Sel.isNull() || SemaRef.MethodPool.count(Sel)) |
8179 | continue; |
8180 | |
8181 | SemaRef.ReadMethodPool(Sel); |
8182 | } |
8183 | } |
8184 | |
8185 | for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(), |
8186 | MEnd = SemaRef.MethodPool.end(); |
8187 | M != MEnd; ++M) { |
8188 | for (ObjCMethodList *MethList = &M->second.second; |
8189 | MethList && MethList->getMethod(); MethList = MethList->getNext()) { |
8190 | if (!isAcceptableObjCMethod(Method: MethList->getMethod(), WantKind: MK_Any, SelIdents)) |
8191 | continue; |
8192 | |
8193 | Result R(MethList->getMethod(), |
8194 | Results.getBasePriority(MethList->getMethod()), nullptr); |
8195 | R.StartParameter = SelIdents.size(); |
8196 | R.AllParametersAreInformative = false; |
8197 | Results.MaybeAddResult(R, CurContext: SemaRef.CurContext); |
8198 | } |
8199 | } |
8200 | } |
8201 | |
8202 | Results.ExitScope(); |
8203 | } |
8204 | |
8205 | void Sema::CodeCompleteObjCClassMessage( |
8206 | Scope *S, ParsedType Receiver, ArrayRef<const IdentifierInfo *> SelIdents, |
8207 | bool AtArgumentExpression, bool IsSuper) { |
8208 | |
8209 | QualType T = this->GetTypeFromParser(Ty: Receiver); |
8210 | |
8211 | ResultBuilder Results( |
8212 | *this, CodeCompleter->getAllocator(), |
8213 | CodeCompleter->getCodeCompletionTUInfo(), |
8214 | CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage, T, |
8215 | SelIdents)); |
8216 | |
8217 | AddClassMessageCompletions(SemaRef&: *this, S, Receiver, SelIdents, |
8218 | AtArgumentExpression, IsSuper, Results); |
8219 | |
8220 | // If we're actually at the argument expression (rather than prior to the |
8221 | // selector), we're actually performing code completion for an expression. |
8222 | // Determine whether we have a single, best method. If so, we can |
8223 | // code-complete the expression using the corresponding parameter type as |
8224 | // our preferred type, improving completion results. |
8225 | if (AtArgumentExpression) { |
8226 | QualType PreferredType = |
8227 | getPreferredArgumentTypeForMessageSend(Results, NumSelIdents: SelIdents.size()); |
8228 | if (PreferredType.isNull()) |
8229 | CodeCompleteOrdinaryName(S, CompletionContext: PCC_Expression); |
8230 | else |
8231 | CodeCompleteExpression(S, PreferredType); |
8232 | return; |
8233 | } |
8234 | |
8235 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
8236 | Results: Results.data(), NumResults: Results.size()); |
8237 | } |
8238 | |
8239 | void Sema::CodeCompleteObjCInstanceMessage( |
8240 | Scope *S, Expr *Receiver, ArrayRef<const IdentifierInfo *> SelIdents, |
8241 | bool AtArgumentExpression, ObjCInterfaceDecl *Super) { |
8242 | typedef CodeCompletionResult Result; |
8243 | |
8244 | Expr *RecExpr = static_cast<Expr *>(Receiver); |
8245 | |
8246 | // If necessary, apply function/array conversion to the receiver. |
8247 | // C99 6.7.5.3p[7,8]. |
8248 | if (RecExpr) { |
8249 | ExprResult Conv = DefaultFunctionArrayLvalueConversion(E: RecExpr); |
8250 | if (Conv.isInvalid()) // conversion failed. bail. |
8251 | return; |
8252 | RecExpr = Conv.get(); |
8253 | } |
8254 | QualType ReceiverType = RecExpr |
8255 | ? RecExpr->getType() |
8256 | : Super ? Context.getObjCObjectPointerType( |
8257 | OIT: Context.getObjCInterfaceType(Decl: Super)) |
8258 | : Context.getObjCIdType(); |
8259 | |
8260 | // If we're messaging an expression with type "id" or "Class", check |
8261 | // whether we know something special about the receiver that allows |
8262 | // us to assume a more-specific receiver type. |
8263 | if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType()) { |
8264 | if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(E: RecExpr)) { |
8265 | if (ReceiverType->isObjCClassType()) |
8266 | return CodeCompleteObjCClassMessage( |
8267 | S, Receiver: ParsedType::make(P: Context.getObjCInterfaceType(Decl: IFace)), SelIdents, |
8268 | AtArgumentExpression, IsSuper: Super); |
8269 | |
8270 | ReceiverType = |
8271 | Context.getObjCObjectPointerType(OIT: Context.getObjCInterfaceType(Decl: IFace)); |
8272 | } |
8273 | } else if (RecExpr && getLangOpts().CPlusPlus) { |
8274 | ExprResult Conv = PerformContextuallyConvertToObjCPointer(From: RecExpr); |
8275 | if (Conv.isUsable()) { |
8276 | RecExpr = Conv.get(); |
8277 | ReceiverType = RecExpr->getType(); |
8278 | } |
8279 | } |
8280 | |
8281 | // Build the set of methods we can see. |
8282 | ResultBuilder Results( |
8283 | *this, CodeCompleter->getAllocator(), |
8284 | CodeCompleter->getCodeCompletionTUInfo(), |
8285 | CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage, |
8286 | ReceiverType, SelIdents)); |
8287 | |
8288 | Results.EnterNewScope(); |
8289 | |
8290 | // If this is a send-to-super, try to add the special "super" send |
8291 | // completion. |
8292 | if (Super) { |
8293 | if (ObjCMethodDecl *SuperMethod = |
8294 | AddSuperSendCompletion(S&: *this, NeedSuperKeyword: false, SelIdents, Results)) |
8295 | Results.Ignore(SuperMethod); |
8296 | } |
8297 | |
8298 | // If we're inside an Objective-C method definition, prefer its selector to |
8299 | // others. |
8300 | if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) |
8301 | Results.setPreferredSelector(CurMethod->getSelector()); |
8302 | |
8303 | // Keep track of the selectors we've already added. |
8304 | VisitedSelectorSet Selectors; |
8305 | |
8306 | // Handle messages to Class. This really isn't a message to an instance |
8307 | // method, so we treat it the same way we would treat a message send to a |
8308 | // class method. |
8309 | if (ReceiverType->isObjCClassType() || |
8310 | ReceiverType->isObjCQualifiedClassType()) { |
8311 | if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) { |
8312 | if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface()) |
8313 | AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, CurContext, |
8314 | Selectors, AtArgumentExpression, Results); |
8315 | } |
8316 | } |
8317 | // Handle messages to a qualified ID ("id<foo>"). |
8318 | else if (const ObjCObjectPointerType *QualID = |
8319 | ReceiverType->getAsObjCQualifiedIdType()) { |
8320 | // Search protocols for instance methods. |
8321 | for (auto *I : QualID->quals()) |
8322 | AddObjCMethods(I, true, MK_Any, SelIdents, CurContext, Selectors, |
8323 | AtArgumentExpression, Results); |
8324 | } |
8325 | // Handle messages to a pointer to interface type. |
8326 | else if (const ObjCObjectPointerType *IFacePtr = |
8327 | ReceiverType->getAsObjCInterfacePointerType()) { |
8328 | // Search the class, its superclasses, etc., for instance methods. |
8329 | AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents, |
8330 | CurContext, Selectors, AtArgumentExpression, Results); |
8331 | |
8332 | // Search protocols for instance methods. |
8333 | for (auto *I : IFacePtr->quals()) |
8334 | AddObjCMethods(I, true, MK_Any, SelIdents, CurContext, Selectors, |
8335 | AtArgumentExpression, Results); |
8336 | } |
8337 | // Handle messages to "id". |
8338 | else if (ReceiverType->isObjCIdType()) { |
8339 | // We're messaging "id", so provide all instance methods we know |
8340 | // about as code-completion results. |
8341 | |
8342 | // If we have an external source, load the entire class method |
8343 | // pool from the AST file. |
8344 | if (ExternalSource) { |
8345 | for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); |
8346 | I != N; ++I) { |
8347 | Selector Sel = ExternalSource->GetExternalSelector(ID: I); |
8348 | if (Sel.isNull() || MethodPool.count(Sel)) |
8349 | continue; |
8350 | |
8351 | ReadMethodPool(Sel); |
8352 | } |
8353 | } |
8354 | |
8355 | for (GlobalMethodPool::iterator M = MethodPool.begin(), |
8356 | MEnd = MethodPool.end(); |
8357 | M != MEnd; ++M) { |
8358 | for (ObjCMethodList *MethList = &M->second.first; |
8359 | MethList && MethList->getMethod(); MethList = MethList->getNext()) { |
8360 | if (!isAcceptableObjCMethod(Method: MethList->getMethod(), WantKind: MK_Any, SelIdents)) |
8361 | continue; |
8362 | |
8363 | if (!Selectors.insert(Ptr: MethList->getMethod()->getSelector()).second) |
8364 | continue; |
8365 | |
8366 | Result R(MethList->getMethod(), |
8367 | Results.getBasePriority(MethList->getMethod()), nullptr); |
8368 | R.StartParameter = SelIdents.size(); |
8369 | R.AllParametersAreInformative = false; |
8370 | Results.MaybeAddResult(R, CurContext); |
8371 | } |
8372 | } |
8373 | } |
8374 | Results.ExitScope(); |
8375 | |
8376 | // If we're actually at the argument expression (rather than prior to the |
8377 | // selector), we're actually performing code completion for an expression. |
8378 | // Determine whether we have a single, best method. If so, we can |
8379 | // code-complete the expression using the corresponding parameter type as |
8380 | // our preferred type, improving completion results. |
8381 | if (AtArgumentExpression) { |
8382 | QualType PreferredType = |
8383 | getPreferredArgumentTypeForMessageSend(Results, NumSelIdents: SelIdents.size()); |
8384 | if (PreferredType.isNull()) |
8385 | CodeCompleteOrdinaryName(S, CompletionContext: PCC_Expression); |
8386 | else |
8387 | CodeCompleteExpression(S, PreferredType); |
8388 | return; |
8389 | } |
8390 | |
8391 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
8392 | Results: Results.data(), NumResults: Results.size()); |
8393 | } |
8394 | |
8395 | void Sema::CodeCompleteObjCForCollection(Scope *S, |
8396 | DeclGroupPtrTy IterationVar) { |
8397 | CodeCompleteExpressionData Data; |
8398 | Data.ObjCCollection = true; |
8399 | |
8400 | if (IterationVar.getAsOpaquePtr()) { |
8401 | DeclGroupRef DG = IterationVar.get(); |
8402 | for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) { |
8403 | if (*I) |
8404 | Data.IgnoreDecls.push_back(Elt: *I); |
8405 | } |
8406 | } |
8407 | |
8408 | CodeCompleteExpression(S, Data); |
8409 | } |
8410 | |
8411 | void Sema::CodeCompleteObjCSelector( |
8412 | Scope *S, ArrayRef<const IdentifierInfo *> SelIdents) { |
8413 | // If we have an external source, load the entire class method |
8414 | // pool from the AST file. |
8415 | if (ExternalSource) { |
8416 | for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); I != N; |
8417 | ++I) { |
8418 | Selector Sel = ExternalSource->GetExternalSelector(ID: I); |
8419 | if (Sel.isNull() || MethodPool.count(Sel)) |
8420 | continue; |
8421 | |
8422 | ReadMethodPool(Sel); |
8423 | } |
8424 | } |
8425 | |
8426 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
8427 | CodeCompleter->getCodeCompletionTUInfo(), |
8428 | CodeCompletionContext::CCC_SelectorName); |
8429 | Results.EnterNewScope(); |
8430 | for (GlobalMethodPool::iterator M = MethodPool.begin(), |
8431 | MEnd = MethodPool.end(); |
8432 | M != MEnd; ++M) { |
8433 | |
8434 | Selector Sel = M->first; |
8435 | if (!isAcceptableObjCSelector(Sel, WantKind: MK_Any, SelIdents)) |
8436 | continue; |
8437 | |
8438 | CodeCompletionBuilder Builder(Results.getAllocator(), |
8439 | Results.getCodeCompletionTUInfo()); |
8440 | if (Sel.isUnarySelector()) { |
8441 | Builder.AddTypedTextChunk( |
8442 | Text: Builder.getAllocator().CopyString(String: Sel.getNameForSlot(argIndex: 0))); |
8443 | Results.AddResult(R: Builder.TakeString()); |
8444 | continue; |
8445 | } |
8446 | |
8447 | std::string Accumulator; |
8448 | for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) { |
8449 | if (I == SelIdents.size()) { |
8450 | if (!Accumulator.empty()) { |
8451 | Builder.AddInformativeChunk( |
8452 | Text: Builder.getAllocator().CopyString(String: Accumulator)); |
8453 | Accumulator.clear(); |
8454 | } |
8455 | } |
8456 | |
8457 | Accumulator += Sel.getNameForSlot(argIndex: I); |
8458 | Accumulator += ':'; |
8459 | } |
8460 | Builder.AddTypedTextChunk(Text: Builder.getAllocator().CopyString(String: Accumulator)); |
8461 | Results.AddResult(R: Builder.TakeString()); |
8462 | } |
8463 | Results.ExitScope(); |
8464 | |
8465 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
8466 | Results: Results.data(), NumResults: Results.size()); |
8467 | } |
8468 | |
8469 | /// Add all of the protocol declarations that we find in the given |
8470 | /// (translation unit) context. |
8471 | static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext, |
8472 | bool OnlyForwardDeclarations, |
8473 | ResultBuilder &Results) { |
8474 | typedef CodeCompletionResult Result; |
8475 | |
8476 | for (const auto *D : Ctx->decls()) { |
8477 | // Record any protocols we find. |
8478 | if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(Val: D)) |
8479 | if (!OnlyForwardDeclarations || !Proto->hasDefinition()) |
8480 | Results.AddResult( |
8481 | R: Result(Proto, Results.getBasePriority(Proto), nullptr), CurContext, |
8482 | Hiding: nullptr, InBaseClass: false); |
8483 | } |
8484 | } |
8485 | |
8486 | void Sema::CodeCompleteObjCProtocolReferences( |
8487 | ArrayRef<IdentifierLocPair> Protocols) { |
8488 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
8489 | CodeCompleter->getCodeCompletionTUInfo(), |
8490 | CodeCompletionContext::CCC_ObjCProtocolName); |
8491 | |
8492 | if (CodeCompleter->includeGlobals()) { |
8493 | Results.EnterNewScope(); |
8494 | |
8495 | // Tell the result set to ignore all of the protocols we have |
8496 | // already seen. |
8497 | // FIXME: This doesn't work when caching code-completion results. |
8498 | for (const IdentifierLocPair &Pair : Protocols) |
8499 | if (ObjCProtocolDecl *Protocol = LookupProtocol(II: Pair.first, IdLoc: Pair.second)) |
8500 | Results.Ignore(Protocol); |
8501 | |
8502 | // Add all protocols. |
8503 | AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false, |
8504 | Results); |
8505 | |
8506 | Results.ExitScope(); |
8507 | } |
8508 | |
8509 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
8510 | Results: Results.data(), NumResults: Results.size()); |
8511 | } |
8512 | |
8513 | void Sema::CodeCompleteObjCProtocolDecl(Scope *) { |
8514 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
8515 | CodeCompleter->getCodeCompletionTUInfo(), |
8516 | CodeCompletionContext::CCC_ObjCProtocolName); |
8517 | |
8518 | if (CodeCompleter->includeGlobals()) { |
8519 | Results.EnterNewScope(); |
8520 | |
8521 | // Add all protocols. |
8522 | AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true, |
8523 | Results); |
8524 | |
8525 | Results.ExitScope(); |
8526 | } |
8527 | |
8528 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
8529 | Results: Results.data(), NumResults: Results.size()); |
8530 | } |
8531 | |
8532 | /// Add all of the Objective-C interface declarations that we find in |
8533 | /// the given (translation unit) context. |
8534 | static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext, |
8535 | bool OnlyForwardDeclarations, |
8536 | bool OnlyUnimplemented, |
8537 | ResultBuilder &Results) { |
8538 | typedef CodeCompletionResult Result; |
8539 | |
8540 | for (const auto *D : Ctx->decls()) { |
8541 | // Record any interfaces we find. |
8542 | if (const auto *Class = dyn_cast<ObjCInterfaceDecl>(Val: D)) |
8543 | if ((!OnlyForwardDeclarations || !Class->hasDefinition()) && |
8544 | (!OnlyUnimplemented || !Class->getImplementation())) |
8545 | Results.AddResult( |
8546 | R: Result(Class, Results.getBasePriority(Class), nullptr), CurContext, |
8547 | Hiding: nullptr, InBaseClass: false); |
8548 | } |
8549 | } |
8550 | |
8551 | void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) { |
8552 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
8553 | CodeCompleter->getCodeCompletionTUInfo(), |
8554 | CodeCompletionContext::CCC_ObjCInterfaceName); |
8555 | Results.EnterNewScope(); |
8556 | |
8557 | if (CodeCompleter->includeGlobals()) { |
8558 | // Add all classes. |
8559 | AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false, |
8560 | false, Results); |
8561 | } |
8562 | |
8563 | Results.ExitScope(); |
8564 | |
8565 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
8566 | Results: Results.data(), NumResults: Results.size()); |
8567 | } |
8568 | |
8569 | void Sema::CodeCompleteObjCClassForwardDecl(Scope *S) { |
8570 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
8571 | CodeCompleter->getCodeCompletionTUInfo(), |
8572 | CodeCompletionContext::CCC_ObjCClassForwardDecl); |
8573 | Results.EnterNewScope(); |
8574 | |
8575 | if (CodeCompleter->includeGlobals()) { |
8576 | // Add all classes. |
8577 | AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false, |
8578 | false, Results); |
8579 | } |
8580 | |
8581 | Results.ExitScope(); |
8582 | |
8583 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
8584 | Results: Results.data(), NumResults: Results.size()); |
8585 | } |
8586 | |
8587 | void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName, |
8588 | SourceLocation ClassNameLoc) { |
8589 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
8590 | CodeCompleter->getCodeCompletionTUInfo(), |
8591 | CodeCompletionContext::CCC_ObjCInterfaceName); |
8592 | Results.EnterNewScope(); |
8593 | |
8594 | // Make sure that we ignore the class we're currently defining. |
8595 | NamedDecl *CurClass = |
8596 | LookupSingleName(S: TUScope, Name: ClassName, Loc: ClassNameLoc, NameKind: LookupOrdinaryName); |
8597 | if (CurClass && isa<ObjCInterfaceDecl>(Val: CurClass)) |
8598 | Results.Ignore(CurClass); |
8599 | |
8600 | if (CodeCompleter->includeGlobals()) { |
8601 | // Add all classes. |
8602 | AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false, |
8603 | false, Results); |
8604 | } |
8605 | |
8606 | Results.ExitScope(); |
8607 | |
8608 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
8609 | Results: Results.data(), NumResults: Results.size()); |
8610 | } |
8611 | |
8612 | void Sema::CodeCompleteObjCImplementationDecl(Scope *S) { |
8613 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
8614 | CodeCompleter->getCodeCompletionTUInfo(), |
8615 | CodeCompletionContext::CCC_ObjCImplementation); |
8616 | Results.EnterNewScope(); |
8617 | |
8618 | if (CodeCompleter->includeGlobals()) { |
8619 | // Add all unimplemented classes. |
8620 | AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false, |
8621 | true, Results); |
8622 | } |
8623 | |
8624 | Results.ExitScope(); |
8625 | |
8626 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
8627 | Results: Results.data(), NumResults: Results.size()); |
8628 | } |
8629 | |
8630 | void Sema::CodeCompleteObjCInterfaceCategory(Scope *S, |
8631 | IdentifierInfo *ClassName, |
8632 | SourceLocation ClassNameLoc) { |
8633 | typedef CodeCompletionResult Result; |
8634 | |
8635 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
8636 | CodeCompleter->getCodeCompletionTUInfo(), |
8637 | CodeCompletionContext::CCC_ObjCCategoryName); |
8638 | |
8639 | // Ignore any categories we find that have already been implemented by this |
8640 | // interface. |
8641 | llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames; |
8642 | NamedDecl *CurClass = |
8643 | LookupSingleName(S: TUScope, Name: ClassName, Loc: ClassNameLoc, NameKind: LookupOrdinaryName); |
8644 | if (ObjCInterfaceDecl *Class = |
8645 | dyn_cast_or_null<ObjCInterfaceDecl>(Val: CurClass)) { |
8646 | for (const auto *Cat : Class->visible_categories()) |
8647 | CategoryNames.insert(Cat->getIdentifier()); |
8648 | } |
8649 | |
8650 | // Add all of the categories we know about. |
8651 | Results.EnterNewScope(); |
8652 | TranslationUnitDecl *TU = Context.getTranslationUnitDecl(); |
8653 | for (const auto *D : TU->decls()) |
8654 | if (const auto *Category = dyn_cast<ObjCCategoryDecl>(D)) |
8655 | if (CategoryNames.insert(Category->getIdentifier()).second) |
8656 | Results.AddResult( |
8657 | Result(Category, Results.getBasePriority(Category), nullptr), |
8658 | CurContext, nullptr, false); |
8659 | Results.ExitScope(); |
8660 | |
8661 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
8662 | Results: Results.data(), NumResults: Results.size()); |
8663 | } |
8664 | |
8665 | void Sema::CodeCompleteObjCImplementationCategory(Scope *S, |
8666 | IdentifierInfo *ClassName, |
8667 | SourceLocation ClassNameLoc) { |
8668 | typedef CodeCompletionResult Result; |
8669 | |
8670 | // Find the corresponding interface. If we couldn't find the interface, the |
8671 | // program itself is ill-formed. However, we'll try to be helpful still by |
8672 | // providing the list of all of the categories we know about. |
8673 | NamedDecl *CurClass = |
8674 | LookupSingleName(S: TUScope, Name: ClassName, Loc: ClassNameLoc, NameKind: LookupOrdinaryName); |
8675 | ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(Val: CurClass); |
8676 | if (!Class) |
8677 | return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc); |
8678 | |
8679 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
8680 | CodeCompleter->getCodeCompletionTUInfo(), |
8681 | CodeCompletionContext::CCC_ObjCCategoryName); |
8682 | |
8683 | // Add all of the categories that have corresponding interface |
8684 | // declarations in this class and any of its superclasses, except for |
8685 | // already-implemented categories in the class itself. |
8686 | llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames; |
8687 | Results.EnterNewScope(); |
8688 | bool IgnoreImplemented = true; |
8689 | while (Class) { |
8690 | for (const auto *Cat : Class->visible_categories()) { |
8691 | if ((!IgnoreImplemented || !Cat->getImplementation()) && |
8692 | CategoryNames.insert(Cat->getIdentifier()).second) |
8693 | Results.AddResult(R: Result(Cat, Results.getBasePriority(Cat), nullptr), |
8694 | CurContext, Hiding: nullptr, InBaseClass: false); |
8695 | } |
8696 | |
8697 | Class = Class->getSuperClass(); |
8698 | IgnoreImplemented = false; |
8699 | } |
8700 | Results.ExitScope(); |
8701 | |
8702 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
8703 | Results: Results.data(), NumResults: Results.size()); |
8704 | } |
8705 | |
8706 | void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) { |
8707 | CodeCompletionContext CCContext(CodeCompletionContext::CCC_Other); |
8708 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
8709 | CodeCompleter->getCodeCompletionTUInfo(), CCContext); |
8710 | |
8711 | // Figure out where this @synthesize lives. |
8712 | ObjCContainerDecl *Container = |
8713 | dyn_cast_or_null<ObjCContainerDecl>(Val: CurContext); |
8714 | if (!Container || (!isa<ObjCImplementationDecl>(Val: Container) && |
8715 | !isa<ObjCCategoryImplDecl>(Val: Container))) |
8716 | return; |
8717 | |
8718 | // Ignore any properties that have already been implemented. |
8719 | Container = getContainerDef(Container); |
8720 | for (const auto *D : Container->decls()) |
8721 | if (const auto *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(D)) |
8722 | Results.Ignore(PropertyImpl->getPropertyDecl()); |
8723 | |
8724 | // Add any properties that we find. |
8725 | AddedPropertiesSet AddedProperties; |
8726 | Results.EnterNewScope(); |
8727 | if (ObjCImplementationDecl *ClassImpl = |
8728 | dyn_cast<ObjCImplementationDecl>(Val: Container)) |
8729 | AddObjCProperties(CCContext, ClassImpl->getClassInterface(), false, |
8730 | /*AllowNullaryMethods=*/false, CurContext, |
8731 | AddedProperties, Results); |
8732 | else |
8733 | AddObjCProperties(CCContext, |
8734 | cast<ObjCCategoryImplDecl>(Val: Container)->getCategoryDecl(), |
8735 | false, /*AllowNullaryMethods=*/false, CurContext, |
8736 | AddedProperties, Results); |
8737 | Results.ExitScope(); |
8738 | |
8739 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
8740 | Results: Results.data(), NumResults: Results.size()); |
8741 | } |
8742 | |
8743 | void Sema::CodeCompleteObjCPropertySynthesizeIvar( |
8744 | Scope *S, IdentifierInfo *PropertyName) { |
8745 | typedef CodeCompletionResult Result; |
8746 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
8747 | CodeCompleter->getCodeCompletionTUInfo(), |
8748 | CodeCompletionContext::CCC_Other); |
8749 | |
8750 | // Figure out where this @synthesize lives. |
8751 | ObjCContainerDecl *Container = |
8752 | dyn_cast_or_null<ObjCContainerDecl>(Val: CurContext); |
8753 | if (!Container || (!isa<ObjCImplementationDecl>(Val: Container) && |
8754 | !isa<ObjCCategoryImplDecl>(Val: Container))) |
8755 | return; |
8756 | |
8757 | // Figure out which interface we're looking into. |
8758 | ObjCInterfaceDecl *Class = nullptr; |
8759 | if (ObjCImplementationDecl *ClassImpl = |
8760 | dyn_cast<ObjCImplementationDecl>(Val: Container)) |
8761 | Class = ClassImpl->getClassInterface(); |
8762 | else |
8763 | Class = cast<ObjCCategoryImplDecl>(Val: Container) |
8764 | ->getCategoryDecl() |
8765 | ->getClassInterface(); |
8766 | |
8767 | // Determine the type of the property we're synthesizing. |
8768 | QualType PropertyType = Context.getObjCIdType(); |
8769 | if (Class) { |
8770 | if (ObjCPropertyDecl *Property = Class->FindPropertyDeclaration( |
8771 | PropertyName, ObjCPropertyQueryKind::OBJC_PR_query_instance)) { |
8772 | PropertyType = |
8773 | Property->getType().getNonReferenceType().getUnqualifiedType(); |
8774 | |
8775 | // Give preference to ivars |
8776 | Results.setPreferredType(PropertyType); |
8777 | } |
8778 | } |
8779 | |
8780 | // Add all of the instance variables in this class and its superclasses. |
8781 | Results.EnterNewScope(); |
8782 | bool SawSimilarlyNamedIvar = false; |
8783 | std::string NameWithPrefix; |
8784 | NameWithPrefix += '_'; |
8785 | NameWithPrefix += PropertyName->getName(); |
8786 | std::string NameWithSuffix = PropertyName->getName().str(); |
8787 | NameWithSuffix += '_'; |
8788 | for (; Class; Class = Class->getSuperClass()) { |
8789 | for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar; |
8790 | Ivar = Ivar->getNextIvar()) { |
8791 | Results.AddResult(R: Result(Ivar, Results.getBasePriority(Ivar), nullptr), |
8792 | CurContext, Hiding: nullptr, InBaseClass: false); |
8793 | |
8794 | // Determine whether we've seen an ivar with a name similar to the |
8795 | // property. |
8796 | if ((PropertyName == Ivar->getIdentifier() || |
8797 | NameWithPrefix == Ivar->getName() || |
8798 | NameWithSuffix == Ivar->getName())) { |
8799 | SawSimilarlyNamedIvar = true; |
8800 | |
8801 | // Reduce the priority of this result by one, to give it a slight |
8802 | // advantage over other results whose names don't match so closely. |
8803 | if (Results.size() && |
8804 | Results.data()[Results.size() - 1].Kind == |
8805 | CodeCompletionResult::RK_Declaration && |
8806 | Results.data()[Results.size() - 1].Declaration == Ivar) |
8807 | Results.data()[Results.size() - 1].Priority--; |
8808 | } |
8809 | } |
8810 | } |
8811 | |
8812 | if (!SawSimilarlyNamedIvar) { |
8813 | // Create ivar result _propName, that the user can use to synthesize |
8814 | // an ivar of the appropriate type. |
8815 | unsigned Priority = CCP_MemberDeclaration + 1; |
8816 | typedef CodeCompletionResult Result; |
8817 | CodeCompletionAllocator &Allocator = Results.getAllocator(); |
8818 | CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo(), |
8819 | Priority, CXAvailability_Available); |
8820 | |
8821 | PrintingPolicy Policy = getCompletionPrintingPolicy(S&: *this); |
8822 | Builder.AddResultTypeChunk( |
8823 | ResultType: GetCompletionTypeString(T: PropertyType, Context, Policy, Allocator)); |
8824 | Builder.AddTypedTextChunk(Text: Allocator.CopyString(String: NameWithPrefix)); |
8825 | Results.AddResult( |
8826 | R: Result(Builder.TakeString(), Priority, CXCursor_ObjCIvarDecl)); |
8827 | } |
8828 | |
8829 | Results.ExitScope(); |
8830 | |
8831 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
8832 | Results: Results.data(), NumResults: Results.size()); |
8833 | } |
8834 | |
8835 | // Mapping from selectors to the methods that implement that selector, along |
8836 | // with the "in original class" flag. |
8837 | typedef llvm::DenseMap<Selector, |
8838 | llvm::PointerIntPair<ObjCMethodDecl *, 1, bool>> |
8839 | KnownMethodsMap; |
8840 | |
8841 | /// Find all of the methods that reside in the given container |
8842 | /// (and its superclasses, protocols, etc.) that meet the given |
8843 | /// criteria. Insert those methods into the map of known methods, |
8844 | /// indexed by selector so they can be easily found. |
8845 | static void FindImplementableMethods(ASTContext &Context, |
8846 | ObjCContainerDecl *Container, |
8847 | std::optional<bool> WantInstanceMethods, |
8848 | QualType ReturnType, |
8849 | KnownMethodsMap &KnownMethods, |
8850 | bool InOriginalClass = true) { |
8851 | if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Val: Container)) { |
8852 | // Make sure we have a definition; that's what we'll walk. |
8853 | if (!IFace->hasDefinition()) |
8854 | return; |
8855 | |
8856 | IFace = IFace->getDefinition(); |
8857 | Container = IFace; |
8858 | |
8859 | const ObjCList<ObjCProtocolDecl> &Protocols = |
8860 | IFace->getReferencedProtocols(); |
8861 | for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), |
8862 | E = Protocols.end(); |
8863 | I != E; ++I) |
8864 | FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, |
8865 | KnownMethods, InOriginalClass); |
8866 | |
8867 | // Add methods from any class extensions and categories. |
8868 | for (auto *Cat : IFace->visible_categories()) { |
8869 | FindImplementableMethods(Context, Cat, WantInstanceMethods, ReturnType, |
8870 | KnownMethods, false); |
8871 | } |
8872 | |
8873 | // Visit the superclass. |
8874 | if (IFace->getSuperClass()) |
8875 | FindImplementableMethods(Context, IFace->getSuperClass(), |
8876 | WantInstanceMethods, ReturnType, KnownMethods, |
8877 | false); |
8878 | } |
8879 | |
8880 | if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Val: Container)) { |
8881 | // Recurse into protocols. |
8882 | const ObjCList<ObjCProtocolDecl> &Protocols = |
8883 | Category->getReferencedProtocols(); |
8884 | for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), |
8885 | E = Protocols.end(); |
8886 | I != E; ++I) |
8887 | FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, |
8888 | KnownMethods, InOriginalClass); |
8889 | |
8890 | // If this category is the original class, jump to the interface. |
8891 | if (InOriginalClass && Category->getClassInterface()) |
8892 | FindImplementableMethods(Context, Category->getClassInterface(), |
8893 | WantInstanceMethods, ReturnType, KnownMethods, |
8894 | false); |
8895 | } |
8896 | |
8897 | if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Val: Container)) { |
8898 | // Make sure we have a definition; that's what we'll walk. |
8899 | if (!Protocol->hasDefinition()) |
8900 | return; |
8901 | Protocol = Protocol->getDefinition(); |
8902 | Container = Protocol; |
8903 | |
8904 | // Recurse into protocols. |
8905 | const ObjCList<ObjCProtocolDecl> &Protocols = |
8906 | Protocol->getReferencedProtocols(); |
8907 | for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(), |
8908 | E = Protocols.end(); |
8909 | I != E; ++I) |
8910 | FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType, |
8911 | KnownMethods, false); |
8912 | } |
8913 | |
8914 | // Add methods in this container. This operation occurs last because |
8915 | // we want the methods from this container to override any methods |
8916 | // we've previously seen with the same selector. |
8917 | for (auto *M : Container->methods()) { |
8918 | if (!WantInstanceMethods || M->isInstanceMethod() == *WantInstanceMethods) { |
8919 | if (!ReturnType.isNull() && |
8920 | !Context.hasSameUnqualifiedType(T1: ReturnType, T2: M->getReturnType())) |
8921 | continue; |
8922 | |
8923 | KnownMethods[M->getSelector()] = |
8924 | KnownMethodsMap::mapped_type(M, InOriginalClass); |
8925 | } |
8926 | } |
8927 | } |
8928 | |
8929 | /// Add the parenthesized return or parameter type chunk to a code |
8930 | /// completion string. |
8931 | static void AddObjCPassingTypeChunk(QualType Type, unsigned ObjCDeclQuals, |
8932 | ASTContext &Context, |
8933 | const PrintingPolicy &Policy, |
8934 | CodeCompletionBuilder &Builder) { |
8935 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
8936 | std::string Quals = formatObjCParamQualifiers(ObjCQuals: ObjCDeclQuals, Type); |
8937 | if (!Quals.empty()) |
8938 | Builder.AddTextChunk(Text: Builder.getAllocator().CopyString(String: Quals)); |
8939 | Builder.AddTextChunk( |
8940 | Text: GetCompletionTypeString(T: Type, Context, Policy, Allocator&: Builder.getAllocator())); |
8941 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
8942 | } |
8943 | |
8944 | /// Determine whether the given class is or inherits from a class by |
8945 | /// the given name. |
8946 | static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class, StringRef Name) { |
8947 | if (!Class) |
8948 | return false; |
8949 | |
8950 | if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name) |
8951 | return true; |
8952 | |
8953 | return InheritsFromClassNamed(Class: Class->getSuperClass(), Name); |
8954 | } |
8955 | |
8956 | /// Add code completions for Objective-C Key-Value Coding (KVC) and |
8957 | /// Key-Value Observing (KVO). |
8958 | static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property, |
8959 | bool IsInstanceMethod, |
8960 | QualType ReturnType, ASTContext &Context, |
8961 | VisitedSelectorSet &KnownSelectors, |
8962 | ResultBuilder &Results) { |
8963 | IdentifierInfo *PropName = Property->getIdentifier(); |
8964 | if (!PropName || PropName->getLength() == 0) |
8965 | return; |
8966 | |
8967 | PrintingPolicy Policy = getCompletionPrintingPolicy(S&: Results.getSema()); |
8968 | |
8969 | // Builder that will create each code completion. |
8970 | typedef CodeCompletionResult Result; |
8971 | CodeCompletionAllocator &Allocator = Results.getAllocator(); |
8972 | CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo()); |
8973 | |
8974 | // The selector table. |
8975 | SelectorTable &Selectors = Context.Selectors; |
8976 | |
8977 | // The property name, copied into the code completion allocation region |
8978 | // on demand. |
8979 | struct KeyHolder { |
8980 | CodeCompletionAllocator &Allocator; |
8981 | StringRef Key; |
8982 | const char *CopiedKey; |
8983 | |
8984 | KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key) |
8985 | : Allocator(Allocator), Key(Key), CopiedKey(nullptr) {} |
8986 | |
8987 | operator const char *() { |
8988 | if (CopiedKey) |
8989 | return CopiedKey; |
8990 | |
8991 | return CopiedKey = Allocator.CopyString(String: Key); |
8992 | } |
8993 | } Key(Allocator, PropName->getName()); |
8994 | |
8995 | // The uppercased name of the property name. |
8996 | std::string UpperKey = std::string(PropName->getName()); |
8997 | if (!UpperKey.empty()) |
8998 | UpperKey[0] = toUppercase(c: UpperKey[0]); |
8999 | |
9000 | bool ReturnTypeMatchesProperty = |
9001 | ReturnType.isNull() || |
9002 | Context.hasSameUnqualifiedType(T1: ReturnType.getNonReferenceType(), |
9003 | T2: Property->getType()); |
9004 | bool ReturnTypeMatchesVoid = ReturnType.isNull() || ReturnType->isVoidType(); |
9005 | |
9006 | // Add the normal accessor -(type)key. |
9007 | if (IsInstanceMethod && |
9008 | KnownSelectors.insert(Ptr: Selectors.getNullarySelector(ID: PropName)).second && |
9009 | ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) { |
9010 | if (ReturnType.isNull()) |
9011 | AddObjCPassingTypeChunk(Type: Property->getType(), /*Quals=*/ObjCDeclQuals: 0, Context, Policy, |
9012 | Builder); |
9013 | |
9014 | Builder.AddTypedTextChunk(Text: Key); |
9015 | Results.AddResult(R: Result(Builder.TakeString(), CCP_CodePattern, |
9016 | CXCursor_ObjCInstanceMethodDecl)); |
9017 | } |
9018 | |
9019 | // If we have an integral or boolean property (or the user has provided |
9020 | // an integral or boolean return type), add the accessor -(type)isKey. |
9021 | if (IsInstanceMethod && |
9022 | ((!ReturnType.isNull() && |
9023 | (ReturnType->isIntegerType() || ReturnType->isBooleanType())) || |
9024 | (ReturnType.isNull() && (Property->getType()->isIntegerType() || |
9025 | Property->getType()->isBooleanType())))) { |
9026 | std::string SelectorName = (Twine("is" ) + UpperKey).str(); |
9027 | IdentifierInfo *SelectorId = &Context.Idents.get(Name: SelectorName); |
9028 | if (KnownSelectors.insert(Ptr: Selectors.getNullarySelector(ID: SelectorId)) |
9029 | .second) { |
9030 | if (ReturnType.isNull()) { |
9031 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
9032 | Builder.AddTextChunk(Text: "BOOL" ); |
9033 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
9034 | } |
9035 | |
9036 | Builder.AddTypedTextChunk(Text: Allocator.CopyString(String: SelectorId->getName())); |
9037 | Results.AddResult(R: Result(Builder.TakeString(), CCP_CodePattern, |
9038 | CXCursor_ObjCInstanceMethodDecl)); |
9039 | } |
9040 | } |
9041 | |
9042 | // Add the normal mutator. |
9043 | if (IsInstanceMethod && ReturnTypeMatchesVoid && |
9044 | !Property->getSetterMethodDecl()) { |
9045 | std::string SelectorName = (Twine("set" ) + UpperKey).str(); |
9046 | IdentifierInfo *SelectorId = &Context.Idents.get(Name: SelectorName); |
9047 | if (KnownSelectors.insert(Ptr: Selectors.getUnarySelector(ID: SelectorId)).second) { |
9048 | if (ReturnType.isNull()) { |
9049 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
9050 | Builder.AddTextChunk(Text: "void" ); |
9051 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
9052 | } |
9053 | |
9054 | Builder.AddTypedTextChunk( |
9055 | Text: Allocator.CopyString(String: SelectorId->getName() + ":" )); |
9056 | AddObjCPassingTypeChunk(Type: Property->getType(), /*Quals=*/ObjCDeclQuals: 0, Context, Policy, |
9057 | Builder); |
9058 | Builder.AddTextChunk(Text: Key); |
9059 | Results.AddResult(R: Result(Builder.TakeString(), CCP_CodePattern, |
9060 | CXCursor_ObjCInstanceMethodDecl)); |
9061 | } |
9062 | } |
9063 | |
9064 | // Indexed and unordered accessors |
9065 | unsigned IndexedGetterPriority = CCP_CodePattern; |
9066 | unsigned IndexedSetterPriority = CCP_CodePattern; |
9067 | unsigned UnorderedGetterPriority = CCP_CodePattern; |
9068 | unsigned UnorderedSetterPriority = CCP_CodePattern; |
9069 | if (const auto *ObjCPointer = |
9070 | Property->getType()->getAs<ObjCObjectPointerType>()) { |
9071 | if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) { |
9072 | // If this interface type is not provably derived from a known |
9073 | // collection, penalize the corresponding completions. |
9074 | if (!InheritsFromClassNamed(Class: IFace, Name: "NSMutableArray" )) { |
9075 | IndexedSetterPriority += CCD_ProbablyNotObjCCollection; |
9076 | if (!InheritsFromClassNamed(Class: IFace, Name: "NSArray" )) |
9077 | IndexedGetterPriority += CCD_ProbablyNotObjCCollection; |
9078 | } |
9079 | |
9080 | if (!InheritsFromClassNamed(Class: IFace, Name: "NSMutableSet" )) { |
9081 | UnorderedSetterPriority += CCD_ProbablyNotObjCCollection; |
9082 | if (!InheritsFromClassNamed(Class: IFace, Name: "NSSet" )) |
9083 | UnorderedGetterPriority += CCD_ProbablyNotObjCCollection; |
9084 | } |
9085 | } |
9086 | } else { |
9087 | IndexedGetterPriority += CCD_ProbablyNotObjCCollection; |
9088 | IndexedSetterPriority += CCD_ProbablyNotObjCCollection; |
9089 | UnorderedGetterPriority += CCD_ProbablyNotObjCCollection; |
9090 | UnorderedSetterPriority += CCD_ProbablyNotObjCCollection; |
9091 | } |
9092 | |
9093 | // Add -(NSUInteger)countOf<key> |
9094 | if (IsInstanceMethod && |
9095 | (ReturnType.isNull() || ReturnType->isIntegerType())) { |
9096 | std::string SelectorName = (Twine("countOf" ) + UpperKey).str(); |
9097 | IdentifierInfo *SelectorId = &Context.Idents.get(Name: SelectorName); |
9098 | if (KnownSelectors.insert(Ptr: Selectors.getNullarySelector(ID: SelectorId)) |
9099 | .second) { |
9100 | if (ReturnType.isNull()) { |
9101 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
9102 | Builder.AddTextChunk(Text: "NSUInteger" ); |
9103 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
9104 | } |
9105 | |
9106 | Builder.AddTypedTextChunk(Text: Allocator.CopyString(String: SelectorId->getName())); |
9107 | Results.AddResult( |
9108 | R: Result(Builder.TakeString(), |
9109 | std::min(a: IndexedGetterPriority, b: UnorderedGetterPriority), |
9110 | CXCursor_ObjCInstanceMethodDecl)); |
9111 | } |
9112 | } |
9113 | |
9114 | // Indexed getters |
9115 | // Add -(id)objectInKeyAtIndex:(NSUInteger)index |
9116 | if (IsInstanceMethod && |
9117 | (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) { |
9118 | std::string SelectorName = (Twine("objectIn" ) + UpperKey + "AtIndex" ).str(); |
9119 | IdentifierInfo *SelectorId = &Context.Idents.get(Name: SelectorName); |
9120 | if (KnownSelectors.insert(Ptr: Selectors.getUnarySelector(ID: SelectorId)).second) { |
9121 | if (ReturnType.isNull()) { |
9122 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
9123 | Builder.AddTextChunk(Text: "id" ); |
9124 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
9125 | } |
9126 | |
9127 | Builder.AddTypedTextChunk(Text: Allocator.CopyString(String: SelectorName + ":" )); |
9128 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
9129 | Builder.AddTextChunk(Text: "NSUInteger" ); |
9130 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
9131 | Builder.AddTextChunk(Text: "index" ); |
9132 | Results.AddResult(R: Result(Builder.TakeString(), IndexedGetterPriority, |
9133 | CXCursor_ObjCInstanceMethodDecl)); |
9134 | } |
9135 | } |
9136 | |
9137 | // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes |
9138 | if (IsInstanceMethod && |
9139 | (ReturnType.isNull() || |
9140 | (ReturnType->isObjCObjectPointerType() && |
9141 | ReturnType->castAs<ObjCObjectPointerType>()->getInterfaceDecl() && |
9142 | ReturnType->castAs<ObjCObjectPointerType>() |
9143 | ->getInterfaceDecl() |
9144 | ->getName() == "NSArray" ))) { |
9145 | std::string SelectorName = (Twine(Property->getName()) + "AtIndexes" ).str(); |
9146 | IdentifierInfo *SelectorId = &Context.Idents.get(Name: SelectorName); |
9147 | if (KnownSelectors.insert(Ptr: Selectors.getUnarySelector(ID: SelectorId)).second) { |
9148 | if (ReturnType.isNull()) { |
9149 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
9150 | Builder.AddTextChunk(Text: "NSArray *" ); |
9151 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
9152 | } |
9153 | |
9154 | Builder.AddTypedTextChunk(Text: Allocator.CopyString(String: SelectorName + ":" )); |
9155 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
9156 | Builder.AddTextChunk(Text: "NSIndexSet *" ); |
9157 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
9158 | Builder.AddTextChunk(Text: "indexes" ); |
9159 | Results.AddResult(R: Result(Builder.TakeString(), IndexedGetterPriority, |
9160 | CXCursor_ObjCInstanceMethodDecl)); |
9161 | } |
9162 | } |
9163 | |
9164 | // Add -(void)getKey:(type **)buffer range:(NSRange)inRange |
9165 | if (IsInstanceMethod && ReturnTypeMatchesVoid) { |
9166 | std::string SelectorName = (Twine("get" ) + UpperKey).str(); |
9167 | const IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(Name: SelectorName), |
9168 | &Context.Idents.get(Name: "range" )}; |
9169 | |
9170 | if (KnownSelectors.insert(Ptr: Selectors.getSelector(NumArgs: 2, IIV: SelectorIds)).second) { |
9171 | if (ReturnType.isNull()) { |
9172 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
9173 | Builder.AddTextChunk(Text: "void" ); |
9174 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
9175 | } |
9176 | |
9177 | Builder.AddTypedTextChunk(Text: Allocator.CopyString(String: SelectorName + ":" )); |
9178 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
9179 | Builder.AddPlaceholderChunk(Placeholder: "object-type" ); |
9180 | Builder.AddTextChunk(Text: " **" ); |
9181 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
9182 | Builder.AddTextChunk(Text: "buffer" ); |
9183 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
9184 | Builder.AddTypedTextChunk(Text: "range:" ); |
9185 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
9186 | Builder.AddTextChunk(Text: "NSRange" ); |
9187 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
9188 | Builder.AddTextChunk(Text: "inRange" ); |
9189 | Results.AddResult(R: Result(Builder.TakeString(), IndexedGetterPriority, |
9190 | CXCursor_ObjCInstanceMethodDecl)); |
9191 | } |
9192 | } |
9193 | |
9194 | // Mutable indexed accessors |
9195 | |
9196 | // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index |
9197 | if (IsInstanceMethod && ReturnTypeMatchesVoid) { |
9198 | std::string SelectorName = (Twine("in" ) + UpperKey + "AtIndex" ).str(); |
9199 | const IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(Name: "insertObject" ), |
9200 | &Context.Idents.get(Name: SelectorName)}; |
9201 | |
9202 | if (KnownSelectors.insert(Ptr: Selectors.getSelector(NumArgs: 2, IIV: SelectorIds)).second) { |
9203 | if (ReturnType.isNull()) { |
9204 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
9205 | Builder.AddTextChunk(Text: "void" ); |
9206 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
9207 | } |
9208 | |
9209 | Builder.AddTypedTextChunk(Text: "insertObject:" ); |
9210 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
9211 | Builder.AddPlaceholderChunk(Placeholder: "object-type" ); |
9212 | Builder.AddTextChunk(Text: " *" ); |
9213 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
9214 | Builder.AddTextChunk(Text: "object" ); |
9215 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
9216 | Builder.AddTypedTextChunk(Text: Allocator.CopyString(String: SelectorName + ":" )); |
9217 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
9218 | Builder.AddPlaceholderChunk(Placeholder: "NSUInteger" ); |
9219 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
9220 | Builder.AddTextChunk(Text: "index" ); |
9221 | Results.AddResult(R: Result(Builder.TakeString(), IndexedSetterPriority, |
9222 | CXCursor_ObjCInstanceMethodDecl)); |
9223 | } |
9224 | } |
9225 | |
9226 | // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes |
9227 | if (IsInstanceMethod && ReturnTypeMatchesVoid) { |
9228 | std::string SelectorName = (Twine("insert" ) + UpperKey).str(); |
9229 | const IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(Name: SelectorName), |
9230 | &Context.Idents.get(Name: "atIndexes" )}; |
9231 | |
9232 | if (KnownSelectors.insert(Ptr: Selectors.getSelector(NumArgs: 2, IIV: SelectorIds)).second) { |
9233 | if (ReturnType.isNull()) { |
9234 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
9235 | Builder.AddTextChunk(Text: "void" ); |
9236 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
9237 | } |
9238 | |
9239 | Builder.AddTypedTextChunk(Text: Allocator.CopyString(String: SelectorName + ":" )); |
9240 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
9241 | Builder.AddTextChunk(Text: "NSArray *" ); |
9242 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
9243 | Builder.AddTextChunk(Text: "array" ); |
9244 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
9245 | Builder.AddTypedTextChunk(Text: "atIndexes:" ); |
9246 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
9247 | Builder.AddPlaceholderChunk(Placeholder: "NSIndexSet *" ); |
9248 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
9249 | Builder.AddTextChunk(Text: "indexes" ); |
9250 | Results.AddResult(R: Result(Builder.TakeString(), IndexedSetterPriority, |
9251 | CXCursor_ObjCInstanceMethodDecl)); |
9252 | } |
9253 | } |
9254 | |
9255 | // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index |
9256 | if (IsInstanceMethod && ReturnTypeMatchesVoid) { |
9257 | std::string SelectorName = |
9258 | (Twine("removeObjectFrom" ) + UpperKey + "AtIndex" ).str(); |
9259 | const IdentifierInfo *SelectorId = &Context.Idents.get(Name: SelectorName); |
9260 | if (KnownSelectors.insert(Ptr: Selectors.getUnarySelector(ID: SelectorId)).second) { |
9261 | if (ReturnType.isNull()) { |
9262 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
9263 | Builder.AddTextChunk(Text: "void" ); |
9264 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
9265 | } |
9266 | |
9267 | Builder.AddTypedTextChunk(Text: Allocator.CopyString(String: SelectorName + ":" )); |
9268 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
9269 | Builder.AddTextChunk(Text: "NSUInteger" ); |
9270 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
9271 | Builder.AddTextChunk(Text: "index" ); |
9272 | Results.AddResult(R: Result(Builder.TakeString(), IndexedSetterPriority, |
9273 | CXCursor_ObjCInstanceMethodDecl)); |
9274 | } |
9275 | } |
9276 | |
9277 | // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes |
9278 | if (IsInstanceMethod && ReturnTypeMatchesVoid) { |
9279 | std::string SelectorName = (Twine("remove" ) + UpperKey + "AtIndexes" ).str(); |
9280 | const IdentifierInfo *SelectorId = &Context.Idents.get(Name: SelectorName); |
9281 | if (KnownSelectors.insert(Ptr: Selectors.getUnarySelector(ID: SelectorId)).second) { |
9282 | if (ReturnType.isNull()) { |
9283 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
9284 | Builder.AddTextChunk(Text: "void" ); |
9285 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
9286 | } |
9287 | |
9288 | Builder.AddTypedTextChunk(Text: Allocator.CopyString(String: SelectorName + ":" )); |
9289 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
9290 | Builder.AddTextChunk(Text: "NSIndexSet *" ); |
9291 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
9292 | Builder.AddTextChunk(Text: "indexes" ); |
9293 | Results.AddResult(R: Result(Builder.TakeString(), IndexedSetterPriority, |
9294 | CXCursor_ObjCInstanceMethodDecl)); |
9295 | } |
9296 | } |
9297 | |
9298 | // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object |
9299 | if (IsInstanceMethod && ReturnTypeMatchesVoid) { |
9300 | std::string SelectorName = |
9301 | (Twine("replaceObjectIn" ) + UpperKey + "AtIndex" ).str(); |
9302 | const IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(Name: SelectorName), |
9303 | &Context.Idents.get(Name: "withObject" )}; |
9304 | |
9305 | if (KnownSelectors.insert(Ptr: Selectors.getSelector(NumArgs: 2, IIV: SelectorIds)).second) { |
9306 | if (ReturnType.isNull()) { |
9307 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
9308 | Builder.AddTextChunk(Text: "void" ); |
9309 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
9310 | } |
9311 | |
9312 | Builder.AddTypedTextChunk(Text: Allocator.CopyString(String: SelectorName + ":" )); |
9313 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
9314 | Builder.AddPlaceholderChunk(Placeholder: "NSUInteger" ); |
9315 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
9316 | Builder.AddTextChunk(Text: "index" ); |
9317 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
9318 | Builder.AddTypedTextChunk(Text: "withObject:" ); |
9319 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
9320 | Builder.AddTextChunk(Text: "id" ); |
9321 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
9322 | Builder.AddTextChunk(Text: "object" ); |
9323 | Results.AddResult(R: Result(Builder.TakeString(), IndexedSetterPriority, |
9324 | CXCursor_ObjCInstanceMethodDecl)); |
9325 | } |
9326 | } |
9327 | |
9328 | // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array |
9329 | if (IsInstanceMethod && ReturnTypeMatchesVoid) { |
9330 | std::string SelectorName1 = |
9331 | (Twine("replace" ) + UpperKey + "AtIndexes" ).str(); |
9332 | std::string SelectorName2 = (Twine("with" ) + UpperKey).str(); |
9333 | const IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(Name: SelectorName1), |
9334 | &Context.Idents.get(Name: SelectorName2)}; |
9335 | |
9336 | if (KnownSelectors.insert(Ptr: Selectors.getSelector(NumArgs: 2, IIV: SelectorIds)).second) { |
9337 | if (ReturnType.isNull()) { |
9338 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
9339 | Builder.AddTextChunk(Text: "void" ); |
9340 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
9341 | } |
9342 | |
9343 | Builder.AddTypedTextChunk(Text: Allocator.CopyString(String: SelectorName1 + ":" )); |
9344 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
9345 | Builder.AddPlaceholderChunk(Placeholder: "NSIndexSet *" ); |
9346 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
9347 | Builder.AddTextChunk(Text: "indexes" ); |
9348 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
9349 | Builder.AddTypedTextChunk(Text: Allocator.CopyString(String: SelectorName2 + ":" )); |
9350 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
9351 | Builder.AddTextChunk(Text: "NSArray *" ); |
9352 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
9353 | Builder.AddTextChunk(Text: "array" ); |
9354 | Results.AddResult(R: Result(Builder.TakeString(), IndexedSetterPriority, |
9355 | CXCursor_ObjCInstanceMethodDecl)); |
9356 | } |
9357 | } |
9358 | |
9359 | // Unordered getters |
9360 | // - (NSEnumerator *)enumeratorOfKey |
9361 | if (IsInstanceMethod && |
9362 | (ReturnType.isNull() || |
9363 | (ReturnType->isObjCObjectPointerType() && |
9364 | ReturnType->castAs<ObjCObjectPointerType>()->getInterfaceDecl() && |
9365 | ReturnType->castAs<ObjCObjectPointerType>() |
9366 | ->getInterfaceDecl() |
9367 | ->getName() == "NSEnumerator" ))) { |
9368 | std::string SelectorName = (Twine("enumeratorOf" ) + UpperKey).str(); |
9369 | const IdentifierInfo *SelectorId = &Context.Idents.get(Name: SelectorName); |
9370 | if (KnownSelectors.insert(Ptr: Selectors.getNullarySelector(ID: SelectorId)) |
9371 | .second) { |
9372 | if (ReturnType.isNull()) { |
9373 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
9374 | Builder.AddTextChunk(Text: "NSEnumerator *" ); |
9375 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
9376 | } |
9377 | |
9378 | Builder.AddTypedTextChunk(Text: Allocator.CopyString(String: SelectorName)); |
9379 | Results.AddResult(R: Result(Builder.TakeString(), UnorderedGetterPriority, |
9380 | CXCursor_ObjCInstanceMethodDecl)); |
9381 | } |
9382 | } |
9383 | |
9384 | // - (type *)memberOfKey:(type *)object |
9385 | if (IsInstanceMethod && |
9386 | (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) { |
9387 | std::string SelectorName = (Twine("memberOf" ) + UpperKey).str(); |
9388 | const IdentifierInfo *SelectorId = &Context.Idents.get(Name: SelectorName); |
9389 | if (KnownSelectors.insert(Ptr: Selectors.getUnarySelector(ID: SelectorId)).second) { |
9390 | if (ReturnType.isNull()) { |
9391 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
9392 | Builder.AddPlaceholderChunk(Placeholder: "object-type" ); |
9393 | Builder.AddTextChunk(Text: " *" ); |
9394 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
9395 | } |
9396 | |
9397 | Builder.AddTypedTextChunk(Text: Allocator.CopyString(String: SelectorName + ":" )); |
9398 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
9399 | if (ReturnType.isNull()) { |
9400 | Builder.AddPlaceholderChunk(Placeholder: "object-type" ); |
9401 | Builder.AddTextChunk(Text: " *" ); |
9402 | } else { |
9403 | Builder.AddTextChunk(Text: GetCompletionTypeString( |
9404 | T: ReturnType, Context, Policy, Allocator&: Builder.getAllocator())); |
9405 | } |
9406 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
9407 | Builder.AddTextChunk(Text: "object" ); |
9408 | Results.AddResult(R: Result(Builder.TakeString(), UnorderedGetterPriority, |
9409 | CXCursor_ObjCInstanceMethodDecl)); |
9410 | } |
9411 | } |
9412 | |
9413 | // Mutable unordered accessors |
9414 | // - (void)addKeyObject:(type *)object |
9415 | if (IsInstanceMethod && ReturnTypeMatchesVoid) { |
9416 | std::string SelectorName = |
9417 | (Twine("add" ) + UpperKey + Twine("Object" )).str(); |
9418 | const IdentifierInfo *SelectorId = &Context.Idents.get(Name: SelectorName); |
9419 | if (KnownSelectors.insert(Ptr: Selectors.getUnarySelector(ID: SelectorId)).second) { |
9420 | if (ReturnType.isNull()) { |
9421 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
9422 | Builder.AddTextChunk(Text: "void" ); |
9423 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
9424 | } |
9425 | |
9426 | Builder.AddTypedTextChunk(Text: Allocator.CopyString(String: SelectorName + ":" )); |
9427 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
9428 | Builder.AddPlaceholderChunk(Placeholder: "object-type" ); |
9429 | Builder.AddTextChunk(Text: " *" ); |
9430 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
9431 | Builder.AddTextChunk(Text: "object" ); |
9432 | Results.AddResult(R: Result(Builder.TakeString(), UnorderedSetterPriority, |
9433 | CXCursor_ObjCInstanceMethodDecl)); |
9434 | } |
9435 | } |
9436 | |
9437 | // - (void)addKey:(NSSet *)objects |
9438 | if (IsInstanceMethod && ReturnTypeMatchesVoid) { |
9439 | std::string SelectorName = (Twine("add" ) + UpperKey).str(); |
9440 | const IdentifierInfo *SelectorId = &Context.Idents.get(Name: SelectorName); |
9441 | if (KnownSelectors.insert(Ptr: Selectors.getUnarySelector(ID: SelectorId)).second) { |
9442 | if (ReturnType.isNull()) { |
9443 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
9444 | Builder.AddTextChunk(Text: "void" ); |
9445 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
9446 | } |
9447 | |
9448 | Builder.AddTypedTextChunk(Text: Allocator.CopyString(String: SelectorName + ":" )); |
9449 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
9450 | Builder.AddTextChunk(Text: "NSSet *" ); |
9451 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
9452 | Builder.AddTextChunk(Text: "objects" ); |
9453 | Results.AddResult(R: Result(Builder.TakeString(), UnorderedSetterPriority, |
9454 | CXCursor_ObjCInstanceMethodDecl)); |
9455 | } |
9456 | } |
9457 | |
9458 | // - (void)removeKeyObject:(type *)object |
9459 | if (IsInstanceMethod && ReturnTypeMatchesVoid) { |
9460 | std::string SelectorName = |
9461 | (Twine("remove" ) + UpperKey + Twine("Object" )).str(); |
9462 | const IdentifierInfo *SelectorId = &Context.Idents.get(Name: SelectorName); |
9463 | if (KnownSelectors.insert(Ptr: Selectors.getUnarySelector(ID: SelectorId)).second) { |
9464 | if (ReturnType.isNull()) { |
9465 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
9466 | Builder.AddTextChunk(Text: "void" ); |
9467 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
9468 | } |
9469 | |
9470 | Builder.AddTypedTextChunk(Text: Allocator.CopyString(String: SelectorName + ":" )); |
9471 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
9472 | Builder.AddPlaceholderChunk(Placeholder: "object-type" ); |
9473 | Builder.AddTextChunk(Text: " *" ); |
9474 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
9475 | Builder.AddTextChunk(Text: "object" ); |
9476 | Results.AddResult(R: Result(Builder.TakeString(), UnorderedSetterPriority, |
9477 | CXCursor_ObjCInstanceMethodDecl)); |
9478 | } |
9479 | } |
9480 | |
9481 | // - (void)removeKey:(NSSet *)objects |
9482 | if (IsInstanceMethod && ReturnTypeMatchesVoid) { |
9483 | std::string SelectorName = (Twine("remove" ) + UpperKey).str(); |
9484 | const IdentifierInfo *SelectorId = &Context.Idents.get(Name: SelectorName); |
9485 | if (KnownSelectors.insert(Ptr: Selectors.getUnarySelector(ID: SelectorId)).second) { |
9486 | if (ReturnType.isNull()) { |
9487 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
9488 | Builder.AddTextChunk(Text: "void" ); |
9489 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
9490 | } |
9491 | |
9492 | Builder.AddTypedTextChunk(Text: Allocator.CopyString(String: SelectorName + ":" )); |
9493 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
9494 | Builder.AddTextChunk(Text: "NSSet *" ); |
9495 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
9496 | Builder.AddTextChunk(Text: "objects" ); |
9497 | Results.AddResult(R: Result(Builder.TakeString(), UnorderedSetterPriority, |
9498 | CXCursor_ObjCInstanceMethodDecl)); |
9499 | } |
9500 | } |
9501 | |
9502 | // - (void)intersectKey:(NSSet *)objects |
9503 | if (IsInstanceMethod && ReturnTypeMatchesVoid) { |
9504 | std::string SelectorName = (Twine("intersect" ) + UpperKey).str(); |
9505 | const IdentifierInfo *SelectorId = &Context.Idents.get(Name: SelectorName); |
9506 | if (KnownSelectors.insert(Ptr: Selectors.getUnarySelector(ID: SelectorId)).second) { |
9507 | if (ReturnType.isNull()) { |
9508 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
9509 | Builder.AddTextChunk(Text: "void" ); |
9510 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
9511 | } |
9512 | |
9513 | Builder.AddTypedTextChunk(Text: Allocator.CopyString(String: SelectorName + ":" )); |
9514 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
9515 | Builder.AddTextChunk(Text: "NSSet *" ); |
9516 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
9517 | Builder.AddTextChunk(Text: "objects" ); |
9518 | Results.AddResult(R: Result(Builder.TakeString(), UnorderedSetterPriority, |
9519 | CXCursor_ObjCInstanceMethodDecl)); |
9520 | } |
9521 | } |
9522 | |
9523 | // Key-Value Observing |
9524 | // + (NSSet *)keyPathsForValuesAffectingKey |
9525 | if (!IsInstanceMethod && |
9526 | (ReturnType.isNull() || |
9527 | (ReturnType->isObjCObjectPointerType() && |
9528 | ReturnType->castAs<ObjCObjectPointerType>()->getInterfaceDecl() && |
9529 | ReturnType->castAs<ObjCObjectPointerType>() |
9530 | ->getInterfaceDecl() |
9531 | ->getName() == "NSSet" ))) { |
9532 | std::string SelectorName = |
9533 | (Twine("keyPathsForValuesAffecting" ) + UpperKey).str(); |
9534 | const IdentifierInfo *SelectorId = &Context.Idents.get(Name: SelectorName); |
9535 | if (KnownSelectors.insert(Ptr: Selectors.getNullarySelector(ID: SelectorId)) |
9536 | .second) { |
9537 | if (ReturnType.isNull()) { |
9538 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
9539 | Builder.AddTextChunk(Text: "NSSet<NSString *> *" ); |
9540 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
9541 | } |
9542 | |
9543 | Builder.AddTypedTextChunk(Text: Allocator.CopyString(String: SelectorName)); |
9544 | Results.AddResult(R: Result(Builder.TakeString(), CCP_CodePattern, |
9545 | CXCursor_ObjCClassMethodDecl)); |
9546 | } |
9547 | } |
9548 | |
9549 | // + (BOOL)automaticallyNotifiesObserversForKey |
9550 | if (!IsInstanceMethod && |
9551 | (ReturnType.isNull() || ReturnType->isIntegerType() || |
9552 | ReturnType->isBooleanType())) { |
9553 | std::string SelectorName = |
9554 | (Twine("automaticallyNotifiesObserversOf" ) + UpperKey).str(); |
9555 | const IdentifierInfo *SelectorId = &Context.Idents.get(Name: SelectorName); |
9556 | if (KnownSelectors.insert(Ptr: Selectors.getNullarySelector(ID: SelectorId)) |
9557 | .second) { |
9558 | if (ReturnType.isNull()) { |
9559 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
9560 | Builder.AddTextChunk(Text: "BOOL" ); |
9561 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
9562 | } |
9563 | |
9564 | Builder.AddTypedTextChunk(Text: Allocator.CopyString(String: SelectorName)); |
9565 | Results.AddResult(R: Result(Builder.TakeString(), CCP_CodePattern, |
9566 | CXCursor_ObjCClassMethodDecl)); |
9567 | } |
9568 | } |
9569 | } |
9570 | |
9571 | void Sema::CodeCompleteObjCMethodDecl(Scope *S, |
9572 | std::optional<bool> IsInstanceMethod, |
9573 | ParsedType ReturnTy) { |
9574 | // Determine the return type of the method we're declaring, if |
9575 | // provided. |
9576 | QualType ReturnType = GetTypeFromParser(Ty: ReturnTy); |
9577 | Decl *IDecl = nullptr; |
9578 | if (CurContext->isObjCContainer()) { |
9579 | ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(Val: CurContext); |
9580 | IDecl = OCD; |
9581 | } |
9582 | // Determine where we should start searching for methods. |
9583 | ObjCContainerDecl *SearchDecl = nullptr; |
9584 | bool IsInImplementation = false; |
9585 | if (Decl *D = IDecl) { |
9586 | if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(Val: D)) { |
9587 | SearchDecl = Impl->getClassInterface(); |
9588 | IsInImplementation = true; |
9589 | } else if (ObjCCategoryImplDecl *CatImpl = |
9590 | dyn_cast<ObjCCategoryImplDecl>(Val: D)) { |
9591 | SearchDecl = CatImpl->getCategoryDecl(); |
9592 | IsInImplementation = true; |
9593 | } else |
9594 | SearchDecl = dyn_cast<ObjCContainerDecl>(Val: D); |
9595 | } |
9596 | |
9597 | if (!SearchDecl && S) { |
9598 | if (DeclContext *DC = S->getEntity()) |
9599 | SearchDecl = dyn_cast<ObjCContainerDecl>(Val: DC); |
9600 | } |
9601 | |
9602 | if (!SearchDecl) { |
9603 | HandleCodeCompleteResults(S: this, CodeCompleter, |
9604 | Context: CodeCompletionContext::CCC_Other, Results: nullptr, NumResults: 0); |
9605 | return; |
9606 | } |
9607 | |
9608 | // Find all of the methods that we could declare/implement here. |
9609 | KnownMethodsMap KnownMethods; |
9610 | FindImplementableMethods(Context, Container: SearchDecl, WantInstanceMethods: IsInstanceMethod, ReturnType, |
9611 | KnownMethods); |
9612 | |
9613 | // Add declarations or definitions for each of the known methods. |
9614 | typedef CodeCompletionResult Result; |
9615 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
9616 | CodeCompleter->getCodeCompletionTUInfo(), |
9617 | CodeCompletionContext::CCC_Other); |
9618 | Results.EnterNewScope(); |
9619 | PrintingPolicy Policy = getCompletionPrintingPolicy(S&: *this); |
9620 | for (KnownMethodsMap::iterator M = KnownMethods.begin(), |
9621 | MEnd = KnownMethods.end(); |
9622 | M != MEnd; ++M) { |
9623 | ObjCMethodDecl *Method = M->second.getPointer(); |
9624 | CodeCompletionBuilder Builder(Results.getAllocator(), |
9625 | Results.getCodeCompletionTUInfo()); |
9626 | |
9627 | // Add the '-'/'+' prefix if it wasn't provided yet. |
9628 | if (!IsInstanceMethod) { |
9629 | Builder.AddTextChunk(Text: Method->isInstanceMethod() ? "-" : "+" ); |
9630 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
9631 | } |
9632 | |
9633 | // If the result type was not already provided, add it to the |
9634 | // pattern as (type). |
9635 | if (ReturnType.isNull()) { |
9636 | QualType ResTy = Method->getSendResultType().stripObjCKindOfType(ctx: Context); |
9637 | AttributedType::stripOuterNullability(T&: ResTy); |
9638 | AddObjCPassingTypeChunk(Type: ResTy, ObjCDeclQuals: Method->getObjCDeclQualifier(), Context, |
9639 | Policy, Builder); |
9640 | } |
9641 | |
9642 | Selector Sel = Method->getSelector(); |
9643 | |
9644 | if (Sel.isUnarySelector()) { |
9645 | // Unary selectors have no arguments. |
9646 | Builder.AddTypedTextChunk( |
9647 | Text: Builder.getAllocator().CopyString(String: Sel.getNameForSlot(argIndex: 0))); |
9648 | } else { |
9649 | // Add all parameters to the pattern. |
9650 | unsigned I = 0; |
9651 | for (ObjCMethodDecl::param_iterator P = Method->param_begin(), |
9652 | PEnd = Method->param_end(); |
9653 | P != PEnd; (void)++P, ++I) { |
9654 | // Add the part of the selector name. |
9655 | if (I == 0) |
9656 | Builder.AddTypedTextChunk( |
9657 | Text: Builder.getAllocator().CopyString(String: Sel.getNameForSlot(argIndex: I) + ":" )); |
9658 | else if (I < Sel.getNumArgs()) { |
9659 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
9660 | Builder.AddTypedTextChunk( |
9661 | Text: Builder.getAllocator().CopyString(String: Sel.getNameForSlot(argIndex: I) + ":" )); |
9662 | } else |
9663 | break; |
9664 | |
9665 | // Add the parameter type. |
9666 | QualType ParamType; |
9667 | if ((*P)->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) |
9668 | ParamType = (*P)->getType(); |
9669 | else |
9670 | ParamType = (*P)->getOriginalType(); |
9671 | ParamType = ParamType.substObjCTypeArgs( |
9672 | ctx&: Context, typeArgs: {}, context: ObjCSubstitutionContext::Parameter); |
9673 | AttributedType::stripOuterNullability(T&: ParamType); |
9674 | AddObjCPassingTypeChunk(Type: ParamType, ObjCDeclQuals: (*P)->getObjCDeclQualifier(), |
9675 | Context, Policy, Builder); |
9676 | |
9677 | if (IdentifierInfo *Id = (*P)->getIdentifier()) |
9678 | Builder.AddTextChunk( |
9679 | Text: Builder.getAllocator().CopyString(String: Id->getName())); |
9680 | } |
9681 | } |
9682 | |
9683 | if (Method->isVariadic()) { |
9684 | if (Method->param_size() > 0) |
9685 | Builder.AddChunk(CK: CodeCompletionString::CK_Comma); |
9686 | Builder.AddTextChunk(Text: "..." ); |
9687 | } |
9688 | |
9689 | if (IsInImplementation && Results.includeCodePatterns()) { |
9690 | // We will be defining the method here, so add a compound statement. |
9691 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
9692 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftBrace); |
9693 | Builder.AddChunk(CK: CodeCompletionString::CK_VerticalSpace); |
9694 | if (!Method->getReturnType()->isVoidType()) { |
9695 | // If the result type is not void, add a return clause. |
9696 | Builder.AddTextChunk(Text: "return" ); |
9697 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
9698 | Builder.AddPlaceholderChunk(Placeholder: "expression" ); |
9699 | Builder.AddChunk(CK: CodeCompletionString::CK_SemiColon); |
9700 | } else |
9701 | Builder.AddPlaceholderChunk(Placeholder: "statements" ); |
9702 | |
9703 | Builder.AddChunk(CK: CodeCompletionString::CK_VerticalSpace); |
9704 | Builder.AddChunk(CK: CodeCompletionString::CK_RightBrace); |
9705 | } |
9706 | |
9707 | unsigned Priority = CCP_CodePattern; |
9708 | auto R = Result(Builder.TakeString(), Method, Priority); |
9709 | if (!M->second.getInt()) |
9710 | setInBaseClass(R); |
9711 | Results.AddResult(std::move(R)); |
9712 | } |
9713 | |
9714 | // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of |
9715 | // the properties in this class and its categories. |
9716 | if (Context.getLangOpts().ObjC) { |
9717 | SmallVector<ObjCContainerDecl *, 4> Containers; |
9718 | Containers.push_back(Elt: SearchDecl); |
9719 | |
9720 | VisitedSelectorSet KnownSelectors; |
9721 | for (KnownMethodsMap::iterator M = KnownMethods.begin(), |
9722 | MEnd = KnownMethods.end(); |
9723 | M != MEnd; ++M) |
9724 | KnownSelectors.insert(M->first); |
9725 | |
9726 | ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Val: SearchDecl); |
9727 | if (!IFace) |
9728 | if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Val: SearchDecl)) |
9729 | IFace = Category->getClassInterface(); |
9730 | |
9731 | if (IFace) |
9732 | llvm::append_range(C&: Containers, R: IFace->visible_categories()); |
9733 | |
9734 | if (IsInstanceMethod) { |
9735 | for (unsigned I = 0, N = Containers.size(); I != N; ++I) |
9736 | for (auto *P : Containers[I]->instance_properties()) |
9737 | AddObjCKeyValueCompletions(Property: P, IsInstanceMethod: *IsInstanceMethod, ReturnType, Context, |
9738 | KnownSelectors, Results); |
9739 | } |
9740 | } |
9741 | |
9742 | Results.ExitScope(); |
9743 | |
9744 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
9745 | Results: Results.data(), NumResults: Results.size()); |
9746 | } |
9747 | |
9748 | void Sema::CodeCompleteObjCMethodDeclSelector( |
9749 | Scope *S, bool IsInstanceMethod, bool AtParameterName, ParsedType ReturnTy, |
9750 | ArrayRef<const IdentifierInfo *> SelIdents) { |
9751 | // If we have an external source, load the entire class method |
9752 | // pool from the AST file. |
9753 | if (ExternalSource) { |
9754 | for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); I != N; |
9755 | ++I) { |
9756 | Selector Sel = ExternalSource->GetExternalSelector(ID: I); |
9757 | if (Sel.isNull() || MethodPool.count(Sel)) |
9758 | continue; |
9759 | |
9760 | ReadMethodPool(Sel); |
9761 | } |
9762 | } |
9763 | |
9764 | // Build the set of methods we can see. |
9765 | typedef CodeCompletionResult Result; |
9766 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
9767 | CodeCompleter->getCodeCompletionTUInfo(), |
9768 | CodeCompletionContext::CCC_Other); |
9769 | |
9770 | if (ReturnTy) |
9771 | Results.setPreferredType(GetTypeFromParser(Ty: ReturnTy).getNonReferenceType()); |
9772 | |
9773 | Results.EnterNewScope(); |
9774 | for (GlobalMethodPool::iterator M = MethodPool.begin(), |
9775 | MEnd = MethodPool.end(); |
9776 | M != MEnd; ++M) { |
9777 | for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first |
9778 | : &M->second.second; |
9779 | MethList && MethList->getMethod(); MethList = MethList->getNext()) { |
9780 | if (!isAcceptableObjCMethod(Method: MethList->getMethod(), WantKind: MK_Any, SelIdents)) |
9781 | continue; |
9782 | |
9783 | if (AtParameterName) { |
9784 | // Suggest parameter names we've seen before. |
9785 | unsigned NumSelIdents = SelIdents.size(); |
9786 | if (NumSelIdents && |
9787 | NumSelIdents <= MethList->getMethod()->param_size()) { |
9788 | ParmVarDecl *Param = |
9789 | MethList->getMethod()->parameters()[NumSelIdents - 1]; |
9790 | if (Param->getIdentifier()) { |
9791 | CodeCompletionBuilder Builder(Results.getAllocator(), |
9792 | Results.getCodeCompletionTUInfo()); |
9793 | Builder.AddTypedTextChunk(Text: Builder.getAllocator().CopyString( |
9794 | String: Param->getIdentifier()->getName())); |
9795 | Results.AddResult(R: Builder.TakeString()); |
9796 | } |
9797 | } |
9798 | |
9799 | continue; |
9800 | } |
9801 | |
9802 | Result R(MethList->getMethod(), |
9803 | Results.getBasePriority(MethList->getMethod()), nullptr); |
9804 | R.StartParameter = SelIdents.size(); |
9805 | R.AllParametersAreInformative = false; |
9806 | R.DeclaringEntity = true; |
9807 | Results.MaybeAddResult(R, CurContext); |
9808 | } |
9809 | } |
9810 | |
9811 | Results.ExitScope(); |
9812 | |
9813 | if (!AtParameterName && !SelIdents.empty() && |
9814 | SelIdents.front()->getName().starts_with(Prefix: "init" )) { |
9815 | for (const auto &M : PP.macros()) { |
9816 | if (M.first->getName() != "NS_DESIGNATED_INITIALIZER" ) |
9817 | continue; |
9818 | Results.EnterNewScope(); |
9819 | CodeCompletionBuilder Builder(Results.getAllocator(), |
9820 | Results.getCodeCompletionTUInfo()); |
9821 | Builder.AddTypedTextChunk( |
9822 | Text: Builder.getAllocator().CopyString(String: M.first->getName())); |
9823 | Results.AddResult(R: CodeCompletionResult(Builder.TakeString(), CCP_Macro, |
9824 | CXCursor_MacroDefinition)); |
9825 | Results.ExitScope(); |
9826 | } |
9827 | } |
9828 | |
9829 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
9830 | Results: Results.data(), NumResults: Results.size()); |
9831 | } |
9832 | |
9833 | void Sema::CodeCompletePreprocessorDirective(bool InConditional) { |
9834 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
9835 | CodeCompleter->getCodeCompletionTUInfo(), |
9836 | CodeCompletionContext::CCC_PreprocessorDirective); |
9837 | Results.EnterNewScope(); |
9838 | |
9839 | // #if <condition> |
9840 | CodeCompletionBuilder Builder(Results.getAllocator(), |
9841 | Results.getCodeCompletionTUInfo()); |
9842 | Builder.AddTypedTextChunk(Text: "if" ); |
9843 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
9844 | Builder.AddPlaceholderChunk(Placeholder: "condition" ); |
9845 | Results.AddResult(R: Builder.TakeString()); |
9846 | |
9847 | // #ifdef <macro> |
9848 | Builder.AddTypedTextChunk(Text: "ifdef" ); |
9849 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
9850 | Builder.AddPlaceholderChunk(Placeholder: "macro" ); |
9851 | Results.AddResult(R: Builder.TakeString()); |
9852 | |
9853 | // #ifndef <macro> |
9854 | Builder.AddTypedTextChunk(Text: "ifndef" ); |
9855 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
9856 | Builder.AddPlaceholderChunk(Placeholder: "macro" ); |
9857 | Results.AddResult(R: Builder.TakeString()); |
9858 | |
9859 | if (InConditional) { |
9860 | // #elif <condition> |
9861 | Builder.AddTypedTextChunk(Text: "elif" ); |
9862 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
9863 | Builder.AddPlaceholderChunk(Placeholder: "condition" ); |
9864 | Results.AddResult(R: Builder.TakeString()); |
9865 | |
9866 | // #elifdef <macro> |
9867 | Builder.AddTypedTextChunk(Text: "elifdef" ); |
9868 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
9869 | Builder.AddPlaceholderChunk(Placeholder: "macro" ); |
9870 | Results.AddResult(R: Builder.TakeString()); |
9871 | |
9872 | // #elifndef <macro> |
9873 | Builder.AddTypedTextChunk(Text: "elifndef" ); |
9874 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
9875 | Builder.AddPlaceholderChunk(Placeholder: "macro" ); |
9876 | Results.AddResult(R: Builder.TakeString()); |
9877 | |
9878 | // #else |
9879 | Builder.AddTypedTextChunk(Text: "else" ); |
9880 | Results.AddResult(R: Builder.TakeString()); |
9881 | |
9882 | // #endif |
9883 | Builder.AddTypedTextChunk(Text: "endif" ); |
9884 | Results.AddResult(R: Builder.TakeString()); |
9885 | } |
9886 | |
9887 | // #include "header" |
9888 | Builder.AddTypedTextChunk(Text: "include" ); |
9889 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
9890 | Builder.AddTextChunk(Text: "\"" ); |
9891 | Builder.AddPlaceholderChunk(Placeholder: "header" ); |
9892 | Builder.AddTextChunk(Text: "\"" ); |
9893 | Results.AddResult(R: Builder.TakeString()); |
9894 | |
9895 | // #include <header> |
9896 | Builder.AddTypedTextChunk(Text: "include" ); |
9897 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
9898 | Builder.AddTextChunk(Text: "<" ); |
9899 | Builder.AddPlaceholderChunk(Placeholder: "header" ); |
9900 | Builder.AddTextChunk(Text: ">" ); |
9901 | Results.AddResult(R: Builder.TakeString()); |
9902 | |
9903 | // #define <macro> |
9904 | Builder.AddTypedTextChunk(Text: "define" ); |
9905 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
9906 | Builder.AddPlaceholderChunk(Placeholder: "macro" ); |
9907 | Results.AddResult(R: Builder.TakeString()); |
9908 | |
9909 | // #define <macro>(<args>) |
9910 | Builder.AddTypedTextChunk(Text: "define" ); |
9911 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
9912 | Builder.AddPlaceholderChunk(Placeholder: "macro" ); |
9913 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
9914 | Builder.AddPlaceholderChunk(Placeholder: "args" ); |
9915 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
9916 | Results.AddResult(R: Builder.TakeString()); |
9917 | |
9918 | // #undef <macro> |
9919 | Builder.AddTypedTextChunk(Text: "undef" ); |
9920 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
9921 | Builder.AddPlaceholderChunk(Placeholder: "macro" ); |
9922 | Results.AddResult(R: Builder.TakeString()); |
9923 | |
9924 | // #line <number> |
9925 | Builder.AddTypedTextChunk(Text: "line" ); |
9926 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
9927 | Builder.AddPlaceholderChunk(Placeholder: "number" ); |
9928 | Results.AddResult(R: Builder.TakeString()); |
9929 | |
9930 | // #line <number> "filename" |
9931 | Builder.AddTypedTextChunk(Text: "line" ); |
9932 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
9933 | Builder.AddPlaceholderChunk(Placeholder: "number" ); |
9934 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
9935 | Builder.AddTextChunk(Text: "\"" ); |
9936 | Builder.AddPlaceholderChunk(Placeholder: "filename" ); |
9937 | Builder.AddTextChunk(Text: "\"" ); |
9938 | Results.AddResult(R: Builder.TakeString()); |
9939 | |
9940 | // #error <message> |
9941 | Builder.AddTypedTextChunk(Text: "error" ); |
9942 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
9943 | Builder.AddPlaceholderChunk(Placeholder: "message" ); |
9944 | Results.AddResult(R: Builder.TakeString()); |
9945 | |
9946 | // #pragma <arguments> |
9947 | Builder.AddTypedTextChunk(Text: "pragma" ); |
9948 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
9949 | Builder.AddPlaceholderChunk(Placeholder: "arguments" ); |
9950 | Results.AddResult(R: Builder.TakeString()); |
9951 | |
9952 | if (getLangOpts().ObjC) { |
9953 | // #import "header" |
9954 | Builder.AddTypedTextChunk(Text: "import" ); |
9955 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
9956 | Builder.AddTextChunk(Text: "\"" ); |
9957 | Builder.AddPlaceholderChunk(Placeholder: "header" ); |
9958 | Builder.AddTextChunk(Text: "\"" ); |
9959 | Results.AddResult(R: Builder.TakeString()); |
9960 | |
9961 | // #import <header> |
9962 | Builder.AddTypedTextChunk(Text: "import" ); |
9963 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
9964 | Builder.AddTextChunk(Text: "<" ); |
9965 | Builder.AddPlaceholderChunk(Placeholder: "header" ); |
9966 | Builder.AddTextChunk(Text: ">" ); |
9967 | Results.AddResult(R: Builder.TakeString()); |
9968 | } |
9969 | |
9970 | // #include_next "header" |
9971 | Builder.AddTypedTextChunk(Text: "include_next" ); |
9972 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
9973 | Builder.AddTextChunk(Text: "\"" ); |
9974 | Builder.AddPlaceholderChunk(Placeholder: "header" ); |
9975 | Builder.AddTextChunk(Text: "\"" ); |
9976 | Results.AddResult(R: Builder.TakeString()); |
9977 | |
9978 | // #include_next <header> |
9979 | Builder.AddTypedTextChunk(Text: "include_next" ); |
9980 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
9981 | Builder.AddTextChunk(Text: "<" ); |
9982 | Builder.AddPlaceholderChunk(Placeholder: "header" ); |
9983 | Builder.AddTextChunk(Text: ">" ); |
9984 | Results.AddResult(R: Builder.TakeString()); |
9985 | |
9986 | // #warning <message> |
9987 | Builder.AddTypedTextChunk(Text: "warning" ); |
9988 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
9989 | Builder.AddPlaceholderChunk(Placeholder: "message" ); |
9990 | Results.AddResult(R: Builder.TakeString()); |
9991 | |
9992 | // Note: #ident and #sccs are such crazy anachronisms that we don't provide |
9993 | // completions for them. And __include_macros is a Clang-internal extension |
9994 | // that we don't want to encourage anyone to use. |
9995 | |
9996 | // FIXME: we don't support #assert or #unassert, so don't suggest them. |
9997 | Results.ExitScope(); |
9998 | |
9999 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
10000 | Results: Results.data(), NumResults: Results.size()); |
10001 | } |
10002 | |
10003 | void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) { |
10004 | CodeCompleteOrdinaryName(S, CompletionContext: S->getFnParent() ? Sema::PCC_RecoveryInFunction |
10005 | : Sema::PCC_Namespace); |
10006 | } |
10007 | |
10008 | void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) { |
10009 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
10010 | CodeCompleter->getCodeCompletionTUInfo(), |
10011 | IsDefinition ? CodeCompletionContext::CCC_MacroName |
10012 | : CodeCompletionContext::CCC_MacroNameUse); |
10013 | if (!IsDefinition && CodeCompleter->includeMacros()) { |
10014 | // Add just the names of macros, not their arguments. |
10015 | CodeCompletionBuilder Builder(Results.getAllocator(), |
10016 | Results.getCodeCompletionTUInfo()); |
10017 | Results.EnterNewScope(); |
10018 | for (Preprocessor::macro_iterator M = PP.macro_begin(), |
10019 | MEnd = PP.macro_end(); |
10020 | M != MEnd; ++M) { |
10021 | Builder.AddTypedTextChunk( |
10022 | Text: Builder.getAllocator().CopyString(String: M->first->getName())); |
10023 | Results.AddResult(R: CodeCompletionResult( |
10024 | Builder.TakeString(), CCP_CodePattern, CXCursor_MacroDefinition)); |
10025 | } |
10026 | Results.ExitScope(); |
10027 | } else if (IsDefinition) { |
10028 | // FIXME: Can we detect when the user just wrote an include guard above? |
10029 | } |
10030 | |
10031 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
10032 | Results: Results.data(), NumResults: Results.size()); |
10033 | } |
10034 | |
10035 | void Sema::CodeCompletePreprocessorExpression() { |
10036 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
10037 | CodeCompleter->getCodeCompletionTUInfo(), |
10038 | CodeCompletionContext::CCC_PreprocessorExpression); |
10039 | |
10040 | if (CodeCompleter->includeMacros()) |
10041 | AddMacroResults(PP, Results, LoadExternal: CodeCompleter->loadExternal(), IncludeUndefined: true); |
10042 | |
10043 | // defined (<macro>) |
10044 | Results.EnterNewScope(); |
10045 | CodeCompletionBuilder Builder(Results.getAllocator(), |
10046 | Results.getCodeCompletionTUInfo()); |
10047 | Builder.AddTypedTextChunk(Text: "defined" ); |
10048 | Builder.AddChunk(CK: CodeCompletionString::CK_HorizontalSpace); |
10049 | Builder.AddChunk(CK: CodeCompletionString::CK_LeftParen); |
10050 | Builder.AddPlaceholderChunk(Placeholder: "macro" ); |
10051 | Builder.AddChunk(CK: CodeCompletionString::CK_RightParen); |
10052 | Results.AddResult(R: Builder.TakeString()); |
10053 | Results.ExitScope(); |
10054 | |
10055 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
10056 | Results: Results.data(), NumResults: Results.size()); |
10057 | } |
10058 | |
10059 | void Sema::CodeCompletePreprocessorMacroArgument(Scope *S, |
10060 | IdentifierInfo *Macro, |
10061 | MacroInfo *MacroInfo, |
10062 | unsigned Argument) { |
10063 | // FIXME: In the future, we could provide "overload" results, much like we |
10064 | // do for function calls. |
10065 | |
10066 | // Now just ignore this. There will be another code-completion callback |
10067 | // for the expanded tokens. |
10068 | } |
10069 | |
10070 | // This handles completion inside an #include filename, e.g. #include <foo/ba |
10071 | // We look for the directory "foo" under each directory on the include path, |
10072 | // list its files, and reassemble the appropriate #include. |
10073 | void Sema::CodeCompleteIncludedFile(llvm::StringRef Dir, bool Angled) { |
10074 | // RelDir should use /, but unescaped \ is possible on windows! |
10075 | // Our completions will normalize to / for simplicity, this case is rare. |
10076 | std::string RelDir = llvm::sys::path::convert_to_slash(path: Dir); |
10077 | // We need the native slashes for the actual file system interactions. |
10078 | SmallString<128> NativeRelDir = StringRef(RelDir); |
10079 | llvm::sys::path::native(path&: NativeRelDir); |
10080 | llvm::vfs::FileSystem &FS = |
10081 | getSourceManager().getFileManager().getVirtualFileSystem(); |
10082 | |
10083 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
10084 | CodeCompleter->getCodeCompletionTUInfo(), |
10085 | CodeCompletionContext::CCC_IncludedFile); |
10086 | llvm::DenseSet<StringRef> SeenResults; // To deduplicate results. |
10087 | |
10088 | // Helper: adds one file or directory completion result. |
10089 | auto AddCompletion = [&](StringRef Filename, bool IsDirectory) { |
10090 | SmallString<64> TypedChunk = Filename; |
10091 | // Directory completion is up to the slash, e.g. <sys/ |
10092 | TypedChunk.push_back(Elt: IsDirectory ? '/' : Angled ? '>' : '"'); |
10093 | auto R = SeenResults.insert(V: TypedChunk); |
10094 | if (R.second) { // New completion |
10095 | const char *InternedTyped = Results.getAllocator().CopyString(String: TypedChunk); |
10096 | *R.first = InternedTyped; // Avoid dangling StringRef. |
10097 | CodeCompletionBuilder Builder(CodeCompleter->getAllocator(), |
10098 | CodeCompleter->getCodeCompletionTUInfo()); |
10099 | Builder.AddTypedTextChunk(Text: InternedTyped); |
10100 | // The result is a "Pattern", which is pretty opaque. |
10101 | // We may want to include the real filename to allow smart ranking. |
10102 | Results.AddResult(R: CodeCompletionResult(Builder.TakeString())); |
10103 | } |
10104 | }; |
10105 | |
10106 | // Helper: scans IncludeDir for nice files, and adds results for each. |
10107 | auto AddFilesFromIncludeDir = [&](StringRef IncludeDir, |
10108 | bool IsSystem, |
10109 | DirectoryLookup::LookupType_t LookupType) { |
10110 | llvm::SmallString<128> Dir = IncludeDir; |
10111 | if (!NativeRelDir.empty()) { |
10112 | if (LookupType == DirectoryLookup::LT_Framework) { |
10113 | // For a framework dir, #include <Foo/Bar/> actually maps to |
10114 | // a path of Foo.framework/Headers/Bar/. |
10115 | auto Begin = llvm::sys::path::begin(path: NativeRelDir); |
10116 | auto End = llvm::sys::path::end(path: NativeRelDir); |
10117 | |
10118 | llvm::sys::path::append(path&: Dir, a: *Begin + ".framework" , b: "Headers" ); |
10119 | llvm::sys::path::append(path&: Dir, begin: ++Begin, end: End); |
10120 | } else { |
10121 | llvm::sys::path::append(path&: Dir, a: NativeRelDir); |
10122 | } |
10123 | } |
10124 | |
10125 | const StringRef &Dirname = llvm::sys::path::filename(path: Dir); |
10126 | const bool isQt = Dirname.starts_with(Prefix: "Qt" ) || Dirname == "ActiveQt" ; |
10127 | const bool = |
10128 | IsSystem || isQt || Dir.ends_with(Suffix: ".framework/Headers" ); |
10129 | std::error_code EC; |
10130 | unsigned Count = 0; |
10131 | for (auto It = FS.dir_begin(Dir, EC); |
10132 | !EC && It != llvm::vfs::directory_iterator(); It.increment(EC)) { |
10133 | if (++Count == 2500) // If we happen to hit a huge directory, |
10134 | break; // bail out early so we're not too slow. |
10135 | StringRef Filename = llvm::sys::path::filename(path: It->path()); |
10136 | |
10137 | // To know whether a symlink should be treated as file or a directory, we |
10138 | // have to stat it. This should be cheap enough as there shouldn't be many |
10139 | // symlinks. |
10140 | llvm::sys::fs::file_type Type = It->type(); |
10141 | if (Type == llvm::sys::fs::file_type::symlink_file) { |
10142 | if (auto FileStatus = FS.status(Path: It->path())) |
10143 | Type = FileStatus->getType(); |
10144 | } |
10145 | switch (Type) { |
10146 | case llvm::sys::fs::file_type::directory_file: |
10147 | // All entries in a framework directory must have a ".framework" suffix, |
10148 | // but the suffix does not appear in the source code's include/import. |
10149 | if (LookupType == DirectoryLookup::LT_Framework && |
10150 | NativeRelDir.empty() && !Filename.consume_back(Suffix: ".framework" )) |
10151 | break; |
10152 | |
10153 | AddCompletion(Filename, /*IsDirectory=*/true); |
10154 | break; |
10155 | case llvm::sys::fs::file_type::regular_file: { |
10156 | // Only files that really look like headers. (Except in special dirs). |
10157 | const bool = Filename.ends_with_insensitive(Suffix: ".h" ) || |
10158 | Filename.ends_with_insensitive(Suffix: ".hh" ) || |
10159 | Filename.ends_with_insensitive(Suffix: ".hpp" ) || |
10160 | Filename.ends_with_insensitive(Suffix: ".hxx" ) || |
10161 | Filename.ends_with_insensitive(Suffix: ".inc" ) || |
10162 | (ExtensionlessHeaders && !Filename.contains(C: '.')); |
10163 | if (!IsHeader) |
10164 | break; |
10165 | AddCompletion(Filename, /*IsDirectory=*/false); |
10166 | break; |
10167 | } |
10168 | default: |
10169 | break; |
10170 | } |
10171 | } |
10172 | }; |
10173 | |
10174 | // Helper: adds results relative to IncludeDir, if possible. |
10175 | auto AddFilesFromDirLookup = [&](const DirectoryLookup &IncludeDir, |
10176 | bool IsSystem) { |
10177 | switch (IncludeDir.getLookupType()) { |
10178 | case DirectoryLookup::LT_HeaderMap: |
10179 | // header maps are not (currently) enumerable. |
10180 | break; |
10181 | case DirectoryLookup::LT_NormalDir: |
10182 | AddFilesFromIncludeDir(IncludeDir.getDirRef()->getName(), IsSystem, |
10183 | DirectoryLookup::LT_NormalDir); |
10184 | break; |
10185 | case DirectoryLookup::LT_Framework: |
10186 | AddFilesFromIncludeDir(IncludeDir.getFrameworkDirRef()->getName(), |
10187 | IsSystem, DirectoryLookup::LT_Framework); |
10188 | break; |
10189 | } |
10190 | }; |
10191 | |
10192 | // Finally with all our helpers, we can scan the include path. |
10193 | // Do this in standard order so deduplication keeps the right file. |
10194 | // (In case we decide to add more details to the results later). |
10195 | const auto &S = PP.getHeaderSearchInfo(); |
10196 | using llvm::make_range; |
10197 | if (!Angled) { |
10198 | // The current directory is on the include path for "quoted" includes. |
10199 | if (auto CurFile = PP.getCurrentFileLexer()->getFileEntry()) |
10200 | AddFilesFromIncludeDir(CurFile->getDir().getName(), false, |
10201 | DirectoryLookup::LT_NormalDir); |
10202 | for (const auto &D : make_range(x: S.quoted_dir_begin(), y: S.quoted_dir_end())) |
10203 | AddFilesFromDirLookup(D, false); |
10204 | } |
10205 | for (const auto &D : make_range(x: S.angled_dir_begin(), y: S.angled_dir_end())) |
10206 | AddFilesFromDirLookup(D, false); |
10207 | for (const auto &D : make_range(x: S.system_dir_begin(), y: S.system_dir_end())) |
10208 | AddFilesFromDirLookup(D, true); |
10209 | |
10210 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
10211 | Results: Results.data(), NumResults: Results.size()); |
10212 | } |
10213 | |
10214 | void Sema::CodeCompleteNaturalLanguage() { |
10215 | HandleCodeCompleteResults(S: this, CodeCompleter, |
10216 | Context: CodeCompletionContext::CCC_NaturalLanguage, Results: nullptr, |
10217 | NumResults: 0); |
10218 | } |
10219 | |
10220 | void Sema::CodeCompleteAvailabilityPlatformName() { |
10221 | ResultBuilder Results(*this, CodeCompleter->getAllocator(), |
10222 | CodeCompleter->getCodeCompletionTUInfo(), |
10223 | CodeCompletionContext::CCC_Other); |
10224 | Results.EnterNewScope(); |
10225 | static const char *Platforms[] = {"macOS" , "iOS" , "watchOS" , "tvOS" }; |
10226 | for (const char *Platform : llvm::ArrayRef(Platforms)) { |
10227 | Results.AddResult(R: CodeCompletionResult(Platform)); |
10228 | Results.AddResult(R: CodeCompletionResult(Results.getAllocator().CopyString( |
10229 | String: Twine(Platform) + "ApplicationExtension" ))); |
10230 | } |
10231 | Results.ExitScope(); |
10232 | HandleCodeCompleteResults(S: this, CodeCompleter, Context: Results.getCompletionContext(), |
10233 | Results: Results.data(), NumResults: Results.size()); |
10234 | } |
10235 | |
10236 | void Sema::GatherGlobalCodeCompletions( |
10237 | CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo, |
10238 | SmallVectorImpl<CodeCompletionResult> &Results) { |
10239 | ResultBuilder Builder(*this, Allocator, CCTUInfo, |
10240 | CodeCompletionContext::CCC_Recovery); |
10241 | if (!CodeCompleter || CodeCompleter->includeGlobals()) { |
10242 | CodeCompletionDeclConsumer Consumer(Builder, |
10243 | Context.getTranslationUnitDecl()); |
10244 | LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName, |
10245 | Consumer, |
10246 | !CodeCompleter || CodeCompleter->loadExternal()); |
10247 | } |
10248 | |
10249 | if (!CodeCompleter || CodeCompleter->includeMacros()) |
10250 | AddMacroResults(PP, Results&: Builder, |
10251 | LoadExternal: !CodeCompleter || CodeCompleter->loadExternal(), IncludeUndefined: true); |
10252 | |
10253 | Results.clear(); |
10254 | Results.insert(I: Results.end(), From: Builder.data(), |
10255 | To: Builder.data() + Builder.size()); |
10256 | } |
10257 | |