clang  7.0.0svn
CodeCompleteConsumer.h
Go to the documentation of this file.
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"
21 #include "clang/Sema/DeclSpec.h"
22 #include "llvm/ADT/ArrayRef.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/None.h"
25 #include "llvm/ADT/Optional.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/Support/Allocator.h"
30 #include "llvm/Support/type_traits.h"
31 #include <cassert>
32 #include <memory>
33 #include <string>
34 #include <utility>
35 
36 namespace clang {
37 
38 class ASTContext;
39 class Decl;
40 class DeclContext;
41 class FunctionDecl;
42 class FunctionTemplateDecl;
43 class IdentifierInfo;
44 class LangOptions;
45 class NamedDecl;
46 class NestedNameSpecifier;
47 class Preprocessor;
48 class Sema;
49 class RawComment;
50 
51 /// Default priority values for code-completion results based
52 /// on their kind.
53 enum {
54  /// Priority for the next initialization in a constructor initializer
55  /// list.
57 
58  /// Priority for an enumeration constant inside a switch whose
59  /// condition is of the enumeration type.
61 
62  /// Priority for a send-to-super completion.
64 
65  /// Priority for a declaration that is in the local scope.
67 
68  /// Priority for a member declaration found from the current
69  /// method or member function.
71 
72  /// Priority for a language keyword (that isn't any of the other
73  /// categories).
75 
76  /// Priority for a code pattern.
78 
79  /// Priority for a non-type declaration.
81 
82  /// Priority for a type.
84 
85  /// Priority for a constant value (e.g., enumerator).
87 
88  /// Priority for a preprocessor macro.
89  CCP_Macro = 70,
90 
91  /// Priority for a nested-name-specifier.
93 
94  /// Priority for a result that isn't likely to be what the user wants,
95  /// but is included for completeness.
97 
98  /// Priority for the Objective-C "_cmd" implicit parameter.
100 };
101 
102 /// Priority value deltas that are added to code-completion results
103 /// based on the context of the result.
104 enum {
105  /// The result is in a base class.
107 
108  /// The result is a C++ non-static member function whose qualifiers
109  /// exactly match the object type on which the member function can be called.
111 
112  /// The selector of the given message exactly matches the selector
113  /// of the current method, which might imply that some kind of delegation
114  /// is occurring.
116 
117  /// Adjustment to the "bool" type in Objective-C, where the typedef
118  /// "BOOL" is preferred.
120 
121  /// Adjustment for KVC code pattern priorities when it doesn't look
122  /// like the
124 
125  /// An Objective-C method being used as a property.
127 
128  /// An Objective-C block property completed as a setter with a
129  /// block placeholder.
131 };
132 
133 /// Priority value factors by which we will divide or multiply the
134 /// priority of a code-completion result.
135 enum {
136  /// Divide by this factor when a code-completion result's type exactly
137  /// matches the type we expect.
139 
140  /// Divide by this factor when a code-completion result's type is
141  /// similar to the type we expect (e.g., both arithmetic types, both
142  /// Objective-C object pointer types).
144 };
145 
146 /// A simplified classification of types used when determining
147 /// "similar" types for code completion.
158 };
159 
160 /// Determine the simplified type class of the given canonical type.
162 
163 /// Determine the type that this declaration will have if it is used
164 /// as a type or in an expression.
166 
167 /// Determine the priority to be given to a macro code completion result
168 /// with the given name.
169 ///
170 /// \param MacroName The name of the macro.
171 ///
172 /// \param LangOpts Options describing the current language dialect.
173 ///
174 /// \param PreferredTypeIsPointer Whether the preferred type for the context
175 /// of this macro is a pointer type.
176 unsigned getMacroUsagePriority(StringRef MacroName,
177  const LangOptions &LangOpts,
178  bool PreferredTypeIsPointer = false);
179 
180 /// Determine the libclang cursor kind associated with the given
181 /// declaration.
183 
184 /// The context in which code completion occurred, so that the
185 /// code-completion consumer can process the results accordingly.
187 public:
188  enum Kind {
189  /// An unspecified code-completion context.
191 
192  /// An unspecified code-completion context where we should also add
193  /// macro completions.
195 
196  /// Code completion occurred within a "top-level" completion context,
197  /// e.g., at namespace or global scope.
199 
200  /// Code completion occurred within an Objective-C interface,
201  /// protocol, or category interface.
203 
204  /// Code completion occurred within an Objective-C implementation
205  /// or category implementation.
207 
208  /// Code completion occurred within the instance variable list of
209  /// an Objective-C interface, implementation, or category implementation.
211 
212  /// Code completion occurred within a class, struct, or union.
214 
215  /// Code completion occurred where a statement (or declaration) is
216  /// expected in a function, method, or block.
218 
219  /// Code completion occurred where an expression is expected.
221 
222  /// Code completion occurred where an Objective-C message receiver
223  /// is expected.
225 
226  /// Code completion occurred on the right-hand side of a member
227  /// access expression using the dot operator.
228  ///
229  /// The results of this completion are the members of the type being
230  /// accessed. The type itself is available via
231  /// \c CodeCompletionContext::getType().
233 
234  /// Code completion occurred on the right-hand side of a member
235  /// access expression using the arrow operator.
236  ///
237  /// The results of this completion are the members of the type being
238  /// accessed. The type itself is available via
239  /// \c CodeCompletionContext::getType().
241 
242  /// Code completion occurred on the right-hand side of an Objective-C
243  /// property access expression.
244  ///
245  /// The results of this completion are the members of the type being
246  /// accessed. The type itself is available via
247  /// \c CodeCompletionContext::getType().
249 
250  /// Code completion occurred after the "enum" keyword, to indicate
251  /// an enumeration name.
253 
254  /// Code completion occurred after the "union" keyword, to indicate
255  /// a union name.
257 
258  /// Code completion occurred after the "struct" or "class" keyword,
259  /// to indicate a struct or class name.
261 
262  /// Code completion occurred where a protocol name is expected.
264 
265  /// Code completion occurred where a namespace or namespace alias
266  /// is expected.
268 
269  /// Code completion occurred where a type name is expected.
271 
272  /// Code completion occurred where a new name is expected.
274 
275  /// Code completion occurred where a new name is expected and a
276  /// qualified name is permissible.
278 
279  /// Code completion occurred where an macro is being defined.
281 
282  /// Code completion occurred where a macro name is expected
283  /// (without any arguments, in the case of a function-like macro).
285 
286  /// Code completion occurred within a preprocessor expression.
288 
289  /// Code completion occurred where a preprocessor directive is
290  /// expected.
292 
293  /// Code completion occurred in a context where natural language is
294  /// expected, e.g., a comment or string literal.
295  ///
296  /// This context usually implies that no completions should be added,
297  /// unless they come from an appropriate natural-language dictionary.
299 
300  /// Code completion for a selector, as in an \@selector expression.
302 
303  /// Code completion within a type-qualifier list.
305 
306  /// Code completion in a parenthesized expression, which means that
307  /// we may also have types here in C and Objective-C (as well as in C++).
309 
310  /// Code completion where an Objective-C instance message is
311  /// expected.
313 
314  /// Code completion where an Objective-C class message is expected.
316 
317  /// Code completion where the name of an Objective-C class is
318  /// expected.
320 
321  /// Code completion where an Objective-C category name is expected.
323 
324  /// An unknown context, in which we are recovering from a parsing
325  /// error and don't know which completions we should give.
327  };
328 
329  using VisitedContextSet = llvm::SmallPtrSet<DeclContext *, 8>;
330 
331 private:
332  Kind CCKind;
333 
334  /// The type that would prefer to see at this point (e.g., the type
335  /// of an initializer or function parameter).
336  QualType PreferredType;
337 
338  /// The type of the base object in a member access expression.
339  QualType BaseType;
340 
341  /// The identifiers for Objective-C selector parts.
342  ArrayRef<IdentifierInfo *> SelIdents;
343 
344  /// The scope specifier that comes before the completion token e.g.
345  /// "a::b::"
346  llvm::Optional<CXXScopeSpec> ScopeSpecifier;
347 
348  /// A set of declaration contexts visited by Sema when doing lookup for
349  /// code completion.
350  VisitedContextSet VisitedContexts;
351 
352 public:
353  /// Construct a new code-completion context of the given kind.
354  CodeCompletionContext(Kind CCKind) : CCKind(CCKind), SelIdents(None) {}
355 
356  /// Construct a new code-completion context of the given kind.
358  ArrayRef<IdentifierInfo *> SelIdents = None)
359  : CCKind(CCKind), SelIdents(SelIdents) {
360  if (CCKind == CCC_DotMemberAccess || CCKind == CCC_ArrowMemberAccess ||
361  CCKind == CCC_ObjCPropertyAccess || CCKind == CCC_ObjCClassMessage ||
362  CCKind == CCC_ObjCInstanceMessage)
363  BaseType = T;
364  else
365  PreferredType = T;
366  }
367 
368  /// Retrieve the kind of code-completion context.
369  Kind getKind() const { return CCKind; }
370 
371  /// Retrieve the type that this expression would prefer to have, e.g.,
372  /// if the expression is a variable initializer or a function argument, the
373  /// type of the corresponding variable or function parameter.
374  QualType getPreferredType() const { return PreferredType; }
375 
376  /// Retrieve the type of the base object in a member-access
377  /// expression.
378  QualType getBaseType() const { return BaseType; }
379 
380  /// Retrieve the Objective-C selector identifiers.
381  ArrayRef<IdentifierInfo *> getSelIdents() const { return SelIdents; }
382 
383  /// Determines whether we want C++ constructors as results within this
384  /// context.
385  bool wantConstructorResults() const;
386 
387  /// Sets the scope specifier that comes before the completion token.
388  /// This is expected to be set in code completions on qualfied specifiers
389  /// (e.g. "a::b::").
391  this->ScopeSpecifier = std::move(SS);
392  }
393 
394  /// Adds a visited context.
396  VisitedContexts.insert(Ctx);
397  }
398 
399  /// Retrieves all visited contexts.
401  return VisitedContexts;
402  }
403 
405  if (ScopeSpecifier)
406  return ScopeSpecifier.getPointer();
407  return llvm::None;
408  }
409 };
410 
411 /// Get string representation of \p Kind, useful for for debugging.
413 
414 /// A "string" used to describe how code completion can
415 /// be performed for an entity.
416 ///
417 /// A code completion string typically shows how a particular entity can be
418 /// used. For example, the code completion string for a function would show
419 /// the syntax to call it, including the parentheses, placeholders for the
420 /// arguments, etc.
422 public:
423  /// The different kinds of "chunks" that can occur within a code
424  /// completion string.
425  enum ChunkKind {
426  /// The piece of text that the user is expected to type to
427  /// match the code-completion string, typically a keyword or the name of a
428  /// declarator or macro.
430 
431  /// A piece of text that should be placed in the buffer, e.g.,
432  /// parentheses or a comma in a function call.
434 
435  /// A code completion string that is entirely optional. For example,
436  /// an optional code completion string that describes the default arguments
437  /// in a function call.
439 
440  /// A string that acts as a placeholder for, e.g., a function
441  /// call argument.
443 
444  /// A piece of text that describes something about the result but
445  /// should not be inserted into the buffer.
447  /// A piece of text that describes the type of an entity or, for
448  /// functions and methods, the return type.
450 
451  /// A piece of text that describes the parameter that corresponds
452  /// to the code-completion location within a function call, message send,
453  /// macro invocation, etc.
455 
456  /// A left parenthesis ('(').
458 
459  /// A right parenthesis (')').
461 
462  /// A left bracket ('[').
464 
465  /// A right bracket (']').
467 
468  /// A left brace ('{').
470 
471  /// A right brace ('}').
473 
474  /// A left angle bracket ('<').
476 
477  /// A right angle bracket ('>').
479 
480  /// A comma separator (',').
482 
483  /// A colon (':').
485 
486  /// A semicolon (';').
488 
489  /// An '=' sign.
491 
492  /// Horizontal whitespace (' ').
494 
495  /// Vertical whitespace ('\\n' or '\\r\\n', depending on the
496  /// platform).
497  CK_VerticalSpace
498  };
499 
500  /// One piece of the code completion string.
501  struct Chunk {
502  /// The kind of data stored in this piece of the code completion
503  /// string.
504  ChunkKind Kind = CK_Text;
505 
506  union {
507  /// The text string associated with a CK_Text, CK_Placeholder,
508  /// CK_Informative, or CK_Comma chunk.
509  /// The string is owned by the chunk and will be deallocated
510  /// (with delete[]) when the chunk is destroyed.
511  const char *Text;
512 
513  /// The code completion string associated with a CK_Optional chunk.
514  /// The optional code completion string is owned by the chunk, and will
515  /// be deallocated (with delete) when the chunk is destroyed.
517  };
518 
519  Chunk() : Text(nullptr) {}
520 
521  explicit Chunk(ChunkKind Kind, const char *Text = "");
522 
523  /// Create a new text chunk.
524  static Chunk CreateText(const char *Text);
525 
526  /// Create a new optional chunk.
527  static Chunk CreateOptional(CodeCompletionString *Optional);
528 
529  /// Create a new placeholder chunk.
530  static Chunk CreatePlaceholder(const char *Placeholder);
531 
532  /// Create a new informative chunk.
533  static Chunk CreateInformative(const char *Informative);
534 
535  /// Create a new result type chunk.
536  static Chunk CreateResultType(const char *ResultType);
537 
538  /// Create a new current-parameter chunk.
539  static Chunk CreateCurrentParameter(const char *CurrentParameter);
540  };
541 
542 private:
543  friend class CodeCompletionBuilder;
544  friend class CodeCompletionResult;
545 
546  /// The number of chunks stored in this string.
547  unsigned NumChunks : 16;
548 
549  /// The number of annotations for this code-completion result.
550  unsigned NumAnnotations : 16;
551 
552  /// The priority of this code-completion string.
553  unsigned Priority : 16;
554 
555  /// The availability of this code-completion result.
556  unsigned Availability : 2;
557 
558  /// The name of the parent context.
559  StringRef ParentName;
560 
561  /// A brief documentation comment attached to the declaration of
562  /// entity being completed by this result.
563  const char *BriefComment;
564 
565  CodeCompletionString(const Chunk *Chunks, unsigned NumChunks,
566  unsigned Priority, CXAvailabilityKind Availability,
567  const char **Annotations, unsigned NumAnnotations,
568  StringRef ParentName,
569  const char *BriefComment);
570  ~CodeCompletionString() = default;
571 
572 public:
573  CodeCompletionString(const CodeCompletionString &) = delete;
574  CodeCompletionString &operator=(const CodeCompletionString &) = delete;
575 
576  using iterator = const Chunk *;
577 
578  iterator begin() const { return reinterpret_cast<const Chunk *>(this + 1); }
579  iterator end() const { return begin() + NumChunks; }
580  bool empty() const { return NumChunks == 0; }
581  unsigned size() const { return NumChunks; }
582 
583  const Chunk &operator[](unsigned I) const {
584  assert(I < size() && "Chunk index out-of-range");
585  return begin()[I];
586  }
587 
588  /// Returns the text in the TypedText chunk.
589  const char *getTypedText() const;
590 
591  /// Retrieve the priority of this code completion result.
592  unsigned getPriority() const { return Priority; }
593 
594  /// Retrieve the availability of this code completion result.
595  unsigned getAvailability() const { return Availability; }
596 
597  /// Retrieve the number of annotations for this code completion result.
598  unsigned getAnnotationCount() const;
599 
600  /// Retrieve the annotation string specified by \c AnnotationNr.
601  const char *getAnnotation(unsigned AnnotationNr) const;
602 
603  /// Retrieve the name of the parent context.
604  StringRef getParentContextName() const {
605  return ParentName;
606  }
607 
608  const char *getBriefComment() const {
609  return BriefComment;
610  }
611 
612  /// Retrieve a string representation of the code completion string,
613  /// which is mainly useful for debugging.
614  std::string getAsString() const;
615 };
616 
617 /// An allocator used specifically for the purpose of code completion.
618 class CodeCompletionAllocator : public llvm::BumpPtrAllocator {
619 public:
620  /// Copy the given string into this allocator.
621  const char *CopyString(const Twine &String);
622 };
623 
624 /// Allocator for a cached set of global code completions.
626 
628  llvm::DenseMap<const DeclContext *, StringRef> ParentNames;
629  std::shared_ptr<GlobalCodeCompletionAllocator> AllocatorRef;
630 
631 public:
633  std::shared_ptr<GlobalCodeCompletionAllocator> Allocator)
634  : AllocatorRef(std::move(Allocator)) {}
635 
636  std::shared_ptr<GlobalCodeCompletionAllocator> getAllocatorRef() const {
637  return AllocatorRef;
638  }
639 
641  assert(AllocatorRef);
642  return *AllocatorRef;
643  }
644 
645  StringRef getParentName(const DeclContext *DC);
646 };
647 
648 } // namespace clang
649 
650 namespace llvm {
651 
652 template <> struct isPodLike<clang::CodeCompletionString::Chunk> {
653  static const bool value = true;
654 };
655 
656 } // namespace llvm
657 
658 namespace clang {
659 
660 /// A builder class used to construct new code-completion strings.
662 public:
664 
665 private:
666  CodeCompletionAllocator &Allocator;
667  CodeCompletionTUInfo &CCTUInfo;
668  unsigned Priority = 0;
670  StringRef ParentName;
671  const char *BriefComment = nullptr;
672 
673  /// The chunks stored in this string.
674  SmallVector<Chunk, 4> Chunks;
675 
676  SmallVector<const char *, 2> Annotations;
677 
678 public:
680  CodeCompletionTUInfo &CCTUInfo)
681  : Allocator(Allocator), CCTUInfo(CCTUInfo) {}
682 
684  CodeCompletionTUInfo &CCTUInfo,
685  unsigned Priority, CXAvailabilityKind Availability)
686  : Allocator(Allocator), CCTUInfo(CCTUInfo), Priority(Priority),
687  Availability(Availability) {}
688 
689  /// Retrieve the allocator into which the code completion
690  /// strings should be allocated.
691  CodeCompletionAllocator &getAllocator() const { return Allocator; }
692 
693  CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo; }
694 
695  /// Take the resulting completion string.
696  ///
697  /// This operation can only be performed once.
698  CodeCompletionString *TakeString();
699 
700  /// Add a new typed-text chunk.
701  void AddTypedTextChunk(const char *Text);
702 
703  /// Add a new text chunk.
704  void AddTextChunk(const char *Text);
705 
706  /// Add a new optional chunk.
707  void AddOptionalChunk(CodeCompletionString *Optional);
708 
709  /// Add a new placeholder chunk.
710  void AddPlaceholderChunk(const char *Placeholder);
711 
712  /// Add a new informative chunk.
713  void AddInformativeChunk(const char *Text);
714 
715  /// Add a new result-type chunk.
716  void AddResultTypeChunk(const char *ResultType);
717 
718  /// Add a new current-parameter chunk.
719  void AddCurrentParameterChunk(const char *CurrentParameter);
720 
721  /// Add a new chunk.
722  void AddChunk(CodeCompletionString::ChunkKind CK, const char *Text = "");
723 
724  void AddAnnotation(const char *A) { Annotations.push_back(A); }
725 
726  /// Add the parent context information to this code completion.
727  void addParentContext(const DeclContext *DC);
728 
729  const char *getBriefComment() const { return BriefComment; }
730  void addBriefComment(StringRef Comment);
731 
732  StringRef getParentName() const { return ParentName; }
733 };
734 
735 /// Captures a result of code completion.
737 public:
738  /// Describes the kind of result generated.
739  enum ResultKind {
740  /// Refers to a declaration.
741  RK_Declaration = 0,
742 
743  /// Refers to a keyword or symbol.
745 
746  /// Refers to a macro.
748 
749  /// Refers to a precomputed pattern.
750  RK_Pattern
751  };
752 
753  /// When Kind == RK_Declaration or RK_Pattern, the declaration we are
754  /// referring to. In the latter case, the declaration might be NULL.
755  const NamedDecl *Declaration = nullptr;
756 
757  union {
758  /// When Kind == RK_Keyword, the string representing the keyword
759  /// or symbol's spelling.
760  const char *Keyword;
761 
762  /// When Kind == RK_Pattern, the code-completion string that
763  /// describes the completion text to insert.
765 
766  /// When Kind == RK_Macro, the identifier that refers to a macro.
768  };
769 
770  /// The priority of this particular code-completion result.
771  unsigned Priority;
772 
773  /// Specifies which parameter (of a function, Objective-C method,
774  /// macro, etc.) we should start with when formatting the result.
775  unsigned StartParameter = 0;
776 
777  /// The kind of result stored here.
779 
780  /// The cursor kind that describes this result.
782 
783  /// The availability of this result.
785 
786  /// Whether this result is hidden by another name.
787  bool Hidden : 1;
788 
789  /// Whether this result was found via lookup into a base class.
791 
792  /// Whether this declaration is the beginning of a
793  /// nested-name-specifier and, therefore, should be followed by '::'.
795 
796  /// Whether all parameters (of a function, Objective-C
797  /// method, etc.) should be considered "informative".
799 
800  /// Whether we're completing a declaration of the given entity,
801  /// rather than a use of that entity.
802  bool DeclaringEntity : 1;
803 
804  /// If the result should have a nested-name-specifier, this is it.
805  /// When \c QualifierIsInformative, the nested-name-specifier is
806  /// informative rather than required.
807  NestedNameSpecifier *Qualifier = nullptr;
808 
809  /// Build a result that refers to a declaration.
810  CodeCompletionResult(const NamedDecl *Declaration,
811  unsigned Priority,
812  NestedNameSpecifier *Qualifier = nullptr,
813  bool QualifierIsInformative = false,
814  bool Accessible = true)
815  : Declaration(Declaration), Priority(Priority), Kind(RK_Declaration),
816  Hidden(false), QualifierIsInformative(QualifierIsInformative),
817  StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
818  DeclaringEntity(false), Qualifier(Qualifier) {
819  computeCursorKindAndAvailability(Accessible);
820  }
821 
822  /// Build a result that refers to a keyword or symbol.
823  CodeCompletionResult(const char *Keyword, unsigned Priority = CCP_Keyword)
824  : Keyword(Keyword), Priority(Priority), Kind(RK_Keyword),
825  CursorKind(CXCursor_NotImplemented), Hidden(false),
826  QualifierIsInformative(false), StartsNestedNameSpecifier(false),
827  AllParametersAreInformative(false), DeclaringEntity(false) {}
828 
829  /// Build a result that refers to a macro.
831  unsigned Priority = CCP_Macro)
832  : Macro(Macro), Priority(Priority), Kind(RK_Macro),
833  CursorKind(CXCursor_MacroDefinition), Hidden(false),
834  QualifierIsInformative(false), StartsNestedNameSpecifier(false),
835  AllParametersAreInformative(false), DeclaringEntity(false) {}
836 
837  /// Build a result that refers to a pattern.
839  unsigned Priority = CCP_CodePattern,
842  const NamedDecl *D = nullptr)
843  : Declaration(D), Pattern(Pattern), Priority(Priority), Kind(RK_Pattern),
844  CursorKind(CursorKind), Availability(Availability), Hidden(false),
845  QualifierIsInformative(false), StartsNestedNameSpecifier(false),
846  AllParametersAreInformative(false), DeclaringEntity(false) {}
847 
848  /// Build a result that refers to a pattern with an associated
849  /// declaration.
851  unsigned Priority)
852  : Declaration(D), Pattern(Pattern), Priority(Priority), Kind(RK_Pattern),
853  Hidden(false), QualifierIsInformative(false),
854  StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
855  DeclaringEntity(false) {
856  computeCursorKindAndAvailability();
857  }
858 
859  /// Retrieve the declaration stored in this result.
860  const NamedDecl *getDeclaration() const {
861  assert(Kind == RK_Declaration && "Not a declaration result");
862  return Declaration;
863  }
864 
865  /// Retrieve the keyword stored in this result.
866  const char *getKeyword() const {
867  assert(Kind == RK_Keyword && "Not a keyword result");
868  return Keyword;
869  }
870 
871  /// Create a new code-completion string that describes how to insert
872  /// this result into a program.
873  ///
874  /// \param S The semantic analysis that created the result.
875  ///
876  /// \param Allocator The allocator that will be used to allocate the
877  /// string itself.
878  CodeCompletionString *CreateCodeCompletionString(Sema &S,
879  const CodeCompletionContext &CCContext,
880  CodeCompletionAllocator &Allocator,
881  CodeCompletionTUInfo &CCTUInfo,
882  bool IncludeBriefComments);
883  CodeCompletionString *CreateCodeCompletionString(ASTContext &Ctx,
884  Preprocessor &PP,
885  const CodeCompletionContext &CCContext,
886  CodeCompletionAllocator &Allocator,
887  CodeCompletionTUInfo &CCTUInfo,
888  bool IncludeBriefComments);
889 
890  /// Retrieve the name that should be used to order a result.
891  ///
892  /// If the name needs to be constructed as a string, that string will be
893  /// saved into Saved and the returned StringRef will refer to it.
894  StringRef getOrderedName(std::string &Saved) const;
895 
896 private:
897  void computeCursorKindAndAvailability(bool Accessible = true);
898 };
899 
901 
902 inline bool operator>(const CodeCompletionResult &X,
903  const CodeCompletionResult &Y) {
904  return Y < X;
905 }
906 
907 inline bool operator<=(const CodeCompletionResult &X,
908  const CodeCompletionResult &Y) {
909  return !(Y < X);
910 }
911 
912 inline bool operator>=(const CodeCompletionResult &X,
913  const CodeCompletionResult &Y) {
914  return !(X < Y);
915 }
916 
917 raw_ostream &operator<<(raw_ostream &OS,
918  const CodeCompletionString &CCS);
919 
920 /// Abstract interface for a consumer of code-completion
921 /// information.
923 protected:
925 
926  /// Whether the output format for the code-completion consumer is
927  /// binary.
929 
930 public:
932  public:
933  /// Describes the type of overload candidate.
935  /// The candidate is a function declaration.
937 
938  /// The candidate is a function template.
940 
941  /// The "candidate" is actually a variable, expression, or block
942  /// for which we only have a function prototype.
943  CK_FunctionType
944  };
945 
946  private:
947  /// The kind of overload candidate.
949 
950  union {
951  /// The function overload candidate, available when
952  /// Kind == CK_Function.
954 
955  /// The function template overload candidate, available when
956  /// Kind == CK_FunctionTemplate.
958 
959  /// The function type that describes the entity being called,
960  /// when Kind == CK_FunctionType.
962  };
963 
964  public:
966  : Kind(CK_Function), Function(Function) {}
967 
969  : Kind(CK_FunctionTemplate), FunctionTemplate(FunctionTemplateDecl) {}
970 
972  : Kind(CK_FunctionType), Type(Type) {}
973 
974  /// Determine the kind of overload candidate.
975  CandidateKind getKind() const { return Kind; }
976 
977  /// Retrieve the function overload candidate or the templated
978  /// function declaration for a function template.
979  FunctionDecl *getFunction() const;
980 
981  /// Retrieve the function template overload candidate.
983  assert(getKind() == CK_FunctionTemplate && "Not a function template");
984  return FunctionTemplate;
985  }
986 
987  /// Retrieve the function type of the entity, regardless of how the
988  /// function is stored.
989  const FunctionType *getFunctionType() const;
990 
991  /// Create a new code-completion string that describes the function
992  /// signature of this overload candidate.
993  CodeCompletionString *CreateSignatureString(unsigned CurrentArg,
994  Sema &S,
995  CodeCompletionAllocator &Allocator,
996  CodeCompletionTUInfo &CCTUInfo,
997  bool IncludeBriefComments) const;
998  };
999 
1001  bool OutputIsBinary)
1002  : CodeCompleteOpts(CodeCompleteOpts), OutputIsBinary(OutputIsBinary) {}
1003 
1004  /// Whether the code-completion consumer wants to see macros.
1005  bool includeMacros() const {
1006  return CodeCompleteOpts.IncludeMacros;
1007  }
1008 
1009  /// Whether the code-completion consumer wants to see code patterns.
1010  bool includeCodePatterns() const {
1011  return CodeCompleteOpts.IncludeCodePatterns;
1012  }
1013 
1014  /// Whether to include global (top-level) declaration results.
1015  bool includeGlobals() const { return CodeCompleteOpts.IncludeGlobals; }
1016 
1017  /// Whether to include declarations in namespace contexts (including
1018  /// the global namespace). If this is false, `includeGlobals()` will be
1019  /// ignored.
1021  return CodeCompleteOpts.IncludeNamespaceLevelDecls;
1022  }
1023 
1024  /// Whether to include brief documentation comments within the set of
1025  /// code completions returned.
1026  bool includeBriefComments() const {
1027  return CodeCompleteOpts.IncludeBriefComments;
1028  }
1029 
1030  /// Hint whether to load data from the external AST in order to provide
1031  /// full results. If false, declarations from the preamble may be omitted.
1032  bool loadExternal() const {
1033  return CodeCompleteOpts.LoadExternal;
1034  }
1035 
1036  /// Determine whether the output of this consumer is binary.
1037  bool isOutputBinary() const { return OutputIsBinary; }
1038 
1039  /// Deregisters and destroys this code-completion consumer.
1040  virtual ~CodeCompleteConsumer();
1041 
1042  /// \name Code-completion filtering
1043  /// Check if the result should be filtered out.
1044  virtual bool isResultFilteredOut(StringRef Filter,
1045  CodeCompletionResult Results) {
1046  return false;
1047  }
1048 
1049  /// \name Code-completion callbacks
1050  //@{
1051  /// Process the finalized code-completion results.
1053  CodeCompletionContext Context,
1054  CodeCompletionResult *Results,
1055  unsigned NumResults) {}
1056 
1057  /// \param S the semantic-analyzer object for which code-completion is being
1058  /// done.
1059  ///
1060  /// \param CurrentArg the index of the current argument.
1061  ///
1062  /// \param Candidates an array of overload candidates.
1063  ///
1064  /// \param NumCandidates the number of overload candidates
1065  virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1066  OverloadCandidate *Candidates,
1067  unsigned NumCandidates) {}
1068  //@}
1069 
1070  /// Retrieve the allocator that will be used to allocate
1071  /// code completion strings.
1072  virtual CodeCompletionAllocator &getAllocator() = 0;
1073 
1074  virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() = 0;
1075 };
1076 
1077 /// Get the documentation comment used to produce
1078 /// CodeCompletionString::BriefComment for RK_Declaration.
1079 const RawComment *getCompletionComment(const ASTContext &Ctx,
1080  const NamedDecl *Decl);
1081 
1082 /// Get the documentation comment used to produce
1083 /// CodeCompletionString::BriefComment for RK_Pattern.
1085  const NamedDecl *Decl);
1086 
1087 /// Get the documentation comment used to produce
1088 /// CodeCompletionString::BriefComment for OverloadCandidate.
1089 const RawComment *
1090 getParameterComment(const ASTContext &Ctx,
1092  unsigned ArgIndex);
1093 
1094 /// A simple code-completion consumer that prints the results it
1095 /// receives in a simple format.
1097  /// The raw output stream.
1098  raw_ostream &OS;
1099 
1100  CodeCompletionTUInfo CCTUInfo;
1101 
1102 public:
1103  /// Create a new printing code-completion consumer that prints its
1104  /// results to the given raw output stream.
1106  raw_ostream &OS)
1107  : CodeCompleteConsumer(CodeCompleteOpts, false), OS(OS),
1108  CCTUInfo(std::make_shared<GlobalCodeCompletionAllocator>()) {}
1109 
1110  /// Prints the finalized code-completion results.
1111  void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
1112  CodeCompletionResult *Results,
1113  unsigned NumResults) override;
1114 
1115  void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1116  OverloadCandidate *Candidates,
1117  unsigned NumCandidates) override;
1118 
1119  bool isResultFilteredOut(StringRef Filter, CodeCompletionResult Results) override;
1120 
1122  return CCTUInfo.getAllocator();
1123  }
1124 
1125  CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
1126 };
1127 
1128 } // namespace clang
1129 
1130 #endif // LLVM_CLANG_SEMA_CODECOMPLETECONSUMER_H
One piece of the code completion string.
An unknown context, in which we are recovering from a parsing error and don&#39;t know which completions ...
A code completion string that is entirely optional.
CXAvailabilityKind
Describes the availability of a particular entity, which indicates whether the use of this entity wil...
Definition: Index.h:131
Priority for a declaration that is in the local scope.
CodeCompletionAllocator & getAllocator() const
Represents a function declaration or definition.
Definition: Decl.h:1714
llvm::SmallPtrSet< DeclContext *, 8 > VisitedContextSet
ResultKind Kind
The kind of result stored here.
An Objective-C method being used as a property.
CodeCompletionResult(const IdentifierInfo *Macro, unsigned Priority=CCP_Macro)
Build a result that refers to a macro.
const FunctionType * Type
The function type that describes the entity being called, when Kind == CK_FunctionType.
CXCursorKind CursorKind
The cursor kind that describes this result.
A (possibly-)qualified type.
Definition: Type.h:654
unsigned IncludeBriefComments
Show brief documentation comments in code completion results.
llvm::Optional< const CXXScopeSpec * > getCXXScopeSpecifier()
Code completion for a selector, as in an @selector expression.
DominatorTree GraphTraits specialization so the DominatorTree can be iterable by generic graph iterat...
Definition: Dominators.h:30
unsigned IncludeGlobals
Show top-level decls in code completion results.
unsigned getMacroUsagePriority(StringRef MacroName, const LangOptions &LangOpts, bool PreferredTypeIsPointer=false)
Determine the priority to be given to a macro code completion result with the given name...
Code completion where an Objective-C class message is expected.
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3127
C Language Family Type Representation.
Code completion within a type-qualifier list.
static void AddResultTypeChunk(ASTContext &Context, const PrintingPolicy &Policy, const NamedDecl *ND, QualType BaseType, CodeCompletionBuilder &Result)
If the given declaration has an associated type, add it as a result type chunk.
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
CandidateKind
Describes the type of overload candidate.
Adjustment for KVC code pattern priorities when it doesn&#39;t look like the.
const DiagnosticBuilder & operator<<(const DiagnosticBuilder &DB, const Attr *At)
Definition: Attr.h:322
The base class of the type hierarchy.
Definition: Type.h:1420
An unspecified code-completion context.
Allocator for a cached set of global code completions.
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
An Objective-C block property completed as a setter with a block placeholder.
bool loadExternal() const
Hint whether to load data from the external AST in order to provide full results. ...
Code completion occurred where an Objective-C message receiver is expected.
unsigned Priority
The priority of this particular code-completion result.
Code completion occurred on the right-hand side of a member access expression using the arrow operato...
ChunkKind
The different kinds of "chunks" that can occur within a code completion string.
Code completion occurred after the "enum" keyword, to indicate an enumeration name.
bool isOutputBinary() const
Determine whether the output of this consumer is binary.
A piece of text that describes the type of an entity or, for functions and methods, the return type.
bool StartsNestedNameSpecifier
Whether this declaration is the beginning of a nested-name-specifier and, therefore, should be followed by &#39;::&#39;.
const char * Keyword
When Kind == RK_Keyword, the string representing the keyword or symbol&#39;s spelling.
Priority for an enumeration constant inside a switch whose condition is of the enumeration type...
Code completion occurred within the instance variable list of an Objective-C interface, implementation, or category implementation.
bool operator<=(DeclarationName LHS, DeclarationName RHS)
Ordering on two declaration names.
CodeCompletionBuilder(CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo, unsigned Priority, CXAvailabilityKind Availability)
One of these records is kept for each identifier that is lexed.
OverloadCandidate(FunctionTemplateDecl *FunctionTemplateDecl)
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:150
A "string" used to describe how code completion can be performed for an entity.
Adjustment to the "bool" type in Objective-C, where the typedef "BOOL" is preferred.
Definition: Format.h:1989
Kind getKind() const
Retrieve the kind of code-completion context.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:50
bool operator>(DeclarationName LHS, DeclarationName RHS)
Ordering on two declaration names.
Priority for a language keyword (that isn&#39;t any of the other categories).
unsigned IncludeCodePatterns
Show code patterns in code completion results.
An allocator used specifically for the purpose of code completion.
CodeCompletionString * Pattern
When Kind == RK_Pattern, the code-completion string that describes the completion text to insert...
Priority for a nested-name-specifier.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified...
Code completion occurred where a preprocessor directive is expected.
Code completion occurred within an Objective-C implementation or category implementation.
bool QualifierIsInformative
Whether this result was found via lookup into a base class.
Priority for the Objective-C "_cmd" implicit parameter.
FunctionTemplateDecl * FunctionTemplate
The function template overload candidate, available when Kind == CK_FunctionTemplate.
QualType getDeclUsageType(ASTContext &C, const NamedDecl *ND)
Determine the type that this declaration will have if it is used as a type or in an expression...
Code completion occurred where a namespace or namespace alias is expected.
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:63
The piece of text that the user is expected to type to match the code-completion string, typically a keyword or the name of a declarator or macro.
A comma separator (&#39;,&#39;).
bool wantConstructorResults() const
Determines whether we want C++ constructors as results within this context.
CXCursorKind
Describes the kind of entity that a cursor refers to.
Definition: Index.h:1705
FunctionTemplateDecl * getFunctionTemplate() const
Retrieve the function template overload candidate.
CodeCompletionAllocator & getAllocator() const
Retrieve the allocator into which the code completion strings should be allocated.
A right parenthesis (&#39;)&#39;).
Code completion where an Objective-C category name is expected.
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:276
Code completion occurred within a "top-level" completion context, e.g., at namespace or global scope...
CodeCompletionTUInfo & getCodeCompletionTUInfo() override
Code completion occurred where a protocol name is expected.
CXCursorKind getCursorKindForDecl(const Decl *D)
Determine the libclang cursor kind associated with the given declaration.
const RawComment * getCompletionComment(const ASTContext &Ctx, const NamedDecl *Decl)
Get the documentation comment used to produce CodeCompletionString::BriefComment for RK_Declaration...
A simple code-completion consumer that prints the results it receives in a simple format...
QualType getPreferredType() const
Retrieve the type that this expression would prefer to have, e.g., if the expression is a variable in...
llvm::StringRef getCompletionKindString(CodeCompletionContext::Kind Kind)
Get string representation of Kind, useful for for debugging.
Code completion occurred where a new name is expected.
Divide by this factor when a code-completion result&#39;s type is similar to the type we expect (e...
llvm::StringRef getAsString(SyncScope S)
Definition: SyncScope.h:51
const FunctionProtoType * T
CodeCompletionResult(CodeCompletionString *Pattern, const NamedDecl *D, unsigned Priority)
Build a result that refers to a pattern with an associated declaration.
const char * Text
The text string associated with a CK_Text, CK_Placeholder, CK_Informative, or CK_Comma chunk...
This file defines the classes used to store parsed information about declaration-specifiers and decla...
virtual void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context, CodeCompletionResult *Results, unsigned NumResults)
Process the finalized code-completion results.
void addVisitedContext(DeclContext *Ctx)
Adds a visited context.
unsigned IncludeNamespaceLevelDecls
Show decls in namespace (including the global namespace) in code completion results.
Captures a result of code completion.
ArrayRef< IdentifierInfo * > getSelIdents() const
Retrieve the Objective-C selector identifiers.
Code completion occurred where a new name is expected and a qualified name is permissible.
CodeCompletionContext(Kind CCKind)
Construct a new code-completion context of the given kind.
std::shared_ptr< GlobalCodeCompletionAllocator > getAllocatorRef() const
Priority for a member declaration found from the current method or member function.
Code completion in a parenthesized expression, which means that we may also have types here in C and ...
Code completion occurred in a context where natural language is expected, e.g., a comment or string l...
Divide by this factor when a code-completion result&#39;s type exactly matches the type we expect...
virtual bool isResultFilteredOut(StringRef Filter, CodeCompletionResult Results)
FunctionDecl * Function
The function overload candidate, available when Kind == CK_Function.
Priority for a result that isn&#39;t likely to be what the user wants, but is included for completeness...
A piece of text that should be placed in the buffer, e.g., parentheses or a comma in a function call...
The result type of a method or function.
StringRef getParentContextName() const
Retrieve the name of the parent context.
CandidateKind getKind() const
Determine the kind of overload candidate.
CodeCompletionString * Optional
The code completion string associated with a CK_Optional chunk.
The context in which code completion occurred, so that the code-completion consumer can process the r...
const IdentifierInfo * Macro
When Kind == RK_Macro, the identifier that refers to a macro.
The result is in a base class.
PrintingCodeCompleteConsumer(const CodeCompleteOptions &CodeCompleteOpts, raw_ostream &OS)
Create a new printing code-completion consumer that prints its results to the given raw output stream...
Code completion occurred within a class, struct, or union.
const VisitedContextSet & getVisitedContexts() const
Retrieves all visited contexts.
#define false
Definition: stdbool.h:33
const char * getBriefComment() const
Code completion where the name of an Objective-C class is expected.
const Chunk & operator[](unsigned I) const
Code completion occurred within an Objective-C interface, protocol, or category interface.
CodeCompleteConsumer(const CodeCompleteOptions &CodeCompleteOpts, bool OutputIsBinary)
virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg, OverloadCandidate *Candidates, unsigned NumCandidates)
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
The entity is available.
Definition: Index.h:135
SimplifiedTypeClass getSimplifiedTypeClass(CanQualType T)
Determine the simplified type class of the given canonical type.
const RawComment * getParameterComment(const ASTContext &Ctx, const CodeCompleteConsumer::OverloadCandidate &Result, unsigned ArgIndex)
Get the documentation comment used to produce CodeCompletionString::BriefComment for OverloadCandidat...
bool operator>=(DeclarationName LHS, DeclarationName RHS)
Ordering on two declaration names.
bool operator<(DeclarationName LHS, DeclarationName RHS)
Ordering on two declaration names.
const char * getBriefComment() const
bool includeMacros() const
Whether the code-completion consumer wants to see macros.
CodeCompletionTUInfo & getCodeCompletionTUInfo() const
Abstract interface for a consumer of code-completion information.
Options controlling the behavior of code completion.
Dataflow Directional Tag Classes.
Priority for a type.
Code completion occurred where an macro is being defined.
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1262
A piece of text that describes something about the result but should not be inserted into the buffer...
Priority for a send-to-super completion.
Code completion occurred after the "struct" or "class" keyword, to indicate a struct or class name...
CodeCompletionResult(CodeCompletionString *Pattern, unsigned Priority=CCP_CodePattern, CXCursorKind CursorKind=CXCursor_NotImplemented, CXAvailabilityKind Availability=CXAvailability_Available, const NamedDecl *D=nullptr)
Build a result that refers to a pattern.
CodeCompletionResult(const NamedDecl *Declaration, unsigned Priority, NestedNameSpecifier *Qualifier=nullptr, bool QualifierIsInformative=false, bool Accessible=true)
Build a result that refers to a declaration.
Code completion occurred after the "union" keyword, to indicate a union name.
Code completion occurred where a macro name is expected (without any arguments, in the case of a func...
A builder class used to construct new code-completion strings.
Code completion where an Objective-C instance message is expected.
const RawComment * getPatternCompletionComment(const ASTContext &Ctx, const NamedDecl *Decl)
Get the documentation comment used to produce CodeCompletionString::BriefComment for RK_Pattern...
The result is a C++ non-static member function whose qualifiers exactly match the object type on whic...
const char * getKeyword() const
Retrieve the keyword stored in this result.
Priority for a constant value (e.g., enumerator).
Code completion occurred where a statement (or declaration) is expected in a function, method, or block.
Code completion occurred on the right-hand side of an Objective-C property access expression...
const CodeCompleteOptions CodeCompleteOpts
CodeCompletionResult(const char *Keyword, unsigned Priority=CCP_Keyword)
Build a result that refers to a keyword or symbol.
const NamedDecl * getDeclaration() const
Retrieve the declaration stored in this result.
Priority for a preprocessor macro.
QualType getBaseType() const
Retrieve the type of the base object in a member-access expression.
bool includeBriefComments() const
Whether to include brief documentation comments within the set of code completions returned...
A piece of text that describes the parameter that corresponds to the code-completion location within ...
A string that acts as a placeholder for, e.g., a function call argument.
CodeCompletionContext(Kind CCKind, QualType T, ArrayRef< IdentifierInfo *> SelIdents=None)
Construct a new code-completion context of the given kind.
bool Hidden
Whether this result is hidden by another name.
unsigned getAvailability() const
Retrieve the availability of this code completion result.
A left parenthesis (&#39;(&#39;).
X
Add a minimal nested name specifier fixit hint to allow lookup of a tag name from an outer enclosing ...
Definition: SemaDecl.cpp:13503
Code completion occurred within a preprocessor expression.
Code completion occurred where an expression is expected.
Priority for a code pattern.
bool AllParametersAreInformative
Whether all parameters (of a function, Objective-C method, etc.) should be considered "informative"...
An unspecified code-completion context where we should also add macro completions.
CodeCompletionAllocator & getAllocator() override
Retrieve the allocator that will be used to allocate code completion strings.
A left angle bracket (&#39;<&#39;).
void setCXXScopeSpecifier(CXXScopeSpec SS)
Sets the scope specifier that comes before the completion token.
A right angle bracket (&#39;>&#39;).
bool OutputIsBinary
Whether the output format for the code-completion consumer is binary.
ResultKind
Describes the kind of result generated.
The selector of the given message exactly matches the selector of the current method, which might imply that some kind of delegation is occurring.
CodeCompletionTUInfo(std::shared_ptr< GlobalCodeCompletionAllocator > Allocator)
unsigned LoadExternal
Hint whether to load data from the external AST to provide full results.
Code completion occurred on the right-hand side of a member access expression using the dot operator...
SimplifiedTypeClass
A simplified classification of types used when determining "similar" types for code completion...
Code completion occurred where a type name is expected.
Horizontal whitespace (&#39; &#39;).
bool includeCodePatterns() const
Whether the code-completion consumer wants to see code patterns.
StringRef Text
Definition: Format.cpp:1573
bool DeclaringEntity
Whether we&#39;re completing a declaration of the given entity, rather than a use of that entity...
unsigned getPriority() const
Retrieve the priority of this code completion result.
unsigned IncludeMacros
Show macros in code completion results.
CodeCompletionBuilder(CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo)
This represents a decl that may have a name.
Definition: Decl.h:248
bool includeNamespaceLevelDecls() const
Whether to include declarations in namespace contexts (including the global namespace).
Declaration of a template function.
Definition: DeclTemplate.h:968
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:127
bool includeGlobals() const
Whether to include global (top-level) declaration results.
Priority for a non-type declaration.
Priority for the next initialization in a constructor initializer list.