Coverage Report

Created: 2018-09-21 05:35

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/include/clang/Sema/CodeCompleteConsumer.h
Line
Count
Source (jump to first uncovered line)
1
//===- CodeCompleteConsumer.h - Code Completion Interface -------*- C++ -*-===//
2
//
3
//                     The LLVM Compiler Infrastructure
4
//
5
// This file is distributed under the University of Illinois Open Source
6
// License. See LICENSE.TXT for details.
7
//
8
//===----------------------------------------------------------------------===//
9
//
10
//  This file defines the CodeCompleteConsumer class.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#ifndef LLVM_CLANG_SEMA_CODECOMPLETECONSUMER_H
15
#define LLVM_CLANG_SEMA_CODECOMPLETECONSUMER_H
16
17
#include "clang-c/Index.h"
18
#include "clang/AST/Type.h"
19
#include "clang/Basic/LLVM.h"
20
#include "clang/Lex/MacroInfo.h"
21
#include "clang/Sema/CodeCompleteOptions.h"
22
#include "clang/Sema/DeclSpec.h"
23
#include "llvm/ADT/ArrayRef.h"
24
#include "llvm/ADT/DenseMap.h"
25
#include "llvm/ADT/None.h"
26
#include "llvm/ADT/Optional.h"
27
#include "llvm/ADT/SmallPtrSet.h"
28
#include "llvm/ADT/SmallVector.h"
29
#include "llvm/ADT/StringRef.h"
30
#include "llvm/Support/Allocator.h"
31
#include "llvm/Support/type_traits.h"
32
#include <cassert>
33
#include <memory>
34
#include <string>
35
#include <utility>
36
37
namespace clang {
38
39
class ASTContext;
40
class Decl;
41
class DeclContext;
42
class FunctionDecl;
43
class FunctionTemplateDecl;
44
class IdentifierInfo;
45
class LangOptions;
46
class NamedDecl;
47
class NestedNameSpecifier;
48
class Preprocessor;
49
class RawComment;
50
class Sema;
51
class UsingShadowDecl;
52
53
/// Default priority values for code-completion results based
54
/// on their kind.
55
enum {
56
  /// Priority for the next initialization in a constructor initializer
57
  /// list.
58
  CCP_NextInitializer = 7,
59
60
  /// Priority for an enumeration constant inside a switch whose
61
  /// condition is of the enumeration type.
62
  CCP_EnumInCase = 7,
63
64
  /// Priority for a send-to-super completion.
65
  CCP_SuperCompletion = 20,
66
67
  /// Priority for a declaration that is in the local scope.
68
  CCP_LocalDeclaration = 34,
69
70
  /// Priority for a member declaration found from the current
71
  /// method or member function.
72
  CCP_MemberDeclaration = 35,
73
74
  /// Priority for a language keyword (that isn't any of the other
75
  /// categories).
76
  CCP_Keyword = 40,
77
78
  /// Priority for a code pattern.
79
  CCP_CodePattern = 40,
80
81
  /// Priority for a non-type declaration.
82
  CCP_Declaration = 50,
83
84
  /// Priority for a type.
85
  CCP_Type = CCP_Declaration,
86
87
  /// Priority for a constant value (e.g., enumerator).
88
  CCP_Constant = 65,
89
90
  /// Priority for a preprocessor macro.
91
  CCP_Macro = 70,
92
93
  /// Priority for a nested-name-specifier.
94
  CCP_NestedNameSpecifier = 75,
95
96
  /// Priority for a result that isn't likely to be what the user wants,
97
  /// but is included for completeness.
98
  CCP_Unlikely = 80,
99
100
  /// Priority for the Objective-C "_cmd" implicit parameter.
101
  CCP_ObjC_cmd = CCP_Unlikely
102
};
103
104
/// Priority value deltas that are added to code-completion results
105
/// based on the context of the result.
106
enum {
107
  /// The result is in a base class.
108
  CCD_InBaseClass = 2,
109
110
  /// The result is a C++ non-static member function whose qualifiers
111
  /// exactly match the object type on which the member function can be called.
112
  CCD_ObjectQualifierMatch = -1,
113
114
  /// The selector of the given message exactly matches the selector
115
  /// of the current method, which might imply that some kind of delegation
116
  /// is occurring.
117
  CCD_SelectorMatch = -3,
118
119
  /// Adjustment to the "bool" type in Objective-C, where the typedef
120
  /// "BOOL" is preferred.
121
  CCD_bool_in_ObjC = 1,
122
123
  /// Adjustment for KVC code pattern priorities when it doesn't look
124
  /// like the
125
  CCD_ProbablyNotObjCCollection = 15,
126
127
  /// An Objective-C method being used as a property.
128
  CCD_MethodAsProperty = 2,
129
130
  /// An Objective-C block property completed as a setter with a
131
  /// block placeholder.
132
  CCD_BlockPropertySetter = 3
133
};
134
135
/// Priority value factors by which we will divide or multiply the
136
/// priority of a code-completion result.
137
enum {
138
  /// Divide by this factor when a code-completion result's type exactly
139
  /// matches the type we expect.
140
  CCF_ExactTypeMatch = 4,
141
142
  /// Divide by this factor when a code-completion result's type is
143
  /// similar to the type we expect (e.g., both arithmetic types, both
144
  /// Objective-C object pointer types).
145
  CCF_SimilarTypeMatch = 2
146
};
147
148
/// A simplified classification of types used when determining
149
/// "similar" types for code completion.
150
enum SimplifiedTypeClass {
151
  STC_Arithmetic,
152
  STC_Array,
153
  STC_Block,
154
  STC_Function,
155
  STC_ObjectiveC,
156
  STC_Other,
157
  STC_Pointer,
158
  STC_Record,
159
  STC_Void
160
};
161
162
/// Determine the simplified type class of the given canonical type.
163
SimplifiedTypeClass getSimplifiedTypeClass(CanQualType T);
164
165
/// Determine the type that this declaration will have if it is used
166
/// as a type or in an expression.
167
QualType getDeclUsageType(ASTContext &C, const NamedDecl *ND);
168
169
/// Determine the priority to be given to a macro code completion result
170
/// with the given name.
171
///
172
/// \param MacroName The name of the macro.
173
///
174
/// \param LangOpts Options describing the current language dialect.
175
///
176
/// \param PreferredTypeIsPointer Whether the preferred type for the context
177
/// of this macro is a pointer type.
178
unsigned getMacroUsagePriority(StringRef MacroName,
179
                               const LangOptions &LangOpts,
180
                               bool PreferredTypeIsPointer = false);
181
182
/// Determine the libclang cursor kind associated with the given
183
/// declaration.
184
CXCursorKind getCursorKindForDecl(const Decl *D);
185
186
/// The context in which code completion occurred, so that the
187
/// code-completion consumer can process the results accordingly.
188
class CodeCompletionContext {
189
public:
190
  enum Kind {
191
    /// An unspecified code-completion context.
192
    CCC_Other,
193
194
    /// An unspecified code-completion context where we should also add
195
    /// macro completions.
196
    CCC_OtherWithMacros,
197
198
    /// Code completion occurred within a "top-level" completion context,
199
    /// e.g., at namespace or global scope.
200
    CCC_TopLevel,
201
202
    /// Code completion occurred within an Objective-C interface,
203
    /// protocol, or category interface.
204
    CCC_ObjCInterface,
205
206
    /// Code completion occurred within an Objective-C implementation
207
    /// or category implementation.
208
    CCC_ObjCImplementation,
209
210
    /// Code completion occurred within the instance variable list of
211
    /// an Objective-C interface, implementation, or category implementation.
212
    CCC_ObjCIvarList,
213
214
    /// Code completion occurred within a class, struct, or union.
215
    CCC_ClassStructUnion,
216
217
    /// Code completion occurred where a statement (or declaration) is
218
    /// expected in a function, method, or block.
219
    CCC_Statement,
220
221
    /// Code completion occurred where an expression is expected.
222
    CCC_Expression,
223
224
    /// Code completion occurred where an Objective-C message receiver
225
    /// is expected.
226
    CCC_ObjCMessageReceiver,
227
228
    /// Code completion occurred on the right-hand side of a member
229
    /// access expression using the dot operator.
230
    ///
231
    /// The results of this completion are the members of the type being
232
    /// accessed. The type itself is available via
233
    /// \c CodeCompletionContext::getType().
234
    CCC_DotMemberAccess,
235
236
    /// Code completion occurred on the right-hand side of a member
237
    /// access expression using the arrow operator.
238
    ///
239
    /// The results of this completion are the members of the type being
240
    /// accessed. The type itself is available via
241
    /// \c CodeCompletionContext::getType().
242
    CCC_ArrowMemberAccess,
243
244
    /// Code completion occurred on the right-hand side of an Objective-C
245
    /// property access expression.
246
    ///
247
    /// The results of this completion are the members of the type being
248
    /// accessed. The type itself is available via
249
    /// \c CodeCompletionContext::getType().
250
    CCC_ObjCPropertyAccess,
251
252
    /// Code completion occurred after the "enum" keyword, to indicate
253
    /// an enumeration name.
254
    CCC_EnumTag,
255
256
    /// Code completion occurred after the "union" keyword, to indicate
257
    /// a union name.
258
    CCC_UnionTag,
259
260
    /// Code completion occurred after the "struct" or "class" keyword,
261
    /// to indicate a struct or class name.
262
    CCC_ClassOrStructTag,
263
264
    /// Code completion occurred where a protocol name is expected.
265
    CCC_ObjCProtocolName,
266
267
    /// Code completion occurred where a namespace or namespace alias
268
    /// is expected.
269
    CCC_Namespace,
270
271
    /// Code completion occurred where a type name is expected.
272
    CCC_Type,
273
274
    /// Code completion occurred where a new name is expected.
275
    CCC_Name,
276
277
    /// Code completion occurred where a new name is expected and a
278
    /// qualified name is permissible.
279
    CCC_PotentiallyQualifiedName,
280
281
    /// Code completion occurred where an macro is being defined.
282
    CCC_MacroName,
283
284
    /// Code completion occurred where a macro name is expected
285
    /// (without any arguments, in the case of a function-like macro).
286
    CCC_MacroNameUse,
287
288
    /// Code completion occurred within a preprocessor expression.
289
    CCC_PreprocessorExpression,
290
291
    /// Code completion occurred where a preprocessor directive is
292
    /// expected.
293
    CCC_PreprocessorDirective,
294
295
    /// Code completion occurred in a context where natural language is
296
    /// expected, e.g., a comment or string literal.
297
    ///
298
    /// This context usually implies that no completions should be added,
299
    /// unless they come from an appropriate natural-language dictionary.
300
    CCC_NaturalLanguage,
301
302
    /// Code completion for a selector, as in an \@selector expression.
303
    CCC_SelectorName,
304
305
    /// Code completion within a type-qualifier list.
306
    CCC_TypeQualifiers,
307
308
    /// Code completion in a parenthesized expression, which means that
309
    /// we may also have types here in C and Objective-C (as well as in C++).
310
    CCC_ParenthesizedExpression,
311
312
    /// Code completion where an Objective-C instance message is
313
    /// expected.
314
    CCC_ObjCInstanceMessage,
315
316
    /// Code completion where an Objective-C class message is expected.
317
    CCC_ObjCClassMessage,
318
319
    /// Code completion where the name of an Objective-C class is
320
    /// expected.
321
    CCC_ObjCInterfaceName,
322
323
    /// Code completion where an Objective-C category name is expected.
324
    CCC_ObjCCategoryName,
325
326
    /// Code completion inside the filename part of a #include directive.
327
    CCC_IncludedFile,
328
329
    /// An unknown context, in which we are recovering from a parsing
330
    /// error and don't know which completions we should give.
331
    CCC_Recovery
332
  };
333
334
  using VisitedContextSet = llvm::SmallPtrSet<DeclContext *, 8>;
335
336
private:
337
  Kind CCKind;
338
339
  /// The type that would prefer to see at this point (e.g., the type
340
  /// of an initializer or function parameter).
341
  QualType PreferredType;
342
343
  /// The type of the base object in a member access expression.
344
  QualType BaseType;
345
346
  /// The identifiers for Objective-C selector parts.
347
  ArrayRef<IdentifierInfo *> SelIdents;
348
349
  /// The scope specifier that comes before the completion token e.g.
350
  /// "a::b::"
351
  llvm::Optional<CXXScopeSpec> ScopeSpecifier;
352
353
  /// A set of declaration contexts visited by Sema when doing lookup for
354
  /// code completion.
355
  VisitedContextSet VisitedContexts;
356
357
public:
358
  /// Construct a new code-completion context of the given kind.
359
775
  CodeCompletionContext(Kind CCKind) : CCKind(CCKind), SelIdents(None) {}
360
361
  /// Construct a new code-completion context of the given kind.
362
  CodeCompletionContext(Kind CCKind, QualType T,
363
                        ArrayRef<IdentifierInfo *> SelIdents = None)
364
370
      : CCKind(CCKind), SelIdents(SelIdents) {
365
370
    if (CCKind == CCC_DotMemberAccess || 
CCKind == CCC_ArrowMemberAccess338
||
366
370
        
CCKind == CCC_ObjCPropertyAccess305
||
CCKind == CCC_ObjCClassMessage283
||
367
370
        
CCKind == CCC_ObjCInstanceMessage254
)
368
171
      BaseType = T;
369
199
    else
370
199
      PreferredType = T;
371
370
  }
372
373
  /// Retrieve the kind of code-completion context.
374
63.4k
  Kind getKind() const { return CCKind; }
375
376
  /// Retrieve the type that this expression would prefer to have, e.g.,
377
  /// if the expression is a variable initializer or a function argument, the
378
  /// type of the corresponding variable or function parameter.
379
60.2k
  QualType getPreferredType() const { return PreferredType; }
380
381
  /// Retrieve the type of the base object in a member-access
382
  /// expression.
383
5.87k
  QualType getBaseType() const { return BaseType; }
384
385
  /// Retrieve the Objective-C selector identifiers.
386
  ArrayRef<IdentifierInfo *> getSelIdents() const { return SelIdents; }
387
388
  /// Determines whether we want C++ constructors as results within this
389
  /// context.
390
  bool wantConstructorResults() const;
391
392
  /// Sets the scope specifier that comes before the completion token.
393
  /// This is expected to be set in code completions on qualfied specifiers
394
  /// (e.g. "a::b::").
395
35
  void setCXXScopeSpecifier(CXXScopeSpec SS) {
396
35
    this->ScopeSpecifier = std::move(SS);
397
35
  }
398
399
  /// Adds a visited context.
400
639
  void addVisitedContext(DeclContext *Ctx) {
401
639
    VisitedContexts.insert(Ctx);
402
639
  }
403
404
  /// Retrieves all visited contexts.
405
  const VisitedContextSet &getVisitedContexts() const {
406
    return VisitedContexts;
407
  }
408
409
0
  llvm::Optional<const CXXScopeSpec *> getCXXScopeSpecifier() {
410
0
    if (ScopeSpecifier)
411
0
      return ScopeSpecifier.getPointer();
412
0
    return llvm::None;
413
0
  }
414
};
415
416
/// Get string representation of \p Kind, useful for for debugging.
417
llvm::StringRef getCompletionKindString(CodeCompletionContext::Kind Kind);
418
419
/// A "string" used to describe how code completion can
420
/// be performed for an entity.
421
///
422
/// A code completion string typically shows how a particular entity can be
423
/// used. For example, the code completion string for a function would show
424
/// the syntax to call it, including the parentheses, placeholders for the
425
/// arguments, etc.
426
class CodeCompletionString {
427
public:
428
  /// The different kinds of "chunks" that can occur within a code
429
  /// completion string.
430
  enum ChunkKind {
431
    /// The piece of text that the user is expected to type to
432
    /// match the code-completion string, typically a keyword or the name of a
433
    /// declarator or macro.
434
    CK_TypedText,
435
436
    /// A piece of text that should be placed in the buffer, e.g.,
437
    /// parentheses or a comma in a function call.
438
    CK_Text,
439
440
    /// A code completion string that is entirely optional. For example,
441
    /// an optional code completion string that describes the default arguments
442
    /// in a function call.
443
    CK_Optional,
444
445
    /// A string that acts as a placeholder for, e.g., a function
446
    /// call argument.
447
    CK_Placeholder,
448
449
    /// A piece of text that describes something about the result but
450
    /// should not be inserted into the buffer.
451
    CK_Informative,
452
    /// A piece of text that describes the type of an entity or, for
453
    /// functions and methods, the return type.
454
    CK_ResultType,
455
456
    /// A piece of text that describes the parameter that corresponds
457
    /// to the code-completion location within a function call, message send,
458
    /// macro invocation, etc.
459
    CK_CurrentParameter,
460
461
    /// A left parenthesis ('(').
462
    CK_LeftParen,
463
464
    /// A right parenthesis (')').
465
    CK_RightParen,
466
467
    /// A left bracket ('[').
468
    CK_LeftBracket,
469
470
    /// A right bracket (']').
471
    CK_RightBracket,
472
473
    /// A left brace ('{').
474
    CK_LeftBrace,
475
476
    /// A right brace ('}').
477
    CK_RightBrace,
478
479
    /// A left angle bracket ('<').
480
    CK_LeftAngle,
481
482
    /// A right angle bracket ('>').
483
    CK_RightAngle,
484
485
    /// A comma separator (',').
486
    CK_Comma,
487
488
    /// A colon (':').
489
    CK_Colon,
490
491
    /// A semicolon (';').
492
    CK_SemiColon,
493
494
    /// An '=' sign.
495
    CK_Equal,
496
497
    /// Horizontal whitespace (' ').
498
    CK_HorizontalSpace,
499
500
    /// Vertical whitespace ('\\n' or '\\r\\n', depending on the
501
    /// platform).
502
    CK_VerticalSpace
503
  };
504
505
  /// One piece of the code completion string.
506
  struct Chunk {
507
    /// The kind of data stored in this piece of the code completion
508
    /// string.
509
    ChunkKind Kind = CK_Text;
510
511
    union {
512
      /// The text string associated with a CK_Text, CK_Placeholder,
513
      /// CK_Informative, or CK_Comma chunk.
514
      /// The string is owned by the chunk and will be deallocated
515
      /// (with delete[]) when the chunk is destroyed.
516
      const char *Text;
517
518
      /// The code completion string associated with a CK_Optional chunk.
519
      /// The optional code completion string is owned by the chunk, and will
520
      /// be deallocated (with delete) when the chunk is destroyed.
521
      CodeCompletionString *Optional;
522
    };
523
524
86
    Chunk() : Text(nullptr) {}
525
526
    explicit Chunk(ChunkKind Kind, const char *Text = "");
527
528
    /// Create a new text chunk.
529
    static Chunk CreateText(const char *Text);
530
531
    /// Create a new optional chunk.
532
    static Chunk CreateOptional(CodeCompletionString *Optional);
533
534
    /// Create a new placeholder chunk.
535
    static Chunk CreatePlaceholder(const char *Placeholder);
536
537
    /// Create a new informative chunk.
538
    static Chunk CreateInformative(const char *Informative);
539
540
    /// Create a new result type chunk.
541
    static Chunk CreateResultType(const char *ResultType);
542
543
    /// Create a new current-parameter chunk.
544
    static Chunk CreateCurrentParameter(const char *CurrentParameter);
545
  };
546
547
private:
548
  friend class CodeCompletionBuilder;
549
  friend class CodeCompletionResult;
550
551
  /// The number of chunks stored in this string.
552
  unsigned NumChunks : 16;
553
554
  /// The number of annotations for this code-completion result.
555
  unsigned NumAnnotations : 16;
556
557
  /// The priority of this code-completion string.
558
  unsigned Priority : 16;
559
560
  /// The availability of this code-completion result.
561
  unsigned Availability : 2;
562
563
  /// The name of the parent context.
564
  StringRef ParentName;
565
566
  /// A brief documentation comment attached to the declaration of
567
  /// entity being completed by this result.
568
  const char *BriefComment;
569
570
  CodeCompletionString(const Chunk *Chunks, unsigned NumChunks,
571
                       unsigned Priority, CXAvailabilityKind Availability,
572
                       const char **Annotations, unsigned NumAnnotations,
573
                       StringRef ParentName,
574
                       const char *BriefComment);
575
  ~CodeCompletionString() = default;
576
577
public:
578
  CodeCompletionString(const CodeCompletionString &) = delete;
579
  CodeCompletionString &operator=(const CodeCompletionString &) = delete;
580
581
  using iterator = const Chunk *;
582
583
15.3M
  iterator begin() const { return reinterpret_cast<const Chunk *>(this + 1); }
584
7.45M
  iterator end() const { return begin() + NumChunks; }
585
0
  bool empty() const { return NumChunks == 0; }
586
  unsigned size() const { return NumChunks; }
587
588
  const Chunk &operator[](unsigned I) const {
589
    assert(I < size() && "Chunk index out-of-range");
590
    return begin()[I];
591
  }
592
593
  /// Returns the text in the TypedText chunk.
594
  const char *getTypedText() const;
595
596
  /// Retrieve the priority of this code completion result.
597
  unsigned getPriority() const { return Priority; }
598
599
  /// Retrieve the availability of this code completion result.
600
  unsigned getAvailability() const { return Availability; }
601
602
  /// Retrieve the number of annotations for this code completion result.
603
  unsigned getAnnotationCount() const;
604
605
  /// Retrieve the annotation string specified by \c AnnotationNr.
606
  const char *getAnnotation(unsigned AnnotationNr) const;
607
608
  /// Retrieve the name of the parent context.
609
  StringRef getParentContextName() const {
610
    return ParentName;
611
  }
612
613
111k
  const char *getBriefComment() const {
614
111k
    return BriefComment;
615
111k
  }
616
617
  /// Retrieve a string representation of the code completion string,
618
  /// which is mainly useful for debugging.
619
  std::string getAsString() const;
620
};
621
622
/// An allocator used specifically for the purpose of code completion.
623
class CodeCompletionAllocator : public llvm::BumpPtrAllocator {
624
public:
625
  /// Copy the given string into this allocator.
626
  const char *CopyString(const Twine &String);
627
};
628
629
/// Allocator for a cached set of global code completions.
630
class GlobalCodeCompletionAllocator : public CodeCompletionAllocator {};
631
632
class CodeCompletionTUInfo {
633
  llvm::DenseMap<const DeclContext *, StringRef> ParentNames;
634
  std::shared_ptr<GlobalCodeCompletionAllocator> AllocatorRef;
635
636
public:
637
  explicit CodeCompletionTUInfo(
638
      std::shared_ptr<GlobalCodeCompletionAllocator> Allocator)
639
982
      : AllocatorRef(std::move(Allocator)) {}
640
641
  std::shared_ptr<GlobalCodeCompletionAllocator> getAllocatorRef() const {
642
    return AllocatorRef;
643
  }
644
645
3.87k
  CodeCompletionAllocator &getAllocator() const {
646
3.87k
    assert(AllocatorRef);
647
3.87k
    return *AllocatorRef;
648
3.87k
  }
649
650
  StringRef getParentName(const DeclContext *DC);
651
};
652
653
} // namespace clang
654
655
namespace llvm {
656
657
template <> struct isPodLike<clang::CodeCompletionString::Chunk> {
658
  static const bool value = true;
659
};
660
661
} // namespace llvm
662
663
namespace clang {
664
665
/// A builder class used to construct new code-completion strings.
666
class CodeCompletionBuilder {
667
public:
668
  using Chunk = CodeCompletionString::Chunk;
669
670
private:
671
  CodeCompletionAllocator &Allocator;
672
  CodeCompletionTUInfo &CCTUInfo;
673
  unsigned Priority = 0;
674
  CXAvailabilityKind Availability = CXAvailability_Available;
675
  StringRef ParentName;
676
  const char *BriefComment = nullptr;
677
678
  /// The chunks stored in this string.
679
  SmallVector<Chunk, 4> Chunks;
680
681
  SmallVector<const char *, 2> Annotations;
682
683
public:
684
  CodeCompletionBuilder(CodeCompletionAllocator &Allocator,
685
                        CodeCompletionTUInfo &CCTUInfo)
686
2.71k
      : Allocator(Allocator), CCTUInfo(CCTUInfo) {}
687
688
  CodeCompletionBuilder(CodeCompletionAllocator &Allocator,
689
                        CodeCompletionTUInfo &CCTUInfo,
690
                        unsigned Priority, CXAvailabilityKind Availability)
691
      : Allocator(Allocator), CCTUInfo(CCTUInfo), Priority(Priority),
692
185k
        Availability(Availability) {}
693
694
  /// Retrieve the allocator into which the code completion
695
  /// strings should be allocated.
696
273k
  CodeCompletionAllocator &getAllocator() const { return Allocator; }
697
698
1.86k
  CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo; }
699
700
  /// Take the resulting completion string.
701
  ///
702
  /// This operation can only be performed once.
703
  CodeCompletionString *TakeString();
704
705
  /// Add a new typed-text chunk.
706
  void AddTypedTextChunk(const char *Text);
707
708
  /// Add a new text chunk.
709
  void AddTextChunk(const char *Text);
710
711
  /// Add a new optional chunk.
712
  void AddOptionalChunk(CodeCompletionString *Optional);
713
714
  /// Add a new placeholder chunk.
715
  void AddPlaceholderChunk(const char *Placeholder);
716
717
  /// Add a new informative chunk.
718
  void AddInformativeChunk(const char *Text);
719
720
  /// Add a new result-type chunk.
721
  void AddResultTypeChunk(const char *ResultType);
722
723
  /// Add a new current-parameter chunk.
724
  void AddCurrentParameterChunk(const char *CurrentParameter);
725
726
  /// Add a new chunk.
727
  void AddChunk(CodeCompletionString::ChunkKind CK, const char *Text = "");
728
729
6
  void AddAnnotation(const char *A) { Annotations.push_back(A); }
730
731
  /// Add the parent context information to this code completion.
732
  void addParentContext(const DeclContext *DC);
733
734
4
  const char *getBriefComment() const { return BriefComment; }
735
  void addBriefComment(StringRef Comment);
736
737
185
  StringRef getParentName() const { return ParentName; }
738
};
739
740
/// Captures a result of code completion.
741
class CodeCompletionResult {
742
public:
743
  /// Describes the kind of result generated.
744
  enum ResultKind {
745
    /// Refers to a declaration.
746
    RK_Declaration = 0,
747
748
    /// Refers to a keyword or symbol.
749
    RK_Keyword,
750
751
    /// Refers to a macro.
752
    RK_Macro,
753
754
    /// Refers to a precomputed pattern.
755
    RK_Pattern
756
  };
757
758
  /// When Kind == RK_Declaration or RK_Pattern, the declaration we are
759
  /// referring to. In the latter case, the declaration might be NULL.
760
  const NamedDecl *Declaration = nullptr;
761
762
  union {
763
    /// When Kind == RK_Keyword, the string representing the keyword
764
    /// or symbol's spelling.
765
    const char *Keyword;
766
767
    /// When Kind == RK_Pattern, the code-completion string that
768
    /// describes the completion text to insert.
769
    CodeCompletionString *Pattern;
770
771
    /// When Kind == RK_Macro, the identifier that refers to a macro.
772
    const IdentifierInfo *Macro;
773
  };
774
775
  /// The priority of this particular code-completion result.
776
  unsigned Priority;
777
778
  /// Specifies which parameter (of a function, Objective-C method,
779
  /// macro, etc.) we should start with when formatting the result.
780
  unsigned StartParameter = 0;
781
782
  /// The kind of result stored here.
783
  ResultKind Kind;
784
785
  /// The cursor kind that describes this result.
786
  CXCursorKind CursorKind;
787
788
  /// The availability of this result.
789
  CXAvailabilityKind Availability = CXAvailability_Available;
790
791
  /// Fix-its that *must* be applied before inserting the text for the
792
  /// corresponding completion.
793
  ///
794
  /// By default, CodeCompletionBuilder only returns completions with empty
795
  /// fix-its. Extra completions with non-empty fix-its should be explicitly
796
  /// requested by setting CompletionOptions::IncludeFixIts.
797
  ///
798
  /// For the clients to be able to compute position of the cursor after
799
  /// applying fix-its, the following conditions are guaranteed to hold for
800
  /// RemoveRange of the stored fix-its:
801
  ///  - Ranges in the fix-its are guaranteed to never contain the completion
802
  ///  point (or identifier under completion point, if any) inside them, except
803
  ///  at the start or at the end of the range.
804
  ///  - If a fix-it range starts or ends with completion point (or starts or
805
  ///  ends after the identifier under completion point), it will contain at
806
  ///  least one character. It allows to unambiguously recompute completion
807
  ///  point after applying the fix-it.
808
  ///
809
  /// The intuition is that provided fix-its change code around the identifier
810
  /// we complete, but are not allowed to touch the identifier itself or the
811
  /// completion point. One example of completions with corrections are the ones
812
  /// replacing '.' with '->' and vice versa:
813
  ///
814
  /// std::unique_ptr<std::vector<int>> vec_ptr;
815
  /// In 'vec_ptr.^', one of the completions is 'push_back', it requires
816
  /// replacing '.' with '->'.
817
  /// In 'vec_ptr->^', one of the completions is 'release', it requires
818
  /// replacing '->' with '.'.
819
  std::vector<FixItHint> FixIts;
820
821
  /// Whether this result is hidden by another name.
822
  bool Hidden : 1;
823
824
  /// Whether this result was found via lookup into a base class.
825
  bool QualifierIsInformative : 1;
826
827
  /// Whether this declaration is the beginning of a
828
  /// nested-name-specifier and, therefore, should be followed by '::'.
829
  bool StartsNestedNameSpecifier : 1;
830
831
  /// Whether all parameters (of a function, Objective-C
832
  /// method, etc.) should be considered "informative".
833
  bool AllParametersAreInformative : 1;
834
835
  /// Whether we're completing a declaration of the given entity,
836
  /// rather than a use of that entity.
837
  bool DeclaringEntity : 1;
838
839
  /// If the result should have a nested-name-specifier, this is it.
840
  /// When \c QualifierIsInformative, the nested-name-specifier is
841
  /// informative rather than required.
842
  NestedNameSpecifier *Qualifier = nullptr;
843
844
  /// If this Decl was unshadowed by using declaration, this can store a
845
  /// pointer to the UsingShadowDecl which was used in the unshadowing process.
846
  /// This information can be used to uprank CodeCompletionResults / which have
847
  /// corresponding `using decl::qualified::name;` nearby.
848
  const UsingShadowDecl *ShadowDecl = nullptr;
849
850
  /// If the result is RK_Macro, this can store the information about the macro
851
  /// definition. This should be set in most cases but can be missing when
852
  /// the macro has been undefined.
853
  const MacroInfo *MacroDefInfo = nullptr;
854
855
  /// Build a result that refers to a declaration.
856
  CodeCompletionResult(const NamedDecl *Declaration, unsigned Priority,
857
                       NestedNameSpecifier *Qualifier = nullptr,
858
                       bool QualifierIsInformative = false,
859
                       bool Accessible = true,
860
                       std::vector<FixItHint> FixIts = std::vector<FixItHint>())
861
      : Declaration(Declaration), Priority(Priority), Kind(RK_Declaration),
862
        FixIts(std::move(FixIts)), Hidden(false),
863
        QualifierIsInformative(QualifierIsInformative),
864
        StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
865
10.8k
        DeclaringEntity(false), Qualifier(Qualifier) {
866
10.8k
    // FIXME: Add assert to check FixIts range requirements.
867
10.8k
    computeCursorKindAndAvailability(Accessible);
868
10.8k
  }
869
870
  /// Build a result that refers to a keyword or symbol.
871
  CodeCompletionResult(const char *Keyword, unsigned Priority = CCP_Keyword)
872
      : Keyword(Keyword), Priority(Priority), Kind(RK_Keyword),
873
        CursorKind(CXCursor_NotImplemented), Hidden(false),
874
        QualifierIsInformative(false), StartsNestedNameSpecifier(false),
875
8.35k
        AllParametersAreInformative(false), DeclaringEntity(false) {}
876
877
  /// Build a result that refers to a macro.
878
  CodeCompletionResult(const IdentifierInfo *Macro,
879
                       const MacroInfo *MI = nullptr,
880
                       unsigned Priority = CCP_Macro)
881
      : Macro(Macro), Priority(Priority), Kind(RK_Macro),
882
        CursorKind(CXCursor_MacroDefinition), Hidden(false),
883
        QualifierIsInformative(false), StartsNestedNameSpecifier(false),
884
        AllParametersAreInformative(false), DeclaringEntity(false),
885
117k
        MacroDefInfo(MI) {}
886
887
  /// Build a result that refers to a pattern.
888
  CodeCompletionResult(CodeCompletionString *Pattern,
889
                       unsigned Priority = CCP_CodePattern,
890
                       CXCursorKind CursorKind = CXCursor_NotImplemented,
891
                   CXAvailabilityKind Availability = CXAvailability_Available,
892
                       const NamedDecl *D = nullptr)
893
      : Declaration(D), Pattern(Pattern), Priority(Priority), Kind(RK_Pattern),
894
        CursorKind(CursorKind), Availability(Availability), Hidden(false),
895
        QualifierIsInformative(false), StartsNestedNameSpecifier(false),
896
57.6k
        AllParametersAreInformative(false), DeclaringEntity(false) {}
897
898
  /// Build a result that refers to a pattern with an associated
899
  /// declaration.
900
  CodeCompletionResult(CodeCompletionString *Pattern, const NamedDecl *D,
901
                       unsigned Priority)
902
      : Declaration(D), Pattern(Pattern), Priority(Priority), Kind(RK_Pattern),
903
        Hidden(false), QualifierIsInformative(false),
904
        StartsNestedNameSpecifier(false), AllParametersAreInformative(false),
905
169
        DeclaringEntity(false) {
906
169
    computeCursorKindAndAvailability();
907
169
  }
908
909
  /// Retrieve the declaration stored in this result. This might be nullptr if
910
  /// Kind is RK_Pattern.
911
0
  const NamedDecl *getDeclaration() const {
912
0
    assert(((Kind == RK_Declaration) || (Kind == RK_Pattern)) &&
913
0
           "Not a declaration or pattern result");
914
0
    return Declaration;
915
0
  }
916
917
  /// Retrieve the keyword stored in this result.
918
0
  const char *getKeyword() const {
919
0
    assert(Kind == RK_Keyword && "Not a keyword result");
920
0
    return Keyword;
921
0
  }
922
923
  /// Create a new code-completion string that describes how to insert
924
  /// this result into a program.
925
  ///
926
  /// \param S The semantic analysis that created the result.
927
  ///
928
  /// \param Allocator The allocator that will be used to allocate the
929
  /// string itself.
930
  CodeCompletionString *CreateCodeCompletionString(Sema &S,
931
                                         const CodeCompletionContext &CCContext,
932
                                           CodeCompletionAllocator &Allocator,
933
                                           CodeCompletionTUInfo &CCTUInfo,
934
                                           bool IncludeBriefComments);
935
  CodeCompletionString *CreateCodeCompletionString(ASTContext &Ctx,
936
                                                   Preprocessor &PP,
937
                                         const CodeCompletionContext &CCContext,
938
                                           CodeCompletionAllocator &Allocator,
939
                                           CodeCompletionTUInfo &CCTUInfo,
940
                                           bool IncludeBriefComments);
941
  /// Creates a new code-completion string for the macro result. Similar to the
942
  /// above overloads, except this only requires preprocessor information.
943
  /// The result kind must be `RK_Macro`.
944
  CodeCompletionString *
945
  CreateCodeCompletionStringForMacro(Preprocessor &PP,
946
                                     CodeCompletionAllocator &Allocator,
947
                                     CodeCompletionTUInfo &CCTUInfo);
948
949
  /// Retrieve the name that should be used to order a result.
950
  ///
951
  /// If the name needs to be constructed as a string, that string will be
952
  /// saved into Saved and the returned StringRef will refer to it.
953
  StringRef getOrderedName(std::string &Saved) const;
954
955
private:
956
  void computeCursorKindAndAvailability(bool Accessible = true);
957
};
958
959
bool operator<(const CodeCompletionResult &X, const CodeCompletionResult &Y);
960
961
inline bool operator>(const CodeCompletionResult &X,
962
0
                      const CodeCompletionResult &Y) {
963
0
  return Y < X;
964
0
}
965
966
inline bool operator<=(const CodeCompletionResult &X,
967
0
                      const CodeCompletionResult &Y) {
968
0
  return !(Y < X);
969
0
}
970
971
inline bool operator>=(const CodeCompletionResult &X,
972
0
                       const CodeCompletionResult &Y) {
973
0
  return !(X < Y);
974
0
}
975
976
raw_ostream &operator<<(raw_ostream &OS,
977
                              const CodeCompletionString &CCS);
978
979
/// Abstract interface for a consumer of code-completion
980
/// information.
981
class CodeCompleteConsumer {
982
protected:
983
  const CodeCompleteOptions CodeCompleteOpts;
984
985
  /// Whether the output format for the code-completion consumer is
986
  /// binary.
987
  bool OutputIsBinary;
988
989
public:
990
  class OverloadCandidate {
991
  public:
992
    /// Describes the type of overload candidate.
993
    enum CandidateKind {
994
      /// The candidate is a function declaration.
995
      CK_Function,
996
997
      /// The candidate is a function template.
998
      CK_FunctionTemplate,
999
1000
      /// The "candidate" is actually a variable, expression, or block
1001
      /// for which we only have a function prototype.
1002
      CK_FunctionType
1003
    };
1004
1005
  private:
1006
    /// The kind of overload candidate.
1007
    CandidateKind Kind;
1008
1009
    union {
1010
      /// The function overload candidate, available when
1011
      /// Kind == CK_Function.
1012
      FunctionDecl *Function;
1013
1014
      /// The function template overload candidate, available when
1015
      /// Kind == CK_FunctionTemplate.
1016
      FunctionTemplateDecl *FunctionTemplate;
1017
1018
      /// The function type that describes the entity being called,
1019
      /// when Kind == CK_FunctionType.
1020
      const FunctionType *Type;
1021
    };
1022
1023
  public:
1024
    OverloadCandidate(FunctionDecl *Function)
1025
201
        : Kind(CK_Function), Function(Function) {}
1026
1027
    OverloadCandidate(FunctionTemplateDecl *FunctionTemplateDecl)
1028
        : Kind(CK_FunctionTemplate), FunctionTemplate(FunctionTemplateDecl) {}
1029
1030
    OverloadCandidate(const FunctionType *Type)
1031
5
        : Kind(CK_FunctionType), Type(Type) {}
1032
1033
    /// Determine the kind of overload candidate.
1034
211
    CandidateKind getKind() const { return Kind; }
1035
1036
    /// Retrieve the function overload candidate or the templated
1037
    /// function declaration for a function template.
1038
    FunctionDecl *getFunction() const;
1039
1040
    /// Retrieve the function template overload candidate.
1041
    FunctionTemplateDecl *getFunctionTemplate() const {
1042
      assert(getKind() == CK_FunctionTemplate && "Not a function template");
1043
      return FunctionTemplate;
1044
    }
1045
1046
    /// Retrieve the function type of the entity, regardless of how the
1047
    /// function is stored.
1048
    const FunctionType *getFunctionType() const;
1049
1050
    /// Create a new code-completion string that describes the function
1051
    /// signature of this overload candidate.
1052
    CodeCompletionString *CreateSignatureString(unsigned CurrentArg,
1053
                                                Sema &S,
1054
                                      CodeCompletionAllocator &Allocator,
1055
                                      CodeCompletionTUInfo &CCTUInfo,
1056
                                      bool IncludeBriefComments) const;
1057
  };
1058
1059
  CodeCompleteConsumer(const CodeCompleteOptions &CodeCompleteOpts,
1060
                       bool OutputIsBinary)
1061
1.55k
      : CodeCompleteOpts(CodeCompleteOpts), OutputIsBinary(OutputIsBinary) {}
1062
1063
  /// Whether the code-completion consumer wants to see macros.
1064
403
  bool includeMacros() const {
1065
403
    return CodeCompleteOpts.IncludeMacros;
1066
403
  }
1067
1068
  /// Whether the code-completion consumer wants to see code patterns.
1069
410
  bool includeCodePatterns() const {
1070
410
    return CodeCompleteOpts.IncludeCodePatterns;
1071
410
  }
1072
1073
  /// Whether to include global (top-level) declaration results.
1074
517
  bool includeGlobals() const { return CodeCompleteOpts.IncludeGlobals; }
1075
1076
  /// Whether to include declarations in namespace contexts (including
1077
  /// the global namespace). If this is false, `includeGlobals()` will be
1078
  /// ignored.
1079
34
  bool includeNamespaceLevelDecls() const {
1080
34
    return CodeCompleteOpts.IncludeNamespaceLevelDecls;
1081
34
  }
1082
1083
  /// Whether to include brief documentation comments within the set of
1084
  /// code completions returned.
1085
154k
  bool includeBriefComments() const {
1086
154k
    return CodeCompleteOpts.IncludeBriefComments;
1087
154k
  }
1088
1089
  /// Whether to include completion items with small fix-its, e.g. change
1090
  /// '.' to '->' on member access, etc.
1091
153k
  bool includeFixIts() const { return CodeCompleteOpts.IncludeFixIts; }
1092
1093
  /// Hint whether to load data from the external AST in order to provide
1094
  /// full results. If false, declarations from the preamble may be omitted.
1095
1.43k
  bool loadExternal() const {
1096
1.43k
    return CodeCompleteOpts.LoadExternal;
1097
1.43k
  }
1098
1099
  /// Determine whether the output of this consumer is binary.
1100
1.55k
  bool isOutputBinary() const { return OutputIsBinary; }
1101
1102
  /// Deregisters and destroys this code-completion consumer.
1103
  virtual ~CodeCompleteConsumer();
1104
1105
  /// \name Code-completion filtering
1106
  /// Check if the result should be filtered out.
1107
  virtual bool isResultFilteredOut(StringRef Filter,
1108
0
                                   CodeCompletionResult Results) {
1109
0
    return false;
1110
0
  }
1111
1112
  /// \name Code-completion callbacks
1113
  //@{
1114
  /// Process the finalized code-completion results.
1115
  virtual void ProcessCodeCompleteResults(Sema &S,
1116
                                          CodeCompletionContext Context,
1117
                                          CodeCompletionResult *Results,
1118
0
                                          unsigned NumResults) {}
1119
1120
  /// \param S the semantic-analyzer object for which code-completion is being
1121
  /// done.
1122
  ///
1123
  /// \param CurrentArg the index of the current argument.
1124
  ///
1125
  /// \param Candidates an array of overload candidates.
1126
  ///
1127
  /// \param NumCandidates the number of overload candidates
1128
  ///
1129
  /// \param OpenParLoc location of the opening parenthesis of the argument
1130
  ///        list.
1131
  virtual void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1132
                                         OverloadCandidate *Candidates,
1133
                                         unsigned NumCandidates,
1134
0
                                         SourceLocation OpenParLoc) {}
1135
  //@}
1136
1137
  /// Retrieve the allocator that will be used to allocate
1138
  /// code completion strings.
1139
  virtual CodeCompletionAllocator &getAllocator() = 0;
1140
1141
  virtual CodeCompletionTUInfo &getCodeCompletionTUInfo() = 0;
1142
};
1143
1144
/// Get the documentation comment used to produce
1145
/// CodeCompletionString::BriefComment for RK_Declaration.
1146
const RawComment *getCompletionComment(const ASTContext &Ctx,
1147
                                       const NamedDecl *Decl);
1148
1149
/// Get the documentation comment used to produce
1150
/// CodeCompletionString::BriefComment for RK_Pattern.
1151
const RawComment *getPatternCompletionComment(const ASTContext &Ctx,
1152
                                              const NamedDecl *Decl);
1153
1154
/// Get the documentation comment used to produce
1155
/// CodeCompletionString::BriefComment for OverloadCandidate.
1156
const RawComment *
1157
getParameterComment(const ASTContext &Ctx,
1158
                    const CodeCompleteConsumer::OverloadCandidate &Result,
1159
                    unsigned ArgIndex);
1160
1161
/// A simple code-completion consumer that prints the results it
1162
/// receives in a simple format.
1163
class PrintingCodeCompleteConsumer : public CodeCompleteConsumer {
1164
  /// The raw output stream.
1165
  raw_ostream &OS;
1166
1167
  CodeCompletionTUInfo CCTUInfo;
1168
1169
public:
1170
  /// Create a new printing code-completion consumer that prints its
1171
  /// results to the given raw output stream.
1172
  PrintingCodeCompleteConsumer(const CodeCompleteOptions &CodeCompleteOpts,
1173
                               raw_ostream &OS)
1174
      : CodeCompleteConsumer(CodeCompleteOpts, false), OS(OS),
1175
156
        CCTUInfo(std::make_shared<GlobalCodeCompletionAllocator>()) {}
1176
1177
  /// Prints the finalized code-completion results.
1178
  void ProcessCodeCompleteResults(Sema &S, CodeCompletionContext Context,
1179
                                  CodeCompletionResult *Results,
1180
                                  unsigned NumResults) override;
1181
1182
  void ProcessOverloadCandidates(Sema &S, unsigned CurrentArg,
1183
                                 OverloadCandidate *Candidates,
1184
                                 unsigned NumCandidates,
1185
                                 SourceLocation OpenParLoc) override;
1186
1187
  bool isResultFilteredOut(StringRef Filter, CodeCompletionResult Results) override;
1188
1189
3.76k
  CodeCompletionAllocator &getAllocator() override {
1190
3.76k
    return CCTUInfo.getAllocator();
1191
3.76k
  }
1192
1193
1.54k
  CodeCompletionTUInfo &getCodeCompletionTUInfo() override { return CCTUInfo; }
1194
};
1195
1196
} // namespace clang
1197
1198
#endif // LLVM_CLANG_SEMA_CODECOMPLETECONSUMER_H