Coverage Report

Created: 2022-01-25 06:29

/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.32k
bool CodeCompletionContext::wantConstructorResults() const {
46
5.32k
  switch (CCKind) {
47
109
  case CCC_Recovery:
48
1.16k
  case CCC_Statement:
49
4.01k
  case CCC_Expression:
50
4.03k
  case CCC_ObjCMessageReceiver:
51
4.13k
  case CCC_ParenthesizedExpression:
52
4.40k
  case CCC_Symbol:
53
4.40k
  case CCC_SymbolOrNewName:
54
4.40k
    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
668
  case CCC_DotMemberAccess:
62
877
  case CCC_ArrowMemberAccess:
63
877
  case CCC_ObjCPropertyAccess:
64
877
  case CCC_EnumTag:
65
877
  case CCC_UnionTag:
66
884
  case CCC_ClassOrStructTag:
67
884
  case CCC_ObjCProtocolName:
68
894
  case CCC_Namespace:
69
897
  case CCC_Type:
70
897
  case CCC_NewName:
71
897
  case CCC_MacroName:
72
897
  case CCC_MacroNameUse:
73
897
  case CCC_PreprocessorExpression:
74
897
  case CCC_PreprocessorDirective:
75
897
  case CCC_NaturalLanguage:
76
897
  case CCC_SelectorName:
77
897
  case CCC_TypeQualifiers:
78
912
  case CCC_Other:
79
912
  case CCC_OtherWithMacros:
80
921
  case CCC_ObjCInstanceMessage:
81
923
  case CCC_ObjCClassMessage:
82
923
  case CCC_ObjCInterfaceName:
83
923
  case CCC_ObjCCategoryName:
84
923
  case CCC_IncludedFile:
85
923
  case CCC_Attribute:
86
923
    return false;
87
5.32k
  }
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
245k
    : Kind(Kind), Text("") {
179
245k
  switch (Kind) {
180
174k
  case CK_TypedText:
181
176k
  case CK_Text:
182
196k
  case CK_Placeholder:
183
196k
  case CK_Informative:
184
206k
  case CK_ResultType:
185
206k
  case CK_CurrentParameter:
186
206k
    this->Text = Text;
187
206k
    break;
188
189
0
  case CK_Optional:
190
0
    llvm_unreachable("Optional strings cannot be created from text");
191
192
11.8k
  case CK_LeftParen:
193
11.8k
    this->Text = "(";
194
11.8k
    break;
195
196
11.9k
  case CK_RightParen:
197
11.9k
    this->Text = ")";
198
11.9k
    break;
199
200
862
  case CK_LeftBracket:
201
862
    this->Text = "[";
202
862
    break;
203
204
967
  case CK_RightBracket:
205
967
    this->Text = "]";
206
967
    break;
207
208
204
  case CK_LeftBrace:
209
204
    this->Text = "{";
210
204
    break;
211
212
309
  case CK_RightBrace:
213
309
    this->Text = "}";
214
309
    break;
215
216
2.00k
  case CK_LeftAngle:
217
2.00k
    this->Text = "<";
218
2.00k
    break;
219
220
2.00k
  case CK_RightAngle:
221
2.00k
    this->Text = ">";
222
2.00k
    break;
223
224
2.13k
  case CK_Comma:
225
2.13k
    this->Text = ", ";
226
2.13k
    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.26k
  case CK_HorizontalSpace:
241
5.26k
    this->Text = " ";
242
5.26k
    break;
243
244
314
  case CK_VerticalSpace:
245
314
    this->Text = "\n";
246
314
    break;
247
245k
  }
248
245k
}
249
250
CodeCompletionString::Chunk
251
1.87k
CodeCompletionString::Chunk::CreateText(const char *Text) {
252
1.87k
  return Chunk(CK_Text, Text);
253
1.87k
}
254
255
CodeCompletionString::Chunk
256
113
CodeCompletionString::Chunk::CreateOptional(CodeCompletionString *Optional) {
257
113
  Chunk Result;
258
113
  Result.Kind = CK_Optional;
259
113
  Result.Optional = Optional;
260
113
  return Result;
261
113
}
262
263
CodeCompletionString::Chunk
264
20.1k
CodeCompletionString::Chunk::CreatePlaceholder(const char *Placeholder) {
265
20.1k
  return Chunk(CK_Placeholder, Placeholder);
266
20.1k
}
267
268
CodeCompletionString::Chunk
269
231
CodeCompletionString::Chunk::CreateInformative(const char *Informative) {
270
231
  return Chunk(CK_Informative, Informative);
271
231
}
272
273
CodeCompletionString::Chunk
274
9.83k
CodeCompletionString::Chunk::CreateResultType(const char *ResultType) {
275
9.83k
  return Chunk(CK_ResultType, ResultType);
276
9.83k
}
277
278
CodeCompletionString::Chunk CodeCompletionString::Chunk::CreateCurrentParameter(
279
250
    const char *CurrentParameter) {
280
250
  return Chunk(CK_CurrentParameter, CurrentParameter);
281
250
}
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
174k
      BriefComment(BriefComment) {
290
174k
  assert(NumChunks <= 0xffff);
291
0
  assert(NumAnnotations <= 0xffff);
292
293
0
  Chunk *StoredChunks = reinterpret_cast<Chunk *>(this + 1);
294
420k
  for (unsigned I = 0; I != NumChunks; 
++I245k
)
295
245k
    StoredChunks[I] = Chunks[I];
296
297
174k
  const char **StoredAnnotations =
298
174k
      reinterpret_cast<const char **>(StoredChunks + NumChunks);
299
174k
  for (unsigned I = 0; I != NumAnnotations; 
++I6
)
300
6
    StoredAnnotations[I] = Annotations[I];
301
174k
}
302
303
117k
unsigned CodeCompletionString::getAnnotationCount() const {
304
117k
  return NumAnnotations;
305
117k
}
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
10.3k
std::string CodeCompletionString::getAsString() const {
315
10.3k
  std::string Result;
316
10.3k
  llvm::raw_string_ostream OS(Result);
317
318
30.8k
  for (const Chunk &C : *this) {
319
30.8k
    switch (C.Kind) {
320
26
    case CK_Optional:
321
26
      OS << "{#" << C.Optional->getAsString() << "#}";
322
26
      break;
323
6.03k
    case CK_Placeholder:
324
6.03k
      OS << "<#" << C.Text << "#>";
325
6.03k
      break;
326
80
    case CK_Informative:
327
2.17k
    case CK_ResultType:
328
2.17k
      OS << "[#" << C.Text << "#]";
329
2.17k
      break;
330
0
    case CK_CurrentParameter:
331
0
      OS << "<#" << C.Text << "#>";
332
0
      break;
333
22.5k
    default:
334
22.5k
      OS << C.Text;
335
22.5k
      break;
336
30.8k
    }
337
30.8k
  }
338
10.3k
  return Result;
339
10.3k
}
340
341
219k
const char *CodeCompletionString::getTypedText() const {
342
219k
  for (const Chunk &C : *this)
343
230k
    if (C.Kind == CK_TypedText)
344
219k
      return C.Text;
345
346
73
  return nullptr;
347
219k
}
348
349
160k
const char *CodeCompletionAllocator::CopyString(const Twine &String) {
350
160k
  SmallString<128> Data;
351
160k
  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
160k
  char *Mem = (char *)Allocate(Ref.size() + 1, 1);
356
160k
  std::copy(Ref.begin(), Ref.end(), Mem);
357
160k
  Mem[Ref.size()] = 0;
358
160k
  return Mem;
359
160k
}
360
361
2.23k
StringRef CodeCompletionTUInfo::getParentName(const DeclContext *DC) {
362
2.23k
  if (!isa<NamedDecl>(DC))
363
0
    return {};
364
365
  // Check whether we've already cached the parent name.
366
2.23k
  StringRef &CachedParentName = ParentNames[DC];
367
2.23k
  if (!CachedParentName.empty())
368
1.50k
    return CachedParentName;
369
370
  // If we already processed this DeclContext and assigned empty to it, the
371
  // data pointer will be non-null.
372
727
  if (CachedParentName.data() != nullptr)
373
10
    return {};
374
375
  // Find the interesting names.
376
717
  SmallVector<const DeclContext *, 2> Contexts;
377
2.17k
  while (DC && 
!DC->isFunctionOrMethod()1.46k
) {
378
1.45k
    if (const auto *ND = dyn_cast<NamedDecl>(DC)) {
379
745
      if (ND->getIdentifier())
380
721
        Contexts.push_back(DC);
381
745
    }
382
383
1.45k
    DC = DC->getParent();
384
1.45k
  }
385
386
717
  {
387
717
    SmallString<128> S;
388
717
    llvm::raw_svector_ostream OS(S);
389
717
    bool First = true;
390
721
    for (const DeclContext *CurDC : llvm::reverse(Contexts)) {
391
721
      if (First)
392
698
        First = false;
393
23
      else {
394
23
        OS << "::";
395
23
      }
396
397
721
      if (const auto *CatImpl = dyn_cast<ObjCCategoryImplDecl>(CurDC))
398
0
        CurDC = CatImpl->getCategoryDecl();
399
400
721
      if (const auto *Cat = dyn_cast<ObjCCategoryDecl>(CurDC)) {
401
17
        const ObjCInterfaceDecl *Interface = Cat->getClassInterface();
402
17
        if (!Interface) {
403
          // Assign an empty StringRef but with non-null data to distinguish
404
          // between empty because we didn't process the DeclContext yet.
405
0
          CachedParentName = StringRef((const char *)(uintptr_t)~0U, 0);
406
0
          return {};
407
0
        }
408
409
17
        OS << Interface->getName() << '(' << Cat->getName() << ')';
410
704
      } else {
411
704
        OS << cast<NamedDecl>(CurDC)->getName();
412
704
      }
413
721
    }
414
415
717
    CachedParentName = AllocatorRef->CopyString(OS.str());
416
717
  }
417
418
0
  return CachedParentName;
419
717
}
420
421
174k
CodeCompletionString *CodeCompletionBuilder::TakeString() {
422
174k
  void *Mem = getAllocator().Allocate(
423
174k
      sizeof(CodeCompletionString) + sizeof(Chunk) * Chunks.size() +
424
174k
          sizeof(const char *) * Annotations.size(),
425
174k
      alignof(CodeCompletionString));
426
174k
  CodeCompletionString *Result = new (Mem) CodeCompletionString(
427
174k
      Chunks.data(), Chunks.size(), Priority, Availability, Annotations.data(),
428
174k
      Annotations.size(), ParentName, BriefComment);
429
174k
  Chunks.clear();
430
174k
  return Result;
431
174k
}
432
433
174k
void CodeCompletionBuilder::AddTypedTextChunk(const char *Text) {
434
174k
  Chunks.push_back(Chunk(CodeCompletionString::CK_TypedText, Text));
435
174k
}
436
437
1.87k
void CodeCompletionBuilder::AddTextChunk(const char *Text) {
438
1.87k
  Chunks.push_back(Chunk::CreateText(Text));
439
1.87k
}
440
441
113
void CodeCompletionBuilder::AddOptionalChunk(CodeCompletionString *Optional) {
442
113
  Chunks.push_back(Chunk::CreateOptional(Optional));
443
113
}
444
445
20.1k
void CodeCompletionBuilder::AddPlaceholderChunk(const char *Placeholder) {
446
20.1k
  Chunks.push_back(Chunk::CreatePlaceholder(Placeholder));
447
20.1k
}
448
449
231
void CodeCompletionBuilder::AddInformativeChunk(const char *Text) {
450
231
  Chunks.push_back(Chunk::CreateInformative(Text));
451
231
}
452
453
9.83k
void CodeCompletionBuilder::AddResultTypeChunk(const char *ResultType) {
454
9.83k
  Chunks.push_back(Chunk::CreateResultType(ResultType));
455
9.83k
}
456
457
void CodeCompletionBuilder::AddCurrentParameterChunk(
458
250
    const char *CurrentParameter) {
459
250
  Chunks.push_back(Chunk::CreateCurrentParameter(CurrentParameter));
460
250
}
461
462
void CodeCompletionBuilder::AddChunk(CodeCompletionString::ChunkKind CK,
463
39.2k
                                     const char *Text) {
464
39.2k
  Chunks.push_back(Chunk(CK, Text));
465
39.2k
}
466
467
5.87k
void CodeCompletionBuilder::addParentContext(const DeclContext *DC) {
468
5.87k
  if (DC->isTranslationUnit())
469
3.18k
    return;
470
471
2.68k
  if (DC->isFunctionOrMethod())
472
458
    return;
473
474
2.23k
  if (!isa<NamedDecl>(DC))
475
0
    return;
476
477
2.23k
  ParentName = getCodeCompletionTUInfo().getParentName(DC);
478
2.23k
}
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
274
FunctionDecl *CodeCompleteConsumer::OverloadCandidate::getFunction() const {
488
274
  if (getKind() == CK_Function)
489
262
    return Function;
490
12
  else if (getKind() == CK_FunctionTemplate)
491
0
    return FunctionTemplate->getTemplatedDecl();
492
12
  else
493
12
    return nullptr;
494
274
}
495
496
const FunctionType *
497
583
CodeCompleteConsumer::OverloadCandidate::getFunctionType() const {
498
583
  switch (Kind) {
499
561
  case CK_Function:
500
561
    return Function->getType()->getAs<FunctionType>();
501
502
0
  case CK_FunctionTemplate:
503
0
    return FunctionTemplate->getTemplatedDecl()
504
0
        ->getType()
505
0
        ->getAs<FunctionType>();
506
507
15
  case CK_FunctionType:
508
15
    return Type;
509
510
0
  case CK_Template:
511
7
  case CK_Aggregate:
512
7
    return nullptr;
513
583
  }
514
515
0
  llvm_unreachable("Invalid CandidateKind!");
516
0
}
517
518
10
unsigned CodeCompleteConsumer::OverloadCandidate::getNumParams() const {
519
10
  if (Kind == CK_Template)
520
0
    return Template->getTemplateParameters()->size();
521
522
10
  if (Kind == CK_Aggregate) {
523
10
    unsigned Count =
524
10
        std::distance(AggregateType->field_begin(), AggregateType->field_end());
525
10
    if (const auto *CRD = dyn_cast<CXXRecordDecl>(AggregateType))
526
10
      Count += CRD->getNumBases();
527
10
    return Count;
528
10
  }
529
530
0
  if (const auto *FT = getFunctionType())
531
0
    if (const auto *FPT = dyn_cast<FunctionProtoType>(FT))
532
0
      return FPT->getNumParams();
533
534
0
  return 0;
535
0
}
536
537
QualType
538
318
CodeCompleteConsumer::OverloadCandidate::getParamType(unsigned N) const {
539
318
  if (Kind == CK_Aggregate) {
540
7
    if (const auto *CRD = dyn_cast<CXXRecordDecl>(AggregateType)) {
541
7
      if (N < CRD->getNumBases())
542
0
        return std::next(CRD->bases_begin(), N)->getType();
543
7
      N -= CRD->getNumBases();
544
7
    }
545
7
    for (const auto *Field : AggregateType->fields())
546
15
      if (N-- == 0)
547
7
        return Field->getType();
548
0
    return QualType();
549
7
  }
550
551
311
  if (Kind == CK_Template) {
552
7
    TemplateParameterList *TPL = getTemplate()->getTemplateParameters();
553
7
    if (N < TPL->size())
554
6
      if (const auto *D = dyn_cast<NonTypeTemplateParmDecl>(TPL->getParam(N)))
555
3
        return D->getType();
556
4
    return QualType();
557
7
  }
558
559
304
  if (const auto *FT = getFunctionType())
560
304
    if (const auto *FPT = dyn_cast<FunctionProtoType>(FT))
561
303
      if (N < FPT->getNumParams())
562
274
        return FPT->getParamType(N);
563
30
  return QualType();
564
304
}
565
566
const NamedDecl *
567
3
CodeCompleteConsumer::OverloadCandidate::getParamDecl(unsigned N) const {
568
3
  if (Kind == CK_Aggregate) {
569
3
    if (const auto *CRD = dyn_cast<CXXRecordDecl>(AggregateType)) {
570
3
      if (N < CRD->getNumBases())
571
0
        return std::next(CRD->bases_begin(), N)->getType()->getAsTagDecl();
572
3
      N -= CRD->getNumBases();
573
3
    }
574
3
    for (const auto *Field : AggregateType->fields())
575
4
      if (N-- == 0)
576
3
        return Field;
577
0
    return nullptr;
578
3
  }
579
580
0
  if (Kind == CK_Template) {
581
0
    TemplateParameterList *TPL = getTemplate()->getTemplateParameters();
582
0
    if (N < TPL->size())
583
0
      return TPL->getParam(N);
584
0
    return nullptr;
585
0
  }
586
587
  // Note that if we only have a FunctionProtoType, we don't have param decls.
588
0
  if (const auto *FD = getFunction()) {
589
0
    if (N < FD->param_size())
590
0
      return FD->getParamDecl(N);
591
0
  }
592
0
  return nullptr;
593
0
}
594
595
//===----------------------------------------------------------------------===//
596
// Code completion consumer implementation
597
//===----------------------------------------------------------------------===//
598
599
1.99k
CodeCompleteConsumer::~CodeCompleteConsumer() = default;
600
601
bool PrintingCodeCompleteConsumer::isResultFilteredOut(
602
7.35k
    StringRef Filter, CodeCompletionResult Result) {
603
7.35k
  switch (Result.Kind) {
604
32
  case CodeCompletionResult::RK_Declaration:
605
32
    return !(Result.Declaration->getIdentifier() &&
606
32
             Result.Declaration->getIdentifier()->getName().startswith(Filter));
607
405
  case CodeCompletionResult::RK_Keyword:
608
405
    return !StringRef(Result.Keyword).startswith(Filter);
609
798
  case CodeCompletionResult::RK_Macro:
610
798
    return !Result.Macro->getName().startswith(Filter);
611
6.11k
  case CodeCompletionResult::RK_Pattern:
612
6.11k
    return !(Result.Pattern->getTypedText() &&
613
6.11k
             StringRef(Result.Pattern->getTypedText()).startswith(Filter));
614
7.35k
  }
615
0
  llvm_unreachable("Unknown code completion result Kind.");
616
0
}
617
618
void PrintingCodeCompleteConsumer::ProcessCodeCompleteResults(
619
    Sema &SemaRef, CodeCompletionContext Context, CodeCompletionResult *Results,
620
313
    unsigned NumResults) {
621
313
  std::stable_sort(Results, Results + NumResults);
622
623
313
  if (!Context.getPreferredType().isNull())
624
54
    OS << "PREFERRED-TYPE: " << Context.getPreferredType().getAsString()
625
54
       << "\n";
626
627
313
  StringRef Filter = SemaRef.getPreprocessor().getCodeCompletionFilter();
628
  // Print the completions.
629
20.8k
  for (unsigned I = 0; I != NumResults; 
++I20.5k
) {
630
20.5k
    if (!Filter.empty() && 
isResultFilteredOut(Filter, Results[I])7.35k
)
631
7.28k
      continue;
632
13.2k
    OS << "COMPLETION: ";
633
13.2k
    switch (Results[I].Kind) {
634
1.44k
    case CodeCompletionResult::RK_Declaration:
635
1.44k
      OS << *Results[I].Declaration;
636
1.44k
      {
637
1.44k
        std::vector<std::string> Tags;
638
1.44k
        if (Results[I].Hidden)
639
103
          Tags.push_back("Hidden");
640
1.44k
        if (Results[I].InBaseClass)
641
158
          Tags.push_back("InBase");
642
1.44k
        if (Results[I].Availability ==
643
1.44k
            CXAvailabilityKind::CXAvailability_NotAccessible)
644
29
          Tags.push_back("Inaccessible");
645
1.44k
        if (!Tags.empty())
646
225
          OS << " (" << llvm::join(Tags, ",") << ")";
647
1.44k
      }
648
1.44k
      if (CodeCompletionString *CCS = Results[I].CreateCodeCompletionString(
649
1.44k
              SemaRef, Context, getAllocator(), CCTUInfo,
650
1.44k
              includeBriefComments())) {
651
1.44k
        OS << " : " << CCS->getAsString();
652
1.44k
        if (const char *BriefComment = CCS->getBriefComment())
653
9
          OS << " : " << BriefComment;
654
1.44k
      }
655
1.44k
      break;
656
657
3.38k
    case CodeCompletionResult::RK_Keyword:
658
3.38k
      OS << Results[I].Keyword;
659
3.38k
      break;
660
661
1.50k
    case CodeCompletionResult::RK_Macro:
662
1.50k
      OS << Results[I].Macro->getName();
663
1.50k
      if (CodeCompletionString *CCS = Results[I].CreateCodeCompletionString(
664
1.50k
              SemaRef, Context, getAllocator(), CCTUInfo,
665
1.50k
              includeBriefComments())) {
666
1.50k
        OS << " : " << CCS->getAsString();
667
1.50k
      }
668
1.50k
      break;
669
670
6.96k
    case CodeCompletionResult::RK_Pattern:
671
6.96k
      OS << "Pattern : " << Results[I].Pattern->getAsString();
672
6.96k
      break;
673
13.2k
    }
674
13.2k
    for (const FixItHint &FixIt : Results[I].FixIts) {
675
38
      const SourceLocation BLoc = FixIt.RemoveRange.getBegin();
676
38
      const SourceLocation ELoc = FixIt.RemoveRange.getEnd();
677
678
38
      SourceManager &SM = SemaRef.SourceMgr;
679
38
      std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
680
38
      std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
681
      // Adjust for token ranges.
682
38
      if (FixIt.RemoveRange.isTokenRange())
683
38
        EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, SemaRef.LangOpts);
684
685
38
      OS << " (requires fix-it:"
686
38
         << " {" << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
687
38
         << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
688
38
         << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
689
38
         << SM.getColumnNumber(EInfo.first, EInfo.second) << "}"
690
38
         << " to \"" << FixIt.CodeToInsert << "\")";
691
38
    }
692
13.2k
    OS << '\n';
693
13.2k
  }
694
313
}
695
696
// This function is used solely to preserve the former presentation of overloads
697
// by "clang -cc1 -code-completion-at", since CodeCompletionString::getAsString
698
// needs to be improved for printing the newer and more detailed overload
699
// chunks.
700
118
static std::string getOverloadAsString(const CodeCompletionString &CCS) {
701
118
  std::string Result;
702
118
  llvm::raw_string_ostream OS(Result);
703
704
692
  for (auto &C : CCS) {
705
692
    switch (C.Kind) {
706
3
    case CodeCompletionString::CK_Informative:
707
59
    case CodeCompletionString::CK_ResultType:
708
59
      OS << "[#" << C.Text << "#]";
709
59
      break;
710
711
102
    case CodeCompletionString::CK_CurrentParameter:
712
102
      OS << "<#" << C.Text << "#>";
713
102
      break;
714
715
    // FIXME: We can also print optional parameters of an overload.
716
11
    case CodeCompletionString::CK_Optional:
717
11
      break;
718
719
520
    default:
720
520
      OS << C.Text;
721
520
      break;
722
692
    }
723
692
  }
724
118
  return Result;
725
118
}
726
727
void PrintingCodeCompleteConsumer::ProcessOverloadCandidates(
728
    Sema &SemaRef, unsigned CurrentArg, OverloadCandidate *Candidates,
729
58
    unsigned NumCandidates, SourceLocation OpenParLoc, bool Braced) {
730
58
  OS << "OPENING_PAREN_LOC: ";
731
58
  OpenParLoc.print(OS, SemaRef.getSourceManager());
732
58
  OS << "\n";
733
734
176
  for (unsigned I = 0; I != NumCandidates; 
++I118
) {
735
118
    if (CodeCompletionString *CCS = Candidates[I].CreateSignatureString(
736
118
            CurrentArg, SemaRef, getAllocator(), CCTUInfo,
737
118
            includeBriefComments(), Braced)) {
738
118
      OS << "OVERLOAD: " << getOverloadAsString(*CCS) << "\n";
739
118
    }
740
118
  }
741
58
}
742
743
/// Retrieve the effective availability of the given declaration.
744
18.6k
static AvailabilityResult getDeclAvailability(const Decl *D) {
745
18.6k
  AvailabilityResult AR = D->getAvailability();
746
18.6k
  if (isa<EnumConstantDecl>(D))
747
193
    AR = std::max(AR, cast<Decl>(D->getDeclContext())->getAvailability());
748
18.6k
  return AR;
749
18.6k
}
750
751
18.6k
void CodeCompletionResult::computeCursorKindAndAvailability(bool Accessible) {
752
18.6k
  switch (Kind) {
753
245
  case RK_Pattern:
754
245
    if (!Declaration) {
755
      // Do nothing: Patterns can come with cursor kinds!
756
0
      break;
757
0
    }
758
245
    LLVM_FALLTHROUGH;
759
760
18.6k
  case RK_Declaration: {
761
    // Set the availability based on attributes.
762
18.6k
    switch (getDeclAvailability(Declaration)) {
763
18.6k
    case AR_Available:
764
18.6k
    case AR_NotYetIntroduced:
765
18.6k
      Availability = CXAvailability_Available;
766
18.6k
      break;
767
768
19
    case AR_Deprecated:
769
19
      Availability = CXAvailability_Deprecated;
770
19
      break;
771
772
20
    case AR_Unavailable:
773
20
      Availability = CXAvailability_NotAvailable;
774
20
      break;
775
18.6k
    }
776
777
18.6k
    if (const auto *Function = dyn_cast<FunctionDecl>(Declaration))
778
4.80k
      if (Function->isDeleted())
779
36
        Availability = CXAvailability_NotAvailable;
780
781
18.6k
    CursorKind = getCursorKindForDecl(Declaration);
782
18.6k
    if (CursorKind == CXCursor_UnexposedDecl) {
783
      // FIXME: Forward declarations of Objective-C classes and protocols
784
      // are not directly exposed, but we want code completion to treat them
785
      // like a definition.
786
203
      if (isa<ObjCInterfaceDecl>(Declaration))
787
0
        CursorKind = CXCursor_ObjCInterfaceDecl;
788
203
      else if (isa<ObjCProtocolDecl>(Declaration))
789
0
        CursorKind = CXCursor_ObjCProtocolDecl;
790
203
      else
791
203
        CursorKind = CXCursor_NotImplemented;
792
203
    }
793
18.6k
    break;
794
18.6k
  }
795
796
0
  case RK_Macro:
797
0
  case RK_Keyword:
798
0
    llvm_unreachable("Macro and keyword kinds are handled by the constructors");
799
18.6k
  }
800
801
18.6k
  if (!Accessible)
802
83
    Availability = CXAvailability_NotAccessible;
803
18.6k
}
804
805
/// Retrieve the name that should be used to order a result.
806
///
807
/// If the name needs to be constructed as a string, that string will be
808
/// saved into Saved and the returned StringRef will refer to it.
809
269k
StringRef CodeCompletionResult::getOrderedName(std::string &Saved) const {
810
269k
  switch (Kind) {
811
35.9k
  case RK_Keyword:
812
35.9k
    return Keyword;
813
189k
  case RK_Pattern:
814
189k
    return Pattern->getTypedText();
815
33.8k
  case RK_Macro:
816
33.8k
    return Macro->getName();
817
10.6k
  case RK_Declaration:
818
    // Handle declarations below.
819
10.6k
    break;
820
269k
  }
821
822
10.6k
  DeclarationName Name = Declaration->getDeclName();
823
824
  // If the name is a simple identifier (by far the common case), or a
825
  // zero-argument selector, just return a reference to that identifier.
826
10.6k
  if (IdentifierInfo *Id = Name.getAsIdentifierInfo())
827
7.84k
    return Id->getName();
828
2.82k
  if (Name.isObjCZeroArgSelector())
829
42
    if (IdentifierInfo *Id = Name.getObjCSelector().getIdentifierInfoForSlot(0))
830
42
      return Id->getName();
831
832
2.78k
  Saved = Name.getAsString();
833
2.78k
  return Saved;
834
2.82k
}
835
836
bool clang::operator<(const CodeCompletionResult &X,
837
134k
                      const CodeCompletionResult &Y) {
838
134k
  std::string XSaved, YSaved;
839
134k
  StringRef XStr = X.getOrderedName(XSaved);
840
134k
  StringRef YStr = Y.getOrderedName(YSaved);
841
134k
  int cmp = XStr.compare_insensitive(YStr);
842
134k
  if (cmp)
843
133k
    return cmp < 0;
844
845
  // If case-insensitive comparison fails, try case-sensitive comparison.
846
1.08k
  return XStr.compare(YStr) < 0;
847
134k
}