CodeCompleteConsumer.cpp revision 52779fb71795534d0447f6f4d4a6f6a7b09c4639
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/STLExtras.h" 22#include "llvm/Support/raw_ostream.h" 23#include <algorithm> 24#include <cstring> 25#include <functional> 26 27using namespace clang; 28using llvm::StringRef; 29 30//===----------------------------------------------------------------------===// 31// Code completion context implementation 32//===----------------------------------------------------------------------===// 33 34bool CodeCompletionContext::wantConstructorResults() const { 35 switch (Kind) { 36 case CCC_Recovery: 37 case CCC_Statement: 38 case CCC_Expression: 39 case CCC_ObjCMessageReceiver: 40 case CCC_ParenthesizedExpression: 41 return true; 42 43 case CCC_TopLevel: 44 case CCC_ObjCInterface: 45 case CCC_ObjCImplementation: 46 case CCC_ObjCIvarList: 47 case CCC_ClassStructUnion: 48 case CCC_MemberAccess: 49 case CCC_EnumTag: 50 case CCC_UnionTag: 51 case CCC_ClassOrStructTag: 52 case CCC_ObjCProtocolName: 53 case CCC_Namespace: 54 case CCC_Type: 55 case CCC_Name: 56 case CCC_PotentiallyQualifiedName: 57 case CCC_MacroName: 58 case CCC_MacroNameUse: 59 case CCC_PreprocessorExpression: 60 case CCC_PreprocessorDirective: 61 case CCC_NaturalLanguage: 62 case CCC_SelectorName: 63 case CCC_TypeQualifiers: 64 case CCC_Other: 65 return false; 66 } 67 68 return false; 69} 70 71//===----------------------------------------------------------------------===// 72// Code completion string implementation 73//===----------------------------------------------------------------------===// 74CodeCompletionString::Chunk::Chunk(ChunkKind Kind, llvm::StringRef Text) 75 : Kind(Kind), Text("") 76{ 77 switch (Kind) { 78 case CK_TypedText: 79 case CK_Text: 80 case CK_Placeholder: 81 case CK_Informative: 82 case CK_ResultType: 83 case CK_CurrentParameter: { 84 char *New = new char [Text.size() + 1]; 85 std::memcpy(New, Text.data(), Text.size()); 86 New[Text.size()] = '\0'; 87 this->Text = New; 88 break; 89 } 90 91 case CK_Optional: 92 llvm_unreachable("Optional strings cannot be created from text"); 93 break; 94 95 case CK_LeftParen: 96 this->Text = "("; 97 break; 98 99 case CK_RightParen: 100 this->Text = ")"; 101 break; 102 103 case CK_LeftBracket: 104 this->Text = "["; 105 break; 106 107 case CK_RightBracket: 108 this->Text = "]"; 109 break; 110 111 case CK_LeftBrace: 112 this->Text = "{"; 113 break; 114 115 case CK_RightBrace: 116 this->Text = "}"; 117 break; 118 119 case CK_LeftAngle: 120 this->Text = "<"; 121 break; 122 123 case CK_RightAngle: 124 this->Text = ">"; 125 break; 126 127 case CK_Comma: 128 this->Text = ", "; 129 break; 130 131 case CK_Colon: 132 this->Text = ":"; 133 break; 134 135 case CK_SemiColon: 136 this->Text = ";"; 137 break; 138 139 case CK_Equal: 140 this->Text = " = "; 141 break; 142 143 case CK_HorizontalSpace: 144 this->Text = " "; 145 break; 146 147 case CK_VerticalSpace: 148 this->Text = "\n"; 149 break; 150 } 151} 152 153CodeCompletionString::Chunk 154CodeCompletionString::Chunk::CreateText(StringRef Text) { 155 return Chunk(CK_Text, Text); 156} 157 158CodeCompletionString::Chunk 159CodeCompletionString::Chunk::CreateOptional( 160 std::auto_ptr<CodeCompletionString> Optional) { 161 Chunk Result; 162 Result.Kind = CK_Optional; 163 Result.Optional = Optional.release(); 164 return Result; 165} 166 167CodeCompletionString::Chunk 168CodeCompletionString::Chunk::CreatePlaceholder(StringRef Placeholder) { 169 return Chunk(CK_Placeholder, Placeholder); 170} 171 172CodeCompletionString::Chunk 173CodeCompletionString::Chunk::CreateInformative(StringRef Informative) { 174 return Chunk(CK_Informative, Informative); 175} 176 177CodeCompletionString::Chunk 178CodeCompletionString::Chunk::CreateResultType(StringRef ResultType) { 179 return Chunk(CK_ResultType, ResultType); 180} 181 182CodeCompletionString::Chunk 183CodeCompletionString::Chunk::CreateCurrentParameter( 184 StringRef CurrentParameter) { 185 return Chunk(CK_CurrentParameter, CurrentParameter); 186} 187 188CodeCompletionString::Chunk CodeCompletionString::Chunk::Clone() const { 189 switch (Kind) { 190 case CK_TypedText: 191 case CK_Text: 192 case CK_Placeholder: 193 case CK_Informative: 194 case CK_ResultType: 195 case CK_CurrentParameter: 196 case CK_LeftParen: 197 case CK_RightParen: 198 case CK_LeftBracket: 199 case CK_RightBracket: 200 case CK_LeftBrace: 201 case CK_RightBrace: 202 case CK_LeftAngle: 203 case CK_RightAngle: 204 case CK_Comma: 205 case CK_Colon: 206 case CK_SemiColon: 207 case CK_Equal: 208 case CK_HorizontalSpace: 209 case CK_VerticalSpace: 210 return Chunk(Kind, Text); 211 212 case CK_Optional: { 213 std::auto_ptr<CodeCompletionString> Opt(Optional->Clone()); 214 return CreateOptional(Opt); 215 } 216 } 217 218 // Silence GCC warning. 219 return Chunk(); 220} 221 222void 223CodeCompletionString::Chunk::Destroy() { 224 switch (Kind) { 225 case CK_Optional: 226 delete Optional; 227 break; 228 229 case CK_TypedText: 230 case CK_Text: 231 case CK_Placeholder: 232 case CK_Informative: 233 case CK_ResultType: 234 case CK_CurrentParameter: 235 delete [] Text; 236 break; 237 238 case CK_LeftParen: 239 case CK_RightParen: 240 case CK_LeftBracket: 241 case CK_RightBracket: 242 case CK_LeftBrace: 243 case CK_RightBrace: 244 case CK_LeftAngle: 245 case CK_RightAngle: 246 case CK_Comma: 247 case CK_Colon: 248 case CK_SemiColon: 249 case CK_Equal: 250 case CK_HorizontalSpace: 251 case CK_VerticalSpace: 252 break; 253 } 254} 255 256void CodeCompletionString::clear() { 257 std::for_each(Chunks.begin(), Chunks.end(), 258 std::mem_fun_ref(&Chunk::Destroy)); 259 Chunks.clear(); 260} 261 262std::string CodeCompletionString::getAsString() const { 263 std::string Result; 264 llvm::raw_string_ostream OS(Result); 265 266 for (iterator C = begin(), CEnd = end(); C != CEnd; ++C) { 267 switch (C->Kind) { 268 case CK_Optional: OS << "{#" << C->Optional->getAsString() << "#}"; break; 269 case CK_Placeholder: OS << "<#" << C->Text << "#>"; break; 270 271 case CK_Informative: 272 case CK_ResultType: 273 OS << "[#" << C->Text << "#]"; 274 break; 275 276 case CK_CurrentParameter: OS << "<#" << C->Text << "#>"; break; 277 default: OS << C->Text; break; 278 } 279 } 280 return OS.str(); 281} 282 283const char *CodeCompletionString::getTypedText() const { 284 for (iterator C = begin(), CEnd = end(); C != CEnd; ++C) 285 if (C->Kind == CK_TypedText) 286 return C->Text; 287 288 return 0; 289} 290 291CodeCompletionString * 292CodeCompletionString::Clone(CodeCompletionString *Result) const { 293 if (!Result) 294 Result = new CodeCompletionString; 295 for (iterator C = begin(), CEnd = end(); C != CEnd; ++C) 296 Result->AddChunk(C->Clone()); 297 return Result; 298} 299 300static void WriteUnsigned(llvm::raw_ostream &OS, unsigned Value) { 301 OS.write((const char *)&Value, sizeof(unsigned)); 302} 303 304static bool ReadUnsigned(const char *&Memory, const char *MemoryEnd, 305 unsigned &Value) { 306 if (Memory + sizeof(unsigned) > MemoryEnd) 307 return true; 308 309 memmove(&Value, Memory, sizeof(unsigned)); 310 Memory += sizeof(unsigned); 311 return false; 312} 313 314void CodeCompletionString::Serialize(llvm::raw_ostream &OS) const { 315 // Write the number of chunks. 316 WriteUnsigned(OS, size()); 317 318 for (iterator C = begin(), CEnd = end(); C != CEnd; ++C) { 319 WriteUnsigned(OS, C->Kind); 320 321 switch (C->Kind) { 322 case CK_TypedText: 323 case CK_Text: 324 case CK_Placeholder: 325 case CK_Informative: 326 case CK_ResultType: 327 case CK_CurrentParameter: { 328 const char *Text = C->Text; 329 unsigned StrLen = strlen(Text); 330 WriteUnsigned(OS, StrLen); 331 OS.write(Text, StrLen); 332 break; 333 } 334 335 case CK_Optional: 336 C->Optional->Serialize(OS); 337 break; 338 339 case CK_LeftParen: 340 case CK_RightParen: 341 case CK_LeftBracket: 342 case CK_RightBracket: 343 case CK_LeftBrace: 344 case CK_RightBrace: 345 case CK_LeftAngle: 346 case CK_RightAngle: 347 case CK_Comma: 348 case CK_Colon: 349 case CK_SemiColon: 350 case CK_Equal: 351 case CK_HorizontalSpace: 352 case CK_VerticalSpace: 353 break; 354 } 355 } 356} 357 358bool CodeCompletionString::Deserialize(const char *&Str, const char *StrEnd) { 359 if (Str == StrEnd || *Str == 0) 360 return false; 361 362 unsigned NumBlocks; 363 if (ReadUnsigned(Str, StrEnd, NumBlocks)) 364 return false; 365 366 for (unsigned I = 0; I != NumBlocks; ++I) { 367 if (Str + 1 >= StrEnd) 368 break; 369 370 // Parse the next kind. 371 unsigned KindValue; 372 if (ReadUnsigned(Str, StrEnd, KindValue)) 373 return false; 374 375 switch (ChunkKind Kind = (ChunkKind)KindValue) { 376 case CK_TypedText: 377 case CK_Text: 378 case CK_Placeholder: 379 case CK_Informative: 380 case CK_ResultType: 381 case CK_CurrentParameter: { 382 unsigned StrLen; 383 if (ReadUnsigned(Str, StrEnd, StrLen) || (Str + StrLen > StrEnd)) 384 return false; 385 386 AddChunk(Chunk(Kind, StringRef(Str, StrLen))); 387 Str += StrLen; 388 break; 389 } 390 391 case CK_Optional: { 392 std::auto_ptr<CodeCompletionString> Optional(new CodeCompletionString()); 393 if (Optional->Deserialize(Str, StrEnd)) 394 AddOptionalChunk(Optional); 395 break; 396 } 397 398 case CK_LeftParen: 399 case CK_RightParen: 400 case CK_LeftBracket: 401 case CK_RightBracket: 402 case CK_LeftBrace: 403 case CK_RightBrace: 404 case CK_LeftAngle: 405 case CK_RightAngle: 406 case CK_Comma: 407 case CK_Colon: 408 case CK_SemiColon: 409 case CK_Equal: 410 case CK_HorizontalSpace: 411 case CK_VerticalSpace: 412 AddChunk(Chunk(Kind)); 413 break; 414 } 415 }; 416 417 return true; 418} 419 420void CodeCompletionResult::Destroy() { 421 if (Kind == RK_Pattern) { 422 delete Pattern; 423 Pattern = 0; 424 } 425} 426 427unsigned CodeCompletionResult::getPriorityFromDecl(NamedDecl *ND) { 428 if (!ND) 429 return CCP_Unlikely; 430 431 // Context-based decisions. 432 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 433 if (DC->isFunctionOrMethod() || isa<BlockDecl>(DC)) { 434 // _cmd is relatively rare 435 if (ImplicitParamDecl *ImplicitParam = dyn_cast<ImplicitParamDecl>(ND)) 436 if (ImplicitParam->getIdentifier() && 437 ImplicitParam->getIdentifier()->isStr("_cmd")) 438 return CCP_ObjC_cmd; 439 440 return CCP_LocalDeclaration; 441 } 442 if (DC->isRecord() || isa<ObjCContainerDecl>(DC)) 443 return CCP_MemberDeclaration; 444 445 // Content-based decisions. 446 if (isa<EnumConstantDecl>(ND)) 447 return CCP_Constant; 448 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) 449 return CCP_Type; 450 451 return CCP_Declaration; 452} 453 454//===----------------------------------------------------------------------===// 455// Code completion overload candidate implementation 456//===----------------------------------------------------------------------===// 457FunctionDecl * 458CodeCompleteConsumer::OverloadCandidate::getFunction() const { 459 if (getKind() == CK_Function) 460 return Function; 461 else if (getKind() == CK_FunctionTemplate) 462 return FunctionTemplate->getTemplatedDecl(); 463 else 464 return 0; 465} 466 467const FunctionType * 468CodeCompleteConsumer::OverloadCandidate::getFunctionType() const { 469 switch (Kind) { 470 case CK_Function: 471 return Function->getType()->getAs<FunctionType>(); 472 473 case CK_FunctionTemplate: 474 return FunctionTemplate->getTemplatedDecl()->getType() 475 ->getAs<FunctionType>(); 476 477 case CK_FunctionType: 478 return Type; 479 } 480 481 return 0; 482} 483 484//===----------------------------------------------------------------------===// 485// Code completion consumer implementation 486//===----------------------------------------------------------------------===// 487 488CodeCompleteConsumer::~CodeCompleteConsumer() { } 489 490void 491PrintingCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &SemaRef, 492 CodeCompletionContext Context, 493 CodeCompletionResult *Results, 494 unsigned NumResults) { 495 std::stable_sort(Results, Results + NumResults); 496 497 // Print the results. 498 for (unsigned I = 0; I != NumResults; ++I) { 499 OS << "COMPLETION: "; 500 switch (Results[I].Kind) { 501 case CodeCompletionResult::RK_Declaration: 502 OS << Results[I].Declaration; 503 if (Results[I].Hidden) 504 OS << " (Hidden)"; 505 if (CodeCompletionString *CCS 506 = Results[I].CreateCodeCompletionString(SemaRef)) { 507 OS << " : " << CCS->getAsString(); 508 delete CCS; 509 } 510 511 OS << '\n'; 512 break; 513 514 case CodeCompletionResult::RK_Keyword: 515 OS << Results[I].Keyword << '\n'; 516 break; 517 518 case CodeCompletionResult::RK_Macro: { 519 OS << Results[I].Macro->getName(); 520 if (CodeCompletionString *CCS 521 = Results[I].CreateCodeCompletionString(SemaRef)) { 522 OS << " : " << CCS->getAsString(); 523 delete CCS; 524 } 525 OS << '\n'; 526 break; 527 } 528 529 case CodeCompletionResult::RK_Pattern: { 530 OS << "Pattern : " 531 << Results[I].Pattern->getAsString() << '\n'; 532 break; 533 } 534 } 535 } 536} 537 538void 539PrintingCodeCompleteConsumer::ProcessOverloadCandidates(Sema &SemaRef, 540 unsigned CurrentArg, 541 OverloadCandidate *Candidates, 542 unsigned NumCandidates) { 543 for (unsigned I = 0; I != NumCandidates; ++I) { 544 if (CodeCompletionString *CCS 545 = Candidates[I].CreateSignatureString(CurrentArg, SemaRef)) { 546 OS << "OVERLOAD: " << CCS->getAsString() << "\n"; 547 delete CCS; 548 } 549 } 550} 551 552void CodeCompletionResult::computeCursorKindAndAvailability() { 553 switch (Kind) { 554 case RK_Declaration: 555 // Set the availability based on attributes. 556 Availability = CXAvailability_Available; 557 if (Declaration->getAttr<UnavailableAttr>()) 558 Availability = CXAvailability_NotAvailable; 559 else if (Declaration->getAttr<DeprecatedAttr>()) 560 Availability = CXAvailability_Deprecated; 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 CursorKind = CXCursor_NotImplemented; 569 break; 570 571 case RK_Macro: 572 Availability = CXAvailability_Available; 573 CursorKind = CXCursor_MacroDefinition; 574 break; 575 576 case RK_Keyword: 577 Availability = CXAvailability_Available; 578 CursorKind = CXCursor_NotImplemented; 579 break; 580 581 case RK_Pattern: 582 // Do nothing: Patterns can come with cursor kinds! 583 break; 584 } 585} 586 587/// \brief Retrieve the name that should be used to order a result. 588/// 589/// If the name needs to be constructed as a string, that string will be 590/// saved into Saved and the returned StringRef will refer to it. 591static llvm::StringRef getOrderedName(const CodeCompletionResult &R, 592 std::string &Saved) { 593 switch (R.Kind) { 594 case CodeCompletionResult::RK_Keyword: 595 return R.Keyword; 596 597 case CodeCompletionResult::RK_Pattern: 598 return R.Pattern->getTypedText(); 599 600 case CodeCompletionResult::RK_Macro: 601 return R.Macro->getName(); 602 603 case CodeCompletionResult::RK_Declaration: 604 // Handle declarations below. 605 break; 606 } 607 608 DeclarationName Name = R.Declaration->getDeclName(); 609 610 // If the name is a simple identifier (by far the common case), or a 611 // zero-argument selector, just return a reference to that identifier. 612 if (IdentifierInfo *Id = Name.getAsIdentifierInfo()) 613 return Id->getName(); 614 if (Name.isObjCZeroArgSelector()) 615 if (IdentifierInfo *Id 616 = Name.getObjCSelector().getIdentifierInfoForSlot(0)) 617 return Id->getName(); 618 619 Saved = Name.getAsString(); 620 return Saved; 621} 622 623bool clang::operator<(const CodeCompletionResult &X, 624 const CodeCompletionResult &Y) { 625 std::string XSaved, YSaved; 626 llvm::StringRef XStr = getOrderedName(X, XSaved); 627 llvm::StringRef YStr = getOrderedName(Y, YSaved); 628 int cmp = XStr.compare_lower(YStr); 629 if (cmp) 630 return cmp < 0; 631 632 // If case-insensitive comparison fails, try case-sensitive comparison. 633 cmp = XStr.compare(YStr); 634 if (cmp) 635 return cmp < 0; 636 637 return false; 638} 639 640void 641CIndexCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &SemaRef, 642 CodeCompletionContext Context, 643 CodeCompletionResult *Results, 644 unsigned NumResults) { 645 // Print the results. 646 for (unsigned I = 0; I != NumResults; ++I) { 647 WriteUnsigned(OS, Results[I].CursorKind); 648 WriteUnsigned(OS, Results[I].Priority); 649 WriteUnsigned(OS, Results[I].Availability); 650 CodeCompletionString *CCS = Results[I].CreateCodeCompletionString(SemaRef); 651 assert(CCS && "No code-completion string?"); 652 CCS->Serialize(OS); 653 delete CCS; 654 } 655} 656 657void 658CIndexCodeCompleteConsumer::ProcessOverloadCandidates(Sema &SemaRef, 659 unsigned CurrentArg, 660 OverloadCandidate *Candidates, 661 unsigned NumCandidates) { 662 for (unsigned I = 0; I != NumCandidates; ++I) { 663 WriteUnsigned(OS, CXCursor_NotImplemented); 664 WriteUnsigned(OS, /*Priority=*/I); 665 WriteUnsigned(OS, /*Availability=*/CXAvailability_Available); 666 CodeCompletionString *CCS 667 = Candidates[I].CreateSignatureString(CurrentArg, SemaRef); 668 assert(CCS && "No code-completion string?"); 669 CCS->Serialize(OS); 670 delete CCS; 671 } 672} 673