CodeCompleteConsumer.cpp revision 87c08a5d6b9e1e44ae6f554df40139d3a6f60b33
1//===--- CodeCompleteConsumer.cpp - 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 implements the CodeCompleteConsumer class.
11//
12//===----------------------------------------------------------------------===//
13#include "clang/Sema/CodeCompleteConsumer.h"
14#include "clang/Sema/Sema.h"
15#include "clang/AST/DeclCXX.h"
16#include "clang/Parse/Scope.h"
17#include "clang/Lex/Preprocessor.h"
18#include "clang-c/Index.h"
19#include "llvm/ADT/STLExtras.h"
20#include "llvm/Support/raw_ostream.h"
21#include <algorithm>
22#include <cstring>
23#include <functional>
24
25using namespace clang;
26using llvm::StringRef;
27
28//===----------------------------------------------------------------------===//
29// Code completion string implementation
30//===----------------------------------------------------------------------===//
31CodeCompletionString::Chunk::Chunk(ChunkKind Kind, llvm::StringRef Text)
32  : Kind(Kind), Text("")
33{
34  switch (Kind) {
35  case CK_TypedText:
36  case CK_Text:
37  case CK_Placeholder:
38  case CK_Informative:
39  case CK_ResultType:
40  case CK_CurrentParameter: {
41    char *New = new char [Text.size() + 1];
42    std::memcpy(New, Text.data(), Text.size());
43    New[Text.size()] = '\0';
44    this->Text = New;
45    break;
46  }
47
48  case CK_Optional:
49    llvm_unreachable("Optional strings cannot be created from text");
50    break;
51
52  case CK_LeftParen:
53    this->Text = "(";
54    break;
55
56  case CK_RightParen:
57    this->Text = ")";
58    break;
59
60  case CK_LeftBracket:
61    this->Text = "[";
62    break;
63
64  case CK_RightBracket:
65    this->Text = "]";
66    break;
67
68  case CK_LeftBrace:
69    this->Text = "{";
70    break;
71
72  case CK_RightBrace:
73    this->Text = "}";
74    break;
75
76  case CK_LeftAngle:
77    this->Text = "<";
78    break;
79
80  case CK_RightAngle:
81    this->Text = ">";
82    break;
83
84  case CK_Comma:
85    this->Text = ", ";
86    break;
87
88  case CK_Colon:
89    this->Text = ":";
90    break;
91
92  case CK_SemiColon:
93    this->Text = ";";
94    break;
95
96  case CK_Equal:
97    this->Text = " = ";
98    break;
99
100  case CK_HorizontalSpace:
101    this->Text = " ";
102    break;
103
104  case CK_VerticalSpace:
105    this->Text = "\n";
106    break;
107  }
108}
109
110CodeCompletionString::Chunk
111CodeCompletionString::Chunk::CreateText(StringRef Text) {
112  return Chunk(CK_Text, Text);
113}
114
115CodeCompletionString::Chunk
116CodeCompletionString::Chunk::CreateOptional(
117                                 std::auto_ptr<CodeCompletionString> Optional) {
118  Chunk Result;
119  Result.Kind = CK_Optional;
120  Result.Optional = Optional.release();
121  return Result;
122}
123
124CodeCompletionString::Chunk
125CodeCompletionString::Chunk::CreatePlaceholder(StringRef Placeholder) {
126  return Chunk(CK_Placeholder, Placeholder);
127}
128
129CodeCompletionString::Chunk
130CodeCompletionString::Chunk::CreateInformative(StringRef Informative) {
131  return Chunk(CK_Informative, Informative);
132}
133
134CodeCompletionString::Chunk
135CodeCompletionString::Chunk::CreateResultType(StringRef ResultType) {
136  return Chunk(CK_ResultType, ResultType);
137}
138
139CodeCompletionString::Chunk
140CodeCompletionString::Chunk::CreateCurrentParameter(
141                                                StringRef CurrentParameter) {
142  return Chunk(CK_CurrentParameter, CurrentParameter);
143}
144
145CodeCompletionString::Chunk CodeCompletionString::Chunk::Clone() const {
146  switch (Kind) {
147  case CK_TypedText:
148  case CK_Text:
149  case CK_Placeholder:
150  case CK_Informative:
151  case CK_ResultType:
152  case CK_CurrentParameter:
153  case CK_LeftParen:
154  case CK_RightParen:
155  case CK_LeftBracket:
156  case CK_RightBracket:
157  case CK_LeftBrace:
158  case CK_RightBrace:
159  case CK_LeftAngle:
160  case CK_RightAngle:
161  case CK_Comma:
162  case CK_Colon:
163  case CK_SemiColon:
164  case CK_Equal:
165  case CK_HorizontalSpace:
166  case CK_VerticalSpace:
167    return Chunk(Kind, Text);
168
169  case CK_Optional: {
170    std::auto_ptr<CodeCompletionString> Opt(Optional->Clone());
171    return CreateOptional(Opt);
172  }
173  }
174
175  // Silence GCC warning.
176  return Chunk();
177}
178
179void
180CodeCompletionString::Chunk::Destroy() {
181  switch (Kind) {
182  case CK_Optional:
183    delete Optional;
184    break;
185
186  case CK_TypedText:
187  case CK_Text:
188  case CK_Placeholder:
189  case CK_Informative:
190  case CK_ResultType:
191  case CK_CurrentParameter:
192    delete [] Text;
193    break;
194
195  case CK_LeftParen:
196  case CK_RightParen:
197  case CK_LeftBracket:
198  case CK_RightBracket:
199  case CK_LeftBrace:
200  case CK_RightBrace:
201  case CK_LeftAngle:
202  case CK_RightAngle:
203  case CK_Comma:
204  case CK_Colon:
205  case CK_SemiColon:
206  case CK_Equal:
207  case CK_HorizontalSpace:
208  case CK_VerticalSpace:
209    break;
210  }
211}
212
213void CodeCompletionString::clear() {
214  std::for_each(Chunks.begin(), Chunks.end(),
215                std::mem_fun_ref(&Chunk::Destroy));
216  Chunks.clear();
217}
218
219std::string CodeCompletionString::getAsString() const {
220  std::string Result;
221  llvm::raw_string_ostream OS(Result);
222
223  for (iterator C = begin(), CEnd = end(); C != CEnd; ++C) {
224    switch (C->Kind) {
225    case CK_Optional: OS << "{#" << C->Optional->getAsString() << "#}"; break;
226    case CK_Placeholder: OS << "<#" << C->Text << "#>"; break;
227
228    case CK_Informative:
229    case CK_ResultType:
230      OS << "[#" << C->Text << "#]";
231      break;
232
233    case CK_CurrentParameter: OS << "<#" << C->Text << "#>"; break;
234    default: OS << C->Text; break;
235    }
236  }
237  return OS.str();
238}
239
240const char *CodeCompletionString::getTypedText() const {
241  for (iterator C = begin(), CEnd = end(); C != CEnd; ++C)
242    if (C->Kind == CK_TypedText)
243      return C->Text;
244
245  return 0;
246}
247
248CodeCompletionString *
249CodeCompletionString::Clone(CodeCompletionString *Result) const {
250  if (!Result)
251    Result = new CodeCompletionString;
252  for (iterator C = begin(), CEnd = end(); C != CEnd; ++C)
253    Result->AddChunk(C->Clone());
254  return Result;
255}
256
257static void WriteUnsigned(llvm::raw_ostream &OS, unsigned Value) {
258  OS.write((const char *)&Value, sizeof(unsigned));
259}
260
261static bool ReadUnsigned(const char *&Memory, const char *MemoryEnd,
262                         unsigned &Value) {
263  if (Memory + sizeof(unsigned) > MemoryEnd)
264    return true;
265
266  memmove(&Value, Memory, sizeof(unsigned));
267  Memory += sizeof(unsigned);
268  return false;
269}
270
271void CodeCompletionString::Serialize(llvm::raw_ostream &OS) const {
272  // Write the number of chunks.
273  WriteUnsigned(OS, size());
274
275  for (iterator C = begin(), CEnd = end(); C != CEnd; ++C) {
276    WriteUnsigned(OS, C->Kind);
277
278    switch (C->Kind) {
279    case CK_TypedText:
280    case CK_Text:
281    case CK_Placeholder:
282    case CK_Informative:
283    case CK_ResultType:
284    case CK_CurrentParameter: {
285      const char *Text = C->Text;
286      unsigned StrLen = strlen(Text);
287      WriteUnsigned(OS, StrLen);
288      OS.write(Text, StrLen);
289      break;
290    }
291
292    case CK_Optional:
293      C->Optional->Serialize(OS);
294      break;
295
296    case CK_LeftParen:
297    case CK_RightParen:
298    case CK_LeftBracket:
299    case CK_RightBracket:
300    case CK_LeftBrace:
301    case CK_RightBrace:
302    case CK_LeftAngle:
303    case CK_RightAngle:
304    case CK_Comma:
305    case CK_Colon:
306    case CK_SemiColon:
307    case CK_Equal:
308    case CK_HorizontalSpace:
309    case CK_VerticalSpace:
310      break;
311    }
312  }
313}
314
315bool CodeCompletionString::Deserialize(const char *&Str, const char *StrEnd) {
316  if (Str == StrEnd || *Str == 0)
317    return false;
318
319  unsigned NumBlocks;
320  if (ReadUnsigned(Str, StrEnd, NumBlocks))
321    return false;
322
323  for (unsigned I = 0; I != NumBlocks; ++I) {
324    if (Str + 1 >= StrEnd)
325      break;
326
327    // Parse the next kind.
328    unsigned KindValue;
329    if (ReadUnsigned(Str, StrEnd, KindValue))
330      return false;
331
332    switch (ChunkKind Kind = (ChunkKind)KindValue) {
333    case CK_TypedText:
334    case CK_Text:
335    case CK_Placeholder:
336    case CK_Informative:
337    case CK_ResultType:
338    case CK_CurrentParameter: {
339      unsigned StrLen;
340      if (ReadUnsigned(Str, StrEnd, StrLen) || (Str + StrLen > StrEnd))
341        return false;
342
343      AddChunk(Chunk(Kind, StringRef(Str, StrLen)));
344      Str += StrLen;
345      break;
346    }
347
348    case CK_Optional: {
349      std::auto_ptr<CodeCompletionString> Optional(new CodeCompletionString());
350      if (Optional->Deserialize(Str, StrEnd))
351        AddOptionalChunk(Optional);
352      break;
353    }
354
355    case CK_LeftParen:
356    case CK_RightParen:
357    case CK_LeftBracket:
358    case CK_RightBracket:
359    case CK_LeftBrace:
360    case CK_RightBrace:
361    case CK_LeftAngle:
362    case CK_RightAngle:
363    case CK_Comma:
364    case CK_Colon:
365    case CK_SemiColon:
366    case CK_Equal:
367    case CK_HorizontalSpace:
368    case CK_VerticalSpace:
369      AddChunk(Chunk(Kind));
370      break;
371    }
372  };
373
374  return true;
375}
376
377void CodeCompleteConsumer::Result::Destroy() {
378  if (Kind == RK_Pattern) {
379    delete Pattern;
380    Pattern = 0;
381  }
382}
383
384unsigned CodeCompleteConsumer::Result::getPriorityFromDecl(NamedDecl *ND) {
385  if (!ND)
386    return CCP_Unlikely;
387
388  // Context-based decisions.
389  DeclContext *DC = ND->getDeclContext()->getLookupContext();
390  if (DC->isFunctionOrMethod() || isa<BlockDecl>(DC))
391    return CCP_LocalDeclaration;
392  if (DC->isRecord() || isa<ObjCContainerDecl>(DC))
393    return CCP_MemberDeclaration;
394
395  // Content-based decisions.
396  if (isa<EnumConstantDecl>(ND))
397    return CCP_Constant;
398  if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
399    return CCP_Type;
400  return CCP_Declaration;
401}
402
403//===----------------------------------------------------------------------===//
404// Code completion overload candidate implementation
405//===----------------------------------------------------------------------===//
406FunctionDecl *
407CodeCompleteConsumer::OverloadCandidate::getFunction() const {
408  if (getKind() == CK_Function)
409    return Function;
410  else if (getKind() == CK_FunctionTemplate)
411    return FunctionTemplate->getTemplatedDecl();
412  else
413    return 0;
414}
415
416const FunctionType *
417CodeCompleteConsumer::OverloadCandidate::getFunctionType() const {
418  switch (Kind) {
419  case CK_Function:
420    return Function->getType()->getAs<FunctionType>();
421
422  case CK_FunctionTemplate:
423    return FunctionTemplate->getTemplatedDecl()->getType()
424             ->getAs<FunctionType>();
425
426  case CK_FunctionType:
427    return Type;
428  }
429
430  return 0;
431}
432
433//===----------------------------------------------------------------------===//
434// Code completion consumer implementation
435//===----------------------------------------------------------------------===//
436
437CodeCompleteConsumer::~CodeCompleteConsumer() { }
438
439void
440PrintingCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &SemaRef,
441                                                 CodeCompletionContext Context,
442                                                         Result *Results,
443                                                         unsigned NumResults) {
444  // Print the results.
445  for (unsigned I = 0; I != NumResults; ++I) {
446    OS << "COMPLETION: ";
447    switch (Results[I].Kind) {
448    case Result::RK_Declaration:
449      OS << Results[I].Declaration;
450      if (Results[I].Hidden)
451        OS << " (Hidden)";
452      if (CodeCompletionString *CCS
453            = Results[I].CreateCodeCompletionString(SemaRef)) {
454        OS << " : " << CCS->getAsString();
455        delete CCS;
456      }
457
458      OS << '\n';
459      break;
460
461    case Result::RK_Keyword:
462      OS << Results[I].Keyword << '\n';
463      break;
464
465    case Result::RK_Macro: {
466      OS << Results[I].Macro->getName();
467      if (CodeCompletionString *CCS
468            = Results[I].CreateCodeCompletionString(SemaRef)) {
469        OS << " : " << CCS->getAsString();
470        delete CCS;
471      }
472      OS << '\n';
473      break;
474    }
475
476    case Result::RK_Pattern: {
477      OS << "Pattern : "
478         << Results[I].Pattern->getAsString() << '\n';
479      break;
480    }
481    }
482  }
483}
484
485void
486PrintingCodeCompleteConsumer::ProcessOverloadCandidates(Sema &SemaRef,
487                                                        unsigned CurrentArg,
488                                              OverloadCandidate *Candidates,
489                                                     unsigned NumCandidates) {
490  for (unsigned I = 0; I != NumCandidates; ++I) {
491    if (CodeCompletionString *CCS
492          = Candidates[I].CreateSignatureString(CurrentArg, SemaRef)) {
493      OS << "OVERLOAD: " << CCS->getAsString() << "\n";
494      delete CCS;
495    }
496  }
497}
498
499void CodeCompleteConsumer::Result::computeCursorKind() {
500  switch (Kind) {
501  case RK_Declaration:
502    switch (Declaration->getKind()) {
503    case Decl::Record:
504    case Decl::CXXRecord:
505    case Decl::ClassTemplateSpecialization: {
506      RecordDecl *Record = cast<RecordDecl>(Declaration);
507      if (Record->isStruct())
508        CursorKind = CXCursor_StructDecl;
509      else if (Record->isUnion())
510        CursorKind = CXCursor_UnionDecl;
511      else
512        CursorKind = CXCursor_ClassDecl;
513      break;
514    }
515
516    case Decl::ObjCMethod: {
517      ObjCMethodDecl *Method = cast<ObjCMethodDecl>(Declaration);
518      if (Method->isInstanceMethod())
519          CursorKind = CXCursor_ObjCInstanceMethodDecl;
520      else
521        CursorKind = CXCursor_ObjCClassMethodDecl;
522      break;
523    }
524
525    case Decl::Typedef:
526      CursorKind = CXCursor_TypedefDecl;
527      break;
528
529    case Decl::Enum:
530      CursorKind = CXCursor_EnumDecl;
531      break;
532
533    case Decl::Field:
534      CursorKind = CXCursor_FieldDecl;
535      break;
536
537    case Decl::EnumConstant:
538      CursorKind = CXCursor_EnumConstantDecl;
539      break;
540
541    case Decl::Function:
542    case Decl::CXXMethod:
543    case Decl::CXXConstructor:
544    case Decl::CXXDestructor:
545    case Decl::CXXConversion:
546      CursorKind = CXCursor_FunctionDecl;
547      break;
548
549    case Decl::Var:
550      CursorKind = CXCursor_VarDecl;
551      break;
552
553    case Decl::ParmVar:
554      CursorKind = CXCursor_ParmDecl;
555      break;
556
557    case Decl::ObjCInterface:
558      CursorKind = CXCursor_ObjCInterfaceDecl;
559      break;
560
561    case Decl::ObjCCategory:
562      CursorKind = CXCursor_ObjCCategoryDecl;
563      break;
564
565    case Decl::ObjCProtocol:
566      CursorKind = CXCursor_ObjCProtocolDecl;
567      break;
568
569    case Decl::ObjCProperty:
570      CursorKind = CXCursor_ObjCPropertyDecl;
571      break;
572
573    case Decl::ObjCIvar:
574      CursorKind = CXCursor_ObjCIvarDecl;
575      break;
576
577    case Decl::ObjCImplementation:
578      CursorKind = CXCursor_ObjCImplementationDecl;
579      break;
580
581    case Decl::ObjCCategoryImpl:
582      CursorKind = CXCursor_ObjCCategoryImplDecl;
583      break;
584
585    default:
586      CursorKind = CXCursor_NotImplemented;
587      break;
588    }
589    break;
590
591  case Result::RK_Macro:
592    CursorKind = CXCursor_MacroDefinition;
593    break;
594
595  case Result::RK_Keyword:
596    CursorKind = CXCursor_NotImplemented;
597    break;
598
599  case Result::RK_Pattern:
600    // Do nothing: Patterns can come with cursor kinds!
601    break;
602  }
603}
604
605void
606CIndexCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &SemaRef,
607                                                 CodeCompletionContext Context,
608                                                       Result *Results,
609                                                       unsigned NumResults) {
610  // Print the results.
611  for (unsigned I = 0; I != NumResults; ++I) {
612    WriteUnsigned(OS, Results[I].CursorKind);
613    WriteUnsigned(OS, Results[I].Priority);
614    CodeCompletionString *CCS = Results[I].CreateCodeCompletionString(SemaRef);
615    assert(CCS && "No code-completion string?");
616    CCS->Serialize(OS);
617    delete CCS;
618  }
619}
620
621void
622CIndexCodeCompleteConsumer::ProcessOverloadCandidates(Sema &SemaRef,
623                                                      unsigned CurrentArg,
624                                                OverloadCandidate *Candidates,
625                                                       unsigned NumCandidates) {
626  for (unsigned I = 0; I != NumCandidates; ++I) {
627    WriteUnsigned(OS, CXCursor_NotImplemented);
628    WriteUnsigned(OS, /*Priority=*/0);
629    CodeCompletionString *CCS
630      = Candidates[I].CreateSignatureString(CurrentArg, SemaRef);
631    assert(CCS && "No code-completion string?");
632    CCS->Serialize(OS);
633    delete CCS;
634  }
635}
636