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