xref: /freebsd/contrib/llvm-project/clang/include/clang/Sema/CodeCompleteConsumer.h (revision 924226fba12cc9a228c73b956e1b7fa24c60b055)
1 //===- CodeCompleteConsumer.h - Code Completion Interface -------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file defines the CodeCompleteConsumer class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_CLANG_SEMA_CODECOMPLETECONSUMER_H
14 #define LLVM_CLANG_SEMA_CODECOMPLETECONSUMER_H
15 
16 #include "clang-c/Index.h"
17 #include "clang/AST/Type.h"
18 #include "clang/Basic/LLVM.h"
19 #include "clang/Lex/MacroInfo.h"
20 #include "clang/Sema/CodeCompleteOptions.h"
21 #include "clang/Sema/DeclSpec.h"
22 #include "llvm/ADT/ArrayRef.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/None.h"
25 #include "llvm/ADT/Optional.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/Support/Allocator.h"
30 #include "llvm/Support/type_traits.h"
31 #include <cassert>
32 #include <memory>
33 #include <string>
34 #include <utility>
35 
36 namespace clang {
37 
38 class ASTContext;
39 class Decl;
40 class DeclContext;
41 class FunctionDecl;
42 class FunctionTemplateDecl;
43 class IdentifierInfo;
44 class LangOptions;
45 class NamedDecl;
46 class NestedNameSpecifier;
47 class Preprocessor;
48 class RawComment;
49 class Sema;
50 class UsingShadowDecl;
51 
52 /// Default priority values for code-completion results based
53 /// on their kind.
54 enum {
55   /// Priority for the next initialization in a constructor initializer
56   /// list.
57   CCP_NextInitializer = 7,
58 
59   /// Priority for an enumeration constant inside a switch whose
60   /// condition is of the enumeration type.
61   CCP_EnumInCase = 7,
62 
63   /// Priority for a send-to-super completion.
64   CCP_SuperCompletion = 20,
65 
66   /// Priority for a declaration that is in the local scope.
67   CCP_LocalDeclaration = 34,
68 
69   /// Priority for a member declaration found from the current
70   /// method or member function.
71   CCP_MemberDeclaration = 35,
72 
73   /// Priority for a language keyword (that isn't any of the other
74   /// categories).
75   CCP_Keyword = 40,
76 
77   /// Priority for a code pattern.
78   CCP_CodePattern = 40,
79 
80   /// Priority for a non-type declaration.
81   CCP_Declaration = 50,
82 
83   /// Priority for a type.
84   CCP_Type = CCP_Declaration,
85 
86   /// Priority for a constant value (e.g., enumerator).
87   CCP_Constant = 65,
88 
89   /// Priority for a preprocessor macro.
90   CCP_Macro = 70,
91 
92   /// Priority for a nested-name-specifier.
93   CCP_NestedNameSpecifier = 75,
94 
95   /// Priority for a result that isn't likely to be what the user wants,
96   /// but is included for completeness.
97   CCP_Unlikely = 80,
98 
99   /// Priority for the Objective-C "_cmd" implicit parameter.
100   CCP_ObjC_cmd = CCP_Unlikely
101 };
102 
103 /// Priority value deltas that are added to code-completion results
104 /// based on the context of the result.
105 enum {
106   /// The result is in a base class.
107   CCD_InBaseClass = 2,
108 
109   /// The result is a C++ non-static member function whose qualifiers
110   /// exactly match the object type on which the member function can be called.
111   CCD_ObjectQualifierMatch = -1,
112 
113   /// The selector of the given message exactly matches the selector
114   /// of the current method, which might imply that some kind of delegation
115   /// is occurring.
116   CCD_SelectorMatch = -3,
117 
118   /// Adjustment to the "bool" type in Objective-C, where the typedef
119   /// "BOOL" is preferred.
120   CCD_bool_in_ObjC = 1,
121 
122   /// Adjustment for KVC code pattern priorities when it doesn't look
123   /// like the
124   CCD_ProbablyNotObjCCollection = 15,
125 
126   /// An Objective-C method being used as a property.
127   CCD_MethodAsProperty = 2,
128 
129   /// An Objective-C block property completed as a setter with a
130   /// block placeholder.
131   CCD_BlockPropertySetter = 3
132 };
133 
134 /// Priority value factors by which we will divide or multiply the
135 /// priority of a code-completion result.
136 enum {
137   /// Divide by this factor when a code-completion result's type exactly
138   /// matches the type we expect.
139   CCF_ExactTypeMatch = 4,
140 
141   /// Divide by this factor when a code-completion result's type is
142   /// similar to the type we expect (e.g., both arithmetic types, both
143   /// Objective-C object pointer types).
144   CCF_SimilarTypeMatch = 2
145 };
146 
147 /// A simplified classification of types used when determining
148 /// "similar" types for code completion.
149 enum SimplifiedTypeClass {
150   STC_Arithmetic,
151   STC_Array,
152   STC_Block,
153   STC_Function,
154   STC_ObjectiveC,
155   STC_Other,
156   STC_Pointer,
157   STC_Record,
158   STC_Void
159 };
160 
161 /// Determine the simplified type class of the given canonical type.
162 SimplifiedTypeClass getSimplifiedTypeClass(CanQualType T);
163 
164 /// Determine the type that this declaration will have if it is used
165 /// as a type or in an expression.
166 QualType getDeclUsageType(ASTContext &C, const NamedDecl *ND);
167 
168 /// Determine the priority to be given to a macro code completion result
169 /// with the given name.
170 ///
171 /// \param MacroName The name of the macro.
172 ///
173 /// \param LangOpts Options describing the current language dialect.
174 ///
175 /// \param PreferredTypeIsPointer Whether the preferred type for the context
176 /// of this macro is a pointer type.
177 unsigned getMacroUsagePriority(StringRef MacroName,
178                                const LangOptions &LangOpts,
179                                bool PreferredTypeIsPointer = false);
180 
181 /// Determine the libclang cursor kind associated with the given
182 /// declaration.
183 CXCursorKind getCursorKindForDecl(const Decl *D);
184 
185 /// The context in which code completion occurred, so that the
186 /// code-completion consumer can process the results accordingly.
187 class CodeCompletionContext {
188 public:
189   enum Kind {
190     /// An unspecified code-completion context.
191     CCC_Other,
192 
193     /// An unspecified code-completion context where we should also add
194     /// macro completions.
195     CCC_OtherWithMacros,
196 
197     /// Code completion occurred within a "top-level" completion context,
198     /// e.g., at namespace or global scope.
199     CCC_TopLevel,
200 
201     /// Code completion occurred within an Objective-C interface,
202     /// protocol, or category interface.
203     CCC_ObjCInterface,
204 
205     /// Code completion occurred within an Objective-C implementation
206     /// or category implementation.
207     CCC_ObjCImplementation,
208 
209     /// Code completion occurred within the instance variable list of
210     /// an Objective-C interface, implementation, or category implementation.
211     CCC_ObjCIvarList,
212 
213     /// Code completion occurred within a class, struct, or union.
214     CCC_ClassStructUnion,
215 
216     /// Code completion occurred where a statement (or declaration) is
217     /// expected in a function, method, or block.
218     CCC_Statement,
219 
220     /// Code completion occurred where an expression is expected.
221     CCC_Expression,
222 
223     /// Code completion occurred where an Objective-C message receiver
224     /// is expected.
225     CCC_ObjCMessageReceiver,
226 
227     /// Code completion occurred on the right-hand side of a member
228     /// access expression using the dot operator.
229     ///
230     /// The results of this completion are the members of the type being
231     /// accessed. The type itself is available via
232     /// \c CodeCompletionContext::getType().
233     CCC_DotMemberAccess,
234 
235     /// Code completion occurred on the right-hand side of a member
236     /// access expression using the arrow operator.
237     ///
238     /// The results of this completion are the members of the type being
239     /// accessed. The type itself is available via
240     /// \c CodeCompletionContext::getType().
241     CCC_ArrowMemberAccess,
242 
243     /// Code completion occurred on the right-hand side of an Objective-C
244     /// property access expression.
245     ///
246     /// The results of this completion are the members of the type being
247     /// accessed. The type itself is available via
248     /// \c CodeCompletionContext::getType().
249     CCC_ObjCPropertyAccess,
250 
251     /// Code completion occurred after the "enum" keyword, to indicate
252     /// an enumeration name.
253     CCC_EnumTag,
254 
255     /// Code completion occurred after the "union" keyword, to indicate
256     /// a union name.
257     CCC_UnionTag,
258 
259     /// Code completion occurred after the "struct" or "class" keyword,
260     /// to indicate a struct or class name.
261     CCC_ClassOrStructTag,
262 
263     /// Code completion occurred where a protocol name is expected.
264     CCC_ObjCProtocolName,
265 
266     /// Code completion occurred where a namespace or namespace alias
267     /// is expected.
268     CCC_Namespace,
269 
270     /// Code completion occurred where a type name is expected.
271     CCC_Type,
272 
273     /// Code completion occurred where a new name is expected.
274     CCC_NewName,
275 
276     /// Code completion occurred where both a new name and an existing symbol is
277     /// permissible.
278     CCC_SymbolOrNewName,
279 
280     /// Code completion occurred where an existing name(such as type, function
281     /// or variable) is expected.
282     CCC_Symbol,
283 
284     /// Code completion occurred where an macro is being defined.
285     CCC_MacroName,
286 
287     /// Code completion occurred where a macro name is expected
288     /// (without any arguments, in the case of a function-like macro).
289     CCC_MacroNameUse,
290 
291     /// Code completion occurred within a preprocessor expression.
292     CCC_PreprocessorExpression,
293 
294     /// Code completion occurred where a preprocessor directive is
295     /// expected.
296     CCC_PreprocessorDirective,
297 
298     /// Code completion occurred in a context where natural language is
299     /// expected, e.g., a comment or string literal.
300     ///
301     /// This context usually implies that no completions should be added,
302     /// unless they come from an appropriate natural-language dictionary.
303     CCC_NaturalLanguage,
304 
305     /// Code completion for a selector, as in an \@selector expression.
306     CCC_SelectorName,
307 
308     /// Code completion within a type-qualifier list.
309     CCC_TypeQualifiers,
310 
311     /// Code completion in a parenthesized expression, which means that
312     /// we may also have types here in C and Objective-C (as well as in C++).
313     CCC_ParenthesizedExpression,
314 
315     /// Code completion where an Objective-C instance message is
316     /// expected.
317     CCC_ObjCInstanceMessage,
318 
319     /// Code completion where an Objective-C class message is expected.
320     CCC_ObjCClassMessage,
321 
322     /// Code completion where the name of an Objective-C class is
323     /// expected.
324     CCC_ObjCInterfaceName,
325 
326     /// Code completion where an Objective-C category name is expected.
327     CCC_ObjCCategoryName,
328 
329     /// Code completion inside the filename part of a #include directive.
330     CCC_IncludedFile,
331 
332     /// Code completion of an attribute name.
333     CCC_Attribute,
334 
335     /// An unknown context, in which we are recovering from a parsing
336     /// error and don't know which completions we should give.
337     CCC_Recovery
338   };
339 
340   using VisitedContextSet = llvm::SmallPtrSet<DeclContext *, 8>;
341 
342 private:
343   Kind CCKind;
344 
345   /// Indicates whether we are completing a name of a using declaration, e.g.
346   ///     using ^;
347   ///     using a::^;
348   bool IsUsingDeclaration;
349 
350   /// The type that would prefer to see at this point (e.g., the type
351   /// of an initializer or function parameter).
352   QualType PreferredType;
353 
354   /// The type of the base object in a member access expression.
355   QualType BaseType;
356 
357   /// The identifiers for Objective-C selector parts.
358   ArrayRef<IdentifierInfo *> SelIdents;
359 
360   /// The scope specifier that comes before the completion token e.g.
361   /// "a::b::"
362   llvm::Optional<CXXScopeSpec> ScopeSpecifier;
363 
364   /// A set of declaration contexts visited by Sema when doing lookup for
365   /// code completion.
366   VisitedContextSet VisitedContexts;
367 
368 public:
369   /// Construct a new code-completion context of the given kind.
370   CodeCompletionContext(Kind CCKind)
371       : CCKind(CCKind), IsUsingDeclaration(false), SelIdents(None) {}
372 
373   /// Construct a new code-completion context of the given kind.
374   CodeCompletionContext(Kind CCKind, QualType T,
375                         ArrayRef<IdentifierInfo *> SelIdents = None)
376       : CCKind(CCKind), IsUsingDeclaration(false), SelIdents(SelIdents) {
377     if (CCKind == CCC_DotMemberAccess || CCKind == CCC_ArrowMemberAccess ||
378         CCKind == CCC_ObjCPropertyAccess || CCKind == CCC_ObjCClassMessage ||
379         CCKind == CCC_ObjCInstanceMessage)
380       BaseType = T;
381     else
382       PreferredType = T;
383   }
384 
385   bool isUsingDeclaration() const { return IsUsingDeclaration; }
386   void setIsUsingDeclaration(bool V) { IsUsingDeclaration = V; }
387 
388   /// Retrieve the kind of code-completion context.
389   Kind getKind() const { return CCKind; }
390 
391   /// Retrieve the type that this expression would prefer to have, e.g.,
392   /// if the expression is a variable initializer or a function argument, the
393   /// type of the corresponding variable or function parameter.
394   QualType getPreferredType() const { return PreferredType; }
395   void setPreferredType(QualType T) { PreferredType = T; }
396 
397   /// Retrieve the type of the base object in a member-access
398   /// expression.
399   QualType getBaseType() const { return BaseType; }
400 
401   /// Retrieve the Objective-C selector identifiers.
402   ArrayRef<IdentifierInfo *> getSelIdents() const { return SelIdents; }
403 
404   /// Determines whether we want C++ constructors as results within this
405   /// context.
406   bool wantConstructorResults() const;
407 
408   /// Sets the scope specifier that comes before the completion token.
409   /// This is expected to be set in code completions on qualfied specifiers
410   /// (e.g. "a::b::").
411   void setCXXScopeSpecifier(CXXScopeSpec SS) {
412     this->ScopeSpecifier = std::move(SS);
413   }
414 
415   /// Adds a visited context.
416   void addVisitedContext(DeclContext *Ctx) {
417     VisitedContexts.insert(Ctx);
418   }
419 
420   /// Retrieves all visited contexts.
421   const VisitedContextSet &getVisitedContexts() const {
422     return VisitedContexts;
423   }
424 
425   llvm::Optional<const CXXScopeSpec *> getCXXScopeSpecifier() {
426     if (ScopeSpecifier)
427       return ScopeSpecifier.getPointer();
428     return llvm::None;
429   }
430 };
431 
432 /// Get string representation of \p Kind, useful for for debugging.
433 llvm::StringRef getCompletionKindString(CodeCompletionContext::Kind Kind);
434 
435 /// A "string" used to describe how code completion can
436 /// be performed for an entity.
437 ///
438 /// A code completion string typically shows how a particular entity can be
439 /// used. For example, the code completion string for a function would show
440 /// the syntax to call it, including the parentheses, placeholders for the
441 /// arguments, etc.
442 class CodeCompletionString {
443 public:
444   /// The different kinds of "chunks" that can occur within a code
445   /// completion string.
446   enum ChunkKind {
447     /// The piece of text that the user is expected to type to
448     /// match the code-completion string, typically a keyword or the name of a
449     /// declarator or macro.
450     CK_TypedText,
451 
452     /// A piece of text that should be placed in the buffer, e.g.,
453     /// parentheses or a comma in a function call.
454     CK_Text,
455 
456     /// A code completion string that is entirely optional. For example,
457     /// an optional code completion string that describes the default arguments
458     /// in a function call.
459     CK_Optional,
460 
461     /// A string that acts as a placeholder for, e.g., a function
462     /// call argument.
463     CK_Placeholder,
464 
465     /// A piece of text that describes something about the result but
466     /// should not be inserted into the buffer.
467     CK_Informative,
468     /// A piece of text that describes the type of an entity or, for
469     /// functions and methods, the return type.
470     CK_ResultType,
471 
472     /// A piece of text that describes the parameter that corresponds
473     /// to the code-completion location within a function call, message send,
474     /// macro invocation, etc.
475     CK_CurrentParameter,
476 
477     /// A left parenthesis ('(').
478     CK_LeftParen,
479 
480     /// A right parenthesis (')').
481     CK_RightParen,
482 
483     /// A left bracket ('[').
484     CK_LeftBracket,
485 
486     /// A right bracket (']').
487     CK_RightBracket,
488 
489     /// A left brace ('{').
490     CK_LeftBrace,
491 
492     /// A right brace ('}').
493     CK_RightBrace,
494 
495     /// A left angle bracket ('<').
496     CK_LeftAngle,
497 
498     /// A right angle bracket ('>').
499     CK_RightAngle,
500 
501     /// A comma separator (',').
502     CK_Comma,
503 
504     /// A colon (':').
505     CK_Colon,
506 
507     /// A semicolon (';').
508     CK_SemiColon,
509 
510     /// An '=' sign.
511     CK_Equal,
512 
513     /// Horizontal whitespace (' ').
514     CK_HorizontalSpace,
515 
516     /// Vertical whitespace ('\\n' or '\\r\\n', depending on the
517     /// platform).
518     CK_VerticalSpace
519   };
520 
521   /// One piece of the code completion string.
522   struct Chunk {
523     /// The kind of data stored in this piece of the code completion
524     /// string.
525     ChunkKind Kind = CK_Text;
526 
527     union {
528       /// The text string associated with a CK_Text, CK_Placeholder,
529       /// CK_Informative, or CK_Comma chunk.
530       /// The string is owned by the chunk and will be deallocated
531       /// (with delete[]) when the chunk is destroyed.
532       const char *Text;
533 
534       /// The code completion string associated with a CK_Optional chunk.
535       /// The optional code completion string is owned by the chunk, and will
536       /// be deallocated (with delete) when the chunk is destroyed.
537       CodeCompletionString *Optional;
538     };
539 
540     Chunk() : Text(nullptr) {}
541 
542     explicit Chunk(ChunkKind Kind, const char *Text = "");
543 
544     /// Create a new text chunk.
545     static Chunk CreateText(const char *Text);
546 
547     /// Create a new optional chunk.
548     static Chunk CreateOptional(CodeCompletionString *Optional);
549 
550     /// Create a new placeholder chunk.
551     static Chunk CreatePlaceholder(const char *Placeholder);
552 
553     /// Create a new informative chunk.
554     static Chunk CreateInformative(const char *Informative);
555 
556     /// Create a new result type chunk.
557     static Chunk CreateResultType(const char *ResultType);
558 
559     /// Create a new current-parameter chunk.
560     static Chunk CreateCurrentParameter(const char *CurrentParameter);
561   };
562 
563 private:
564   friend class CodeCompletionBuilder;
565   friend class CodeCompletionResult;
566 
567   /// The number of chunks stored in this string.
568   unsigned NumChunks : 16;
569 
570   /// The number of annotations for this code-completion result.
571   unsigned NumAnnotations : 16;
572 
573   /// The priority of this code-completion string.
574   unsigned Priority : 16;
575 
576   /// The availability of this code-completion result.
577   unsigned Availability : 2;
578 
579   /// The name of the parent context.
580   StringRef ParentName;
581 
582   /// A brief documentation comment attached to the declaration of
583   /// entity being completed by this result.
584   const char *BriefComment;
585 
586   CodeCompletionString(const Chunk *Chunks, unsigned NumChunks,
587                        unsigned Priority, CXAvailabilityKind Availability,
588                        const char **Annotations, unsigned NumAnnotations,
589                        StringRef ParentName,
590                        const char *BriefComment);
591   ~CodeCompletionString() = default;
592 
593 public:
594   CodeCompletionString(const CodeCompletionString &) = delete;
595   CodeCompletionString &operator=(const CodeCompletionString &) = delete;
596 
597   using iterator = const Chunk *;
598 
599   iterator begin() const { return reinterpret_cast<const Chunk *>(this + 1); }
600   iterator end() const { return begin() + NumChunks; }
601   bool empty() const { return NumChunks == 0; }
602   unsigned size() const { return NumChunks; }
603 
604   const Chunk &operator[](unsigned I) const {
605     assert(I < size() && "Chunk index out-of-range");
606     return begin()[I];
607   }
608 
609   /// Returns the text in the TypedText chunk.
610   const char *getTypedText() const;
611 
612   /// Retrieve the priority of this code completion result.
613   unsigned getPriority() const { return Priority; }
614 
615   /// Retrieve the availability of this code completion result.
616   unsigned getAvailability() const { return Availability; }
617 
618   /// Retrieve the number of annotations for this code completion result.
619   unsigned getAnnotationCount() const;
620 
621   /// Retrieve the annotation string specified by \c AnnotationNr.
622   const char *getAnnotation(unsigned AnnotationNr) const;
623 
624   /// Retrieve the name of the parent context.
625   StringRef getParentContextName() const {
626     return ParentName;
627   }
628 
629   const char *getBriefComment() const {
630     return BriefComment;
631   }
632 
633   /// Retrieve a string representation of the code completion string,
634   /// which is mainly useful for debugging.
635   std::string getAsString() const;
636 };
637 
638 /// An allocator used specifically for the purpose of code completion.
639 class CodeCompletionAllocator : public llvm::BumpPtrAllocator {
640 public:
641   /// Copy the given string into this allocator.
642   const char *CopyString(const Twine &String);
643 };
644 
645 /// Allocator for a cached set of global code completions.
646 class GlobalCodeCompletionAllocator : public CodeCompletionAllocator {};
647 
648 class CodeCompletionTUInfo {
649   llvm::DenseMap<const DeclContext *, StringRef> ParentNames;
650   std::shared_ptr<GlobalCodeCompletionAllocator> AllocatorRef;
651 
652 public:
653   explicit CodeCompletionTUInfo(
654       std::shared_ptr<GlobalCodeCompletionAllocator> Allocator)
655       : AllocatorRef(std::move(Allocator)) {}
656 
657   std::shared_ptr<GlobalCodeCompletionAllocator> getAllocatorRef() const {
658     return AllocatorRef;
659   }
660 
661   CodeCompletionAllocator &getAllocator() const {
662     assert(AllocatorRef);
663     return *AllocatorRef;
664   }
665 
666   StringRef getParentName(const DeclContext *DC);
667 };
668 
669 } // namespace clang
670 
671 namespace clang {
672 
673 /// A builder class used to construct new code-completion strings.
674 class CodeCompletionBuilder {
675 public:
676   using Chunk = CodeCompletionString::Chunk;
677 
678 private:
679   CodeCompletionAllocator &Allocator;
680   CodeCompletionTUInfo &CCTUInfo;
681   unsigned Priority = 0;
682   CXAvailabilityKind Availability = CXAvailability_Available;
683   StringRef ParentName;
684   const char *BriefComment = nullptr;
685 
686   /// The chunks stored in this string.
687   SmallVector<Chunk, 4> Chunks;
688 
689   SmallVector<const char *, 2> Annotations;
690 
691 public:
692   CodeCompletionBuilder(CodeCompletionAllocator &Allocator,
693                         CodeCompletionTUInfo &CCTUInfo)
694       : Allocator(Allocator), CCTUInfo(CCTUInfo) {}
695 
696   CodeCompletionBuilder(CodeCompletionAllocator &Allocator,
697                         CodeCompletionTUInfo &CCTUInfo,
698                         unsigned Priority, CXAvailabilityKind Availability)
699       : Allocator(Allocator), CCTUInfo(CCTUInfo), Priority(Priority),
700         Availability(Availability) {}
701 
702   /// Retrieve the allocator into which the code completion
703   /// strings should be allocated.
704   CodeCompletionAllocator &getAllocator() const { return Allocator; }
705 
706   CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo; }
707 
708   /// Take the resulting completion string.
709   ///
710   /// This operation can only be performed once.
711   CodeCompletionString *TakeString();
712 
713   /// Add a new typed-text chunk.
714   void AddTypedTextChunk(const char *Text);
715 
716   /// Add a new text chunk.
717   void AddTextChunk(const char *Text);
718 
719   /// Add a new optional chunk.
720   void AddOptionalChunk(CodeCompletionString *Optional);
721 
722   /// Add a new placeholder chunk.
723   void AddPlaceholderChunk(const char *Placeholder);
724 
725   /// Add a new informative chunk.
726   void AddInformativeChunk(const char *Text);
727 
728   /// Add a new result-type chunk.
729   void AddResultTypeChunk(const char *ResultType);
730 
731   /// Add a new current-parameter chunk.
732   void AddCurrentParameterChunk(const char *CurrentParameter);
733 
734   /// Add a new chunk.
735   void AddChunk(CodeCompletionString::ChunkKind CK, const char *Text = "");
736 
737   void AddAnnotation(const char *A) { Annotations.push_back(A); }
738 
739   /// Add the parent context information to this code completion.
740   void addParentContext(const DeclContext *DC);
741 
742   const char *getBriefComment() const { return BriefComment; }
743   void addBriefComment(StringRef Comment);
744 
745   StringRef getParentName() const { return ParentName; }
746 };
747 
748 /// Captures a result of code completion.
749 class CodeCompletionResult {
750 public:
751   /// Describes the kind of result generated.
752   enum ResultKind {
753     /// Refers to a declaration.
754     RK_Declaration = 0,
755 
756     /// Refers to a keyword or symbol.
757     RK_Keyword,
758 
759     /// Refers to a macro.
760     RK_Macro,
761 
762     /// Refers to a precomputed pattern.
763     RK_Pattern
764   };
765 
766   /// When Kind == RK_Declaration or RK_Pattern, the declaration we are
767   /// referring to. In the latter case, the declaration might be NULL.
768   const NamedDecl *Declaration = nullptr;
769 
770   union {
771     /// When Kind == RK_Keyword, the string representing the keyword
772     /// or symbol's spelling.
773     const char *Keyword;
774 
775     /// When Kind == RK_Pattern, the code-completion string that
776     /// describes the completion text to insert.
777     CodeCompletionString *Pattern;
778 
779     /// When Kind == RK_Macro, the identifier that refers to a macro.
780     const IdentifierInfo *Macro;
781   };
782 
783   /// The priority of this particular code-completion result.
784   unsigned Priority;
785 
786   /// Specifies which parameter (of a function, Objective-C method,
787   /// macro, etc.) we should start with when formatting the result.
788   unsigned StartParameter = 0;
789 
790   /// The kind of result stored here.
791   ResultKind Kind;
792 
793   /// The cursor kind that describes this result.
794   CXCursorKind CursorKind;
795 
796   /// The availability of this result.
797   CXAvailabilityKind Availability = CXAvailability_Available;
798 
799   /// Fix-its that *must* be applied before inserting the text for the
800   /// corresponding completion.
801   ///
802   /// By default, CodeCompletionBuilder only returns completions with empty
803   /// fix-its. Extra completions with non-empty fix-its should be explicitly
804   /// requested by setting CompletionOptions::IncludeFixIts.
805   ///
806   /// For the clients to be able to compute position of the cursor after
807   /// applying fix-its, the following conditions are guaranteed to hold for
808   /// RemoveRange of the stored fix-its:
809   ///  - Ranges in the fix-its are guaranteed to never contain the completion
810   ///  point (or identifier under completion point, if any) inside them, except
811   ///  at the start or at the end of the range.
812   ///  - If a fix-it range starts or ends with completion point (or starts or
813   ///  ends after the identifier under completion point), it will contain at
814   ///  least one character. It allows to unambiguously recompute completion
815   ///  point after applying the fix-it.
816   ///
817   /// The intuition is that provided fix-its change code around the identifier
818   /// we complete, but are not allowed to touch the identifier itself or the
819   /// completion point. One example of completions with corrections are the ones
820   /// replacing '.' with '->' and vice versa:
821   ///
822   /// std::unique_ptr<std::vector<int>> vec_ptr;
823   /// In 'vec_ptr.^', one of the completions is 'push_back', it requires
824   /// replacing '.' with '->'.
825   /// In 'vec_ptr->^', one of the completions is 'release', it requires
826   /// replacing '->' with '.'.
827   std::vector<FixItHint> FixIts;
828 
829   /// Whether this result is hidden by another name.
830   bool Hidden : 1;
831 
832   /// Whether this is a class member from base class.
833   bool InBaseClass : 1;
834 
835   /// Whether this result was found via lookup into a base class.
836   bool QualifierIsInformative : 1;
837 
838   /// Whether this declaration is the beginning of a
839   /// nested-name-specifier and, therefore, should be followed by '::'.
840   bool StartsNestedNameSpecifier : 1;
841 
842   /// Whether all parameters (of a function, Objective-C
843   /// method, etc.) should be considered "informative".
844   bool AllParametersAreInformative : 1;
845 
846   /// Whether we're completing a declaration of the given entity,
847   /// rather than a use of that entity.
848   bool DeclaringEntity : 1;
849 
850   /// If the result should have a nested-name-specifier, this is it.
851   /// When \c QualifierIsInformative, the nested-name-specifier is
852   /// informative rather than required.
853   NestedNameSpecifier *Qualifier = nullptr;
854 
855   /// If this Decl was unshadowed by using declaration, this can store a
856   /// pointer to the UsingShadowDecl which was used in the unshadowing process.
857   /// This information can be used to uprank CodeCompletionResults / which have
858   /// corresponding `using decl::qualified::name;` nearby.
859   const UsingShadowDecl *ShadowDecl = nullptr;
860 
861   /// If the result is RK_Macro, this can store the information about the macro
862   /// definition. This should be set in most cases but can be missing when
863   /// the macro has been undefined.
864   const MacroInfo *MacroDefInfo = nullptr;
865 
866   /// Build a result that refers to a declaration.
867   CodeCompletionResult(const NamedDecl *Declaration, unsigned Priority,
868                        NestedNameSpecifier *Qualifier = nullptr,
869                        bool QualifierIsInformative = false,
870                        bool Accessible = true,
871                        std::vector<FixItHint> FixIts = std::vector<FixItHint>())
872       : Declaration(Declaration), Priority(Priority), Kind(RK_Declaration),
873         FixIts(std::move(FixIts)), Hidden(false), InBaseClass(false),
874         QualifierIsInformative(QualifierIsInformative),
875         StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
876         DeclaringEntity(false), Qualifier(Qualifier) {
877     // FIXME: Add assert to check FixIts range requirements.
878     computeCursorKindAndAvailability(Accessible);
879   }
880 
881   /// Build a result that refers to a keyword or symbol.
882   CodeCompletionResult(const char *Keyword, unsigned Priority = CCP_Keyword)
883       : Keyword(Keyword), Priority(Priority), Kind(RK_Keyword),
884         CursorKind(CXCursor_NotImplemented), Hidden(false), InBaseClass(false),
885         QualifierIsInformative(false), StartsNestedNameSpecifier(false),
886         AllParametersAreInformative(false), DeclaringEntity(false) {}
887 
888   /// Build a result that refers to a macro.
889   CodeCompletionResult(const IdentifierInfo *Macro,
890                        const MacroInfo *MI = nullptr,
891                        unsigned Priority = CCP_Macro)
892       : Macro(Macro), Priority(Priority), Kind(RK_Macro),
893         CursorKind(CXCursor_MacroDefinition), Hidden(false), InBaseClass(false),
894         QualifierIsInformative(false), StartsNestedNameSpecifier(false),
895         AllParametersAreInformative(false), DeclaringEntity(false),
896         MacroDefInfo(MI) {}
897 
898   /// Build a result that refers to a pattern.
899   CodeCompletionResult(
900       CodeCompletionString *Pattern, unsigned Priority = CCP_CodePattern,
901       CXCursorKind CursorKind = CXCursor_NotImplemented,
902       CXAvailabilityKind Availability = CXAvailability_Available,
903       const NamedDecl *D = nullptr)
904       : Declaration(D), Pattern(Pattern), Priority(Priority), Kind(RK_Pattern),
905         CursorKind(CursorKind), Availability(Availability), Hidden(false),
906         InBaseClass(false), QualifierIsInformative(false),
907         StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
908         DeclaringEntity(false) {}
909 
910   /// Build a result that refers to a pattern with an associated
911   /// declaration.
912   CodeCompletionResult(CodeCompletionString *Pattern, const NamedDecl *D,
913                        unsigned Priority)
914       : Declaration(D), Pattern(Pattern), Priority(Priority), Kind(RK_Pattern),
915         Hidden(false), InBaseClass(false), QualifierIsInformative(false),
916         StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
917         DeclaringEntity(false) {
918     computeCursorKindAndAvailability();
919   }
920 
921   /// Retrieve the declaration stored in this result. This might be nullptr if
922   /// Kind is RK_Pattern.
923   const NamedDecl *getDeclaration() const {
924     assert(((Kind == RK_Declaration) || (Kind == RK_Pattern)) &&
925            "Not a declaration or pattern result");
926     return Declaration;
927   }
928 
929   /// Retrieve the keyword stored in this result.
930   const char *getKeyword() const {
931     assert(Kind == RK_Keyword && "Not a keyword result");
932     return Keyword;
933   }
934 
935   /// Create a new code-completion string that describes how to insert
936   /// this result into a program.
937   ///
938   /// \param S The semantic analysis that created the result.
939   ///
940   /// \param Allocator The allocator that will be used to allocate the
941   /// string itself.
942   CodeCompletionString *CreateCodeCompletionString(Sema &S,
943                                          const CodeCompletionContext &CCContext,
944                                            CodeCompletionAllocator &Allocator,
945                                            CodeCompletionTUInfo &CCTUInfo,
946                                            bool IncludeBriefComments);
947   CodeCompletionString *CreateCodeCompletionString(ASTContext &Ctx,
948                                                    Preprocessor &PP,
949                                          const CodeCompletionContext &CCContext,
950                                            CodeCompletionAllocator &Allocator,
951                                            CodeCompletionTUInfo &CCTUInfo,
952                                            bool IncludeBriefComments);
953   /// Creates a new code-completion string for the macro result. Similar to the
954   /// above overloads, except this only requires preprocessor information.
955   /// The result kind must be `RK_Macro`.
956   CodeCompletionString *
957   CreateCodeCompletionStringForMacro(Preprocessor &PP,
958                                      CodeCompletionAllocator &Allocator,
959                                      CodeCompletionTUInfo &CCTUInfo);
960 
961   CodeCompletionString *createCodeCompletionStringForDecl(
962       Preprocessor &PP, ASTContext &Ctx, CodeCompletionBuilder &Result,
963       bool IncludeBriefComments, const CodeCompletionContext &CCContext,
964       PrintingPolicy &Policy);
965 
966   CodeCompletionString *createCodeCompletionStringForOverride(
967       Preprocessor &PP, ASTContext &Ctx, CodeCompletionBuilder &Result,
968       bool IncludeBriefComments, const CodeCompletionContext &CCContext,
969       PrintingPolicy &Policy);
970 
971   /// Retrieve the name that should be used to order a result.
972   ///
973   /// If the name needs to be constructed as a string, that string will be
974   /// saved into Saved and the returned StringRef will refer to it.
975   StringRef getOrderedName(std::string &Saved) const;
976 
977 private:
978   void computeCursorKindAndAvailability(bool Accessible = true);
979 };
980 
981 bool operator<(const CodeCompletionResult &X, const CodeCompletionResult &Y);
982 
983 inline bool operator>(const CodeCompletionResult &X,
984                       const CodeCompletionResult &Y) {
985   return Y < X;
986 }
987 
988 inline bool operator<=(const CodeCompletionResult &X,
989                       const CodeCompletionResult &Y) {
990   return !(Y < X);
991 }
992 
993 inline bool operator>=(const CodeCompletionResult &X,
994                        const CodeCompletionResult &Y) {
995   return !(X < Y);
996 }
997 
998 /// Abstract interface for a consumer of code-completion
999 /// information.
1000 class CodeCompleteConsumer {
1001 protected:
1002   const CodeCompleteOptions CodeCompleteOpts;
1003 
1004 public:
1005   class OverloadCandidate {
1006   public:
1007     /// Describes the type of overload candidate.
1008     enum CandidateKind {
1009       /// The candidate is a function declaration.
1010       CK_Function,
1011 
1012       /// The candidate is a function template, arguments are being completed.
1013       CK_FunctionTemplate,
1014 
1015       /// The "candidate" is actually a variable, expression, or block
1016       /// for which we only have a function prototype.
1017       CK_FunctionType,
1018 
1019       /// The candidate is a template, template arguments are being completed.
1020       CK_Template,
1021 
1022       /// The candidate is aggregate initialization of a record type.
1023       CK_Aggregate,
1024     };
1025 
1026   private:
1027     /// The kind of overload candidate.
1028     CandidateKind Kind;
1029 
1030     union {
1031       /// The function overload candidate, available when
1032       /// Kind == CK_Function.
1033       FunctionDecl *Function;
1034 
1035       /// The function template overload candidate, available when
1036       /// Kind == CK_FunctionTemplate.
1037       FunctionTemplateDecl *FunctionTemplate;
1038 
1039       /// The function type that describes the entity being called,
1040       /// when Kind == CK_FunctionType.
1041       const FunctionType *Type;
1042 
1043       /// The template overload candidate, available when
1044       /// Kind == CK_Template.
1045       const TemplateDecl *Template;
1046 
1047       /// The class being aggregate-initialized,
1048       /// when Kind == CK_Aggregate
1049       const RecordDecl *AggregateType;
1050     };
1051 
1052   public:
1053     OverloadCandidate(FunctionDecl *Function)
1054         : Kind(CK_Function), Function(Function) {
1055       assert(Function != nullptr);
1056     }
1057 
1058     OverloadCandidate(FunctionTemplateDecl *FunctionTemplateDecl)
1059         : Kind(CK_FunctionTemplate), FunctionTemplate(FunctionTemplateDecl) {
1060       assert(FunctionTemplateDecl != nullptr);
1061     }
1062 
1063     OverloadCandidate(const FunctionType *Type)
1064         : Kind(CK_FunctionType), Type(Type) {
1065       assert(Type != nullptr);
1066     }
1067 
1068     OverloadCandidate(const RecordDecl *Aggregate)
1069         : Kind(CK_Aggregate), AggregateType(Aggregate) {
1070       assert(Aggregate != nullptr);
1071     }
1072 
1073     OverloadCandidate(const TemplateDecl *Template)
1074         : Kind(CK_Template), Template(Template) {}
1075 
1076     /// Determine the kind of overload candidate.
1077     CandidateKind getKind() const { return Kind; }
1078 
1079     /// Retrieve the function overload candidate or the templated
1080     /// function declaration for a function template.
1081     FunctionDecl *getFunction() const;
1082 
1083     /// Retrieve the function template overload candidate.
1084     FunctionTemplateDecl *getFunctionTemplate() const {
1085       assert(getKind() == CK_FunctionTemplate && "Not a function template");
1086       return FunctionTemplate;
1087     }
1088 
1089     /// Retrieve the function type of the entity, regardless of how the
1090     /// function is stored.
1091     const FunctionType *getFunctionType() const;
1092 
1093     const TemplateDecl *getTemplate() const {
1094       assert(getKind() == CK_Template && "Not a template");
1095       return Template;
1096     }
1097 
1098     /// Retrieve the aggregate type being initialized.
1099     const RecordDecl *getAggregate() const {
1100       assert(getKind() == CK_Aggregate);
1101       return AggregateType;
1102     }
1103 
1104     /// Get the number of parameters in this signature.
1105     unsigned getNumParams() const;
1106 
1107     /// Get the type of the Nth parameter.
1108     /// Returns null if the type is unknown or N is out of range.
1109     QualType getParamType(unsigned N) const;
1110 
1111     /// Get the declaration of the Nth parameter.
1112     /// Returns null if the decl is unknown or N is out of range.
1113     const NamedDecl *getParamDecl(unsigned N) const;
1114 
1115     /// Create a new code-completion string that describes the function
1116     /// signature of this overload candidate.
1117     CodeCompletionString *
1118     CreateSignatureString(unsigned CurrentArg, Sema &S,
1119                           CodeCompletionAllocator &Allocator,
1120                           CodeCompletionTUInfo &CCTUInfo,
1121                           bool IncludeBriefComments, bool Braced) const;
1122   };
1123 
1124   CodeCompleteConsumer(const CodeCompleteOptions &CodeCompleteOpts)
1125       : CodeCompleteOpts(CodeCompleteOpts) {}
1126 
1127   /// Whether the code-completion consumer wants to see macros.
1128   bool includeMacros() const {
1129     return CodeCompleteOpts.IncludeMacros;
1130   }
1131 
1132   /// Whether the code-completion consumer wants to see code patterns.
1133   bool includeCodePatterns() const {
1134     return CodeCompleteOpts.IncludeCodePatterns;
1135   }
1136 
1137   /// Whether to include global (top-level) declaration results.
1138   bool includeGlobals() const { return CodeCompleteOpts.IncludeGlobals; }
1139 
1140   /// Whether to include declarations in namespace contexts (including
1141   /// the global namespace). If this is false, `includeGlobals()` will be
1142   /// ignored.
1143   bool includeNamespaceLevelDecls() const {
1144     return CodeCompleteOpts.IncludeNamespaceLevelDecls;
1145   }
1146 
1147   /// Whether to include brief documentation comments within the set of
1148   /// code completions returned.
1149   bool includeBriefComments() const {
1150     return CodeCompleteOpts.IncludeBriefComments;
1151   }
1152 
1153   /// Whether to include completion items with small fix-its, e.g. change
1154   /// '.' to '->' on member access, etc.
1155   bool includeFixIts() const { return CodeCompleteOpts.IncludeFixIts; }
1156 
1157   /// Hint whether to load data from the external AST in order to provide
1158   /// full results. If false, declarations from the preamble may be omitted.
1159   bool loadExternal() const {
1160     return CodeCompleteOpts.LoadExternal;
1161   }
1162 
1163   /// Deregisters and destroys this code-completion consumer.
1164   virtual ~CodeCompleteConsumer();
1165 
1166   /// \name Code-completion filtering
1167   /// Check if the result should be filtered out.
1168   virtual bool isResultFilteredOut(StringRef Filter,
1169                                    CodeCompletionResult Results) {
1170     return false;
1171   }
1172 
1173   /// \name Code-completion callbacks
1174   //@{
1175   /// Process the finalized code-completion results.
1176   virtual void ProcessCodeCompleteResults(Sema &S,
1177                                           CodeCompletionContext Context,
1178                                           CodeCompletionResult *Results,
1179                                           unsigned NumResults) {}
1180 
1181   /// \param S the semantic-analyzer object for which code-completion is being
1182   /// done.
1183   ///
1184   /// \param CurrentArg the index of the current argument.
1185   ///
1186   /// \param Candidates an array of overload candidates.
1187   ///
1188   /// \param NumCandidates the number of overload candidates
1189   ///
1190   /// \param OpenParLoc location of the opening parenthesis of the argument
1191   ///        list.
1192   virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1193                                          OverloadCandidate *Candidates,
1194                                          unsigned NumCandidates,
1195                                          SourceLocation OpenParLoc,
1196                                          bool Braced) {}
1197   //@}
1198 
1199   /// Retrieve the allocator that will be used to allocate
1200   /// code completion strings.
1201   virtual CodeCompletionAllocator &getAllocator() = 0;
1202 
1203   virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() = 0;
1204 };
1205 
1206 /// Get the documentation comment used to produce
1207 /// CodeCompletionString::BriefComment for RK_Declaration.
1208 const RawComment *getCompletionComment(const ASTContext &Ctx,
1209                                        const NamedDecl *Decl);
1210 
1211 /// Get the documentation comment used to produce
1212 /// CodeCompletionString::BriefComment for RK_Pattern.
1213 const RawComment *getPatternCompletionComment(const ASTContext &Ctx,
1214                                               const NamedDecl *Decl);
1215 
1216 /// Get the documentation comment used to produce
1217 /// CodeCompletionString::BriefComment for OverloadCandidate.
1218 const RawComment *
1219 getParameterComment(const ASTContext &Ctx,
1220                     const CodeCompleteConsumer::OverloadCandidate &Result,
1221                     unsigned ArgIndex);
1222 
1223 /// A simple code-completion consumer that prints the results it
1224 /// receives in a simple format.
1225 class PrintingCodeCompleteConsumer : public CodeCompleteConsumer {
1226   /// The raw output stream.
1227   raw_ostream &OS;
1228 
1229   CodeCompletionTUInfo CCTUInfo;
1230 
1231 public:
1232   /// Create a new printing code-completion consumer that prints its
1233   /// results to the given raw output stream.
1234   PrintingCodeCompleteConsumer(const CodeCompleteOptions &CodeCompleteOpts,
1235                                raw_ostream &OS)
1236       : CodeCompleteConsumer(CodeCompleteOpts), OS(OS),
1237         CCTUInfo(std::make_shared<GlobalCodeCompletionAllocator>()) {}
1238 
1239   /// Prints the finalized code-completion results.
1240   void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
1241                                   CodeCompletionResult *Results,
1242                                   unsigned NumResults) override;
1243 
1244   void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1245                                  OverloadCandidate *Candidates,
1246                                  unsigned NumCandidates,
1247                                  SourceLocation OpenParLoc,
1248                                  bool Braced) override;
1249 
1250   bool isResultFilteredOut(StringRef Filter, CodeCompletionResult Results) override;
1251 
1252   CodeCompletionAllocator &getAllocator() override {
1253     return CCTUInfo.getAllocator();
1254   }
1255 
1256   CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
1257 };
1258 
1259 } // namespace clang
1260 
1261 #endif // LLVM_CLANG_SEMA_CODECOMPLETECONSUMER_H
1262