CodeCompleteConsumer.h revision 03d8aec611380d30ddb0659bb61be9289c3871b3
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/AST/Type.h"
17#include "clang/AST/CanonicalType.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/StringRef.h"
20#include "clang-c/Index.h"
21#include <memory>
22#include <string>
23
24namespace llvm {
25  class raw_ostream;
26}
27
28namespace clang {
29
30/// \brief Default priority values for code-completion results based
31/// on their kind.
32enum {
33  /// \brief Priority for a send-to-super completion.
34  CCP_SuperCompletion = 8,
35  /// \brief Priority for a declaration that is in the local scope.
36  CCP_LocalDeclaration = 8,
37  /// \brief Priority for a member declaration found from the current
38  /// method or member function.
39  CCP_MemberDeclaration = 20,
40  /// \brief Priority for a language keyword (that isn't any of the other
41  /// categories).
42  CCP_Keyword = 30,
43  /// \brief Priority for a code pattern.
44  CCP_CodePattern = 30,
45  /// \brief Priority for a non-type declaration.
46  CCP_Declaration = 50,
47  /// \brief Priority for a constant value (e.g., enumerator).
48  CCP_Constant = 60,
49  /// \brief Priority for a type.
50  CCP_Type = 65,
51  /// \brief Priority for a preprocessor macro.
52  CCP_Macro = 70,
53  /// \brief Priority for a nested-name-specifier.
54  CCP_NestedNameSpecifier = 75,
55  /// \brief Priority for a result that isn't likely to be what the user wants,
56  /// but is included for completeness.
57  CCP_Unlikely = 80
58};
59
60/// \brief Priority value deltas that are added to code-completion results
61/// based on the context of the result.
62enum {
63  /// \brief The result is in a base class.
64  CCD_InBaseClass = 2,
65  /// \brief The result is a type match against void.
66  ///
67  /// Since everything converts to "void", we don't give as drastic an
68  /// adjustment for matching void.
69  CCD_VoidMatch = -5,
70  /// \brief The result is a C++ non-static member function whose qualifiers
71  /// exactly match the object type on which the member function can be called.
72  CCD_ObjectQualifierMatch = -1
73};
74
75/// \brief Priority value factors by which we will divide or multiply the
76/// priority of a code-completion result.
77enum {
78  /// \brief Divide by this factor when a code-completion result's type exactly
79  /// matches the type we expect.
80  CCF_ExactTypeMatch = 4,
81  /// \brief Divide by this factor when a code-completion result's type is
82  /// similar to the type we expect (e.g., both arithmetic types, both
83  /// Objective-C object pointer types).
84  CCF_SimilarTypeMatch = 2
85};
86
87/// \brief A simplified classification of types used when determining
88/// "similar" types for code completion.
89enum SimplifiedTypeClass {
90  STC_Arithmetic,
91  STC_Array,
92  STC_Block,
93  STC_Function,
94  STC_ObjectiveC,
95  STC_Other,
96  STC_Pointer,
97  STC_Record,
98  STC_Void
99};
100
101/// \brief Determine the simplified type class of the given canonical type.
102SimplifiedTypeClass getSimplifiedTypeClass(CanQualType T);
103
104/// \brief Determine the type that this declaration will have if it is used
105/// as a type or in an expression.
106QualType getDeclUsageType(ASTContext &C, NamedDecl *ND);
107
108/// \brief Determine the priority to be given to a macro code completion result
109/// with the given name.
110///
111/// \param MacroName The name of the macro.
112///
113/// \param PreferredTypeIsPointer Whether the preferred type for the context
114/// of this macro is a pointer type.
115unsigned getMacroUsagePriority(llvm::StringRef MacroName,
116                               bool PreferredTypeIsPointer = false);
117
118class FunctionDecl;
119class FunctionType;
120class FunctionTemplateDecl;
121class IdentifierInfo;
122class NamedDecl;
123class NestedNameSpecifier;
124class Sema;
125
126/// \brief The context in which code completion occurred, so that the
127/// code-completion consumer can process the results accordingly.
128class CodeCompletionContext {
129public:
130  enum Kind {
131    /// \brief An unspecified code-completion context.
132    CCC_Other,
133    /// \brief Code completion occurred within a "top-level" completion context,
134    /// e.g., at namespace or global scope.
135    CCC_TopLevel,
136    /// \brief Code completion occurred within an Objective-C interface,
137    /// protocol, or category interface.
138    CCC_ObjCInterface,
139    /// \brief Code completion occurred within an Objective-C implementation
140    /// or category implementation.
141    CCC_ObjCImplementation,
142    /// \brief Code completion occurred within the instance variable list of
143    /// an Objective-C interface, implementation, or category implementation.
144    CCC_ObjCIvarList,
145    /// \brief Code completion occurred within a class, struct, or union.
146    CCC_ClassStructUnion,
147    /// \brief Code completion occurred where a statement (or declaration) is
148    /// expected in a function, method, or block.
149    CCC_Statement,
150    /// \brief Code completion occurred where an expression is expected.
151    CCC_Expression,
152    /// \brief Code completion occurred where an Objective-C message receiver
153    /// is expected.
154    CCC_ObjCMessageReceiver,
155    /// \brief Code completion occurred on the right-hand side of a member
156    /// access expression.
157    ///
158    /// The results of this completion are the members of the type being
159    /// accessed. The type itself is available via
160    /// \c CodeCompletionContext::getType().
161    CCC_MemberAccess,
162    /// \brief Code completion occurred after the "enum" keyword, to indicate
163    /// an enumeration name.
164    CCC_EnumTag,
165    /// \brief Code completion occurred after the "union" keyword, to indicate
166    /// a union name.
167    CCC_UnionTag,
168    /// \brief Code completion occurred after the "struct" or "class" keyword,
169    /// to indicate a struct or class name.
170    CCC_ClassOrStructTag,
171    /// \brief Code completion occurred where a protocol name is expected.
172    CCC_ObjCProtocolName,
173    /// \brief Code completion occurred where a namespace or namespace alias
174    /// is expected.
175    CCC_Namespace,
176    /// \brief Code completion occurred where a type name is expected.
177    CCC_Type,
178    /// \brief Code completion occurred where a new name is expected.
179    CCC_Name,
180    /// \brief Code completion occurred where a new name is expected and a
181    /// qualified name is permissible.
182    CCC_PotentiallyQualifiedName,
183    /// \brief Code completion occurred where an macro is being defined.
184    CCC_MacroName,
185    /// \brief Code completion occurred where a macro name is expected
186    /// (without any arguments, in the case of a function-like macro).
187    CCC_MacroNameUse,
188    /// \brief Code completion occurred within a preprocessor expression.
189    CCC_PreprocessorExpression,
190    /// \brief Code completion occurred where a preprocessor directive is
191    /// expected.
192    CCC_PreprocessorDirective,
193    /// \brief Code completion occurred in a context where natural language is
194    /// expected, e.g., a comment or string literal.
195    ///
196    /// This context usually implies that no completions should be added,
197    /// unless they come from an appropriate natural-language dictionary.
198    CCC_NaturalLanguage,
199    /// \brief Code completion for a selector, as in an @selector expression.
200    CCC_SelectorName
201  };
202
203private:
204  enum Kind Kind;
205
206  /// \brief The type that would prefer to see at this point (e.g., the type
207  /// of an initializer or function parameter).
208  QualType PreferredType;
209
210  /// \brief The type of the base object in a member access expression.
211  QualType BaseType;
212
213public:
214  /// \brief Construct a new code-completion context of the given kind.
215  CodeCompletionContext(enum Kind Kind) : Kind(Kind) { }
216
217  /// \brief Construct a new code-completion context of the given kind.
218  CodeCompletionContext(enum Kind Kind, QualType T) : Kind(Kind) {
219    if (Kind == CCC_MemberAccess)
220      BaseType = T;
221    else
222      PreferredType = T;
223  }
224
225  /// \brief Retrieve the kind of code-completion context.
226  enum Kind getKind() const { return Kind; }
227
228  /// \brief Retrieve the type that this expression would prefer to have, e.g.,
229  /// if the expression is a variable initializer or a function argument, the
230  /// type of the corresponding variable or function parameter.
231  QualType getPreferredType() const { return PreferredType; }
232
233  /// \brief Retrieve the type of the base object in a member-access
234  /// expression.
235  QualType getBaseType() const { return BaseType; }
236};
237
238
239/// \brief A "string" used to describe how code completion can
240/// be performed for an entity.
241///
242/// A code completion string typically shows how a particular entity can be
243/// used. For example, the code completion string for a function would show
244/// the syntax to call it, including the parentheses, placeholders for the
245/// arguments, etc.
246class CodeCompletionString {
247public:
248  /// \brief The different kinds of "chunks" that can occur within a code
249  /// completion string.
250  enum ChunkKind {
251    /// \brief The piece of text that the user is expected to type to
252    /// match the code-completion string, typically a keyword or the name of a
253    /// declarator or macro.
254    CK_TypedText,
255    /// \brief A piece of text that should be placed in the buffer, e.g.,
256    /// parentheses or a comma in a function call.
257    CK_Text,
258    /// \brief A code completion string that is entirely optional. For example,
259    /// an optional code completion string that describes the default arguments
260    /// in a function call.
261    CK_Optional,
262    /// \brief A string that acts as a placeholder for, e.g., a function
263    /// call argument.
264    CK_Placeholder,
265    /// \brief A piece of text that describes something about the result but
266    /// should not be inserted into the buffer.
267    CK_Informative,
268    /// \brief A piece of text that describes the type of an entity or, for
269    /// functions and methods, the return type.
270    CK_ResultType,
271    /// \brief A piece of text that describes the parameter that corresponds
272    /// to the code-completion location within a function call, message send,
273    /// macro invocation, etc.
274    CK_CurrentParameter,
275    /// \brief A left parenthesis ('(').
276    CK_LeftParen,
277    /// \brief A right parenthesis (')').
278    CK_RightParen,
279    /// \brief A left bracket ('[').
280    CK_LeftBracket,
281    /// \brief A right bracket (']').
282    CK_RightBracket,
283    /// \brief A left brace ('{').
284    CK_LeftBrace,
285    /// \brief A right brace ('}').
286    CK_RightBrace,
287    /// \brief A left angle bracket ('<').
288    CK_LeftAngle,
289    /// \brief A right angle bracket ('>').
290    CK_RightAngle,
291    /// \brief A comma separator (',').
292    CK_Comma,
293    /// \brief A colon (':').
294    CK_Colon,
295    /// \brief A semicolon (';').
296    CK_SemiColon,
297    /// \brief An '=' sign.
298    CK_Equal,
299    /// \brief Horizontal whitespace (' ').
300    CK_HorizontalSpace,
301    /// \brief Verticle whitespace ('\n' or '\r\n', depending on the
302    /// platform).
303    CK_VerticalSpace
304  };
305
306  /// \brief One piece of the code completion string.
307  struct Chunk {
308    /// \brief The kind of data stored in this piece of the code completion
309    /// string.
310    ChunkKind Kind;
311
312    union {
313      /// \brief The text string associated with a CK_Text, CK_Placeholder,
314      /// CK_Informative, or CK_Comma chunk.
315      /// The string is owned by the chunk and will be deallocated
316      /// (with delete[]) when the chunk is destroyed.
317      const char *Text;
318
319      /// \brief The code completion string associated with a CK_Optional chunk.
320      /// The optional code completion string is owned by the chunk, and will
321      /// be deallocated (with delete) when the chunk is destroyed.
322      CodeCompletionString *Optional;
323    };
324
325    Chunk() : Kind(CK_Text), Text(0) { }
326
327    Chunk(ChunkKind Kind, llvm::StringRef Text = "");
328
329    /// \brief Create a new text chunk.
330    static Chunk CreateText(llvm::StringRef Text);
331
332    /// \brief Create a new optional chunk.
333    static Chunk CreateOptional(std::auto_ptr<CodeCompletionString> Optional);
334
335    /// \brief Create a new placeholder chunk.
336    static Chunk CreatePlaceholder(llvm::StringRef Placeholder);
337
338    /// \brief Create a new informative chunk.
339    static Chunk CreateInformative(llvm::StringRef Informative);
340
341    /// \brief Create a new result type chunk.
342    static Chunk CreateResultType(llvm::StringRef ResultType);
343
344    /// \brief Create a new current-parameter chunk.
345    static Chunk CreateCurrentParameter(llvm::StringRef CurrentParameter);
346
347    /// \brief Clone the given chunk.
348    Chunk Clone() const;
349
350    /// \brief Destroy this chunk, deallocating any memory it owns.
351    void Destroy();
352  };
353
354private:
355  /// \brief The chunks stored in this string.
356  llvm::SmallVector<Chunk, 4> Chunks;
357
358  CodeCompletionString(const CodeCompletionString &); // DO NOT IMPLEMENT
359  CodeCompletionString &operator=(const CodeCompletionString &); // DITTO
360
361public:
362  CodeCompletionString() { }
363  ~CodeCompletionString() { clear(); }
364
365  typedef llvm::SmallVector<Chunk, 4>::const_iterator iterator;
366  iterator begin() const { return Chunks.begin(); }
367  iterator end() const { return Chunks.end(); }
368  bool empty() const { return Chunks.empty(); }
369  unsigned size() const { return Chunks.size(); }
370  void clear();
371
372  Chunk &operator[](unsigned I) {
373    assert(I < size() && "Chunk index out-of-range");
374    return Chunks[I];
375  }
376
377  const Chunk &operator[](unsigned I) const {
378    assert(I < size() && "Chunk index out-of-range");
379    return Chunks[I];
380  }
381
382  /// \brief Add a new typed-text chunk.
383  /// The text string will be copied.
384  void AddTypedTextChunk(llvm::StringRef Text) {
385    Chunks.push_back(Chunk(CK_TypedText, Text));
386  }
387
388  /// \brief Add a new text chunk.
389  /// The text string will be copied.
390  void AddTextChunk(llvm::StringRef Text) {
391    Chunks.push_back(Chunk::CreateText(Text));
392  }
393
394  /// \brief Add a new optional chunk.
395  void AddOptionalChunk(std::auto_ptr<CodeCompletionString> Optional) {
396    Chunks.push_back(Chunk::CreateOptional(Optional));
397  }
398
399  /// \brief Add a new placeholder chunk.
400  /// The placeholder text will be copied.
401  void AddPlaceholderChunk(llvm::StringRef Placeholder) {
402    Chunks.push_back(Chunk::CreatePlaceholder(Placeholder));
403  }
404
405  /// \brief Add a new informative chunk.
406  /// The text will be copied.
407  void AddInformativeChunk(llvm::StringRef Text) {
408    Chunks.push_back(Chunk::CreateInformative(Text));
409  }
410
411  /// \brief Add a new result-type chunk.
412  /// The text will be copied.
413  void AddResultTypeChunk(llvm::StringRef ResultType) {
414    Chunks.push_back(Chunk::CreateResultType(ResultType));
415  }
416
417  /// \brief Add a new current-parameter chunk.
418  /// The text will be copied.
419  void AddCurrentParameterChunk(llvm::StringRef CurrentParameter) {
420    Chunks.push_back(Chunk::CreateCurrentParameter(CurrentParameter));
421  }
422
423  /// \brief Add a new chunk.
424  void AddChunk(Chunk C) { Chunks.push_back(C); }
425
426  /// \brief Returns the text in the TypedText chunk.
427  const char *getTypedText() const;
428
429  /// \brief Retrieve a string representation of the code completion string,
430  /// which is mainly useful for debugging.
431  std::string getAsString() const;
432
433  /// \brief Clone this code-completion string.
434  ///
435  /// \param Result If non-NULL, points to an empty code-completion
436  /// result that will be given a cloned copy of
437  CodeCompletionString *Clone(CodeCompletionString *Result = 0) const;
438
439  /// \brief Serialize this code-completion string to the given stream.
440  void Serialize(llvm::raw_ostream &OS) const;
441
442  /// \brief Deserialize a code-completion string from the given string.
443  ///
444  /// \returns true if successful, false otherwise.
445  bool Deserialize(const char *&Str, const char *StrEnd);
446};
447
448/// \brief Captures a result of code completion.
449class CodeCompletionResult {
450public:
451  /// \brief Describes the kind of result generated.
452  enum ResultKind {
453    RK_Declaration = 0, //< Refers to a declaration
454    RK_Keyword,         //< Refers to a keyword or symbol.
455    RK_Macro,           //< Refers to a macro
456    RK_Pattern          //< Refers to a precomputed pattern.
457  };
458
459  /// \brief The kind of result stored here.
460  ResultKind Kind;
461
462  union {
463    /// \brief When Kind == RK_Declaration, the declaration we are referring
464    /// to.
465    NamedDecl *Declaration;
466
467    /// \brief When Kind == RK_Keyword, the string representing the keyword
468    /// or symbol's spelling.
469    const char *Keyword;
470
471    /// \brief When Kind == RK_Pattern, the code-completion string that
472    /// describes the completion text to insert.
473    CodeCompletionString *Pattern;
474
475    /// \brief When Kind == RK_Macro, the identifier that refers to a macro.
476    IdentifierInfo *Macro;
477  };
478
479  /// \brief The priority of this particular code-completion result.
480  unsigned Priority;
481
482  /// \brief The cursor kind that describes this result.
483  CXCursorKind CursorKind;
484
485  /// \brief The availability of this result.
486  CXAvailabilityKind Availability;
487
488  /// \brief Specifies which parameter (of a function, Objective-C method,
489  /// macro, etc.) we should start with when formatting the result.
490  unsigned StartParameter;
491
492  /// \brief Whether this result is hidden by another name.
493  bool Hidden : 1;
494
495  /// \brief Whether this result was found via lookup into a base class.
496  bool QualifierIsInformative : 1;
497
498  /// \brief Whether this declaration is the beginning of a
499  /// nested-name-specifier and, therefore, should be followed by '::'.
500  bool StartsNestedNameSpecifier : 1;
501
502  /// \brief Whether all parameters (of a function, Objective-C
503  /// method, etc.) should be considered "informative".
504  bool AllParametersAreInformative : 1;
505
506  /// \brief Whether we're completing a declaration of the given entity,
507  /// rather than a use of that entity.
508  bool DeclaringEntity : 1;
509
510  /// \brief If the result should have a nested-name-specifier, this is it.
511  /// When \c QualifierIsInformative, the nested-name-specifier is
512  /// informative rather than required.
513  NestedNameSpecifier *Qualifier;
514
515  /// \brief Build a result that refers to a declaration.
516  CodeCompletionResult(NamedDecl *Declaration,
517                       NestedNameSpecifier *Qualifier = 0,
518                       bool QualifierIsInformative = false)
519    : Kind(RK_Declaration), Declaration(Declaration),
520      Priority(getPriorityFromDecl(Declaration)),
521      Availability(CXAvailability_Available), StartParameter(0),
522      Hidden(false), QualifierIsInformative(QualifierIsInformative),
523      StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
524      DeclaringEntity(false), Qualifier(Qualifier) {
525    computeCursorKindAndAvailability();
526  }
527
528  /// \brief Build a result that refers to a keyword or symbol.
529  CodeCompletionResult(const char *Keyword, unsigned Priority = CCP_Keyword)
530    : Kind(RK_Keyword), Keyword(Keyword), Priority(Priority),
531      Availability(CXAvailability_Available),
532      StartParameter(0), Hidden(false), QualifierIsInformative(0),
533      StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
534      DeclaringEntity(false), Qualifier(0) {
535    computeCursorKindAndAvailability();
536  }
537
538  /// \brief Build a result that refers to a macro.
539  CodeCompletionResult(IdentifierInfo *Macro, unsigned Priority = CCP_Macro)
540    : Kind(RK_Macro), Macro(Macro), Priority(Priority),
541      Availability(CXAvailability_Available), StartParameter(0),
542      Hidden(false), QualifierIsInformative(0),
543      StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
544      DeclaringEntity(false), Qualifier(0) {
545    computeCursorKindAndAvailability();
546  }
547
548  /// \brief Build a result that refers to a pattern.
549  CodeCompletionResult(CodeCompletionString *Pattern,
550                       unsigned Priority = CCP_CodePattern,
551                       CXCursorKind CursorKind = CXCursor_NotImplemented,
552                   CXAvailabilityKind Availability = CXAvailability_Available)
553    : Kind(RK_Pattern), Pattern(Pattern), Priority(Priority),
554      CursorKind(CursorKind), Availability(Availability), StartParameter(0),
555      Hidden(false), QualifierIsInformative(0),
556      StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
557      DeclaringEntity(false), Qualifier(0)
558  {
559  }
560
561  /// \brief Retrieve the declaration stored in this result.
562  NamedDecl *getDeclaration() const {
563    assert(Kind == RK_Declaration && "Not a declaration result");
564    return Declaration;
565  }
566
567  /// \brief Retrieve the keyword stored in this result.
568  const char *getKeyword() const {
569    assert(Kind == RK_Keyword && "Not a keyword result");
570    return Keyword;
571  }
572
573  /// \brief Create a new code-completion string that describes how to insert
574  /// this result into a program.
575  ///
576  /// \param S The semantic analysis that created the result.
577  ///
578  /// \param Result If non-NULL, the already-allocated, empty
579  /// code-completion string that will be populated with the
580  /// appropriate code completion string for this result.
581  CodeCompletionString *CreateCodeCompletionString(Sema &S,
582                                           CodeCompletionString *Result = 0);
583
584  void Destroy();
585
586  /// brief Determine a base priority for the given declaration.
587  static unsigned getPriorityFromDecl(NamedDecl *ND);
588
589private:
590  void computeCursorKindAndAvailability();
591};
592
593bool operator<(const CodeCompletionResult &X, const CodeCompletionResult &Y);
594
595inline bool operator>(const CodeCompletionResult &X,
596                      const CodeCompletionResult &Y) {
597  return Y < X;
598}
599
600inline bool operator<=(const CodeCompletionResult &X,
601                      const CodeCompletionResult &Y) {
602  return !(Y < X);
603}
604
605inline bool operator>=(const CodeCompletionResult &X,
606                       const CodeCompletionResult &Y) {
607  return !(X < Y);
608}
609
610
611llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
612                              const CodeCompletionString &CCS);
613
614/// \brief Abstract interface for a consumer of code-completion
615/// information.
616class CodeCompleteConsumer {
617protected:
618  /// \brief Whether to include macros in the code-completion results.
619  bool IncludeMacros;
620
621  /// \brief Whether to include code patterns (such as for loops) within
622  /// the completion results.
623  bool IncludeCodePatterns;
624
625  /// \brief Whether to include global (top-level) declarations and names in
626  /// the completion results.
627  bool IncludeGlobals;
628
629  /// \brief Whether the output format for the code-completion consumer is
630  /// binary.
631  bool OutputIsBinary;
632
633public:
634  class OverloadCandidate {
635  public:
636    /// \brief Describes the type of overload candidate.
637    enum CandidateKind {
638      /// \brief The candidate is a function declaration.
639      CK_Function,
640      /// \brief The candidate is a function template.
641      CK_FunctionTemplate,
642      /// \brief The "candidate" is actually a variable, expression, or block
643      /// for which we only have a function prototype.
644      CK_FunctionType
645    };
646
647  private:
648    /// \brief The kind of overload candidate.
649    CandidateKind Kind;
650
651    union {
652      /// \brief The function overload candidate, available when
653      /// Kind == CK_Function.
654      FunctionDecl *Function;
655
656      /// \brief The function template overload candidate, available when
657      /// Kind == CK_FunctionTemplate.
658      FunctionTemplateDecl *FunctionTemplate;
659
660      /// \brief The function type that describes the entity being called,
661      /// when Kind == CK_FunctionType.
662      const FunctionType *Type;
663    };
664
665  public:
666    OverloadCandidate(FunctionDecl *Function)
667      : Kind(CK_Function), Function(Function) { }
668
669    OverloadCandidate(FunctionTemplateDecl *FunctionTemplateDecl)
670      : Kind(CK_FunctionTemplate), FunctionTemplate(FunctionTemplate) { }
671
672    OverloadCandidate(const FunctionType *Type)
673      : Kind(CK_FunctionType), Type(Type) { }
674
675    /// \brief Determine the kind of overload candidate.
676    CandidateKind getKind() const { return Kind; }
677
678    /// \brief Retrieve the function overload candidate or the templated
679    /// function declaration for a function template.
680    FunctionDecl *getFunction() const;
681
682    /// \brief Retrieve the function template overload candidate.
683    FunctionTemplateDecl *getFunctionTemplate() const {
684      assert(getKind() == CK_FunctionTemplate && "Not a function template");
685      return FunctionTemplate;
686    }
687
688    /// \brief Retrieve the function type of the entity, regardless of how the
689    /// function is stored.
690    const FunctionType *getFunctionType() const;
691
692    /// \brief Create a new code-completion string that describes the function
693    /// signature of this overload candidate.
694    CodeCompletionString *CreateSignatureString(unsigned CurrentArg,
695                                                Sema &S) const;
696  };
697
698  CodeCompleteConsumer() : IncludeMacros(false), IncludeCodePatterns(false),
699                           IncludeGlobals(true), OutputIsBinary(false) { }
700
701  CodeCompleteConsumer(bool IncludeMacros, bool IncludeCodePatterns,
702                       bool IncludeGlobals, bool OutputIsBinary)
703    : IncludeMacros(IncludeMacros), IncludeCodePatterns(IncludeCodePatterns),
704      IncludeGlobals(IncludeGlobals), OutputIsBinary(OutputIsBinary) { }
705
706  /// \brief Whether the code-completion consumer wants to see macros.
707  bool includeMacros() const { return IncludeMacros; }
708
709  /// \brief Whether the code-completion consumer wants to see code patterns.
710  bool includeCodePatterns() const { return IncludeCodePatterns; }
711
712  /// \brief Whether to include global (top-level) declaration results.
713  bool includeGlobals() const { return IncludeGlobals; }
714
715  /// \brief Determine whether the output of this consumer is binary.
716  bool isOutputBinary() const { return OutputIsBinary; }
717
718  /// \brief Deregisters and destroys this code-completion consumer.
719  virtual ~CodeCompleteConsumer();
720
721  /// \name Code-completion callbacks
722  //@{
723  /// \brief Process the finalized code-completion results.
724  virtual void ProcessCodeCompleteResults(Sema &S,
725                                          CodeCompletionContext Context,
726                                          CodeCompletionResult *Results,
727                                          unsigned NumResults) { }
728
729  /// \param S the semantic-analyzer object for which code-completion is being
730  /// done.
731  ///
732  /// \param CurrentArg the index of the current argument.
733  ///
734  /// \param Candidates an array of overload candidates.
735  ///
736  /// \param NumCandidates the number of overload candidates
737  virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
738                                         OverloadCandidate *Candidates,
739                                         unsigned NumCandidates) { }
740  //@}
741};
742
743/// \brief A simple code-completion consumer that prints the results it
744/// receives in a simple format.
745class PrintingCodeCompleteConsumer : public CodeCompleteConsumer {
746  /// \brief The raw output stream.
747  llvm::raw_ostream &OS;
748
749public:
750  /// \brief Create a new printing code-completion consumer that prints its
751  /// results to the given raw output stream.
752  PrintingCodeCompleteConsumer(bool IncludeMacros, bool IncludeCodePatterns,
753                               bool IncludeGlobals,
754                               llvm::raw_ostream &OS)
755    : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
756                           false), OS(OS) {}
757
758  /// \brief Prints the finalized code-completion results.
759  virtual void ProcessCodeCompleteResults(Sema &S,
760                                          CodeCompletionContext Context,
761                                          CodeCompletionResult *Results,
762                                          unsigned NumResults);
763
764  virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
765                                         OverloadCandidate *Candidates,
766                                         unsigned NumCandidates);
767};
768
769/// \brief A code-completion consumer that prints the results it receives
770/// in a format that is parsable by the CIndex library.
771class CIndexCodeCompleteConsumer : public CodeCompleteConsumer {
772  /// \brief The raw output stream.
773  llvm::raw_ostream &OS;
774
775public:
776  /// \brief Create a new CIndex code-completion consumer that prints its
777  /// results to the given raw output stream in a format readable to the CIndex
778  /// library.
779  CIndexCodeCompleteConsumer(bool IncludeMacros, bool IncludeCodePatterns,
780                             bool IncludeGlobals, llvm::raw_ostream &OS)
781    : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
782                           true), OS(OS) {}
783
784  /// \brief Prints the finalized code-completion results.
785  virtual void ProcessCodeCompleteResults(Sema &S,
786                                          CodeCompletionContext Context,
787                                          CodeCompletionResult *Results,
788                                          unsigned NumResults);
789
790  virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
791                                         OverloadCandidate *Candidates,
792                                         unsigned NumCandidates);
793};
794
795} // end namespace clang
796
797#endif // LLVM_CLANG_SEMA_CODECOMPLETECONSUMER_H
798