Coverage Report

Created: 2022-05-17 06:19

/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.33k
bool CodeCompletionContext::wantConstructorResults() const {
46
5.33k
  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
676
  case CCC_DotMemberAccess:
62
885
  case CCC_ArrowMemberAccess:
63
885
  case CCC_ObjCPropertyAccess:
64
885
  case CCC_EnumTag:
65
885
  case CCC_UnionTag:
66
892
  case CCC_ClassOrStructTag:
67
892
  case CCC_ObjCProtocolName:
68
902
  case CCC_Namespace:
69
905
  case CCC_Type:
70
905
  case CCC_NewName:
71
905
  case CCC_MacroName:
72
905
  case CCC_MacroNameUse:
73
905
  case CCC_PreprocessorExpression:
74
905
  case CCC_PreprocessorDirective:
75
905
  case CCC_NaturalLanguage:
76
905
  case CCC_SelectorName:
77
905
  case CCC_TypeQualifiers:
78
920
  case CCC_Other:
79
920
  case CCC_OtherWithMacros:
80
929
  case CCC_ObjCInstanceMessage:
81
931
  case CCC_ObjCClassMessage:
82
931
  case CCC_ObjCInterfaceName:
83
931
  case CCC_ObjCCategoryName:
84
931
  case CCC_IncludedFile:
85
931
  case CCC_Attribute:
86
931
    return false;
87
5.33k
  }
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
246k
    : Kind(Kind), Text("") {
179
246k
  switch (Kind) {
180
175k
  case CK_TypedText:
181
176k
  case CK_Text:
182
197k
  case CK_Placeholder:
183
197k
  case CK_Informative:
184
207k
  case CK_ResultType:
185
207k
  case CK_CurrentParameter:
186
207k
    this->Text = Text;
187
207k
    break;
188
189
0
  case CK_Optional:
190
0
    llvm_unreachable("Optional strings cannot be created from text");
191
192
11.9k
  case CK_LeftParen:
193
11.9k
    this->Text = "(";
194
11.9k
    break;
195
196
12.0k
  case CK_RightParen:
197
12.0k
    this->Text = ")";
198
12.0k
    break;
199
200
864
  case CK_LeftBracket:
201
864
    this->Text = "[";
202
864
    break;
203
204
969
  case CK_RightBracket:
205
969
    this->Text = "]";
206
969
    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
246k
  }
248
246k
}
249
250
CodeCompletionString::Chunk
251
1.88k
CodeCompletionString::Chunk::CreateText(const char *Text) {
252
1.88k
  return Chunk(CK_Text, Text);
253
1.88k
}
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
233
CodeCompletionString::Chunk::CreateInformative(const char *Informative) {
270
233
  return Chunk(CK_Informative, Informative);
271
233
}
272
273
CodeCompletionString::Chunk
274
9.85k
CodeCompletionString::Chunk::CreateResultType(const char *ResultType) {
275
9.85k
  return Chunk(CK_ResultType, ResultType);
276
9.85k
}
277
278
CodeCompletionString::Chunk CodeCompletionString::Chunk::CreateCurrentParameter(
279
251
    const char *CurrentParameter) {
280
251
  return Chunk(CK_CurrentParameter, CurrentParameter);
281
251
}
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
175k
      BriefComment(BriefComment) {
290
175k
  assert(NumChunks <= 0xffff);
291
0
  assert(NumAnnotations <= 0xffff);
292
293
0
  Chunk *StoredChunks = reinterpret_cast<Chunk *>(this + 1);
294
422k
  for (unsigned I = 0; I != NumChunks; 
++I246k
)
295
246k
    StoredChunks[I] = Chunks[I];
296
297
175k
  const char **StoredAnnotations =
298
175k
      reinterpret_cast<const char **>(StoredChunks + NumChunks);
299
175k
  for (unsigned I = 0; I != NumAnnotations; 
++I6
)
300
6
    StoredAnnotations[I] = Annotations[I];
301
175k
}
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
31.0k
  for (const Chunk &C : *this) {
319
31.0k
    switch (C.Kind) {
320
26
    case CK_Optional:
321
26
      OS << "{#" << C.Optional->getAsString() << "#}";
322
26
      break;
323
6.07k
    case CK_Placeholder:
324
6.07k
      OS << "<#" << C.Text << "#>";
325
6.07k
      break;
326
82
    case CK_Informative:
327
2.20k
    case CK_ResultType:
328
2.20k
      OS << "[#" << C.Text << "#]";
329
2.20k
      break;
330
0
    case CK_CurrentParameter:
331
0
      OS << "<#" << C.Text << "#>";
332
0
      break;
333
22.7k
    default:
334
22.7k
      OS << C.Text;
335
22.7k
      break;
336
31.0k
    }
337
31.0k
  }
338
10.3k
  return Result;
339
10.3k
}
340
341
220k
const char *CodeCompletionString::getTypedText() const {
342
220k
  for (const Chunk &C : *this)
343
232k
    if (C.Kind == CK_TypedText)
344
220k
      return C.Text;
345
346
73
  return nullptr;
347
220k
}
348
349
161k
const char *CodeCompletionAllocator::CopyString(const Twine &String) {
350
161k
  SmallString<128> Data;
351
161k
  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
161k
  char *Mem = (char *)Allocate(Ref.size() + 1, 1);
356
161k
  std::copy(Ref.begin(), Ref.end(), Mem);
357
161k
  Mem[Ref.size()] = 0;
358
161k
  return Mem;
359
161k
}
360
361
2.24k
StringRef CodeCompletionTUInfo::getParentName(const DeclContext *DC) {
362
2.24k
  if (!isa<NamedDecl>(DC))
363
0
    return {};
364
365
  // Check whether we've already cached the parent name.
366
2.24k
  StringRef &CachedParentName = ParentNames[DC];
367
2.24k
  if (!CachedParentName.empty())
368
1.51k
    return CachedParentName;
369
370
  // If we already processed this DeclContext and assigned empty to it, the
371
  // data pointer will be non-null.
372
730
  if (CachedParentName.data() != nullptr)
373
10
    return {};
374
375
  // Find the interesting names.
376
720
  SmallVector<const DeclContext *, 2> Contexts;
377
2.18k
  while (DC && 
!DC->isFunctionOrMethod()1.47k
) {
378
1.46k
    if (const auto *ND = dyn_cast<NamedDecl>(DC)) {
379
750
      if (ND->getIdentifier())
380
726
        Contexts.push_back(DC);
381
750
    }
382
383
1.46k
    DC = DC->getParent();
384
1.46k
  }
385
386
720
  {
387
720
    SmallString<128> S;
388
720
    llvm::raw_svector_ostream OS(S);
389
720
    bool First = true;
390
726
    for (const DeclContext *CurDC : llvm::reverse(Contexts)) {
391
726
      if (First)
392
701
        First = false;
393
25
      else {
394
25
        OS << "::";
395
25
      }
396
397
726
      if (const auto *CatImpl = dyn_cast<ObjCCategoryImplDecl>(CurDC))
398
0
        CurDC = CatImpl->getCategoryDecl();
399
400
726
      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
709
      } else {
411
709
        OS << cast<NamedDecl>(CurDC)->getName();
412
709
      }
413
726
    }
414
415
720
    CachedParentName = AllocatorRef->CopyString(OS.str());
416
720
  }
417
418
0
  return CachedParentName;
419
720
}
420
421
175k
CodeCompletionString *CodeCompletionBuilder::TakeString() {
422
175k
  void *Mem = getAllocator().Allocate(
423
175k
      sizeof(CodeCompletionString) + sizeof(Chunk) * Chunks.size() +
424
175k
          sizeof(const char *) * Annotations.size(),
425
175k
      alignof(CodeCompletionString));
426
175k
  CodeCompletionString *Result = new (Mem) CodeCompletionString(
427
175k
      Chunks.data(), Chunks.size(), Priority, Availability, Annotations.data(),
428
175k
      Annotations.size(), ParentName, BriefComment);
429
175k
  Chunks.clear();
430
175k
  return Result;
431
175k
}
432
433
175k
void CodeCompletionBuilder::AddTypedTextChunk(const char *Text) {
434
175k
  Chunks.push_back(Chunk(CodeCompletionString::CK_TypedText, Text));
435
175k
}
436
437
1.88k
void CodeCompletionBuilder::AddTextChunk(const char *Text) {
438
1.88k
  Chunks.push_back(Chunk::CreateText(Text));
439
1.88k
}
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
233
void CodeCompletionBuilder::AddInformativeChunk(const char *Text) {
450
233
  Chunks.push_back(Chunk::CreateInformative(Text));
451
233
}
452
453
9.85k
void CodeCompletionBuilder::AddResultTypeChunk(const char *ResultType) {
454
9.85k
  Chunks.push_back(Chunk::CreateResultType(ResultType));
455
9.85k
}
456
457
void CodeCompletionBuilder::AddCurrentParameterChunk(
458
251
    const char *CurrentParameter) {
459
251
  Chunks.push_back(Chunk::CreateCurrentParameter(CurrentParameter));
460
251
}
461
462
void CodeCompletionBuilder::AddChunk(CodeCompletionString::ChunkKind CK,
463
39.3k
                                     const char *Text) {
464
39.3k
  Chunks.push_back(Chunk(CK, Text));
465
39.3k
}
466
467
5.89k
void CodeCompletionBuilder::addParentContext(const DeclContext *DC) {
468
5.89k
  if (DC->isTranslationUnit())
469
3.19k
    return;
470
471
2.70k
  if (DC->isFunctionOrMethod())
472
458
    return;
473
474
2.24k
  if (!isa<NamedDecl>(DC))
475
0
    return;
476
477
2.24k
  ParentName = getCodeCompletionTUInfo().getParentName(DC);
478
2.24k
}
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
275
FunctionDecl *CodeCompleteConsumer::OverloadCandidate::getFunction() const {
488
275
  if (getKind() == CK_Function)
489
263
    return Function;
490
12
  else if (getKind() == CK_FunctionTemplate)
491
0
    return FunctionTemplate->getTemplatedDecl();
492
12
  else
493
12
    return nullptr;
494
275
}
495
496
const FunctionType *
497
585
CodeCompleteConsumer::OverloadCandidate::getFunctionType() const {
498
585
  switch (Kind) {
499
563
  case CK_Function:
500
563
    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
585
  }
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
319
CodeCompleteConsumer::OverloadCandidate::getParamType(unsigned N) const {
539
319
  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
312
  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
305
  if (const auto *FT = getFunctionType())
560
305
    if (const auto *FPT = dyn_cast<FunctionProtoType>(FT))
561
304
      if (N < FPT->getNumParams())
562
275
        return FPT->getParamType(N);
563
30
  return QualType();
564
305
}
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.40k
    StringRef Filter, CodeCompletionResult Result) {
603
7.40k
  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
800
  case CodeCompletionResult::RK_Macro:
610
800
    return !Result.Macro->getName().startswith(Filter);
611
6.16k
  case CodeCompletionResult::RK_Pattern:
612
6.16k
    return !(Result.Pattern->getTypedText() &&
613
6.16k
             StringRef(Result.Pattern->getTypedText()).startswith(Filter));
614
7.40k
  }
615
0
  llvm_unreachable("Unknown code completion result Kind.");
616
0
}
617
618
void PrintingCodeCompleteConsumer::ProcessCodeCompleteResults(
619
    Sema &SemaRef, CodeCompletionContext Context, CodeCompletionResult *Results,
620
316
    unsigned NumResults) {
621
316
  std::stable_sort(Results, Results + NumResults);
622
623
316
  if (!Context.getPreferredType().isNull())
624
56
    OS << "PREFERRED-TYPE: " << Context.getPreferredType() << '\n';
625
626
316
  StringRef Filter = SemaRef.getPreprocessor().getCodeCompletionFilter();
627
  // Print the completions.
628
21.0k
  for (unsigned I = 0; I != NumResults; 
++I20.7k
) {
629
20.7k
    if (!Filter.empty() && 
isResultFilteredOut(Filter, Results[I])7.40k
)
630
7.33k
      continue;
631
13.3k
    OS << "COMPLETION: ";
632
13.3k
    switch (Results[I].Kind) {
633
1.45k
    case CodeCompletionResult::RK_Declaration:
634
1.45k
      OS << *Results[I].Declaration;
635
1.45k
      {
636
1.45k
        std::vector<std::string> Tags;
637
1.45k
        if (Results[I].Hidden)
638
105
          Tags.push_back("Hidden");
639
1.45k
        if (Results[I].InBaseClass)
640
162
          Tags.push_back("InBase");
641
1.45k
        if (Results[I].Availability ==
642
1.45k
            CXAvailabilityKind::CXAvailability_NotAccessible)
643
33
          Tags.push_back("Inaccessible");
644
1.45k
        if (!Tags.empty())
645
229
          OS << " (" << llvm::join(Tags, ",") << ")";
646
1.45k
      }
647
1.45k
      if (CodeCompletionString *CCS = Results[I].CreateCodeCompletionString(
648
1.45k
              SemaRef, Context, getAllocator(), CCTUInfo,
649
1.45k
              includeBriefComments())) {
650
1.45k
        OS << " : " << CCS->getAsString();
651
1.45k
        if (const char *BriefComment = CCS->getBriefComment())
652
9
          OS << " : " << BriefComment;
653
1.45k
      }
654
1.45k
      break;
655
656
3.41k
    case CodeCompletionResult::RK_Keyword:
657
3.41k
      OS << Results[I].Keyword;
658
3.41k
      break;
659
660
1.50k
    case CodeCompletionResult::RK_Macro:
661
1.50k
      OS << Results[I].Macro->getName();
662
1.50k
      if (CodeCompletionString *CCS = Results[I].CreateCodeCompletionString(
663
1.50k
              SemaRef, Context, getAllocator(), CCTUInfo,
664
1.50k
              includeBriefComments())) {
665
1.50k
        OS << " : " << CCS->getAsString();
666
1.50k
      }
667
1.50k
      break;
668
669
7.02k
    case CodeCompletionResult::RK_Pattern:
670
7.02k
      OS << "Pattern : " << Results[I].Pattern->getAsString();
671
7.02k
      break;
672
13.3k
    }
673
13.3k
    for (const FixItHint &FixIt : Results[I].FixIts) {
674
38
      const SourceLocation BLoc = FixIt.RemoveRange.getBegin();
675
38
      const SourceLocation ELoc = FixIt.RemoveRange.getEnd();
676
677
38
      SourceManager &SM = SemaRef.SourceMgr;
678
38
      std::pair<FileID, unsigned> BInfo = SM.getDecomposedLoc(BLoc);
679
38
      std::pair<FileID, unsigned> EInfo = SM.getDecomposedLoc(ELoc);
680
      // Adjust for token ranges.
681
38
      if (FixIt.RemoveRange.isTokenRange())
682
38
        EInfo.second += Lexer::MeasureTokenLength(ELoc, SM, SemaRef.LangOpts);
683
684
38
      OS << " (requires fix-it:"
685
38
         << " {" << SM.getLineNumber(BInfo.first, BInfo.second) << ':'
686
38
         << SM.getColumnNumber(BInfo.first, BInfo.second) << '-'
687
38
         << SM.getLineNumber(EInfo.first, EInfo.second) << ':'
688
38
         << SM.getColumnNumber(EInfo.first, EInfo.second) << "}"
689
38
         << " to \"" << FixIt.CodeToInsert << "\")";
690
38
    }
691
13.3k
    OS << '\n';
692
13.3k
  }
693
316
}
694
695
// This function is used solely to preserve the former presentation of overloads
696
// by "clang -cc1 -code-completion-at", since CodeCompletionString::getAsString
697
// needs to be improved for printing the newer and more detailed overload
698
// chunks.
699
119
static std::string getOverloadAsString(const CodeCompletionString &CCS) {
700
119
  std::string Result;
701
119
  llvm::raw_string_ostream OS(Result);
702
703
697
  for (auto &C : CCS) {
704
697
    switch (C.Kind) {
705
3
    case CodeCompletionString::CK_Informative:
706
60
    case CodeCompletionString::CK_ResultType:
707
60
      OS << "[#" << C.Text << "#]";
708
60
      break;
709
710
103
    case CodeCompletionString::CK_CurrentParameter:
711
103
      OS << "<#" << C.Text << "#>";
712
103
      break;
713
714
    // FIXME: We can also print optional parameters of an overload.
715
11
    case CodeCompletionString::CK_Optional:
716
11
      break;
717
718
523
    default:
719
523
      OS << C.Text;
720
523
      break;
721
697
    }
722
697
  }
723
119
  return Result;
724
119
}
725
726
void PrintingCodeCompleteConsumer::ProcessOverloadCandidates(
727
    Sema &SemaRef, unsigned CurrentArg, OverloadCandidate *Candidates,
728
59
    unsigned NumCandidates, SourceLocation OpenParLoc, bool Braced) {
729
59
  OS << "OPENING_PAREN_LOC: ";
730
59
  OpenParLoc.print(OS, SemaRef.getSourceManager());
731
59
  OS << "\n";
732
733
178
  for (unsigned I = 0; I != NumCandidates; 
++I119
) {
734
119
    if (CodeCompletionString *CCS = Candidates[I].CreateSignatureString(
735
119
            CurrentArg, SemaRef, getAllocator(), CCTUInfo,
736
119
            includeBriefComments(), Braced)) {
737
119
      OS << "OVERLOAD: " << getOverloadAsString(*CCS) << "\n";
738
119
    }
739
119
  }
740
59
}
741
742
/// Retrieve the effective availability of the given declaration.
743
18.7k
static AvailabilityResult getDeclAvailability(const Decl *D) {
744
18.7k
  AvailabilityResult AR = D->getAvailability();
745
18.7k
  if (isa<EnumConstantDecl>(D))
746
193
    AR = std::max(AR, cast<Decl>(D->getDeclContext())->getAvailability());
747
18.7k
  return AR;
748
18.7k
}
749
750
18.7k
void CodeCompletionResult::computeCursorKindAndAvailability(bool Accessible) {
751
18.7k
  switch (Kind) {
752
245
  case RK_Pattern:
753
245
    if (!Declaration) {
754
      // Do nothing: Patterns can come with cursor kinds!
755
0
      break;
756
0
    }
757
245
    LLVM_FALLTHROUGH;
758
759
18.7k
  case RK_Declaration: {
760
    // Set the availability based on attributes.
761
18.7k
    switch (getDeclAvailability(Declaration)) {
762
18.6k
    case AR_Available:
763
18.6k
    case AR_NotYetIntroduced:
764
18.6k
      Availability = CXAvailability_Available;
765
18.6k
      break;
766
767
19
    case AR_Deprecated:
768
19
      Availability = CXAvailability_Deprecated;
769
19
      break;
770
771
20
    case AR_Unavailable:
772
20
      Availability = CXAvailability_NotAvailable;
773
20
      break;
774
18.7k
    }
775
776
18.7k
    if (const auto *Function = dyn_cast<FunctionDecl>(Declaration))
777
4.81k
      if (Function->isDeleted())
778
36
        Availability = CXAvailability_NotAvailable;
779
780
18.7k
    CursorKind = getCursorKindForDecl(Declaration);
781
18.7k
    if (CursorKind == CXCursor_UnexposedDecl) {
782
      // FIXME: Forward declarations of Objective-C classes and protocols
783
      // are not directly exposed, but we want code completion to treat them
784
      // like a definition.
785
203
      if (isa<ObjCInterfaceDecl>(Declaration))
786
0
        CursorKind = CXCursor_ObjCInterfaceDecl;
787
203
      else if (isa<ObjCProtocolDecl>(Declaration))
788
0
        CursorKind = CXCursor_ObjCProtocolDecl;
789
203
      else
790
203
        CursorKind = CXCursor_NotImplemented;
791
203
    }
792
18.7k
    break;
793
18.7k
  }
794
795
0
  case RK_Macro:
796
0
  case RK_Keyword:
797
0
    llvm_unreachable("Macro and keyword kinds are handled by the constructors");
798
18.7k
  }
799
800
18.7k
  if (!Accessible)
801
90
    Availability = CXAvailability_NotAccessible;
802
18.7k
}
803
804
/// Retrieve the name that should be used to order a result.
805
///
806
/// If the name needs to be constructed as a string, that string will be
807
/// saved into Saved and the returned StringRef will refer to it.
808
271k
StringRef CodeCompletionResult::getOrderedName(std::string &Saved) const {
809
271k
  switch (Kind) {
810
36.2k
  case RK_Keyword:
811
36.2k
    return Keyword;
812
190k
  case RK_Pattern:
813
190k
    return Pattern->getTypedText();
814
33.9k
  case RK_Macro:
815
33.9k
    return Macro->getName();
816
10.7k
  case RK_Declaration:
817
    // Handle declarations below.
818
10.7k
    break;
819
271k
  }
820
821
10.7k
  DeclarationName Name = Declaration->getDeclName();
822
823
  // If the name is a simple identifier (by far the common case), or a
824
  // zero-argument selector, just return a reference to that identifier.
825
10.7k
  if (IdentifierInfo *Id = Name.getAsIdentifierInfo())
826
7.91k
    return Id->getName();
827
2.88k
  if (Name.isObjCZeroArgSelector())
828
42
    if (IdentifierInfo *Id = Name.getObjCSelector().getIdentifierInfoForSlot(0))
829
42
      return Id->getName();
830
831
2.83k
  Saved = Name.getAsString();
832
2.83k
  return Saved;
833
2.88k
}
834
835
bool clang::operator<(const CodeCompletionResult &X,
836
135k
                      const CodeCompletionResult &Y) {
837
135k
  std::string XSaved, YSaved;
838
135k
  StringRef XStr = X.getOrderedName(XSaved);
839
135k
  StringRef YStr = Y.getOrderedName(YSaved);
840
135k
  int cmp = XStr.compare_insensitive(YStr);
841
135k
  if (cmp)
842
134k
    return cmp < 0;
843
844
  // If case-insensitive comparison fails, try case-sensitive comparison.
845
1.09k
  return XStr.compare(YStr) < 0;
846
135k
}