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/STLExtras.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:
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");
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 : NumChunks(NumChunks), NumAnnotations(NumAnnotations)
197 , Priority(Priority), Availability(Availability)
199 assert(NumChunks <= 0xffff);
200 assert(NumAnnotations <= 0xffff);
202 Chunk *StoredChunks = reinterpret_cast<Chunk *>(this + 1);
203 for (unsigned I = 0; I != NumChunks; ++I)
204 StoredChunks[I] = Chunks[I];
206 const char **StoredAnnotations = reinterpret_cast<const char **>(StoredChunks + NumChunks);
207 for (unsigned I = 0; I != NumAnnotations; ++I)
208 StoredAnnotations[I] = Annotations[I];
211 unsigned CodeCompletionString::getAnnotationCount() const {
212 return NumAnnotations;
215 const char *CodeCompletionString::getAnnotation(unsigned AnnotationNr) const {
216 if (AnnotationNr < NumAnnotations)
217 return reinterpret_cast<const char * const*>(end())[AnnotationNr];
223 std::string CodeCompletionString::getAsString() const {
225 llvm::raw_string_ostream OS(Result);
227 for (iterator C = begin(), CEnd = end(); C != CEnd; ++C) {
229 case CK_Optional: OS << "{#" << C->Optional->getAsString() << "#}"; break;
230 case CK_Placeholder: OS << "<#" << C->Text << "#>"; break;
234 OS << "[#" << C->Text << "#]";
237 case CK_CurrentParameter: OS << "<#" << C->Text << "#>"; break;
238 default: OS << C->Text; break;
244 const char *CodeCompletionString::getTypedText() const {
245 for (iterator C = begin(), CEnd = end(); C != CEnd; ++C)
246 if (C->Kind == CK_TypedText)
252 const char *CodeCompletionAllocator::CopyString(StringRef String) {
253 char *Mem = (char *)Allocate(String.size() + 1, 1);
254 std::copy(String.begin(), String.end(), Mem);
255 Mem[String.size()] = 0;
259 const char *CodeCompletionAllocator::CopyString(Twine String) {
260 // FIXME: It would be more efficient to teach Twine to tell us its size and
261 // then add a routine there to fill in an allocated char* with the contents
263 llvm::SmallString<128> Data;
264 return CopyString(String.toStringRef(Data));
267 CodeCompletionString *CodeCompletionBuilder::TakeString() {
268 void *Mem = Allocator.Allocate(
269 sizeof(CodeCompletionString) + sizeof(Chunk) * Chunks.size()
270 + sizeof(const char *) * Annotations.size(),
271 llvm::alignOf<CodeCompletionString>());
272 CodeCompletionString *Result
273 = new (Mem) CodeCompletionString(Chunks.data(), Chunks.size(),
274 Priority, Availability,
275 Annotations.data(), Annotations.size());
280 unsigned CodeCompletionResult::getPriorityFromDecl(NamedDecl *ND) {
284 // Context-based decisions.
285 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
286 if (DC->isFunctionOrMethod() || isa<BlockDecl>(DC)) {
287 // _cmd is relatively rare
288 if (ImplicitParamDecl *ImplicitParam = dyn_cast<ImplicitParamDecl>(ND))
289 if (ImplicitParam->getIdentifier() &&
290 ImplicitParam->getIdentifier()->isStr("_cmd"))
293 return CCP_LocalDeclaration;
295 if (DC->isRecord() || isa<ObjCContainerDecl>(DC))
296 return CCP_MemberDeclaration;
298 // Content-based decisions.
299 if (isa<EnumConstantDecl>(ND))
301 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
304 return CCP_Declaration;
307 //===----------------------------------------------------------------------===//
308 // Code completion overload candidate implementation
309 //===----------------------------------------------------------------------===//
311 CodeCompleteConsumer::OverloadCandidate::getFunction() const {
312 if (getKind() == CK_Function)
314 else if (getKind() == CK_FunctionTemplate)
315 return FunctionTemplate->getTemplatedDecl();
321 CodeCompleteConsumer::OverloadCandidate::getFunctionType() const {
324 return Function->getType()->getAs<FunctionType>();
326 case CK_FunctionTemplate:
327 return FunctionTemplate->getTemplatedDecl()->getType()
328 ->getAs<FunctionType>();
330 case CK_FunctionType:
337 //===----------------------------------------------------------------------===//
338 // Code completion consumer implementation
339 //===----------------------------------------------------------------------===//
341 CodeCompleteConsumer::~CodeCompleteConsumer() { }
344 PrintingCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &SemaRef,
345 CodeCompletionContext Context,
346 CodeCompletionResult *Results,
347 unsigned NumResults) {
348 std::stable_sort(Results, Results + NumResults);
350 // Print the results.
351 for (unsigned I = 0; I != NumResults; ++I) {
352 OS << "COMPLETION: ";
353 switch (Results[I].Kind) {
354 case CodeCompletionResult::RK_Declaration:
355 OS << *Results[I].Declaration;
356 if (Results[I].Hidden)
358 if (CodeCompletionString *CCS
359 = Results[I].CreateCodeCompletionString(SemaRef, Allocator)) {
360 OS << " : " << CCS->getAsString();
366 case CodeCompletionResult::RK_Keyword:
367 OS << Results[I].Keyword << '\n';
370 case CodeCompletionResult::RK_Macro: {
371 OS << Results[I].Macro->getName();
372 if (CodeCompletionString *CCS
373 = Results[I].CreateCodeCompletionString(SemaRef, Allocator)) {
374 OS << " : " << CCS->getAsString();
380 case CodeCompletionResult::RK_Pattern: {
382 << Results[I].Pattern->getAsString() << '\n';
390 PrintingCodeCompleteConsumer::ProcessOverloadCandidates(Sema &SemaRef,
392 OverloadCandidate *Candidates,
393 unsigned NumCandidates) {
394 for (unsigned I = 0; I != NumCandidates; ++I) {
395 if (CodeCompletionString *CCS
396 = Candidates[I].CreateSignatureString(CurrentArg, SemaRef,
398 OS << "OVERLOAD: " << CCS->getAsString() << "\n";
403 void CodeCompletionResult::computeCursorKindAndAvailability(bool Accessible) {
406 // Set the availability based on attributes.
407 switch (Declaration->getAvailability()) {
409 case AR_NotYetIntroduced:
410 Availability = CXAvailability_Available;
414 Availability = CXAvailability_Deprecated;
418 Availability = CXAvailability_NotAvailable;
422 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Declaration))
423 if (Function->isDeleted())
424 Availability = CXAvailability_NotAvailable;
426 CursorKind = getCursorKindForDecl(Declaration);
427 if (CursorKind == CXCursor_UnexposedDecl)
428 CursorKind = CXCursor_NotImplemented;
432 Availability = CXAvailability_Available;
433 CursorKind = CXCursor_MacroDefinition;
437 Availability = CXAvailability_Available;
438 CursorKind = CXCursor_NotImplemented;
442 // Do nothing: Patterns can come with cursor kinds!
447 Availability = CXAvailability_NotAccessible;
450 /// \brief Retrieve the name that should be used to order a result.
452 /// If the name needs to be constructed as a string, that string will be
453 /// saved into Saved and the returned StringRef will refer to it.
454 static StringRef getOrderedName(const CodeCompletionResult &R,
455 std::string &Saved) {
457 case CodeCompletionResult::RK_Keyword:
460 case CodeCompletionResult::RK_Pattern:
461 return R.Pattern->getTypedText();
463 case CodeCompletionResult::RK_Macro:
464 return R.Macro->getName();
466 case CodeCompletionResult::RK_Declaration:
467 // Handle declarations below.
471 DeclarationName Name = R.Declaration->getDeclName();
473 // If the name is a simple identifier (by far the common case), or a
474 // zero-argument selector, just return a reference to that identifier.
475 if (IdentifierInfo *Id = Name.getAsIdentifierInfo())
476 return Id->getName();
477 if (Name.isObjCZeroArgSelector())
478 if (IdentifierInfo *Id
479 = Name.getObjCSelector().getIdentifierInfoForSlot(0))
480 return Id->getName();
482 Saved = Name.getAsString();
486 bool clang::operator<(const CodeCompletionResult &X,
487 const CodeCompletionResult &Y) {
488 std::string XSaved, YSaved;
489 StringRef XStr = getOrderedName(X, XSaved);
490 StringRef YStr = getOrderedName(Y, YSaved);
491 int cmp = XStr.compare_lower(YStr);
495 // If case-insensitive comparison fails, try case-sensitive comparison.
496 cmp = XStr.compare(YStr);