Coverage Report

Created: 2020-02-25 14:32

/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
142k
                             unsigned chunk_number) {
59
142k
  CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
60
142k
  if (!CCStr || chunk_number >= CCStr->size())
61
0
    return CXCompletionChunk_Text;
62
142k
63
142k
  switch ((*CCStr)[chunk_number].Kind) {
64
112k
  case CodeCompletionString::CK_TypedText:
65
112k
    return CXCompletionChunk_TypedText;
66
1.42k
  case CodeCompletionString::CK_Text:
67
1.42k
    return CXCompletionChunk_Text;
68
68
  case CodeCompletionString::CK_Optional:
69
68
    return CXCompletionChunk_Optional;
70
8.07k
  case CodeCompletionString::CK_Placeholder:
71
8.07k
    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
143
  case CodeCompletionString::CK_CurrentParameter:
77
143
    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
288
  case CodeCompletionString::CK_SemiColon:
99
288
    return CXCompletionChunk_SemiColon;
100
26
  case CodeCompletionString::CK_Equal:
101
26
    return CXCompletionChunk_Equal;
102
1.78k
  case CodeCompletionString::CK_HorizontalSpace:
103
1.78k
    return CXCompletionChunk_HorizontalSpace;
104
96
  case CodeCompletionString::CK_VerticalSpace:
105
96
    return CXCompletionChunk_VerticalSpace;
106
0
  }
107
0
108
0
  llvm_unreachable("Invalid CompletionKind!");
109
0
}
110
111
CXString clang_getCompletionChunkText(CXCompletionString completion_string,
112
142k
                                      unsigned chunk_number) {
113
142k
  CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
114
142k
  if (!CCStr || chunk_number >= CCStr->size())
115
0
    return cxstring::createNull();
116
142k
117
142k
  switch ((*CCStr)[chunk_number].Kind) {
118
142k
  case CodeCompletionString::CK_TypedText:
119
142k
  case CodeCompletionString::CK_Text:
120
142k
  case CodeCompletionString::CK_Placeholder:
121
142k
  case CodeCompletionString::CK_CurrentParameter:
122
142k
  case CodeCompletionString::CK_Informative:
123
142k
  case CodeCompletionString::CK_LeftParen:
124
142k
  case CodeCompletionString::CK_RightParen:
125
142k
  case CodeCompletionString::CK_LeftBracket:
126
142k
  case CodeCompletionString::CK_RightBracket:
127
142k
  case CodeCompletionString::CK_LeftBrace:
128
142k
  case CodeCompletionString::CK_RightBrace:
129
142k
  case CodeCompletionString::CK_LeftAngle:
130
142k
  case CodeCompletionString::CK_RightAngle:
131
142k
  case CodeCompletionString::CK_Comma:
132
142k
  case CodeCompletionString::CK_ResultType:
133
142k
  case CodeCompletionString::CK_Colon:
134
142k
  case CodeCompletionString::CK_SemiColon:
135
142k
  case CodeCompletionString::CK_Equal:
136
142k
  case CodeCompletionString::CK_HorizontalSpace:
137
142k
  case CodeCompletionString::CK_VerticalSpace:
138
142k
    return cxstring::createRef((*CCStr)[chunk_number].Text);
139
142k
      
140
142k
  case CodeCompletionString::CK_Optional:
141
0
    // Note: treated as an empty text block.
142
0
    return cxstring::createEmpty();
143
0
  }
144
0
145
0
  llvm_unreachable("Invalid CodeCompletionString Kind!");
146
0
}
147
148
149
CXCompletionString
150
clang_getCompletionChunkCompletionString(CXCompletionString completion_string,
151
68
                                         unsigned chunk_number) {
152
68
  CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
153
68
  if (!CCStr || chunk_number >= CCStr->size())
154
0
    return nullptr;
155
68
156
68
  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
0
179
68
  case CodeCompletionString::CK_Optional:
180
68
    // Note: treated as an empty text block.
181
68
    return (*CCStr)[chunk_number].Optional;
182
0
  }
183
0
184
0
  llvm_unreachable("Invalid CompletionKind!");
185
0
}
186
187
112k
unsigned clang_getNumCompletionChunks(CXCompletionString completion_string) {
188
112k
  CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
189
112k
  return CCStr? CCStr->size() : 
00
;
190
112k
}
191
192
112k
unsigned clang_getCompletionPriority(CXCompletionString completion_string) {
193
112k
  CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
194
112k
  return CCStr? CCStr->getPriority() : 
unsigned(CCP_Unlikely)0
;
195
112k
}
196
  
197
enum CXAvailabilityKind 
198
112k
clang_getCompletionAvailability(CXCompletionString completion_string) {
199
112k
  CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
200
112k
  return CCStr? static_cast<CXAvailabilityKind>(CCStr->getAvailability())
201
112k
              : 
CXAvailability_Available0
;
202
112k
}
203
204
unsigned clang_getCompletionNumAnnotations(CXCompletionString completion_string)
205
112k
{
206
112k
  CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
207
112k
  return CCStr ? CCStr->getAnnotationCount() : 
00
;
208
112k
}
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
6
               : 
cxstring::createNull()0
;
215
6
}
216
217
CXString
218
clang_getCompletionParent(CXCompletionString completion_string,
219
112k
                          CXCursorKind *kind) {
220
112k
  if (kind)
221
112k
    *kind = CXCursor_NotImplemented;
222
112k
  
223
112k
  CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
224
112k
  if (!CCStr)
225
0
    return cxstring::createNull();
226
112k
  
227
112k
  return cxstring::createRef(CCStr->getParentContextName());
228
112k
}
229
230
CXString
231
112k
clang_getCompletionBriefComment(CXCompletionString completion_string) {
232
112k
  CodeCompletionString *CCStr = (CodeCompletionString *)completion_string;
233
112k
234
112k
  if (!CCStr)
235
0
    return cxstring::createNull();
236
112k
237
112k
  return cxstring::createRef(CCStr->getBriefComment());
238
112k
}
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<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
112k
                                      unsigned completion_index) {
314
112k
  AllocatedCXCodeCompleteResults *allocated_results = (AllocatedCXCodeCompleteResults *)results;
315
112k
316
112k
  if (!allocated_results || allocated_results->FixItsVector.size() <= completion_index)
317
112k
    return 0;
318
24
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
12
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
12
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
12
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
12
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
719
      ContainerKind(CXCursor_InvalidCode), ContainerIsIncomplete(1) {
368
719
  if (getenv("LIBCLANG_OBJTRACKING"))
369
0
    fprintf(stderr, "+++ %u completion results\n",
370
0
            ++CodeCompletionResultObjects);
371
719
}
372
  
373
716
AllocatedCXCodeCompleteResults::~AllocatedCXCodeCompleteResults() {
374
716
  llvm::DeleteContainerPointers(DiagnosticsWrappers);
375
716
  delete [] Results;
376
716
377
792
  for (unsigned I = 0, N = TemporaryBuffers.size(); I != N; 
++I76
)
378
76
    delete TemporaryBuffers[I];
379
716
380
716
  if (getenv("LIBCLANG_OBJTRACKING"))
381
0
    fprintf(stderr, "--- %u completion results\n",
382
0
            --CodeCompletionResultObjects);
383
716
}
384
385
static unsigned long long getContextsForContextKind(
386
                                          enum CodeCompletionContext::Kind kind, 
387
713
                                                    Sema &S) {
388
713
  unsigned long long contexts = 0;
389
713
  switch (kind) {
390
0
    case CodeCompletionContext::CCC_OtherWithMacros: {
391
0
      //We can allow macros here, but we don't know what else is permissible
392
0
      //So we'll say the only thing permissible are macros
393
0
      contexts = CXCompletionContext_MacroName;
394
0
      break;
395
0
    }
396
53
    case CodeCompletionContext::CCC_TopLevel:
397
53
    case CodeCompletionContext::CCC_ObjCIvarList:
398
53
    case CodeCompletionContext::CCC_ClassStructUnion:
399
53
    case CodeCompletionContext::CCC_Type: {
400
53
      contexts = CXCompletionContext_AnyType | 
401
53
                 CXCompletionContext_ObjCInterface;
402
53
      if (S.getLangOpts().CPlusPlus) {
403
18
        contexts |= CXCompletionContext_EnumTag |
404
18
                    CXCompletionContext_UnionTag |
405
18
                    CXCompletionContext_StructTag |
406
18
                    CXCompletionContext_ClassTag |
407
18
                    CXCompletionContext_NestedNameSpecifier;
408
18
      }
409
53
      break;
410
53
    }
411
75
    case CodeCompletionContext::CCC_Statement: {
412
75
      contexts = CXCompletionContext_AnyType |
413
75
                 CXCompletionContext_ObjCInterface |
414
75
                 CXCompletionContext_AnyValue;
415
75
      if (S.getLangOpts().CPlusPlus) {
416
31
        contexts |= CXCompletionContext_EnumTag |
417
31
                    CXCompletionContext_UnionTag |
418
31
                    CXCompletionContext_StructTag |
419
31
                    CXCompletionContext_ClassTag |
420
31
                    CXCompletionContext_NestedNameSpecifier;
421
31
      }
422
75
      break;
423
53
    }
424
186
    case CodeCompletionContext::CCC_Expression: {
425
186
      contexts = CXCompletionContext_AnyValue;
426
186
      if (S.getLangOpts().CPlusPlus) {
427
106
        contexts |= CXCompletionContext_AnyType |
428
106
                    CXCompletionContext_ObjCInterface |
429
106
                    CXCompletionContext_EnumTag |
430
106
                    CXCompletionContext_UnionTag |
431
106
                    CXCompletionContext_StructTag |
432
106
                    CXCompletionContext_ClassTag |
433
106
                    CXCompletionContext_NestedNameSpecifier;
434
106
      }
435
186
      break;
436
53
    }
437
53
    case CodeCompletionContext::CCC_ObjCMessageReceiver: {
438
7
      contexts = CXCompletionContext_ObjCObjectValue |
439
7
                 CXCompletionContext_ObjCSelectorValue |
440
7
                 CXCompletionContext_ObjCInterface;
441
7
      if (S.getLangOpts().CPlusPlus) {
442
2
        contexts |= CXCompletionContext_CXXClassTypeValue |
443
2
                    CXCompletionContext_AnyType |
444
2
                    CXCompletionContext_EnumTag |
445
2
                    CXCompletionContext_UnionTag |
446
2
                    CXCompletionContext_StructTag |
447
2
                    CXCompletionContext_ClassTag |
448
2
                    CXCompletionContext_NestedNameSpecifier;
449
2
      }
450
7
      break;
451
53
    }
452
53
    case CodeCompletionContext::CCC_DotMemberAccess: {
453
22
      contexts = CXCompletionContext_DotMemberAccess;
454
22
      break;
455
53
    }
456
53
    case CodeCompletionContext::CCC_ArrowMemberAccess: {
457
24
      contexts = CXCompletionContext_ArrowMemberAccess;
458
24
      break;
459
53
    }
460
53
    case CodeCompletionContext::CCC_ObjCPropertyAccess: {
461
24
      contexts = CXCompletionContext_ObjCPropertyAccess;
462
24
      break;
463
53
    }
464
53
    case CodeCompletionContext::CCC_EnumTag: {
465
0
      contexts = CXCompletionContext_EnumTag |
466
0
                 CXCompletionContext_NestedNameSpecifier;
467
0
      break;
468
53
    }
469
53
    case CodeCompletionContext::CCC_UnionTag: {
470
0
      contexts = CXCompletionContext_UnionTag |
471
0
                 CXCompletionContext_NestedNameSpecifier;
472
0
      break;
473
53
    }
474
53
    case CodeCompletionContext::CCC_ClassOrStructTag: {
475
6
      contexts = CXCompletionContext_StructTag |
476
6
                 CXCompletionContext_ClassTag |
477
6
                 CXCompletionContext_NestedNameSpecifier;
478
6
      break;
479
53
    }
480
53
    case CodeCompletionContext::CCC_ObjCProtocolName: {
481
9
      contexts = CXCompletionContext_ObjCProtocol;
482
9
      break;
483
53
    }
484
53
    case CodeCompletionContext::CCC_Namespace: {
485
0
      contexts = CXCompletionContext_Namespace;
486
0
      break;
487
53
    }
488
53
    case CodeCompletionContext::CCC_SymbolOrNewName:
489
49
    case CodeCompletionContext::CCC_Symbol: {
490
49
      contexts = CXCompletionContext_NestedNameSpecifier;
491
49
      break;
492
49
    }
493
49
    case CodeCompletionContext::CCC_MacroNameUse: {
494
8
      contexts = CXCompletionContext_MacroName;
495
8
      break;
496
49
    }
497
49
    case CodeCompletionContext::CCC_NaturalLanguage: {
498
45
      contexts = CXCompletionContext_NaturalLanguage;
499
45
      break;
500
49
    }
501
49
    case CodeCompletionContext::CCC_IncludedFile: {
502
0
      contexts = CXCompletionContext_IncludedFile;
503
0
      break;
504
49
    }
505
49
    case CodeCompletionContext::CCC_SelectorName: {
506
2
      contexts = CXCompletionContext_ObjCSelectorName;
507
2
      break;
508
49
    }
509
49
    case CodeCompletionContext::CCC_ParenthesizedExpression: {
510
13
      contexts = CXCompletionContext_AnyType |
511
13
                 CXCompletionContext_ObjCInterface |
512
13
                 CXCompletionContext_AnyValue;
513
13
      if (S.getLangOpts().CPlusPlus) {
514
0
        contexts |= CXCompletionContext_EnumTag |
515
0
                    CXCompletionContext_UnionTag |
516
0
                    CXCompletionContext_StructTag |
517
0
                    CXCompletionContext_ClassTag |
518
0
                    CXCompletionContext_NestedNameSpecifier;
519
0
      }
520
13
      break;
521
49
    }
522
49
    case CodeCompletionContext::CCC_ObjCInstanceMessage: {
523
49
      contexts = CXCompletionContext_ObjCInstanceMessage;
524
49
      break;
525
49
    }
526
49
    case CodeCompletionContext::CCC_ObjCClassMessage: {
527
22
      contexts = CXCompletionContext_ObjCClassMessage;
528
22
      break;
529
49
    }
530
49
    case CodeCompletionContext::CCC_ObjCInterfaceName: {
531
8
      contexts = CXCompletionContext_ObjCInterface;
532
8
      break;
533
49
    }
534
49
    case CodeCompletionContext::CCC_ObjCCategoryName: {
535
5
      contexts = CXCompletionContext_ObjCCategory;
536
5
      break;
537
49
    }
538
105
    case CodeCompletionContext::CCC_Other:
539
105
    case CodeCompletionContext::CCC_ObjCInterface:
540
105
    case CodeCompletionContext::CCC_ObjCImplementation:
541
105
    case CodeCompletionContext::CCC_NewName:
542
105
    case CodeCompletionContext::CCC_MacroName:
543
105
    case CodeCompletionContext::CCC_PreprocessorExpression:
544
105
    case CodeCompletionContext::CCC_PreprocessorDirective:
545
105
    case CodeCompletionContext::CCC_TypeQualifiers: {
546
105
      //Only Clang results should be accepted, so we'll set all of the other
547
105
      //context bits to 0 (i.e. the empty set)
548
105
      contexts = CXCompletionContext_Unexposed;
549
105
      break;
550
105
    }
551
105
    case CodeCompletionContext::CCC_Recovery: {
552
1
      //We don't know what the current context is, so we'll return unknown
553
1
      //This is the equivalent of setting all of the other context bits
554
1
      contexts = CXCompletionContext_Unknown;
555
1
      break;
556
713
    }
557
713
  }
558
713
  return contexts;
559
713
}
560
561
namespace {
562
  class CaptureCompletionResults : public CodeCompleteConsumer {
563
    AllocatedCXCodeCompleteResults &AllocatedResults;
564
    CodeCompletionTUInfo CCTUInfo;
565
    SmallVector<CXCompletionResult, 16> StoredResults;
566
    CXTranslationUnit *TU;
567
  public:
568
    CaptureCompletionResults(const CodeCompleteOptions &Opts,
569
                             AllocatedCXCodeCompleteResults &Results,
570
                             CXTranslationUnit *TranslationUnit)
571
        : CodeCompleteConsumer(Opts), AllocatedResults(Results),
572
719
          CCTUInfo(Results.CodeCompletionAllocator), TU(TranslationUnit) {}
573
716
    ~CaptureCompletionResults() override { Finish(); }
574
575
    void ProcessCodeCompleteResults(Sema &S, 
576
                                    CodeCompletionContext Context,
577
                                    CodeCompletionResult *Results,
578
713
                                    unsigned NumResults) override {
579
713
      StoredResults.reserve(StoredResults.size() + NumResults);
580
713
      if (includeFixIts())
581
2
        AllocatedResults.FixItsVector.reserve(NumResults);
582
156k
      for (unsigned I = 0; I != NumResults; 
++I156k
) {
583
156k
        CodeCompletionString *StoredCompletion
584
156k
          = Results[I].CreateCodeCompletionString(S, Context, getAllocator(),
585
156k
                                                  getCodeCompletionTUInfo(),
586
156k
                                                  includeBriefComments());
587
156k
        
588
156k
        CXCompletionResult R;
589
156k
        R.CursorKind = Results[I].CursorKind;
590
156k
        R.CompletionString = StoredCompletion;
591
156k
        StoredResults.push_back(R);
592
156k
        if (includeFixIts())
593
12
          AllocatedResults.FixItsVector.emplace_back(std::move(Results[I].FixIts));
594
156k
      }
595
713
596
713
      enum CodeCompletionContext::Kind contextKind = Context.getKind();
597
713
      
598
713
      AllocatedResults.ContextKind = contextKind;
599
713
      AllocatedResults.Contexts = getContextsForContextKind(contextKind, S);
600
713
      
601
713
      AllocatedResults.Selector = "";
602
713
      ArrayRef<IdentifierInfo *> SelIdents = Context.getSelIdents();
603
713
      for (ArrayRef<IdentifierInfo *>::iterator I = SelIdents.begin(),
604
713
                                                E = SelIdents.end();
605
735
           I != E; 
++I22
) {
606
22
        if (IdentifierInfo *selIdent = *I)
607
22
          AllocatedResults.Selector += selIdent->getName();
608
22
        AllocatedResults.Selector += ":";
609
22
      }
610
713
      
611
713
      QualType baseType = Context.getBaseType();
612
713
      NamedDecl *D = nullptr;
613
713
614
713
      if (!baseType.isNull()) {
615
138
        // Get the declaration for a class/struct/union/enum type
616
138
        if (const TagType *Tag = baseType->getAs<TagType>())
617
37
          D = Tag->getDecl();
618
101
        // Get the @interface declaration for a (possibly-qualified) Objective-C
619
101
        // object pointer type, e.g., NSString*
620
101
        else if (const ObjCObjectPointerType *ObjPtr = 
621
79
                 baseType->getAs<ObjCObjectPointerType>())
622
79
          D = ObjPtr->getInterfaceDecl();
623
22
        // Get the @interface declaration for an Objective-C object type
624
22
        else if (const ObjCObjectType *Obj = baseType->getAs<ObjCObjectType>())
625
20
          D = Obj->getInterface();
626
2
        // Get the class for a C++ injected-class-name
627
2
        else if (const InjectedClassNameType *Injected =
628
0
                 baseType->getAs<InjectedClassNameType>())
629
0
          D = Injected->getDecl();
630
138
      }
631
713
632
713
      if (D != nullptr) {
633
128
        CXCursor cursor = cxcursor::MakeCXCursor(D, *TU);
634
128
635
128
        AllocatedResults.ContainerKind = clang_getCursorKind(cursor);
636
128
637
128
        CXString CursorUSR = clang_getCursorUSR(cursor);
638
128
        AllocatedResults.ContainerUSR = clang_getCString(CursorUSR);
639
128
        clang_disposeString(CursorUSR);
640
128
641
128
        const Type *type = baseType.getTypePtrOrNull();
642
128
        if (type) {
643
128
          AllocatedResults.ContainerIsIncomplete = type->isIncompleteType();
644
128
        }
645
0
        else {
646
0
          AllocatedResults.ContainerIsIncomplete = 1;
647
0
        }
648
128
      }
649
585
      else {
650
585
        AllocatedResults.ContainerKind = CXCursor_InvalidCode;
651
585
        AllocatedResults.ContainerUSR.clear();
652
585
        AllocatedResults.ContainerIsIncomplete = 1;
653
585
      }
654
713
    }
655
656
    void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
657
                                   OverloadCandidate *Candidates,
658
                                   unsigned NumCandidates,
659
100
                                   SourceLocation OpenParLoc) override {
660
100
      StoredResults.reserve(StoredResults.size() + NumCandidates);
661
262
      for (unsigned I = 0; I != NumCandidates; 
++I162
) {
662
162
        CodeCompletionString *StoredCompletion
663
162
          = Candidates[I].CreateSignatureString(CurrentArg, S, getAllocator(),
664
162
                                                getCodeCompletionTUInfo(),
665
162
                                                includeBriefComments());
666
162
        
667
162
        CXCompletionResult R;
668
162
        R.CursorKind = CXCursor_OverloadCandidate;
669
162
        R.CompletionString = StoredCompletion;
670
162
        StoredResults.push_back(R);
671
162
      }
672
100
    }
673
674
158k
    CodeCompletionAllocator &getAllocator() override {
675
158k
      return *AllocatedResults.CodeCompletionAllocator;
676
158k
    }
677
678
158k
    CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo;}
679
680
  private:
681
716
    void Finish() {
682
716
      AllocatedResults.Results = new CXCompletionResult [StoredResults.size()];
683
716
      AllocatedResults.NumResults = StoredResults.size();
684
716
      std::memcpy(AllocatedResults.Results, StoredResults.data(), 
685
716
                  StoredResults.size() * sizeof(CXCompletionResult));
686
716
      StoredResults.clear();
687
716
    }
688
  };
689
}
690
691
static CXCodeCompleteResults *
692
clang_codeCompleteAt_Impl(CXTranslationUnit TU, const char *complete_filename,
693
                          unsigned complete_line, unsigned complete_column,
694
                          ArrayRef<CXUnsavedFile> unsaved_files,
695
719
                          unsigned options) {
696
719
  bool IncludeBriefComments = options & CXCodeComplete_IncludeBriefComments;
697
719
  bool SkipPreamble = options & CXCodeComplete_SkipPreamble;
698
719
  bool IncludeFixIts = options & CXCodeComplete_IncludeCompletionsWithFixIts;
699
719
700
#ifdef UDP_CODE_COMPLETION_LOGGER
701
#ifdef UDP_CODE_COMPLETION_LOGGER_PORT
702
  const llvm::TimeRecord &StartTime =  llvm::TimeRecord::getCurrentTime();
703
#endif
704
#endif
705
  bool EnableLogging = getenv("LIBCLANG_CODE_COMPLETION_LOGGING") != nullptr;
706
719
707
719
  if (cxtu::isNotUsableTU(TU)) {
708
0
    LOG_BAD_TU(TU);
709
0
    return nullptr;
710
0
  }
711
719
712
719
  ASTUnit *AST = cxtu::getASTUnit(TU);
713
719
  if (!AST)
714
0
    return nullptr;
715
719
716
719
  CIndexer *CXXIdx = TU->CIdx;
717
719
  if (CXXIdx->isOptEnabled(CXGlobalOpt_ThreadBackgroundPriorityForEditing))
718
0
    setThreadBackgroundPriority();
719
719
720
719
  ASTUnit::ConcurrencyCheck Check(*AST);
721
719
722
719
  // Perform the remapping of source files.
723
719
  SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
724
719
725
719
  for (auto &UF : unsaved_files) {
726
4
    std::unique_ptr<llvm::MemoryBuffer> MB =
727
4
        llvm::MemoryBuffer::getMemBufferCopy(getContents(UF), UF.Filename);
728
4
    RemappedFiles.push_back(std::make_pair(UF.Filename, MB.release()));
729
4
  }
730
719
731
719
  if (EnableLogging) {
732
0
    // FIXME: Add logging.
733
0
  }
734
719
735
719
  // Parse the resulting source file to find code-completion results.
736
719
  AllocatedCXCodeCompleteResults *Results = new AllocatedCXCodeCompleteResults(
737
719
      &AST->getFileManager());
738
719
  Results->Results = nullptr;
739
719
  Results->NumResults = 0;
740
719
  
741
719
  // Create a code-completion consumer to capture the results.
742
719
  CodeCompleteOptions Opts;
743
719
  Opts.IncludeBriefComments = IncludeBriefComments;
744
719
  Opts.LoadExternal = !SkipPreamble;
745
719
  Opts.IncludeFixIts = IncludeFixIts;
746
719
  CaptureCompletionResults Capture(Opts, *Results, &TU);
747
719
748
719
  // Perform completion.
749
719
  std::vector<const char *> CArgs;
750
719
  for (const auto &Arg : TU->Arguments)
751
4.68k
    CArgs.push_back(Arg.c_str());
752
719
  std::string CompletionInvocation =
753
719
      llvm::formatv("-code-completion-at={0}:{1}:{2}", complete_filename,
754
719
                    complete_line, complete_column)
755
719
          .str();
756
719
  LibclangInvocationReporter InvocationReporter(
757
719
      *CXXIdx, LibclangInvocationReporter::OperationKind::CompletionOperation,
758
719
      TU->ParsingOptions, CArgs, CompletionInvocation, unsaved_files);
759
719
  AST->CodeComplete(complete_filename, complete_line, complete_column,
760
719
                    RemappedFiles, (options & CXCodeComplete_IncludeMacros),
761
719
                    (options & CXCodeComplete_IncludeCodePatterns),
762
719
                    IncludeBriefComments, Capture,
763
719
                    CXXIdx->getPCHContainerOperations(), *Results->Diag,
764
719
                    Results->LangOpts, *Results->SourceMgr, *Results->FileMgr,
765
719
                    Results->Diagnostics, Results->TemporaryBuffers);
766
719
767
719
  Results->DiagnosticsWrappers.resize(Results->Diagnostics.size());
768
719
769
719
  // Keep a reference to the allocator used for cached global completions, so
770
719
  // that we can be sure that the memory used by our code completion strings
771
719
  // doesn't get freed due to subsequent reparses (while the code completion
772
719
  // results are still active).
773
719
  Results->CachedCompletionAllocator = AST->getCachedCompletionAllocator();
774
719
775
719
  
776
719
777
#ifdef UDP_CODE_COMPLETION_LOGGER
778
#ifdef UDP_CODE_COMPLETION_LOGGER_PORT
779
  const llvm::TimeRecord &EndTime =  llvm::TimeRecord::getCurrentTime();
780
  SmallString<256> LogResult;
781
  llvm::raw_svector_ostream os(LogResult);
782
783
  // Figure out the language and whether or not it uses PCH.
784
  const char *lang = 0;
785
  bool usesPCH = false;
786
787
  for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
788
       I != E; ++I) {
789
    if (*I == 0)
790
      continue;
791
    if (strcmp(*I, "-x") == 0) {
792
      if (I + 1 != E) {
793
        lang = *(++I);
794
        continue;
795
      }
796
    }
797
    else if (strcmp(*I, "-include") == 0) {
798
      if (I+1 != E) {
799
        const char *arg = *(++I);
800
        SmallString<512> pchName;
801
        {
802
          llvm::raw_svector_ostream os(pchName);
803
          os << arg << ".pth";
804
        }
805
        pchName.push_back('\0');
806
        llvm::sys::fs::file_status stat_results;
807
        if (!llvm::sys::fs::status(pchName, stat_results))
808
          usesPCH = true;
809
        continue;
810
      }
811
    }
812
  }
813
814
  os << "{ ";
815
  os << "\"wall\": " << (EndTime.getWallTime() - StartTime.getWallTime());
816
  os << ", \"numRes\": " << Results->NumResults;
817
  os << ", \"diags\": " << Results->Diagnostics.size();
818
  os << ", \"pch\": " << (usesPCH ? "true" : "false");
819
  os << ", \"lang\": \"" << (lang ? lang : "<unknown>") << '"';
820
  const char *name = getlogin();
821
  os << ", \"user\": \"" << (name ? name : "unknown") << '"';
822
  os << ", \"clangVer\": \"" << getClangFullVersion() << '"';
823
  os << " }";
824
825
  StringRef res = os.str();
826
  if (res.size() > 0) {
827
    do {
828
      // Setup the UDP socket.
829
      struct sockaddr_in servaddr;
830
      bzero(&servaddr, sizeof(servaddr));
831
      servaddr.sin_family = AF_INET;
832
      servaddr.sin_port = htons(UDP_CODE_COMPLETION_LOGGER_PORT);
833
      if (inet_pton(AF_INET, UDP_CODE_COMPLETION_LOGGER,
834
                    &servaddr.sin_addr) <= 0)
835
        break;
836
837
      int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
838
      if (sockfd < 0)
839
        break;
840
841
      sendto(sockfd, res.data(), res.size(), 0,
842
             (struct sockaddr *)&servaddr, sizeof(servaddr));
843
      close(sockfd);
844
    }
845
    while (false);
846
  }
847
#endif
848
#endif
849
  return Results;
850
719
}
851
852
CXCodeCompleteResults *clang_codeCompleteAt(CXTranslationUnit TU,
853
                                            const char *complete_filename,
854
                                            unsigned complete_line,
855
                                            unsigned complete_column,
856
                                            struct CXUnsavedFile *unsaved_files,
857
                                            unsigned num_unsaved_files,
858
719
                                            unsigned options) {
859
719
  LOG_FUNC_SECTION {
860
0
    *Log << TU << ' '
861
0
         << complete_filename << ':' << complete_line << ':' << complete_column;
862
0
  }
863
719
864
719
  if (num_unsaved_files && 
!unsaved_files4
)
865
0
    return nullptr;
866
719
867
719
  CXCodeCompleteResults *result;
868
719
  auto CodeCompleteAtImpl = [=, &result]() {
869
719
    result = clang_codeCompleteAt_Impl(
870
719
        TU, complete_filename, complete_line, complete_column,
871
719
        llvm::makeArrayRef(unsaved_files, num_unsaved_files), options);
872
719
  };
873
719
874
719
  llvm::CrashRecoveryContext CRC;
875
719
876
719
  if (!RunSafely(CRC, CodeCompleteAtImpl)) {
877
3
    fprintf(stderr, "libclang: crash detected in code completion\n");
878
3
    cxtu::getASTUnit(TU)->setUnsafeToFree(true);
879
3
    return nullptr;
880
716
  } else if (getenv("LIBCLANG_RESOURCE_USAGE"))
881
0
    PrintLibclangResourceUsage(TU);
882
719
883
719
  
return result716
;
884
719
}
885
886
535
unsigned clang_defaultCodeCompleteOptions(void) {
887
535
  return CXCodeComplete_IncludeMacros;
888
535
}
889
890
716
void clang_disposeCodeCompleteResults(CXCodeCompleteResults *ResultsIn) {
891
716
  if (!ResultsIn)
892
0
    return;
893
716
894
716
  AllocatedCXCodeCompleteResults *Results
895
716
    = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
896
716
  delete Results;
897
716
}
898
  
899
unsigned 
900
532
clang_codeCompleteGetNumDiagnostics(CXCodeCompleteResults *ResultsIn) {
901
532
  AllocatedCXCodeCompleteResults *Results
902
532
    = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
903
532
  if (!Results)
904
0
    return 0;
905
532
906
532
  return Results->Diagnostics.size();
907
532
}
908
909
CXDiagnostic 
910
clang_codeCompleteGetDiagnostic(CXCodeCompleteResults *ResultsIn,
911
188
                                unsigned Index) {
912
188
  AllocatedCXCodeCompleteResults *Results
913
188
    = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
914
188
  if (!Results || Index >= Results->Diagnostics.size())
915
0
    return nullptr;
916
188
917
188
  CXStoredDiagnostic *Diag = Results->DiagnosticsWrappers[Index];
918
188
  if (!Diag)
919
188
    Results->DiagnosticsWrappers[Index] = Diag =
920
188
        new CXStoredDiagnostic(Results->Diagnostics[Index], Results->LangOpts);
921
188
  return Diag;
922
188
}
923
924
unsigned long long
925
532
clang_codeCompleteGetContexts(CXCodeCompleteResults *ResultsIn) {
926
532
  AllocatedCXCodeCompleteResults *Results
927
532
    = static_cast<AllocatedCXCodeCompleteResults*>(ResultsIn);
928
532
  if (!Results)
929
0
    return 0;
930
532
  
931
532
  return Results->Contexts;
932
532
}
933
934
enum CXCursorKind clang_codeCompleteGetContainerKind(
935
                                               CXCodeCompleteResults *ResultsIn,
936
532
                                                     unsigned *IsIncomplete) {
937
532
  AllocatedCXCodeCompleteResults *Results =
938
532
    static_cast<AllocatedCXCodeCompleteResults *>(ResultsIn);
939
532
  if (!Results)
940
0
    return CXCursor_InvalidCode;
941
532
942
532
  if (IsIncomplete != nullptr) {
943
532
    *IsIncomplete = Results->ContainerIsIncomplete;
944
532
  }
945
532
  
946
532
  return Results->ContainerKind;
947
532
}
948
  
949
124
CXString clang_codeCompleteGetContainerUSR(CXCodeCompleteResults *ResultsIn) {
950
124
  AllocatedCXCodeCompleteResults *Results =
951
124
    static_cast<AllocatedCXCodeCompleteResults *>(ResultsIn);
952
124
  if (!Results)
953
0
    return cxstring::createEmpty();
954
124
955
124
  return cxstring::createRef(Results->ContainerUSR.c_str());
956
124
}
957
958
  
959
532
CXString clang_codeCompleteGetObjCSelector(CXCodeCompleteResults *ResultsIn) {
960
532
  AllocatedCXCodeCompleteResults *Results =
961
532
    static_cast<AllocatedCXCodeCompleteResults *>(ResultsIn);
962
532
  if (!Results)
963
0
    return cxstring::createEmpty();
964
532
  
965
532
  return cxstring::createDup(Results->Selector);
966
532
}
967
  
968
/// Simple utility function that appends a \p New string to the given
969
/// \p Old string, using the \p Buffer for storage.
970
///
971
/// \param Old The string to which we are appending. This parameter will be
972
/// updated to reflect the complete string.
973
///
974
///
975
/// \param New The string to append to \p Old.
976
///
977
/// \param Buffer A buffer that stores the actual, concatenated string. It will
978
/// be used if the old string is already-non-empty.
979
static void AppendToString(StringRef &Old, StringRef New,
980
7.40M
                           SmallString<256> &Buffer) {
981
7.40M
  if (Old.empty()) {
982
7.40M
    Old = New;
983
7.40M
    return;
984
7.40M
  }
985
2.94k
  
986
2.94k
  if (Buffer.empty())
987
2.75k
    Buffer.append(Old.begin(), Old.end());
988
2.94k
  Buffer.append(New.begin(), New.end());
989
2.94k
  Old = Buffer.str();
990
2.94k
}
991
992
/// Get the typed-text blocks from the given code-completion string
993
/// and return them as a single string.
994
///
995
/// \param String The code-completion string whose typed-text blocks will be
996
/// concatenated.
997
///
998
/// \param Buffer A buffer used for storage of the completed name.
999
static StringRef GetTypedName(CodeCompletionString *String,
1000
7.41M
                                    SmallString<256> &Buffer) {
1001
7.41M
  StringRef Result;
1002
7.41M
  for (CodeCompletionString::iterator C = String->begin(), CEnd = String->end();
1003
17.0M
       C != CEnd; 
++C9.58M
) {
1004
9.58M
    if (C->Kind == CodeCompletionString::CK_TypedText)
1005
7.40M
      AppendToString(Result, C->Text, Buffer);
1006
9.58M
  }
1007
7.41M
  
1008
7.41M
  return Result;
1009
7.41M
}
1010
1011
namespace {
1012
  struct OrderCompletionResults {
1013
    bool operator()(const CXCompletionResult &XR, 
1014
3.70M
                    const CXCompletionResult &YR) const {
1015
3.70M
      CodeCompletionString *X
1016
3.70M
        = (CodeCompletionString *)XR.CompletionString;
1017
3.70M
      CodeCompletionString *Y
1018
3.70M
        = (CodeCompletionString *)YR.CompletionString;
1019
3.70M
1020
3.70M
      SmallString<256> XBuffer;
1021
3.70M
      StringRef XText = GetTypedName(X, XBuffer);
1022
3.70M
      SmallString<256> YBuffer;
1023
3.70M
      StringRef YText = GetTypedName(Y, YBuffer);
1024
3.70M
      
1025
3.70M
      if (XText.empty() || 
YText.empty()3.70M
)
1026
17.4k
        return !XText.empty();
1027
3.69M
            
1028
3.69M
      int result = XText.compare_lower(YText);
1029
3.69M
      if (result < 0)
1030
3.49M
        return true;
1031
198k
      if (result > 0)
1032
192k
        return false;
1033
5.68k
      
1034
5.68k
      result = XText.compare(YText);
1035
5.68k
      return result < 0;
1036
5.68k
    }
1037
  };
1038
}
1039
1040
void clang_sortCodeCompletionResults(CXCompletionResult *Results,
1041
532
                                     unsigned NumResults) {
1042
532
  std::stable_sort(Results, Results + NumResults, OrderCompletionResults());
1043
532
}