Coverage Report

Created: 2021-06-15 06:44

/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.17k
bool CodeCompletionContext::wantConstructorResults() const {
46
5.17k
  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
    return false;
86
5.17k
  }
87
88
5.17k
  
llvm_unreachable0
("Invalid CodeCompletionContext::Kind!");
89
5.17k
}
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
228k
    : Kind(Kind), Text("") {
176
228k
  switch (Kind) {
177
163k
  case CK_TypedText:
178
165k
  case CK_Text:
179
183k
  case CK_Placeholder:
180
183k
  case CK_Informative:
181
193k
  case CK_ResultType:
182
193k
  case CK_CurrentParameter:
183
193k
    this->Text = Text;
184
193k
    break;
185
186
0
  case CK_Optional:
187
0
    llvm_unreachable("Optional strings cannot be created from text");
188
189
10.2k
  case CK_LeftParen:
190
10.2k
    this->Text = "(";
191
10.2k
    break;
192
193
10.3k
  case CK_RightParen:
194
10.3k
    this->Text = ")";
195
10.3k
    break;
196
197
820
  case CK_LeftBracket:
198
820
    this->Text = "[";
199
820
    break;
200
201
925
  case CK_RightBracket:
202
925
    this->Text = "]";
203
925
    break;
204
205
176
  case CK_LeftBrace:
206
176
    this->Text = "{";
207
176
    break;
208
209
281
  case CK_RightBrace:
210
281
    this->Text = "}";
211
281
    break;
212
213
1.87k
  case CK_LeftAngle:
214
1.87k
    this->Text = "<";
215
1.87k
    break;
216
217
1.87k
  case CK_RightAngle:
218
1.87k
    this->Text = ">";
219
1.87k
    break;
220
221
1.62k
  case CK_Comma:
222
1.62k
    this->Text = ", ";
223
1.62k
    break;
224
225
130
  case CK_Colon:
226
130
    this->Text = ":";
227
130
    break;
228
229
1.04k
  case CK_SemiColon:
230
1.04k
    this->Text = ";";
231
1.04k
    break;
232
233
167
  case CK_Equal:
234
167
    this->Text = " = ";
235
167
    break;
236
237
5.11k
  case CK_HorizontalSpace:
238
5.11k
    this->Text = " ";
239
5.11k
    break;
240
241
314
  case CK_VerticalSpace:
242
314
    this->Text = "\n";
243
314
    break;
244
228k
  }
245
228k
}
246
247
CodeCompletionString::Chunk
248
1.82k
CodeCompletionString::Chunk::CreateText(const char *Text) {
249
1.82k
  return Chunk(CK_Text, Text);
250
1.82k
}
251
252
CodeCompletionString::Chunk
253
110
CodeCompletionString::Chunk::CreateOptional(CodeCompletionString *Optional) {
254
110
  Chunk Result;
255
110
  Result.Kind = CK_Optional;
256
110
  Result.Optional = Optional;
257
110
  return Result;
258
110
}
259
260
CodeCompletionString::Chunk
261
17.7k
CodeCompletionString::Chunk::CreatePlaceholder(const char *Placeholder) {
262
17.7k
  return Chunk(CK_Placeholder, Placeholder);
263
17.7k
}
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.51k
CodeCompletionString::Chunk::CreateResultType(const char *ResultType) {
272
9.51k
  return Chunk(CK_ResultType, ResultType);
273
9.51k
}
274
275
CodeCompletionString::Chunk CodeCompletionString::Chunk::CreateCurrentParameter(
276
223
    const char *CurrentParameter) {
277
223
  return Chunk(CK_CurrentParameter, CurrentParameter);
278
223
}
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
163k
      BriefComment(BriefComment) {
287
163k
  assert(NumChunks <= 0xffff);
288
0
  assert(NumAnnotations <= 0xffff);
289
290
0
  Chunk *StoredChunks = reinterpret_cast<Chunk *>(this + 1);
291
392k
  for (unsigned I = 0; I != NumChunks; 
++I228k
)
292
228k
    StoredChunks[I] = Chunks[I];
293
294
163k
  const char **StoredAnnotations =
295
163k
      reinterpret_cast<const char **>(StoredChunks + NumChunks);
296
163k
  for (unsigned I = 0; I != NumAnnotations; 
++I6
)
297
6
    StoredAnnotations[I] = Annotations[I];
298
163k
}
299
300
113k
unsigned CodeCompletionString::getAnnotationCount() const {
301
113k
  return NumAnnotations;
302
113k
}
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.64k
std::string CodeCompletionString::getAsString() const {
312
6.64k
  std::string Result;
313
6.64k
  llvm::raw_string_ostream OS(Result);
314
315
20.1k
  for (const Chunk &C : *this) {
316
20.1k
    switch (C.Kind) {
317
24
    case CK_Optional:
318
24
      OS << "{#" << C.Optional->getAsString() << "#}";
319
24
      break;
320
3.65k
    case CK_Placeholder:
321
3.65k
      OS << "<#" << C.Text << "#>";
322
3.65k
      break;
323
80
    case CK_Informative:
324
1.87k
    case CK_ResultType:
325
1.87k
      OS << "[#" << C.Text << "#]";
326
1.87k
      break;
327
0
    case CK_CurrentParameter:
328
0
      OS << "<#" << C.Text << "#>";
329
0
      break;
330
14.6k
    default:
331
14.6k
      OS << C.Text;
332
14.6k
      break;
333
20.1k
    }
334
20.1k
  }
335
6.64k
  return OS.str();
336
6.64k
}
337
338
128k
const char *CodeCompletionString::getTypedText() const {
339
128k
  for (const Chunk &C : *this)
340
137k
    if (C.Kind == CK_TypedText)
341
127k
      return C.Text;
342
343
73
  return nullptr;
344
128k
}
345
346
150k
const char *CodeCompletionAllocator::CopyString(const Twine &String) {
347
150k
  SmallString<128> Data;
348
150k
  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
150k
  char *Mem = (char *)Allocate(Ref.size() + 1, 1);
353
150k
  std::copy(Ref.begin(), Ref.end(), Mem);
354
150k
  Mem[Ref.size()] = 0;
355
150k
  return Mem;
356
150k
}
357
358
2.13k
StringRef CodeCompletionTUInfo::getParentName(const DeclContext *DC) {
359
2.13k
  if (!isa<NamedDecl>(DC))
360
0
    return {};
361
362
  // Check whether we've already cached the parent name.
363
2.13k
  StringRef &CachedParentName = ParentNames[DC];
364
2.13k
  if (!CachedParentName.empty())
365
1.43k
    return CachedParentName;
366
367
  // If we already processed this DeclContext and assigned empty to it, the
368
  // data pointer will be non-null.
369
699
  if (CachedParentName.data() != nullptr)
370
10
    return {};
371
372
  // Find the interesting names.
373
689
  SmallVector<const DeclContext *, 2> Contexts;
374
2.09k
  while (DC && 
!DC->isFunctionOrMethod()1.40k
) {
375
1.40k
    if (const auto *ND = dyn_cast<NamedDecl>(DC)) {
376
716
      if (ND->getIdentifier())
377
693
        Contexts.push_back(DC);
378
716
    }
379
380
1.40k
    DC = DC->getParent();
381
1.40k
  }
382
383
689
  {
384
689
    SmallString<128> S;
385
689
    llvm::raw_svector_ostream OS(S);
386
689
    bool First = true;
387
1.38k
    for (unsigned I = Contexts.size(); I != 0; 
--I693
) {
388
693
      if (First)
389
670
        First = false;
390
23
      else {
391
23
        OS << "::";
392
23
      }
393
394
693
      const DeclContext *CurDC = Contexts[I - 1];
395
693
      if (const auto *CatImpl = dyn_cast<ObjCCategoryImplDecl>(CurDC))
396
0
        CurDC = CatImpl->getCategoryDecl();
397
398
693
      if (const auto *Cat = dyn_cast<ObjCCategoryDecl>(CurDC)) {
399
17
        const ObjCInterfaceDecl *Interface = Cat->getClassInterface();
400
17
        if (!Interface) {
401
          // Assign an empty StringRef but with non-null data to distinguish
402
          // between empty because we didn't process the DeclContext yet.
403
0
          CachedParentName = StringRef((const char *)(uintptr_t)~0U, 0);
404
0
          return {};
405
0
        }
406
407
17
        OS << Interface->getName() << '(' << Cat->getName() << ')';
408
676
      } else {
409
676
        OS << cast<NamedDecl>(CurDC)->getName();
410
676
      }
411
693
    }
412
413
689
    CachedParentName = AllocatorRef->CopyString(OS.str());
414
689
  }
415
416
0
  return CachedParentName;
417
689
}
418
419
163k
CodeCompletionString *CodeCompletionBuilder::TakeString() {
420
163k
  void *Mem = getAllocator().Allocate(
421
163k
      sizeof(CodeCompletionString) + sizeof(Chunk) * Chunks.size() +
422
163k
          sizeof(const char *) * Annotations.size(),
423
163k
      alignof(CodeCompletionString));
424
163k
  CodeCompletionString *Result = new (Mem) CodeCompletionString(
425
163k
      Chunks.data(), Chunks.size(), Priority, Availability, Annotations.data(),
426
163k
      Annotations.size(), ParentName, BriefComment);
427
163k
  Chunks.clear();
428
163k
  return Result;
429
163k
}
430
431
163k
void CodeCompletionBuilder::AddTypedTextChunk(const char *Text) {
432
163k
  Chunks.push_back(Chunk(CodeCompletionString::CK_TypedText, Text));
433
163k
}
434
435
1.82k
void CodeCompletionBuilder::AddTextChunk(const char *Text) {
436
1.82k
  Chunks.push_back(Chunk::CreateText(Text));
437
1.82k
}
438
439
110
void CodeCompletionBuilder::AddOptionalChunk(CodeCompletionString *Optional) {
440
110
  Chunks.push_back(Chunk::CreateOptional(Optional));
441
110
}
442
443
17.7k
void CodeCompletionBuilder::AddPlaceholderChunk(const char *Placeholder) {
444
17.7k
  Chunks.push_back(Chunk::CreatePlaceholder(Placeholder));
445
17.7k
}
446
447
228
void CodeCompletionBuilder::AddInformativeChunk(const char *Text) {
448
228
  Chunks.push_back(Chunk::CreateInformative(Text));
449
228
}
450
451
9.51k
void CodeCompletionBuilder::AddResultTypeChunk(const char *ResultType) {
452
9.51k
  Chunks.push_back(Chunk::CreateResultType(ResultType));
453
9.51k
}
454
455
void CodeCompletionBuilder::AddCurrentParameterChunk(
456
223
    const char *CurrentParameter) {
457
223
  Chunks.push_back(Chunk::CreateCurrentParameter(CurrentParameter));
458
223
}
459
460
void CodeCompletionBuilder::AddChunk(CodeCompletionString::ChunkKind CK,
461
34.8k
                                     const char *Text) {
462
34.8k
  Chunks.push_back(Chunk(CK, Text));
463
34.8k
}
464
465
5.63k
void CodeCompletionBuilder::addParentContext(const DeclContext *DC) {
466
5.63k
  if (DC->isTranslationUnit())
467
3.04k
    return;
468
469
2.59k
  if (DC->isFunctionOrMethod())
470
458
    return;
471
472
2.13k
  if (!isa<NamedDecl>(DC))
473
0
    return;
474
475
2.13k
  ParentName = getCodeCompletionTUInfo().getParentName(DC);
476
2.13k
}
477
478
118
void CodeCompletionBuilder::addBriefComment(StringRef Comment) {
479
118
  BriefComment = Allocator.CopyString(Comment);
480
118
}
481
482
//===----------------------------------------------------------------------===//
483
// Code completion overload candidate implementation
484
//===----------------------------------------------------------------------===//
485
242
FunctionDecl *CodeCompleteConsumer::OverloadCandidate::getFunction() const {
486
242
  if (getKind() == CK_Function)
487
237
    return Function;
488
5
  else if (getKind() == CK_FunctionTemplate)
489
0
    return FunctionTemplate->getTemplatedDecl();
490
5
  else
491
5
    return nullptr;
492
242
}
493
494
const FunctionType *
495
530
CodeCompleteConsumer::OverloadCandidate::getFunctionType() const {
496
530
  switch (Kind) {
497
520
  case CK_Function:
498
520
    return Function->getType()->getAs<FunctionType>();
499
500
0
  case CK_FunctionTemplate:
501
0
    return FunctionTemplate->getTemplatedDecl()
502
0
        ->getType()
503
0
        ->getAs<FunctionType>();
504
505
10
  case CK_FunctionType:
506
10
    return Type;
507
530
  }
508
509
530
  
llvm_unreachable0
("Invalid CandidateKind!");
510
530
}
511
512
//===----------------------------------------------------------------------===//
513
// Code completion consumer implementation
514
//===----------------------------------------------------------------------===//
515
516
1.95k
CodeCompleteConsumer::~CodeCompleteConsumer() = default;
517
518
bool PrintingCodeCompleteConsumer::isResultFilteredOut(
519
5.04k
    StringRef Filter, CodeCompletionResult Result) {
520
5.04k
  switch (Result.Kind) {
521
32
  case CodeCompletionResult::RK_Declaration:
522
32
    return !(Result.Declaration->getIdentifier() &&
523
32
             Result.Declaration->getIdentifier()->getName().startswith(Filter));
524
405
  case CodeCompletionResult::RK_Keyword:
525
405
    return !StringRef(Result.Keyword).startswith(Filter);
526
770
  case CodeCompletionResult::RK_Macro:
527
770
    return !Result.Macro->getName().startswith(Filter);
528
3.83k
  case CodeCompletionResult::RK_Pattern:
529
3.83k
    return !(Result.Pattern->getTypedText() &&
530
3.83k
             StringRef(Result.Pattern->getTypedText()).startswith(Filter));
531
5.04k
  }
532
5.04k
  
llvm_unreachable0
("Unknown code completion result Kind.");
533
5.04k
}
534
535
void PrintingCodeCompleteConsumer::ProcessCodeCompleteResults(
536
    Sema &SemaRef, CodeCompletionContext Context, CodeCompletionResult *Results,
537
273
    unsigned NumResults) {
538
273
  std::stable_sort(Results, Results + NumResults);
539
540
273
  if (!Context.getPreferredType().isNull())
541
44
    OS << "PREFERRED-TYPE: " << Context.getPreferredType().getAsString()
542
44
       << "\n";
543
544
273
  StringRef Filter = SemaRef.getPreprocessor().getCodeCompletionFilter();
545
  // Print the completions.
546
14.3k
  for (unsigned I = 0; I != NumResults; 
++I14.0k
) {
547
14.0k
    if (!Filter.empty() && 
isResultFilteredOut(Filter, Results[I])5.04k
)
548
4.98k
      continue;
549
9.09k
    OS << "COMPLETION: ";
550
9.09k
    switch (Results[I].Kind) {
551
1.18k
    case CodeCompletionResult::RK_Declaration:
552
1.18k
      OS << *Results[I].Declaration;
553
1.18k
      {
554
1.18k
        std::vector<std::string> Tags;
555
1.18k
        if (Results[I].Hidden)
556
99
          Tags.push_back("Hidden");
557
1.18k
        if (Results[I].InBaseClass)
558
158
          Tags.push_back("InBase");
559
1.18k
        if (Results[I].Availability ==
560
1.18k
            CXAvailabilityKind::CXAvailability_NotAccessible)
561
29
          Tags.push_back("Inaccessible");
562
1.18k
        if (!Tags.empty())
563
221
          OS << " (" << llvm::join(Tags, ",") << ")";
564
1.18k
      }
565
1.18k
      if (CodeCompletionString *CCS = Results[I].CreateCodeCompletionString(
566
1.18k
              SemaRef, Context, getAllocator(), CCTUInfo,
567
1.18k
              includeBriefComments())) {
568
1.18k
        OS << " : " << CCS->getAsString();
569
1.18k
        if (const char *BriefComment = CCS->getBriefComment())
570
9
          OS << " : " << BriefComment;
571
1.18k
      }
572
1.18k
      break;
573
574
2.86k
    case CodeCompletionResult::RK_Keyword:
575
2.86k
      OS << Results[I].Keyword;
576
2.86k
      break;
577
578
1.44k
    case CodeCompletionResult::RK_Macro:
579
1.44k
      OS << Results[I].Macro->getName();
580
1.44k
      if (CodeCompletionString *CCS = Results[I].CreateCodeCompletionString(
581
1.44k
              SemaRef, Context, getAllocator(), CCTUInfo,
582
1.44k
              includeBriefComments())) {
583
1.44k
        OS << " : " << CCS->getAsString();
584
1.44k
      }
585
1.44k
      break;
586
587
3.60k
    case CodeCompletionResult::RK_Pattern:
588
3.60k
      OS << "Pattern : " << Results[I].Pattern->getAsString();
589
3.60k
      break;
590
9.09k
    }
591
9.09k
    for (const FixItHint &FixIt : Results[I].FixIts) {
592
38
      const SourceLocation BLoc = FixIt.RemoveRange.getBegin();
593
38
      const SourceLocation ELoc = FixIt.RemoveRange.getEnd();
594
595
38
      SourceManager &SM = SemaRef.SourceMgr;
596
38
      std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
597
38
      std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
598
      // Adjust for token ranges.
599
38
      if (FixIt.RemoveRange.isTokenRange())
600
38
        EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, SemaRef.LangOpts);
601
602
38
      OS << " (requires fix-it:"
603
38
         << " {" << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
604
38
         << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
605
38
         << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
606
38
         << SM.getColumnNumber(EInfo.first, EInfo.second) << "}"
607
38
         << " to \"" << FixIt.CodeToInsert << "\")";
608
38
    }
609
9.09k
    OS << '\n';
610
9.09k
  }
611
273
}
612
613
// This function is used solely to preserve the former presentation of overloads
614
// by "clang -cc1 -code-completion-at", since CodeCompletionString::getAsString
615
// needs to be improved for printing the newer and more detailed overload
616
// chunks.
617
79
static std::string getOverloadAsString(const CodeCompletionString &CCS) {
618
79
  std::string Result;
619
79
  llvm::raw_string_ostream OS(Result);
620
621
471
  for (auto &C : CCS) {
622
471
    switch (C.Kind) {
623
0
    case CodeCompletionString::CK_Informative:
624
45
    case CodeCompletionString::CK_ResultType:
625
45
      OS << "[#" << C.Text << "#]";
626
45
      break;
627
628
69
    case CodeCompletionString::CK_CurrentParameter:
629
69
      OS << "<#" << C.Text << "#>";
630
69
      break;
631
632
    // FIXME: We can also print optional parameters of an overload.
633
10
    case CodeCompletionString::CK_Optional:
634
10
      break;
635
636
347
    default:
637
347
      OS << C.Text;
638
347
      break;
639
471
    }
640
471
  }
641
79
  return OS.str();
642
79
}
643
644
void PrintingCodeCompleteConsumer::ProcessOverloadCandidates(
645
    Sema &SemaRef, unsigned CurrentArg, OverloadCandidate *Candidates,
646
38
    unsigned NumCandidates, SourceLocation OpenParLoc) {
647
38
  OS << "OPENING_PAREN_LOC: ";
648
38
  OpenParLoc.print(OS, SemaRef.getSourceManager());
649
38
  OS << "\n";
650
651
117
  for (unsigned I = 0; I != NumCandidates; 
++I79
) {
652
79
    if (CodeCompletionString *CCS = Candidates[I].CreateSignatureString(
653
79
            CurrentArg, SemaRef, getAllocator(), CCTUInfo,
654
79
            includeBriefComments())) {
655
79
      OS << "OVERLOAD: " << getOverloadAsString(*CCS) << "\n";
656
79
    }
657
79
  }
658
38
}
659
660
/// Retrieve the effective availability of the given declaration.
661
18.1k
static AvailabilityResult getDeclAvailability(const Decl *D) {
662
18.1k
  AvailabilityResult AR = D->getAvailability();
663
18.1k
  if (isa<EnumConstantDecl>(D))
664
193
    AR = std::max(AR, cast<Decl>(D->getDeclContext())->getAvailability());
665
18.1k
  return AR;
666
18.1k
}
667
668
18.1k
void CodeCompletionResult::computeCursorKindAndAvailability(bool Accessible) {
669
18.1k
  switch (Kind) {
670
243
  case RK_Pattern:
671
243
    if (!Declaration) {
672
      // Do nothing: Patterns can come with cursor kinds!
673
0
      break;
674
0
    }
675
243
    LLVM_FALLTHROUGH;
676
677
18.1k
  case RK_Declaration: {
678
    // Set the availability based on attributes.
679
18.1k
    switch (getDeclAvailability(Declaration)) {
680
18.0k
    case AR_Available:
681
18.0k
    case AR_NotYetIntroduced:
682
18.0k
      Availability = CXAvailability_Available;
683
18.0k
      break;
684
685
19
    case AR_Deprecated:
686
19
      Availability = CXAvailability_Deprecated;
687
19
      break;
688
689
20
    case AR_Unavailable:
690
20
      Availability = CXAvailability_NotAvailable;
691
20
      break;
692
18.1k
    }
693
694
18.1k
    if (const auto *Function = dyn_cast<FunctionDecl>(Declaration))
695
4.74k
      if (Function->isDeleted())
696
36
        Availability = CXAvailability_NotAvailable;
697
698
18.1k
    CursorKind = getCursorKindForDecl(Declaration);
699
18.1k
    if (CursorKind == CXCursor_UnexposedDecl) {
700
      // FIXME: Forward declarations of Objective-C classes and protocols
701
      // are not directly exposed, but we want code completion to treat them
702
      // like a definition.
703
195
      if (isa<ObjCInterfaceDecl>(Declaration))
704
0
        CursorKind = CXCursor_ObjCInterfaceDecl;
705
195
      else if (isa<ObjCProtocolDecl>(Declaration))
706
0
        CursorKind = CXCursor_ObjCProtocolDecl;
707
195
      else
708
195
        CursorKind = CXCursor_NotImplemented;
709
195
    }
710
18.1k
    break;
711
18.1k
  }
712
713
0
  case RK_Macro:
714
0
  case RK_Keyword:
715
0
    llvm_unreachable("Macro and keyword kinds are handled by the constructors");
716
18.1k
  }
717
718
18.1k
  if (!Accessible)
719
83
    Availability = CXAvailability_NotAccessible;
720
18.1k
}
721
722
/// Retrieve the name that should be used to order a result.
723
///
724
/// If the name needs to be constructed as a string, that string will be
725
/// saved into Saved and the returned StringRef will refer to it.
726
175k
StringRef CodeCompletionResult::getOrderedName(std::string &Saved) const {
727
175k
  switch (Kind) {
728
31.0k
  case RK_Keyword:
729
31.0k
    return Keyword;
730
103k
  case RK_Pattern:
731
103k
    return Pattern->getTypedText();
732
32.3k
  case RK_Macro:
733
32.3k
    return Macro->getName();
734
8.45k
  case RK_Declaration:
735
    // Handle declarations below.
736
8.45k
    break;
737
175k
  }
738
739
8.45k
  DeclarationName Name = Declaration->getDeclName();
740
741
  // If the name is a simple identifier (by far the common case), or a
742
  // zero-argument selector, just return a reference to that identifier.
743
8.45k
  if (IdentifierInfo *Id = Name.getAsIdentifierInfo())
744
6.36k
    return Id->getName();
745
2.08k
  if (Name.isObjCZeroArgSelector())
746
42
    if (IdentifierInfo *Id = Name.getObjCSelector().getIdentifierInfoForSlot(0))
747
42
      return Id->getName();
748
749
2.04k
  Saved = Name.getAsString();
750
2.04k
  return Saved;
751
2.08k
}
752
753
bool clang::operator<(const CodeCompletionResult &X,
754
87.5k
                      const CodeCompletionResult &Y) {
755
87.5k
  std::string XSaved, YSaved;
756
87.5k
  StringRef XStr = X.getOrderedName(XSaved);
757
87.5k
  StringRef YStr = Y.getOrderedName(YSaved);
758
87.5k
  int cmp = XStr.compare_lower(YStr);
759
87.5k
  if (cmp)
760
86.7k
    return cmp < 0;
761
762
  // If case-insensitive comparison fails, try case-sensitive comparison.
763
866
  return XStr.compare(YStr) < 0;
764
87.5k
}