blob: 9c4d315a692f86362837ab710dfaf98200cacc67 [file] [log] [blame]
Eugene Zelenko711964d2018-02-20 02:16:28 +00001//===- CodeCompleteConsumer.cpp - Code Completion Interface ---------------===//
Douglas Gregor2436e712009-09-17 21:32:03 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the CodeCompleteConsumer class.
11//
12//===----------------------------------------------------------------------===//
Eugene Zelenko711964d2018-02-20 02:16:28 +000013
Douglas Gregor2436e712009-09-17 21:32:03 +000014#include "clang/Sema/CodeCompleteConsumer.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "clang-c/Index.h"
Eugene Zelenko711964d2018-02-20 02:16:28 +000016#include "clang/AST/Decl.h"
17#include "clang/AST/DeclBase.h"
John McCallde6836a2010-08-24 07:21:54 +000018#include "clang/AST/DeclObjC.h"
John McCall19c1bfd2010-08-25 05:32:35 +000019#include "clang/AST/DeclTemplate.h"
Eugene Zelenko711964d2018-02-20 02:16:28 +000020#include "clang/AST/DeclarationName.h"
21#include "clang/AST/Type.h"
22#include "clang/Basic/IdentifierTable.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "clang/Sema/Sema.h"
Vassil Vassilev644ea612016-07-27 14:56:59 +000024#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "llvm/ADT/SmallString.h"
Eugene Zelenko711964d2018-02-20 02:16:28 +000026#include "llvm/ADT/SmallVector.h"
27#include "llvm/ADT/StringRef.h"
Douglas Gregor669a25a2011-02-17 00:22:45 +000028#include "llvm/ADT/Twine.h"
Eugene Zelenko711964d2018-02-20 02:16:28 +000029#include "llvm/Support/Casting.h"
30#include "llvm/Support/Compiler.h"
31#include "llvm/Support/ErrorHandling.h"
Douglas Gregor2436e712009-09-17 21:32:03 +000032#include "llvm/Support/raw_ostream.h"
33#include <algorithm>
Eugene Zelenko711964d2018-02-20 02:16:28 +000034#include <cassert>
35#include <cstdint>
36#include <string>
Douglas Gregorab6ccb52009-11-17 16:43:05 +000037
Douglas Gregor2436e712009-09-17 21:32:03 +000038using namespace clang;
39
Douglas Gregorfedc3282009-09-18 22:15:54 +000040//===----------------------------------------------------------------------===//
Douglas Gregor0212fd72010-09-21 16:06:22 +000041// Code completion context implementation
42//===----------------------------------------------------------------------===//
43
44bool CodeCompletionContext::wantConstructorResults() const {
Ilya Biryukov3289ab22018-02-19 13:53:49 +000045 switch (CCKind) {
Douglas Gregor0ac41382010-09-23 23:01:17 +000046 case CCC_Recovery:
Douglas Gregor0212fd72010-09-21 16:06:22 +000047 case CCC_Statement:
48 case CCC_Expression:
49 case CCC_ObjCMessageReceiver:
50 case CCC_ParenthesizedExpression:
51 return true;
52
53 case CCC_TopLevel:
54 case CCC_ObjCInterface:
55 case CCC_ObjCImplementation:
56 case CCC_ObjCIvarList:
57 case CCC_ClassStructUnion:
Douglas Gregor21325842011-07-07 16:03:39 +000058 case CCC_DotMemberAccess:
59 case CCC_ArrowMemberAccess:
60 case CCC_ObjCPropertyAccess:
Douglas Gregor0212fd72010-09-21 16:06:22 +000061 case CCC_EnumTag:
62 case CCC_UnionTag:
63 case CCC_ClassOrStructTag:
64 case CCC_ObjCProtocolName:
65 case CCC_Namespace:
66 case CCC_Type:
67 case CCC_Name:
68 case CCC_PotentiallyQualifiedName:
69 case CCC_MacroName:
70 case CCC_MacroNameUse:
71 case CCC_PreprocessorExpression:
72 case CCC_PreprocessorDirective:
73 case CCC_NaturalLanguage:
74 case CCC_SelectorName:
75 case CCC_TypeQualifiers:
Douglas Gregor0ac41382010-09-23 23:01:17 +000076 case CCC_Other:
Douglas Gregor3a69eaf2011-02-18 23:30:37 +000077 case CCC_OtherWithMacros:
Douglas Gregor21325842011-07-07 16:03:39 +000078 case CCC_ObjCInstanceMessage:
79 case CCC_ObjCClassMessage:
Douglas Gregor2c595ad2011-07-30 06:55:39 +000080 case CCC_ObjCInterfaceName:
Douglas Gregor21325842011-07-07 16:03:39 +000081 case CCC_ObjCCategoryName:
Douglas Gregor0212fd72010-09-21 16:06:22 +000082 return false;
83 }
David Blaikie8a40f702012-01-17 06:56:22 +000084
85 llvm_unreachable("Invalid CodeCompletionContext::Kind!");
Douglas Gregor0212fd72010-09-21 16:06:22 +000086}
87
Ilya Biryukov3289ab22018-02-19 13:53:49 +000088StringRef clang::getCompletionKindString(CodeCompletionContext::Kind Kind) {
89 using CCKind = CodeCompletionContext::Kind;
Ilya Biryukov27d82582018-02-19 12:35:33 +000090 switch (Kind) {
91 case CCKind::CCC_Other:
92 return "Other";
93 case CCKind::CCC_OtherWithMacros:
94 return "OtherWithMacros";
95 case CCKind::CCC_TopLevel:
96 return "TopLevel";
97 case CCKind::CCC_ObjCInterface:
98 return "ObjCInterface";
99 case CCKind::CCC_ObjCImplementation:
100 return "ObjCImplementation";
101 case CCKind::CCC_ObjCIvarList:
102 return "ObjCIvarList";
103 case CCKind::CCC_ClassStructUnion:
104 return "ClassStructUnion";
105 case CCKind::CCC_Statement:
106 return "Statement";
107 case CCKind::CCC_Expression:
108 return "Expression";
109 case CCKind::CCC_ObjCMessageReceiver:
110 return "ObjCMessageReceiver";
111 case CCKind::CCC_DotMemberAccess:
112 return "DotMemberAccess";
113 case CCKind::CCC_ArrowMemberAccess:
114 return "ArrowMemberAccess";
115 case CCKind::CCC_ObjCPropertyAccess:
116 return "ObjCPropertyAccess";
117 case CCKind::CCC_EnumTag:
118 return "EnumTag";
119 case CCKind::CCC_UnionTag:
120 return "UnionTag";
121 case CCKind::CCC_ClassOrStructTag:
122 return "ClassOrStructTag";
123 case CCKind::CCC_ObjCProtocolName:
124 return "ObjCProtocolName";
125 case CCKind::CCC_Namespace:
126 return "Namespace";
127 case CCKind::CCC_Type:
128 return "Type";
129 case CCKind::CCC_Name:
130 return "Name";
131 case CCKind::CCC_PotentiallyQualifiedName:
132 return "PotentiallyQualifiedName";
133 case CCKind::CCC_MacroName:
134 return "MacroName";
135 case CCKind::CCC_MacroNameUse:
136 return "MacroNameUse";
137 case CCKind::CCC_PreprocessorExpression:
138 return "PreprocessorExpression";
139 case CCKind::CCC_PreprocessorDirective:
140 return "PreprocessorDirective";
141 case CCKind::CCC_NaturalLanguage:
142 return "NaturalLanguage";
143 case CCKind::CCC_SelectorName:
144 return "SelectorName";
145 case CCKind::CCC_TypeQualifiers:
146 return "TypeQualifiers";
147 case CCKind::CCC_ParenthesizedExpression:
148 return "ParenthesizedExpression";
149 case CCKind::CCC_ObjCInstanceMessage:
150 return "ObjCInstanceMessage";
151 case CCKind::CCC_ObjCClassMessage:
152 return "ObjCClassMessage";
153 case CCKind::CCC_ObjCInterfaceName:
154 return "ObjCInterfaceName";
155 case CCKind::CCC_ObjCCategoryName:
156 return "ObjCCategoryName";
157 case CCKind::CCC_Recovery:
158 return "Recovery";
159 }
160 llvm_unreachable("Invalid CodeCompletionContext::Kind!");
161}
162
Douglas Gregor0212fd72010-09-21 16:06:22 +0000163//===----------------------------------------------------------------------===//
Douglas Gregorfedc3282009-09-18 22:15:54 +0000164// Code completion string implementation
165//===----------------------------------------------------------------------===//
Eugene Zelenko711964d2018-02-20 02:16:28 +0000166
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000167CodeCompletionString::Chunk::Chunk(ChunkKind Kind, const char *Text)
Eugene Zelenko711964d2018-02-20 02:16:28 +0000168 : Kind(Kind), Text("") {
Douglas Gregor9eb77012009-11-07 00:00:49 +0000169 switch (Kind) {
170 case CK_TypedText:
171 case CK_Text:
172 case CK_Placeholder:
173 case CK_Informative:
Douglas Gregorb3fa9192009-12-18 18:53:37 +0000174 case CK_ResultType:
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000175 case CK_CurrentParameter:
176 this->Text = Text;
Douglas Gregor9eb77012009-11-07 00:00:49 +0000177 break;
Douglas Gregor9eb77012009-11-07 00:00:49 +0000178
179 case CK_Optional:
Jeffrey Yasskin1615d452009-12-12 05:05:38 +0000180 llvm_unreachable("Optional strings cannot be created from text");
Douglas Gregor9eb77012009-11-07 00:00:49 +0000181
182 case CK_LeftParen:
183 this->Text = "(";
184 break;
185
186 case CK_RightParen:
187 this->Text = ")";
188 break;
189
190 case CK_LeftBracket:
191 this->Text = "[";
192 break;
193
194 case CK_RightBracket:
195 this->Text = "]";
196 break;
197
198 case CK_LeftBrace:
199 this->Text = "{";
200 break;
201
202 case CK_RightBrace:
203 this->Text = "}";
204 break;
205
206 case CK_LeftAngle:
207 this->Text = "<";
208 break;
209
210 case CK_RightAngle:
211 this->Text = ">";
212 break;
213
214 case CK_Comma:
215 this->Text = ", ";
216 break;
Douglas Gregor504a6ae2010-01-10 23:08:15 +0000217
218 case CK_Colon:
Douglas Gregor636a61e2010-04-07 00:21:17 +0000219 this->Text = ":";
Douglas Gregor504a6ae2010-01-10 23:08:15 +0000220 break;
221
222 case CK_SemiColon:
223 this->Text = ";";
224 break;
225
226 case CK_Equal:
227 this->Text = " = ";
228 break;
229
230 case CK_HorizontalSpace:
231 this->Text = " ";
232 break;
233
234 case CK_VerticalSpace:
235 this->Text = "\n";
236 break;
Douglas Gregor9eb77012009-11-07 00:00:49 +0000237 }
Douglas Gregor5bf52692009-09-22 23:15:58 +0000238}
239
240CodeCompletionString::Chunk
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000241CodeCompletionString::Chunk::CreateText(const char *Text) {
Douglas Gregor5bf52692009-09-22 23:15:58 +0000242 return Chunk(CK_Text, Text);
Douglas Gregorfedc3282009-09-18 22:15:54 +0000243}
244
245CodeCompletionString::Chunk
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000246CodeCompletionString::Chunk::CreateOptional(CodeCompletionString *Optional) {
Douglas Gregorfedc3282009-09-18 22:15:54 +0000247 Chunk Result;
248 Result.Kind = CK_Optional;
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000249 Result.Optional = Optional;
Douglas Gregorfedc3282009-09-18 22:15:54 +0000250 return Result;
251}
252
253CodeCompletionString::Chunk
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000254CodeCompletionString::Chunk::CreatePlaceholder(const char *Placeholder) {
Douglas Gregor5bf52692009-09-22 23:15:58 +0000255 return Chunk(CK_Placeholder, Placeholder);
256}
257
258CodeCompletionString::Chunk
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000259CodeCompletionString::Chunk::CreateInformative(const char *Informative) {
Douglas Gregor5bf52692009-09-22 23:15:58 +0000260 return Chunk(CK_Informative, Informative);
Douglas Gregorfedc3282009-09-18 22:15:54 +0000261}
262
Douglas Gregor9eb77012009-11-07 00:00:49 +0000263CodeCompletionString::Chunk
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000264CodeCompletionString::Chunk::CreateResultType(const char *ResultType) {
Douglas Gregorb3fa9192009-12-18 18:53:37 +0000265 return Chunk(CK_ResultType, ResultType);
266}
267
268CodeCompletionString::Chunk
Douglas Gregor9eb77012009-11-07 00:00:49 +0000269CodeCompletionString::Chunk::CreateCurrentParameter(
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000270 const char *CurrentParameter) {
Douglas Gregor9eb77012009-11-07 00:00:49 +0000271 return Chunk(CK_CurrentParameter, CurrentParameter);
272}
273
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000274CodeCompletionString::CodeCompletionString(const Chunk *Chunks,
275 unsigned NumChunks,
276 unsigned Priority,
Erik Verbruggen98ea7f62011-10-14 15:31:08 +0000277 CXAvailabilityKind Availability,
278 const char **Annotations,
Douglas Gregor78254c82012-03-27 23:34:16 +0000279 unsigned NumAnnotations,
Dmitri Gribenko3292d062012-07-02 17:35:10 +0000280 StringRef ParentName,
281 const char *BriefComment)
Eugene Zelenko711964d2018-02-20 02:16:28 +0000282 : NumChunks(NumChunks), NumAnnotations(NumAnnotations),
283 Priority(Priority), Availability(Availability),
284 ParentName(ParentName), BriefComment(BriefComment) {
Erik Verbruggen98ea7f62011-10-14 15:31:08 +0000285 assert(NumChunks <= 0xffff);
286 assert(NumAnnotations <= 0xffff);
287
Eugene Zelenko1e95bc02018-04-05 22:15:42 +0000288 Chunk *StoredChunks = reinterpret_cast<Chunk *>(this + 1);
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000289 for (unsigned I = 0; I != NumChunks; ++I)
290 StoredChunks[I] = Chunks[I];
Erik Verbruggen98ea7f62011-10-14 15:31:08 +0000291
Eugene Zelenko1e95bc02018-04-05 22:15:42 +0000292 const char **StoredAnnotations = reinterpret_cast<const char **>(StoredChunks + NumChunks);
Erik Verbruggen98ea7f62011-10-14 15:31:08 +0000293 for (unsigned I = 0; I != NumAnnotations; ++I)
294 StoredAnnotations[I] = Annotations[I];
Douglas Gregorfedc3282009-09-18 22:15:54 +0000295}
296
Erik Verbruggen98ea7f62011-10-14 15:31:08 +0000297unsigned CodeCompletionString::getAnnotationCount() const {
298 return NumAnnotations;
299}
300
301const char *CodeCompletionString::getAnnotation(unsigned AnnotationNr) const {
302 if (AnnotationNr < NumAnnotations)
303 return reinterpret_cast<const char * const*>(end())[AnnotationNr];
304 else
Craig Topperc3ec1492014-05-26 06:22:03 +0000305 return nullptr;
Erik Verbruggen98ea7f62011-10-14 15:31:08 +0000306}
307
Douglas Gregorfedc3282009-09-18 22:15:54 +0000308std::string CodeCompletionString::getAsString() const {
309 std::string Result;
310 llvm::raw_string_ostream OS(Result);
311
312 for (iterator C = begin(), CEnd = end(); C != CEnd; ++C) {
313 switch (C->Kind) {
Douglas Gregorfedc3282009-09-18 22:15:54 +0000314 case CK_Optional: OS << "{#" << C->Optional->getAsString() << "#}"; break;
Douglas Gregor5bf52692009-09-22 23:15:58 +0000315 case CK_Placeholder: OS << "<#" << C->Text << "#>"; break;
Douglas Gregorb3fa9192009-12-18 18:53:37 +0000316
317 case CK_Informative:
318 case CK_ResultType:
319 OS << "[#" << C->Text << "#]";
320 break;
321
Douglas Gregor9eb77012009-11-07 00:00:49 +0000322 case CK_CurrentParameter: OS << "<#" << C->Text << "#>"; break;
323 default: OS << C->Text; break;
Douglas Gregorfedc3282009-09-18 22:15:54 +0000324 }
325 }
Dan Gohman4888f1a2010-07-26 21:33:22 +0000326 return OS.str();
Douglas Gregorfedc3282009-09-18 22:15:54 +0000327}
328
Douglas Gregor45f83ee2009-11-19 00:01:57 +0000329const char *CodeCompletionString::getTypedText() const {
330 for (iterator C = begin(), CEnd = end(); C != CEnd; ++C)
331 if (C->Kind == CK_TypedText)
332 return C->Text;
Craig Topperc3ec1492014-05-26 06:22:03 +0000333
334 return nullptr;
Douglas Gregor45f83ee2009-11-19 00:01:57 +0000335}
336
Yaron Keren1ee89fc2015-03-17 09:51:17 +0000337const char *CodeCompletionAllocator::CopyString(const Twine &String) {
338 SmallString<128> Data;
339 StringRef Ref = String.toStringRef(Data);
Douglas Gregor669a25a2011-02-17 00:22:45 +0000340 // FIXME: It would be more efficient to teach Twine to tell us its size and
341 // then add a routine there to fill in an allocated char* with the contents
342 // of the string.
Eugene Zelenko1e95bc02018-04-05 22:15:42 +0000343 char *Mem = (char *)Allocate(Ref.size() + 1, 1);
Yaron Keren1ee89fc2015-03-17 09:51:17 +0000344 std::copy(Ref.begin(), Ref.end(), Mem);
345 Mem[Ref.size()] = 0;
346 return Mem;
Douglas Gregor669a25a2011-02-17 00:22:45 +0000347}
348
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000349StringRef CodeCompletionTUInfo::getParentName(const DeclContext *DC) {
Eugene Zelenko1e95bc02018-04-05 22:15:42 +0000350 const NamedDecl *ND = dyn_cast<NamedDecl>(DC);
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000351 if (!ND)
Eugene Zelenko711964d2018-02-20 02:16:28 +0000352 return {};
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000353
354 // Check whether we've already cached the parent name.
355 StringRef &CachedParentName = ParentNames[DC];
356 if (!CachedParentName.empty())
357 return CachedParentName;
358
359 // If we already processed this DeclContext and assigned empty to it, the
360 // data pointer will be non-null.
Craig Topperc3ec1492014-05-26 06:22:03 +0000361 if (CachedParentName.data() != nullptr)
Eugene Zelenko711964d2018-02-20 02:16:28 +0000362 return {};
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000363
364 // Find the interesting names.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000365 SmallVector<const DeclContext *, 2> Contexts;
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000366 while (DC && !DC->isFunctionOrMethod()) {
Eugene Zelenko1e95bc02018-04-05 22:15:42 +0000367 if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC)) {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000368 if (ND->getIdentifier())
369 Contexts.push_back(DC);
370 }
371
372 DC = DC->getParent();
373 }
374
375 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000376 SmallString<128> S;
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000377 llvm::raw_svector_ostream OS(S);
378 bool First = true;
379 for (unsigned I = Contexts.size(); I != 0; --I) {
380 if (First)
381 First = false;
382 else {
383 OS << "::";
384 }
385
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000386 const DeclContext *CurDC = Contexts[I-1];
Eugene Zelenko1e95bc02018-04-05 22:15:42 +0000387 if (const ObjCCategoryImplDecl *CatImpl = dyn_cast<ObjCCategoryImplDecl>(CurDC))
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000388 CurDC = CatImpl->getCategoryDecl();
389
Eugene Zelenko1e95bc02018-04-05 22:15:42 +0000390 if (const ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(CurDC)) {
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000391 const ObjCInterfaceDecl *Interface = Cat->getClassInterface();
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000392 if (!Interface) {
393 // Assign an empty StringRef but with non-null data to distinguish
394 // between empty because we didn't process the DeclContext yet.
Reid Klecknerd16cebe2016-02-10 19:09:15 +0000395 CachedParentName = StringRef((const char *)(uintptr_t)~0U, 0);
Eugene Zelenko711964d2018-02-20 02:16:28 +0000396 return {};
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000397 }
398
399 OS << Interface->getName() << '(' << Cat->getName() << ')';
400 } else {
401 OS << cast<NamedDecl>(CurDC)->getName();
402 }
403 }
404
405 CachedParentName = AllocatorRef->CopyString(OS.str());
406 }
407
408 return CachedParentName;
409}
410
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000411CodeCompletionString *CodeCompletionBuilder::TakeString() {
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000412 void *Mem = getAllocator().Allocate(
Benjamin Kramerc3f89252016-10-20 14:27:22 +0000413 sizeof(CodeCompletionString) + sizeof(Chunk) * Chunks.size() +
414 sizeof(const char *) * Annotations.size(),
415 alignof(CodeCompletionString));
Eugene Zelenko1e95bc02018-04-05 22:15:42 +0000416 CodeCompletionString *Result
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000417 = new (Mem) CodeCompletionString(Chunks.data(), Chunks.size(),
Erik Verbruggen98ea7f62011-10-14 15:31:08 +0000418 Priority, Availability,
Douglas Gregor78254c82012-03-27 23:34:16 +0000419 Annotations.data(), Annotations.size(),
Argyrios Kyrtzidis9ae39562012-09-26 16:39:56 +0000420 ParentName, BriefComment);
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000421 Chunks.clear();
Douglas Gregor45f83ee2009-11-19 00:01:57 +0000422 return Result;
423}
Douglas Gregor9eb77012009-11-07 00:00:49 +0000424
Benjamin Kramerdb534a42012-03-26 16:57:36 +0000425void CodeCompletionBuilder::AddTypedTextChunk(const char *Text) {
426 Chunks.push_back(Chunk(CodeCompletionString::CK_TypedText, Text));
427}
428
429void CodeCompletionBuilder::AddTextChunk(const char *Text) {
430 Chunks.push_back(Chunk::CreateText(Text));
431}
432
433void CodeCompletionBuilder::AddOptionalChunk(CodeCompletionString *Optional) {
434 Chunks.push_back(Chunk::CreateOptional(Optional));
435}
436
437void CodeCompletionBuilder::AddPlaceholderChunk(const char *Placeholder) {
438 Chunks.push_back(Chunk::CreatePlaceholder(Placeholder));
439}
440
441void CodeCompletionBuilder::AddInformativeChunk(const char *Text) {
442 Chunks.push_back(Chunk::CreateInformative(Text));
443}
444
445void CodeCompletionBuilder::AddResultTypeChunk(const char *ResultType) {
446 Chunks.push_back(Chunk::CreateResultType(ResultType));
447}
448
449void
450CodeCompletionBuilder::AddCurrentParameterChunk(const char *CurrentParameter) {
451 Chunks.push_back(Chunk::CreateCurrentParameter(CurrentParameter));
452}
453
454void CodeCompletionBuilder::AddChunk(CodeCompletionString::ChunkKind CK,
455 const char *Text) {
456 Chunks.push_back(Chunk(CK, Text));
457}
458
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000459void CodeCompletionBuilder::addParentContext(const DeclContext *DC) {
Eugene Zelenko711964d2018-02-20 02:16:28 +0000460 if (DC->isTranslationUnit())
Douglas Gregor78254c82012-03-27 23:34:16 +0000461 return;
Douglas Gregor78254c82012-03-27 23:34:16 +0000462
463 if (DC->isFunctionOrMethod())
464 return;
465
Eugene Zelenko1e95bc02018-04-05 22:15:42 +0000466 const NamedDecl *ND = dyn_cast<NamedDecl>(DC);
Douglas Gregor78254c82012-03-27 23:34:16 +0000467 if (!ND)
468 return;
469
Argyrios Kyrtzidis9d7c0fe2012-04-10 17:23:48 +0000470 ParentName = getCodeCompletionTUInfo().getParentName(DC);
Douglas Gregor78254c82012-03-27 23:34:16 +0000471}
472
Dmitri Gribenko3292d062012-07-02 17:35:10 +0000473void CodeCompletionBuilder::addBriefComment(StringRef Comment) {
474 BriefComment = Allocator.CopyString(Comment);
475}
476
Douglas Gregorfedc3282009-09-18 22:15:54 +0000477//===----------------------------------------------------------------------===//
Douglas Gregor05f477c2009-09-23 00:16:58 +0000478// Code completion overload candidate implementation
479//===----------------------------------------------------------------------===//
480FunctionDecl *
481CodeCompleteConsumer::OverloadCandidate::getFunction() const {
482 if (getKind() == CK_Function)
483 return Function;
484 else if (getKind() == CK_FunctionTemplate)
485 return FunctionTemplate->getTemplatedDecl();
486 else
Craig Topperc3ec1492014-05-26 06:22:03 +0000487 return nullptr;
Douglas Gregor05f477c2009-09-23 00:16:58 +0000488}
489
490const FunctionType *
491CodeCompleteConsumer::OverloadCandidate::getFunctionType() const {
492 switch (Kind) {
493 case CK_Function:
494 return Function->getType()->getAs<FunctionType>();
495
496 case CK_FunctionTemplate:
497 return FunctionTemplate->getTemplatedDecl()->getType()
498 ->getAs<FunctionType>();
499
500 case CK_FunctionType:
501 return Type;
502 }
David Blaikie8a40f702012-01-17 06:56:22 +0000503
504 llvm_unreachable("Invalid CandidateKind!");
Douglas Gregor05f477c2009-09-23 00:16:58 +0000505}
506
507//===----------------------------------------------------------------------===//
Douglas Gregorfedc3282009-09-18 22:15:54 +0000508// Code completion consumer implementation
509//===----------------------------------------------------------------------===//
510
Eugene Zelenko711964d2018-02-20 02:16:28 +0000511CodeCompleteConsumer::~CodeCompleteConsumer() = default;
Douglas Gregorfedc3282009-09-18 22:15:54 +0000512
Vassil Vassilev644ea612016-07-27 14:56:59 +0000513bool PrintingCodeCompleteConsumer::isResultFilteredOut(StringRef Filter,
514 CodeCompletionResult Result) {
515 switch (Result.Kind) {
Eugene Zelenko711964d2018-02-20 02:16:28 +0000516 case CodeCompletionResult::RK_Declaration:
Vassil Vassilev644ea612016-07-27 14:56:59 +0000517 return !(Result.Declaration->getIdentifier() &&
518 Result.Declaration->getIdentifier()->getName().startswith(Filter));
Eugene Zelenko711964d2018-02-20 02:16:28 +0000519 case CodeCompletionResult::RK_Keyword:
Vassil Vassilev644ea612016-07-27 14:56:59 +0000520 return !StringRef(Result.Keyword).startswith(Filter);
Eugene Zelenko711964d2018-02-20 02:16:28 +0000521 case CodeCompletionResult::RK_Macro:
Vassil Vassilev644ea612016-07-27 14:56:59 +0000522 return !Result.Macro->getName().startswith(Filter);
Eugene Zelenko711964d2018-02-20 02:16:28 +0000523 case CodeCompletionResult::RK_Pattern:
Vassil Vassilev644ea612016-07-27 14:56:59 +0000524 return !StringRef(Result.Pattern->getAsString()).startswith(Filter);
525 }
Simon Pilgrime71a1f92016-07-27 16:41:56 +0000526 llvm_unreachable("Unknown code completion result Kind.");
Vassil Vassilev644ea612016-07-27 14:56:59 +0000527}
528
Douglas Gregor2436e712009-09-17 21:32:03 +0000529void
Daniel Dunbar242ea9a2009-11-13 08:58:20 +0000530PrintingCodeCompleteConsumer::ProcessCodeCompleteResults(Sema &SemaRef,
Douglas Gregor00c37ef2010-08-11 21:23:17 +0000531 CodeCompletionContext Context,
John McCall276321a2010-08-25 06:19:51 +0000532 CodeCompletionResult *Results,
Douglas Gregor2436e712009-09-17 21:32:03 +0000533 unsigned NumResults) {
Douglas Gregor49f67ce2010-08-26 13:48:20 +0000534 std::stable_sort(Results, Results + NumResults);
535
Vassil Vassilev644ea612016-07-27 14:56:59 +0000536 StringRef Filter = SemaRef.getPreprocessor().getCodeCompletionFilter();
537
Douglas Gregor2436e712009-09-17 21:32:03 +0000538 // Print the results.
539 for (unsigned I = 0; I != NumResults; ++I) {
Vassil Vassilev644ea612016-07-27 14:56:59 +0000540 if(!Filter.empty() && isResultFilteredOut(Filter, Results[I]))
541 continue;
Douglas Gregor58acf322009-10-09 22:16:47 +0000542 OS << "COMPLETION: ";
Douglas Gregor2436e712009-09-17 21:32:03 +0000543 switch (Results[I].Kind) {
John McCall276321a2010-08-25 06:19:51 +0000544 case CodeCompletionResult::RK_Declaration:
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000545 OS << *Results[I].Declaration;
Douglas Gregor2436e712009-09-17 21:32:03 +0000546 if (Results[I].Hidden)
547 OS << " (Hidden)";
Douglas Gregor3545ff42009-09-21 16:56:56 +0000548 if (CodeCompletionString *CCS
Douglas Gregorc3425b12015-07-07 06:20:19 +0000549 = Results[I].CreateCodeCompletionString(SemaRef, Context,
550 getAllocator(),
Dmitri Gribenko3292d062012-07-02 17:35:10 +0000551 CCTUInfo,
552 includeBriefComments())) {
Douglas Gregorfedc3282009-09-18 22:15:54 +0000553 OS << " : " << CCS->getAsString();
Dmitri Gribenko3292d062012-07-02 17:35:10 +0000554 if (const char *BriefComment = CCS->getBriefComment())
555 OS << " : " << BriefComment;
Douglas Gregorfedc3282009-09-18 22:15:54 +0000556 }
Ivan Donchevskiib4670fc2018-05-25 12:56:26 +0000557 for (const FixItHint &FixIt : Results[I].FixIts) {
558 const SourceLocation BLoc = FixIt.RemoveRange.getBegin();
559 const SourceLocation ELoc = FixIt.RemoveRange.getEnd();
560
561 SourceManager &SM = SemaRef.SourceMgr;
562 std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
563 std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
564 // Adjust for token ranges.
565 if (FixIt.RemoveRange.isTokenRange())
566 EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, SemaRef.LangOpts);
567
568 OS << " (requires fix-it:"
569 << " {" << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
570 << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
571 << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
572 << SM.getColumnNumber(EInfo.first, EInfo.second) << "}"
573 << " to \"" << FixIt.CodeToInsert << "\")";
574 }
Douglas Gregor2436e712009-09-17 21:32:03 +0000575 OS << '\n';
576 break;
577
John McCall276321a2010-08-25 06:19:51 +0000578 case CodeCompletionResult::RK_Keyword:
Douglas Gregor52ce62f2010-01-13 23:24:38 +0000579 OS << Results[I].Keyword << '\n';
Douglas Gregor2436e712009-09-17 21:32:03 +0000580 break;
Douglas Gregorf329c7c2009-10-30 16:50:04 +0000581
Eugene Zelenko711964d2018-02-20 02:16:28 +0000582 case CodeCompletionResult::RK_Macro:
Douglas Gregor52ce62f2010-01-13 23:24:38 +0000583 OS << Results[I].Macro->getName();
Douglas Gregorf329c7c2009-10-30 16:50:04 +0000584 if (CodeCompletionString *CCS
Douglas Gregorc3425b12015-07-07 06:20:19 +0000585 = Results[I].CreateCodeCompletionString(SemaRef, Context,
586 getAllocator(),
Dmitri Gribenko3292d062012-07-02 17:35:10 +0000587 CCTUInfo,
588 includeBriefComments())) {
Douglas Gregorf329c7c2009-10-30 16:50:04 +0000589 OS << " : " << CCS->getAsString();
Douglas Gregorf329c7c2009-10-30 16:50:04 +0000590 }
591 OS << '\n';
592 break;
Douglas Gregor45f83ee2009-11-19 00:01:57 +0000593
Eugene Zelenko711964d2018-02-20 02:16:28 +0000594 case CodeCompletionResult::RK_Pattern:
Douglas Gregor52ce62f2010-01-13 23:24:38 +0000595 OS << "Pattern : "
Douglas Gregor45f83ee2009-11-19 00:01:57 +0000596 << Results[I].Pattern->getAsString() << '\n';
597 break;
598 }
Douglas Gregor2436e712009-09-17 21:32:03 +0000599 }
Douglas Gregor2436e712009-09-17 21:32:03 +0000600}
Douglas Gregor05f477c2009-09-23 00:16:58 +0000601
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +0000602// This function is used solely to preserve the former presentation of overloads
603// by "clang -cc1 -code-completion-at", since CodeCompletionString::getAsString
604// needs to be improved for printing the newer and more detailed overload
605// chunks.
606static std::string getOverloadAsString(const CodeCompletionString &CCS) {
607 std::string Result;
608 llvm::raw_string_ostream OS(Result);
609
610 for (auto &C : CCS) {
611 switch (C.Kind) {
612 case CodeCompletionString::CK_Informative:
613 case CodeCompletionString::CK_ResultType:
614 OS << "[#" << C.Text << "#]";
615 break;
616
617 case CodeCompletionString::CK_CurrentParameter:
618 OS << "<#" << C.Text << "#>";
619 break;
620
621 default: OS << C.Text; break;
622 }
623 }
624 return OS.str();
625}
626
Douglas Gregor05f477c2009-09-23 00:16:58 +0000627void
Daniel Dunbar242ea9a2009-11-13 08:58:20 +0000628PrintingCodeCompleteConsumer::ProcessOverloadCandidates(Sema &SemaRef,
629 unsigned CurrentArg,
Douglas Gregor05f477c2009-09-23 00:16:58 +0000630 OverloadCandidate *Candidates,
631 unsigned NumCandidates) {
632 for (unsigned I = 0; I != NumCandidates; ++I) {
Douglas Gregorf0f51982009-09-23 00:34:09 +0000633 if (CodeCompletionString *CCS
Douglas Gregorb278aaf2011-02-01 19:23:04 +0000634 = Candidates[I].CreateSignatureString(CurrentArg, SemaRef,
Francisco Lopes da Silva0c010cd2015-01-28 14:17:22 +0000635 getAllocator(), CCTUInfo,
636 includeBriefComments())) {
637 OS << "OVERLOAD: " << getOverloadAsString(*CCS) << "\n";
Douglas Gregor05f477c2009-09-23 00:16:58 +0000638 }
639 }
Douglas Gregor05f477c2009-09-23 00:16:58 +0000640}
Douglas Gregor9eb77012009-11-07 00:00:49 +0000641
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000642/// Retrieve the effective availability of the given declaration.
Dmitri Gribenkofe0483d2013-01-23 17:21:11 +0000643static AvailabilityResult getDeclAvailability(const Decl *D) {
Douglas Gregor7b316822012-03-17 06:39:06 +0000644 AvailabilityResult AR = D->getAvailability();
645 if (isa<EnumConstantDecl>(D))
646 AR = std::max(AR, cast<Decl>(D->getDeclContext())->getAvailability());
647 return AR;
648}
649
Erik Verbruggen2e657ff2011-10-06 07:27:49 +0000650void CodeCompletionResult::computeCursorKindAndAvailability(bool Accessible) {
Douglas Gregorb14904c2010-08-13 22:48:40 +0000651 switch (Kind) {
Douglas Gregor78254c82012-03-27 23:34:16 +0000652 case RK_Pattern:
653 if (!Declaration) {
654 // Do nothing: Patterns can come with cursor kinds!
655 break;
656 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +0000657 LLVM_FALLTHROUGH;
Douglas Gregor78254c82012-03-27 23:34:16 +0000658
Douglas Gregor7b316822012-03-17 06:39:06 +0000659 case RK_Declaration: {
Douglas Gregorf757a122010-08-23 23:00:57 +0000660 // Set the availability based on attributes.
Douglas Gregor7b316822012-03-17 06:39:06 +0000661 switch (getDeclAvailability(Declaration)) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000662 case AR_Available:
663 case AR_NotYetIntroduced:
664 Availability = CXAvailability_Available;
665 break;
Douglas Gregorf757a122010-08-23 23:00:57 +0000666
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000667 case AR_Deprecated:
668 Availability = CXAvailability_Deprecated;
669 break;
670
671 case AR_Unavailable:
672 Availability = CXAvailability_NotAvailable;
673 break;
674 }
675
Eugene Zelenko1e95bc02018-04-05 22:15:42 +0000676 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Declaration))
Douglas Gregor09c0eb12010-09-03 23:30:36 +0000677 if (Function->isDeleted())
Douglas Gregorf757a122010-08-23 23:00:57 +0000678 Availability = CXAvailability_NotAvailable;
Douglas Gregor09c0eb12010-09-03 23:30:36 +0000679
680 CursorKind = getCursorKindForDecl(Declaration);
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000681 if (CursorKind == CXCursor_UnexposedDecl) {
Douglas Gregorf6102672012-01-01 21:23:57 +0000682 // FIXME: Forward declarations of Objective-C classes and protocols
683 // are not directly exposed, but we want code completion to treat them
684 // like a definition.
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000685 if (isa<ObjCInterfaceDecl>(Declaration))
686 CursorKind = CXCursor_ObjCInterfaceDecl;
Douglas Gregorf6102672012-01-01 21:23:57 +0000687 else if (isa<ObjCProtocolDecl>(Declaration))
688 CursorKind = CXCursor_ObjCProtocolDecl;
Douglas Gregordeafd0b2011-12-27 22:43:10 +0000689 else
690 CursorKind = CXCursor_NotImplemented;
691 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000692 break;
Douglas Gregor7b316822012-03-17 06:39:06 +0000693 }
Douglas Gregorb14904c2010-08-13 22:48:40 +0000694
John McCall276321a2010-08-25 06:19:51 +0000695 case RK_Macro:
John McCall276321a2010-08-25 06:19:51 +0000696 case RK_Keyword:
Benjamin Kramerc25c0b92012-05-20 14:19:46 +0000697 llvm_unreachable("Macro and keyword kinds are handled by the constructors");
Douglas Gregor8e984da2010-08-04 16:47:14 +0000698 }
Erik Verbruggen2e657ff2011-10-06 07:27:49 +0000699
700 if (!Accessible)
701 Availability = CXAvailability_NotAccessible;
Douglas Gregor8e984da2010-08-04 16:47:14 +0000702}
Douglas Gregorf09935f2009-12-01 05:55:20 +0000703
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000704/// Retrieve the name that should be used to order a result.
Douglas Gregor0de55ce2010-08-25 18:41:16 +0000705///
706/// If the name needs to be constructed as a string, that string will be
707/// saved into Saved and the returned StringRef will refer to it.
Sam McCall1102a862017-11-15 09:15:06 +0000708StringRef CodeCompletionResult::getOrderedName(std::string &Saved) const {
709 switch (Kind) {
710 case RK_Keyword:
711 return Keyword;
712 case RK_Pattern:
713 return Pattern->getTypedText();
714 case RK_Macro:
715 return Macro->getName();
716 case RK_Declaration:
Douglas Gregor0de55ce2010-08-25 18:41:16 +0000717 // Handle declarations below.
718 break;
719 }
720
Sam McCall1102a862017-11-15 09:15:06 +0000721 DeclarationName Name = Declaration->getDeclName();
Douglas Gregor0de55ce2010-08-25 18:41:16 +0000722
723 // If the name is a simple identifier (by far the common case), or a
724 // zero-argument selector, just return a reference to that identifier.
725 if (IdentifierInfo *Id = Name.getAsIdentifierInfo())
726 return Id->getName();
727 if (Name.isObjCZeroArgSelector())
728 if (IdentifierInfo *Id
729 = Name.getObjCSelector().getIdentifierInfoForSlot(0))
730 return Id->getName();
731
732 Saved = Name.getAsString();
733 return Saved;
734}
735
736bool clang::operator<(const CodeCompletionResult &X,
737 const CodeCompletionResult &Y) {
738 std::string XSaved, YSaved;
Sam McCall1102a862017-11-15 09:15:06 +0000739 StringRef XStr = X.getOrderedName(XSaved);
740 StringRef YStr = Y.getOrderedName(YSaved);
Douglas Gregor0de55ce2010-08-25 18:41:16 +0000741 int cmp = XStr.compare_lower(YStr);
742 if (cmp)
743 return cmp < 0;
744
Douglas Gregor49f67ce2010-08-26 13:48:20 +0000745 // If case-insensitive comparison fails, try case-sensitive comparison.
746 cmp = XStr.compare(YStr);
747 if (cmp)
748 return cmp < 0;
Douglas Gregor0de55ce2010-08-25 18:41:16 +0000749
750 return false;
751}