CodeCompleteConsumer.h revision d12059673dcef32bc2b6bae5321654d33863afe6
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 the name of an Objective-C class is
252    /// expected.
253    CCC_ObjCInterfaceName,
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
271  /// \brief The identifiers for Objective-C selector parts.
272  IdentifierInfo **SelIdents;
273
274  /// \brief The number of Objective-C selector parts.
275  unsigned NumSelIdents;
276
277public:
278  /// \brief Construct a new code-completion context of the given kind.
279  CodeCompletionContext(enum Kind Kind) : Kind(Kind), SelIdents(NULL),
280                                          NumSelIdents(0) { }
281
282  /// \brief Construct a new code-completion context of the given kind.
283  CodeCompletionContext(enum Kind Kind, QualType T,
284                        IdentifierInfo **SelIdents = NULL,
285                        unsigned NumSelIdents = 0) : Kind(Kind),
286                                                     SelIdents(SelIdents),
287                                                    NumSelIdents(NumSelIdents) {
288    if (Kind == CCC_DotMemberAccess || Kind == CCC_ArrowMemberAccess ||
289        Kind == CCC_ObjCPropertyAccess || Kind == CCC_ObjCClassMessage ||
290        Kind == CCC_ObjCInstanceMessage)
291      BaseType = T;
292    else
293      PreferredType = T;
294  }
295
296  /// \brief Retrieve the kind of code-completion context.
297  enum Kind getKind() const { return Kind; }
298
299  /// \brief Retrieve the type that this expression would prefer to have, e.g.,
300  /// if the expression is a variable initializer or a function argument, the
301  /// type of the corresponding variable or function parameter.
302  QualType getPreferredType() const { return PreferredType; }
303
304  /// \brief Retrieve the type of the base object in a member-access
305  /// expression.
306  QualType getBaseType() const { return BaseType; }
307
308  /// \brief Retrieve the Objective-C selector identifiers.
309  IdentifierInfo **getSelIdents() const { return SelIdents; }
310
311  /// \brief Retrieve the number of Objective-C selector identifiers.
312  unsigned getNumSelIdents() const { return NumSelIdents; }
313
314  /// \brief Determines whether we want C++ constructors as results within this
315  /// context.
316  bool wantConstructorResults() const;
317};
318
319
320/// \brief A "string" used to describe how code completion can
321/// be performed for an entity.
322///
323/// A code completion string typically shows how a particular entity can be
324/// used. For example, the code completion string for a function would show
325/// the syntax to call it, including the parentheses, placeholders for the
326/// arguments, etc.
327class CodeCompletionString {
328public:
329  /// \brief The different kinds of "chunks" that can occur within a code
330  /// completion string.
331  enum ChunkKind {
332    /// \brief The piece of text that the user is expected to type to
333    /// match the code-completion string, typically a keyword or the name of a
334    /// declarator or macro.
335    CK_TypedText,
336    /// \brief A piece of text that should be placed in the buffer, e.g.,
337    /// parentheses or a comma in a function call.
338    CK_Text,
339    /// \brief A code completion string that is entirely optional. For example,
340    /// an optional code completion string that describes the default arguments
341    /// in a function call.
342    CK_Optional,
343    /// \brief A string that acts as a placeholder for, e.g., a function
344    /// call argument.
345    CK_Placeholder,
346    /// \brief A piece of text that describes something about the result but
347    /// should not be inserted into the buffer.
348    CK_Informative,
349    /// \brief A piece of text that describes the type of an entity or, for
350    /// functions and methods, the return type.
351    CK_ResultType,
352    /// \brief A piece of text that describes the parameter that corresponds
353    /// to the code-completion location within a function call, message send,
354    /// macro invocation, etc.
355    CK_CurrentParameter,
356    /// \brief A left parenthesis ('(').
357    CK_LeftParen,
358    /// \brief A right parenthesis (')').
359    CK_RightParen,
360    /// \brief A left bracket ('[').
361    CK_LeftBracket,
362    /// \brief A right bracket (']').
363    CK_RightBracket,
364    /// \brief A left brace ('{').
365    CK_LeftBrace,
366    /// \brief A right brace ('}').
367    CK_RightBrace,
368    /// \brief A left angle bracket ('<').
369    CK_LeftAngle,
370    /// \brief A right angle bracket ('>').
371    CK_RightAngle,
372    /// \brief A comma separator (',').
373    CK_Comma,
374    /// \brief A colon (':').
375    CK_Colon,
376    /// \brief A semicolon (';').
377    CK_SemiColon,
378    /// \brief An '=' sign.
379    CK_Equal,
380    /// \brief Horizontal whitespace (' ').
381    CK_HorizontalSpace,
382    /// \brief Verticle whitespace ('\n' or '\r\n', depending on the
383    /// platform).
384    CK_VerticalSpace
385  };
386
387  /// \brief One piece of the code completion string.
388  struct Chunk {
389    /// \brief The kind of data stored in this piece of the code completion
390    /// string.
391    ChunkKind Kind;
392
393    union {
394      /// \brief The text string associated with a CK_Text, CK_Placeholder,
395      /// CK_Informative, or CK_Comma chunk.
396      /// The string is owned by the chunk and will be deallocated
397      /// (with delete[]) when the chunk is destroyed.
398      const char *Text;
399
400      /// \brief The code completion string associated with a CK_Optional chunk.
401      /// The optional code completion string is owned by the chunk, and will
402      /// be deallocated (with delete) when the chunk is destroyed.
403      CodeCompletionString *Optional;
404    };
405
406    Chunk() : Kind(CK_Text), Text(0) { }
407
408    Chunk(ChunkKind Kind, const char *Text = "");
409
410    /// \brief Create a new text chunk.
411    static Chunk CreateText(const char *Text);
412
413    /// \brief Create a new optional chunk.
414    static Chunk CreateOptional(CodeCompletionString *Optional);
415
416    /// \brief Create a new placeholder chunk.
417    static Chunk CreatePlaceholder(const char *Placeholder);
418
419    /// \brief Create a new informative chunk.
420    static Chunk CreateInformative(const char *Informative);
421
422    /// \brief Create a new result type chunk.
423    static Chunk CreateResultType(const char *ResultType);
424
425    /// \brief Create a new current-parameter chunk.
426    static Chunk CreateCurrentParameter(const char *CurrentParameter);
427  };
428
429private:
430  /// \brief The number of chunks stored in this string.
431  unsigned NumChunks;
432
433  /// \brief The priority of this code-completion string.
434  unsigned Priority : 30;
435
436  /// \brief The availability of this code-completion result.
437  unsigned Availability : 2;
438
439  CodeCompletionString(const CodeCompletionString &); // DO NOT IMPLEMENT
440  CodeCompletionString &operator=(const CodeCompletionString &); // DITTO
441
442  CodeCompletionString(const Chunk *Chunks, unsigned NumChunks,
443                       unsigned Priority, CXAvailabilityKind Availability);
444  ~CodeCompletionString() { }
445
446  friend class CodeCompletionBuilder;
447  friend class CodeCompletionResult;
448
449public:
450  typedef const Chunk *iterator;
451  iterator begin() const { return reinterpret_cast<const Chunk *>(this + 1); }
452  iterator end() const { return begin() + NumChunks; }
453  bool empty() const { return NumChunks == 0; }
454  unsigned size() const { return NumChunks; }
455
456  const Chunk &operator[](unsigned I) const {
457    assert(I < size() && "Chunk index out-of-range");
458    return begin()[I];
459  }
460
461  /// \brief Returns the text in the TypedText chunk.
462  const char *getTypedText() const;
463
464  /// \brief Retrieve the priority of this code completion result.
465  unsigned getPriority() const { return Priority; }
466
467  /// \brief Reteirve the availability of this code completion result.
468  unsigned getAvailability() const { return Availability; }
469
470  /// \brief Retrieve a string representation of the code completion string,
471  /// which is mainly useful for debugging.
472  std::string getAsString() const;
473};
474
475/// \brief An allocator used specifically for the purpose of code completion.
476class CodeCompletionAllocator : public llvm::BumpPtrAllocator {
477public:
478  /// \brief Copy the given string into this allocator.
479  const char *CopyString(StringRef String);
480
481  /// \brief Copy the given string into this allocator.
482  const char *CopyString(Twine String);
483
484  // \brief Copy the given string into this allocator.
485  const char *CopyString(const char *String) {
486    return CopyString(StringRef(String));
487  }
488
489  /// \brief Copy the given string into this allocator.
490  const char *CopyString(const std::string &String) {
491    return CopyString(StringRef(String));
492  }
493};
494
495/// \brief A builder class used to construct new code-completion strings.
496class CodeCompletionBuilder {
497public:
498  typedef CodeCompletionString::Chunk Chunk;
499
500private:
501  CodeCompletionAllocator &Allocator;
502  unsigned Priority;
503  CXAvailabilityKind Availability;
504
505  /// \brief The chunks stored in this string.
506  SmallVector<Chunk, 4> Chunks;
507
508public:
509  CodeCompletionBuilder(CodeCompletionAllocator &Allocator)
510    : Allocator(Allocator), Priority(0), Availability(CXAvailability_Available){
511  }
512
513  CodeCompletionBuilder(CodeCompletionAllocator &Allocator,
514                        unsigned Priority, CXAvailabilityKind Availability)
515    : Allocator(Allocator), Priority(Priority), Availability(Availability) { }
516
517  /// \brief Retrieve the allocator into which the code completion
518  /// strings should be allocated.
519  CodeCompletionAllocator &getAllocator() const { return Allocator; }
520
521  /// \brief Take the resulting completion string.
522  ///
523  /// This operation can only be performed once.
524  CodeCompletionString *TakeString();
525
526  /// \brief Add a new typed-text chunk.
527  void AddTypedTextChunk(const char *Text) {
528    Chunks.push_back(Chunk(CodeCompletionString::CK_TypedText, Text));
529  }
530
531  /// \brief Add a new text chunk.
532  void AddTextChunk(const char *Text) {
533    Chunks.push_back(Chunk::CreateText(Text));
534  }
535
536  /// \brief Add a new optional chunk.
537  void AddOptionalChunk(CodeCompletionString *Optional) {
538    Chunks.push_back(Chunk::CreateOptional(Optional));
539  }
540
541  /// \brief Add a new placeholder chunk.
542  void AddPlaceholderChunk(const char *Placeholder) {
543    Chunks.push_back(Chunk::CreatePlaceholder(Placeholder));
544  }
545
546  /// \brief Add a new informative chunk.
547  void AddInformativeChunk(const char *Text) {
548    Chunks.push_back(Chunk::CreateInformative(Text));
549  }
550
551  /// \brief Add a new result-type chunk.
552  void AddResultTypeChunk(const char *ResultType) {
553    Chunks.push_back(Chunk::CreateResultType(ResultType));
554  }
555
556  /// \brief Add a new current-parameter chunk.
557  void AddCurrentParameterChunk(const char *CurrentParameter) {
558    Chunks.push_back(Chunk::CreateCurrentParameter(CurrentParameter));
559  }
560
561  /// \brief Add a new chunk.
562  void AddChunk(Chunk C) { Chunks.push_back(C); }
563};
564
565/// \brief Captures a result of code completion.
566class CodeCompletionResult {
567public:
568  /// \brief Describes the kind of result generated.
569  enum ResultKind {
570    RK_Declaration = 0, //< Refers to a declaration
571    RK_Keyword,         //< Refers to a keyword or symbol.
572    RK_Macro,           //< Refers to a macro
573    RK_Pattern          //< Refers to a precomputed pattern.
574  };
575
576  /// \brief The kind of result stored here.
577  ResultKind Kind;
578
579  union {
580    /// \brief When Kind == RK_Declaration, the declaration we are referring
581    /// to.
582    NamedDecl *Declaration;
583
584    /// \brief When Kind == RK_Keyword, the string representing the keyword
585    /// or symbol's spelling.
586    const char *Keyword;
587
588    /// \brief When Kind == RK_Pattern, the code-completion string that
589    /// describes the completion text to insert.
590    CodeCompletionString *Pattern;
591
592    /// \brief When Kind == RK_Macro, the identifier that refers to a macro.
593    IdentifierInfo *Macro;
594  };
595
596  /// \brief The priority of this particular code-completion result.
597  unsigned Priority;
598
599  /// \brief The cursor kind that describes this result.
600  CXCursorKind CursorKind;
601
602  /// \brief The availability of this result.
603  CXAvailabilityKind Availability;
604
605  /// \brief Specifies which parameter (of a function, Objective-C method,
606  /// macro, etc.) we should start with when formatting the result.
607  unsigned StartParameter;
608
609  /// \brief Whether this result is hidden by another name.
610  bool Hidden : 1;
611
612  /// \brief Whether this result was found via lookup into a base class.
613  bool QualifierIsInformative : 1;
614
615  /// \brief Whether this declaration is the beginning of a
616  /// nested-name-specifier and, therefore, should be followed by '::'.
617  bool StartsNestedNameSpecifier : 1;
618
619  /// \brief Whether all parameters (of a function, Objective-C
620  /// method, etc.) should be considered "informative".
621  bool AllParametersAreInformative : 1;
622
623  /// \brief Whether we're completing a declaration of the given entity,
624  /// rather than a use of that entity.
625  bool DeclaringEntity : 1;
626
627  /// \brief If the result should have a nested-name-specifier, this is it.
628  /// When \c QualifierIsInformative, the nested-name-specifier is
629  /// informative rather than required.
630  NestedNameSpecifier *Qualifier;
631
632  /// \brief Build a result that refers to a declaration.
633  CodeCompletionResult(NamedDecl *Declaration,
634                       NestedNameSpecifier *Qualifier = 0,
635                       bool QualifierIsInformative = false,
636                       bool Accessible = true)
637    : Kind(RK_Declaration), Declaration(Declaration),
638      Priority(getPriorityFromDecl(Declaration)),
639      Availability(CXAvailability_Available), StartParameter(0),
640      Hidden(false), QualifierIsInformative(QualifierIsInformative),
641      StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
642      DeclaringEntity(false), Qualifier(Qualifier) {
643    computeCursorKindAndAvailability(Accessible);
644  }
645
646  /// \brief Build a result that refers to a keyword or symbol.
647  CodeCompletionResult(const char *Keyword, unsigned Priority = CCP_Keyword)
648    : Kind(RK_Keyword), Keyword(Keyword), Priority(Priority),
649      Availability(CXAvailability_Available),
650      StartParameter(0), Hidden(false), QualifierIsInformative(0),
651      StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
652      DeclaringEntity(false), Qualifier(0) {
653    computeCursorKindAndAvailability();
654  }
655
656  /// \brief Build a result that refers to a macro.
657  CodeCompletionResult(IdentifierInfo *Macro, unsigned Priority = CCP_Macro)
658    : Kind(RK_Macro), Macro(Macro), Priority(Priority),
659      Availability(CXAvailability_Available), StartParameter(0),
660      Hidden(false), QualifierIsInformative(0),
661      StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
662      DeclaringEntity(false), Qualifier(0) {
663    computeCursorKindAndAvailability();
664  }
665
666  /// \brief Build a result that refers to a pattern.
667  CodeCompletionResult(CodeCompletionString *Pattern,
668                       unsigned Priority = CCP_CodePattern,
669                       CXCursorKind CursorKind = CXCursor_NotImplemented,
670                   CXAvailabilityKind Availability = CXAvailability_Available)
671    : Kind(RK_Pattern), Pattern(Pattern), Priority(Priority),
672      CursorKind(CursorKind), Availability(Availability), StartParameter(0),
673      Hidden(false), QualifierIsInformative(0),
674      StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
675      DeclaringEntity(false), Qualifier(0)
676  {
677  }
678
679  /// \brief Retrieve the declaration stored in this result.
680  NamedDecl *getDeclaration() const {
681    assert(Kind == RK_Declaration && "Not a declaration result");
682    return Declaration;
683  }
684
685  /// \brief Retrieve the keyword stored in this result.
686  const char *getKeyword() const {
687    assert(Kind == RK_Keyword && "Not a keyword result");
688    return Keyword;
689  }
690
691  /// \brief Create a new code-completion string that describes how to insert
692  /// this result into a program.
693  ///
694  /// \param S The semantic analysis that created the result.
695  ///
696  /// \param Allocator The allocator that will be used to allocate the
697  /// string itself.
698  CodeCompletionString *CreateCodeCompletionString(Sema &S,
699                                           CodeCompletionAllocator &Allocator);
700
701  /// \brief Determine a base priority for the given declaration.
702  static unsigned getPriorityFromDecl(NamedDecl *ND);
703
704private:
705  void computeCursorKindAndAvailability(bool Accessible = true);
706};
707
708bool operator<(const CodeCompletionResult &X, const CodeCompletionResult &Y);
709
710inline bool operator>(const CodeCompletionResult &X,
711                      const CodeCompletionResult &Y) {
712  return Y < X;
713}
714
715inline bool operator<=(const CodeCompletionResult &X,
716                      const CodeCompletionResult &Y) {
717  return !(Y < X);
718}
719
720inline bool operator>=(const CodeCompletionResult &X,
721                       const CodeCompletionResult &Y) {
722  return !(X < Y);
723}
724
725
726raw_ostream &operator<<(raw_ostream &OS,
727                              const CodeCompletionString &CCS);
728
729/// \brief Abstract interface for a consumer of code-completion
730/// information.
731class CodeCompleteConsumer {
732protected:
733  /// \brief Whether to include macros in the code-completion results.
734  bool IncludeMacros;
735
736  /// \brief Whether to include code patterns (such as for loops) within
737  /// the completion results.
738  bool IncludeCodePatterns;
739
740  /// \brief Whether to include global (top-level) declarations and names in
741  /// the completion results.
742  bool IncludeGlobals;
743
744  /// \brief Whether the output format for the code-completion consumer is
745  /// binary.
746  bool OutputIsBinary;
747
748public:
749  class OverloadCandidate {
750  public:
751    /// \brief Describes the type of overload candidate.
752    enum CandidateKind {
753      /// \brief The candidate is a function declaration.
754      CK_Function,
755      /// \brief The candidate is a function template.
756      CK_FunctionTemplate,
757      /// \brief The "candidate" is actually a variable, expression, or block
758      /// for which we only have a function prototype.
759      CK_FunctionType
760    };
761
762  private:
763    /// \brief The kind of overload candidate.
764    CandidateKind Kind;
765
766    union {
767      /// \brief The function overload candidate, available when
768      /// Kind == CK_Function.
769      FunctionDecl *Function;
770
771      /// \brief The function template overload candidate, available when
772      /// Kind == CK_FunctionTemplate.
773      FunctionTemplateDecl *FunctionTemplate;
774
775      /// \brief The function type that describes the entity being called,
776      /// when Kind == CK_FunctionType.
777      const FunctionType *Type;
778    };
779
780  public:
781    OverloadCandidate(FunctionDecl *Function)
782      : Kind(CK_Function), Function(Function) { }
783
784    OverloadCandidate(FunctionTemplateDecl *FunctionTemplateDecl)
785      : Kind(CK_FunctionTemplate), FunctionTemplate(FunctionTemplateDecl) { }
786
787    OverloadCandidate(const FunctionType *Type)
788      : Kind(CK_FunctionType), Type(Type) { }
789
790    /// \brief Determine the kind of overload candidate.
791    CandidateKind getKind() const { return Kind; }
792
793    /// \brief Retrieve the function overload candidate or the templated
794    /// function declaration for a function template.
795    FunctionDecl *getFunction() const;
796
797    /// \brief Retrieve the function template overload candidate.
798    FunctionTemplateDecl *getFunctionTemplate() const {
799      assert(getKind() == CK_FunctionTemplate && "Not a function template");
800      return FunctionTemplate;
801    }
802
803    /// \brief Retrieve the function type of the entity, regardless of how the
804    /// function is stored.
805    const FunctionType *getFunctionType() const;
806
807    /// \brief Create a new code-completion string that describes the function
808    /// signature of this overload candidate.
809    CodeCompletionString *CreateSignatureString(unsigned CurrentArg,
810                                                Sema &S,
811                                      CodeCompletionAllocator &Allocator) const;
812  };
813
814  CodeCompleteConsumer() : IncludeMacros(false), IncludeCodePatterns(false),
815                           IncludeGlobals(true), OutputIsBinary(false) { }
816
817  CodeCompleteConsumer(bool IncludeMacros, bool IncludeCodePatterns,
818                       bool IncludeGlobals, bool OutputIsBinary)
819    : IncludeMacros(IncludeMacros), IncludeCodePatterns(IncludeCodePatterns),
820      IncludeGlobals(IncludeGlobals), OutputIsBinary(OutputIsBinary) { }
821
822  /// \brief Whether the code-completion consumer wants to see macros.
823  bool includeMacros() const { return IncludeMacros; }
824
825  /// \brief Whether the code-completion consumer wants to see code patterns.
826  bool includeCodePatterns() const { return IncludeCodePatterns; }
827
828  /// \brief Whether to include global (top-level) declaration results.
829  bool includeGlobals() const { return IncludeGlobals; }
830
831  /// \brief Determine whether the output of this consumer is binary.
832  bool isOutputBinary() const { return OutputIsBinary; }
833
834  /// \brief Deregisters and destroys this code-completion consumer.
835  virtual ~CodeCompleteConsumer();
836
837  /// \name Code-completion callbacks
838  //@{
839  /// \brief Process the finalized code-completion results.
840  virtual void ProcessCodeCompleteResults(Sema &S,
841                                          CodeCompletionContext Context,
842                                          CodeCompletionResult *Results,
843                                          unsigned NumResults) { }
844
845  /// \param S the semantic-analyzer object for which code-completion is being
846  /// done.
847  ///
848  /// \param CurrentArg the index of the current argument.
849  ///
850  /// \param Candidates an array of overload candidates.
851  ///
852  /// \param NumCandidates the number of overload candidates
853  virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
854                                         OverloadCandidate *Candidates,
855                                         unsigned NumCandidates) { }
856  //@}
857
858  /// \brief Retrieve the allocator that will be used to allocate
859  /// code completion strings.
860  virtual CodeCompletionAllocator &getAllocator() = 0;
861};
862
863/// \brief A simple code-completion consumer that prints the results it
864/// receives in a simple format.
865class PrintingCodeCompleteConsumer : public CodeCompleteConsumer {
866  /// \brief The raw output stream.
867  raw_ostream &OS;
868
869  CodeCompletionAllocator Allocator;
870
871public:
872  /// \brief Create a new printing code-completion consumer that prints its
873  /// results to the given raw output stream.
874  PrintingCodeCompleteConsumer(bool IncludeMacros, bool IncludeCodePatterns,
875                               bool IncludeGlobals,
876                               raw_ostream &OS)
877    : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, IncludeGlobals,
878                           false), OS(OS) {}
879
880  /// \brief Prints the finalized code-completion results.
881  virtual void ProcessCodeCompleteResults(Sema &S,
882                                          CodeCompletionContext Context,
883                                          CodeCompletionResult *Results,
884                                          unsigned NumResults);
885
886  virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
887                                         OverloadCandidate *Candidates,
888                                         unsigned NumCandidates);
889
890  virtual CodeCompletionAllocator &getAllocator() { return Allocator; }
891};
892
893} // end namespace clang
894
895#endif // LLVM_CLANG_SEMA_CODECOMPLETECONSUMER_H
896