Coverage Report

Created: 2021-09-21 08:58

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