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