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