-------------------------------------------------------------------------------- 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 time_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=2b56edfe744aaf87 -C extra-filename=-2b56edfe744aaf87 --out-dir /usr/home/liquid/tmp/.tmp56T4rW/target/debug/deps -L dependency=/usr/home/liquid/tmp/.tmp56T4rW/target/debug/deps --extern proc_macro -Adeprecated -Aunknown-lints -Zincremental-verify-ich Data file: results/cgout-w-profiling-time-macros-0.2.3-Debug-Full Events recorded: Ir Events shown: Ir Event sort order: Ir Thresholds: 0.1 Include dirs: User annotated: Auto-annotation: on -------------------------------------------------------------------------------- Ir -------------------------------------------------------------------------------- 8,695,134,519 (100.0%) PROGRAM TOTALS -------------------------------------------------------------------------------- Ir file:function -------------------------------------------------------------------------------- 324,084,385 ( 3.73%) ./malloc/malloc.c:_int_free 274,161,235 ( 3.15%) ???:llvm::SelectionDAG::Combine(llvm::CombineLevel, llvm::AAResults*, llvm::CodeGenOpt::Level) 249,639,915 ( 2.87%) ./malloc/malloc.c:_int_malloc 210,878,128 ( 2.43%) ./malloc/malloc.c:malloc 186,446,227 ( 2.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe/macro_parser.rs:rustc_expand::mbe::macro_parser::parse_tt 178,530,307 ( 2.05%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::bump 173,132,617 ( 1.99%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::next 159,197,155 ( 1.83%) ???:llvm::FPPassManager::runOnFunction(llvm::Function&) 146,867,522 ( 1.69%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs:rustc_expand::mbe::macro_parser::parse_tt 121,915,604 ( 1.40%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/tokenstream.rs:::next_with_spacing 105,017,277 ( 1.21%) ???:llvm::SelectionDAGISel::SelectCodeCommon(llvm::SDNode*, unsigned char const*, unsigned int) 103,480,738 ( 1.19%) ./malloc/malloc.c:free 101,312,137 ( 1.17%) ???:(anonymous namespace)::Verifier::visitInstruction(llvm::Instruction&) 80,834,550 ( 0.93%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::bump_with 76,979,808 ( 0.89%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::next_desugared 71,299,754 ( 0.82%) ???:llvm::ScheduleDAGSDNodes::BuildSchedUnits() 68,864,077 ( 0.79%) ???:llvm::MachineInstr::addOperand(llvm::MachineFunction&, llvm::MachineOperand const&) 68,842,467 ( 0.79%) ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:__memcpy_avx_unaligned_erms 62,625,204 ( 0.72%) ???:(anonymous namespace)::RegAllocFast::allocateBasicBlock(llvm::MachineBasicBlock&) 55,236,015 ( 0.64%) ???:llvm::raw_svector_ostream::write_impl(char const*, unsigned long) 54,312,583 ( 0.62%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::clone 52,262,524 ( 0.60%) ???:llvm::TargetLoweringBase::getTypeConversion(llvm::LLVMContext&, llvm::EVT) const 51,734,112 ( 0.59%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:>::truncate 46,307,724 ( 0.53%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe/macro_parser.rs:::clone 44,119,759 ( 0.51%) ???:(anonymous namespace)::Verifier::visitMDNode(llvm::MDNode const&, (anonymous namespace)::Verifier::AreDebugLocsAllowed) 44,066,523 ( 0.51%) ???:llvm::MCExpr::evaluateAsRelocatableImpl(llvm::MCValue&, llvm::MCAssembler const*, llvm::MCAsmLayout const*, llvm::MCFixup const*, llvm::DenseMap, llvm::detail::DenseMapPair > const*, bool) const 43,719,192 ( 0.50%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe.rs:::get_tt 40,706,136 ( 0.47%) ./string/../sysdeps/x86_64/multiarch/memset-vec-unaligned-erms.S:__memset_avx2_erms 40,297,052 ( 0.46%) ./malloc/malloc.c:malloc_consolidate 39,741,636 ( 0.46%) ???:llvm::AttributeList::addAttributes(llvm::LLVMContext&, unsigned int, llvm::AttrBuilder const&) const 37,888,537 ( 0.44%) ???:(anonymous namespace)::VarLocBasedLDV::process(llvm::MachineInstr&, (anonymous namespace)::VarLocBasedLDV::OpenRangesSet&, (anonymous namespace)::VarLocBasedLDV::VarLocMap&, llvm::SmallVector<(anonymous namespace)::VarLocBasedLDV::TransferDebugPair, 4u>&) 37,866,071 ( 0.44%) ???:llvm::InstrEmitter::EmitMachineNode(llvm::SDNode*, bool, bool, llvm::DenseMap, llvm::detail::DenseMapPair >&) 37,186,714 ( 0.43%) ???:(anonymous namespace)::SelectionDAGLegalize::LegalizeOp(llvm::SDNode*) [clone .llvm.8386621111310650999] 36,394,151 ( 0.42%) ???:llvm::SelectionDAG::MorphNodeTo(llvm::SDNode*, unsigned int, llvm::SDVTList, llvm::ArrayRef) 36,209,356 ( 0.42%) ???:llvm::DAGTypeLegalizer::run() 36,098,780 ( 0.42%) ???:llvm::MCAsmLayout::getSymbolOffset(llvm::MCSymbol const&) const 34,405,336 ( 0.40%) ???:llvm::PMDataManager::verifyPreservedAnalysis(llvm::Pass*) 34,221,904 ( 0.39%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:rustc_expand::mbe::macro_parser::parse_tt 31,734,673 ( 0.36%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs: as core::iter::traits::collect::Extend>::extend::>> 31,614,183 ( 0.36%) ???:llvm::SelectionDAG::getConstant(llvm::ConstantInt const&, llvm::SDLoc const&, llvm::EVT, bool, bool) 31,388,815 ( 0.36%) ???:(anonymous namespace)::Verifier::visitCallBase(llvm::CallBase&) 31,279,413 ( 0.36%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:core::ptr::drop_in_place:: 30,704,509 ( 0.35%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::parse_token_tree 29,479,464 ( 0.34%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe.rs:rustc_expand::mbe::macro_parser::parse_tt 29,456,474 ( 0.34%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/nonterminal.rs:::parse_nonterminal 29,409,453 ( 0.34%) ???:llvm::SelectionDAG::Legalize() 29,339,521 ( 0.34%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::eq 29,100,438 ( 0.33%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:::bump_with 29,046,512 ( 0.33%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs:>>::make_mut 27,799,004 ( 0.32%) ???:(anonymous namespace)::ScheduleDAGRRList::Schedule() [clone .llvm.6953762222372402862] 27,482,269 ( 0.32%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::ident 27,125,216 ( 0.31%) ./malloc/malloc.c:unlink_chunk.constprop.0 27,004,392 ( 0.31%) ???:llvm::TargetRegisterInfo::shouldRealignStack(llvm::MachineFunction const&) const 26,759,502 ( 0.31%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs: as core::iter::traits::collect::Extend>::extend::>> 26,633,247 ( 0.31%) ???:(anonymous namespace)::TwoAddressInstructionPass::runOnMachineFunction(llvm::MachineFunction&) 26,585,400 ( 0.31%) ???:(anonymous namespace)::Verifier::verify(llvm::Function const&) [clone .llvm.4153962086227604281] 25,928,456 ( 0.30%) ???:(anonymous namespace)::DAGCombiner::combine(llvm::SDNode*) 25,779,348 ( 0.30%) ./string/../sysdeps/x86_64/multiarch/memcmp-avx2-movbe.S:__memcmp_avx2_movbe 24,659,563 ( 0.28%) ???:(anonymous namespace)::X86MCCodeEmitter::emitPrefixImpl(unsigned int&, llvm::MCInst const&, llvm::MCSubtargetInfo const&, llvm::raw_ostream&) const 24,635,900 ( 0.28%) /usr/home/liquid/rust/worktree-benchmarking/library/std/src/sys/unix/alloc.rs:__rdl_alloc 24,078,790 ( 0.28%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::lifetime 24,053,585 ( 0.28%) ???:llvm::MetadataTracking::track(void*, llvm::Metadata&, llvm::PointerUnion) 22,654,807 ( 0.26%) ???:llvm::SmallSet >::insert(llvm::Register const&) 21,666,764 ( 0.25%) ???:llvm::ScheduleDAGSDNodes::AddSchedEdges() 21,155,405 ( 0.24%) ???:llvm::FoldingSetBase::FindNodeOrInsertPos(llvm::FoldingSetNodeID const&, void*&, llvm::FoldingSetBase::FoldingSetInfo const&) 20,738,073 ( 0.24%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs:>::try_reserve 20,473,315 ( 0.24%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs: as core::ops::drop::Drop>::drop 20,312,947 ( 0.23%) ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:__memcpy_sse2_unaligned_erms 19,442,047 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:::bump_with 19,400,286 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/span_encoding.rs:::bump 19,328,334 ( 0.22%) ???:(anonymous namespace)::Verifier::verifyFunctionAttrs(llvm::FunctionType*, llvm::AttributeList, llvm::Value const*, bool) 19,324,432 ( 0.22%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs:>::try_reserve 18,269,314 ( 0.21%) ???:llvm::DomTreeBuilder::SemiNCAInfo >::CalculateFromScratch(llvm::DominatorTreeBase&, llvm::DomTreeBuilder::SemiNCAInfo >::BatchUpdateInfo*) 18,207,270 ( 0.21%) ???:llvm::calculateDbgEntityHistory(llvm::MachineFunction const*, llvm::TargetRegisterInfo const*, llvm::DbgValueHistoryMap&, llvm::DbgLabelInstrMap&) 17,883,711 ( 0.21%) ???:(anonymous namespace)::PEI::runOnMachineFunction(llvm::MachineFunction&) 17,343,077 ( 0.20%) ???:llvm::SelectionDAG::AssignTopologicalOrder() 16,911,370 ( 0.19%) ???:(anonymous namespace)::VarLocBasedLDV::ExtendRanges(llvm::MachineFunction&, llvm::TargetPassConfig*) [clone .llvm.4451506318407214204] 16,842,367 ( 0.19%) ???:llvm::StringMapImpl::LookupBucketFor(llvm::StringRef) 16,725,856 ( 0.19%) ???:llvm::DataLayout::getAlignment(llvm::Type*, bool) const 16,418,835 ( 0.19%) ???:llvm::FunctionLoweringInfo::set(llvm::Function const&, llvm::MachineFunction&, llvm::SelectionDAG*) 16,284,157 ( 0.19%) ???:llvm::MCAsmLayout::getFragmentOffset(llvm::MCFragment const*) const 16,169,285 ( 0.19%) ./stdlib/msort.c:msort_with_tmp.part.0 15,873,850 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe.rs:::clone 15,873,292 ( 0.18%) ???:llvm::SelectionDAG::getRegister(unsigned int, llvm::EVT) 15,832,720 ( 0.18%) ???:(anonymous namespace)::X86MCInstLower::Lower(llvm::MachineInstr const*, llvm::MCInst&) const 15,288,713 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs: as core::ops::drop::Drop>::drop 15,212,281 ( 0.17%) ???:llvm::AttributeSetNode::get(llvm::LLVMContext&, llvm::AttrBuilder const&) 14,871,165 ( 0.17%) ???:llvm::MCContext::getOrCreateSymbol(llvm::Twine const&) 14,707,463 ( 0.17%) ???:(anonymous namespace)::X86MCCodeEmitter::encodeInstruction(llvm::MCInst const&, llvm::raw_ostream&, llvm::SmallVectorImpl&, llvm::MCSubtargetInfo const&) const 14,642,432 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs:core::ptr::drop_in_place:: 14,608,801 ( 0.17%) ???:llvm::InstrEmitter::EmitCopyFromReg(llvm::SDNode*, unsigned int, bool, bool, llvm::Register, llvm::DenseMap, llvm::detail::DenseMapPair >&) 14,333,053 ( 0.16%) ???:llvm::MCObjectStreamer::emitBytes(llvm::StringRef) 14,314,485 ( 0.16%) ???:llvm::SmallPtrSetImplBase::insert_imp_big(void const*) 14,230,793 ( 0.16%) ???:llvm::ScheduleDAGSDNodes::EmitSchedule(llvm::MachineInstrBundleIterator&) 13,881,705 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs: as core::ops::drop::Drop>::drop 13,306,998 ( 0.15%) ???:llvm::TargetRegisterInfo::checkAllSuperRegsMarked(llvm::BitVector const&, llvm::ArrayRef) const 13,275,313 ( 0.15%) ???:llvm::X86FrameLowering::hasFP(llvm::MachineFunction const&) const 13,235,626 ( 0.15%) ???:llvm::coro::declaresIntrinsics(llvm::Module const&, std::initializer_list) 13,167,235 ( 0.15%) ???:llvm::DwarfDebug::beginInstruction(llvm::MachineInstr const*) 13,152,511 ( 0.15%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs: as core::ops::drop::Drop>::drop 12,988,252 ( 0.15%) ???:llvm::SelectionDAG::getNode(unsigned int, llvm::SDLoc const&, llvm::SDVTList, llvm::ArrayRef) 12,978,313 ( 0.15%) ???:llvm::SelectionDAGISel::SelectAllBasicBlocks(llvm::Function const&) 12,933,528 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/mem/mod.rs:::bump_with 12,368,254 ( 0.14%) ./malloc/malloc.c:realloc 12,258,024 ( 0.14%) ???:(anonymous namespace)::Verifier::visitFunction(llvm::Function const&)::$_3::operator()(llvm::Instruction const&, llvm::MDNode const*) const 12,101,144 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::clone 12,042,436 ( 0.14%) ./string/../sysdeps/x86_64/multiarch/strcmp-avx2.S:__strncmp_avx2 11,645,830 ( 0.13%) ???:(anonymous namespace)::RegAllocFast::markRegUsedInInstr(unsigned short) 11,606,406 ( 0.13%) ???:llvm::FoldingSet::NodeEquals(llvm::FoldingSetBase const*, llvm::FoldingSetBase::Node*, llvm::FoldingSetNodeID const&, unsigned int, llvm::FoldingSetNodeID&) 11,602,842 ( 0.13%) ???:llvm::FoldingSetNodeID::AddInteger(unsigned int) 11,546,906 ( 0.13%) ???:llvm::MachineFunction::CreateMachineInstr(llvm::MCInstrDesc const&, llvm::DebugLoc const&, bool) 11,524,538 ( 0.13%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs: as core::ops::drop::Drop>::drop 11,302,863 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs:rustc_expand::mbe::macro_parser::parse_tt 11,229,015 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs: as core::iter::traits::collect::Extend>::extend::>> 11,196,418 ( 0.13%) ???:(anonymous namespace)::CFIInstrInserter::runOnMachineFunction(llvm::MachineFunction&) 11,159,070 ( 0.13%) ???:llvm::SelectionDAG::clear() 11,081,937 ( 0.13%) ???:llvm::X86RegisterInfo::eliminateFrameIndex(llvm::MachineInstrBundleIterator, int, unsigned int, llvm::RegScavenger*) const 11,017,774 ( 0.13%) ???:llvm::SelectionDAG::getNode(unsigned int, llvm::SDLoc const&, llvm::EVT, llvm::SDValue, llvm::SDValue, llvm::SDNodeFlags) 10,851,784 ( 0.12%) ???:llvm::DomTreeBuilder::SemiNCAInfo >::runSemiNCA(llvm::DominatorTreeBase&, unsigned int) 10,841,787 ( 0.12%) ???:llvm::SmallDenseMap, llvm::detail::DenseSetPair >::grow(unsigned int) 10,809,995 ( 0.12%) ./string/../sysdeps/x86_64/multiarch/memset-vec-unaligned-erms.S:__memset_avx2_unaligned_erms 10,607,041 ( 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 10,599,220 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/nonterminal.rs:::nonterminal_may_begin_with 10,307,302 ( 0.12%) ./elf/dl-lookup.c:_dl_lookup_symbol_x 10,242,427 ( 0.12%) ???:llvm::AsmPrinter::emitFunctionBody() 10,165,311 ( 0.12%) ???:multikeySort(llvm::MutableArrayRef*>, int) 10,164,388 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/alloc.rs:rustc_expand::mbe::macro_parser::parse_tt 10,139,635 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs:> as core::ops::drop::Drop>::drop 10,137,715 ( 0.12%) ???:llvm::MCELFStreamer::emitInstToData(llvm::MCInst const&, llvm::MCSubtargetInfo const&) 9,930,240 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/boxed.rs:>]> as core::clone::Clone>::clone 9,903,738 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe/macro_parser.rs:::clone 9,815,629 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:core::ptr::drop_in_place:: 9,576,808 ( 0.11%) ???:(anonymous namespace)::VarLocBasedLDV::collectIDsForRegs(llvm::SmallSet >&, llvm::SmallSet > const&, llvm::CoalescingBitVector const&, (anonymous namespace)::VarLocBasedLDV::VarLocMap const&) 9,352,539 ( 0.11%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, (), core::hash::BuildHasherDefault>>::from_hash::>::{closure#0}> 9,242,107 ( 0.11%) ???:llvm::MCObjectStreamer::emitInstruction(llvm::MCInst const&, llvm::MCSubtargetInfo const&) 9,110,958 ( 0.10%) ???:llvm::Twine::printOneChild(llvm::raw_ostream&, llvm::Twine::Child, llvm::Twine::NodeKind) const 9,071,873 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe/transcribe.rs:rustc_expand::mbe::transcribe::transcribe 9,055,739 ( 0.10%) /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) 9,015,331 ( 0.10%) ???:llvm::SelectionDAGISel::DoInstructionSelection() 8,745,836 ( 0.10%) ???:(anonymous namespace)::ELFObjectWriter::recordRelocation(llvm::MCAssembler&, llvm::MCAsmLayout const&, llvm::MCFragment const*, llvm::MCFixup const&, llvm::MCValue, unsigned long&) [clone .llvm.14145361893594770252] 8,723,297 ( 0.10%) ???:llvm::X86TargetMachine::getTargetTransformInfo(llvm::Function const&) 8,706,897 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs: as core::ops::drop::Drop>::drop -------------------------------------------------------------------------------- -- 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,659,195 ( 0.02%) 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)); 116,681 ( 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::()); 34,381,140 ( 0.40%) 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" . ); . 243,336 ( 0.00%) self.stride += Group::WIDTH; 243,336 ( 0.00%) self.pos += self.stride; 211,265 ( 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. 115,474 ( 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. 252,555 ( 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. 43,356 ( 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 { 321,583 ( 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. 55,900 ( 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, -- line 233 ---------------------------------------- -- line 246 ---------------------------------------- . . #[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 = 253,381 ( 0.00%) size.checked_mul(buckets)?.checked_add(ctrl_align - 1)? & !(ctrl_align - 1); 325,155 ( 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 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 { 740 ( 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 422 ---------------------------------------- . /// 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] . pub fn new_in(alloc: A) -> Self { 26,748 ( 0.00%) Self { . table: RawTableInner::new_in(alloc), . marker: PhantomData, . } . } . . /// Allocates a new hash table with the given number of buckets. . /// . /// The control bytes are left uninitialized. -- line 438 ---------------------------------------- -- line 440 ---------------------------------------- . unsafe fn new_uninitialized( . alloc: A, . buckets: usize, . fallibility: Fallibility, . ) -> Result { . debug_assert!(buckets.is_power_of_two()); . . Ok(Self { 95 ( 0.00%) table: RawTableInner::new_uninitialized( . alloc, . TableLayout::new::(), . buckets, . fallibility, . )?, . marker: PhantomData, . }) . } -- line 456 ---------------------------------------- -- line 458 ---------------------------------------- . /// Attempts to allocate a new hash table with at least enough capacity . /// for inserting the given number of elements without reallocating. . fn fallible_with_capacity( . alloc: A, . capacity: usize, . fallibility: Fallibility, . ) -> Result { . Ok(Self { 23,825 ( 0.00%) table: RawTableInner::fallible_with_capacity( . alloc, . TableLayout::new::(), . capacity, . fallibility, . )?, . marker: PhantomData, . }) . } -- line 474 ---------------------------------------- -- 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")] 16,127 ( 0.00%) pub unsafe fn erase_no_drop(&mut self, item: &Bucket) { 16,127 ( 0.00%) let index = self.bucket_index(item); . self.table.erase(index); 32,254 ( 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. 16,068 ( 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 { 16,186 ( 0.00%) self.erase_no_drop(&item); 175 ( 0.00%) item.read() . } . . /// Finds and removes an element from the table, returning it. . #[cfg_attr(feature = "inline-more", inline)] 565,903 ( 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,868 ( 0.00%) match self.find(hash, eq) { 15,055 ( 0.00%) Some(bucket) => Some(unsafe { self.remove(bucket) }), 127,339 ( 0.00%) None => None, . } 798,335 ( 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) { 14,322 ( 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 642 ---------------------------------------- . } . } . } . . /// Ensures that at least `additional` items can be inserted into the table . /// without reallocation. . #[cfg_attr(feature = "inline-more", inline)] . pub fn reserve(&mut self, additional: usize, hasher: impl Fn(&T) -> u64) { 305,509 ( 0.00%) if additional > self.table.growth_left { . // Avoid `Result::unwrap_or_else` because it bloats LLVM IR. 207,865 ( 0.00%) if self . .reserve_rehash(additional, hasher, Fallibility::Infallible) . .is_err() . { . unsafe { hint::unreachable_unchecked() } . } . } . } . -- line 660 ---------------------------------------- -- line 671 ---------------------------------------- . } else { . Ok(()) . } . } . . /// Out-of-line slow path for `reserve` and `try_reserve`. . #[cold] . #[inline(never)] 461,579 ( 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 . }, . ) . } 362,280 ( 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,044,392 ( 0.02%) 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,435 ( 0.00%) let old_ctrl = *self.table.ctrl(index); 1,565,212 ( 0.02%) 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,512,774 ( 0.02%) } . . /// 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)] 533,448 ( 0.01%) pub fn insert_entry(&mut self, hash: u64, value: T, hasher: impl Fn(&T) -> u64) -> &mut T { 94 ( 0.00%) unsafe { self.insert(hash, value, hasher).as_mut() } 400,086 ( 0.00%) } . . /// 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"))] 6,131 ( 0.00%) pub unsafe fn insert_no_grow(&mut self, hash: u64, value: T) -> Bucket { 320,168 ( 0.00%) let (index, old_ctrl) = self.table.prepare_insert_slot(hash); 12,233 ( 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. 675,594 ( 0.01%) self.table.growth_left -= special_is_empty(old_ctrl) as usize; . . bucket.write(value); 541,217 ( 0.01%) self.table.items += 1; . bucket 12,257 ( 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] 53,738 ( 0.00%) pub fn find(&self, hash: u64, mut eq: impl FnMut(&T) -> bool) -> Option> { 10,690 ( 0.00%) let result = self.table.find_inner(hash, &mut |index| unsafe { 37,271 ( 0.00%) eq(self.bucket(index).as_ref()) 6,124 ( 0.00%) }); . . // Avoid `Option::map` because it bloats LLVM IR. . match result { 1,710 ( 0.00%) Some(index) => Some(unsafe { self.bucket(index) }), . None => None, . } 61,360 ( 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. 190,522 ( 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] 6,853 ( 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. 29,401 ( 0.00%) match self.find(hash, eq) { . Some(bucket) => Some(unsafe { bucket.as_mut() }), . None => None, . } 7,832 ( 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 920 ---------------------------------------- . #[inline] . pub fn len(&self) -> usize { . self.table.items . } . . /// Returns `true` if the table contains no elements. . #[inline] . pub fn is_empty(&self) -> bool { 1,145,200 ( 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] . pub unsafe fn iter(&self) -> RawIter { 15 ( 0.00%) let data = Bucket::from_base_index(self.data_end(), 0); . RawIter { . iter: RawIterRange::new(self.table.ctrl.as_ptr(), data, self.table.buckets()), 101,839 ( 0.00%) items: self.table.items, . } . } . . /// 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. -- line 954 ---------------------------------------- -- line 995 ---------------------------------------- . /// 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. . pub unsafe fn into_iter_from(self, iter: RawIter) -> RawIntoIter { . debug_assert_eq!(iter.len(), self.len()); . . let alloc = self.table.alloc.clone(); 54,264 ( 0.00%) let allocation = self.into_allocation(); 40,698 ( 0.00%) RawIntoIter { 67,830 ( 0.00%) iter, . allocation, . marker: PhantomData, . alloc, . } . } . . /// 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)] . pub(crate) fn into_allocation(self) -> Option<(NonNull, Layout)> { 14,037 ( 0.00%) let alloc = if self.table.is_empty_singleton() { . 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(( 9,853 ( 0.00%) unsafe { NonNull::new_unchecked(self.table.ctrl.as_ptr().sub(ctrl_offset)) }, . layout, . )) . }; . mem::forget(self); . alloc . } . } . -- line 1033 ---------------------------------------- -- line 1042 ---------------------------------------- . T: Sync, . A: Sync, . { . } . . impl RawTableInner { . #[inline] . const fn new_in(alloc: A) -> Self { 598,025 ( 0.01%) Self { . // Be careful to cast the entire slice to a raw pointer. . ctrl: unsafe { NonNull::new_unchecked(Group::static_empty() as *const _ as *mut u8) }, . bucket_mask: 0, . items: 0, . growth_left: 0, . alloc, . } . } . } . . impl RawTableInner { . #[cfg_attr(feature = "inline-more", inline)] 342,392 ( 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()); . } . 106,332 ( 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)); 190,842 ( 0.00%) Ok(Self { . ctrl, 89,563 ( 0.00%) bucket_mask: buckets - 1, . items: 0, . growth_left: bucket_mask_to_capacity(buckets - 1), . alloc, . }) 249,466 ( 0.00%) } . . #[inline] 156,011 ( 0.00%) fn fallible_with_capacity( . alloc: A, . table_layout: TableLayout, . capacity: usize, . fallibility: Fallibility, . ) -> Result { 39,080 ( 0.00%) if capacity == 0 { 21,884 ( 0.00%) Ok(Self::new_in(alloc)) . } else { . unsafe { . let buckets = . capacity_to_buckets(capacity).ok_or_else(|| fallibility.capacity_overflow())?; . 156,121 ( 0.00%) let result = Self::new_uninitialized(alloc, table_layout, buckets, fallibility)?; . result.ctrl(0).write_bytes(EMPTY, result.num_ctrl_bytes()); . 90,856 ( 0.00%) Ok(result) . } . } 156,011 ( 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] 110,555 ( 0.00%) unsafe fn prepare_insert_slot(&self, hash: u64) -> (usize, u8) { . let index = self.find_insert_slot(hash); 110,555 ( 0.00%) let old_ctrl = *self.ctrl(index); . self.set_ctrl_h2(index, hash); . (index, old_ctrl) 221,110 ( 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,068,656 ( 0.01%) if let Some(bit) = group.match_empty_or_deleted().lowest_set_bit() { 3,130,706 ( 0.04%) 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,432,970 ( 0.02%) 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); . 109,108 ( 0.00%) loop { . let group = unsafe { Group::load(self.ctrl(probe_seq.pos)) }; . 4,076,899 ( 0.05%) for bit in group.match_byte(h2_hash) { 8,583,401 ( 0.10%) let index = (probe_seq.pos + bit) & self.bucket_mask; . 5,929,392 ( 0.07%) if likely(eq(index)) { . return Some(index); . } . } . 1,084,265 ( 0.01%) 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(); 3,988,280 ( 0.05%) 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 { 22,352,242 ( 0.26%) 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) { 1,959,297 ( 0.02%) self.growth_left -= special_is_empty(old_ctrl) as usize; . self.set_ctrl_h2(index, hash); 1,564,624 ( 0.02%) 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; 18 ( 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,021,458 ( 0.03%) let index2 = ((index.wrapping_sub(Group::WIDTH)) & self.bucket_mask) + Group::WIDTH; . 1,006,372 ( 0.01%) *self.ctrl(index) = ctrl; 1,006,505 ( 0.01%) *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] . fn buckets(&self) -> usize { 316,346 ( 0.00%) self.bucket_mask + 1 . } . . #[inline] . fn num_ctrl_bytes(&self) -> usize { 200,690 ( 0.00%) self.bucket_mask + 1 + Group::WIDTH . } . . #[inline] . fn is_empty_singleton(&self) -> bool { 1,135,612 ( 0.01%) self.bucket_mask == 0 . } . . #[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. 40,674 ( 0.00%) let mut new_table = RawTableInner::fallible_with_capacity( . self.alloc.clone(), . table_layout, . capacity, . fallibility, . )?; 130,578 ( 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_| { 56,152 ( 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. 112,306 ( 0.00%) let new_items = match self.items.checked_add(additional) { . Some(new_items) => new_items, . None => return Err(fallibility.capacity_overflow()), . }; 112,306 ( 0.00%) let full_capacity = bucket_mask_to_capacity(self.bucket_mask); 239,326 ( 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( 56,152 ( 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> { 104,943 ( 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() { 617,343 ( 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); . 56,152 ( 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. 6 ( 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( 35,853 ( 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) { 12,279 ( 0.00%) if !self.is_empty_singleton() { . unsafe { . self.ctrl(0).write_bytes(EMPTY, self.num_ctrl_bytes()); . } . } 17,768 ( 0.00%) self.items = 0; 12,376 ( 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))); 93,947 ( 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. 375,788 ( 0.00%) let ctrl = if empty_before.leading_zeros() + empty_after.trailing_zeros() >= Group::WIDTH { . DELETED . } else { 452,960 ( 0.01%) self.growth_left += 1; . EMPTY . }; . self.set_ctrl(index, ctrl); 375,788 ( 0.00%) self.items -= 1; . } . } . . impl Clone for RawTable { 71,352 ( 0.00%) fn clone(&self) -> Self { 8,935 ( 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) . } . } 80,271 ( 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; 38 ( 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)] 585,268 ( 0.01%) fn drop(&mut self) { 465,641 ( 0.01%) if !self.table.is_empty_singleton() { . unsafe { . self.drop_elements(); . self.free_buckets(); . } . } 617,000 ( 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)] 54,264 ( 0.00%) fn into_iter(self) -> RawIntoIter { . unsafe { . let iter = self.iter(); . self.into_iter_from(iter) . } 67,830 ( 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 1934 ---------------------------------------- . . impl Iterator for RawIterRange { . type Item = Bucket; . . #[cfg_attr(feature = "inline-more", inline)] . fn next(&mut self) -> Option> { . unsafe { . loop { 280,078 ( 0.00%) if let Some(index) = self.current_group.lowest_set_bit() { 47,416 ( 0.00%) self.current_group = self.current_group.remove_lowest_bit(); 86,474 ( 0.00%) return Some(self.data.next_n(index)); . } . 216,840 ( 0.00%) if self.next_ctrl >= self.end { . 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). 15,603 ( 0.00%) self.current_group = Group::load_aligned(self.next_ctrl).match_full(); 7,346 ( 0.00%) self.data = self.data.next_n(Group::WIDTH); 24,636 ( 0.00%) self.next_ctrl = self.next_ctrl.add(Group::WIDTH); . } . } . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { . // We don't have an item count, so just guess based on the range size. . ( -- line 1966 ---------------------------------------- -- line 2102 ---------------------------------------- . } . } else { . // We must have already iterated past the removed item. . } . } . } . . unsafe fn drop_elements(&mut self) { 38,657 ( 0.00%) if mem::needs_drop::() && self.len() != 0 { . for item in self { . item.drop(); . } . } . } . } . . impl Clone for RawIter { -- line 2118 ---------------------------------------- -- line 2124 ---------------------------------------- . } . } . } . . impl Iterator for RawIter { . type Item = Bucket; . . #[cfg_attr(feature = "inline-more", inline)] 44,858 ( 0.00%) fn next(&mut self) -> Option> { 141,280 ( 0.00%) if let Some(b) = self.iter.next() { 411,624 ( 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); . None . } 89,716 ( 0.00%) } . . #[inline] . fn size_hint(&self) -> (usize, Option) { . (self.items, Some(self.items)) . } . } . . impl ExactSizeIterator for RawIter {} -- line 2151 ---------------------------------------- -- 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)] 65,536 ( 0.00%) fn drop(&mut self) { . unsafe { . // Drop all remaining elements . self.iter.drop_elements(); . . // Free the table 63,249 ( 0.00%) if let Some((ptr, layout)) = self.allocation { . self.alloc.deallocate(ptr, layout); . } . } 19,528 ( 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,285 ( 0.00%) fn next(&mut self) -> Option { 3 ( 0.00%) unsafe { Some(self.iter.next()?.read()) } 3,642 ( 0.00%) } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 2 ( 0.00%) self.iter.size_hint() . } . } . . 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> { -- line 2231 ---------------------------------------- -- line 2259 ---------------------------------------- . where . T: Sync, . A: Sync, . { . } . . impl Drop for RawDrain<'_, T, A> { . #[cfg_attr(feature = "inline-more", inline)] 7,432 ( 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. 929 ( 0.00%) self.orig_table . .as_ptr() . .copy_from_nonoverlapping(&*self.table, 1); . } 7,432 ( 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 ---------------------------------------- 12,764,953 ( 0.15%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/mem/mod.rs -------------------------------------------------------------------------------- Ir -- line 326 ---------------------------------------- . /// ``` . #[inline] . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_size_of_val", issue = "46571")] . #[cfg_attr(not(test), rustc_diagnostic_item = "mem_size_of_val")] . pub const fn size_of_val(val: &T) -> usize { . // SAFETY: `val` is a reference, so it's a valid raw pointer 35,160 ( 0.00%) unsafe { intrinsics::size_of_val(val) } . } . . /// Returns the size of the pointed-to value in bytes. . /// . /// This is usually the same as `size_of::()`. However, when `T` *has* no . /// statically-known size, e.g., a slice [`[T]`][slice] or a [trait object], . /// then `size_of_val_raw` can be used to get the dynamically-known size. . /// -- line 342 ---------------------------------------- -- line 375 ---------------------------------------- . /// assert_eq!(13, unsafe { mem::size_of_val_raw(y) }); . /// ``` . #[inline] . #[must_use] . #[unstable(feature = "layout_for_ptr", issue = "69835")] . #[rustc_const_unstable(feature = "const_size_of_val_raw", issue = "46571")] . pub const unsafe fn size_of_val_raw(val: *const T) -> usize { . // SAFETY: the caller must provide a valid raw pointer 252 ( 0.00%) unsafe { intrinsics::size_of_val(val) } . } . . /// Returns the [ABI]-required minimum alignment of a type. . /// . /// Every reference to a value of the type `T` must be a multiple of this number. . /// . /// This is the alignment used for struct fields. It may be smaller than the preferred alignment. . /// -- line 391 ---------------------------------------- -- line 831 ---------------------------------------- . #[must_use = "if you don't need the old value, you can just assign the new value directly"] . #[rustc_const_unstable(feature = "const_replace", issue = "83164")] . #[cfg_attr(not(test), rustc_diagnostic_item = "mem_replace")] . pub const fn replace(dest: &mut T, src: T) -> T { . // SAFETY: We read from `dest` but directly write `src` into it afterwards, . // such that the old value is not duplicated. Nothing is dropped and . // nothing here can panic. . unsafe { 161,125 ( 0.00%) let result = ptr::read(dest); 15,698,991 ( 0.18%) ptr::write(dest, src); . result . } . } . . /// Disposes of a value. . /// . /// This does so by calling the argument's implementation of [`Drop`][drop]. . /// -- line 848 ---------------------------------------- -- line 901 ---------------------------------------- . /// . /// println!("x: {}, y: {}", x, y.0); // still available . /// ``` . /// . /// [`RefCell`]: crate::cell::RefCell . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[cfg_attr(not(test), rustc_diagnostic_item = "mem_drop")] 1,008 ( 0.00%) pub fn drop(_x: T) {} . . /// Interprets `src` as having type `&U`, and then reads `src` without moving . /// the contained value. . /// . /// This function will unsafely assume the pointer `src` is valid for [`size_of::`][size_of] . /// bytes by transmuting `&T` to `&U` and then reading the `&U` (except that this is done in a way . /// that is correct even when `&U` makes stricter alignment requirements than `&T`). It will also . /// unsafely create a copy of the contained value instead of moving out of `src`. -- line 917 ---------------------------------------- -- line 991 ---------------------------------------- . } . } . . #[stable(feature = "discriminant_value", since = "1.21.0")] . impl cmp::Eq for Discriminant {} . . #[stable(feature = "discriminant_value", since = "1.21.0")] . impl hash::Hash for Discriminant { 1,979 ( 0.00%) fn hash(&self, state: &mut H) { . self.0.hash(state); 3,454 ( 0.00%) } . } . . #[stable(feature = "discriminant_value", since = "1.21.0")] . impl fmt::Debug for Discriminant { . fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { . fmt.debug_tuple("Discriminant").field(&self.0).finish() . } . } -- line 1009 ---------------------------------------- -- line 1031 ---------------------------------------- . /// assert_eq!(mem::discriminant(&Foo::A("bar")), mem::discriminant(&Foo::A("baz"))); . /// assert_eq!(mem::discriminant(&Foo::B(1)), mem::discriminant(&Foo::B(2))); . /// assert_ne!(mem::discriminant(&Foo::B(3)), mem::discriminant(&Foo::C(3))); . /// ``` . #[stable(feature = "discriminant_value", since = "1.21.0")] . #[rustc_const_unstable(feature = "const_discriminant", issue = "69821")] . #[cfg_attr(not(test), rustc_diagnostic_item = "mem_discriminant")] . pub const fn discriminant(v: &T) -> Discriminant { 16,792 ( 0.00%) Discriminant(intrinsics::discriminant_value(v)) . } . . /// Returns the number of variants in the enum type `T`. . /// . /// If `T` is not an enum, calling this function will not result in undefined behavior, but the . /// return value is unspecified. Equally, if `T` is an enum with more variants than `usize::MAX` . /// the return value is unspecified. Uninhabited variants will be counted. . /// -- line 1047 ---------------------------------------- 4,666 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/alloc.rs -------------------------------------------------------------------------------- Ir -- line 79 ---------------------------------------- . /// . /// dealloc(ptr, layout); . /// } . /// ``` . #[stable(feature = "global_alloc", since = "1.28.0")] . #[must_use = "losing the pointer will leak memory"] . #[inline] . pub unsafe fn alloc(layout: Layout) -> *mut u8 { 10,979,643 ( 0.13%) unsafe { __rust_alloc(layout.size(), layout.align()) } . } . . /// Deallocate memory with the global allocator. . /// . /// This function forwards calls to the [`GlobalAlloc::dealloc`] method . /// of the allocator registered with the `#[global_allocator]` attribute . /// if there is one, or the `std` crate’s default. . /// -- line 95 ---------------------------------------- -- line 97 ---------------------------------------- . /// of the [`Global`] type when it and the [`Allocator`] trait become stable. . /// . /// # Safety . /// . /// See [`GlobalAlloc::dealloc`]. . #[stable(feature = "global_alloc", since = "1.28.0")] . #[inline] . pub unsafe fn dealloc(ptr: *mut u8, layout: Layout) { 11,336,920 ( 0.13%) unsafe { __rust_dealloc(ptr, layout.size(), layout.align()) } . } . . /// Reallocate memory with the global allocator. . /// . /// This function forwards calls to the [`GlobalAlloc::realloc`] method . /// of the allocator registered with the `#[global_allocator]` attribute . /// if there is one, or the `std` crate’s default. . /// -- line 113 ---------------------------------------- -- line 116 ---------------------------------------- . /// . /// # Safety . /// . /// See [`GlobalAlloc::realloc`]. . #[stable(feature = "global_alloc", since = "1.28.0")] . #[must_use = "losing the pointer will leak memory"] . #[inline] . pub unsafe fn realloc(ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { 457,409 ( 0.01%) unsafe { __rust_realloc(ptr, layout.size(), layout.align(), new_size) } . } . . /// Allocate zero-initialized memory with the global allocator. . /// . /// This function forwards calls to the [`GlobalAlloc::alloc_zeroed`] method . /// of the allocator registered with the `#[global_allocator]` attribute . /// if there is one, or the `std` crate’s default. . /// -- line 132 ---------------------------------------- -- line 150 ---------------------------------------- . /// . /// dealloc(ptr, layout); . /// } . /// ``` . #[stable(feature = "global_alloc", since = "1.28.0")] . #[must_use = "losing the pointer will leak memory"] . #[inline] . pub unsafe fn alloc_zeroed(layout: Layout) -> *mut u8 { 85,374 ( 0.00%) unsafe { __rust_alloc_zeroed(layout.size(), layout.align()) } . } . . #[cfg(not(test))] . impl Global { . #[inline] . fn alloc_impl(&self, layout: Layout, zeroed: bool) -> Result, AllocError> { 1,252,984 ( 0.01%) match layout.size() { . 0 => Ok(NonNull::slice_from_raw_parts(layout.dangling(), 0)), . // SAFETY: `layout` is non-zero in size, . size => unsafe { . let raw_ptr = if zeroed { alloc_zeroed(layout) } else { alloc(layout) }; 6,550,068 ( 0.08%) let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?; . Ok(NonNull::slice_from_raw_parts(ptr, size)) . }, . } . } . . // SAFETY: Same as `Allocator::grow` . #[inline] . unsafe fn grow_impl( -- line 178 ---------------------------------------- -- line 182 ---------------------------------------- . new_layout: Layout, . zeroed: bool, . ) -> Result, AllocError> { . debug_assert!( . new_layout.size() >= old_layout.size(), . "`new_layout.size()` must be greater than or equal to `old_layout.size()`" . ); . 186,858 ( 0.00%) match old_layout.size() { . 0 => self.alloc_impl(new_layout, zeroed), . . // SAFETY: `new_size` is non-zero as `old_size` is greater than or equal to `new_size` . // as required by safety conditions. Other conditions must be upheld by the caller . old_size if old_layout.align() == new_layout.align() => unsafe { . let new_size = new_layout.size(); . . // `realloc` probably checks for `new_size >= old_layout.size()` or something similar. -- line 198 ---------------------------------------- -- line 231 ---------------------------------------- . . #[inline] . fn allocate_zeroed(&self, layout: Layout) -> Result, AllocError> { . self.alloc_impl(layout, true) . } . . #[inline] . unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { 1,524,690 ( 0.02%) if layout.size() != 0 { . // SAFETY: `layout` is non-zero in size, . // other conditions must be upheld by the caller . unsafe { dealloc(ptr.as_ptr(), layout) } . } . } . . #[inline] . unsafe fn grow( -- line 247 ---------------------------------------- -- line 272 ---------------------------------------- . old_layout: Layout, . new_layout: Layout, . ) -> Result, AllocError> { . debug_assert!( . new_layout.size() <= old_layout.size(), . "`new_layout.size()` must be smaller than or equal to `old_layout.size()`" . ); . 4,944 ( 0.00%) match new_layout.size() { . // SAFETY: conditions must be upheld by the caller . 0 => unsafe { . self.deallocate(ptr, old_layout); . Ok(NonNull::slice_from_raw_parts(new_layout.dangling(), 0)) . }, . . // SAFETY: `new_size` is non-zero. Other conditions must be upheld by the caller . new_size if old_layout.align() == new_layout.align() => unsafe { . // `realloc` probably checks for `new_size <= old_layout.size()` or something similar. . intrinsics::assume(new_size <= old_layout.size()); . . let raw_ptr = realloc(ptr.as_ptr(), old_layout, new_size); 4,944 ( 0.00%) let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?; . Ok(NonNull::slice_from_raw_parts(ptr, new_size)) . }, . . // SAFETY: because `new_size` must be smaller than or equal to `old_layout.size()`, . // both the old and new memory allocation are valid for reads and writes for `new_size` . // bytes. Also, because the old allocation wasn't yet deallocated, it cannot overlap . // `new_ptr`. Thus, the call to `copy_nonoverlapping` is safe. The safety contract . // for `dealloc` must be upheld by the caller. -- line 301 ---------------------------------------- -- line 308 ---------------------------------------- . } . } . } . . /// The allocator for unique pointers. . #[cfg(all(not(no_global_oom_handling), not(test)))] . #[lang = "exchange_malloc"] . #[inline] 4,793 ( 0.00%) unsafe fn exchange_malloc(size: usize, align: usize) -> *mut u8 { . let layout = unsafe { Layout::from_size_align_unchecked(size, align) }; 19,010 ( 0.00%) match Global.allocate(layout) { . Ok(ptr) => ptr.as_mut_ptr(), . Err(_) => handle_alloc_error(layout), . } 6,514 ( 0.00%) } . . #[cfg_attr(not(test), lang = "box_free")] . #[inline] . #[rustc_const_unstable(feature = "const_box", issue = "92521")] . // This signature has to be the same as `Box`, otherwise an ICE will happen. . // When an additional parameter to `Box` is added (like `A: Allocator`), this has to be added here as . // well. . // For example if `Box` is changed to `struct Box(Unique, A)`, . // this function has to be changed to `fn box_free(Unique, A)` as well. . pub(crate) const unsafe fn box_free( . ptr: Unique, . alloc: A, . ) { . unsafe { 20,291 ( 0.00%) let size = size_of_val(ptr.as_ref()); 8,758 ( 0.00%) let align = min_align_of_val(ptr.as_ref()); . let layout = Layout::from_size_align_unchecked(size, align); . alloc.deallocate(From::from(ptr.cast()), layout) . } . } . . // # Allocation error handler . . #[cfg(not(no_global_oom_handling))] -- line 346 ---------------------------------------- -- line 417 ---------------------------------------- . /// Specialize clones into pre-allocated, uninitialized memory. . /// Used by `Box::clone` and `Rc`/`Arc::make_mut`. . pub(crate) trait WriteCloneIntoRaw: Sized { . unsafe fn write_clone_into_raw(&self, target: *mut Self); . } . . impl WriteCloneIntoRaw for T { . #[inline] 1,332 ( 0.00%) default unsafe fn write_clone_into_raw(&self, target: *mut Self) { . // Having allocated *first* may allow the optimizer to create . // the cloned value in-place, skipping the local and move. 17,671 ( 0.00%) unsafe { target.write(self.clone()) }; 1,184 ( 0.00%) } . } . . impl WriteCloneIntoRaw for T { . #[inline] . unsafe fn write_clone_into_raw(&self, target: *mut Self) { . // We can always copy in-place, without ever involving a local value. . unsafe { target.copy_from_nonoverlapping(self, 1) }; . } -- line 437 ---------------------------------------- 7,321,835 ( 0.08%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/boxed.rs -------------------------------------------------------------------------------- Ir -- line 187 ---------------------------------------- . /// ``` . /// let five = Box::new(5); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[inline(always)] . #[stable(feature = "rust1", since = "1.0.0")] . #[must_use] . pub fn new(x: T) -> Self { 975,947 ( 0.01%) box x . } . . /// Constructs a new box with uninitialized contents. . /// . /// # Examples . /// . /// ``` . /// #![feature(new_uninit)] -- line 203 ---------------------------------------- -- line 410 ---------------------------------------- . /// . /// assert_eq!(*five, 5) . /// ``` . #[unstable(feature = "allocator_api", issue = "32838")] . #[rustc_const_unstable(feature = "const_box", issue = "92521")] . #[cfg(not(no_global_oom_handling))] . #[must_use] . // #[unstable(feature = "new_uninit", issue = "63291")] 4,228 ( 0.00%) pub const fn new_uninit_in(alloc: A) -> Box, A> . where . A: ~const Allocator + ~const Drop, . { . let layout = Layout::new::>(); . // NOTE: Prefer match over unwrap_or_else since closure sometimes not inlineable. . // That would make code size bigger. 52 ( 0.00%) match Box::try_new_uninit_in(alloc) { . Ok(m) => m, . Err(_) => handle_alloc_error(layout), . } 8,456 ( 0.00%) } . . /// Constructs a new box with uninitialized contents in the provided allocator, . /// returning an error if the allocation fails . /// . /// # Examples . /// . /// ``` . /// #![feature(allocator_api, new_uninit)] -- line 437 ---------------------------------------- -- line 600 ---------------------------------------- . /// }; . /// . /// assert_eq!(*values, [1, 2, 3]) . /// ``` . #[cfg(not(no_global_oom_handling))] . #[unstable(feature = "new_uninit", issue = "63291")] . #[must_use] . pub fn new_uninit_slice(len: usize) -> Box<[mem::MaybeUninit]> { 90 ( 0.00%) unsafe { RawVec::with_capacity(len).into_box(len) } . } . . /// Constructs a new boxed slice with uninitialized contents, with the memory . /// being filled with `0` bytes. . /// . /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage . /// of this method. . /// -- line 616 ---------------------------------------- -- line 688 ---------------------------------------- . #[unstable(feature = "allocator_api", issue = "32838")] . #[inline] . pub fn try_new_zeroed_slice(len: usize) -> Result]>, AllocError> { . unsafe { . let layout = match Layout::array::>(len) { . Ok(l) => l, . Err(_) => return Err(AllocError), . }; 820 ( 0.00%) let ptr = Global.allocate_zeroed(layout)?; . Ok(RawVec::from_raw_parts_in(ptr.as_mut_ptr() as *mut _, len, Global).into_box(len)) . } . } . } . . impl Box<[T], A> { . /// Constructs a new boxed slice with uninitialized contents in the provided allocator. . /// -- line 704 ---------------------------------------- -- line 1215 ---------------------------------------- . /// . /// // The value is the same . /// assert_eq!(x, y); . /// . /// // But they are unique objects . /// assert_ne!(&*x as *const i32, &*y as *const i32); . /// ``` . #[inline] 3,480 ( 0.00%) fn clone(&self) -> Self { . // Pre-allocate memory to allow writing the cloned value directly. 4,228 ( 0.00%) let mut boxed = Self::new_uninit_in(self.1.clone()); . unsafe { 18,113 ( 0.00%) (**self).write_clone_into_raw(boxed.as_mut_ptr()); . boxed.assume_init() . } 3,915 ( 0.00%) } . . /// Copies `source`'s contents into `self` without creating a new allocation. . /// . /// # Examples . /// . /// ``` . /// let x = Box::new(5); . /// let mut y = Box::new(10); -- line 1238 ---------------------------------------- -- line 1303 ---------------------------------------- . Ord::cmp(&**self, &**other) . } . } . #[stable(feature = "rust1", since = "1.0.0")] . impl Eq for Box {} . . #[stable(feature = "rust1", since = "1.0.0")] . impl Hash for Box { 3,366 ( 0.00%) fn hash(&self, state: &mut H) { 7,220 ( 0.00%) (**self).hash(state); 3,366 ( 0.00%) } . } . . #[stable(feature = "indirect_hasher_impl", since = "1.22.0")] . impl Hasher for Box { . fn finish(&self) -> u64 { . (**self).finish() . } . fn write(&mut self, bytes: &[u8]) { -- line 1321 ---------------------------------------- -- line 1574 ---------------------------------------- . /// . /// let my_string = "Hello World".to_string(); . /// print_if_string(Box::new(my_string)); . /// print_if_string(Box::new(0i8)); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn downcast(self) -> Result, Self> { 1 ( 0.00%) if self.is::() { unsafe { Ok(self.downcast_unchecked::()) } } else { Err(self) } . } . . /// Downcasts the box to a concrete type. . /// . /// For a safe alternative see [`downcast`]. . /// . /// # Examples . /// -- line 1590 ---------------------------------------- -- line 1633 ---------------------------------------- . /// . /// let my_string = "Hello World".to_string(); . /// print_if_string(Box::new(my_string)); . /// print_if_string(Box::new(0i8)); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn downcast(self) -> Result, Self> { 52 ( 0.00%) if self.is::() { unsafe { Ok(self.downcast_unchecked::()) } } else { Err(self) } . } . . /// Downcasts the box to a concrete type. . /// . /// For a safe alternative see [`downcast`]. . /// . /// # Examples . /// -- line 1649 ---------------------------------------- -- line 1769 ---------------------------------------- . &**self . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_box", issue = "92521")] . impl const DerefMut for Box { . fn deref_mut(&mut self) -> &mut T { 1 ( 0.00%) &mut **self . } . } . . #[unstable(feature = "receiver_trait", issue = "none")] . impl Receiver for Box {} . . #[stable(feature = "rust1", since = "1.0.0")] . impl Iterator for Box { . type Item = I::Item; . fn next(&mut self) -> Option { 595 ( 0.00%) (**self).next() . } . fn size_hint(&self) -> (usize, Option) { . (**self).size_hint() . } . fn nth(&mut self, n: usize) -> Option { . (**self).nth(n) . } . fn last(self) -> Option { -- line 1796 ---------------------------------------- -- line 1846 ---------------------------------------- . #[stable(feature = "fused", since = "1.26.0")] . impl FusedIterator for Box {} . . #[stable(feature = "boxed_closure_impls", since = "1.35.0")] . impl + ?Sized, A: Allocator> FnOnce for Box { . type Output = >::Output; . . extern "rust-call" fn call_once(self, args: Args) -> Self::Output { 80 ( 0.00%) >::call_once(*self, args) . } . } . . #[stable(feature = "boxed_closure_impls", since = "1.35.0")] . impl + ?Sized, A: Allocator> FnMut for Box { . extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output { 157 ( 0.00%) >::call_mut(self, args) . } . } . . #[stable(feature = "boxed_closure_impls", since = "1.35.0")] . impl + ?Sized, A: Allocator> Fn for Box { . extern "rust-call" fn call(&self, args: Args) -> Self::Output { 77,208 ( 0.00%) >::call(self, args) . } . } . . #[unstable(feature = "coerce_unsized", issue = "27732")] . impl, U: ?Sized, A: Allocator> CoerceUnsized> for Box {} . . #[unstable(feature = "dispatch_from_dyn", issue = "none")] . impl, U: ?Sized> DispatchFromDyn> for Box {} . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "boxed_slice_from_iter", since = "1.32.0")] . impl FromIterator for Box<[I]> { 1,739 ( 0.00%) fn from_iter>(iter: T) -> Self { . iter.into_iter().collect::>().into_boxed_slice() 2,099 ( 0.00%) } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "box_slice_clone", since = "1.3.0")] . impl Clone for Box<[T], A> { 2,648,064 ( 0.03%) fn clone(&self) -> Self { . let alloc = Box::allocator(self).clone(); 1,324,041 ( 0.02%) self.to_vec_in(alloc).into_boxed_slice() 3,972,096 ( 0.05%) } . . fn clone_from(&mut self, other: &Self) { . if self.len() == other.len() { . self.clone_from_slice(&other); . } else { . *self = other.clone(); . } . } . } . . #[stable(feature = "box_borrow", since = "1.1.0")] . impl borrow::Borrow for Box { . fn borrow(&self) -> &T { 791 ( 0.00%) &**self . } . } . . #[stable(feature = "box_borrow", since = "1.1.0")] . impl borrow::BorrowMut for Box { . fn borrow_mut(&mut self) -> &mut T { 785 ( 0.00%) &mut **self . } . } . . #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")] . impl AsRef for Box { . fn as_ref(&self) -> &T { 2,684 ( 0.00%) &**self . } . } . . #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")] . impl AsMut for Box { . fn as_mut(&mut self) -> &mut T { . &mut **self . } -- line 1928 ---------------------------------------- 5,394,703 ( 0.06%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs -------------------------------------------------------------------------------- Ir -- line 417 ---------------------------------------- . /// # #![allow(unused_mut)] . /// let mut vec: Vec = Vec::new(); . /// ``` . #[inline] . #[rustc_const_stable(feature = "const_vec_new", since = "1.39.0")] . #[stable(feature = "rust1", since = "1.0.0")] . #[must_use] . pub const fn new() -> Self { 2,946,023 ( 0.03%) Vec { buf: RawVec::NEW, len: 0 } 1,537 ( 0.00%) } . . /// Constructs a new, empty `Vec` with the specified capacity. . /// . /// The vector will be able to hold exactly `capacity` elements without . /// reallocating. If `capacity` is 0, the vector will not allocate. . /// . /// It is important to note that although the returned vector has the . /// *capacity* specified, the vector will have a zero *length*. For an -- line 434 ---------------------------------------- -- line 601 ---------------------------------------- . /// vec.push(11); . /// assert_eq!(vec.len(), 11); . /// assert!(vec.capacity() >= 11); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[inline] . #[unstable(feature = "allocator_api", issue = "32838")] . pub fn with_capacity_in(capacity: usize, alloc: A) -> Self { 2,628,600 ( 0.03%) Vec { buf: RawVec::with_capacity_in(capacity, alloc), len: 0 } . } . . /// Creates a `Vec` directly from the raw components of another vector. . /// . /// # Safety . /// . /// This is highly unsafe, due to the number of invariants that aren't . /// checked: -- line 617 ---------------------------------------- -- line 677 ---------------------------------------- . /// // Put everything back together into a Vec . /// let rebuilt = Vec::from_raw_parts_in(p, len, cap, alloc.clone()); . /// assert_eq!(rebuilt, [4, 5, 6]); . /// } . /// ``` . #[inline] . #[unstable(feature = "allocator_api", issue = "32838")] . pub unsafe fn from_raw_parts_in(ptr: *mut T, length: usize, capacity: usize, alloc: A) -> Self { 86,619 ( 0.00%) unsafe { Vec { buf: RawVec::from_raw_parts_in(ptr, capacity, alloc), len: length } } . } . . /// Decomposes a `Vec` into its raw components. . /// . /// Returns the raw pointer to the underlying data, the length of . /// the vector (in elements), and the allocated capacity of the . /// data (in elements). These are the same arguments in the same . /// order as the arguments to [`from_raw_parts`]. -- line 693 ---------------------------------------- -- line 778 ---------------------------------------- . /// . /// ``` . /// let vec: Vec = Vec::with_capacity(10); . /// assert_eq!(vec.capacity(), 10); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn capacity(&self) -> usize { 679,961 ( 0.01%) self.buf.capacity() . } . . /// Reserves capacity for at least `additional` more elements to be inserted . /// in the given `Vec`. The collection may reserve more space to avoid . /// frequent reallocations. After calling `reserve`, capacity will be . /// greater than or equal to `self.len() + additional`. Does nothing if . /// capacity is already sufficient. . /// -- line 794 ---------------------------------------- -- line 801 ---------------------------------------- . /// ``` . /// let mut vec = vec![1]; . /// vec.reserve(10); . /// assert!(vec.capacity() >= 11); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn reserve(&mut self, additional: usize) { 533,171 ( 0.01%) self.buf.reserve(self.len, additional); . } . . /// Reserves the minimum capacity for exactly `additional` more elements to . /// be inserted in the given `Vec`. After calling `reserve_exact`, . /// capacity will be greater than or equal to `self.len() + additional`. . /// Does nothing if the capacity is already sufficient. . /// . /// Note that the allocator may give the collection more space than it -- line 817 ---------------------------------------- -- line 829 ---------------------------------------- . /// ``` . /// let mut vec = vec![1]; . /// vec.reserve_exact(10); . /// assert!(vec.capacity() >= 11); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn reserve_exact(&mut self, additional: usize) { 5,993 ( 0.00%) self.buf.reserve_exact(self.len, additional); . } . . /// Tries to reserve capacity for at least `additional` more elements to be inserted . /// in the given `Vec`. The collection may reserve more space to avoid . /// frequent reallocations. After calling `try_reserve`, capacity will be . /// greater than or equal to `self.len() + additional`. Does nothing if . /// capacity is already sufficient. . /// -- line 845 ---------------------------------------- -- line 930 ---------------------------------------- . /// assert!(vec.capacity() >= 3); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn shrink_to_fit(&mut self) { . // The capacity is never less than the length, and there's nothing to do when . // they are equal, so we can avoid the panic case in `RawVec::shrink_to_fit` . // by only calling it with a greater capacity. 1,422,253 ( 0.02%) if self.capacity() > self.len { 7,959 ( 0.00%) self.buf.shrink_to_fit(self.len); . } . } . . /// Shrinks the capacity of the vector with a lower bound. . /// . /// The capacity will remain at least as large as both the length . /// and the supplied value. . /// -- line 947 ---------------------------------------- -- line 990 ---------------------------------------- . /// let slice = vec.into_boxed_slice(); . /// assert_eq!(slice.into_vec().capacity(), 3); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn into_boxed_slice(mut self) -> Box<[T], A> { . unsafe { . self.shrink_to_fit(); 688,386 ( 0.01%) let me = ManuallyDrop::new(self); . let buf = ptr::read(&me.buf); . let len = me.len(); . buf.into_box(len).assume_init() . } . } . . /// Shortens the vector, keeping the first `len` elements and dropping . /// the rest. -- line 1006 ---------------------------------------- -- line 1040 ---------------------------------------- . /// let mut vec = vec![1, 2, 3]; . /// vec.truncate(0); . /// assert_eq!(vec, []); . /// ``` . /// . /// [`clear`]: Vec::clear . /// [`drain`]: Vec::drain . #[stable(feature = "rust1", since = "1.0.0")] 16,169,824 ( 0.19%) pub fn truncate(&mut self, len: usize) { . // This is safe because: . // . // * the slice passed to `drop_in_place` is valid; the `len > self.len` . // case avoids creating an invalid slice, and . // * the `len` of the vector is shrunk before calling `drop_in_place`, . // such that no value will be dropped twice in case `drop_in_place` . // were to panic once (if it panics twice, the program aborts). . unsafe { . // Note: It's intentional that this is `>` and not `>=`. . // Changing it to `>=` has negative performance . // implications in some cases. See #78884 for more. 9,740,285 ( 0.11%) if len > self.len { . return; . } . let remaining_len = self.len - len; . let s = ptr::slice_from_raw_parts_mut(self.as_mut_ptr().add(len), remaining_len); 3,454,741 ( 0.04%) self.len = len; 4,606 ( 0.00%) ptr::drop_in_place(s); . } 19,403,768 ( 0.22%) } . . /// Extracts a slice containing the entire vector. . /// . /// Equivalent to `&s[..]`. . /// . /// # Examples . /// . /// ``` -- line 1076 ---------------------------------------- -- line 1126 ---------------------------------------- . /// ``` . /// . /// [`as_mut_ptr`]: Vec::as_mut_ptr . #[stable(feature = "vec_as_ptr", since = "1.37.0")] . #[inline] . pub fn as_ptr(&self) -> *const T { . // We shadow the slice method of the same name to avoid going through . // `deref`, which creates an intermediate reference. 9,243,908 ( 0.11%) let ptr = self.buf.ptr(); . unsafe { . assume(!ptr.is_null()); . } . ptr . } . . /// Returns an unsafe mutable pointer to the vector's buffer. . /// -- line 1142 ---------------------------------------- -- line 1162 ---------------------------------------- . /// } . /// assert_eq!(&*x, &[0, 1, 2, 3]); . /// ``` . #[stable(feature = "vec_as_ptr", since = "1.37.0")] . #[inline] . pub fn as_mut_ptr(&mut self) -> *mut T { . // We shadow the slice method of the same name to avoid going through . // `deref_mut`, which creates an intermediate reference. 7,789,265 ( 0.09%) let ptr = self.buf.ptr(); . unsafe { . assume(!ptr.is_null()); . } . ptr . } . . /// Returns a reference to the underlying allocator. . #[unstable(feature = "allocator_api", issue = "32838")] -- line 1178 ---------------------------------------- -- line 1259 ---------------------------------------- . /// . /// Normally, here, one would use [`clear`] instead to correctly drop . /// the contents and thus not leak memory. . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub unsafe fn set_len(&mut self, new_len: usize) { . debug_assert!(new_len <= self.capacity()); . 1,263,237 ( 0.01%) self.len = new_len; 34,162 ( 0.00%) } . . /// Removes an element from the vector and returns it. . /// . /// The removed element is replaced by the last element of the vector. . /// . /// This does not preserve ordering, but is *O*(1). . /// If you need to preserve the element order, use [`remove`] instead. . /// -- line 1276 ---------------------------------------- -- line 1305 ---------------------------------------- . assert_failed(index, len); . } . unsafe { . // We replace self[index] with the last element. Note that if the . // bounds check above succeeds there must be a last element (which . // can be self[index] itself). . let value = ptr::read(self.as_ptr().add(index)); . let base_ptr = self.as_mut_ptr(); 17 ( 0.00%) ptr::copy(base_ptr.add(len - 1), base_ptr.add(index), 1); . self.set_len(len - 1); . value . } . } . . /// Inserts an element at position `index` within the vector, shifting all . /// elements after it to the right. . /// -- line 1321 ---------------------------------------- -- line 1329 ---------------------------------------- . /// let mut vec = vec![1, 2, 3]; . /// vec.insert(1, 4); . /// assert_eq!(vec, [1, 4, 2, 3]); . /// vec.insert(4, 5); . /// assert_eq!(vec, [1, 4, 2, 3, 5]); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] 4,942 ( 0.00%) pub fn insert(&mut self, index: usize, element: T) { . #[cold] . #[inline(never)] . fn assert_failed(index: usize, len: usize) -> ! { . panic!("insertion index (is {}) should be <= len (is {})", index, len); . } . 707 ( 0.00%) let len = self.len(); 1,684 ( 0.00%) if index > len { . assert_failed(index, len); . } . . // space for the new element 2,594 ( 0.00%) if len == self.buf.capacity() { . self.reserve(1); . } . . unsafe { . // infallible . // The spot to put the new value . { . let p = self.as_mut_ptr().add(index); . // Shift everything over to make space. (Duplicating the . // `index`th element into two consecutive places.) 3,888 ( 0.00%) ptr::copy(p, p.offset(1), len - index); . // Write it in, overwriting the first copy of the `index`th . // element. . ptr::write(p, element); . } 2,594 ( 0.00%) self.set_len(len + 1); . } 4,236 ( 0.00%) } . . /// Removes and returns the element at position `index` within the vector, . /// shifting all elements after it to the left. . /// . /// Note: Because this shifts over the remaining elements, it has a . /// worst-case performance of *O*(*n*). If you don't need the order of elements . /// to be preserved, use [`swap_remove`] instead. If you'd like to remove . /// elements from the beginning of the `Vec`, consider using -- line 1376 ---------------------------------------- -- line 1395 ---------------------------------------- . pub fn remove(&mut self, index: usize) -> T { . #[cold] . #[inline(never)] . #[track_caller] . fn assert_failed(index: usize, len: usize) -> ! { . panic!("removal index (is {}) should be < len (is {})", index, len); . } . 422 ( 0.00%) let len = self.len(); 1,685 ( 0.00%) if index >= len { . assert_failed(index, len); . } . unsafe { . // infallible . let ret; . { . // the place we are taking from. . let ptr = self.as_mut_ptr().add(index); . // copy it out, unsafely having a copy of the value on . // the stack and in the vector at the same time. 48 ( 0.00%) ret = ptr::read(ptr); . . // Shift everything down to fill in that spot. 1,040 ( 0.00%) ptr::copy(ptr.offset(1), ptr, len - index - 1); . } 567 ( 0.00%) self.set_len(len - 1); . ret . } . } . . /// 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, visiting each element exactly once in the -- line 1428 ---------------------------------------- -- line 1442 ---------------------------------------- . /// ``` . /// let mut vec = vec![1, 2, 3, 4, 5]; . /// let keep = [false, true, true, false, true]; . /// let mut iter = keep.iter(); . /// vec.retain(|_| *iter.next().unwrap()); . /// assert_eq!(vec, [2, 3, 5]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 712,377 ( 0.01%) pub fn retain(&mut self, mut f: F) . where . F: FnMut(&T) -> bool, . { 51,203 ( 0.00%) self.retain_mut(|elem| f(elem)); 686,288 ( 0.01%) } . . /// Retains only the elements specified by the predicate, passing a mutable reference to it. . /// . /// In other words, remove all elements `e` such that `f(&mut e)` returns `false`. . /// This method operates in place, visiting each element exactly once in the . /// original order, and preserves the order of the retained elements. . /// . /// # Examples -- line 1463 ---------------------------------------- -- line 1474 ---------------------------------------- . /// }); . /// assert_eq!(vec, [2, 3, 4]); . /// ``` . #[unstable(feature = "vec_retain_mut", issue = "90829")] . pub fn retain_mut(&mut self, mut f: F) . where . F: FnMut(&mut T) -> bool, . { 86,034 ( 0.00%) let original_len = self.len(); . // Avoid double drop if the drop guard is not executed, . // since we may make some holes during the process. . unsafe { self.set_len(0) }; . . // Vec: [Kept, Kept, Hole, Hole, Hole, Hole, Unchecked, Unchecked] . // |<- processed len ->| ^- next to check . // |<- deleted cnt ->| . // |<- original_len ->| -- line 1490 ---------------------------------------- -- line 1499 ---------------------------------------- . v: &'a mut Vec, . processed_len: usize, . deleted_cnt: usize, . original_len: usize, . } . . impl Drop for BackshiftOnDrop<'_, T, A> { . fn drop(&mut self) { 102,907 ( 0.00%) if self.deleted_cnt > 0 { . // SAFETY: Trailing unchecked items must be valid since we never touch them. . unsafe { . ptr::copy( . self.v.as_ptr().add(self.processed_len), 93,829 ( 0.00%) self.v.as_mut_ptr().add(self.processed_len - self.deleted_cnt), . self.original_len - self.processed_len, . ); . } . } . // SAFETY: After filling holes, all items are in contiguous memory. . unsafe { 2 ( 0.00%) self.v.set_len(self.original_len - self.deleted_cnt); . } . } . } . . let mut g = BackshiftOnDrop { v: self, processed_len: 0, deleted_cnt: 0, original_len }; . . fn process_loop( . original_len: usize, . f: &mut F, . g: &mut BackshiftOnDrop<'_, T, A>, . ) where . F: FnMut(&mut T) -> bool, . { 712,429 ( 0.01%) while g.processed_len != original_len { . // SAFETY: Unchecked element must be valid. . let cur = unsafe { &mut *g.v.as_mut_ptr().add(g.processed_len) }; 165,920 ( 0.00%) if !f(cur) { . // Advance early to avoid double drop if `drop_in_place` panicked. 35,232 ( 0.00%) g.processed_len += 1; 17,828 ( 0.00%) g.deleted_cnt += 1; . // SAFETY: We never touch this element again after dropped. 216 ( 0.00%) unsafe { ptr::drop_in_place(cur) }; . // We already advanced the counter. . if DELETED { . continue; . } else { . break; . } . } . if DELETED { . // SAFETY: `deleted_cnt` > 0, so the hole slot must not overlap with current element. . // We use copy for move, and never touch this element again. . unsafe { 14,118 ( 0.00%) let hole_slot = g.v.as_mut_ptr().add(g.processed_len - g.deleted_cnt); . ptr::copy_nonoverlapping(cur, hole_slot, 1); . } . } 13,321 ( 0.00%) g.processed_len += 1; . } . } . . // Stage 1: Nothing was deleted. . process_loop::(original_len, &mut f, &mut g); . . // Stage 2: Some elements were deleted. . process_loop::(original_len, &mut f, &mut g); -- line 1565 ---------------------------------------- -- line 1606 ---------------------------------------- . /// ``` . /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"]; . /// . /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b)); . /// . /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]); . /// ``` . #[stable(feature = "dedup_by", since = "1.16.0")] 252 ( 0.00%) pub fn dedup_by(&mut self, mut same_bucket: F) . where . F: FnMut(&mut T, &mut T) -> bool, . { 3,430 ( 0.00%) let len = self.len(); 7,568 ( 0.00%) if len <= 1 { . return; . } . . /* INVARIANT: vec.len() > read >= write > write-1 >= 0 */ . struct FillGapOnDrop<'a, T, A: core::alloc::Allocator> { . /* Offset of the element we want to check if it is duplicate */ . read: usize, . -- line 1627 ---------------------------------------- -- line 1670 ---------------------------------------- . let ptr = gap.vec.as_mut_ptr(); . . /* Drop items while going through Vec, it should be more efficient than . * doing slice partition_dedup + truncate */ . . /* SAFETY: Because of the invariant, read_ptr, prev_ptr and write_ptr . * are always in-bounds and read_ptr never aliases prev_ptr */ . unsafe { 19,089 ( 0.00%) while gap.read < len { . let read_ptr = ptr.add(gap.read); . let prev_ptr = ptr.add(gap.write.wrapping_sub(1)); . 562 ( 0.00%) if same_bucket(&mut *read_ptr, &mut *prev_ptr) { . // Increase `gap.read` now since the drop may panic. . gap.read += 1; . /* We have found duplicate, drop it in-place */ . ptr::drop_in_place(read_ptr); . } else { . let write_ptr = ptr.add(gap.write); . . /* Because `read_ptr` can be equal to `write_ptr`, we either . * have to use `copy` or conditional `copy_nonoverlapping`. . * Looks like the first option is faster. */ . ptr::copy(read_ptr, write_ptr, 1); . . /* We have filled that place, so go further */ 11,237 ( 0.00%) gap.write += 1; . gap.read += 1; . } . } . . /* Technically we could let `gap` clean up with its Drop, but . * when `same_bucket` is guaranteed to not panic, this bloats a little . * the codegen, so we just do it manually */ . gap.vec.set_len(gap.write); . mem::forget(gap); . } 288 ( 0.00%) } . . /// Appends an element to the back of a collection. . /// . /// # Panics . /// . /// Panics if the new capacity exceeds `isize::MAX` bytes. . /// . /// # Examples -- line 1715 ---------------------------------------- -- line 1717 ---------------------------------------- . /// ``` . /// let mut vec = vec![1, 2]; . /// vec.push(3); . /// assert_eq!(vec, [1, 2, 3]); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 195 ( 0.00%) pub fn push(&mut self, value: T) { . // This will panic or abort if we would allocate > isize::MAX bytes . // or if the length increment would overflow for zero-sized types. 5,943,475 ( 0.07%) if self.len == self.buf.capacity() { 357,474 ( 0.00%) self.buf.reserve_for_push(self.len); . } . unsafe { 170,369 ( 0.00%) let end = self.as_mut_ptr().add(self.len); . ptr::write(end, value); 8,277,801 ( 0.10%) self.len += 1; . } 156 ( 0.00%) } . . /// Removes the last element from a vector and returns it, or [`None`] if it . /// is empty. . /// . /// If you'd like to pop the first element, consider using . /// [`VecDeque::pop_front`] instead. . /// . /// [`VecDeque::pop_front`]: crate::collections::VecDeque::pop_front -- line 1744 ---------------------------------------- -- line 1748 ---------------------------------------- . /// ``` . /// let mut vec = vec![1, 2, 3]; . /// assert_eq!(vec.pop(), Some(3)); . /// assert_eq!(vec, [1, 2]); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn pop(&mut self) -> Option { 3,134,587 ( 0.04%) if self.len == 0 { 45 ( 0.00%) None . } else { . unsafe { 2,039,873 ( 0.02%) self.len -= 1; 470,364 ( 0.01%) Some(ptr::read(self.as_ptr().add(self.len()))) . } . } . } . . /// Moves all the elements of `other` into `Self`, leaving `other` empty. . /// . /// # Panics . /// -- line 1769 ---------------------------------------- -- line 1776 ---------------------------------------- . /// let mut vec2 = vec![4, 5, 6]; . /// vec.append(&mut vec2); . /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]); . /// assert_eq!(vec2, []); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[inline] . #[stable(feature = "append", since = "1.4.0")] 448 ( 0.00%) pub fn append(&mut self, other: &mut Self) { . unsafe { . self.append_elements(other.as_slice() as _); . other.set_len(0); . } 384 ( 0.00%) } . . /// Appends elements to `Self` from other buffer. . #[cfg(not(no_global_oom_handling))] . #[inline] . unsafe fn append_elements(&mut self, other: *const [T]) { . let count = unsafe { (*other).len() }; . self.reserve(count); 134,909 ( 0.00%) let len = self.len(); 44 ( 0.00%) unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) }; 623,097 ( 0.01%) self.len += count; . } . . /// Creates a draining iterator that removes the specified range in the vector . /// and yields the removed items. . /// . /// When the iterator **is** dropped, all elements in the range are removed . /// from the vector, even if the iterator was not fully consumed. If the . /// iterator **is not** dropped (with [`mem::forget`] for example), it is -- line 1807 ---------------------------------------- -- line 1834 ---------------------------------------- . // When the Drain is first created, it shortens the length of . // the source vector to make sure no uninitialized or moved-from elements . // are accessible at all if the Drain's destructor never gets to run. . // . // Drain will ptr::read out the values to remove. . // When finished, remaining tail of the vec is copied back to cover . // the hole, and the vector length is restored to the new length. . // 10,736 ( 0.00%) let len = self.len(); . let Range { start, end } = slice::range(range, ..len); . . unsafe { . // set self.vec length's to start, to be safe in case Drain is leaked . self.set_len(start); . // Use the borrow in the IterMut to indicate borrowing behavior of the . // whole Drain iterator (like &mut T). 884 ( 0.00%) let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start), end - start); 93,893 ( 0.00%) Drain { . tail_start: end, 626 ( 0.00%) tail_len: len - end, . iter: range_slice.iter(), . vec: NonNull::from(self), . } . } . } . . /// Clears the vector, removing all values. . /// -- line 1861 ---------------------------------------- -- line 1869 ---------------------------------------- . /// . /// v.clear(); . /// . /// assert!(v.is_empty()); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn clear(&mut self) { 29,101,632 ( 0.33%) self.truncate(0) . } . . /// Returns the number of elements in the vector, also referred to . /// as its 'length'. . /// . /// # Examples . /// . /// ``` -- line 1885 ---------------------------------------- -- line 1900 ---------------------------------------- . /// let mut v = Vec::new(); . /// assert!(v.is_empty()); . /// . /// v.push(1); . /// assert!(!v.is_empty()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn is_empty(&self) -> bool { 1,198,106 ( 0.01%) self.len() == 0 . } . . /// Splits the collection into two at the given index. . /// . /// Returns a newly allocated vector containing the elements in the range . /// `[at, len)`. After the call, the original vector will be left containing . /// the elements `[0, at)` with its previous capacity unchanged. . /// -- line 1916 ---------------------------------------- -- line 1935 ---------------------------------------- . A: Clone, . { . #[cold] . #[inline(never)] . fn assert_failed(at: usize, len: usize) -> ! { . panic!("`at` split index (is {}) should be <= len (is {})", at, len); . } . 562 ( 0.00%) if at > self.len() { . assert_failed(at, self.len()); . } . 434 ( 0.00%) if at == 0 { . // the new vector can take over the original buffer and avoid the copy . return mem::replace( . self, . Vec::with_capacity_in(self.capacity(), self.allocator().clone()), . ); . } . . let other_len = self.len - at; -- line 1955 ---------------------------------------- -- line 1988 ---------------------------------------- . /// . /// let mut vec = vec![]; . /// let mut p = 1; . /// vec.resize_with(4, || { p *= 2; p }); . /// assert_eq!(vec, [2, 4, 8, 16]); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "vec_resize_with", since = "1.33.0")] 25,559 ( 0.00%) pub fn resize_with(&mut self, new_len: usize, f: F) . where . F: FnMut() -> T, . { 3,225 ( 0.00%) let len = self.len(); 6,450 ( 0.00%) if new_len > len { 21,141 ( 0.00%) self.extend_with(new_len - len, ExtendFunc(f)); . } else { . self.truncate(new_len); . } 22,334 ( 0.00%) } . . /// Consumes and leaks the `Vec`, returning a mutable reference to the contents, . /// `&'a mut [T]`. Note that the type `T` must outlive the chosen lifetime . /// `'a`. If the type has only static references, or none at all, then this . /// may be chosen to be `'static`. . /// . /// As of Rust 1.57, this method does not reallocate or shrink the `Vec`, . /// so the leaked allocation may include unused capacity that is not part -- line 2014 ---------------------------------------- -- line 2070 ---------------------------------------- . #[stable(feature = "vec_spare_capacity", since = "1.60.0")] . #[inline] . pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit] { . // Note: . // This method is not implemented in terms of `split_at_spare_mut`, . // to prevent invalidation of pointers to the buffer. . unsafe { . slice::from_raw_parts_mut( 4 ( 0.00%) self.as_mut_ptr().add(self.len) as *mut MaybeUninit, 71 ( 0.00%) self.buf.capacity() - self.len, . ) . } . } . . /// Returns vector content as a slice of `T`, along with the remaining spare . /// capacity of the vector as a slice of `MaybeUninit`. . /// . /// The returned spare capacity slice can be used to fill the vector with data -- line 2087 ---------------------------------------- -- line 2189 ---------------------------------------- . /// assert_eq!(vec, ["hello", "world", "world"]); . /// . /// let mut vec = vec![1, 2, 3, 4]; . /// vec.resize(2, 0); . /// assert_eq!(vec, [1, 2]); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "vec_resize", since = "1.5.0")] 65,870 ( 0.00%) pub fn resize(&mut self, new_len: usize, value: T) { 6,587 ( 0.00%) let len = self.len(); . 19,761 ( 0.00%) if new_len > len { 3,240 ( 0.00%) self.extend_with(new_len - len, ExtendElement(value)) . } else { . self.truncate(new_len); . } 7,923 ( 0.00%) } . . /// Clones and appends all elements in a slice to the `Vec`. . /// . /// Iterates over the slice `other`, clones each element, and then appends . /// it to this `Vec`. The `other` slice is traversed in-order. . /// . /// Note that this function is same as [`extend`] except that it is . /// specialized to work with slices instead. If and when Rust gets -- line 2213 ---------------------------------------- -- line 2271 ---------------------------------------- . trait ExtendWith { . fn next(&mut self) -> T; . fn last(self) -> T; . } . . struct ExtendElement(T); . impl ExtendWith for ExtendElement { . fn next(&mut self) -> T { 926 ( 0.00%) self.0.clone() . } . fn last(self) -> T { . self.0 . } . } . . struct ExtendFunc(F); . impl T> ExtendWith for ExtendFunc { -- line 2287 ---------------------------------------- -- line 2291 ---------------------------------------- . fn last(mut self) -> T { . (self.0)() . } . } . . impl Vec { . #[cfg(not(no_global_oom_handling))] . /// Extend the vector by `n` values, using the given generator. 544,186 ( 0.01%) fn extend_with>(&mut self, n: usize, mut value: E) { . self.reserve(n); . . unsafe { 4,382 ( 0.00%) let mut ptr = self.as_mut_ptr().add(self.len()); . // Use SetLenOnDrop to work around bug where compiler . // might not realize the store through `ptr` through self.set_len() . // don't alias. . let mut local_len = SetLenOnDrop::new(&mut self.len); . . // Write all elements except the last one . for _ in 1..n { . ptr::write(ptr, value.next()); . ptr = ptr.offset(1); . // Increment the length in every step in case next() panics . local_len.increment_len(1); . } . 258,188 ( 0.00%) if n > 0 { . // We can write the last element directly without cloning needlessly . ptr::write(ptr, value.last()); . local_len.increment_len(1); . } . . // len set by scope guard . } 417,163 ( 0.00%) } . } . . impl Vec { . /// Removes consecutive repeated elements in the vector according to the . /// [`PartialEq`] trait implementation. . /// . /// If the vector is sorted, this removes all duplicates. . /// -- line 2333 ---------------------------------------- -- line 2338 ---------------------------------------- . /// . /// vec.dedup(); . /// . /// assert_eq!(vec, [1, 2, 3, 2]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . pub fn dedup(&mut self) { 37 ( 0.00%) self.dedup_by(|a, b| a == b) . } . } . . //////////////////////////////////////////////////////////////////////////////// . // Internal methods and functions . //////////////////////////////////////////////////////////////////////////////// . . #[doc(hidden)] . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] 46,475 ( 0.00%) pub fn from_elem(elem: T, n: usize) -> Vec { 529,725 ( 0.01%) ::from_elem(elem, n, Global) 58,395 ( 0.00%) } . . #[doc(hidden)] . #[cfg(not(no_global_oom_handling))] . #[unstable(feature = "allocator_api", issue = "32838")] . pub fn from_elem_in(elem: T, n: usize, alloc: A) -> Vec { . ::from_elem(elem, n, alloc) . } . -- line 2367 ---------------------------------------- -- line 2424 ---------------------------------------- . // Common trait implementations for Vec . //////////////////////////////////////////////////////////////////////////////// . . #[stable(feature = "rust1", since = "1.0.0")] . impl ops::Deref for Vec { . type Target = [T]; . . fn deref(&self) -> &[T] { 11,485,416 ( 0.13%) unsafe { slice::from_raw_parts(self.as_ptr(), self.len) } 24 ( 0.00%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl ops::DerefMut for Vec { . fn deref_mut(&mut self) -> &mut [T] { 2,956,223 ( 0.03%) unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) } . } . } . . #[cfg(not(no_global_oom_handling))] . trait SpecCloneFrom { . fn clone_from(this: &mut Self, other: &Self); . } . -- line 2447 ---------------------------------------- -- line 2468 ---------------------------------------- . this.extend_from_slice(other); . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl Clone for Vec { . #[cfg(not(test))] 411,304 ( 0.00%) fn clone(&self) -> Self { . let alloc = self.allocator().clone(); 2 ( 0.00%) <[T]>::to_vec_in(&**self, alloc) 492,028 ( 0.01%) } . . // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is . // required for this method definition, is not available. Instead use the . // `slice::to_vec` function which is only available with cfg(test) . // NB see the slice::hack module in slice.rs for more information . #[cfg(test)] . fn clone(&self) -> Self { . let alloc = self.allocator().clone(); -- line 2487 ---------------------------------------- -- line 2518 ---------------------------------------- . message = "vector indices are of type `usize` or ranges of `usize`", . label = "vector indices are of type `usize` or ranges of `usize`" . )] . impl, A: Allocator> Index for Vec { . type Output = I::Output; . . #[inline] . fn index(&self, index: I) -> &Self::Output { 231,585 ( 0.00%) Index::index(&**self, index) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_on_unimplemented( . message = "vector indices are of type `usize` or ranges of `usize`", . label = "vector indices are of type `usize` or ranges of `usize`" . )] . impl, A: Allocator> IndexMut for Vec { . #[inline] . fn index_mut(&mut self, index: I) -> &mut Self::Output { 208 ( 0.00%) IndexMut::index_mut(&mut **self, index) . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl FromIterator for Vec { . #[inline] . fn from_iter>(iter: I) -> Vec { 1,489,017 ( 0.02%) >::from_iter(iter.into_iter()) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl IntoIterator for Vec { . type Item = T; . type IntoIter = IntoIter; . -- line 2555 ---------------------------------------- -- line 2564 ---------------------------------------- . /// for s in v.into_iter() { . /// // s has type String, not &String . /// println!("{}", s); . /// } . /// ``` . #[inline] . fn into_iter(self) -> IntoIter { . unsafe { 560,253 ( 0.01%) let mut me = ManuallyDrop::new(self); . let alloc = ptr::read(me.allocator()); . let begin = me.as_mut_ptr(); . let end = if mem::size_of::() == 0 { . arith_offset(begin as *const i8, me.len() as isize) as *const T . } else { . begin.add(me.len()) as *const T . }; . let cap = me.buf.capacity(); 161,102 ( 0.00%) IntoIter { . buf: NonNull::new_unchecked(begin), . phantom: PhantomData, . cap, . alloc, . ptr: begin, . end, . } . } -- line 2589 ---------------------------------------- -- line 2591 ---------------------------------------- . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl<'a, T, A: Allocator> IntoIterator for &'a Vec { . type Item = &'a T; . type IntoIter = slice::Iter<'a, T>; . . fn into_iter(self) -> slice::Iter<'a, T> { 56 ( 0.00%) self.iter() . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl<'a, T, A: Allocator> IntoIterator for &'a mut Vec { . type Item = &'a mut T; . type IntoIter = slice::IterMut<'a, T>; . . fn into_iter(self) -> slice::IterMut<'a, T> { 1,090 ( 0.00%) self.iter_mut() . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl Extend for Vec { . #[inline] 2,576 ( 0.00%) fn extend>(&mut self, iter: I) { 673,889 ( 0.01%) >::spec_extend(self, iter.into_iter()) 2,576 ( 0.00%) } . . #[inline] . fn extend_one(&mut self, item: T) { . self.push(item); . } . . #[inline] . fn extend_reserve(&mut self, additional: usize) { -- line 2627 ---------------------------------------- -- line 2636 ---------------------------------------- . fn extend_desugared>(&mut self, mut iterator: I) { . // This is the case for a general iterator. . // . // This function should be the moral equivalent of: . // . // for item in iterator { . // self.push(item); . // } 57,787 ( 0.00%) while let Some(element) = iterator.next() { 17,955 ( 0.00%) let len = self.len(); 596,517 ( 0.01%) if len == self.capacity() { 990 ( 0.00%) let (lower, _) = iterator.size_hint(); . self.reserve(lower.saturating_add(1)); . } . unsafe { . ptr::write(self.as_mut_ptr().add(len), element); . // Since next() executes user code which can panic we have to bump the length . // after each step. . // NB can't overflow since we would have had to alloc the address space 380,083 ( 0.00%) self.set_len(len + 1); . } . } 4,509 ( 0.00%) } . . /// Creates a splicing iterator that replaces the specified range in the vector . /// with the given `replace_with` iterator and yields the removed items. . /// `replace_with` does not need to be the same length as `range`. . /// . /// `range` is removed even if the iterator is not consumed until the end. . /// . /// It is unspecified how many elements are removed from the vector -- line 2666 ---------------------------------------- -- line 2693 ---------------------------------------- . #[cfg(not(no_global_oom_handling))] . #[inline] . #[stable(feature = "vec_splice", since = "1.21.0")] . pub fn splice(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter, A> . where . R: RangeBounds, . I: IntoIterator, . { 3,190 ( 0.00%) Splice { drain: self.drain(range), replace_with: replace_with.into_iter() } . } . . /// Creates an iterator which uses a closure to determine if an element should be removed. . /// . /// If the closure returns true, then the element is removed and yielded. . /// If the closure returns false, the element will remain in the vector and will not be yielded . /// by the iterator. . /// -- line 2709 ---------------------------------------- -- line 2745 ---------------------------------------- . /// assert_eq!(evens, vec![2, 4, 6, 8, 14]); . /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]); . /// ``` . #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")] . pub fn drain_filter(&mut self, filter: F) -> DrainFilter<'_, T, F, A> . where . F: FnMut(&mut T) -> bool, . { 2,106 ( 0.00%) let old_len = self.len(); . . // Guard against us getting leaked (leak amplification) . unsafe { . self.set_len(0); . } . 6,032 ( 0.00%) DrainFilter { vec: self, idx: 0, del: 0, old_len, pred: filter, panic_flag: false } . } . } . . /// Extend implementation that copies elements out of references before pushing them onto the Vec. . /// . /// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to . /// append the entire slice at once. . /// . /// [`copy_from_slice`]: slice::copy_from_slice . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "extend_ref", since = "1.2.0")] . impl<'a, T: Copy + 'a, A: Allocator + 'a> Extend<&'a T> for Vec { 11,488 ( 0.00%) fn extend>(&mut self, iter: I) { . self.spec_extend(iter.into_iter()) 8,616 ( 0.00%) } . . #[inline] . fn extend_one(&mut self, &item: &'a T) { . self.push(item); . } . . #[inline] . fn extend_reserve(&mut self, additional: usize) { -- line 2783 ---------------------------------------- -- line 2803 ---------------------------------------- . #[inline] . fn cmp(&self, other: &Self) -> Ordering { . Ord::cmp(&**self, &**other) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . unsafe impl<#[may_dangle] T, A: Allocator> Drop for Vec { 937,415 ( 0.01%) fn drop(&mut self) { . unsafe { . // use drop for [T] . // use a raw slice to refer to the elements of the vector as weakest necessary type; . // could avoid questions of validity in certain cases 438,225 ( 0.01%) ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len)) . } . // RawVec handles deallocation 1,108,314 ( 0.01%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")] . impl const Default for Vec { . /// Creates an empty `Vec`. . fn default() -> Vec { . Vec::new() -- line 2827 ---------------------------------------- -- line 2976 ---------------------------------------- . /// newly-allocated buffer with exactly the right capacity. . /// . /// # Examples . /// . /// ``` . /// assert_eq!(Box::from(vec![1, 2, 3]), vec![1, 2, 3].into_boxed_slice()); . /// ``` . fn from(v: Vec) -> Self { 4 ( 0.00%) v.into_boxed_slice() . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl From<&str> for Vec { . /// Allocate a `Vec` and fill it with a UTF-8 string. . /// -- line 2992 ---------------------------------------- 2,034,237 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe/transcribe.rs -------------------------------------------------------------------------------- Ir -- line 16 ---------------------------------------- . use std::mem; . . // A Marker adds the given mark to the syntax context. . struct Marker(LocalExpnId, Transparency); . . impl MutVisitor for Marker { . const VISIT_TOKENS: bool = true; . 334,674 ( 0.00%) fn visit_span(&mut self, span: &mut Span) { 223,116 ( 0.00%) *span = span.apply_mark(self.0.to_expn_id(), self.1) 297,488 ( 0.00%) } . } . . /// An iterator over the token trees in a delimited token tree (`{ ... }`) or a sequence (`$(...)`). . enum Frame { . Delimited { forest: Lrc, idx: usize, span: DelimSpan }, . Sequence { forest: Lrc, idx: usize, sep: Option }, . } . . impl Frame { . /// Construct a new frame around the delimited set of tokens. . fn new(tts: Vec) -> Frame { . let forest = Lrc::new(mbe::Delimited { delim: token::NoDelim, tts }); 7,424 ( 0.00%) Frame::Delimited { forest, idx: 0, span: DelimSpan::dummy() } . } . } . . impl Iterator for Frame { . type Item = mbe::TokenTree; . . fn next(&mut self) -> Option { 797,840 ( 0.01%) match *self { 78,274 ( 0.00%) Frame::Delimited { ref forest, ref mut idx, .. } => { 117,411 ( 0.00%) *idx += 1; . forest.tts.get(*idx - 1).cloned() . } 480,969 ( 0.01%) Frame::Sequence { ref forest, ref mut idx, .. } => { 480,969 ( 0.01%) *idx += 1; . forest.tts.get(*idx - 1).cloned() . } . } . } . } . . /// This can do Macro-By-Example transcription. . /// - `interp` is a map of meta-variables to the tokens (non-terminals) they matched in the -- line 61 ---------------------------------------- -- line 72 ---------------------------------------- . /// foo!(bar); . /// ``` . /// . /// `interp` would contain `$id => bar` and `src` would contain `println!("{}", stringify!($id));`. . /// . /// `transcribe` would return a `TokenStream` containing `println!("{}", stringify!(bar));`. . /// . /// Along the way, we do some additional error checking. 9,280 ( 0.00%) pub(super) fn transcribe<'a>( . cx: &ExtCtxt<'a>, . interp: &FxHashMap, . src: Vec, . transparency: Transparency, . ) -> PResult<'a, TokenStream> { . // Nothing for us to transcribe... 928 ( 0.00%) if src.is_empty() { . return Ok(TokenStream::default()); . } . . // We descend into the RHS (`src`), expanding things as we go. This stack contains the things . // we have yet to expand/are still expanding. We start the stack off with the whole RHS. 7,424 ( 0.00%) let mut stack: SmallVec<[Frame; 1]> = smallvec![Frame::new(src)]; . . // As we descend in the RHS, we will need to be able to match nested sequences of matchers. . // `repeats` keeps track of where we are in matching at each level, with the last element being . // the most deeply nested sequence. This is used as a stack. . let mut repeats = Vec::new(); . . // `result` contains resulting token stream from the TokenTree we just finished processing. At . // the end, this will contain the full result of transcription, but at arbitrary points during -- line 101 ---------------------------------------- -- line 105 ---------------------------------------- . // `result_stack` and clear `results`. We will then produce the results of transcribing the . // TokenTree into `results`. Then, as we unwind back out of the `TokenTree`, we will pop the . // `result_stack` and append `results` too it to produce the new `results` up to that point. . // . // Thus, if we try to pop the `result_stack` and it is empty, we have reached the top-level . // again, and we are done transcribing. . let mut result: Vec = Vec::new(); . let mut result_stack = Vec::new(); 3,712 ( 0.00%) let mut marker = Marker(cx.current_expansion.id, transparency); . . loop { . // Look at the last frame on the stack. . // If it still has a TokenTree we have not looked at yet, use that tree. 909,727 ( 0.01%) let Some(tree) = stack.last_mut().unwrap().next() else { . // This else-case never produces a value for `tree` (it `continue`s or `return`s). . . // Otherwise, if we have just reached the end of a sequence and we can keep repeating, . // go back to the beginning of the sequence. 344,812 ( 0.00%) if let Frame::Sequence { idx, sep, .. } = stack.last_mut().unwrap() { . let (repeat_idx, repeat_len) = repeats.last_mut().unwrap(); 319,500 ( 0.00%) *repeat_idx += 1; 79,875 ( 0.00%) if repeat_idx < repeat_len { 78,462 ( 0.00%) *idx = 0; 156,924 ( 0.00%) if let Some(sep) = sep { 343 ( 0.00%) result.push(TokenTree::Token(sep.clone()).into()); . } . continue; . } . } . . // We are done with the top of the stack. Pop it. Depending on what it was, we do . // different things. Note that the outermost item must be the delimited, wrapped RHS . // that was passed in originally to `transcribe`. 15,482 ( 0.00%) match stack.pop().unwrap() { . // Done with a sequence. Pop from repeats. . Frame::Sequence { .. } => { . repeats.pop(); . } . . // We are done processing a Delimited. If this is the top-level delimited, we are . // done. Otherwise, we unwind the result_stack to append what we have produced to . // any previous results. 25,312 ( 0.00%) Frame::Delimited { forest, span, .. } => { 6,328 ( 0.00%) if result_stack.is_empty() { . // No results left to compute! We are back at the top-level. 5,568 ( 0.00%) return Ok(TokenStream::new(result)); . } . . // Step back into the parent Delimited. 70,200 ( 0.00%) let tree = TokenTree::Delimited(span, forest.delim, TokenStream::new(result)); 16,200 ( 0.00%) result = result_stack.pop().unwrap(); . result.push(tree.into()); . } 12,656 ( 0.00%) } . continue; . }; . . // At this point, we know we are in the middle of a TokenTree (the last one on `stack`). . // `tree` contains the next `TokenTree` to be processed. 679,542 ( 0.01%) match tree { . // We are descending into a sequence. We first make sure that the matchers in the RHS . // and the matches in `interp` have the same shape. Otherwise, either the caller or the . // macro writer has made a mistake. 6,916 ( 0.00%) seq @ mbe::TokenTree::Sequence(..) => { 12,103 ( 0.00%) match lockstep_iter_size(&seq, interp, &repeats) { . LockstepIterSize::Unconstrained => { . return Err(cx.struct_span_err( . seq.span(), /* blame macro writer */ . "attempted to repeat an expression containing no syntax variables \ . matched as repeating at this depth", . )); . } . -- line 177 ---------------------------------------- -- line 181 ---------------------------------------- . // sequence, but they come from different sequence matchers and repeat . // different amounts. . return Err(cx.struct_span_err(seq.span(), &msg)); . } . . LockstepIterSize::Constraint(len, _) => { . // We do this to avoid an extra clone above. We know that this is a . // sequence already. 12,103 ( 0.00%) let mbe::TokenTree::Sequence(sp, seq) = seq else { . unreachable!() . }; . . // Is the repetition empty? 3,458 ( 0.00%) if len == 0 { 316 ( 0.00%) if seq.kleene.op == mbe::KleeneOp::OneOrMore { . // FIXME: this really ought to be caught at macro definition . // time... It happens when the Kleene operator in the matcher and . // the body for the same meta-variable do not match. . return Err(cx.struct_span_err( . sp.entire(), . "this must repeat at least once", . )); . } -- line 203 ---------------------------------------- -- line 204 ---------------------------------------- . } else { . // 0 is the initial counter (we have done 0 repretitions so far). `len` . // is the total number of repetitions we should generate. . repeats.push((0, len)); . . // The first time we encounter the sequence we push it to the stack. It . // then gets reused (see the beginning of the loop) until we are done . // repeating. 12,717 ( 0.00%) stack.push(Frame::Sequence { . idx: 0, . sep: seq.separator.clone(), . forest: seq, . }); . } . } . } . } . . // Replace the meta-var with the matched token tree from the invocation. 482,826 ( 0.01%) mbe::TokenTree::MetaVar(mut sp, mut orignal_ident) => { . // Find the matched nonterminal from the macro invocation, and use it to replace . // the meta-var. 321,884 ( 0.00%) let ident = MacroRulesNormalizedIdent::new(orignal_ident); 482,826 ( 0.01%) if let Some(cur_matched) = lookup_cur_matched(ident, interp, &repeats) { 241,413 ( 0.00%) if let MatchedNonterminal(nt) = cur_matched { 241,413 ( 0.00%) let token = if let NtTT(tt) = &**nt { . // `tt`s are emitted into the output stream directly as "raw tokens", . // without wrapping them into groups. . tt.clone() . } else { . // Other variables are emitted into the output stream as groups with . // `Delimiter::None` to maintain parsing priorities. . // `Interpolated` is currenty used for such groups in rustc parser. 2,187 ( 0.00%) marker.visit_span(&mut sp); 4,374 ( 0.00%) TokenTree::token(token::Interpolated(nt.clone()), sp) . }; . result.push(token.into()); . } else { . // We were unable to descend far enough. This is an error. . return Err(cx.struct_span_err( . sp, /* blame the macro writer */ . &format!("variable '{}' is still repeating at this depth", ident), . )); -- line 246 ---------------------------------------- -- line 255 ---------------------------------------- . } . } . . // If we are entering a new delimiter, we push its contents to the `stack` to be . // processed, and we push all of the currently produced results to the `result_stack`. . // We will produce all of the results of the inside of the `Delimited` and then we will . // jump back out of the Delimited, pop the result_stack and add the new results back to . // the previous results (from outside the Delimited). 32,400 ( 0.00%) mbe::TokenTree::Delimited(mut span, delimited) => { . mut_visit::visit_delim_span(&mut span, &mut marker); 32,400 ( 0.00%) stack.push(Frame::Delimited { forest: delimited, idx: 0, span }); . result_stack.push(mem::take(&mut result)); . } . . // Nothing much to do here. Just push the token to the result, being careful to . // preserve syntax context. . mbe::TokenTree::Token(token) => { 153,942 ( 0.00%) let mut tt = TokenTree::Token(token); 76,971 ( 0.00%) mut_visit::visit_tt(&mut tt, &mut marker); . result.push(tt.into()); . } . . // There should be no meta-var declarations in the invocation of a macro. . mbe::TokenTree::MetaVarDecl(..) => panic!("unexpected `TokenTree::MetaVarDecl"), . } . } 11,136 ( 0.00%) } . . /// Lookup the meta-var named `ident` and return the matched token tree from the invocation using . /// the set of matches `interpolations`. . /// . /// See the definition of `repeats` in the `transcribe` function. `repeats` is used to descend . /// into the right place in nested matchers. If we attempt to descend too far, the macro writer has . /// made a mistake, and we return `None`. 740,439 ( 0.01%) fn lookup_cur_matched<'a>( . ident: MacroRulesNormalizedIdent, . interpolations: &'a FxHashMap, . repeats: &[(usize, usize)], . ) -> Option<&'a NamedMatch> { . interpolations.get(&ident).map(|matched| { . let mut matched = matched; . for &(idx, _) in repeats { 480,324 ( 0.01%) match matched { . MatchedNonterminal(_) => break, 80,054 ( 0.00%) MatchedSeq(ref ads) => matched = ads.get(idx).unwrap(), . } . } . . matched . }) 740,439 ( 0.01%) } . . /// An accumulator over a TokenTree to be used with `fold`. During transcription, we need to make . /// sure that the size of each sequence and all of its nested sequences are the same as the sizes . /// of all the matched (nested) sequences in the macro invocation. If they don't match, somebody . /// has made a mistake (either the macro writer or caller). . #[derive(Clone)] . enum LockstepIterSize { . /// No constraints on length of matcher. This is true for any TokenTree variants except a -- line 313 ---------------------------------------- -- line 322 ---------------------------------------- . Contradiction(String), . } . . impl LockstepIterSize { . /// Find incompatibilities in matcher/invocation sizes. . /// - `Unconstrained` is compatible with everything. . /// - `Contradiction` is incompatible with everything. . /// - `Constraint(len)` is only compatible with other constraints of the same length. 20,691 ( 0.00%) fn with(self, other: LockstepIterSize) -> LockstepIterSize { 7,205 ( 0.00%) match self { . LockstepIterSize::Unconstrained => other, . LockstepIterSize::Contradiction(_) => self, 1,220 ( 0.00%) LockstepIterSize::Constraint(l_len, ref l_id) => match other { . LockstepIterSize::Unconstrained => self, . LockstepIterSize::Contradiction(_) => other, 213 ( 0.00%) LockstepIterSize::Constraint(r_len, _) if l_len == r_len => self, . LockstepIterSize::Constraint(r_len, r_id) => { . let msg = format!( . "meta-variable `{}` repeats {} time{}, but `{}` repeats {} time{}", . l_id, . l_len, . pluralize!(l_len), . r_id, . r_len, . pluralize!(r_len), . ); . LockstepIterSize::Contradiction(msg) . } . }, . } 16,401 ( 0.00%) } . } . . /// Given a `tree`, make sure that all sequences have the same length as the matches for the . /// appropriate meta-vars in `interpolations`. . /// . /// Note that if `repeats` does not match the exact correct depth of a meta-var, . /// `lookup_cur_matched` will return `None`, which is why this still works even in the presence of . /// multiple nested matcher sequences. 40,280 ( 0.00%) fn lockstep_iter_size( . tree: &mbe::TokenTree, . interpolations: &FxHashMap, . repeats: &[(usize, usize)], . ) -> LockstepIterSize { . use mbe::TokenTree; 28,196 ( 0.00%) match *tree { . TokenTree::Delimited(_, ref delimed) => { 141 ( 0.00%) delimed.tts.iter().fold(LockstepIterSize::Unconstrained, |size, tt| { 4,019 ( 0.00%) size.with(lockstep_iter_size(tt, interpolations, repeats)) . }) . } . TokenTree::Sequence(_, ref seq) => { 1,749 ( 0.00%) seq.tts.iter().fold(LockstepIterSize::Unconstrained, |size, tt| { 35,278 ( 0.00%) size.with(lockstep_iter_size(tt, interpolations, repeats)) . }) . } . TokenTree::MetaVar(_, name) | TokenTree::MetaVarDecl(_, name, _) => { 3,600 ( 0.00%) let name = MacroRulesNormalizedIdent::new(name); 16,200 ( 0.00%) match lookup_cur_matched(name, interpolations, repeats) { 3,600 ( 0.00%) Some(matched) => match matched { . MatchedNonterminal(_) => LockstepIterSize::Unconstrained, 10,800 ( 0.00%) MatchedSeq(ref ads) => LockstepIterSize::Constraint(ads.len(), name), . }, . _ => LockstepIterSize::Unconstrained, . } . } . TokenTree::Token(..) => LockstepIterSize::Unconstrained, . } 32,224 ( 0.00%) } 2,252,496 ( 0.03%) -------------------------------------------------------------------------------- -- 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. 7,885,609 ( 0.09%) #[derive(Clone)] . enum TokenTreeOrTokenTreeSlice<'tt> { . Tt(TokenTree), 1,969,140 ( 0.02%) 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 { 13,396,393 ( 0.15%) match *self { 48,362 ( 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 { 2,640,692 ( 0.03%) match *self { 60,916 ( 0.00%) TtSeq(ref v) => v[index].clone(), 7,289,278 ( 0.08%) 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. 1,307,194 ( 0.02%) #[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. 653,597 ( 0.01%) 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. 31,114,752 ( 0.36%) #[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 662,016 ( 0.01%) 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`. 2,648,064 ( 0.03%) 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]`. 662,016 ( 0.01%) 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. 662,016 ( 0.01%) 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. 662,016 ( 0.01%) 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. 1,324,032 ( 0.02%) 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) { 5,265,612 ( 0.06%) 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. 2,648,064 ( 0.03%) fn clone(&self) -> Self { 1,324,032 ( 0.02%) MatcherPosHandle::Box(match *self { 1,959,546 ( 0.02%) MatcherPosHandle::Ref(ref r) => Box::new((**r).clone()), . MatcherPosHandle::Box(ref b) => b.clone(), . }) 3,972,096 ( 0.05%) } . } . . 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 { 111,508 ( 0.00%) ms.iter().fold(0, |count, elt| { 55,754 ( 0.00%) count 167,262 ( 0.00%) + match *elt { 26,988 ( 0.00%) TokenTree::Sequence(_, ref seq) => seq.num_captures, 8,107 ( 0.00%) TokenTree::Delimited(_, ref delim) => count_names(&delim.tts), . TokenTree::MetaVar(..) => 0, . TokenTree::MetaVarDecl(..) => 1, . TokenTree::Token(..) => 0, . } 139,385 ( 0.00%) }) . } . . /// `len` `Vec`s (initially shared and empty) that will store matches of metavars. . fn create_matches(len: usize) -> Box<[Lrc]> { 39,476 ( 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); 119,115 ( 0.00%) 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. 2,458 ( 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`. 59,136 ( 0.00%) fn n_rec>( . sess: &ParseSess, . m: &TokenTree, . res: &mut I, . ret_val: &mut FxHashMap, . ) -> Result<(), (rustc_span::Span, String)> { 31,204 ( 0.00%) match *m { . TokenTree::Sequence(_, ref seq) => { 1,741 ( 0.00%) for next_m in &seq.tts { 11,316 ( 0.00%) n_rec(sess, next_m, res.by_ref(), ret_val)? . } . } . TokenTree::Delimited(_, ref delim) => { 988 ( 0.00%) for next_m in &delim.tts { 5,964 ( 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())); . } . } 12,972 ( 0.00%) TokenTree::MetaVarDecl(sp, bind_name, _) => match ret_val 8,648 ( 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(..) => (), . } . 5,376 ( 0.00%) Ok(()) 43,008 ( 0.00%) } . . let mut ret_val = FxHashMap::default(); . for m in ms { 24,698 ( 0.00%) match n_rec(sess, m, res.by_ref(), &mut ret_val) { . Ok(_) => {} . Err((sp, msg)) => return Error(sp, msg), . } . } . 8,523 ( 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 { 3,341,712 ( 0.04%) if let (Some((ident1, is_raw1)), Some((ident2, is_raw2))) = (t1.ident(), t2.ident()) { 66 ( 0.00%) ident1.name == ident2.name && is_raw1 == is_raw2 4,678,030 ( 0.05%) } else if let (Some(ident1), Some(ident2)) = (t1.lifetime(), t2.lifetime()) { . ident1.name == ident2.name . } else { 2,004,773 ( 0.02%) 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. 8,040,124 ( 0.09%) 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. 25,466,430 ( 0.29%) while item.idx >= item.top_elts.len() { 14,330 ( 0.00%) match item.stack.pop() { . Some(MatcherTtFrame { elts, idx }) => { 64,485 ( 0.00%) item.top_elts = elts; 28,660 ( 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`. 4,689,053 ( 0.05%) 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. 663,434 ( 0.01%) 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. 1,308,244 ( 0.02%) 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` 1,308,064 ( 0.02%) for idx in item.match_lo..item.match_hi { 3,270,535 ( 0.04%) let sub = item.matches[idx].clone(); 1,962,321 ( 0.02%) new_pos.push_match(idx, MatchedSeq(sub)); . } . . // Move the "dot" past the repetition in `up` 1,307,970 ( 0.02%) new_pos.match_cur = item.match_hi; 3,924,192 ( 0.05%) new_pos.idx += 1; . cur_items.push(new_pos); . } . . // Check if we need a separator. 654,032 ( 0.01%) if idx == len && item.sep.is_some() { . // We have a separator, and it is the current token. We can advance past the . // separator token. 188 ( 0.00%) if item.sep.as_ref().map_or(false, |sep| token_name_eq(token, sep)) { 630 ( 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. 654,028 ( 0.01%) else if item.seq_op != Some(mbe::KleeneOp::ZeroOrOne) { 1,307,948 ( 0.02%) item.match_cur = item.match_lo; 2,615,896 ( 0.03%) 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. 13,976,861 ( 0.16%) match item.top_elts.get_tt(idx) { . // Need to descend into a sequence 38,918 ( 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. 15,914 ( 0.00%) if seq.kleene.op == mbe::KleeneOp::ZeroOrMore . || seq.kleene.op == mbe::KleeneOp::ZeroOrOne . { 15,828 ( 0.00%) let mut new_item = item.clone(); 31,656 ( 0.00%) new_item.match_cur += seq.num_captures; 39,570 ( 0.00%) new_item.idx += 1; 47,484 ( 0.00%) for idx in item.match_cur..item.match_cur + seq.num_captures { 23,442 ( 0.00%) new_item.push_match(idx, MatchedSeq(Lrc::new(smallvec![]))); . } . cur_items.push(new_item); . } . 7,957 ( 0.00%) let matches = create_matches(item.matches.len()); 95,484 ( 0.00%) cur_items.push(MatcherPosHandle::Box(Box::new(MatcherPos { 7,957 ( 0.00%) stack: smallvec![], . sep: seq.separator.clone(), 7,957 ( 0.00%) seq_op: Some(seq.kleene.op), . idx: 0, 39,785 ( 0.00%) matches, 15,914 ( 0.00%) match_lo: item.match_cur, . match_cur: item.match_cur, 15,914 ( 0.00%) match_hi: item.match_cur + seq.num_captures, . up: Some(item), 55,699 ( 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. 3,311,790 ( 0.04%) 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. 40,300 ( 0.00%) seq @ (TokenTree::Delimited(..) . | TokenTree::Token(Token { kind: DocComment(..), .. })) => { . let lower_elts = mem::replace(&mut item.top_elts, Tt(seq)); 8,060 ( 0.00%) let idx = item.idx; 56,420 ( 0.00%) item.stack.push(MatcherTtFrame { elts: lower_elts, idx }); 32,240 ( 0.00%) item.idx = 0; . cur_items.push(item); . } . . // We just matched a normal token. We can just advance the parser. 1,414,296 ( 0.02%) TokenTree::Token(t) if token_name_eq(&t, token) => { 109,067 ( 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(..) => {} . } 7,360,907 ( 0.08%) } 2,677,074 ( 0.03%) } . . // 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. 79,410 ( 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); 39,705 ( 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(); 678,004 ( 0.01%) 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 678,004 ( 0.01%) 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. 3,390,020 ( 0.04%) if parser.token == token::Eof { 3,788 ( 0.00%) if eof_items.len() == 1 { . let matches = 4,056 ( 0.00%) eof_items[0].matches.iter_mut().map(|dv| Lrc::make_mut(dv).pop().unwrap()); 2,841 ( 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 { . return Failure( . Token::new( -- line 680 ---------------------------------------- -- line 687 ---------------------------------------- . ), . "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. 2,708,228 ( 0.03%) 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. 2,053,746 ( 0.02%) if bb_items.is_empty() && next_items.is_empty() { 90,922 ( 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. 2,617,928 ( 0.03%) 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 46,743 ( 0.00%) cur_items.extend(next_items.drain(..)); 15,581 ( 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); . 1,308,964 ( 0.02%) let mut item = bb_items.pop().unwrap(); 5,234,776 ( 0.06%) if let TokenTree::MetaVarDecl(span, _, Some(kind)) = item.top_elts.get_tt(item.idx) { 654,482 ( 0.01%) let match_cur = item.match_cur; . // We use the span of the metavariable declaration to determine any . // edition-specific matching behavior for non-terminals. 3,927,041 ( 0.05%) 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; . } 3,926,892 ( 0.05%) Ok(nt) => nt, . }; 2,617,928 ( 0.03%) item.push_match(match_cur, MatchedNonterminal(Lrc::new(nt))); 2,617,928 ( 0.03%) item.idx += 1; 3,926,892 ( 0.05%) item.match_cur += 1; . } else { . unreachable!() . } . cur_items.push(item); . } . 1,340,126 ( 0.02%) assert!(!cur_items.is_empty()); . } 71,469 ( 0.00%) } 24,777,598 ( 0.28%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs -------------------------------------------------------------------------------- Ir -- line 12 ---------------------------------------- . use rustc_data_structures::sync::Lrc; . use rustc_macros::HashStable_Generic; . use rustc_span::symbol::{kw, sym}; . use rustc_span::symbol::{Ident, Symbol}; . use rustc_span::{self, edition::Edition, Span, DUMMY_SP}; . use std::borrow::Cow; . use std::{fmt, mem}; . 21,524 ( 0.00%) #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub enum CommentKind { . Line, . Block, . } . 97 ( 0.00%) #[derive(Clone, PartialEq, Encodable, Decodable, Hash, Debug, Copy)] . #[derive(HashStable_Generic)] . pub enum BinOpToken { . Plus, . Minus, . Star, . Slash, . Percent, . Caret, . And, . Or, . Shl, . Shr, . } . . /// A delimiter token. 701,034 ( 0.01%) #[derive(Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug, Copy)] . #[derive(HashStable_Generic)] . pub enum DelimToken { . /// A round parenthesis (i.e., `(` or `)`). . Paren, . /// A square bracket (i.e., `[` or `]`). . Bracket, . /// A curly brace (i.e., `{` or `}`). . Brace, . /// An empty delimiter. . NoDelim, . } . 2,970 ( 0.00%) #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub enum LitKind { . Bool, // AST only, must never appear in a `Token` . Byte, . Char, . Integer, . Float, . Str, . StrRaw(u16), // raw string delimited by `n` hash symbols . ByteStr, . ByteStrRaw(u16), // raw byte string delimited by `n` hash symbols . Err, . } . . /// A literal token. 115,051 ( 0.00%) #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub struct Lit { . pub kind: LitKind, . pub symbol: Symbol, . pub suffix: Option, . } . . impl fmt::Display for Lit { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { -- line 78 ---------------------------------------- -- line 130 ---------------------------------------- . crate fn may_have_suffix(self) -> bool { . matches!(self, Integer | Float | Err) . } . } . . impl Lit { . pub fn new(kind: LitKind, symbol: Symbol, suffix: Option) -> Lit { . Lit { kind, symbol, suffix } 2,565 ( 0.00%) } . } . 480 ( 0.00%) pub fn ident_can_begin_expr(name: Symbol, span: Span, is_raw: bool) -> bool { 840 ( 0.00%) let ident_token = Token::new(Ident(name, is_raw), span); . 392 ( 0.00%) !ident_token.is_reserved_ident() . || ident_token.is_path_segment_keyword() . || [ . kw::Async, . kw::Do, . kw::Box, . kw::Break, . kw::Const, . kw::Continue, -- line 152 ---------------------------------------- -- line 161 ---------------------------------------- . kw::True, . kw::Try, . kw::Unsafe, . kw::While, . kw::Yield, . kw::Static, . ] . .contains(&name) 600 ( 0.00%) } . . fn ident_can_begin_type(name: Symbol, span: Span, is_raw: bool) -> bool { 798 ( 0.00%) let ident_token = Token::new(Ident(name, is_raw), span); . 270 ( 0.00%) !ident_token.is_reserved_ident() . || ident_token.is_path_segment_keyword() . || [kw::Underscore, kw::For, kw::Impl, kw::Fn, kw::Unsafe, kw::Extern, kw::Typeof, kw::Dyn] . .contains(&name) . } . 75,358,781 ( 0.87%) #[derive(Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub enum TokenKind { . /* Expression-operator symbols. */ . Eq, . Lt, . Le, . EqEq, . Ne, . Ge, . Gt, . AndAnd, . OrOr, . Not, . Tilde, 31,974 ( 0.00%) BinOp(BinOpToken), 42 ( 0.00%) BinOpEq(BinOpToken), . . /* Structural symbols */ . At, . Dot, . DotDot, . DotDotDot, . DotDotEq, . Comma, -- line 203 ---------------------------------------- -- line 208 ---------------------------------------- . LArrow, . FatArrow, . Pound, . Dollar, . Question, . /// Used by proc macros for representing lifetimes, not generated by lexer right now. . SingleQuote, . /// An opening delimiter (e.g., `{`). 98,439 ( 0.00%) OpenDelim(DelimToken), . /// A closing delimiter (e.g., `}`). 31,140 ( 0.00%) CloseDelim(DelimToken), . . /* Literals */ 161,435 ( 0.00%) Literal(Lit), . . /// Identifier token. . /// Do not forget about `NtIdent` when you want to match on identifiers. . /// It's recommended to use `Token::(ident,uninterpolate,uninterpolated_span)` to . /// treat regular and interpolated identifiers in the same way. 1,422,128 ( 0.02%) Ident(Symbol, /* is_raw */ bool), . /// Lifetime identifier token. . /// Do not forget about `NtLifetime` when you want to match on lifetime identifiers. . /// It's recommended to use `Token::(lifetime,uninterpolate,uninterpolated_span)` to . /// treat regular and interpolated lifetime identifiers in the same way. 1,716 ( 0.00%) Lifetime(Symbol), . 45,639 ( 0.00%) Interpolated(Lrc), . . /// A doc comment token. . /// `Symbol` is the doc comment's data excluding its "quotes" (`///`, `/**`, etc) . /// similarly to symbols in string literal tokens. . DocComment(CommentKind, ast::AttrStyle, Symbol), . . Eof, . } . . // `TokenKind` 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!(TokenKind, 16); . 10,652,875 ( 0.12%) #[derive(Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub struct Token { 1,162,737 ( 0.01%) pub kind: TokenKind, 37 ( 0.00%) pub span: Span, . } . . impl TokenKind { . pub fn lit(kind: LitKind, symbol: Symbol, suffix: Option) -> TokenKind { . Literal(Lit::new(kind, symbol, suffix)) . } . . // An approximation to proc-macro-style single-character operators used by rustc parser. . // If the operator token can be broken into two tokens, the first of which is single-character, . // then this function performs that operation, otherwise it returns `None`. 5,952 ( 0.00%) pub fn break_two_token_op(&self) -> Option<(TokenKind, TokenKind)> { 36,245 ( 0.00%) Some(match *self { . Le => (Lt, Eq), . EqEq => (Eq, Eq), . Ne => (Not, Eq), . Ge => (Gt, Eq), . AndAnd => (BinOp(And), BinOp(And)), . OrOr => (BinOp(Or), BinOp(Or)), . BinOp(Shl) => (Lt, Lt), . BinOp(Shr) => (Gt, Gt), -- line 271 ---------------------------------------- -- line 280 ---------------------------------------- . BinOpEq(Shl) => (Lt, Le), . BinOpEq(Shr) => (Gt, Ge), . DotDot => (Dot, Dot), . DotDotDot => (Dot, DotDot), . ModSep => (Colon, Colon), . RArrow => (BinOp(Minus), Gt), . LArrow => (Lt, BinOp(Minus)), . FatArrow => (Eq, Gt), 2,844 ( 0.00%) _ => return None, . }) 5,952 ( 0.00%) } . . /// Returns tokens that are likely to be typed accidentally instead of the current token. . /// Enables better error recovery when the wrong token is found. . pub fn similar_tokens(&self) -> Option> { . match *self { . Comma => Some(vec![Dot, Lt, Semi]), . Semi => Some(vec![Colon, Comma]), . FatArrow => Some(vec![Eq, RArrow]), . _ => None, . } . } . . pub fn should_end_const_arg(&self) -> bool { 766 ( 0.00%) matches!(self, Gt | Ge | BinOp(Shr) | BinOpEq(Shr)) 190 ( 0.00%) } . } . . impl Token { 679,965 ( 0.01%) pub fn new(kind: TokenKind, span: Span) -> Self { 2,058,259 ( 0.02%) Token { kind, span } 679,965 ( 0.01%) } . . /// Some token that will be thrown away later. 5,784 ( 0.00%) pub fn dummy() -> Self { . Token::new(TokenKind::Question, DUMMY_SP) 5,784 ( 0.00%) } . . /// Recovers a `Token` from an `Ident`. This creates a raw identifier if necessary. . pub fn from_ast_ident(ident: Ident) -> Self { 184 ( 0.00%) Token::new(Ident(ident.name, ident.is_raw_guess()), ident.span) . } . . /// Return this token by value and leave a dummy token in its place. 9,865 ( 0.00%) pub fn take(&mut self) -> Self { . mem::replace(self, Token::dummy()) 9,865 ( 0.00%) } . . /// For interpolated tokens, returns a span of the fragment to which the interpolated . /// token refers. For all other tokens this is just a regular span. . /// It is particularly important to use this for identifiers and lifetimes . /// for which spans affect name resolution and edition checks. . /// Note that keywords are also identifiers, so they should use this . /// if they keep spans or perform edition checks. . pub fn uninterpolated_span(&self) -> Span { 1,366 ( 0.00%) match &self.kind { 50 ( 0.00%) Interpolated(nt) => nt.span(), 658 ( 0.00%) _ => self.span, . } 658 ( 0.00%) } . . pub fn is_op(&self) -> bool { 29,595 ( 0.00%) !matches!( 9,865 ( 0.00%) self.kind, . OpenDelim(..) . | CloseDelim(..) . | Literal(..) . | DocComment(..) . | Ident(..) . | Lifetime(..) . | Interpolated(..) . | Eof . ) 9,865 ( 0.00%) } . . pub fn is_like_plus(&self) -> bool { 5,862 ( 0.00%) matches!(self.kind, BinOp(Plus) | BinOpEq(Plus)) 1,172 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of an expression. 159 ( 0.00%) pub fn can_begin_expr(&self) -> bool { 795 ( 0.00%) match self.uninterpolate().kind { 1,080 ( 0.00%) Ident(name, is_raw) => 360 ( 0.00%) ident_can_begin_expr(name, self.span, is_raw), // value name or keyword . OpenDelim(..) | // tuple, array or block . Literal(..) | // literal . Not | // operator not . BinOp(Minus) | // unary minus . BinOp(Star) | // dereference . BinOp(Or) | OrOr | // closure . BinOp(And) | // reference . AndAnd | // double reference -- line 371 ---------------------------------------- -- line 376 ---------------------------------------- . Lifetime(..) | // labeled loop . Pound => true, // expression attributes . Interpolated(ref nt) => matches!(**nt, NtLiteral(..) | . NtExpr(..) | . NtBlock(..) | . NtPath(..)), . _ => false, . } 318 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of a type. 1,100 ( 0.00%) pub fn can_begin_type(&self) -> bool { 1,411 ( 0.00%) match self.uninterpolate().kind { 1,197 ( 0.00%) Ident(name, is_raw) => 133 ( 0.00%) ident_can_begin_type(name, self.span, is_raw), // type name or keyword . OpenDelim(Paren) | // tuple . OpenDelim(Bracket) | // array . Not | // never . BinOp(Star) | // raw pointer . BinOp(And) | // reference . AndAnd | // double reference . Question | // maybe bound in trait object . Lifetime(..) | // lifetime bound in trait object . Lt | BinOp(Shl) | // associated path . ModSep => true, // global path . Interpolated(ref nt) => matches!(**nt, NtTy(..) | NtPath(..)), . _ => false, . } 1,650 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of a const param. . pub fn can_begin_const_arg(&self) -> bool { 995 ( 0.00%) match self.kind { . OpenDelim(Brace) => true, . Interpolated(ref nt) => matches!(**nt, NtExpr(..) | NtBlock(..) | NtLiteral(..)), 199 ( 0.00%) _ => self.can_begin_literal_maybe_minus(), . } . } . . /// Returns `true` if the token can appear at the start of a generic bound. . pub fn can_begin_bound(&self) -> bool { . self.is_path_start() . || self.is_lifetime() . || self.is_keyword(kw::For) -- line 419 ---------------------------------------- -- line 427 ---------------------------------------- . } . . /// Returns `true` if the token is any literal, a minus (which can prefix a literal, . /// for example a '-42', or one of the boolean idents). . /// . /// In other words, would this token be a valid start of `parse_literal_maybe_minus`? . /// . /// Keep this in sync with and `Lit::from_token`, excluding unary negation. 210 ( 0.00%) pub fn can_begin_literal_maybe_minus(&self) -> bool { 1,440 ( 0.00%) match self.uninterpolate().kind { . Literal(..) | BinOp(Minus) => true, 312 ( 0.00%) Ident(name, false) if name.is_bool_lit() => true, . Interpolated(ref nt) => match &**nt { . NtLiteral(_) => true, . NtExpr(e) => match &e.kind { . ast::ExprKind::Lit(_) => true, . ast::ExprKind::Unary(ast::UnOp::Neg, e) => { . matches!(&e.kind, ast::ExprKind::Lit(_)) . } . _ => false, . }, . _ => false, . }, . _ => false, . } 420 ( 0.00%) } . . // A convenience function for matching on identifiers during parsing. . // Turns interpolated identifier (`$i: ident`) or lifetime (`$l: lifetime`) token . // into the regular identifier or lifetime token it refers to, . // otherwise returns the original token. 7,797 ( 0.00%) pub fn uninterpolate(&self) -> Cow<'_, Token> { 5,600,487 ( 0.06%) match &self.kind { 19,952 ( 0.00%) Interpolated(nt) => match **nt { 4,919 ( 0.00%) NtIdent(ident, is_raw) => { 12,312 ( 0.00%) Cow::Owned(Token::new(Ident(ident.name, is_raw), ident.span)) . } . NtLifetime(ident) => Cow::Owned(Token::new(Lifetime(ident.name), ident.span)), . _ => Cow::Borrowed(self), . }, . _ => Cow::Borrowed(self), . } 7,797 ( 0.00%) } . . /// Returns an identifier if this token is an identifier. 1,387,094 ( 0.02%) pub fn ident(&self) -> Option<(Ident, /* is_raw */ bool)> { . let token = self.uninterpolate(); 2,865,822 ( 0.03%) match token.kind { 4,499,760 ( 0.05%) Ident(name, is_raw) => Some((Ident::new(name, token.span), is_raw)), . _ => None, . } 8,357,624 ( 0.10%) } . . /// Returns a lifetime identifier if this token is a lifetime. 1,336,722 ( 0.02%) pub fn lifetime(&self) -> Option { . let token = self.uninterpolate(); 2,674,124 ( 0.03%) match token.kind { 4,578 ( 0.00%) Lifetime(name) => Some(Ident::new(name, token.span)), . _ => None, . } 9,357,054 ( 0.11%) } . . /// Returns `true` if the token is an identifier. . pub fn is_ident(&self) -> bool { . self.ident().is_some() 4,150 ( 0.00%) } . . /// Returns `true` if the token is a lifetime. 340 ( 0.00%) pub fn is_lifetime(&self) -> bool { . self.lifetime().is_some() 680 ( 0.00%) } . . /// Returns `true` if the token is an identifier whose name is the given . /// string slice. 2,252 ( 0.00%) pub fn is_ident_named(&self, name: Symbol) -> bool { . self.ident().map_or(false, |(ident, _)| ident.name == name) 4,504 ( 0.00%) } . . /// Returns `true` if the token is an interpolated path. . fn is_path(&self) -> bool { 14,348 ( 0.00%) if let Interpolated(ref nt) = self.kind { 88 ( 0.00%) if let NtPath(..) = **nt { . return true; . } . } . false . } . . /// Would `maybe_whole_expr` in `parser.rs` return `Ok(..)`? . /// That is, is this a pre-parsed expression dropped into the token stream . /// (which happens while parsing the result of macro expansion)? . pub fn is_whole_expr(&self) -> bool { 10 ( 0.00%) if let Interpolated(ref nt) = self.kind { . if let NtExpr(_) | NtLiteral(_) | NtPath(_) | NtIdent(..) | NtBlock(_) = **nt { . return true; . } . } . . false 5 ( 0.00%) } . . // Is the token an interpolated block (`$b:block`)? . pub fn is_whole_block(&self) -> bool { 94 ( 0.00%) if let Interpolated(ref nt) = self.kind { . if let NtBlock(..) = **nt { . return true; . } . } . false 47 ( 0.00%) } . . /// Returns `true` if the token is either the `mut` or `const` keyword. . pub fn is_mutability(&self) -> bool { . self.is_keyword(kw::Mut) || self.is_keyword(kw::Const) . } . 546 ( 0.00%) pub fn is_qpath_start(&self) -> bool { 7,720 ( 0.00%) self == &Lt || self == &BinOp(Shl) . } . 26,776 ( 0.00%) pub fn is_path_start(&self) -> bool { 27,082 ( 0.00%) self == &ModSep . || self.is_qpath_start() . || self.is_path() . || self.is_path_segment_keyword() 3,251 ( 0.00%) || self.is_ident() && !self.is_reserved_ident() 33,470 ( 0.00%) } . . /// Returns `true` if the token is a given keyword, `kw`. 30,118 ( 0.00%) pub fn is_keyword(&self, kw: Symbol) -> bool { . self.is_non_raw_ident_where(|id| id.name == kw) 60,236 ( 0.00%) } . 389 ( 0.00%) pub fn is_path_segment_keyword(&self) -> bool { . self.is_non_raw_ident_where(Ident::is_path_segment_keyword) . } . . // Returns true for reserved identifiers used internally for elided lifetimes, . // unnamed method parameters, crate root module, error recovery etc. 40 ( 0.00%) pub fn is_special_ident(&self) -> bool { . self.is_non_raw_ident_where(Ident::is_special) . } . . /// Returns `true` if the token is a keyword used in the language. 40 ( 0.00%) pub fn is_used_keyword(&self) -> bool { . self.is_non_raw_ident_where(Ident::is_used_keyword) . } . . /// Returns `true` if the token is a keyword reserved for possible future use. 40 ( 0.00%) pub fn is_unused_keyword(&self) -> bool { . self.is_non_raw_ident_where(Ident::is_unused_keyword) . } . . /// Returns `true` if the token is either a special identifier or a keyword. . pub fn is_reserved_ident(&self) -> bool { . self.is_non_raw_ident_where(Ident::is_reserved) . } . . /// Returns `true` if the token is the identifier `true` or `false`. 389 ( 0.00%) pub fn is_bool_lit(&self) -> bool { 778 ( 0.00%) self.is_non_raw_ident_where(|id| id.name.is_bool_lit()) . } . . pub fn is_numeric_lit(&self) -> bool { . matches!( . self.kind, . Literal(Lit { kind: LitKind::Integer, .. }) | Literal(Lit { kind: LitKind::Float, .. }) . ) . } . . /// Returns `true` if the token is a non-raw identifier for which `pred` holds. . pub fn is_non_raw_ident_where(&self, pred: impl FnOnce(Ident) -> bool) -> bool { 282,346 ( 0.00%) match self.ident() { 2,946 ( 0.00%) Some((id, false)) => pred(id), . _ => false, . } . } . 32,470 ( 0.00%) pub fn glue(&self, joint: &Token) -> Option { 16,235 ( 0.00%) let kind = match self.kind { 1,202 ( 0.00%) Eq => match joint.kind { . Eq => EqEq, . Gt => FatArrow, . _ => return None, . }, 3 ( 0.00%) Lt => match joint.kind { . Eq => Le, . Lt => BinOp(Shl), . Le => BinOpEq(Shl), . BinOp(Minus) => LArrow, . _ => return None, . }, 252 ( 0.00%) Gt => match joint.kind { . Eq => Ge, . Gt => BinOp(Shr), . Ge => BinOpEq(Shr), . _ => return None, . }, 4 ( 0.00%) Not => match joint.kind { . Eq => Ne, . _ => return None, . }, 601 ( 0.00%) BinOp(op) => match joint.kind { . Eq => BinOpEq(op), 9 ( 0.00%) BinOp(And) if op == And => AndAnd, 8 ( 0.00%) BinOp(Or) if op == Or => OrOr, 54 ( 0.00%) Gt if op == Minus => RArrow, . _ => return None, . }, 169 ( 0.00%) Dot => match joint.kind { . Dot => DotDot, . DotDot => DotDotDot, . _ => return None, . }, 18 ( 0.00%) DotDot => match joint.kind { . Dot => DotDotDot, . Eq => DotDotEq, . _ => return None, . }, 1,386 ( 0.00%) Colon => match joint.kind { . Colon => ModSep, . _ => return None, . }, . SingleQuote => match joint.kind { . Ident(name, false) => Lifetime(Symbol::intern(&format!("'{}", name))), . _ => return None, . }, . . Le | EqEq | Ne | Ge | AndAnd | OrOr | Tilde | BinOpEq(..) | At | DotDotDot . | DotDotEq | Comma | Semi | ModSep | RArrow | LArrow | FatArrow | Pound | Dollar . | Question | OpenDelim(..) | CloseDelim(..) | Literal(..) | Ident(..) . | Lifetime(..) | Interpolated(..) | DocComment(..) | Eof => return None, . }; . 14,170 ( 0.00%) Some(Token::new(kind, self.span.to(joint.span))) 29,223 ( 0.00%) } . } . . impl PartialEq for Token { . fn eq(&self, rhs: &TokenKind) -> bool { 909,999 ( 0.01%) self.kind == *rhs . } . } . . #[derive(Clone, Encodable, Decodable)] . /// For interpolation during macro expansion. . pub enum Nonterminal { . NtItem(P), . NtBlock(P), -- line 675 ---------------------------------------- -- line 711 ---------------------------------------- . Path, . Vis, . TT, . } . . impl NonterminalKind { . /// The `edition` closure is used to get the edition for the given symbol. Doing . /// `span.edition()` is expensive, so we do it lazily. 312 ( 0.00%) pub fn from_symbol( . symbol: Symbol, . edition: impl FnOnce() -> Edition, . ) -> Option { 742 ( 0.00%) Some(match symbol { . sym::item => NonterminalKind::Item, . sym::block => NonterminalKind::Block, . sym::stmt => NonterminalKind::Stmt, . sym::pat => match edition() { . Edition::Edition2015 | Edition::Edition2018 => { . NonterminalKind::PatParam { inferred: true } . } . Edition::Edition2021 => NonterminalKind::PatWithOr, -- line 731 ---------------------------------------- -- line 737 ---------------------------------------- . sym::lifetime => NonterminalKind::Lifetime, . sym::literal => NonterminalKind::Literal, . sym::meta => NonterminalKind::Meta, . sym::path => NonterminalKind::Path, . sym::vis => NonterminalKind::Vis, . sym::tt => NonterminalKind::TT, . _ => return None, . }) 312 ( 0.00%) } . fn symbol(self) -> Symbol { . match self { . NonterminalKind::Item => sym::item, . NonterminalKind::Block => sym::block, . NonterminalKind::Stmt => sym::stmt, . NonterminalKind::PatParam { inferred: false } => sym::pat_param, . NonterminalKind::PatParam { inferred: true } | NonterminalKind::PatWithOr => sym::pat, . NonterminalKind::Expr => sym::expr, -- line 753 ---------------------------------------- -- line 765 ---------------------------------------- . . impl fmt::Display for NonterminalKind { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . write!(f, "{}", self.symbol()) . } . } . . impl Nonterminal { 25 ( 0.00%) pub fn span(&self) -> Span { 125 ( 0.00%) match self { . NtItem(item) => item.span, . NtBlock(block) => block.span, . NtStmt(stmt) => stmt.span, . NtPat(pat) => pat.span, . NtExpr(expr) | NtLiteral(expr) => expr.span, . NtTy(ty) => ty.span, 25 ( 0.00%) NtIdent(ident, _) | NtLifetime(ident) => ident.span, . NtMeta(attr_item) => attr_item.span(), . NtPath(path) => path.span, . NtVis(vis) => vis.span, . NtTT(tt) => tt.span(), . } 50 ( 0.00%) } . } . . impl PartialEq for Nonterminal { . fn eq(&self, rhs: &Self) -> bool { . match (self, rhs) { . (NtIdent(ident_lhs, is_raw_lhs), NtIdent(ident_rhs, is_raw_rhs)) => { . ident_lhs == ident_rhs && is_raw_lhs == is_raw_rhs . } -- line 795 ---------------------------------------- 25,181,019 ( 0.29%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe.rs -------------------------------------------------------------------------------- Ir -- line 23 ---------------------------------------- . struct Delimited { . delim: token::DelimToken, . tts: Vec, . } . . impl Delimited { . /// Returns a `self::TokenTree` with a `Span` corresponding to the opening delimiter. . fn open_tt(&self, span: DelimSpan) -> TokenTree { 24,292 ( 0.00%) TokenTree::token(token::OpenDelim(self.delim), span.open) . } . . /// Returns a `self::TokenTree` with a `Span` corresponding to the closing delimiter. . fn close_tt(&self, span: DelimSpan) -> TokenTree { 2,617,508 ( 0.03%) TokenTree::token(token::CloseDelim(self.delim), span.close) . } . } . . #[derive(Clone, PartialEq, Encodable, Decodable, Debug)] . struct SequenceRepetition { . /// The sequence of token trees . tts: Vec, . /// The optional separator . separator: Option, . /// Whether the sequence can be repeated zero (*), or one or more times (+) . kleene: KleeneToken, . /// The number of `Match`s that appear in the sequence (and subsequences) . num_captures: usize, . } . 224 ( 0.00%) #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)] . struct KleeneToken { . span: Span, . op: KleeneOp, . } . . impl KleeneToken { . fn new(op: KleeneOp, span: Span) -> KleeneToken { . KleeneToken { span, op } 12 ( 0.00%) } . } . . /// A Kleene-style [repetition operator](https://en.wikipedia.org/wiki/Kleene_star) . /// for token sequences. 377 ( 0.00%) #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)] . enum KleeneOp { . /// Kleene star (`*`) for zero or more repetitions . ZeroOrMore, . /// Kleene plus (`+`) for one or more repetitions . OneOrMore, . /// Kleene optional (`?`) for zero or one repetitions . ZeroOrOne, . } . . /// Similar to `tokenstream::TokenTree`, except that `$i`, `$i:ident`, and `$(...)` . /// are "first-class" token trees. Useful for parsing macros. 20,486,153 ( 0.24%) #[derive(Debug, Clone, PartialEq, Encodable, Decodable)] . enum TokenTree { 22,184 ( 0.00%) Token(Token), 668,349 ( 0.01%) Delimited(DelimSpan, Lrc), . /// A kleene-style repetition sequence 9,780 ( 0.00%) Sequence(DelimSpan, Lrc), . /// e.g., `$var` . MetaVar(Span, Ident), . /// e.g., `$var:expr`. This is only used in the left hand side of MBE macros. 1,317,024 ( 0.02%) MetaVarDecl(Span, Ident /* name to bind */, Option), . } . . impl TokenTree { . /// Return the number of tokens in the tree. . fn len(&self) -> usize { 14,628,901 ( 0.17%) match *self { 4,038,459 ( 0.05%) TokenTree::Delimited(_, ref delimed) => match delimed.delim { . token::NoDelim => delimed.tts.len(), 2,692,306 ( 0.03%) _ => delimed.tts.len() + 2, . }, 6,581,780 ( 0.08%) TokenTree::Sequence(_, ref seq) => seq.tts.len(), . _ => 0, . } . } . . /// Returns `true` if the given token tree is delimited. . fn is_delimited(&self) -> bool { . matches!(*self, TokenTree::Delimited(..)) . } -- line 106 ---------------------------------------- -- line 109 ---------------------------------------- . fn is_token(&self, expected_kind: &TokenKind) -> bool { . match self { . TokenTree::Token(Token { kind: actual_kind, .. }) => actual_kind == expected_kind, . _ => false, . } . } . . /// Gets the `index`-th sub-token-tree. This only makes sense for delimited trees and sequences. 5,957,550 ( 0.07%) fn get_tt(&self, index: usize) -> TokenTree { 8,590,132 ( 0.10%) match (self, index) { 2,008,677 ( 0.02%) (&TokenTree::Delimited(_, ref delimed), _) if delimed.delim == token::NoDelim => { . delimed.tts[index].clone() . } . (&TokenTree::Delimited(span, ref delimed), _) => { 1,339,118 ( 0.02%) if index == 0 { . return delimed.open_tt(span); . } 3,968,994 ( 0.05%) if index == delimed.tts.len() + 1 { . return delimed.close_tt(span); . } 7,150 ( 0.00%) delimed.tts[index - 1].clone() . } 1,316,291 ( 0.02%) (&TokenTree::Sequence(_, ref seq), _) => seq.tts[index].clone(), . _ => panic!("Cannot expand a token tree"), . } 7,943,400 ( 0.09%) } . . /// Retrieves the `TokenTree`'s span. . fn span(&self) -> Span { 26,242 ( 0.00%) match *self { . TokenTree::Token(Token { span, .. }) . | TokenTree::MetaVar(span, _) . | TokenTree::MetaVarDecl(span, _, _) => span, 3,560 ( 0.00%) TokenTree::Delimited(span, _) | TokenTree::Sequence(span, _) => span.entire(), . } . } . . fn token(kind: TokenKind, span: Span) -> TokenTree { 815 ( 0.00%) TokenTree::Token(Token::new(kind, span)) . } . } 11,310,057 ( 0.13%) -------------------------------------------------------------------------------- -- 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. 26,831,996 ( 0.31%) #[derive(Debug, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)] . pub enum TokenTree { . /// A single token. 10,354,124 ( 0.12%) Token(Token), . /// A delimited sequence of token trees. 730,992 ( 0.01%) 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 { 8,786 ( 0.00%) match self { 3,263 ( 0.00%) TokenTree::Token(token) => token.span, 5,012 ( 0.00%) TokenTree::Delimited(sp, ..) => sp.entire(), . } 3,141 ( 0.00%) } . . /// Modify the `TokenTree`'s span in-place. . pub fn set_span(&mut self, span: Span) { 8,786 ( 0.00%) match self { 3,141 ( 0.00%) TokenTree::Token(token) => token.span = span, 2,504 ( 0.00%) TokenTree::Delimited(dspan, ..) => *dspan = DelimSpan::from_single(span), . } 4,393 ( 0.00%) } . 729 ( 0.00%) pub fn token(kind: TokenKind, span: Span) -> TokenTree { 2,841,288 ( 0.03%) TokenTree::Token(Token::new(kind, span)) 729 ( 0.00%) } . . /// Returns the opening delimiter as a token tree. 352,126 ( 0.00%) pub fn open_tt(span: DelimSpan, delim: DelimToken) -> TokenTree { 1,056,378 ( 0.01%) TokenTree::token(token::OpenDelim(delim), span.open) 352,126 ( 0.00%) } . . /// Returns the closing delimiter as a token tree. 357,467 ( 0.00%) pub fn close_tt(span: DelimSpan, delim: DelimToken) -> TokenTree { 1,072,401 ( 0.01%) TokenTree::token(token::CloseDelim(delim), span.close) 357,467 ( 0.00%) } . 1,242 ( 0.00%) pub fn uninterpolate(self) -> TokenTree { 828 ( 0.00%) match self { 3,726 ( 0.00%) TokenTree::Token(token) => TokenTree::Token(token.uninterpolate().into_owned()), . tt => tt, . } 1,656 ( 0.00%) } . } . . impl HashStable for TokenStream . where . CTX: crate::HashStableContext, . { 6,795 ( 0.00%) fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) { 42,746 ( 0.00%) for sub_tt in self.trees() { . sub_tt.hash_stable(hcx, hasher); . } 6,040 ( 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 { 216 ( 0.00%) pub fn new(inner: impl CreateTokenStream + 'static) -> LazyTokenStream { . LazyTokenStream(Lrc::new(Box::new(inner))) 216 ( 0.00%) } . . pub fn create_token_stream(&self) -> AttrAnnotatedTokenStream { 4 ( 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 { 16,194 ( 0.00%) pub fn new(tokens: Vec<(AttrAnnotatedTokenTree, Spacing)>) -> AttrAnnotatedTokenStream { . AttrAnnotatedTokenStream(Lrc::new(tokens)) 16,194 ( 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. 1 ( 0.00%) pub fn to_tokenstream(&self) -> TokenStream { 1 ( 0.00%) let trees: Vec<_> = self . .0 . .iter() 3 ( 0.00%) .flat_map(|tree| match &tree.0 { 2 ( 0.00%) AttrAnnotatedTokenTree::Token(inner) => { 5 ( 0.00%) smallvec![(TokenTree::Token(inner.clone()), tree.1)].into_iter() . } . AttrAnnotatedTokenTree::Delimited(span, delim, stream) => smallvec![( . TokenTree::Delimited(*span, *delim, stream.to_tokenstream()), . tree.1, . )] . .into_iter(), . AttrAnnotatedTokenTree::Attributes(data) => { . let mut outer_attrs = Vec::new(); -- line 219 ---------------------------------------- -- line 279 ---------------------------------------- . flat.extend(attr.tokens().to_tokenstream().0.clone().iter().cloned()); . } . flat.extend(target_tokens); . flat.into_iter() . } . }) . .collect(); . TokenStream::new(trees) 2 ( 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); . 2,895,903 ( 0.03%) #[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 371 ---------------------------------------- . impl From<(AttrAnnotatedTokenTree, Spacing)> for AttrAnnotatedTokenStream { . fn from((tree, spacing): (AttrAnnotatedTokenTree, Spacing)) -> AttrAnnotatedTokenStream { . AttrAnnotatedTokenStream::new(vec![(tree, spacing)]) . } . } . . impl From for TokenStream { . fn from(tree: TokenTree) -> TokenStream { 450 ( 0.00%) TokenStream::new(vec![(tree, Spacing::Alone)]) . } . } . . impl From for TreeAndSpacing { . fn from(tree: TokenTree) -> TreeAndSpacing { 822,969 ( 0.01%) (tree, Spacing::Alone) . } . } . . impl iter::FromIterator for TokenStream { . fn from_iter>(iter: I) -> Self { . TokenStream::new(iter.into_iter().map(Into::into).collect::>()) . } . } -- line 393 ---------------------------------------- -- line 401 ---------------------------------------- . } . . impl TokenStream { . pub fn new(streams: Vec) -> TokenStream { . TokenStream(Lrc::new(streams)) . } . . pub fn is_empty(&self) -> bool { 1,753 ( 0.00%) self.0.is_empty() 1,753 ( 0.00%) } . . pub fn len(&self) -> usize { 3,609,052 ( 0.04%) self.0.len() 930 ( 0.00%) } . . pub fn from_streams(mut streams: SmallVec<[TokenStream; 2]>) -> TokenStream { . 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 -- line 422 ---------------------------------------- -- line 448 ---------------------------------------- . . // Create the final `TokenStream`. . TokenStream(first_stream_lrc) . } . } . } . . pub fn trees(&self) -> Cursor { 1,947 ( 0.00%) self.clone().into_trees() 3,894 ( 0.00%) } . 354,645 ( 0.00%) pub fn into_trees(self) -> Cursor { . Cursor::new(self) 709,290 ( 0.01%) } . . /// 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 { 904 ( 0.00%) TokenStream(Lrc::new( . self.0 . .iter() . .enumerate() 26,358 ( 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]>); -- line 488 ---------------------------------------- -- line 572 ---------------------------------------- . pub struct Cursor { . pub stream: TokenStream, . index: usize, . } . . impl Iterator for Cursor { . type Item = TokenTree; . 39,747 ( 0.00%) fn next(&mut self) -> Option { 69,970 ( 0.00%) self.next_with_spacing().map(|(tree, _)| tree) 52,996 ( 0.00%) } . } . . impl Cursor { . fn new(stream: TokenStream) -> Self { . Cursor { stream, index: 0 } . } . 17,969,715 ( 0.21%) pub fn next_with_spacing(&mut self) -> Option { 10,821,576 ( 0.12%) if self.index < self.stream.len() { 5,774,452 ( 0.07%) self.index += 1; 20,135,647 ( 0.23%) Some(self.stream.0[self.index - 1].clone()) . } else { 1,434,844 ( 0.02%) None . } 21,563,658 ( 0.25%) } . . 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; . } . 51,538 ( 0.00%) pub fn look_ahead(&self, n: usize) -> Option<&TokenTree> { 103,076 ( 0.00%) self.stream.0[self.index..].get(n).map(|(tree, _)| tree) 103,076 ( 0.00%) } . } . 1,424,820 ( 0.02%) #[derive(Debug, Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)] . pub struct DelimSpan { . pub open: Span, . pub close: Span, . } . . impl DelimSpan { 5 ( 0.00%) pub fn from_single(sp: Span) -> Self { . DelimSpan { open: sp, close: sp } 10 ( 0.00%) } . 3,506 ( 0.00%) pub fn from_pair(open: Span, close: Span) -> Self { . DelimSpan { open, close } 1,753 ( 0.00%) } . . pub fn dummy() -> Self { . Self::from_single(DUMMY_SP) 8,658 ( 0.00%) } . 39,296 ( 0.00%) pub fn entire(self) -> Span { . self.open.with_hi(self.close.hi()) 29,472 ( 0.00%) } . } 34,225 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs -------------------------------------------------------------------------------- Ir -- line 70 ---------------------------------------- . . impl<'a, T> $name<'a, T> { . // Helper function for creating a slice from the iterator. . #[inline(always)] . fn make_slice(&self) -> &'a [T] { . // SAFETY: the iterator was created from a slice with pointer . // `self.ptr` and length `len!(self)`. This guarantees that all . // the prerequisites for `from_raw_parts` are fulfilled. 32,684 ( 0.00%) unsafe { from_raw_parts(self.ptr.as_ptr(), len!(self)) } . } . . // Helper function for moving the start of the iterator forwards by `offset` elements, . // returning the old start. . // Unsafe because the offset must not exceed `self.len()`. . #[inline(always)] . unsafe fn post_inc_start(&mut self, offset: isize) -> * $raw_mut T { . if mem::size_of::() == 0 { . zst_shrink!(self, offset); . self.ptr.as_ptr() . } else { . let old = self.ptr.as_ptr(); . // SAFETY: the caller guarantees that `offset` doesn't exceed `self.len()`, . // so this new pointer is inside `self` and thus guaranteed to be non-null. 334,907 ( 0.00%) self.ptr = unsafe { NonNull::new_unchecked(self.ptr.as_ptr().offset(offset)) }; . old . } . } . . // Helper function for moving the end of the iterator backwards by `offset` elements, . // returning the new end. . // Unsafe because the offset must not exceed `self.len()`. . #[inline(always)] -- line 101 ---------------------------------------- -- line 102 ---------------------------------------- . unsafe fn pre_dec_end(&mut self, offset: isize) -> * $raw_mut T { . if mem::size_of::() == 0 { . zst_shrink!(self, offset); . self.ptr.as_ptr() . } else { . // SAFETY: the caller guarantees that `offset` doesn't exceed `self.len()`, . // which is guaranteed to not overflow an `isize`. Also, the resulting pointer . // is in bounds of `slice`, which fulfills the other requirements for `offset`. 2,485 ( 0.00%) self.end = unsafe { self.end.offset(-offset) }; . self.end . } . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl ExactSizeIterator for $name<'_, T> { . #[inline(always)] . fn len(&self) -> usize { 87,012 ( 0.00%) len!(self) . } . . #[inline(always)] . fn is_empty(&self) -> bool { . is_empty!(self) . } . } . -- line 128 ---------------------------------------- -- line 134 ---------------------------------------- . fn next(&mut self) -> Option<$elem> { . // could be implemented with slices, but this avoids bounds checks . . // SAFETY: `assume` calls are safe since a slice's start pointer . // must be non-null, and slices over non-ZSTs must also have a . // non-null end pointer. The call to `next_unchecked!` is safe . // since we check if the iterator is empty first. . unsafe { 151,423 ( 0.00%) assume(!self.ptr.as_ptr().is_null()); . if mem::size_of::() != 0 { 33,185 ( 0.00%) assume(!self.end.is_null()); . } 53,284,299 ( 0.61%) if is_empty!(self) { . None . } else { 4 ( 0.00%) Some(next_unchecked!(self)) . } . } . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 7,544,263 ( 0.09%) let exact = len!(self); . (exact, Some(exact)) . } . . #[inline] . fn count(self) -> usize { . len!(self) . } . . #[inline] . fn nth(&mut self, n: usize) -> Option<$elem> { 26,683 ( 0.00%) if n >= len!(self) { . // This iterator is now empty. . if mem::size_of::() == 0 { . // We have to do it this way as `ptr` may never be 0, but `end` . // could be (due to wrapping). . self.end = self.ptr.as_ptr(); . } else { . // SAFETY: end can't be 0 if T isn't ZST because ptr isn't 0 and end >= ptr . unsafe { -- line 175 ---------------------------------------- -- line 203 ---------------------------------------- . // faster to compile. . #[inline] . fn for_each(mut self, mut f: F) . where . Self: Sized, . F: FnMut(Self::Item), . { . while let Some(x) = self.next() { 1,914 ( 0.00%) f(x); . } . } . . // We override the default implementation, which uses `try_fold`, . // because this simple implementation generates less LLVM IR and is . // faster to compile. . #[inline] . fn all(&mut self, mut f: F) -> bool . where . Self: Sized, . F: FnMut(Self::Item) -> bool, . { 1,014 ( 0.00%) while let Some(x) = self.next() { 96,586 ( 0.00%) if !f(x) { . return false; . } . } . true . } . . // We override the default implementation, which uses `try_fold`, . // because this simple implementation generates less LLVM IR and is . // faster to compile. . #[inline] . fn any(&mut self, mut f: F) -> bool . where . Self: Sized, . F: FnMut(Self::Item) -> bool, . { 500,819 ( 0.01%) while let Some(x) = self.next() { 226,072 ( 0.00%) if f(x) { . return true; . } . } . false . } . . // We override the default implementation, which uses `try_fold`, . // because this simple implementation generates less LLVM IR and is . // faster to compile. . #[inline] . fn find

(&mut self, mut predicate: P) -> Option . where . Self: Sized, . P: FnMut(&Self::Item) -> bool, . { 143,403 ( 0.00%) while let Some(x) = self.next() { 452,304 ( 0.01%) if predicate(&x) { . return Some(x); . } . } . None 51,616 ( 0.00%) } . . // We override the default implementation, which uses `try_fold`, . // because this simple implementation generates less LLVM IR and is . // faster to compile. . #[inline] . fn find_map(&mut self, mut f: F) -> Option . where . Self: Sized, . F: FnMut(Self::Item) -> Option, . { 14,386 ( 0.00%) while let Some(x) = self.next() { 104,739 ( 0.00%) if let Some(y) = f(x) { 10,787 ( 0.00%) return Some(y); . } . } . None 2,115 ( 0.00%) } . . // We override the default implementation, which uses `try_fold`, . // because this simple implementation generates less LLVM IR and is . // faster to compile. Also, the `assume` avoids a bounds check. . #[inline] . #[rustc_inherit_overflow_checks] . fn position

(&mut self, mut predicate: P) -> Option where . Self: Sized, . P: FnMut(Self::Item) -> bool, . { . let n = len!(self); . let mut i = 0; . while let Some(x) = self.next() { 105,061 ( 0.00%) if predicate(x) { . // SAFETY: we are guaranteed to be in bounds by the loop invariant: . // when `i >= n`, `self.next()` returns `None` and the loop breaks. . unsafe { assume(i < n) }; . return Some(i); . } . i += 1; . } . None -- line 303 ---------------------------------------- -- line 308 ---------------------------------------- . // faster to compile. Also, the `assume` avoids a bounds check. . #[inline] . fn rposition

(&mut self, mut predicate: P) -> Option where . P: FnMut(Self::Item) -> bool, . Self: Sized + ExactSizeIterator + DoubleEndedIterator . { . let n = len!(self); . let mut i = n; 10,927 ( 0.00%) while let Some(x) = self.next_back() { 158,177 ( 0.00%) i -= 1; 128,918 ( 0.00%) if predicate(x) { . // SAFETY: `i` must be lower than `n` since it starts at `n` . // and is only decreasing. . unsafe { assume(i < n) }; . return Some(i); . } . } . None . } -- line 326 ---------------------------------------- -- line 332 ---------------------------------------- . // the returned references is guaranteed to refer to an element . // of the slice and thus guaranteed to be valid. . // . // Also note that the caller also guarantees that we're never . // called with the same index again, and that no other methods . // that will access this subslice are called, so it is valid . // for the returned reference to be mutable in the case of . // `IterMut` 43,921 ( 0.00%) unsafe { & $( $mut_ )? * self.ptr.as_ptr().add(idx) } . } . . $($extra)* . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl<'a, T> DoubleEndedIterator for $name<'a, T> { . #[inline] -- line 348 ---------------------------------------- -- line 349 ---------------------------------------- . fn next_back(&mut self) -> Option<$elem> { . // could be implemented with slices, but this avoids bounds checks . . // SAFETY: `assume` calls are safe since a slice's start pointer must be non-null, . // and slices over non-ZSTs must also have a non-null end pointer. . // The call to `next_back_unchecked!` is safe since we check if the iterator is . // empty first. . unsafe { 4,024 ( 0.00%) assume(!self.ptr.as_ptr().is_null()); . if mem::size_of::() != 0 { 4,045 ( 0.00%) assume(!self.end.is_null()); . } 848,130 ( 0.01%) if is_empty!(self) { . None . } else { . Some(next_back_unchecked!(self)) . } . } . } . . #[inline] -- line 369 ---------------------------------------- 7,292,507 ( 0.08%) -------------------------------------------------------------------------------- -- 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 . // . 14,077,652 ( 0.16%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 10,558,236 ( 0.12%) 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. 90,104 ( 0.00%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 135,156 ( 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) { 3,541,928 ( 0.04%) libc::free(ptr as *mut libc::c_void) . } . . #[inline] . unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { 491,964 ( 0.01%) if layout.align() <= MIN_ALIGN && layout.align() <= new_size { 983,928 ( 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/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs -------------------------------------------------------------------------------- Ir -- line 294 ---------------------------------------- . #[allow(deprecated)] . impl From for CollectionAllocErr { . fn from(_: LayoutErr) -> Self { . CollectionAllocErr::CapacityOverflow . } . } . . fn infallible(result: Result) -> T { 3,060,409 ( 0.04%) match result { . Ok(x) => x, . Err(CollectionAllocErr::CapacityOverflow) => panic!("capacity overflow"), . Err(CollectionAllocErr::AllocErr { layout }) => alloc::alloc::handle_alloc_error(layout), . } . } . . /// FIXME: use `Layout::array` when we require a Rust version where it’s stable . /// https://github.com/rust-lang/rust/issues/55724 -- line 310 ---------------------------------------- -- 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 { 30,668 ( 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) { 294,049 ( 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::() . ); 4,492,265 ( 0.05%) 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 579 ---------------------------------------- . /// let v: SmallVec<[u8; 3]> = SmallVec::with_capacity(100); . /// . /// assert!(v.is_empty()); . /// assert!(v.capacity() >= 100); . /// ``` . #[inline] . pub fn with_capacity(n: usize) -> Self { . let mut v = SmallVec::new(); 4 ( 0.00%) v.reserve_exact(n); . v . } . . /// Construct a new `SmallVec` from a `Vec`. . /// . /// Elements will be copied to the inline buffer if vec.capacity() <= Self::inline_capacity(). . /// . /// ```rust -- line 595 ---------------------------------------- -- 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 { 1,356 ( 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); . 2,139 ( 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(), 22,449 ( 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 { 29,570 ( 0.00%) assert!(len <= A::size()); 88,710 ( 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 { 14,785 ( 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(); 69,808 ( 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 { 60 ( 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 { 2,085,285 ( 0.02%) 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 { 8,272,357 ( 0.10%) 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 { 84,769,604 ( 0.97%) if self.spilled() { 37,352 ( 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 { 46,163,312 ( 0.53%) 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. . /// -- line 784 ---------------------------------------- -- line 821 ---------------------------------------- . iter: range_slice.iter(), . vec: NonNull::from(self), . } . } . } . . /// Append an item to the vector. . #[inline] 39,430 ( 0.00%) pub fn push(&mut self, value: A::Item) { . unsafe { . let (mut ptr, mut len, cap) = self.triple_mut(); 13,295,774 ( 0.15%) if *len == cap { 2,317 ( 0.00%) self.reserve(1); 61,066 ( 0.00%) let &mut (heap_ptr, ref mut heap_len) = self.data.heap_mut(); . ptr = heap_ptr; . len = heap_len; . } 83,364 ( 0.00%) ptr::write(ptr.add(*len), value); 16,601,566 ( 0.19%) *len += 1; . } 31,544 ( 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(); 7,061,742 ( 0.08%) if *len_ptr == 0 { . return None; . } 2,071,386 ( 0.02%) let last_index = *len_ptr - 1; 2,725,870 ( 0.03%) *len_ptr = last_index; 42,294 ( 0.00%) Some(ptr::read(ptr.add(last_index))) . } 15 ( 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 5,269 ( 0.00%) pub fn try_grow(&mut self, new_cap: usize) -> Result<(), CollectionAllocErr> { . unsafe { 131 ( 0.00%) let (ptr, &mut len, cap) = self.triple_mut(); . let unspilled = !self.spilled(); 104,420 ( 0.00%) assert!(new_cap >= len); 104,420 ( 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); 104,420 ( 0.00%) } else if new_cap != cap { 102,335 ( 0.00%) let layout = layout_array::(new_cap)?; . debug_assert!(layout.size() > 0); . let new_alloc; 52,210 ( 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`. 54,193 ( 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(); . } 104,420 ( 0.00%) self.data = SmallVecData::from_heap(new_alloc, len); 153,004 ( 0.00%) self.capacity = new_cap; . } . Ok(()) . } 5,400 ( 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] 288,224 ( 0.00%) pub fn reserve(&mut self, additional: usize) { 3,163,079 ( 0.04%) infallible(self.try_reserve(additional)) 325,616 ( 0.00%) } . . /// Reserve capacity for `additional` more elements to be inserted. . /// . /// May reserve more space to avoid frequent reallocations. 12,259,432 ( 0.14%) 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() 2,484 ( 0.00%) let (_, &mut len, cap) = self.triple_mut(); 8,131,828 ( 0.09%) 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)?; 653 ( 0.00%) self.try_grow(new_cap) 13,769,097 ( 0.16%) } . . /// Reserve the minimum capacity for `additional` more elements to be inserted. . /// . /// Panics if the new capacity overflows `usize`. 4 ( 0.00%) pub fn reserve_exact(&mut self, additional: usize) { . infallible(self.try_reserve_exact(additional)) 4 ( 0.00%) } . . /// 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(); 89,599 ( 0.00%) if cap - len >= additional { . return Ok(()); . } . let new_cap = len . .checked_add(additional) . .ok_or(CollectionAllocErr::CapacityOverflow)?; 381 ( 0.00%) self.try_grow(new_cap) 381 ( 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(); 18,296 ( 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. 6,256 ( 0.00%) pub fn remove(&mut self, index: usize) -> A::Item { . unsafe { . let (mut ptr, len_ptr, _) = self.triple_mut(); 2,544 ( 0.00%) let len = *len_ptr; 13,383 ( 0.00%) assert!(index < len); 16,213 ( 0.00%) *len_ptr = len - 1; . ptr = ptr.add(index); . let item = ptr::read(ptr); 8,922 ( 0.00%) ptr::copy(ptr.add(1), ptr, len - index - 1); . item . } 7,820 ( 0.00%) } . . /// Insert an element at position `index`, shifting all elements after it to the right. . /// . /// Panics if `index` is out of bounds. 26,167 ( 0.00%) pub fn insert(&mut self, index: usize, element: A::Item) { . self.reserve(1); . . unsafe { . let (mut ptr, len_ptr, _) = self.triple_mut(); 2,379 ( 0.00%) let len = *len_ptr; 4,758 ( 0.00%) assert!(index <= len); 9,516 ( 0.00%) *len_ptr = len + 1; . ptr = ptr.add(index); 4,758 ( 0.00%) ptr::copy(ptr, ptr.add(1), len - index); . ptr::write(ptr, element); . } 16,654 ( 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. 47,250 ( 0.00%) pub fn retain bool>(&mut self, mut f: F) { . let mut del = 0; . let len = self.len(); . for i in 0..len { 8,740 ( 0.00%) if !f(&mut self[i]) { . del += 1; 2,390 ( 0.00%) } else if del > 0 { . self.swap(i - del, i); . } . } 10,500 ( 0.00%) self.truncate(len - del); 42,000 ( 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, . ); 375 ( 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`. 365,312 ( 0.00%) pub fn insert_from_slice(&mut self, index: usize, slice: &[A::Item]) { . self.reserve(slice.len()); . . let len = self.len(); 109,590 ( 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()); 73,060 ( 0.00%) self.set_len(len + slice.len()); . } 292,240 ( 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(); 81,026 ( 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`. . /// . /// If `len` is less than the current length, the vector simply truncated. . /// . /// If `len` is greater than the current length, `value` is appended to the . /// vector until its length equals `len`. 80 ( 0.00%) pub fn resize(&mut self, len: usize, value: A::Item) { . let old_len = self.len(); . 16 ( 0.00%) if len > old_len { . self.extend(repeat(value).take(len - old_len)); . } else { . self.truncate(len); . } 56 ( 0.00%) } . . /// 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 { 4,966 ( 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); . } . } 7,344 ( 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 { 276,409 ( 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 1691 ---------------------------------------- . fn from(array: A) -> SmallVec { . SmallVec::from_buf(array) . } . } . . impl> ops::Index for SmallVec { . type Output = I::Output; . 2 ( 0.00%) fn index(&self, index: I) -> &I::Output { . &(**self)[index] 6 ( 0.00%) } . } . . impl> ops::IndexMut for SmallVec { . fn index_mut(&mut self, index: I) -> &mut I::Output { . &mut (&mut **self)[index] . } . } . -- line 1709 ---------------------------------------- -- line 1716 ---------------------------------------- . SmallVec::extend_from_slice(self, other) . } . } . . impl FromIterator for SmallVec { . #[inline] . fn from_iter>(iterable: I) -> SmallVec { . let mut v = SmallVec::new(); 2,451,864 ( 0.03%) v.extend(iterable); . v . } . } . . impl Extend for SmallVec { 15,244,780 ( 0.18%) fn extend>(&mut self, iterable: I) { 177,680 ( 0.00%) let mut iter = iterable.into_iter(); . let (lower_size_bound, _) = iter.size_hint(); 43,870 ( 0.00%) self.reserve(lower_size_bound); . . unsafe { . let (ptr, len_ptr, cap) = self.triple_mut(); . let mut len = SetLenOnDrop::new(len_ptr); 6,148,139 ( 0.07%) while len.get() < cap { 941,406 ( 0.01%) if let Some(out) = iter.next() { 8 ( 0.00%) ptr::write(ptr.add(len.get()), out); . len.increment_len(1); . } else { . return; . } . } . } . 78,751 ( 0.00%) for elem in iter { 7,782 ( 0.00%) self.push(elem); . } 12,290,545 ( 0.14%) } . } . . 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 { 19,078,351 ( 0.22%) fn drop(&mut self) { . unsafe { 6,782,159 ( 0.08%) if self.spilled() { . let (ptr, len) = self.data.heap(); . Vec::from_raw_parts(ptr, len, self.capacity); . } else { . ptr::drop_in_place(&mut self[..]); . } . } 19,179,837 ( 0.22%) } . } . . #[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,198 ( 0.00%) fn drop(&mut self) { 45,252 ( 0.00%) for _ in self {} 1,312 ( 0.00%) } . } . . impl Iterator for IntoIter { . type Item = A::Item; . . #[inline] . fn next(&mut self) -> Option { 257,690 ( 0.00%) if self.current == self.end { 3 ( 0.00%) None . } else { . unsafe { . let current = self.current; 140,359 ( 0.00%) self.current += 1; 1,484 ( 0.00%) Some(ptr::read(self.data.as_ptr().add(current))) . } . } . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 2,630 ( 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); 13,175 ( 0.00%) IntoIter { 134,010 ( 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 { 1,541,944 ( 0.02%) local_len: *len, . len, . } . } . . #[inline] . fn get(&self) -> usize { . self.local_len . } . . #[inline] . fn increment_len(&mut self, increment: usize) { 772,344 ( 0.01%) self.local_len += increment; . } . } . . impl<'a> Drop for SetLenOnDrop<'a> { . #[inline] . fn drop(&mut self) { 2,224,886 ( 0.03%) *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 ---------------------------------------- 21,157,078 ( 0.24%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs -------------------------------------------------------------------------------- Ir -- line 180 ---------------------------------------- . /// assert_eq!(v, &[0.into()]); . /// . /// // Ensure that the last item was dropped. . /// assert!(weak.upgrade().is_none()); . /// ``` . #[stable(feature = "drop_in_place", since = "1.8.0")] . #[lang = "drop_in_place"] . #[allow(unconditional_recursion)] 95,084,428 ( 1.09%) pub unsafe fn drop_in_place(to_drop: *mut T) { . // Code here does not matter - this is replaced by the . // real drop glue by the compiler. . . // SAFETY: see comment above . unsafe { drop_in_place(to_drop) } . } . . /// Creates a null raw pointer. -- line 196 ---------------------------------------- -- line 367 ---------------------------------------- . . // Perform the swap . // SAFETY: the caller must guarantee that `x` and `y` are . // valid for writes and properly aligned. `tmp` cannot be . // overlapping either `x` or `y` because `tmp` was just allocated . // on the stack as a separate allocated object. . unsafe { . copy_nonoverlapping(x, tmp.as_mut_ptr(), 1); 232 ( 0.00%) copy(y, x, 1); // `x` and `y` may overlap . copy_nonoverlapping(tmp.as_ptr(), y, 1); . } . } . . /// Swaps `count * size_of::()` bytes between the two regions of memory . /// beginning at `x` and `y`. The two regions must *not* overlap. . /// . /// # Safety -- line 383 ---------------------------------------- -- line 448 ---------------------------------------- . return; . } . } . . // Direct swapping, for the cases not going through the block optimization. . // SAFETY: the caller must guarantee that `x` and `y` are valid . // for writes, properly aligned, and non-overlapping. . unsafe { 1,680 ( 0.00%) let z = read(x); 102 ( 0.00%) copy_nonoverlapping(y, x, 1); . write(y, z); . } . } . . #[inline] . #[rustc_const_unstable(feature = "const_swap", issue = "83163")] . const unsafe fn swap_nonoverlapping_bytes(x: *mut u8, y: *mut u8, len: usize) { . // The approach here is to utilize simd to swap x & y efficiently. Testing reveals -- line 465 ---------------------------------------- -- line 693 ---------------------------------------- . let mut tmp = MaybeUninit::::uninit(); . // SAFETY: the caller must guarantee that `src` is valid for reads. . // `src` cannot overlap `tmp` because `tmp` was just allocated on . // the stack as a separate allocated object. . // . // Also, since we just wrote a valid value into `tmp`, it is guaranteed . // to be properly initialized. . unsafe { 13,315,824 ( 0.15%) copy_nonoverlapping(src, tmp.as_mut_ptr(), 1); 19,506,495 ( 0.22%) tmp.assume_init() . } . } . . /// Reads the value from `src` without moving it. This leaves the . /// memory in `src` unchanged. . /// . /// Unlike [`read`], `read_unaligned` works with unaligned pointers. . /// -- line 710 ---------------------------------------- -- line 884 ---------------------------------------- . #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")] . fn copy_nonoverlapping(src: *const T, dst: *mut T, count: usize); . } . . // SAFETY: the caller must guarantee that `dst` is valid for writes. . // `dst` cannot overlap `src` because the caller has mutable access . // to `dst` while `src` is owned by this function. . unsafe { 66,466,584 ( 0.76%) copy_nonoverlapping(&src as *const T, dst, 1); . intrinsics::forget(src); . } . } . . /// Overwrites a memory location with the given value without reading or . /// dropping the old value. . /// . /// Unlike [`write()`], the pointer may be unaligned. -- line 900 ---------------------------------------- -- line 1206 ---------------------------------------- . if stride == 1 { . // `stride == 1` case can be computed more simply through `-p (mod a)`, but doing so . // inhibits LLVM's ability to select instructions like `lea`. Instead we compute . // . // round_up_to_next_alignment(p, a) - p . // . // which distributes operations around the load-bearing, but pessimizing `and` sufficiently . // for LLVM to be able to utilize the various optimizations it knows about. 3,232 ( 0.00%) return wrapping_sub( 8,020 ( 0.00%) wrapping_add(p as usize, a_minus_one) & wrapping_sub(0, a), . p as usize, . ); . } . . let pmoda = p as usize & a_minus_one; . if pmoda == 0 { . // Already aligned. Yay! . return 0; -- line 1223 ---------------------------------------- -- line 1348 ---------------------------------------- . /// assert!(std::ptr::eq( . /// &wrapper as &dyn Trait as *const dyn Trait as *const u8, . /// &wrapper.member as &dyn Trait as *const dyn Trait as *const u8, . /// )); . /// ``` . #[stable(feature = "ptr_eq", since = "1.17.0")] . #[inline] . pub fn eq(a: *const T, b: *const T) -> bool { 1,103,970 ( 0.01%) a == b . } . . /// Hash a raw pointer. . /// . /// This can be used to hash a `&T` reference (which coerces to `*const T` implicitly) . /// by its address rather than the value it points to . /// (which is what the `Hash for &T` implementation does). . /// -- line 1364 ---------------------------------------- 8,802,882 ( 0.10%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/nonterminal.rs -------------------------------------------------------------------------------- Ir -- line 8 ---------------------------------------- . use crate::parser::pat::{RecoverColon, RecoverComma}; . use crate::parser::{FollowedByType, ForceCollect, Parser, PathStyle}; . . impl<'a> Parser<'a> { . /// Checks whether a non-terminal may begin with a particular token. . /// . /// Returning `false` is a *stability guarantee* that such a matcher will *never* begin with that . /// token. Be conservative (return true) if not sure. 1,324,716 ( 0.02%) pub fn nonterminal_may_begin_with(kind: NonterminalKind, token: &Token) -> bool { . /// Checks whether the non-terminal may contain a single (non-keyword) identifier. . fn may_be_ident(nt: &token::Nonterminal) -> bool { . match *nt { . token::NtItem(_) | token::NtBlock(_) | token::NtVis(_) | token::NtLifetime(_) => { . false . } . _ => true, . } . } . 6,623,580 ( 0.08%) match kind { . NonterminalKind::Expr => { 660 ( 0.00%) token.can_begin_expr() . // This exception is here for backwards compatibility. 330 ( 0.00%) && !token.is_keyword(kw::Let) . // This exception is here for backwards compatibility. 440 ( 0.00%) && !token.is_keyword(kw::Const) . } . NonterminalKind::Ty => token.can_begin_type(), . NonterminalKind::Ident => get_macro_ident(token).is_some(), . NonterminalKind::Literal => token.can_begin_literal_maybe_minus(), 195 ( 0.00%) NonterminalKind::Vis => match token.kind { . // The follow-set of :vis + "priv" keyword + interpolated . token::Comma | token::Ident(..) | token::Interpolated(..) => true, . _ => token.can_begin_type(), . }, . NonterminalKind::Block => match token.kind { . token::OpenDelim(token::Brace) => true, . token::Interpolated(ref nt) => !matches!( . **nt, -- line 46 ---------------------------------------- -- line 85 ---------------------------------------- . NonterminalKind::Lifetime => match token.kind { . token::Lifetime(_) => true, . token::Interpolated(ref nt) => { . matches!(**nt, token::NtLifetime(_) | token::NtTT(_)) . } . _ => false, . }, . NonterminalKind::TT | NonterminalKind::Item | NonterminalKind::Stmt => { 1,323,260 ( 0.02%) !matches!(token.kind, token::CloseDelim(_)) . } . } 1,324,574 ( 0.02%) } . . /// Parse a non-terminal (e.g. MBE `:pat` or `:ident`). 5,890,338 ( 0.07%) pub fn parse_nonterminal(&mut self, kind: NonterminalKind) -> PResult<'a, Nonterminal> { . // Any `Nonterminal` which stores its tokens (currently `NtItem` and `NtExpr`) . // needs to have them force-captured here. . // A `macro_rules!` invocation may pass a captured item/expr to a proc-macro, . // which requires having captured tokens available. Since we cannot determine . // in advance whether or not a proc-macro will be (transitively) invoked, . // we always capture tokens for any `Nonterminal` which needs them. 7,199,302 ( 0.08%) let mut nt = match kind { . NonterminalKind::Item => match self.parse_item(ForceCollect::Yes)? { . Some(item) => token::NtItem(item), . None => { . return Err(self.struct_span_err(self.token.span, "expected an item keyword")); . } . }, . NonterminalKind::Block => { . // While a block *expression* may have attributes (e.g. `#[my_attr] { ... }`), -- line 114 ---------------------------------------- -- line 126 ---------------------------------------- . NonterminalKind::PatParam { .. } => this.parse_pat_no_top_alt(None), . NonterminalKind::PatWithOr { .. } => { . this.parse_pat_allow_top_alt(None, RecoverComma::No, RecoverColon::No) . } . _ => unreachable!(), . })?) . } . 440 ( 0.00%) NonterminalKind::Expr => token::NtExpr(self.parse_expr_force_collect()?), . NonterminalKind::Literal => { . // The `:literal` matcher does not support attributes . token::NtLiteral( . self.collect_tokens_no_attrs(|this| this.parse_literal_maybe_minus())?, . ) . } . . NonterminalKind::Ty => { 108 ( 0.00%) token::NtTy(self.collect_tokens_no_attrs(|this| this.parse_ty())?) . } . // this could be handled like a token, since it is one . NonterminalKind::Ident 2,208 ( 0.00%) if let Some((ident, is_raw)) = get_macro_ident(&self.token) => . { 736 ( 0.00%) self.bump(); 2,576 ( 0.00%) token::NtIdent(ident, is_raw) . } . NonterminalKind::Ident => { . let token_str = pprust::token_to_string(&self.token); . let msg = &format!("expected ident, found {}", &token_str); . return Err(self.struct_span_err(self.token.span, msg)); . } . NonterminalKind::Path => token::NtPath( . self.collect_tokens_no_attrs(|this| this.parse_path(PathStyle::Type))?, . ), . NonterminalKind::Meta => token::NtMeta(P(self.parse_attr_item(true)?)), 3,269,495 ( 0.04%) NonterminalKind::TT => token::NtTT(self.parse_token_tree()), 153 ( 0.00%) NonterminalKind::Vis => token::NtVis( 153 ( 0.00%) self.collect_tokens_no_attrs(|this| this.parse_visibility(FollowedByType::Yes))?, . ), . NonterminalKind::Lifetime => { . if self.check_lifetime() { . token::NtLifetime(self.expect_lifetime().ident) . } else { . let token_str = pprust::token_to_string(&self.token); . let msg = &format!("expected a lifetime, found `{}`", &token_str); . return Err(self.struct_span_err(self.token.span, msg)); . } . } . }; . . // If tokens are supported at all, they should be collected. 1,963,876 ( 0.02%) if matches!(nt.tokens_mut(), Some(None)) { . panic!( . "Missing tokens for nt {:?} at {:?}: {:?}", . nt, . nt.span(), . pprust::nonterminal_to_string(&nt) . ); . } . 4,581,374 ( 0.05%) Ok(nt) 5,890,338 ( 0.07%) } . } . . /// The token is an identifier, but not `_`. . /// We prohibit passing `_` to macros expecting `ident` for now. . fn get_macro_ident(token: &Token) -> Option<(Ident, bool)> { 1,728 ( 0.00%) token.ident().filter(|(ident, _)| ident.name != kw::Underscore) . } 655,114 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs -------------------------------------------------------------------------------- Ir -- line 357 ---------------------------------------- . /// . /// ``` . /// use std::rc::Rc; . /// . /// let five = Rc::new(5); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] 9,280 ( 0.00%) pub fn new(value: T) -> Rc { . // There is an implicit weak pointer owned by all the strong . // pointers, which ensures that the weak destructor never frees . // the allocation while the strong destructor is running, even . // if the weak pointer is stored inside the strong one. . unsafe { . Self::from_inner( 5,847,780 ( 0.07%) Box::leak(box RcBox { strong: Cell::new(1), weak: Cell::new(1), value }).into(), . ) . } 9,280 ( 0.00%) } . . /// Constructs a new `Rc` using a closure `data_fn` that has access to a . /// weak reference to the constructing `Rc`. . /// . /// Generally, a structure circularly referencing itself, either directly or . /// indirectly, should not hold a strong reference to prevent a memory leak. . /// In `data_fn`, initialization of `T` can make use of the weak reference . /// by cloning and storing it inside `T` for use at a later time. -- line 383 ---------------------------------------- -- line 637 ---------------------------------------- . /// . /// let x = Rc::new(4); . /// let _y = Rc::clone(&x); . /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4); . /// ``` . #[inline] . #[stable(feature = "rc_unique", since = "1.4.0")] . pub fn try_unwrap(this: Self) -> Result { 2 ( 0.00%) if Rc::strong_count(&this) == 1 { . unsafe { . let val = ptr::read(&*this); // copy the contained object . . // Indicate to Weaks that they can't be promoted by decrementing . // the strong count, and then remove the implicit "strong weak" . // pointer while also handling drop logic by just crafting a . // fake Weak. . this.inner().dec_strong(); -- line 653 ---------------------------------------- -- line 931 ---------------------------------------- . /// let five = Rc::new(5); . /// let _weak_five = Rc::downgrade(&five); . /// . /// assert_eq!(1, Rc::weak_count(&five)); . /// ``` . #[inline] . #[stable(feature = "rc_counts", since = "1.15.0")] . pub fn weak_count(this: &Self) -> usize { 1,957,617 ( 0.02%) this.inner().weak() - 1 . } . . /// Gets the number of strong (`Rc`) pointers to this allocation. . /// . /// # Examples . /// . /// ``` . /// use std::rc::Rc; -- line 947 ---------------------------------------- -- line 1023 ---------------------------------------- . pub unsafe fn decrement_strong_count(ptr: *const T) { . unsafe { mem::drop(Rc::from_raw(ptr)) }; . } . . /// Returns `true` if there are no other `Rc` or [`Weak`] pointers to . /// this allocation. . #[inline] . fn is_unique(this: &Self) -> bool { 7,965 ( 0.00%) Rc::weak_count(this) == 0 && Rc::strong_count(this) == 1 . } . . /// Returns a mutable reference into the given `Rc`, if there are . /// no other `Rc` or [`Weak`] pointers to the same allocation. . /// . /// Returns [`None`] otherwise, because it is not safe to . /// mutate a shared value. . /// -- line 1039 ---------------------------------------- -- line 1053 ---------------------------------------- . /// assert_eq!(*x, 4); . /// . /// let _y = Rc::clone(&x); . /// assert!(Rc::get_mut(&mut x).is_none()); . /// ``` . #[inline] . #[stable(feature = "rc_unique", since = "1.4.0")] . pub fn get_mut(this: &mut Self) -> Option<&mut T> { 2,655 ( 0.00%) if Rc::is_unique(this) { unsafe { Some(Rc::get_mut_unchecked(this)) } } else { None } . } . . /// Returns a mutable reference into the given `Rc`, . /// without any check. . /// . /// See also [`get_mut`], which is safe and does appropriate checks. . /// . /// [`get_mut`]: Rc::get_mut -- line 1069 ---------------------------------------- -- line 1088 ---------------------------------------- . /// } . /// assert_eq!(*x, "foo"); . /// ``` . #[inline] . #[unstable(feature = "get_mut_unchecked", issue = "63292")] . pub unsafe fn get_mut_unchecked(this: &mut Self) -> &mut T { . // We are careful to *not* create a reference covering the "count" fields, as . // this would conflict with accesses to the reference counts (e.g. by `Weak`). 1,393,094 ( 0.02%) unsafe { &mut (*this.ptr.as_ptr()).value } . } . . #[inline] . #[stable(feature = "ptr_eq", since = "1.17.0")] . /// Returns `true` if the two `Rc`s point to the same allocation . /// (in a vein similar to [`ptr::eq`]). . /// . /// # Examples -- line 1104 ---------------------------------------- -- line 1109 ---------------------------------------- . /// let five = Rc::new(5); . /// let same_five = Rc::clone(&five); . /// let other_five = Rc::new(5); . /// . /// assert!(Rc::ptr_eq(&five, &same_five)); . /// assert!(!Rc::ptr_eq(&five, &other_five)); . /// ``` . pub fn ptr_eq(this: &Self, other: &Self) -> bool { 3,172 ( 0.00%) this.ptr.as_ptr() == other.ptr.as_ptr() . } . } . . impl Rc { . /// Makes a mutable reference into the given `Rc`. . /// . /// If there are other `Rc` pointers to the same allocation, then `make_mut` will . /// [`clone`] the inner value to a new allocation to ensure unique ownership. This is also -- line 1125 ---------------------------------------- -- line 1167 ---------------------------------------- . /// *Rc::make_mut(&mut data) += 1; . /// . /// assert!(76 == *data); . /// assert!(weak.upgrade().is_none()); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[inline] . #[stable(feature = "rc_unique", since = "1.4.0")] 6,592,841 ( 0.08%) pub fn make_mut(this: &mut Self) -> &mut T { 3,955,701 ( 0.05%) if Rc::strong_count(this) != 1 { . // Gotta clone the data, there are other Rcs. . // Pre-allocate memory to allow writing the cloned value directly. 668,803 ( 0.01%) let mut rc = Self::new_uninit(); . unsafe { . let data = Rc::get_mut_unchecked(&mut rc); . (**this).write_clone_into_raw(data.as_mut_ptr()); 1,337,606 ( 0.02%) *this = rc.assume_init(); . } 1,299,768 ( 0.01%) } else if Rc::weak_count(this) != 0 { . // Can just steal the data, all that's left is Weaks . let mut rc = Self::new_uninit(); . unsafe { . let data = Rc::get_mut_unchecked(&mut rc); . data.as_mut_ptr().copy_from_nonoverlapping(&**this, 1); . . this.inner().dec_strong(); . // Remove implicit strong-weak ref (no need to craft a fake -- line 1193 ---------------------------------------- -- line 1196 ---------------------------------------- . ptr::write(this, rc.assume_init()); . } . } . // This unsafety is ok because we're guaranteed that the pointer . // returned is the *only* pointer that will ever be returned to T. Our . // reference count is guaranteed to be 1 at this point, and we required . // the `Rc` itself to be `mut`, so we're returning the only possible . // reference to the allocation. 1,318,686 ( 0.02%) unsafe { &mut this.ptr.as_mut().value } 7,911,408 ( 0.09%) } . } . . impl Rc { . #[inline] . #[stable(feature = "rc_downcast", since = "1.29.0")] . /// Attempt to downcast the `Rc` to a concrete type. . /// . /// # Examples -- line 1213 ---------------------------------------- -- line 1344 ---------------------------------------- . ) . } . } . . /// Copy elements from slice into newly allocated Rc<\[T\]> . /// . /// Unsafe because the caller must either take ownership or bind `T: Copy` . #[cfg(not(no_global_oom_handling))] 2,891 ( 0.00%) unsafe fn copy_from_slice(v: &[T]) -> Rc<[T]> { . unsafe { . let ptr = Self::allocate_for_slice(v.len()); 582 ( 0.00%) ptr::copy_nonoverlapping(v.as_ptr(), &mut (*ptr).value as *mut [T] as *mut T, v.len()); . Self::from_ptr(ptr) . } 3,996 ( 0.00%) } . . /// Constructs an `Rc<[T]>` from an iterator known to be of a certain size. . /// . /// Behavior is undefined should the size be wrong. . #[cfg(not(no_global_oom_handling))] . unsafe fn from_iter_exact(iter: impl iter::Iterator, len: usize) -> Rc<[T]> { . // Panic guard while cloning T elements. . // In the event of a panic, elements that have been written -- line 1366 ---------------------------------------- -- line 1419 ---------------------------------------- . unsafe { Self::from_iter_exact(v.iter().cloned(), v.len()) } . } . } . . #[cfg(not(no_global_oom_handling))] . impl RcFromSlice for Rc<[T]> { . #[inline] . fn from_slice(v: &[T]) -> Self { 17 ( 0.00%) unsafe { Rc::copy_from_slice(v) } . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Deref for Rc { . type Target = T; . . #[inline(always)] . fn deref(&self) -> &T { 377,274 ( 0.00%) &self.inner().value . } . } . . #[unstable(feature = "receiver_trait", issue = "none")] . impl Receiver for Rc {} . . #[stable(feature = "rust1", since = "1.0.0")] . unsafe impl<#[may_dangle] T: ?Sized> Drop for Rc { -- line 1445 ---------------------------------------- -- line 1463 ---------------------------------------- . /// } . /// . /// let foo = Rc::new(Foo); . /// let foo2 = Rc::clone(&foo); . /// . /// drop(foo); // Doesn't print anything . /// drop(foo2); // Prints "dropped!" . /// ``` 5,986,706 ( 0.07%) fn drop(&mut self) { . unsafe { 4,084,438 ( 0.05%) self.inner().dec_strong(); 9,735,212 ( 0.11%) if self.inner().strong() == 0 { . // destroy the contained object 697,344 ( 0.01%) ptr::drop_in_place(Self::get_mut_unchecked(self)); . . // remove the implicit "strong weak" pointer now that we've . // destroyed the contents. 1 ( 0.00%) self.inner().dec_weak(); . 2,824,079 ( 0.03%) if self.inner().weak() == 0 { 473 ( 0.00%) Global.deallocate(self.ptr.cast(), Layout::for_value(self.ptr.as_ref())); . } . } . } 7,199,380 ( 0.08%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Clone for Rc { . /// Makes a clone of the `Rc` pointer. . /// . /// This creates another pointer to the same allocation, increasing the . /// strong reference count. -- line 1495 ---------------------------------------- -- line 1562 ---------------------------------------- . /// cost to pay off more easily. It's also more likely to have two `Rc` clones, that point to . /// the same value, than two `&T`s. . /// . /// We can only do this when `T: Eq` as a `PartialEq` might be deliberately irreflexive. . #[stable(feature = "rust1", since = "1.0.0")] . impl RcEqIdent for Rc { . #[inline] . fn eq(&self, other: &Rc) -> bool { 3,288 ( 0.00%) Rc::ptr_eq(self, other) || **self == **other . } . . #[inline] . fn ne(&self, other: &Rc) -> bool { . !Rc::ptr_eq(self, other) && **self != **other . } . } . -- line 1578 ---------------------------------------- -- line 1741 ---------------------------------------- . fn cmp(&self, other: &Rc) -> Ordering { . (**self).cmp(&**other) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Hash for Rc { . fn hash(&self, state: &mut H) { 1,412 ( 0.00%) (**self).hash(state); . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl fmt::Display for Rc { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . fmt::Display::fmt(&**self, f) . } -- line 1757 ---------------------------------------- -- line 1879 ---------------------------------------- . /// # use std::rc::Rc; . /// let original: Box> = Box::new(vec![1, 2, 3]); . /// let shared: Rc> = Rc::from(original); . /// assert_eq!(vec![1, 2, 3], *shared); . /// ``` . #[inline] . fn from(mut v: Vec) -> Rc<[T]> { . unsafe { 1,107 ( 0.00%) let rc = Rc::copy_from_slice(&v); . . // Allow the Vec to free its memory, but not destroy its contents . v.set_len(0); . . rc . } . } . } -- line 1895 ---------------------------------------- -- line 2080 ---------------------------------------- . #[must_use] . pub fn new() -> Weak { . Weak { ptr: NonNull::new(usize::MAX as *mut RcBox).expect("MAX is not 0") } . } . } . . pub(crate) fn is_dangling(ptr: *mut T) -> bool { . let address = ptr as *mut () as usize; 143 ( 0.00%) address == usize::MAX . } . . /// Helper type to allow accessing the reference counts without . /// making any assertions about the data field. . struct WeakInner<'a> { . weak: &'a Cell, . strong: &'a Cell, . } -- line 2096 ---------------------------------------- -- line 2299 ---------------------------------------- . }) . .unwrap_or(0) . } . . /// Returns `None` when the pointer is dangling and there is no allocated `RcBox`, . /// (i.e., when this `Weak` was created by `Weak::new`). . #[inline] . fn inner(&self) -> Option> { 1 ( 0.00%) if is_dangling(self.ptr.as_ptr()) { . None . } else { . // We are careful to *not* create a reference covering the "data" field, as . // the field may be mutated concurrently (for example, if the last `Rc` . // is dropped, the data field will be dropped in-place). . Some(unsafe { . let ptr = self.ptr.as_ptr(); . WeakInner { strong: &(*ptr).strong, weak: &(*ptr).weak } -- line 2315 ---------------------------------------- -- line 2391 ---------------------------------------- . /// assert!(other_weak_foo.upgrade().is_none()); . /// ``` . fn drop(&mut self) { . let inner = if let Some(inner) = self.inner() { inner } else { return }; . . inner.dec_weak(); . // the weak count starts at 1, and will only go to zero if all . // the strong pointers have disappeared. 2 ( 0.00%) if inner.weak() == 0 { . unsafe { . Global.deallocate(self.ptr.cast(), Layout::for_value_raw(self.ptr.as_ptr())); . } . } . } . } . . #[stable(feature = "rc_weak", since = "1.4.0")] -- line 2407 ---------------------------------------- -- line 2469 ---------------------------------------- . . #[inline] . fn strong(&self) -> usize { . self.strong_ref().get() . } . . #[inline] . fn inc_strong(&self) { 3,453,429 ( 0.04%) let strong = self.strong(); . . // We want to abort on overflow instead of dropping the value. . // The reference count will never be zero when this is called; . // nevertheless, we insert an abort here to hint LLVM at . // an otherwise missed optimization. 10,411,177 ( 0.12%) if strong == 0 || strong == usize::MAX { . abort(); . } 3,478 ( 0.00%) self.strong_ref().set(strong + 1); . } . . #[inline] . fn dec_strong(&self) { 17,310,298 ( 0.20%) self.strong_ref().set(self.strong() - 1); . } . . #[inline] . fn weak(&self) -> usize { . self.weak_ref().get() . } . . #[inline] -- line 2499 ---------------------------------------- -- line 2507 ---------------------------------------- . if weak == 0 || weak == usize::MAX { . abort(); . } . self.weak_ref().set(weak + 1); . } . . #[inline] . fn dec_weak(&self) { 4,231,293 ( 0.05%) self.weak_ref().set(self.weak() - 1); . } . } . . impl RcInnerPtr for RcBox { . #[inline(always)] . fn weak_ref(&self) -> &Cell { . &self.weak . } -- line 2523 ---------------------------------------- 5,512,027 ( 0.06%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/span_encoding.rs -------------------------------------------------------------------------------- Ir -- line 55 ---------------------------------------- . /// `ctxt` values depend partly on the crate size and partly on the form of . /// the code. No crates in `rustc-perf` need more than 15 bits for `ctxt`, . /// but larger crates might need more than 16 bits. . /// . /// In order to reliably use parented spans in incremental compilation, . /// the dependency to the parent definition's span. This is performed . /// using the callback `SPAN_TRACK` to access the query engine. . /// 4,803,575 ( 0.06%) #[derive(Clone, Copy, Eq, PartialEq, Hash)] . // FIXME(@lcnr): Enable this attribute once the bootstrap . // compiler knows of `rustc_pass_by_value`. . // . // Right now, this lint would only trigger when compiling the . // stage 2 compiler, which is fairly annoying as there are . // a lot of places using `&Span` right now. After the next bootstrap bump, . // the lint will already trigger when using stage 1, which is a lot less annoying. . // . // #[cfg_attr(not(bootstrap), rustc_pass_by_value)] . pub struct Span { 8,140 ( 0.00%) base_or_index: u32, 3,993 ( 0.00%) len_or_tag: u16, 4,864 ( 0.00%) ctxt_or_zero: u16, . } . . const LEN_TAG: u16 = 0b1000_0000_0000_0000; . const MAX_LEN: u32 = 0b0111_1111_1111_1111; . const MAX_CTXT: u32 = 0b1111_1111_1111_1111; . . /// Dummy span, both position and length are zero, syntax context is zero as well. . pub const DUMMY_SP: Span = Span { base_or_index: 0, len_or_tag: 0, ctxt_or_zero: 0 }; -- line 84 ---------------------------------------- -- line 86 ---------------------------------------- . impl Span { . #[inline] . pub fn new( . mut lo: BytePos, . mut hi: BytePos, . ctxt: SyntaxContext, . parent: Option, . ) -> Self { 312,357 ( 0.00%) if lo > hi { . std::mem::swap(&mut lo, &mut hi); . } . 624,714 ( 0.01%) let (base, len, ctxt2) = (lo.0, hi.0 - lo.0, ctxt.as_u32()); . 2,821,650 ( 0.03%) if len <= MAX_LEN && ctxt2 <= MAX_CTXT && parent.is_none() { . // Inline format. . Span { base_or_index: base, len_or_tag: len as u16, ctxt_or_zero: ctxt2 as u16 } . } else { . // Interned format. . let index = 240 ( 0.00%) with_span_interner(|interner| interner.intern(&SpanData { lo, hi, ctxt, parent })); . Span { base_or_index: index, len_or_tag: LEN_TAG, ctxt_or_zero: 0 } . } 1,053,170 ( 0.01%) } . . #[inline] . pub fn data(self) -> SpanData { . let data = self.data_untracked(); . if let Some(parent) = data.parent { . (*SPAN_TRACK)(parent); . } . data . } . . /// Internal function to translate between an encoded span and the expanded representation. . /// This function must not be used outside the incremental engine. . #[inline] . pub fn data_untracked(self) -> SpanData { 13,647,271 ( 0.16%) if self.len_or_tag != LEN_TAG { . // Inline format. . debug_assert!(self.len_or_tag as u32 <= MAX_LEN); . SpanData { . lo: BytePos(self.base_or_index), 13,311,781 ( 0.15%) hi: BytePos(self.base_or_index + self.len_or_tag as u32), . ctxt: SyntaxContext::from_u32(self.ctxt_or_zero as u32), . parent: None, . } . } else { . // Interned format. . debug_assert!(self.ctxt_or_zero == 0); . let index = self.base_or_index; . with_span_interner(|interner| interner.spans[index as usize]) . } 393,208 ( 0.00%) } . } . 4 ( 0.00%) #[derive(Default)] . pub struct SpanInterner { . spans: FxIndexSet, . } . . impl SpanInterner { 72 ( 0.00%) fn intern(&mut self, span_data: &SpanData) -> u32 { 96 ( 0.00%) let (index, _) = self.spans.insert_full(*span_data); . index as u32 96 ( 0.00%) } . } . . // If an interner exists, return it. Otherwise, prepare a fresh one. . #[inline] . fn with_span_interner T>(f: F) -> T { . crate::with_session_globals(|session_globals| f(&mut *session_globals.span_interner.lock())) . } 3,122,213 ( 0.04%) -------------------------------------------------------------------------------- -- 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}; . 22,116 ( 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); . } . } . } . }; . } . 502,570 ( 0.01%) #[derive(Clone)] . pub struct Parser<'a> { 18,622 ( 0.00%) pub sess: &'a ParseSess, . /// The current token. 17,556 ( 0.00%) pub token: Token, . /// The spacing for the current token 8,916 ( 0.00%) pub token_spacing: Spacing, . /// The previous token. 26,334 ( 0.00%) pub prev_token: Token, 9,054 ( 0.00%) pub capture_cfg: bool, 18,246 ( 0.00%) restrictions: Restrictions, 17,832 ( 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, 17,832 ( 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. 17,832 ( 0.00%) unmatched_angle_bracket_count: u32, 26,748 ( 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. 8,916 ( 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` 8,916 ( 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, . } . 36,592 ( 0.00%) #[derive(Clone)] . struct CaptureState { 35,664 ( 0.00%) capturing: Capturing, 8,916 ( 0.00%) replace_ranges: Vec, . inner_attr_ranges: FxHashMap, . } . . impl<'a> Drop for Parser<'a> { . fn drop(&mut self) { 32,662 ( 0.00%) emit_unclosed_delims(&mut self.unclosed_delims, &self.sess); . } . } . 157,920 ( 0.00%) #[derive(Clone)] . struct TokenCursor { . frame: TokenCursorFrame, 36,160 ( 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. 11,936 ( 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, . } . 72,121 ( 0.00%) #[derive(Clone)] . struct TokenCursorFrame { 20,912 ( 0.00%) delim: token::DelimToken, . span: DelimSpan, . open_delim: bool, 41,824 ( 0.00%) tree_cursor: tokenstream::Cursor, . close_delim: bool, . } . . impl TokenCursorFrame { . fn new(span: DelimSpan, delim: DelimToken, tts: TokenStream) -> Self { 9,600 ( 0.00%) TokenCursorFrame { . delim, . span, . open_delim: false, 355,966 ( 0.00%) tree_cursor: tts.into_trees(), . close_delim: false, . } . } . } . . impl TokenCursor { 38,823,804 ( 0.45%) fn next(&mut self) -> (Token, Spacing) { . loop { 18,652,149 ( 0.21%) let (tree, spacing) = if !self.frame.open_delim { 352,126 ( 0.00%) self.frame.open_delim = true; 1,760,630 ( 0.02%) TokenTree::open_tt(self.frame.span, self.frame.delim).into() 38,094,842 ( 0.44%) } else if let Some(tree) = self.frame.tree_cursor.next_with_spacing() { . tree 1,433,876 ( 0.02%) } else if !self.frame.close_delim { 357,467 ( 0.00%) self.frame.close_delim = true; 1,787,335 ( 0.02%) TokenTree::close_tt(self.frame.span, self.frame.delim).into() 714,934 ( 0.01%) } else if let Some(frame) = self.stack.pop() { 4,647,071 ( 0.05%) self.frame = frame; . continue; . } else { 36,072 ( 0.00%) (TokenTree::Token(Token::new(token::Eof, DUMMY_SP)), Spacing::Alone) . }; . 7,174,886 ( 0.08%) match tree { . TokenTree::Token(token) => { 25,882,536 ( 0.30%) return (token, spacing); . } . TokenTree::Delimited(sp, delim, tts) => { . let frame = TokenCursorFrame::new(sp, delim, tts); . self.stack.push(mem::replace(&mut self.frame, frame)); . } . } . } 25,882,536 ( 0.30%) } . 28,511,040 ( 0.33%) fn next_desugared(&mut self) -> (Token, Spacing) { 8,553,312 ( 0.10%) let (data, attr_style, sp) = match self.next() { . (Token { kind: token::DocComment(_, attr_style, data), span }, _) => { . (data, attr_style, span) . } 14,255,520 ( 0.16%) 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() 25,659,936 ( 0.30%) } . } . 7,390 ( 0.00%) #[derive(Debug, Clone, PartialEq)] . enum TokenType { 5,912 ( 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 { 18 ( 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> { 80 ( 0.00%) Some(match token.kind { 160 ( 0.00%) _ if token.is_special_ident() => "reserved identifier", 160 ( 0.00%) _ if token.is_used_keyword() => "keyword", 160 ( 0.00%) _ if token.is_unused_keyword() => "reserved keyword", . token::DocComment(..) => "doc comment", . _ => return None, . }) . } . 280 ( 0.00%) pub(super) fn token_descr(token: &Token) -> String { 80 ( 0.00%) let token_str = pprust::token_to_string(token); . match token_descr_opt(token) { . Some(prefix) => format!("{} `{}`", prefix, token_str), 280 ( 0.00%) _ => format!("`{}`", token_str), . } 200 ( 0.00%) } . . impl<'a> Parser<'a> { 26,880 ( 0.00%) pub fn new( . sess: &'a ParseSess, . tokens: TokenStream, . desugar_doc_comments: bool, . subparser_name: Option<&'static str>, . ) -> Self { 1,920 ( 0.00%) let mut start_frame = TokenCursorFrame::new(DelimSpan::dummy(), token::NoDelim, tokens); 3,840 ( 0.00%) start_frame.open_delim = true; . start_frame.close_delim = true; . 59,520 ( 0.00%) let mut parser = Parser { . sess, 1,920 ( 0.00%) token: Token::dummy(), . token_spacing: Spacing::Alone, 1,920 ( 0.00%) prev_token: Token::dummy(), . capture_cfg: false, . restrictions: Restrictions::empty(), . expected_tokens: Vec::new(), . token_cursor: TokenCursor { 11,520 ( 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. 3,840 ( 0.00%) parser.bump(); . . parser 17,280 ( 0.00%) } . . fn next_tok(&mut self, fallback_span: Span) -> (Token, Spacing) { . loop { 19,400,286 ( 0.22%) let (mut next, spacing) = if self.desugar_doc_comments { 11,404,416 ( 0.13%) self.token_cursor.next_desugared() . } else { 1,146,831 ( 0.01%) self.token_cursor.next() . }; 12,933,524 ( 0.15%) 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 3,233,381 ( 0.04%) self.token_cursor.break_last_token = false; 12,933,524 ( 0.15%) if next.span.is_dummy() { . // Tweak the location for better diagnostics, but keep syntactic context intact. 7,740 ( 0.00%) next.span = fallback_span.with_ctxt(next.span.ctxt()); . } 10,767,097 ( 0.12%) if matches!( 6,466,762 ( 0.07%) next.kind, . token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) . ) { . continue; . } 12,933,524 ( 0.15%) 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`. 58,491 ( 0.00%) pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> { 6,499 ( 0.00%) if self.expected_tokens.is_empty() { 2,460 ( 0.00%) if self.token == *t { 2,050 ( 0.00%) self.bump(); . Ok(false) . } else { . self.unexpected_try_recover(t) . } . } else { 73,068 ( 0.00%) self.expect_one_of(slice::from_ref(t), &[]) . } 97,485 ( 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. 79,356 ( 0.00%) pub fn expect_one_of( . &mut self, . edible: &[TokenKind], . inedible: &[TokenKind], . ) -> PResult<'a, bool /* recovered */> { 13,226 ( 0.00%) if edible.contains(&self.token.kind) { 19,185 ( 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) . } 99,195 ( 0.00%) } . . // Public for rustfmt usage. . pub fn parse_ident(&mut self) -> PResult<'a, Ident> { 55,409 ( 0.00%) self.parse_ident_common(true) . } . . fn ident_or_err(&mut self) -> PResult<'a, (Ident, /* is_raw */ bool)> { 42,408 ( 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(), . }) . } . 97,958 ( 0.00%) fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> { 13,994 ( 0.00%) let (ident, is_raw) = self.ident_or_err()?; 83,964 ( 0.00%) if !is_raw && ident.is_reserved() { . let mut err = self.expected_ident_found(); . if recover { . err.emit(); . } else { . return Err(err); . } . } 55,976 ( 0.00%) self.bump(); . Ok(ident) 139,940 ( 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. 983,430 ( 0.01%) fn check(&mut self, tok: &TokenKind) -> bool { 430,506 ( 0.00%) let is_present = self.token == *tok; 296,388 ( 0.00%) if !is_present { 549,014 ( 0.01%) self.expected_tokens.push(TokenType::Token(tok.clone())); . } . is_present 983,430 ( 0.01%) } . . /// Consumes a token 'tok' if it exists. Returns whether the given token was present. 88 ( 0.00%) pub fn eat(&mut self, tok: &TokenKind) -> bool { 179,765 ( 0.00%) let is_present = self.check(tok); 117,712 ( 0.00%) if is_present { 35,123 ( 0.00%) self.bump() . } . is_present 110 ( 0.00%) } . . /// If the next token is the given keyword, returns `true` without eating it. . /// An expectation is also added for diagnostics purposes. 12,475 ( 0.00%) fn check_keyword(&mut self, kw: Symbol) -> bool { 2,560 ( 0.00%) self.expected_tokens.push(TokenType::Keyword(kw)); 84,385 ( 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. 27,565 ( 0.00%) pub fn eat_keyword(&mut self, kw: Symbol) -> bool { 19,520 ( 0.00%) if self.check_keyword(kw) { 1,648 ( 0.00%) self.bump(); . true . } else { . false . } 27,565 ( 0.00%) } . . fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool { 2,418 ( 0.00%) if self.token.is_keyword(kw) { 594 ( 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. 440 ( 0.00%) fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> { . if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) } 352 ( 0.00%) } . . /// Is the given keyword `kw` followed by a non-reserved identifier? 14,288 ( 0.00%) fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool { 7,144 ( 0.00%) self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()) 16,074 ( 0.00%) } . 46,854 ( 0.00%) fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool { 16,478 ( 0.00%) if ok { . true . } else { 5,480 ( 0.00%) self.expected_tokens.push(typ); . false . } 46,854 ( 0.00%) } . . fn check_ident(&mut self) -> bool { 5,396 ( 0.00%) self.check_or_expected(self.token.is_ident(), TokenType::Ident) . } . 23,588 ( 0.00%) fn check_path(&mut self) -> bool { 51,148 ( 0.00%) self.check_or_expected(self.token.is_path_start(), TokenType::Path) 29,485 ( 0.00%) } . . fn check_type(&mut self) -> bool { 1,604 ( 0.00%) self.check_or_expected(self.token.can_begin_type(), TokenType::Type) . } . . fn check_const_arg(&mut self) -> bool { 1,592 ( 0.00%) self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const) . } . 6,120 ( 0.00%) fn check_inline_const(&self, dist: usize) -> bool { 3,400 ( 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, . }) 6,120 ( 0.00%) } . . /// Checks to see if the next token is either `+` or `+=`. . /// Otherwise returns `false`. . fn check_plus(&mut self) -> bool { 2,224 ( 0.00%) self.check_or_expected( 1,112 ( 0.00%) self.token.is_like_plus(), 1,112 ( 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. 77,208 ( 0.00%) fn break_and_eat(&mut self, expected: TokenKind) -> bool { 45,038 ( 0.00%) if self.token.kind == expected { 964 ( 0.00%) self.bump(); . return true; . } 29,760 ( 0.00%) match self.token.kind.break_two_token_op() { 9,328 ( 0.00%) Some((first, second)) if first == expected => { 4 ( 0.00%) let first_span = self.sess.source_map().start_point(self.token.span); 5 ( 0.00%) let second_span = self.token.span.with_lo(first_span.hi()); 9 ( 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` 1 ( 0.00%) self.token_cursor.break_last_token = true; . // Use the spacing of the glued token as the spacing . // of the unglued second token. 14 ( 0.00%) self.bump_with((Token::new(second, second_span), self.token_spacing)); . true . } . _ => { 17,853 ( 0.00%) self.expected_tokens.push(TokenType::Token(expected)); . false . } . } 84,817 ( 0.00%) } . . /// Eats `+` possibly breaking tokens like `+=` in process. . fn eat_plus(&mut self) -> bool { 24 ( 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, ()> { 486 ( 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, ()> { 36 ( 0.00%) if self.break_and_eat(token::BinOp(token::Or)) { Ok(()) } else { self.unexpected() } . } . . /// Eats `<` possibly breaking tokens like `<<` in process. 1,446 ( 0.00%) fn eat_lt(&mut self) -> bool { 18,757 ( 0.00%) let ate = self.break_and_eat(token::Lt); 12,478 ( 0.00%) if ate { . // See doc comment for `unmatched_angle_bracket_count`. 788 ( 0.00%) self.unmatched_angle_bracket_count += 1; 795 ( 0.00%) self.max_angle_bracket_count += 1; . debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count); . } . ate 1,446 ( 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, ()> { 1,182 ( 0.00%) if self.break_and_eat(token::Gt) { . // See doc comment for `unmatched_angle_bracket_count`. 591 ( 0.00%) if self.unmatched_angle_bracket_count > 0 { 394 ( 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 { 20,577 ( 0.00%) TokenExpectType::Expect => self.check(k), 90 ( 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) { 28,544 ( 0.00%) if let token::CloseDelim(..) | token::Eof = self.token.kind { . break; . } 21,544 ( 0.00%) if let Some(ref t) = sep.sep { 22,858 ( 0.00%) if first { . first = false; . } else { 13,628 ( 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; . } . } . } . } . } . } 9,878 ( 0.00%) if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) { . trailing = true; . break; . } . 5,328 ( 0.00%) let t = f(self)?; 1,379 ( 0.00%) v.push(t); . } . 16,012 ( 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)> { 15,871 ( 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. 34,760 ( 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 */)> { 11,501 ( 0.00%) let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?; 4,487 ( 0.00%) if !recovered { . self.eat(ket); . } 32,799 ( 0.00%) Ok((val, trailing)) 27,808 ( 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)> { 11,005 ( 0.00%) self.expect(bra)?; 27,808 ( 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( 3,815 ( 0.00%) &token::OpenDelim(delim), 4,166 ( 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. 42,033,966 ( 0.48%) fn bump_with(&mut self, (next_token, next_spacing): (Token, Spacing)) { . // Bumping after EOF is a bad sign, usually an infinite loop. 19,400,292 ( 0.22%) 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. 12,933,528 ( 0.15%) self.prev_token = mem::replace(&mut self.token, next_token); 3,233,382 ( 0.04%) self.token_spacing = next_spacing; . . // Diagnostics. 3,233,382 ( 0.04%) self.expected_tokens.clear(); . } . . /// Advance the parser by one token. 25,867,048 ( 0.30%) pub fn bump(&mut self) { 12,933,524 ( 0.15%) let next_token = self.next_tok(self.token.span); 19,400,286 ( 0.22%) self.bump_with(next_token); 25,867,048 ( 0.30%) } . . /// Look-ahead `dist` tokens of `self.token` and get access to that token there. . /// When `dist == 0` then the current token is looked at. 80 ( 0.00%) pub fn look_ahead(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R { 2,198 ( 0.00%) if dist == 0 { 844 ( 0.00%) return looker(&self.token); . } . 23,627 ( 0.00%) let frame = &self.token_cursor.frame; 27,331 ( 0.00%) if frame.delim != DelimToken::NoDelim { . let all_normal = (0..dist).all(|i| { 74,720 ( 0.00%) let token = frame.tree_cursor.look_ahead(i); 102,183 ( 0.00%) !matches!(token, Some(TokenTree::Delimited(_, DelimToken::NoDelim, _))) . }); . if all_normal { 124,397 ( 0.00%) return match frame.tree_cursor.look_ahead(dist - 1) { 47,870 ( 0.00%) Some(tree) => match tree { 23,673 ( 0.00%) TokenTree::Token(token) => looker(token), . TokenTree::Delimited(dspan, delim, _) => { 4,343 ( 0.00%) looker(&Token::new(token::OpenDelim(*delim), dspan.open)) . } . }, 11,025 ( 0.00%) None => looker(&Token::new(token::CloseDelim(frame.delim), frame.span.close)), . }; . } . } . . let mut cursor = self.token_cursor.clone(); . let mut i = 0; 1,941 ( 0.00%) let mut token = Token::dummy(); 120 ( 0.00%) while i < dist { 13,634 ( 0.00%) token = cursor.next().0; 6,037 ( 0.00%) if matches!( 3,872 ( 0.00%) token.kind, . token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) . ) { . continue; . } 50 ( 0.00%) i += 1; . } 282 ( 0.00%) return looker(&token); 90 ( 0.00%) } . . /// Returns whether any of the given keywords are `dist` tokens ahead of the current one. 8,091 ( 0.00%) fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool { 1,975 ( 0.00%) self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw))) 8,091 ( 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. 362 ( 0.00%) fn parse_unsafety(&mut self) -> Unsafe { . if self.eat_keyword(kw::Unsafe) { . Unsafe::Yes(self.prev_token.uninterpolated_span()) . } else { . Unsafe::No . } 1,448 ( 0.00%) } . . /// Parses constness: `const` or nothing. 4,008 ( 0.00%) fn parse_constness(&mut self) -> Const { . // Avoid const blocks to be parsed as const items 1,278 ( 0.00%) if self.look_ahead(1, |t| t != &token::OpenDelim(DelimToken::Brace)) . && self.eat_keyword(kw::Const) . { 10 ( 0.00%) Const::Yes(self.prev_token.uninterpolated_span()) . } else { . Const::No . } 7,014 ( 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 1110 ---------------------------------------- . }; . 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). . fn parse_mutability(&mut self) -> Mutability { . if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not } 156 ( 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> { 346 ( 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 { 519 ( 0.00%) self.parse_ident_common(true) . } . } . . fn parse_mac_args(&mut self) -> PResult<'a, P> { 3,557 ( 0.00%) self.parse_mac_args_common(true).map(P) . } . . fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> { 63 ( 0.00%) self.parse_mac_args_common(false) . } . 11,349 ( 0.00%) fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> { 10,088 ( 0.00%) Ok( 6,633 ( 0.00%) if self.check(&token::OpenDelim(DelimToken::Paren)) 249 ( 0.00%) || self.check(&token::OpenDelim(DelimToken::Bracket)) 243 ( 0.00%) || self.check(&token::OpenDelim(DelimToken::Brace)) . { 5,016 ( 0.00%) match self.parse_token_tree() { 6,270 ( 0.00%) TokenTree::Delimited(dspan, delim, tokens) => . // We've confirmed above that there is a delimiter so unwrapping is OK. . { 2,508 ( 0.00%) MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens) . } . _ => unreachable!(), . } 14 ( 0.00%) } else if !delimited_only { . if self.eat(&token::Eq) { 1 ( 0.00%) let eq_span = self.prev_token.span; . . // Collect tokens because they are used during lowering to HIR. 1 ( 0.00%) let expr = self.parse_expr_force_collect()?; 1 ( 0.00%) let span = expr.span; . 5 ( 0.00%) let token_kind = token::Interpolated(Lrc::new(token::NtExpr(expr))); 9 ( 0.00%) MacArgs::Eq(eq_span, Token::new(token_kind, span)) . } else { . MacArgs::Empty . } . } else { . return self.unexpected(); . }, . ) 8,827 ( 0.00%) } . . fn parse_or_use_outer_attributes( . &mut self, . already_parsed_attrs: Option, . ) -> PResult<'a, AttrWrapper> { 19,377 ( 0.00%) if let Some(attrs) = already_parsed_attrs { . Ok(attrs) . } else { 12,310 ( 0.00%) self.parse_outer_attributes() . } . } . . /// Parses a single token tree from the input. 5,241,224 ( 0.06%) pub(crate) fn parse_token_tree(&mut self) -> TokenTree { 4,254,323 ( 0.05%) 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. 6,336,434 ( 0.07%) 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. 5,036,890 ( 0.06%) 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; 165,874 ( 0.00%) let stream = frame.tree_cursor.stream.clone(); 165,874 ( 0.00%) let span = frame.span; 82,937 ( 0.00%) let delim = frame.delim; . // Consume close delimiter 165,874 ( 0.00%) self.bump(); 414,685 ( 0.00%) TokenTree::Delimited(span, delim, stream) . } . token::CloseDelim(_) | token::Eof => unreachable!(), . _ => { 1,144,432 ( 0.01%) self.bump(); 2,861,080 ( 0.03%) TokenTree::Token(self.prev_token.clone()) . } . } 4,586,071 ( 0.05%) } . . /// 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 { 6,457 ( 0.00%) let old = self.restrictions; 6,928 ( 0.00%) self.restrictions = res; . let res = f(self); 6,928 ( 0.00%) self.restrictions = old; . res . } . 7,504 ( 0.00%) fn is_crate_vis(&self) -> bool { 4,690 ( 0.00%) self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep) 8,442 ( 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. 7,100 ( 0.00%) pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> { 2,005 ( 0.00%) maybe_whole!(self, NtVis, |x| x); . 665 ( 0.00%) self.expected_tokens.push(TokenType::Keyword(kw::Crate)); 2,660 ( 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". 552 ( 0.00%) return Ok(Visibility { 1,656 ( 0.00%) span: self.token.span.shrink_to_lo(), . kind: VisibilityKind::Inherited, . tokens: None, . }); . } 113 ( 0.00%) let lo = self.prev_token.span; . 565 ( 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. 972 ( 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)`. 324 ( 0.00%) self.bump(); // `(` 216 ( 0.00%) self.bump(); // `crate` 324 ( 0.00%) self.expect(&token::CloseDelim(token::Paren))?; // `)` 108 ( 0.00%) let vis = VisibilityKind::Crate(CrateSugar::PubCrate); . return Ok(Visibility { 324 ( 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 }) 6,390 ( 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 { 101 ( 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, . } . } . 1,110 ( 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, 165 ( 0.00%) |this, _attrs| Ok((f(this)?, TrailingToken::None)), . ) 1,110 ( 0.00%) } . . /// `::{` or `::*` 105,528 ( 0.00%) fn is_import_coupler(&mut self) -> bool { 52,764 ( 0.00%) self.check(&token::ModSep) . && self.look_ahead(1, |t| { 106,339 ( 0.00%) *t == token::OpenDelim(token::Brace) || *t == token::BinOp(token::Star) . }) 60,138 ( 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) . } . 86,688 ( 0.00%) pub fn emit_unclosed_delims(unclosed_delims: &mut Vec, sess: &ParseSess) { 43,344 ( 0.00%) *sess.reached_eof.borrow_mut() |= . unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none()); 43,344 ( 0.00%) for unmatched in unclosed_delims.drain(..) { . if let Some(mut e) = make_unclosed_delims_error(unmatched, sess) { . e.emit(); . } . } 86,688 ( 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 ---------------------------------------- 10,893,731 ( 0.13%) -------------------------------------------------------------------------------- The following files chosen for auto-annotation could not be found: -------------------------------------------------------------------------------- ./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 -------------------------------------------------------------------------------- 2,237,029,454 (25.73%) events annotated