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