CodeCompleteConsumer.h revision d8e8a58ee35ab334ab9d0c2154dca029c1822e8a
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 "llvm/ADT/SmallVector.h"
17#include "llvm/ADT/StringRef.h"
18#include <memory>
19#include <string>
20
21namespace llvm {
22class raw_ostream;
23}
24
25namespace clang {
26
27class FunctionDecl;
28class FunctionType;
29class FunctionTemplateDecl;
30class IdentifierInfo;
31class NamedDecl;
32class NestedNameSpecifier;
33class Sema;
34
35/// \brief A "string" used to describe how code completion can
36/// be performed for an entity.
37///
38/// A code completion string typically shows how a particular entity can be
39/// used. For example, the code completion string for a function would show
40/// the syntax to call it, including the parentheses, placeholders for the
41/// arguments, etc.
42class CodeCompletionString {
43public:
44  /// \brief The different kinds of "chunks" that can occur within a code
45  /// completion string.
46  enum ChunkKind {
47    /// \brief The piece of text that the user is expected to type to
48    /// match the code-completion string, typically a keyword or the name of a
49    /// declarator or macro.
50    CK_TypedText,
51    /// \brief A piece of text that should be placed in the buffer, e.g.,
52    /// parentheses or a comma in a function call.
53    CK_Text,
54    /// \brief A code completion string that is entirely optional. For example,
55    /// an optional code completion string that describes the default arguments
56    /// in a function call.
57    CK_Optional,
58    /// \brief A string that acts as a placeholder for, e.g., a function
59    /// call argument.
60    CK_Placeholder,
61    /// \brief A piece of text that describes something about the result but
62    /// should not be inserted into the buffer.
63    CK_Informative,
64    /// \brief A piece of text that describes the type of an entity or, for
65    /// functions and methods, the return type.
66    CK_ResultType,
67    /// \brief A piece of text that describes the parameter that corresponds
68    /// to the code-completion location within a function call, message send,
69    /// macro invocation, etc.
70    CK_CurrentParameter,
71    /// \brief A left parenthesis ('(').
72    CK_LeftParen,
73    /// \brief A right parenthesis (')').
74    CK_RightParen,
75    /// \brief A left bracket ('[').
76    CK_LeftBracket,
77    /// \brief A right bracket (']').
78    CK_RightBracket,
79    /// \brief A left brace ('{').
80    CK_LeftBrace,
81    /// \brief A right brace ('}').
82    CK_RightBrace,
83    /// \brief A left angle bracket ('<').
84    CK_LeftAngle,
85    /// \brief A right angle bracket ('>').
86    CK_RightAngle,
87    /// \brief A comma separator (',').
88    CK_Comma,
89    /// \brief A colon (':').
90    CK_Colon,
91    /// \brief A semicolon (';').
92    CK_SemiColon,
93    /// \brief An '=' sign.
94    CK_Equal,
95    /// \brief Horizontal whitespace (' ').
96    CK_HorizontalSpace,
97    /// \brief Verticle whitespace ('\n' or '\r\n', depending on the
98    /// platform).
99    CK_VerticalSpace
100  };
101
102  /// \brief One piece of the code completion string.
103  struct Chunk {
104    /// \brief The kind of data stored in this piece of the code completion
105    /// string.
106    ChunkKind Kind;
107
108    union {
109      /// \brief The text string associated with a CK_Text, CK_Placeholder,
110      /// CK_Informative, or CK_Comma chunk.
111      /// The string is owned by the chunk and will be deallocated
112      /// (with delete[]) when the chunk is destroyed.
113      const char *Text;
114
115      /// \brief The code completion string associated with a CK_Optional chunk.
116      /// The optional code completion string is owned by the chunk, and will
117      /// be deallocated (with delete) when the chunk is destroyed.
118      CodeCompletionString *Optional;
119    };
120
121    Chunk() : Kind(CK_Text), Text(0) { }
122
123    Chunk(ChunkKind Kind, llvm::StringRef Text = "");
124
125    /// \brief Create a new text chunk.
126    static Chunk CreateText(llvm::StringRef Text);
127
128    /// \brief Create a new optional chunk.
129    static Chunk CreateOptional(std::auto_ptr<CodeCompletionString> Optional);
130
131    /// \brief Create a new placeholder chunk.
132    static Chunk CreatePlaceholder(llvm::StringRef Placeholder);
133
134    /// \brief Create a new informative chunk.
135    static Chunk CreateInformative(llvm::StringRef Informative);
136
137    /// \brief Create a new result type chunk.
138    static Chunk CreateResultType(llvm::StringRef ResultType);
139
140    /// \brief Create a new current-parameter chunk.
141    static Chunk CreateCurrentParameter(llvm::StringRef CurrentParameter);
142
143    /// \brief Clone the given chunk.
144    Chunk Clone() const;
145
146    /// \brief Destroy this chunk, deallocating any memory it owns.
147    void Destroy();
148  };
149
150private:
151  /// \brief The chunks stored in this string.
152  llvm::SmallVector<Chunk, 4> Chunks;
153
154  CodeCompletionString(const CodeCompletionString &); // DO NOT IMPLEMENT
155  CodeCompletionString &operator=(const CodeCompletionString &); // DITTO
156
157public:
158  CodeCompletionString() { }
159  ~CodeCompletionString();
160
161  typedef llvm::SmallVector<Chunk, 4>::const_iterator iterator;
162  iterator begin() const { return Chunks.begin(); }
163  iterator end() const { return Chunks.end(); }
164  bool empty() const { return Chunks.empty(); }
165  unsigned size() const { return Chunks.size(); }
166
167  Chunk &operator[](unsigned I) {
168    assert(I < size() && "Chunk index out-of-range");
169    return Chunks[I];
170  }
171
172  const Chunk &operator[](unsigned I) const {
173    assert(I < size() && "Chunk index out-of-range");
174    return Chunks[I];
175  }
176
177  /// \brief Add a new typed-text chunk.
178  /// The text string will be copied.
179  void AddTypedTextChunk(llvm::StringRef Text) {
180    Chunks.push_back(Chunk(CK_TypedText, Text));
181  }
182
183  /// \brief Add a new text chunk.
184  /// The text string will be copied.
185  void AddTextChunk(llvm::StringRef Text) {
186    Chunks.push_back(Chunk::CreateText(Text));
187  }
188
189  /// \brief Add a new optional chunk.
190  void AddOptionalChunk(std::auto_ptr<CodeCompletionString> Optional) {
191    Chunks.push_back(Chunk::CreateOptional(Optional));
192  }
193
194  /// \brief Add a new placeholder chunk.
195  /// The placeholder text will be copied.
196  void AddPlaceholderChunk(llvm::StringRef Placeholder) {
197    Chunks.push_back(Chunk::CreatePlaceholder(Placeholder));
198  }
199
200  /// \brief Add a new informative chunk.
201  /// The text will be copied.
202  void AddInformativeChunk(llvm::StringRef Text) {
203    Chunks.push_back(Chunk::CreateInformative(Text));
204  }
205
206  /// \brief Add a new result-type chunk.
207  /// The text will be copied.
208  void AddResultTypeChunk(llvm::StringRef ResultType) {
209    Chunks.push_back(Chunk::CreateResultType(ResultType));
210  }
211
212  /// \brief Add a new current-parameter chunk.
213  /// The text will be copied.
214  void AddCurrentParameterChunk(llvm::StringRef CurrentParameter) {
215    Chunks.push_back(Chunk::CreateCurrentParameter(CurrentParameter));
216  }
217
218  /// \brief Add a new chunk.
219  void AddChunk(Chunk C) { Chunks.push_back(C); }
220
221  /// \brief Returns the text in the TypedText chunk.
222  const char *getTypedText() const;
223
224  /// \brief Retrieve a string representation of the code completion string,
225  /// which is mainly useful for debugging.
226  std::string getAsString() const;
227
228  /// \brief Clone this code-completion string.
229  CodeCompletionString *Clone() const;
230
231  /// \brief Serialize this code-completion string to the given stream.
232  void Serialize(llvm::raw_ostream &OS) const;
233
234  /// \brief Deserialize a code-completion string from the given string.
235  static CodeCompletionString *Deserialize(const char *&Str,
236                                           const char *StrEnd);
237};
238
239llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
240                              const CodeCompletionString &CCS);
241
242/// \brief Abstract interface for a consumer of code-completion
243/// information.
244class CodeCompleteConsumer {
245protected:
246  /// \brief Whether to include macros in the code-completion results.
247  bool IncludeMacros;
248
249  /// \brief Whether to include code patterns (such as for loops) within
250  /// the completion results.
251  bool IncludeCodePatterns;
252
253  /// \brief Whether the output format for the code-completion consumer is
254  /// binary.
255  bool OutputIsBinary;
256
257public:
258  /// \brief Captures a result of code completion.
259  struct Result {
260    /// \brief Describes the kind of result generated.
261    enum ResultKind {
262      RK_Declaration = 0, //< Refers to a declaration
263      RK_Keyword,         //< Refers to a keyword or symbol.
264      RK_Macro,           //< Refers to a macro
265      RK_Pattern          //< Refers to a precomputed pattern.
266    };
267
268    /// \brief The kind of result stored here.
269    ResultKind Kind;
270
271    union {
272      /// \brief When Kind == RK_Declaration, the declaration we are referring
273      /// to.
274      NamedDecl *Declaration;
275
276      /// \brief When Kind == RK_Keyword, the string representing the keyword
277      /// or symbol's spelling.
278      const char *Keyword;
279
280      /// \brief When Kind == RK_Pattern, the code-completion string that
281      /// describes the completion text to insert.
282      CodeCompletionString *Pattern;
283
284      /// \brief When Kind == RK_Macro, the identifier that refers to a macro.
285      IdentifierInfo *Macro;
286    };
287
288    /// \brief Specifiers which parameter (of a function, Objective-C method,
289    /// macro, etc.) we should start with when formatting the result.
290    unsigned StartParameter;
291
292    /// \brief Whether this result is hidden by another name.
293    bool Hidden : 1;
294
295    /// \brief Whether this result was found via lookup into a base class.
296    bool QualifierIsInformative : 1;
297
298    /// \brief Whether this declaration is the beginning of a
299    /// nested-name-specifier and, therefore, should be followed by '::'.
300    bool StartsNestedNameSpecifier : 1;
301
302    /// \brief Whether all parameters (of a function, Objective-C
303    /// method, etc.) should be considered "informative".
304    bool AllParametersAreInformative : 1;
305
306    /// \brief If the result should have a nested-name-specifier, this is it.
307    /// When \c QualifierIsInformative, the nested-name-specifier is
308    /// informative rather than required.
309    NestedNameSpecifier *Qualifier;
310
311    /// \brief Build a result that refers to a declaration.
312    Result(NamedDecl *Declaration,
313           NestedNameSpecifier *Qualifier = 0,
314           bool QualifierIsInformative = false)
315      : Kind(RK_Declaration), Declaration(Declaration),
316        StartParameter(0), Hidden(false),
317        QualifierIsInformative(QualifierIsInformative),
318        StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
319        Qualifier(Qualifier) { }
320
321    /// \brief Build a result that refers to a keyword or symbol.
322    Result(const char *Keyword)
323      : Kind(RK_Keyword), Keyword(Keyword), StartParameter(0),
324        Hidden(false), QualifierIsInformative(0),
325        StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
326        Qualifier(0) { }
327
328    /// \brief Build a result that refers to a macro.
329    Result(IdentifierInfo *Macro)
330     : Kind(RK_Macro), Macro(Macro), StartParameter(0),
331       Hidden(false), QualifierIsInformative(0),
332       StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
333       Qualifier(0) { }
334
335    /// \brief Build a result that refers to a pattern.
336    Result(CodeCompletionString *Pattern)
337      : Kind(RK_Pattern), Pattern(Pattern), StartParameter(0),
338        Hidden(false), QualifierIsInformative(0),
339        StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
340        Qualifier(0) { }
341
342    /// \brief Retrieve the declaration stored in this result.
343    NamedDecl *getDeclaration() const {
344      assert(Kind == RK_Declaration && "Not a declaration result");
345      return Declaration;
346    }
347
348    /// \brief Retrieve the keyword stored in this result.
349    const char *getKeyword() const {
350      assert(Kind == RK_Keyword && "Not a keyword result");
351      return Keyword;
352    }
353
354    /// \brief Create a new code-completion string that describes how to insert
355    /// this result into a program.
356    CodeCompletionString *CreateCodeCompletionString(Sema &S);
357
358    void Destroy();
359  };
360
361  class OverloadCandidate {
362  public:
363    /// \brief Describes the type of overload candidate.
364    enum CandidateKind {
365      /// \brief The candidate is a function declaration.
366      CK_Function,
367      /// \brief The candidate is a function template.
368      CK_FunctionTemplate,
369      /// \brief The "candidate" is actually a variable, expression, or block
370      /// for which we only have a function prototype.
371      CK_FunctionType
372    };
373
374  private:
375    /// \brief The kind of overload candidate.
376    CandidateKind Kind;
377
378    union {
379      /// \brief The function overload candidate, available when
380      /// Kind == CK_Function.
381      FunctionDecl *Function;
382
383      /// \brief The function template overload candidate, available when
384      /// Kind == CK_FunctionTemplate.
385      FunctionTemplateDecl *FunctionTemplate;
386
387      /// \brief The function type that describes the entity being called,
388      /// when Kind == CK_FunctionType.
389      const FunctionType *Type;
390    };
391
392  public:
393    OverloadCandidate(FunctionDecl *Function)
394      : Kind(CK_Function), Function(Function) { }
395
396    OverloadCandidate(FunctionTemplateDecl *FunctionTemplateDecl)
397      : Kind(CK_FunctionTemplate), FunctionTemplate(FunctionTemplate) { }
398
399    OverloadCandidate(const FunctionType *Type)
400      : Kind(CK_FunctionType), Type(Type) { }
401
402    /// \brief Determine the kind of overload candidate.
403    CandidateKind getKind() const { return Kind; }
404
405    /// \brief Retrieve the function overload candidate or the templated
406    /// function declaration for a function template.
407    FunctionDecl *getFunction() const;
408
409    /// \brief Retrieve the function template overload candidate.
410    FunctionTemplateDecl *getFunctionTemplate() const {
411      assert(getKind() == CK_FunctionTemplate && "Not a function template");
412      return FunctionTemplate;
413    }
414
415    /// \brief Retrieve the function type of the entity, regardless of how the
416    /// function is stored.
417    const FunctionType *getFunctionType() const;
418
419    /// \brief Create a new code-completion string that describes the function
420    /// signature of this overload candidate.
421    CodeCompletionString *CreateSignatureString(unsigned CurrentArg,
422                                                Sema &S) const;
423  };
424
425  CodeCompleteConsumer() : IncludeMacros(false), OutputIsBinary(false) { }
426
427  CodeCompleteConsumer(bool IncludeMacros, bool IncludeCodePatterns,
428                       bool OutputIsBinary)
429    : IncludeMacros(IncludeMacros), IncludeCodePatterns(IncludeCodePatterns),
430      OutputIsBinary(OutputIsBinary) { }
431
432  /// \brief Whether the code-completion consumer wants to see macros.
433  bool includeMacros() const { return IncludeMacros; }
434
435  /// \brief Whether the code-completion consumer wants to see code patterns.
436  bool includeCodePatterns() const { return IncludeCodePatterns; }
437
438  /// \brief Determine whether the output of this consumer is binary.
439  bool isOutputBinary() const { return OutputIsBinary; }
440
441  /// \brief Deregisters and destroys this code-completion consumer.
442  virtual ~CodeCompleteConsumer();
443
444  /// \name Code-completion callbacks
445  //@{
446  /// \brief Process the finalized code-completion results.
447  virtual void ProcessCodeCompleteResults(Sema &S, Result *Results,
448                                          unsigned NumResults) { }
449
450  /// \param S the semantic-analyzer object for which code-completion is being
451  /// done.
452  ///
453  /// \param CurrentArg the index of the current argument.
454  ///
455  /// \param Candidates an array of overload candidates.
456  ///
457  /// \param NumCandidates the number of overload candidates
458  virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
459                                         OverloadCandidate *Candidates,
460                                         unsigned NumCandidates) { }
461  //@}
462};
463
464/// \brief A simple code-completion consumer that prints the results it
465/// receives in a simple format.
466class PrintingCodeCompleteConsumer : public CodeCompleteConsumer {
467  /// \brief The raw output stream.
468  llvm::raw_ostream &OS;
469
470public:
471  /// \brief Create a new printing code-completion consumer that prints its
472  /// results to the given raw output stream.
473  PrintingCodeCompleteConsumer(bool IncludeMacros, bool IncludeCodePatterns,
474                               llvm::raw_ostream &OS)
475    : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, false), OS(OS) {}
476
477  /// \brief Prints the finalized code-completion results.
478  virtual void ProcessCodeCompleteResults(Sema &S, Result *Results,
479                                          unsigned NumResults);
480
481  virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
482                                         OverloadCandidate *Candidates,
483                                         unsigned NumCandidates);
484};
485
486/// \brief A code-completion consumer that prints the results it receives
487/// in a format that is parsable by the CIndex library.
488class CIndexCodeCompleteConsumer : public CodeCompleteConsumer {
489  /// \brief The raw output stream.
490  llvm::raw_ostream &OS;
491
492public:
493  /// \brief Create a new CIndex code-completion consumer that prints its
494  /// results to the given raw output stream in a format readable to the CIndex
495  /// library.
496  CIndexCodeCompleteConsumer(bool IncludeMacros, bool IncludeCodePatterns,
497                             llvm::raw_ostream &OS)
498    : CodeCompleteConsumer(IncludeMacros, IncludeCodePatterns, true), OS(OS) {}
499
500  /// \brief Prints the finalized code-completion results.
501  virtual void ProcessCodeCompleteResults(Sema &S, Result *Results,
502                                          unsigned NumResults);
503
504  virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
505                                         OverloadCandidate *Candidates,
506                                         unsigned NumCandidates);
507};
508
509} // end namespace clang
510
511#endif // LLVM_CLANG_SEMA_CODECOMPLETECONSUMER_H
512