Coverage Report

Created: 2020-09-15 12:33

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Sema/CodeCompleteConsumer.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- CodeCompleteConsumer.cpp - Code Completion Interface ---------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
//  This file implements the CodeCompleteConsumer class.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/Sema/CodeCompleteConsumer.h"
14
#include "clang-c/Index.h"
15
#include "clang/AST/Decl.h"
16
#include "clang/AST/DeclBase.h"
17
#include "clang/AST/DeclObjC.h"
18
#include "clang/AST/DeclTemplate.h"
19
#include "clang/AST/DeclarationName.h"
20
#include "clang/AST/Type.h"
21
#include "clang/Basic/IdentifierTable.h"
22
#include "clang/Lex/Preprocessor.h"
23
#include "clang/Sema/Sema.h"
24
#include "llvm/ADT/SmallString.h"
25
#include "llvm/ADT/SmallVector.h"
26
#include "llvm/ADT/StringExtras.h"
27
#include "llvm/ADT/StringRef.h"
28
#include "llvm/ADT/Twine.h"
29
#include "llvm/Support/Casting.h"
30
#include "llvm/Support/Compiler.h"
31
#include "llvm/Support/ErrorHandling.h"
32
#include "llvm/Support/FormatVariadic.h"
33
#include "llvm/Support/raw_ostream.h"
34
#include <algorithm>
35
#include <cassert>
36
#include <cstdint>
37
#include <string>
38
39
using namespace clang;
40
41
//===----------------------------------------------------------------------===//
42
// Code completion context implementation
43
//===----------------------------------------------------------------------===//
44
45
5.14k
bool CodeCompletionContext::wantConstructorResults() const {
46
5.14k
  switch (CCKind) {
47
4.24k
  case CCC_Recovery:
48
4.24k
  case CCC_Statement:
49
4.24k
  case CCC_Expression:
50
4.24k
  case CCC_ObjCMessageReceiver:
51
4.24k
  case CCC_ParenthesizedExpression:
52
4.24k
  case CCC_Symbol:
53
4.24k
  case CCC_SymbolOrNewName:
54
4.24k
    return true;
55
4.24k
56
898
  case CCC_TopLevel:
57
898
  case CCC_ObjCInterface:
58
898
  case CCC_ObjCImplementation:
59
898
  case CCC_ObjCIvarList:
60
898
  case CCC_ClassStructUnion:
61
898
  case CCC_DotMemberAccess:
62
898
  case CCC_ArrowMemberAccess:
63
898
  case CCC_ObjCPropertyAccess:
64
898
  case CCC_EnumTag:
65
898
  case CCC_UnionTag:
66
898
  case CCC_ClassOrStructTag:
67
898
  case CCC_ObjCProtocolName:
68
898
  case CCC_Namespace:
69
898
  case CCC_Type:
70
898
  case CCC_NewName:
71
898
  case CCC_MacroName:
72
898
  case CCC_MacroNameUse:
73
898
  case CCC_PreprocessorExpression:
74
898
  case CCC_PreprocessorDirective:
75
898
  case CCC_NaturalLanguage:
76
898
  case CCC_SelectorName:
77
898
  case CCC_TypeQualifiers:
78
898
  case CCC_Other:
79
898
  case CCC_OtherWithMacros:
80
898
  case CCC_ObjCInstanceMessage:
81
898
  case CCC_ObjCClassMessage:
82
898
  case CCC_ObjCInterfaceName:
83
898
  case CCC_ObjCCategoryName:
84
898
  case CCC_IncludedFile:
85
898
    return false;
86
0
  }
87
0
88
0
  llvm_unreachable("Invalid CodeCompletionContext::Kind!");
89
0
}
90
91
0
StringRef clang::getCompletionKindString(CodeCompletionContext::Kind Kind) {
92
0
  using CCKind = CodeCompletionContext::Kind;
93
0
  switch (Kind) {
94
0
  case CCKind::CCC_Other:
95
0
    return "Other";
96
0
  case CCKind::CCC_OtherWithMacros:
97
0
    return "OtherWithMacros";
98
0
  case CCKind::CCC_TopLevel:
99
0
    return "TopLevel";
100
0
  case CCKind::CCC_ObjCInterface:
101
0
    return "ObjCInterface";
102
0
  case CCKind::CCC_ObjCImplementation:
103
0
    return "ObjCImplementation";
104
0
  case CCKind::CCC_ObjCIvarList:
105
0
    return "ObjCIvarList";
106
0
  case CCKind::CCC_ClassStructUnion:
107
0
    return "ClassStructUnion";
108
0
  case CCKind::CCC_Statement:
109
0
    return "Statement";
110
0
  case CCKind::CCC_Expression:
111
0
    return "Expression";
112
0
  case CCKind::CCC_ObjCMessageReceiver:
113
0
    return "ObjCMessageReceiver";
114
0
  case CCKind::CCC_DotMemberAccess:
115
0
    return "DotMemberAccess";
116
0
  case CCKind::CCC_ArrowMemberAccess:
117
0
    return "ArrowMemberAccess";
118
0
  case CCKind::CCC_ObjCPropertyAccess:
119
0
    return "ObjCPropertyAccess";
120
0
  case CCKind::CCC_EnumTag:
121
0
    return "EnumTag";
122
0
  case CCKind::CCC_UnionTag:
123
0
    return "UnionTag";
124
0
  case CCKind::CCC_ClassOrStructTag:
125
0
    return "ClassOrStructTag";
126
0
  case CCKind::CCC_ObjCProtocolName:
127
0
    return "ObjCProtocolName";
128
0
  case CCKind::CCC_Namespace:
129
0
    return "Namespace";
130
0
  case CCKind::CCC_Type:
131
0
    return "Type";
132
0
  case CCKind::CCC_NewName:
133
0
    return "NewName";
134
0
  case CCKind::CCC_Symbol:
135
0
    return "Symbol";
136
0
  case CCKind::CCC_SymbolOrNewName:
137
0
    return "SymbolOrNewName";
138
0
  case CCKind::CCC_MacroName:
139
0
    return "MacroName";
140
0
  case CCKind::CCC_MacroNameUse:
141
0
    return "MacroNameUse";
142
0
  case CCKind::CCC_PreprocessorExpression:
143
0
    return "PreprocessorExpression";
144
0
  case CCKind::CCC_PreprocessorDirective:
145
0
    return "PreprocessorDirective";
146
0
  case CCKind::CCC_NaturalLanguage:
147
0
    return "NaturalLanguage";
148
0
  case CCKind::CCC_SelectorName:
149
0
    return "SelectorName";
150
0
  case CCKind::CCC_TypeQualifiers:
151
0
    return "TypeQualifiers";
152
0
  case CCKind::CCC_ParenthesizedExpression:
153
0
    return "ParenthesizedExpression";
154
0
  case CCKind::CCC_ObjCInstanceMessage:
155
0
    return "ObjCInstanceMessage";
156
0
  case CCKind::CCC_ObjCClassMessage:
157
0
    return "ObjCClassMessage";
158
0
  case CCKind::CCC_ObjCInterfaceName:
159
0
    return "ObjCInterfaceName";
160
0
  case CCKind::CCC_ObjCCategoryName:
161
0
    return "ObjCCategoryName";
162
0
  case CCKind::CCC_IncludedFile:
163
0
    return "IncludedFile";
164
0
  case CCKind::CCC_Recovery:
165
0
    return "Recovery";
166
0
  }
167
0
  llvm_unreachable("Invalid CodeCompletionContext::Kind!");
168
0
}
169
170
//===----------------------------------------------------------------------===//
171
// Code completion string implementation
172
//===----------------------------------------------------------------------===//
173
174
CodeCompletionString::Chunk::Chunk(ChunkKind Kind, const char *Text)
175
220k
    : Kind(Kind), Text("") {
176
220k
  switch (Kind) {
177
186k
  case CK_TypedText:
178
186k
  case CK_Text:
179
186k
  case CK_Placeholder:
180
186k
  case CK_Informative:
181
186k
  case CK_ResultType:
182
186k
  case CK_CurrentParameter:
183
186k
    this->Text = Text;
184
186k
    break;
185
186k
186
0
  case CK_Optional:
187
0
    llvm_unreachable("Optional strings cannot be created from text");
188
186k
189
10.1k
  case CK_LeftParen:
190
10.1k
    this->Text = "(";
191
10.1k
    break;
192
186k
193
10.2k
  case CK_RightParen:
194
10.2k
    this->Text = ")";
195
10.2k
    break;
196
186k
197
812
  case CK_LeftBracket:
198
812
    this->Text = "[";
199
812
    break;
200
186k
201
917
  case CK_RightBracket:
202
917
    this->Text = "]";
203
917
    break;
204
186k
205
161
  case CK_LeftBrace:
206
161
    this->Text = "{";
207
161
    break;
208
186k
209
266
  case CK_RightBrace:
210
266
    this->Text = "}";
211
266
    break;
212
186k
213
1.86k
  case CK_LeftAngle:
214
1.86k
    this->Text = "<";
215
1.86k
    break;
216
186k
217
1.86k
  case CK_RightAngle:
218
1.86k
    this->Text = ">";
219
1.86k
    break;
220
186k
221
1.61k
  case CK_Comma:
222
1.61k
    this->Text = ", ";
223
1.61k
    break;
224
186k
225
117
  case CK_Colon:
226
117
    this->Text = ":";
227
117
    break;
228
186k
229
1.04k
  case CK_SemiColon:
230
1.04k
    this->Text = ";";
231
1.04k
    break;
232
186k
233
167
  case CK_Equal:
234
167
    this->Text = " = ";
235
167
    break;
236
186k
237
5.01k
  case CK_HorizontalSpace:
238
5.01k
    this->Text = " ";
239
5.01k
    break;
240
186k
241
284
  case CK_VerticalSpace:
242
284
    this->Text = "\n";
243
284
    break;
244
220k
  }
245
220k
}
246
247
CodeCompletionString::Chunk
248
1.81k
CodeCompletionString::Chunk::CreateText(const char *Text) {
249
1.81k
  return Chunk(CK_Text, Text);
250
1.81k
}
251
252
CodeCompletionString::Chunk
253
100
CodeCompletionString::Chunk::CreateOptional(CodeCompletionString *Optional) {
254
100
  Chunk Result;
255
100
  Result.Kind = CK_Optional;
256
100
  Result.Optional = Optional;
257
100
  return Result;
258
100
}
259
260
CodeCompletionString::Chunk
261
17.5k
CodeCompletionString::Chunk::CreatePlaceholder(const char *Placeholder) {
262
17.5k
  return Chunk(CK_Placeholder, Placeholder);
263
17.5k
}
264
265
CodeCompletionString::Chunk
266
228
CodeCompletionString::Chunk::CreateInformative(const char *Informative) {
267
228
  return Chunk(CK_Informative, Informative);
268
228
}
269
270
CodeCompletionString::Chunk
271
9.42k
CodeCompletionString::Chunk::CreateResultType(const char *ResultType) {
272
9.42k
  return Chunk(CK_ResultType, ResultType);
273
9.42k
}
274
275
CodeCompletionString::Chunk CodeCompletionString::Chunk::CreateCurrentParameter(
276
221
    const char *CurrentParameter) {
277
221
  return Chunk(CK_CurrentParameter, CurrentParameter);
278
221
}
279
280
CodeCompletionString::CodeCompletionString(
281
    const Chunk *Chunks, unsigned NumChunks, unsigned Priority,
282
    CXAvailabilityKind Availability, const char **Annotations,
283
    unsigned NumAnnotations, StringRef ParentName, const char *BriefComment)
284
    : NumChunks(NumChunks), NumAnnotations(NumAnnotations), Priority(Priority),
285
      Availability(Availability), ParentName(ParentName),
286
156k
      BriefComment(BriefComment) {
287
156k
  assert(NumChunks <= 0xffff);
288
156k
  assert(NumAnnotations <= 0xffff);
289
156k
290
156k
  Chunk *StoredChunks = reinterpret_cast<Chunk *>(this + 1);
291
377k
  for (unsigned I = 0; I != NumChunks; 
++I220k
)
292
220k
    StoredChunks[I] = Chunks[I];
293
156k
294
156k
  const char **StoredAnnotations =
295
156k
      reinterpret_cast<const char **>(StoredChunks + NumChunks);
296
156k
  for (unsigned I = 0; I != NumAnnotations; 
++I6
)
297
6
    StoredAnnotations[I] = Annotations[I];
298
156k
}
299
300
112k
unsigned CodeCompletionString::getAnnotationCount() const {
301
112k
  return NumAnnotations;
302
112k
}
303
304
6
const char *CodeCompletionString::getAnnotation(unsigned AnnotationNr) const {
305
6
  if (AnnotationNr < NumAnnotations)
306
6
    return reinterpret_cast<const char *const *>(end())[AnnotationNr];
307
0
  else
308
0
    return nullptr;
309
6
}
310
311
6.47k
std::string CodeCompletionString::getAsString() const {
312
6.47k
  std::string Result;
313
6.47k
  llvm::raw_string_ostream OS(Result);
314
6.47k
315
19.4k
  for (const Chunk &C : *this) {
316
19.4k
    switch (C.Kind) {
317
20
    case CK_Optional:
318
20
      OS << "{#" << C.Optional->getAsString() << "#}";
319
20
      break;
320
3.52k
    case CK_Placeholder:
321
3.52k
      OS << "<#" << C.Text << "#>";
322
3.52k
      break;
323
1.80k
    case CK_Informative:
324
1.80k
    case CK_ResultType:
325
1.80k
      OS << "[#" << C.Text << "#]";
326
1.80k
      break;
327
0
    case CK_CurrentParameter:
328
0
      OS << "<#" << C.Text << "#>";
329
0
      break;
330
14.1k
    default:
331
14.1k
      OS << C.Text;
332
14.1k
      break;
333
19.4k
    }
334
19.4k
  }
335
6.47k
  return OS.str();
336
6.47k
}
337
338
125k
const char *CodeCompletionString::getTypedText() const {
339
125k
  for (const Chunk &C : *this)
340
134k
    if (C.Kind == CK_TypedText)
341
125k
      return C.Text;
342
125k
343
73
  return nullptr;
344
125k
}
345
346
143k
const char *CodeCompletionAllocator::CopyString(const Twine &String) {
347
143k
  SmallString<128> Data;
348
143k
  StringRef Ref = String.toStringRef(Data);
349
  // FIXME: It would be more efficient to teach Twine to tell us its size and
350
  // then add a routine there to fill in an allocated char* with the contents
351
  // of the string.
352
143k
  char *Mem = (char *)Allocate(Ref.size() + 1, 1);
353
143k
  std::copy(Ref.begin(), Ref.end(), Mem);
354
143k
  Mem[Ref.size()] = 0;
355
143k
  return Mem;
356
143k
}
357
358
2.10k
StringRef CodeCompletionTUInfo::getParentName(const DeclContext *DC) {
359
2.10k
  const NamedDecl *ND = dyn_cast<NamedDecl>(DC);
360
2.10k
  if (!ND)
361
0
    return {};
362
2.10k
363
  // Check whether we've already cached the parent name.
364
2.10k
  StringRef &CachedParentName = ParentNames[DC];
365
2.10k
  if (!CachedParentName.empty())
366
1.41k
    return CachedParentName;
367
686
368
  // If we already processed this DeclContext and assigned empty to it, the
369
  // data pointer will be non-null.
370
686
  if (CachedParentName.data() != nullptr)
371
10
    return {};
372
676
373
  // Find the interesting names.
374
676
  SmallVector<const DeclContext *, 2> Contexts;
375
2.05k
  while (DC && 
!DC->isFunctionOrMethod()1.37k
) {
376
1.37k
    if (const auto *ND = dyn_cast<NamedDecl>(DC)) {
377
703
      if (ND->getIdentifier())
378
680
        Contexts.push_back(DC);
379
703
    }
380
1.37k
381
1.37k
    DC = DC->getParent();
382
1.37k
  }
383
676
384
676
  {
385
676
    SmallString<128> S;
386
676
    llvm::raw_svector_ostream OS(S);
387
676
    bool First = true;
388
1.35k
    for (unsigned I = Contexts.size(); I != 0; 
--I680
) {
389
680
      if (First)
390
657
        First = false;
391
23
      else {
392
23
        OS << "::";
393
23
      }
394
680
395
680
      const DeclContext *CurDC = Contexts[I - 1];
396
680
      if (const auto *CatImpl = dyn_cast<ObjCCategoryImplDecl>(CurDC))
397
0
        CurDC = CatImpl->getCategoryDecl();
398
680
399
680
      if (const auto *Cat = dyn_cast<ObjCCategoryDecl>(CurDC)) {
400
17
        const ObjCInterfaceDecl *Interface = Cat->getClassInterface();
401
17
        if (!Interface) {
402
          // Assign an empty StringRef but with non-null data to distinguish
403
          // between empty because we didn't process the DeclContext yet.
404
0
          CachedParentName = StringRef((const char *)(uintptr_t)~0U, 0);
405
0
          return {};
406
0
        }
407
17
408
17
        OS << Interface->getName() << '(' << Cat->getName() << ')';
409
663
      } else {
410
663
        OS << cast<NamedDecl>(CurDC)->getName();
411
663
      }
412
680
    }
413
676
414
676
    CachedParentName = AllocatorRef->CopyString(OS.str());
415
676
  }
416
676
417
676
  return CachedParentName;
418
676
}
419
420
156k
CodeCompletionString *CodeCompletionBuilder::TakeString() {
421
156k
  void *Mem = getAllocator().Allocate(
422
156k
      sizeof(CodeCompletionString) + sizeof(Chunk) * Chunks.size() +
423
156k
          sizeof(const char *) * Annotations.size(),
424
156k
      alignof(CodeCompletionString));
425
156k
  CodeCompletionString *Result = new (Mem) CodeCompletionString(
426
156k
      Chunks.data(), Chunks.size(), Priority, Availability, Annotations.data(),
427
156k
      Annotations.size(), ParentName, BriefComment);
428
156k
  Chunks.clear();
429
156k
  return Result;
430
156k
}
431
432
156k
void CodeCompletionBuilder::AddTypedTextChunk(const char *Text) {
433
156k
  Chunks.push_back(Chunk(CodeCompletionString::CK_TypedText, Text));
434
156k
}
435
436
1.81k
void CodeCompletionBuilder::AddTextChunk(const char *Text) {
437
1.81k
  Chunks.push_back(Chunk::CreateText(Text));
438
1.81k
}
439
440
100
void CodeCompletionBuilder::AddOptionalChunk(CodeCompletionString *Optional) {
441
100
  Chunks.push_back(Chunk::CreateOptional(Optional));
442
100
}
443
444
17.5k
void CodeCompletionBuilder::AddPlaceholderChunk(const char *Placeholder) {
445
17.5k
  Chunks.push_back(Chunk::CreatePlaceholder(Placeholder));
446
17.5k
}
447
448
228
void CodeCompletionBuilder::AddInformativeChunk(const char *Text) {
449
228
  Chunks.push_back(Chunk::CreateInformative(Text));
450
228
}
451
452
9.42k
void CodeCompletionBuilder::AddResultTypeChunk(const char *ResultType) {
453
9.42k
  Chunks.push_back(Chunk::CreateResultType(ResultType));
454
9.42k
}
455
456
void CodeCompletionBuilder::AddCurrentParameterChunk(
457
221
    const char *CurrentParameter) {
458
221
  Chunks.push_back(Chunk::CreateCurrentParameter(CurrentParameter));
459
221
}
460
461
void CodeCompletionBuilder::AddChunk(CodeCompletionString::ChunkKind CK,
462
34.4k
                                     const char *Text) {
463
34.4k
  Chunks.push_back(Chunk(CK, Text));
464
34.4k
}
465
466
5.55k
void CodeCompletionBuilder::addParentContext(const DeclContext *DC) {
467
5.55k
  if (DC->isTranslationUnit())
468
2.99k
    return;
469
2.55k
470
2.55k
  if (DC->isFunctionOrMethod())
471
456
    return;
472
2.10k
473
2.10k
  const NamedDecl *ND = dyn_cast<NamedDecl>(DC);
474
2.10k
  if (!ND)
475
0
    return;
476
2.10k
477
2.10k
  ParentName = getCodeCompletionTUInfo().getParentName(DC);
478
2.10k
}
479
480
118
void CodeCompletionBuilder::addBriefComment(StringRef Comment) {
481
118
  BriefComment = Allocator.CopyString(Comment);
482
118
}
483
484
//===----------------------------------------------------------------------===//
485
// Code completion overload candidate implementation
486
//===----------------------------------------------------------------------===//
487
239
FunctionDecl *CodeCompleteConsumer::OverloadCandidate::getFunction() const {
488
239
  if (getKind() == CK_Function)
489
234
    return Function;
490
5
  else if (getKind() == CK_FunctionTemplate)
491
0
    return FunctionTemplate->getTemplatedDecl();
492
5
  else
493
5
    return nullptr;
494
239
}
495
496
const FunctionType *
497
516
CodeCompleteConsumer::OverloadCandidate::getFunctionType() const {
498
516
  switch (Kind) {
499
506
  case CK_Function:
500
506
    return Function->getType()->getAs<FunctionType>();
501
0
502
0
  case CK_FunctionTemplate:
503
0
    return FunctionTemplate->getTemplatedDecl()
504
0
        ->getType()
505
0
        ->getAs<FunctionType>();
506
0
507
10
  case CK_FunctionType:
508
10
    return Type;
509
0
  }
510
0
511
0
  llvm_unreachable("Invalid CandidateKind!");
512
0
}
513
514
//===----------------------------------------------------------------------===//
515
// Code completion consumer implementation
516
//===----------------------------------------------------------------------===//
517
518
1.93k
CodeCompleteConsumer::~CodeCompleteConsumer() = default;
519
520
bool PrintingCodeCompleteConsumer::isResultFilteredOut(
521
4.94k
    StringRef Filter, CodeCompletionResult Result) {
522
4.94k
  switch (Result.Kind) {
523
32
  case CodeCompletionResult::RK_Declaration:
524
32
    return !(Result.Declaration->getIdentifier() &&
525
32
             Result.Declaration->getIdentifier()->getName().startswith(Filter));
526
405
  case CodeCompletionResult::RK_Keyword:
527
405
    return !StringRef(Result.Keyword).startswith(Filter);
528
764
  case CodeCompletionResult::RK_Macro:
529
764
    return !Result.Macro->getName().startswith(Filter);
530
3.74k
  case CodeCompletionResult::RK_Pattern:
531
3.74k
    return !(Result.Pattern->getTypedText() &&
532
3.74k
             StringRef(Result.Pattern->getTypedText()).startswith(Filter));
533
0
  }
534
0
  llvm_unreachable("Unknown code completion result Kind.");
535
0
}
536
537
void PrintingCodeCompleteConsumer::ProcessCodeCompleteResults(
538
    Sema &SemaRef, CodeCompletionContext Context, CodeCompletionResult *Results,
539
259
    unsigned NumResults) {
540
259
  std::stable_sort(Results, Results + NumResults);
541
259
542
259
  if (!Context.getPreferredType().isNull())
543
44
    OS << "PREFERRED-TYPE: " << Context.getPreferredType().getAsString()
544
44
       << "\n";
545
259
546
259
  StringRef Filter = SemaRef.getPreprocessor().getCodeCompletionFilter();
547
  // Print the completions.
548
14.0k
  for (unsigned I = 0; I != NumResults; 
++I13.7k
) {
549
13.7k
    if (!Filter.empty() && 
isResultFilteredOut(Filter, Results[I])4.94k
)
550
4.89k
      continue;
551
8.85k
    OS << "COMPLETION: ";
552
8.85k
    switch (Results[I].Kind) {
553
1.13k
    case CodeCompletionResult::RK_Declaration:
554
1.13k
      OS << *Results[I].Declaration;
555
1.13k
      {
556
1.13k
        std::vector<std::string> Tags;
557
1.13k
        if (Results[I].Hidden)
558
99
          Tags.push_back("Hidden");
559
1.13k
        if (Results[I].InBaseClass)
560
158
          Tags.push_back("InBase");
561
1.13k
        if (Results[I].Availability ==
562
1.13k
            CXAvailabilityKind::CXAvailability_NotAccessible)
563
29
          Tags.push_back("Inaccessible");
564
1.13k
        if (!Tags.empty())
565
221
          OS << " (" << llvm::join(Tags, ",") << ")";
566
1.13k
      }
567
1.13k
      if (CodeCompletionString *CCS = Results[I].CreateCodeCompletionString(
568
1.13k
              SemaRef, Context, getAllocator(), CCTUInfo,
569
1.13k
              includeBriefComments())) {
570
1.13k
        OS << " : " << CCS->getAsString();
571
1.13k
        if (const char *BriefComment = CCS->getBriefComment())
572
9
          OS << " : " << BriefComment;
573
1.13k
      }
574
1.13k
      break;
575
0
576
2.78k
    case CodeCompletionResult::RK_Keyword:
577
2.78k
      OS << Results[I].Keyword;
578
2.78k
      break;
579
0
580
1.43k
    case CodeCompletionResult::RK_Macro:
581
1.43k
      OS << Results[I].Macro->getName();
582
1.43k
      if (CodeCompletionString *CCS = Results[I].CreateCodeCompletionString(
583
1.43k
              SemaRef, Context, getAllocator(), CCTUInfo,
584
1.43k
              includeBriefComments())) {
585
1.43k
        OS << " : " << CCS->getAsString();
586
1.43k
      }
587
1.43k
      break;
588
0
589
3.50k
    case CodeCompletionResult::RK_Pattern:
590
3.50k
      OS << "Pattern : " << Results[I].Pattern->getAsString();
591
3.50k
      break;
592
8.85k
    }
593
8.85k
    for (const FixItHint &FixIt : Results[I].FixIts) {
594
38
      const SourceLocation BLoc = FixIt.RemoveRange.getBegin();
595
38
      const SourceLocation ELoc = FixIt.RemoveRange.getEnd();
596
38
597
38
      SourceManager &SM = SemaRef.SourceMgr;
598
38
      std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
599
38
      std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
600
      // Adjust for token ranges.
601
38
      if (FixIt.RemoveRange.isTokenRange())
602
38
        EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, SemaRef.LangOpts);
603
38
604
38
      OS << " (requires fix-it:"
605
38
         << " {" << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
606
38
         << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
607
38
         << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
608
38
         << SM.getColumnNumber(EInfo.first, EInfo.second) << "}"
609
38
         << " to \"" << FixIt.CodeToInsert << "\")";
610
38
    }
611
8.85k
    OS << '\n';
612
8.85k
  }
613
259
}
614
615
// This function is used solely to preserve the former presentation of overloads
616
// by "clang -cc1 -code-completion-at", since CodeCompletionString::getAsString
617
// needs to be improved for printing the newer and more detailed overload
618
// chunks.
619
76
static std::string getOverloadAsString(const CodeCompletionString &CCS) {
620
76
  std::string Result;
621
76
  llvm::raw_string_ostream OS(Result);
622
76
623
449
  for (auto &C : CCS) {
624
449
    switch (C.Kind) {
625
42
    case CodeCompletionString::CK_Informative:
626
42
    case CodeCompletionString::CK_ResultType:
627
42
      OS << "[#" << C.Text << "#]";
628
42
      break;
629
42
630
67
    case CodeCompletionString::CK_CurrentParameter:
631
67
      OS << "<#" << C.Text << "#>";
632
67
      break;
633
42
634
    // FIXME: We can also print optional parameters of an overload.
635
6
    case CodeCompletionString::CK_Optional:
636
6
      break;
637
42
638
334
    default:
639
334
      OS << C.Text;
640
334
      break;
641
449
    }
642
449
  }
643
76
  return OS.str();
644
76
}
645
646
void PrintingCodeCompleteConsumer::ProcessOverloadCandidates(
647
    Sema &SemaRef, unsigned CurrentArg, OverloadCandidate *Candidates,
648
37
    unsigned NumCandidates, SourceLocation OpenParLoc) {
649
37
  OS << "OPENING_PAREN_LOC: ";
650
37
  OpenParLoc.print(OS, SemaRef.getSourceManager());
651
37
  OS << "\n";
652
37
653
113
  for (unsigned I = 0; I != NumCandidates; 
++I76
) {
654
76
    if (CodeCompletionString *CCS = Candidates[I].CreateSignatureString(
655
76
            CurrentArg, SemaRef, getAllocator(), CCTUInfo,
656
76
            includeBriefComments())) {
657
76
      OS << "OVERLOAD: " << getOverloadAsString(*CCS) << "\n";
658
76
    }
659
76
  }
660
37
}
661
662
/// Retrieve the effective availability of the given declaration.
663
17.9k
static AvailabilityResult getDeclAvailability(const Decl *D) {
664
17.9k
  AvailabilityResult AR = D->getAvailability();
665
17.9k
  if (isa<EnumConstantDecl>(D))
666
193
    AR = std::max(AR, cast<Decl>(D->getDeclContext())->getAvailability());
667
17.9k
  return AR;
668
17.9k
}
669
670
17.9k
void CodeCompletionResult::computeCursorKindAndAvailability(bool Accessible) {
671
17.9k
  switch (Kind) {
672
243
  case RK_Pattern:
673
243
    if (!Declaration) {
674
      // Do nothing: Patterns can come with cursor kinds!
675
0
      break;
676
0
    }
677
243
    LLVM_FALLTHROUGH;
678
243
679
17.9k
  case RK_Declaration: {
680
    // Set the availability based on attributes.
681
17.9k
    switch (getDeclAvailability(Declaration)) {
682
17.8k
    case AR_Available:
683
17.8k
    case AR_NotYetIntroduced:
684
17.8k
      Availability = CXAvailability_Available;
685
17.8k
      break;
686
17.8k
687
19
    case AR_Deprecated:
688
19
      Availability = CXAvailability_Deprecated;
689
19
      break;
690
17.8k
691
20
    case AR_Unavailable:
692
20
      Availability = CXAvailability_NotAvailable;
693
20
      break;
694
17.9k
    }
695
17.9k
696
17.9k
    if (const auto *Function = dyn_cast<FunctionDecl>(Declaration))
697
4.71k
      if (Function->isDeleted())
698
30
        Availability = CXAvailability_NotAvailable;
699
17.9k
700
17.9k
    CursorKind = getCursorKindForDecl(Declaration);
701
17.9k
    if (CursorKind == CXCursor_UnexposedDecl) {
702
      // FIXME: Forward declarations of Objective-C classes and protocols
703
      // are not directly exposed, but we want code completion to treat them
704
      // like a definition.
705
195
      if (isa<ObjCInterfaceDecl>(Declaration))
706
0
        CursorKind = CXCursor_ObjCInterfaceDecl;
707
195
      else if (isa<ObjCProtocolDecl>(Declaration))
708
0
        CursorKind = CXCursor_ObjCProtocolDecl;
709
195
      else
710
195
        CursorKind = CXCursor_NotImplemented;
711
195
    }
712
17.9k
    break;
713
17.9k
  }
714
17.9k
715
0
  case RK_Macro:
716
0
  case RK_Keyword:
717
0
    llvm_unreachable("Macro and keyword kinds are handled by the constructors");
718
17.9k
  }
719
17.9k
720
17.9k
  if (!Accessible)
721
83
    Availability = CXAvailability_NotAccessible;
722
17.9k
}
723
724
/// Retrieve the name that should be used to order a result.
725
///
726
/// If the name needs to be constructed as a string, that string will be
727
/// saved into Saved and the returned StringRef will refer to it.
728
171k
StringRef CodeCompletionResult::getOrderedName(std::string &Saved) const {
729
171k
  switch (Kind) {
730
30.3k
  case RK_Keyword:
731
30.3k
    return Keyword;
732
100k
  case RK_Pattern:
733
100k
    return Pattern->getTypedText();
734
32.1k
  case RK_Macro:
735
32.1k
    return Macro->getName();
736
8.04k
  case RK_Declaration:
737
    // Handle declarations below.
738
8.04k
    break;
739
8.04k
  }
740
8.04k
741
8.04k
  DeclarationName Name = Declaration->getDeclName();
742
8.04k
743
  // If the name is a simple identifier (by far the common case), or a
744
  // zero-argument selector, just return a reference to that identifier.
745
8.04k
  if (IdentifierInfo *Id = Name.getAsIdentifierInfo())
746
6.01k
    return Id->getName();
747
2.03k
  if (Name.isObjCZeroArgSelector())
748
42
    if (IdentifierInfo *Id = Name.getObjCSelector().getIdentifierInfoForSlot(0))
749
42
      return Id->getName();
750
1.99k
751
1.99k
  Saved = Name.getAsString();
752
1.99k
  return Saved;
753
1.99k
}
754
755
bool clang::operator<(const CodeCompletionResult &X,
756
85.5k
                      const CodeCompletionResult &Y) {
757
85.5k
  std::string XSaved, YSaved;
758
85.5k
  StringRef XStr = X.getOrderedName(XSaved);
759
85.5k
  StringRef YStr = Y.getOrderedName(YSaved);
760
85.5k
  int cmp = XStr.compare_lower(YStr);
761
85.5k
  if (cmp)
762
84.7k
    return cmp < 0;
763
844
764
  // If case-insensitive comparison fails, try case-sensitive comparison.
765
844
  return XStr.compare(YStr) < 0;
766
844
}