Coverage Report

Created: 2020-03-31 06:27

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