1 //===--- CodeCompleteConsumer.cpp - Code Completion Interface ---*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the CodeCompleteConsumer class.
12 //===----------------------------------------------------------------------===//
13 #include "clang/Sema/CodeCompleteConsumer.h"
14 #include "clang-c/Index.h"
15 #include "clang/AST/DeclCXX.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/DeclTemplate.h"
18 #include "clang/Sema/Scope.h"
19 #include "clang/Sema/Sema.h"
20 #include "clang/Lex/Preprocessor.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/Support/raw_ostream.h"
29 using namespace clang;
31 //===----------------------------------------------------------------------===//
32 // Code completion context implementation
33 //===----------------------------------------------------------------------===//
35 bool CodeCompletionContext::wantConstructorResults() const {
40 case CCC_ObjCMessageReceiver:
41 case CCC_ParenthesizedExpression:
45 case CCC_ObjCInterface:
46 case CCC_ObjCImplementation:
47 case CCC_ObjCIvarList:
48 case CCC_ClassStructUnion:
49 case CCC_DotMemberAccess:
50 case CCC_ArrowMemberAccess:
51 case CCC_ObjCPropertyAccess:
54 case CCC_ClassOrStructTag:
55 case CCC_ObjCProtocolName:
59 case CCC_PotentiallyQualifiedName:
61 case CCC_MacroNameUse:
62 case CCC_PreprocessorExpression:
63 case CCC_PreprocessorDirective:
64 case CCC_NaturalLanguage:
65 case CCC_SelectorName:
66 case CCC_TypeQualifiers:
68 case CCC_OtherWithMacros:
69 case CCC_ObjCInstanceMessage:
70 case CCC_ObjCClassMessage:
71 case CCC_ObjCInterfaceName:
72 case CCC_ObjCCategoryName:
76 llvm_unreachable("Invalid CodeCompletionContext::Kind!");
79 //===----------------------------------------------------------------------===//
80 // Code completion string implementation
81 //===----------------------------------------------------------------------===//
82 CodeCompletionString::Chunk::Chunk(ChunkKind Kind, const char *Text)
83 : Kind(Kind), Text("")
91 case CK_CurrentParameter:
96 llvm_unreachable("Optional strings cannot be created from text");
110 case CK_RightBracket:
146 case CK_HorizontalSpace:
150 case CK_VerticalSpace:
156 CodeCompletionString::Chunk
157 CodeCompletionString::Chunk::CreateText(const char *Text) {
158 return Chunk(CK_Text, Text);
161 CodeCompletionString::Chunk
162 CodeCompletionString::Chunk::CreateOptional(CodeCompletionString *Optional) {
164 Result.Kind = CK_Optional;
165 Result.Optional = Optional;
169 CodeCompletionString::Chunk
170 CodeCompletionString::Chunk::CreatePlaceholder(const char *Placeholder) {
171 return Chunk(CK_Placeholder, Placeholder);
174 CodeCompletionString::Chunk
175 CodeCompletionString::Chunk::CreateInformative(const char *Informative) {
176 return Chunk(CK_Informative, Informative);
179 CodeCompletionString::Chunk
180 CodeCompletionString::Chunk::CreateResultType(const char *ResultType) {
181 return Chunk(CK_ResultType, ResultType);
184 CodeCompletionString::Chunk
185 CodeCompletionString::Chunk::CreateCurrentParameter(
186 const char *CurrentParameter) {
187 return Chunk(CK_CurrentParameter, CurrentParameter);
190 CodeCompletionString::CodeCompletionString(const Chunk *Chunks,
193 CXAvailabilityKind Availability,
194 const char **Annotations,
195 unsigned NumAnnotations,
196 StringRef ParentName,
197 const char *BriefComment)
198 : NumChunks(NumChunks), NumAnnotations(NumAnnotations),
199 Priority(Priority), Availability(Availability),
200 ParentName(ParentName), BriefComment(BriefComment)
202 assert(NumChunks <= 0xffff);
203 assert(NumAnnotations <= 0xffff);
205 Chunk *StoredChunks = reinterpret_cast<Chunk *>(this + 1);
206 for (unsigned I = 0; I != NumChunks; ++I)
207 StoredChunks[I] = Chunks[I];
209 const char **StoredAnnotations = reinterpret_cast<const char **>(StoredChunks + NumChunks);
210 for (unsigned I = 0; I != NumAnnotations; ++I)
211 StoredAnnotations[I] = Annotations[I];
214 unsigned CodeCompletionString::getAnnotationCount() const {
215 return NumAnnotations;
218 const char *CodeCompletionString::getAnnotation(unsigned AnnotationNr) const {
219 if (AnnotationNr < NumAnnotations)
220 return reinterpret_cast<const char * const*>(end())[AnnotationNr];
226 std::string CodeCompletionString::getAsString() const {
228 llvm::raw_string_ostream OS(Result);
230 for (iterator C = begin(), CEnd = end(); C != CEnd; ++C) {
232 case CK_Optional: OS << "{#" << C->Optional->getAsString() << "#}"; break;
233 case CK_Placeholder: OS << "<#" << C->Text << "#>"; break;
237 OS << "[#" << C->Text << "#]";
240 case CK_CurrentParameter: OS << "<#" << C->Text << "#>"; break;
241 default: OS << C->Text; break;
247 const char *CodeCompletionString::getTypedText() const {
248 for (iterator C = begin(), CEnd = end(); C != CEnd; ++C)
249 if (C->Kind == CK_TypedText)
255 const char *CodeCompletionAllocator::CopyString(const Twine &String) {
256 SmallString<128> Data;
257 StringRef Ref = String.toStringRef(Data);
258 // FIXME: It would be more efficient to teach Twine to tell us its size and
259 // then add a routine there to fill in an allocated char* with the contents
261 char *Mem = (char *)Allocate(Ref.size() + 1, 1);
262 std::copy(Ref.begin(), Ref.end(), Mem);
267 StringRef CodeCompletionTUInfo::getParentName(const DeclContext *DC) {
268 const NamedDecl *ND = dyn_cast<NamedDecl>(DC);
272 // Check whether we've already cached the parent name.
273 StringRef &CachedParentName = ParentNames[DC];
274 if (!CachedParentName.empty())
275 return CachedParentName;
277 // If we already processed this DeclContext and assigned empty to it, the
278 // data pointer will be non-null.
279 if (CachedParentName.data() != nullptr)
282 // Find the interesting names.
283 SmallVector<const DeclContext *, 2> Contexts;
284 while (DC && !DC->isFunctionOrMethod()) {
285 if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC)) {
286 if (ND->getIdentifier())
287 Contexts.push_back(DC);
290 DC = DC->getParent();
295 llvm::raw_svector_ostream OS(S);
297 for (unsigned I = Contexts.size(); I != 0; --I) {
304 const DeclContext *CurDC = Contexts[I-1];
305 if (const ObjCCategoryImplDecl *CatImpl = dyn_cast<ObjCCategoryImplDecl>(CurDC))
306 CurDC = CatImpl->getCategoryDecl();
308 if (const ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(CurDC)) {
309 const ObjCInterfaceDecl *Interface = Cat->getClassInterface();
311 // Assign an empty StringRef but with non-null data to distinguish
312 // between empty because we didn't process the DeclContext yet.
313 CachedParentName = StringRef((const char *)(uintptr_t)~0U, 0);
317 OS << Interface->getName() << '(' << Cat->getName() << ')';
319 OS << cast<NamedDecl>(CurDC)->getName();
323 CachedParentName = AllocatorRef->CopyString(OS.str());
326 return CachedParentName;
329 CodeCompletionString *CodeCompletionBuilder::TakeString() {
330 void *Mem = getAllocator().Allocate(
331 sizeof(CodeCompletionString) + sizeof(Chunk) * Chunks.size() +
332 sizeof(const char *) * Annotations.size(),
333 alignof(CodeCompletionString));
334 CodeCompletionString *Result
335 = new (Mem) CodeCompletionString(Chunks.data(), Chunks.size(),
336 Priority, Availability,
337 Annotations.data(), Annotations.size(),
338 ParentName, BriefComment);
343 void CodeCompletionBuilder::AddTypedTextChunk(const char *Text) {
344 Chunks.push_back(Chunk(CodeCompletionString::CK_TypedText, Text));
347 void CodeCompletionBuilder::AddTextChunk(const char *Text) {
348 Chunks.push_back(Chunk::CreateText(Text));
351 void CodeCompletionBuilder::AddOptionalChunk(CodeCompletionString *Optional) {
352 Chunks.push_back(Chunk::CreateOptional(Optional));
355 void CodeCompletionBuilder::AddPlaceholderChunk(const char *Placeholder) {
356 Chunks.push_back(Chunk::CreatePlaceholder(Placeholder));
359 void CodeCompletionBuilder::AddInformativeChunk(const char *Text) {
360 Chunks.push_back(Chunk::CreateInformative(Text));
363 void CodeCompletionBuilder::AddResultTypeChunk(const char *ResultType) {
364 Chunks.push_back(Chunk::CreateResultType(ResultType));
368 CodeCompletionBuilder::AddCurrentParameterChunk(const char *CurrentParameter) {
369 Chunks.push_back(Chunk::CreateCurrentParameter(CurrentParameter));
372 void CodeCompletionBuilder::AddChunk(CodeCompletionString::ChunkKind CK,
374 Chunks.push_back(Chunk(CK, Text));
377 void CodeCompletionBuilder::addParentContext(const DeclContext *DC) {
378 if (DC->isTranslationUnit()) {
382 if (DC->isFunctionOrMethod())
385 const NamedDecl *ND = dyn_cast<NamedDecl>(DC);
389 ParentName = getCodeCompletionTUInfo().getParentName(DC);
392 void CodeCompletionBuilder::addBriefComment(StringRef Comment) {
393 BriefComment = Allocator.CopyString(Comment);
396 //===----------------------------------------------------------------------===//
397 // Code completion overload candidate implementation
398 //===----------------------------------------------------------------------===//
400 CodeCompleteConsumer::OverloadCandidate::getFunction() const {
401 if (getKind() == CK_Function)
403 else if (getKind() == CK_FunctionTemplate)
404 return FunctionTemplate->getTemplatedDecl();
410 CodeCompleteConsumer::OverloadCandidate::getFunctionType() const {
413 return Function->getType()->getAs<FunctionType>();
415 case CK_FunctionTemplate:
416 return FunctionTemplate->getTemplatedDecl()->getType()
417 ->getAs<FunctionType>();
419 case CK_FunctionType:
423 llvm_unreachable("Invalid CandidateKind!");
426 //===----------------------------------------------------------------------===//
427 // Code completion consumer implementation
428 //===----------------------------------------------------------------------===//
430 CodeCompleteConsumer::~CodeCompleteConsumer() { }
432 bool PrintingCodeCompleteConsumer::isResultFilteredOut(StringRef Filter,
433 CodeCompletionResult Result) {
434 switch (Result.Kind) {
435 case CodeCompletionResult::RK_Declaration: {
436 return !(Result.Declaration->getIdentifier() &&
437 Result.Declaration->getIdentifier()->getName().startswith(Filter));
439 case CodeCompletionResult::RK_Keyword: {
440 return !StringRef(Result.Keyword).startswith(Filter);
442 case CodeCompletionResult::RK_Macro: {
443 return !Result.Macro->getName().startswith(Filter);
445 case CodeCompletionResult::RK_Pattern: {
446 return !StringRef(Result.Pattern->getAsString()).startswith(Filter);
449 llvm_unreachable("Unknown code completion result Kind.");
453 PrintingCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &SemaRef,
454 CodeCompletionContext Context,
455 CodeCompletionResult *Results,
456 unsigned NumResults) {
457 std::stable_sort(Results, Results + NumResults);
459 StringRef Filter = SemaRef.getPreprocessor().getCodeCompletionFilter();
461 // Print the results.
462 for (unsigned I = 0; I != NumResults; ++I) {
463 if(!Filter.empty() && isResultFilteredOut(Filter, Results[I]))
465 OS << "COMPLETION: ";
466 switch (Results[I].Kind) {
467 case CodeCompletionResult::RK_Declaration:
468 OS << *Results[I].Declaration;
469 if (Results[I].Hidden)
471 if (CodeCompletionString *CCS
472 = Results[I].CreateCodeCompletionString(SemaRef, Context,
475 includeBriefComments())) {
476 OS << " : " << CCS->getAsString();
477 if (const char *BriefComment = CCS->getBriefComment())
478 OS << " : " << BriefComment;
484 case CodeCompletionResult::RK_Keyword:
485 OS << Results[I].Keyword << '\n';
488 case CodeCompletionResult::RK_Macro: {
489 OS << Results[I].Macro->getName();
490 if (CodeCompletionString *CCS
491 = Results[I].CreateCodeCompletionString(SemaRef, Context,
494 includeBriefComments())) {
495 OS << " : " << CCS->getAsString();
501 case CodeCompletionResult::RK_Pattern: {
503 << Results[I].Pattern->getAsString() << '\n';
510 // This function is used solely to preserve the former presentation of overloads
511 // by "clang -cc1 -code-completion-at", since CodeCompletionString::getAsString
512 // needs to be improved for printing the newer and more detailed overload
514 static std::string getOverloadAsString(const CodeCompletionString &CCS) {
516 llvm::raw_string_ostream OS(Result);
518 for (auto &C : CCS) {
520 case CodeCompletionString::CK_Informative:
521 case CodeCompletionString::CK_ResultType:
522 OS << "[#" << C.Text << "#]";
525 case CodeCompletionString::CK_CurrentParameter:
526 OS << "<#" << C.Text << "#>";
529 default: OS << C.Text; break;
536 PrintingCodeCompleteConsumer::ProcessOverloadCandidates(Sema &SemaRef,
538 OverloadCandidate *Candidates,
539 unsigned NumCandidates) {
540 for (unsigned I = 0; I != NumCandidates; ++I) {
541 if (CodeCompletionString *CCS
542 = Candidates[I].CreateSignatureString(CurrentArg, SemaRef,
543 getAllocator(), CCTUInfo,
544 includeBriefComments())) {
545 OS << "OVERLOAD: " << getOverloadAsString(*CCS) << "\n";
550 /// \brief Retrieve the effective availability of the given declaration.
551 static AvailabilityResult getDeclAvailability(const Decl *D) {
552 AvailabilityResult AR = D->getAvailability();
553 if (isa<EnumConstantDecl>(D))
554 AR = std::max(AR, cast<Decl>(D->getDeclContext())->getAvailability());
558 void CodeCompletionResult::computeCursorKindAndAvailability(bool Accessible) {
562 // Do nothing: Patterns can come with cursor kinds!
567 case RK_Declaration: {
568 // Set the availability based on attributes.
569 switch (getDeclAvailability(Declaration)) {
571 case AR_NotYetIntroduced:
572 Availability = CXAvailability_Available;
576 Availability = CXAvailability_Deprecated;
580 Availability = CXAvailability_NotAvailable;
584 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Declaration))
585 if (Function->isDeleted())
586 Availability = CXAvailability_NotAvailable;
588 CursorKind = getCursorKindForDecl(Declaration);
589 if (CursorKind == CXCursor_UnexposedDecl) {
590 // FIXME: Forward declarations of Objective-C classes and protocols
591 // are not directly exposed, but we want code completion to treat them
592 // like a definition.
593 if (isa<ObjCInterfaceDecl>(Declaration))
594 CursorKind = CXCursor_ObjCInterfaceDecl;
595 else if (isa<ObjCProtocolDecl>(Declaration))
596 CursorKind = CXCursor_ObjCProtocolDecl;
598 CursorKind = CXCursor_NotImplemented;
605 llvm_unreachable("Macro and keyword kinds are handled by the constructors");
609 Availability = CXAvailability_NotAccessible;
612 /// \brief Retrieve the name that should be used to order a result.
614 /// If the name needs to be constructed as a string, that string will be
615 /// saved into Saved and the returned StringRef will refer to it.
616 static StringRef getOrderedName(const CodeCompletionResult &R,
617 std::string &Saved) {
619 case CodeCompletionResult::RK_Keyword:
622 case CodeCompletionResult::RK_Pattern:
623 return R.Pattern->getTypedText();
625 case CodeCompletionResult::RK_Macro:
626 return R.Macro->getName();
628 case CodeCompletionResult::RK_Declaration:
629 // Handle declarations below.
633 DeclarationName Name = R.Declaration->getDeclName();
635 // If the name is a simple identifier (by far the common case), or a
636 // zero-argument selector, just return a reference to that identifier.
637 if (IdentifierInfo *Id = Name.getAsIdentifierInfo())
638 return Id->getName();
639 if (Name.isObjCZeroArgSelector())
640 if (IdentifierInfo *Id
641 = Name.getObjCSelector().getIdentifierInfoForSlot(0))
642 return Id->getName();
644 Saved = Name.getAsString();
648 bool clang::operator<(const CodeCompletionResult &X,
649 const CodeCompletionResult &Y) {
650 std::string XSaved, YSaved;
651 StringRef XStr = getOrderedName(X, XSaved);
652 StringRef YStr = getOrderedName(Y, YSaved);
653 int cmp = XStr.compare_lower(YStr);
657 // If case-insensitive comparison fails, try case-sensitive comparison.
658 cmp = XStr.compare(YStr);