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/Sema/Scope.h"
15 #include "clang/Sema/Sema.h"
16 #include "clang/AST/DeclCXX.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/Lex/Preprocessor.h"
20 #include "clang-c/Index.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/STLExtras.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 CXCursorKind ParentKind,
197 StringRef ParentName)
198 : NumChunks(NumChunks), NumAnnotations(NumAnnotations),
199 Priority(Priority), Availability(Availability), ParentKind(ParentKind),
200 ParentName(ParentName)
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(StringRef String) {
256 char *Mem = (char *)Allocate(String.size() + 1, 1);
257 std::copy(String.begin(), String.end(), Mem);
258 Mem[String.size()] = 0;
262 const char *CodeCompletionAllocator::CopyString(Twine String) {
263 // FIXME: It would be more efficient to teach Twine to tell us its size and
264 // then add a routine there to fill in an allocated char* with the contents
266 SmallString<128> Data;
267 return CopyString(String.toStringRef(Data));
270 StringRef CodeCompletionTUInfo::getParentName(DeclContext *DC) {
271 NamedDecl *ND = dyn_cast<NamedDecl>(DC);
275 // Check whether we've already cached the parent name.
276 StringRef &CachedParentName = ParentNames[DC];
277 if (!CachedParentName.empty())
278 return CachedParentName;
280 // If we already processed this DeclContext and assigned empty to it, the
281 // data pointer will be non-null.
282 if (CachedParentName.data() != 0)
285 // Find the interesting names.
286 llvm::SmallVector<DeclContext *, 2> Contexts;
287 while (DC && !DC->isFunctionOrMethod()) {
288 if (NamedDecl *ND = dyn_cast<NamedDecl>(DC)) {
289 if (ND->getIdentifier())
290 Contexts.push_back(DC);
293 DC = DC->getParent();
297 llvm::SmallString<128> S;
298 llvm::raw_svector_ostream OS(S);
300 for (unsigned I = Contexts.size(); I != 0; --I) {
307 DeclContext *CurDC = Contexts[I-1];
308 if (ObjCCategoryImplDecl *CatImpl = dyn_cast<ObjCCategoryImplDecl>(CurDC))
309 CurDC = CatImpl->getCategoryDecl();
311 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(CurDC)) {
312 ObjCInterfaceDecl *Interface = Cat->getClassInterface();
314 // Assign an empty StringRef but with non-null data to distinguish
315 // between empty because we didn't process the DeclContext yet.
316 CachedParentName = StringRef((const char *)~0U, 0);
320 OS << Interface->getName() << '(' << Cat->getName() << ')';
322 OS << cast<NamedDecl>(CurDC)->getName();
326 CachedParentName = AllocatorRef->CopyString(OS.str());
329 return CachedParentName;
332 CodeCompletionString *CodeCompletionBuilder::TakeString() {
333 void *Mem = getAllocator().Allocate(
334 sizeof(CodeCompletionString) + sizeof(Chunk) * Chunks.size()
335 + sizeof(const char *) * Annotations.size(),
336 llvm::alignOf<CodeCompletionString>());
337 CodeCompletionString *Result
338 = new (Mem) CodeCompletionString(Chunks.data(), Chunks.size(),
339 Priority, Availability,
340 Annotations.data(), Annotations.size(),
341 ParentKind, ParentName);
346 void CodeCompletionBuilder::AddTypedTextChunk(const char *Text) {
347 Chunks.push_back(Chunk(CodeCompletionString::CK_TypedText, Text));
350 void CodeCompletionBuilder::AddTextChunk(const char *Text) {
351 Chunks.push_back(Chunk::CreateText(Text));
354 void CodeCompletionBuilder::AddOptionalChunk(CodeCompletionString *Optional) {
355 Chunks.push_back(Chunk::CreateOptional(Optional));
358 void CodeCompletionBuilder::AddPlaceholderChunk(const char *Placeholder) {
359 Chunks.push_back(Chunk::CreatePlaceholder(Placeholder));
362 void CodeCompletionBuilder::AddInformativeChunk(const char *Text) {
363 Chunks.push_back(Chunk::CreateInformative(Text));
366 void CodeCompletionBuilder::AddResultTypeChunk(const char *ResultType) {
367 Chunks.push_back(Chunk::CreateResultType(ResultType));
371 CodeCompletionBuilder::AddCurrentParameterChunk(const char *CurrentParameter) {
372 Chunks.push_back(Chunk::CreateCurrentParameter(CurrentParameter));
375 void CodeCompletionBuilder::AddChunk(CodeCompletionString::ChunkKind CK,
377 Chunks.push_back(Chunk(CK, Text));
380 void CodeCompletionBuilder::addParentContext(DeclContext *DC) {
381 if (DC->isTranslationUnit()) {
382 ParentKind = CXCursor_TranslationUnit;
386 if (DC->isFunctionOrMethod())
389 NamedDecl *ND = dyn_cast<NamedDecl>(DC);
393 ParentKind = getCursorKindForDecl(ND);
394 ParentName = getCodeCompletionTUInfo().getParentName(DC);
397 unsigned CodeCompletionResult::getPriorityFromDecl(NamedDecl *ND) {
401 // Context-based decisions.
402 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
403 if (DC->isFunctionOrMethod() || isa<BlockDecl>(DC)) {
404 // _cmd is relatively rare
405 if (ImplicitParamDecl *ImplicitParam = dyn_cast<ImplicitParamDecl>(ND))
406 if (ImplicitParam->getIdentifier() &&
407 ImplicitParam->getIdentifier()->isStr("_cmd"))
410 return CCP_LocalDeclaration;
412 if (DC->isRecord() || isa<ObjCContainerDecl>(DC))
413 return CCP_MemberDeclaration;
415 // Content-based decisions.
416 if (isa<EnumConstantDecl>(ND))
418 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
421 return CCP_Declaration;
424 //===----------------------------------------------------------------------===//
425 // Code completion overload candidate implementation
426 //===----------------------------------------------------------------------===//
428 CodeCompleteConsumer::OverloadCandidate::getFunction() const {
429 if (getKind() == CK_Function)
431 else if (getKind() == CK_FunctionTemplate)
432 return FunctionTemplate->getTemplatedDecl();
438 CodeCompleteConsumer::OverloadCandidate::getFunctionType() const {
441 return Function->getType()->getAs<FunctionType>();
443 case CK_FunctionTemplate:
444 return FunctionTemplate->getTemplatedDecl()->getType()
445 ->getAs<FunctionType>();
447 case CK_FunctionType:
451 llvm_unreachable("Invalid CandidateKind!");
454 //===----------------------------------------------------------------------===//
455 // Code completion consumer implementation
456 //===----------------------------------------------------------------------===//
458 CodeCompleteConsumer::~CodeCompleteConsumer() { }
461 PrintingCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &SemaRef,
462 CodeCompletionContext Context,
463 CodeCompletionResult *Results,
464 unsigned NumResults) {
465 std::stable_sort(Results, Results + NumResults);
467 // Print the results.
468 for (unsigned I = 0; I != NumResults; ++I) {
469 OS << "COMPLETION: ";
470 switch (Results[I].Kind) {
471 case CodeCompletionResult::RK_Declaration:
472 OS << *Results[I].Declaration;
473 if (Results[I].Hidden)
475 if (CodeCompletionString *CCS
476 = Results[I].CreateCodeCompletionString(SemaRef, getAllocator(),
478 OS << " : " << CCS->getAsString();
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, getAllocator(),
493 OS << " : " << CCS->getAsString();
499 case CodeCompletionResult::RK_Pattern: {
501 << Results[I].Pattern->getAsString() << '\n';
509 PrintingCodeCompleteConsumer::ProcessOverloadCandidates(Sema &SemaRef,
511 OverloadCandidate *Candidates,
512 unsigned NumCandidates) {
513 for (unsigned I = 0; I != NumCandidates; ++I) {
514 if (CodeCompletionString *CCS
515 = Candidates[I].CreateSignatureString(CurrentArg, SemaRef,
516 getAllocator(), CCTUInfo)) {
517 OS << "OVERLOAD: " << CCS->getAsString() << "\n";
522 /// \brief Retrieve the effective availability of the given declaration.
523 static AvailabilityResult getDeclAvailability(Decl *D) {
524 AvailabilityResult AR = D->getAvailability();
525 if (isa<EnumConstantDecl>(D))
526 AR = std::max(AR, cast<Decl>(D->getDeclContext())->getAvailability());
530 void CodeCompletionResult::computeCursorKindAndAvailability(bool Accessible) {
534 // Do nothing: Patterns can come with cursor kinds!
539 case RK_Declaration: {
540 // Set the availability based on attributes.
541 switch (getDeclAvailability(Declaration)) {
543 case AR_NotYetIntroduced:
544 Availability = CXAvailability_Available;
548 Availability = CXAvailability_Deprecated;
552 Availability = CXAvailability_NotAvailable;
556 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Declaration))
557 if (Function->isDeleted())
558 Availability = CXAvailability_NotAvailable;
560 CursorKind = getCursorKindForDecl(Declaration);
561 if (CursorKind == CXCursor_UnexposedDecl) {
562 // FIXME: Forward declarations of Objective-C classes and protocols
563 // are not directly exposed, but we want code completion to treat them
564 // like a definition.
565 if (isa<ObjCInterfaceDecl>(Declaration))
566 CursorKind = CXCursor_ObjCInterfaceDecl;
567 else if (isa<ObjCProtocolDecl>(Declaration))
568 CursorKind = CXCursor_ObjCProtocolDecl;
570 CursorKind = CXCursor_NotImplemented;
576 Availability = CXAvailability_Available;
577 CursorKind = CXCursor_MacroDefinition;
581 Availability = CXAvailability_Available;
582 CursorKind = CXCursor_NotImplemented;
587 Availability = CXAvailability_NotAccessible;
590 /// \brief Retrieve the name that should be used to order a result.
592 /// If the name needs to be constructed as a string, that string will be
593 /// saved into Saved and the returned StringRef will refer to it.
594 static StringRef getOrderedName(const CodeCompletionResult &R,
595 std::string &Saved) {
597 case CodeCompletionResult::RK_Keyword:
600 case CodeCompletionResult::RK_Pattern:
601 return R.Pattern->getTypedText();
603 case CodeCompletionResult::RK_Macro:
604 return R.Macro->getName();
606 case CodeCompletionResult::RK_Declaration:
607 // Handle declarations below.
611 DeclarationName Name = R.Declaration->getDeclName();
613 // If the name is a simple identifier (by far the common case), or a
614 // zero-argument selector, just return a reference to that identifier.
615 if (IdentifierInfo *Id = Name.getAsIdentifierInfo())
616 return Id->getName();
617 if (Name.isObjCZeroArgSelector())
618 if (IdentifierInfo *Id
619 = Name.getObjCSelector().getIdentifierInfoForSlot(0))
620 return Id->getName();
622 Saved = Name.getAsString();
626 bool clang::operator<(const CodeCompletionResult &X,
627 const CodeCompletionResult &Y) {
628 std::string XSaved, YSaved;
629 StringRef XStr = getOrderedName(X, XSaved);
630 StringRef YStr = getOrderedName(Y, YSaved);
631 int cmp = XStr.compare_lower(YStr);
635 // If case-insensitive comparison fails, try case-sensitive comparison.
636 cmp = XStr.compare(YStr);