clang  6.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 private:
272  enum Kind Kind;
273 
274  /// \brief The type that would prefer to see at this point (e.g., the type
275  /// of an initializer or function parameter).
276  QualType PreferredType;
277 
278  /// \brief The type of the base object in a member access expression.
279  QualType BaseType;
280 
281  /// \brief The identifiers for Objective-C selector parts.
282  ArrayRef<IdentifierInfo *> SelIdents;
283 
284  /// \brief The scope specifier that comes before the completion token e.g.
285  /// "a::b::"
286  llvm::Optional<CXXScopeSpec> ScopeSpecifier;
287 
288 public:
289  /// \brief Construct a new code-completion context of the given kind.
290  CodeCompletionContext(enum Kind Kind) : Kind(Kind), SelIdents(None) { }
291 
292  /// \brief Construct a new code-completion context of the given kind.
294  ArrayRef<IdentifierInfo *> SelIdents = None)
295  : Kind(Kind),
296  SelIdents(SelIdents) {
297  if (Kind == CCC_DotMemberAccess || Kind == CCC_ArrowMemberAccess ||
298  Kind == CCC_ObjCPropertyAccess || Kind == CCC_ObjCClassMessage ||
299  Kind == CCC_ObjCInstanceMessage)
300  BaseType = T;
301  else
302  PreferredType = T;
303  }
304 
305  /// \brief Retrieve the kind of code-completion context.
306  enum Kind getKind() const { return Kind; }
307 
308  /// \brief Retrieve the type that this expression would prefer to have, e.g.,
309  /// if the expression is a variable initializer or a function argument, the
310  /// type of the corresponding variable or function parameter.
311  QualType getPreferredType() const { return PreferredType; }
312 
313  /// \brief Retrieve the type of the base object in a member-access
314  /// expression.
315  QualType getBaseType() const { return BaseType; }
316 
317  /// \brief Retrieve the Objective-C selector identifiers.
318  ArrayRef<IdentifierInfo *> getSelIdents() const { return SelIdents; }
319 
320  /// \brief Determines whether we want C++ constructors as results within this
321  /// context.
322  bool wantConstructorResults() const;
323 
324  /// \brief Sets the scope specifier that comes before the completion token.
325  /// This is expected to be set in code completions on qualfied specifiers
326  /// (e.g. "a::b::").
328  this->ScopeSpecifier = std::move(SS);
329  }
330 
332  if (ScopeSpecifier)
333  return ScopeSpecifier.getPointer();
334  return llvm::None;
335  }
336 };
337 
338 /// \brief A "string" used to describe how code completion can
339 /// be performed for an entity.
340 ///
341 /// A code completion string typically shows how a particular entity can be
342 /// used. For example, the code completion string for a function would show
343 /// the syntax to call it, including the parentheses, placeholders for the
344 /// arguments, etc.
346 public:
347  /// \brief The different kinds of "chunks" that can occur within a code
348  /// completion string.
349  enum ChunkKind {
350  /// \brief The piece of text that the user is expected to type to
351  /// match the code-completion string, typically a keyword or the name of a
352  /// declarator or macro.
354  /// \brief A piece of text that should be placed in the buffer, e.g.,
355  /// parentheses or a comma in a function call.
357  /// \brief A code completion string that is entirely optional. For example,
358  /// an optional code completion string that describes the default arguments
359  /// in a function call.
361  /// \brief A string that acts as a placeholder for, e.g., a function
362  /// call argument.
364  /// \brief A piece of text that describes something about the result but
365  /// should not be inserted into the buffer.
367  /// \brief A piece of text that describes the type of an entity or, for
368  /// functions and methods, the return type.
370  /// \brief A piece of text that describes the parameter that corresponds
371  /// to the code-completion location within a function call, message send,
372  /// macro invocation, etc.
374  /// \brief A left parenthesis ('(').
376  /// \brief A right parenthesis (')').
378  /// \brief A left bracket ('[').
380  /// \brief A right bracket (']').
382  /// \brief A left brace ('{').
384  /// \brief A right brace ('}').
386  /// \brief A left angle bracket ('<').
388  /// \brief A right angle bracket ('>').
390  /// \brief A comma separator (',').
392  /// \brief A colon (':').
394  /// \brief A semicolon (';').
396  /// \brief An '=' sign.
398  /// \brief Horizontal whitespace (' ').
400  /// \brief Vertical whitespace ('\\n' or '\\r\\n', depending on the
401  /// platform).
402  CK_VerticalSpace
403  };
404 
405  /// \brief One piece of the code completion string.
406  struct Chunk {
407  /// \brief The kind of data stored in this piece of the code completion
408  /// string.
410 
411  union {
412  /// \brief The text string associated with a CK_Text, CK_Placeholder,
413  /// CK_Informative, or CK_Comma chunk.
414  /// The string is owned by the chunk and will be deallocated
415  /// (with delete[]) when the chunk is destroyed.
416  const char *Text;
417 
418  /// \brief The code completion string associated with a CK_Optional chunk.
419  /// The optional code completion string is owned by the chunk, and will
420  /// be deallocated (with delete) when the chunk is destroyed.
422  };
423 
424  Chunk() : Kind(CK_Text), Text(nullptr) { }
425 
426  explicit Chunk(ChunkKind Kind, const char *Text = "");
427 
428  /// \brief Create a new text chunk.
429  static Chunk CreateText(const char *Text);
430 
431  /// \brief Create a new optional chunk.
432  static Chunk CreateOptional(CodeCompletionString *Optional);
433 
434  /// \brief Create a new placeholder chunk.
435  static Chunk CreatePlaceholder(const char *Placeholder);
436 
437  /// \brief Create a new informative chunk.
438  static Chunk CreateInformative(const char *Informative);
439 
440  /// \brief Create a new result type chunk.
441  static Chunk CreateResultType(const char *ResultType);
442 
443  /// \brief Create a new current-parameter chunk.
444  static Chunk CreateCurrentParameter(const char *CurrentParameter);
445  };
446 
447 private:
448  /// \brief The number of chunks stored in this string.
449  unsigned NumChunks : 16;
450 
451  /// \brief The number of annotations for this code-completion result.
452  unsigned NumAnnotations : 16;
453 
454  /// \brief The priority of this code-completion string.
455  unsigned Priority : 16;
456 
457  /// \brief The availability of this code-completion result.
458  unsigned Availability : 2;
459 
460  /// \brief The name of the parent context.
461  StringRef ParentName;
462 
463  /// \brief A brief documentation comment attached to the declaration of
464  /// entity being completed by this result.
465  const char *BriefComment;
466 
467  CodeCompletionString(const CodeCompletionString &) = delete;
468  void operator=(const CodeCompletionString &) = delete;
469 
470  CodeCompletionString(const Chunk *Chunks, unsigned NumChunks,
471  unsigned Priority, CXAvailabilityKind Availability,
472  const char **Annotations, unsigned NumAnnotations,
473  StringRef ParentName,
474  const char *BriefComment);
475  ~CodeCompletionString() = default;
476 
477  friend class CodeCompletionBuilder;
478  friend class CodeCompletionResult;
479 
480 public:
481  typedef const Chunk *iterator;
482  iterator begin() const { return reinterpret_cast<const Chunk *>(this + 1); }
483  iterator end() const { return begin() + NumChunks; }
484  bool empty() const { return NumChunks == 0; }
485  unsigned size() const { return NumChunks; }
486 
487  const Chunk &operator[](unsigned I) const {
488  assert(I < size() && "Chunk index out-of-range");
489  return begin()[I];
490  }
491 
492  /// \brief Returns the text in the TypedText chunk.
493  const char *getTypedText() const;
494 
495  /// \brief Retrieve the priority of this code completion result.
496  unsigned getPriority() const { return Priority; }
497 
498  /// \brief Retrieve the availability of this code completion result.
499  unsigned getAvailability() const { return Availability; }
500 
501  /// \brief Retrieve the number of annotations for this code completion result.
502  unsigned getAnnotationCount() const;
503 
504  /// \brief Retrieve the annotation string specified by \c AnnotationNr.
505  const char *getAnnotation(unsigned AnnotationNr) const;
506 
507  /// \brief Retrieve the name of the parent context.
508  StringRef getParentContextName() const {
509  return ParentName;
510  }
511 
512  const char *getBriefComment() const {
513  return BriefComment;
514  }
515 
516  /// \brief Retrieve a string representation of the code completion string,
517  /// which is mainly useful for debugging.
518  std::string getAsString() const;
519 };
520 
521 /// \brief An allocator used specifically for the purpose of code completion.
522 class CodeCompletionAllocator : public llvm::BumpPtrAllocator {
523 public:
524  /// \brief Copy the given string into this allocator.
525  const char *CopyString(const Twine &String);
526 };
527 
528 /// \brief Allocator for a cached set of global code completions.
530 
532  llvm::DenseMap<const DeclContext *, StringRef> ParentNames;
533  std::shared_ptr<GlobalCodeCompletionAllocator> AllocatorRef;
534 
535 public:
537  std::shared_ptr<GlobalCodeCompletionAllocator> Allocator)
538  : AllocatorRef(std::move(Allocator)) {}
539 
540  std::shared_ptr<GlobalCodeCompletionAllocator> getAllocatorRef() const {
541  return AllocatorRef;
542  }
544  assert(AllocatorRef);
545  return *AllocatorRef;
546  }
547 
548  StringRef getParentName(const DeclContext *DC);
549 };
550 
551 } // end namespace clang
552 
553 namespace llvm {
554  template <> struct isPodLike<clang::CodeCompletionString::Chunk> {
555  static const bool value = true;
556  };
557 }
558 
559 namespace clang {
560 
561 /// \brief A builder class used to construct new code-completion strings.
563 public:
565 
566 private:
567  CodeCompletionAllocator &Allocator;
568  CodeCompletionTUInfo &CCTUInfo;
569  unsigned Priority;
570  CXAvailabilityKind Availability;
571  StringRef ParentName;
572  const char *BriefComment;
573 
574  /// \brief The chunks stored in this string.
575  SmallVector<Chunk, 4> Chunks;
576 
577  SmallVector<const char *, 2> Annotations;
578 
579 public:
581  CodeCompletionTUInfo &CCTUInfo)
582  : Allocator(Allocator), CCTUInfo(CCTUInfo),
583  Priority(0), Availability(CXAvailability_Available),
584  BriefComment(nullptr) { }
585 
587  CodeCompletionTUInfo &CCTUInfo,
588  unsigned Priority, CXAvailabilityKind Availability)
589  : Allocator(Allocator), CCTUInfo(CCTUInfo),
590  Priority(Priority), Availability(Availability),
591  BriefComment(nullptr) { }
592 
593  /// \brief Retrieve the allocator into which the code completion
594  /// strings should be allocated.
595  CodeCompletionAllocator &getAllocator() const { return Allocator; }
596 
597  CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo; }
598 
599  /// \brief Take the resulting completion string.
600  ///
601  /// This operation can only be performed once.
602  CodeCompletionString *TakeString();
603 
604  /// \brief Add a new typed-text chunk.
605  void AddTypedTextChunk(const char *Text);
606 
607  /// \brief Add a new text chunk.
608  void AddTextChunk(const char *Text);
609 
610  /// \brief Add a new optional chunk.
611  void AddOptionalChunk(CodeCompletionString *Optional);
612 
613  /// \brief Add a new placeholder chunk.
614  void AddPlaceholderChunk(const char *Placeholder);
615 
616  /// \brief Add a new informative chunk.
617  void AddInformativeChunk(const char *Text);
618 
619  /// \brief Add a new result-type chunk.
620  void AddResultTypeChunk(const char *ResultType);
621 
622  /// \brief Add a new current-parameter chunk.
623  void AddCurrentParameterChunk(const char *CurrentParameter);
624 
625  /// \brief Add a new chunk.
626  void AddChunk(CodeCompletionString::ChunkKind CK, const char *Text = "");
627 
628  void AddAnnotation(const char *A) { Annotations.push_back(A); }
629 
630  /// \brief Add the parent context information to this code completion.
631  void addParentContext(const DeclContext *DC);
632 
633  const char *getBriefComment() const { return BriefComment; }
634  void addBriefComment(StringRef Comment);
635 
636  StringRef getParentName() const { return ParentName; }
637 };
638 
639 /// \brief Captures a result of code completion.
641 public:
642  /// \brief Describes the kind of result generated.
643  enum ResultKind {
644  RK_Declaration = 0, ///< Refers to a declaration
645  RK_Keyword, ///< Refers to a keyword or symbol.
646  RK_Macro, ///< Refers to a macro
647  RK_Pattern ///< Refers to a precomputed pattern.
648  };
649 
650  /// \brief When Kind == RK_Declaration or RK_Pattern, the declaration we are
651  /// referring to. In the latter case, the declaration might be NULL.
653 
654  union {
655  /// \brief When Kind == RK_Keyword, the string representing the keyword
656  /// or symbol's spelling.
657  const char *Keyword;
658 
659  /// \brief When Kind == RK_Pattern, the code-completion string that
660  /// describes the completion text to insert.
662 
663  /// \brief When Kind == RK_Macro, the identifier that refers to a macro.
665  };
666 
667  /// \brief The priority of this particular code-completion result.
668  unsigned Priority;
669 
670  /// \brief Specifies which parameter (of a function, Objective-C method,
671  /// macro, etc.) we should start with when formatting the result.
672  unsigned StartParameter;
673 
674  /// \brief The kind of result stored here.
676 
677  /// \brief The cursor kind that describes this result.
679 
680  /// \brief The availability of this result.
682 
683  /// \brief Whether this result is hidden by another name.
684  bool Hidden : 1;
685 
686  /// \brief Whether this result was found via lookup into a base class.
688 
689  /// \brief Whether this declaration is the beginning of a
690  /// nested-name-specifier and, therefore, should be followed by '::'.
692 
693  /// \brief Whether all parameters (of a function, Objective-C
694  /// method, etc.) should be considered "informative".
696 
697  /// \brief Whether we're completing a declaration of the given entity,
698  /// rather than a use of that entity.
699  bool DeclaringEntity : 1;
700 
701  /// \brief If the result should have a nested-name-specifier, this is it.
702  /// When \c QualifierIsInformative, the nested-name-specifier is
703  /// informative rather than required.
705 
706  /// \brief Build a result that refers to a declaration.
707  CodeCompletionResult(const NamedDecl *Declaration,
708  unsigned Priority,
709  NestedNameSpecifier *Qualifier = nullptr,
710  bool QualifierIsInformative = false,
711  bool Accessible = true)
712  : Declaration(Declaration), Priority(Priority),
713  StartParameter(0), Kind(RK_Declaration),
714  Availability(CXAvailability_Available), Hidden(false),
715  QualifierIsInformative(QualifierIsInformative),
716  StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
717  DeclaringEntity(false), Qualifier(Qualifier) {
718  computeCursorKindAndAvailability(Accessible);
719  }
720 
721  /// \brief Build a result that refers to a keyword or symbol.
722  CodeCompletionResult(const char *Keyword, unsigned Priority = CCP_Keyword)
723  : Declaration(nullptr), Keyword(Keyword), Priority(Priority),
724  StartParameter(0), Kind(RK_Keyword), CursorKind(CXCursor_NotImplemented),
725  Availability(CXAvailability_Available), Hidden(false),
726  QualifierIsInformative(0), StartsNestedNameSpecifier(false),
727  AllParametersAreInformative(false), DeclaringEntity(false),
728  Qualifier(nullptr) {}
729 
730  /// \brief Build a result that refers to a macro.
732  unsigned Priority = CCP_Macro)
733  : Declaration(nullptr), Macro(Macro), Priority(Priority), StartParameter(0),
734  Kind(RK_Macro), CursorKind(CXCursor_MacroDefinition),
735  Availability(CXAvailability_Available), Hidden(false),
736  QualifierIsInformative(0), StartsNestedNameSpecifier(false),
737  AllParametersAreInformative(false), DeclaringEntity(false),
738  Qualifier(nullptr) {}
739 
740  /// \brief Build a result that refers to a pattern.
742  unsigned Priority = CCP_CodePattern,
745  const NamedDecl *D = nullptr)
746  : Declaration(D), Pattern(Pattern), Priority(Priority), StartParameter(0),
747  Kind(RK_Pattern), CursorKind(CursorKind), Availability(Availability),
748  Hidden(false), QualifierIsInformative(0),
749  StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
750  DeclaringEntity(false), Qualifier(nullptr)
751  {
752  }
753 
754  /// \brief Build a result that refers to a pattern with an associated
755  /// declaration.
757  unsigned Priority)
758  : Declaration(D), Pattern(Pattern), Priority(Priority), StartParameter(0),
759  Kind(RK_Pattern), Availability(CXAvailability_Available), Hidden(false),
760  QualifierIsInformative(false), StartsNestedNameSpecifier(false),
761  AllParametersAreInformative(false), DeclaringEntity(false),
762  Qualifier(nullptr) {
763  computeCursorKindAndAvailability();
764  }
765 
766  /// \brief Retrieve the declaration stored in this result.
767  const NamedDecl *getDeclaration() const {
768  assert(Kind == RK_Declaration && "Not a declaration result");
769  return Declaration;
770  }
771 
772  /// \brief Retrieve the keyword stored in this result.
773  const char *getKeyword() const {
774  assert(Kind == RK_Keyword && "Not a keyword result");
775  return Keyword;
776  }
777 
778  /// \brief Create a new code-completion string that describes how to insert
779  /// this result into a program.
780  ///
781  /// \param S The semantic analysis that created the result.
782  ///
783  /// \param Allocator The allocator that will be used to allocate the
784  /// string itself.
785  CodeCompletionString *CreateCodeCompletionString(Sema &S,
786  const CodeCompletionContext &CCContext,
787  CodeCompletionAllocator &Allocator,
788  CodeCompletionTUInfo &CCTUInfo,
789  bool IncludeBriefComments);
790  CodeCompletionString *CreateCodeCompletionString(ASTContext &Ctx,
791  Preprocessor &PP,
792  const CodeCompletionContext &CCContext,
793  CodeCompletionAllocator &Allocator,
794  CodeCompletionTUInfo &CCTUInfo,
795  bool IncludeBriefComments);
796 
797  /// \brief Retrieve the name that should be used to order a result.
798  ///
799  /// If the name needs to be constructed as a string, that string will be
800  /// saved into Saved and the returned StringRef will refer to it.
801  StringRef getOrderedName(std::string &Saved) const;
802 
803 private:
804  void computeCursorKindAndAvailability(bool Accessible = true);
805 };
806 
808 
809 inline bool operator>(const CodeCompletionResult &X,
810  const CodeCompletionResult &Y) {
811  return Y < X;
812 }
813 
814 inline bool operator<=(const CodeCompletionResult &X,
815  const CodeCompletionResult &Y) {
816  return !(Y < X);
817 }
818 
819 inline bool operator>=(const CodeCompletionResult &X,
820  const CodeCompletionResult &Y) {
821  return !(X < Y);
822 }
823 
824 
825 raw_ostream &operator<<(raw_ostream &OS,
826  const CodeCompletionString &CCS);
827 
828 /// \brief Abstract interface for a consumer of code-completion
829 /// information.
831 protected:
833 
834  /// \brief Whether the output format for the code-completion consumer is
835  /// binary.
837 
838 public:
840  public:
841  /// \brief Describes the type of overload candidate.
843  /// \brief The candidate is a function declaration.
845  /// \brief The candidate is a function template.
847  /// \brief The "candidate" is actually a variable, expression, or block
848  /// for which we only have a function prototype.
849  CK_FunctionType
850  };
851 
852  private:
853  /// \brief The kind of overload candidate.
855 
856  union {
857  /// \brief The function overload candidate, available when
858  /// Kind == CK_Function.
860 
861  /// \brief The function template overload candidate, available when
862  /// Kind == CK_FunctionTemplate.
864 
865  /// \brief The function type that describes the entity being called,
866  /// when Kind == CK_FunctionType.
868  };
869 
870  public:
872  : Kind(CK_Function), Function(Function) { }
873 
875  : Kind(CK_FunctionTemplate), FunctionTemplate(FunctionTemplateDecl) { }
876 
878  : Kind(CK_FunctionType), Type(Type) { }
879 
880  /// \brief Determine the kind of overload candidate.
881  CandidateKind getKind() const { return Kind; }
882 
883  /// \brief Retrieve the function overload candidate or the templated
884  /// function declaration for a function template.
885  FunctionDecl *getFunction() const;
886 
887  /// \brief Retrieve the function template overload candidate.
889  assert(getKind() == CK_FunctionTemplate && "Not a function template");
890  return FunctionTemplate;
891  }
892 
893  /// \brief Retrieve the function type of the entity, regardless of how the
894  /// function is stored.
895  const FunctionType *getFunctionType() const;
896 
897  /// \brief Create a new code-completion string that describes the function
898  /// signature of this overload candidate.
899  CodeCompletionString *CreateSignatureString(unsigned CurrentArg,
900  Sema &S,
901  CodeCompletionAllocator &Allocator,
902  CodeCompletionTUInfo &CCTUInfo,
903  bool IncludeBriefComments) const;
904  };
905 
906  CodeCompleteConsumer(const CodeCompleteOptions &CodeCompleteOpts,
907  bool OutputIsBinary)
908  : CodeCompleteOpts(CodeCompleteOpts), OutputIsBinary(OutputIsBinary)
909  { }
910 
911  /// \brief Whether the code-completion consumer wants to see macros.
912  bool includeMacros() const {
913  return CodeCompleteOpts.IncludeMacros;
914  }
915 
916  /// \brief Whether the code-completion consumer wants to see code patterns.
917  bool includeCodePatterns() const {
918  return CodeCompleteOpts.IncludeCodePatterns;
919  }
920 
921  /// \brief Whether to include global (top-level) declaration results.
922  bool includeGlobals() const { return CodeCompleteOpts.IncludeGlobals; }
923 
924  /// \brief Whether to include declarations in namespace contexts (including
925  /// the global namespace). If this is false, `includeGlobals()` will be
926  /// ignored.
928  return CodeCompleteOpts.IncludeNamespaceLevelDecls;
929  }
930 
931  /// \brief Whether to include brief documentation comments within the set of
932  /// code completions returned.
933  bool includeBriefComments() const {
934  return CodeCompleteOpts.IncludeBriefComments;
935  }
936 
937  /// \brief Determine whether the output of this consumer is binary.
938  bool isOutputBinary() const { return OutputIsBinary; }
939 
940  /// \brief Deregisters and destroys this code-completion consumer.
941  virtual ~CodeCompleteConsumer();
942 
943  /// \name Code-completion filtering
944  /// \brief Check if the result should be filtered out.
945  virtual bool isResultFilteredOut(StringRef Filter,
946  CodeCompletionResult Results) {
947  return false;
948  }
949 
950  /// \name Code-completion callbacks
951  //@{
952  /// \brief Process the finalized code-completion results.
954  CodeCompletionContext Context,
955  CodeCompletionResult *Results,
956  unsigned NumResults) { }
957 
958  /// \param S the semantic-analyzer object for which code-completion is being
959  /// done.
960  ///
961  /// \param CurrentArg the index of the current argument.
962  ///
963  /// \param Candidates an array of overload candidates.
964  ///
965  /// \param NumCandidates the number of overload candidates
966  virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
967  OverloadCandidate *Candidates,
968  unsigned NumCandidates) { }
969  //@}
970 
971  /// \brief Retrieve the allocator that will be used to allocate
972  /// code completion strings.
973  virtual CodeCompletionAllocator &getAllocator() = 0;
974 
975  virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() = 0;
976 };
977 
978 /// \brief A simple code-completion consumer that prints the results it
979 /// receives in a simple format.
981  /// \brief The raw output stream.
982  raw_ostream &OS;
983 
984  CodeCompletionTUInfo CCTUInfo;
985 
986 public:
987  /// \brief Create a new printing code-completion consumer that prints its
988  /// results to the given raw output stream.
990  raw_ostream &OS)
991  : CodeCompleteConsumer(CodeCompleteOpts, false), OS(OS),
992  CCTUInfo(std::make_shared<GlobalCodeCompletionAllocator>()) {}
993 
994  /// \brief Prints the finalized code-completion results.
995  void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
996  CodeCompletionResult *Results,
997  unsigned NumResults) override;
998 
999  void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1000  OverloadCandidate *Candidates,
1001  unsigned NumCandidates) override;
1002 
1003  bool isResultFilteredOut(StringRef Filter, CodeCompletionResult Results) override;
1004 
1006  return CCTUInfo.getAllocator();
1007  }
1008 
1009  CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
1010 };
1011 
1012 } // end namespace clang
1013 
1014 #endif // LLVM_CLANG_SEMA_CODECOMPLETECONSUMER_H
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
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
Definition: Decl.h:1698
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:3058
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:195
The base class of the type hierarchy.
Definition: Type.h:1353
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.
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:1900
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:48
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:274
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.
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.
#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:1252
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:13010
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)
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:1346
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)
NamedDecl - This represents a decl with a name.
Definition: Decl.h:245
bool includeNamespaceLevelDecls() const
Whether to include declarations in namespace contexts (including the global namespace).
Declaration of a template function.
Definition: DeclTemplate.h:958
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.