xref: /netbsd-src/external/apache2/llvm/dist/clang/lib/Sema/CodeCompleteConsumer.cpp (revision e038c9c4676b0f19b1b7dd08a940c6ed64a6d5ae)
17330f729Sjoerg //===- CodeCompleteConsumer.cpp - Code Completion Interface ---------------===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg //
97330f729Sjoerg //  This file implements the CodeCompleteConsumer class.
107330f729Sjoerg //
117330f729Sjoerg //===----------------------------------------------------------------------===//
127330f729Sjoerg 
137330f729Sjoerg #include "clang/Sema/CodeCompleteConsumer.h"
147330f729Sjoerg #include "clang-c/Index.h"
157330f729Sjoerg #include "clang/AST/Decl.h"
167330f729Sjoerg #include "clang/AST/DeclBase.h"
177330f729Sjoerg #include "clang/AST/DeclObjC.h"
187330f729Sjoerg #include "clang/AST/DeclTemplate.h"
197330f729Sjoerg #include "clang/AST/DeclarationName.h"
207330f729Sjoerg #include "clang/AST/Type.h"
217330f729Sjoerg #include "clang/Basic/IdentifierTable.h"
227330f729Sjoerg #include "clang/Lex/Preprocessor.h"
237330f729Sjoerg #include "clang/Sema/Sema.h"
247330f729Sjoerg #include "llvm/ADT/SmallString.h"
257330f729Sjoerg #include "llvm/ADT/SmallVector.h"
26*e038c9c4Sjoerg #include "llvm/ADT/StringExtras.h"
277330f729Sjoerg #include "llvm/ADT/StringRef.h"
287330f729Sjoerg #include "llvm/ADT/Twine.h"
297330f729Sjoerg #include "llvm/Support/Casting.h"
307330f729Sjoerg #include "llvm/Support/Compiler.h"
317330f729Sjoerg #include "llvm/Support/ErrorHandling.h"
327330f729Sjoerg #include "llvm/Support/FormatVariadic.h"
337330f729Sjoerg #include "llvm/Support/raw_ostream.h"
347330f729Sjoerg #include <algorithm>
357330f729Sjoerg #include <cassert>
367330f729Sjoerg #include <cstdint>
377330f729Sjoerg #include <string>
387330f729Sjoerg 
397330f729Sjoerg using namespace clang;
407330f729Sjoerg 
417330f729Sjoerg //===----------------------------------------------------------------------===//
427330f729Sjoerg // Code completion context implementation
437330f729Sjoerg //===----------------------------------------------------------------------===//
447330f729Sjoerg 
wantConstructorResults() const457330f729Sjoerg bool CodeCompletionContext::wantConstructorResults() const {
467330f729Sjoerg   switch (CCKind) {
477330f729Sjoerg   case CCC_Recovery:
487330f729Sjoerg   case CCC_Statement:
497330f729Sjoerg   case CCC_Expression:
507330f729Sjoerg   case CCC_ObjCMessageReceiver:
517330f729Sjoerg   case CCC_ParenthesizedExpression:
527330f729Sjoerg   case CCC_Symbol:
537330f729Sjoerg   case CCC_SymbolOrNewName:
547330f729Sjoerg     return true;
557330f729Sjoerg 
567330f729Sjoerg   case CCC_TopLevel:
577330f729Sjoerg   case CCC_ObjCInterface:
587330f729Sjoerg   case CCC_ObjCImplementation:
597330f729Sjoerg   case CCC_ObjCIvarList:
607330f729Sjoerg   case CCC_ClassStructUnion:
617330f729Sjoerg   case CCC_DotMemberAccess:
627330f729Sjoerg   case CCC_ArrowMemberAccess:
637330f729Sjoerg   case CCC_ObjCPropertyAccess:
647330f729Sjoerg   case CCC_EnumTag:
657330f729Sjoerg   case CCC_UnionTag:
667330f729Sjoerg   case CCC_ClassOrStructTag:
677330f729Sjoerg   case CCC_ObjCProtocolName:
687330f729Sjoerg   case CCC_Namespace:
697330f729Sjoerg   case CCC_Type:
707330f729Sjoerg   case CCC_NewName:
717330f729Sjoerg   case CCC_MacroName:
727330f729Sjoerg   case CCC_MacroNameUse:
737330f729Sjoerg   case CCC_PreprocessorExpression:
747330f729Sjoerg   case CCC_PreprocessorDirective:
757330f729Sjoerg   case CCC_NaturalLanguage:
767330f729Sjoerg   case CCC_SelectorName:
777330f729Sjoerg   case CCC_TypeQualifiers:
787330f729Sjoerg   case CCC_Other:
797330f729Sjoerg   case CCC_OtherWithMacros:
807330f729Sjoerg   case CCC_ObjCInstanceMessage:
817330f729Sjoerg   case CCC_ObjCClassMessage:
827330f729Sjoerg   case CCC_ObjCInterfaceName:
837330f729Sjoerg   case CCC_ObjCCategoryName:
847330f729Sjoerg   case CCC_IncludedFile:
857330f729Sjoerg     return false;
867330f729Sjoerg   }
877330f729Sjoerg 
887330f729Sjoerg   llvm_unreachable("Invalid CodeCompletionContext::Kind!");
897330f729Sjoerg }
907330f729Sjoerg 
getCompletionKindString(CodeCompletionContext::Kind Kind)917330f729Sjoerg StringRef clang::getCompletionKindString(CodeCompletionContext::Kind Kind) {
927330f729Sjoerg   using CCKind = CodeCompletionContext::Kind;
937330f729Sjoerg   switch (Kind) {
947330f729Sjoerg   case CCKind::CCC_Other:
957330f729Sjoerg     return "Other";
967330f729Sjoerg   case CCKind::CCC_OtherWithMacros:
977330f729Sjoerg     return "OtherWithMacros";
987330f729Sjoerg   case CCKind::CCC_TopLevel:
997330f729Sjoerg     return "TopLevel";
1007330f729Sjoerg   case CCKind::CCC_ObjCInterface:
1017330f729Sjoerg     return "ObjCInterface";
1027330f729Sjoerg   case CCKind::CCC_ObjCImplementation:
1037330f729Sjoerg     return "ObjCImplementation";
1047330f729Sjoerg   case CCKind::CCC_ObjCIvarList:
1057330f729Sjoerg     return "ObjCIvarList";
1067330f729Sjoerg   case CCKind::CCC_ClassStructUnion:
1077330f729Sjoerg     return "ClassStructUnion";
1087330f729Sjoerg   case CCKind::CCC_Statement:
1097330f729Sjoerg     return "Statement";
1107330f729Sjoerg   case CCKind::CCC_Expression:
1117330f729Sjoerg     return "Expression";
1127330f729Sjoerg   case CCKind::CCC_ObjCMessageReceiver:
1137330f729Sjoerg     return "ObjCMessageReceiver";
1147330f729Sjoerg   case CCKind::CCC_DotMemberAccess:
1157330f729Sjoerg     return "DotMemberAccess";
1167330f729Sjoerg   case CCKind::CCC_ArrowMemberAccess:
1177330f729Sjoerg     return "ArrowMemberAccess";
1187330f729Sjoerg   case CCKind::CCC_ObjCPropertyAccess:
1197330f729Sjoerg     return "ObjCPropertyAccess";
1207330f729Sjoerg   case CCKind::CCC_EnumTag:
1217330f729Sjoerg     return "EnumTag";
1227330f729Sjoerg   case CCKind::CCC_UnionTag:
1237330f729Sjoerg     return "UnionTag";
1247330f729Sjoerg   case CCKind::CCC_ClassOrStructTag:
1257330f729Sjoerg     return "ClassOrStructTag";
1267330f729Sjoerg   case CCKind::CCC_ObjCProtocolName:
1277330f729Sjoerg     return "ObjCProtocolName";
1287330f729Sjoerg   case CCKind::CCC_Namespace:
1297330f729Sjoerg     return "Namespace";
1307330f729Sjoerg   case CCKind::CCC_Type:
1317330f729Sjoerg     return "Type";
1327330f729Sjoerg   case CCKind::CCC_NewName:
1337330f729Sjoerg     return "NewName";
1347330f729Sjoerg   case CCKind::CCC_Symbol:
1357330f729Sjoerg     return "Symbol";
1367330f729Sjoerg   case CCKind::CCC_SymbolOrNewName:
1377330f729Sjoerg     return "SymbolOrNewName";
1387330f729Sjoerg   case CCKind::CCC_MacroName:
1397330f729Sjoerg     return "MacroName";
1407330f729Sjoerg   case CCKind::CCC_MacroNameUse:
1417330f729Sjoerg     return "MacroNameUse";
1427330f729Sjoerg   case CCKind::CCC_PreprocessorExpression:
1437330f729Sjoerg     return "PreprocessorExpression";
1447330f729Sjoerg   case CCKind::CCC_PreprocessorDirective:
1457330f729Sjoerg     return "PreprocessorDirective";
1467330f729Sjoerg   case CCKind::CCC_NaturalLanguage:
1477330f729Sjoerg     return "NaturalLanguage";
1487330f729Sjoerg   case CCKind::CCC_SelectorName:
1497330f729Sjoerg     return "SelectorName";
1507330f729Sjoerg   case CCKind::CCC_TypeQualifiers:
1517330f729Sjoerg     return "TypeQualifiers";
1527330f729Sjoerg   case CCKind::CCC_ParenthesizedExpression:
1537330f729Sjoerg     return "ParenthesizedExpression";
1547330f729Sjoerg   case CCKind::CCC_ObjCInstanceMessage:
1557330f729Sjoerg     return "ObjCInstanceMessage";
1567330f729Sjoerg   case CCKind::CCC_ObjCClassMessage:
1577330f729Sjoerg     return "ObjCClassMessage";
1587330f729Sjoerg   case CCKind::CCC_ObjCInterfaceName:
1597330f729Sjoerg     return "ObjCInterfaceName";
1607330f729Sjoerg   case CCKind::CCC_ObjCCategoryName:
1617330f729Sjoerg     return "ObjCCategoryName";
1627330f729Sjoerg   case CCKind::CCC_IncludedFile:
1637330f729Sjoerg     return "IncludedFile";
1647330f729Sjoerg   case CCKind::CCC_Recovery:
1657330f729Sjoerg     return "Recovery";
1667330f729Sjoerg   }
1677330f729Sjoerg   llvm_unreachable("Invalid CodeCompletionContext::Kind!");
1687330f729Sjoerg }
1697330f729Sjoerg 
1707330f729Sjoerg //===----------------------------------------------------------------------===//
1717330f729Sjoerg // Code completion string implementation
1727330f729Sjoerg //===----------------------------------------------------------------------===//
1737330f729Sjoerg 
Chunk(ChunkKind Kind,const char * Text)1747330f729Sjoerg CodeCompletionString::Chunk::Chunk(ChunkKind Kind, const char *Text)
1757330f729Sjoerg     : Kind(Kind), Text("") {
1767330f729Sjoerg   switch (Kind) {
1777330f729Sjoerg   case CK_TypedText:
1787330f729Sjoerg   case CK_Text:
1797330f729Sjoerg   case CK_Placeholder:
1807330f729Sjoerg   case CK_Informative:
1817330f729Sjoerg   case CK_ResultType:
1827330f729Sjoerg   case CK_CurrentParameter:
1837330f729Sjoerg     this->Text = Text;
1847330f729Sjoerg     break;
1857330f729Sjoerg 
1867330f729Sjoerg   case CK_Optional:
1877330f729Sjoerg     llvm_unreachable("Optional strings cannot be created from text");
1887330f729Sjoerg 
1897330f729Sjoerg   case CK_LeftParen:
1907330f729Sjoerg     this->Text = "(";
1917330f729Sjoerg     break;
1927330f729Sjoerg 
1937330f729Sjoerg   case CK_RightParen:
1947330f729Sjoerg     this->Text = ")";
1957330f729Sjoerg     break;
1967330f729Sjoerg 
1977330f729Sjoerg   case CK_LeftBracket:
1987330f729Sjoerg     this->Text = "[";
1997330f729Sjoerg     break;
2007330f729Sjoerg 
2017330f729Sjoerg   case CK_RightBracket:
2027330f729Sjoerg     this->Text = "]";
2037330f729Sjoerg     break;
2047330f729Sjoerg 
2057330f729Sjoerg   case CK_LeftBrace:
2067330f729Sjoerg     this->Text = "{";
2077330f729Sjoerg     break;
2087330f729Sjoerg 
2097330f729Sjoerg   case CK_RightBrace:
2107330f729Sjoerg     this->Text = "}";
2117330f729Sjoerg     break;
2127330f729Sjoerg 
2137330f729Sjoerg   case CK_LeftAngle:
2147330f729Sjoerg     this->Text = "<";
2157330f729Sjoerg     break;
2167330f729Sjoerg 
2177330f729Sjoerg   case CK_RightAngle:
2187330f729Sjoerg     this->Text = ">";
2197330f729Sjoerg     break;
2207330f729Sjoerg 
2217330f729Sjoerg   case CK_Comma:
2227330f729Sjoerg     this->Text = ", ";
2237330f729Sjoerg     break;
2247330f729Sjoerg 
2257330f729Sjoerg   case CK_Colon:
2267330f729Sjoerg     this->Text = ":";
2277330f729Sjoerg     break;
2287330f729Sjoerg 
2297330f729Sjoerg   case CK_SemiColon:
2307330f729Sjoerg     this->Text = ";";
2317330f729Sjoerg     break;
2327330f729Sjoerg 
2337330f729Sjoerg   case CK_Equal:
2347330f729Sjoerg     this->Text = " = ";
2357330f729Sjoerg     break;
2367330f729Sjoerg 
2377330f729Sjoerg   case CK_HorizontalSpace:
2387330f729Sjoerg     this->Text = " ";
2397330f729Sjoerg     break;
2407330f729Sjoerg 
2417330f729Sjoerg   case CK_VerticalSpace:
2427330f729Sjoerg     this->Text = "\n";
2437330f729Sjoerg     break;
2447330f729Sjoerg   }
2457330f729Sjoerg }
2467330f729Sjoerg 
2477330f729Sjoerg CodeCompletionString::Chunk
CreateText(const char * Text)2487330f729Sjoerg CodeCompletionString::Chunk::CreateText(const char *Text) {
2497330f729Sjoerg   return Chunk(CK_Text, Text);
2507330f729Sjoerg }
2517330f729Sjoerg 
2527330f729Sjoerg CodeCompletionString::Chunk
CreateOptional(CodeCompletionString * Optional)2537330f729Sjoerg CodeCompletionString::Chunk::CreateOptional(CodeCompletionString *Optional) {
2547330f729Sjoerg   Chunk Result;
2557330f729Sjoerg   Result.Kind = CK_Optional;
2567330f729Sjoerg   Result.Optional = Optional;
2577330f729Sjoerg   return Result;
2587330f729Sjoerg }
2597330f729Sjoerg 
2607330f729Sjoerg CodeCompletionString::Chunk
CreatePlaceholder(const char * Placeholder)2617330f729Sjoerg CodeCompletionString::Chunk::CreatePlaceholder(const char *Placeholder) {
2627330f729Sjoerg   return Chunk(CK_Placeholder, Placeholder);
2637330f729Sjoerg }
2647330f729Sjoerg 
2657330f729Sjoerg CodeCompletionString::Chunk
CreateInformative(const char * Informative)2667330f729Sjoerg CodeCompletionString::Chunk::CreateInformative(const char *Informative) {
2677330f729Sjoerg   return Chunk(CK_Informative, Informative);
2687330f729Sjoerg }
2697330f729Sjoerg 
2707330f729Sjoerg CodeCompletionString::Chunk
CreateResultType(const char * ResultType)2717330f729Sjoerg CodeCompletionString::Chunk::CreateResultType(const char *ResultType) {
2727330f729Sjoerg   return Chunk(CK_ResultType, ResultType);
2737330f729Sjoerg }
2747330f729Sjoerg 
CreateCurrentParameter(const char * CurrentParameter)2757330f729Sjoerg CodeCompletionString::Chunk CodeCompletionString::Chunk::CreateCurrentParameter(
2767330f729Sjoerg     const char *CurrentParameter) {
2777330f729Sjoerg   return Chunk(CK_CurrentParameter, CurrentParameter);
2787330f729Sjoerg }
2797330f729Sjoerg 
CodeCompletionString(const Chunk * Chunks,unsigned NumChunks,unsigned Priority,CXAvailabilityKind Availability,const char ** Annotations,unsigned NumAnnotations,StringRef ParentName,const char * BriefComment)2807330f729Sjoerg CodeCompletionString::CodeCompletionString(
2817330f729Sjoerg     const Chunk *Chunks, unsigned NumChunks, unsigned Priority,
2827330f729Sjoerg     CXAvailabilityKind Availability, const char **Annotations,
2837330f729Sjoerg     unsigned NumAnnotations, StringRef ParentName, const char *BriefComment)
2847330f729Sjoerg     : NumChunks(NumChunks), NumAnnotations(NumAnnotations), Priority(Priority),
2857330f729Sjoerg       Availability(Availability), ParentName(ParentName),
2867330f729Sjoerg       BriefComment(BriefComment) {
2877330f729Sjoerg   assert(NumChunks <= 0xffff);
2887330f729Sjoerg   assert(NumAnnotations <= 0xffff);
2897330f729Sjoerg 
2907330f729Sjoerg   Chunk *StoredChunks = reinterpret_cast<Chunk *>(this + 1);
2917330f729Sjoerg   for (unsigned I = 0; I != NumChunks; ++I)
2927330f729Sjoerg     StoredChunks[I] = Chunks[I];
2937330f729Sjoerg 
2947330f729Sjoerg   const char **StoredAnnotations =
2957330f729Sjoerg       reinterpret_cast<const char **>(StoredChunks + NumChunks);
2967330f729Sjoerg   for (unsigned I = 0; I != NumAnnotations; ++I)
2977330f729Sjoerg     StoredAnnotations[I] = Annotations[I];
2987330f729Sjoerg }
2997330f729Sjoerg 
getAnnotationCount() const3007330f729Sjoerg unsigned CodeCompletionString::getAnnotationCount() const {
3017330f729Sjoerg   return NumAnnotations;
3027330f729Sjoerg }
3037330f729Sjoerg 
getAnnotation(unsigned AnnotationNr) const3047330f729Sjoerg const char *CodeCompletionString::getAnnotation(unsigned AnnotationNr) const {
3057330f729Sjoerg   if (AnnotationNr < NumAnnotations)
3067330f729Sjoerg     return reinterpret_cast<const char *const *>(end())[AnnotationNr];
3077330f729Sjoerg   else
3087330f729Sjoerg     return nullptr;
3097330f729Sjoerg }
3107330f729Sjoerg 
getAsString() const3117330f729Sjoerg std::string CodeCompletionString::getAsString() const {
3127330f729Sjoerg   std::string Result;
3137330f729Sjoerg   llvm::raw_string_ostream OS(Result);
3147330f729Sjoerg 
3157330f729Sjoerg   for (const Chunk &C : *this) {
3167330f729Sjoerg     switch (C.Kind) {
3177330f729Sjoerg     case CK_Optional:
3187330f729Sjoerg       OS << "{#" << C.Optional->getAsString() << "#}";
3197330f729Sjoerg       break;
3207330f729Sjoerg     case CK_Placeholder:
3217330f729Sjoerg       OS << "<#" << C.Text << "#>";
3227330f729Sjoerg       break;
3237330f729Sjoerg     case CK_Informative:
3247330f729Sjoerg     case CK_ResultType:
3257330f729Sjoerg       OS << "[#" << C.Text << "#]";
3267330f729Sjoerg       break;
3277330f729Sjoerg     case CK_CurrentParameter:
3287330f729Sjoerg       OS << "<#" << C.Text << "#>";
3297330f729Sjoerg       break;
3307330f729Sjoerg     default:
3317330f729Sjoerg       OS << C.Text;
3327330f729Sjoerg       break;
3337330f729Sjoerg     }
3347330f729Sjoerg   }
3357330f729Sjoerg   return OS.str();
3367330f729Sjoerg }
3377330f729Sjoerg 
getTypedText() const3387330f729Sjoerg const char *CodeCompletionString::getTypedText() const {
3397330f729Sjoerg   for (const Chunk &C : *this)
3407330f729Sjoerg     if (C.Kind == CK_TypedText)
3417330f729Sjoerg       return C.Text;
3427330f729Sjoerg 
3437330f729Sjoerg   return nullptr;
3447330f729Sjoerg }
3457330f729Sjoerg 
CopyString(const Twine & String)3467330f729Sjoerg const char *CodeCompletionAllocator::CopyString(const Twine &String) {
3477330f729Sjoerg   SmallString<128> Data;
3487330f729Sjoerg   StringRef Ref = String.toStringRef(Data);
3497330f729Sjoerg   // FIXME: It would be more efficient to teach Twine to tell us its size and
3507330f729Sjoerg   // then add a routine there to fill in an allocated char* with the contents
3517330f729Sjoerg   // of the string.
3527330f729Sjoerg   char *Mem = (char *)Allocate(Ref.size() + 1, 1);
3537330f729Sjoerg   std::copy(Ref.begin(), Ref.end(), Mem);
3547330f729Sjoerg   Mem[Ref.size()] = 0;
3557330f729Sjoerg   return Mem;
3567330f729Sjoerg }
3577330f729Sjoerg 
getParentName(const DeclContext * DC)3587330f729Sjoerg StringRef CodeCompletionTUInfo::getParentName(const DeclContext *DC) {
359*e038c9c4Sjoerg   if (!isa<NamedDecl>(DC))
3607330f729Sjoerg     return {};
3617330f729Sjoerg 
3627330f729Sjoerg   // Check whether we've already cached the parent name.
3637330f729Sjoerg   StringRef &CachedParentName = ParentNames[DC];
3647330f729Sjoerg   if (!CachedParentName.empty())
3657330f729Sjoerg     return CachedParentName;
3667330f729Sjoerg 
3677330f729Sjoerg   // If we already processed this DeclContext and assigned empty to it, the
3687330f729Sjoerg   // data pointer will be non-null.
3697330f729Sjoerg   if (CachedParentName.data() != nullptr)
3707330f729Sjoerg     return {};
3717330f729Sjoerg 
3727330f729Sjoerg   // Find the interesting names.
3737330f729Sjoerg   SmallVector<const DeclContext *, 2> Contexts;
3747330f729Sjoerg   while (DC && !DC->isFunctionOrMethod()) {
3757330f729Sjoerg     if (const auto *ND = dyn_cast<NamedDecl>(DC)) {
3767330f729Sjoerg       if (ND->getIdentifier())
3777330f729Sjoerg         Contexts.push_back(DC);
3787330f729Sjoerg     }
3797330f729Sjoerg 
3807330f729Sjoerg     DC = DC->getParent();
3817330f729Sjoerg   }
3827330f729Sjoerg 
3837330f729Sjoerg   {
3847330f729Sjoerg     SmallString<128> S;
3857330f729Sjoerg     llvm::raw_svector_ostream OS(S);
3867330f729Sjoerg     bool First = true;
3877330f729Sjoerg     for (unsigned I = Contexts.size(); I != 0; --I) {
3887330f729Sjoerg       if (First)
3897330f729Sjoerg         First = false;
3907330f729Sjoerg       else {
3917330f729Sjoerg         OS << "::";
3927330f729Sjoerg       }
3937330f729Sjoerg 
3947330f729Sjoerg       const DeclContext *CurDC = Contexts[I - 1];
3957330f729Sjoerg       if (const auto *CatImpl = dyn_cast<ObjCCategoryImplDecl>(CurDC))
3967330f729Sjoerg         CurDC = CatImpl->getCategoryDecl();
3977330f729Sjoerg 
3987330f729Sjoerg       if (const auto *Cat = dyn_cast<ObjCCategoryDecl>(CurDC)) {
3997330f729Sjoerg         const ObjCInterfaceDecl *Interface = Cat->getClassInterface();
4007330f729Sjoerg         if (!Interface) {
4017330f729Sjoerg           // Assign an empty StringRef but with non-null data to distinguish
4027330f729Sjoerg           // between empty because we didn't process the DeclContext yet.
4037330f729Sjoerg           CachedParentName = StringRef((const char *)(uintptr_t)~0U, 0);
4047330f729Sjoerg           return {};
4057330f729Sjoerg         }
4067330f729Sjoerg 
4077330f729Sjoerg         OS << Interface->getName() << '(' << Cat->getName() << ')';
4087330f729Sjoerg       } else {
4097330f729Sjoerg         OS << cast<NamedDecl>(CurDC)->getName();
4107330f729Sjoerg       }
4117330f729Sjoerg     }
4127330f729Sjoerg 
4137330f729Sjoerg     CachedParentName = AllocatorRef->CopyString(OS.str());
4147330f729Sjoerg   }
4157330f729Sjoerg 
4167330f729Sjoerg   return CachedParentName;
4177330f729Sjoerg }
4187330f729Sjoerg 
TakeString()4197330f729Sjoerg CodeCompletionString *CodeCompletionBuilder::TakeString() {
4207330f729Sjoerg   void *Mem = getAllocator().Allocate(
4217330f729Sjoerg       sizeof(CodeCompletionString) + sizeof(Chunk) * Chunks.size() +
4227330f729Sjoerg           sizeof(const char *) * Annotations.size(),
4237330f729Sjoerg       alignof(CodeCompletionString));
4247330f729Sjoerg   CodeCompletionString *Result = new (Mem) CodeCompletionString(
4257330f729Sjoerg       Chunks.data(), Chunks.size(), Priority, Availability, Annotations.data(),
4267330f729Sjoerg       Annotations.size(), ParentName, BriefComment);
4277330f729Sjoerg   Chunks.clear();
4287330f729Sjoerg   return Result;
4297330f729Sjoerg }
4307330f729Sjoerg 
AddTypedTextChunk(const char * Text)4317330f729Sjoerg void CodeCompletionBuilder::AddTypedTextChunk(const char *Text) {
4327330f729Sjoerg   Chunks.push_back(Chunk(CodeCompletionString::CK_TypedText, Text));
4337330f729Sjoerg }
4347330f729Sjoerg 
AddTextChunk(const char * Text)4357330f729Sjoerg void CodeCompletionBuilder::AddTextChunk(const char *Text) {
4367330f729Sjoerg   Chunks.push_back(Chunk::CreateText(Text));
4377330f729Sjoerg }
4387330f729Sjoerg 
AddOptionalChunk(CodeCompletionString * Optional)4397330f729Sjoerg void CodeCompletionBuilder::AddOptionalChunk(CodeCompletionString *Optional) {
4407330f729Sjoerg   Chunks.push_back(Chunk::CreateOptional(Optional));
4417330f729Sjoerg }
4427330f729Sjoerg 
AddPlaceholderChunk(const char * Placeholder)4437330f729Sjoerg void CodeCompletionBuilder::AddPlaceholderChunk(const char *Placeholder) {
4447330f729Sjoerg   Chunks.push_back(Chunk::CreatePlaceholder(Placeholder));
4457330f729Sjoerg }
4467330f729Sjoerg 
AddInformativeChunk(const char * Text)4477330f729Sjoerg void CodeCompletionBuilder::AddInformativeChunk(const char *Text) {
4487330f729Sjoerg   Chunks.push_back(Chunk::CreateInformative(Text));
4497330f729Sjoerg }
4507330f729Sjoerg 
AddResultTypeChunk(const char * ResultType)4517330f729Sjoerg void CodeCompletionBuilder::AddResultTypeChunk(const char *ResultType) {
4527330f729Sjoerg   Chunks.push_back(Chunk::CreateResultType(ResultType));
4537330f729Sjoerg }
4547330f729Sjoerg 
AddCurrentParameterChunk(const char * CurrentParameter)4557330f729Sjoerg void CodeCompletionBuilder::AddCurrentParameterChunk(
4567330f729Sjoerg     const char *CurrentParameter) {
4577330f729Sjoerg   Chunks.push_back(Chunk::CreateCurrentParameter(CurrentParameter));
4587330f729Sjoerg }
4597330f729Sjoerg 
AddChunk(CodeCompletionString::ChunkKind CK,const char * Text)4607330f729Sjoerg void CodeCompletionBuilder::AddChunk(CodeCompletionString::ChunkKind CK,
4617330f729Sjoerg                                      const char *Text) {
4627330f729Sjoerg   Chunks.push_back(Chunk(CK, Text));
4637330f729Sjoerg }
4647330f729Sjoerg 
addParentContext(const DeclContext * DC)4657330f729Sjoerg void CodeCompletionBuilder::addParentContext(const DeclContext *DC) {
4667330f729Sjoerg   if (DC->isTranslationUnit())
4677330f729Sjoerg     return;
4687330f729Sjoerg 
4697330f729Sjoerg   if (DC->isFunctionOrMethod())
4707330f729Sjoerg     return;
4717330f729Sjoerg 
472*e038c9c4Sjoerg   if (!isa<NamedDecl>(DC))
4737330f729Sjoerg     return;
4747330f729Sjoerg 
4757330f729Sjoerg   ParentName = getCodeCompletionTUInfo().getParentName(DC);
4767330f729Sjoerg }
4777330f729Sjoerg 
addBriefComment(StringRef Comment)4787330f729Sjoerg void CodeCompletionBuilder::addBriefComment(StringRef Comment) {
4797330f729Sjoerg   BriefComment = Allocator.CopyString(Comment);
4807330f729Sjoerg }
4817330f729Sjoerg 
4827330f729Sjoerg //===----------------------------------------------------------------------===//
4837330f729Sjoerg // Code completion overload candidate implementation
4847330f729Sjoerg //===----------------------------------------------------------------------===//
getFunction() const4857330f729Sjoerg FunctionDecl *CodeCompleteConsumer::OverloadCandidate::getFunction() const {
4867330f729Sjoerg   if (getKind() == CK_Function)
4877330f729Sjoerg     return Function;
4887330f729Sjoerg   else if (getKind() == CK_FunctionTemplate)
4897330f729Sjoerg     return FunctionTemplate->getTemplatedDecl();
4907330f729Sjoerg   else
4917330f729Sjoerg     return nullptr;
4927330f729Sjoerg }
4937330f729Sjoerg 
4947330f729Sjoerg const FunctionType *
getFunctionType() const4957330f729Sjoerg CodeCompleteConsumer::OverloadCandidate::getFunctionType() const {
4967330f729Sjoerg   switch (Kind) {
4977330f729Sjoerg   case CK_Function:
4987330f729Sjoerg     return Function->getType()->getAs<FunctionType>();
4997330f729Sjoerg 
5007330f729Sjoerg   case CK_FunctionTemplate:
5017330f729Sjoerg     return FunctionTemplate->getTemplatedDecl()
5027330f729Sjoerg         ->getType()
5037330f729Sjoerg         ->getAs<FunctionType>();
5047330f729Sjoerg 
5057330f729Sjoerg   case CK_FunctionType:
5067330f729Sjoerg     return Type;
5077330f729Sjoerg   }
5087330f729Sjoerg 
5097330f729Sjoerg   llvm_unreachable("Invalid CandidateKind!");
5107330f729Sjoerg }
5117330f729Sjoerg 
5127330f729Sjoerg //===----------------------------------------------------------------------===//
5137330f729Sjoerg // Code completion consumer implementation
5147330f729Sjoerg //===----------------------------------------------------------------------===//
5157330f729Sjoerg 
5167330f729Sjoerg CodeCompleteConsumer::~CodeCompleteConsumer() = default;
5177330f729Sjoerg 
isResultFilteredOut(StringRef Filter,CodeCompletionResult Result)5187330f729Sjoerg bool PrintingCodeCompleteConsumer::isResultFilteredOut(
5197330f729Sjoerg     StringRef Filter, CodeCompletionResult Result) {
5207330f729Sjoerg   switch (Result.Kind) {
5217330f729Sjoerg   case CodeCompletionResult::RK_Declaration:
5227330f729Sjoerg     return !(Result.Declaration->getIdentifier() &&
5237330f729Sjoerg              Result.Declaration->getIdentifier()->getName().startswith(Filter));
5247330f729Sjoerg   case CodeCompletionResult::RK_Keyword:
5257330f729Sjoerg     return !StringRef(Result.Keyword).startswith(Filter);
5267330f729Sjoerg   case CodeCompletionResult::RK_Macro:
5277330f729Sjoerg     return !Result.Macro->getName().startswith(Filter);
5287330f729Sjoerg   case CodeCompletionResult::RK_Pattern:
5297330f729Sjoerg     return !(Result.Pattern->getTypedText() &&
5307330f729Sjoerg              StringRef(Result.Pattern->getTypedText()).startswith(Filter));
5317330f729Sjoerg   }
5327330f729Sjoerg   llvm_unreachable("Unknown code completion result Kind.");
5337330f729Sjoerg }
5347330f729Sjoerg 
ProcessCodeCompleteResults(Sema & SemaRef,CodeCompletionContext Context,CodeCompletionResult * Results,unsigned NumResults)5357330f729Sjoerg void PrintingCodeCompleteConsumer::ProcessCodeCompleteResults(
5367330f729Sjoerg     Sema &SemaRef, CodeCompletionContext Context, CodeCompletionResult *Results,
5377330f729Sjoerg     unsigned NumResults) {
5387330f729Sjoerg   std::stable_sort(Results, Results + NumResults);
5397330f729Sjoerg 
5407330f729Sjoerg   if (!Context.getPreferredType().isNull())
5417330f729Sjoerg     OS << "PREFERRED-TYPE: " << Context.getPreferredType().getAsString()
5427330f729Sjoerg        << "\n";
5437330f729Sjoerg 
5447330f729Sjoerg   StringRef Filter = SemaRef.getPreprocessor().getCodeCompletionFilter();
5457330f729Sjoerg   // Print the completions.
5467330f729Sjoerg   for (unsigned I = 0; I != NumResults; ++I) {
5477330f729Sjoerg     if (!Filter.empty() && isResultFilteredOut(Filter, Results[I]))
5487330f729Sjoerg       continue;
5497330f729Sjoerg     OS << "COMPLETION: ";
5507330f729Sjoerg     switch (Results[I].Kind) {
5517330f729Sjoerg     case CodeCompletionResult::RK_Declaration:
5527330f729Sjoerg       OS << *Results[I].Declaration;
5537330f729Sjoerg       {
5547330f729Sjoerg         std::vector<std::string> Tags;
5557330f729Sjoerg         if (Results[I].Hidden)
5567330f729Sjoerg           Tags.push_back("Hidden");
5577330f729Sjoerg         if (Results[I].InBaseClass)
5587330f729Sjoerg           Tags.push_back("InBase");
5597330f729Sjoerg         if (Results[I].Availability ==
5607330f729Sjoerg             CXAvailabilityKind::CXAvailability_NotAccessible)
5617330f729Sjoerg           Tags.push_back("Inaccessible");
5627330f729Sjoerg         if (!Tags.empty())
5637330f729Sjoerg           OS << " (" << llvm::join(Tags, ",") << ")";
5647330f729Sjoerg       }
5657330f729Sjoerg       if (CodeCompletionString *CCS = Results[I].CreateCodeCompletionString(
5667330f729Sjoerg               SemaRef, Context, getAllocator(), CCTUInfo,
5677330f729Sjoerg               includeBriefComments())) {
5687330f729Sjoerg         OS << " : " << CCS->getAsString();
5697330f729Sjoerg         if (const char *BriefComment = CCS->getBriefComment())
5707330f729Sjoerg           OS << " : " << BriefComment;
5717330f729Sjoerg       }
572*e038c9c4Sjoerg       break;
573*e038c9c4Sjoerg 
574*e038c9c4Sjoerg     case CodeCompletionResult::RK_Keyword:
575*e038c9c4Sjoerg       OS << Results[I].Keyword;
576*e038c9c4Sjoerg       break;
577*e038c9c4Sjoerg 
578*e038c9c4Sjoerg     case CodeCompletionResult::RK_Macro:
579*e038c9c4Sjoerg       OS << Results[I].Macro->getName();
580*e038c9c4Sjoerg       if (CodeCompletionString *CCS = Results[I].CreateCodeCompletionString(
581*e038c9c4Sjoerg               SemaRef, Context, getAllocator(), CCTUInfo,
582*e038c9c4Sjoerg               includeBriefComments())) {
583*e038c9c4Sjoerg         OS << " : " << CCS->getAsString();
584*e038c9c4Sjoerg       }
585*e038c9c4Sjoerg       break;
586*e038c9c4Sjoerg 
587*e038c9c4Sjoerg     case CodeCompletionResult::RK_Pattern:
588*e038c9c4Sjoerg       OS << "Pattern : " << Results[I].Pattern->getAsString();
589*e038c9c4Sjoerg       break;
590*e038c9c4Sjoerg     }
5917330f729Sjoerg     for (const FixItHint &FixIt : Results[I].FixIts) {
5927330f729Sjoerg       const SourceLocation BLoc = FixIt.RemoveRange.getBegin();
5937330f729Sjoerg       const SourceLocation ELoc = FixIt.RemoveRange.getEnd();
5947330f729Sjoerg 
5957330f729Sjoerg       SourceManager &SM = SemaRef.SourceMgr;
5967330f729Sjoerg       std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
5977330f729Sjoerg       std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
5987330f729Sjoerg       // Adjust for token ranges.
5997330f729Sjoerg       if (FixIt.RemoveRange.isTokenRange())
6007330f729Sjoerg         EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, SemaRef.LangOpts);
6017330f729Sjoerg 
6027330f729Sjoerg       OS << " (requires fix-it:"
6037330f729Sjoerg          << " {" << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
6047330f729Sjoerg          << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
6057330f729Sjoerg          << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
6067330f729Sjoerg          << SM.getColumnNumber(EInfo.first, EInfo.second) << "}"
6077330f729Sjoerg          << " to \"" << FixIt.CodeToInsert << "\")";
6087330f729Sjoerg     }
6097330f729Sjoerg     OS << '\n';
6107330f729Sjoerg   }
6117330f729Sjoerg }
6127330f729Sjoerg 
6137330f729Sjoerg // This function is used solely to preserve the former presentation of overloads
6147330f729Sjoerg // by "clang -cc1 -code-completion-at", since CodeCompletionString::getAsString
6157330f729Sjoerg // needs to be improved for printing the newer and more detailed overload
6167330f729Sjoerg // chunks.
getOverloadAsString(const CodeCompletionString & CCS)6177330f729Sjoerg static std::string getOverloadAsString(const CodeCompletionString &CCS) {
6187330f729Sjoerg   std::string Result;
6197330f729Sjoerg   llvm::raw_string_ostream OS(Result);
6207330f729Sjoerg 
6217330f729Sjoerg   for (auto &C : CCS) {
6227330f729Sjoerg     switch (C.Kind) {
6237330f729Sjoerg     case CodeCompletionString::CK_Informative:
6247330f729Sjoerg     case CodeCompletionString::CK_ResultType:
6257330f729Sjoerg       OS << "[#" << C.Text << "#]";
6267330f729Sjoerg       break;
6277330f729Sjoerg 
6287330f729Sjoerg     case CodeCompletionString::CK_CurrentParameter:
6297330f729Sjoerg       OS << "<#" << C.Text << "#>";
6307330f729Sjoerg       break;
6317330f729Sjoerg 
6327330f729Sjoerg     // FIXME: We can also print optional parameters of an overload.
6337330f729Sjoerg     case CodeCompletionString::CK_Optional:
6347330f729Sjoerg       break;
6357330f729Sjoerg 
6367330f729Sjoerg     default:
6377330f729Sjoerg       OS << C.Text;
6387330f729Sjoerg       break;
6397330f729Sjoerg     }
6407330f729Sjoerg   }
6417330f729Sjoerg   return OS.str();
6427330f729Sjoerg }
6437330f729Sjoerg 
ProcessOverloadCandidates(Sema & SemaRef,unsigned CurrentArg,OverloadCandidate * Candidates,unsigned NumCandidates,SourceLocation OpenParLoc)6447330f729Sjoerg void PrintingCodeCompleteConsumer::ProcessOverloadCandidates(
6457330f729Sjoerg     Sema &SemaRef, unsigned CurrentArg, OverloadCandidate *Candidates,
6467330f729Sjoerg     unsigned NumCandidates, SourceLocation OpenParLoc) {
6477330f729Sjoerg   OS << "OPENING_PAREN_LOC: ";
6487330f729Sjoerg   OpenParLoc.print(OS, SemaRef.getSourceManager());
6497330f729Sjoerg   OS << "\n";
6507330f729Sjoerg 
6517330f729Sjoerg   for (unsigned I = 0; I != NumCandidates; ++I) {
6527330f729Sjoerg     if (CodeCompletionString *CCS = Candidates[I].CreateSignatureString(
6537330f729Sjoerg             CurrentArg, SemaRef, getAllocator(), CCTUInfo,
6547330f729Sjoerg             includeBriefComments())) {
6557330f729Sjoerg       OS << "OVERLOAD: " << getOverloadAsString(*CCS) << "\n";
6567330f729Sjoerg     }
6577330f729Sjoerg   }
6587330f729Sjoerg }
6597330f729Sjoerg 
6607330f729Sjoerg /// Retrieve the effective availability of the given declaration.
getDeclAvailability(const Decl * D)6617330f729Sjoerg static AvailabilityResult getDeclAvailability(const Decl *D) {
6627330f729Sjoerg   AvailabilityResult AR = D->getAvailability();
6637330f729Sjoerg   if (isa<EnumConstantDecl>(D))
6647330f729Sjoerg     AR = std::max(AR, cast<Decl>(D->getDeclContext())->getAvailability());
6657330f729Sjoerg   return AR;
6667330f729Sjoerg }
6677330f729Sjoerg 
computeCursorKindAndAvailability(bool Accessible)6687330f729Sjoerg void CodeCompletionResult::computeCursorKindAndAvailability(bool Accessible) {
6697330f729Sjoerg   switch (Kind) {
6707330f729Sjoerg   case RK_Pattern:
6717330f729Sjoerg     if (!Declaration) {
6727330f729Sjoerg       // Do nothing: Patterns can come with cursor kinds!
6737330f729Sjoerg       break;
6747330f729Sjoerg     }
6757330f729Sjoerg     LLVM_FALLTHROUGH;
6767330f729Sjoerg 
6777330f729Sjoerg   case RK_Declaration: {
6787330f729Sjoerg     // Set the availability based on attributes.
6797330f729Sjoerg     switch (getDeclAvailability(Declaration)) {
6807330f729Sjoerg     case AR_Available:
6817330f729Sjoerg     case AR_NotYetIntroduced:
6827330f729Sjoerg       Availability = CXAvailability_Available;
6837330f729Sjoerg       break;
6847330f729Sjoerg 
6857330f729Sjoerg     case AR_Deprecated:
6867330f729Sjoerg       Availability = CXAvailability_Deprecated;
6877330f729Sjoerg       break;
6887330f729Sjoerg 
6897330f729Sjoerg     case AR_Unavailable:
6907330f729Sjoerg       Availability = CXAvailability_NotAvailable;
6917330f729Sjoerg       break;
6927330f729Sjoerg     }
6937330f729Sjoerg 
6947330f729Sjoerg     if (const auto *Function = dyn_cast<FunctionDecl>(Declaration))
6957330f729Sjoerg       if (Function->isDeleted())
6967330f729Sjoerg         Availability = CXAvailability_NotAvailable;
6977330f729Sjoerg 
6987330f729Sjoerg     CursorKind = getCursorKindForDecl(Declaration);
6997330f729Sjoerg     if (CursorKind == CXCursor_UnexposedDecl) {
7007330f729Sjoerg       // FIXME: Forward declarations of Objective-C classes and protocols
7017330f729Sjoerg       // are not directly exposed, but we want code completion to treat them
7027330f729Sjoerg       // like a definition.
7037330f729Sjoerg       if (isa<ObjCInterfaceDecl>(Declaration))
7047330f729Sjoerg         CursorKind = CXCursor_ObjCInterfaceDecl;
7057330f729Sjoerg       else if (isa<ObjCProtocolDecl>(Declaration))
7067330f729Sjoerg         CursorKind = CXCursor_ObjCProtocolDecl;
7077330f729Sjoerg       else
7087330f729Sjoerg         CursorKind = CXCursor_NotImplemented;
7097330f729Sjoerg     }
7107330f729Sjoerg     break;
7117330f729Sjoerg   }
7127330f729Sjoerg 
7137330f729Sjoerg   case RK_Macro:
7147330f729Sjoerg   case RK_Keyword:
7157330f729Sjoerg     llvm_unreachable("Macro and keyword kinds are handled by the constructors");
7167330f729Sjoerg   }
7177330f729Sjoerg 
7187330f729Sjoerg   if (!Accessible)
7197330f729Sjoerg     Availability = CXAvailability_NotAccessible;
7207330f729Sjoerg }
7217330f729Sjoerg 
7227330f729Sjoerg /// Retrieve the name that should be used to order a result.
7237330f729Sjoerg ///
7247330f729Sjoerg /// If the name needs to be constructed as a string, that string will be
7257330f729Sjoerg /// saved into Saved and the returned StringRef will refer to it.
getOrderedName(std::string & Saved) const7267330f729Sjoerg StringRef CodeCompletionResult::getOrderedName(std::string &Saved) const {
7277330f729Sjoerg   switch (Kind) {
7287330f729Sjoerg   case RK_Keyword:
7297330f729Sjoerg     return Keyword;
7307330f729Sjoerg   case RK_Pattern:
7317330f729Sjoerg     return Pattern->getTypedText();
7327330f729Sjoerg   case RK_Macro:
7337330f729Sjoerg     return Macro->getName();
7347330f729Sjoerg   case RK_Declaration:
7357330f729Sjoerg     // Handle declarations below.
7367330f729Sjoerg     break;
7377330f729Sjoerg   }
7387330f729Sjoerg 
7397330f729Sjoerg   DeclarationName Name = Declaration->getDeclName();
7407330f729Sjoerg 
7417330f729Sjoerg   // If the name is a simple identifier (by far the common case), or a
7427330f729Sjoerg   // zero-argument selector, just return a reference to that identifier.
7437330f729Sjoerg   if (IdentifierInfo *Id = Name.getAsIdentifierInfo())
7447330f729Sjoerg     return Id->getName();
7457330f729Sjoerg   if (Name.isObjCZeroArgSelector())
7467330f729Sjoerg     if (IdentifierInfo *Id = Name.getObjCSelector().getIdentifierInfoForSlot(0))
7477330f729Sjoerg       return Id->getName();
7487330f729Sjoerg 
7497330f729Sjoerg   Saved = Name.getAsString();
7507330f729Sjoerg   return Saved;
7517330f729Sjoerg }
7527330f729Sjoerg 
operator <(const CodeCompletionResult & X,const CodeCompletionResult & Y)7537330f729Sjoerg bool clang::operator<(const CodeCompletionResult &X,
7547330f729Sjoerg                       const CodeCompletionResult &Y) {
7557330f729Sjoerg   std::string XSaved, YSaved;
7567330f729Sjoerg   StringRef XStr = X.getOrderedName(XSaved);
7577330f729Sjoerg   StringRef YStr = Y.getOrderedName(YSaved);
7587330f729Sjoerg   int cmp = XStr.compare_lower(YStr);
7597330f729Sjoerg   if (cmp)
7607330f729Sjoerg     return cmp < 0;
7617330f729Sjoerg 
7627330f729Sjoerg   // If case-insensitive comparison fails, try case-sensitive comparison.
7637330f729Sjoerg   return XStr.compare(YStr) < 0;
7647330f729Sjoerg }
765