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