-------------------------------------------------------------------------------- I1 cache: 65536 B, 64 B, 4-way associative D1 cache: 32768 B, 64 B, 8-way associative LL cache: 67108864 B, 64 B, 64-way associative Command: /usr/home/liquid/.rustup/toolchains/w-profiling/bin/rustc --crate-name serde_with_macros --edition=2018 src/lib.rs --error-format=json --json=diagnostic-rendered-ansi,artifacts,future-incompat --crate-type proc-macro --emit=dep-info,link -C prefer-dynamic -C embed-bitcode=no -C debuginfo=2 -C metadata=2a9675f58a1d187c -C extra-filename=-2a9675f58a1d187c --out-dir /usr/home/liquid/tmp/.tmpWM9VOE/target/debug/deps -L dependency=/usr/home/liquid/tmp/.tmpWM9VOE/target/debug/deps --extern darling=/usr/home/liquid/tmp/.tmpWM9VOE/target/debug/deps/libdarling-e50cbb3f4262f6e7.rlib --extern proc_macro2=/usr/home/liquid/tmp/.tmpWM9VOE/target/debug/deps/libproc_macro2-6a5da36f1567e87b.rlib --extern quote=/usr/home/liquid/tmp/.tmpWM9VOE/target/debug/deps/libquote-0435a7dc5b0bef76.rlib --extern syn=/usr/home/liquid/tmp/.tmpWM9VOE/target/debug/deps/libsyn-c8e2ca5c3bbe4c08.rlib --extern proc_macro -Adeprecated -Aunknown-lints -Zincremental-verify-ich Data file: results/cgout-w-profiling-serde_with_macros-1.5.1-Debug-Full Events recorded: Ir Events shown: Ir Event sort order: Ir Thresholds: 0.1 Include dirs: User annotated: Auto-annotation: on -------------------------------------------------------------------------------- Ir -------------------------------------------------------------------------------- 5,214,058,349 (100.0%) PROGRAM TOTALS -------------------------------------------------------------------------------- Ir file:function -------------------------------------------------------------------------------- 186,963,319 ( 3.59%) ???:llvm::FPPassManager::runOnFunction(llvm::Function&) 142,844,991 ( 2.74%) ???:llvm::SelectionDAG::Combine(llvm::CombineLevel, llvm::AAResults*, llvm::CodeGenOpt::Level) 127,272,696 ( 2.44%) ./malloc/malloc.c:_int_free 126,532,524 ( 2.43%) ./malloc/malloc.c:_int_malloc 86,984,039 ( 1.67%) ???:(anonymous namespace)::Verifier::visitMDNode(llvm::MDNode const&, (anonymous namespace)::Verifier::AreDebugLocsAllowed) 79,190,447 ( 1.52%) ./malloc/malloc.c:malloc 62,832,897 ( 1.21%) ???:llvm::AttributeList::addAttributes(llvm::LLVMContext&, unsigned int, llvm::AttrBuilder const&) const 53,276,393 ( 1.02%) ???:llvm::raw_svector_ostream::write_impl(char const*, unsigned long) 50,537,301 ( 0.97%) ???:llvm::SelectionDAGISel::SelectCodeCommon(llvm::SDNode*, unsigned char const*, unsigned int) 49,563,829 ( 0.95%) ???:(anonymous namespace)::Verifier::visitInstruction(llvm::Instruction&) 45,364,062 ( 0.87%) ???:llvm::FoldingSetNodeID::AddInteger(unsigned int) 44,690,153 ( 0.86%) ???:llvm::MachineInstr::addOperand(llvm::MachineFunction&, llvm::MachineOperand const&) 42,960,370 ( 0.82%) ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:__memcpy_avx_unaligned_erms 40,288,249 ( 0.77%) ???:(anonymous namespace)::RegAllocFast::allocateBasicBlock(llvm::MachineBasicBlock&) 40,158,750 ( 0.77%) ???:llvm::PMDataManager::verifyPreservedAnalysis(llvm::Pass*) 37,652,049 ( 0.72%) ./malloc/malloc.c:free 37,452,428 ( 0.72%) ???:llvm::MCObjectStreamer::emitBytes(llvm::StringRef) 36,365,839 ( 0.70%) ???:llvm::MCExpr::evaluateAsRelocatableImpl(llvm::MCValue&, llvm::MCAssembler const*, llvm::MCAsmLayout const*, llvm::MCFixup const*, llvm::DenseMap, llvm::detail::DenseMapPair > const*, bool) const 36,035,189 ( 0.69%) ./string/../sysdeps/x86_64/multiarch/memset-vec-unaligned-erms.S:__memset_avx2_erms 35,765,982 ( 0.69%) ???:llvm::MCAsmLayout::getSymbolOffset(llvm::MCSymbol const&) const 30,944,142 ( 0.59%) ???:llvm::ScheduleDAGSDNodes::BuildSchedUnits() 26,801,232 ( 0.51%) ???:llvm::StringMapImpl::LookupBucketFor(llvm::StringRef) 26,619,888 ( 0.51%) ???:llvm::TargetLoweringBase::getTypeConversion(llvm::LLVMContext&, llvm::EVT) const 24,118,720 ( 0.46%) ./elf/dl-lookup.c:_dl_lookup_symbol_x 23,709,343 ( 0.45%) ???:llvm::MDNode::MDNode(llvm::LLVMContext&, unsigned int, llvm::Metadata::StorageType, llvm::ArrayRef, llvm::ArrayRef) 22,868,842 ( 0.44%) ???:(anonymous namespace)::ELFObjectWriter::recordRelocation(llvm::MCAssembler&, llvm::MCAsmLayout const&, llvm::MCFragment const*, llvm::MCFixup const&, llvm::MCValue, unsigned long&) [clone .llvm.14145361893594770252] 22,278,766 ( 0.43%) ???:(anonymous namespace)::VarLocBasedLDV::process(llvm::MachineInstr&, (anonymous namespace)::VarLocBasedLDV::OpenRangesSet&, (anonymous namespace)::VarLocBasedLDV::VarLocMap&, llvm::SmallVector<(anonymous namespace)::VarLocBasedLDV::TransferDebugPair, 4u>&) 21,106,460 ( 0.40%) ???:llvm::FoldingSetBase::FindNodeOrInsertPos(llvm::FoldingSetNodeID const&, void*&, llvm::FoldingSetBase::FoldingSetInfo const&) 20,505,652 ( 0.39%) ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:__memcpy_sse2_unaligned_erms 20,254,732 ( 0.39%) ???:llvm::InstrEmitter::EmitMachineNode(llvm::SDNode*, bool, bool, llvm::DenseMap, llvm::detail::DenseMapPair >&) 20,214,140 ( 0.39%) ./string/../sysdeps/x86_64/multiarch/memcmp-avx2-movbe.S:__memcmp_avx2_movbe 19,916,954 ( 0.38%) ???:llvm::MDString::get(llvm::LLVMContext&, llvm::StringRef) 19,857,218 ( 0.38%) ???:llvm::SelectionDAG::MorphNodeTo(llvm::SDNode*, unsigned int, llvm::SDVTList, llvm::ArrayRef) 19,464,227 ( 0.37%) ???:llvm::hashing::detail::hash_combine_recursive_helper::combine(unsigned long, char*, char*) 18,817,714 ( 0.36%) ???:char* llvm::hashing::detail::hash_combine_recursive_helper::combine_data(unsigned long&, char*, char*, llvm::Metadata*) 18,779,285 ( 0.36%) ???:llvm::DAGTypeLegalizer::run() 18,545,645 ( 0.36%) ???:(anonymous namespace)::SelectionDAGLegalize::LegalizeOp(llvm::SDNode*) [clone .llvm.8386621111310650999] 18,490,216 ( 0.35%) ./malloc/malloc.c:malloc_consolidate 18,265,218 ( 0.35%) ???:(anonymous namespace)::Verifier::visitCallBase(llvm::CallBase&) 17,816,243 ( 0.34%) ./elf/dl-lookup.c:do_lookup_x 17,694,957 ( 0.34%) ???:llvm::MCAsmLayout::getFragmentOffset(llvm::MCFragment const*) const 17,667,171 ( 0.34%) ???:(anonymous namespace)::Verifier::verifyFunctionAttrs(llvm::FunctionType*, llvm::AttributeList, llvm::Value const*, bool) 16,781,700 ( 0.32%) ???:(anonymous namespace)::TwoAddressInstructionPass::runOnMachineFunction(llvm::MachineFunction&) 16,713,080 ( 0.32%) ???:llvm::SelectionDAG::getConstant(llvm::ConstantInt const&, llvm::SDLoc const&, llvm::EVT, bool, bool) 16,149,054 ( 0.31%) ???:llvm::TargetRegisterInfo::shouldRealignStack(llvm::MachineFunction const&) const 15,879,966 ( 0.30%) ???:llvm::SelectionDAG::Legalize() 15,797,812 ( 0.30%) ???:llvm::SmallSet >::insert(llvm::Register const&) 15,601,308 ( 0.30%) ???:llvm::TargetRegisterInfo::checkAllSuperRegsMarked(llvm::BitVector const&, llvm::ArrayRef) const 15,583,458 ( 0.30%) ???:llvm::MDNodeKeyImpl::MDNodeKeyImpl(llvm::DICompositeType const*) 15,547,533 ( 0.30%) ???:llvm::coro::declaresIntrinsics(llvm::Module const&, std::initializer_list) 15,298,560 ( 0.29%) ???:llvm::MetadataTracking::track(void*, llvm::Metadata&, llvm::PointerUnion) 14,827,680 ( 0.28%) ./malloc/malloc.c:unlink_chunk.constprop.0 14,567,354 ( 0.28%) ???:(anonymous namespace)::X86MCCodeEmitter::emitPrefixImpl(unsigned int&, llvm::MCInst const&, llvm::MCSubtargetInfo const&, llvm::raw_ostream&) const 14,284,772 ( 0.27%) ???:(anonymous namespace)::Verifier::verify(llvm::Function const&) [clone .llvm.4153962086227604281] 14,108,114 ( 0.27%) ???:(anonymous namespace)::DAGCombiner::combine(llvm::SDNode*) 14,094,720 ( 0.27%) ./string/../sysdeps/x86_64/multiarch/strcmp-avx2.S:__strncmp_avx2 14,016,188 ( 0.27%) ???:(anonymous namespace)::VarLocBasedLDV::ExtendRanges(llvm::MachineFunction&, llvm::TargetPassConfig*) [clone .llvm.4451506318407214204] 13,879,599 ( 0.27%) ???:(anonymous namespace)::ScheduleDAGRRList::Schedule() [clone .llvm.6953762222372402862] 13,770,162 ( 0.26%) ???:llvm::calculateDbgEntityHistory(llvm::MachineFunction const*, llvm::TargetRegisterInfo const*, llvm::DbgValueHistoryMap&, llvm::DbgLabelInstrMap&) 13,606,644 ( 0.26%) ???:llvm::DIEAbbrev::Profile(llvm::FoldingSetNodeID&) const 13,340,700 ( 0.26%) ???:llvm::MCStreamer::emitULEB128IntValue(unsigned long, unsigned int) 13,295,888 ( 0.26%) ???:llvm::BumpPtrAllocatorImpl::Allocate(unsigned long, llvm::Align) 13,268,866 ( 0.25%) ???:llvm::MDString* llvm::DINode::getOperandAs(unsigned int) const 13,121,616 ( 0.25%) ???:multikeySort(llvm::MutableArrayRef*>, int) 13,054,797 ( 0.25%) ???:llvm::MCAssembler::layout(llvm::MCAsmLayout&) 12,390,812 ( 0.24%) ???:llvm::MCContext::getOrCreateSymbol(llvm::Twine const&) 12,272,665 ( 0.24%) ???:llvm::DomTreeBuilder::SemiNCAInfo >::CalculateFromScratch(llvm::DominatorTreeBase&, llvm::DomTreeBuilder::SemiNCAInfo >::BatchUpdateInfo*) 11,472,441 ( 0.22%) ???:llvm::raw_ostream::write(char const*, unsigned long) 11,190,321 ( 0.21%) ???:(anonymous namespace)::PEI::runOnMachineFunction(llvm::MachineFunction&) 11,097,979 ( 0.21%) ???:(anonymous namespace)::ELFWriter::writeObject(llvm::MCAssembler&, llvm::MCAsmLayout const&) 10,608,235 ( 0.20%) ???:bool llvm::DenseMapBase, llvm::detail::DenseSetPair >, llvm::DICompositeType*, llvm::detail::DenseSetEmpty, llvm::MDNodeInfo, llvm::detail::DenseSetPair >::LookupBucketFor(llvm::DICompositeType* const&, llvm::detail::DenseSetPair const*&) const 10,592,689 ( 0.20%) ???:llvm::FoldingSet::NodeEquals(llvm::FoldingSetBase const*, llvm::FoldingSetBase::Node*, llvm::FoldingSetNodeID const&, unsigned int, llvm::FoldingSetNodeID&) 10,584,497 ( 0.20%) ???:(anonymous namespace)::X86AsmBackend::applyFixup(llvm::MCAssembler const&, llvm::MCFixup const&, llvm::MCValue const&, llvm::MutableArrayRef, unsigned long, bool, llvm::MCSubtargetInfo const*) const 10,554,867 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe/macro_parser.rs:rustc_expand::mbe::macro_parser::parse_tt 10,518,586 ( 0.20%) ???:llvm::ScheduleDAGSDNodes::AddSchedEdges() 10,467,368 ( 0.20%) ???:llvm::MDTuple::getImpl(llvm::LLVMContext&, llvm::ArrayRef, llvm::Metadata::StorageType, bool) 10,277,451 ( 0.20%) ???:llvm::LLVMContextImpl::~LLVMContextImpl() 10,093,961 ( 0.19%) ???:llvm::MDNode::dropAllReferences() 10,068,731 ( 0.19%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, (), core::hash::BuildHasherDefault>>::from_hash::>::{closure#0}> 10,045,193 ( 0.19%) ???:llvm::DIEValueList::addValue(llvm::BumpPtrAllocatorImpl&, llvm::DIEValue const&) 9,763,757 ( 0.19%) ???:llvm::SelectionDAG::AssignTopologicalOrder() 9,510,751 ( 0.18%) ???:(anonymous namespace)::X86MCInstLower::Lower(llvm::MachineInstr const*, llvm::MCInst&) const 9,506,174 ( 0.18%) ./stdlib/msort.c:msort_with_tmp.part.0 9,486,712 ( 0.18%) ???:llvm::MCObjectStreamer::emitValueImpl(llvm::MCExpr const*, unsigned int, llvm::SMLoc) 9,023,353 ( 0.17%) ???:(anonymous namespace)::X86MCCodeEmitter::encodeInstruction(llvm::MCInst const&, llvm::raw_ostream&, llvm::SmallVectorImpl&, llvm::MCSubtargetInfo const&) const 9,014,630 ( 0.17%) ???:llvm::DwarfDebug::beginInstruction(llvm::MachineInstr const*) 8,995,841 ( 0.17%) ???:llvm::AttributeSetNode::get(llvm::LLVMContext&, llvm::AttrBuilder const&) 8,670,152 ( 0.17%) ???:llvm::SelectionDAG::getRegister(unsigned int, llvm::EVT) 8,410,233 ( 0.16%) ???:llvm::X86FrameLowering::hasFP(llvm::MachineFunction const&) const 8,331,202 ( 0.16%) ???:llvm::PMDataManager::removeNotPreservedAnalysis(llvm::Pass*) 8,291,619 ( 0.16%) ???:llvm::FunctionLoweringInfo::set(llvm::Function const&, llvm::MachineFunction&, llvm::SelectionDAG*) 8,278,421 ( 0.16%) ???:llvm::MachineFunction::CreateMachineInstr(llvm::MCInstrDesc const&, llvm::DebugLoc const&, bool) 8,085,138 ( 0.16%) ???:(anonymous namespace)::Verifier::visitFunction(llvm::Function const&)::$_3::operator()(llvm::Instruction const&, llvm::MDNode const*) const 8,069,193 ( 0.15%) /tmp/gcc-build/x86_64-unknown-linux-gnu/libstdc++-v3/libsupc++/../../../../gcc-5.5.0/libstdc++-v3/libsupc++/new_op.cc:operator new(unsigned long) 8,050,937 ( 0.15%) ???:llvm::Twine::printOneChild(llvm::raw_ostream&, llvm::Twine::Child, llvm::Twine::NodeKind) const 8,007,049 ( 0.15%) ???:llvm::MCELFStreamer::emitLabel(llvm::MCSymbol*, llvm::SMLoc) 7,988,866 ( 0.15%) ???:llvm::DIE::generateAbbrev() const 7,825,064 ( 0.15%) ???:llvm::DIEInteger::SizeOf(llvm::AsmPrinter const*, llvm::dwarf::Form) const 7,763,166 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/mod.rs:::lookup_source_file_idx 7,733,732 ( 0.15%) ???:llvm::DataLayout::getAlignment(llvm::Type*, bool) const 7,728,241 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::bump 7,724,331 ( 0.15%) ./malloc/malloc.c:realloc 7,705,659 ( 0.15%) ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:memcpy@GLIBC_2.2.5 7,669,816 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::next 7,590,528 ( 0.15%) ???:llvm::FoldingSet::NodeEquals(llvm::FoldingSetBase const*, llvm::FoldingSetBase::Node*, llvm::FoldingSetNodeID const&, unsigned int, llvm::FoldingSetNodeID&) 7,551,298 ( 0.14%) ./string/../sysdeps/x86_64/multiarch/memset-vec-unaligned-erms.S:__memset_avx2_unaligned_erms 7,387,316 ( 0.14%) ???:(anonymous namespace)::RegAllocFast::markRegUsedInInstr(unsigned short) 7,358,809 ( 0.14%) ???:llvm::SmallPtrSetImplBase::insert_imp_big(void const*) 7,354,334 ( 0.14%) ???:llvm::SelectionDAGISel::SelectAllBasicBlocks(llvm::Function const&) 7,349,305 ( 0.14%) ???:llvm::ScheduleDAGSDNodes::EmitSchedule(llvm::MachineInstrBundleIterator&) 7,347,238 ( 0.14%) ???:llvm::hash_code llvm::hashing::detail::hash_combine_recursive_helper::combine(unsigned long, char*, char*, llvm::Metadata* const&, unsigned int const&, llvm::Metadata* const&, llvm::Metadata* const&, llvm::Metadata* const&, llvm::Metadata* const&) 7,340,609 ( 0.14%) ???:(anonymous namespace)::CFIInstrInserter::runOnMachineFunction(llvm::MachineFunction&) 7,191,783 ( 0.14%) ???:llvm::X86TargetMachine::getTargetTransformInfo(llvm::Function const&) 7,179,042 ( 0.14%) ???:llvm::SelectionDAG::getNode(unsigned int, llvm::SDLoc const&, llvm::SDVTList, llvm::ArrayRef) 7,113,966 ( 0.14%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs:rustc_expand::mbe::macro_parser::parse_tt 7,094,455 ( 0.14%) ???:(anonymous namespace)::X86AsmBackend::getFixupKindInfo(llvm::MCFixupKind) const 7,005,506 ( 0.13%) ???:llvm::hash_code llvm::hashing::detail::hash_combine_recursive_helper::combine(unsigned long, char*, char*, llvm::Metadata* const&, llvm::Metadata* const&, llvm::Metadata* const&, llvm::Metadata* const&) 6,994,031 ( 0.13%) ???:??? 6,937,845 ( 0.13%) ???:(anonymous namespace)::VectorLegalizer::LegalizeOp(llvm::SDValue) [clone .llvm.3993696295502019106] 6,848,527 ( 0.13%) ???:(anonymous namespace)::VarLocBasedLDV::collectIDsForRegs(llvm::SmallSet >&, llvm::SmallSet > const&, llvm::CoalescingBitVector const&, (anonymous namespace)::VarLocBasedLDV::VarLocMap const&) 6,839,809 ( 0.13%) ???:llvm::DwarfUnit::addDIEEntry(llvm::DIE&, llvm::dwarf::Attribute, llvm::DIEEntry) 6,774,064 ( 0.13%) ???:bool llvm::DenseMapBase, llvm::detail::DenseSetPair >, llvm::DICompositeType*, llvm::detail::DenseSetEmpty, llvm::MDNodeInfo, llvm::detail::DenseSetPair >::LookupBucketFor >(llvm::MDNodeKeyImpl const&, llvm::detail::DenseSetPair const*&) const 6,761,198 ( 0.13%) ???:llvm::AsmPrinter::emitFunctionBody() 6,743,411 ( 0.13%) ???:llvm::DIE::computeOffsetsAndAbbrevs(llvm::AsmPrinter const*, llvm::DIEAbbrevSet&, unsigned int) 6,542,956 ( 0.13%) ???:llvm::AsmPrinter::emitDwarfDIE(llvm::DIE const&) const 6,403,524 ( 0.12%) ???:llvm::MCELFStreamer::emitInstToData(llvm::MCInst const&, llvm::MCSubtargetInfo const&) 6,267,847 ( 0.12%) ???:llvm::DomTreeBuilder::SemiNCAInfo >::runSemiNCA(llvm::DominatorTreeBase&, unsigned int) 6,170,944 ( 0.12%) ???:llvm::MCStreamer::emitIntValue(unsigned long, unsigned int) 6,027,246 ( 0.12%) ???:llvm::SelectionDAG::clear() 6,026,433 ( 0.12%) ???:(anonymous namespace)::X86MCCodeEmitter::emitMemModRMByte(llvm::MCInst const&, unsigned int, unsigned int, unsigned long, bool, unsigned long, llvm::raw_ostream&, llvm::SmallVectorImpl&, llvm::MCSubtargetInfo const&, bool) const 5,910,786 ( 0.11%) ???:llvm::X86RegisterInfo::eliminateFrameIndex(llvm::MachineInstrBundleIterator, int, unsigned int, llvm::RegScavenger*) const 5,861,075 ( 0.11%) ???:bool llvm::DenseMapBase, llvm::detail::DenseSetPair >, llvm::DIDerivedType*, llvm::detail::DenseSetEmpty, llvm::MDNodeInfo, llvm::detail::DenseSetPair >::LookupBucketFor(llvm::DIDerivedType* const&, llvm::detail::DenseSetPair const*&) const 5,797,975 ( 0.11%) ???:llvm::MachineFunctionPass::runOnFunction(llvm::Function&) 5,722,159 ( 0.11%) ???:llvm::TargetLowering::SimplifyDemandedBits(llvm::SDValue, llvm::APInt const&, llvm::APInt const&, llvm::KnownBits&, llvm::TargetLowering::TargetLoweringOpt&, unsigned int, bool) const 5,718,497 ( 0.11%) ???:llvm::DwarfUnit::getDIE(llvm::DINode const*) const 5,712,725 ( 0.11%) ???:llvm::MCObjectStreamer::emitInstruction(llvm::MCInst const&, llvm::MCSubtargetInfo const&) 5,677,066 ( 0.11%) ???:llvm::CoalescingBitVector::find(unsigned long) const 5,644,089 ( 0.11%) ???:llvm::hash_code llvm::hashing::detail::hash_combine_recursive_helper::combine(unsigned long, char*, char*, llvm::Metadata* const&, llvm::Metadata* const&) 5,599,780 ( 0.11%) ???:llvm::MCSymbolRefExpr::create(llvm::MCSymbol const*, llvm::MCSymbolRefExpr::VariantKind, llvm::MCContext&, llvm::SMLoc) 5,572,794 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/tokenstream.rs:::next_with_spacing 5,547,546 ( 0.11%) ???:llvm::hashing::detail::hash_combine_recursive_helper::hash_combine_recursive_helper() 5,542,025 ( 0.11%) ???:llvm::MCAssembler::layoutSectionOnce(llvm::MCAsmLayout&, llvm::MCSection&) 5,468,808 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/library/std/src/sys/unix/alloc.rs:__rdl_alloc 5,468,078 ( 0.10%) ./elf/../sysdeps/x86_64/dl-machine.h:_dl_relocate_object 5,437,678 ( 0.10%) ./malloc/malloc.c:_int_realloc 5,385,550 ( 0.10%) ???:llvm::SelectionDAG::getNode(unsigned int, llvm::SDLoc const&, llvm::EVT, llvm::SDValue, llvm::SDValue, llvm::SDNodeFlags) 5,346,349 ( 0.10%) ???:llvm::DwarfUnit::addString(llvm::DIE&, llvm::dwarf::Attribute, llvm::StringRef) 5,340,492 ( 0.10%) ???:llvm::MCDwarfLineAddr::Encode(llvm::MCContext&, llvm::MCDwarfLineTableParams, long, unsigned long, llvm::raw_ostream&) 5,248,105 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/subst.rs:::fold_ty -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/std/src/sys/unix/alloc.rs -------------------------------------------------------------------------------- Ir -- line 5 ---------------------------------------- . #[stable(feature = "alloc_system_type", since = "1.28.0")] . unsafe impl GlobalAlloc for System { . #[inline] . unsafe fn alloc(&self, layout: Layout) -> *mut u8 { . // jemalloc provides alignment less than MIN_ALIGN for small allocations. . // So only rely on MIN_ALIGN if size >= align. . // Also see and . // . 3,125,028 ( 0.06%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 2,343,768 ( 0.04%) libc::malloc(layout.size()) as *mut u8 . } else { . #[cfg(target_os = "macos")] . { . if layout.align() > (1 << 31) { . return ptr::null_mut(); . } . } . aligned_malloc(&layout) . } . } . . #[inline] . unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { . // See the comment above in `alloc` for why this check looks the way it does. 71,624 ( 0.00%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 107,436 ( 0.00%) libc::calloc(layout.size(), 1) as *mut u8 . } else { . let ptr = self.alloc(layout); . if !ptr.is_null() { . ptr::write_bytes(ptr, 0, layout.size()); . } . ptr . } . } . . #[inline] . unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) { 799,151 ( 0.02%) libc::free(ptr as *mut libc::c_void) . } . . #[inline] . unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { 297,212 ( 0.01%) if layout.align() <= MIN_ALIGN && layout.align() <= new_size { 594,424 ( 0.01%) libc::realloc(ptr as *mut libc::c_void, new_size) as *mut u8 . } else { . realloc_fallback(self, ptr, layout, new_size) . } . } . } . . cfg_if::cfg_if! { . if #[cfg(any( -- line 56 ---------------------------------------- -- line 84 ---------------------------------------- . } else if #[cfg(target_os = "wasi")] { . #[inline] . unsafe fn aligned_malloc(layout: &Layout) -> *mut u8 { . libc::aligned_alloc(layout.align(), layout.size()) as *mut u8 . } . } else { . #[inline] . unsafe fn aligned_malloc(layout: &Layout) -> *mut u8 { 2 ( 0.00%) let mut out = ptr::null_mut(); . // posix_memalign requires that the alignment be a multiple of `sizeof(void*)`. . // Since these are all powers of 2, we can just use max. . let align = layout.align().max(crate::mem::size_of::()); 4 ( 0.00%) let ret = libc::posix_memalign(&mut out, align, layout.size()); 4 ( 0.00%) if ret != 0 { ptr::null_mut() } else { out as *mut u8 } . } . } . } 2 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/mod.rs -------------------------------------------------------------------------------- Ir -- line 118 ---------------------------------------- . /// let a = [1, 2, 3]; . /// assert_eq!(a.len(), 3); . /// ``` . #[lang = "slice_len_fn"] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_slice_len", since = "1.39.0")] . #[inline] . // SAFETY: const sound because we transmute out the length field as a usize (which it must be) 1,974 ( 0.00%) pub const fn len(&self) -> usize { . // FIXME: Replace with `crate::ptr::metadata(self)` when that is const-stable. . // As of this writing this causes a "Const-stable functions can only call other . // const-stable functions" error. . . // SAFETY: Accessing the value from the `PtrRepr` union is safe since *const T . // and PtrComponents have the same memory layouts. Only std can make this . // guarantee. 1,974 ( 0.00%) unsafe { crate::ptr::PtrRepr { const_ptr: self }.components.metadata } 1,316 ( 0.00%) } . . /// Returns `true` if the slice has a length of 0. . /// . /// # Examples . /// . /// ``` . /// let a = [1, 2, 3]; . /// assert!(!a.is_empty()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_slice_is_empty", since = "1.39.0")] . #[inline] . pub const fn is_empty(&self) -> bool { 517,568 ( 0.01%) self.len() == 0 . } . . /// Returns the first element of the slice, or `None` if it is empty. . /// . /// # Examples . /// . /// ``` . /// let v = [10, 40, 30]; -- line 157 ---------------------------------------- -- line 159 ---------------------------------------- . /// . /// let w: &[i32] = &[]; . /// assert_eq!(None, w.first()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")] . #[inline] . pub const fn first(&self) -> Option<&T> { 1,545 ( 0.00%) if let [first, ..] = self { Some(first) } else { None } . } . . /// Returns a mutable pointer to the first element of the slice, or `None` if it is empty. . /// . /// # Examples . /// . /// ``` . /// let x = &mut [0, 1, 2]; -- line 175 ---------------------------------------- -- line 178 ---------------------------------------- . /// *first = 5; . /// } . /// assert_eq!(x, &[5, 1, 2]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")] . #[inline] . pub const fn first_mut(&mut self) -> Option<&mut T> { 720 ( 0.00%) if let [first, ..] = self { Some(first) } else { None } . } . . /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty. . /// . /// # Examples . /// . /// ``` . /// let x = &[0, 1, 2]; -- line 194 ---------------------------------------- -- line 237 ---------------------------------------- . /// assert_eq!(last, &2); . /// assert_eq!(elements, &[0, 1]); . /// } . /// ``` . #[stable(feature = "slice_splits", since = "1.5.0")] . #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")] . #[inline] . pub const fn split_last(&self) -> Option<(&T, &[T])> { 10,040 ( 0.00%) if let [init @ .., last] = self { Some((last, init)) } else { None } . } . . /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty. . /// . /// # Examples . /// . /// ``` . /// let x = &mut [0, 1, 2]; -- line 253 ---------------------------------------- -- line 276 ---------------------------------------- . /// . /// let w: &[i32] = &[]; . /// assert_eq!(None, w.last()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")] . #[inline] . pub const fn last(&self) -> Option<&T> { 149,382 ( 0.00%) if let [.., last] = self { Some(last) } else { None } . } . . /// Returns a mutable pointer to the last item in the slice. . /// . /// # Examples . /// . /// ``` . /// let x = &mut [0, 1, 2]; -- line 292 ---------------------------------------- -- line 295 ---------------------------------------- . /// *last = 10; . /// } . /// assert_eq!(x, &[0, 1, 10]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")] . #[inline] . pub const fn last_mut(&mut self) -> Option<&mut T> { 571,300 ( 0.01%) if let [.., last] = self { Some(last) } else { None } . } . . /// Returns a reference to an element or subslice depending on the type of . /// index. . /// . /// - If given a position, returns a reference to the element at that . /// position or `None` if out of bounds. . /// - If given a range, returns the subslice corresponding to that range, -- line 311 ---------------------------------------- -- line 317 ---------------------------------------- . /// let v = [10, 40, 30]; . /// assert_eq!(Some(&40), v.get(1)); . /// assert_eq!(Some(&[10, 40][..]), v.get(0..2)); . /// assert_eq!(None, v.get(3)); . /// assert_eq!(None, v.get(0..4)); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] 1,440 ( 0.00%) pub fn get(&self, index: I) -> Option<&I::Output> . where . I: SliceIndex, . { 360 ( 0.00%) index.get(self) 360 ( 0.00%) } . . /// Returns a mutable reference to an element or subslice depending on the . /// type of index (see [`get`]) or `None` if the index is out of bounds. . /// . /// [`get`]: slice::get . /// . /// # Examples . /// -- line 338 ---------------------------------------- -- line 408 ---------------------------------------- . /// unsafe { . /// let elem = x.get_unchecked_mut(1); . /// *elem = 13; . /// } . /// assert_eq!(x, &[1, 13, 4]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] 24 ( 0.00%) pub unsafe fn get_unchecked_mut(&mut self, index: I) -> &mut I::Output . where . I: SliceIndex, . { . // SAFETY: the caller must uphold the safety requirements for `get_unchecked_mut`; . // the slice is dereferenceable because `self` is a safe reference. . // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is. 9 ( 0.00%) unsafe { &mut *index.get_unchecked_mut(self) } 6 ( 0.00%) } . . /// Returns a raw pointer to the slice's buffer. . /// . /// The caller must ensure that the slice outlives the pointer this . /// function returns, or else it will end up pointing to garbage. . /// . /// The caller must also ensure that the memory the pointer (non-transitively) points to . /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer -- line 432 ---------------------------------------- -- line 447 ---------------------------------------- . /// } . /// } . /// ``` . /// . /// [`as_mut_ptr`]: slice::as_mut_ptr . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_slice_as_ptr", since = "1.32.0")] . #[inline] 26,420 ( 0.00%) pub const fn as_ptr(&self) -> *const T { 695,287 ( 0.01%) self as *const [T] as *const T 13,210 ( 0.00%) } . . /// Returns an unsafe mutable pointer to the slice's buffer. . /// . /// The caller must ensure that the slice outlives the pointer this . /// function returns, or else it will end up pointing to garbage. . /// . /// Modifying the container referenced by this slice may cause its buffer . /// to be reallocated, which would also make any pointers to it invalid. -- line 465 ---------------------------------------- -- line 475 ---------------------------------------- . /// *x_ptr.add(i) += 2; . /// } . /// } . /// assert_eq!(x, &[3, 4, 6]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")] . #[inline] 16 ( 0.00%) pub const fn as_mut_ptr(&mut self) -> *mut T { 2 ( 0.00%) self as *mut [T] as *mut T 8 ( 0.00%) } . . /// Returns the two raw pointers spanning the slice. . /// . /// The returned range is half-open, which means that the end pointer . /// points *one past* the last element of the slice. This way, an empty . /// slice is represented by two equal pointers, and the difference between . /// the two pointers represents the size of the slice. . /// -- line 493 ---------------------------------------- -- line 582 ---------------------------------------- . /// v.swap(2, 4); . /// assert!(v == ["a", "b", "e", "d", "c"]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_swap", issue = "83163")] . #[inline] . #[track_caller] . pub const fn swap(&mut self, a: usize, b: usize) { 24,344 ( 0.00%) let _ = &self[a]; 41,715 ( 0.00%) let _ = &self[b]; . . // SAFETY: we just checked that both `a` and `b` are in bounds . unsafe { self.swap_unchecked(a, b) } . } . . /// Swaps two elements in the slice, without doing bounds checking. . /// . /// For a safe alternative see [`swap`]. -- line 599 ---------------------------------------- -- line 677 ---------------------------------------- . . // Because this function is first compiled in isolation, . // this check tells LLVM that the indexing below is . // in-bounds. Then after inlining -- once the actual . // lengths of the slices are known -- it's removed. . let (a, b) = (&mut a[..n], &mut b[..n]); . . for i in 0..n { 8,905 ( 0.00%) mem::swap(&mut a[i], &mut b[n - 1 - i]); . } . } . } . . /// Returns an iterator over the slice. . /// . /// # Examples . /// -- line 693 ---------------------------------------- -- line 697 ---------------------------------------- . /// . /// assert_eq!(iterator.next(), Some(&1)); . /// assert_eq!(iterator.next(), Some(&2)); . /// assert_eq!(iterator.next(), Some(&4)); . /// assert_eq!(iterator.next(), None); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] 8,055 ( 0.00%) pub fn iter(&self) -> Iter<'_, T> { 8,055 ( 0.00%) Iter::new(self) 5,370 ( 0.00%) } . . /// Returns an iterator that allows modifying each value. . /// . /// # Examples . /// . /// ``` . /// let x = &mut [1, 2, 4]; . /// for elem in x.iter_mut() { -- line 715 ---------------------------------------- -- line 1499 ---------------------------------------- . /// assert_eq!(left, [1, 2, 3, 4, 5, 6]); . /// assert_eq!(right, []); . /// } . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . #[track_caller] . pub fn split_at(&self, mid: usize) -> (&[T], &[T]) { 330 ( 0.00%) assert!(mid <= self.len()); . // SAFETY: `[ptr; mid]` and `[mid; len]` are inside `self`, which . // fulfills the requirements of `from_raw_parts_mut`. . unsafe { self.split_at_unchecked(mid) } . } . . /// Divides one mutable slice into two at an index. . /// . /// The first will contain all indices from `[0, mid)` (excluding -- line 1515 ---------------------------------------- -- line 1530 ---------------------------------------- . /// left[1] = 2; . /// right[1] = 4; . /// assert_eq!(v, [1, 2, 3, 4, 5, 6]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . #[track_caller] . pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) { 24,506 ( 0.00%) assert!(mid <= self.len()); . // SAFETY: `[ptr; mid]` and `[mid; len]` are inside `self`, which . // fulfills the requirements of `from_raw_parts_mut`. . unsafe { self.split_at_mut_unchecked(mid) } . } . . /// Divides one slice into two at an index, without doing bounds checking. . /// . /// The first will contain all indices from `[0, mid)` (excluding -- line 1546 ---------------------------------------- -- line 1628 ---------------------------------------- . pub unsafe fn split_at_mut_unchecked(&mut self, mid: usize) -> (&mut [T], &mut [T]) { . let len = self.len(); . let ptr = self.as_mut_ptr(); . . // SAFETY: Caller has to check that `0 <= mid <= self.len()`. . // . // `[ptr; mid]` and `[mid; len]` are not overlapping, so returning a mutable reference . // is fine. 2,174 ( 0.00%) unsafe { (from_raw_parts_mut(ptr, mid), from_raw_parts_mut(ptr.add(mid), len - mid)) } . } . . /// Divides one slice into an array and a remainder slice at an index. . /// . /// The array will contain all indices from `[0, N)` (excluding . /// the index `N` itself) and the slice will contain all . /// indices from `[N, len)` (excluding the index `len` itself). . /// -- line 1644 ---------------------------------------- -- line 2113 ---------------------------------------- . /// assert!(!v.iter().any(|e| e == "hi")); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . pub fn contains(&self, x: &T) -> bool . where . T: PartialEq, . { 518 ( 0.00%) cmp::SliceContains::slice_contains(x, self) . } . . /// Returns `true` if `needle` is a prefix of the slice. . /// . /// # Examples . /// . /// ``` . /// let v = [10, 40, 30]; -- line 2129 ---------------------------------------- -- line 2137 ---------------------------------------- . /// . /// ``` . /// let v = &[10, 40, 30]; . /// assert!(v.starts_with(&[])); . /// let v: &[u8] = &[]; . /// assert!(v.starts_with(&[])); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 7,049 ( 0.00%) pub fn starts_with(&self, needle: &[T]) -> bool . where . T: PartialEq, . { 3,021 ( 0.00%) let n = needle.len(); 30,873 ( 0.00%) self.len() >= n && needle == &self[..n] 5,035 ( 0.00%) } . . /// Returns `true` if `needle` is a suffix of the slice. . /// . /// # Examples . /// . /// ``` . /// let v = [10, 40, 30]; . /// assert!(v.ends_with(&[30])); -- line 2159 ---------------------------------------- -- line 2171 ---------------------------------------- . /// assert!(v.ends_with(&[])); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn ends_with(&self, needle: &[T]) -> bool . where . T: PartialEq, . { . let (m, n) = (self.len(), needle.len()); 80,805 ( 0.00%) m >= n && needle == &self[m - n..] . } . . /// Returns a subslice with the prefix removed. . /// . /// If the slice starts with `prefix`, returns the subslice after the prefix, wrapped in `Some`. . /// If `prefix` is empty, simply returns the original slice. . /// . /// If the slice does not start with `prefix`, returns `None`. -- line 2187 ---------------------------------------- -- line 2293 ---------------------------------------- . /// s.insert(idx, num); . /// assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn binary_search(&self, x: &T) -> Result . where . T: Ord, . { 3 ( 0.00%) self.binary_search_by(|p| p.cmp(x)) . } . . /// Binary searches this sorted slice with a comparator function. . /// . /// The comparator function should implement an order consistent . /// with the sort order of the underlying slice, returning an . /// order code that indicates whether its argument is `Less`, . /// `Equal` or `Greater` the desired target. -- line 2309 ---------------------------------------- -- line 2345 ---------------------------------------- . #[inline] . pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result . where . F: FnMut(&'a T) -> Ordering, . { . let mut size = self.len(); . let mut left = 0; . let mut right = size; 3,687,245 ( 0.07%) while left < right { 5,905,824 ( 0.11%) let mid = left + size / 2; . . // SAFETY: the call is made safe by the following invariants: . // - `mid >= 0` . // - `mid < size`: `mid` is limited by `[left; right)` bound. 673,170 ( 0.01%) let cmp = f(unsafe { self.get_unchecked(mid) }); . . // The reason why we use if/else control flow rather than match . // is because match reorders comparison operations, which is perf sensitive. . // This is x86 asm for u8: https://rust.godbolt.org/z/8Y8Pra. 1,527,199 ( 0.03%) if cmp == Less { 3,328,355 ( 0.06%) left = mid + 1; 770,068 ( 0.01%) } else if cmp == Greater { . right = mid; . } else { . // SAFETY: same as the `get_unchecked` above . unsafe { crate::intrinsics::assume(mid < self.len()) }; . return Ok(mid); . } . 4,564,199 ( 0.09%) size = right - left; . } . Err(left) . } . . /// Binary searches this sorted slice with a key extraction function. . /// . /// Assumes that the slice is sorted by the key, for instance with . /// [`sort_by_key`] using the same key extraction function. -- line 2382 ---------------------------------------- -- line 3187 ---------------------------------------- . /// assert_eq!(slice, [4, 5, 3, 4, 5]); . /// ``` . /// . /// [`clone_from_slice`]: slice::clone_from_slice . /// [`split_at_mut`]: slice::split_at_mut . #[doc(alias = "memcpy")] . #[stable(feature = "copy_from_slice", since = "1.9.0")] . #[track_caller] 40 ( 0.00%) pub fn copy_from_slice(&mut self, src: &[T]) . where . T: Copy, . { . // The panic code path was put into a cold function to not bloat the . // call site. . #[inline(never)] . #[cold] . #[track_caller] . fn len_mismatch_fail(dst_len: usize, src_len: usize) -> ! { . panic!( . "source slice length ({}) does not match destination slice length ({})", . src_len, dst_len, . ); . } . 91,470 ( 0.00%) if self.len() != src.len() { . len_mismatch_fail(self.len(), src.len()); . } . . // SAFETY: `self` is valid for `self.len()` elements by definition, and `src` was . // checked to have the same length. The slices cannot overlap because . // mutable references are exclusive. . unsafe { 24 ( 0.00%) ptr::copy_nonoverlapping(src.as_ptr(), self.as_mut_ptr(), self.len()); . } 8 ( 0.00%) } . . /// Copies elements from one part of the slice to another part of itself, . /// using a memmove. . /// . /// `src` is the range within `self` to copy from. `dest` is the starting . /// index of the range within `self` to copy to, which will have the same . /// length as `src`. The two ranges may overlap. The ends of the two ranges . /// must be less than or equal to `self.len()`. -- line 3229 ---------------------------------------- -- line 3380 ---------------------------------------- . } . a << k . } . let gcd: usize = gcd(mem::size_of::(), mem::size_of::()); . let ts: usize = mem::size_of::() / gcd; . let us: usize = mem::size_of::() / gcd; . . // Armed with this knowledge, we can find how many `U`s we can fit! 3 ( 0.00%) let us_len = self.len() / ts * us; . // And how many `T`s will be in the trailing slice! 5,018 ( 0.00%) let ts_len = self.len() % ts; . (us_len, ts_len) . } . . /// Transmute the slice to a slice of another type, ensuring alignment of the types is . /// maintained. . /// . /// This method splits the slice into three distinct slices: prefix, correctly aligned middle . /// slice of a new type, and the suffix slice. The method may make the middle slice the greatest -- line 3398 ---------------------------------------- -- line 3429 ---------------------------------------- . return (self, &[], &[]); . } . . // First, find at what point do we split between the first and 2nd slice. Easy with . // ptr.align_offset. . let ptr = self.as_ptr(); . // SAFETY: See the `align_to_mut` method for the detailed safety comment. . let offset = unsafe { crate::ptr::align_offset(ptr, mem::align_of::()) }; 5,018 ( 0.00%) if offset > self.len() { . (self, &[], &[]) . } else { . let (left, rest) = self.split_at(offset); . let (us_len, ts_len) = rest.align_to_offsets::(); . // SAFETY: now `rest` is definitely aligned, so `from_raw_parts` below is okay, . // since the caller guarantees that we can transmute `T` to `U` safely. . unsafe { . ( . left, . from_raw_parts(rest.as_ptr() as *const U, us_len), 5,021 ( 0.00%) from_raw_parts(rest.as_ptr().add(rest.len() - ts_len), ts_len), . ) . } . } . } . . /// Transmute the slice to a slice of another type, ensuring alignment of the types is . /// maintained. . /// -- line 3456 ---------------------------------------- 2,752,453 ( 0.05%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/subst.rs -------------------------------------------------------------------------------- Ir -- line 22 ---------------------------------------- . . /// An entity in the Rust type system, which can be one of . /// several kinds (types, lifetimes, and consts). . /// To reduce memory usage, a `GenericArg` is an interned pointer, . /// with the lowest 2 bits being reserved for a tag to . /// indicate the type (`Ty`, `Region`, or `Const`) it points to. . #[derive(Copy, Clone, PartialEq, Eq, Hash)] . pub struct GenericArg<'tcx> { 244,457 ( 0.00%) ptr: NonZeroUsize, 534,946 ( 0.01%) marker: PhantomData<(Ty<'tcx>, ty::Region<'tcx>, &'tcx ty::Const<'tcx>)>, . } . . const TAG_MASK: usize = 0b11; . const TYPE_TAG: usize = 0b00; . const REGION_TAG: usize = 0b01; . const CONST_TAG: usize = 0b10; . 220,300 ( 0.00%) #[derive(Debug, TyEncodable, TyDecodable, PartialEq, Eq, PartialOrd, Ord, HashStable)] . pub enum GenericArgKind<'tcx> { . Lifetime(ty::Region<'tcx>), . Type(Ty<'tcx>), . Const(&'tcx ty::Const<'tcx>), . } . . impl<'tcx> GenericArgKind<'tcx> { 54,592 ( 0.00%) fn pack(self) -> GenericArg<'tcx> { 54,592 ( 0.00%) let (tag, ptr) = match self { . GenericArgKind::Lifetime(lt) => { . // Ensure we can use the tag bits. . assert_eq!(mem::align_of_val(lt) & TAG_MASK, 0); . (REGION_TAG, lt as *const _ as usize) . } . GenericArgKind::Type(ty) => { . // Ensure we can use the tag bits. . assert_eq!(mem::align_of_val(ty) & TAG_MASK, 0); -- line 56 ---------------------------------------- -- line 58 ---------------------------------------- . } . GenericArgKind::Const(ct) => { . // Ensure we can use the tag bits. . assert_eq!(mem::align_of_val(ct) & TAG_MASK, 0); . (CONST_TAG, ct as *const _ as usize) . } . }; . 98,316 ( 0.00%) GenericArg { ptr: unsafe { NonZeroUsize::new_unchecked(ptr | tag) }, marker: PhantomData } 54,592 ( 0.00%) } . } . . impl<'tcx> fmt::Debug for GenericArg<'tcx> { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . match self.unpack() { . GenericArgKind::Lifetime(lt) => lt.fmt(f), . GenericArgKind::Type(ty) => ty.fmt(f), . GenericArgKind::Const(ct) => ct.fmt(f), -- line 75 ---------------------------------------- -- line 85 ---------------------------------------- . . impl<'tcx> PartialOrd for GenericArg<'tcx> { . fn partial_cmp(&self, other: &GenericArg<'_>) -> Option { . Some(self.cmp(&other)) . } . } . . impl<'tcx> From> for GenericArg<'tcx> { 26,537 ( 0.00%) fn from(r: ty::Region<'tcx>) -> GenericArg<'tcx> { . GenericArgKind::Lifetime(r).pack() 26,537 ( 0.00%) } . } . . impl<'tcx> From> for GenericArg<'tcx> { 211,631 ( 0.00%) fn from(ty: Ty<'tcx>) -> GenericArg<'tcx> { . GenericArgKind::Type(ty).pack() 211,631 ( 0.00%) } . } . . impl<'tcx> From<&'tcx ty::Const<'tcx>> for GenericArg<'tcx> { 35 ( 0.00%) fn from(c: &'tcx ty::Const<'tcx>) -> GenericArg<'tcx> { . GenericArgKind::Const(c).pack() 35 ( 0.00%) } . } . . impl<'tcx> GenericArg<'tcx> { . #[inline] . pub fn unpack(self) -> GenericArgKind<'tcx> { . let ptr = self.ptr.get(); . unsafe { 3,627,865 ( 0.07%) match ptr & TAG_MASK { 28,419 ( 0.00%) REGION_TAG => GenericArgKind::Lifetime(&*((ptr & !TAG_MASK) as *const _)), 906,414 ( 0.02%) TYPE_TAG => GenericArgKind::Type(&*((ptr & !TAG_MASK) as *const _)), 698 ( 0.00%) CONST_TAG => GenericArgKind::Const(&*((ptr & !TAG_MASK) as *const _)), . _ => intrinsics::unreachable(), . } . } . } . . /// Unpack the `GenericArg` as a type when it is known certainly to be a type. . /// This is true in cases where `Substs` is used in places where the kinds are known . /// to be limited (e.g. in tuples, where the only parameters are type parameters). . pub fn expect_ty(self) -> Ty<'tcx> { . match self.unpack() { . GenericArgKind::Type(ty) => ty, . _ => bug!("expected a type, but found another kind"), . } 51,052 ( 0.00%) } . . /// Unpack the `GenericArg` as a const when it is known certainly to be a const. . pub fn expect_const(self) -> &'tcx ty::Const<'tcx> { . match self.unpack() { . GenericArgKind::Const(c) => c, . _ => bug!("expected a const, but found another kind"), . } . } -- line 140 ---------------------------------------- -- line 155 ---------------------------------------- . impl<'tcx> TypeFoldable<'tcx> for GenericArg<'tcx> { . fn try_super_fold_with>( . self, . folder: &mut F, . ) -> Result { . match self.unpack() { . GenericArgKind::Lifetime(lt) => lt.try_fold_with(folder).map(Into::into), . GenericArgKind::Type(ty) => ty.try_fold_with(folder).map(Into::into), 6 ( 0.00%) GenericArgKind::Const(ct) => ct.try_fold_with(folder).map(Into::into), . } . } . . fn super_visit_with>(&self, visitor: &mut V) -> ControlFlow { . match self.unpack() { . GenericArgKind::Lifetime(lt) => lt.visit_with(visitor), . GenericArgKind::Type(ty) => ty.visit_with(visitor), . GenericArgKind::Const(ct) => ct.visit_with(visitor), -- line 171 ---------------------------------------- -- line 175 ---------------------------------------- . . impl<'tcx, E: TyEncoder<'tcx>> Encodable for GenericArg<'tcx> { . fn encode(&self, e: &mut E) -> Result<(), E::Error> { . self.unpack().encode(e) . } . } . . impl<'tcx, D: TyDecoder<'tcx>> Decodable for GenericArg<'tcx> { 272,960 ( 0.01%) fn decode(d: &mut D) -> GenericArg<'tcx> { 272,960 ( 0.01%) GenericArgKind::decode(d).pack() . } . } . . /// A substitution mapping generic parameters to new values. . pub type InternalSubsts<'tcx> = List>; . . pub type SubstsRef<'tcx> = &'tcx InternalSubsts<'tcx>; . . impl<'a, 'tcx> InternalSubsts<'tcx> { . /// Interpret these substitutions as the substitutions of a closure type. . /// Closure substitutions have a particular structure controlled by the . /// compiler that encodes information like the signature and closure kind; . /// see `ty::ClosureSubsts` struct for more comments. 4,558 ( 0.00%) pub fn as_closure(&'a self) -> ClosureSubsts<'a> { . ClosureSubsts { substs: self } 4,558 ( 0.00%) } . . /// Interpret these substitutions as the substitutions of a generator type. . /// Generator substitutions have a particular structure controlled by the . /// compiler that encodes information like the signature and generator kind; . /// see `ty::GeneratorSubsts` struct for more comments. . pub fn as_generator(&'tcx self) -> GeneratorSubsts<'tcx> { . GeneratorSubsts { substs: self } . } -- line 208 ---------------------------------------- -- line 211 ---------------------------------------- . /// Inline const substitutions have a particular structure controlled by the . /// compiler that encodes information like the inferred type; . /// see `ty::InlineConstSubsts` struct for more comments. . pub fn as_inline_const(&'tcx self) -> InlineConstSubsts<'tcx> { . InlineConstSubsts { substs: self } . } . . /// Creates an `InternalSubsts` that maps each generic parameter to itself. 3,020 ( 0.00%) pub fn identity_for_item(tcx: TyCtxt<'tcx>, def_id: DefId) -> SubstsRef<'tcx> { 1,040 ( 0.00%) Self::for_item(tcx, def_id, |param, _| tcx.mk_param_from_def(param)) 2,718 ( 0.00%) } . . /// Creates an `InternalSubsts` for generic parameter definitions, . /// by calling closures to obtain each kind. . /// The closures get to observe the `InternalSubsts` as they're . /// being built, which can be used to correctly . /// substitute defaults of generic parameters. 48,788 ( 0.00%) pub fn for_item(tcx: TyCtxt<'tcx>, def_id: DefId, mut mk_kind: F) -> SubstsRef<'tcx> . where . F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>, . { . let defs = tcx.generics_of(def_id); . let count = defs.count(); . let mut substs = SmallVec::with_capacity(count); 17,405 ( 0.00%) Self::fill_item(&mut substs, tcx, defs, &mut mk_kind); 10,618 ( 0.00%) tcx.intern_substs(&substs) 49,077 ( 0.00%) } . . pub fn extend_to(&self, tcx: TyCtxt<'tcx>, def_id: DefId, mut mk_kind: F) -> SubstsRef<'tcx> . where . F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>, . { . Self::for_item(tcx, def_id, |param, substs| { . self.get(param.index as usize).cloned().unwrap_or_else(|| mk_kind(param, substs)) . }) . } . 62,814 ( 0.00%) pub fn fill_item( . substs: &mut SmallVec<[GenericArg<'tcx>; 8]>, . tcx: TyCtxt<'tcx>, . defs: &ty::Generics, . mk_kind: &mut F, . ) where . F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>, . { 26,030 ( 0.00%) if let Some(def_id) = defs.parent { . let parent_defs = tcx.generics_of(def_id); 2,572 ( 0.00%) Self::fill_item(substs, tcx, parent_defs, mk_kind); . } . Self::fill_single(substs, defs, mk_kind) 50,024 ( 0.00%) } . . pub fn fill_single( . substs: &mut SmallVec<[GenericArg<'tcx>; 8]>, . defs: &ty::Generics, . mk_kind: &mut F, . ) where . F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>, . { . substs.reserve(defs.params.len()); . for param in &defs.params { . let kind = mk_kind(param, substs); 53,158 ( 0.00%) assert_eq!(param.index as usize, substs.len()); . substs.push(kind); . } . } . . #[inline] . pub fn types(&'a self) -> impl DoubleEndedIterator> + 'a { . self.iter() . .filter_map(|k| if let GenericArgKind::Type(ty) = k.unpack() { Some(ty) } else { None }) -- line 281 ---------------------------------------- -- line 301 ---------------------------------------- . ) -> impl DoubleEndedIterator> + 'a { . self.iter().filter_map(|k| match k.unpack() { . GenericArgKind::Lifetime(_) => None, . generic => Some(generic), . }) . } . . #[inline] 12 ( 0.00%) pub fn type_at(&self, i: usize) -> Ty<'tcx> { 121,248 ( 0.00%) if let GenericArgKind::Type(ty) = self[i].unpack() { . ty . } else { . bug!("expected type for param #{} in {:?}", i, self); . } 8 ( 0.00%) } . . #[inline] . pub fn region_at(&self, i: usize) -> ty::Region<'tcx> { . if let GenericArgKind::Lifetime(lt) = self[i].unpack() { . lt . } else { . bug!("expected region for param #{} in {:?}", i, self); . } -- line 323 ---------------------------------------- -- line 350 ---------------------------------------- . /// impl X for U { fn f() {} } . /// ``` . /// . /// * If `self` is `[Self, S, T]`: the identity substs of `f` in the trait. . /// * If `source_ancestor` is the def_id of the trait. . /// * If `target_substs` is `[U]`, the substs for the impl. . /// * Then we will return `[U, T]`, the subst for `f` in the impl that . /// are needed for it to match the trait. 8,183 ( 0.00%) pub fn rebase_onto( . &self, . tcx: TyCtxt<'tcx>, . source_ancestor: DefId, . target_substs: SubstsRef<'tcx>, . ) -> SubstsRef<'tcx> { . let defs = tcx.generics_of(source_ancestor); 2,338 ( 0.00%) tcx.mk_substs(target_substs.iter().chain(self.iter().skip(defs.params.len()))) 9,352 ( 0.00%) } . 1,253 ( 0.00%) pub fn truncate_to(&self, tcx: TyCtxt<'tcx>, generics: &ty::Generics) -> SubstsRef<'tcx> { . tcx.mk_substs(self.iter().take(generics.count())) 2,506 ( 0.00%) } . } . . impl<'tcx> TypeFoldable<'tcx> for SubstsRef<'tcx> { 25,389 ( 0.00%) fn try_super_fold_with>( . self, . folder: &mut F, . ) -> Result { . // This code is hot enough that it's worth specializing for the most . // common length lists, to avoid the overhead of `SmallVec` creation. . // The match arms are in order of frequency. The 1, 2, and 0 cases are . // typically hit in 90--99.99% of cases. When folding doesn't change . // the substs, it's faster to reuse the existing substs rather than . // calling `intern_substs`. 763,636 ( 0.01%) match self.len() { . 1 => { 97,840 ( 0.00%) let param0 = self[0].try_fold_with(folder)?; 353,917 ( 0.01%) if param0 == self[0] { Ok(self) } else { Ok(folder.tcx().intern_substs(&[param0])) } . } . 2 => { 81,253 ( 0.00%) let param0 = self[0].try_fold_with(folder)?; 199,963 ( 0.00%) let param1 = self[1].try_fold_with(folder)?; 195,280 ( 0.00%) if param0 == self[0] && param1 == self[1] { . Ok(self) . } else { 152,303 ( 0.00%) Ok(folder.tcx().intern_substs(&[param0, param1])) . } . } . 0 => Ok(self), . _ => { . let params: SmallVec<[_; 8]> = 22,301 ( 0.00%) self.iter().map(|k| k.try_fold_with(folder)).collect::>()?; 1,725 ( 0.00%) if params[..] == self[..] { . Ok(self) . } else { 5,531 ( 0.00%) Ok(folder.tcx().intern_substs(¶ms)) . } . } . } 40,758 ( 0.00%) } . . fn super_visit_with>(&self, visitor: &mut V) -> ControlFlow { 112,307 ( 0.00%) self.iter().try_for_each(|t| t.visit_with(visitor)) . } . } . . /////////////////////////////////////////////////////////////////////////// . // Public trait `Subst` . // . // Just call `foo.subst(tcx, substs)` to perform a substitution across . // `foo`. Or use `foo.subst_spanned(tcx, substs, Some(span))` when -- line 420 ---------------------------------------- -- line 435 ---------------------------------------- . . impl<'tcx, T: TypeFoldable<'tcx>> Subst<'tcx> for T { . fn subst_spanned( . self, . tcx: TyCtxt<'tcx>, . substs: &[GenericArg<'tcx>], . span: Option, . ) -> T { 1,003,415 ( 0.02%) let mut folder = SubstFolder { tcx, substs, span, binders_passed: 0 }; . self.fold_with(&mut folder) . } . } . . /////////////////////////////////////////////////////////////////////////// . // The actual substitution engine itself is a type folder. . . struct SubstFolder<'a, 'tcx> { -- line 451 ---------------------------------------- -- line 456 ---------------------------------------- . span: Option, . . /// Number of region binders we have passed through while doing the substitution . binders_passed: u32, . } . . impl<'a, 'tcx> TypeFolder<'tcx> for SubstFolder<'a, 'tcx> { . fn tcx<'b>(&'b self) -> TyCtxt<'tcx> { 113,175 ( 0.00%) self.tcx . } . . fn fold_binder>( . &mut self, . t: ty::Binder<'tcx, T>, . ) -> ty::Binder<'tcx, T> { 76,344 ( 0.00%) self.binders_passed += 1; 19,108 ( 0.00%) let t = t.super_fold_with(self); 76,344 ( 0.00%) self.binders_passed -= 1; . t . } . 118,386 ( 0.00%) fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> { . // Note: This routine only handles regions that are bound on . // type declarations and other outer declarations, not those . // bound in *fn types*. Region substitution of the bound . // regions that appear in a function signature is done using . // the specialized routine `ty::replace_late_regions()`. 39,462 ( 0.00%) match *r { 16,178 ( 0.00%) ty::ReEarlyBound(data) => { 16,178 ( 0.00%) let rk = self.substs.get(data.index as usize).map(|k| k.unpack()); . match rk { 8,089 ( 0.00%) Some(GenericArgKind::Lifetime(lt)) => self.shift_region_through_binders(lt), . _ => { . let span = self.span.unwrap_or(DUMMY_SP); . let msg = format!( . "Region parameter out of range \ . when substituting in region {} (index={})", . data.name, data.index . ); . span_bug!(span, "{}", msg); . } . } . } . _ => r, . } 138,117 ( 0.00%) } . 1,083,324 ( 0.02%) fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { 361,108 ( 0.01%) if !t.needs_subst() { . return t; . } . 327,398 ( 0.01%) match *t.kind() { 504,375 ( 0.01%) ty::Param(p) => self.ty_for_param(p, t), 376,944 ( 0.01%) _ => t.super_fold_with(self), . } 1,491,420 ( 0.03%) } . 75,929 ( 0.00%) fn fold_const(&mut self, c: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> { 22,384 ( 0.00%) if let ty::ConstKind::Param(p) = c.val { . self.const_for_param(p, c) . } else { 96,381 ( 0.00%) c.super_fold_with(self) . } 1,104 ( 0.00%) } . . #[inline] . fn fold_mir_const(&mut self, c: mir::ConstantKind<'tcx>) -> mir::ConstantKind<'tcx> { . c.super_fold_with(self) . } . } . . impl<'a, 'tcx> SubstFolder<'a, 'tcx> { . fn ty_for_param(&self, p: ty::ParamTy, source_ty: Ty<'tcx>) -> Ty<'tcx> { . // Look up the type in the substitutions. It really should be in there. 201,750 ( 0.00%) let opt_ty = self.substs.get(p.index as usize).map(|k| k.unpack()); . let ty = match opt_ty { . Some(GenericArgKind::Type(ty)) => ty, . Some(kind) => { . let span = self.span.unwrap_or(DUMMY_SP); . span_bug!( . span, . "expected type for `{:?}` ({:?}/{}) but found {:?} \ . when substituting, substs={:?}", -- line 539 ---------------------------------------- -- line 562 ---------------------------------------- . } . . fn const_for_param( . &self, . p: ParamConst, . source_ct: &'tcx ty::Const<'tcx>, . ) -> &'tcx ty::Const<'tcx> { . // Look up the const in the substitutions. It really should be in there. 276 ( 0.00%) let opt_ct = self.substs.get(p.index as usize).map(|k| k.unpack()); . let ct = match opt_ct { . Some(GenericArgKind::Const(ct)) => ct, . Some(kind) => { . let span = self.span.unwrap_or(DUMMY_SP); . span_bug!( . span, . "expected const for `{:?}` ({:?}/{}) but found {:?} \ . when substituting substs={:?}", -- line 578 ---------------------------------------- -- line 645 ---------------------------------------- . fn shift_vars_through_binders>(&self, val: T) -> T { . debug!( . "shift_vars(val={:?}, binders_passed={:?}, has_escaping_bound_vars={:?})", . val, . self.binders_passed, . val.has_escaping_bound_vars() . ); . 334,961 ( 0.01%) if self.binders_passed == 0 || !val.has_escaping_bound_vars() { . return val; . } . . let result = ty::fold::shift_vars(self.tcx(), val, self.binders_passed); . debug!("shift_vars: shifted result = {:?}", result); . . result . } . . fn shift_region_through_binders(&self, region: ty::Region<'tcx>) -> ty::Region<'tcx> { 18,675 ( 0.00%) if self.binders_passed == 0 || !region.has_escaping_bound_vars() { . return region; . } . ty::fold::shift_region(self.tcx, region, self.binders_passed) . } . } . . /// Stores the user-given substs to reach some fully qualified path . /// (e.g., `::Item` or `::Item`). . #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyEncodable, TyDecodable)] 1,541 ( 0.00%) #[derive(HashStable, TypeFoldable, Lift)] . pub struct UserSubsts<'tcx> { . /// The substitutions for the item as given by the user. . pub substs: SubstsRef<'tcx>, . . /// The self type, in the case of a `::Item` path (when applied . /// to an inherent impl). See `UserSelfTy` below. 241 ( 0.00%) pub user_self_ty: Option>, . } . . /// Specifies the user-given self type. In the case of a path that . /// refers to a member in an inherent impl, this self type is . /// sometimes needed to constrain the type parameters on the impl. For . /// example, in this code: . /// . /// ``` -- line 689 ---------------------------------------- -- line 696 ---------------------------------------- . /// self type `Foo`. Then we can instantiate the parameters of . /// the impl (with the substs from `UserSubsts`) and apply those to . /// the self type, giving `Foo`. Finally, we unify that with . /// the self type here, which contains `?A` to be `&'static u32` . #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyEncodable, TyDecodable)] . #[derive(HashStable, TypeFoldable, Lift)] . pub struct UserSelfTy<'tcx> { . pub impl_def_id: DefId, 108 ( 0.00%) pub self_ty: Ty<'tcx>, . } 1,330,259 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs -------------------------------------------------------------------------------- Ir -- line 36 ---------------------------------------- . use rustc_session::parse::ParseSess; . use rustc_span::source_map::{MultiSpan, Span, DUMMY_SP}; . use rustc_span::symbol::{kw, sym, Ident, Symbol}; . use tracing::debug; . . use std::ops::Range; . use std::{cmp, mem, slice}; . 8,438 ( 0.00%) bitflags::bitflags! { . struct Restrictions: u8 { . const STMT_EXPR = 1 << 0; . const NO_STRUCT_LITERAL = 1 << 1; . const CONST_EXPR = 1 << 2; . } . } . . #[derive(Clone, Copy, PartialEq, Debug)] -- line 52 ---------------------------------------- -- line 104 ---------------------------------------- . $self.bump(); . return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_token.span, ty); . } . } . } . }; . } . 1,225,478 ( 0.02%) #[derive(Clone)] . pub struct Parser<'a> { 45,164 ( 0.00%) pub sess: &'a ParseSess, . /// The current token. 43,638 ( 0.00%) pub token: Token, . /// The spacing for the current token 21,848 ( 0.00%) pub token_spacing: Spacing, . /// The previous token. 65,457 ( 0.00%) pub prev_token: Token, 21,877 ( 0.00%) pub capture_cfg: bool, 43,783 ( 0.00%) restrictions: Restrictions, 43,696 ( 0.00%) expected_tokens: Vec, . // Important: This must only be advanced from `next_tok` . // to ensure that `token_cursor.num_next_calls` is updated properly . token_cursor: TokenCursor, 43,696 ( 0.00%) desugar_doc_comments: bool, . /// This field is used to keep track of how many left angle brackets we have seen. This is . /// required in order to detect extra leading left angle brackets (`<` characters) and error . /// appropriately. . /// . /// See the comments in the `parse_path_segment` function for more details. 43,696 ( 0.00%) unmatched_angle_bracket_count: u32, 65,544 ( 0.00%) max_angle_bracket_count: u32, . /// A list of all unclosed delimiters found by the lexer. If an entry is used for error recovery . /// it gets removed from here. Every entry left at the end gets emitted as an independent . /// error. 21,848 ( 0.00%) pub(super) unclosed_delims: Vec, . last_unexpected_token_span: Option, . /// Span pointing at the `:` for the last type ascription the parser has seen, and whether it . /// looked like it could have been a mistyped path or literal `Option:Some(42)`). . pub last_type_ascription: Option<(Span, bool /* likely path typo */)>, . /// If present, this `Parser` is not parsing Rust code but rather a macro call. . subparser_name: Option<&'static str>, . capture_state: CaptureState, . /// This allows us to recover when the user forget to add braces around -- line 146 ---------------------------------------- -- line 173 ---------------------------------------- . /// the first macro inner attribute to invoke a proc-macro). . /// When create a `TokenStream`, the inner attributes get inserted . /// into the proper place in the token stream. . pub type ReplaceRange = (Range, Vec<(FlatToken, Spacing)>); . . /// Controls how we capture tokens. Capturing can be expensive, . /// so we try to avoid performing capturing in cases where . /// we will never need an `AttrAnnotatedTokenStream` 21,848 ( 0.00%) #[derive(Copy, Clone)] . pub enum Capturing { . /// We aren't performing any capturing - this is the default mode. . No, . /// We are capturing tokens . Yes, . } . 88,889 ( 0.00%) #[derive(Clone)] . struct CaptureState { 87,392 ( 0.00%) capturing: Capturing, 21,848 ( 0.00%) replace_ranges: Vec, . inner_attr_ranges: FxHashMap, . } . . impl<'a> Drop for Parser<'a> { . fn drop(&mut self) { 74,709 ( 0.00%) emit_unclosed_delims(&mut self.unclosed_delims, &self.sess); . } . } . 384,520 ( 0.01%) #[derive(Clone)] . struct TokenCursor { . frame: TokenCursorFrame, 89,700 ( 0.00%) stack: Vec, . desugar_doc_comments: bool, . // Counts the number of calls to `next` or `next_desugared`, . // depending on whether `desugar_doc_comments` is set. 29,178 ( 0.00%) num_next_calls: usize, . // During parsing, we may sometimes need to 'unglue' a . // glued token into two component tokens . // (e.g. '>>' into '>' and '>), so that the parser . // can consume them one at a time. This process . // bypasses the normal capturing mechanism . // (e.g. `num_next_calls` will not be incremented), . // since the 'unglued' tokens due not exist in . // the original `TokenStream`. -- line 217 ---------------------------------------- -- line 226 ---------------------------------------- . // in `Option>` requires us to unglue . // the trailing `>>` token. The `break_last_token` . // field is used to track this token - it gets . // appended to the captured stream when . // we evaluate a `LazyTokenStream` . break_last_token: bool, . } . 175,204 ( 0.00%) #[derive(Clone)] . struct TokenCursorFrame { 31,040 ( 0.00%) delim: token::DelimToken, . span: DelimSpan, . open_delim: bool, 62,080 ( 0.00%) tree_cursor: tokenstream::Cursor, . close_delim: bool, . } . . impl TokenCursorFrame { . fn new(span: DelimSpan, delim: DelimToken, tts: TokenStream) -> Self { 15,185 ( 0.00%) TokenCursorFrame { . delim, . span, . open_delim: false, 19,327 ( 0.00%) tree_cursor: tts.into_trees(), . close_delim: false, . } . } . } . . impl TokenCursor { 1,750,404 ( 0.03%) fn next(&mut self) -> (Token, Spacing) { . loop { 817,430 ( 0.02%) let (tree, spacing) = if !self.frame.open_delim { 13,253 ( 0.00%) self.frame.open_delim = true; 66,265 ( 0.00%) TokenTree::open_tt(self.frame.span, self.frame.delim).into() 1,707,126 ( 0.03%) } else if let Some(tree) = self.frame.tree_cursor.next_with_spacing() { . tree 49,788 ( 0.00%) } else if !self.frame.close_delim { 10,922 ( 0.00%) self.frame.close_delim = true; 54,610 ( 0.00%) TokenTree::close_tt(self.frame.span, self.frame.delim).into() 21,830 ( 0.00%) } else if let Some(frame) = self.stack.pop() { 141,895 ( 0.00%) self.frame = frame; . continue; . } else { 55,026 ( 0.00%) (TokenTree::Token(Token::new(token::Eof, DUMMY_SP)), Spacing::Alone) . }; . 318,240 ( 0.01%) match tree { . TokenTree::Token(token) => { 1,166,936 ( 0.02%) return (token, spacing); . } . TokenTree::Delimited(sp, delim, tts) => { . let frame = TokenCursorFrame::new(sp, delim, tts); . self.stack.push(mem::replace(&mut self.frame, frame)); . } . } . } 1,166,936 ( 0.02%) } . 771,090 ( 0.01%) fn next_desugared(&mut self) -> (Token, Spacing) { 231,327 ( 0.00%) let (data, attr_style, sp) = match self.next() { . (Token { kind: token::DocComment(_, attr_style, data), span }, _) => { . (data, attr_style, span) . } 385,545 ( 0.01%) tok => return tok, . }; . . // Searches for the occurrences of `"#*` and returns the minimum number of `#`s . // required to wrap the text. . let mut num_of_hashes = 0; . let mut count = 0; . for ch in data.as_str().chars() { . count = match ch { -- line 298 ---------------------------------------- -- line 332 ---------------------------------------- . .iter() . .cloned() . .collect::() . }, . ), . )); . . self.next() 693,981 ( 0.01%) } . } . 2,690 ( 0.00%) #[derive(Debug, Clone, PartialEq)] . enum TokenType { 2,152 ( 0.00%) Token(TokenKind), . Keyword(Symbol), . Operator, . Lifetime, . Ident, . Path, . Type, . Const, . } -- line 353 ---------------------------------------- -- line 378 ---------------------------------------- . /// The separator token. . sep: Option, . /// `true` if a trailing separator is allowed. . trailing_sep_allowed: bool, . } . . impl SeqSep { . fn trailing_allowed(t: TokenKind) -> SeqSep { 111 ( 0.00%) SeqSep { sep: Some(t), trailing_sep_allowed: true } . } . . fn none() -> SeqSep { . SeqSep { sep: None, trailing_sep_allowed: false } . } . } . . pub enum FollowedByType { . Yes, . No, . } . . fn token_descr_opt(token: &Token) -> Option<&'static str> { 126 ( 0.00%) Some(match token.kind { 252 ( 0.00%) _ if token.is_special_ident() => "reserved identifier", 252 ( 0.00%) _ if token.is_used_keyword() => "keyword", 252 ( 0.00%) _ if token.is_unused_keyword() => "reserved keyword", . token::DocComment(..) => "doc comment", . _ => return None, . }) . } . 441 ( 0.00%) pub(super) fn token_descr(token: &Token) -> String { 126 ( 0.00%) let token_str = pprust::token_to_string(token); . match token_descr_opt(token) { . Some(prefix) => format!("{} `{}`", prefix, token_str), 441 ( 0.00%) _ => format!("`{}`", token_str), . } 315 ( 0.00%) } . . impl<'a> Parser<'a> { 42,518 ( 0.00%) pub fn new( . sess: &'a ParseSess, . tokens: TokenStream, . desugar_doc_comments: bool, . subparser_name: Option<&'static str>, . ) -> Self { 3,037 ( 0.00%) let mut start_frame = TokenCursorFrame::new(DelimSpan::dummy(), token::NoDelim, tokens); 6,074 ( 0.00%) start_frame.open_delim = true; . start_frame.close_delim = true; . 94,147 ( 0.00%) let mut parser = Parser { . sess, 3,037 ( 0.00%) token: Token::dummy(), . token_spacing: Spacing::Alone, 3,037 ( 0.00%) prev_token: Token::dummy(), . capture_cfg: false, . restrictions: Restrictions::empty(), . expected_tokens: Vec::new(), . token_cursor: TokenCursor { 18,222 ( 0.00%) frame: start_frame, . stack: Vec::new(), . num_next_calls: 0, . desugar_doc_comments, . break_last_token: false, . }, . desugar_doc_comments, . unmatched_angle_bracket_count: 0, . max_angle_bracket_count: 0, -- line 445 ---------------------------------------- -- line 451 ---------------------------------------- . capturing: Capturing::No, . replace_ranges: Vec::new(), . inner_attr_ranges: Default::default(), . }, . current_closure: None, . }; . . // Make parser point to the first token. 6,074 ( 0.00%) parser.bump(); . . parser 27,333 ( 0.00%) } . . fn next_tok(&mut self, fallback_span: Span) -> (Token, Spacing) { . loop { 844,548 ( 0.02%) let (mut next, spacing) = if self.desugar_doc_comments { 308,436 ( 0.01%) self.token_cursor.next_desugared() . } else { 190,947 ( 0.00%) self.token_cursor.next() . }; 563,032 ( 0.01%) self.token_cursor.num_next_calls += 1; . // We've retrieved an token from the underlying . // cursor, so we no longer need to worry about . // an unglued token. See `break_and_eat` for more details 140,758 ( 0.00%) self.token_cursor.break_last_token = false; 563,032 ( 0.01%) if next.span.is_dummy() { . // Tweak the location for better diagnostics, but keep syntactic context intact. 12,180 ( 0.00%) next.span = fallback_span.with_ctxt(next.span.ctxt()); . } 457,249 ( 0.01%) if matches!( 281,516 ( 0.01%) next.kind, . token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) . ) { . continue; . } 563,032 ( 0.01%) return (next, spacing); . } . } . . pub fn unexpected(&mut self) -> PResult<'a, T> { . match self.expect_one_of(&[], &[]) { . Err(e) => Err(e), . // We can get `Ok(true)` from `recover_closing_delimiter` . // which is called in `expected_one_of_not_found`. . Ok(_) => FatalError.raise(), . } . } . . /// Expects and consumes the token `t`. Signals an error if the next token is not `t`. 18,576 ( 0.00%) pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> { 2,064 ( 0.00%) if self.expected_tokens.is_empty() { 444 ( 0.00%) if self.token == *t { 370 ( 0.00%) self.bump(); . Ok(false) . } else { . self.unexpected_try_recover(t) . } . } else { 23,880 ( 0.00%) self.expect_one_of(slice::from_ref(t), &[]) . } 30,960 ( 0.00%) } . . /// Expect next token to be edible or inedible token. If edible, . /// then consume it; if inedible, then return without consuming . /// anything. Signal a fatal error if next token is unexpected. 32,976 ( 0.00%) pub fn expect_one_of( . &mut self, . edible: &[TokenKind], . inedible: &[TokenKind], . ) -> PResult<'a, bool /* recovered */> { 5,496 ( 0.00%) if edible.contains(&self.token.kind) { 6,183 ( 0.00%) self.bump(); . Ok(false) . } else if inedible.contains(&self.token.kind) { . // leave it in the input . Ok(false) . } else if self.last_unexpected_token_span == Some(self.token.span) { . FatalError.raise(); . } else { . self.expected_one_of_not_found(edible, inedible) . } 41,220 ( 0.00%) } . . // Public for rustfmt usage. . pub fn parse_ident(&mut self) -> PResult<'a, Ident> { 23,715 ( 0.00%) self.parse_ident_common(true) . } . . fn ident_or_err(&mut self) -> PResult<'a, (Ident, /* is_raw */ bool)> { 17,616 ( 0.00%) self.token.ident().ok_or_else(|| match self.prev_token.kind { . TokenKind::DocComment(..) => { . self.span_err(self.prev_token.span, Error::UselessDocComment) . } . _ => self.expected_ident_found(), . }) . } . 41,041 ( 0.00%) fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> { 5,863 ( 0.00%) let (ident, is_raw) = self.ident_or_err()?; 35,128 ( 0.00%) if !is_raw && ident.is_reserved() { . let mut err = self.expected_ident_found(); . if recover { . err.emit(); . } else { . return Err(err); . } . } 23,452 ( 0.00%) self.bump(); . Ok(ident) 58,630 ( 0.00%) } . . /// Checks if the next token is `tok`, and returns `true` if so. . /// . /// This method will automatically add `tok` to `expected_tokens` if `tok` is not . /// encountered. 498,519 ( 0.01%) fn check(&mut self, tok: &TokenKind) -> bool { 216,893 ( 0.00%) let is_present = self.token == *tok; 147,468 ( 0.00%) if !is_present { 268,895 ( 0.01%) self.expected_tokens.push(TokenType::Token(tok.clone())); . } . is_present 498,519 ( 0.01%) } . . /// Consumes a token 'tok' if it exists. Returns whether the given token was present. . pub fn eat(&mut self, tok: &TokenKind) -> bool { 101,024 ( 0.00%) let is_present = self.check(tok); 66,419 ( 0.00%) if is_present { 19,642 ( 0.00%) self.bump() . } . is_present . } . . /// If the next token is the given keyword, returns `true` without eating it. . /// An expectation is also added for diagnostics purposes. 7,120 ( 0.00%) fn check_keyword(&mut self, kw: Symbol) -> bool { 3,625 ( 0.00%) self.expected_tokens.push(TokenType::Keyword(kw)); 66,230 ( 0.00%) self.token.is_keyword(kw) . } . . /// If the next token is the given keyword, eats it and returns `true`. . /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes. . // Public for rustfmt usage. 20,760 ( 0.00%) pub fn eat_keyword(&mut self, kw: Symbol) -> bool { 13,532 ( 0.00%) if self.check_keyword(kw) { 2,018 ( 0.00%) self.bump(); . true . } else { . false . } 20,760 ( 0.00%) } . . fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool { 910 ( 0.00%) if self.token.is_keyword(kw) { 220 ( 0.00%) self.bump(); . true . } else { . false . } . } . . /// If the given word is not a keyword, signals an error. . /// If the next token is not the given word, signals an error. . /// Otherwise, eats it. 50 ( 0.00%) fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> { . if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) } 40 ( 0.00%) } . . /// Is the given keyword `kw` followed by a non-reserved identifier? 70,304 ( 0.00%) fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool { 35,152 ( 0.00%) self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()) 79,092 ( 0.00%) } . 17,496 ( 0.00%) fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool { 10,228 ( 0.00%) if ok { . true . } else { 2,256 ( 0.00%) self.expected_tokens.push(typ); . false . } 17,496 ( 0.00%) } . . fn check_ident(&mut self) -> bool { 4,283 ( 0.00%) self.check_or_expected(self.token.is_ident(), TokenType::Ident) . } . 7,488 ( 0.00%) fn check_path(&mut self) -> bool { 18,764 ( 0.00%) self.check_or_expected(self.token.is_path_start(), TokenType::Path) 9,360 ( 0.00%) } . . fn check_type(&mut self) -> bool { 886 ( 0.00%) self.check_or_expected(self.token.can_begin_type(), TokenType::Type) . } . . fn check_const_arg(&mut self) -> bool { 808 ( 0.00%) self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const) . } . 4,896 ( 0.00%) fn check_inline_const(&self, dist: usize) -> bool { 2,720 ( 0.00%) self.is_keyword_ahead(dist, &[kw::Const]) . && self.look_ahead(dist + 1, |t| match t.kind { . token::Interpolated(ref nt) => matches!(**nt, token::NtBlock(..)), . token::OpenDelim(DelimToken::Brace) => true, . _ => false, . }) 4,896 ( 0.00%) } . . /// Checks to see if the next token is either `+` or `+=`. . /// Otherwise returns `false`. . fn check_plus(&mut self) -> bool { 768 ( 0.00%) self.check_or_expected( 384 ( 0.00%) self.token.is_like_plus(), 384 ( 0.00%) TokenType::Token(token::BinOp(token::Plus)), . ) . } . . /// Eats the expected token if it's present possibly breaking . /// compound tokens like multi-character operators in process. . /// Returns `true` if the token was eaten. 31,776 ( 0.00%) fn break_and_eat(&mut self, expected: TokenKind) -> bool { 18,536 ( 0.00%) if self.token.kind == expected { 1,568 ( 0.00%) self.bump(); . return true; . } 9,320 ( 0.00%) match self.token.kind.break_two_token_op() { 467 ( 0.00%) Some((first, second)) if first == expected => { 44 ( 0.00%) let first_span = self.sess.source_map().start_point(self.token.span); 55 ( 0.00%) let second_span = self.token.span.with_lo(first_span.hi()); 99 ( 0.00%) self.token = Token::new(first, first_span); . // Keep track of this token - if we end token capturing now, . // we'll want to append this token to the captured stream. . // . // If we consume any additional tokens, then this token . // is not needed (we'll capture the entire 'glued' token), . // and `next_tok` will set this field to `None` 11 ( 0.00%) self.token_cursor.break_last_token = true; . // Use the spacing of the glued token as the spacing . // of the unglued second token. 154 ( 0.00%) self.bump_with((Token::new(second, second_span), self.token_spacing)); . true . } . _ => { 5,559 ( 0.00%) self.expected_tokens.push(TokenType::Token(expected)); . false . } . } 31,374 ( 0.00%) } . . /// Eats `+` possibly breaking tokens like `+=` in process. . fn eat_plus(&mut self) -> bool { 40 ( 0.00%) self.break_and_eat(token::BinOp(token::Plus)) . } . . /// Eats `&` possibly breaking tokens like `&&` in process. . /// Signals an error if `&` is not eaten. . fn expect_and(&mut self) -> PResult<'a, ()> { 3,534 ( 0.00%) if self.break_and_eat(token::BinOp(token::And)) { Ok(()) } else { self.unexpected() } . } . . /// Eats `|` possibly breaking tokens like `||` in process. . /// Signals an error if `|` was not eaten. . fn expect_or(&mut self) -> PResult<'a, ()> { 222 ( 0.00%) if self.break_and_eat(token::BinOp(token::Or)) { Ok(()) } else { self.unexpected() } . } . . /// Eats `<` possibly breaking tokens like `<<` in process. 710 ( 0.00%) fn eat_lt(&mut self) -> bool { 5,902 ( 0.00%) let ate = self.break_and_eat(token::Lt); 3,940 ( 0.00%) if ate { . // See doc comment for `unmatched_angle_bracket_count`. 336 ( 0.00%) self.unmatched_angle_bracket_count += 1; 342 ( 0.00%) self.max_angle_bracket_count += 1; . debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count); . } . ate 710 ( 0.00%) } . . /// Eats `<` possibly breaking tokens like `<<` in process. . /// Signals an error if `<` was not eaten. . fn expect_lt(&mut self) -> PResult<'a, ()> { . if self.eat_lt() { Ok(()) } else { self.unexpected() } . } . . /// Eats `>` possibly breaking tokens like `>>` in process. . /// Signals an error if `>` was not eaten. . fn expect_gt(&mut self) -> PResult<'a, ()> { 498 ( 0.00%) if self.break_and_eat(token::Gt) { . // See doc comment for `unmatched_angle_bracket_count`. 249 ( 0.00%) if self.unmatched_angle_bracket_count > 0 { 166 ( 0.00%) self.unmatched_angle_bracket_count -= 1; . debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count); . } . Ok(()) . } else { . self.unexpected() . } . } . . fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool { . kets.iter().any(|k| match expect { 6,129 ( 0.00%) TokenExpectType::Expect => self.check(k), 567 ( 0.00%) TokenExpectType::NoExpect => self.token == **k, . }) . } . . fn parse_seq_to_before_tokens( . &mut self, . kets: &[&TokenKind], . sep: SeqSep, . expect: TokenExpectType, -- line 759 ---------------------------------------- -- line 761 ---------------------------------------- . ) -> PResult<'a, (Vec, bool /* trailing */, bool /* recovered */)> { . let mut first = true; . let mut recovered = false; . let mut trailing = false; . let mut v = vec![]; . let unclosed_delims = !self.unclosed_delims.is_empty(); . . while !self.expect_any_with_type(kets, expect) { 8,931 ( 0.00%) if let token::CloseDelim(..) | token::Eof = self.token.kind { . break; . } 6,770 ( 0.00%) if let Some(ref t) = sep.sep { 7,091 ( 0.00%) if first { . first = false; . } else { 3,481 ( 0.00%) match self.expect(t) { . Ok(false) => { . self.current_closure.take(); . } . Ok(true) => { . self.current_closure.take(); . recovered = true; . break; . } -- line 784 ---------------------------------------- -- line 857 ---------------------------------------- . e.cancel(); . break; . } . } . } . } . } . } 3,066 ( 0.00%) if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) { . trailing = true; . break; . } . 1,638 ( 0.00%) let t = f(self)?; 572 ( 0.00%) v.push(t); . } . 4,992 ( 0.00%) Ok((v, trailing, recovered)) . } . . fn recover_missing_braces_around_closure_body( . &mut self, . closure_spans: ClosureSpans, . mut expect_err: DiagnosticBuilder<'_>, . ) -> PResult<'a, ()> { . let initial_semicolon = self.token.span; -- line 882 ---------------------------------------- -- line 937 ---------------------------------------- . /// `f` must consume tokens until reaching the next separator or . /// closing bracket. . fn parse_seq_to_before_end( . &mut self, . ket: &TokenKind, . sep: SeqSep, . f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, . ) -> PResult<'a, (Vec, bool, bool)> { 4,709 ( 0.00%) self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f) . } . . /// Parses a sequence, including the closing delimiter. The function . /// `f` must consume tokens until reaching the next separator or . /// closing bracket. 9,680 ( 0.00%) fn parse_seq_to_end( . &mut self, . ket: &TokenKind, . sep: SeqSep, . f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, . ) -> PResult<'a, (Vec, bool /* trailing */)> { 3,395 ( 0.00%) let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?; 1,449 ( 0.00%) if !recovered { . self.eat(ket); . } 9,445 ( 0.00%) Ok((val, trailing)) 7,744 ( 0.00%) } . . /// Parses a sequence, including the closing delimiter. The function . /// `f` must consume tokens until reaching the next separator or . /// closing bracket. . fn parse_unspanned_seq( . &mut self, . bra: &TokenKind, . ket: &TokenKind, . sep: SeqSep, . f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, . ) -> PResult<'a, (Vec, bool)> { 3,281 ( 0.00%) self.expect(bra)?; 7,744 ( 0.00%) self.parse_seq_to_end(ket, sep, f) . } . . fn parse_delim_comma_seq( . &mut self, . delim: DelimToken, . f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, . ) -> PResult<'a, (Vec, bool)> { . self.parse_unspanned_seq( 1,170 ( 0.00%) &token::OpenDelim(delim), 1,372 ( 0.00%) &token::CloseDelim(delim), . SeqSep::trailing_allowed(token::Comma), . f, . ) . } . . fn parse_paren_comma_seq( . &mut self, . f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, . ) -> PResult<'a, (Vec, bool)> { . self.parse_delim_comma_seq(token::Paren, f) . } . . /// Advance the parser by one token using provided token as the next one. 1,829,997 ( 0.04%) fn bump_with(&mut self, (next_token, next_spacing): (Token, Spacing)) { . // Bumping after EOF is a bad sign, usually an infinite loop. 844,614 ( 0.02%) if self.prev_token.kind == TokenKind::Eof { . let msg = "attempted to bump the parser past EOF (may be stuck in a loop)"; . self.span_bug(self.token.span, msg); . } . . // Update the current and previous tokens. 563,076 ( 0.01%) self.prev_token = mem::replace(&mut self.token, next_token); 140,769 ( 0.00%) self.token_spacing = next_spacing; . . // Diagnostics. 140,769 ( 0.00%) self.expected_tokens.clear(); . } . . /// Advance the parser by one token. 1,126,064 ( 0.02%) pub fn bump(&mut self) { 563,032 ( 0.01%) let next_token = self.next_tok(self.token.span); 844,548 ( 0.02%) self.bump_with(next_token); 1,126,064 ( 0.02%) } . . /// Look-ahead `dist` tokens of `self.token` and get access to that token there. . /// When `dist == 0` then the current token is looked at. . pub fn look_ahead(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R { 1,248 ( 0.00%) if dist == 0 { 596 ( 0.00%) return looker(&self.token); . } . 10,620 ( 0.00%) let frame = &self.token_cursor.frame; 11,651 ( 0.00%) if frame.delim != DelimToken::NoDelim { . let all_normal = (0..dist).all(|i| { 20,225 ( 0.00%) let token = frame.tree_cursor.look_ahead(i); 26,574 ( 0.00%) !matches!(token, Some(TokenTree::Delimited(_, DelimToken::NoDelim, _))) . }); . if all_normal { 33,043 ( 0.00%) return match frame.tree_cursor.look_ahead(dist - 1) { 11,606 ( 0.00%) Some(tree) => match tree { 5,612 ( 0.00%) TokenTree::Token(token) => looker(token), . TokenTree::Delimited(dspan, delim, _) => { 1,893 ( 0.00%) looker(&Token::new(token::OpenDelim(*delim), dspan.open)) . } . }, 7,018 ( 0.00%) None => looker(&Token::new(token::CloseDelim(frame.delim), frame.span.close)), . }; . } . } . . let mut cursor = self.token_cursor.clone(); . let mut i = 0; 4,927 ( 0.00%) let mut token = Token::dummy(); 38 ( 0.00%) while i < dist { 34,281 ( 0.00%) token = cursor.next().0; 14,735 ( 0.00%) if matches!( 9,790 ( 0.00%) token.kind, . token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) . ) { . continue; . } 20 ( 0.00%) i += 1; . } 2,372 ( 0.00%) return looker(&token); . } . . /// Returns whether any of the given keywords are `dist` tokens ahead of the current one. 5,310 ( 0.00%) fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool { 1,291 ( 0.00%) self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw))) 5,310 ( 0.00%) } . . /// Parses asyncness: `async` or nothing. . fn parse_asyncness(&mut self) -> Async { . if self.eat_keyword(kw::Async) { . let span = self.prev_token.uninterpolated_span(); . Async::Yes { span, closure_id: DUMMY_NODE_ID, return_impl_trait_id: DUMMY_NODE_ID } . } else { . Async::No . } . } . . /// Parses unsafety: `unsafe` or nothing. 74 ( 0.00%) fn parse_unsafety(&mut self) -> Unsafe { . if self.eat_keyword(kw::Unsafe) { . Unsafe::Yes(self.prev_token.uninterpolated_span()) . } else { . Unsafe::No . } 296 ( 0.00%) } . . /// Parses constness: `const` or nothing. 1,360 ( 0.00%) fn parse_constness(&mut self) -> Const { . // Avoid const blocks to be parsed as const items 378 ( 0.00%) if self.look_ahead(1, |t| t != &token::OpenDelim(DelimToken::Brace)) . && self.eat_keyword(kw::Const) . { . Const::Yes(self.prev_token.uninterpolated_span()) . } else { . Const::No . } 2,380 ( 0.00%) } . . /// Parses inline const expressions. . fn parse_const_block(&mut self, span: Span, pat: bool) -> PResult<'a, P> { . if pat { . self.sess.gated_spans.gate(sym::inline_const_pat, span); . } else { . self.sess.gated_spans.gate(sym::inline_const, span); . } -- line 1104 ---------------------------------------- -- line 1108 ---------------------------------------- . id: DUMMY_NODE_ID, . value: self.mk_expr(blk.span, ExprKind::Block(blk, None), AttrVec::new()), . }; . let blk_span = anon_const.value.span; . Ok(self.mk_expr(span.to(blk_span), ExprKind::ConstBlock(anon_const), AttrVec::new())) . } . . /// Parses mutability (`mut` or nothing). 32 ( 0.00%) fn parse_mutability(&mut self) -> Mutability { . if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not } 1,226 ( 0.00%) } . . /// Possibly parses mutability (`const` or `mut`). . fn parse_const_or_mut(&mut self) -> Option { . if self.eat_keyword(kw::Mut) { . Some(Mutability::Mut) . } else if self.eat_keyword(kw::Const) { . Some(Mutability::Not) . } else { . None . } . } . . fn parse_field_name(&mut self) -> PResult<'a, Ident> { 18 ( 0.00%) if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind . { . self.expect_no_suffix(self.token.span, "a tuple index", suffix); . self.bump(); . Ok(Ident::new(symbol, self.prev_token.span)) . } else { 27 ( 0.00%) self.parse_ident_common(true) . } . } . . fn parse_mac_args(&mut self) -> PResult<'a, P> { 3,680 ( 0.00%) self.parse_mac_args_common(true).map(P) . } . . fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> { 102 ( 0.00%) self.parse_mac_args_common(false) . } . 15,606 ( 0.00%) fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> { 13,872 ( 0.00%) Ok( 8,692 ( 0.00%) if self.check(&token::OpenDelim(DelimToken::Paren)) 21 ( 0.00%) || self.check(&token::OpenDelim(DelimToken::Bracket)) 12 ( 0.00%) || self.check(&token::OpenDelim(DelimToken::Brace)) . { 6,928 ( 0.00%) match self.parse_token_tree() { 8,660 ( 0.00%) TokenTree::Delimited(dspan, delim, tokens) => . // We've confirmed above that there is a delimiter so unwrapping is OK. . { 3,464 ( 0.00%) MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens) . } . _ => unreachable!(), . } 4 ( 0.00%) } else if !delimited_only { . if self.eat(&token::Eq) { . let eq_span = self.prev_token.span; . . // Collect tokens because they are used during lowering to HIR. . let expr = self.parse_expr_force_collect()?; . let span = expr.span; . . let token_kind = token::Interpolated(Lrc::new(token::NtExpr(expr))); -- line 1172 ---------------------------------------- -- line 1173 ---------------------------------------- . MacArgs::Eq(eq_span, Token::new(token_kind, span)) . } else { . MacArgs::Empty . } . } else { . return self.unexpected(); . }, . ) 12,138 ( 0.00%) } . . fn parse_or_use_outer_attributes( . &mut self, . already_parsed_attrs: Option, . ) -> PResult<'a, AttrWrapper> { 7,914 ( 0.00%) if let Some(attrs) = already_parsed_attrs { . Ok(attrs) . } else { 4,816 ( 0.00%) self.parse_outer_attributes() . } . } . . /// Parses a single token tree from the input. 197,576 ( 0.00%) pub(crate) fn parse_token_tree(&mut self) -> TokenTree { 159,627 ( 0.00%) match self.token.kind { . token::OpenDelim(..) => { . let depth = self.token_cursor.stack.len(); . . // We keep advancing the token cursor until we hit . // the matching `CloseDelim` token. 181,568 ( 0.00%) while !(depth == self.token_cursor.stack.len() . && matches!(self.token.kind, token::CloseDelim(_))) . { . // Advance one token at a time, so `TokenCursor::next()` . // can capture these tokens if necessary. 131,778 ( 0.00%) self.bump(); . } . // We are still inside the frame corresponding . // to the delimited stream we captured, so grab . // the tokens from this frame. . let frame = &self.token_cursor.frame; 6,626 ( 0.00%) let stream = frame.tree_cursor.stream.clone(); 6,626 ( 0.00%) let span = frame.span; 3,313 ( 0.00%) let delim = frame.delim; . // Consume close delimiter 6,626 ( 0.00%) self.bump(); 16,565 ( 0.00%) TokenTree::Delimited(span, delim, stream) . } . token::CloseDelim(_) | token::Eof => unreachable!(), . _ => { 42,768 ( 0.00%) self.bump(); 106,920 ( 0.00%) TokenTree::Token(self.prev_token.clone()) . } . } 172,879 ( 0.00%) } . . /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF. . pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec> { . let mut tts = Vec::new(); . while self.token != token::Eof { . tts.push(self.parse_token_tree()); . } . Ok(tts) -- line 1234 ---------------------------------------- -- line 1244 ---------------------------------------- . } . TokenStream::new(result) . } . . /// Evaluates the closure with restrictions in place. . /// . /// Afters the closure is evaluated, restrictions are reset. . fn with_res(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T { 3,170 ( 0.00%) let old = self.restrictions; 4,055 ( 0.00%) self.restrictions = res; . let res = f(self); 3,569 ( 0.00%) self.restrictions = old; . res . } . 18,088 ( 0.00%) fn is_crate_vis(&self) -> bool { 11,305 ( 0.00%) self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep) 20,349 ( 0.00%) } . . /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`, . /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`. . /// If the following element can't be a tuple (i.e., it's a function definition), then . /// it's not a tuple struct field), and the contents within the parentheses aren't valid, . /// so emit a proper diagnostic. . // Public for rustfmt usage. 1,880 ( 0.00%) pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> { 376 ( 0.00%) maybe_whole!(self, NtVis, |x| x); . 188 ( 0.00%) self.expected_tokens.push(TokenType::Keyword(kw::Crate)); 752 ( 0.00%) if self.is_crate_vis() { . self.bump(); // `crate` . self.sess.gated_spans.gate(sym::crate_visibility_modifier, self.prev_token.span); . return Ok(Visibility { . span: self.prev_token.span, . kind: VisibilityKind::Crate(CrateSugar::JustCrate), . tokens: None, . }); . } . . if !self.eat_keyword(kw::Pub) { . // We need a span for our `Spanned`, but there's inherently no . // keyword to grab a span from for inherited visibility; an empty span at the . // beginning of the current token would seem to be the "Schelling span". 178 ( 0.00%) return Ok(Visibility { 534 ( 0.00%) span: self.token.span.shrink_to_lo(), . kind: VisibilityKind::Inherited, . tokens: None, . }); . } 10 ( 0.00%) let lo = self.prev_token.span; . 50 ( 0.00%) if self.check(&token::OpenDelim(token::Paren)) { . // We don't `self.bump()` the `(` yet because this might be a struct definition where . // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`. . // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so . // by the following tokens. 45 ( 0.00%) if self.is_keyword_ahead(1, &[kw::Crate]) && self.look_ahead(2, |t| t != &token::ModSep) . // account for `pub(crate::foo)` . { . // Parse `pub(crate)`. 15 ( 0.00%) self.bump(); // `(` 10 ( 0.00%) self.bump(); // `crate` 15 ( 0.00%) self.expect(&token::CloseDelim(token::Paren))?; // `)` 5 ( 0.00%) let vis = VisibilityKind::Crate(CrateSugar::PubCrate); . return Ok(Visibility { 15 ( 0.00%) span: lo.to(self.prev_token.span), . kind: vis, . tokens: None, . }); . } else if self.is_keyword_ahead(1, &[kw::In]) { . // Parse `pub(in path)`. . self.bump(); // `(` . self.bump(); // `in` . let path = self.parse_path(PathStyle::Mod)?; // `path` -- line 1317 ---------------------------------------- -- line 1338 ---------------------------------------- . } else if let FollowedByType::No = fbt { . // Provide this diagnostic if a type cannot follow; . // in particular, if this is not a tuple struct. . self.recover_incorrect_vis_restriction()?; . // Emit diagnostic, but continue with public visibility. . } . } . 15 ( 0.00%) Ok(Visibility { span: lo, kind: VisibilityKind::Public, tokens: None }) 1,692 ( 0.00%) } . . /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }` . fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> { . self.bump(); // `(` . let path = self.parse_path(PathStyle::Mod)?; . self.expect(&token::CloseDelim(token::Paren))?; // `)` . . let msg = "incorrect visibility restriction"; -- line 1355 ---------------------------------------- -- line 1370 ---------------------------------------- . ) . .emit(); . . Ok(()) . } . . /// Parses `extern string_literal?`. . fn parse_extern(&mut self) -> Extern { 27 ( 0.00%) if self.eat_keyword(kw::Extern) { Extern::from_abi(self.parse_abi()) } else { Extern::None } . } . . /// Parses a string literal as an ABI spec. . fn parse_abi(&mut self) -> Option { . match self.parse_str_lit() { . Ok(str_lit) => Some(str_lit), . Err(Some(lit)) => match lit.kind { . ast::LitKind::Err(_) => None, -- line 1386 ---------------------------------------- -- line 1395 ---------------------------------------- . .emit(); . None . } . }, . Err(None) => None, . } . } . 30 ( 0.00%) pub fn collect_tokens_no_attrs( . &mut self, . f: impl FnOnce(&mut Self) -> PResult<'a, R>, . ) -> PResult<'a, R> { . // The only reason to call `collect_tokens_no_attrs` is if you want tokens, so use . // `ForceCollect::Yes` . self.collect_tokens_trailing_token( . AttrWrapper::empty(), . ForceCollect::Yes, 6 ( 0.00%) |this, _attrs| Ok((f(this)?, TrailingToken::None)), . ) 30 ( 0.00%) } . . /// `::{` or `::*` 58,136 ( 0.00%) fn is_import_coupler(&mut self) -> bool { 29,068 ( 0.00%) self.check(&token::ModSep) . && self.look_ahead(1, |t| { 32,041 ( 0.00%) *t == token::OpenDelim(token::Brace) || *t == token::BinOp(token::Star) . }) 58,122 ( 0.00%) } . . pub fn clear_expected_tokens(&mut self) { . self.expected_tokens.clear(); . } . } . . crate fn make_unclosed_delims_error( . unmatched: UnmatchedBrace, -- line 1430 ---------------------------------------- -- line 1450 ---------------------------------------- . err.span_label(sp, "closing delimiter possibly meant for this"); . } . if let Some(sp) = unmatched.unclosed_span { . err.span_label(sp, "unclosed delimiter"); . } . Some(err) . } . 199,280 ( 0.00%) pub fn emit_unclosed_delims(unclosed_delims: &mut Vec, sess: &ParseSess) { 99,640 ( 0.00%) *sess.reached_eof.borrow_mut() |= . unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none()); 99,640 ( 0.00%) for unmatched in unclosed_delims.drain(..) { . if let Some(mut e) = make_unclosed_delims_error(unmatched, sess) { . e.emit(); . } . } 199,280 ( 0.00%) } . . /// A helper struct used when building an `AttrAnnotatedTokenStream` from . /// a `LazyTokenStream`. Both delimiter and non-delimited tokens . /// are stored as `FlatToken::Token`. A vector of `FlatToken`s . /// is then 'parsed' to build up an `AttrAnnotatedTokenStream` with nested . /// `AttrAnnotatedTokenTree::Delimited` tokens . #[derive(Debug, Clone)] . pub enum FlatToken { -- line 1474 ---------------------------------------- 737,146 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs -------------------------------------------------------------------------------- Ir -- line 293 ---------------------------------------- . . #[allow(deprecated)] . impl From for CollectionAllocErr { . fn from(_: LayoutErr) -> Self { . CollectionAllocErr::CapacityOverflow . } . } . 481 ( 0.00%) fn infallible(result: Result) -> T { 229,801 ( 0.00%) match result { . Ok(x) => x, . Err(CollectionAllocErr::CapacityOverflow) => panic!("capacity overflow"), . Err(CollectionAllocErr::AllocErr { layout }) => alloc::alloc::handle_alloc_error(layout), . } 962 ( 0.00%) } . . /// FIXME: use `Layout::array` when we require a Rust version where it’s stable . /// https://github.com/rust-lang/rust/issues/55724 . fn layout_array(n: usize) -> Result { . let size = mem::size_of::() . .checked_mul(n) . .ok_or(CollectionAllocErr::CapacityOverflow)?; . let align = mem::align_of::(); -- line 315 ---------------------------------------- -- line 376 ---------------------------------------- . fn len(&self) -> usize { . self.iter.len() . } . } . . impl<'a, T: Array> FusedIterator for Drain<'a, T> {} . . impl<'a, T: 'a + Array> Drop for Drain<'a, T> { 3,948 ( 0.00%) fn drop(&mut self) { . self.for_each(drop); . 1,692 ( 0.00%) if self.tail_len > 0 { . unsafe { . let source_vec = self.vec.as_mut(); . . // memmove back untouched tail, update to new length . let start = source_vec.len(); . let tail = self.tail_start; . if tail != start { . let src = source_vec.as_ptr().add(tail); . let dst = source_vec.as_mut_ptr().add(start); . ptr::copy(src, dst, self.tail_len); . } . source_vec.set_len(start + self.tail_len); . } . } 3,948 ( 0.00%) } . } . . #[cfg(feature = "union")] . union SmallVecData { . inline: core::mem::ManuallyDrop>, . heap: (*mut A::Item, usize), . } . -- line 410 ---------------------------------------- -- line 422 ---------------------------------------- . #[cfg(feature = "union")] . impl SmallVecData { . #[inline] . unsafe fn inline(&self) -> *const A::Item { . self.inline.as_ptr() as *const A::Item . } . #[inline] . unsafe fn inline_mut(&mut self) -> *mut A::Item { 38,196 ( 0.00%) self.inline.as_mut_ptr() as *mut A::Item . } . #[inline] . fn from_inline(inline: MaybeUninit) -> SmallVecData { . SmallVecData { . inline: core::mem::ManuallyDrop::new(inline), . } . } . #[inline] . unsafe fn into_inline(self) -> MaybeUninit { . core::mem::ManuallyDrop::into_inner(self.inline) . } . #[inline] . unsafe fn heap(&self) -> (*mut A::Item, usize) { 40,052 ( 0.00%) self.heap . } . #[inline] . unsafe fn heap_mut(&mut self) -> &mut (*mut A::Item, usize) { . &mut self.heap . } . #[inline] . fn from_heap(ptr: *mut A::Item, len: usize) -> SmallVecData { . SmallVecData { heap: (ptr, len) } -- line 452 ---------------------------------------- -- line 557 ---------------------------------------- . #[inline] . pub fn new() -> SmallVec { . // Try to detect invalid custom implementations of `Array`. Hopefully, . // this check should be optimized away entirely for valid ones. . assert!( . mem::size_of::() == A::size() * mem::size_of::() . && mem::align_of::() >= mem::align_of::() . ); 435,214 ( 0.01%) SmallVec { . capacity: 0, . data: SmallVecData::from_inline(MaybeUninit::uninit()), . } . } . . /// Construct an empty vector with enough capacity pre-allocated to store at least `n` . /// elements. . /// -- line 573 ---------------------------------------- -- line 597 ---------------------------------------- . /// . /// let vec = vec![1, 2, 3, 4, 5]; . /// let small_vec: SmallVec<[_; 3]> = SmallVec::from_vec(vec); . /// . /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]); . /// ``` . #[inline] . pub fn from_vec(mut vec: Vec) -> SmallVec { 2,222 ( 0.00%) if vec.capacity() <= Self::inline_capacity() { . unsafe { . let mut data = SmallVecData::::from_inline(MaybeUninit::uninit()); . let len = vec.len(); . vec.set_len(0); . ptr::copy_nonoverlapping(vec.as_ptr(), data.inline_mut(), len); . . SmallVec { . capacity: len, . data, . } . } . } else { . let (ptr, cap, len) = (vec.as_mut_ptr(), vec.capacity(), vec.len()); . mem::forget(vec); . 3,516 ( 0.00%) SmallVec { . capacity: cap, . data: SmallVecData::from_heap(ptr, len), . } . } . } . . /// Constructs a new `SmallVec` on the stack from an `A` without . /// copying elements. -- line 629 ---------------------------------------- -- line 635 ---------------------------------------- . /// let small_vec: SmallVec<_> = SmallVec::from_buf(buf); . /// . /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]); . /// ``` . #[inline] . pub fn from_buf(buf: A) -> SmallVec { . SmallVec { . capacity: A::size(), 2,730 ( 0.00%) data: SmallVecData::from_inline(MaybeUninit::new(buf)), . } . } . . /// Constructs a new `SmallVec` on the stack from an `A` without . /// copying elements. Also sets the length, which must be less or . /// equal to the size of `buf`. . /// . /// ```rust -- line 651 ---------------------------------------- -- line 653 ---------------------------------------- . /// . /// let buf = [1, 2, 3, 4, 5, 0, 0, 0]; . /// let small_vec: SmallVec<_> = SmallVec::from_buf_and_len(buf, 5); . /// . /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]); . /// ``` . #[inline] . pub fn from_buf_and_len(buf: A, len: usize) -> SmallVec { 22,650 ( 0.00%) assert!(len <= A::size()); 67,950 ( 0.00%) unsafe { SmallVec::from_buf_and_len_unchecked(MaybeUninit::new(buf), len) } . } . . /// Constructs a new `SmallVec` on the stack from an `A` without . /// copying elements. Also sets the length. The user is responsible . /// for ensuring that `len <= A::size()`. . /// . /// ```rust . /// use smallvec::SmallVec; -- line 670 ---------------------------------------- -- line 674 ---------------------------------------- . /// let small_vec: SmallVec<_> = unsafe { . /// SmallVec::from_buf_and_len_unchecked(MaybeUninit::new(buf), 5) . /// }; . /// . /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]); . /// ``` . #[inline] . pub unsafe fn from_buf_and_len_unchecked(buf: MaybeUninit, len: usize) -> SmallVec { 11,325 ( 0.00%) SmallVec { . capacity: len, . data: SmallVecData::from_inline(buf), . } . } . . /// Sets the length of a vector. . /// . /// This will explicitly set the size of the vector, without actually . /// modifying its buffers, so it is up to the caller to ensure that the . /// vector is actually the specified size. . pub unsafe fn set_len(&mut self, new_len: usize) { . let (_, len_ptr, _) = self.triple_mut(); 49,021 ( 0.00%) *len_ptr = new_len; . } . . /// The maximum number of elements this vector can hold inline . #[inline] . fn inline_capacity() -> usize { . if mem::size_of::() > 0 { 8 ( 0.00%) A::size() . } else { . // For zero-size items code like `ptr.add(offset)` always returns the same pointer. . // Therefore all items are at the same address, . // and any array size has capacity for infinitely many items. . // The capacity is limited by the bit width of the length field. . // . // `Vec` also does this: . // https://github.com/rust-lang/rust/blob/1.44.0/src/liballoc/raw_vec.rs#L186 -- line 710 ---------------------------------------- -- line 725 ---------------------------------------- . #[inline] . pub fn len(&self) -> usize { . self.triple().1 . } . . /// Returns `true` if the vector is empty . #[inline] . pub fn is_empty(&self) -> bool { 204,606 ( 0.00%) self.len() == 0 . } . . /// The number of items the vector can hold without reallocating . #[inline] . pub fn capacity(&self) -> usize { . self.triple().2 . } . . /// Returns a tuple with (data ptr, len, capacity) . /// Useful to get all SmallVec properties with a single check of the current storage variant. . #[inline] . fn triple(&self) -> (*const A::Item, usize, usize) { . unsafe { 2,163,362 ( 0.04%) if self.spilled() { . let (ptr, len) = self.data.heap(); . (ptr, len, self.capacity) . } else { . (self.data.inline(), self.capacity, Self::inline_capacity()) . } . } . } . . /// Returns a tuple with (data ptr, len ptr, capacity) . #[inline] . fn triple_mut(&mut self) -> (*mut A::Item, &mut usize, usize) { . unsafe { 6,124,254 ( 0.12%) if self.spilled() { 14,656 ( 0.00%) let &mut (ptr, ref mut len_ptr) = self.data.heap_mut(); . (ptr, len_ptr, self.capacity) . } else { . ( . self.data.inline_mut(), . &mut self.capacity, . Self::inline_capacity(), . ) . } . } . } . . /// Returns `true` if the data has spilled into a separate heap-allocated buffer. . #[inline] . pub fn spilled(&self) -> bool { 5,119,579 ( 0.10%) self.capacity > Self::inline_capacity() . } . . /// Creates a draining iterator that removes the specified range in the vector . /// and yields the removed items. . /// . /// Note 1: The element range is removed even if the iterator is only . /// partially consumed or not consumed at all. . /// . /// Note 2: It is unspecified how many elements are removed from the vector . /// if the `Drain` value is leaked. . /// . /// # Panics . /// . /// Panics if the starting point is greater than the end point or if . /// the end point is greater than the length of the vector. 564 ( 0.00%) pub fn drain(&mut self, range: R) -> Drain<'_, A> . where . R: RangeBounds, . { . use core::ops::Bound::*; . . let len = self.len(); . let start = match range.start_bound() { . Included(&n) => n, -- line 800 ---------------------------------------- -- line 810 ---------------------------------------- . assert!(start <= end); . assert!(end <= len); . . unsafe { . self.set_len(start); . . let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start), end - start); . 2,820 ( 0.00%) Drain { . tail_start: end, . tail_len: len - end, . iter: range_slice.iter(), . vec: NonNull::from(self), . } . } 564 ( 0.00%) } . . /// Append an item to the vector. . #[inline] 54,480 ( 0.00%) pub fn push(&mut self, value: A::Item) { . unsafe { . let (mut ptr, mut len, cap) = self.triple_mut(); 901,374 ( 0.02%) if *len == cap { 697 ( 0.00%) self.reserve(1); 8,325 ( 0.00%) let &mut (heap_ptr, ref mut heap_len) = self.data.heap_mut(); . ptr = heap_ptr; . len = heap_len; . } 10,910 ( 0.00%) ptr::write(ptr.add(*len), value); 1,298,220 ( 0.02%) *len += 1; . } 43,584 ( 0.00%) } . . /// Remove an item from the end of the vector and return it, or None if empty. . #[inline] . pub fn pop(&mut self) -> Option { . unsafe { . let (ptr, len_ptr, _) = self.triple_mut(); 541,338 ( 0.01%) if *len_ptr == 0 { 368 ( 0.00%) return None; . } 145,204 ( 0.00%) let last_index = *len_ptr - 1; 188,686 ( 0.00%) *len_ptr = last_index; 38,825 ( 0.00%) Some(ptr::read(ptr.add(last_index))) . } 1,420 ( 0.00%) } . . /// Moves all the elements of `other` into `self`, leaving `other` empty. . /// . /// # Example . /// . /// ``` . /// # use smallvec::{SmallVec, smallvec}; . /// let mut v0: SmallVec<[u8; 16]> = smallvec![1, 2, 3]; -- line 863 ---------------------------------------- -- line 879 ---------------------------------------- . /// or if the capacity computation overflows `usize`. . pub fn grow(&mut self, new_cap: usize) { . infallible(self.try_grow(new_cap)) . } . . /// Re-allocate to set the capacity to `max(new_cap, inline_size())`. . /// . /// Panics if `new_cap` is less than the vector's length 2,610 ( 0.00%) pub fn try_grow(&mut self, new_cap: usize) -> Result<(), CollectionAllocErr> { . unsafe { 70 ( 0.00%) let (ptr, &mut len, cap) = self.triple_mut(); . let unspilled = !self.spilled(); 16,168 ( 0.00%) assert!(new_cap >= len); 16,168 ( 0.00%) if new_cap <= self.inline_size() { . if unspilled { . return Ok(()); . } . self.data = SmallVecData::from_inline(MaybeUninit::uninit()); . ptr::copy_nonoverlapping(ptr, self.data.inline_mut(), len); . self.capacity = len; . deallocate(ptr, cap); 16,168 ( 0.00%) } else if new_cap != cap { 14,346 ( 0.00%) let layout = layout_array::(new_cap)?; . debug_assert!(layout.size() > 0); . let new_alloc; 8,084 ( 0.00%) if unspilled { . new_alloc = NonNull::new(alloc::alloc::alloc(layout)) . .ok_or(CollectionAllocErr::AllocErr { layout })? . .cast() . .as_ptr(); . ptr::copy_nonoverlapping(ptr, new_alloc, len); . } else { . // This should never fail since the same succeeded . // when previously allocating `ptr`. 4,288 ( 0.00%) let old_layout = layout_array::(cap)?; . . let new_ptr = alloc::alloc::realloc(ptr as *mut u8, old_layout, layout.size()); . new_alloc = NonNull::new(new_ptr) . .ok_or(CollectionAllocErr::AllocErr { layout })? . .cast() . .as_ptr(); . } 16,168 ( 0.00%) self.data = SmallVecData::from_heap(new_alloc, len); 22,367 ( 0.00%) self.capacity = new_cap; . } . Ok(()) . } 2,680 ( 0.00%) } . . /// Reserve capacity for `additional` more elements to be inserted. . /// . /// May reserve more space to avoid frequent reallocations. . /// . /// Panics if the capacity computation overflows `usize`. . #[inline] 130,933 ( 0.00%) pub fn reserve(&mut self, additional: usize) { 246,295 ( 0.00%) infallible(self.try_reserve(additional)) 148,232 ( 0.00%) } . . /// Reserve capacity for `additional` more elements to be inserted. . /// . /// May reserve more space to avoid frequent reallocations. 947,512 ( 0.02%) pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> { . // prefer triple_mut() even if triple() would work . // so that the optimizer removes duplicated calls to it . // from callers like insert() 3,138 ( 0.00%) let (_, &mut len, cap) = self.triple_mut(); 889,982 ( 0.02%) if cap - len >= additional { . return Ok(()); . } . let new_cap = len . .checked_add(additional) . .and_then(usize::checked_next_power_of_two) . .ok_or(CollectionAllocErr::CapacityOverflow)?; 726 ( 0.00%) self.try_grow(new_cap) 1,032,931 ( 0.02%) } . . /// Reserve the minimum capacity for `additional` more elements to be inserted. . /// . /// Panics if the new capacity overflows `usize`. . pub fn reserve_exact(&mut self, additional: usize) { . infallible(self.try_reserve_exact(additional)) . } . . /// Reserve the minimum capacity for `additional` more elements to be inserted. . pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), CollectionAllocErr> { . let (_, &mut len, cap) = self.triple_mut(); 42,589 ( 0.00%) if cap - len >= additional { . return Ok(()); . } . let new_cap = len . .checked_add(additional) . .ok_or(CollectionAllocErr::CapacityOverflow)?; 1 ( 0.00%) self.try_grow(new_cap) 1 ( 0.00%) } . . /// Shrink the capacity of the vector as much as possible. . /// . /// When possible, this will move data from an external heap buffer to the vector's inline . /// storage. . pub fn shrink_to_fit(&mut self) { . if !self.spilled() { . return; -- line 981 ---------------------------------------- -- line 999 ---------------------------------------- . /// If `len` is greater than or equal to the vector's current length, this has no . /// effect. . /// . /// This does not re-allocate. If you want the vector's capacity to shrink, call . /// `shrink_to_fit` after truncating. . pub fn truncate(&mut self, len: usize) { . unsafe { . let (ptr, len_ptr, _) = self.triple_mut(); 21,114 ( 0.00%) while len < *len_ptr { . let last_index = *len_ptr - 1; . *len_ptr = last_index; . ptr::drop_in_place(ptr.add(last_index)); . } . } . } . . /// Extracts a slice containing the entire vector. -- line 1015 ---------------------------------------- -- line 1044 ---------------------------------------- . pub fn clear(&mut self) { . self.truncate(0); . } . . /// Remove and return the element at position `index`, shifting all elements after it to the . /// left. . /// . /// Panics if `index` is out of bounds. 48 ( 0.00%) pub fn remove(&mut self, index: usize) -> A::Item { . unsafe { . let (mut ptr, len_ptr, _) = self.triple_mut(); 2,475 ( 0.00%) let len = *len_ptr; 7,965 ( 0.00%) assert!(index < len); 11,166 ( 0.00%) *len_ptr = len - 1; . ptr = ptr.add(index); . let item = ptr::read(ptr); 5,310 ( 0.00%) ptr::copy(ptr.add(1), ptr, len - index - 1); . item . } 60 ( 0.00%) } . . /// Insert an element at position `index`, shifting all elements after it to the right. . /// . /// Panics if `index` is out of bounds. 18,896 ( 0.00%) pub fn insert(&mut self, index: usize, element: A::Item) { . self.reserve(1); . . unsafe { . let (mut ptr, len_ptr, _) = self.triple_mut(); 3,927 ( 0.00%) let len = *len_ptr; 7,854 ( 0.00%) assert!(index <= len); 15,708 ( 0.00%) *len_ptr = len + 1; . ptr = ptr.add(index); 7,854 ( 0.00%) ptr::copy(ptr, ptr.add(1), len - index); . ptr::write(ptr, element); . } 12,027 ( 0.00%) } . . /// Insert multiple elements at position `index`, shifting all following elements toward the . /// back. . pub fn insert_many>(&mut self, index: usize, iterable: I) { . let mut iter = iterable.into_iter(); . if index == self.len() { . return self.extend(iter); . } -- line 1088 ---------------------------------------- -- line 1201 ---------------------------------------- . } . } . . /// Retains only the elements specified by the predicate. . /// . /// In other words, remove all elements `e` such that `f(&e)` returns `false`. . /// This method operates in place and preserves the order of the retained . /// elements. 49,527 ( 0.00%) pub fn retain bool>(&mut self, mut f: F) { . let mut del = 0; . let len = self.len(); . for i in 0..len { 9,756 ( 0.00%) if !f(&mut self[i]) { . del += 1; 3,114 ( 0.00%) } else if del > 0 { . self.swap(i - del, i); . } . } 11,006 ( 0.00%) self.truncate(len - del); 44,024 ( 0.00%) } . . /// Removes consecutive duplicate elements. . pub fn dedup(&mut self) . where . A::Item: PartialEq, . { . self.dedup_by(|a, b| a == b); . } -- line 1228 ---------------------------------------- -- line 1418 ---------------------------------------- . capacity: len, . data: SmallVecData::from_inline(unsafe { . let mut data: MaybeUninit = MaybeUninit::uninit(); . ptr::copy_nonoverlapping( . slice.as_ptr(), . data.as_mut_ptr() as *mut A::Item, . len, . ); 1,998 ( 0.00%) data . }), . } . } else { . let mut b = slice.to_vec(); . let (ptr, cap) = (b.as_mut_ptr(), b.capacity()); . mem::forget(b); . SmallVec { . capacity: cap, -- line 1434 ---------------------------------------- -- line 1436 ---------------------------------------- . } . } . } . . /// Copy elements from a slice into the vector at position `index`, shifting any following . /// elements toward the back. . /// . /// For slices of `Copy` types, this is more efficient than `insert`. 144,024 ( 0.00%) pub fn insert_from_slice(&mut self, index: usize, slice: &[A::Item]) { . self.reserve(slice.len()); . . let len = self.len(); 46,275 ( 0.00%) assert!(index <= len); . . unsafe { . let slice_ptr = slice.as_ptr(); . let ptr = self.as_mut_ptr().add(index); . ptr::copy(ptr, ptr.add(slice.len()), len - index); . ptr::copy_nonoverlapping(slice_ptr, ptr, slice.len()); 30,850 ( 0.00%) self.set_len(len + slice.len()); . } 123,400 ( 0.00%) } . . /// Copy elements from a slice and append them to the vector. . /// . /// For slices of `Copy` types, this is more efficient than `extend`. . #[inline] . pub fn extend_from_slice(&mut self, slice: &[A::Item]) { . let len = self.len(); 36,778 ( 0.00%) self.insert_from_slice(len, slice); . } . } . . impl SmallVec . where . A::Item: Clone, . { . /// Resizes the vector so that its length is equal to `len`. -- line 1473 ---------------------------------------- -- line 1489 ---------------------------------------- . /// Creates a `SmallVec` with `n` copies of `elem`. . /// ``` . /// use smallvec::SmallVec; . /// . /// let v = SmallVec::<[char; 128]>::from_elem('d', 2); . /// assert_eq!(v, SmallVec::from_buf(['d', 'd'])); . /// ``` . pub fn from_elem(elem: A::Item, n: usize) -> Self { 6,644 ( 0.00%) if n > Self::inline_capacity() { . vec![elem; n].into() . } else { . let mut v = SmallVec::::new(); . unsafe { . let (ptr, len_ptr, _) = v.triple_mut(); . let mut local_len = SetLenOnDrop::new(len_ptr); . . for i in 0..n { . ::core::ptr::write(ptr.add(i), elem.clone()); . local_len.increment_len(1); . } . } 9,783 ( 0.00%) v . } . } . } . . impl ops::Deref for SmallVec { . type Target = [A::Item]; . #[inline] . fn deref(&self) -> &[A::Item] { -- line 1518 ---------------------------------------- -- line 1522 ---------------------------------------- . } . } . } . . impl ops::DerefMut for SmallVec { . #[inline] . fn deref_mut(&mut self) -> &mut [A::Item] { . unsafe { 48,264 ( 0.00%) let (ptr, &mut len, _) = self.triple_mut(); . slice::from_raw_parts_mut(ptr, len) . } . } . } . . impl AsRef<[A::Item]> for SmallVec { . #[inline] . fn as_ref(&self) -> &[A::Item] { -- line 1538 ---------------------------------------- -- line 1716 ---------------------------------------- . SmallVec::extend_from_slice(self, other) . } . } . . impl FromIterator for SmallVec { . #[inline] . fn from_iter>(iterable: I) -> SmallVec { . let mut v = SmallVec::new(); 438,509 ( 0.01%) v.extend(iterable); . v . } . } . . impl Extend for SmallVec { 1,464,981 ( 0.03%) fn extend>(&mut self, iterable: I) { 162,717 ( 0.00%) let mut iter = iterable.into_iter(); . let (lower_size_bound, _) = iter.size_hint(); 22,868 ( 0.00%) self.reserve(lower_size_bound); . . unsafe { . let (ptr, len_ptr, cap) = self.triple_mut(); . let mut len = SetLenOnDrop::new(len_ptr); 696,320 ( 0.01%) while len.get() < cap { 235,940 ( 0.00%) if let Some(out) = iter.next() { 130 ( 0.00%) ptr::write(ptr.add(len.get()), out); . len.increment_len(1); . } else { . return; . } . } . } . 56,538 ( 0.00%) for elem in iter { 4,736 ( 0.00%) self.push(elem); . } 1,273,205 ( 0.02%) } . } . . impl fmt::Debug for SmallVec . where . A::Item: fmt::Debug, . { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . f.debug_list().entries(self.iter()).finish() -- line 1759 ---------------------------------------- -- line 1764 ---------------------------------------- . #[inline] . fn default() -> SmallVec { . SmallVec::new() . } . } . . #[cfg(feature = "may_dangle")] . unsafe impl<#[may_dangle] A: Array> Drop for SmallVec { 1,859,473 ( 0.04%) fn drop(&mut self) { . unsafe { 1,099,158 ( 0.02%) if self.spilled() { . let (ptr, len) = self.data.heap(); . Vec::from_raw_parts(ptr, len, self.capacity); . } else { . ptr::drop_in_place(&mut self[..]); . } . } 1,903,998 ( 0.04%) } . } . . #[cfg(not(feature = "may_dangle"))] . impl Drop for SmallVec { . fn drop(&mut self) { . unsafe { . if self.spilled() { . let (ptr, len) = self.data.heap(); -- line 1789 ---------------------------------------- -- line 1888 ---------------------------------------- . A::Item: Clone, . { . fn clone(&self) -> IntoIter { . SmallVec::from(self.as_slice()).into_iter() . } . } . . impl Drop for IntoIter { 1,071 ( 0.00%) fn drop(&mut self) { 17,849 ( 0.00%) for _ in self {} 1,000 ( 0.00%) } . } . . impl Iterator for IntoIter { . type Item = A::Item; . . #[inline] . fn next(&mut self) -> Option { 170,099 ( 0.00%) if self.current == self.end { 576 ( 0.00%) None . } else { . unsafe { . let current = self.current; 86,159 ( 0.00%) self.current += 1; 1,650 ( 0.00%) Some(ptr::read(self.data.as_ptr().add(current))) . } . } . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 6,282 ( 0.00%) let size = self.end - self.current; . (size, Some(size)) . } . } . . impl DoubleEndedIterator for IntoIter { . #[inline] . fn next_back(&mut self) -> Option { . if self.current == self.end { -- line 1927 ---------------------------------------- -- line 1955 ---------------------------------------- . impl IntoIterator for SmallVec { . type IntoIter = IntoIter; . type Item = A::Item; . fn into_iter(mut self) -> Self::IntoIter { . unsafe { . // Set SmallVec len to zero as `IntoIter` drop handles dropping of the elements . let len = self.len(); . self.set_len(0); 16,920 ( 0.00%) IntoIter { 102,613 ( 0.00%) data: self, . current: 0, . end: len, . } . } . } . } . . impl<'a, A: Array> IntoIterator for &'a SmallVec { -- line 1972 ---------------------------------------- -- line 2000 ---------------------------------------- . len: &'a mut usize, . local_len: usize, . } . . impl<'a> SetLenOnDrop<'a> { . #[inline] . fn new(len: &'a mut usize) -> Self { . SetLenOnDrop { 162,453 ( 0.00%) local_len: *len, . len, . } . } . . #[inline] . fn get(&self) -> usize { . self.local_len . } . . #[inline] . fn increment_len(&mut self, increment: usize) { 126,966 ( 0.00%) self.local_len += increment; . } . } . . impl<'a> Drop for SetLenOnDrop<'a> { . #[inline] . fn drop(&mut self) { 188,443 ( 0.00%) *self.len = self.local_len; . } . } . . #[cfg(feature = "const_new")] . impl SmallVec<[T; N]> { . /// Construct an empty vector. . /// . /// This is a `const` version of [`SmallVec::new`] that is enabled by the feature `const_new`, with the limitation that it only works for arrays. -- line 2035 ---------------------------------------- 2,955,736 ( 0.06%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe/macro_parser.rs -------------------------------------------------------------------------------- Ir -- line 90 ---------------------------------------- . use std::collections::hash_map::Entry::{Occupied, Vacant}; . use std::mem; . use std::ops::{Deref, DerefMut}; . . // To avoid costly uniqueness checks, we require that `MatchSeq` always has a nonempty body. . . /// Either a sequence of token trees or a single one. This is used as the representation of the . /// sequence of tokens that make up a matcher. 88,027 ( 0.00%) #[derive(Clone)] . enum TokenTreeOrTokenTreeSlice<'tt> { . Tt(TokenTree), 21,659 ( 0.00%) TtSeq(&'tt [TokenTree]), . } . . impl<'tt> TokenTreeOrTokenTreeSlice<'tt> { . /// Returns the number of constituent top-level token trees of `self` (top-level in that it . /// will not recursively descend into subtrees). . fn len(&self) -> usize { 500,025 ( 0.01%) match *self { 118,036 ( 0.00%) TtSeq(ref v) => v.len(), . Tt(ref tt) => tt.len(), . } . } . . /// The `index`-th token tree of `self`. . fn get_tt(&self, index: usize) -> TokenTree { 109,119 ( 0.00%) match *self { 367,000 ( 0.01%) TtSeq(ref v) => v[index].clone(), 112,731 ( 0.00%) Tt(ref tt) => tt.get_tt(index), . } . } . } . . /// An unzipping of `TokenTree`s... see the `stack` field of `MatcherPos`. . /// . /// This is used by `inner_parse_loop` to keep track of delimited submatchers that we have . /// descended into. 13,512 ( 0.00%) #[derive(Clone)] . struct MatcherTtFrame<'tt> { . /// The "parent" matcher that we are descending into. . elts: TokenTreeOrTokenTreeSlice<'tt>, . /// The position of the "dot" in `elts` at the time we descended. 6,756 ( 0.00%) idx: usize, . } . . type NamedMatchVec = SmallVec<[NamedMatch; 4]>; . . /// Represents a single "position" (aka "matcher position", aka "item"), as . /// described in the module documentation. . /// . /// Here: -- line 140 ---------------------------------------- -- line 147 ---------------------------------------- . /// position refers to. . /// . /// It is important to distinguish these two lifetimes because we have a . /// `SmallVec>` below, and the destructor of . /// that is considered to possibly access the data from its elements (it lacks . /// a `#[may_dangle]` attribute). As a result, the compiler needs to know that . /// all the elements in that `SmallVec` strictly outlive the root stack slot . /// lifetime. By separating `'tt` from `'root`, we can show that. 382,909 ( 0.01%) #[derive(Clone)] . struct MatcherPos<'root, 'tt> { . /// The token or sequence of tokens that make up the matcher . top_elts: TokenTreeOrTokenTreeSlice<'tt>, . . /// The position of the "dot" in this matcher 8,147 ( 0.00%) idx: usize, . . /// For each named metavar in the matcher, we keep track of token trees matched against the . /// metavar by the black box parser. In particular, there may be more than one match per . /// metavar if we are in a repetition (each repetition matches each of the variables). . /// Moreover, matchers and repetitions can be nested; the `matches` field is shared (hence the . /// `Rc`) among all "nested" matchers. `match_lo`, `match_cur`, and `match_hi` keep track of . /// the current position of the `self` matcher position in the shared `matches` list. . /// . /// Also, note that while we are descending into a sequence, matchers are given their own . /// `matches` vector. Only once we reach the end of a full repetition of the sequence do we add . /// all bound matches from the submatcher into the shared top-level `matches` vector. If `sep` . /// and `up` are `Some`, then `matches` is _not_ the shared top-level list. Instead, if one . /// wants the shared `matches`, one should use `up.matches`. 32,588 ( 0.00%) matches: Box<[Lrc]>, . /// The position in `matches` corresponding to the first metavar in this matcher's sequence of . /// token trees. In other words, the first metavar in the first token of `top_elts` corresponds . /// to `matches[match_lo]`. 8,147 ( 0.00%) match_lo: usize, . /// The position in `matches` corresponding to the metavar we are currently trying to match . /// against the source token stream. `match_lo <= match_cur <= match_hi`. . match_cur: usize, . /// Similar to `match_lo` except `match_hi` is the position in `matches` of the _last_ metavar . /// in this matcher. 8,147 ( 0.00%) match_hi: usize, . . // The following fields are used if we are matching a repetition. If we aren't, they should be . // `None`. . /// The KleeneOp of this sequence if we are in a repetition. 8,147 ( 0.00%) seq_op: Option, . . /// The separator if we are in a repetition. . sep: Option, . . /// The "parent" matcher position if we are in a repetition. That is, the matcher position just . /// before we enter the sequence. 16,294 ( 0.00%) up: Option>, . . /// Specifically used to "unzip" token trees. By "unzip", we mean to unwrap the delimiters from . /// a delimited token tree (e.g., something wrapped in `(` `)`) or to get the contents of a doc . /// comment... . /// . /// When matching against matchers with nested delimited submatchers (e.g., `pat ( pat ( .. ) . /// pat ) pat`), we need to keep track of the matchers we are descending into. This stack does . /// that where the bottom of the stack is the outermost matcher. . /// Also, throughout the comments, this "descent" is often referred to as "unzipping"... . stack: SmallVec<[MatcherTtFrame<'tt>; 1]>, . } . . impl<'root, 'tt> MatcherPos<'root, 'tt> { . /// Adds `m` as a named match for the `idx`-th metavar. . fn push_match(&mut self, idx: usize, m: NamedMatch) { 206,136 ( 0.00%) let matches = Lrc::make_mut(&mut self.matches[idx]); . matches.push(m); . } . } . . // Lots of MatcherPos instances are created at runtime. Allocating them on the . // heap is slow. Furthermore, using SmallVec to allocate them all . // on the stack is also slow, because MatcherPos is quite a large type and . // instances get moved around a lot between vectors, which requires lots of -- line 221 ---------------------------------------- -- line 226 ---------------------------------------- . // and this type is used to encapsulate both cases. . enum MatcherPosHandle<'root, 'tt> { . Ref(&'root mut MatcherPos<'root, 'tt>), . Box(Box>), . } . . impl<'root, 'tt> Clone for MatcherPosHandle<'root, 'tt> { . // This always produces a new Box. 32,588 ( 0.00%) fn clone(&self) -> Self { 16,294 ( 0.00%) MatcherPosHandle::Box(match *self { 7,665 ( 0.00%) MatcherPosHandle::Ref(ref r) => Box::new((**r).clone()), . MatcherPosHandle::Box(ref b) => b.clone(), . }) 48,882 ( 0.00%) } . } . . impl<'root, 'tt> Deref for MatcherPosHandle<'root, 'tt> { . type Target = MatcherPos<'root, 'tt>; . fn deref(&self) -> &Self::Target { . match *self { . MatcherPosHandle::Ref(ref r) => r, . MatcherPosHandle::Box(ref b) => b, -- line 247 ---------------------------------------- -- line 272 ---------------------------------------- . . /// A `ParseResult` where the `Success` variant contains a mapping of . /// `MacroRulesNormalizedIdent`s to `NamedMatch`es. This represents the mapping . /// of metavars to the token trees they bind to. . crate type NamedParseResult = ParseResult>; . . /// Count how many metavars are named in the given matcher `ms`. . pub(super) fn count_names(ms: &[TokenTree]) -> usize { 361,340 ( 0.01%) ms.iter().fold(0, |count, elt| { 180,670 ( 0.00%) count 542,010 ( 0.01%) + match *elt { 11,830 ( 0.00%) TokenTree::Sequence(_, ref seq) => seq.num_captures, 11,267 ( 0.00%) TokenTree::Delimited(_, ref delim) => count_names(&delim.tts), . TokenTree::MetaVar(..) => 0, . TokenTree::MetaVarDecl(..) => 1, . TokenTree::Token(..) => 0, . } 451,675 ( 0.01%) }) . } . . /// `len` `Vec`s (initially shared and empty) that will store matches of metavars. . fn create_matches(len: usize) -> Box<[Lrc]> { 62,274 ( 0.00%) if len == 0 { . vec![] . } else { . let empty_matches = Lrc::new(SmallVec::new()); . vec![empty_matches; len] . } . .into_boxed_slice() . } . . /// Generates the top-level matcher position in which the "dot" is before the first token of the . /// matcher `ms`. . fn initial_matcher_pos<'root, 'tt>(ms: &'tt [TokenTree]) -> MatcherPos<'root, 'tt> { . let match_idx_hi = count_names(ms); . let matches = create_matches(match_idx_hi); 305,745 ( 0.01%) MatcherPos { . // Start with the top level matcher given to us . top_elts: TtSeq(ms), // "elts" is an abbr. for "elements" . // The "dot" is before the first token of the matcher . idx: 0, . . // Initialize `matches` to a bunch of empty `Vec`s -- one for each metavar in `top_elts`. . // `match_lo` for `top_elts` is 0 and `match_hi` is `matches.len()`. `match_cur` is 0 since . // we haven't actually matched anything yet. -- line 316 ---------------------------------------- -- line 340 ---------------------------------------- . /// particular token tree. . /// . /// The width of each `MatchedSeq` in the `NamedMatch`, and the identity of . /// the `MatchedNonterminal`s, will depend on the token tree it was applied . /// to: each `MatchedSeq` corresponds to a single `TTSeq` in the originating . /// token tree. The depth of the `NamedMatch` structure will therefore depend . /// only on the nesting depth of `ast::TTSeq`s in the originating . /// token tree it was derived from. 308 ( 0.00%) #[derive(Debug, Clone)] . crate enum NamedMatch { . MatchedSeq(Lrc), . MatchedNonterminal(Lrc), . } . . /// Takes a sequence of token trees `ms` representing a matcher which successfully matched input . /// and an iterator of items that matched input and produces a `NamedParseResult`. . fn nameize>( -- line 356 ---------------------------------------- -- line 357 ---------------------------------------- . sess: &ParseSess, . ms: &[TokenTree], . mut res: I, . ) -> NamedParseResult { . // Recursively descend into each type of matcher (e.g., sequences, delimited, metavars) and make . // sure that each metavar has _exactly one_ binding. If a metavar does not have exactly one . // binding, then there is an error. If it does, then we insert the binding into the . // `NamedParseResult`. 109,329 ( 0.00%) fn n_rec>( . sess: &ParseSess, . m: &TokenTree, . res: &mut I, . ret_val: &mut FxHashMap, . ) -> Result<(), (rustc_span::Span, String)> { 65,235 ( 0.00%) match *m { . TokenTree::Sequence(_, ref seq) => { 588 ( 0.00%) for next_m in &seq.tts { 3,684 ( 0.00%) n_rec(sess, next_m, res.by_ref(), ret_val)? . } . } . TokenTree::Delimited(_, ref delim) => { 946 ( 0.00%) for next_m in &delim.tts { 5,676 ( 0.00%) n_rec(sess, next_m, res.by_ref(), ret_val)?; . } . } . TokenTree::MetaVarDecl(span, _, None) => { . if sess.missing_fragment_specifiers.borrow_mut().remove(&span).is_some() { . return Err((span, "missing fragment specifier".to_string())); . } . } 46,620 ( 0.00%) TokenTree::MetaVarDecl(sp, bind_name, _) => match ret_val 31,080 ( 0.00%) .entry(MacroRulesNormalizedIdent::new(bind_name)) . { . Vacant(spot) => { . spot.insert(res.next().unwrap()); . } . Occupied(..) => return Err((sp, format!("duplicated bind name: {}", bind_name))), . }, . TokenTree::MetaVar(..) | TokenTree::Token(..) => (), . } . 9,939 ( 0.00%) Ok(()) 79,512 ( 0.00%) } . . let mut ret_val = FxHashMap::default(); . for m in ms { 74,562 ( 0.00%) match n_rec(sess, m, res.by_ref(), &mut ret_val) { . Ok(_) => {} . Err((sp, msg)) => return Error(sp, msg), . } . } . 13,590 ( 0.00%) Success(ret_val) . } . . /// Performs a token equality check, ignoring syntax context (that is, an unhygienic comparison) . fn token_name_eq(t1: &Token, t2: &Token) -> bool { 149,094 ( 0.00%) if let (Some((ident1, is_raw1)), Some((ident2, is_raw2))) = (t1.ident(), t2.ident()) { 9 ( 0.00%) ident1.name == ident2.name && is_raw1 == is_raw2 208,663 ( 0.00%) } else if let (Some(ident1), Some(ident2)) = (t1.lifetime(), t2.lifetime()) { . ident1.name == ident2.name . } else { 89,348 ( 0.00%) t1.kind == t2.kind . } . } . . /// Process the matcher positions of `cur_items` until it is empty. In the process, this will . /// produce more items in `next_items`, `eof_items`, and `bb_items`. . /// . /// For more info about the how this happens, see the module-level doc comments and the inline . /// comments of this function. -- line 427 ---------------------------------------- -- line 443 ---------------------------------------- . sess: &ParseSess, . cur_items: &mut SmallVec<[MatcherPosHandle<'root, 'tt>; 1]>, . next_items: &mut Vec>, . eof_items: &mut SmallVec<[MatcherPosHandle<'root, 'tt>; 1]>, . bb_items: &mut SmallVec<[MatcherPosHandle<'root, 'tt>; 1]>, . token: &Token, . ) -> ParseResult<()> { . // Pop items from `cur_items` until it is empty. 355,168 ( 0.01%) while let Some(mut item) = cur_items.pop() { . // When unzipped trees end, remove them. This corresponds to backtracking out of a . // delimited submatcher into which we already descended. In backtracking out again, we need . // to advance the "dot" past the delimiters in the outer matcher. 1,089,745 ( 0.02%) while item.idx >= item.top_elts.len() { 2,050 ( 0.00%) match item.stack.pop() { . Some(MatcherTtFrame { elts, idx }) => { 9,225 ( 0.00%) item.top_elts = elts; 4,100 ( 0.00%) item.idx = idx + 1; . } . None => break, . } . } . . // Get the current position of the "dot" (`idx`) in `item` and the number of token trees in . // the matcher (`len`). . let idx = item.idx; . let len = item.top_elts.len(); . . // If `idx >= len`, then we are at or past the end of the matcher of `item`. 241,442 ( 0.00%) if idx >= len { . // We are repeating iff there is a parent. If the matcher is inside of a repetition, . // then we could be at the end of a sequence or at the beginning of the next . // repetition. 10,326 ( 0.00%) if item.up.is_some() { . // At this point, regardless of whether there is a separator, we should add all . // matches from the complete repetition of the sequence to the shared, top-level . // `matches` list (actually, `up.matches`, which could itself not be the top-level, . // but anyway...). Moreover, we add another item to `cur_items` in which the "dot" . // is at the end of the `up` matcher. This ensures that the "dot" in the `up` . // matcher is also advanced sufficiently. . // . // NOTE: removing the condition `idx == len` allows trailing separators. 15,166 ( 0.00%) if idx == len { . // Get the `up` matcher . let mut new_pos = item.up.clone().unwrap(); . . // Add matches from this repetition to the `matches` of `up` 15,012 ( 0.00%) for idx in item.match_lo..item.match_hi { 37,540 ( 0.00%) let sub = item.matches[idx].clone(); 22,524 ( 0.00%) new_pos.push_match(idx, MatchedSeq(sub)); . } . . // Move the "dot" past the repetition in `up` 14,935 ( 0.00%) new_pos.match_cur = item.match_hi; 45,036 ( 0.00%) new_pos.idx += 1; . cur_items.push(new_pos); . } . . // Check if we need a separator. 7,506 ( 0.00%) if idx == len && item.sep.is_some() { . // We have a separator, and it is the current token. We can advance past the . // separator token. 158 ( 0.00%) if item.sep.as_ref().map_or(false, |sep| token_name_eq(token, sep)) { 539 ( 0.00%) item.idx += 1; . next_items.push(item); . } . } . // We don't need a separator. Move the "dot" back to the beginning of the matcher . // and try to match again UNLESS we are only allowed to have _one_ repetition. 7,504 ( 0.00%) else if item.seq_op != Some(mbe::KleeneOp::ZeroOrOne) { 15,008 ( 0.00%) item.match_cur = item.match_lo; 30,016 ( 0.00%) item.idx = 0; . cur_items.push(item); . } . } . // If we are not in a repetition, then being at the end of a matcher means that we have . // reached the potential end of the input. . else { . eof_items.push(item); . } . } . // We are in the middle of a matcher. . else { . // Look at what token in the matcher we are trying to match the current token (`token`) . // against. Depending on that, we may generate new items. 333,697 ( 0.01%) match item.top_elts.get_tt(idx) { . // Need to descend into a sequence 3,055 ( 0.00%) TokenTree::Sequence(sp, seq) => { . // Examine the case where there are 0 matches of this sequence. We are . // implicitly disallowing OneOrMore from having 0 matches here. Thus, that will . // result in a "no rules expected token" error by virtue of this matcher not . // working. 1,308 ( 0.00%) if seq.kleene.op == mbe::KleeneOp::ZeroOrMore . || seq.kleene.op == mbe::KleeneOp::ZeroOrOne . { 1,282 ( 0.00%) let mut new_item = item.clone(); 2,564 ( 0.00%) new_item.match_cur += seq.num_captures; 3,205 ( 0.00%) new_item.idx += 1; 3,846 ( 0.00%) for idx in item.match_cur..item.match_cur + seq.num_captures { 1,686 ( 0.00%) new_item.push_match(idx, MatchedSeq(Lrc::new(smallvec![]))); . } . cur_items.push(new_item); . } . 654 ( 0.00%) let matches = create_matches(item.matches.len()); 7,848 ( 0.00%) cur_items.push(MatcherPosHandle::Box(Box::new(MatcherPos { 654 ( 0.00%) stack: smallvec![], . sep: seq.separator.clone(), 654 ( 0.00%) seq_op: Some(seq.kleene.op), . idx: 0, 3,270 ( 0.00%) matches, 1,308 ( 0.00%) match_lo: item.match_cur, . match_cur: item.match_cur, 1,308 ( 0.00%) match_hi: item.match_cur + seq.num_captures, . up: Some(item), 4,578 ( 0.00%) top_elts: Tt(TokenTree::Sequence(sp, seq)), . }))); . } . . // We need to match a metavar (but the identifier is invalid)... this is an error . TokenTree::MetaVarDecl(span, _, None) => { . if sess.missing_fragment_specifiers.borrow_mut().remove(&span).is_some() { . return Error(span, "missing fragment specifier".to_string()); . } -- line 565 ---------------------------------------- -- line 568 ---------------------------------------- . // We need to match a metavar with a valid ident... call out to the black-box . // parser by adding an item to `bb_items`. . TokenTree::MetaVarDecl(_, _, Some(kind)) => { . // Built-in nonterminals never start with these tokens, so we can eliminate . // them from consideration. . // . // We use the span of the metavariable declaration to determine any . // edition-specific matching behavior for non-terminals. 220,330 ( 0.00%) if Parser::nonterminal_may_begin_with(kind, token) { . bb_items.push(item); . } . } . . // We need to descend into a delimited submatcher or a doc comment. To do this, we . // push the current matcher onto a stack and push a new item containing the . // submatcher onto `cur_items`. . // . // At the beginning of the loop, if we reach the end of the delimited submatcher, . // we pop the stack to backtrack out of the descent. 20,065 ( 0.00%) seq @ (TokenTree::Delimited(..) . | TokenTree::Token(Token { kind: DocComment(..), .. })) => { . let lower_elts = mem::replace(&mut item.top_elts, Tt(seq)); 4,013 ( 0.00%) let idx = item.idx; 28,091 ( 0.00%) item.stack.push(MatcherTtFrame { elts: lower_elts, idx }); 16,052 ( 0.00%) item.idx = 0; . cur_items.push(item); . } . . // We just matched a normal token. We can just advance the parser. 82,210 ( 0.00%) TokenTree::Token(t) if token_name_eq(&t, token) => { 31,850 ( 0.00%) item.idx += 1; . next_items.push(item); . } . . // There was another token that was not `token`... This means we can't add any . // rules. NOTE that this is not necessarily an error unless _all_ items in . // `cur_items` end up doing this. There may still be some other matchers that do . // end up working out. . TokenTree::Token(..) | TokenTree::MetaVar(..) => {} . } 401,998 ( 0.01%) } 148,906 ( 0.00%) } . . // Yay a successful parse (so far)! . Success(()) . } . . /// Use the given sequence of token trees (`ms`) as a matcher. Match the token . /// stream from the given `parser` against it and return the match. 203,830 ( 0.00%) pub(super) fn parse_tt( . parser: &mut Cow<'_, Parser<'_>>, . ms: &[TokenTree], . macro_name: Ident, . ) -> NamedParseResult { . // A queue of possible matcher positions. We initialize it with the matcher position in which . // the "dot" is before the first token of the first token tree in `ms`. `inner_parse_loop` then . // processes all of these possible matcher positions and produces possible next positions into . // `next_items`. After some post-processing, the contents of `next_items` replenish `cur_items` . // and we start over again. . // . // This MatcherPos instance is allocated on the stack. All others -- and . // there are frequently *no* others! -- are allocated on the heap. . let mut initial = initial_matcher_pos(ms); 101,915 ( 0.00%) let mut cur_items = smallvec![MatcherPosHandle::Ref(&mut initial)]; . let mut next_items = Vec::new(); . . loop { . // Matcher positions black-box parsed by parser.rs (`parser`) . let mut bb_items = SmallVec::new(); . . // Matcher positions that would be valid if the macro invocation was over now . let mut eof_items = SmallVec::new(); 68,397 ( 0.00%) assert!(next_items.is_empty()); . . // Process `cur_items` until either we have finished the input or we need to get some . // parsing from the black-box parser done. The result is that `next_items` will contain a . // bunch of possible next matcher positions in `next_items`. . match inner_parse_loop( . parser.sess, . &mut cur_items, . &mut next_items, -- line 648 ---------------------------------------- -- line 652 ---------------------------------------- . ) { . Success(_) => {} . Failure(token, msg) => return Failure(token, msg), . Error(sp, msg) => return Error(sp, msg), . ErrorReported => return ErrorReported, . } . . // inner parse loop handled all cur_items, so it's empty 68,397 ( 0.00%) assert!(cur_items.is_empty()); . . // We need to do some post processing after the `inner_parser_loop`. . // . // Error messages here could be improved with links to original rules. . . // If we reached the EOF, check that there is EXACTLY ONE possible matcher. Otherwise, . // either the parse is ambiguous (which should never happen) or there is a syntax error. 341,985 ( 0.01%) if parser.token == token::Eof { 6,052 ( 0.00%) if eof_items.len() == 1 { . let matches = 10,790 ( 0.00%) eof_items[0].matches.iter_mut().map(|dv| Lrc::make_mut(dv).pop().unwrap()); 4,530 ( 0.00%) return nameize(parser.sess, ms, matches); . } else if eof_items.len() > 1 { . return Error( . parser.token.span, . "ambiguity: multiple successful parses".to_string(), . ); . } else { 54 ( 0.00%) return Failure( 18 ( 0.00%) Token::new( . token::Eof, 24 ( 0.00%) if parser.token.span.is_dummy() { . parser.token.span . } else { . parser.token.span.shrink_to_hi() . }, . ), . "missing tokens in macro arguments", . ); . } . } . // Performance hack: eof_items may share matchers via Rc with other things that we want . // to modify. Dropping eof_items now may drop these refcounts to 1, preventing an . // unnecessary implicit clone later in Rc::make_mut. 267,524 ( 0.01%) drop(eof_items); . . // If there are no possible next positions AND we aren't waiting for the black-box parser, . // then there is a syntax error. 224,060 ( 0.00%) if bb_items.is_empty() && next_items.is_empty() { 245,271 ( 0.00%) return Failure(parser.token.clone(), "no rules expected this token in macro call"); . } . // Another possibility is that we need to call out to parse some rust nonterminal . // (black-box) parser. However, if there is not EXACTLY ONE of these, something is wrong. 173,856 ( 0.00%) else if (!bb_items.is_empty() && !next_items.is_empty()) || bb_items.len() > 1 { . let nts = bb_items . .iter() . .map(|item| match item.top_elts.get_tt(item.idx) { . TokenTree::MetaVarDecl(_, bind, Some(kind)) => format!("{} ('{}')", kind, bind), . _ => panic!(), . }) . .collect::>() . .join(" or "); -- line 712 ---------------------------------------- -- line 721 ---------------------------------------- . n => format!("built-in NTs {} or {} other options.", nts, n), . } . ), . ); . } . // Dump all possible `next_items` into `cur_items` for the next iteration. . else if !next_items.is_empty() { . // Now process the next token 13,650 ( 0.00%) cur_items.extend(next_items.drain(..)); 4,550 ( 0.00%) parser.to_mut().bump(); . } . // Finally, we have the case where we need to call the black-box parser to get some . // nonterminal. . else { . assert_eq!(bb_items.len(), 1); . 86,928 ( 0.00%) let mut item = bb_items.pop().unwrap(); 241,287 ( 0.00%) if let TokenTree::MetaVarDecl(span, _, Some(kind)) = item.top_elts.get_tt(item.idx) { 43,464 ( 0.00%) let match_cur = item.match_cur; . // We use the span of the metavariable declaration to determine any . // edition-specific matching behavior for non-terminals. 281,106 ( 0.01%) let nt = match parser.to_mut().parse_nonterminal(kind) { . Err(mut err) => { . err.span_label( . span, . format!("while parsing argument for this `{}` macro fragment", kind), . ) . .emit(); . return ErrorReported; . } 260,784 ( 0.01%) Ok(nt) => nt, . }; 173,856 ( 0.00%) item.push_match(match_cur, MatchedNonterminal(Lrc::new(nt))); 173,856 ( 0.00%) item.idx += 1; 260,784 ( 0.01%) item.match_cur += 1; . } else { . unreachable!() . } . cur_items.push(item); . } . 96,028 ( 0.00%) assert!(!cur_items.is_empty()); . } 183,447 ( 0.00%) } 1,574,647 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/tokenstream.rs -------------------------------------------------------------------------------- Ir -- line 32 ---------------------------------------- . /// . /// If the syntax extension is an MBE macro, it will attempt to match its . /// LHS token tree against the provided token tree, and if it finds a . /// match, will transcribe the RHS token tree, splicing in any captured . /// `macro_parser::matched_nonterminals` into the `SubstNt`s it finds. . /// . /// The RHS of an MBE macro is the only place `SubstNt`s are substituted. . /// Nothing special happens to misnamed or misplaced `SubstNt`s. 1,541,511 ( 0.03%) #[derive(Debug, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)] . pub enum TokenTree { . /// A single token. 548,481 ( 0.01%) Token(Token), . /// A delimited sequence of token trees. 33,866 ( 0.00%) Delimited(DelimSpan, DelimToken, TokenStream), . } . . #[derive(Copy, Clone)] . pub enum CanSynthesizeMissingTokens { . Yes, . No, . } . -- line 53 ---------------------------------------- -- line 71 ---------------------------------------- . delim == delim2 && tts.eq_unspanned(&tts2) . } . _ => false, . } . } . . /// Retrieves the `TokenTree`'s span. . pub fn span(&self) -> Span { 13,254 ( 0.00%) match self { 5,803 ( 0.00%) TokenTree::Token(token) => token.span, 5,164 ( 0.00%) TokenTree::Delimited(sp, ..) => sp.entire(), . } 5,555 ( 0.00%) } . . /// Modify the `TokenTree`'s span in-place. . pub fn set_span(&mut self, span: Span) { 13,254 ( 0.00%) match self { 5,555 ( 0.00%) TokenTree::Token(token) => token.span = span, 2,144 ( 0.00%) TokenTree::Delimited(dspan, ..) => *dspan = DelimSpan::from_single(span), . } 6,627 ( 0.00%) } . 6,063 ( 0.00%) pub fn token(kind: TokenKind, span: Span) -> TokenTree { 120,952 ( 0.00%) TokenTree::Token(Token::new(kind, span)) 6,063 ( 0.00%) } . . /// Returns the opening delimiter as a token tree. 13,253 ( 0.00%) pub fn open_tt(span: DelimSpan, delim: DelimToken) -> TokenTree { 39,759 ( 0.00%) TokenTree::token(token::OpenDelim(delim), span.open) 13,253 ( 0.00%) } . . /// Returns the closing delimiter as a token tree. 10,922 ( 0.00%) pub fn close_tt(span: DelimSpan, delim: DelimToken) -> TokenTree { 32,766 ( 0.00%) TokenTree::token(token::CloseDelim(delim), span.close) 10,922 ( 0.00%) } . 2,034 ( 0.00%) pub fn uninterpolate(self) -> TokenTree { 1,356 ( 0.00%) match self { 6,102 ( 0.00%) TokenTree::Token(token) => TokenTree::Token(token.uninterpolate().into_owned()), . tt => tt, . } 2,712 ( 0.00%) } . } . . impl HashStable for TokenStream . where . CTX: crate::HashStableContext, . { 531 ( 0.00%) fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) { 2,063 ( 0.00%) for sub_tt in self.trees() { . sub_tt.hash_stable(hcx, hasher); . } 472 ( 0.00%) } . } . . pub trait CreateTokenStream: sync::Send + sync::Sync { . fn create_token_stream(&self) -> AttrAnnotatedTokenStream; . } . . impl CreateTokenStream for AttrAnnotatedTokenStream { . fn create_token_stream(&self) -> AttrAnnotatedTokenStream { -- line 131 ---------------------------------------- -- line 135 ---------------------------------------- . . /// A lazy version of [`TokenStream`], which defers creation . /// of an actual `TokenStream` until it is needed. . /// `Box` is here only to reduce the structure size. . #[derive(Clone)] . pub struct LazyTokenStream(Lrc>); . . impl LazyTokenStream { 12 ( 0.00%) pub fn new(inner: impl CreateTokenStream + 'static) -> LazyTokenStream { . LazyTokenStream(Lrc::new(Box::new(inner))) 12 ( 0.00%) } . . pub fn create_token_stream(&self) -> AttrAnnotatedTokenStream { 43 ( 0.00%) self.0.create_token_stream() . } . } . . impl fmt::Debug for LazyTokenStream { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . write!(f, "LazyTokenStream({:?})", self.create_token_stream()) . } . } -- line 156 ---------------------------------------- -- line 188 ---------------------------------------- . Delimited(DelimSpan, DelimToken, AttrAnnotatedTokenStream), . /// Stores the attributes for an attribute target, . /// along with the tokens for that attribute target. . /// See `AttributesData` for more information . Attributes(AttributesData), . } . . impl AttrAnnotatedTokenStream { 13,662 ( 0.00%) pub fn new(tokens: Vec<(AttrAnnotatedTokenTree, Spacing)>) -> AttrAnnotatedTokenStream { . AttrAnnotatedTokenStream(Lrc::new(tokens)) 13,662 ( 0.00%) } . . /// Converts this `AttrAnnotatedTokenStream` to a plain `TokenStream . /// During conversion, `AttrAnnotatedTokenTree::Attributes` get 'flattened' . /// back to a `TokenStream` of the form `outer_attr attr_target`. . /// If there are inner attributes, they are inserted into the proper . /// place in the attribute target tokens. 4 ( 0.00%) pub fn to_tokenstream(&self) -> TokenStream { 37 ( 0.00%) let trees: Vec<_> = self . .0 . .iter() 648 ( 0.00%) .flat_map(|tree| match &tree.0 { 312 ( 0.00%) AttrAnnotatedTokenTree::Token(inner) => { 780 ( 0.00%) smallvec![(TokenTree::Token(inner.clone()), tree.1)].into_iter() . } 660 ( 0.00%) AttrAnnotatedTokenTree::Delimited(span, delim, stream) => smallvec![( 99 ( 0.00%) TokenTree::Delimited(*span, *delim, stream.to_tokenstream()), 33 ( 0.00%) tree.1, . )] . .into_iter(), . AttrAnnotatedTokenTree::Attributes(data) => { . let mut outer_attrs = Vec::new(); . let mut inner_attrs = Vec::new(); . for attr in &data.attrs { 8 ( 0.00%) match attr.style { . crate::AttrStyle::Outer => { . outer_attrs.push(attr); . } . crate::AttrStyle::Inner => { . inner_attrs.push(attr); . } . } . } . 6 ( 0.00%) let mut target_tokens: Vec<_> = data . .tokens . .create_token_stream() . .to_tokenstream() . .0 . .iter() . .cloned() . .collect(); 3 ( 0.00%) if !inner_attrs.is_empty() { . let mut found = false; . // Check the last two trees (to account for a trailing semi) . for (tree, _) in target_tokens.iter_mut().rev().take(2) { . if let TokenTree::Delimited(span, delim, delim_tokens) = tree { . // Inner attributes are only supported on extern blocks, functions, impls, . // and modules. All of these have their inner attributes placed at . // the beginning of the rightmost outermost braced group: . // e.g. fn foo() { #![my_attr} } -- line 248 ---------------------------------------- -- line 269 ---------------------------------------- . . assert!( . found, . "Failed to find trailing delimited group in: {:?}", . target_tokens . ); . } . let mut flat: SmallVec<[_; 1]> = SmallVec::new(); 47 ( 0.00%) for attr in outer_attrs { . // FIXME: Make this more efficient 24 ( 0.00%) flat.extend(attr.tokens().to_tokenstream().0.clone().iter().cloned()); . } 24 ( 0.00%) flat.extend(target_tokens); 30 ( 0.00%) flat.into_iter() 3 ( 0.00%) } . }) . .collect(); . TokenStream::new(trees) 8 ( 0.00%) } . } . . /// Stores the tokens for an attribute target, along . /// with its attributes. . /// . /// This is constructed during parsing when we need to capture . /// tokens. . /// -- line 295 ---------------------------------------- -- line 316 ---------------------------------------- . pub struct TokenStream(pub(crate) Lrc>); . . pub type TreeAndSpacing = (TokenTree, Spacing); . . // `TokenStream` is used a lot. Make sure it doesn't unintentionally get bigger. . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . rustc_data_structures::static_assert_size!(TokenStream, 8); . 172,758 ( 0.00%) #[derive(Clone, Copy, Debug, PartialEq, Encodable, Decodable)] . pub enum Spacing { . Alone, . Joint, . } . . impl TokenStream { . /// Given a `TokenStream` with a `Stream` of only two arguments, return a new `TokenStream` . /// separating the two arguments with a comma for diagnostic suggestions. -- line 332 ---------------------------------------- -- line 365 ---------------------------------------- . return Some((TokenStream::new(new_stream), sp)); . } . None . } . } . . impl From<(AttrAnnotatedTokenTree, Spacing)> for AttrAnnotatedTokenStream { . fn from((tree, spacing): (AttrAnnotatedTokenTree, Spacing)) -> AttrAnnotatedTokenStream { 5 ( 0.00%) AttrAnnotatedTokenStream::new(vec![(tree, spacing)]) . } . } . . impl From for TokenStream { . fn from(tree: TokenTree) -> TokenStream { 14,105 ( 0.00%) TokenStream::new(vec![(tree, Spacing::Alone)]) . } . } . . impl From for TreeAndSpacing { . fn from(tree: TokenTree) -> TreeAndSpacing { 56,658 ( 0.00%) (tree, Spacing::Alone) . } . } . . impl iter::FromIterator for TokenStream { 4 ( 0.00%) fn from_iter>(iter: I) -> Self { 4 ( 0.00%) TokenStream::new(iter.into_iter().map(Into::into).collect::>()) 6 ( 0.00%) } . } . . impl Eq for TokenStream {} . . impl PartialEq for TokenStream { . fn eq(&self, other: &TokenStream) -> bool { . self.trees().eq(other.trees()) . } -- line 400 ---------------------------------------- -- line 401 ---------------------------------------- . } . . impl TokenStream { . pub fn new(streams: Vec) -> TokenStream { . TokenStream(Lrc::new(streams)) . } . . pub fn is_empty(&self) -> bool { 1,253 ( 0.00%) self.0.is_empty() 1,253 ( 0.00%) } . . pub fn len(&self) -> usize { 171,974 ( 0.00%) self.0.len() 1,497 ( 0.00%) } . 4,656 ( 0.00%) pub fn from_streams(mut streams: SmallVec<[TokenStream; 2]>) -> TokenStream { 2,328 ( 0.00%) match streams.len() { . 0 => TokenStream::default(), . 1 => streams.pop().unwrap(), . _ => { . // We are going to extend the first stream in `streams` with . // the elements from the subsequent streams. This requires . // using `make_mut()` on the first stream, and in practice this . // doesn't cause cloning 99.9% of the time. . // -- line 425 ---------------------------------------- -- line 430 ---------------------------------------- . . // Determine how much the first stream will be extended. . // Needed to avoid quadratic blow up from on-the-fly . // reallocations (#57735). . let num_appends = streams.iter().skip(1).map(|ts| ts.len()).sum(); . . // Get the first stream. If it's `None`, create an empty . // stream. 1,128 ( 0.00%) let mut iter = streams.drain(..); 1,128 ( 0.00%) let mut first_stream_lrc = iter.next().unwrap().0; . . // Append the elements to the first stream, after reserving . // space for them. 564 ( 0.00%) let first_vec_mut = Lrc::make_mut(&mut first_stream_lrc); . first_vec_mut.reserve(num_appends); 12,477 ( 0.00%) for stream in iter { . first_vec_mut.extend(stream.0.iter().cloned()); . } . . // Create the final `TokenStream`. 1,128 ( 0.00%) TokenStream(first_stream_lrc) . } . } 5,238 ( 0.00%) } . . pub fn trees(&self) -> Cursor { 1,868 ( 0.00%) self.clone().into_trees() 3,736 ( 0.00%) } . 16,351 ( 0.00%) pub fn into_trees(self) -> Cursor { . Cursor::new(self) 32,702 ( 0.00%) } . . /// Compares two `TokenStream`s, checking equality without regarding span information. . pub fn eq_unspanned(&self, other: &TokenStream) -> bool { . let mut t1 = self.trees(); . let mut t2 = other.trees(); . for (t1, t2) in iter::zip(&mut t1, &mut t2) { . if !t1.eq_unspanned(&t2) { . return false; . } . } . t1.next().is_none() && t2.next().is_none() . } . . pub fn map_enumerated TokenTree>(self, mut f: F) -> TokenStream { 1,440 ( 0.00%) TokenStream(Lrc::new( . self.0 . .iter() . .enumerate() 39,762 ( 0.00%) .map(|(i, (tree, is_joint))| (f(i, tree), *is_joint)) . .collect(), . )) . } . } . . // 99.5%+ of the time we have 1 or 2 elements in this vector. . #[derive(Clone)] . pub struct TokenStreamBuilder(SmallVec<[TokenStream; 2]>); . . impl TokenStreamBuilder { 582 ( 0.00%) pub fn new() -> TokenStreamBuilder { 582 ( 0.00%) TokenStreamBuilder(SmallVec::new()) 582 ( 0.00%) } . 37,863 ( 0.00%) pub fn push>(&mut self, stream: T) { 4,207 ( 0.00%) let mut stream = stream.into(); . . // If `self` is not empty and the last tree within the last stream is a . // token tree marked with `Joint`... 12,621 ( 0.00%) if let Some(TokenStream(ref mut last_stream_lrc)) = self.0.last_mut() { 22,434 ( 0.00%) if let Some((TokenTree::Token(last_token), Spacing::Joint)) = last_stream_lrc.last() { . // ...and `stream` is not empty and the first tree within it is . // a token tree... . let TokenStream(ref mut stream_lrc) = stream; 4,158 ( 0.00%) if let Some((TokenTree::Token(token), spacing)) = stream_lrc.first() { . // ...and the two tokens can be glued together... 4,158 ( 0.00%) if let Some(glued_tok) = last_token.glue(&token) { . // ...then do so, by overwriting the last token . // tree in `self` and removing the first token tree . // from `stream`. This requires using `make_mut()` . // on the last stream in `self` and on `stream`, . // and in practice this doesn't cause cloning 99.9% . // of the time. . . // Overwrite the last token tree with the merged . // token. 594 ( 0.00%) let last_vec_mut = Lrc::make_mut(last_stream_lrc); 13,662 ( 0.00%) *last_vec_mut.last_mut().unwrap() = (TokenTree::Token(glued_tok), *spacing); . . // Remove the first token tree from `stream`. (This . // is almost always the only tree in `stream`.) 594 ( 0.00%) let stream_vec_mut = Lrc::make_mut(stream_lrc); 3,564 ( 0.00%) stream_vec_mut.remove(0); . . // Don't push `stream` if it's empty -- that could . // block subsequent token gluing, by getting . // between two token trees that should be glued . // together. 1,782 ( 0.00%) if !stream.is_empty() { . self.0.push(stream); . } . return; . } . } . } . } . self.0.push(stream); 33,656 ( 0.00%) } . 582 ( 0.00%) pub fn build(self) -> TokenStream { 3,492 ( 0.00%) TokenStream::from_streams(self.0) 1,164 ( 0.00%) } . } . . /// By-reference iterator over a [`TokenStream`]. . #[derive(Clone)] . pub struct CursorRef<'t> { . stream: &'t TokenStream, . index: usize, . } -- line 550 ---------------------------------------- -- line 572 ---------------------------------------- . pub struct Cursor { . pub stream: TokenStream, . index: usize, . } . . impl Iterator for Cursor { . type Item = TokenTree; . 17,565 ( 0.00%) fn next(&mut self) -> Option { 36,203 ( 0.00%) self.next_with_spacing().map(|(tree, _)| tree) 23,420 ( 0.00%) } . } . . impl Cursor { . fn new(stream: TokenStream) -> Self { . Cursor { stream, index: 0 } . } . 800,470 ( 0.02%) pub fn next_with_spacing(&mut self) -> Option { 497,847 ( 0.01%) if self.index < self.stream.len() { 276,054 ( 0.01%) self.index += 1; 937,454 ( 0.02%) Some(self.stream.0[self.index - 1].clone()) . } else { 52,344 ( 0.00%) None . } 960,564 ( 0.02%) } . . pub fn index(&self) -> usize { . self.index . } . . pub fn append(&mut self, new_stream: TokenStream) { . if new_stream.is_empty() { . return; . } . let index = self.index; . let stream = mem::take(&mut self.stream); . *self = TokenStream::from_streams(smallvec![stream, new_stream]).into_trees(); . self.index = index; . } . 13,815 ( 0.00%) pub fn look_ahead(&self, n: usize) -> Option<&TokenTree> { 27,630 ( 0.00%) self.stream.0[self.index..].get(n).map(|(tree, _)| tree) 27,630 ( 0.00%) } . } . 79,329 ( 0.00%) #[derive(Debug, Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)] . pub struct DelimSpan { . pub open: Span, . pub close: Span, . } . . impl DelimSpan { 744 ( 0.00%) pub fn from_single(sp: Span) -> Self { . DelimSpan { open: sp, close: sp } 1,488 ( 0.00%) } . 1,384 ( 0.00%) pub fn from_pair(open: Span, close: Span) -> Self { . DelimSpan { open, close } 692 ( 0.00%) } . . pub fn dummy() -> Self { . Self::from_single(DUMMY_SP) 12,576 ( 0.00%) } . 45,952 ( 0.00%) pub fn entire(self) -> Span { . self.open.with_hi(self.close.hi()) 34,464 ( 0.00%) } . } 50,082 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs -------------------------------------------------------------------------------- Ir -- line 111 ---------------------------------------- . const EMPTY: u8 = 0b1111_1111; . . /// Control byte value for a deleted bucket. . const DELETED: u8 = 0b1000_0000; . . /// Checks whether a control byte represents a full bucket (top bit is clear). . #[inline] . fn is_full(ctrl: u8) -> bool { 1,809,428 ( 0.03%) ctrl & 0x80 == 0 . } . . /// Checks whether a control byte represents a special value (top bit is set). . #[inline] . fn is_special(ctrl: u8) -> bool { . ctrl & 0x80 != 0 . } . . /// Checks whether a special control value is EMPTY (just check 1 bit). . #[inline] . fn special_is_empty(ctrl: u8) -> bool { . debug_assert!(is_special(ctrl)); 121,776 ( 0.00%) ctrl & 0x01 != 0 . } . . /// Primary hash function, used to select the initial bucket to probe from. . #[inline] . #[allow(clippy::cast_possible_truncation)] . fn h1(hash: u64) -> usize { . // On 32-bit platforms we simply ignore the higher hash bits. . hash as usize -- line 140 ---------------------------------------- -- line 143 ---------------------------------------- . /// Secondary hash function, saved in the low 7 bits of the control byte. . #[inline] . #[allow(clippy::cast_possible_truncation)] . fn h2(hash: u64) -> u8 { . // Grab the top 7 bits of the hash. While the hash is normally a full 64-bit . // value, some hash functions (such as FxHash) produce a usize result . // instead, which means that the top 32 bits are 0 on 32-bit platforms. . let hash_len = usize::min(mem::size_of::(), mem::size_of::()); 26,570,744 ( 0.51%) let top7 = hash >> (hash_len * 8 - 7); . (top7 & 0x7f) as u8 // truncation . } . . /// Probe sequence based on triangular numbers, which is guaranteed (since our . /// table size is a power of two) to visit every group of elements exactly once. . /// . /// A triangular probe has us jump by 1 more group every time. So first we . /// jump by 1 group (meaning we just continue our linear scan), then 2 groups -- line 159 ---------------------------------------- -- line 170 ---------------------------------------- . #[inline] . fn move_next(&mut self, bucket_mask: usize) { . // We should have found an empty bucket by now and ended the probe. . debug_assert!( . self.stride <= bucket_mask, . "Went past end of probe sequence" . ); . 301,644 ( 0.01%) self.stride += Group::WIDTH; 301,644 ( 0.01%) self.pos += self.stride; 257,925 ( 0.00%) self.pos &= bucket_mask; . } . } . . /// Returns the number of buckets needed to hold the given number of items, . /// taking the maximum load factor into account. . /// . /// Returns `None` if an overflow occurs. . // Workaround for emscripten bug emscripten-core/emscripten-fastcomp#258 . #[cfg_attr(target_os = "emscripten", inline(never))] . #[cfg_attr(not(target_os = "emscripten"), inline)] . fn capacity_to_buckets(cap: usize) -> Option { . debug_assert_ne!(cap, 0); . . // For small tables we require at least 1 empty bucket so that lookups are . // guaranteed to terminate if an element doesn't exist in the table. 66,304 ( 0.00%) if cap < 8 { . // We don't bother with a table size of 2 buckets since that can only . // hold a single element. Instead we skip directly to a 4 bucket table . // which can hold 3 elements. 120,440 ( 0.00%) return Some(if cap < 4 { 4 } else { 8 }); . } . . // Otherwise require 1/8 buckets to be empty (87.5% load) . // . // Be careful when modifying this, calculate_layout relies on the . // overflow check here. 54,384 ( 0.00%) let adjusted_cap = cap.checked_mul(8)? / 7; . . // Any overflows will have been caught by the checked_mul. Also, any . // rounding errors from the division above will be cleaned up by . // next_power_of_two (which can't overflow because of the previous division). . Some(adjusted_cap.next_power_of_two()) . } . . /// Returns the maximum effective capacity for the given bucket mask, taking . /// the maximum load factor into account. . #[inline] . fn bucket_mask_to_capacity(bucket_mask: usize) -> usize { 194,591 ( 0.00%) if bucket_mask < 8 { . // For tables with 1/2/4/8 buckets, we always reserve one empty slot. . // Keep in mind that the bucket mask is one less than the bucket count. . bucket_mask . } else { . // For larger tables we reserve 12.5% of the slots as empty. 67,088 ( 0.00%) ((bucket_mask + 1) / 8) * 7 . } . } . . /// Helper which allows the max calculation for ctrl_align to be statically computed for each T . /// while keeping the rest of `calculate_layout_for` independent of `T` . #[derive(Copy, Clone)] . struct TableLayout { . size: usize, . ctrl_align: usize, . } . . impl TableLayout { . #[inline] 17 ( 0.00%) fn new() -> Self { 68 ( 0.00%) let layout = Layout::new::(); 34 ( 0.00%) Self { 51 ( 0.00%) size: layout.size(), 102 ( 0.00%) ctrl_align: usize::max(layout.align(), Group::WIDTH), . } 68 ( 0.00%) } . . #[inline] . fn calculate_layout_for(self, buckets: usize) -> Option<(Layout, usize)> { . debug_assert!(buckets.is_power_of_two()); . . let TableLayout { size, ctrl_align } = self; . // Manual layout calculation since Layout methods are not yet stable. . let ctrl_offset = 117,005 ( 0.00%) size.checked_mul(buckets)?.checked_add(ctrl_align - 1)? & !(ctrl_align - 1); 172,498 ( 0.00%) let len = ctrl_offset.checked_add(buckets + Group::WIDTH)?; . . Some(( . unsafe { Layout::from_size_align_unchecked(len, ctrl_align) }, . ctrl_offset, . )) . } . } . -- line 263 ---------------------------------------- -- line 292 ---------------------------------------- . #[inline] . fn clone(&self) -> Self { . Self { ptr: self.ptr } . } . } . . impl Bucket { . #[inline] 395 ( 0.00%) unsafe fn from_base_index(base: NonNull, index: usize) -> Self { 316 ( 0.00%) let ptr = if mem::size_of::() == 0 { . // won't overflow because index must be less than length . (index + 1) as *mut T . } else { 316 ( 0.00%) base.as_ptr().sub(index) . }; 79 ( 0.00%) Self { 316 ( 0.00%) ptr: NonNull::new_unchecked(ptr), . } 237 ( 0.00%) } . #[inline] . unsafe fn to_base_index(&self, base: NonNull) -> usize { . if mem::size_of::() == 0 { . self.ptr.as_ptr() as usize - 1 . } else { . offset_from(base.as_ptr(), self.ptr.as_ptr()) . } . } -- line 318 ---------------------------------------- -- line 337 ---------------------------------------- . } . } . #[cfg_attr(feature = "inline-more", inline)] . pub unsafe fn drop(&self) { . self.as_ptr().drop_in_place(); . } . #[inline] . pub unsafe fn read(&self) -> T { 356 ( 0.00%) self.as_ptr().read() . } . #[inline] . pub unsafe fn write(&self, val: T) { . self.as_ptr().write(val); . } . #[inline] . pub unsafe fn as_ref<'a>(&self) -> &'a T { . &*self.as_ptr() -- line 353 ---------------------------------------- -- line 392 ---------------------------------------- . . impl RawTable { . /// Creates a new empty hash table without allocating any memory. . /// . /// In effect this returns a table with exactly 1 bucket. However we can . /// leave the data pointer dangling since that bucket is never written to . /// due to our load factor forcing us to always have at least 1 free bucket. . #[inline] 99 ( 0.00%) pub const fn new() -> Self { 264 ( 0.00%) Self { 66 ( 0.00%) table: RawTableInner::new_in(Global), . marker: PhantomData, . } 66 ( 0.00%) } . . /// Attempts to allocate a new hash table with at least enough capacity . /// for inserting the given number of elements without reallocating. . #[cfg(feature = "raw")] . pub fn try_with_capacity(capacity: usize) -> Result { . Self::try_with_capacity_in(capacity, Global) . } . . /// Allocates a new hash table with at least enough capacity for inserting . /// the given number of elements without reallocating. 68 ( 0.00%) pub fn with_capacity(capacity: usize) -> Self { 17 ( 0.00%) Self::with_capacity_in(capacity, Global) 34 ( 0.00%) } . } . . impl RawTable { . /// Creates a new empty hash table without allocating any memory, using the . /// given allocator. . /// . /// In effect this returns a table with exactly 1 bucket. However we can . /// leave the data pointer dangling since that bucket is never written to . /// due to our load factor forcing us to always have at least 1 free bucket. . #[inline] 36 ( 0.00%) pub fn new_in(alloc: A) -> Self { 65,640 ( 0.00%) Self { 24 ( 0.00%) table: RawTableInner::new_in(alloc), . marker: PhantomData, . } 24 ( 0.00%) } . . /// Allocates a new hash table with the given number of buckets. . /// . /// The control bytes are left uninitialized. . #[cfg_attr(feature = "inline-more", inline)] . unsafe fn new_uninitialized( . alloc: A, . buckets: usize, . fallibility: Fallibility, . ) -> Result { . debug_assert!(buckets.is_power_of_two()); . . Ok(Self { 80 ( 0.00%) table: RawTableInner::new_uninitialized( . alloc, . TableLayout::new::(), . buckets, . fallibility, . )?, . marker: PhantomData, . }) . } . . /// Attempts to allocate a new hash table with at least enough capacity . /// for inserting the given number of elements without reallocating. 153 ( 0.00%) fn fallible_with_capacity( . alloc: A, . capacity: usize, . fallibility: Fallibility, . ) -> Result { 306 ( 0.00%) Ok(Self { 6,125 ( 0.00%) table: RawTableInner::fallible_with_capacity( 17 ( 0.00%) alloc, 85 ( 0.00%) TableLayout::new::(), . capacity, . fallibility, 17 ( 0.00%) )?, . marker: PhantomData, . }) 51 ( 0.00%) } . . /// Attempts to allocate a new hash table using the given allocator, with at least enough . /// capacity for inserting the given number of elements without reallocating. . #[cfg(feature = "raw")] . pub fn try_with_capacity_in(capacity: usize, alloc: A) -> Result { . Self::fallible_with_capacity(alloc, capacity, Fallibility::Fallible) . } . . /// Allocates a new hash table using the given allocator, with at least enough capacity for . /// inserting the given number of elements without reallocating. 68 ( 0.00%) pub fn with_capacity_in(capacity: usize, alloc: A) -> Self { . // Avoid `Result::unwrap_or_else` because it bloats LLVM IR. 153 ( 0.00%) match Self::fallible_with_capacity(alloc, capacity, Fallibility::Infallible) { 136 ( 0.00%) Ok(capacity) => capacity, . Err(_) => unsafe { hint::unreachable_unchecked() }, . } 34 ( 0.00%) } . . /// Returns a reference to the underlying allocator. . #[inline] . pub fn allocator(&self) -> &A { . &self.table.alloc . } . . /// Deallocates the table without dropping any entries. . #[cfg_attr(feature = "inline-more", inline)] . unsafe fn free_buckets(&mut self) { . self.table.free_buckets(TableLayout::new::()); . } . . /// Returns pointer to one past last element of data table. . #[inline] 158 ( 0.00%) pub unsafe fn data_end(&self) -> NonNull { 395 ( 0.00%) NonNull::new_unchecked(self.table.ctrl.as_ptr().cast()) 158 ( 0.00%) } . . /// Returns pointer to start of data table. . #[inline] . #[cfg(feature = "nightly")] . pub unsafe fn data_start(&self) -> *mut T { . self.data_end().as_ptr().wrapping_sub(self.buckets()) . } . -- line 517 ---------------------------------------- -- line 527 ---------------------------------------- . debug_assert_ne!(self.table.bucket_mask, 0); . debug_assert!(index < self.buckets()); . Bucket::from_base_index(self.data_end(), index) . } . . /// Erases an element from the table without dropping it. . #[cfg_attr(feature = "inline-more", inline)] . #[deprecated(since = "0.8.1", note = "use erase or remove instead")] 9,917 ( 0.00%) pub unsafe fn erase_no_drop(&mut self, item: &Bucket) { 9,917 ( 0.00%) let index = self.bucket_index(item); . self.table.erase(index); 19,834 ( 0.00%) } . . /// Erases an element from the table, dropping it in place. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::needless_pass_by_value)] . #[allow(deprecated)] . pub unsafe fn erase(&mut self, item: Bucket) { . // Erase the element from the table first since drop might panic. 4,040 ( 0.00%) self.erase_no_drop(&item); . item.drop(); . } . . /// Finds and erases an element from the table, dropping it in place. . /// Returns true if an element was found. . #[cfg(feature = "raw")] . #[cfg_attr(feature = "inline-more", inline)] . pub fn erase_entry(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> bool { -- line 554 ---------------------------------------- -- line 563 ---------------------------------------- . } . } . . /// Removes an element from the table, returning it. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::needless_pass_by_value)] . #[allow(deprecated)] . pub unsafe fn remove(&mut self, item: Bucket) -> T { 15,794 ( 0.00%) self.erase_no_drop(&item); 1,441 ( 0.00%) item.read() . } . . /// Finds and removes an element from the table, returning it. . #[cfg_attr(feature = "inline-more", inline)] 428,617 ( 0.01%) pub fn remove_entry(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option { . // Avoid `Option::map` because it bloats LLVM IR. 1,434 ( 0.00%) match self.find(hash, eq) { 2,621 ( 0.00%) Some(bucket) => Some(unsafe { self.remove(bucket) }), 60,389 ( 0.00%) None => None, . } 600,116 ( 0.01%) } . . /// Marks all table buckets as empty without dropping their contents. . #[cfg_attr(feature = "inline-more", inline)] . pub fn clear_no_drop(&mut self) { . self.table.clear_no_drop(); . } . . /// Removes all elements from the table without freeing the backing memory. . #[cfg_attr(feature = "inline-more", inline)] . pub fn clear(&mut self) { . // Ensure that the table is reset even if one of the drops panic . let mut self_ = guard(self, |self_| self_.clear_no_drop()); . unsafe { 1 ( 0.00%) self_.drop_elements(); . } . } . 7 ( 0.00%) unsafe fn drop_elements(&mut self) { 7,632 ( 0.00%) if mem::needs_drop::() && !self.is_empty() { . for item in self.iter() { . item.drop(); . } . } 8 ( 0.00%) } . . /// Shrinks the table to fit `max(self.len(), min_size)` elements. . #[cfg_attr(feature = "inline-more", inline)] . pub fn shrink_to(&mut self, min_size: usize, hasher: impl Fn(&T) -> u64) { . // Calculate the minimal number of elements that we need to reserve . // space for. . let min_size = usize::max(self.table.items, min_size); . if min_size == 0 { -- line 615 ---------------------------------------- -- line 641 ---------------------------------------- . } . } . } . } . . /// Ensures that at least `additional` items can be inserted into the table . /// without reallocation. . #[cfg_attr(feature = "inline-more", inline)] 581 ( 0.00%) pub fn reserve(&mut self, additional: usize, hasher: impl Fn(&T) -> u64) { 284,417 ( 0.01%) if additional > self.table.growth_left { . // Avoid `Result::unwrap_or_else` because it bloats LLVM IR. 119,683 ( 0.00%) if self . .reserve_rehash(additional, hasher, Fallibility::Infallible) . .is_err() . { . unsafe { hint::unreachable_unchecked() } . } . } 415 ( 0.00%) } . . /// Tries to ensure that at least `additional` items can be inserted into . /// the table without reallocation. . #[cfg_attr(feature = "inline-more", inline)] . pub fn try_reserve( . &mut self, . additional: usize, . hasher: impl Fn(&T) -> u64, -- line 667 ---------------------------------------- -- line 671 ---------------------------------------- . } else { . Ok(()) . } . } . . /// Out-of-line slow path for `reserve` and `try_reserve`. . #[cold] . #[inline(never)] 265,900 ( 0.01%) fn reserve_rehash( . &mut self, . additional: usize, . hasher: impl Fn(&T) -> u64, . fallibility: Fallibility, . ) -> Result<(), TryReserveError> { . unsafe { . self.table.reserve_rehash_inner( . additional, -- line 687 ---------------------------------------- -- line 690 ---------------------------------------- . TableLayout::new::(), . if mem::needs_drop::() { . Some(mem::transmute(ptr::drop_in_place:: as unsafe fn(*mut T))) . } else { . None . }, . ) . } 161,240 ( 0.00%) } . . /// Allocates a new table of a different size and moves the contents of the . /// current table into it. . fn resize( . &mut self, . capacity: usize, . hasher: impl Fn(&T) -> u64, . fallibility: Fallibility, -- line 706 ---------------------------------------- -- line 714 ---------------------------------------- . ) . } . } . . /// Inserts a new element into the table, and returns its raw bucket. . /// . /// This does not check if the given element already exists in the table. . #[cfg_attr(feature = "inline-more", inline)] 2,009,958 ( 0.04%) pub fn insert(&mut self, hash: u64, value: T, hasher: impl Fn(&T) -> u64) -> Bucket { . unsafe { . let mut index = self.table.find_insert_slot(hash); . . // We can avoid growing the table once we have reached our load . // factor if we are replacing a tombstone. This works since the . // number of EMPTY slots does not change in this case. 2,441 ( 0.00%) let old_ctrl = *self.table.ctrl(index); 1,704,571 ( 0.03%) if unlikely(self.table.growth_left == 0 && special_is_empty(old_ctrl)) { . self.reserve(1, hasher); . index = self.table.find_insert_slot(hash); . } . . self.table.record_item_insert_at(index, old_ctrl, hash); . . let bucket = self.bucket(index); 2 ( 0.00%) bucket.write(value); . bucket . } 1,489,295 ( 0.03%) } . . /// Attempts to insert a new element without growing the table and return its raw bucket. . /// . /// Returns an `Err` containing the given element if inserting it would require growing the . /// table. . /// . /// This does not check if the given element already exists in the table. . #[cfg(feature = "raw")] -- line 749 ---------------------------------------- -- line 760 ---------------------------------------- . } . } . } . . /// Inserts a new element into the table, and returns a mutable reference to it. . /// . /// This does not check if the given element already exists in the table. . #[cfg_attr(feature = "inline-more", inline)] 676,176 ( 0.01%) pub fn insert_entry(&mut self, hash: u64, value: T, hasher: impl Fn(&T) -> u64) -> &mut T { 5,980 ( 0.00%) unsafe { self.insert(hash, value, hasher).as_mut() } 507,132 ( 0.01%) } . . /// Inserts a new element into the table, without growing the table. . /// . /// There must be enough space in the table to insert the new element. . /// . /// This does not check if the given element already exists in the table. . #[cfg_attr(feature = "inline-more", inline)] . #[cfg(any(feature = "raw", feature = "rustc-internal-api"))] 2,952 ( 0.00%) pub unsafe fn insert_no_grow(&mut self, hash: u64, value: T) -> Bucket { 354,366 ( 0.01%) let (index, old_ctrl) = self.table.prepare_insert_slot(hash); 12,083 ( 0.00%) let bucket = self.table.bucket(index); . . // If we are replacing a DELETED entry then we don't need to update . // the load counter. 705,381 ( 0.01%) self.table.growth_left -= special_is_empty(old_ctrl) as usize; . . bucket.write(value); 573,058 ( 0.01%) self.table.items += 1; . bucket 5,899 ( 0.00%) } . . /// Temporary removes a bucket, applying the given function to the removed . /// element and optionally put back the returned value in the same bucket. . /// . /// Returns `true` if the bucket still contains an element . /// . /// This does not check if the given bucket is actually occupied. . #[cfg_attr(feature = "inline-more", inline)] -- line 798 ---------------------------------------- -- line 813 ---------------------------------------- . true . } else { . false . } . } . . /// Searches for an element in the table. . #[inline] 48,491 ( 0.00%) pub fn find(&self, hash: u64, mut eq: impl FnMut(&T) -> bool) -> Option> { 5,112 ( 0.00%) let result = self.table.find_inner(hash, &mut |index| unsafe { 33,915 ( 0.00%) eq(self.bucket(index).as_ref()) 1,971 ( 0.00%) }); . . // Avoid `Option::map` because it bloats LLVM IR. . match result { 696 ( 0.00%) Some(index) => Some(unsafe { self.bucket(index) }), . None => None, . } 55,376 ( 0.00%) } . . /// Gets a reference to an element in the table. . #[inline] . pub fn get(&self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option<&T> { . // Avoid `Option::map` because it bloats LLVM IR. 48,446 ( 0.00%) match self.find(hash, eq) { . Some(bucket) => Some(unsafe { bucket.as_ref() }), . None => None, . } . } . . /// Gets a mutable reference to an element in the table. . #[inline] 10,787 ( 0.00%) pub fn get_mut(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option<&mut T> { . // Avoid `Option::map` because it bloats LLVM IR. 25,535 ( 0.00%) match self.find(hash, eq) { . Some(bucket) => Some(unsafe { bucket.as_mut() }), . None => None, . } 12,328 ( 0.00%) } . . /// Attempts to get mutable references to `N` entries in the table at once. . /// . /// Returns an array of length `N` with the results of each query. . /// . /// At most one mutable reference will be returned to any entry. `None` will be returned if any . /// of the hashes are duplicates. `None` will be returned if the hash is not found. . /// -- line 859 ---------------------------------------- -- line 913 ---------------------------------------- . /// more, but is guaranteed to be able to hold at least this many. . #[inline] . pub fn capacity(&self) -> usize { . self.table.items + self.table.growth_left . } . . /// Returns the number of elements in the table. . #[inline] 200 ( 0.00%) pub fn len(&self) -> usize { 100 ( 0.00%) self.table.items 200 ( 0.00%) } . . /// Returns `true` if the table contains no elements. . #[inline] . pub fn is_empty(&self) -> bool { 734,831 ( 0.01%) self.len() == 0 . } . . /// Returns the number of buckets in the table. . #[inline] . pub fn buckets(&self) -> usize { . self.table.bucket_mask + 1 . } . . /// Returns an iterator over every element in the table. It is up to . /// the caller to ensure that the `RawTable` outlives the `RawIter`. . /// Because we cannot make the `next` method unsafe on the `RawIter` . /// struct, we have to make the `iter` method unsafe. . #[inline] 553 ( 0.00%) pub unsafe fn iter(&self) -> RawIter { 555 ( 0.00%) let data = Bucket::from_base_index(self.data_end(), 0); 711 ( 0.00%) RawIter { 553 ( 0.00%) iter: RawIterRange::new(self.table.ctrl.as_ptr(), data, self.table.buckets()), 51,435 ( 0.00%) items: self.table.items, . } 158 ( 0.00%) } . . /// Returns an iterator over occupied buckets that could match a given hash. . /// . /// `RawTable` only stores 7 bits of the hash value, so this iterator may . /// return items that have a hash value different than the one provided. You . /// should always validate the returned values before using them. . /// . /// It is up to the caller to ensure that the `RawTable` outlives the -- line 956 ---------------------------------------- -- line 991 ---------------------------------------- . } . . /// Returns an iterator which consumes all elements from the table. . /// . /// Iteration starts at the provided iterator's current location. . /// . /// It is up to the caller to ensure that the iterator is valid for this . /// `RawTable` and covers all items that remain in the table. 378 ( 0.00%) pub unsafe fn into_iter_from(self, iter: RawIter) -> RawIntoIter { 108 ( 0.00%) debug_assert_eq!(iter.len(), self.len()); . 108 ( 0.00%) let alloc = self.table.alloc.clone(); 2,176 ( 0.00%) let allocation = self.into_allocation(); 1,821 ( 0.00%) RawIntoIter { 2,261 ( 0.00%) iter, 324 ( 0.00%) allocation, . marker: PhantomData, . alloc, . } 108 ( 0.00%) } . . /// Converts the table into a raw allocation. The contents of the table . /// should be dropped using a `RawIter` before freeing the allocation. . #[cfg_attr(feature = "inline-more", inline)] 324 ( 0.00%) pub(crate) fn into_allocation(self) -> Option<(NonNull, Layout)> { 999 ( 0.00%) let alloc = if self.table.is_empty_singleton() { 54 ( 0.00%) None . } else { . // Avoid `Option::unwrap_or_else` because it bloats LLVM IR. . let (layout, ctrl_offset) = match calculate_layout::(self.table.buckets()) { . Some(lco) => lco, . None => unsafe { hint::unreachable_unchecked() }, . }; . Some(( 183 ( 0.00%) unsafe { NonNull::new_unchecked(self.table.ctrl.as_ptr().sub(ctrl_offset)) }, . layout, . )) . }; 486 ( 0.00%) mem::forget(self); . alloc 108 ( 0.00%) } . } . . unsafe impl Send for RawTable . where . T: Send, . A: Send, . { . } -- line 1039 ---------------------------------------- -- line 1041 ---------------------------------------- . where . T: Sync, . A: Sync, . { . } . . impl RawTableInner { . #[inline] 186 ( 0.00%) const fn new_in(alloc: A) -> Self { 384,913 ( 0.01%) Self { . // Be careful to cast the entire slice to a raw pointer. 434 ( 0.00%) ctrl: unsafe { NonNull::new_unchecked(Group::static_empty() as *const _ as *mut u8) }, . bucket_mask: 0, . items: 0, . growth_left: 0, . alloc, . } 124 ( 0.00%) } . } . . impl RawTableInner { . #[cfg_attr(feature = "inline-more", inline)] 185,530 ( 0.00%) unsafe fn new_uninitialized( . alloc: A, . table_layout: TableLayout, . buckets: usize, . fallibility: Fallibility, . ) -> Result { . debug_assert!(buckets.is_power_of_two()); . . // Avoid `Option::ok_or_else` because it bloats LLVM IR. -- line 1071 ---------------------------------------- -- line 1078 ---------------------------------------- . // exceed `isize::MAX`. We can skip this check on 64-bit systems since . // such allocations will never succeed anyways. . // . // This mirrors what Vec does in the standard library. . if mem::size_of::() < 8 && layout.size() > isize::MAX as usize { . return Err(fallibility.capacity_overflow()); . } . 55,486 ( 0.00%) let ptr: NonNull = match do_alloc(&alloc, layout) { . Ok(block) => block.cast(), . Err(_) => return Err(fallibility.alloc_err(layout)), . }; . . let ctrl = NonNull::new_unchecked(ptr.as_ptr().add(ctrl_offset)); 110,604 ( 0.00%) Ok(Self { . ctrl, 51,602 ( 0.00%) bucket_mask: buckets - 1, . items: 0, . growth_left: bucket_mask_to_capacity(buckets - 1), . alloc, . }) 135,976 ( 0.00%) } . . #[inline] 18,041 ( 0.00%) fn fallible_with_capacity( . alloc: A, . table_layout: TableLayout, . capacity: usize, . fallibility: Fallibility, . ) -> Result { 4,569 ( 0.00%) if capacity == 0 { 4,302 ( 0.00%) Ok(Self::new_in(alloc)) . } else { . unsafe { . let buckets = . capacity_to_buckets(capacity).ok_or_else(|| fallibility.capacity_overflow())?; . 83,474 ( 0.00%) let result = Self::new_uninitialized(alloc, table_layout, buckets, fallibility)?; . result.ctrl(0).write_bytes(EMPTY, result.num_ctrl_bytes()); . 8,538 ( 0.00%) Ok(result) . } . } 17,888 ( 0.00%) } . . /// Searches for an empty or deleted bucket which is suitable for inserting . /// a new element and sets the hash for that slot. . /// . /// There must be at least 1 empty bucket in the table. . #[inline] 118,829 ( 0.00%) unsafe fn prepare_insert_slot(&self, hash: u64) -> (usize, u8) { . let index = self.find_insert_slot(hash); 118,829 ( 0.00%) let old_ctrl = *self.ctrl(index); . self.set_ctrl_h2(index, hash); . (index, old_ctrl) 237,658 ( 0.00%) } . . /// Searches for an empty or deleted bucket which is suitable for inserting . /// a new element. . /// . /// There must be at least 1 empty bucket in the table. . #[inline] . fn find_insert_slot(&self, hash: u64) -> usize { . let mut probe_seq = self.probe_seq(hash); . loop { . unsafe { . let group = Group::load(self.ctrl(probe_seq.pos)); 1,173,924 ( 0.02%) if let Some(bit) = group.match_empty_or_deleted().lowest_set_bit() { 3,415,053 ( 0.07%) let result = (probe_seq.pos + bit) & self.bucket_mask; . . // In tables smaller than the group width, trailing control . // bytes outside the range of the table are filled with . // EMPTY entries. These will unfortunately trigger a . // match, but once masked may point to a full bucket that . // is already occupied. We detect this situation here and . // perform a second scan starting at the beginning of the . // table. This second scan is guaranteed to find an empty . // slot (due to the load factor) before hitting the trailing . // control bytes (containing EMPTY). 1,562,186 ( 0.03%) if unlikely(is_full(*self.ctrl(result))) { . debug_assert!(self.bucket_mask < Group::WIDTH); . debug_assert_ne!(probe_seq.pos, 0); . return Group::load_aligned(self.ctrl(0)) . .match_empty_or_deleted() . .lowest_set_bit_nonzero(); . } . . return result; -- line 1165 ---------------------------------------- -- line 1171 ---------------------------------------- . . /// Searches for an element in the table. This uses dynamic dispatch to reduce the amount of . /// code generated, but it is eliminated by LLVM optimizations. . #[inline] . fn find_inner(&self, hash: u64, eq: &mut dyn FnMut(usize) -> bool) -> Option { . let h2_hash = h2(hash); . let mut probe_seq = self.probe_seq(hash); . 73,652 ( 0.00%) loop { . let group = unsafe { Group::load(self.ctrl(probe_seq.pos)) }; . 3,481,074 ( 0.07%) for bit in group.match_byte(h2_hash) { 6,731,314 ( 0.13%) let index = (probe_seq.pos + bit) & self.bucket_mask; . 4,840,282 ( 0.09%) if likely(eq(index)) { . return Some(index); . } . } . 1,025,108 ( 0.02%) if likely(group.match_empty().any_bit_set()) { . return None; . } . . probe_seq.move_next(self.bucket_mask); . } . } . . #[allow(clippy::mut_mut)] . #[inline] . unsafe fn prepare_rehash_in_place(&mut self) { . // Bulk convert all full control bytes to DELETED, and all DELETED . // control bytes to EMPTY. This effectively frees up all buckets . // containing a DELETED entry. 3 ( 0.00%) for i in (0..self.buckets()).step_by(Group::WIDTH) { . let group = Group::load_aligned(self.ctrl(i)); . let group = group.convert_special_to_empty_and_full_to_deleted(); . group.store_aligned(self.ctrl(i)); . } . . // Fix up the trailing control bytes. See the comments in set_ctrl . // for the handling of tables smaller than the group width. 3 ( 0.00%) if self.buckets() < Group::WIDTH { . self.ctrl(0) . .copy_to(self.ctrl(Group::WIDTH), self.buckets()); . } else { . self.ctrl(0) . .copy_to(self.ctrl(self.buckets()), Group::WIDTH); . } . } . -- line 1220 ---------------------------------------- -- line 1225 ---------------------------------------- . Bucket::from_base_index(self.data_end(), index) . } . . #[inline] . unsafe fn bucket_ptr(&self, index: usize, size_of: usize) -> *mut u8 { . debug_assert_ne!(self.bucket_mask, 0); . debug_assert!(index < self.buckets()); . let base: *mut u8 = self.data_end().as_ptr(); 4,553,224 ( 0.09%) base.sub((index + 1) * size_of) . } . . #[inline] . unsafe fn data_end(&self) -> NonNull { . NonNull::new_unchecked(self.ctrl.as_ptr().cast()) . } . . /// Returns an iterator-like object for a probe sequence on the table. . /// . /// This iterator never terminates, but is guaranteed to visit each bucket . /// group exactly once. The loop using `probe_seq` must terminate upon . /// reaching a group containing an empty bucket. . #[inline] . fn probe_seq(&self, hash: u64) -> ProbeSeq { . ProbeSeq { 21,539,736 ( 0.41%) pos: h1(hash) & self.bucket_mask, . stride: 0, . } . } . . /// Returns the index of a bucket for which a value must be inserted if there is enough rooom . /// in the table, otherwise returns error . #[cfg(feature = "raw")] . #[inline] -- line 1257 ---------------------------------------- -- line 1263 ---------------------------------------- . } else { . self.record_item_insert_at(index, old_ctrl, hash); . Ok(index) . } . } . . #[inline] . unsafe fn record_item_insert_at(&mut self, index: usize, old_ctrl: u8, hash: u64) { 2,148,785 ( 0.04%) self.growth_left -= special_is_empty(old_ctrl) as usize; . self.set_ctrl_h2(index, hash); 1,704,516 ( 0.03%) self.items += 1; . } . . #[inline] . fn is_in_same_group(&self, i: usize, new_i: usize, hash: u64) -> bool { . let probe_seq_pos = self.probe_seq(hash).pos; . let probe_index = . |pos: usize| (pos.wrapping_sub(probe_seq_pos) & self.bucket_mask) / Group::WIDTH; 39 ( 0.00%) probe_index(i) == probe_index(new_i) . } . . /// Sets a control byte to the hash, and possibly also the replicated control byte at . /// the end of the array. . #[inline] . unsafe fn set_ctrl_h2(&self, index: usize, hash: u64) { . self.set_ctrl(index, h2(hash)); . } -- line 1289 ---------------------------------------- -- line 1312 ---------------------------------------- . // replicate the buckets at the end of the trailing group. For example . // with 2 buckets and a group size of 4, the control bytes will look . // like this: . // . // Real | Replicated . // --------------------------------------------- . // | [A] | [B] | [EMPTY] | [EMPTY] | [A] | [B] | . // --------------------------------------------- 3,354,338 ( 0.06%) let index2 = ((index.wrapping_sub(Group::WIDTH)) & self.bucket_mask) + Group::WIDTH; . 1,117,058 ( 0.02%) *self.ctrl(index) = ctrl; 1,117,161 ( 0.02%) *self.ctrl(index2) = ctrl; . } . . /// Returns a pointer to a control byte. . #[inline] . unsafe fn ctrl(&self, index: usize) -> *mut u8 { . debug_assert!(index < self.num_ctrl_bytes()); . self.ctrl.as_ptr().add(index) . } . . #[inline] 158 ( 0.00%) fn buckets(&self) -> usize { 163,935 ( 0.00%) self.bucket_mask + 1 158 ( 0.00%) } . . #[inline] . fn num_ctrl_bytes(&self) -> usize { 133,391 ( 0.00%) self.bucket_mask + 1 + Group::WIDTH . } . . #[inline] 124 ( 0.00%) fn is_empty_singleton(&self) -> bool { 762,476 ( 0.01%) self.bucket_mask == 0 248 ( 0.00%) } . . #[allow(clippy::mut_mut)] . #[inline] . unsafe fn prepare_resize( . &self, . table_layout: TableLayout, . capacity: usize, . fallibility: Fallibility, . ) -> Result, TryReserveError> { . debug_assert!(self.items <= capacity); . . // Allocate and initialize the new table. 2,490 ( 0.00%) let mut new_table = RawTableInner::fallible_with_capacity( . self.alloc.clone(), . table_layout, . capacity, . fallibility, . )?; 73,700 ( 0.00%) new_table.growth_left -= self.items; . new_table.items = self.items; . . // The hash function may panic, in which case we simply free the new . // table without dropping any elements that may have been copied into . // it. . // . // This guard is also used to free the old table on success, see . // the comment at the bottom of this function. . Ok(guard(new_table, move |self_| { 32,557 ( 0.00%) if !self_.is_empty_singleton() { . self_.free_buckets(table_layout); . } . })) . } . . /// Reserves or rehashes to make room for `additional` more elements. . /// . /// This uses dynamic dispatch to reduce the amount of -- line 1383 ---------------------------------------- -- line 1388 ---------------------------------------- . &mut self, . additional: usize, . hasher: &dyn Fn(&mut Self, usize) -> u64, . fallibility: Fallibility, . layout: TableLayout, . drop: Option, . ) -> Result<(), TryReserveError> { . // Avoid `Option::ok_or_else` because it bloats LLVM IR. 65,116 ( 0.00%) let new_items = match self.items.checked_add(additional) { . Some(new_items) => new_items, . None => return Err(fallibility.capacity_overflow()), . }; 65,116 ( 0.00%) let full_capacity = bucket_mask_to_capacity(self.bucket_mask); 137,020 ( 0.00%) if new_items <= full_capacity / 2 { . // Rehash in-place without re-allocating if we have plenty of spare . // capacity that is locked up due to DELETED entries. . self.rehash_in_place(hasher, layout.size, drop); 2 ( 0.00%) Ok(()) . } else { . // Otherwise, conservatively resize to at least the next size up . // to avoid churning deletes into frequent rehashes. . self.resize_inner( 32,557 ( 0.00%) usize::max(new_items, full_capacity + 1), . hasher, . fallibility, . layout, . ) . } . } . . /// Allocates a new table of a different size and moves the contents of the -- line 1418 ---------------------------------------- -- line 1424 ---------------------------------------- . #[inline(always)] . unsafe fn resize_inner( . &mut self, . capacity: usize, . hasher: &dyn Fn(&mut Self, usize) -> u64, . fallibility: Fallibility, . layout: TableLayout, . ) -> Result<(), TryReserveError> { 6,210 ( 0.00%) let mut new_table = self.prepare_resize(layout, capacity, fallibility)?; . . // Copy all elements to the new table. . for i in 0..self.buckets() { 673,333 ( 0.01%) if !is_full(*self.ctrl(i)) { . continue; . } . . // This may panic. . let hash = hasher(self, i); . . // We can use a simpler version of insert() here since: . // - there are no DELETED entries. -- line 1444 ---------------------------------------- -- line 1454 ---------------------------------------- . } . . // We successfully copied all elements without panicking. Now replace . // self with the new table. The old table will have its memory freed but . // the items will not be dropped (since they have been moved into the . // new table). . mem::swap(self, &mut new_table); . 32,557 ( 0.00%) Ok(()) . } . . /// Rehashes the contents of the table in place (i.e. without changing the . /// allocation). . /// . /// If `hasher` panics then some the table's contents may be lost. . /// . /// This uses dynamic dispatch to reduce the amount of -- line 1470 ---------------------------------------- -- line 1496 ---------------------------------------- . } . self_.growth_left = bucket_mask_to_capacity(self_.bucket_mask) - self_.items; . }); . . // At this point, DELETED elements are elements that we haven't . // rehashed yet. Find them and re-insert them at their ideal . // position. . 'outer: for i in 0..guard.buckets() { 64 ( 0.00%) if *guard.ctrl(i) != DELETED { . continue; . } . . let i_p = guard.bucket_ptr(i, size_of); . . 'inner: loop { . // Hash the current item . let hash = hasher(*guard, i); -- line 1512 ---------------------------------------- -- line 1515 ---------------------------------------- . let new_i = guard.find_insert_slot(hash); . let new_i_p = guard.bucket_ptr(new_i, size_of); . . // Probing works by scanning through all of the control . // bytes in groups, which may not be aligned to the group . // size. If both the new and old position fall within the . // same unaligned group, then there is no benefit in moving . // it and we can just continue to the next item. 13 ( 0.00%) if likely(guard.is_in_same_group(i, new_i, hash)) { . guard.set_ctrl_h2(i, hash); . continue 'outer; . } . . // We are moving the current item to a new position. Write . // our H2 to the control byte of the new position. . let prev_ctrl = guard.replace_ctrl_h2(new_i, hash); . if prev_ctrl == EMPTY { -- line 1531 ---------------------------------------- -- line 1541 ---------------------------------------- . // swapped into the old slot. . debug_assert_eq!(prev_ctrl, DELETED); . ptr::swap_nonoverlapping(i_p, new_i_p, size_of); . continue 'inner; . } . } . } . 3 ( 0.00%) guard.growth_left = bucket_mask_to_capacity(guard.bucket_mask) - guard.items; . . mem::forget(guard); . } . . #[inline] . unsafe fn free_buckets(&mut self, table_layout: TableLayout) { . // Avoid `Option::unwrap_or_else` because it bloats LLVM IR. . let (layout, ctrl_offset) = match table_layout.calculate_layout_for(self.buckets()) { . Some(lco) => lco, . None => hint::unreachable_unchecked(), . }; . self.alloc.deallocate( 19,942 ( 0.00%) NonNull::new_unchecked(self.ctrl.as_ptr().sub(ctrl_offset)), . layout, . ); . } . . /// Marks all table buckets as empty without dropping their contents. . #[inline] . fn clear_no_drop(&mut self) { 9,701 ( 0.00%) if !self.is_empty_singleton() { . unsafe { . self.ctrl(0).write_bytes(EMPTY, self.num_ctrl_bytes()); . } . } 12,168 ( 0.00%) self.items = 0; 9,768 ( 0.00%) self.growth_left = bucket_mask_to_capacity(self.bucket_mask); . } . . #[inline] . unsafe fn erase(&mut self, index: usize) { . debug_assert!(is_full(*self.ctrl(index))); 83,572 ( 0.00%) let index_before = index.wrapping_sub(Group::WIDTH) & self.bucket_mask; . let empty_before = Group::load(self.ctrl(index_before)).match_empty(); . let empty_after = Group::load(self.ctrl(index)).match_empty(); . . // If we are inside a continuous block of Group::WIDTH full or deleted . // cells then a probe window may have seen a full block when trying to . // insert. We therefore need to keep that block non-empty so that . // lookups will continue searching to the next probe window. . // . // Note that in this context `leading_zeros` refers to the bytes at the . // end of a group, while `trailing_zeros` refers to the bytes at the . // beginning of a group. 334,288 ( 0.01%) let ctrl = if empty_before.leading_zeros() + empty_after.trailing_zeros() >= Group::WIDTH { . DELETED . } else { 409,080 ( 0.01%) self.growth_left += 1; . EMPTY . }; . self.set_ctrl(index, ctrl); 334,288 ( 0.01%) self.items -= 1; . } . } . . impl Clone for RawTable { 174,808 ( 0.00%) fn clone(&self) -> Self { 21,868 ( 0.00%) if self.table.is_empty_singleton() { . Self::new_in(self.table.alloc.clone()) . } else { . unsafe { . let mut new_table = ManuallyDrop::new( . // Avoid `Result::ok_or_else` because it bloats LLVM IR. . match Self::new_uninitialized( . self.table.alloc.clone(), . self.table.buckets(), -- line 1615 ---------------------------------------- -- line 1624 ---------------------------------------- . // We need to free the memory allocated for the new table. . new_table.free_buckets(); . }); . . // Return the newly created table. . ManuallyDrop::into_inner(new_table) . } . } 196,659 ( 0.00%) } . . fn clone_from(&mut self, source: &Self) { . if source.table.is_empty_singleton() { . *self = Self::new_in(self.table.alloc.clone()); . } else { . unsafe { . // First, drop all our elements without clearing the control bytes. . self.drop_elements(); -- line 1640 ---------------------------------------- -- line 1687 ---------------------------------------- . .table . .ctrl(0) . .copy_to_nonoverlapping(self.table.ctrl(0), self.table.num_ctrl_bytes()); . source . .data_start() . .copy_to_nonoverlapping(self.data_start(), self.table.buckets()); . . self.table.items = source.table.items; 32 ( 0.00%) self.table.growth_left = source.table.growth_left; . } . } . . impl RawTable { . /// Common code for clone and clone_from. Assumes `self.buckets() == source.buckets()`. . #[cfg_attr(feature = "inline-more", inline)] . unsafe fn clone_from_impl(&mut self, source: &Self, mut on_panic: impl FnMut(&mut Self)) { . // Copy the control bytes unchanged. We do this in a single pass -- line 1703 ---------------------------------------- -- line 1790 ---------------------------------------- . fn default() -> Self { . Self::new_in(Default::default()) . } . } . . #[cfg(feature = "nightly")] . unsafe impl<#[may_dangle] T, A: Allocator + Clone> Drop for RawTable { . #[cfg_attr(feature = "inline-more", inline)] 605,206 ( 0.01%) fn drop(&mut self) { 310,620 ( 0.01%) if !self.table.is_empty_singleton() { . unsafe { . self.drop_elements(); . self.free_buckets(); . } . } 663,604 ( 0.01%) } . } . #[cfg(not(feature = "nightly"))] . impl Drop for RawTable { . #[cfg_attr(feature = "inline-more", inline)] . fn drop(&mut self) { . if !self.table.is_empty_singleton() { . unsafe { . self.drop_elements(); -- line 1813 ---------------------------------------- -- line 1817 ---------------------------------------- . } . } . . impl IntoIterator for RawTable { . type Item = T; . type IntoIter = RawIntoIter; . . #[cfg_attr(feature = "inline-more", inline)] 1,852 ( 0.00%) fn into_iter(self) -> RawIntoIter { . unsafe { 324 ( 0.00%) let iter = self.iter(); 864 ( 0.00%) self.into_iter_from(iter) . } 2,153 ( 0.00%) } . } . . /// Iterator over a sub-range of a table. Unlike `RawIter` this iterator does . /// not track an item count. . pub(crate) struct RawIterRange { . // Mask of full buckets in the current group. Bits are cleared from this . // mask as each element is processed. . current_group: BitMask, -- line 1838 ---------------------------------------- -- line 1848 ---------------------------------------- . end: *const u8, . } . . impl RawIterRange { . /// Returns a `RawIterRange` covering a subset of a table. . /// . /// The control byte address must be aligned to the group size. . #[cfg_attr(feature = "inline-more", inline)] 948 ( 0.00%) unsafe fn new(ctrl: *const u8, data: Bucket, len: usize) -> Self { . debug_assert_ne!(len, 0); . debug_assert_eq!(ctrl as usize % Group::WIDTH, 0); 79 ( 0.00%) let end = ctrl.add(len); . . // Load the first group and advance ctrl to point to the next group 474 ( 0.00%) let current_group = Group::load_aligned(ctrl).match_full(); 79 ( 0.00%) let next_ctrl = ctrl.add(Group::WIDTH); . 316 ( 0.00%) Self { . current_group, . data, . next_ctrl, . end, . } 158 ( 0.00%) } . . /// Splits a `RawIterRange` into two halves. . /// . /// Returns `None` if the remaining range is smaller than or equal to the . /// group width. . #[cfg_attr(feature = "inline-more", inline)] . #[cfg(feature = "rayon")] . pub(crate) fn split(mut self) -> (Self, Option>) { -- line 1879 ---------------------------------------- -- line 1931 ---------------------------------------- . } . } . } . . impl Iterator for RawIterRange { . type Item = Bucket; . . #[cfg_attr(feature = "inline-more", inline)] 316 ( 0.00%) fn next(&mut self) -> Option> { . unsafe { . loop { 156,840 ( 0.00%) if let Some(index) = self.current_group.lowest_set_bit() { 24,950 ( 0.00%) self.current_group = self.current_group.remove_lowest_bit(); 35,278 ( 0.00%) return Some(self.data.next_n(index)); . } . 118,266 ( 0.00%) if self.next_ctrl >= self.end { 79 ( 0.00%) return None; . } . . // We might read past self.end up to the next group boundary, . // but this is fine because it only occurs on tables smaller . // than the group size where the trailing control bytes are all . // EMPTY. On larger tables self.end is guaranteed to be aligned . // to the group size (since tables are power-of-two sized). 5,331 ( 0.00%) self.current_group = Group::load_aligned(self.next_ctrl).match_full(); 3,917 ( 0.00%) self.data = self.data.next_n(Group::WIDTH); 8,952 ( 0.00%) self.next_ctrl = self.next_ctrl.add(Group::WIDTH); . } . } 237 ( 0.00%) } . . #[inline] . fn size_hint(&self) -> (usize, Option) { . // We don't have an item count, so just guess based on the range size. . ( . 0, . Some(unsafe { offset_from(self.end, self.next_ctrl) + Group::WIDTH }), . ) -- line 1969 ---------------------------------------- -- line 2101 ---------------------------------------- . } . } . } else { . // We must have already iterated past the removed item. . } . } . } . 108 ( 0.00%) unsafe fn drop_elements(&mut self) { 5,469 ( 0.00%) if mem::needs_drop::() && self.len() != 0 { . for item in self { . item.drop(); . } . } 108 ( 0.00%) } . } . . impl Clone for RawIter { . #[cfg_attr(feature = "inline-more", inline)] . fn clone(&self) -> Self { . Self { . iter: self.iter.clone(), . items: self.items, -- line 2123 ---------------------------------------- -- line 2124 ---------------------------------------- . } . } . } . . impl Iterator for RawIter { . type Item = Bucket; . . #[cfg_attr(feature = "inline-more", inline)] 23,739 ( 0.00%) fn next(&mut self) -> Option> { 59,800 ( 0.00%) if let Some(b) = self.iter.next() { 239,236 ( 0.00%) self.items -= 1; . Some(b) . } else { . // We don't check against items == 0 here to allow the . // compiler to optimize away the item count entirely if the . // iterator length is never queried. . debug_assert_eq!(self.items, 0); 79 ( 0.00%) None . } 47,241 ( 0.00%) } . . #[inline] 237 ( 0.00%) fn size_hint(&self) -> (usize, Option) { 711 ( 0.00%) (self.items, Some(self.items)) 158 ( 0.00%) } . } . . impl ExactSizeIterator for RawIter {} . impl FusedIterator for RawIter {} . . /// Iterator which consumes a table and returns elements. . pub struct RawIntoIter { . iter: RawIter, -- line 2156 ---------------------------------------- -- line 2177 ---------------------------------------- . T: Sync, . A: Sync, . { . } . . #[cfg(feature = "nightly")] . unsafe impl<#[may_dangle] T, A: Allocator + Clone> Drop for RawIntoIter { . #[cfg_attr(feature = "inline-more", inline)] 1,160 ( 0.00%) fn drop(&mut self) { . unsafe { . // Drop all remaining elements 54 ( 0.00%) self.iter.drop_elements(); . . // Free the table 2,982 ( 0.00%) if let Some((ptr, layout)) = self.allocation { . self.alloc.deallocate(ptr, layout); . } . } 342 ( 0.00%) } . } . #[cfg(not(feature = "nightly"))] . impl Drop for RawIntoIter { . #[cfg_attr(feature = "inline-more", inline)] . fn drop(&mut self) { . unsafe { . // Drop all remaining elements . self.iter.drop_elements(); -- line 2203 ---------------------------------------- -- line 2209 ---------------------------------------- . } . } . } . . impl Iterator for RawIntoIter { . type Item = T; . . #[cfg_attr(feature = "inline-more", inline)] 1,429 ( 0.00%) fn next(&mut self) -> Option { 705 ( 0.00%) unsafe { Some(self.iter.next()?.read()) } 4,128 ( 0.00%) } . . #[inline] 216 ( 0.00%) fn size_hint(&self) -> (usize, Option) { 56 ( 0.00%) self.iter.size_hint() 108 ( 0.00%) } . } . . impl ExactSizeIterator for RawIntoIter {} . impl FusedIterator for RawIntoIter {} . . /// Iterator which consumes elements without freeing the table storage. . pub struct RawDrain<'a, T, A: Allocator + Clone = Global> { . iter: RawIter, -- line 2232 ---------------------------------------- -- line 2259 ---------------------------------------- . where . T: Sync, . A: Sync, . { . } . . impl Drop for RawDrain<'_, T, A> { . #[cfg_attr(feature = "inline-more", inline)] 11,984 ( 0.00%) fn drop(&mut self) { . unsafe { . // Drop all remaining elements. Note that this may panic. . self.iter.drop_elements(); . . // Reset the contents of the table now that all elements have been . // dropped. . self.table.clear_no_drop(); . . // Move the now empty table back to its original location. 1,498 ( 0.00%) self.orig_table . .as_ptr() . .copy_from_nonoverlapping(&*self.table, 1); . } 11,984 ( 0.00%) } . } . . impl Iterator for RawDrain<'_, T, A> { . type Item = T; . . #[cfg_attr(feature = "inline-more", inline)] . fn next(&mut self) -> Option { . unsafe { -- line 2289 ---------------------------------------- 10,085,580 ( 0.19%) -------------------------------------------------------------------------------- The following files chosen for auto-annotation could not be found: -------------------------------------------------------------------------------- ./elf/../sysdeps/x86_64/dl-machine.h ./elf/dl-lookup.c ./malloc/malloc.c ./stdlib/msort.c ./string/../sysdeps/x86_64/multiarch/memcmp-avx2-movbe.S ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S ./string/../sysdeps/x86_64/multiarch/memset-vec-unaligned-erms.S ./string/../sysdeps/x86_64/multiarch/strcmp-avx2.S /tmp/gcc-build/x86_64-unknown-linux-gnu/libstdc++-v3/libsupc++/../../../../gcc-5.5.0/libstdc++-v3/libsupc++/new_op.cc -------------------------------------------------------------------------------- Ir -------------------------------------------------------------------------------- 232,305,571 ( 4.46%) events annotated