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