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