Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/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
3.45k
bool CodeCompletionContext::wantConstructorResults() const {
45
3.45k
  switch (CCKind) {
46
3.45k
  case CCC_Recovery:
47
2.90k
  case CCC_Statement:
48
2.90k
  case CCC_Expression:
49
2.90k
  case CCC_ObjCMessageReceiver:
50
2.90k
  case CCC_ParenthesizedExpression:
51
2.90k
  case CCC_Symbol:
52
2.90k
  case CCC_SymbolOrNewName:
53
2.90k
    return true;
54
2.90k
55
2.90k
  case CCC_TopLevel:
56
551
  case CCC_ObjCInterface:
57
551
  case CCC_ObjCImplementation:
58
551
  case CCC_ObjCIvarList:
59
551
  case CCC_ClassStructUnion:
60
551
  case CCC_DotMemberAccess:
61
551
  case CCC_ArrowMemberAccess:
62
551
  case CCC_ObjCPropertyAccess:
63
551
  case CCC_EnumTag:
64
551
  case CCC_UnionTag:
65
551
  case CCC_ClassOrStructTag:
66
551
  case CCC_ObjCProtocolName:
67
551
  case CCC_Namespace:
68
551
  case CCC_Type:
69
551
  case CCC_NewName:
70
551
  case CCC_MacroName:
71
551
  case CCC_MacroNameUse:
72
551
  case CCC_PreprocessorExpression:
73
551
  case CCC_PreprocessorDirective:
74
551
  case CCC_NaturalLanguage:
75
551
  case CCC_SelectorName:
76
551
  case CCC_TypeQualifiers:
77
551
  case CCC_Other:
78
551
  case CCC_OtherWithMacros:
79
551
  case CCC_ObjCInstanceMessage:
80
551
  case CCC_ObjCClassMessage:
81
551
  case CCC_ObjCInterfaceName:
82
551
  case CCC_ObjCCategoryName:
83
551
  case CCC_IncludedFile:
84
551
    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
209k
    : Kind(Kind), Text("") {
175
209k
  switch (Kind) {
176
209k
  case CK_TypedText:
177
179k
  case CK_Text:
178
179k
  case CK_Placeholder:
179
179k
  case CK_Informative:
180
179k
  case CK_ResultType:
181
179k
  case CK_CurrentParameter:
182
179k
    this->Text = Text;
183
179k
    break;
184
179k
185
179k
  case CK_Optional:
186
0
    llvm_unreachable("Optional strings cannot be created from text");
187
179k
188
179k
  case CK_LeftParen:
189
9.01k
    this->Text = "(";
190
9.01k
    break;
191
179k
192
179k
  case CK_RightParen:
193
9.08k
    this->Text = ")";
194
9.08k
    break;
195
179k
196
179k
  case CK_LeftBracket:
197
696
    this->Text = "[";
198
696
    break;
199
179k
200
179k
  case CK_RightBracket:
201
763
    this->Text = "]";
202
763
    break;
203
179k
204
179k
  case CK_LeftBrace:
205
129
    this->Text = "{";
206
129
    break;
207
179k
208
179k
  case CK_RightBrace:
209
196
    this->Text = "}";
210
196
    break;
211
179k
212
179k
  case CK_LeftAngle:
213
1.61k
    this->Text = "<";
214
1.61k
    break;
215
179k
216
179k
  case CK_RightAngle:
217
1.61k
    this->Text = ">";
218
1.61k
    break;
219
179k
220
179k
  case CK_Comma:
221
1.53k
    this->Text = ", ";
222
1.53k
    break;
223
179k
224
179k
  case CK_Colon:
225
79
    this->Text = ":";
226
79
    break;
227
179k
228
179k
  case CK_SemiColon:
229
727
    this->Text = ";";
230
727
    break;
231
179k
232
179k
  case CK_Equal:
233
45
    this->Text = " = ";
234
45
    break;
235
179k
236
179k
  case CK_HorizontalSpace:
237
4.19k
    this->Text = " ";
238
4.19k
    break;
239
179k
240
179k
  case CK_VerticalSpace:
241
218
    this->Text = "\n";
242
218
    break;
243
209k
  }
244
209k
}
245
246
CodeCompletionString::Chunk
247
2.10k
CodeCompletionString::Chunk::CreateText(const char *Text) {
248
2.10k
  return Chunk(CK_Text, Text);
249
2.10k
}
250
251
CodeCompletionString::Chunk
252
96
CodeCompletionString::Chunk::CreateOptional(CodeCompletionString *Optional) {
253
96
  Chunk Result;
254
96
  Result.Kind = CK_Optional;
255
96
  Result.Optional = Optional;
256
96
  return Result;
257
96
}
258
259
CodeCompletionString::Chunk
260
15.5k
CodeCompletionString::Chunk::CreatePlaceholder(const char *Placeholder) {
261
15.5k
  return Chunk(CK_Placeholder, Placeholder);
262
15.5k
}
263
264
CodeCompletionString::Chunk
265
223
CodeCompletionString::Chunk::CreateInformative(const char *Informative) {
266
223
  return Chunk(CK_Informative, Informative);
267
223
}
268
269
CodeCompletionString::Chunk
270
8.42k
CodeCompletionString::Chunk::CreateResultType(const char *ResultType) {
271
8.42k
  return Chunk(CK_ResultType, ResultType);
272
8.42k
}
273
274
CodeCompletionString::Chunk CodeCompletionString::Chunk::CreateCurrentParameter(
275
197
    const char *CurrentParameter) {
276
197
  return Chunk(CK_CurrentParameter, CurrentParameter);
277
197
}
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
153k
      BriefComment(BriefComment) {
286
153k
  assert(NumChunks <= 0xffff);
287
153k
  assert(NumAnnotations <= 0xffff);
288
153k
289
153k
  Chunk *StoredChunks = reinterpret_cast<Chunk *>(this + 1);
290
362k
  for (unsigned I = 0; I != NumChunks; 
++I209k
)
291
209k
    StoredChunks[I] = Chunks[I];
292
153k
293
153k
  const char **StoredAnnotations =
294
153k
      reinterpret_cast<const char **>(StoredChunks + NumChunks);
295
153k
  for (unsigned I = 0; I != NumAnnotations; 
++I6
)
296
6
    StoredAnnotations[I] = Annotations[I];
297
153k
}
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
5.50k
std::string CodeCompletionString::getAsString() const {
311
5.50k
  std::string Result;
312
5.50k
  llvm::raw_string_ostream OS(Result);
313
5.50k
314
14.6k
  for (const Chunk &C : *this) {
315
14.6k
    switch (C.Kind) {
316
14.6k
    case CK_Optional:
317
18
      OS << "{#" << C.Optional->getAsString() << "#}";
318
18
      break;
319
14.6k
    case CK_Placeholder:
320
2.47k
      OS << "<#" << C.Text << "#>";
321
2.47k
      break;
322
14.6k
    case CK_Informative:
323
1.28k
    case CK_ResultType:
324
1.28k
      OS << "[#" << C.Text << "#]";
325
1.28k
      break;
326
1.28k
    case CK_CurrentParameter:
327
0
      OS << "<#" << C.Text << "#>";
328
0
      break;
329
10.8k
    default:
330
10.8k
      OS << C.Text;
331
10.8k
      break;
332
14.6k
    }
333
14.6k
  }
334
5.50k
  return OS.str();
335
5.50k
}
336
337
88.2k
const char *CodeCompletionString::getTypedText() const {
338
88.2k
  for (const Chunk &C : *this)
339
95.7k
    if (C.Kind == CK_TypedText)
340
88.1k
      return C.Text;
341
88.2k
342
88.2k
  
return nullptr73
;
343
88.2k
}
344
345
141k
const char *CodeCompletionAllocator::CopyString(const Twine &String) {
346
141k
  SmallString<128> Data;
347
141k
  StringRef Ref = String.toStringRef(Data);
348
141k
  // FIXME: It would be more efficient to teach Twine to tell us its size and
349
141k
  // then add a routine there to fill in an allocated char* with the contents
350
141k
  // of the string.
351
141k
  char *Mem = (char *)Allocate(Ref.size() + 1, 1);
352
141k
  std::copy(Ref.begin(), Ref.end(), Mem);
353
141k
  Mem[Ref.size()] = 0;
354
141k
  return Mem;
355
141k
}
356
357
2.05k
StringRef CodeCompletionTUInfo::getParentName(const DeclContext *DC) {
358
2.05k
  const NamedDecl *ND = dyn_cast<NamedDecl>(DC);
359
2.05k
  if (!ND)
360
0
    return {};
361
2.05k
362
2.05k
  // Check whether we've already cached the parent name.
363
2.05k
  StringRef &CachedParentName = ParentNames[DC];
364
2.05k
  if (!CachedParentName.empty())
365
1.38k
    return CachedParentName;
366
670
367
670
  // If we already processed this DeclContext and assigned empty to it, the
368
670
  // data pointer will be non-null.
369
670
  if (CachedParentName.data() != nullptr)
370
10
    return {};
371
660
372
660
  // Find the interesting names.
373
660
  SmallVector<const DeclContext *, 2> Contexts;
374
2.00k
  while (DC && 
!DC->isFunctionOrMethod()1.34k
) {
375
1.34k
    if (const auto *ND = dyn_cast<NamedDecl>(DC)) {
376
687
      if (ND->getIdentifier())
377
664
        Contexts.push_back(DC);
378
687
    }
379
1.34k
380
1.34k
    DC = DC->getParent();
381
1.34k
  }
382
660
383
660
  {
384
660
    SmallString<128> S;
385
660
    llvm::raw_svector_ostream OS(S);
386
660
    bool First = true;
387
1.32k
    for (unsigned I = Contexts.size(); I != 0; 
--I664
) {
388
664
      if (First)
389
641
        First = false;
390
23
      else {
391
23
        OS << "::";
392
23
      }
393
664
394
664
      const DeclContext *CurDC = Contexts[I - 1];
395
664
      if (const auto *CatImpl = dyn_cast<ObjCCategoryImplDecl>(CurDC))
396
0
        CurDC = CatImpl->getCategoryDecl();
397
664
398
664
      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
647
      } else {
409
647
        OS << cast<NamedDecl>(CurDC)->getName();
410
647
      }
411
664
    }
412
660
413
660
    CachedParentName = AllocatorRef->CopyString(OS.str());
414
660
  }
415
660
416
660
  return CachedParentName;
417
660
}
418
419
153k
CodeCompletionString *CodeCompletionBuilder::TakeString() {
420
153k
  void *Mem = getAllocator().Allocate(
421
153k
      sizeof(CodeCompletionString) + sizeof(Chunk) * Chunks.size() +
422
153k
          sizeof(const char *) * Annotations.size(),
423
153k
      alignof(CodeCompletionString));
424
153k
  CodeCompletionString *Result = new (Mem) CodeCompletionString(
425
153k
      Chunks.data(), Chunks.size(), Priority, Availability, Annotations.data(),
426
153k
      Annotations.size(), ParentName, BriefComment);
427
153k
  Chunks.clear();
428
153k
  return Result;
429
153k
}
430
431
152k
void CodeCompletionBuilder::AddTypedTextChunk(const char *Text) {
432
152k
  Chunks.push_back(Chunk(CodeCompletionString::CK_TypedText, Text));
433
152k
}
434
435
2.10k
void CodeCompletionBuilder::AddTextChunk(const char *Text) {
436
2.10k
  Chunks.push_back(Chunk::CreateText(Text));
437
2.10k
}
438
439
96
void CodeCompletionBuilder::AddOptionalChunk(CodeCompletionString *Optional) {
440
96
  Chunks.push_back(Chunk::CreateOptional(Optional));
441
96
}
442
443
15.5k
void CodeCompletionBuilder::AddPlaceholderChunk(const char *Placeholder) {
444
15.5k
  Chunks.push_back(Chunk::CreatePlaceholder(Placeholder));
445
15.5k
}
446
447
223
void CodeCompletionBuilder::AddInformativeChunk(const char *Text) {
448
223
  Chunks.push_back(Chunk::CreateInformative(Text));
449
223
}
450
451
8.42k
void CodeCompletionBuilder::AddResultTypeChunk(const char *ResultType) {
452
8.42k
  Chunks.push_back(Chunk::CreateResultType(ResultType));
453
8.42k
}
454
455
void CodeCompletionBuilder::AddCurrentParameterChunk(
456
197
    const char *CurrentParameter) {
457
197
  Chunks.push_back(Chunk::CreateCurrentParameter(CurrentParameter));
458
197
}
459
460
void CodeCompletionBuilder::AddChunk(CodeCompletionString::ChunkKind CK,
461
29.9k
                                     const char *Text) {
462
29.9k
  Chunks.push_back(Chunk(CK, Text));
463
29.9k
}
464
465
5.37k
void CodeCompletionBuilder::addParentContext(const DeclContext *DC) {
466
5.37k
  if (DC->isTranslationUnit())
467
2.86k
    return;
468
2.50k
469
2.50k
  if (DC->isFunctionOrMethod())
470
448
    return;
471
2.05k
472
2.05k
  const NamedDecl *ND = dyn_cast<NamedDecl>(DC);
473
2.05k
  if (!ND)
474
0
    return;
475
2.05k
476
2.05k
  ParentName = getCodeCompletionTUInfo().getParentName(DC);
477
2.05k
}
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
212
FunctionDecl *CodeCompleteConsumer::OverloadCandidate::getFunction() const {
487
212
  if (getKind() == CK_Function)
488
207
    return Function;
489
5
  else if (getKind() == CK_FunctionTemplate)
490
0
    return FunctionTemplate->getTemplatedDecl();
491
5
  else
492
5
    return nullptr;
493
212
}
494
495
const FunctionType *
496
464
CodeCompleteConsumer::OverloadCandidate::getFunctionType() const {
497
464
  switch (Kind) {
498
464
  case CK_Function:
499
454
    return Function->getType()->getAs<FunctionType>();
500
464
501
464
  case CK_FunctionTemplate:
502
0
    return FunctionTemplate->getTemplatedDecl()
503
0
        ->getType()
504
0
        ->getAs<FunctionType>();
505
464
506
464
  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.81k
CodeCompleteConsumer::~CodeCompleteConsumer() = default;
518
519
bool PrintingCodeCompleteConsumer::isResultFilteredOut(
520
3.36k
    StringRef Filter, CodeCompletionResult Result) {
521
3.36k
  switch (Result.Kind) {
522
3.36k
  case CodeCompletionResult::RK_Declaration:
523
32
    return !(Result.Declaration->getIdentifier() &&
524
32
             Result.Declaration->getIdentifier()->getName().startswith(Filter));
525
3.36k
  case CodeCompletionResult::RK_Keyword:
526
405
    return !StringRef(Result.Keyword).startswith(Filter);
527
3.36k
  case CodeCompletionResult::RK_Macro:
528
806
    return !Result.Macro->getName().startswith(Filter);
529
3.36k
  case CodeCompletionResult::RK_Pattern:
530
2.12k
    return !(Result.Pattern->getTypedText() &&
531
2.12k
             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
215
    unsigned NumResults) {
539
215
  std::stable_sort(Results, Results + NumResults);
540
215
541
215
  if (!Context.getPreferredType().isNull())
542
39
    OS << "PREFERRED-TYPE: " << Context.getPreferredType().getAsString()
543
39
       << "\n";
544
215
545
215
  StringRef Filter = SemaRef.getPreprocessor().getCodeCompletionFilter();
546
215
  // Print the completions.
547
11.3k
  for (unsigned I = 0; I != NumResults; 
++I11.0k
) {
548
11.0k
    if (!Filter.empty() && 
isResultFilteredOut(Filter, Results[I])3.36k
)
549
3.31k
      continue;
550
7.77k
    OS << "COMPLETION: ";
551
7.77k
    switch (Results[I].Kind) {
552
7.77k
    case CodeCompletionResult::RK_Declaration:
553
973
      OS << *Results[I].Declaration;
554
973
      {
555
973
        std::vector<std::string> Tags;
556
973
        if (Results[I].Hidden)
557
96
          Tags.push_back("Hidden");
558
973
        if (Results[I].InBaseClass)
559
153
          Tags.push_back("InBase");
560
973
        if (Results[I].Availability ==
561
973
            CXAvailabilityKind::CXAvailability_NotAccessible)
562
24
          Tags.push_back("Inaccessible");
563
973
        if (!Tags.empty())
564
216
          OS << " (" << llvm::join(Tags, ",") << ")";
565
973
      }
566
973
      if (CodeCompletionString *CCS = Results[I].CreateCodeCompletionString(
567
973
              SemaRef, Context, getAllocator(), CCTUInfo,
568
973
              includeBriefComments())) {
569
973
        OS << " : " << CCS->getAsString();
570
973
        if (const char *BriefComment = CCS->getBriefComment())
571
9
          OS << " : " << BriefComment;
572
973
      }
573
973
      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
973
      OS << '\n';
592
973
      break;
593
7.77k
594
7.77k
    case CodeCompletionResult::RK_Keyword:
595
2.29k
      OS << Results[I].Keyword << '\n';
596
2.29k
      break;
597
7.77k
598
7.77k
    case CodeCompletionResult::RK_Macro:
599
1.50k
      OS << Results[I].Macro->getName();
600
1.50k
      if (CodeCompletionString *CCS = Results[I].CreateCodeCompletionString(
601
1.50k
              SemaRef, Context, getAllocator(), CCTUInfo,
602
1.50k
              includeBriefComments())) {
603
1.50k
        OS << " : " << CCS->getAsString();
604
1.50k
      }
605
1.50k
      OS << '\n';
606
1.50k
      break;
607
7.77k
608
7.77k
    case CodeCompletionResult::RK_Pattern:
609
3.00k
      OS << "Pattern : " << Results[I].Pattern->getAsString() << '\n';
610
3.00k
      break;
611
7.77k
    }
612
7.77k
  }
613
215
}
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
50
static std::string getOverloadAsString(const CodeCompletionString &CCS) {
620
50
  std::string Result;
621
50
  llvm::raw_string_ostream OS(Result);
622
50
623
291
  for (auto &C : CCS) {
624
291
    switch (C.Kind) {
625
291
    case CodeCompletionString::CK_Informative:
626
25
    case CodeCompletionString::CK_ResultType:
627
25
      OS << "[#" << C.Text << "#]";
628
25
      break;
629
25
630
44
    case CodeCompletionString::CK_CurrentParameter:
631
44
      OS << "<#" << C.Text << "#>";
632
44
      break;
633
25
634
25
    // FIXME: We can also print optional parameters of an overload.
635
25
    case CodeCompletionString::CK_Optional:
636
6
      break;
637
25
638
216
    default:
639
216
      OS << C.Text;
640
216
      break;
641
291
    }
642
291
  }
643
50
  return OS.str();
644
50
}
645
646
void PrintingCodeCompleteConsumer::ProcessOverloadCandidates(
647
    Sema &SemaRef, unsigned CurrentArg, OverloadCandidate *Candidates,
648
27
    unsigned NumCandidates, SourceLocation OpenParLoc) {
649
27
  OS << "OPENING_PAREN_LOC: ";
650
27
  OpenParLoc.print(OS, SemaRef.getSourceManager());
651
27
  OS << "\n";
652
27
653
77
  for (unsigned I = 0; I != NumCandidates; 
++I50
) {
654
50
    if (CodeCompletionString *CCS = Candidates[I].CreateSignatureString(
655
50
            CurrentArg, SemaRef, getAllocator(), CCTUInfo,
656
50
            includeBriefComments())) {
657
50
      OS << "OVERLOAD: " << getOverloadAsString(*CCS) << "\n";
658
50
    }
659
50
  }
660
27
}
661
662
/// Retrieve the effective availability of the given declaration.
663
14.4k
static AvailabilityResult getDeclAvailability(const Decl *D) {
664
14.4k
  AvailabilityResult AR = D->getAvailability();
665
14.4k
  if (isa<EnumConstantDecl>(D))
666
193
    AR = std::max(AR, cast<Decl>(D->getDeclContext())->getAvailability());
667
14.4k
  return AR;
668
14.4k
}
669
670
14.4k
void CodeCompletionResult::computeCursorKindAndAvailability(bool Accessible) {
671
14.4k
  switch (Kind) {
672
14.4k
  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
14.4k
  case RK_Declaration: {
680
14.4k
    // Set the availability based on attributes.
681
14.4k
    switch (getDeclAvailability(Declaration)) {
682
14.4k
    case AR_Available:
683
14.3k
    case AR_NotYetIntroduced:
684
14.3k
      Availability = CXAvailability_Available;
685
14.3k
      break;
686
14.3k
687
14.3k
    case AR_Deprecated:
688
19
      Availability = CXAvailability_Deprecated;
689
19
      break;
690
14.3k
691
14.3k
    case AR_Unavailable:
692
20
      Availability = CXAvailability_NotAvailable;
693
20
      break;
694
14.4k
    }
695
14.4k
696
14.4k
    if (const auto *Function = dyn_cast<FunctionDecl>(Declaration))
697
3.86k
      if (Function->isDeleted())
698
0
        Availability = CXAvailability_NotAvailable;
699
14.4k
700
14.4k
    CursorKind = getCursorKindForDecl(Declaration);
701
14.4k
    if (CursorKind == CXCursor_UnexposedDecl) {
702
86
      // FIXME: Forward declarations of Objective-C classes and protocols
703
86
      // are not directly exposed, but we want code completion to treat them
704
86
      // like a definition.
705
86
      if (isa<ObjCInterfaceDecl>(Declaration))
706
0
        CursorKind = CXCursor_ObjCInterfaceDecl;
707
86
      else if (isa<ObjCProtocolDecl>(Declaration))
708
0
        CursorKind = CXCursor_ObjCProtocolDecl;
709
86
      else
710
86
        CursorKind = CXCursor_NotImplemented;
711
86
    }
712
14.4k
    break;
713
14.4k
  }
714
14.4k
715
14.4k
  case RK_Macro:
716
0
  case RK_Keyword:
717
0
    llvm_unreachable("Macro and keyword kinds are handled by the constructors");
718
14.4k
  }
719
14.4k
720
14.4k
  if (!Accessible)
721
74
    Availability = CXAvailability_NotAccessible;
722
14.4k
}
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
134k
StringRef CodeCompletionResult::getOrderedName(std::string &Saved) const {
729
134k
  switch (Kind) {
730
134k
  case RK_Keyword:
731
25.5k
    return Keyword;
732
134k
  case RK_Pattern:
733
67.9k
    return Pattern->getTypedText();
734
134k
  case RK_Macro:
735
33.9k
    return Macro->getName();
736
134k
  case RK_Declaration:
737
6.77k
    // Handle declarations below.
738
6.77k
    break;
739
6.77k
  }
740
6.77k
741
6.77k
  DeclarationName Name = Declaration->getDeclName();
742
6.77k
743
6.77k
  // If the name is a simple identifier (by far the common case), or a
744
6.77k
  // zero-argument selector, just return a reference to that identifier.
745
6.77k
  if (IdentifierInfo *Id = Name.getAsIdentifierInfo())
746
4.81k
    return Id->getName();
747
1.95k
  if (Name.isObjCZeroArgSelector())
748
42
    if (IdentifierInfo *Id = Name.getObjCSelector().getIdentifierInfoForSlot(0))
749
42
      return Id->getName();
750
1.91k
751
1.91k
  Saved = Name.getAsString();
752
1.91k
  return Saved;
753
1.91k
}
754
755
bool clang::operator<(const CodeCompletionResult &X,
756
67.1k
                      const CodeCompletionResult &Y) {
757
67.1k
  std::string XSaved, YSaved;
758
67.1k
  StringRef XStr = X.getOrderedName(XSaved);
759
67.1k
  StringRef YStr = Y.getOrderedName(YSaved);
760
67.1k
  int cmp = XStr.compare_lower(YStr);
761
67.1k
  if (cmp)
762
66.3k
    return cmp < 0;
763
742
764
742
  // If case-insensitive comparison fails, try case-sensitive comparison.
765
742
  return XStr.compare(YStr) < 0;
766
742
}