Bug Summary

File:src/gnu/usr.bin/clang/libclangSema/../../../llvm/clang/include/clang/Sema/CodeCompleteConsumer.h
Warning:line 746, column 7
Assigned value is garbage or undefined

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple amd64-unknown-openbsd7.0 -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CodeCompleteConsumer.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -mrelocation-model static -mframe-pointer=all -relaxed-aliasing -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fcoverage-compilation-dir=/usr/src/gnu/usr.bin/clang/libclangSema/obj -resource-dir /usr/local/lib/clang/13.0.0 -I /usr/src/gnu/usr.bin/clang/libclangSema/obj/../include/clang/Sema -I /usr/src/gnu/usr.bin/clang/libclangSema/../../../llvm/clang/include -I /usr/src/gnu/usr.bin/clang/libclangSema/../../../llvm/llvm/include -I /usr/src/gnu/usr.bin/clang/libclangSema/../include -I /usr/src/gnu/usr.bin/clang/libclangSema/obj -I /usr/src/gnu/usr.bin/clang/libclangSema/obj/../include -D NDEBUG -D __STDC_LIMIT_MACROS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D LLVM_PREFIX="/usr" -internal-isystem /usr/include/c++/v1 -internal-isystem /usr/local/lib/clang/13.0.0/include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/usr/src/gnu/usr.bin/clang/libclangSema/obj -ferror-limit 19 -fvisibility-inlines-hidden -fwrapv -stack-protector 2 -fno-rtti -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -fno-builtin-malloc -fno-builtin-calloc -fno-builtin-realloc -fno-builtin-valloc -fno-builtin-free -fno-builtin-strdup -fno-builtin-strndup -analyzer-output=html -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /home/ben/Projects/vmm/scan-build/2022-01-12-194120-40624-1 -x c++ /usr/src/gnu/usr.bin/clang/libclangSema/../../../llvm/clang/lib/Sema/CodeCompleteConsumer.cpp

/usr/src/gnu/usr.bin/clang/libclangSema/../../../llvm/clang/lib/Sema/CodeCompleteConsumer.cpp

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

/usr/include/c++/v1/__algorithm/stable_sort.h

1//===----------------------------------------------------------------------===//
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#ifndef _LIBCPP___ALGORITHM_STABLE_SORT_H
10#define _LIBCPP___ALGORITHM_STABLE_SORT_H
11
12#include <__config>
13#include <__algorithm/comp.h>
14#include <__algorithm/comp_ref_type.h>
15#include <__algorithm/inplace_merge.h>
16#include <__algorithm/sort.h>
17#include <__iterator/iterator_traits.h>
18#include <__utility/swap.h>
19#include <memory>
20#include <type_traits> // swap
21
22#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
23#pragma GCC system_header
24#endif
25
26_LIBCPP_PUSH_MACROSpush_macro("min") push_macro("max")
27#include <__undef_macros>
28
29_LIBCPP_BEGIN_NAMESPACE_STDnamespace std { inline namespace __1 {
30
31template <class _Compare, class _InputIterator1, class _InputIterator2>
32void
33__merge_move_construct(_InputIterator1 __first1, _InputIterator1 __last1,
34 _InputIterator2 __first2, _InputIterator2 __last2,
35 typename iterator_traits<_InputIterator1>::value_type* __result, _Compare __comp)
36{
37 typedef typename iterator_traits<_InputIterator1>::value_type value_type;
38 __destruct_n __d(0);
39 unique_ptr<value_type, __destruct_n&> __h(__result, __d);
40 for (; true; ++__result)
41 {
42 if (__first1 == __last1)
43 {
44 for (; __first2 != __last2; ++__first2, ++__result, (void)__d.template __incr<value_type>())
45 ::new ((void*)__result) value_type(_VSTDstd::__1::move(*__first2));
46 __h.release();
47 return;
48 }
49 if (__first2 == __last2)
50 {
51 for (; __first1 != __last1; ++__first1, ++__result, (void)__d.template __incr<value_type>())
52 ::new ((void*)__result) value_type(_VSTDstd::__1::move(*__first1));
53 __h.release();
54 return;
55 }
56 if (__comp(*__first2, *__first1))
57 {
58 ::new ((void*)__result) value_type(_VSTDstd::__1::move(*__first2));
59 __d.template __incr<value_type>();
60 ++__first2;
61 }
62 else
63 {
64 ::new ((void*)__result) value_type(_VSTDstd::__1::move(*__first1));
65 __d.template __incr<value_type>();
66 ++__first1;
67 }
68 }
69}
70
71template <class _Compare, class _InputIterator1, class _InputIterator2, class _OutputIterator>
72void
73__merge_move_assign(_InputIterator1 __first1, _InputIterator1 __last1,
74 _InputIterator2 __first2, _InputIterator2 __last2,
75 _OutputIterator __result, _Compare __comp)
76{
77 for (; __first1
33.1
'__first1' is not equal to '__last1'
33.1
'__first1' is not equal to '__last1'
33.1
'__first1' is not equal to '__last1'
33.1
'__first1' is not equal to '__last1'
33.1
'__first1' is not equal to '__last1'
33.1
'__first1' is not equal to '__last1'
!= __last1; ++__result)
34
Loop condition is true. Entering loop body
78 {
79 if (__first2
34.1
'__first2' is not equal to '__last2'
34.1
'__first2' is not equal to '__last2'
34.1
'__first2' is not equal to '__last2'
34.1
'__first2' is not equal to '__last2'
34.1
'__first2' is not equal to '__last2'
34.1
'__first2' is not equal to '__last2'
== __last2)
35
Taking false branch
80 {
81 for (; __first1 != __last1; ++__first1, (void) ++__result)
82 *__result = _VSTDstd::__1::move(*__first1);
83 return;
84 }
85 if (__comp(*__first2, *__first1))
36
Taking false branch
86 {
87 *__result = _VSTDstd::__1::move(*__first2);
88 ++__first2;
89 }
90 else
91 {
92 *__result = _VSTDstd::__1::move(*__first1);
37
Calling 'move<clang::CodeCompletionResult &>'
38
Returning from 'move<clang::CodeCompletionResult &>'
39
Calling implicit move assignment operator for 'CodeCompletionResult'
93 ++__first1;
94 }
95 }
96 for (; __first2 != __last2; ++__first2, (void) ++__result)
97 *__result = _VSTDstd::__1::move(*__first2);
98}
99
100template <class _Compare, class _RandomAccessIterator>
101void
102__stable_sort(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp,
103 typename iterator_traits<_RandomAccessIterator>::difference_type __len,
104 typename iterator_traits<_RandomAccessIterator>::value_type* __buff, ptrdiff_t __buff_size);
105
106template <class _Compare, class _RandomAccessIterator>
107void
108__stable_sort_move(_RandomAccessIterator __first1, _RandomAccessIterator __last1, _Compare __comp,
109 typename iterator_traits<_RandomAccessIterator>::difference_type __len,
110 typename iterator_traits<_RandomAccessIterator>::value_type* __first2)
111{
112 typedef typename iterator_traits<_RandomAccessIterator>::value_type value_type;
113 switch (__len)
25
'Default' branch taken. Execution continues on line 140
114 {
115 case 0:
116 return;
117 case 1:
118 ::new ((void*)__first2) value_type(_VSTDstd::__1::move(*__first1));
119 return;
120 case 2:
121 __destruct_n __d(0);
122 unique_ptr<value_type, __destruct_n&> __h2(__first2, __d);
123 if (__comp(*--__last1, *__first1))
124 {
125 ::new ((void*)__first2) value_type(_VSTDstd::__1::move(*__last1));
126 __d.template __incr<value_type>();
127 ++__first2;
128 ::new ((void*)__first2) value_type(_VSTDstd::__1::move(*__first1));
129 }
130 else
131 {
132 ::new ((void*)__first2) value_type(_VSTDstd::__1::move(*__first1));
133 __d.template __incr<value_type>();
134 ++__first2;
135 ::new ((void*)__first2) value_type(_VSTDstd::__1::move(*__last1));
136 }
137 __h2.release();
138 return;
139 }
140 if (__len <= 8)
26
Assuming '__len' is <= 8
27
Taking true branch
141 {
142 _VSTDstd::__1::__insertion_sort_move<_Compare>(__first1, __last1, __first2, __comp);
28
Calling '__insertion_sort_move<std::__less<clang::CodeCompletionResult> &, clang::CodeCompletionResult *>'
31
Returning from '__insertion_sort_move<std::__less<clang::CodeCompletionResult> &, clang::CodeCompletionResult *>'
143 return;
144 }
145 typename iterator_traits<_RandomAccessIterator>::difference_type __l2 = __len / 2;
146 _RandomAccessIterator __m = __first1 + __l2;
147 _VSTDstd::__1::__stable_sort<_Compare>(__first1, __m, __comp, __l2, __first2, __l2);
148 _VSTDstd::__1::__stable_sort<_Compare>(__m, __last1, __comp, __len - __l2, __first2 + __l2, __len - __l2);
149 _VSTDstd::__1::__merge_move_construct<_Compare>(__first1, __m, __m, __last1, __first2, __comp);
150}
151
152template <class _Tp>
153struct __stable_sort_switch
154{
155 static const unsigned value = 128*is_trivially_copy_assignable<_Tp>::value;
156};
157
158template <class _Compare, class _RandomAccessIterator>
159void
160__stable_sort(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp,
161 typename iterator_traits<_RandomAccessIterator>::difference_type __len,
162 typename iterator_traits<_RandomAccessIterator>::value_type* __buff, ptrdiff_t __buff_size)
163{
164 typedef typename iterator_traits<_RandomAccessIterator>::value_type value_type;
165 typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type;
166 switch (__len)
19
'Default' branch taken. Execution continues on line 176
167 {
168 case 0:
169 case 1:
170 return;
171 case 2:
172 if (__comp(*--__last, *__first))
173 swap(*__first, *__last);
174 return;
175 }
176 if (__len
19.1
'__len' is > 'value'
19.1
'__len' is > 'value'
19.1
'__len' is > 'value'
19.1
'__len' is > 'value'
19.1
'__len' is > 'value'
19.1
'__len' is > 'value'
<= static_cast<difference_type>(__stable_sort_switch<value_type>::value))
20
Taking false branch
177 {
178 _VSTDstd::__1::__insertion_sort<_Compare>(__first, __last, __comp);
179 return;
180 }
181 typename iterator_traits<_RandomAccessIterator>::difference_type __l2 = __len / 2;
182 _RandomAccessIterator __m = __first + __l2;
183 if (__len
20.1
'__len' is <= '__buff_size'
20.1
'__len' is <= '__buff_size'
20.1
'__len' is <= '__buff_size'
20.1
'__len' is <= '__buff_size'
20.1
'__len' is <= '__buff_size'
20.1
'__len' is <= '__buff_size'
<= __buff_size)
21
Taking true branch
184 {
185 __destruct_n __d(0);
186 unique_ptr<value_type, __destruct_n&> __h2(__buff, __d);
22
Calling constructor for 'unique_ptr<clang::CodeCompletionResult, std::__destruct_n &>'
23
Returning from constructor for 'unique_ptr<clang::CodeCompletionResult, std::__destruct_n &>'
187 _VSTDstd::__1::__stable_sort_move<_Compare>(__first, __m, __comp, __l2, __buff);
24
Calling '__stable_sort_move<std::__less<clang::CodeCompletionResult> &, clang::CodeCompletionResult *>'
32
Returning from '__stable_sort_move<std::__less<clang::CodeCompletionResult> &, clang::CodeCompletionResult *>'
188 __d.__set(__l2, (value_type*)nullptr);
189 _VSTDstd::__1::__stable_sort_move<_Compare>(__m, __last, __comp, __len - __l2, __buff + __l2);
190 __d.__set(__len, (value_type*)nullptr);
191 _VSTDstd::__1::__merge_move_assign<_Compare>(__buff, __buff + __l2, __buff + __l2, __buff + __len, __first, __comp);
33
Calling '__merge_move_assign<std::__less<clang::CodeCompletionResult> &, clang::CodeCompletionResult *, clang::CodeCompletionResult *, clang::CodeCompletionResult *>'
192// _VSTD::__merge<_Compare>(move_iterator<value_type*>(__buff),
193// move_iterator<value_type*>(__buff + __l2),
194// move_iterator<_RandomAccessIterator>(__buff + __l2),
195// move_iterator<_RandomAccessIterator>(__buff + __len),
196// __first, __comp);
197 return;
198 }
199 _VSTDstd::__1::__stable_sort<_Compare>(__first, __m, __comp, __l2, __buff, __buff_size);
200 _VSTDstd::__1::__stable_sort<_Compare>(__m, __last, __comp, __len - __l2, __buff, __buff_size);
201 _VSTDstd::__1::__inplace_merge<_Compare>(__first, __m, __last, __comp, __l2, __len - __l2, __buff, __buff_size);
202}
203
204template <class _RandomAccessIterator, class _Compare>
205inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
206void
207stable_sort(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
208{
209 typedef typename iterator_traits<_RandomAccessIterator>::value_type value_type;
210 typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type;
211 difference_type __len = __last - __first;
212 pair<value_type*, ptrdiff_t> __buf(0, 0);
213 unique_ptr<value_type, __return_temporary_buffer> __h;
214 if (__len > static_cast<difference_type>(__stable_sort_switch<value_type>::value))
3
Assuming '__len' is > 'value'
4
Taking true branch
215 {
216 __buf = _VSTDstd::__1::get_temporary_buffer<value_type>(__len);
5
Calling 'get_temporary_buffer<clang::CodeCompletionResult>'
14
Returning from 'get_temporary_buffer<clang::CodeCompletionResult>'
217 __h.reset(__buf.first);
15
Calling 'unique_ptr::reset'
17
Returning from 'unique_ptr::reset'
218 }
219 typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
220 _VSTDstd::__1::__stable_sort<_Comp_ref>(__first, __last, __comp, __len, __buf.first, __buf.second);
18
Calling '__stable_sort<std::__less<clang::CodeCompletionResult> &, clang::CodeCompletionResult *>'
221}
222
223template <class _RandomAccessIterator>
224inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
225void
226stable_sort(_RandomAccessIterator __first, _RandomAccessIterator __last)
227{
228 _VSTDstd::__1::stable_sort(__first, __last, __less<typename iterator_traits<_RandomAccessIterator>::value_type>());
2
Calling 'stable_sort<clang::CodeCompletionResult *, std::__less<clang::CodeCompletionResult>>'
229}
230
231_LIBCPP_END_NAMESPACE_STD} }
232
233_LIBCPP_POP_MACROSpop_macro("min") pop_macro("max")
234
235#endif // _LIBCPP___ALGORITHM_STABLE_SORT_H

/usr/include/c++/v1/__memory/temporary_buffer.h

1// -*- C++ -*-
2//===----------------------------------------------------------------------===//
3//
4// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5// See https://llvm.org/LICENSE.txt for license information.
6// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7//
8//===----------------------------------------------------------------------===//
9
10#ifndef _LIBCPP___MEMORY_TEMPORARY_BUFFER_H
11#define _LIBCPP___MEMORY_TEMPORARY_BUFFER_H
12
13#include <__config>
14#include <cstddef>
15#include <new>
16#include <utility> // pair
17
18#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
19#pragma GCC system_header
20#endif
21
22_LIBCPP_PUSH_MACROSpush_macro("min") push_macro("max")
23#include <__undef_macros>
24
25_LIBCPP_BEGIN_NAMESPACE_STDnamespace std { inline namespace __1 {
26
27template <class _Tp>
28_LIBCPP_NODISCARD_EXT _LIBCPP_NO_CFI__attribute__((__no_sanitize__("cfi")))
29pair<_Tp*, ptrdiff_t>
30get_temporary_buffer(ptrdiff_t __n) _NOEXCEPTnoexcept
31{
32 pair<_Tp*, ptrdiff_t> __r(0, 0);
33 const ptrdiff_t __m = (~ptrdiff_t(0) ^
34 ptrdiff_t(ptrdiff_t(1) << (sizeof(ptrdiff_t) * __CHAR_BIT__8 - 1)))
35 / sizeof(_Tp);
36 if (__n > __m)
6
Assuming '__n' is <= '__m'
7
Taking false branch
37 __n = __m;
38 while (__n
7.1
'__n' is > 0
7.1
'__n' is > 0
7.1
'__n' is > 0
7.1
'__n' is > 0
7.1
'__n' is > 0
7.1
'__n' is > 0
> 0)
8
Loop condition is true. Entering loop body
39 {
40#if !defined(_LIBCPP_HAS_NO_ALIGNED_ALLOCATION)
41 if (__is_overaligned_for_new(_LIBCPP_ALIGNOF(_Tp)alignof(_Tp)))
42 {
43 align_val_t __al =
44 align_val_t(alignment_of<_Tp>::value);
45 __r.first = static_cast<_Tp*>(::operator new(
46 __n * sizeof(_Tp), __al, nothrow));
47 } else {
48 __r.first = static_cast<_Tp*>(::operator new(
49 __n * sizeof(_Tp), nothrow));
50 }
51#else
52 if (__is_overaligned_for_new(_LIBCPP_ALIGNOF(_Tp)alignof(_Tp)))
9
Taking false branch
53 {
54 // Since aligned operator new is unavailable, return an empty
55 // buffer rather than one with invalid alignment.
56 return __r;
57 }
58
59 __r.first = static_cast<_Tp*>(::operator new(__n * sizeof(_Tp), nothrow));
10
Uninitialized value stored to field 'Declaration'
60#endif
61
62 if (__r.first)
11
Assuming field 'first' is non-null
12
Taking true branch
63 {
64 __r.second = __n;
65 break;
13
Execution continues on line 69
66 }
67 __n /= 2;
68 }
69 return __r;
70}
71
72template <class _Tp>
73inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
74void return_temporary_buffer(_Tp* __p) _NOEXCEPTnoexcept
75{
76 _VSTDstd::__1::__libcpp_deallocate_unsized((void*)__p, _LIBCPP_ALIGNOF(_Tp)alignof(_Tp));
77}
78
79struct __return_temporary_buffer
80{
81 template <class _Tp>
82 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
void operator()(_Tp* __p) const {_VSTDstd::__1::return_temporary_buffer(__p);}
83};
84
85_LIBCPP_END_NAMESPACE_STD} }
86
87_LIBCPP_POP_MACROSpop_macro("min") pop_macro("max")
88
89#endif // _LIBCPP___MEMORY_TEMPORARY_BUFFER_H

/usr/include/c++/v1/__memory/unique_ptr.h

1// -*- C++ -*-
2//===----------------------------------------------------------------------===//
3//
4// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5// See https://llvm.org/LICENSE.txt for license information.
6// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7//
8//===----------------------------------------------------------------------===//
9
10#ifndef _LIBCPP___MEMORY_UNIQUE_PTR_H
11#define _LIBCPP___MEMORY_UNIQUE_PTR_H
12
13#include <__config>
14#include <__functional_base>
15#include <__functional/hash.h>
16#include <__functional/operations.h>
17#include <__memory/allocator_traits.h> // __pointer
18#include <__memory/compressed_pair.h>
19#include <__utility/forward.h>
20#include <cstddef>
21#include <type_traits>
22#include <utility>
23
24#if _LIBCPP_STD_VER14 <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR)
25# include <__memory/auto_ptr.h>
26#endif
27
28#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
29#pragma GCC system_header
30#endif
31
32_LIBCPP_PUSH_MACROSpush_macro("min") push_macro("max")
33#include <__undef_macros>
34
35_LIBCPP_BEGIN_NAMESPACE_STDnamespace std { inline namespace __1 {
36
37template <class _Tp>
38struct _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) default_delete {
39 static_assert(!is_function<_Tp>::value,
40 "default_delete cannot be instantiated for function types");
41#ifndef _LIBCPP_CXX03_LANG
42 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
constexpr default_delete() _NOEXCEPTnoexcept = default;
43#else
44 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
default_delete() {}
45#endif
46 template <class _Up>
47 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
48 default_delete(const default_delete<_Up>&,
49 typename enable_if<is_convertible<_Up*, _Tp*>::value>::type* =
50 0) _NOEXCEPTnoexcept {}
51
52 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
void operator()(_Tp* __ptr) const _NOEXCEPTnoexcept {
53 static_assert(sizeof(_Tp) > 0,
54 "default_delete can not delete incomplete type");
55 static_assert(!is_void<_Tp>::value,
56 "default_delete can not delete incomplete type");
57 delete __ptr;
58 }
59};
60
61template <class _Tp>
62struct _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) default_delete<_Tp[]> {
63private:
64 template <class _Up>
65 struct _EnableIfConvertible
66 : enable_if<is_convertible<_Up(*)[], _Tp(*)[]>::value> {};
67
68public:
69#ifndef _LIBCPP_CXX03_LANG
70 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
constexpr default_delete() _NOEXCEPTnoexcept = default;
71#else
72 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
default_delete() {}
73#endif
74
75 template <class _Up>
76 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
77 default_delete(const default_delete<_Up[]>&,
78 typename _EnableIfConvertible<_Up>::type* = 0) _NOEXCEPTnoexcept {}
79
80 template <class _Up>
81 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
82 typename _EnableIfConvertible<_Up>::type
83 operator()(_Up* __ptr) const _NOEXCEPTnoexcept {
84 static_assert(sizeof(_Tp) > 0,
85 "default_delete can not delete incomplete type");
86 static_assert(!is_void<_Tp>::value,
87 "default_delete can not delete void type");
88 delete[] __ptr;
89 }
90};
91
92template <class _Deleter>
93struct __unique_ptr_deleter_sfinae {
94 static_assert(!is_reference<_Deleter>::value, "incorrect specialization");
95 typedef const _Deleter& __lval_ref_type;
96 typedef _Deleter&& __good_rval_ref_type;
97 typedef true_type __enable_rval_overload;
98};
99
100template <class _Deleter>
101struct __unique_ptr_deleter_sfinae<_Deleter const&> {
102 typedef const _Deleter& __lval_ref_type;
103 typedef const _Deleter&& __bad_rval_ref_type;
104 typedef false_type __enable_rval_overload;
105};
106
107template <class _Deleter>
108struct __unique_ptr_deleter_sfinae<_Deleter&> {
109 typedef _Deleter& __lval_ref_type;
110 typedef _Deleter&& __bad_rval_ref_type;
111 typedef false_type __enable_rval_overload;
112};
113
114#if defined(_LIBCPP_ABI_ENABLE_UNIQUE_PTR_TRIVIAL_ABI)
115# define _LIBCPP_UNIQUE_PTR_TRIVIAL_ABI __attribute__((trivial_abi))
116#else
117# define _LIBCPP_UNIQUE_PTR_TRIVIAL_ABI
118#endif
119
120template <class _Tp, class _Dp = default_delete<_Tp> >
121class _LIBCPP_UNIQUE_PTR_TRIVIAL_ABI _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) unique_ptr {
122public:
123 typedef _Tp element_type;
124 typedef _Dp deleter_type;
125 typedef _LIBCPP_NODEBUG_TYPE__attribute__((nodebug)) typename __pointer<_Tp, deleter_type>::type pointer;
126
127 static_assert(!is_rvalue_reference<deleter_type>::value,
128 "the specified deleter type cannot be an rvalue reference");
129
130private:
131 __compressed_pair<pointer, deleter_type> __ptr_;
132
133 struct __nat { int __for_bool_; };
134
135 typedef _LIBCPP_NODEBUG_TYPE__attribute__((nodebug)) __unique_ptr_deleter_sfinae<_Dp> _DeleterSFINAE;
136
137 template <bool _Dummy>
138 using _LValRefType _LIBCPP_NODEBUG_TYPE__attribute__((nodebug)) =
139 typename __dependent_type<_DeleterSFINAE, _Dummy>::__lval_ref_type;
140
141 template <bool _Dummy>
142 using _GoodRValRefType _LIBCPP_NODEBUG_TYPE__attribute__((nodebug)) =
143 typename __dependent_type<_DeleterSFINAE, _Dummy>::__good_rval_ref_type;
144
145 template <bool _Dummy>
146 using _BadRValRefType _LIBCPP_NODEBUG_TYPE__attribute__((nodebug)) =
147 typename __dependent_type<_DeleterSFINAE, _Dummy>::__bad_rval_ref_type;
148
149 template <bool _Dummy, class _Deleter = typename __dependent_type<
150 __identity<deleter_type>, _Dummy>::type>
151 using _EnableIfDeleterDefaultConstructible _LIBCPP_NODEBUG_TYPE__attribute__((nodebug)) =
152 typename enable_if<is_default_constructible<_Deleter>::value &&
153 !is_pointer<_Deleter>::value>::type;
154
155 template <class _ArgType>
156 using _EnableIfDeleterConstructible _LIBCPP_NODEBUG_TYPE__attribute__((nodebug)) =
157 typename enable_if<is_constructible<deleter_type, _ArgType>::value>::type;
158
159 template <class _UPtr, class _Up>
160 using _EnableIfMoveConvertible _LIBCPP_NODEBUG_TYPE__attribute__((nodebug)) = typename enable_if<
161 is_convertible<typename _UPtr::pointer, pointer>::value &&
162 !is_array<_Up>::value
163 >::type;
164
165 template <class _UDel>
166 using _EnableIfDeleterConvertible _LIBCPP_NODEBUG_TYPE__attribute__((nodebug)) = typename enable_if<
167 (is_reference<_Dp>::value && is_same<_Dp, _UDel>::value) ||
168 (!is_reference<_Dp>::value && is_convertible<_UDel, _Dp>::value)
169 >::type;
170
171 template <class _UDel>
172 using _EnableIfDeleterAssignable = typename enable_if<
173 is_assignable<_Dp&, _UDel&&>::value
174 >::type;
175
176public:
177 template <bool _Dummy = true,
178 class = _EnableIfDeleterDefaultConstructible<_Dummy> >
179 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
180 _LIBCPP_CONSTEXPRconstexpr unique_ptr() _NOEXCEPTnoexcept : __ptr_(pointer(), __default_init_tag()) {}
181
182 template <bool _Dummy = true,
183 class = _EnableIfDeleterDefaultConstructible<_Dummy> >
184 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
185 _LIBCPP_CONSTEXPRconstexpr unique_ptr(nullptr_t) _NOEXCEPTnoexcept : __ptr_(pointer(), __default_init_tag()) {}
186
187 template <bool _Dummy = true,
188 class = _EnableIfDeleterDefaultConstructible<_Dummy> >
189 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
190 explicit unique_ptr(pointer __p) _NOEXCEPTnoexcept : __ptr_(__p, __default_init_tag()) {}
191
192 template <bool _Dummy = true,
193 class = _EnableIfDeleterConstructible<_LValRefType<_Dummy> > >
194 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
195 unique_ptr(pointer __p, _LValRefType<_Dummy> __d) _NOEXCEPTnoexcept
196 : __ptr_(__p, __d) {}
197
198 template <bool _Dummy = true,
199 class = _EnableIfDeleterConstructible<_GoodRValRefType<_Dummy> > >
200 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
201 unique_ptr(pointer __p, _GoodRValRefType<_Dummy> __d) _NOEXCEPTnoexcept
202 : __ptr_(__p, _VSTDstd::__1::move(__d)) {
203 static_assert(!is_reference<deleter_type>::value,
204 "rvalue deleter bound to reference");
205 }
206
207 template <bool _Dummy = true,
208 class = _EnableIfDeleterConstructible<_BadRValRefType<_Dummy> > >
209 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
210 unique_ptr(pointer __p, _BadRValRefType<_Dummy> __d) = delete;
211
212 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
213 unique_ptr(unique_ptr&& __u) _NOEXCEPTnoexcept
214 : __ptr_(__u.release(), _VSTDstd::__1::forward<deleter_type>(__u.get_deleter())) {
215 }
216
217 template <class _Up, class _Ep,
218 class = _EnableIfMoveConvertible<unique_ptr<_Up, _Ep>, _Up>,
219 class = _EnableIfDeleterConvertible<_Ep>
220 >
221 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
222 unique_ptr(unique_ptr<_Up, _Ep>&& __u) _NOEXCEPTnoexcept
223 : __ptr_(__u.release(), _VSTDstd::__1::forward<_Ep>(__u.get_deleter())) {}
224
225#if _LIBCPP_STD_VER14 <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR)
226 template <class _Up>
227 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
228 unique_ptr(auto_ptr<_Up>&& __p,
229 typename enable_if<is_convertible<_Up*, _Tp*>::value &&
230 is_same<_Dp, default_delete<_Tp> >::value,
231 __nat>::type = __nat()) _NOEXCEPTnoexcept
232 : __ptr_(__p.release(), __default_init_tag()) {}
233#endif
234
235 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
236 unique_ptr& operator=(unique_ptr&& __u) _NOEXCEPTnoexcept {
237 reset(__u.release());
238 __ptr_.second() = _VSTDstd::__1::forward<deleter_type>(__u.get_deleter());
239 return *this;
240 }
241
242 template <class _Up, class _Ep,
243 class = _EnableIfMoveConvertible<unique_ptr<_Up, _Ep>, _Up>,
244 class = _EnableIfDeleterAssignable<_Ep>
245 >
246 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
247 unique_ptr& operator=(unique_ptr<_Up, _Ep>&& __u) _NOEXCEPTnoexcept {
248 reset(__u.release());
249 __ptr_.second() = _VSTDstd::__1::forward<_Ep>(__u.get_deleter());
250 return *this;
251 }
252
253#if _LIBCPP_STD_VER14 <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR)
254 template <class _Up>
255 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
256 typename enable_if<is_convertible<_Up*, _Tp*>::value &&
257 is_same<_Dp, default_delete<_Tp> >::value,
258 unique_ptr&>::type
259 operator=(auto_ptr<_Up> __p) {
260 reset(__p.release());
261 return *this;
262 }
263#endif
264
265#ifdef _LIBCPP_CXX03_LANG
266 unique_ptr(unique_ptr const&) = delete;
267 unique_ptr& operator=(unique_ptr const&) = delete;
268#endif
269
270
271 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
272 ~unique_ptr() { reset(); }
273
274 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
275 unique_ptr& operator=(nullptr_t) _NOEXCEPTnoexcept {
276 reset();
277 return *this;
278 }
279
280 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
281 typename add_lvalue_reference<_Tp>::type
282 operator*() const {
283 return *__ptr_.first();
284 }
285 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
286 pointer operator->() const _NOEXCEPTnoexcept {
287 return __ptr_.first();
288 }
289 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
290 pointer get() const _NOEXCEPTnoexcept {
291 return __ptr_.first();
292 }
293 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
294 deleter_type& get_deleter() _NOEXCEPTnoexcept {
295 return __ptr_.second();
296 }
297 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
298 const deleter_type& get_deleter() const _NOEXCEPTnoexcept {
299 return __ptr_.second();
300 }
301 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
302 explicit operator bool() const _NOEXCEPTnoexcept {
303 return __ptr_.first() != nullptr;
304 }
305
306 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
307 pointer release() _NOEXCEPTnoexcept {
308 pointer __t = __ptr_.first();
309 __ptr_.first() = pointer();
310 return __t;
311 }
312
313 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
314 void reset(pointer __p = pointer()) _NOEXCEPTnoexcept {
315 pointer __tmp = __ptr_.first();
316 __ptr_.first() = __p;
317 if (__tmp
15.1
'__tmp' is null
15.1
'__tmp' is null
15.1
'__tmp' is null
15.1
'__tmp' is null
15.1
'__tmp' is null
15.1
'__tmp' is null
)
16
Taking false branch
318 __ptr_.second()(__tmp);
319 }
320
321 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
322 void swap(unique_ptr& __u) _NOEXCEPTnoexcept {
323 __ptr_.swap(__u.__ptr_);
324 }
325};
326
327
328template <class _Tp, class _Dp>
329class _LIBCPP_UNIQUE_PTR_TRIVIAL_ABI _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) unique_ptr<_Tp[], _Dp> {
330public:
331 typedef _Tp element_type;
332 typedef _Dp deleter_type;
333 typedef typename __pointer<_Tp, deleter_type>::type pointer;
334
335private:
336 __compressed_pair<pointer, deleter_type> __ptr_;
337
338 template <class _From>
339 struct _CheckArrayPointerConversion : is_same<_From, pointer> {};
340
341 template <class _FromElem>
342 struct _CheckArrayPointerConversion<_FromElem*>
343 : integral_constant<bool,
344 is_same<_FromElem*, pointer>::value ||
345 (is_same<pointer, element_type*>::value &&
346 is_convertible<_FromElem(*)[], element_type(*)[]>::value)
347 >
348 {};
349
350 typedef __unique_ptr_deleter_sfinae<_Dp> _DeleterSFINAE;
351
352 template <bool _Dummy>
353 using _LValRefType _LIBCPP_NODEBUG_TYPE__attribute__((nodebug)) =
354 typename __dependent_type<_DeleterSFINAE, _Dummy>::__lval_ref_type;
355
356 template <bool _Dummy>
357 using _GoodRValRefType _LIBCPP_NODEBUG_TYPE__attribute__((nodebug)) =
358 typename __dependent_type<_DeleterSFINAE, _Dummy>::__good_rval_ref_type;
359
360 template <bool _Dummy>
361 using _BadRValRefType _LIBCPP_NODEBUG_TYPE__attribute__((nodebug)) =
362 typename __dependent_type<_DeleterSFINAE, _Dummy>::__bad_rval_ref_type;
363
364 template <bool _Dummy, class _Deleter = typename __dependent_type<
365 __identity<deleter_type>, _Dummy>::type>
366 using _EnableIfDeleterDefaultConstructible _LIBCPP_NODEBUG_TYPE__attribute__((nodebug)) =
367 typename enable_if<is_default_constructible<_Deleter>::value &&
368 !is_pointer<_Deleter>::value>::type;
369
370 template <class _ArgType>
371 using _EnableIfDeleterConstructible _LIBCPP_NODEBUG_TYPE__attribute__((nodebug)) =
372 typename enable_if<is_constructible<deleter_type, _ArgType>::value>::type;
373
374 template <class _Pp>
375 using _EnableIfPointerConvertible _LIBCPP_NODEBUG_TYPE__attribute__((nodebug)) = typename enable_if<
376 _CheckArrayPointerConversion<_Pp>::value
377 >::type;
378
379 template <class _UPtr, class _Up,
380 class _ElemT = typename _UPtr::element_type>
381 using _EnableIfMoveConvertible _LIBCPP_NODEBUG_TYPE__attribute__((nodebug)) = typename enable_if<
382 is_array<_Up>::value &&
383 is_same<pointer, element_type*>::value &&
384 is_same<typename _UPtr::pointer, _ElemT*>::value &&
385 is_convertible<_ElemT(*)[], element_type(*)[]>::value
386 >::type;
387
388 template <class _UDel>
389 using _EnableIfDeleterConvertible _LIBCPP_NODEBUG_TYPE__attribute__((nodebug)) = typename enable_if<
390 (is_reference<_Dp>::value && is_same<_Dp, _UDel>::value) ||
391 (!is_reference<_Dp>::value && is_convertible<_UDel, _Dp>::value)
392 >::type;
393
394 template <class _UDel>
395 using _EnableIfDeleterAssignable _LIBCPP_NODEBUG_TYPE__attribute__((nodebug)) = typename enable_if<
396 is_assignable<_Dp&, _UDel&&>::value
397 >::type;
398
399public:
400 template <bool _Dummy = true,
401 class = _EnableIfDeleterDefaultConstructible<_Dummy> >
402 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
403 _LIBCPP_CONSTEXPRconstexpr unique_ptr() _NOEXCEPTnoexcept : __ptr_(pointer(), __default_init_tag()) {}
404
405 template <bool _Dummy = true,
406 class = _EnableIfDeleterDefaultConstructible<_Dummy> >
407 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
408 _LIBCPP_CONSTEXPRconstexpr unique_ptr(nullptr_t) _NOEXCEPTnoexcept : __ptr_(pointer(), __default_init_tag()) {}
409
410 template <class _Pp, bool _Dummy = true,
411 class = _EnableIfDeleterDefaultConstructible<_Dummy>,
412 class = _EnableIfPointerConvertible<_Pp> >
413 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
414 explicit unique_ptr(_Pp __p) _NOEXCEPTnoexcept
415 : __ptr_(__p, __default_init_tag()) {}
416
417 template <class _Pp, bool _Dummy = true,
418 class = _EnableIfDeleterConstructible<_LValRefType<_Dummy> >,
419 class = _EnableIfPointerConvertible<_Pp> >
420 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
421 unique_ptr(_Pp __p, _LValRefType<_Dummy> __d) _NOEXCEPTnoexcept
422 : __ptr_(__p, __d) {}
423
424 template <bool _Dummy = true,
425 class = _EnableIfDeleterConstructible<_LValRefType<_Dummy> > >
426 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
427 unique_ptr(nullptr_t, _LValRefType<_Dummy> __d) _NOEXCEPTnoexcept
428 : __ptr_(nullptr, __d) {}
429
430 template <class _Pp, bool _Dummy = true,
431 class = _EnableIfDeleterConstructible<_GoodRValRefType<_Dummy> >,
432 class = _EnableIfPointerConvertible<_Pp> >
433 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
434 unique_ptr(_Pp __p, _GoodRValRefType<_Dummy> __d) _NOEXCEPTnoexcept
435 : __ptr_(__p, _VSTDstd::__1::move(__d)) {
436 static_assert(!is_reference<deleter_type>::value,
437 "rvalue deleter bound to reference");
438 }
439
440 template <bool _Dummy = true,
441 class = _EnableIfDeleterConstructible<_GoodRValRefType<_Dummy> > >
442 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
443 unique_ptr(nullptr_t, _GoodRValRefType<_Dummy> __d) _NOEXCEPTnoexcept
444 : __ptr_(nullptr, _VSTDstd::__1::move(__d)) {
445 static_assert(!is_reference<deleter_type>::value,
446 "rvalue deleter bound to reference");
447 }
448
449 template <class _Pp, bool _Dummy = true,
450 class = _EnableIfDeleterConstructible<_BadRValRefType<_Dummy> >,
451 class = _EnableIfPointerConvertible<_Pp> >
452 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
453 unique_ptr(_Pp __p, _BadRValRefType<_Dummy> __d) = delete;
454
455 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
456 unique_ptr(unique_ptr&& __u) _NOEXCEPTnoexcept
457 : __ptr_(__u.release(), _VSTDstd::__1::forward<deleter_type>(__u.get_deleter())) {
458 }
459
460 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
461 unique_ptr& operator=(unique_ptr&& __u) _NOEXCEPTnoexcept {
462 reset(__u.release());
463 __ptr_.second() = _VSTDstd::__1::forward<deleter_type>(__u.get_deleter());
464 return *this;
465 }
466
467 template <class _Up, class _Ep,
468 class = _EnableIfMoveConvertible<unique_ptr<_Up, _Ep>, _Up>,
469 class = _EnableIfDeleterConvertible<_Ep>
470 >
471 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
472 unique_ptr(unique_ptr<_Up, _Ep>&& __u) _NOEXCEPTnoexcept
473 : __ptr_(__u.release(), _VSTDstd::__1::forward<_Ep>(__u.get_deleter())) {
474 }
475
476 template <class _Up, class _Ep,
477 class = _EnableIfMoveConvertible<unique_ptr<_Up, _Ep>, _Up>,
478 class = _EnableIfDeleterAssignable<_Ep>
479 >
480 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
481 unique_ptr&
482 operator=(unique_ptr<_Up, _Ep>&& __u) _NOEXCEPTnoexcept {
483 reset(__u.release());
484 __ptr_.second() = _VSTDstd::__1::forward<_Ep>(__u.get_deleter());
485 return *this;
486 }
487
488#ifdef _LIBCPP_CXX03_LANG
489 unique_ptr(unique_ptr const&) = delete;
490 unique_ptr& operator=(unique_ptr const&) = delete;
491#endif
492
493public:
494 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
495 ~unique_ptr() { reset(); }
496
497 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
498 unique_ptr& operator=(nullptr_t) _NOEXCEPTnoexcept {
499 reset();
500 return *this;
501 }
502
503 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
504 typename add_lvalue_reference<_Tp>::type
505 operator[](size_t __i) const {
506 return __ptr_.first()[__i];
507 }
508 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
509 pointer get() const _NOEXCEPTnoexcept {
510 return __ptr_.first();
511 }
512
513 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
514 deleter_type& get_deleter() _NOEXCEPTnoexcept {
515 return __ptr_.second();
516 }
517
518 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
519 const deleter_type& get_deleter() const _NOEXCEPTnoexcept {
520 return __ptr_.second();
521 }
522 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
523 explicit operator bool() const _NOEXCEPTnoexcept {
524 return __ptr_.first() != nullptr;
525 }
526
527 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
528 pointer release() _NOEXCEPTnoexcept {
529 pointer __t = __ptr_.first();
530 __ptr_.first() = pointer();
531 return __t;
532 }
533
534 template <class _Pp>
535 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
536 typename enable_if<
537 _CheckArrayPointerConversion<_Pp>::value
538 >::type
539 reset(_Pp __p) _NOEXCEPTnoexcept {
540 pointer __tmp = __ptr_.first();
541 __ptr_.first() = __p;
542 if (__tmp)
543 __ptr_.second()(__tmp);
544 }
545
546 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
547 void reset(nullptr_t = nullptr) _NOEXCEPTnoexcept {
548 pointer __tmp = __ptr_.first();
549 __ptr_.first() = nullptr;
550 if (__tmp)
551 __ptr_.second()(__tmp);
552 }
553
554 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
555 void swap(unique_ptr& __u) _NOEXCEPTnoexcept {
556 __ptr_.swap(__u.__ptr_);
557 }
558
559};
560
561template <class _Tp, class _Dp>
562inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
563typename enable_if<
564 __is_swappable<_Dp>::value,
565 void
566>::type
567swap(unique_ptr<_Tp, _Dp>& __x, unique_ptr<_Tp, _Dp>& __y) _NOEXCEPTnoexcept {__x.swap(__y);}
568
569template <class _T1, class _D1, class _T2, class _D2>
570inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
571bool
572operator==(const unique_ptr<_T1, _D1>& __x, const unique_ptr<_T2, _D2>& __y) {return __x.get() == __y.get();}
573
574template <class _T1, class _D1, class _T2, class _D2>
575inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
576bool
577operator!=(const unique_ptr<_T1, _D1>& __x, const unique_ptr<_T2, _D2>& __y) {return !(__x == __y);}
578
579template <class _T1, class _D1, class _T2, class _D2>
580inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
581bool
582operator< (const unique_ptr<_T1, _D1>& __x, const unique_ptr<_T2, _D2>& __y)
583{
584 typedef typename unique_ptr<_T1, _D1>::pointer _P1;
585 typedef typename unique_ptr<_T2, _D2>::pointer _P2;
586 typedef typename common_type<_P1, _P2>::type _Vp;
587 return less<_Vp>()(__x.get(), __y.get());
588}
589
590template <class _T1, class _D1, class _T2, class _D2>
591inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
592bool
593operator> (const unique_ptr<_T1, _D1>& __x, const unique_ptr<_T2, _D2>& __y) {return __y < __x;}
594
595template <class _T1, class _D1, class _T2, class _D2>
596inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
597bool
598operator<=(const unique_ptr<_T1, _D1>& __x, const unique_ptr<_T2, _D2>& __y) {return !(__y < __x);}
599
600template <class _T1, class _D1, class _T2, class _D2>
601inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
602bool
603operator>=(const unique_ptr<_T1, _D1>& __x, const unique_ptr<_T2, _D2>& __y) {return !(__x < __y);}
604
605template <class _T1, class _D1>
606inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
607bool
608operator==(const unique_ptr<_T1, _D1>& __x, nullptr_t) _NOEXCEPTnoexcept
609{
610 return !__x;
611}
612
613template <class _T1, class _D1>
614inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
615bool
616operator==(nullptr_t, const unique_ptr<_T1, _D1>& __x) _NOEXCEPTnoexcept
617{
618 return !__x;
619}
620
621template <class _T1, class _D1>
622inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
623bool
624operator!=(const unique_ptr<_T1, _D1>& __x, nullptr_t) _NOEXCEPTnoexcept
625{
626 return static_cast<bool>(__x);
627}
628
629template <class _T1, class _D1>
630inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
631bool
632operator!=(nullptr_t, const unique_ptr<_T1, _D1>& __x) _NOEXCEPTnoexcept
633{
634 return static_cast<bool>(__x);
635}
636
637template <class _T1, class _D1>
638inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
639bool
640operator<(const unique_ptr<_T1, _D1>& __x, nullptr_t)
641{
642 typedef typename unique_ptr<_T1, _D1>::pointer _P1;
643 return less<_P1>()(__x.get(), nullptr);
644}
645
646template <class _T1, class _D1>
647inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
648bool
649operator<(nullptr_t, const unique_ptr<_T1, _D1>& __x)
650{
651 typedef typename unique_ptr<_T1, _D1>::pointer _P1;
652 return less<_P1>()(nullptr, __x.get());
653}
654
655template <class _T1, class _D1>
656inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
657bool
658operator>(const unique_ptr<_T1, _D1>& __x, nullptr_t)
659{
660 return nullptr < __x;
661}
662
663template <class _T1, class _D1>
664inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
665bool
666operator>(nullptr_t, const unique_ptr<_T1, _D1>& __x)
667{
668 return __x < nullptr;
669}
670
671template <class _T1, class _D1>
672inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
673bool
674operator<=(const unique_ptr<_T1, _D1>& __x, nullptr_t)
675{
676 return !(nullptr < __x);
677}
678
679template <class _T1, class _D1>
680inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
681bool
682operator<=(nullptr_t, const unique_ptr<_T1, _D1>& __x)
683{
684 return !(__x < nullptr);
685}
686
687template <class _T1, class _D1>
688inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
689bool
690operator>=(const unique_ptr<_T1, _D1>& __x, nullptr_t)
691{
692 return !(__x < nullptr);
693}
694
695template <class _T1, class _D1>
696inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
697bool
698operator>=(nullptr_t, const unique_ptr<_T1, _D1>& __x)
699{
700 return !(nullptr < __x);
701}
702
703#if _LIBCPP_STD_VER14 > 11
704
705template<class _Tp>
706struct __unique_if
707{
708 typedef unique_ptr<_Tp> __unique_single;
709};
710
711template<class _Tp>
712struct __unique_if<_Tp[]>
713{
714 typedef unique_ptr<_Tp[]> __unique_array_unknown_bound;
715};
716
717template<class _Tp, size_t _Np>
718struct __unique_if<_Tp[_Np]>
719{
720 typedef void __unique_array_known_bound;
721};
722
723template<class _Tp, class... _Args>
724inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
725typename __unique_if<_Tp>::__unique_single
726make_unique(_Args&&... __args)
727{
728 return unique_ptr<_Tp>(new _Tp(_VSTDstd::__1::forward<_Args>(__args)...));
729}
730
731template<class _Tp>
732inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
733typename __unique_if<_Tp>::__unique_array_unknown_bound
734make_unique(size_t __n)
735{
736 typedef typename remove_extent<_Tp>::type _Up;
737 return unique_ptr<_Tp>(new _Up[__n]());
738}
739
740template<class _Tp, class... _Args>
741 typename __unique_if<_Tp>::__unique_array_known_bound
742 make_unique(_Args&&...) = delete;
743
744#endif // _LIBCPP_STD_VER > 11
745
746template <class _Tp> struct _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) hash;
747
748template <class _Tp, class _Dp>
749#ifdef _LIBCPP_CXX03_LANG
750struct _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) hash<unique_ptr<_Tp, _Dp> >
751#else
752struct _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) hash<__enable_hash_helper<
753 unique_ptr<_Tp, _Dp>, typename unique_ptr<_Tp, _Dp>::pointer> >
754#endif
755{
756#if _LIBCPP_STD_VER14 <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
757 _LIBCPP_DEPRECATED_IN_CXX17 typedef unique_ptr<_Tp, _Dp> argument_type;
758 _LIBCPP_DEPRECATED_IN_CXX17 typedef size_t result_type;
759#endif
760
761 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
762 size_t operator()(const unique_ptr<_Tp, _Dp>& __ptr) const
763 {
764 typedef typename unique_ptr<_Tp, _Dp>::pointer pointer;
765 return hash<pointer>()(__ptr.get());
766 }
767};
768
769_LIBCPP_END_NAMESPACE_STD} }
770
771_LIBCPP_POP_MACROSpop_macro("min") pop_macro("max")
772
773#endif // _LIBCPP___MEMORY_UNIQUE_PTR_H

/usr/include/c++/v1/__algorithm/sort.h

1//===----------------------------------------------------------------------===//
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#ifndef _LIBCPP___ALGORITHM_SORT_H
10#define _LIBCPP___ALGORITHM_SORT_H
11
12#include <__config>
13#include <__algorithm/comp.h>
14#include <__algorithm/comp_ref_type.h>
15#include <__algorithm/min_element.h>
16#include <__algorithm/partial_sort.h>
17#include <__algorithm/unwrap_iter.h>
18#include <__utility/swap.h>
19#include <memory>
20#include <type_traits> // swap
21
22#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
23#pragma GCC system_header
24#endif
25
26_LIBCPP_PUSH_MACROSpush_macro("min") push_macro("max")
27#include <__undef_macros>
28
29_LIBCPP_BEGIN_NAMESPACE_STDnamespace std { inline namespace __1 {
30
31// stable, 2-3 compares, 0-2 swaps
32
33template <class _Compare, class _ForwardIterator>
34_LIBCPP_CONSTEXPR_AFTER_CXX11constexpr unsigned
35__sort3(_ForwardIterator __x, _ForwardIterator __y, _ForwardIterator __z, _Compare __c)
36{
37 unsigned __r = 0;
38 if (!__c(*__y, *__x)) // if x <= y
39 {
40 if (!__c(*__z, *__y)) // if y <= z
41 return __r; // x <= y && y <= z
42 // x <= y && y > z
43 swap(*__y, *__z); // x <= z && y < z
44 __r = 1;
45 if (__c(*__y, *__x)) // if x > y
46 {
47 swap(*__x, *__y); // x < y && y <= z
48 __r = 2;
49 }
50 return __r; // x <= y && y < z
51 }
52 if (__c(*__z, *__y)) // x > y, if y > z
53 {
54 swap(*__x, *__z); // x < y && y < z
55 __r = 1;
56 return __r;
57 }
58 swap(*__x, *__y); // x > y && y <= z
59 __r = 1; // x < y && x <= z
60 if (__c(*__z, *__y)) // if y > z
61 {
62 swap(*__y, *__z); // x <= y && y < z
63 __r = 2;
64 }
65 return __r;
66} // x <= y && y <= z
67
68// stable, 3-6 compares, 0-5 swaps
69
70template <class _Compare, class _ForwardIterator>
71unsigned
72__sort4(_ForwardIterator __x1, _ForwardIterator __x2, _ForwardIterator __x3,
73 _ForwardIterator __x4, _Compare __c)
74{
75 unsigned __r = _VSTDstd::__1::__sort3<_Compare>(__x1, __x2, __x3, __c);
76 if (__c(*__x4, *__x3))
77 {
78 swap(*__x3, *__x4);
79 ++__r;
80 if (__c(*__x3, *__x2))
81 {
82 swap(*__x2, *__x3);
83 ++__r;
84 if (__c(*__x2, *__x1))
85 {
86 swap(*__x1, *__x2);
87 ++__r;
88 }
89 }
90 }
91 return __r;
92}
93
94// stable, 4-10 compares, 0-9 swaps
95
96template <class _Compare, class _ForwardIterator>
97_LIBCPP_HIDDEN__attribute__ ((__visibility__("hidden")))
98unsigned
99__sort5(_ForwardIterator __x1, _ForwardIterator __x2, _ForwardIterator __x3,
100 _ForwardIterator __x4, _ForwardIterator __x5, _Compare __c)
101{
102 unsigned __r = _VSTDstd::__1::__sort4<_Compare>(__x1, __x2, __x3, __x4, __c);
103 if (__c(*__x5, *__x4))
104 {
105 swap(*__x4, *__x5);
106 ++__r;
107 if (__c(*__x4, *__x3))
108 {
109 swap(*__x3, *__x4);
110 ++__r;
111 if (__c(*__x3, *__x2))
112 {
113 swap(*__x2, *__x3);
114 ++__r;
115 if (__c(*__x2, *__x1))
116 {
117 swap(*__x1, *__x2);
118 ++__r;
119 }
120 }
121 }
122 }
123 return __r;
124}
125
126// Assumes size > 0
127template <class _Compare, class _BidirectionalIterator>
128_LIBCPP_CONSTEXPR_AFTER_CXX11constexpr void
129__selection_sort(_BidirectionalIterator __first, _BidirectionalIterator __last, _Compare __comp)
130{
131 _BidirectionalIterator __lm1 = __last;
132 for (--__lm1; __first != __lm1; ++__first)
133 {
134 _BidirectionalIterator __i = _VSTDstd::__1::min_element<_BidirectionalIterator,
135 typename add_lvalue_reference<_Compare>::type>
136 (__first, __last, __comp);
137 if (__i != __first)
138 swap(*__first, *__i);
139 }
140}
141
142template <class _Compare, class _BidirectionalIterator>
143void
144__insertion_sort(_BidirectionalIterator __first, _BidirectionalIterator __last, _Compare __comp)
145{
146 typedef typename iterator_traits<_BidirectionalIterator>::value_type value_type;
147 if (__first != __last)
148 {
149 _BidirectionalIterator __i = __first;
150 for (++__i; __i != __last; ++__i)
151 {
152 _BidirectionalIterator __j = __i;
153 value_type __t(_VSTDstd::__1::move(*__j));
154 for (_BidirectionalIterator __k = __i; __k != __first && __comp(__t, *--__k); --__j)
155 *__j = _VSTDstd::__1::move(*__k);
156 *__j = _VSTDstd::__1::move(__t);
157 }
158 }
159}
160
161template <class _Compare, class _RandomAccessIterator>
162void
163__insertion_sort_3(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
164{
165 typedef typename iterator_traits<_RandomAccessIterator>::value_type value_type;
166 _RandomAccessIterator __j = __first+2;
167 _VSTDstd::__1::__sort3<_Compare>(__first, __first+1, __j, __comp);
168 for (_RandomAccessIterator __i = __j+1; __i != __last; ++__i)
169 {
170 if (__comp(*__i, *__j))
171 {
172 value_type __t(_VSTDstd::__1::move(*__i));
173 _RandomAccessIterator __k = __j;
174 __j = __i;
175 do
176 {
177 *__j = _VSTDstd::__1::move(*__k);
178 __j = __k;
179 } while (__j != __first && __comp(__t, *--__k));
180 *__j = _VSTDstd::__1::move(__t);
181 }
182 __j = __i;
183 }
184}
185
186template <class _Compare, class _RandomAccessIterator>
187bool
188__insertion_sort_incomplete(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
189{
190 switch (__last - __first)
191 {
192 case 0:
193 case 1:
194 return true;
195 case 2:
196 if (__comp(*--__last, *__first))
197 swap(*__first, *__last);
198 return true;
199 case 3:
200 _VSTDstd::__1::__sort3<_Compare>(__first, __first+1, --__last, __comp);
201 return true;
202 case 4:
203 _VSTDstd::__1::__sort4<_Compare>(__first, __first+1, __first+2, --__last, __comp);
204 return true;
205 case 5:
206 _VSTDstd::__1::__sort5<_Compare>(__first, __first+1, __first+2, __first+3, --__last, __comp);
207 return true;
208 }
209 typedef typename iterator_traits<_RandomAccessIterator>::value_type value_type;
210 _RandomAccessIterator __j = __first+2;
211 _VSTDstd::__1::__sort3<_Compare>(__first, __first+1, __j, __comp);
212 const unsigned __limit = 8;
213 unsigned __count = 0;
214 for (_RandomAccessIterator __i = __j+1; __i != __last; ++__i)
215 {
216 if (__comp(*__i, *__j))
217 {
218 value_type __t(_VSTDstd::__1::move(*__i));
219 _RandomAccessIterator __k = __j;
220 __j = __i;
221 do
222 {
223 *__j = _VSTDstd::__1::move(*__k);
224 __j = __k;
225 } while (__j != __first && __comp(__t, *--__k));
226 *__j = _VSTDstd::__1::move(__t);
227 if (++__count == __limit)
228 return ++__i == __last;
229 }
230 __j = __i;
231 }
232 return true;
233}
234
235template <class _Compare, class _BidirectionalIterator>
236void
237__insertion_sort_move(_BidirectionalIterator __first1, _BidirectionalIterator __last1,
238 typename iterator_traits<_BidirectionalIterator>::value_type* __first2, _Compare __comp)
239{
240 typedef typename iterator_traits<_BidirectionalIterator>::value_type value_type;
241 if (__first1 != __last1)
29
Assuming '__first1' is equal to '__last1'
30
Taking false branch
242 {
243 __destruct_n __d(0);
244 unique_ptr<value_type, __destruct_n&> __h(__first2, __d);
245 value_type* __last2 = __first2;
246 ::new ((void*)__last2) value_type(_VSTDstd::__1::move(*__first1));
247 __d.template __incr<value_type>();
248 for (++__last2; ++__first1 != __last1; ++__last2)
249 {
250 value_type* __j2 = __last2;
251 value_type* __i2 = __j2;
252 if (__comp(*__first1, *--__i2))
253 {
254 ::new ((void*)__j2) value_type(_VSTDstd::__1::move(*__i2));
255 __d.template __incr<value_type>();
256 for (--__j2; __i2 != __first2 && __comp(*__first1, *--__i2); --__j2)
257 *__j2 = _VSTDstd::__1::move(*__i2);
258 *__j2 = _VSTDstd::__1::move(*__first1);
259 }
260 else
261 {
262 ::new ((void*)__j2) value_type(_VSTDstd::__1::move(*__first1));
263 __d.template __incr<value_type>();
264 }
265 }
266 __h.release();
267 }
268}
269
270template <class _Compare, class _RandomAccessIterator>
271void
272__sort(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
273{
274 typedef typename iterator_traits<_RandomAccessIterator>::difference_type difference_type;
275 typedef typename iterator_traits<_RandomAccessIterator>::value_type value_type;
276 const difference_type __limit = is_trivially_copy_constructible<value_type>::value &&
277 is_trivially_copy_assignable<value_type>::value ? 30 : 6;
278 while (true)
279 {
280 __restart:
281 difference_type __len = __last - __first;
282 switch (__len)
283 {
284 case 0:
285 case 1:
286 return;
287 case 2:
288 if (__comp(*--__last, *__first))
289 swap(*__first, *__last);
290 return;
291 case 3:
292 _VSTDstd::__1::__sort3<_Compare>(__first, __first+1, --__last, __comp);
293 return;
294 case 4:
295 _VSTDstd::__1::__sort4<_Compare>(__first, __first+1, __first+2, --__last, __comp);
296 return;
297 case 5:
298 _VSTDstd::__1::__sort5<_Compare>(__first, __first+1, __first+2, __first+3, --__last, __comp);
299 return;
300 }
301 if (__len <= __limit)
302 {
303 _VSTDstd::__1::__insertion_sort_3<_Compare>(__first, __last, __comp);
304 return;
305 }
306 // __len > 5
307 _RandomAccessIterator __m = __first;
308 _RandomAccessIterator __lm1 = __last;
309 --__lm1;
310 unsigned __n_swaps;
311 {
312 difference_type __delta;
313 if (__len >= 1000)
314 {
315 __delta = __len/2;
316 __m += __delta;
317 __delta /= 2;
318 __n_swaps = _VSTDstd::__1::__sort5<_Compare>(__first, __first + __delta, __m, __m+__delta, __lm1, __comp);
319 }
320 else
321 {
322 __delta = __len/2;
323 __m += __delta;
324 __n_swaps = _VSTDstd::__1::__sort3<_Compare>(__first, __m, __lm1, __comp);
325 }
326 }
327 // *__m is median
328 // partition [__first, __m) < *__m and *__m <= [__m, __last)
329 // (this inhibits tossing elements equivalent to __m around unnecessarily)
330 _RandomAccessIterator __i = __first;
331 _RandomAccessIterator __j = __lm1;
332 // j points beyond range to be tested, *__m is known to be <= *__lm1
333 // The search going up is known to be guarded but the search coming down isn't.
334 // Prime the downward search with a guard.
335 if (!__comp(*__i, *__m)) // if *__first == *__m
336 {
337 // *__first == *__m, *__first doesn't go in first part
338 // manually guard downward moving __j against __i
339 while (true)
340 {
341 if (__i == --__j)
342 {
343 // *__first == *__m, *__m <= all other elements
344 // Parition instead into [__first, __i) == *__first and *__first < [__i, __last)
345 ++__i; // __first + 1
346 __j = __last;
347 if (!__comp(*__first, *--__j)) // we need a guard if *__first == *(__last-1)
348 {
349 while (true)
350 {
351 if (__i == __j)
352 return; // [__first, __last) all equivalent elements
353 if (__comp(*__first, *__i))
354 {
355 swap(*__i, *__j);
356 ++__n_swaps;
357 ++__i;
358 break;
359 }
360 ++__i;
361 }
362 }
363 // [__first, __i) == *__first and *__first < [__j, __last) and __j == __last - 1
364 if (__i == __j)
365 return;
366 while (true)
367 {
368 while (!__comp(*__first, *__i))
369 ++__i;
370 while (__comp(*__first, *--__j))
371 ;
372 if (__i >= __j)
373 break;
374 swap(*__i, *__j);
375 ++__n_swaps;
376 ++__i;
377 }
378 // [__first, __i) == *__first and *__first < [__i, __last)
379 // The first part is sorted, sort the second part
380 // _VSTD::__sort<_Compare>(__i, __last, __comp);
381 __first = __i;
382 goto __restart;
383 }
384 if (__comp(*__j, *__m))
385 {
386 swap(*__i, *__j);
387 ++__n_swaps;
388 break; // found guard for downward moving __j, now use unguarded partition
389 }
390 }
391 }
392 // It is known that *__i < *__m
393 ++__i;
394 // j points beyond range to be tested, *__m is known to be <= *__lm1
395 // if not yet partitioned...
396 if (__i < __j)
397 {
398 // known that *(__i - 1) < *__m
399 // known that __i <= __m
400 while (true)
401 {
402 // __m still guards upward moving __i
403 while (__comp(*__i, *__m))
404 ++__i;
405 // It is now known that a guard exists for downward moving __j
406 while (!__comp(*--__j, *__m))
407 ;
408 if (__i > __j)
409 break;
410 swap(*__i, *__j);
411 ++__n_swaps;
412 // It is known that __m != __j
413 // If __m just moved, follow it
414 if (__m == __i)
415 __m = __j;
416 ++__i;
417 }
418 }
419 // [__first, __i) < *__m and *__m <= [__i, __last)
420 if (__i != __m && __comp(*__m, *__i))
421 {
422 swap(*__i, *__m);
423 ++__n_swaps;
424 }
425 // [__first, __i) < *__i and *__i <= [__i+1, __last)
426 // If we were given a perfect partition, see if insertion sort is quick...
427 if (__n_swaps == 0)
428 {
429 bool __fs = _VSTDstd::__1::__insertion_sort_incomplete<_Compare>(__first, __i, __comp);
430 if (_VSTDstd::__1::__insertion_sort_incomplete<_Compare>(__i+1, __last, __comp))
431 {
432 if (__fs)
433 return;
434 __last = __i;
435 continue;
436 }
437 else
438 {
439 if (__fs)
440 {
441 __first = ++__i;
442 continue;
443 }
444 }
445 }
446 // sort smaller range with recursive call and larger with tail recursion elimination
447 if (__i - __first < __last - __i)
448 {
449 _VSTDstd::__1::__sort<_Compare>(__first, __i, __comp);
450 // _VSTD::__sort<_Compare>(__i+1, __last, __comp);
451 __first = ++__i;
452 }
453 else
454 {
455 _VSTDstd::__1::__sort<_Compare>(__i+1, __last, __comp);
456 // _VSTD::__sort<_Compare>(__first, __i, __comp);
457 __last = __i;
458 }
459 }
460}
461
462template <class _Compare, class _Tp>
463inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
464void
465__sort(_Tp** __first, _Tp** __last, __less<_Tp*>&)
466{
467 __less<uintptr_t> __comp;
468 _VSTDstd::__1::__sort<__less<uintptr_t>&, uintptr_t*>((uintptr_t*)__first, (uintptr_t*)__last, __comp);
469}
470
471_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<char>&, char*>(char*, char*, __less<char>&))extern template __attribute__ ((__visibility__("default"))) void
__sort<__less<char>&, char*>(char*, char*, __less
<char>&);
472_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<wchar_t>&, wchar_t*>(wchar_t*, wchar_t*, __less<wchar_t>&))extern template __attribute__ ((__visibility__("default"))) void
__sort<__less<wchar_t>&, wchar_t*>(wchar_t*,
wchar_t*, __less<wchar_t>&);
473_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<signed char>&, signed char*>(signed char*, signed char*, __less<signed char>&))extern template __attribute__ ((__visibility__("default"))) void
__sort<__less<signed char>&, signed char*>(signed
char*, signed char*, __less<signed char>&);
474_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<unsigned char>&, unsigned char*>(unsigned char*, unsigned char*, __less<unsigned char>&))extern template __attribute__ ((__visibility__("default"))) void
__sort<__less<unsigned char>&, unsigned char*>
(unsigned char*, unsigned char*, __less<unsigned char>&
);
475_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<short>&, short*>(short*, short*, __less<short>&))extern template __attribute__ ((__visibility__("default"))) void
__sort<__less<short>&, short*>(short*, short
*, __less<short>&);
476_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<unsigned short>&, unsigned short*>(unsigned short*, unsigned short*, __less<unsigned short>&))extern template __attribute__ ((__visibility__("default"))) void
__sort<__less<unsigned short>&, unsigned short*
>(unsigned short*, unsigned short*, __less<unsigned short
>&);
477_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<int>&, int*>(int*, int*, __less<int>&))extern template __attribute__ ((__visibility__("default"))) void
__sort<__less<int>&, int*>(int*, int*, __less
<int>&);
478_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<unsigned>&, unsigned*>(unsigned*, unsigned*, __less<unsigned>&))extern template __attribute__ ((__visibility__("default"))) void
__sort<__less<unsigned>&, unsigned*>(unsigned
*, unsigned*, __less<unsigned>&);
479_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<long>&, long*>(long*, long*, __less<long>&))extern template __attribute__ ((__visibility__("default"))) void
__sort<__less<long>&, long*>(long*, long*, __less
<long>&);
480_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<unsigned long>&, unsigned long*>(unsigned long*, unsigned long*, __less<unsigned long>&))extern template __attribute__ ((__visibility__("default"))) void
__sort<__less<unsigned long>&, unsigned long*>
(unsigned long*, unsigned long*, __less<unsigned long>&
);
481_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<long long>&, long long*>(long long*, long long*, __less<long long>&))extern template __attribute__ ((__visibility__("default"))) void
__sort<__less<long long>&, long long*>(long long
*, long long*, __less<long long>&);
482_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<unsigned long long>&, unsigned long long*>(unsigned long long*, unsigned long long*, __less<unsigned long long>&))extern template __attribute__ ((__visibility__("default"))) void
__sort<__less<unsigned long long>&, unsigned long
long*>(unsigned long long*, unsigned long long*, __less<
unsigned long long>&);
483_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<float>&, float*>(float*, float*, __less<float>&))extern template __attribute__ ((__visibility__("default"))) void
__sort<__less<float>&, float*>(float*, float
*, __less<float>&);
484_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<double>&, double*>(double*, double*, __less<double>&))extern template __attribute__ ((__visibility__("default"))) void
__sort<__less<double>&, double*>(double*, double
*, __less<double>&);
485_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS void __sort<__less<long double>&, long double*>(long double*, long double*, __less<long double>&))extern template __attribute__ ((__visibility__("default"))) void
__sort<__less<long double>&, long double*>(long
double*, long double*, __less<long double>&);
486
487_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<char>&, char*>(char*, char*, __less<char>&))extern template __attribute__ ((__visibility__("default"))) bool
__insertion_sort_incomplete<__less<char>&, char
*>(char*, char*, __less<char>&);
488_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<wchar_t>&, wchar_t*>(wchar_t*, wchar_t*, __less<wchar_t>&))extern template __attribute__ ((__visibility__("default"))) bool
__insertion_sort_incomplete<__less<wchar_t>&, wchar_t
*>(wchar_t*, wchar_t*, __less<wchar_t>&);
489_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<signed char>&, signed char*>(signed char*, signed char*, __less<signed char>&))extern template __attribute__ ((__visibility__("default"))) bool
__insertion_sort_incomplete<__less<signed char>&
, signed char*>(signed char*, signed char*, __less<signed
char>&);
490_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<unsigned char>&, unsigned char*>(unsigned char*, unsigned char*, __less<unsigned char>&))extern template __attribute__ ((__visibility__("default"))) bool
__insertion_sort_incomplete<__less<unsigned char>&
, unsigned char*>(unsigned char*, unsigned char*, __less<
unsigned char>&);
491_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<short>&, short*>(short*, short*, __less<short>&))extern template __attribute__ ((__visibility__("default"))) bool
__insertion_sort_incomplete<__less<short>&, short
*>(short*, short*, __less<short>&);
492_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<unsigned short>&, unsigned short*>(unsigned short*, unsigned short*, __less<unsigned short>&))extern template __attribute__ ((__visibility__("default"))) bool
__insertion_sort_incomplete<__less<unsigned short>&
, unsigned short*>(unsigned short*, unsigned short*, __less
<unsigned short>&);
493_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<int>&, int*>(int*, int*, __less<int>&))extern template __attribute__ ((__visibility__("default"))) bool
__insertion_sort_incomplete<__less<int>&, int*>
(int*, int*, __less<int>&);
494_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<unsigned>&, unsigned*>(unsigned*, unsigned*, __less<unsigned>&))extern template __attribute__ ((__visibility__("default"))) bool
__insertion_sort_incomplete<__less<unsigned>&, unsigned
*>(unsigned*, unsigned*, __less<unsigned>&);
495_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<long>&, long*>(long*, long*, __less<long>&))extern template __attribute__ ((__visibility__("default"))) bool
__insertion_sort_incomplete<__less<long>&, long
*>(long*, long*, __less<long>&);
496_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<unsigned long>&, unsigned long*>(unsigned long*, unsigned long*, __less<unsigned long>&))extern template __attribute__ ((__visibility__("default"))) bool
__insertion_sort_incomplete<__less<unsigned long>&
, unsigned long*>(unsigned long*, unsigned long*, __less<
unsigned long>&);
497_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<long long>&, long long*>(long long*, long long*, __less<long long>&))extern template __attribute__ ((__visibility__("default"))) bool
__insertion_sort_incomplete<__less<long long>&,
long long*>(long long*, long long*, __less<long long>
&);
498_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<unsigned long long>&, unsigned long long*>(unsigned long long*, unsigned long long*, __less<unsigned long long>&))extern template __attribute__ ((__visibility__("default"))) bool
__insertion_sort_incomplete<__less<unsigned long long>
&, unsigned long long*>(unsigned long long*, unsigned long
long*, __less<unsigned long long>&);
499_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<float>&, float*>(float*, float*, __less<float>&))extern template __attribute__ ((__visibility__("default"))) bool
__insertion_sort_incomplete<__less<float>&, float
*>(float*, float*, __less<float>&);
500_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<double>&, double*>(double*, double*, __less<double>&))extern template __attribute__ ((__visibility__("default"))) bool
__insertion_sort_incomplete<__less<double>&, double
*>(double*, double*, __less<double>&);
501_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS bool __insertion_sort_incomplete<__less<long double>&, long double*>(long double*, long double*, __less<long double>&))extern template __attribute__ ((__visibility__("default"))) bool
__insertion_sort_incomplete<__less<long double>&
, long double*>(long double*, long double*, __less<long
double>&);
502
503_LIBCPP_EXTERN_TEMPLATE(_LIBCPP_FUNC_VIS unsigned __sort5<__less<long double>&, long double*>(long double*, long double*, long double*, long double*, long double*, __less<long double>&))extern template __attribute__ ((__visibility__("default"))) unsigned
__sort5<__less<long double>&, long double*>(
long double*, long double*, long double*, long double*, long double
*, __less<long double>&);
504
505template <class _RandomAccessIterator, class _Compare>
506inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
_LIBCPP_CONSTEXPR_AFTER_CXX17
507void
508sort(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp)
509{
510 typedef typename __comp_ref_type<_Compare>::type _Comp_ref;
511 if (__libcpp_is_constant_evaluated()) {
512 _VSTDstd::__1::__partial_sort<_Comp_ref>(__first, __last, __last, _Comp_ref(__comp));
513 } else {
514 _VSTDstd::__1::__sort<_Comp_ref>(_VSTDstd::__1::__unwrap_iter(__first), _VSTDstd::__1::__unwrap_iter(__last), _Comp_ref(__comp));
515 }
516}
517
518template <class _RandomAccessIterator>
519inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
_LIBCPP_CONSTEXPR_AFTER_CXX17
520void
521sort(_RandomAccessIterator __first, _RandomAccessIterator __last)
522{
523 _VSTDstd::__1::sort(__first, __last, __less<typename iterator_traits<_RandomAccessIterator>::value_type>());
524}
525
526_LIBCPP_END_NAMESPACE_STD} }
527
528_LIBCPP_POP_MACROSpop_macro("min") pop_macro("max")
529
530#endif // _LIBCPP___ALGORITHM_SORT_H

/usr/src/gnu/usr.bin/clang/libclangSema/../../../llvm/clang/include/clang/Sema/CodeCompleteConsumer.h

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