CIndexCodeCompletion.cpp revision d99ef536b241071b6f4c01db6525dc03242ac30b
1//===- CIndexCodeCompletion.cpp - Code Completion API hooks ---------------===// 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 Clang-C Source Indexing library hooks for 11// code completion. 12// 13//===----------------------------------------------------------------------===// 14 15#include "CIndexer.h" 16#include "CXTranslationUnit.h" 17#include "CXString.h" 18#include "CXCursor.h" 19#include "CXString.h" 20#include "CIndexDiagnostic.h" 21#include "clang/AST/Type.h" 22#include "clang/AST/Decl.h" 23#include "clang/AST/DeclObjC.h" 24#include "clang/Basic/SourceManager.h" 25#include "clang/Basic/FileManager.h" 26#include "clang/Frontend/ASTUnit.h" 27#include "clang/Frontend/CompilerInstance.h" 28#include "clang/Frontend/FrontendDiagnostic.h" 29#include "clang/Sema/CodeCompleteConsumer.h" 30#include "llvm/ADT/SmallString.h" 31#include "llvm/ADT/StringExtras.h" 32#include "llvm/Support/Atomic.h" 33#include "llvm/Support/CrashRecoveryContext.h" 34#include "llvm/Support/MemoryBuffer.h" 35#include "llvm/Support/Timer.h" 36#include "llvm/Support/raw_ostream.h" 37#include "llvm/Support/Program.h" 38#include <cstdlib> 39#include <cstdio> 40 41 42#ifdef UDP_CODE_COMPLETION_LOGGER 43#include "clang/Basic/Version.h" 44#include <arpa/inet.h> 45#include <sys/socket.h> 46#include <sys/types.h> 47#include <unistd.h> 48#endif 49 50using namespace clang; 51using namespace clang::cxstring; 52 53extern "C" { 54 55enum CXCompletionChunkKind 56clang_getCompletionChunkKind(CXCompletionString completion_string, 57 unsigned chunk_number) { 58 CodeCompletionString *CCStr = (CodeCompletionString *)completion_string; 59 if (!CCStr || chunk_number >= CCStr->size()) 60 return CXCompletionChunk_Text; 61 62 switch ((*CCStr)[chunk_number].Kind) { 63 case CodeCompletionString::CK_TypedText: 64 return CXCompletionChunk_TypedText; 65 case CodeCompletionString::CK_Text: 66 return CXCompletionChunk_Text; 67 case CodeCompletionString::CK_Optional: 68 return CXCompletionChunk_Optional; 69 case CodeCompletionString::CK_Placeholder: 70 return CXCompletionChunk_Placeholder; 71 case CodeCompletionString::CK_Informative: 72 return CXCompletionChunk_Informative; 73 case CodeCompletionString::CK_ResultType: 74 return CXCompletionChunk_ResultType; 75 case CodeCompletionString::CK_CurrentParameter: 76 return CXCompletionChunk_CurrentParameter; 77 case CodeCompletionString::CK_LeftParen: 78 return CXCompletionChunk_LeftParen; 79 case CodeCompletionString::CK_RightParen: 80 return CXCompletionChunk_RightParen; 81 case CodeCompletionString::CK_LeftBracket: 82 return CXCompletionChunk_LeftBracket; 83 case CodeCompletionString::CK_RightBracket: 84 return CXCompletionChunk_RightBracket; 85 case CodeCompletionString::CK_LeftBrace: 86 return CXCompletionChunk_LeftBrace; 87 case CodeCompletionString::CK_RightBrace: 88 return CXCompletionChunk_RightBrace; 89 case CodeCompletionString::CK_LeftAngle: 90 return CXCompletionChunk_LeftAngle; 91 case CodeCompletionString::CK_RightAngle: 92 return CXCompletionChunk_RightAngle; 93 case CodeCompletionString::CK_Comma: 94 return CXCompletionChunk_Comma; 95 case CodeCompletionString::CK_Colon: 96 return CXCompletionChunk_Colon; 97 case CodeCompletionString::CK_SemiColon: 98 return CXCompletionChunk_SemiColon; 99 case CodeCompletionString::CK_Equal: 100 return CXCompletionChunk_Equal; 101 case CodeCompletionString::CK_HorizontalSpace: 102 return CXCompletionChunk_HorizontalSpace; 103 case CodeCompletionString::CK_VerticalSpace: 104 return CXCompletionChunk_VerticalSpace; 105 } 106 107 llvm_unreachable("Invalid CompletionKind!"); 108} 109 110CXString clang_getCompletionChunkText(CXCompletionString completion_string, 111 unsigned chunk_number) { 112 CodeCompletionString *CCStr = (CodeCompletionString *)completion_string; 113 if (!CCStr || chunk_number >= CCStr->size()) 114 return createCXString((const char*)0); 115 116 switch ((*CCStr)[chunk_number].Kind) { 117 case CodeCompletionString::CK_TypedText: 118 case CodeCompletionString::CK_Text: 119 case CodeCompletionString::CK_Placeholder: 120 case CodeCompletionString::CK_CurrentParameter: 121 case CodeCompletionString::CK_Informative: 122 case CodeCompletionString::CK_LeftParen: 123 case CodeCompletionString::CK_RightParen: 124 case CodeCompletionString::CK_LeftBracket: 125 case CodeCompletionString::CK_RightBracket: 126 case CodeCompletionString::CK_LeftBrace: 127 case CodeCompletionString::CK_RightBrace: 128 case CodeCompletionString::CK_LeftAngle: 129 case CodeCompletionString::CK_RightAngle: 130 case CodeCompletionString::CK_Comma: 131 case CodeCompletionString::CK_ResultType: 132 case CodeCompletionString::CK_Colon: 133 case CodeCompletionString::CK_SemiColon: 134 case CodeCompletionString::CK_Equal: 135 case CodeCompletionString::CK_HorizontalSpace: 136 case CodeCompletionString::CK_VerticalSpace: 137 return createCXString((*CCStr)[chunk_number].Text, false); 138 139 case CodeCompletionString::CK_Optional: 140 // Note: treated as an empty text block. 141 return createCXString(""); 142 } 143 144 llvm_unreachable("Invalid CodeCompletionString Kind!"); 145} 146 147 148CXCompletionString 149clang_getCompletionChunkCompletionString(CXCompletionString completion_string, 150 unsigned chunk_number) { 151 CodeCompletionString *CCStr = (CodeCompletionString *)completion_string; 152 if (!CCStr || chunk_number >= CCStr->size()) 153 return 0; 154 155 switch ((*CCStr)[chunk_number].Kind) { 156 case CodeCompletionString::CK_TypedText: 157 case CodeCompletionString::CK_Text: 158 case CodeCompletionString::CK_Placeholder: 159 case CodeCompletionString::CK_CurrentParameter: 160 case CodeCompletionString::CK_Informative: 161 case CodeCompletionString::CK_LeftParen: 162 case CodeCompletionString::CK_RightParen: 163 case CodeCompletionString::CK_LeftBracket: 164 case CodeCompletionString::CK_RightBracket: 165 case CodeCompletionString::CK_LeftBrace: 166 case CodeCompletionString::CK_RightBrace: 167 case CodeCompletionString::CK_LeftAngle: 168 case CodeCompletionString::CK_RightAngle: 169 case CodeCompletionString::CK_Comma: 170 case CodeCompletionString::CK_ResultType: 171 case CodeCompletionString::CK_Colon: 172 case CodeCompletionString::CK_SemiColon: 173 case CodeCompletionString::CK_Equal: 174 case CodeCompletionString::CK_HorizontalSpace: 175 case CodeCompletionString::CK_VerticalSpace: 176 return 0; 177 178 case CodeCompletionString::CK_Optional: 179 // Note: treated as an empty text block. 180 return (*CCStr)[chunk_number].Optional; 181 } 182 183 llvm_unreachable("Invalid CompletionKind!"); 184} 185 186unsigned clang_getNumCompletionChunks(CXCompletionString completion_string) { 187 CodeCompletionString *CCStr = (CodeCompletionString *)completion_string; 188 return CCStr? CCStr->size() : 0; 189} 190 191unsigned clang_getCompletionPriority(CXCompletionString completion_string) { 192 CodeCompletionString *CCStr = (CodeCompletionString *)completion_string; 193 return CCStr? CCStr->getPriority() : unsigned(CCP_Unlikely); 194} 195 196enum CXAvailabilityKind 197clang_getCompletionAvailability(CXCompletionString completion_string) { 198 CodeCompletionString *CCStr = (CodeCompletionString *)completion_string; 199 return CCStr? static_cast<CXAvailabilityKind>(CCStr->getAvailability()) 200 : CXAvailability_Available; 201} 202 203unsigned clang_getCompletionNumAnnotations(CXCompletionString completion_string) 204{ 205 CodeCompletionString *CCStr = (CodeCompletionString *)completion_string; 206 return CCStr ? CCStr->getAnnotationCount() : 0; 207} 208 209CXString clang_getCompletionAnnotation(CXCompletionString completion_string, 210 unsigned annotation_number) { 211 CodeCompletionString *CCStr = (CodeCompletionString *)completion_string; 212 return CCStr ? createCXString(CCStr->getAnnotation(annotation_number)) 213 : createCXString((const char *) 0); 214} 215 216CXString 217clang_getCompletionParent(CXCompletionString completion_string, 218 CXCursorKind *kind) { 219 if (kind) 220 *kind = CXCursor_NotImplemented; 221 222 CodeCompletionString *CCStr = (CodeCompletionString *)completion_string; 223 if (!CCStr) 224 return createCXString((const char *)0); 225 226 if (kind) 227 *kind = CCStr->getParentContextKind(); 228 return createCXString(CCStr->getParentContextName(), /*DupString=*/false); 229} 230 231CXString 232clang_getCompletionBriefComment(CXCompletionString completion_string) { 233 CodeCompletionString *CCStr = (CodeCompletionString *)completion_string; 234 235 if (!CCStr) 236 return createCXString((const char *) NULL); 237 238 return createCXString(CCStr->getBriefComment(), /*DupString=*/false); 239} 240 241 242/// \brief The CXCodeCompleteResults structure we allocate internally; 243/// the client only sees the initial CXCodeCompleteResults structure. 244struct AllocatedCXCodeCompleteResults : public CXCodeCompleteResults { 245 AllocatedCXCodeCompleteResults(const FileSystemOptions& FileSystemOpts); 246 ~AllocatedCXCodeCompleteResults(); 247 248 /// \brief Diagnostics produced while performing code completion. 249 SmallVector<StoredDiagnostic, 8> Diagnostics; 250 251 /// \brief Diag object 252 IntrusiveRefCntPtr<DiagnosticsEngine> Diag; 253 254 /// \brief Language options used to adjust source locations. 255 LangOptions LangOpts; 256 257 FileSystemOptions FileSystemOpts; 258 259 /// \brief File manager, used for diagnostics. 260 IntrusiveRefCntPtr<FileManager> FileMgr; 261 262 /// \brief Source manager, used for diagnostics. 263 IntrusiveRefCntPtr<SourceManager> SourceMgr; 264 265 /// \brief Temporary files that should be removed once we have finished 266 /// with the code-completion results. 267 std::vector<llvm::sys::Path> TemporaryFiles; 268 269 /// \brief Temporary buffers that will be deleted once we have finished with 270 /// the code-completion results. 271 SmallVector<const llvm::MemoryBuffer *, 1> TemporaryBuffers; 272 273 /// \brief Allocator used to store globally cached code-completion results. 274 IntrusiveRefCntPtr<clang::GlobalCodeCompletionAllocator> 275 CachedCompletionAllocator; 276 277 /// \brief Allocator used to store code completion results. 278 IntrusiveRefCntPtr<clang::GlobalCodeCompletionAllocator> 279 CodeCompletionAllocator; 280 281 /// \brief Context under which completion occurred. 282 enum clang::CodeCompletionContext::Kind ContextKind; 283 284 /// \brief A bitfield representing the acceptable completions for the 285 /// current context. 286 unsigned long long Contexts; 287 288 /// \brief The kind of the container for the current context for completions. 289 enum CXCursorKind ContainerKind; 290 /// \brief The USR of the container for the current context for completions. 291 CXString ContainerUSR; 292 /// \brief a boolean value indicating whether there is complete information 293 /// about the container 294 unsigned ContainerIsIncomplete; 295 296 /// \brief A string containing the Objective-C selector entered thus far for a 297 /// message send. 298 std::string Selector; 299}; 300 301/// \brief Tracks the number of code-completion result objects that are 302/// currently active. 303/// 304/// Used for debugging purposes only. 305static llvm::sys::cas_flag CodeCompletionResultObjects; 306 307AllocatedCXCodeCompleteResults::AllocatedCXCodeCompleteResults( 308 const FileSystemOptions& FileSystemOpts) 309 : CXCodeCompleteResults(), 310 Diag(new DiagnosticsEngine( 311 IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs))), 312 FileSystemOpts(FileSystemOpts), 313 FileMgr(new FileManager(FileSystemOpts)), 314 SourceMgr(new SourceManager(*Diag, *FileMgr)), 315 CodeCompletionAllocator(new clang::GlobalCodeCompletionAllocator), 316 Contexts(CXCompletionContext_Unknown), 317 ContainerKind(CXCursor_InvalidCode), 318 ContainerUSR(createCXString("")), 319 ContainerIsIncomplete(1) 320{ 321 if (getenv("LIBCLANG_OBJTRACKING")) { 322 llvm::sys::AtomicIncrement(&CodeCompletionResultObjects); 323 fprintf(stderr, "+++ %d completion results\n", CodeCompletionResultObjects); 324 } 325} 326 327AllocatedCXCodeCompleteResults::~AllocatedCXCodeCompleteResults() { 328 delete [] Results; 329 330 clang_disposeString(ContainerUSR); 331 332 for (unsigned I = 0, N = TemporaryFiles.size(); I != N; ++I) 333 TemporaryFiles[I].eraseFromDisk(); 334 for (unsigned I = 0, N = TemporaryBuffers.size(); I != N; ++I) 335 delete TemporaryBuffers[I]; 336 337 if (getenv("LIBCLANG_OBJTRACKING")) { 338 llvm::sys::AtomicDecrement(&CodeCompletionResultObjects); 339 fprintf(stderr, "--- %d completion results\n", CodeCompletionResultObjects); 340 } 341} 342 343} // end extern "C" 344 345static unsigned long long getContextsForContextKind( 346 enum CodeCompletionContext::Kind kind, 347 Sema &S) { 348 unsigned long long contexts = 0; 349 switch (kind) { 350 case CodeCompletionContext::CCC_OtherWithMacros: { 351 //We can allow macros here, but we don't know what else is permissible 352 //So we'll say the only thing permissible are macros 353 contexts = CXCompletionContext_MacroName; 354 break; 355 } 356 case CodeCompletionContext::CCC_TopLevel: 357 case CodeCompletionContext::CCC_ObjCIvarList: 358 case CodeCompletionContext::CCC_ClassStructUnion: 359 case CodeCompletionContext::CCC_Type: { 360 contexts = CXCompletionContext_AnyType | 361 CXCompletionContext_ObjCInterface; 362 if (S.getLangOpts().CPlusPlus) { 363 contexts |= CXCompletionContext_EnumTag | 364 CXCompletionContext_UnionTag | 365 CXCompletionContext_StructTag | 366 CXCompletionContext_ClassTag | 367 CXCompletionContext_NestedNameSpecifier; 368 } 369 break; 370 } 371 case CodeCompletionContext::CCC_Statement: { 372 contexts = CXCompletionContext_AnyType | 373 CXCompletionContext_ObjCInterface | 374 CXCompletionContext_AnyValue; 375 if (S.getLangOpts().CPlusPlus) { 376 contexts |= CXCompletionContext_EnumTag | 377 CXCompletionContext_UnionTag | 378 CXCompletionContext_StructTag | 379 CXCompletionContext_ClassTag | 380 CXCompletionContext_NestedNameSpecifier; 381 } 382 break; 383 } 384 case CodeCompletionContext::CCC_Expression: { 385 contexts = CXCompletionContext_AnyValue; 386 if (S.getLangOpts().CPlusPlus) { 387 contexts |= CXCompletionContext_AnyType | 388 CXCompletionContext_ObjCInterface | 389 CXCompletionContext_EnumTag | 390 CXCompletionContext_UnionTag | 391 CXCompletionContext_StructTag | 392 CXCompletionContext_ClassTag | 393 CXCompletionContext_NestedNameSpecifier; 394 } 395 break; 396 } 397 case CodeCompletionContext::CCC_ObjCMessageReceiver: { 398 contexts = CXCompletionContext_ObjCObjectValue | 399 CXCompletionContext_ObjCSelectorValue | 400 CXCompletionContext_ObjCInterface; 401 if (S.getLangOpts().CPlusPlus) { 402 contexts |= CXCompletionContext_CXXClassTypeValue | 403 CXCompletionContext_AnyType | 404 CXCompletionContext_EnumTag | 405 CXCompletionContext_UnionTag | 406 CXCompletionContext_StructTag | 407 CXCompletionContext_ClassTag | 408 CXCompletionContext_NestedNameSpecifier; 409 } 410 break; 411 } 412 case CodeCompletionContext::CCC_DotMemberAccess: { 413 contexts = CXCompletionContext_DotMemberAccess; 414 break; 415 } 416 case CodeCompletionContext::CCC_ArrowMemberAccess: { 417 contexts = CXCompletionContext_ArrowMemberAccess; 418 break; 419 } 420 case CodeCompletionContext::CCC_ObjCPropertyAccess: { 421 contexts = CXCompletionContext_ObjCPropertyAccess; 422 break; 423 } 424 case CodeCompletionContext::CCC_EnumTag: { 425 contexts = CXCompletionContext_EnumTag | 426 CXCompletionContext_NestedNameSpecifier; 427 break; 428 } 429 case CodeCompletionContext::CCC_UnionTag: { 430 contexts = CXCompletionContext_UnionTag | 431 CXCompletionContext_NestedNameSpecifier; 432 break; 433 } 434 case CodeCompletionContext::CCC_ClassOrStructTag: { 435 contexts = CXCompletionContext_StructTag | 436 CXCompletionContext_ClassTag | 437 CXCompletionContext_NestedNameSpecifier; 438 break; 439 } 440 case CodeCompletionContext::CCC_ObjCProtocolName: { 441 contexts = CXCompletionContext_ObjCProtocol; 442 break; 443 } 444 case CodeCompletionContext::CCC_Namespace: { 445 contexts = CXCompletionContext_Namespace; 446 break; 447 } 448 case CodeCompletionContext::CCC_PotentiallyQualifiedName: { 449 contexts = CXCompletionContext_NestedNameSpecifier; 450 break; 451 } 452 case CodeCompletionContext::CCC_MacroNameUse: { 453 contexts = CXCompletionContext_MacroName; 454 break; 455 } 456 case CodeCompletionContext::CCC_NaturalLanguage: { 457 contexts = CXCompletionContext_NaturalLanguage; 458 break; 459 } 460 case CodeCompletionContext::CCC_SelectorName: { 461 contexts = CXCompletionContext_ObjCSelectorName; 462 break; 463 } 464 case CodeCompletionContext::CCC_ParenthesizedExpression: { 465 contexts = CXCompletionContext_AnyType | 466 CXCompletionContext_ObjCInterface | 467 CXCompletionContext_AnyValue; 468 if (S.getLangOpts().CPlusPlus) { 469 contexts |= CXCompletionContext_EnumTag | 470 CXCompletionContext_UnionTag | 471 CXCompletionContext_StructTag | 472 CXCompletionContext_ClassTag | 473 CXCompletionContext_NestedNameSpecifier; 474 } 475 break; 476 } 477 case CodeCompletionContext::CCC_ObjCInstanceMessage: { 478 contexts = CXCompletionContext_ObjCInstanceMessage; 479 break; 480 } 481 case CodeCompletionContext::CCC_ObjCClassMessage: { 482 contexts = CXCompletionContext_ObjCClassMessage; 483 break; 484 } 485 case CodeCompletionContext::CCC_ObjCInterfaceName: { 486 contexts = CXCompletionContext_ObjCInterface; 487 break; 488 } 489 case CodeCompletionContext::CCC_ObjCCategoryName: { 490 contexts = CXCompletionContext_ObjCCategory; 491 break; 492 } 493 case CodeCompletionContext::CCC_Other: 494 case CodeCompletionContext::CCC_ObjCInterface: 495 case CodeCompletionContext::CCC_ObjCImplementation: 496 case CodeCompletionContext::CCC_Name: 497 case CodeCompletionContext::CCC_MacroName: 498 case CodeCompletionContext::CCC_PreprocessorExpression: 499 case CodeCompletionContext::CCC_PreprocessorDirective: 500 case CodeCompletionContext::CCC_TypeQualifiers: { 501 //Only Clang results should be accepted, so we'll set all of the other 502 //context bits to 0 (i.e. the empty set) 503 contexts = CXCompletionContext_Unexposed; 504 break; 505 } 506 case CodeCompletionContext::CCC_Recovery: { 507 //We don't know what the current context is, so we'll return unknown 508 //This is the equivalent of setting all of the other context bits 509 contexts = CXCompletionContext_Unknown; 510 break; 511 } 512 } 513 return contexts; 514} 515 516namespace { 517 class CaptureCompletionResults : public CodeCompleteConsumer { 518 AllocatedCXCodeCompleteResults &AllocatedResults; 519 CodeCompletionTUInfo CCTUInfo; 520 SmallVector<CXCompletionResult, 16> StoredResults; 521 CXTranslationUnit *TU; 522 public: 523 CaptureCompletionResults(const CodeCompleteOptions &Opts, 524 AllocatedCXCodeCompleteResults &Results, 525 CXTranslationUnit *TranslationUnit) 526 : CodeCompleteConsumer(Opts, false), 527 AllocatedResults(Results), CCTUInfo(Results.CodeCompletionAllocator), 528 TU(TranslationUnit) { } 529 ~CaptureCompletionResults() { Finish(); } 530 531 virtual void ProcessCodeCompleteResults(Sema &S, 532 CodeCompletionContext Context, 533 CodeCompletionResult *Results, 534 unsigned NumResults) { 535 StoredResults.reserve(StoredResults.size() + NumResults); 536 for (unsigned I = 0; I != NumResults; ++I) { 537 CodeCompletionString *StoredCompletion 538 = Results[I].CreateCodeCompletionString(S, getAllocator(), 539 getCodeCompletionTUInfo(), 540 includeBriefComments()); 541 542 CXCompletionResult R; 543 R.CursorKind = Results[I].CursorKind; 544 R.CompletionString = StoredCompletion; 545 StoredResults.push_back(R); 546 } 547 548 enum CodeCompletionContext::Kind contextKind = Context.getKind(); 549 550 AllocatedResults.ContextKind = contextKind; 551 AllocatedResults.Contexts = getContextsForContextKind(contextKind, S); 552 553 AllocatedResults.Selector = ""; 554 if (Context.getNumSelIdents() > 0) { 555 for (unsigned i = 0; i < Context.getNumSelIdents(); i++) { 556 IdentifierInfo *selIdent = Context.getSelIdents()[i]; 557 if (selIdent != NULL) { 558 StringRef selectorString = Context.getSelIdents()[i]->getName(); 559 AllocatedResults.Selector += selectorString; 560 } 561 AllocatedResults.Selector += ":"; 562 } 563 } 564 565 QualType baseType = Context.getBaseType(); 566 NamedDecl *D = NULL; 567 568 if (!baseType.isNull()) { 569 // Get the declaration for a class/struct/union/enum type 570 if (const TagType *Tag = baseType->getAs<TagType>()) 571 D = Tag->getDecl(); 572 // Get the @interface declaration for a (possibly-qualified) Objective-C 573 // object pointer type, e.g., NSString* 574 else if (const ObjCObjectPointerType *ObjPtr = 575 baseType->getAs<ObjCObjectPointerType>()) 576 D = ObjPtr->getInterfaceDecl(); 577 // Get the @interface declaration for an Objective-C object type 578 else if (const ObjCObjectType *Obj = baseType->getAs<ObjCObjectType>()) 579 D = Obj->getInterface(); 580 // Get the class for a C++ injected-class-name 581 else if (const InjectedClassNameType *Injected = 582 baseType->getAs<InjectedClassNameType>()) 583 D = Injected->getDecl(); 584 } 585 586 if (D != NULL) { 587 CXCursor cursor = cxcursor::MakeCXCursor(D, *TU); 588 589 CXCursorKind cursorKind = clang_getCursorKind(cursor); 590 CXString cursorUSR = clang_getCursorUSR(cursor); 591 592 // Normally, clients of CXString shouldn't care whether or not 593 // a CXString is managed by a pool or by explicitly malloc'ed memory. 594 // However, there are cases when AllocatedResults outlives the 595 // CXTranslationUnit. This is a workaround that failure mode. 596 if (cxstring::isManagedByPool(cursorUSR)) { 597 CXString heapStr = 598 cxstring::createCXString(clang_getCString(cursorUSR), true); 599 clang_disposeString(cursorUSR); 600 cursorUSR = heapStr; 601 } 602 603 AllocatedResults.ContainerKind = cursorKind; 604 AllocatedResults.ContainerUSR = cursorUSR; 605 606 const Type *type = baseType.getTypePtrOrNull(); 607 if (type != NULL) { 608 AllocatedResults.ContainerIsIncomplete = type->isIncompleteType(); 609 } 610 else { 611 AllocatedResults.ContainerIsIncomplete = 1; 612 } 613 } 614 else { 615 AllocatedResults.ContainerKind = CXCursor_InvalidCode; 616 AllocatedResults.ContainerUSR = createCXString(""); 617 AllocatedResults.ContainerIsIncomplete = 1; 618 } 619 } 620 621 virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg, 622 OverloadCandidate *Candidates, 623 unsigned NumCandidates) { 624 StoredResults.reserve(StoredResults.size() + NumCandidates); 625 for (unsigned I = 0; I != NumCandidates; ++I) { 626 CodeCompletionString *StoredCompletion 627 = Candidates[I].CreateSignatureString(CurrentArg, S, getAllocator(), 628 getCodeCompletionTUInfo()); 629 630 CXCompletionResult R; 631 R.CursorKind = CXCursor_NotImplemented; 632 R.CompletionString = StoredCompletion; 633 StoredResults.push_back(R); 634 } 635 } 636 637 virtual CodeCompletionAllocator &getAllocator() { 638 return *AllocatedResults.CodeCompletionAllocator; 639 } 640 641 virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() { return CCTUInfo; } 642 643 private: 644 void Finish() { 645 AllocatedResults.Results = new CXCompletionResult [StoredResults.size()]; 646 AllocatedResults.NumResults = StoredResults.size(); 647 std::memcpy(AllocatedResults.Results, StoredResults.data(), 648 StoredResults.size() * sizeof(CXCompletionResult)); 649 StoredResults.clear(); 650 } 651 }; 652} 653 654extern "C" { 655struct CodeCompleteAtInfo { 656 CXTranslationUnit TU; 657 const char *complete_filename; 658 unsigned complete_line; 659 unsigned complete_column; 660 struct CXUnsavedFile *unsaved_files; 661 unsigned num_unsaved_files; 662 unsigned options; 663 CXCodeCompleteResults *result; 664}; 665void clang_codeCompleteAt_Impl(void *UserData) { 666 CodeCompleteAtInfo *CCAI = static_cast<CodeCompleteAtInfo*>(UserData); 667 CXTranslationUnit TU = CCAI->TU; 668 const char *complete_filename = CCAI->complete_filename; 669 unsigned complete_line = CCAI->complete_line; 670 unsigned complete_column = CCAI->complete_column; 671 struct CXUnsavedFile *unsaved_files = CCAI->unsaved_files; 672 unsigned num_unsaved_files = CCAI->num_unsaved_files; 673 unsigned options = CCAI->options; 674 bool IncludeBriefComments = options & CXCodeComplete_IncludeBriefComments; 675 CCAI->result = 0; 676 677#ifdef UDP_CODE_COMPLETION_LOGGER 678#ifdef UDP_CODE_COMPLETION_LOGGER_PORT 679 const llvm::TimeRecord &StartTime = llvm::TimeRecord::getCurrentTime(); 680#endif 681#endif 682 683 bool EnableLogging = getenv("LIBCLANG_CODE_COMPLETION_LOGGING") != 0; 684 685 ASTUnit *AST = static_cast<ASTUnit *>(TU->TUData); 686 if (!AST) 687 return; 688 689 CIndexer *CXXIdx = (CIndexer*)TU->CIdx; 690 if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing)) 691 setThreadBackgroundPriority(); 692 693 ASTUnit::ConcurrencyCheck Check(*AST); 694 695 // Perform the remapping of source files. 696 SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles; 697 for (unsigned I = 0; I != num_unsaved_files; ++I) { 698 StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length); 699 const llvm::MemoryBuffer *Buffer 700 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename); 701 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename, 702 Buffer)); 703 } 704 705 if (EnableLogging) { 706 // FIXME: Add logging. 707 } 708 709 // Parse the resulting source file to find code-completion results. 710 AllocatedCXCodeCompleteResults *Results = 711 new AllocatedCXCodeCompleteResults(AST->getFileSystemOpts()); 712 Results->Results = 0; 713 Results->NumResults = 0; 714 715 // Create a code-completion consumer to capture the results. 716 CodeCompleteOptions Opts; 717 Opts.IncludeBriefComments = IncludeBriefComments; 718 CaptureCompletionResults Capture(Opts, *Results, &TU); 719 720 // Perform completion. 721 AST->CodeComplete(complete_filename, complete_line, complete_column, 722 RemappedFiles.data(), RemappedFiles.size(), 723 (options & CXCodeComplete_IncludeMacros), 724 (options & CXCodeComplete_IncludeCodePatterns), 725 IncludeBriefComments, 726 Capture, 727 *Results->Diag, Results->LangOpts, *Results->SourceMgr, 728 *Results->FileMgr, Results->Diagnostics, 729 Results->TemporaryBuffers); 730 731 // Keep a reference to the allocator used for cached global completions, so 732 // that we can be sure that the memory used by our code completion strings 733 // doesn't get freed due to subsequent reparses (while the code completion 734 // results are still active). 735 Results->CachedCompletionAllocator = AST->getCachedCompletionAllocator(); 736 737 738 739#ifdef UDP_CODE_COMPLETION_LOGGER 740#ifdef UDP_CODE_COMPLETION_LOGGER_PORT 741 const llvm::TimeRecord &EndTime = llvm::TimeRecord::getCurrentTime(); 742 SmallString<256> LogResult; 743 llvm::raw_svector_ostream os(LogResult); 744 745 // Figure out the language and whether or not it uses PCH. 746 const char *lang = 0; 747 bool usesPCH = false; 748 749 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end(); 750 I != E; ++I) { 751 if (*I == 0) 752 continue; 753 if (strcmp(*I, "-x") == 0) { 754 if (I + 1 != E) { 755 lang = *(++I); 756 continue; 757 } 758 } 759 else if (strcmp(*I, "-include") == 0) { 760 if (I+1 != E) { 761 const char *arg = *(++I); 762 SmallString<512> pchName; 763 { 764 llvm::raw_svector_ostream os(pchName); 765 os << arg << ".pth"; 766 } 767 pchName.push_back('\0'); 768 struct stat stat_results; 769 if (stat(pchName.str().c_str(), &stat_results) == 0) 770 usesPCH = true; 771 continue; 772 } 773 } 774 } 775 776 os << "{ "; 777 os << "\"wall\": " << (EndTime.getWallTime() - StartTime.getWallTime()); 778 os << ", \"numRes\": " << Results->NumResults; 779 os << ", \"diags\": " << Results->Diagnostics.size(); 780 os << ", \"pch\": " << (usesPCH ? "true" : "false"); 781 os << ", \"lang\": \"" << (lang ? lang : "<unknown>") << '"'; 782 const char *name = getlogin(); 783 os << ", \"user\": \"" << (name ? name : "unknown") << '"'; 784 os << ", \"clangVer\": \"" << getClangFullVersion() << '"'; 785 os << " }"; 786 787 StringRef res = os.str(); 788 if (res.size() > 0) { 789 do { 790 // Setup the UDP socket. 791 struct sockaddr_in servaddr; 792 bzero(&servaddr, sizeof(servaddr)); 793 servaddr.sin_family = AF_INET; 794 servaddr.sin_port = htons(UDP_CODE_COMPLETION_LOGGER_PORT); 795 if (inet_pton(AF_INET, UDP_CODE_COMPLETION_LOGGER, 796 &servaddr.sin_addr) <= 0) 797 break; 798 799 int sockfd = socket(AF_INET, SOCK_DGRAM, 0); 800 if (sockfd < 0) 801 break; 802 803 sendto(sockfd, res.data(), res.size(), 0, 804 (struct sockaddr *)&servaddr, sizeof(servaddr)); 805 close(sockfd); 806 } 807 while (false); 808 } 809#endif 810#endif 811 CCAI->result = Results; 812} 813CXCodeCompleteResults *clang_codeCompleteAt(CXTranslationUnit TU, 814 const char *complete_filename, 815 unsigned complete_line, 816 unsigned complete_column, 817 struct CXUnsavedFile *unsaved_files, 818 unsigned num_unsaved_files, 819 unsigned options) { 820 CodeCompleteAtInfo CCAI = { TU, complete_filename, complete_line, 821 complete_column, unsaved_files, num_unsaved_files, 822 options, 0 }; 823 llvm::CrashRecoveryContext CRC; 824 825 if (!RunSafely(CRC, clang_codeCompleteAt_Impl, &CCAI)) { 826 fprintf(stderr, "libclang: crash detected in code completion\n"); 827 static_cast<ASTUnit *>(TU->TUData)->setUnsafeToFree(true); 828 return 0; 829 } else if (getenv("LIBCLANG_RESOURCE_USAGE")) 830 PrintLibclangResourceUsage(TU); 831 832 return CCAI.result; 833} 834 835unsigned clang_defaultCodeCompleteOptions(void) { 836 return CXCodeComplete_IncludeMacros; 837} 838 839void clang_disposeCodeCompleteResults(CXCodeCompleteResults *ResultsIn) { 840 if (!ResultsIn) 841 return; 842 843 AllocatedCXCodeCompleteResults *Results 844 = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn); 845 delete Results; 846} 847 848unsigned 849clang_codeCompleteGetNumDiagnostics(CXCodeCompleteResults *ResultsIn) { 850 AllocatedCXCodeCompleteResults *Results 851 = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn); 852 if (!Results) 853 return 0; 854 855 return Results->Diagnostics.size(); 856} 857 858CXDiagnostic 859clang_codeCompleteGetDiagnostic(CXCodeCompleteResults *ResultsIn, 860 unsigned Index) { 861 AllocatedCXCodeCompleteResults *Results 862 = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn); 863 if (!Results || Index >= Results->Diagnostics.size()) 864 return 0; 865 866 return new CXStoredDiagnostic(Results->Diagnostics[Index], Results->LangOpts); 867} 868 869unsigned long long 870clang_codeCompleteGetContexts(CXCodeCompleteResults *ResultsIn) { 871 AllocatedCXCodeCompleteResults *Results 872 = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn); 873 if (!Results) 874 return 0; 875 876 return Results->Contexts; 877} 878 879enum CXCursorKind clang_codeCompleteGetContainerKind( 880 CXCodeCompleteResults *ResultsIn, 881 unsigned *IsIncomplete) { 882 AllocatedCXCodeCompleteResults *Results = 883 static_cast<AllocatedCXCodeCompleteResults *>(ResultsIn); 884 if (!Results) 885 return CXCursor_InvalidCode; 886 887 if (IsIncomplete != NULL) { 888 *IsIncomplete = Results->ContainerIsIncomplete; 889 } 890 891 return Results->ContainerKind; 892} 893 894CXString clang_codeCompleteGetContainerUSR(CXCodeCompleteResults *ResultsIn) { 895 AllocatedCXCodeCompleteResults *Results = 896 static_cast<AllocatedCXCodeCompleteResults *>(ResultsIn); 897 if (!Results) 898 return createCXString(""); 899 900 return createCXString(clang_getCString(Results->ContainerUSR)); 901} 902 903 904CXString clang_codeCompleteGetObjCSelector(CXCodeCompleteResults *ResultsIn) { 905 AllocatedCXCodeCompleteResults *Results = 906 static_cast<AllocatedCXCodeCompleteResults *>(ResultsIn); 907 if (!Results) 908 return createCXString(""); 909 910 return createCXString(Results->Selector); 911} 912 913} // end extern "C" 914 915/// \brief Simple utility function that appends a \p New string to the given 916/// \p Old string, using the \p Buffer for storage. 917/// 918/// \param Old The string to which we are appending. This parameter will be 919/// updated to reflect the complete string. 920/// 921/// 922/// \param New The string to append to \p Old. 923/// 924/// \param Buffer A buffer that stores the actual, concatenated string. It will 925/// be used if the old string is already-non-empty. 926static void AppendToString(StringRef &Old, StringRef New, 927 SmallString<256> &Buffer) { 928 if (Old.empty()) { 929 Old = New; 930 return; 931 } 932 933 if (Buffer.empty()) 934 Buffer.append(Old.begin(), Old.end()); 935 Buffer.append(New.begin(), New.end()); 936 Old = Buffer.str(); 937} 938 939/// \brief Get the typed-text blocks from the given code-completion string 940/// and return them as a single string. 941/// 942/// \param String The code-completion string whose typed-text blocks will be 943/// concatenated. 944/// 945/// \param Buffer A buffer used for storage of the completed name. 946static StringRef GetTypedName(CodeCompletionString *String, 947 SmallString<256> &Buffer) { 948 StringRef Result; 949 for (CodeCompletionString::iterator C = String->begin(), CEnd = String->end(); 950 C != CEnd; ++C) { 951 if (C->Kind == CodeCompletionString::CK_TypedText) 952 AppendToString(Result, C->Text, Buffer); 953 } 954 955 return Result; 956} 957 958namespace { 959 struct OrderCompletionResults { 960 bool operator()(const CXCompletionResult &XR, 961 const CXCompletionResult &YR) const { 962 CodeCompletionString *X 963 = (CodeCompletionString *)XR.CompletionString; 964 CodeCompletionString *Y 965 = (CodeCompletionString *)YR.CompletionString; 966 967 SmallString<256> XBuffer; 968 StringRef XText = GetTypedName(X, XBuffer); 969 SmallString<256> YBuffer; 970 StringRef YText = GetTypedName(Y, YBuffer); 971 972 if (XText.empty() || YText.empty()) 973 return !XText.empty(); 974 975 int result = XText.compare_lower(YText); 976 if (result < 0) 977 return true; 978 if (result > 0) 979 return false; 980 981 result = XText.compare(YText); 982 return result < 0; 983 } 984 }; 985} 986 987extern "C" { 988 void clang_sortCodeCompletionResults(CXCompletionResult *Results, 989 unsigned NumResults) { 990 std::stable_sort(Results, Results + NumResults, OrderCompletionResults()); 991 } 992} 993