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/Scope.h"
15 #include "clang/Sema/Sema.h"
16 #include "clang/AST/DeclCXX.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/Lex/Preprocessor.h"
20 #include "clang-c/Index.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include <algorithm>
26 #include <cstring>
27 #include <functional>
28 
29 using namespace clang;
30 
31 //===----------------------------------------------------------------------===//
32 // Code completion context implementation
33 //===----------------------------------------------------------------------===//
34 
35 bool CodeCompletionContext::wantConstructorResults() const {
36   switch (Kind) {
37   case CCC_Recovery:
38   case CCC_Statement:
39   case CCC_Expression:
40   case CCC_ObjCMessageReceiver:
41   case CCC_ParenthesizedExpression:
42     return true;
43 
44   case CCC_TopLevel:
45   case CCC_ObjCInterface:
46   case CCC_ObjCImplementation:
47   case CCC_ObjCIvarList:
48   case CCC_ClassStructUnion:
49   case CCC_DotMemberAccess:
50   case CCC_ArrowMemberAccess:
51   case CCC_ObjCPropertyAccess:
52   case CCC_EnumTag:
53   case CCC_UnionTag:
54   case CCC_ClassOrStructTag:
55   case CCC_ObjCProtocolName:
56   case CCC_Namespace:
57   case CCC_Type:
58   case CCC_Name:
59   case CCC_PotentiallyQualifiedName:
60   case CCC_MacroName:
61   case CCC_MacroNameUse:
62   case CCC_PreprocessorExpression:
63   case CCC_PreprocessorDirective:
64   case CCC_NaturalLanguage:
65   case CCC_SelectorName:
66   case CCC_TypeQualifiers:
67   case CCC_Other:
68   case CCC_OtherWithMacros:
69   case CCC_ObjCInstanceMessage:
70   case CCC_ObjCClassMessage:
71   case CCC_ObjCInterfaceName:
72   case CCC_ObjCCategoryName:
73     return false;
74   }
75 
76   llvm_unreachable("Invalid CodeCompletionContext::Kind!");
77 }
78 
79 //===----------------------------------------------------------------------===//
80 // Code completion string implementation
81 //===----------------------------------------------------------------------===//
82 CodeCompletionString::Chunk::Chunk(ChunkKind Kind, const char *Text)
83   : Kind(Kind), Text("")
84 {
85   switch (Kind) {
86   case CK_TypedText:
87   case CK_Text:
88   case CK_Placeholder:
89   case CK_Informative:
90   case CK_ResultType:
91   case CK_CurrentParameter:
92     this->Text = Text;
93     break;
94 
95   case CK_Optional:
96     llvm_unreachable("Optional strings cannot be created from text");
97 
98   case CK_LeftParen:
99     this->Text = "(";
100     break;
101 
102   case CK_RightParen:
103     this->Text = ")";
104     break;
105 
106   case CK_LeftBracket:
107     this->Text = "[";
108     break;
109 
110   case CK_RightBracket:
111     this->Text = "]";
112     break;
113 
114   case CK_LeftBrace:
115     this->Text = "{";
116     break;
117 
118   case CK_RightBrace:
119     this->Text = "}";
120     break;
121 
122   case CK_LeftAngle:
123     this->Text = "<";
124     break;
125 
126   case CK_RightAngle:
127     this->Text = ">";
128     break;
129 
130   case CK_Comma:
131     this->Text = ", ";
132     break;
133 
134   case CK_Colon:
135     this->Text = ":";
136     break;
137 
138   case CK_SemiColon:
139     this->Text = ";";
140     break;
141 
142   case CK_Equal:
143     this->Text = " = ";
144     break;
145 
146   case CK_HorizontalSpace:
147     this->Text = " ";
148     break;
149 
150   case CK_VerticalSpace:
151     this->Text = "\n";
152     break;
153   }
154 }
155 
156 CodeCompletionString::Chunk
157 CodeCompletionString::Chunk::CreateText(const char *Text) {
158   return Chunk(CK_Text, Text);
159 }
160 
161 CodeCompletionString::Chunk
162 CodeCompletionString::Chunk::CreateOptional(CodeCompletionString *Optional) {
163   Chunk Result;
164   Result.Kind = CK_Optional;
165   Result.Optional = Optional;
166   return Result;
167 }
168 
169 CodeCompletionString::Chunk
170 CodeCompletionString::Chunk::CreatePlaceholder(const char *Placeholder) {
171   return Chunk(CK_Placeholder, Placeholder);
172 }
173 
174 CodeCompletionString::Chunk
175 CodeCompletionString::Chunk::CreateInformative(const char *Informative) {
176   return Chunk(CK_Informative, Informative);
177 }
178 
179 CodeCompletionString::Chunk
180 CodeCompletionString::Chunk::CreateResultType(const char *ResultType) {
181   return Chunk(CK_ResultType, ResultType);
182 }
183 
184 CodeCompletionString::Chunk
185 CodeCompletionString::Chunk::CreateCurrentParameter(
186                                                 const char *CurrentParameter) {
187   return Chunk(CK_CurrentParameter, CurrentParameter);
188 }
189 
190 CodeCompletionString::CodeCompletionString(const Chunk *Chunks,
191                                            unsigned NumChunks,
192                                            unsigned Priority,
193                                            CXAvailabilityKind Availability,
194                                            const char **Annotations,
195                                            unsigned NumAnnotations,
196                                            StringRef ParentName,
197                                            const char *BriefComment)
198   : NumChunks(NumChunks), NumAnnotations(NumAnnotations),
199     Priority(Priority), Availability(Availability),
200     ParentName(ParentName), BriefComment(BriefComment)
201 {
202   assert(NumChunks <= 0xffff);
203   assert(NumAnnotations <= 0xffff);
204 
205   Chunk *StoredChunks = reinterpret_cast<Chunk *>(this + 1);
206   for (unsigned I = 0; I != NumChunks; ++I)
207     StoredChunks[I] = Chunks[I];
208 
209   const char **StoredAnnotations = reinterpret_cast<const char **>(StoredChunks + NumChunks);
210   for (unsigned I = 0; I != NumAnnotations; ++I)
211     StoredAnnotations[I] = Annotations[I];
212 }
213 
214 unsigned CodeCompletionString::getAnnotationCount() const {
215   return NumAnnotations;
216 }
217 
218 const char *CodeCompletionString::getAnnotation(unsigned AnnotationNr) const {
219   if (AnnotationNr < NumAnnotations)
220     return reinterpret_cast<const char * const*>(end())[AnnotationNr];
221   else
222     return 0;
223 }
224 
225 
226 std::string CodeCompletionString::getAsString() const {
227   std::string Result;
228   llvm::raw_string_ostream OS(Result);
229 
230   for (iterator C = begin(), CEnd = end(); C != CEnd; ++C) {
231     switch (C->Kind) {
232     case CK_Optional: OS << "{#" << C->Optional->getAsString() << "#}"; break;
233     case CK_Placeholder: OS << "<#" << C->Text << "#>"; break;
234 
235     case CK_Informative:
236     case CK_ResultType:
237       OS << "[#" << C->Text << "#]";
238       break;
239 
240     case CK_CurrentParameter: OS << "<#" << C->Text << "#>"; break;
241     default: OS << C->Text; break;
242     }
243   }
244   return OS.str();
245 }
246 
247 const char *CodeCompletionString::getTypedText() const {
248   for (iterator C = begin(), CEnd = end(); C != CEnd; ++C)
249     if (C->Kind == CK_TypedText)
250       return C->Text;
251 
252   return 0;
253 }
254 
255 const char *CodeCompletionAllocator::CopyString(StringRef String) {
256   char *Mem = (char *)Allocate(String.size() + 1, 1);
257   std::copy(String.begin(), String.end(), Mem);
258   Mem[String.size()] = 0;
259   return Mem;
260 }
261 
262 const char *CodeCompletionAllocator::CopyString(Twine String) {
263   // FIXME: It would be more efficient to teach Twine to tell us its size and
264   // then add a routine there to fill in an allocated char* with the contents
265   // of the string.
266   SmallString<128> Data;
267   return CopyString(String.toStringRef(Data));
268 }
269 
270 StringRef CodeCompletionTUInfo::getParentName(DeclContext *DC) {
271   NamedDecl *ND = dyn_cast<NamedDecl>(DC);
272   if (!ND)
273     return StringRef();
274 
275   // Check whether we've already cached the parent name.
276   StringRef &CachedParentName = ParentNames[DC];
277   if (!CachedParentName.empty())
278     return CachedParentName;
279 
280   // If we already processed this DeclContext and assigned empty to it, the
281   // data pointer will be non-null.
282   if (CachedParentName.data() != 0)
283     return StringRef();
284 
285   // Find the interesting names.
286   llvm::SmallVector<DeclContext *, 2> Contexts;
287   while (DC && !DC->isFunctionOrMethod()) {
288     if (NamedDecl *ND = dyn_cast<NamedDecl>(DC)) {
289       if (ND->getIdentifier())
290         Contexts.push_back(DC);
291     }
292 
293     DC = DC->getParent();
294   }
295 
296   {
297     llvm::SmallString<128> S;
298     llvm::raw_svector_ostream OS(S);
299     bool First = true;
300     for (unsigned I = Contexts.size(); I != 0; --I) {
301       if (First)
302         First = false;
303       else {
304         OS << "::";
305       }
306 
307       DeclContext *CurDC = Contexts[I-1];
308       if (ObjCCategoryImplDecl *CatImpl = dyn_cast<ObjCCategoryImplDecl>(CurDC))
309         CurDC = CatImpl->getCategoryDecl();
310 
311       if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(CurDC)) {
312         ObjCInterfaceDecl *Interface = Cat->getClassInterface();
313         if (!Interface) {
314           // Assign an empty StringRef but with non-null data to distinguish
315           // between empty because we didn't process the DeclContext yet.
316           CachedParentName = StringRef((const char *)~0U, 0);
317           return StringRef();
318         }
319 
320         OS << Interface->getName() << '(' << Cat->getName() << ')';
321       } else {
322         OS << cast<NamedDecl>(CurDC)->getName();
323       }
324     }
325 
326     CachedParentName = AllocatorRef->CopyString(OS.str());
327   }
328 
329   return CachedParentName;
330 }
331 
332 CodeCompletionString *CodeCompletionBuilder::TakeString() {
333   void *Mem = getAllocator().Allocate(
334                   sizeof(CodeCompletionString) + sizeof(Chunk) * Chunks.size()
335                                     + sizeof(const char *) * Annotations.size(),
336                                  llvm::alignOf<CodeCompletionString>());
337   CodeCompletionString *Result
338     = new (Mem) CodeCompletionString(Chunks.data(), Chunks.size(),
339                                      Priority, Availability,
340                                      Annotations.data(), Annotations.size(),
341                                      ParentName, BriefComment);
342   Chunks.clear();
343   return Result;
344 }
345 
346 void CodeCompletionBuilder::AddTypedTextChunk(const char *Text) {
347   Chunks.push_back(Chunk(CodeCompletionString::CK_TypedText, Text));
348 }
349 
350 void CodeCompletionBuilder::AddTextChunk(const char *Text) {
351   Chunks.push_back(Chunk::CreateText(Text));
352 }
353 
354 void CodeCompletionBuilder::AddOptionalChunk(CodeCompletionString *Optional) {
355   Chunks.push_back(Chunk::CreateOptional(Optional));
356 }
357 
358 void CodeCompletionBuilder::AddPlaceholderChunk(const char *Placeholder) {
359   Chunks.push_back(Chunk::CreatePlaceholder(Placeholder));
360 }
361 
362 void CodeCompletionBuilder::AddInformativeChunk(const char *Text) {
363   Chunks.push_back(Chunk::CreateInformative(Text));
364 }
365 
366 void CodeCompletionBuilder::AddResultTypeChunk(const char *ResultType) {
367   Chunks.push_back(Chunk::CreateResultType(ResultType));
368 }
369 
370 void
371 CodeCompletionBuilder::AddCurrentParameterChunk(const char *CurrentParameter) {
372   Chunks.push_back(Chunk::CreateCurrentParameter(CurrentParameter));
373 }
374 
375 void CodeCompletionBuilder::AddChunk(CodeCompletionString::ChunkKind CK,
376                                      const char *Text) {
377   Chunks.push_back(Chunk(CK, Text));
378 }
379 
380 void CodeCompletionBuilder::addParentContext(DeclContext *DC) {
381   if (DC->isTranslationUnit()) {
382     return;
383   }
384 
385   if (DC->isFunctionOrMethod())
386     return;
387 
388   NamedDecl *ND = dyn_cast<NamedDecl>(DC);
389   if (!ND)
390     return;
391 
392   ParentName = getCodeCompletionTUInfo().getParentName(DC);
393 }
394 
395 void CodeCompletionBuilder::addBriefComment(StringRef Comment) {
396   BriefComment = Allocator.CopyString(Comment);
397 }
398 
399 unsigned CodeCompletionResult::getPriorityFromDecl(NamedDecl *ND) {
400   if (!ND)
401     return CCP_Unlikely;
402 
403   // Context-based decisions.
404   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
405   if (DC->isFunctionOrMethod() || isa<BlockDecl>(DC)) {
406     // _cmd is relatively rare
407     if (ImplicitParamDecl *ImplicitParam = dyn_cast<ImplicitParamDecl>(ND))
408       if (ImplicitParam->getIdentifier() &&
409           ImplicitParam->getIdentifier()->isStr("_cmd"))
410         return CCP_ObjC_cmd;
411 
412     return CCP_LocalDeclaration;
413   }
414   if (DC->isRecord() || isa<ObjCContainerDecl>(DC))
415     return CCP_MemberDeclaration;
416 
417   // Content-based decisions.
418   if (isa<EnumConstantDecl>(ND))
419     return CCP_Constant;
420   if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
421     return CCP_Type;
422 
423   return CCP_Declaration;
424 }
425 
426 //===----------------------------------------------------------------------===//
427 // Code completion overload candidate implementation
428 //===----------------------------------------------------------------------===//
429 FunctionDecl *
430 CodeCompleteConsumer::OverloadCandidate::getFunction() const {
431   if (getKind() == CK_Function)
432     return Function;
433   else if (getKind() == CK_FunctionTemplate)
434     return FunctionTemplate->getTemplatedDecl();
435   else
436     return 0;
437 }
438 
439 const FunctionType *
440 CodeCompleteConsumer::OverloadCandidate::getFunctionType() const {
441   switch (Kind) {
442   case CK_Function:
443     return Function->getType()->getAs<FunctionType>();
444 
445   case CK_FunctionTemplate:
446     return FunctionTemplate->getTemplatedDecl()->getType()
447              ->getAs<FunctionType>();
448 
449   case CK_FunctionType:
450     return Type;
451   }
452 
453   llvm_unreachable("Invalid CandidateKind!");
454 }
455 
456 //===----------------------------------------------------------------------===//
457 // Code completion consumer implementation
458 //===----------------------------------------------------------------------===//
459 
460 CodeCompleteConsumer::~CodeCompleteConsumer() { }
461 
462 void
463 PrintingCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &SemaRef,
464                                                  CodeCompletionContext Context,
465                                                  CodeCompletionResult *Results,
466                                                          unsigned NumResults) {
467   std::stable_sort(Results, Results + NumResults);
468 
469   // Print the results.
470   for (unsigned I = 0; I != NumResults; ++I) {
471     OS << "COMPLETION: ";
472     switch (Results[I].Kind) {
473     case CodeCompletionResult::RK_Declaration:
474       OS << *Results[I].Declaration;
475       if (Results[I].Hidden)
476         OS << " (Hidden)";
477       if (CodeCompletionString *CCS
478             = Results[I].CreateCodeCompletionString(SemaRef, getAllocator(),
479                                                     CCTUInfo,
480                                                     includeBriefComments())) {
481         OS << " : " << CCS->getAsString();
482         if (const char *BriefComment = CCS->getBriefComment())
483           OS << " : " << BriefComment;
484       }
485 
486       OS << '\n';
487       break;
488 
489     case CodeCompletionResult::RK_Keyword:
490       OS << Results[I].Keyword << '\n';
491       break;
492 
493     case CodeCompletionResult::RK_Macro: {
494       OS << Results[I].Macro->getName();
495       if (CodeCompletionString *CCS
496             = Results[I].CreateCodeCompletionString(SemaRef, getAllocator(),
497                                                     CCTUInfo,
498                                                     includeBriefComments())) {
499         OS << " : " << CCS->getAsString();
500       }
501       OS << '\n';
502       break;
503     }
504 
505     case CodeCompletionResult::RK_Pattern: {
506       OS << "Pattern : "
507          << Results[I].Pattern->getAsString() << '\n';
508       break;
509     }
510     }
511   }
512 }
513 
514 void
515 PrintingCodeCompleteConsumer::ProcessOverloadCandidates(Sema &SemaRef,
516                                                         unsigned CurrentArg,
517                                               OverloadCandidate *Candidates,
518                                                      unsigned NumCandidates) {
519   for (unsigned I = 0; I != NumCandidates; ++I) {
520     if (CodeCompletionString *CCS
521           = Candidates[I].CreateSignatureString(CurrentArg, SemaRef,
522                                                 getAllocator(), CCTUInfo)) {
523       OS << "OVERLOAD: " << CCS->getAsString() << "\n";
524     }
525   }
526 }
527 
528 /// \brief Retrieve the effective availability of the given declaration.
529 static AvailabilityResult getDeclAvailability(Decl *D) {
530   AvailabilityResult AR = D->getAvailability();
531   if (isa<EnumConstantDecl>(D))
532     AR = std::max(AR, cast<Decl>(D->getDeclContext())->getAvailability());
533   return AR;
534 }
535 
536 void CodeCompletionResult::computeCursorKindAndAvailability(bool Accessible) {
537   switch (Kind) {
538   case RK_Pattern:
539     if (!Declaration) {
540       // Do nothing: Patterns can come with cursor kinds!
541       break;
542     }
543     // Fall through
544 
545   case RK_Declaration: {
546     // Set the availability based on attributes.
547     switch (getDeclAvailability(Declaration)) {
548     case AR_Available:
549     case AR_NotYetIntroduced:
550       Availability = CXAvailability_Available;
551       break;
552 
553     case AR_Deprecated:
554       Availability = CXAvailability_Deprecated;
555       break;
556 
557     case AR_Unavailable:
558       Availability = CXAvailability_NotAvailable;
559       break;
560     }
561 
562     if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Declaration))
563       if (Function->isDeleted())
564         Availability = CXAvailability_NotAvailable;
565 
566     CursorKind = getCursorKindForDecl(Declaration);
567     if (CursorKind == CXCursor_UnexposedDecl) {
568       // FIXME: Forward declarations of Objective-C classes and protocols
569       // are not directly exposed, but we want code completion to treat them
570       // like a definition.
571       if (isa<ObjCInterfaceDecl>(Declaration))
572         CursorKind = CXCursor_ObjCInterfaceDecl;
573       else if (isa<ObjCProtocolDecl>(Declaration))
574         CursorKind = CXCursor_ObjCProtocolDecl;
575       else
576         CursorKind = CXCursor_NotImplemented;
577     }
578     break;
579   }
580 
581   case RK_Macro:
582   case RK_Keyword:
583     llvm_unreachable("Macro and keyword kinds are handled by the constructors");
584   }
585 
586   if (!Accessible)
587     Availability = CXAvailability_NotAccessible;
588 }
589 
590 /// \brief Retrieve the name that should be used to order a result.
591 ///
592 /// If the name needs to be constructed as a string, that string will be
593 /// saved into Saved and the returned StringRef will refer to it.
594 static StringRef getOrderedName(const CodeCompletionResult &R,
595                                     std::string &Saved) {
596   switch (R.Kind) {
597     case CodeCompletionResult::RK_Keyword:
598       return R.Keyword;
599 
600     case CodeCompletionResult::RK_Pattern:
601       return R.Pattern->getTypedText();
602 
603     case CodeCompletionResult::RK_Macro:
604       return R.Macro->getName();
605 
606     case CodeCompletionResult::RK_Declaration:
607       // Handle declarations below.
608       break;
609   }
610 
611   DeclarationName Name = R.Declaration->getDeclName();
612 
613   // If the name is a simple identifier (by far the common case), or a
614   // zero-argument selector, just return a reference to that identifier.
615   if (IdentifierInfo *Id = Name.getAsIdentifierInfo())
616     return Id->getName();
617   if (Name.isObjCZeroArgSelector())
618     if (IdentifierInfo *Id
619         = Name.getObjCSelector().getIdentifierInfoForSlot(0))
620       return Id->getName();
621 
622   Saved = Name.getAsString();
623   return Saved;
624 }
625 
626 bool clang::operator<(const CodeCompletionResult &X,
627                       const CodeCompletionResult &Y) {
628   std::string XSaved, YSaved;
629   StringRef XStr = getOrderedName(X, XSaved);
630   StringRef YStr = getOrderedName(Y, YSaved);
631   int cmp = XStr.compare_lower(YStr);
632   if (cmp)
633     return cmp < 0;
634 
635   // If case-insensitive comparison fails, try case-sensitive comparison.
636   cmp = XStr.compare(YStr);
637   if (cmp)
638     return cmp < 0;
639 
640   return false;
641 }
642