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 "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/Support/raw_ostream.h"
28 using namespace clang;
30 //===----------------------------------------------------------------------===//
31 // Code completion context implementation
32 //===----------------------------------------------------------------------===//
34 bool CodeCompletionContext::wantConstructorResults() const {
39 case CCC_ObjCMessageReceiver:
40 case CCC_ParenthesizedExpression:
44 case CCC_ObjCInterface:
45 case CCC_ObjCImplementation:
46 case CCC_ObjCIvarList:
47 case CCC_ClassStructUnion:
48 case CCC_DotMemberAccess:
49 case CCC_ArrowMemberAccess:
50 case CCC_ObjCPropertyAccess:
53 case CCC_ClassOrStructTag:
54 case CCC_ObjCProtocolName:
58 case CCC_PotentiallyQualifiedName:
60 case CCC_MacroNameUse:
61 case CCC_PreprocessorExpression:
62 case CCC_PreprocessorDirective:
63 case CCC_NaturalLanguage:
64 case CCC_SelectorName:
65 case CCC_TypeQualifiers:
67 case CCC_OtherWithMacros:
68 case CCC_ObjCInstanceMessage:
69 case CCC_ObjCClassMessage:
70 case CCC_ObjCInterfaceName:
71 case CCC_ObjCCategoryName:
75 llvm_unreachable("Invalid CodeCompletionContext::Kind!");
78 //===----------------------------------------------------------------------===//
79 // Code completion string implementation
80 //===----------------------------------------------------------------------===//
81 CodeCompletionString::Chunk::Chunk(ChunkKind Kind, const char *Text)
82 : Kind(Kind), Text("")
90 case CK_CurrentParameter:
95 llvm_unreachable("Optional strings cannot be created from text");
109 case CK_RightBracket:
145 case CK_HorizontalSpace:
149 case CK_VerticalSpace:
155 CodeCompletionString::Chunk
156 CodeCompletionString::Chunk::CreateText(const char *Text) {
157 return Chunk(CK_Text, Text);
160 CodeCompletionString::Chunk
161 CodeCompletionString::Chunk::CreateOptional(CodeCompletionString *Optional) {
163 Result.Kind = CK_Optional;
164 Result.Optional = Optional;
168 CodeCompletionString::Chunk
169 CodeCompletionString::Chunk::CreatePlaceholder(const char *Placeholder) {
170 return Chunk(CK_Placeholder, Placeholder);
173 CodeCompletionString::Chunk
174 CodeCompletionString::Chunk::CreateInformative(const char *Informative) {
175 return Chunk(CK_Informative, Informative);
178 CodeCompletionString::Chunk
179 CodeCompletionString::Chunk::CreateResultType(const char *ResultType) {
180 return Chunk(CK_ResultType, ResultType);
183 CodeCompletionString::Chunk
184 CodeCompletionString::Chunk::CreateCurrentParameter(
185 const char *CurrentParameter) {
186 return Chunk(CK_CurrentParameter, CurrentParameter);
189 CodeCompletionString::CodeCompletionString(const Chunk *Chunks,
192 CXAvailabilityKind Availability,
193 const char **Annotations,
194 unsigned NumAnnotations,
195 StringRef ParentName,
196 const char *BriefComment)
197 : NumChunks(NumChunks), NumAnnotations(NumAnnotations),
198 Priority(Priority), Availability(Availability),
199 ParentName(ParentName), BriefComment(BriefComment)
201 assert(NumChunks <= 0xffff);
202 assert(NumAnnotations <= 0xffff);
204 Chunk *StoredChunks = reinterpret_cast<Chunk *>(this + 1);
205 for (unsigned I = 0; I != NumChunks; ++I)
206 StoredChunks[I] = Chunks[I];
208 const char **StoredAnnotations = reinterpret_cast<const char **>(StoredChunks + NumChunks);
209 for (unsigned I = 0; I != NumAnnotations; ++I)
210 StoredAnnotations[I] = Annotations[I];
213 unsigned CodeCompletionString::getAnnotationCount() const {
214 return NumAnnotations;
217 const char *CodeCompletionString::getAnnotation(unsigned AnnotationNr) const {
218 if (AnnotationNr < NumAnnotations)
219 return reinterpret_cast<const char * const*>(end())[AnnotationNr];
225 std::string CodeCompletionString::getAsString() const {
227 llvm::raw_string_ostream OS(Result);
229 for (iterator C = begin(), CEnd = end(); C != CEnd; ++C) {
231 case CK_Optional: OS << "{#" << C->Optional->getAsString() << "#}"; break;
232 case CK_Placeholder: OS << "<#" << C->Text << "#>"; break;
236 OS << "[#" << C->Text << "#]";
239 case CK_CurrentParameter: OS << "<#" << C->Text << "#>"; break;
240 default: OS << C->Text; break;
246 const char *CodeCompletionString::getTypedText() const {
247 for (iterator C = begin(), CEnd = end(); C != CEnd; ++C)
248 if (C->Kind == CK_TypedText)
254 const char *CodeCompletionAllocator::CopyString(const Twine &String) {
255 SmallString<128> Data;
256 StringRef Ref = String.toStringRef(Data);
257 // FIXME: It would be more efficient to teach Twine to tell us its size and
258 // then add a routine there to fill in an allocated char* with the contents
260 char *Mem = (char *)Allocate(Ref.size() + 1, 1);
261 std::copy(Ref.begin(), Ref.end(), Mem);
266 StringRef CodeCompletionTUInfo::getParentName(const DeclContext *DC) {
267 const NamedDecl *ND = dyn_cast<NamedDecl>(DC);
271 // Check whether we've already cached the parent name.
272 StringRef &CachedParentName = ParentNames[DC];
273 if (!CachedParentName.empty())
274 return CachedParentName;
276 // If we already processed this DeclContext and assigned empty to it, the
277 // data pointer will be non-null.
278 if (CachedParentName.data() != nullptr)
281 // Find the interesting names.
282 SmallVector<const DeclContext *, 2> Contexts;
283 while (DC && !DC->isFunctionOrMethod()) {
284 if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC)) {
285 if (ND->getIdentifier())
286 Contexts.push_back(DC);
289 DC = DC->getParent();
294 llvm::raw_svector_ostream OS(S);
296 for (unsigned I = Contexts.size(); I != 0; --I) {
303 const DeclContext *CurDC = Contexts[I-1];
304 if (const ObjCCategoryImplDecl *CatImpl = dyn_cast<ObjCCategoryImplDecl>(CurDC))
305 CurDC = CatImpl->getCategoryDecl();
307 if (const ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(CurDC)) {
308 const ObjCInterfaceDecl *Interface = Cat->getClassInterface();
310 // Assign an empty StringRef but with non-null data to distinguish
311 // between empty because we didn't process the DeclContext yet.
312 CachedParentName = StringRef((const char *)~0U, 0);
316 OS << Interface->getName() << '(' << Cat->getName() << ')';
318 OS << cast<NamedDecl>(CurDC)->getName();
322 CachedParentName = AllocatorRef->CopyString(OS.str());
325 return CachedParentName;
328 CodeCompletionString *CodeCompletionBuilder::TakeString() {
329 void *Mem = getAllocator().Allocate(
330 sizeof(CodeCompletionString) + sizeof(Chunk) * Chunks.size()
331 + sizeof(const char *) * Annotations.size(),
332 llvm::alignOf<CodeCompletionString>());
333 CodeCompletionString *Result
334 = new (Mem) CodeCompletionString(Chunks.data(), Chunks.size(),
335 Priority, Availability,
336 Annotations.data(), Annotations.size(),
337 ParentName, BriefComment);
342 void CodeCompletionBuilder::AddTypedTextChunk(const char *Text) {
343 Chunks.push_back(Chunk(CodeCompletionString::CK_TypedText, Text));
346 void CodeCompletionBuilder::AddTextChunk(const char *Text) {
347 Chunks.push_back(Chunk::CreateText(Text));
350 void CodeCompletionBuilder::AddOptionalChunk(CodeCompletionString *Optional) {
351 Chunks.push_back(Chunk::CreateOptional(Optional));
354 void CodeCompletionBuilder::AddPlaceholderChunk(const char *Placeholder) {
355 Chunks.push_back(Chunk::CreatePlaceholder(Placeholder));
358 void CodeCompletionBuilder::AddInformativeChunk(const char *Text) {
359 Chunks.push_back(Chunk::CreateInformative(Text));
362 void CodeCompletionBuilder::AddResultTypeChunk(const char *ResultType) {
363 Chunks.push_back(Chunk::CreateResultType(ResultType));
367 CodeCompletionBuilder::AddCurrentParameterChunk(const char *CurrentParameter) {
368 Chunks.push_back(Chunk::CreateCurrentParameter(CurrentParameter));
371 void CodeCompletionBuilder::AddChunk(CodeCompletionString::ChunkKind CK,
373 Chunks.push_back(Chunk(CK, Text));
376 void CodeCompletionBuilder::addParentContext(const DeclContext *DC) {
377 if (DC->isTranslationUnit()) {
381 if (DC->isFunctionOrMethod())
384 const NamedDecl *ND = dyn_cast<NamedDecl>(DC);
388 ParentName = getCodeCompletionTUInfo().getParentName(DC);
391 void CodeCompletionBuilder::addBriefComment(StringRef Comment) {
392 BriefComment = Allocator.CopyString(Comment);
395 //===----------------------------------------------------------------------===//
396 // Code completion overload candidate implementation
397 //===----------------------------------------------------------------------===//
399 CodeCompleteConsumer::OverloadCandidate::getFunction() const {
400 if (getKind() == CK_Function)
402 else if (getKind() == CK_FunctionTemplate)
403 return FunctionTemplate->getTemplatedDecl();
409 CodeCompleteConsumer::OverloadCandidate::getFunctionType() const {
412 return Function->getType()->getAs<FunctionType>();
414 case CK_FunctionTemplate:
415 return FunctionTemplate->getTemplatedDecl()->getType()
416 ->getAs<FunctionType>();
418 case CK_FunctionType:
422 llvm_unreachable("Invalid CandidateKind!");
425 //===----------------------------------------------------------------------===//
426 // Code completion consumer implementation
427 //===----------------------------------------------------------------------===//
429 CodeCompleteConsumer::~CodeCompleteConsumer() { }
432 PrintingCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &SemaRef,
433 CodeCompletionContext Context,
434 CodeCompletionResult *Results,
435 unsigned NumResults) {
436 std::stable_sort(Results, Results + NumResults);
438 // Print the results.
439 for (unsigned I = 0; I != NumResults; ++I) {
440 OS << "COMPLETION: ";
441 switch (Results[I].Kind) {
442 case CodeCompletionResult::RK_Declaration:
443 OS << *Results[I].Declaration;
444 if (Results[I].Hidden)
446 if (CodeCompletionString *CCS
447 = Results[I].CreateCodeCompletionString(SemaRef, Context,
450 includeBriefComments())) {
451 OS << " : " << CCS->getAsString();
452 if (const char *BriefComment = CCS->getBriefComment())
453 OS << " : " << BriefComment;
459 case CodeCompletionResult::RK_Keyword:
460 OS << Results[I].Keyword << '\n';
463 case CodeCompletionResult::RK_Macro: {
464 OS << Results[I].Macro->getName();
465 if (CodeCompletionString *CCS
466 = Results[I].CreateCodeCompletionString(SemaRef, Context,
469 includeBriefComments())) {
470 OS << " : " << CCS->getAsString();
476 case CodeCompletionResult::RK_Pattern: {
478 << Results[I].Pattern->getAsString() << '\n';
485 // This function is used solely to preserve the former presentation of overloads
486 // by "clang -cc1 -code-completion-at", since CodeCompletionString::getAsString
487 // needs to be improved for printing the newer and more detailed overload
489 static std::string getOverloadAsString(const CodeCompletionString &CCS) {
491 llvm::raw_string_ostream OS(Result);
493 for (auto &C : CCS) {
495 case CodeCompletionString::CK_Informative:
496 case CodeCompletionString::CK_ResultType:
497 OS << "[#" << C.Text << "#]";
500 case CodeCompletionString::CK_CurrentParameter:
501 OS << "<#" << C.Text << "#>";
504 default: OS << C.Text; break;
511 PrintingCodeCompleteConsumer::ProcessOverloadCandidates(Sema &SemaRef,
513 OverloadCandidate *Candidates,
514 unsigned NumCandidates) {
515 for (unsigned I = 0; I != NumCandidates; ++I) {
516 if (CodeCompletionString *CCS
517 = Candidates[I].CreateSignatureString(CurrentArg, SemaRef,
518 getAllocator(), CCTUInfo,
519 includeBriefComments())) {
520 OS << "OVERLOAD: " << getOverloadAsString(*CCS) << "\n";
525 /// \brief Retrieve the effective availability of the given declaration.
526 static AvailabilityResult getDeclAvailability(const Decl *D) {
527 AvailabilityResult AR = D->getAvailability();
528 if (isa<EnumConstantDecl>(D))
529 AR = std::max(AR, cast<Decl>(D->getDeclContext())->getAvailability());
533 void CodeCompletionResult::computeCursorKindAndAvailability(bool Accessible) {
537 // Do nothing: Patterns can come with cursor kinds!
542 case RK_Declaration: {
543 // Set the availability based on attributes.
544 switch (getDeclAvailability(Declaration)) {
546 case AR_NotYetIntroduced:
547 Availability = CXAvailability_Available;
551 Availability = CXAvailability_Deprecated;
555 Availability = CXAvailability_NotAvailable;
559 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Declaration))
560 if (Function->isDeleted())
561 Availability = CXAvailability_NotAvailable;
563 CursorKind = getCursorKindForDecl(Declaration);
564 if (CursorKind == CXCursor_UnexposedDecl) {
565 // FIXME: Forward declarations of Objective-C classes and protocols
566 // are not directly exposed, but we want code completion to treat them
567 // like a definition.
568 if (isa<ObjCInterfaceDecl>(Declaration))
569 CursorKind = CXCursor_ObjCInterfaceDecl;
570 else if (isa<ObjCProtocolDecl>(Declaration))
571 CursorKind = CXCursor_ObjCProtocolDecl;
573 CursorKind = CXCursor_NotImplemented;
580 llvm_unreachable("Macro and keyword kinds are handled by the constructors");
584 Availability = CXAvailability_NotAccessible;
587 /// \brief Retrieve the name that should be used to order a result.
589 /// If the name needs to be constructed as a string, that string will be
590 /// saved into Saved and the returned StringRef will refer to it.
591 static StringRef getOrderedName(const CodeCompletionResult &R,
592 std::string &Saved) {
594 case CodeCompletionResult::RK_Keyword:
597 case CodeCompletionResult::RK_Pattern:
598 return R.Pattern->getTypedText();
600 case CodeCompletionResult::RK_Macro:
601 return R.Macro->getName();
603 case CodeCompletionResult::RK_Declaration:
604 // Handle declarations below.
608 DeclarationName Name = R.Declaration->getDeclName();
610 // If the name is a simple identifier (by far the common case), or a
611 // zero-argument selector, just return a reference to that identifier.
612 if (IdentifierInfo *Id = Name.getAsIdentifierInfo())
613 return Id->getName();
614 if (Name.isObjCZeroArgSelector())
615 if (IdentifierInfo *Id
616 = Name.getObjCSelector().getIdentifierInfoForSlot(0))
617 return Id->getName();
619 Saved = Name.getAsString();
623 bool clang::operator<(const CodeCompletionResult &X,
624 const CodeCompletionResult &Y) {
625 std::string XSaved, YSaved;
626 StringRef XStr = getOrderedName(X, XSaved);
627 StringRef YStr = getOrderedName(Y, YSaved);
628 int cmp = XStr.compare_lower(YStr);
632 // If case-insensitive comparison fails, try case-sensitive comparison.
633 cmp = XStr.compare(YStr);