• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===---- CodeCompleteConsumer.h - Code Completion Interface ----*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file defines the CodeCompleteConsumer class.
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/CanonicalType.h"
18 #include "clang/AST/DeclBase.h"
19 #include "clang/AST/Type.h"
20 #include "clang/Sema/CodeCompleteOptions.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/Support/Allocator.h"
25 #include <string>
26 #include <utility>
27 
28 namespace clang {
29 
30 class Decl;
31 
32 /// \brief Default priority values for code-completion results based
33 /// on their kind.
34 enum {
35   /// \brief Priority for the next initialization in a constructor initializer
36   /// list.
37   CCP_NextInitializer = 7,
38   /// \brief Priority for an enumeration constant inside a switch whose
39   /// condition is of the enumeration type.
40   CCP_EnumInCase = 7,
41   /// \brief Priority for a send-to-super completion.
42   CCP_SuperCompletion = 20,
43   /// \brief Priority for a declaration that is in the local scope.
44   CCP_LocalDeclaration = 34,
45   /// \brief Priority for a member declaration found from the current
46   /// method or member function.
47   CCP_MemberDeclaration = 35,
48   /// \brief Priority for a language keyword (that isn't any of the other
49   /// categories).
50   CCP_Keyword = 40,
51   /// \brief Priority for a code pattern.
52   CCP_CodePattern = 40,
53   /// \brief Priority for a non-type declaration.
54   CCP_Declaration = 50,
55   /// \brief Priority for a type.
56   CCP_Type = CCP_Declaration,
57   /// \brief Priority for a constant value (e.g., enumerator).
58   CCP_Constant = 65,
59   /// \brief Priority for a preprocessor macro.
60   CCP_Macro = 70,
61   /// \brief Priority for a nested-name-specifier.
62   CCP_NestedNameSpecifier = 75,
63   /// \brief Priority for a result that isn't likely to be what the user wants,
64   /// but is included for completeness.
65   CCP_Unlikely = 80,
66 
67   /// \brief Priority for the Objective-C "_cmd" implicit parameter.
68   CCP_ObjC_cmd = CCP_Unlikely
69 };
70 
71 /// \brief Priority value deltas that are added to code-completion results
72 /// based on the context of the result.
73 enum {
74   /// \brief The result is in a base class.
75   CCD_InBaseClass = 2,
76   /// \brief The result is a C++ non-static member function whose qualifiers
77   /// exactly match the object type on which the member function can be called.
78   CCD_ObjectQualifierMatch = -1,
79   /// \brief The selector of the given message exactly matches the selector
80   /// of the current method, which might imply that some kind of delegation
81   /// is occurring.
82   CCD_SelectorMatch = -3,
83 
84   /// \brief Adjustment to the "bool" type in Objective-C, where the typedef
85   /// "BOOL" is preferred.
86   CCD_bool_in_ObjC = 1,
87 
88   /// \brief Adjustment for KVC code pattern priorities when it doesn't look
89   /// like the
90   CCD_ProbablyNotObjCCollection = 15,
91 
92   /// \brief An Objective-C method being used as a property.
93   CCD_MethodAsProperty = 2
94 };
95 
96 /// \brief Priority value factors by which we will divide or multiply the
97 /// priority of a code-completion result.
98 enum {
99   /// \brief Divide by this factor when a code-completion result's type exactly
100   /// matches the type we expect.
101   CCF_ExactTypeMatch = 4,
102   /// \brief Divide by this factor when a code-completion result's type is
103   /// similar to the type we expect (e.g., both arithmetic types, both
104   /// Objective-C object pointer types).
105   CCF_SimilarTypeMatch = 2
106 };
107 
108 /// \brief A simplified classification of types used when determining
109 /// "similar" types for code completion.
110 enum SimplifiedTypeClass {
111   STC_Arithmetic,
112   STC_Array,
113   STC_Block,
114   STC_Function,
115   STC_ObjectiveC,
116   STC_Other,
117   STC_Pointer,
118   STC_Record,
119   STC_Void
120 };
121 
122 /// \brief Determine the simplified type class of the given canonical type.
123 SimplifiedTypeClass getSimplifiedTypeClass(CanQualType T);
124 
125 /// \brief Determine the type that this declaration will have if it is used
126 /// as a type or in an expression.
127 QualType getDeclUsageType(ASTContext &C, const NamedDecl *ND);
128 
129 /// \brief Determine the priority to be given to a macro code completion result
130 /// with the given name.
131 ///
132 /// \param MacroName The name of the macro.
133 ///
134 /// \param LangOpts Options describing the current language dialect.
135 ///
136 /// \param PreferredTypeIsPointer Whether the preferred type for the context
137 /// of this macro is a pointer type.
138 unsigned getMacroUsagePriority(StringRef MacroName,
139                                const LangOptions &LangOpts,
140                                bool PreferredTypeIsPointer = false);
141 
142 /// \brief Determine the libclang cursor kind associated with the given
143 /// declaration.
144 CXCursorKind getCursorKindForDecl(const Decl *D);
145 
146 class FunctionDecl;
147 class FunctionType;
148 class FunctionTemplateDecl;
149 class IdentifierInfo;
150 class NamedDecl;
151 class NestedNameSpecifier;
152 class Sema;
153 
154 /// \brief The context in which code completion occurred, so that the
155 /// code-completion consumer can process the results accordingly.
156 class CodeCompletionContext {
157 public:
158   enum Kind {
159     /// \brief An unspecified code-completion context.
160     CCC_Other,
161     /// \brief An unspecified code-completion context where we should also add
162     /// macro completions.
163     CCC_OtherWithMacros,
164     /// \brief Code completion occurred within a "top-level" completion context,
165     /// e.g., at namespace or global scope.
166     CCC_TopLevel,
167     /// \brief Code completion occurred within an Objective-C interface,
168     /// protocol, or category interface.
169     CCC_ObjCInterface,
170     /// \brief Code completion occurred within an Objective-C implementation
171     /// or category implementation.
172     CCC_ObjCImplementation,
173     /// \brief Code completion occurred within the instance variable list of
174     /// an Objective-C interface, implementation, or category implementation.
175     CCC_ObjCIvarList,
176     /// \brief Code completion occurred within a class, struct, or union.
177     CCC_ClassStructUnion,
178     /// \brief Code completion occurred where a statement (or declaration) is
179     /// expected in a function, method, or block.
180     CCC_Statement,
181     /// \brief Code completion occurred where an expression is expected.
182     CCC_Expression,
183     /// \brief Code completion occurred where an Objective-C message receiver
184     /// is expected.
185     CCC_ObjCMessageReceiver,
186     /// \brief Code completion occurred on the right-hand side of a member
187     /// access expression using the dot operator.
188     ///
189     /// The results of this completion are the members of the type being
190     /// accessed. The type itself is available via
191     /// \c CodeCompletionContext::getType().
192     CCC_DotMemberAccess,
193     /// \brief Code completion occurred on the right-hand side of a member
194     /// access expression using the arrow operator.
195     ///
196     /// The results of this completion are the members of the type being
197     /// accessed. The type itself is available via
198     /// \c CodeCompletionContext::getType().
199     CCC_ArrowMemberAccess,
200     /// \brief Code completion occurred on the right-hand side of an Objective-C
201     /// property access expression.
202     ///
203     /// The results of this completion are the members of the type being
204     /// accessed. The type itself is available via
205     /// \c CodeCompletionContext::getType().
206     CCC_ObjCPropertyAccess,
207     /// \brief Code completion occurred after the "enum" keyword, to indicate
208     /// an enumeration name.
209     CCC_EnumTag,
210     /// \brief Code completion occurred after the "union" keyword, to indicate
211     /// a union name.
212     CCC_UnionTag,
213     /// \brief Code completion occurred after the "struct" or "class" keyword,
214     /// to indicate a struct or class name.
215     CCC_ClassOrStructTag,
216     /// \brief Code completion occurred where a protocol name is expected.
217     CCC_ObjCProtocolName,
218     /// \brief Code completion occurred where a namespace or namespace alias
219     /// is expected.
220     CCC_Namespace,
221     /// \brief Code completion occurred where a type name is expected.
222     CCC_Type,
223     /// \brief Code completion occurred where a new name is expected.
224     CCC_Name,
225     /// \brief Code completion occurred where a new name is expected and a
226     /// qualified name is permissible.
227     CCC_PotentiallyQualifiedName,
228     /// \brief Code completion occurred where an macro is being defined.
229     CCC_MacroName,
230     /// \brief Code completion occurred where a macro name is expected
231     /// (without any arguments, in the case of a function-like macro).
232     CCC_MacroNameUse,
233     /// \brief Code completion occurred within a preprocessor expression.
234     CCC_PreprocessorExpression,
235     /// \brief Code completion occurred where a preprocessor directive is
236     /// expected.
237     CCC_PreprocessorDirective,
238     /// \brief Code completion occurred in a context where natural language is
239     /// expected, e.g., a comment or string literal.
240     ///
241     /// This context usually implies that no completions should be added,
242     /// unless they come from an appropriate natural-language dictionary.
243     CCC_NaturalLanguage,
244     /// \brief Code completion for a selector, as in an \@selector expression.
245     CCC_SelectorName,
246     /// \brief Code completion within a type-qualifier list.
247     CCC_TypeQualifiers,
248     /// \brief Code completion in a parenthesized expression, which means that
249     /// we may also have types here in C and Objective-C (as well as in C++).
250     CCC_ParenthesizedExpression,
251     /// \brief Code completion where an Objective-C instance message is
252     /// expected.
253     CCC_ObjCInstanceMessage,
254     /// \brief Code completion where an Objective-C class message is expected.
255     CCC_ObjCClassMessage,
256     /// \brief Code completion where the name of an Objective-C class is
257     /// expected.
258     CCC_ObjCInterfaceName,
259     /// \brief Code completion where an Objective-C category name is expected.
260     CCC_ObjCCategoryName,
261     /// \brief An unknown context, in which we are recovering from a parsing
262     /// error and don't know which completions we should give.
263     CCC_Recovery
264   };
265 
266 private:
267   enum Kind Kind;
268 
269   /// \brief The type that would prefer to see at this point (e.g., the type
270   /// of an initializer or function parameter).
271   QualType PreferredType;
272 
273   /// \brief The type of the base object in a member access expression.
274   QualType BaseType;
275 
276   /// \brief The identifiers for Objective-C selector parts.
277   ArrayRef<IdentifierInfo *> SelIdents;
278 
279 public:
280   /// \brief Construct a new code-completion context of the given kind.
CodeCompletionContext(enum Kind Kind)281   CodeCompletionContext(enum Kind Kind) : Kind(Kind), SelIdents(None) { }
282 
283   /// \brief Construct a new code-completion context of the given kind.
284   CodeCompletionContext(enum Kind Kind, QualType T,
285                         ArrayRef<IdentifierInfo *> SelIdents = None)
Kind(Kind)286                         : Kind(Kind),
287                           SelIdents(SelIdents) {
288     if (Kind == CCC_DotMemberAccess || Kind == CCC_ArrowMemberAccess ||
289         Kind == CCC_ObjCPropertyAccess || Kind == CCC_ObjCClassMessage ||
290         Kind == CCC_ObjCInstanceMessage)
291       BaseType = T;
292     else
293       PreferredType = T;
294   }
295 
296   /// \brief Retrieve the kind of code-completion context.
getKind()297   enum Kind getKind() const { return Kind; }
298 
299   /// \brief Retrieve the type that this expression would prefer to have, e.g.,
300   /// if the expression is a variable initializer or a function argument, the
301   /// type of the corresponding variable or function parameter.
getPreferredType()302   QualType getPreferredType() const { return PreferredType; }
303 
304   /// \brief Retrieve the type of the base object in a member-access
305   /// expression.
getBaseType()306   QualType getBaseType() const { return BaseType; }
307 
308   /// \brief Retrieve the Objective-C selector identifiers.
getSelIdents()309   ArrayRef<IdentifierInfo *> getSelIdents() const { return SelIdents; }
310 
311   /// \brief Determines whether we want C++ constructors as results within this
312   /// context.
313   bool wantConstructorResults() const;
314 };
315 
316 
317 /// \brief A "string" used to describe how code completion can
318 /// be performed for an entity.
319 ///
320 /// A code completion string typically shows how a particular entity can be
321 /// used. For example, the code completion string for a function would show
322 /// the syntax to call it, including the parentheses, placeholders for the
323 /// arguments, etc.
324 class CodeCompletionString {
325 public:
326   /// \brief The different kinds of "chunks" that can occur within a code
327   /// completion string.
328   enum ChunkKind {
329     /// \brief The piece of text that the user is expected to type to
330     /// match the code-completion string, typically a keyword or the name of a
331     /// declarator or macro.
332     CK_TypedText,
333     /// \brief A piece of text that should be placed in the buffer, e.g.,
334     /// parentheses or a comma in a function call.
335     CK_Text,
336     /// \brief A code completion string that is entirely optional. For example,
337     /// an optional code completion string that describes the default arguments
338     /// in a function call.
339     CK_Optional,
340     /// \brief A string that acts as a placeholder for, e.g., a function
341     /// call argument.
342     CK_Placeholder,
343     /// \brief A piece of text that describes something about the result but
344     /// should not be inserted into the buffer.
345     CK_Informative,
346     /// \brief A piece of text that describes the type of an entity or, for
347     /// functions and methods, the return type.
348     CK_ResultType,
349     /// \brief A piece of text that describes the parameter that corresponds
350     /// to the code-completion location within a function call, message send,
351     /// macro invocation, etc.
352     CK_CurrentParameter,
353     /// \brief A left parenthesis ('(').
354     CK_LeftParen,
355     /// \brief A right parenthesis (')').
356     CK_RightParen,
357     /// \brief A left bracket ('[').
358     CK_LeftBracket,
359     /// \brief A right bracket (']').
360     CK_RightBracket,
361     /// \brief A left brace ('{').
362     CK_LeftBrace,
363     /// \brief A right brace ('}').
364     CK_RightBrace,
365     /// \brief A left angle bracket ('<').
366     CK_LeftAngle,
367     /// \brief A right angle bracket ('>').
368     CK_RightAngle,
369     /// \brief A comma separator (',').
370     CK_Comma,
371     /// \brief A colon (':').
372     CK_Colon,
373     /// \brief A semicolon (';').
374     CK_SemiColon,
375     /// \brief An '=' sign.
376     CK_Equal,
377     /// \brief Horizontal whitespace (' ').
378     CK_HorizontalSpace,
379     /// \brief Vertical whitespace ('\\n' or '\\r\\n', depending on the
380     /// platform).
381     CK_VerticalSpace
382   };
383 
384   /// \brief One piece of the code completion string.
385   struct Chunk {
386     /// \brief The kind of data stored in this piece of the code completion
387     /// string.
388     ChunkKind Kind;
389 
390     union {
391       /// \brief The text string associated with a CK_Text, CK_Placeholder,
392       /// CK_Informative, or CK_Comma chunk.
393       /// The string is owned by the chunk and will be deallocated
394       /// (with delete[]) when the chunk is destroyed.
395       const char *Text;
396 
397       /// \brief The code completion string associated with a CK_Optional chunk.
398       /// The optional code completion string is owned by the chunk, and will
399       /// be deallocated (with delete) when the chunk is destroyed.
400       CodeCompletionString *Optional;
401     };
402 
ChunkChunk403     Chunk() : Kind(CK_Text), Text(nullptr) { }
404 
405     explicit Chunk(ChunkKind Kind, const char *Text = "");
406 
407     /// \brief Create a new text chunk.
408     static Chunk CreateText(const char *Text);
409 
410     /// \brief Create a new optional chunk.
411     static Chunk CreateOptional(CodeCompletionString *Optional);
412 
413     /// \brief Create a new placeholder chunk.
414     static Chunk CreatePlaceholder(const char *Placeholder);
415 
416     /// \brief Create a new informative chunk.
417     static Chunk CreateInformative(const char *Informative);
418 
419     /// \brief Create a new result type chunk.
420     static Chunk CreateResultType(const char *ResultType);
421 
422     /// \brief Create a new current-parameter chunk.
423     static Chunk CreateCurrentParameter(const char *CurrentParameter);
424   };
425 
426 private:
427   /// \brief The number of chunks stored in this string.
428   unsigned NumChunks : 16;
429 
430   /// \brief The number of annotations for this code-completion result.
431   unsigned NumAnnotations : 16;
432 
433   /// \brief The priority of this code-completion string.
434   unsigned Priority : 16;
435 
436   /// \brief The availability of this code-completion result.
437   unsigned Availability : 2;
438 
439   /// \brief The name of the parent context.
440   StringRef ParentName;
441 
442   /// \brief A brief documentation comment attached to the declaration of
443   /// entity being completed by this result.
444   const char *BriefComment;
445 
446   CodeCompletionString(const CodeCompletionString &) = delete;
447   void operator=(const CodeCompletionString &) = delete;
448 
449   CodeCompletionString(const Chunk *Chunks, unsigned NumChunks,
450                        unsigned Priority, CXAvailabilityKind Availability,
451                        const char **Annotations, unsigned NumAnnotations,
452                        StringRef ParentName,
453                        const char *BriefComment);
454   ~CodeCompletionString() = default;
455 
456   friend class CodeCompletionBuilder;
457   friend class CodeCompletionResult;
458 
459 public:
460   typedef const Chunk *iterator;
begin()461   iterator begin() const { return reinterpret_cast<const Chunk *>(this + 1); }
end()462   iterator end() const { return begin() + NumChunks; }
empty()463   bool empty() const { return NumChunks == 0; }
size()464   unsigned size() const { return NumChunks; }
465 
466   const Chunk &operator[](unsigned I) const {
467     assert(I < size() && "Chunk index out-of-range");
468     return begin()[I];
469   }
470 
471   /// \brief Returns the text in the TypedText chunk.
472   const char *getTypedText() const;
473 
474   /// \brief Retrieve the priority of this code completion result.
getPriority()475   unsigned getPriority() const { return Priority; }
476 
477   /// \brief Retrieve the availability of this code completion result.
getAvailability()478   unsigned getAvailability() const { return Availability; }
479 
480   /// \brief Retrieve the number of annotations for this code completion result.
481   unsigned getAnnotationCount() const;
482 
483   /// \brief Retrieve the annotation string specified by \c AnnotationNr.
484   const char *getAnnotation(unsigned AnnotationNr) const;
485 
486   /// \brief Retrieve the name of the parent context.
getParentContextName()487   StringRef getParentContextName() const {
488     return ParentName;
489   }
490 
getBriefComment()491   const char *getBriefComment() const {
492     return BriefComment;
493   }
494 
495   /// \brief Retrieve a string representation of the code completion string,
496   /// which is mainly useful for debugging.
497   std::string getAsString() const;
498 };
499 
500 /// \brief An allocator used specifically for the purpose of code completion.
501 class CodeCompletionAllocator : public llvm::BumpPtrAllocator {
502 public:
503   /// \brief Copy the given string into this allocator.
504   const char *CopyString(const Twine &String);
505 };
506 
507 /// \brief Allocator for a cached set of global code completions.
508 class GlobalCodeCompletionAllocator
509   : public CodeCompletionAllocator,
510     public RefCountedBase<GlobalCodeCompletionAllocator>
511 {
512 
513 };
514 
515 class CodeCompletionTUInfo {
516   llvm::DenseMap<const DeclContext *, StringRef> ParentNames;
517   IntrusiveRefCntPtr<GlobalCodeCompletionAllocator> AllocatorRef;
518 
519 public:
CodeCompletionTUInfo(IntrusiveRefCntPtr<GlobalCodeCompletionAllocator> Allocator)520   explicit CodeCompletionTUInfo(
521       IntrusiveRefCntPtr<GlobalCodeCompletionAllocator> Allocator)
522       : AllocatorRef(std::move(Allocator)) {}
523 
getAllocatorRef()524   IntrusiveRefCntPtr<GlobalCodeCompletionAllocator> getAllocatorRef() const {
525     return AllocatorRef;
526   }
getAllocator()527   CodeCompletionAllocator &getAllocator() const {
528     assert(AllocatorRef);
529     return *AllocatorRef;
530   }
531 
532   StringRef getParentName(const DeclContext *DC);
533 };
534 
535 } // end namespace clang
536 
537 namespace llvm {
538   template <> struct isPodLike<clang::CodeCompletionString::Chunk> {
539     static const bool value = true;
540   };
541 }
542 
543 namespace clang {
544 
545 /// \brief A builder class used to construct new code-completion strings.
546 class CodeCompletionBuilder {
547 public:
548   typedef CodeCompletionString::Chunk Chunk;
549 
550 private:
551   CodeCompletionAllocator &Allocator;
552   CodeCompletionTUInfo &CCTUInfo;
553   unsigned Priority;
554   CXAvailabilityKind Availability;
555   StringRef ParentName;
556   const char *BriefComment;
557 
558   /// \brief The chunks stored in this string.
559   SmallVector<Chunk, 4> Chunks;
560 
561   SmallVector<const char *, 2> Annotations;
562 
563 public:
564   CodeCompletionBuilder(CodeCompletionAllocator &Allocator,
565                         CodeCompletionTUInfo &CCTUInfo)
566     : Allocator(Allocator), CCTUInfo(CCTUInfo),
567       Priority(0), Availability(CXAvailability_Available),
568       BriefComment(nullptr) { }
569 
570   CodeCompletionBuilder(CodeCompletionAllocator &Allocator,
571                         CodeCompletionTUInfo &CCTUInfo,
572                         unsigned Priority, CXAvailabilityKind Availability)
573     : Allocator(Allocator), CCTUInfo(CCTUInfo),
574       Priority(Priority), Availability(Availability),
575       BriefComment(nullptr) { }
576 
577   /// \brief Retrieve the allocator into which the code completion
578   /// strings should be allocated.
579   CodeCompletionAllocator &getAllocator() const { return Allocator; }
580 
581   CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo; }
582 
583   /// \brief Take the resulting completion string.
584   ///
585   /// This operation can only be performed once.
586   CodeCompletionString *TakeString();
587 
588   /// \brief Add a new typed-text chunk.
589   void AddTypedTextChunk(const char *Text);
590 
591   /// \brief Add a new text chunk.
592   void AddTextChunk(const char *Text);
593 
594   /// \brief Add a new optional chunk.
595   void AddOptionalChunk(CodeCompletionString *Optional);
596 
597   /// \brief Add a new placeholder chunk.
598   void AddPlaceholderChunk(const char *Placeholder);
599 
600   /// \brief Add a new informative chunk.
601   void AddInformativeChunk(const char *Text);
602 
603   /// \brief Add a new result-type chunk.
604   void AddResultTypeChunk(const char *ResultType);
605 
606   /// \brief Add a new current-parameter chunk.
607   void AddCurrentParameterChunk(const char *CurrentParameter);
608 
609   /// \brief Add a new chunk.
610   void AddChunk(CodeCompletionString::ChunkKind CK, const char *Text = "");
611 
612   void AddAnnotation(const char *A) { Annotations.push_back(A); }
613 
614   /// \brief Add the parent context information to this code completion.
615   void addParentContext(const DeclContext *DC);
616 
617   const char *getBriefComment() const { return BriefComment; }
618   void addBriefComment(StringRef Comment);
619 
620   StringRef getParentName() const { return ParentName; }
621 };
622 
623 /// \brief Captures a result of code completion.
624 class CodeCompletionResult {
625 public:
626   /// \brief Describes the kind of result generated.
627   enum ResultKind {
628     RK_Declaration = 0, ///< Refers to a declaration
629     RK_Keyword,         ///< Refers to a keyword or symbol.
630     RK_Macro,           ///< Refers to a macro
631     RK_Pattern          ///< Refers to a precomputed pattern.
632   };
633 
634   /// \brief When Kind == RK_Declaration or RK_Pattern, the declaration we are
635   /// referring to. In the latter case, the declaration might be NULL.
636   const NamedDecl *Declaration;
637 
638   union {
639     /// \brief When Kind == RK_Keyword, the string representing the keyword
640     /// or symbol's spelling.
641     const char *Keyword;
642 
643     /// \brief When Kind == RK_Pattern, the code-completion string that
644     /// describes the completion text to insert.
645     CodeCompletionString *Pattern;
646 
647     /// \brief When Kind == RK_Macro, the identifier that refers to a macro.
648     const IdentifierInfo *Macro;
649   };
650 
651   /// \brief The priority of this particular code-completion result.
652   unsigned Priority;
653 
654   /// \brief Specifies which parameter (of a function, Objective-C method,
655   /// macro, etc.) we should start with when formatting the result.
656   unsigned StartParameter;
657 
658   /// \brief The kind of result stored here.
659   ResultKind Kind;
660 
661   /// \brief The cursor kind that describes this result.
662   CXCursorKind CursorKind;
663 
664   /// \brief The availability of this result.
665   CXAvailabilityKind Availability;
666 
667   /// \brief Whether this result is hidden by another name.
668   bool Hidden : 1;
669 
670   /// \brief Whether this result was found via lookup into a base class.
671   bool QualifierIsInformative : 1;
672 
673   /// \brief Whether this declaration is the beginning of a
674   /// nested-name-specifier and, therefore, should be followed by '::'.
675   bool StartsNestedNameSpecifier : 1;
676 
677   /// \brief Whether all parameters (of a function, Objective-C
678   /// method, etc.) should be considered "informative".
679   bool AllParametersAreInformative : 1;
680 
681   /// \brief Whether we're completing a declaration of the given entity,
682   /// rather than a use of that entity.
683   bool DeclaringEntity : 1;
684 
685   /// \brief If the result should have a nested-name-specifier, this is it.
686   /// When \c QualifierIsInformative, the nested-name-specifier is
687   /// informative rather than required.
688   NestedNameSpecifier *Qualifier;
689 
690   /// \brief Build a result that refers to a declaration.
691   CodeCompletionResult(const NamedDecl *Declaration,
692                        unsigned Priority,
693                        NestedNameSpecifier *Qualifier = nullptr,
694                        bool QualifierIsInformative = false,
695                        bool Accessible = true)
696     : Declaration(Declaration), Priority(Priority),
697       StartParameter(0), Kind(RK_Declaration),
698       Availability(CXAvailability_Available), Hidden(false),
699       QualifierIsInformative(QualifierIsInformative),
700       StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
701       DeclaringEntity(false), Qualifier(Qualifier) {
702     computeCursorKindAndAvailability(Accessible);
703   }
704 
705   /// \brief Build a result that refers to a keyword or symbol.
706   CodeCompletionResult(const char *Keyword, unsigned Priority = CCP_Keyword)
707     : Declaration(nullptr), Keyword(Keyword), Priority(Priority),
708       StartParameter(0), Kind(RK_Keyword), CursorKind(CXCursor_NotImplemented),
709       Availability(CXAvailability_Available), Hidden(false),
710       QualifierIsInformative(0), StartsNestedNameSpecifier(false),
711       AllParametersAreInformative(false), DeclaringEntity(false),
712       Qualifier(nullptr) {}
713 
714   /// \brief Build a result that refers to a macro.
715   CodeCompletionResult(const IdentifierInfo *Macro,
716                        unsigned Priority = CCP_Macro)
717     : Declaration(nullptr), Macro(Macro), Priority(Priority), StartParameter(0),
718       Kind(RK_Macro), CursorKind(CXCursor_MacroDefinition),
719       Availability(CXAvailability_Available), Hidden(false),
720       QualifierIsInformative(0), StartsNestedNameSpecifier(false),
721       AllParametersAreInformative(false), DeclaringEntity(false),
722       Qualifier(nullptr) {}
723 
724   /// \brief Build a result that refers to a pattern.
725   CodeCompletionResult(CodeCompletionString *Pattern,
726                        unsigned Priority = CCP_CodePattern,
727                        CXCursorKind CursorKind = CXCursor_NotImplemented,
728                    CXAvailabilityKind Availability = CXAvailability_Available,
729                        const NamedDecl *D = nullptr)
730     : Declaration(D), Pattern(Pattern), Priority(Priority), StartParameter(0),
731       Kind(RK_Pattern), CursorKind(CursorKind), Availability(Availability),
732       Hidden(false), QualifierIsInformative(0),
733       StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
734       DeclaringEntity(false), Qualifier(nullptr)
735   {
736   }
737 
738   /// \brief Build a result that refers to a pattern with an associated
739   /// declaration.
740   CodeCompletionResult(CodeCompletionString *Pattern, NamedDecl *D,
741                        unsigned Priority)
742     : Declaration(D), Pattern(Pattern), Priority(Priority), StartParameter(0),
743       Kind(RK_Pattern), Availability(CXAvailability_Available), Hidden(false),
744       QualifierIsInformative(false), StartsNestedNameSpecifier(false),
745       AllParametersAreInformative(false), DeclaringEntity(false),
746       Qualifier(nullptr) {
747     computeCursorKindAndAvailability();
748   }
749 
750   /// \brief Retrieve the declaration stored in this result.
751   const NamedDecl *getDeclaration() const {
752     assert(Kind == RK_Declaration && "Not a declaration result");
753     return Declaration;
754   }
755 
756   /// \brief Retrieve the keyword stored in this result.
757   const char *getKeyword() const {
758     assert(Kind == RK_Keyword && "Not a keyword result");
759     return Keyword;
760   }
761 
762   /// \brief Create a new code-completion string that describes how to insert
763   /// this result into a program.
764   ///
765   /// \param S The semantic analysis that created the result.
766   ///
767   /// \param Allocator The allocator that will be used to allocate the
768   /// string itself.
769   CodeCompletionString *CreateCodeCompletionString(Sema &S,
770                                          const CodeCompletionContext &CCContext,
771                                            CodeCompletionAllocator &Allocator,
772                                            CodeCompletionTUInfo &CCTUInfo,
773                                            bool IncludeBriefComments);
774   CodeCompletionString *CreateCodeCompletionString(ASTContext &Ctx,
775                                                    Preprocessor &PP,
776                                          const CodeCompletionContext &CCContext,
777                                            CodeCompletionAllocator &Allocator,
778                                            CodeCompletionTUInfo &CCTUInfo,
779                                            bool IncludeBriefComments);
780 
781 private:
782   void computeCursorKindAndAvailability(bool Accessible = true);
783 };
784 
785 bool operator<(const CodeCompletionResult &X, const CodeCompletionResult &Y);
786 
787 inline bool operator>(const CodeCompletionResult &X,
788                       const CodeCompletionResult &Y) {
789   return Y < X;
790 }
791 
792 inline bool operator<=(const CodeCompletionResult &X,
793                       const CodeCompletionResult &Y) {
794   return !(Y < X);
795 }
796 
797 inline bool operator>=(const CodeCompletionResult &X,
798                        const CodeCompletionResult &Y) {
799   return !(X < Y);
800 }
801 
802 
803 raw_ostream &operator<<(raw_ostream &OS,
804                               const CodeCompletionString &CCS);
805 
806 /// \brief Abstract interface for a consumer of code-completion
807 /// information.
808 class CodeCompleteConsumer {
809 protected:
810   const CodeCompleteOptions CodeCompleteOpts;
811 
812   /// \brief Whether the output format for the code-completion consumer is
813   /// binary.
814   bool OutputIsBinary;
815 
816 public:
817   class OverloadCandidate {
818   public:
819     /// \brief Describes the type of overload candidate.
820     enum CandidateKind {
821       /// \brief The candidate is a function declaration.
822       CK_Function,
823       /// \brief The candidate is a function template.
824       CK_FunctionTemplate,
825       /// \brief The "candidate" is actually a variable, expression, or block
826       /// for which we only have a function prototype.
827       CK_FunctionType
828     };
829 
830   private:
831     /// \brief The kind of overload candidate.
832     CandidateKind Kind;
833 
834     union {
835       /// \brief The function overload candidate, available when
836       /// Kind == CK_Function.
837       FunctionDecl *Function;
838 
839       /// \brief The function template overload candidate, available when
840       /// Kind == CK_FunctionTemplate.
841       FunctionTemplateDecl *FunctionTemplate;
842 
843       /// \brief The function type that describes the entity being called,
844       /// when Kind == CK_FunctionType.
845       const FunctionType *Type;
846     };
847 
848   public:
849     OverloadCandidate(FunctionDecl *Function)
850       : Kind(CK_Function), Function(Function) { }
851 
852     OverloadCandidate(FunctionTemplateDecl *FunctionTemplateDecl)
853       : Kind(CK_FunctionTemplate), FunctionTemplate(FunctionTemplateDecl) { }
854 
855     OverloadCandidate(const FunctionType *Type)
856       : Kind(CK_FunctionType), Type(Type) { }
857 
858     /// \brief Determine the kind of overload candidate.
859     CandidateKind getKind() const { return Kind; }
860 
861     /// \brief Retrieve the function overload candidate or the templated
862     /// function declaration for a function template.
863     FunctionDecl *getFunction() const;
864 
865     /// \brief Retrieve the function template overload candidate.
866     FunctionTemplateDecl *getFunctionTemplate() const {
867       assert(getKind() == CK_FunctionTemplate && "Not a function template");
868       return FunctionTemplate;
869     }
870 
871     /// \brief Retrieve the function type of the entity, regardless of how the
872     /// function is stored.
873     const FunctionType *getFunctionType() const;
874 
875     /// \brief Create a new code-completion string that describes the function
876     /// signature of this overload candidate.
877     CodeCompletionString *CreateSignatureString(unsigned CurrentArg,
878                                                 Sema &S,
879                                       CodeCompletionAllocator &Allocator,
880                                       CodeCompletionTUInfo &CCTUInfo,
881                                       bool IncludeBriefComments) const;
882   };
883 
884   CodeCompleteConsumer(const CodeCompleteOptions &CodeCompleteOpts,
885                        bool OutputIsBinary)
886     : CodeCompleteOpts(CodeCompleteOpts), OutputIsBinary(OutputIsBinary)
887   { }
888 
889   /// \brief Whether the code-completion consumer wants to see macros.
890   bool includeMacros() const {
891     return CodeCompleteOpts.IncludeMacros;
892   }
893 
894   /// \brief Whether the code-completion consumer wants to see code patterns.
895   bool includeCodePatterns() const {
896     return CodeCompleteOpts.IncludeCodePatterns;
897   }
898 
899   /// \brief Whether to include global (top-level) declaration results.
900   bool includeGlobals() const {
901     return CodeCompleteOpts.IncludeGlobals;
902   }
903 
904   /// \brief Whether to include brief documentation comments within the set of
905   /// code completions returned.
906   bool includeBriefComments() const {
907     return CodeCompleteOpts.IncludeBriefComments;
908   }
909 
910   /// \brief Determine whether the output of this consumer is binary.
911   bool isOutputBinary() const { return OutputIsBinary; }
912 
913   /// \brief Deregisters and destroys this code-completion consumer.
914   virtual ~CodeCompleteConsumer();
915 
916   /// \name Code-completion callbacks
917   //@{
918   /// \brief Process the finalized code-completion results.
919   virtual void ProcessCodeCompleteResults(Sema &S,
920                                           CodeCompletionContext Context,
921                                           CodeCompletionResult *Results,
922                                           unsigned NumResults) { }
923 
924   /// \param S the semantic-analyzer object for which code-completion is being
925   /// done.
926   ///
927   /// \param CurrentArg the index of the current argument.
928   ///
929   /// \param Candidates an array of overload candidates.
930   ///
931   /// \param NumCandidates the number of overload candidates
932   virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
933                                          OverloadCandidate *Candidates,
934                                          unsigned NumCandidates) { }
935   //@}
936 
937   /// \brief Retrieve the allocator that will be used to allocate
938   /// code completion strings.
939   virtual CodeCompletionAllocator &getAllocator() = 0;
940 
941   virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() = 0;
942 };
943 
944 /// \brief A simple code-completion consumer that prints the results it
945 /// receives in a simple format.
946 class PrintingCodeCompleteConsumer : public CodeCompleteConsumer {
947   /// \brief The raw output stream.
948   raw_ostream &OS;
949 
950   CodeCompletionTUInfo CCTUInfo;
951 
952 public:
953   /// \brief Create a new printing code-completion consumer that prints its
954   /// results to the given raw output stream.
955   PrintingCodeCompleteConsumer(const CodeCompleteOptions &CodeCompleteOpts,
956                                raw_ostream &OS)
957     : CodeCompleteConsumer(CodeCompleteOpts, false), OS(OS),
958       CCTUInfo(new GlobalCodeCompletionAllocator) {}
959 
960   /// \brief Prints the finalized code-completion results.
961   void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
962                                   CodeCompletionResult *Results,
963                                   unsigned NumResults) override;
964 
965   void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
966                                  OverloadCandidate *Candidates,
967                                  unsigned NumCandidates) override;
968 
969   CodeCompletionAllocator &getAllocator() override {
970     return CCTUInfo.getAllocator();
971   }
972 
973   CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
974 };
975 
976 } // end namespace clang
977 
978 #endif // LLVM_CLANG_SEMA_CODECOMPLETECONSUMER_H
979