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