clang API Documentation

CodeCompleteConsumer.cpp
Go to the documentation of this file.
00001 //===--- CodeCompleteConsumer.cpp - Code Completion Interface ---*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file implements the CodeCompleteConsumer class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 #include "clang/Sema/CodeCompleteConsumer.h"
00014 #include "clang/Sema/Scope.h"
00015 #include "clang/Sema/Sema.h"
00016 #include "clang/AST/DeclCXX.h"
00017 #include "clang/AST/DeclObjC.h"
00018 #include "clang/AST/DeclTemplate.h"
00019 #include "clang/Lex/Preprocessor.h"
00020 #include "clang-c/Index.h"
00021 #include "llvm/ADT/SmallString.h"
00022 #include "llvm/ADT/STLExtras.h"
00023 #include "llvm/ADT/Twine.h"
00024 #include "llvm/Support/raw_ostream.h"
00025 #include <algorithm>
00026 #include <cstring>
00027 #include <functional>
00028 
00029 using namespace clang;
00030 
00031 //===----------------------------------------------------------------------===//
00032 // Code completion context implementation
00033 //===----------------------------------------------------------------------===//
00034 
00035 bool CodeCompletionContext::wantConstructorResults() const {
00036   switch (Kind) {
00037   case CCC_Recovery:
00038   case CCC_Statement:
00039   case CCC_Expression:
00040   case CCC_ObjCMessageReceiver:
00041   case CCC_ParenthesizedExpression:
00042     return true;
00043     
00044   case CCC_TopLevel:
00045   case CCC_ObjCInterface:
00046   case CCC_ObjCImplementation:
00047   case CCC_ObjCIvarList:
00048   case CCC_ClassStructUnion:
00049   case CCC_DotMemberAccess:
00050   case CCC_ArrowMemberAccess:
00051   case CCC_ObjCPropertyAccess:
00052   case CCC_EnumTag:
00053   case CCC_UnionTag:
00054   case CCC_ClassOrStructTag:
00055   case CCC_ObjCProtocolName:
00056   case CCC_Namespace:
00057   case CCC_Type:
00058   case CCC_Name:
00059   case CCC_PotentiallyQualifiedName:
00060   case CCC_MacroName:
00061   case CCC_MacroNameUse:
00062   case CCC_PreprocessorExpression:
00063   case CCC_PreprocessorDirective:
00064   case CCC_NaturalLanguage:
00065   case CCC_SelectorName:
00066   case CCC_TypeQualifiers:
00067   case CCC_Other:
00068   case CCC_OtherWithMacros:
00069   case CCC_ObjCInstanceMessage:
00070   case CCC_ObjCClassMessage:
00071   case CCC_ObjCInterfaceName:
00072   case CCC_ObjCCategoryName:
00073     return false;
00074   }
00075 
00076   llvm_unreachable("Invalid CodeCompletionContext::Kind!");
00077 }
00078 
00079 //===----------------------------------------------------------------------===//
00080 // Code completion string implementation
00081 //===----------------------------------------------------------------------===//
00082 CodeCompletionString::Chunk::Chunk(ChunkKind Kind, const char *Text) 
00083   : Kind(Kind), Text("")
00084 {
00085   switch (Kind) {
00086   case CK_TypedText:
00087   case CK_Text:
00088   case CK_Placeholder:
00089   case CK_Informative:
00090   case CK_ResultType:
00091   case CK_CurrentParameter:
00092     this->Text = Text;
00093     break;
00094 
00095   case CK_Optional:
00096     llvm_unreachable("Optional strings cannot be created from text");
00097       
00098   case CK_LeftParen:
00099     this->Text = "(";
00100     break;
00101 
00102   case CK_RightParen:
00103     this->Text = ")";
00104     break;
00105 
00106   case CK_LeftBracket:
00107     this->Text = "[";
00108     break;
00109     
00110   case CK_RightBracket:
00111     this->Text = "]";
00112     break;
00113     
00114   case CK_LeftBrace:
00115     this->Text = "{";
00116     break;
00117 
00118   case CK_RightBrace:
00119     this->Text = "}";
00120     break;
00121 
00122   case CK_LeftAngle:
00123     this->Text = "<";
00124     break;
00125     
00126   case CK_RightAngle:
00127     this->Text = ">";
00128     break;
00129       
00130   case CK_Comma:
00131     this->Text = ", ";
00132     break;
00133 
00134   case CK_Colon:
00135     this->Text = ":";
00136     break;
00137 
00138   case CK_SemiColon:
00139     this->Text = ";";
00140     break;
00141 
00142   case CK_Equal:
00143     this->Text = " = ";
00144     break;
00145 
00146   case CK_HorizontalSpace:
00147     this->Text = " ";
00148     break;
00149 
00150   case CK_VerticalSpace:
00151     this->Text = "\n";
00152     break;
00153   }
00154 }
00155 
00156 CodeCompletionString::Chunk
00157 CodeCompletionString::Chunk::CreateText(const char *Text) {
00158   return Chunk(CK_Text, Text);
00159 }
00160 
00161 CodeCompletionString::Chunk 
00162 CodeCompletionString::Chunk::CreateOptional(CodeCompletionString *Optional) {
00163   Chunk Result;
00164   Result.Kind = CK_Optional;
00165   Result.Optional = Optional;
00166   return Result;
00167 }
00168 
00169 CodeCompletionString::Chunk 
00170 CodeCompletionString::Chunk::CreatePlaceholder(const char *Placeholder) {
00171   return Chunk(CK_Placeholder, Placeholder);
00172 }
00173 
00174 CodeCompletionString::Chunk 
00175 CodeCompletionString::Chunk::CreateInformative(const char *Informative) {
00176   return Chunk(CK_Informative, Informative);
00177 }
00178 
00179 CodeCompletionString::Chunk 
00180 CodeCompletionString::Chunk::CreateResultType(const char *ResultType) {
00181   return Chunk(CK_ResultType, ResultType);
00182 }
00183 
00184 CodeCompletionString::Chunk 
00185 CodeCompletionString::Chunk::CreateCurrentParameter(
00186                                                 const char *CurrentParameter) {
00187   return Chunk(CK_CurrentParameter, CurrentParameter);
00188 }
00189 
00190 CodeCompletionString::CodeCompletionString(const Chunk *Chunks, 
00191                                            unsigned NumChunks,
00192                                            unsigned Priority, 
00193                                            CXAvailabilityKind Availability,
00194                                            const char **Annotations,
00195                                            unsigned NumAnnotations,
00196                                            CXCursorKind ParentKind,
00197                                            StringRef ParentName)
00198   : NumChunks(NumChunks), NumAnnotations(NumAnnotations),
00199     Priority(Priority), Availability(Availability), ParentKind(ParentKind),
00200     ParentName(ParentName)
00201 { 
00202   assert(NumChunks <= 0xffff);
00203   assert(NumAnnotations <= 0xffff);
00204 
00205   Chunk *StoredChunks = reinterpret_cast<Chunk *>(this + 1);
00206   for (unsigned I = 0; I != NumChunks; ++I)
00207     StoredChunks[I] = Chunks[I];
00208 
00209   const char **StoredAnnotations = reinterpret_cast<const char **>(StoredChunks + NumChunks);
00210   for (unsigned I = 0; I != NumAnnotations; ++I)
00211     StoredAnnotations[I] = Annotations[I];
00212 }
00213 
00214 unsigned CodeCompletionString::getAnnotationCount() const {
00215   return NumAnnotations;
00216 }
00217 
00218 const char *CodeCompletionString::getAnnotation(unsigned AnnotationNr) const {
00219   if (AnnotationNr < NumAnnotations)
00220     return reinterpret_cast<const char * const*>(end())[AnnotationNr];
00221   else
00222     return 0;
00223 }
00224 
00225 
00226 std::string CodeCompletionString::getAsString() const {
00227   std::string Result;
00228   llvm::raw_string_ostream OS(Result);
00229                           
00230   for (iterator C = begin(), CEnd = end(); C != CEnd; ++C) {
00231     switch (C->Kind) {
00232     case CK_Optional: OS << "{#" << C->Optional->getAsString() << "#}"; break;
00233     case CK_Placeholder: OS << "<#" << C->Text << "#>"; break;
00234         
00235     case CK_Informative: 
00236     case CK_ResultType:
00237       OS << "[#" << C->Text << "#]"; 
00238       break;
00239         
00240     case CK_CurrentParameter: OS << "<#" << C->Text << "#>"; break;
00241     default: OS << C->Text; break;
00242     }
00243   }
00244   return OS.str();
00245 }
00246 
00247 const char *CodeCompletionString::getTypedText() const {
00248   for (iterator C = begin(), CEnd = end(); C != CEnd; ++C)
00249     if (C->Kind == CK_TypedText)
00250       return C->Text;
00251   
00252   return 0;
00253 }
00254 
00255 const char *CodeCompletionAllocator::CopyString(StringRef String) {
00256   char *Mem = (char *)Allocate(String.size() + 1, 1);
00257   std::copy(String.begin(), String.end(), Mem);
00258   Mem[String.size()] = 0;
00259   return Mem;
00260 }
00261 
00262 const char *CodeCompletionAllocator::CopyString(Twine String) {
00263   // FIXME: It would be more efficient to teach Twine to tell us its size and
00264   // then add a routine there to fill in an allocated char* with the contents
00265   // of the string.
00266   SmallString<128> Data;
00267   return CopyString(String.toStringRef(Data));
00268 }
00269 
00270 StringRef CodeCompletionTUInfo::getParentName(DeclContext *DC) {
00271   NamedDecl *ND = dyn_cast<NamedDecl>(DC);
00272   if (!ND)
00273     return StringRef();
00274   
00275   // Check whether we've already cached the parent name.
00276   StringRef &CachedParentName = ParentNames[DC];
00277   if (!CachedParentName.empty())
00278     return CachedParentName;
00279 
00280   // If we already processed this DeclContext and assigned empty to it, the
00281   // data pointer will be non-null.
00282   if (CachedParentName.data() != 0)
00283     return StringRef();
00284 
00285   // Find the interesting names.
00286   llvm::SmallVector<DeclContext *, 2> Contexts;
00287   while (DC && !DC->isFunctionOrMethod()) {
00288     if (NamedDecl *ND = dyn_cast<NamedDecl>(DC)) {
00289       if (ND->getIdentifier())
00290         Contexts.push_back(DC);
00291     }
00292     
00293     DC = DC->getParent();
00294   }
00295 
00296   {
00297     llvm::SmallString<128> S;
00298     llvm::raw_svector_ostream OS(S);
00299     bool First = true;
00300     for (unsigned I = Contexts.size(); I != 0; --I) {
00301       if (First)
00302         First = false;
00303       else {
00304         OS << "::";
00305       }
00306       
00307       DeclContext *CurDC = Contexts[I-1];
00308       if (ObjCCategoryImplDecl *CatImpl = dyn_cast<ObjCCategoryImplDecl>(CurDC))
00309         CurDC = CatImpl->getCategoryDecl();
00310       
00311       if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(CurDC)) {
00312         ObjCInterfaceDecl *Interface = Cat->getClassInterface();
00313         if (!Interface) {
00314           // Assign an empty StringRef but with non-null data to distinguish
00315           // between empty because we didn't process the DeclContext yet.
00316           CachedParentName = StringRef((const char *)~0U, 0);
00317           return StringRef();
00318         }
00319         
00320         OS << Interface->getName() << '(' << Cat->getName() << ')';
00321       } else {
00322         OS << cast<NamedDecl>(CurDC)->getName();
00323       }
00324     }
00325     
00326     CachedParentName = AllocatorRef->CopyString(OS.str());
00327   }
00328 
00329   return CachedParentName;
00330 }
00331 
00332 CodeCompletionString *CodeCompletionBuilder::TakeString() {
00333   void *Mem = getAllocator().Allocate(
00334                   sizeof(CodeCompletionString) + sizeof(Chunk) * Chunks.size()
00335                                     + sizeof(const char *) * Annotations.size(),
00336                                  llvm::alignOf<CodeCompletionString>());
00337   CodeCompletionString *Result 
00338     = new (Mem) CodeCompletionString(Chunks.data(), Chunks.size(),
00339                                      Priority, Availability,
00340                                      Annotations.data(), Annotations.size(),
00341                                      ParentKind, ParentName);
00342   Chunks.clear();
00343   return Result;
00344 }
00345 
00346 void CodeCompletionBuilder::AddTypedTextChunk(const char *Text) {
00347   Chunks.push_back(Chunk(CodeCompletionString::CK_TypedText, Text));
00348 }
00349 
00350 void CodeCompletionBuilder::AddTextChunk(const char *Text) {
00351   Chunks.push_back(Chunk::CreateText(Text));
00352 }
00353 
00354 void CodeCompletionBuilder::AddOptionalChunk(CodeCompletionString *Optional) {
00355   Chunks.push_back(Chunk::CreateOptional(Optional));
00356 }
00357 
00358 void CodeCompletionBuilder::AddPlaceholderChunk(const char *Placeholder) {
00359   Chunks.push_back(Chunk::CreatePlaceholder(Placeholder));
00360 }
00361 
00362 void CodeCompletionBuilder::AddInformativeChunk(const char *Text) {
00363   Chunks.push_back(Chunk::CreateInformative(Text));
00364 }
00365 
00366 void CodeCompletionBuilder::AddResultTypeChunk(const char *ResultType) {
00367   Chunks.push_back(Chunk::CreateResultType(ResultType));
00368 }
00369 
00370 void
00371 CodeCompletionBuilder::AddCurrentParameterChunk(const char *CurrentParameter) {
00372   Chunks.push_back(Chunk::CreateCurrentParameter(CurrentParameter));
00373 }
00374 
00375 void CodeCompletionBuilder::AddChunk(CodeCompletionString::ChunkKind CK,
00376                                      const char *Text) {
00377   Chunks.push_back(Chunk(CK, Text));
00378 }
00379 
00380 void CodeCompletionBuilder::addParentContext(DeclContext *DC) {
00381   if (DC->isTranslationUnit()) {
00382     ParentKind = CXCursor_TranslationUnit;
00383     return;
00384   }
00385   
00386   if (DC->isFunctionOrMethod())
00387     return;
00388   
00389   NamedDecl *ND = dyn_cast<NamedDecl>(DC);
00390   if (!ND)
00391     return;
00392   
00393   ParentKind = getCursorKindForDecl(ND);
00394   ParentName = getCodeCompletionTUInfo().getParentName(DC);
00395 }
00396 
00397 unsigned CodeCompletionResult::getPriorityFromDecl(NamedDecl *ND) {
00398   if (!ND)
00399     return CCP_Unlikely;
00400   
00401   // Context-based decisions.
00402   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
00403   if (DC->isFunctionOrMethod() || isa<BlockDecl>(DC)) {
00404     // _cmd is relatively rare
00405     if (ImplicitParamDecl *ImplicitParam = dyn_cast<ImplicitParamDecl>(ND))
00406       if (ImplicitParam->getIdentifier() &&
00407           ImplicitParam->getIdentifier()->isStr("_cmd"))
00408         return CCP_ObjC_cmd;
00409     
00410     return CCP_LocalDeclaration;
00411   }
00412   if (DC->isRecord() || isa<ObjCContainerDecl>(DC))
00413     return CCP_MemberDeclaration;
00414   
00415   // Content-based decisions.
00416   if (isa<EnumConstantDecl>(ND))
00417     return CCP_Constant;
00418   if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
00419     return CCP_Type;
00420   
00421   return CCP_Declaration;
00422 }
00423 
00424 //===----------------------------------------------------------------------===//
00425 // Code completion overload candidate implementation
00426 //===----------------------------------------------------------------------===//
00427 FunctionDecl *
00428 CodeCompleteConsumer::OverloadCandidate::getFunction() const {
00429   if (getKind() == CK_Function)
00430     return Function;
00431   else if (getKind() == CK_FunctionTemplate)
00432     return FunctionTemplate->getTemplatedDecl();
00433   else
00434     return 0;
00435 }
00436 
00437 const FunctionType *
00438 CodeCompleteConsumer::OverloadCandidate::getFunctionType() const {
00439   switch (Kind) {
00440   case CK_Function:
00441     return Function->getType()->getAs<FunctionType>();
00442       
00443   case CK_FunctionTemplate:
00444     return FunctionTemplate->getTemplatedDecl()->getType()
00445              ->getAs<FunctionType>();
00446       
00447   case CK_FunctionType:
00448     return Type;
00449   }
00450 
00451   llvm_unreachable("Invalid CandidateKind!");
00452 }
00453 
00454 //===----------------------------------------------------------------------===//
00455 // Code completion consumer implementation
00456 //===----------------------------------------------------------------------===//
00457 
00458 CodeCompleteConsumer::~CodeCompleteConsumer() { }
00459 
00460 void 
00461 PrintingCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &SemaRef,
00462                                                  CodeCompletionContext Context,
00463                                                  CodeCompletionResult *Results,
00464                                                          unsigned NumResults) {
00465   std::stable_sort(Results, Results + NumResults);
00466   
00467   // Print the results.
00468   for (unsigned I = 0; I != NumResults; ++I) {
00469     OS << "COMPLETION: ";
00470     switch (Results[I].Kind) {
00471     case CodeCompletionResult::RK_Declaration:
00472       OS << *Results[I].Declaration;
00473       if (Results[I].Hidden)
00474         OS << " (Hidden)";
00475       if (CodeCompletionString *CCS 
00476             = Results[I].CreateCodeCompletionString(SemaRef, getAllocator(),
00477                                                     CCTUInfo)) {
00478         OS << " : " << CCS->getAsString();
00479       }
00480         
00481       OS << '\n';
00482       break;
00483       
00484     case CodeCompletionResult::RK_Keyword:
00485       OS << Results[I].Keyword << '\n';
00486       break;
00487         
00488     case CodeCompletionResult::RK_Macro: {
00489       OS << Results[I].Macro->getName();
00490       if (CodeCompletionString *CCS 
00491             = Results[I].CreateCodeCompletionString(SemaRef, getAllocator(),
00492                                                     CCTUInfo)) {
00493         OS << " : " << CCS->getAsString();
00494       }
00495       OS << '\n';
00496       break;
00497     }
00498         
00499     case CodeCompletionResult::RK_Pattern: {
00500       OS << "Pattern : " 
00501          << Results[I].Pattern->getAsString() << '\n';
00502       break;
00503     }
00504     }
00505   }
00506 }
00507 
00508 void 
00509 PrintingCodeCompleteConsumer::ProcessOverloadCandidates(Sema &SemaRef,
00510                                                         unsigned CurrentArg,
00511                                               OverloadCandidate *Candidates,
00512                                                      unsigned NumCandidates) {
00513   for (unsigned I = 0; I != NumCandidates; ++I) {
00514     if (CodeCompletionString *CCS
00515           = Candidates[I].CreateSignatureString(CurrentArg, SemaRef,
00516                                                 getAllocator(), CCTUInfo)) {
00517       OS << "OVERLOAD: " << CCS->getAsString() << "\n";
00518     }
00519   }
00520 }
00521 
00522 /// \brief Retrieve the effective availability of the given declaration.
00523 static AvailabilityResult getDeclAvailability(Decl *D) {
00524   AvailabilityResult AR = D->getAvailability();
00525   if (isa<EnumConstantDecl>(D))
00526     AR = std::max(AR, cast<Decl>(D->getDeclContext())->getAvailability());
00527   return AR;
00528 }
00529 
00530 void CodeCompletionResult::computeCursorKindAndAvailability(bool Accessible) {
00531   switch (Kind) {
00532   case RK_Pattern:
00533     if (!Declaration) {
00534       // Do nothing: Patterns can come with cursor kinds!
00535       break;
00536     }
00537     // Fall through
00538       
00539   case RK_Declaration: {
00540     // Set the availability based on attributes.
00541     switch (getDeclAvailability(Declaration)) {
00542     case AR_Available:
00543     case AR_NotYetIntroduced:
00544       Availability = CXAvailability_Available;      
00545       break;
00546       
00547     case AR_Deprecated:
00548       Availability = CXAvailability_Deprecated;
00549       break;
00550       
00551     case AR_Unavailable:
00552       Availability = CXAvailability_NotAvailable;
00553       break;
00554     }
00555 
00556     if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Declaration))
00557       if (Function->isDeleted())
00558         Availability = CXAvailability_NotAvailable;
00559       
00560     CursorKind = getCursorKindForDecl(Declaration);
00561     if (CursorKind == CXCursor_UnexposedDecl) {
00562       // FIXME: Forward declarations of Objective-C classes and protocols 
00563       // are not directly exposed, but we want code completion to treat them 
00564       // like a definition.
00565       if (isa<ObjCInterfaceDecl>(Declaration))
00566         CursorKind = CXCursor_ObjCInterfaceDecl;
00567       else if (isa<ObjCProtocolDecl>(Declaration))
00568         CursorKind = CXCursor_ObjCProtocolDecl;
00569       else
00570         CursorKind = CXCursor_NotImplemented;
00571     }
00572     break;
00573   }
00574 
00575   case RK_Macro:
00576     Availability = CXAvailability_Available;      
00577     CursorKind = CXCursor_MacroDefinition;
00578     break;
00579       
00580   case RK_Keyword:
00581     Availability = CXAvailability_Available;      
00582     CursorKind = CXCursor_NotImplemented;
00583     break;      
00584   }
00585 
00586   if (!Accessible)
00587     Availability = CXAvailability_NotAccessible;
00588 }
00589 
00590 /// \brief Retrieve the name that should be used to order a result.
00591 ///
00592 /// If the name needs to be constructed as a string, that string will be
00593 /// saved into Saved and the returned StringRef will refer to it.
00594 static StringRef getOrderedName(const CodeCompletionResult &R,
00595                                     std::string &Saved) {
00596   switch (R.Kind) {
00597     case CodeCompletionResult::RK_Keyword:
00598       return R.Keyword;
00599       
00600     case CodeCompletionResult::RK_Pattern:
00601       return R.Pattern->getTypedText();
00602       
00603     case CodeCompletionResult::RK_Macro:
00604       return R.Macro->getName();
00605       
00606     case CodeCompletionResult::RK_Declaration:
00607       // Handle declarations below.
00608       break;
00609   }
00610   
00611   DeclarationName Name = R.Declaration->getDeclName();
00612   
00613   // If the name is a simple identifier (by far the common case), or a
00614   // zero-argument selector, just return a reference to that identifier.
00615   if (IdentifierInfo *Id = Name.getAsIdentifierInfo())
00616     return Id->getName();
00617   if (Name.isObjCZeroArgSelector())
00618     if (IdentifierInfo *Id
00619         = Name.getObjCSelector().getIdentifierInfoForSlot(0))
00620       return Id->getName();
00621   
00622   Saved = Name.getAsString();
00623   return Saved;
00624 }
00625     
00626 bool clang::operator<(const CodeCompletionResult &X, 
00627                       const CodeCompletionResult &Y) {
00628   std::string XSaved, YSaved;
00629   StringRef XStr = getOrderedName(X, XSaved);
00630   StringRef YStr = getOrderedName(Y, YSaved);
00631   int cmp = XStr.compare_lower(YStr);
00632   if (cmp)
00633     return cmp < 0;
00634   
00635   // If case-insensitive comparison fails, try case-sensitive comparison.
00636   cmp = XStr.compare(YStr);
00637   if (cmp)
00638     return cmp < 0;
00639   
00640   return false;
00641 }