Coverage Report

Created: 2020-11-24 06:42

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/tools/libclang/CIndexCodeCompletion.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- CIndexCodeCompletion.cpp - Code Completion API hooks ---------------===//
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 Clang-C Source Indexing library hooks for
10
// code completion.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "CIndexer.h"
15
#include "CIndexDiagnostic.h"
16
#include "CLog.h"
17
#include "CXCursor.h"
18
#include "CXSourceLocation.h"
19
#include "CXString.h"
20
#include "CXTranslationUnit.h"
21
#include "clang/AST/Decl.h"
22
#include "clang/AST/DeclObjC.h"
23
#include "clang/AST/Type.h"
24
#include "clang/Basic/FileManager.h"
25
#include "clang/Basic/SourceManager.h"
26
#include "clang/Frontend/ASTUnit.h"
27
#include "clang/Frontend/CompilerInstance.h"
28
#include "clang/Sema/CodeCompleteConsumer.h"
29
#include "clang/Sema/Sema.h"
30
#include "llvm/ADT/SmallString.h"
31
#include "llvm/ADT/StringExtras.h"
32
#include "llvm/Support/CrashRecoveryContext.h"
33
#include "llvm/Support/FileSystem.h"
34
#include "llvm/Support/FormatVariadic.h"
35
#include "llvm/Support/MemoryBuffer.h"
36
#include "llvm/Support/Program.h"
37
#include "llvm/Support/Timer.h"
38
#include "llvm/Support/raw_ostream.h"
39
#include <atomic>
40
#include <cstdio>
41
#include <cstdlib>
42
#include <string>
43
44
45
#ifdef UDP_CODE_COMPLETION_LOGGER
46
#include "clang/Basic/Version.h"
47
#include <arpa/inet.h>
48
#include <sys/socket.h>
49
#include <sys/types.h>
50
#include <unistd.h>
51
#endif
52
53
using namespace clang;
54
using namespace clang::cxindex;
55
56
enum CXCompletionChunkKind
57
clang_getCompletionChunkKind(CXCompletionString completion_string,
58
143k
                             unsigned chunk_number) {
59
143k
  CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
60
143k
  if (!CCStr || chunk_number >= CCStr->size())
61
0
    return CXCompletionChunk_Text;
62
63
143k
  switch ((*CCStr)[chunk_number].Kind) {
64
113k
  case CodeCompletionString::CK_TypedText:
65
113k
    return CXCompletionChunk_TypedText;
66
1.30k
  case CodeCompletionString::CK_Text:
67
1.30k
    return CXCompletionChunk_Text;
68
70
  case CodeCompletionString::CK_Optional:
69
70
    return CXCompletionChunk_Optional;
70
8.00k
  case CodeCompletionString::CK_Placeholder:
71
8.00k
    return CXCompletionChunk_Placeholder;
72
146
  case CodeCompletionString::CK_Informative:
73
146
    return CXCompletionChunk_Informative;
74
4.87k
  case CodeCompletionString::CK_ResultType:
75
4.87k
    return CXCompletionChunk_ResultType;
76
144
  case CodeCompletionString::CK_CurrentParameter:
77
144
    return CXCompletionChunk_CurrentParameter;
78
5.02k
  case CodeCompletionString::CK_LeftParen:
79
5.02k
    return CXCompletionChunk_LeftParen;
80
5.07k
  case CodeCompletionString::CK_RightParen:
81
5.07k
    return CXCompletionChunk_RightParen;
82
246
  case CodeCompletionString::CK_LeftBracket:
83
246
    return CXCompletionChunk_LeftBracket;
84
291
  case CodeCompletionString::CK_RightBracket:
85
291
    return CXCompletionChunk_RightBracket;
86
60
  case CodeCompletionString::CK_LeftBrace:
87
60
    return CXCompletionChunk_LeftBrace;
88
105
  case CodeCompletionString::CK_RightBrace:
89
105
    return CXCompletionChunk_RightBrace;
90
689
  case CodeCompletionString::CK_LeftAngle:
91
689
    return CXCompletionChunk_LeftAngle;
92
689
  case CodeCompletionString::CK_RightAngle:
93
689
    return CXCompletionChunk_RightAngle;
94
1.33k
  case CodeCompletionString::CK_Comma:
95
1.33k
    return CXCompletionChunk_Comma;
96
51
  case CodeCompletionString::CK_Colon:
97
51
    return CXCompletionChunk_Colon;
98
317
  case CodeCompletionString::CK_SemiColon:
99
317
    return CXCompletionChunk_SemiColon;
100
55
  case CodeCompletionString::CK_Equal:
101
55
    return CXCompletionChunk_Equal;
102
1.81k
  case CodeCompletionString::CK_HorizontalSpace:
103
1.81k
    return CXCompletionChunk_HorizontalSpace;
104
96
  case CodeCompletionString::CK_VerticalSpace:
105
96
    return CXCompletionChunk_VerticalSpace;
106
0
  }
107
108
0
  llvm_unreachable("Invalid CompletionKind!");
109
0
}
110
111
CXString clang_getCompletionChunkText(CXCompletionString completion_string,
112
143k
                                      unsigned chunk_number) {
113
143k
  CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
114
143k
  if (!CCStr || chunk_number >= CCStr->size())
115
0
    return cxstring::createNull();
116
117
143k
  switch ((*CCStr)[chunk_number].Kind) {
118
143k
  case CodeCompletionString::CK_TypedText:
119
143k
  case CodeCompletionString::CK_Text:
120
143k
  case CodeCompletionString::CK_Placeholder:
121
143k
  case CodeCompletionString::CK_CurrentParameter:
122
143k
  case CodeCompletionString::CK_Informative:
123
143k
  case CodeCompletionString::CK_LeftParen:
124
143k
  case CodeCompletionString::CK_RightParen:
125
143k
  case CodeCompletionString::CK_LeftBracket:
126
143k
  case CodeCompletionString::CK_RightBracket:
127
143k
  case CodeCompletionString::CK_LeftBrace:
128
143k
  case CodeCompletionString::CK_RightBrace:
129
143k
  case CodeCompletionString::CK_LeftAngle:
130
143k
  case CodeCompletionString::CK_RightAngle:
131
143k
  case CodeCompletionString::CK_Comma:
132
143k
  case CodeCompletionString::CK_ResultType:
133
143k
  case CodeCompletionString::CK_Colon:
134
143k
  case CodeCompletionString::CK_SemiColon:
135
143k
  case CodeCompletionString::CK_Equal:
136
143k
  case CodeCompletionString::CK_HorizontalSpace:
137
143k
  case CodeCompletionString::CK_VerticalSpace:
138
143k
    return cxstring::createRef((*CCStr)[chunk_number].Text);
139
      
140
0
  case CodeCompletionString::CK_Optional:
141
    // Note: treated as an empty text block.
142
0
    return cxstring::createEmpty();
143
0
  }
144
145
0
  llvm_unreachable("Invalid CodeCompletionString Kind!");
146
0
}
147
148
149
CXCompletionString
150
clang_getCompletionChunkCompletionString(CXCompletionString completion_string,
151
70
                                         unsigned chunk_number) {
152
70
  CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
153
70
  if (!CCStr || chunk_number >= CCStr->size())
154
0
    return nullptr;
155
156
70
  switch ((*CCStr)[chunk_number].Kind) {
157
0
  case CodeCompletionString::CK_TypedText:
158
0
  case CodeCompletionString::CK_Text:
159
0
  case CodeCompletionString::CK_Placeholder:
160
0
  case CodeCompletionString::CK_CurrentParameter:
161
0
  case CodeCompletionString::CK_Informative:
162
0
  case CodeCompletionString::CK_LeftParen:
163
0
  case CodeCompletionString::CK_RightParen:
164
0
  case CodeCompletionString::CK_LeftBracket:
165
0
  case CodeCompletionString::CK_RightBracket:
166
0
  case CodeCompletionString::CK_LeftBrace:
167
0
  case CodeCompletionString::CK_RightBrace:
168
0
  case CodeCompletionString::CK_LeftAngle:
169
0
  case CodeCompletionString::CK_RightAngle:
170
0
  case CodeCompletionString::CK_Comma:
171
0
  case CodeCompletionString::CK_ResultType:
172
0
  case CodeCompletionString::CK_Colon:
173
0
  case CodeCompletionString::CK_SemiColon:
174
0
  case CodeCompletionString::CK_Equal:
175
0
  case CodeCompletionString::CK_HorizontalSpace:
176
0
  case CodeCompletionString::CK_VerticalSpace:
177
0
    return nullptr;
178
179
70
  case CodeCompletionString::CK_Optional:
180
    // Note: treated as an empty text block.
181
70
    return (*CCStr)[chunk_number].Optional;
182
0
  }
183
184
0
  llvm_unreachable("Invalid CompletionKind!");
185
0
}
186
187
113k
unsigned clang_getNumCompletionChunks(CXCompletionString completion_string) {
188
113k
  CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
189
113k
  return CCStr? CCStr->size() : 
00
;
190
113k
}
191
192
113k
unsigned clang_getCompletionPriority(CXCompletionString completion_string) {
193
113k
  CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
194
113k
  return CCStr? CCStr->getPriority() : 
unsigned(CCP_Unlikely)0
;
195
113k
}
196
  
197
enum CXAvailabilityKind 
198
113k
clang_getCompletionAvailability(CXCompletionString completion_string) {
199
113k
  CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
200
113k
  return CCStr? static_cast<CXAvailabilityKind>(CCStr->getAvailability())
201
0
              : CXAvailability_Available;
202
113k
}
203
204
unsigned clang_getCompletionNumAnnotations(CXCompletionString completion_string)
205
113k
{
206
113k
  CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
207
113k
  return CCStr ? CCStr->getAnnotationCount() : 
00
;
208
113k
}
209
210
CXString clang_getCompletionAnnotation(CXCompletionString completion_string,
211
6
                                       unsigned annotation_number) {
212
6
  CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
213
6
  return CCStr ? cxstring::createRef(CCStr->getAnnotation(annotation_number))
214
0
               : cxstring::createNull();
215
6
}
216
217
CXString
218
clang_getCompletionParent(CXCompletionString completion_string,
219
113k
                          CXCursorKind *kind) {
220
113k
  if (kind)
221
113k
    *kind = CXCursor_NotImplemented;
222
  
223
113k
  CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
224
113k
  if (!CCStr)
225
0
    return cxstring::createNull();
226
  
227
113k
  return cxstring::createRef(CCStr->getParentContextName());
228
113k
}
229
230
CXString
231
113k
clang_getCompletionBriefComment(CXCompletionString completion_string) {
232
113k
  CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
233
234
113k
  if (!CCStr)
235
0
    return cxstring::createNull();
236
237
113k
  return cxstring::createRef(CCStr->getBriefComment());
238
113k
}
239
240
namespace {
241
242
/// The CXCodeCompleteResults structure we allocate internally;
243
/// the client only sees the initial CXCodeCompleteResults structure.
244
///
245
/// Normally, clients of CXString shouldn't care whether or not a CXString is
246
/// managed by a pool or by explicitly malloc'ed memory.  But
247
/// AllocatedCXCodeCompleteResults outlives the CXTranslationUnit, so we can
248
/// not rely on the StringPool in the TU.
249
struct AllocatedCXCodeCompleteResults : public CXCodeCompleteResults {
250
  AllocatedCXCodeCompleteResults(IntrusiveRefCntPtr<FileManager> FileMgr);
251
  ~AllocatedCXCodeCompleteResults();
252
  
253
  /// Diagnostics produced while performing code completion.
254
  SmallVector<StoredDiagnostic, 8> Diagnostics;
255
256
  /// Allocated API-exposed wrappters for Diagnostics.
257
  SmallVector<std::unique_ptr<CXStoredDiagnostic>, 8> DiagnosticsWrappers;
258
259
  IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts;
260
  
261
  /// Diag object
262
  IntrusiveRefCntPtr<DiagnosticsEngine> Diag;
263
  
264
  /// Language options used to adjust source locations.
265
  LangOptions LangOpts;
266
267
  /// File manager, used for diagnostics.
268
  IntrusiveRefCntPtr<FileManager> FileMgr;
269
270
  /// Source manager, used for diagnostics.
271
  IntrusiveRefCntPtr<SourceManager> SourceMgr;
272
  
273
  /// Temporary buffers that will be deleted once we have finished with
274
  /// the code-completion results.
275
  SmallVector<const llvm::MemoryBuffer *, 1> TemporaryBuffers;
276
  
277
  /// Allocator used to store globally cached code-completion results.
278
  std::shared_ptr<clang::GlobalCodeCompletionAllocator>
279
      CachedCompletionAllocator;
280
281
  /// Allocator used to store code completion results.
282
  std::shared_ptr<clang::GlobalCodeCompletionAllocator> CodeCompletionAllocator;
283
284
  /// Context under which completion occurred.
285
  enum clang::CodeCompletionContext::Kind ContextKind;
286
  
287
  /// A bitfield representing the acceptable completions for the
288
  /// current context.
289
  unsigned long long Contexts;
290
  
291
  /// The kind of the container for the current context for completions.
292
  enum CXCursorKind ContainerKind;
293
294
  /// The USR of the container for the current context for completions.
295
  std::string ContainerUSR;
296
297
  /// a boolean value indicating whether there is complete information
298
  /// about the container
299
  unsigned ContainerIsIncomplete;
300
  
301
  /// A string containing the Objective-C selector entered thus far for a
302
  /// message send.
303
  std::string Selector;
304
305
  /// Vector of fix-its for each completion result that *must* be applied
306
  /// before that result for the corresponding completion item.
307
  std::vector<std::vector<FixItHint>> FixItsVector;
308
};
309
310
} // end anonymous namespace
311
312
unsigned clang_getCompletionNumFixIts(CXCodeCompleteResults *results,
313
113k
                                      unsigned completion_index) {
314
113k
  AllocatedCXCodeCompleteResults *allocated_results = (AllocatedCXCodeCompleteResults *)results;
315
316
113k
  if (!allocated_results || allocated_results->FixItsVector.size() <= completion_index)
317
113k
    return 0;
318
319
24
  return static_cast<unsigned>(allocated_results->FixItsVector[completion_index].size());
320
24
}
321
322
CXString clang_getCompletionFixIt(CXCodeCompleteResults *results,
323
                                  unsigned completion_index,
324
                                  unsigned fixit_index,
325
12
                                  CXSourceRange *replacement_range) {
326
12
  AllocatedCXCodeCompleteResults *allocated_results = (AllocatedCXCodeCompleteResults *)results;
327
328
12
  if (!allocated_results || allocated_results->FixItsVector.size() <= completion_index) {
329
0
    if (replacement_range)
330
0
      *replacement_range = clang_getNullRange();
331
0
    return cxstring::createNull();
332
0
  }
333
334
12
  ArrayRef<FixItHint> FixIts = allocated_results->FixItsVector[completion_index];
335
12
  if (FixIts.size() <= fixit_index) {
336
0
    if (replacement_range)
337
0
      *replacement_range = clang_getNullRange();
338
0
    return cxstring::createNull();
339
0
  }
340
341
12
  const FixItHint &FixIt = FixIts[fixit_index];
342
12
  if (replacement_range) {
343
12
    *replacement_range = cxloc::translateSourceRange(
344
12
        *allocated_results->SourceMgr, allocated_results->LangOpts,
345
12
        FixIt.RemoveRange);
346
12
  }
347
348
12
  return cxstring::createRef(FixIt.CodeToInsert.c_str());
349
12
}
350
351
/// Tracks the number of code-completion result objects that are 
352
/// currently active.
353
///
354
/// Used for debugging purposes only.
355
static std::atomic<unsigned> CodeCompletionResultObjects;
356
357
AllocatedCXCodeCompleteResults::AllocatedCXCodeCompleteResults(
358
    IntrusiveRefCntPtr<FileManager> FileMgr)
359
    : CXCodeCompleteResults(), DiagOpts(new DiagnosticOptions),
360
      Diag(new DiagnosticsEngine(
361
          IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs), &*DiagOpts)),
362
      FileMgr(std::move(FileMgr)),
363
      SourceMgr(new SourceManager(*Diag, *this->FileMgr)),
364
      CodeCompletionAllocator(
365
          std::make_shared<clang::GlobalCodeCompletionAllocator>()),
366
      Contexts(CXCompletionContext_Unknown),
367
720
      ContainerKind(CXCursor_InvalidCode), ContainerIsIncomplete(1) {
368
720
  if (getenv("LIBCLANG_OBJTRACKING"))
369
0
    fprintf(stderr, "+++ %u completion results\n",
370
0
            ++CodeCompletionResultObjects);
371
720
}
372
  
373
717
AllocatedCXCodeCompleteResults::~AllocatedCXCodeCompleteResults() {
374
717
  delete [] Results;
375
376
793
  for (unsigned I = 0, N = TemporaryBuffers.size(); I != N; 
++I76
)
377
76
    delete TemporaryBuffers[I];
378
379
717
  if (getenv("LIBCLANG_OBJTRACKING"))
380
0
    fprintf(stderr, "--- %u completion results\n",
381
0
            --CodeCompletionResultObjects);
382
717
}
383
384
static unsigned long long getContextsForContextKind(
385
                                          enum CodeCompletionContext::Kind kind, 
386
715
                                                    Sema &S) {
387
715
  unsigned long long contexts = 0;
388
715
  switch (kind) {
389
0
    case CodeCompletionContext::CCC_OtherWithMacros: {
390
      //We can allow macros here, but we don't know what else is permissible
391
      //So we'll say the only thing permissible are macros
392
0
      contexts = CXCompletionContext_MacroName;
393
0
      break;
394
0
    }
395
53
    case CodeCompletionContext::CCC_TopLevel:
396
53
    case CodeCompletionContext::CCC_ObjCIvarList:
397
53
    case CodeCompletionContext::CCC_ClassStructUnion:
398
53
    case CodeCompletionContext::CCC_Type: {
399
53
      contexts = CXCompletionContext_AnyType | 
400
53
                 CXCompletionContext_ObjCInterface;
401
53
      if (S.getLangOpts().CPlusPlus) {
402
18
        contexts |= CXCompletionContext_EnumTag |
403
18
                    CXCompletionContext_UnionTag |
404
18
                    CXCompletionContext_StructTag |
405
18
                    CXCompletionContext_ClassTag |
406
18
                    CXCompletionContext_NestedNameSpecifier;
407
18
      }
408
53
      break;
409
53
    }
410
75
    case CodeCompletionContext::CCC_Statement: {
411
75
      contexts = CXCompletionContext_AnyType |
412
75
                 CXCompletionContext_ObjCInterface |
413
75
                 CXCompletionContext_AnyValue;
414
75
      if (S.getLangOpts().CPlusPlus) {
415
31
        contexts |= CXCompletionContext_EnumTag |
416
31
                    CXCompletionContext_UnionTag |
417
31
                    CXCompletionContext_StructTag |
418
31
                    CXCompletionContext_ClassTag |
419
31
                    CXCompletionContext_NestedNameSpecifier;
420
31
      }
421
75
      break;
422
53
    }
423
186
    case CodeCompletionContext::CCC_Expression: {
424
186
      contexts = CXCompletionContext_AnyValue;
425
186
      if (S.getLangOpts().CPlusPlus) {
426
106
        contexts |= CXCompletionContext_AnyType |
427
106
                    CXCompletionContext_ObjCInterface |
428
106
                    CXCompletionContext_EnumTag |
429
106
                    CXCompletionContext_UnionTag |
430
106
                    CXCompletionContext_StructTag |
431
106
                    CXCompletionContext_ClassTag |
432
106
                    CXCompletionContext_NestedNameSpecifier;
433
106
      }
434
186
      break;
435
53
    }
436
7
    case CodeCompletionContext::CCC_ObjCMessageReceiver: {
437
7
      contexts = CXCompletionContext_ObjCObjectValue |
438
7
                 CXCompletionContext_ObjCSelectorValue |
439
7
                 CXCompletionContext_ObjCInterface;
440
7
      if (S.getLangOpts().CPlusPlus) {
441
2
        contexts |= CXCompletionContext_CXXClassTypeValue |
442
2
                    CXCompletionContext_AnyType |
443
2
                    CXCompletionContext_EnumTag |
444
2
                    CXCompletionContext_UnionTag |
445
2
                    CXCompletionContext_StructTag |
446
2
                    CXCompletionContext_ClassTag |
447
2
                    CXCompletionContext_NestedNameSpecifier;
448
2
      }
449
7
      break;
450
53
    }
451
22
    case CodeCompletionContext::CCC_DotMemberAccess: {
452
22
      contexts = CXCompletionContext_DotMemberAccess;
453
22
      break;
454
53
    }
455
24
    case CodeCompletionContext::CCC_ArrowMemberAccess: {
456
24
      contexts = CXCompletionContext_ArrowMemberAccess;
457
24
      break;
458
53
    }
459
24
    case CodeCompletionContext::CCC_ObjCPropertyAccess: {
460
24
      contexts = CXCompletionContext_ObjCPropertyAccess;
461
24
      break;
462
53
    }
463
0
    case CodeCompletionContext::CCC_EnumTag: {
464
0
      contexts = CXCompletionContext_EnumTag |
465
0
                 CXCompletionContext_NestedNameSpecifier;
466
0
      break;
467
53
    }
468
0
    case CodeCompletionContext::CCC_UnionTag: {
469
0
      contexts = CXCompletionContext_UnionTag |
470
0
                 CXCompletionContext_NestedNameSpecifier;
471
0
      break;
472
53
    }
473
6
    case CodeCompletionContext::CCC_ClassOrStructTag: {
474
6
      contexts = CXCompletionContext_StructTag |
475
6
                 CXCompletionContext_ClassTag |
476
6
                 CXCompletionContext_NestedNameSpecifier;
477
6
      break;
478
53
    }
479
9
    case CodeCompletionContext::CCC_ObjCProtocolName: {
480
9
      contexts = CXCompletionContext_ObjCProtocol;
481
9
      break;
482
53
    }
483
0
    case CodeCompletionContext::CCC_Namespace: {
484
0
      contexts = CXCompletionContext_Namespace;
485
0
      break;
486
53
    }
487
49
    case CodeCompletionContext::CCC_SymbolOrNewName:
488
49
    case CodeCompletionContext::CCC_Symbol: {
489
49
      contexts = CXCompletionContext_NestedNameSpecifier;
490
49
      break;
491
49
    }
492
8
    case CodeCompletionContext::CCC_MacroNameUse: {
493
8
      contexts = CXCompletionContext_MacroName;
494
8
      break;
495
49
    }
496
45
    case CodeCompletionContext::CCC_NaturalLanguage: {
497
45
      contexts = CXCompletionContext_NaturalLanguage;
498
45
      break;
499
49
    }
500
0
    case CodeCompletionContext::CCC_IncludedFile: {
501
0
      contexts = CXCompletionContext_IncludedFile;
502
0
      break;
503
49
    }
504
2
    case CodeCompletionContext::CCC_SelectorName: {
505
2
      contexts = CXCompletionContext_ObjCSelectorName;
506
2
      break;
507
49
    }
508
13
    case CodeCompletionContext::CCC_ParenthesizedExpression: {
509
13
      contexts = CXCompletionContext_AnyType |
510
13
                 CXCompletionContext_ObjCInterface |
511
13
                 CXCompletionContext_AnyValue;
512
13
      if (S.getLangOpts().CPlusPlus) {
513
0
        contexts |= CXCompletionContext_EnumTag |
514
0
                    CXCompletionContext_UnionTag |
515
0
                    CXCompletionContext_StructTag |
516
0
                    CXCompletionContext_ClassTag |
517
0
                    CXCompletionContext_NestedNameSpecifier;
518
0
      }
519
13
      break;
520
49
    }
521
49
    case CodeCompletionContext::CCC_ObjCInstanceMessage: {
522
49
      contexts = CXCompletionContext_ObjCInstanceMessage;
523
49
      break;
524
49
    }
525
22
    case CodeCompletionContext::CCC_ObjCClassMessage: {
526
22
      contexts = CXCompletionContext_ObjCClassMessage;
527
22
      break;
528
49
    }
529
8
    case CodeCompletionContext::CCC_ObjCInterfaceName: {
530
8
      contexts = CXCompletionContext_ObjCInterface;
531
8
      break;
532
49
    }
533
5
    case CodeCompletionContext::CCC_ObjCCategoryName: {
534
5
      contexts = CXCompletionContext_ObjCCategory;
535
5
      break;
536
49
    }
537
107
    case CodeCompletionContext::CCC_Other:
538
107
    case CodeCompletionContext::CCC_ObjCInterface:
539
107
    case CodeCompletionContext::CCC_ObjCImplementation:
540
107
    case CodeCompletionContext::CCC_NewName:
541
107
    case CodeCompletionContext::CCC_MacroName:
542
107
    case CodeCompletionContext::CCC_PreprocessorExpression:
543
107
    case CodeCompletionContext::CCC_PreprocessorDirective:
544
107
    case CodeCompletionContext::CCC_TypeQualifiers: {
545
      //Only Clang results should be accepted, so we'll set all of the other
546
      //context bits to 0 (i.e. the empty set)
547
107
      contexts = CXCompletionContext_Unexposed;
548
107
      break;
549
107
    }
550
1
    case CodeCompletionContext::CCC_Recovery: {
551
      //We don't know what the current context is, so we'll return unknown
552
      //This is the equivalent of setting all of the other context bits
553
1
      contexts = CXCompletionContext_Unknown;
554
1
      break;
555
715
    }
556
715
  }
557
715
  return contexts;
558
715
}
559
560
namespace {
561
  class CaptureCompletionResults : public CodeCompleteConsumer {
562
    AllocatedCXCodeCompleteResults &AllocatedResults;
563
    CodeCompletionTUInfo CCTUInfo;
564
    SmallVector<CXCompletionResult, 16> StoredResults;
565
    CXTranslationUnit *TU;
566
  public:
567
    CaptureCompletionResults(const CodeCompleteOptions &Opts,
568
                             AllocatedCXCodeCompleteResults &Results,
569
                             CXTranslationUnit *TranslationUnit)
570
        : CodeCompleteConsumer(Opts), AllocatedResults(Results),
571
720
          CCTUInfo(Results.CodeCompletionAllocator), TU(TranslationUnit) {}
572
717
    ~CaptureCompletionResults() override { Finish(); }
573
574
    void ProcessCodeCompleteResults(Sema &S, 
575
                                    CodeCompletionContext Context,
576
                                    CodeCompletionResult *Results,
577
715
                                    unsigned NumResults) override {
578
715
      StoredResults.reserve(StoredResults.size() + NumResults);
579
715
      if (includeFixIts())
580
2
        AllocatedResults.FixItsVector.reserve(NumResults);
581
157k
      for (unsigned I = 0; I != NumResults; 
++I157k
) {
582
157k
        CodeCompletionString *StoredCompletion
583
157k
          = Results[I].CreateCodeCompletionString(S, Context, getAllocator(),
584
157k
                                                  getCodeCompletionTUInfo(),
585
157k
                                                  includeBriefComments());
586
        
587
157k
        CXCompletionResult R;
588
157k
        R.CursorKind = Results[I].CursorKind;
589
157k
        R.CompletionString = StoredCompletion;
590
157k
        StoredResults.push_back(R);
591
157k
        if (includeFixIts())
592
12
          AllocatedResults.FixItsVector.emplace_back(std::move(Results[I].FixIts));
593
157k
      }
594
595
715
      enum CodeCompletionContext::Kind contextKind = Context.getKind();
596
      
597
715
      AllocatedResults.ContextKind = contextKind;
598
715
      AllocatedResults.Contexts = getContextsForContextKind(contextKind, S);
599
      
600
715
      AllocatedResults.Selector = "";
601
715
      ArrayRef<IdentifierInfo *> SelIdents = Context.getSelIdents();
602
715
      for (ArrayRef<IdentifierInfo *>::iterator I = SelIdents.begin(),
603
715
                                                E = SelIdents.end();
604
737
           I != E; 
++I22
) {
605
22
        if (IdentifierInfo *selIdent = *I)
606
22
          AllocatedResults.Selector += selIdent->getName();
607
22
        AllocatedResults.Selector += ":";
608
22
      }
609
      
610
715
      QualType baseType = Context.getBaseType();
611
715
      NamedDecl *D = nullptr;
612
613
715
      if (!baseType.isNull()) {
614
        // Get the declaration for a class/struct/union/enum type
615
138
        if (const TagType *Tag = baseType->getAs<TagType>())
616
37
          D = Tag->getDecl();
617
        // Get the @interface declaration for a (possibly-qualified) Objective-C
618
        // object pointer type, e.g., NSString*
619
101
        else if (const ObjCObjectPointerType *ObjPtr = 
620
79
                 baseType->getAs<ObjCObjectPointerType>())
621
79
          D = ObjPtr->getInterfaceDecl();
622
        // Get the @interface declaration for an Objective-C object type
623
22
        else if (const ObjCObjectType *Obj = baseType->getAs<ObjCObjectType>())
624
20
          D = Obj->getInterface();
625
        // Get the class for a C++ injected-class-name
626
2
        else if (const InjectedClassNameType *Injected =
627
0
                 baseType->getAs<InjectedClassNameType>())
628
0
          D = Injected->getDecl();
629
138
      }
630
631
715
      if (D != nullptr) {
632
128
        CXCursor cursor = cxcursor::MakeCXCursor(D, *TU);
633
634
128
        AllocatedResults.ContainerKind = clang_getCursorKind(cursor);
635
636
128
        CXString CursorUSR = clang_getCursorUSR(cursor);
637
128
        AllocatedResults.ContainerUSR = clang_getCString(CursorUSR);
638
128
        clang_disposeString(CursorUSR);
639
640
128
        const Type *type = baseType.getTypePtrOrNull();
641
128
        if (type) {
642
128
          AllocatedResults.ContainerIsIncomplete = type->isIncompleteType();
643
128
        }
644
0
        else {
645
0
          AllocatedResults.ContainerIsIncomplete = 1;
646
0
        }
647
128
      }
648
587
      else {
649
587
        AllocatedResults.ContainerKind = CXCursor_InvalidCode;
650
587
        AllocatedResults.ContainerUSR.clear();
651
587
        AllocatedResults.ContainerIsIncomplete = 1;
652
587
      }
653
715
    }
654
655
    void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
656
                                   OverloadCandidate *Candidates,
657
                                   unsigned NumCandidates,
658
101
                                   SourceLocation OpenParLoc) override {
659
101
      StoredResults.reserve(StoredResults.size() + NumCandidates);
660
264
      for (unsigned I = 0; I != NumCandidates; 
++I163
) {
661
163
        CodeCompletionString *StoredCompletion
662
163
          = Candidates[I].CreateSignatureString(CurrentArg, S, getAllocator(),
663
163
                                                getCodeCompletionTUInfo(),
664
163
                                                includeBriefComments());
665
        
666
163
        CXCompletionResult R;
667
163
        R.CursorKind = CXCursor_OverloadCandidate;
668
163
        R.CompletionString = StoredCompletion;
669
163
        StoredResults.push_back(R);
670
163
      }
671
101
    }
672
673
159k
    CodeCompletionAllocator &getAllocator() override {
674
159k
      return *AllocatedResults.CodeCompletionAllocator;
675
159k
    }
676
677
159k
    CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo;}
678
679
  private:
680
717
    void Finish() {
681
717
      AllocatedResults.Results = new CXCompletionResult [StoredResults.size()];
682
717
      AllocatedResults.NumResults = StoredResults.size();
683
717
      std::memcpy(AllocatedResults.Results, StoredResults.data(), 
684
717
                  StoredResults.size() * sizeof(CXCompletionResult));
685
717
      StoredResults.clear();
686
717
    }
687
  };
688
}
689
690
static CXCodeCompleteResults *
691
clang_codeCompleteAt_Impl(CXTranslationUnit TU, const char *complete_filename,
692
                          unsigned complete_line, unsigned complete_column,
693
                          ArrayRef<CXUnsavedFile> unsaved_files,
694
720
                          unsigned options) {
695
720
  bool IncludeBriefComments = options & CXCodeComplete_IncludeBriefComments;
696
720
  bool SkipPreamble = options & CXCodeComplete_SkipPreamble;
697
720
  bool IncludeFixIts = options & CXCodeComplete_IncludeCompletionsWithFixIts;
698
699
#ifdef UDP_CODE_COMPLETION_LOGGER
700
#ifdef UDP_CODE_COMPLETION_LOGGER_PORT
701
  const llvm::TimeRecord &StartTime =  llvm::TimeRecord::getCurrentTime();
702
#endif
703
#endif
704
720
  bool EnableLogging = getenv("LIBCLANG_CODE_COMPLETION_LOGGING") != nullptr;
705
706
720
  if (cxtu::isNotUsableTU(TU)) {
707
0
    LOG_BAD_TU(TU);
708
0
    return nullptr;
709
0
  }
710
711
720
  ASTUnit *AST = cxtu::getASTUnit(TU);
712
720
  if (!AST)
713
0
    return nullptr;
714
715
720
  CIndexer *CXXIdx = TU->CIdx;
716
720
  if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
717
0
    setThreadBackgroundPriority();
718
719
720
  ASTUnit::ConcurrencyCheck Check(*AST);
720
721
  // Perform the remapping of source files.
722
720
  SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
723
724
4
  for (auto &UF : unsaved_files) {
725
4
    std::unique_ptr<llvm::MemoryBuffer> MB =
726
4
        llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
727
4
    RemappedFiles.push_back(std::make_pair(UF.Filename, MB.release()));
728
4
  }
729
730
720
  if (EnableLogging) {
731
    // FIXME: Add logging.
732
0
  }
733
734
  // Parse the resulting source file to find code-completion results.
735
720
  AllocatedCXCodeCompleteResults *Results = new AllocatedCXCodeCompleteResults(
736
720
      &AST->getFileManager());
737
720
  Results->Results = nullptr;
738
720
  Results->NumResults = 0;
739
  
740
  // Create a code-completion consumer to capture the results.
741
720
  CodeCompleteOptions Opts;
742
720
  Opts.IncludeBriefComments = IncludeBriefComments;
743
720
  Opts.LoadExternal = !SkipPreamble;
744
720
  Opts.IncludeFixIts = IncludeFixIts;
745
720
  CaptureCompletionResults Capture(Opts, *Results, &TU);
746
747
  // Perform completion.
748
720
  std::vector<const char *> CArgs;
749
720
  for (const auto &Arg : TU->Arguments)
750
4.68k
    CArgs.push_back(Arg.c_str());
751
720
  std::string CompletionInvocation =
752
720
      llvm::formatv("-code-completion-at={0}:{1}:{2}", complete_filename,
753
720
                    complete_line, complete_column)
754
720
          .str();
755
720
  LibclangInvocationReporter InvocationReporter(
756
720
      *CXXIdx, LibclangInvocationReporter::OperationKind::CompletionOperation,
757
720
      TU->ParsingOptions, CArgs, CompletionInvocation, unsaved_files);
758
720
  AST->CodeComplete(complete_filename, complete_line, complete_column,
759
720
                    RemappedFiles, (options & CXCodeComplete_IncludeMacros),
760
720
                    (options & CXCodeComplete_IncludeCodePatterns),
761
720
                    IncludeBriefComments, Capture,
762
720
                    CXXIdx->getPCHContainerOperations(), *Results->Diag,
763
720
                    Results->LangOpts, *Results->SourceMgr, *Results->FileMgr,
764
720
                    Results->Diagnostics, Results->TemporaryBuffers);
765
766
720
  Results->DiagnosticsWrappers.resize(Results->Diagnostics.size());
767
768
  // Keep a reference to the allocator used for cached global completions, so
769
  // that we can be sure that the memory used by our code completion strings
770
  // doesn't get freed due to subsequent reparses (while the code completion
771
  // results are still active).
772
720
  Results->CachedCompletionAllocator = AST->getCachedCompletionAllocator();
773
774
  
775
776
#ifdef UDP_CODE_COMPLETION_LOGGER
777
#ifdef UDP_CODE_COMPLETION_LOGGER_PORT
778
  const llvm::TimeRecord &EndTime =  llvm::TimeRecord::getCurrentTime();
779
  SmallString<256> LogResult;
780
  llvm::raw_svector_ostream os(LogResult);
781
782
  // Figure out the language and whether or not it uses PCH.
783
  const char *lang = 0;
784
  bool usesPCH = false;
785
786
  for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
787
       I != E; ++I) {
788
    if (*I == 0)
789
      continue;
790
    if (strcmp(*I, "-x") == 0) {
791
      if (I + 1 != E) {
792
        lang = *(++I);
793
        continue;
794
      }
795
    }
796
    else if (strcmp(*I, "-include") == 0) {
797
      if (I+1 != E) {
798
        const char *arg = *(++I);
799
        SmallString<512> pchName;
800
        {
801
          llvm::raw_svector_ostream os(pchName);
802
          os << arg << ".pth";
803
        }
804
        pchName.push_back('\0');
805
        llvm::sys::fs::file_status stat_results;
806
        if (!llvm::sys::fs::status(pchName, stat_results))
807
          usesPCH = true;
808
        continue;
809
      }
810
    }
811
  }
812
813
  os << "{ ";
814
  os << "\"wall\": " << (EndTime.getWallTime() - StartTime.getWallTime());
815
  os << ", \"numRes\": " << Results->NumResults;
816
  os << ", \"diags\": " << Results->Diagnostics.size();
817
  os << ", \"pch\": " << (usesPCH ? "true" : "false");
818
  os << ", \"lang\": \"" << (lang ? lang : "<unknown>") << '"';
819
  const char *name = getlogin();
820
  os << ", \"user\": \"" << (name ? name : "unknown") << '"';
821
  os << ", \"clangVer\": \"" << getClangFullVersion() << '"';
822
  os << " }";
823
824
  StringRef res = os.str();
825
  if (res.size() > 0) {
826
    do {
827
      // Setup the UDP socket.
828
      struct sockaddr_in servaddr;
829
      bzero(&servaddr, sizeof(servaddr));
830
      servaddr.sin_family = AF_INET;
831
      servaddr.sin_port = htons(UDP_CODE_COMPLETION_LOGGER_PORT);
832
      if (inet_pton(AF_INET, UDP_CODE_COMPLETION_LOGGER,
833
                    &servaddr.sin_addr) <= 0)
834
        break;
835
836
      int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
837
      if (sockfd < 0)
838
        break;
839
840
      sendto(sockfd, res.data(), res.size(), 0,
841
             (struct sockaddr *)&servaddr, sizeof(servaddr));
842
      close(sockfd);
843
    }
844
    while (false);
845
  }
846
#endif
847
#endif
848
720
  return Results;
849
720
}
850
851
CXCodeCompleteResults *clang_codeCompleteAt(CXTranslationUnit TU,
852
                                            const char *complete_filename,
853
                                            unsigned complete_line,
854
                                            unsigned complete_column,
855
                                            struct CXUnsavedFile *unsaved_files,
856
                                            unsigned num_unsaved_files,
857
720
                                            unsigned options) {
858
720
  LOG_FUNC_SECTION {
859
0
    *Log << TU << ' '
860
0
         << complete_filename << ':' << complete_line << ':' << complete_column;
861
0
  }
862
863
720
  if (num_unsaved_files && 
!unsaved_files4
)
864
0
    return nullptr;
865
866
720
  CXCodeCompleteResults *result;
867
720
  auto CodeCompleteAtImpl = [=, &result]() {
868
720
    result = clang_codeCompleteAt_Impl(
869
720
        TU, complete_filename, complete_line, complete_column,
870
720
        llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
871
720
  };
872
873
720
  llvm::CrashRecoveryContext CRC;
874
875
720
  if (!RunSafely(CRC, CodeCompleteAtImpl)) {
876
3
    fprintf(stderr, "libclang: crash detected in code completion\n");
877
3
    cxtu::getASTUnit(TU)->setUnsafeToFree(true);
878
3
    return nullptr;
879
717
  } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
880
0
    PrintLibclangResourceUsage(TU);
881
882
717
  return result;
883
720
}
884
885
536
unsigned clang_defaultCodeCompleteOptions(void) {
886
536
  return CXCodeComplete_IncludeMacros;
887
536
}
888
889
717
void clang_disposeCodeCompleteResults(CXCodeCompleteResults *ResultsIn) {
890
717
  if (!ResultsIn)
891
0
    return;
892
893
717
  AllocatedCXCodeCompleteResults *Results
894
717
    = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
895
717
  delete Results;
896
717
}
897
  
898
unsigned 
899
533
clang_codeCompleteGetNumDiagnostics(CXCodeCompleteResults *ResultsIn) {
900
533
  AllocatedCXCodeCompleteResults *Results
901
533
    = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
902
533
  if (!Results)
903
0
    return 0;
904
905
533
  return Results->Diagnostics.size();
906
533
}
907
908
CXDiagnostic 
909
clang_codeCompleteGetDiagnostic(CXCodeCompleteResults *ResultsIn,
910
205
                                unsigned Index) {
911
205
  AllocatedCXCodeCompleteResults *Results
912
205
    = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
913
205
  if (!Results || Index >= Results->Diagnostics.size())
914
0
    return nullptr;
915
916
205
  CXStoredDiagnostic *Diag = Results->DiagnosticsWrappers[Index].get();
917
205
  if (!Diag)
918
205
    Diag = (Results->DiagnosticsWrappers[Index] =
919
205
                std::make_unique<CXStoredDiagnostic>(
920
205
                    Results->Diagnostics[Index], Results->LangOpts))
921
205
               .get();
922
205
  return Diag;
923
205
}
924
925
unsigned long long
926
533
clang_codeCompleteGetContexts(CXCodeCompleteResults *ResultsIn) {
927
533
  AllocatedCXCodeCompleteResults *Results
928
533
    = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
929
533
  if (!Results)
930
0
    return 0;
931
  
932
533
  return Results->Contexts;
933
533
}
934
935
enum CXCursorKind clang_codeCompleteGetContainerKind(
936
                                               CXCodeCompleteResults *ResultsIn,
937
533
                                                     unsigned *IsIncomplete) {
938
533
  AllocatedCXCodeCompleteResults *Results =
939
533
    static_cast<AllocatedCXCodeCompleteResults *>(ResultsIn);
940
533
  if (!Results)
941
0
    return CXCursor_InvalidCode;
942
943
533
  if (IsIncomplete != nullptr) {
944
533
    *IsIncomplete = Results->ContainerIsIncomplete;
945
533
  }
946
  
947
533
  return Results->ContainerKind;
948
533
}
949
  
950
124
CXString clang_codeCompleteGetContainerUSR(CXCodeCompleteResults *ResultsIn) {
951
124
  AllocatedCXCodeCompleteResults *Results =
952
124
    static_cast<AllocatedCXCodeCompleteResults *>(ResultsIn);
953
124
  if (!Results)
954
0
    return cxstring::createEmpty();
955
956
124
  return cxstring::createRef(Results->ContainerUSR.c_str());
957
124
}
958
959
  
960
533
CXString clang_codeCompleteGetObjCSelector(CXCodeCompleteResults *ResultsIn) {
961
533
  AllocatedCXCodeCompleteResults *Results =
962
533
    static_cast<AllocatedCXCodeCompleteResults *>(ResultsIn);
963
533
  if (!Results)
964
0
    return cxstring::createEmpty();
965
  
966
533
  return cxstring::createDup(Results->Selector);
967
533
}
968
  
969
/// Simple utility function that appends a \p New string to the given
970
/// \p Old string, using the \p Buffer for storage.
971
///
972
/// \param Old The string to which we are appending. This parameter will be
973
/// updated to reflect the complete string.
974
///
975
///
976
/// \param New The string to append to \p Old.
977
///
978
/// \param Buffer A buffer that stores the actual, concatenated string. It will
979
/// be used if the old string is already-non-empty.
980
static void AppendToString(StringRef &Old, StringRef New,
981
7.44M
                           SmallString<256> &Buffer) {
982
7.44M
  if (Old.empty()) {
983
7.44M
    Old = New;
984
7.44M
    return;
985
7.44M
  }
986
  
987
2.17k
  if (Buffer.empty())
988
2.01k
    Buffer.append(Old.begin(), Old.end());
989
2.17k
  Buffer.append(New.begin(), New.end());
990
2.17k
  Old = Buffer.str();
991
2.17k
}
992
993
/// Get the typed-text blocks from the given code-completion string
994
/// and return them as a single string.
995
///
996
/// \param String The code-completion string whose typed-text blocks will be
997
/// concatenated.
998
///
999
/// \param Buffer A buffer used for storage of the completed name.
1000
static StringRef GetTypedName(CodeCompletionString *String,
1001
7.46M
                                    SmallString<256> &Buffer) {
1002
7.46M
  StringRef Result;
1003
7.46M
  for (CodeCompletionString::iterator C = String->begin(), CEnd = String->end();
1004
17.1M
       C != CEnd; 
++C9.64M
) {
1005
9.64M
    if (C->Kind == CodeCompletionString::CK_TypedText)
1006
7.44M
      AppendToString(Result, C->Text, Buffer);
1007
9.64M
  }
1008
  
1009
7.46M
  return Result;
1010
7.46M
}
1011
1012
namespace {
1013
  struct OrderCompletionResults {
1014
    bool operator()(const CXCompletionResult &XR, 
1015
3.73M
                    const CXCompletionResult &YR) const {
1016
3.73M
      CodeCompletionString *X
1017
3.73M
        = (CodeCompletionString *)XR.CompletionString;
1018
3.73M
      CodeCompletionString *Y
1019
3.73M
        = (CodeCompletionString *)YR.CompletionString;
1020
1021
3.73M
      SmallString<256> XBuffer;
1022
3.73M
      StringRef XText = GetTypedName(X, XBuffer);
1023
3.73M
      SmallString<256> YBuffer;
1024
3.73M
      StringRef YText = GetTypedName(Y, YBuffer);
1025
      
1026
3.73M
      if (XText.empty() || 
YText.empty()3.73M
)
1027
17.6k
        return !XText.empty();
1028
            
1029
3.71M
      int result = XText.compare_lower(YText);
1030
3.71M
      if (result < 0)
1031
3.51M
        return true;
1032
199k
      if (result > 0)
1033
193k
        return false;
1034
      
1035
5.71k
      result = XText.compare(YText);
1036
5.71k
      return result < 0;
1037
5.71k
    }
1038
  };
1039
}
1040
1041
void clang_sortCodeCompletionResults(CXCompletionResult *Results,
1042
533
                                     unsigned NumResults) {
1043
533
  std::stable_sort(Results, Results + NumResults, OrderCompletionResults());
1044
533
}