-------------------------------------------------------------------------------- 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 inotify --edition=2018 src/lib.rs --error-format=json --json=diagnostic-rendered-ansi,artifacts,future-incompat --crate-type lib --emit=dep-info,metadata,link -C opt-level=3 -C embed-bitcode=no --cfg feature="default" --cfg feature="futures-core" --cfg feature="stream" --cfg feature="tokio" -C metadata=367b5a86c36c4291 -C extra-filename=-367b5a86c36c4291 --out-dir /usr/home/liquid/tmp/.tmpYw25rV/target/release/deps -L dependency=/usr/home/liquid/tmp/.tmpYw25rV/target/release/deps --extern bitflags=/usr/home/liquid/tmp/.tmpYw25rV/target/release/deps/libbitflags-923cad7af34a271a.rmeta --extern futures_core=/usr/home/liquid/tmp/.tmpYw25rV/target/release/deps/libfutures_core-a2d93a201d329a91.rmeta --extern inotify_sys=/usr/home/liquid/tmp/.tmpYw25rV/target/release/deps/libinotify_sys-a0cbd0a7cbb199e1.rmeta --extern libc=/usr/home/liquid/tmp/.tmpYw25rV/target/release/deps/liblibc-adbe6767c2fae048.rmeta --extern tokio=/usr/home/liquid/tmp/.tmpYw25rV/target/release/deps/libtokio-93b4b77e87d54dca.rmeta -Adeprecated -Aunknown-lints -Zincremental-verify-ich Data file: results/cgout-w-profiling-inotify-0.10.0-Opt-Full Events recorded: Ir Events shown: Ir Event sort order: Ir Thresholds: 0.1 Include dirs: User annotated: Auto-annotation: on -------------------------------------------------------------------------------- Ir -------------------------------------------------------------------------------- 2,915,442,286 (100.0%) PROGRAM TOTALS -------------------------------------------------------------------------------- Ir file:function -------------------------------------------------------------------------------- 117,379,149 ( 4.03%) ./malloc/malloc.c:_int_free 98,795,575 ( 3.39%) ./malloc/malloc.c:_int_malloc 73,573,981 ( 2.52%) ./malloc/malloc.c:malloc 56,986,947 ( 1.95%) ???:llvm::FPPassManager::runOnFunction(llvm::Function&) 38,275,193 ( 1.31%) ./malloc/malloc.c:free 34,967,166 ( 1.20%) ???:llvm::AnalysisManager::getResultImpl(llvm::AnalysisKey*, llvm::Function&) 33,046,703 ( 1.13%) ???:llvm::AnalysisManager::invalidate(llvm::Function&, llvm::PreservedAnalyses const&) 30,152,680 ( 1.03%) ???:llvm::InstCombinerImpl::run() 26,822,110 ( 0.92%) ???:llvm::SelectionDAG::Combine(llvm::CombineLevel, llvm::AAResults*, llvm::CodeGenOpt::Level) 25,052,433 ( 0.86%) ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:__memcpy_avx_unaligned_erms 21,548,812 ( 0.74%) ???:combineInstructionsOverFunction(llvm::Function&, llvm::InstCombineWorklist&, llvm::AAResults*, llvm::AssumptionCache&, llvm::TargetLibraryInfo&, llvm::TargetTransformInfo&, llvm::DominatorTree&, llvm::OptimizationRemarkEmitter&, llvm::BlockFrequencyInfo*, llvm::ProfileSummaryInfo*, unsigned int, llvm::LoopInfo*) 21,465,616 ( 0.74%) ???:llvm::BitstreamCursor::readRecord(unsigned int, llvm::SmallVectorImpl&, llvm::StringRef*) 20,737,639 ( 0.71%) ???:llvm::AttributeList::addAttributes(llvm::LLVMContext&, unsigned int, llvm::AttrBuilder const&) const 17,958,384 ( 0.62%) ./elf/dl-lookup.c:_dl_lookup_symbol_x 17,728,646 ( 0.61%) ???:llvm::DomTreeBuilder::SemiNCAInfo >::CalculateFromScratch(llvm::DominatorTreeBase&, llvm::DomTreeBuilder::SemiNCAInfo >::BatchUpdateInfo*) 16,968,472 ( 0.58%) ./string/../sysdeps/x86_64/multiarch/memcmp-avx2-movbe.S:__memcmp_avx2_movbe 16,197,615 ( 0.56%) ???:runCVP(llvm::Module&) [clone .llvm.11785992503873176614] 15,349,019 ( 0.53%) ./malloc/malloc.c:malloc_consolidate 14,415,886 ( 0.49%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe/macro_parser.rs:rustc_expand::mbe::macro_parser::parse_tt 14,374,063 ( 0.49%) ???:llvm::TargetLibraryInfoImpl::getLibFunc(llvm::Function const&, llvm::LibFunc&) const 12,913,282 ( 0.44%) ./string/../sysdeps/x86_64/multiarch/memset-vec-unaligned-erms.S:__memset_avx2_erms 12,301,189 ( 0.42%) ./elf/dl-lookup.c:do_lookup_x 11,774,525 ( 0.40%) ???:llvm::removeUnreachableBlocks(llvm::Function&, llvm::DomTreeUpdater*, llvm::MemorySSAUpdater*) 11,561,407 ( 0.40%) ???:llvm::ValueHandleBase::AddToUseList() 11,091,380 ( 0.38%) ???:llvm::LiveVariables::runOnBlock(llvm::MachineBasicBlock*, unsigned int) 11,088,988 ( 0.38%) ???:llvm::AttributeList::get(llvm::LLVMContext&, llvm::ArrayRef) 11,017,764 ( 0.38%) ???:bool llvm::DenseMapBase*, llvm::DenseMapInfo<(anonymous namespace)::SimpleValue>, llvm::detail::DenseMapPair<(anonymous namespace)::SimpleValue, llvm::ScopedHashTableVal<(anonymous namespace)::SimpleValue, llvm::Value*>*> >, (anonymous namespace)::SimpleValue, llvm::ScopedHashTableVal<(anonymous namespace)::SimpleValue, llvm::Value*>*, llvm::DenseMapInfo<(anonymous namespace)::SimpleValue>, llvm::detail::DenseMapPair<(anonymous namespace)::SimpleValue, llvm::ScopedHashTableVal<(anonymous namespace)::SimpleValue, llvm::Value*>*> >::LookupBucketFor<(anonymous namespace)::SimpleValue>((anonymous namespace)::SimpleValue const&, llvm::detail::DenseMapPair<(anonymous namespace)::SimpleValue, llvm::ScopedHashTableVal<(anonymous namespace)::SimpleValue, llvm::Value*>*> const*&) const 10,777,083 ( 0.37%) ./malloc/malloc.c:unlink_chunk.constprop.0 10,654,466 ( 0.37%) ???:computeKnownBits(llvm::Value const*, llvm::KnownBits&, unsigned int, (anonymous namespace)::Query const&) [clone .llvm.15619146473165121143] 10,379,420 ( 0.36%) ???:llvm::coro::declaresIntrinsics(llvm::Module const&, std::initializer_list) 10,283,344 ( 0.35%) ???:llvm::PassRegistry::enumerateWith(llvm::PassRegistrationListener*) 9,822,842 ( 0.34%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs:rustc_expand::mbe::macro_parser::parse_tt 9,591,371 ( 0.33%) ./string/../sysdeps/x86_64/multiarch/strcmp-avx2.S:__strncmp_avx2 8,887,307 ( 0.30%) /tmp/gcc-build/x86_64-unknown-linux-gnu/libstdc++-v3/libsupc++/../../../../gcc-5.5.0/libstdc++-v3/libsupc++/new_op.cc:operator new(unsigned long) 8,710,802 ( 0.30%) ???:llvm::PMDataManager::verifyPreservedAnalysis(llvm::Pass*) 8,610,497 ( 0.30%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::next 8,569,501 ( 0.29%) ???:SimplifyICmpInst(unsigned int, llvm::Value*, llvm::Value*, llvm::SimplifyQuery const&, unsigned int) [clone .llvm.1619516508949622737] 8,548,658 ( 0.29%) ???:llvm::detail::PassModel>, llvm::PreservedAnalyses, llvm::AnalysisManager>::run(llvm::Function&, llvm::AnalysisManager&) 8,489,135 ( 0.29%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::bump 8,354,839 ( 0.29%) ???:(anonymous namespace)::LazyValueInfoImpl::solve() [clone .llvm.4316243980339171764] 8,256,325 ( 0.28%) ???:llvm::InstCombinerImpl::visitCallInst(llvm::CallInst&) 8,202,966 ( 0.28%) ???:llvm::AttributeSetNode::get(llvm::LLVMContext&, llvm::AttrBuilder const&) 8,010,986 ( 0.27%) ???:llvm::DataLayout::getAlignment(llvm::Type*, bool) const 7,839,006 ( 0.27%) ???:llvm::DomTreeBuilder::SemiNCAInfo >::runSemiNCA(llvm::DominatorTreeBase&, unsigned int) 7,724,298 ( 0.26%) ???:llvm::InstCombinerImpl::visitICmpInst(llvm::ICmpInst&) 7,539,794 ( 0.26%) ???:llvm::InlineFunction(llvm::CallBase&, llvm::InlineFunctionInfo&, llvm::AAResults*, bool, llvm::Function*) 7,160,413 ( 0.25%) ???:llvm::simplifyCFG(llvm::BasicBlock*, llvm::TargetTransformInfo const&, llvm::DomTreeUpdater*, llvm::SimplifyCFGOptions const&, llvm::ArrayRef) 7,137,696 ( 0.24%) ???:llvm::X86TargetLowering::X86TargetLowering(llvm::X86TargetMachine const&, llvm::X86Subtarget const&) 7,130,554 ( 0.24%) ???:llvm::FindFunctionBackedges(llvm::Function const&, llvm::SmallVectorImpl >&) 6,927,807 ( 0.24%) ???:(anonymous namespace)::MachineCopyPropagation::runOnMachineFunction(llvm::MachineFunction&) 6,908,815 ( 0.24%) ???:llvm::SimplifyInstruction(llvm::Instruction*, llvm::SimplifyQuery const&, llvm::OptimizationRemarkEmitter*) 6,770,390 ( 0.23%) ???:isKnownNonZero(llvm::Value const*, llvm::APInt const&, unsigned int, (anonymous namespace)::Query const&) [clone .llvm.15619146473165121143] 6,645,206 ( 0.23%) ???:llvm::AttributeList::addAttribute(llvm::LLVMContext&, unsigned int, llvm::Attribute::AttrKind) const 6,419,678 ( 0.22%) ???:llvm::DataLayout::getTypeSizeInBits(llvm::Type*) const 6,378,695 ( 0.22%) ???:(anonymous namespace)::EarlyCSE::run() [clone .llvm.7062997131228810369] 6,255,056 ( 0.21%) ???:llvm::DomTreeBuilder::SemiNCAInfo >::CalculateFromScratch(llvm::DominatorTreeBase&, llvm::DomTreeBuilder::SemiNCAInfo >::BatchUpdateInfo*) 6,238,776 ( 0.21%) ???:computeKnownBitsFromOperator(llvm::Operator const*, llvm::APInt const&, llvm::KnownBits&, unsigned int, (anonymous namespace)::Query const&) 6,105,920 ( 0.21%) ???:llvm::TargetLoweringBase::computeRegisterProperties(llvm::TargetRegisterInfo const*) 5,944,525 ( 0.20%) ./string/../sysdeps/x86_64/multiarch/strlen-avx2.S:__strlen_avx2 5,873,689 ( 0.20%) ???:(anonymous namespace)::SimplifyCFGOpt::simplifyCondBranch(llvm::BranchInst*, llvm::IRBuilder&) 5,873,515 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/tokenstream.rs:::next_with_spacing 5,657,714 ( 0.19%) ???:llvm::DomTreeBuilder::SemiNCAInfo >::FindRoots(llvm::DominatorTreeBase const&, llvm::DomTreeBuilder::SemiNCAInfo >::BatchUpdateInfo*) 5,631,703 ( 0.19%) ???:llvm::SelectionDAGISel::SelectCodeCommon(llvm::SDNode*, unsigned char const*, unsigned int) 5,467,353 ( 0.19%) ./string/../sysdeps/x86_64/multiarch/memset-vec-unaligned-erms.S:__memset_avx2_unaligned_erms 5,440,887 ( 0.19%) ???:(anonymous namespace)::LazyValueInfoImpl::getEdgeValue(llvm::Value*, llvm::BasicBlock*, llvm::BasicBlock*, llvm::Instruction*) [clone .llvm.4316243980339171764] 5,166,914 ( 0.18%) ???:llvm::PMDataManager::removeNotPreservedAnalysis(llvm::Pass*) 5,104,931 ( 0.18%) ???:llvm::LiveVariables::HandleRegMask(llvm::MachineOperand const&) 5,098,906 ( 0.17%) ???:computeKnownBits(llvm::Value const*, llvm::APInt const&, llvm::KnownBits&, unsigned int, (anonymous namespace)::Query const&) 5,066,656 ( 0.17%) ???:llvm::MD5::final(llvm::MD5::MD5Result&) 4,970,766 ( 0.17%) ???:llvm::MemorySSA::buildMemorySSA(llvm::BatchAAResults&) 4,916,127 ( 0.17%) ./elf/../sysdeps/x86_64/dl-machine.h:_dl_relocate_object 4,829,990 ( 0.17%) ???:(anonymous namespace)::DeadMachineInstructionElim::eliminateDeadMI(llvm::MachineFunction&) 4,798,606 ( 0.16%) ???:computeKnownBitsFromAssume(llvm::Value const*, llvm::KnownBits&, unsigned int, (anonymous namespace)::Query const&) 4,751,875 ( 0.16%) ???:llvm::FoldingSetBase::FindNodeOrInsertPos(llvm::FoldingSetNodeID const&, void*&, llvm::FoldingSetBase::FoldingSetInfo const&) 4,745,378 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/library/std/src/sys/unix/alloc.rs:__rdl_alloc 4,687,487 ( 0.16%) ???:llvm::BasicAAResult::alias(llvm::MemoryLocation const&, llvm::MemoryLocation const&, llvm::AAQueryInfo&) 4,640,467 ( 0.16%) ???:??? 4,611,756 ( 0.16%) ./malloc/malloc.c:realloc 4,516,348 ( 0.15%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, (), core::hash::BuildHasherDefault>>::from_hash::>::{closure#0}> 4,443,583 ( 0.15%) ???:(anonymous namespace)::CVPLatticeFunc::ComputeInstructionState(llvm::Instruction&, llvm::DenseMap, llvm::PointerIntPairInfo > >, (anonymous namespace)::CVPLatticeVal, llvm::DenseMapInfo, llvm::PointerIntPairInfo > > >, llvm::detail::DenseMapPair, llvm::PointerIntPairInfo > >, (anonymous namespace)::CVPLatticeVal> >&, llvm::SparseSolver, llvm::PointerIntPairInfo > >, (anonymous namespace)::CVPLatticeVal, llvm::LatticeKeyInfo, llvm::PointerIntPairInfo > > > >&) 4,376,133 ( 0.15%) ???:(anonymous namespace)::BitcodeReader::parseModule(unsigned long, bool, llvm::function_ref, std::allocator > > (llvm::StringRef)>) 4,372,605 ( 0.15%) ???:llvm::ScheduleDAGSDNodes::BuildSchedUnits() 4,341,368 ( 0.15%) ???:llvm::SROA::runOnAlloca(llvm::AllocaInst&) 4,289,631 ( 0.15%) ???:llvm::PMTopLevelManager::setLastUser(llvm::ArrayRef, llvm::Pass*) 4,289,201 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs:::short_write_process_buffer:: 4,198,495 ( 0.14%) ???:llvm::InstCombinerImpl::SimplifyDemandedUseBits(llvm::Value*, llvm::APInt, llvm::KnownBits&, unsigned int, llvm::Instruction*) 4,169,562 ( 0.14%) ???:llvm::TargetLoweringBase::getTypeConversion(llvm::LLVMContext&, llvm::EVT) const 4,156,881 ( 0.14%) ???:llvm::BlockFrequencyInfoImpl::initializeRPOT() 4,056,377 ( 0.14%) ???:SetImpliedBits(llvm::FeatureBitset&, llvm::FeatureBitset const&, llvm::ArrayRef) 4,040,911 ( 0.14%) ???:(anonymous namespace)::AggressiveDeadCodeElimination::performDeadCodeElimination() 3,991,371 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:core::ptr::drop_in_place:: 3,974,014 ( 0.14%) ???:llvm::LivePhysRegs::stepBackward(llvm::MachineInstr const&) 3,944,898 ( 0.14%) ???:(anonymous namespace)::LazyValueInfoImpl::getValueInBlock(llvm::Value*, llvm::BasicBlock*, llvm::Instruction*) [clone .llvm.4316243980339171764] 3,848,200 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::bump_with 3,795,550 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe/macro_parser.rs:::clone 3,720,770 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe/transcribe.rs:rustc_expand::mbe::transcribe::transcribe 3,701,460 ( 0.13%) ???:(anonymous namespace)::DAGCombiner::combine(llvm::SDNode*) 3,696,328 ( 0.13%) ???:llvm::PopulateLoopsDFS::traverse(llvm::BasicBlock*) 3,688,133 ( 0.13%) ./stdlib/msort.c:msort_with_tmp.part.0 3,636,742 ( 0.12%) ???:llvm::GVN::processBlock(llvm::BasicBlock*) 3,616,080 ( 0.12%) ???:llvm::PMTopLevelManager::AUFoldingSetNode::Profile(llvm::FoldingSetNodeID&, llvm::AnalysisUsage const&) 3,608,781 ( 0.12%) ???:llvm::LoopInfoBase::analyze(llvm::DominatorTreeBase const&) 3,574,775 ( 0.12%) ./malloc/malloc.c:calloc 3,547,974 ( 0.12%) ???:llvm::isNonEscapingLocalObject(llvm::Value const*, llvm::SmallDenseMap, llvm::detail::DenseMapPair >*) 3,438,789 ( 0.12%) ???:llvm::MachineInstr::addOperand(llvm::MachineFunction&, llvm::MachineOperand const&) 3,388,240 ( 0.12%) ???:(anonymous namespace)::GetCFGOnlyPasses::passEnumerate(llvm::PassInfo const*) [clone .llvm.764396836974782617] 3,386,715 ( 0.12%) ???:(anonymous namespace)::eliminateDeadStores(llvm::Function&, llvm::AAResults&, llvm::MemorySSA&, llvm::DominatorTree&, llvm::PostDominatorTree&, llvm::TargetLibraryInfo const&, llvm::LoopInfo const&) [clone .llvm.5769264623867638418] 3,364,225 ( 0.12%) ???:llvm::SmallPtrSetImplBase::insert_imp_big(void const*) 3,360,715 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::ident 3,341,618 ( 0.11%) ???:llvm::JumpThreadingPass::processBlock(llvm::BasicBlock*) 3,326,075 ( 0.11%) ???:llvm::SCCPInstVisitor::solve() 3,316,640 ( 0.11%) ???:llvm::DemandedBits::isInstructionDead(llvm::Instruction*) 3,299,409 ( 0.11%) ???:llvm::ConstantFoldTerminator(llvm::BasicBlock*, bool, llvm::TargetLibraryInfo const*, llvm::DomTreeUpdater*) 3,274,903 ( 0.11%) ???:llvm::SimplifyGEPInst(llvm::Type*, llvm::ArrayRef, llvm::SimplifyQuery const&) 3,261,068 ( 0.11%) ???:llvm::BlockFrequencyInfoImpl::tryToComputeMassInFunction() 3,237,949 ( 0.11%) ./malloc/malloc.c:_int_realloc 3,231,747 ( 0.11%) ???:llvm::X86TargetMachine::getTargetTransformInfo(llvm::Function const&) 3,212,903 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_serialize/src/opaque.rs:>::decode 3,199,547 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::clone 3,189,630 ( 0.11%) ???:int llvm::array_pod_sort_comparator(void const*, void const*) 3,180,611 ( 0.11%) ???:llvm::BlockFrequencyInfoImplBase::finalizeMetrics() 3,166,578 ( 0.11%) ???:updateCGAndAnalysisManagerForPass(llvm::LazyCallGraph&, llvm::LazyCallGraph::SCC&, llvm::LazyCallGraph::Node&, llvm::AnalysisManager&, llvm::CGSCCUpdateResult&, llvm::AnalysisManager&, bool) [clone .llvm.5426518467876156712] 3,155,399 ( 0.11%) ???:llvm::ConstantRange::makeExactICmpRegion(llvm::CmpInst::Predicate, llvm::APInt const&) 3,135,042 ( 0.11%) ???:(anonymous namespace)::PruningFunctionCloner::CloneBlock(llvm::BasicBlock const*, llvm::ilist_iterator, false, true>, std::vector >&) 3,109,392 ( 0.11%) ???:llvm::X86TargetMachine::getSubtargetImpl(llvm::Function const&) const 3,082,744 ( 0.11%) ???:llvm::IDFCalculatorBase::calculate(llvm::SmallVectorImpl&) 3,038,821 ( 0.10%) ???:std::back_insert_iterator > > std::__copy_move_a2, false, llvm::GraphTraits >, std::back_insert_iterator > > >(llvm::po_iterator, false, llvm::GraphTraits >, llvm::po_iterator, false, llvm::GraphTraits >, std::back_insert_iterator > >) 3,034,712 ( 0.10%) ???:llvm::PassManager, llvm::LazyCallGraph&, llvm::CGSCCUpdateResult&>::run(llvm::LazyCallGraph::SCC&, llvm::AnalysisManager&, llvm::LazyCallGraph&, llvm::CGSCCUpdateResult&) 3,032,401 ( 0.10%) ???:llvm::DenseMapBase, std::unique_ptr<(anonymous namespace)::LazyValueInfoCache::BlockCacheEntry, std::default_delete<(anonymous namespace)::LazyValueInfoCache::BlockCacheEntry> >, llvm::DenseMapInfo >, llvm::detail::DenseMapPair, std::unique_ptr<(anonymous namespace)::LazyValueInfoCache::BlockCacheEntry, std::default_delete<(anonymous namespace)::LazyValueInfoCache::BlockCacheEntry> > > >, llvm::PoisoningVH, std::unique_ptr<(anonymous namespace)::LazyValueInfoCache::BlockCacheEntry, std::default_delete<(anonymous namespace)::LazyValueInfoCache::BlockCacheEntry> >, llvm::DenseMapInfo >, llvm::detail::DenseMapPair, std::unique_ptr<(anonymous namespace)::LazyValueInfoCache::BlockCacheEntry, std::default_delete<(anonymous namespace)::LazyValueInfoCache::BlockCacheEntry> > > >::destroyAll() [clone .llvm.4316243980339171764] 3,013,446 ( 0.10%) ???:llvm::Intrinsic::getDeclaration(llvm::Module*, unsigned int, llvm::ArrayRef) 3,013,399 ( 0.10%) ???:llvm::detail::AnalysisResultModel, llvm::Function>, llvm::OuterAnalysisManagerProxy, llvm::Function>::Result, llvm::PreservedAnalyses, llvm::AnalysisManager::Invalidator, true>::invalidate(llvm::Function&, llvm::PreservedAnalyses const&, llvm::AnalysisManager::Invalidator&) 3,013,364 ( 0.10%) ./string/../sysdeps/x86_64/multiarch/memchr-avx2.S:__memchr_avx2 3,006,441 ( 0.10%) ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:__memcpy_sse2_unaligned_erms 3,003,399 ( 0.10%) ???:runImpl(llvm::Function&, llvm::LazyValueInfo*, llvm::DominatorTree*, llvm::SimplifyQuery const&) [clone .llvm.16011871802505272439] 2,955,076 ( 0.10%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/rustc_entry.rs:>>::rustc_entry 2,948,032 ( 0.10%) ???:llvm::DomTreeBuilder::SemiNCAInfo >::runSemiNCA(llvm::DominatorTreeBase&, unsigned int) 2,940,711 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_metadata/src/rmeta/decoder.rs:>::decode 2,923,905 ( 0.10%) ???:llvm::SROA::runImpl(llvm::Function&, llvm::DominatorTree&, llvm::AssumptionCache&) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs -------------------------------------------------------------------------------- Ir -- line 57 ---------------------------------------- . /// # Examples . /// . /// Basic usage: . /// . /// ``` . #[doc = concat!("assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 336 ( 0.00%) pub fn from_str_radix(src: &str, radix: u32) -> Result { 168 ( 0.00%) from_str_radix(src, radix) 504 ( 0.00%) } . . /// Returns the number of ones in the binary representation of `self`. . /// . /// # Examples . /// . /// Basic usage: . /// . /// ``` -- line 75 ---------------------------------------- -- line 80 ---------------------------------------- . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_math", since = "1.32.0")] . #[doc(alias = "popcount")] . #[doc(alias = "popcnt")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn count_ones(self) -> u32 { 137,895 ( 0.00%) intrinsics::ctpop(self as $ActualT) as u32 . } . . /// Returns the number of zeros in the binary representation of `self`. . /// . /// # Examples . /// . /// Basic usage: . /// -- line 96 ---------------------------------------- -- line 118 ---------------------------------------- . /// assert_eq!(n.leading_zeros(), 2); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn leading_zeros(self) -> u32 { 330,894 ( 0.01%) intrinsics::ctlz(self as $ActualT) as u32 . } . . /// Returns the number of trailing zeros in the binary representation . /// of `self`. . /// . /// # Examples . /// . /// Basic usage: -- line 134 ---------------------------------------- -- line 139 ---------------------------------------- . /// assert_eq!(n.trailing_zeros(), 3); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn trailing_zeros(self) -> u32 { 281,416 ( 0.01%) intrinsics::cttz(self) as u32 . } . . /// Returns the number of leading ones in the binary representation of `self`. . /// . /// # Examples . /// . /// Basic usage: . /// -- line 155 ---------------------------------------- -- line 204 ---------------------------------------- . #[doc = concat!("assert_eq!(n.rotate_left(", $rot, "), m);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn rotate_left(self, n: u32) -> Self { 5,989,799 ( 0.21%) intrinsics::rotate_left(self, n as $SelfT) . } . . /// Shifts the bits to the right by a specified amount, `n`, . /// wrapping the truncated bits to the beginning of the resulting . /// integer. . /// . /// Please note this isn't the same operation as the `>>` shifting operator! . /// -- line 220 ---------------------------------------- -- line 430 ---------------------------------------- . #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline] . pub const fn checked_add(self, rhs: Self) -> Option { 4 ( 0.00%) let (a, b) = self.overflowing_add(rhs); . if unlikely!(b) {None} else {Some(a)} . } . . /// Unchecked integer addition. Computes `self + rhs`, assuming overflow . /// cannot occur. . /// . /// # Safety . /// -- line 446 ---------------------------------------- -- line 456 ---------------------------------------- . )] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")] . #[inline(always)] . pub const unsafe fn unchecked_add(self, rhs: Self) -> Self { . // SAFETY: the caller must uphold the safety contract for . // `unchecked_add`. 632,421 ( 0.02%) unsafe { intrinsics::unchecked_add(self, rhs) } . } . . /// Checked addition with a signed integer. Computes `self + rhs`, . /// returning `None` if overflow occurred. . /// . /// # Examples . /// . /// Basic usage: -- line 472 ---------------------------------------- -- line 525 ---------------------------------------- . )] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")] . #[inline(always)] . pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self { . // SAFETY: the caller must uphold the safety contract for . // `unchecked_sub`. 25,369 ( 0.00%) unsafe { intrinsics::unchecked_sub(self, rhs) } . } . . /// Checked integer multiplication. Computes `self * rhs`, returning . /// `None` if overflow occurred. . /// . /// # Examples . /// . /// Basic usage: -- line 541 ---------------------------------------- -- line 596 ---------------------------------------- . without modifying the original"] . #[inline] . pub const fn checked_div(self, rhs: Self) -> Option { . if unlikely!(rhs == 0) { . None . } else { . // SAFETY: div by zero has been checked above and unsigned types have no other . // failure modes for division 616 ( 0.00%) Some(unsafe { intrinsics::unchecked_div(self, rhs) }) . } . } . . /// Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None` . /// if `rhs == 0`. . /// . /// # Examples . /// -- line 612 ---------------------------------------- -- line 1035 ---------------------------------------- . #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_add(127), ", stringify!($SelfT), "::MAX);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")] . #[inline(always)] . pub const fn saturating_add(self, rhs: Self) -> Self { 117,533 ( 0.00%) intrinsics::saturating_add(self, rhs) . } . . /// Saturating addition with a signed integer. Computes `self + rhs`, . /// saturating at the numeric bounds instead of overflowing. . /// . /// # Examples . /// . /// Basic usage: -- line 1051 ---------------------------------------- -- line 1084 ---------------------------------------- . #[doc = concat!("assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")] . #[inline(always)] . pub const fn saturating_sub(self, rhs: Self) -> Self { 5,713 ( 0.00%) intrinsics::saturating_sub(self, rhs) . } . . /// Saturating integer multiplication. Computes `self * rhs`, . /// saturating at the numeric bounds instead of overflowing. . /// . /// # Examples . /// . /// Basic usage: -- line 1100 ---------------------------------------- -- line 1175 ---------------------------------------- . #[doc = concat!("assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::MAX), 199);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn wrapping_add(self, rhs: Self) -> Self { 3,035,091 ( 0.10%) intrinsics::wrapping_add(self, rhs) . } . . /// Wrapping (modular) addition with a signed integer. Computes . /// `self + rhs`, wrapping around at the boundary of the type. . /// . /// # Examples . /// . /// Basic usage: -- line 1191 ---------------------------------------- -- line 1217 ---------------------------------------- . #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::MAX), 101);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn wrapping_sub(self, rhs: Self) -> Self { 1,178,289 ( 0.04%) intrinsics::wrapping_sub(self, rhs) . } . . /// Wrapping (modular) multiplication. Computes `self * . /// rhs`, wrapping around at the boundary of the type. . /// . /// # Examples . /// . /// Basic usage: -- line 1233 ---------------------------------------- -- line 1240 ---------------------------------------- . /// assert_eq!(25u8.wrapping_mul(12), 44); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn wrapping_mul(self, rhs: Self) -> Self { 3,917,282 ( 0.13%) intrinsics::wrapping_mul(self, rhs) . } . . /// Wrapping (modular) division. Computes `self / rhs`. . /// Wrapped division on unsigned types is just normal division. . /// There's no way wrapping could ever happen. . /// This function exists, so that all operations . /// are accounted for in the wrapping operations. . /// -- line 1256 ---------------------------------------- -- line 1397 ---------------------------------------- . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn wrapping_shl(self, rhs: u32) -> Self { . // SAFETY: the masking by the bitsize of the type ensures that we do not shift . // out of bounds . unsafe { 4 ( 0.00%) intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT) . } . } . . /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`, . /// where `mask` removes any high-order bits of `rhs` that . /// would cause the shift to exceed the bitwidth of the type. . /// . /// Note that this is *not* the same as a rotate-right; the -- line 1413 ---------------------------------------- -- line 1491 ---------------------------------------- . #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));")] . #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));")] . /// ``` . #[stable(feature = "wrapping", since = "1.7.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] 9 ( 0.00%) pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) { 496,403 ( 0.02%) let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT); . (a as Self, b) 18 ( 0.00%) } . . /// Calculates `self + rhs + carry` without the ability to overflow. . /// . /// Performs "ternary addition" which takes in an extra bit to add, and may return an . /// additional bit of overflow. This allows for chaining together multiple additions . /// to create "big integers" which represent larger values. . /// . #[doc = concat!("This can be thought of as a ", stringify!($BITS), "-bit \"full adder\", in the electronics sense.")] -- line 1510 ---------------------------------------- -- line 1588 ---------------------------------------- . #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));")] . /// ``` . #[stable(feature = "wrapping", since = "1.7.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) { 126,731 ( 0.00%) let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT); . (a as Self, b) . } . . /// Calculates `self - rhs - borrow` without the ability to overflow. . /// . /// Performs "ternary subtraction" which takes in an extra bit to subtract, and may return . /// an additional bit of overflow. This allows for chaining together multiple subtractions . /// to create "big integers" which represent larger values. -- line 1604 ---------------------------------------- -- line 1673 ---------------------------------------- . /// assert_eq!(5u32.overflowing_mul(2), (10, false)); . /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true)); . /// ``` . #[stable(feature = "wrapping", since = "1.7.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] 2 ( 0.00%) pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) { 1,128,600 ( 0.04%) let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT); . (a as Self, b) 1 ( 0.00%) } . . /// Calculates the divisor when `self` is divided by `rhs`. . /// . /// Returns a tuple of the divisor along with a boolean indicating . /// whether an arithmetic overflow would occur. Note that for unsigned . /// integers overflow never occurs, so the second value is always . /// `false`. . /// -- line 1692 ---------------------------------------- -- line 2132 ---------------------------------------- . #[doc = concat!("assert!(16", stringify!($SelfT), ".is_power_of_two());")] . #[doc = concat!("assert!(!10", stringify!($SelfT), ".is_power_of_two());")] . /// ``` . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")] . #[inline(always)] . pub const fn is_power_of_two(self) -> bool { 222 ( 0.00%) self.count_ones() == 1 . } . . // Returns one less than next power of two. . // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8) . // . // 8u8.one_less_than_next_power_of_two() == 7 . // 6u8.one_less_than_next_power_of_two() == 7 . // . // This method cannot overflow, as in the `next_power_of_two` . // overflow cases it instead ends up returning the maximum value . // of the type, and can return 0 for 0. . #[inline] . #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")] . const fn one_less_than_next_power_of_two(self) -> Self { 35,070 ( 0.00%) if self <= 1 { return 0; } . 26,089 ( 0.00%) let p = self - 1; . // SAFETY: Because `p > 0`, it cannot consist entirely of leading zeros. . // That means the shift is always in-bounds, and some processors . // (such as intel pre-haswell) have more efficient ctlz . // intrinsics when the argument is non-zero. 78,156 ( 0.00%) let z = unsafe { intrinsics::ctlz_nonzero(p) }; 26,064 ( 0.00%) <$SelfT>::MAX >> z . } . . /// Returns the smallest power of two greater than or equal to `self`. . /// . /// When return value overflows (i.e., `self > (1 << (N-1))` for type . /// `uN`), it panics in debug mode and the return value is wrapped to 0 in . /// release mode (the only situation in which method can return 0). . /// -- line 2171 ---------------------------------------- -- line 2179 ---------------------------------------- . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline] . #[rustc_inherit_overflow_checks] . pub const fn next_power_of_two(self) -> Self { 17,040 ( 0.00%) self.one_less_than_next_power_of_two() + 1 . } . . /// Returns the smallest power of two greater than or equal to `n`. If . /// the next power of two is greater than the type's maximum value, . /// `None` is returned, otherwise the power of two is wrapped in `Some`. . /// . /// # Examples . /// -- line 2195 ---------------------------------------- 56,632 ( 0.00%) -------------------------------------------------------------------------------- -- 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; . 345,087 ( 0.01%) fn visit_span(&mut self, span: &mut Span) { 230,058 ( 0.01%) *span = span.apply_mark(self.0.to_expn_id(), self.1) 306,744 ( 0.01%) } . } . . /// 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 }); 5,432 ( 0.00%) Frame::Delimited { forest, idx: 0, span: DelimSpan::dummy() } . } . } . . impl Iterator for Frame { . type Item = mbe::TokenTree; . . fn next(&mut self) -> Option { 316,532 ( 0.01%) match *self { 58,018 ( 0.00%) Frame::Delimited { ref forest, ref mut idx, .. } => { 87,027 ( 0.00%) *idx += 1; . forest.tts.get(*idx - 1).cloned() . } 150,372 ( 0.01%) Frame::Sequence { ref forest, ref mut idx, .. } => { 150,372 ( 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. 6,810 ( 0.00%) pub(super) fn transcribe<'a>( . cx: &ExtCtxt<'a>, . interp: &FxHashMap, . src: Vec, . transparency: Transparency, . ) -> PResult<'a, TokenStream> { . // Nothing for us to transcribe... 681 ( 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. 5,432 ( 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(); 2,716 ( 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. 413,018 ( 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. 110,360 ( 0.00%) if let Frame::Sequence { idx, sep, .. } = stack.last_mut().unwrap() { . let (repeat_idx, repeat_len) = repeats.last_mut().unwrap(); 78,704 ( 0.00%) *repeat_idx += 1; 19,676 ( 0.00%) if repeat_idx < repeat_len { 13,189 ( 0.00%) *idx = 0; 26,378 ( 0.00%) if let Some(sep) = sep { 238 ( 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`. 28,802 ( 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. 31,656 ( 0.00%) Frame::Delimited { forest, span, .. } => { 7,914 ( 0.00%) if result_stack.is_empty() { . // No results left to compute! We are back at the top-level. 4,074 ( 0.00%) return Ok(TokenStream::new(result)); . } . . // Step back into the parent Delimited. 94,055 ( 0.00%) let tree = TokenTree::Delimited(span, forest.delim, TokenStream::new(result)); 21,705 ( 0.00%) result = result_stack.pop().unwrap(); . result.push(tree.into()); . } 15,828 ( 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. 309,258 ( 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. 26,244 ( 0.00%) seq @ mbe::TokenTree::Sequence(..) => { 45,927 ( 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. 45,927 ( 0.00%) let mbe::TokenTree::Sequence(sp, seq) = seq else { . unreachable!() . }; . . // Is the repetition empty? 13,122 ( 0.00%) if len == 0 { 74 ( 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. 58,383 ( 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. 120,636 ( 0.00%) mbe::TokenTree::MetaVar(mut sp, mut orignal_ident) => { . // Find the matched nonterminal from the macro invocation, and use it to replace . // the meta-var. 80,424 ( 0.00%) let ident = MacroRulesNormalizedIdent::new(orignal_ident); 120,636 ( 0.00%) if let Some(cur_matched) = lookup_cur_matched(ident, interp, &repeats) { 60,318 ( 0.00%) if let MatchedNonterminal(nt) = cur_matched { 60,318 ( 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. 18,696 ( 0.00%) marker.visit_span(&mut sp); 37,392 ( 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). 43,410 ( 0.00%) mbe::TokenTree::Delimited(mut span, delimited) => { . mut_visit::visit_delim_span(&mut span, &mut marker); 43,410 ( 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) => { 105,846 ( 0.00%) let mut tt = TokenTree::Token(token); 52,923 ( 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"), . } . } 8,168 ( 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`. 247,347 ( 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 { 178,536 ( 0.01%) match matched { . MatchedNonterminal(_) => break, 39,556 ( 0.00%) MatchedSeq(ref ads) => matched = ads.get(idx).unwrap(), . } . } . . matched . }) 247,347 ( 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. 108,297 ( 0.00%) fn with(self, other: LockstepIterSize) -> LockstepIterSize { 37,943 ( 0.00%) match self { . LockstepIterSize::Unconstrained => other, . LockstepIterSize::Contradiction(_) => self, 8,078 ( 0.00%) LockstepIterSize::Constraint(l_len, ref l_id) => match other { . LockstepIterSize::Unconstrained => self, . LockstepIterSize::Contradiction(_) => other, 2,436 ( 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) . } . }, . } 86,075 ( 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. 185,940 ( 0.01%) fn lockstep_iter_size( . tree: &mbe::TokenTree, . interpolations: &FxHashMap, . repeats: &[(usize, usize)], . ) -> LockstepIterSize { . use mbe::TokenTree; 130,158 ( 0.00%) match *tree { . TokenTree::Delimited(_, ref delimed) => { 1,498 ( 0.00%) delimed.tts.iter().fold(LockstepIterSize::Unconstrained, |size, tt| { 39,340 ( 0.00%) size.with(lockstep_iter_size(tt, interpolations, repeats)) . }) . } . TokenTree::Sequence(_, ref seq) => { 7,357 ( 0.00%) seq.tts.iter().fold(LockstepIterSize::Unconstrained, |size, tt| { 161,364 ( 0.01%) size.with(lockstep_iter_size(tt, interpolations, repeats)) . }) . } . TokenTree::MetaVar(_, name) | TokenTree::MetaVarDecl(_, name, _) => { 14,754 ( 0.00%) let name = MacroRulesNormalizedIdent::new(name); 66,393 ( 0.00%) match lookup_cur_matched(name, interpolations, repeats) { 14,754 ( 0.00%) Some(matched) => match matched { . MatchedNonterminal(_) => LockstepIterSize::Unconstrained, 44,238 ( 0.00%) MatchedSeq(ref ads) => LockstepIterSize::Constraint(ads.len(), name), . }, . _ => LockstepIterSize::Unconstrained, . } . } . TokenTree::Token(..) => LockstepIterSize::Unconstrained, . } 148,752 ( 0.01%) } 904,589 ( 0.03%) -------------------------------------------------------------------------------- -- 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,162,922 ( 0.04%) 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)); 96,556 ( 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::()); 14,970,368 ( 0.51%) let top7 = hash >> (hash_len * 8 - 7); . (top7 & 0x7f) as u8 // truncation . } . . /// Probe sequence based on triangular numbers, which is guaranteed (since our . /// table size is a power of two) to visit every group of elements exactly once. . /// . /// A triangular probe has us jump by 1 more group every time. So first we . /// jump by 1 group (meaning we just continue our linear scan), then 2 groups -- line 159 ---------------------------------------- -- line 170 ---------------------------------------- . #[inline] . fn move_next(&mut self, bucket_mask: usize) { . // We should have found an empty bucket by now and ended the probe. . debug_assert!( . self.stride <= bucket_mask, . "Went past end of probe sequence" . ); . 138,852 ( 0.00%) self.stride += Group::WIDTH; 138,852 ( 0.00%) self.pos += self.stride; 116,134 ( 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. 68,114 ( 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. 145,610 ( 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. 29,610 ( 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 { 178,329 ( 0.01%) 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. 39,968 ( 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 = 140,294 ( 0.00%) size.checked_mul(buckets)?.checked_add(ctrl_align - 1)? & !(ctrl_align - 1); 186,650 ( 0.01%) 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 { 1,386 ( 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 { 9,426 ( 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 { 60 ( 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 { 4,811 ( 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")] 8,487 ( 0.00%) pub unsafe fn erase_no_drop(&mut self, item: &Bucket) { 8,487 ( 0.00%) let index = self.bucket_index(item); . self.table.erase(index); 16,974 ( 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. 5,794 ( 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 { 11,180 ( 0.00%) self.erase_no_drop(&item); 51 ( 0.00%) item.read() . } . . /// Finds and removes an element from the table, returning it. . #[cfg_attr(feature = "inline-more", inline)] 373,637 ( 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,584 ( 0.00%) match self.find(hash, eq) { 5,807 ( 0.00%) Some(bucket) => Some(unsafe { self.remove(bucket) }), 55,887 ( 0.00%) None => None, . } 546,400 ( 0.02%) } . . /// 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) { 8,364 ( 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) { 231,701 ( 0.01%) if additional > self.table.growth_left { . // Avoid `Result::unwrap_or_else` because it bloats LLVM IR. 118,278 ( 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)] 272,637 ( 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 . }, . ) . } 193,792 ( 0.01%) } . . /// 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)] 1,645,346 ( 0.06%) 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,743 ( 0.00%) let old_ctrl = *self.table.ctrl(index); 1,062,225 ( 0.04%) 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); 4 ( 0.00%) bucket.write(value); . bucket . } 1,210,283 ( 0.04%) } . . /// 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)] 355,688 ( 0.01%) pub fn insert_entry(&mut self, hash: u64, value: T, hasher: impl Fn(&T) -> u64) -> &mut T { 107 ( 0.00%) unsafe { self.insert(hash, value, hasher).as_mut() } 266,766 ( 0.01%) } . . /// Inserts a new element into the table, without growing the table. . /// . /// There must be enough space in the table to insert the new element. . /// . /// This does not check if the given element already exists in the table. . #[cfg_attr(feature = "inline-more", inline)] . #[cfg(any(feature = "raw", feature = "rustc-internal-api"))] 1,842 ( 0.00%) pub unsafe fn insert_no_grow(&mut self, hash: u64, value: T) -> Bucket { 279,010 ( 0.01%) let (index, old_ctrl) = self.table.prepare_insert_slot(hash); 8,415 ( 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. 570,783 ( 0.02%) self.table.growth_left -= special_is_empty(old_ctrl) as usize; . . bucket.write(value); 460,984 ( 0.02%) self.table.items += 1; . bucket 3,671 ( 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] 24,305 ( 0.00%) pub fn find(&self, hash: u64, mut eq: impl FnMut(&T) -> bool) -> Option> { 8,703 ( 0.00%) let result = self.table.find_inner(hash, &mut |index| unsafe { 16,422 ( 0.00%) eq(self.bucket(index).as_ref()) 2,749 ( 0.00%) }); . . // Avoid `Option::map` because it bloats LLVM IR. . match result { 1,069 ( 0.00%) Some(index) => Some(unsafe { self.bucket(index) }), . None => None, . } 27,520 ( 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. 69,824 ( 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] 1,778 ( 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. 10,542 ( 0.00%) match self.find(hash, eq) { . Some(bucket) => Some(unsafe { bucket.as_mut() }), . None => None, . } 2,032 ( 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 { 484,162 ( 0.02%) self.len() == 0 . } . . /// Returns the number of buckets in the table. . #[inline] . pub fn buckets(&self) -> usize { . self.table.bucket_mask + 1 . } . -- line 936 ---------------------------------------- -- line 938 ---------------------------------------- . /// 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 { . let data = Bucket::from_base_index(self.data_end(), 0); . RawIter { . iter: RawIterRange::new(self.table.ctrl.as_ptr(), data, self.table.buckets()), 57,354 ( 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(); 4,524 ( 0.00%) let allocation = self.into_allocation(); 3,393 ( 0.00%) RawIntoIter { 5,655 ( 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)> { 2,111 ( 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(( 344 ( 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 { 371,947 ( 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)] 243,779 ( 0.01%) 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()); . } . 58,988 ( 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)); 137,598 ( 0.00%) Ok(Self { . ctrl, 57,002 ( 0.00%) bucket_mask: buckets - 1, . items: 0, . growth_left: bucket_mask_to_capacity(buckets - 1), . alloc, . }) 177,808 ( 0.01%) } . . #[inline] 20,177 ( 0.00%) fn fallible_with_capacity( . alloc: A, . table_layout: TableLayout, . capacity: usize, . fallibility: Fallibility, . ) -> Result { 5,276 ( 0.00%) if capacity == 0 { 3,387 ( 0.00%) Ok(Self::new_in(alloc)) . } else { . unsafe { . let buckets = . capacity_to_buckets(capacity).ok_or_else(|| fallibility.capacity_overflow())?; . 111,448 ( 0.00%) let result = Self::new_uninitialized(alloc, table_layout, buckets, fallibility)?; . result.ctrl(0).write_bytes(EMPTY, result.num_ctrl_bytes()); . 11,393 ( 0.00%) Ok(result) . } . } 20,177 ( 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] 94,725 ( 0.00%) unsafe fn prepare_insert_slot(&self, hash: u64) -> (usize, u8) { . let index = self.find_insert_slot(hash); 94,725 ( 0.00%) let old_ctrl = *self.ctrl(index); . self.set_ctrl_h2(index, hash); . (index, old_ctrl) 189,450 ( 0.01%) } . . /// 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)); 754,750 ( 0.03%) if let Some(bit) = group.match_empty_or_deleted().lowest_set_bit() { 2,208,921 ( 0.08%) 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,000,944 ( 0.03%) if unlikely(is_full(*self.ctrl(result))) { . debug_assert!(self.bucket_mask < Group::WIDTH); . debug_assert_ne!(probe_seq.pos, 0); . return Group::load_aligned(self.ctrl(0)) . .match_empty_or_deleted() . .lowest_set_bit_nonzero(); . } . . return result; -- line 1165 ---------------------------------------- -- line 1171 ---------------------------------------- . . /// Searches for an element in the table. This uses dynamic dispatch to reduce the amount of . /// code generated, but it is eliminated by LLVM optimizations. . #[inline] . fn find_inner(&self, hash: u64, eq: &mut dyn FnMut(usize) -> bool) -> Option { . let h2_hash = h2(hash); . let mut probe_seq = self.probe_seq(hash); . 43,356 ( 0.00%) loop { . let group = unsafe { Group::load(self.ctrl(probe_seq.pos)) }; . 1,946,419 ( 0.07%) for bit in group.match_byte(h2_hash) { 3,591,612 ( 0.12%) let index = (probe_seq.pos + bit) & self.bucket_mask; . 2,489,692 ( 0.09%) if likely(eq(index)) { . return Some(index); . } . } . 669,963 ( 0.02%) if likely(group.match_empty().any_bit_set()) { . return None; . } . . probe_seq.move_next(self.bucket_mask); . } . } . . #[allow(clippy::mut_mut)] -- line 1198 ---------------------------------------- -- 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(); 2,804,488 ( 0.10%) 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 { 12,287,099 ( 0.42%) 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,327,267 ( 0.05%) self.growth_left -= special_is_empty(old_ctrl) as usize; . self.set_ctrl_h2(index, hash); 1,061,776 ( 0.04%) 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; . probe_index(i) == probe_index(new_i) -- line 1281 ---------------------------------------- -- 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] | . // --------------------------------------------- 2,138,673 ( 0.07%) let index2 = ((index.wrapping_sub(Group::WIDTH)) & self.bucket_mask) + Group::WIDTH; . 712,561 ( 0.02%) *self.ctrl(index) = ctrl; 712,865 ( 0.02%) *self.ctrl(index2) = ctrl; . } . . /// Returns a pointer to a control byte. . #[inline] . unsafe fn ctrl(&self, index: usize) -> *mut u8 { . debug_assert!(index < self.num_ctrl_bytes()); . self.ctrl.as_ptr().add(index) . } . . #[inline] . fn buckets(&self) -> usize { 171,942 ( 0.01%) self.bucket_mask + 1 . } . . #[inline] . fn num_ctrl_bytes(&self) -> usize { 136,892 ( 0.00%) self.bucket_mask + 1 + Group::WIDTH . } . . #[inline] . fn is_empty_singleton(&self) -> bool { 711,649 ( 0.02%) 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. 4,074 ( 0.00%) let mut new_table = RawTableInner::fallible_with_capacity( . self.alloc.clone(), . table_layout, . capacity, . fallibility, . )?; 74,597 ( 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_| { 33,516 ( 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. 67,033 ( 0.00%) let new_items = match self.items.checked_add(additional) { . Some(new_items) => new_items, . None => return Err(fallibility.capacity_overflow()), . }; 67,032 ( 0.00%) let full_capacity = bucket_mask_to_capacity(self.bucket_mask); 140,772 ( 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); . Ok(()) . } else { . // Otherwise, conservatively resize to at least the next size up . // to avoid churning deletes into frequent rehashes. . self.resize_inner( 33,516 ( 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> { 10,075 ( 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() { 427,422 ( 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); . 33,516 ( 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 1554 ---------------------------------------- . #[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( 22,662 ( 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) { 5,932 ( 0.00%) if !self.is_empty_singleton() { . unsafe { . self.ctrl(0).write_bytes(EMPTY, self.num_ctrl_bytes()); . } . } 8,114 ( 0.00%) self.items = 0; 5,949 ( 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))); 81,455 ( 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. 325,820 ( 0.01%) let ctrl = if empty_before.leading_zeros() + empty_after.trailing_zeros() >= Group::WIDTH { . DELETED . } else { 402,130 ( 0.01%) self.growth_left += 1; . EMPTY . }; . self.set_ctrl(index, ctrl); 325,820 ( 0.01%) self.items -= 1; . } . } . . impl Clone for RawTable { 25,152 ( 0.00%) fn clone(&self) -> Self { 3,154 ( 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) . } . } 28,296 ( 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; 24 ( 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)] 435,070 ( 0.01%) fn drop(&mut self) { 307,125 ( 0.01%) if !self.table.is_empty_singleton() { . unsafe { . self.drop_elements(); . self.free_buckets(); . } . } 468,526 ( 0.02%) } . } . #[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)] 4,524 ( 0.00%) fn into_iter(self) -> RawIntoIter { . unsafe { . let iter = self.iter(); . self.into_iter_from(iter) . } 5,655 ( 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 { 127,263 ( 0.00%) if let Some(index) = self.current_group.lowest_set_bit() { 19,260 ( 0.00%) self.current_group = self.current_group.remove_lowest_bit(); 33,456 ( 0.00%) return Some(self.data.next_n(index)); . } . 115,212 ( 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). 3,088 ( 0.00%) self.current_group = Group::load_aligned(self.next_ctrl).match_full(); 2,387 ( 0.00%) self.data = self.data.next_n(Group::WIDTH); 5,219 ( 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) { 2,692 ( 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)] 22,405 ( 0.00%) fn next(&mut self) -> Option> { 50,088 ( 0.00%) if let Some(b) = self.iter.next() { 188,369 ( 0.01%) 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 . } 44,810 ( 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)] 1,464 ( 0.00%) fn drop(&mut self) { . unsafe { . // Drop all remaining elements . self.iter.drop_elements(); . . // Free the table 10,186 ( 0.00%) if let Some((ptr, layout)) = self.allocation { . self.alloc.deallocate(ptr, layout); . } . } 232 ( 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)] 2,368 ( 0.00%) fn next(&mut self) -> Option { 2,265 ( 0.00%) unsafe { Some(self.iter.next()?.read()) } 5,400 ( 0.00%) } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 68 ( 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)] 5,456 ( 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. 682 ( 0.00%) self.orig_table . .as_ptr() . .copy_from_nonoverlapping(&*self.table, 1); . } 5,456 ( 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 ---------------------------------------- 6,552,259 ( 0.22%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_metadata/src/rmeta/decoder.rs -------------------------------------------------------------------------------- Ir -- line 176 ---------------------------------------- . } . fn sess(self) -> Option<&'tcx Session> { . None . } . fn tcx(self) -> Option> { . None . } . 12,297 ( 0.00%) fn decoder(self, pos: usize) -> DecodeContext<'a, 'tcx> { 4,099 ( 0.00%) let tcx = self.tcx(); 649,564 ( 0.02%) DecodeContext { 68,170 ( 0.00%) opaque: opaque::Decoder::new(self.blob(), pos), 4,099 ( 0.00%) cdata: self.cdata(), . blob: self.blob(), 26,982 ( 0.00%) sess: self.sess().or(tcx.map(|tcx| tcx.sess)), . tcx, . last_source_file_index: 0, . lazy_state: LazyState::NoNode, . alloc_decoding_session: self . .cdata() 61,787 ( 0.00%) .map(|cdata| cdata.cdata.alloc_decoding_state.new_decoding_session()), . } 12,297 ( 0.00%) } . } . . impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a MetadataBlob { . #[inline] . fn blob(self) -> &'a MetadataBlob { . self . } . } -- line 206 ---------------------------------------- -- line 255 ---------------------------------------- . } . #[inline] . fn tcx(self) -> Option> { . Some(self.1) . } . } . . impl<'a, 'tcx, T: Decodable>> Lazy { 109,381 ( 0.00%) fn decode>(self, metadata: M) -> T { 56,903 ( 0.00%) let mut dcx = metadata.decoder(self.position.get()); 189,406 ( 0.01%) dcx.lazy_state = LazyState::NodeStart(self.position); 55,119 ( 0.00%) T::decode(&mut dcx) 139,627 ( 0.00%) } . } . . impl<'a: 'x, 'tcx: 'x, 'x, T: Decodable>> Lazy<[T]> { . fn decode>( . self, . metadata: M, . ) -> impl ExactSizeIterator + Captures<'a> + Captures<'tcx> + 'x { 161 ( 0.00%) let mut dcx = metadata.decoder(self.position.get()); 46 ( 0.00%) dcx.lazy_state = LazyState::NodeStart(self.position); 47,751 ( 0.00%) (0..self.meta).map(move |_| T::decode(&mut dcx)) . } . } . . impl<'a, 'tcx> DecodeContext<'a, 'tcx> { . #[inline] . fn tcx(&self) -> TyCtxt<'tcx> { . debug_assert!(self.tcx.is_some(), "missing TyCtxt in DecodeContext"); . self.tcx.unwrap() -- line 285 ---------------------------------------- -- line 292 ---------------------------------------- . . #[inline] . pub fn cdata(&self) -> CrateMetadataRef<'a> { . debug_assert!(self.cdata.is_some(), "missing CrateMetadata in DecodeContext"); . self.cdata.unwrap() . } . . fn map_encoded_cnum_to_current(&self, cnum: CrateNum) -> CrateNum { 168,206 ( 0.01%) if cnum == LOCAL_CRATE { self.cdata().cnum } else { self.cdata().cnum_map[cnum] } . } . 66,526 ( 0.00%) fn read_lazy_with_meta(&mut self, meta: T::Meta) -> Lazy { . let distance = self.read_usize(); 63,374 ( 0.00%) let position = match self.lazy_state { . LazyState::NoNode => bug!("read_lazy_with_meta: outside of a metadata node"), 14,053 ( 0.00%) LazyState::NodeStart(start) => { . let start = start.get(); 28,106 ( 0.00%) assert!(distance <= start); . start - distance . } 12,729 ( 0.00%) LazyState::Previous(last_pos) => last_pos.get() + distance, . }; 36,592 ( 0.00%) self.lazy_state = LazyState::Previous(NonZeroUsize::new(position).unwrap()); . Lazy::from_position_and_meta(NonZeroUsize::new(position).unwrap(), meta) 66,526 ( 0.00%) } . . #[inline] . pub fn read_raw_bytes(&mut self, len: usize) -> &'a [u8] { . self.opaque.read_raw_bytes(len) . } . } . . impl<'a, 'tcx> TyDecoder<'tcx> for DecodeContext<'a, 'tcx> { -- line 324 ---------------------------------------- -- line 326 ---------------------------------------- . . #[inline] . fn tcx(&self) -> TyCtxt<'tcx> { . self.tcx.expect("missing TyCtxt in DecodeContext") . } . . #[inline] . fn peek_byte(&self) -> u8 { 154,240 ( 0.01%) self.opaque.data[self.opaque.position()] . } . . #[inline] . fn position(&self) -> usize { . self.opaque.position() . } . 144,130 ( 0.00%) fn cached_ty_for_shorthand(&mut self, shorthand: usize, or_insert_with: F) -> Ty<'tcx> . where . F: FnOnce(&mut Self) -> Ty<'tcx>, . { 20,590 ( 0.00%) let tcx = self.tcx(); . 20,590 ( 0.00%) let key = ty::CReaderCacheKey { cnum: Some(self.cdata().cnum), pos: shorthand }; . 64,564 ( 0.00%) if let Some(&ty) = tcx.ty_rcache.borrow().get(&key) { . return ty; . } . 4,449 ( 0.00%) let ty = or_insert_with(self); . tcx.ty_rcache.borrow_mut().insert(key, ty); . ty 185,310 ( 0.01%) } . . fn with_position(&mut self, pos: usize, f: F) -> R . where . F: FnOnce(&mut Self) -> R, . { . let new_opaque = opaque::Decoder::new(self.opaque.data, pos); . let old_opaque = mem::replace(&mut self.opaque, new_opaque); . let old_state = mem::replace(&mut self.lazy_state, LazyState::NoNode); . let r = f(self); 24,170 ( 0.00%) self.opaque = old_opaque; 4,834 ( 0.00%) self.lazy_state = old_state; . r . } . . fn decode_alloc_id(&mut self) -> rustc_middle::mir::interpret::AllocId { . if let Some(alloc_decoding_session) = self.alloc_decoding_session { . alloc_decoding_session.decode_alloc_id(self) . } else { . bug!("Attempting to decode interpret::AllocId without CrateMetadata") . } . } . } . . impl<'a, 'tcx> Decodable> for CrateNum { . fn decode(d: &mut DecodeContext<'a, 'tcx>) -> CrateNum { 89,444 ( 0.00%) let cnum = CrateNum::from_u32(d.read_u32()); . d.map_encoded_cnum_to_current(cnum) . } . } . . impl<'a, 'tcx> Decodable> for DefIndex { 1,394 ( 0.00%) fn decode(d: &mut DecodeContext<'a, 'tcx>) -> DefIndex { 162,835 ( 0.01%) DefIndex::from_u32(d.read_u32()) 2,788 ( 0.00%) } . } . . impl<'a, 'tcx> Decodable> for ExpnIndex { . fn decode(d: &mut DecodeContext<'a, 'tcx>) -> ExpnIndex { . ExpnIndex::from_u32(d.read_u32()) . } . } . . impl<'a, 'tcx> Decodable> for SyntaxContext { 208,968 ( 0.01%) fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> SyntaxContext { 52,242 ( 0.00%) let cdata = decoder.cdata(); 52,242 ( 0.00%) let sess = decoder.sess.unwrap(); 104,484 ( 0.00%) let cname = cdata.root.name; . rustc_span::hygiene::decode_syntax_context(decoder, &cdata.hygiene_context, |_, id| { . debug!("SpecializedDecoder: decoding {}", id); 1,152 ( 0.00%) cdata . .root . .syntax_contexts . .get(cdata, id) . .unwrap_or_else(|| panic!("Missing SyntaxContext {:?} for crate {:?}", id, cname)) . .decode((cdata, sess)) . }) 261,210 ( 0.01%) } . } . . impl<'a, 'tcx> Decodable> for ExpnId { 8,057 ( 0.00%) fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> ExpnId { 1,151 ( 0.00%) let local_cdata = decoder.cdata(); 1,151 ( 0.00%) let sess = decoder.sess.unwrap(); . . let cnum = CrateNum::decode(decoder); . let index = u32::decode(decoder); . . let expn_id = rustc_span::hygiene::decode_expn_id(cnum, index, |expn_id| { . let ExpnId { krate: cnum, local_id: index } = expn_id; . // Lookup local `ExpnData`s in our own crate data. Foreign `ExpnData`s . // are stored in the owning crate, to avoid duplication. . debug_assert_ne!(cnum, LOCAL_CRATE); 325 ( 0.00%) let crate_data = if cnum == local_cdata.cnum { . local_cdata . } else { . local_cdata.cstore.get_crate_data(cnum) . }; 1,625 ( 0.00%) let expn_data = crate_data . .root . .expn_data . .get(crate_data, index) . .unwrap() . .decode((crate_data, sess)); 1,625 ( 0.00%) let expn_hash = crate_data . .root . .expn_hashes . .get(crate_data, index) . .unwrap() . .decode((crate_data, sess)); 3,250 ( 0.00%) (expn_data, expn_hash) . }); . expn_id 9,208 ( 0.00%) } . } . . impl<'a, 'tcx> Decodable> for Span { 411,024 ( 0.01%) fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Span { 51,378 ( 0.00%) let ctxt = SyntaxContext::decode(decoder); . let tag = u8::decode(decoder); . 102,756 ( 0.00%) if tag == TAG_PARTIAL_SPAN { . return DUMMY_SP.with_ctxt(ctxt); . } . . debug_assert!(tag == TAG_VALID_SPAN_LOCAL || tag == TAG_VALID_SPAN_FOREIGN); . . let lo = BytePos::decode(decoder); . let len = BytePos::decode(decoder); . let hi = lo + len; . 153,879 ( 0.01%) let Some(sess) = decoder.sess else { . bug!("Cannot decode Span without Session.") . }; . . // There are two possibilities here: . // 1. This is a 'local span', which is located inside a `SourceFile` . // that came from this crate. In this case, we use the source map data . // encoded in this crate. This branch should be taken nearly all of the time. . // 2. This is a 'foreign span', which is located inside a `SourceFile` -- line 476 ---------------------------------------- -- line 492 ---------------------------------------- . // a transitive dependency. . // . // When we encode a foreign span, we adjust its 'lo' and 'high' values . // to be based on the *foreign* crate (e.g. crate C), not the crate . // we are writing metadata for (e.g. crate B). This allows us to . // treat the 'local' and 'foreign' cases almost identically during deserialization: . // we can call `imported_source_files` for the proper crate, and binary search . // through the returned slice using our span. 121,310 ( 0.00%) let imported_source_files = if tag == TAG_VALID_SPAN_LOCAL { . decoder.cdata().imported_source_files(sess) . } else { . // When we encode a proc-macro crate, all `Span`s should be encoded . // with `TAG_VALID_SPAN_LOCAL` 90 ( 0.00%) if decoder.cdata().root.is_proc_macro_crate() { . // Decode `CrateNum` as u32 - using `CrateNum::decode` will ICE . // since we don't have `cnum_map` populated. . let cnum = u32::decode(decoder); . panic!( . "Decoding of crate {:?} tried to access proc-macro dep {:?}", . decoder.cdata().root.name, . cnum . ); -- line 513 ---------------------------------------- -- line 518 ---------------------------------------- . "SpecializedDecoder::specialized_decode: loading source files from cnum {:?}", . cnum . ); . . // Decoding 'foreign' spans should be rare enough that it's . // not worth it to maintain a per-CrateNum cache for `last_source_file_index`. . // We just set it to 0, to ensure that we don't try to access something out . // of bounds for our initial 'guess' 180 ( 0.00%) decoder.last_source_file_index = 0; . 90 ( 0.00%) let foreign_data = decoder.cdata().cstore.get_crate_data(cnum); . foreign_data.imported_source_files(sess) . }; . . let source_file = { . // Optimize for the case that most spans within a translated item . // originate from the same source_file. 153,879 ( 0.01%) let last_source_file = &imported_source_files[decoder.last_source_file_index]; . 199,847 ( 0.01%) if lo >= last_source_file.original_start_pos && lo <= last_source_file.original_end_pos . { . last_source_file . } else { . let index = imported_source_files . .binary_search_by_key(&lo, |source_file| source_file.original_start_pos) 37,430 ( 0.00%) .unwrap_or_else(|index| index - 1); . . // Don't try to cache the index for foreign spans, . // as this would require a map from CrateNums to indices 18,724 ( 0.00%) if tag == TAG_VALID_SPAN_LOCAL { 18,635 ( 0.00%) decoder.last_source_file_index = index; . } 37,448 ( 0.00%) &imported_source_files[index] . } . }; . . // Make sure our binary search above is correct. . debug_assert!( . lo >= source_file.original_start_pos && lo <= source_file.original_end_pos, . "Bad binary search: lo={:?} source_file.original_start_pos={:?} source_file.original_end_pos={:?}", . lo, -- line 558 ---------------------------------------- -- line 565 ---------------------------------------- . hi >= source_file.original_start_pos && hi <= source_file.original_end_pos, . "Bad binary search: hi={:?} source_file.original_start_pos={:?} source_file.original_end_pos={:?}", . hi, . source_file.original_start_pos, . source_file.original_end_pos . ); . . let lo = 205,172 ( 0.01%) (lo + source_file.translated_source_file.start_pos) - source_file.original_start_pos; . let hi = . (hi + source_file.translated_source_file.start_pos) - source_file.original_start_pos; . . // Do not try to decode parent for foreign spans. . Span::new(lo, hi, ctxt, None) 462,402 ( 0.02%) } . } . . impl<'a, 'tcx> Decodable> for &'tcx [thir::abstract_const::Node<'tcx>] { . fn decode(d: &mut DecodeContext<'a, 'tcx>) -> Self { . ty::codec::RefDecodable::decode(d) . } . } . -- line 587 ---------------------------------------- -- line 590 ---------------------------------------- . ty::codec::RefDecodable::decode(d) . } . } . . impl<'a, 'tcx, T: Decodable>> Decodable> . for Lazy . { . fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Self { 25,564 ( 0.00%) decoder.read_lazy_with_meta(()) . } . } . . impl<'a, 'tcx, T: Decodable>> Decodable> . for Lazy<[T]> . { . fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Self { . let len = decoder.read_usize(); 20,612 ( 0.00%) if len == 0 { Lazy::empty() } else { decoder.read_lazy_with_meta(len) } . } . } . . impl<'a, 'tcx, I: Idx, T: Decodable>> Decodable> . for Lazy> . where . Option: FixedSizeEncoding, . { . fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Self { . let len = decoder.read_usize(); 15,548 ( 0.00%) decoder.read_lazy_with_meta(len) . } . } . . implement_ty_decoder!(DecodeContext<'a, 'tcx>); . . impl<'tcx> MetadataBlob { . crate fn new(metadata_ref: MetadataRef) -> MetadataBlob { . MetadataBlob(Lrc::new(metadata_ref)) -- line 626 ---------------------------------------- -- line 630 ---------------------------------------- . self.blob().starts_with(METADATA_HEADER) . } . . crate fn get_rustc_version(&self) -> String { . Lazy::::from_position(NonZeroUsize::new(METADATA_HEADER.len() + 4).unwrap()) . .decode(self) . } . 276 ( 0.00%) crate fn get_root(&self) -> CrateRoot<'tcx> { 92 ( 0.00%) let slice = &self.blob()[..]; . let offset = METADATA_HEADER.len(); 460 ( 0.00%) let pos = (((slice[offset + 0] as u32) << 24) 184 ( 0.00%) | ((slice[offset + 1] as u32) << 16) 368 ( 0.00%) | ((slice[offset + 2] as u32) << 8) 276 ( 0.00%) | ((slice[offset + 3] as u32) << 0)) as usize; . Lazy::>::from_position(NonZeroUsize::new(pos).unwrap()).decode(self) 460 ( 0.00%) } . . crate fn list_crate_metadata(&self, out: &mut dyn io::Write) -> io::Result<()> { . let root = self.get_root(); . writeln!(out, "Crate info:")?; . writeln!(out, "name {}{}", root.name, root.extra_filename)?; . writeln!(out, "hash {} stable_crate_id {:?}", root.hash, root.stable_crate_id)?; . writeln!(out, "proc_macro {:?}", root.proc_macro_data.is_some())?; . writeln!(out, "=External Dependencies=")?; -- line 654 ---------------------------------------- -- line 666 ---------------------------------------- . } . write!(out, "\n")?; . Ok(()) . } . } . . impl CrateRoot<'_> { . crate fn is_proc_macro_crate(&self) -> bool { 59 ( 0.00%) self.proc_macro_data.is_some() . } . . crate fn name(&self) -> Symbol { 10 ( 0.00%) self.name . } . . crate fn hash(&self) -> Svh { 30 ( 0.00%) self.hash . } . . crate fn stable_crate_id(&self) -> StableCrateId { 63 ( 0.00%) self.stable_crate_id . } . . crate fn triple(&self) -> &TargetTriple { . &self.triple . } . . crate fn decode_crate_deps<'a>( . &self, . metadata: &'a MetadataBlob, . ) -> impl ExactSizeIterator + Captures<'a> { 58 ( 0.00%) self.crate_deps.decode(metadata) . } . } . . impl<'a, 'tcx> CrateMetadataRef<'a> { . fn raw_proc_macro(self, id: DefIndex) -> &'a ProcMacro { . // DefIndex's in root.proc_macro_data have a one-to-one correspondence . // with items in 'raw_proc_macros'. . let pos = self -- line 705 ---------------------------------------- -- line 709 ---------------------------------------- . .unwrap() . .macros . .decode(self) . .position(|i| i == id) . .unwrap(); . &self.raw_proc_macros.unwrap()[pos] . } . 52,250 ( 0.00%) fn opt_item_ident(self, item_index: DefIndex, sess: &Session) -> Option { 39,020 ( 0.00%) let name = self.def_key(item_index).disambiguated_data.data.get_opt_name()?; 26,278 ( 0.00%) let span = match self.root.tables.ident_span.get(self, item_index) { . Some(lazy_span) => lazy_span.decode((self, sess)), . None => { . // FIXME: this weird case of a name with no span is specific to `extern crate` . // items, which are supposed to be treated like `use` items and only be encoded . // to metadata as `Export`s, return `None` because that's what all the callers . // expect in this case. 144 ( 0.00%) assert_eq!(self.def_kind(item_index), DefKind::ExternCrate); . return None; . } . }; . Some(Ident::new(name, span)) 66,908 ( 0.00%) } . 1,356 ( 0.00%) fn item_ident(self, item_index: DefIndex, sess: &Session) -> Ident { 9,548 ( 0.00%) self.opt_item_ident(item_index, sess).expect("no encoded ident for item") 2,712 ( 0.00%) } . . fn maybe_kind(self, item_id: DefIndex) -> Option { 26,002 ( 0.00%) self.root.tables.kind.get(self, item_id).map(|k| k.decode(self)) . } . 104,008 ( 0.00%) fn kind(self, item_id: DefIndex) -> EntryKind { . self.maybe_kind(item_id).unwrap_or_else(|| { . bug!( . "CrateMetadata::kind({:?}): id not found, in crate {:?} with number {}", . item_id, . self.root.name, . self.cnum, . ) . }) 78,006 ( 0.00%) } . 33,782 ( 0.00%) fn def_kind(self, item_id: DefIndex) -> DefKind { 24,464 ( 0.00%) self.root.tables.def_kind.get(self, item_id).map(|k| k.decode(self)).unwrap_or_else(|| { . bug!( . "CrateMetadata::def_kind({:?}): id not found, in crate {:?} with number {}", . item_id, . self.root.name, . self.cnum, . ) . }) 19,304 ( 0.00%) } . 12,204 ( 0.00%) fn get_span(self, index: DefIndex, sess: &Session) -> Span { 12,069 ( 0.00%) self.root . .tables . .span . .get(self, index) . .unwrap_or_else(|| panic!("Missing span for {:?}", index)) . .decode((self, sess)) 6,780 ( 0.00%) } . . fn load_proc_macro(self, id: DefIndex, sess: &Session) -> SyntaxExtension { . let (name, kind, helper_attrs) = match *self.raw_proc_macro(id) { . ProcMacro::CustomDerive { trait_name, attributes, client } => { . let helper_attrs = . attributes.iter().cloned().map(Symbol::intern).collect::>(); . ( . trait_name, -- line 778 ---------------------------------------- -- line 795 ---------------------------------------- . self.get_span(id, sess), . helper_attrs, . self.root.edition, . Symbol::intern(name), . &attrs, . ) . } . 845 ( 0.00%) fn get_trait_def(self, item_id: DefIndex, sess: &Session) -> ty::TraitDef { 260 ( 0.00%) match self.kind(item_id) { 65 ( 0.00%) EntryKind::Trait(data) => { 390 ( 0.00%) let data = data.decode((self, sess)); 1,040 ( 0.00%) ty::TraitDef::new( . self.local_def_id(item_id), 130 ( 0.00%) data.unsafety, 130 ( 0.00%) data.paren_sugar, 130 ( 0.00%) data.has_auto_impl, 130 ( 0.00%) data.is_marker, 65 ( 0.00%) data.skip_array_during_method_dispatch, 65 ( 0.00%) data.specialization_kind, 260 ( 0.00%) self.def_path_hash(item_id), 65 ( 0.00%) data.must_implement_one_of, . ) . } . EntryKind::TraitAlias => ty::TraitDef::new( . self.local_def_id(item_id), . hir::Unsafety::Normal, . false, . false, . false, . false, . ty::trait_def::TraitSpecializationKind::None, . self.def_path_hash(item_id), . None, . ), . _ => bug!("def-index does not refer to trait or trait alias"), . } 585 ( 0.00%) } . 1,440 ( 0.00%) fn get_variant( . self, . kind: &EntryKind, . index: DefIndex, . parent_did: DefId, . sess: &Session, . ) -> ty::VariantDef { 640 ( 0.00%) let data = match kind { . EntryKind::Variant(data) | EntryKind::Struct(data, _) | EntryKind::Union(data, _) => { 800 ( 0.00%) data.decode(self) . } . _ => bug!(), . }; . 500 ( 0.00%) let adt_kind = match kind { . EntryKind::Variant(_) => ty::AdtKind::Enum, . EntryKind::Struct(..) => ty::AdtKind::Struct, . EntryKind::Union(..) => ty::AdtKind::Union, . _ => bug!(), . }; . . let variant_did = . if adt_kind == ty::AdtKind::Enum { Some(self.local_def_id(index)) } else { None }; 320 ( 0.00%) let ctor_did = data.ctor.map(|index| self.local_def_id(index)); . 3,520 ( 0.00%) ty::VariantDef::new( . self.item_ident(index, sess).name, . variant_did, . ctor_did, 640 ( 0.00%) data.discr, 960 ( 0.00%) self.root . .tables . .children . .get(self, index) . .unwrap_or_else(Lazy::empty) . .decode(self) . .map(|index| ty::FieldDef { 176 ( 0.00%) did: self.local_def_id(index), 352 ( 0.00%) name: self.item_ident(index, sess).name, 352 ( 0.00%) vis: self.get_visibility(index), . }) . .collect(), . data.ctor_kind, . adt_kind, . parent_did, . false, 160 ( 0.00%) data.is_non_exhaustive, . ) 1,440 ( 0.00%) } . 1,545 ( 0.00%) fn get_adt_def(self, item_id: DefIndex, tcx: TyCtxt<'tcx>) -> &'tcx ty::AdtDef { 412 ( 0.00%) let kind = self.kind(item_id); 206 ( 0.00%) let did = self.local_def_id(item_id); . 489 ( 0.00%) let (adt_kind, repr) = match kind { . EntryKind::Enum(repr) => (ty::AdtKind::Enum, repr), . EntryKind::Struct(_, repr) => (ty::AdtKind::Struct, repr), . EntryKind::Union(_, repr) => (ty::AdtKind::Union, repr), . _ => bug!("get_adt_def called on a non-ADT {:?}", did), . }; . . let variants = if let ty::AdtKind::Enum = adt_kind { 70 ( 0.00%) self.root . .tables . .children . .get(self, item_id) . .unwrap_or_else(Lazy::empty) . .decode(self) 1,207 ( 0.00%) .map(|index| self.get_variant(&self.kind(index), index, did, tcx.sess)) . .collect() . } else { 712 ( 0.00%) std::iter::once(self.get_variant(&kind, item_id, did, tcx.sess)).collect() . }; . 1,512 ( 0.00%) tcx.alloc_adt_def(did, adt_kind, variants, repr) 721 ( 0.00%) } . . fn get_explicit_predicates( . self, . item_id: DefIndex, . tcx: TyCtxt<'tcx>, . ) -> ty::GenericPredicates<'tcx> { 4,650 ( 0.00%) self.root.tables.explicit_predicates.get(self, item_id).unwrap().decode((self, tcx)) . } . . fn get_inferred_outlives( . self, . item_id: DefIndex, . tcx: TyCtxt<'tcx>, . ) -> &'tcx [(ty::Predicate<'tcx>, Span)] { 4,650 ( 0.00%) self.root . .tables . .inferred_outlives . .get(self, item_id) 40 ( 0.00%) .map(|predicates| tcx.arena.alloc_from_iter(predicates.decode((self, tcx)))) . .unwrap_or_default() . } . . fn get_super_predicates( . self, . item_id: DefIndex, . tcx: TyCtxt<'tcx>, . ) -> ty::GenericPredicates<'tcx> { 290 ( 0.00%) self.root.tables.super_predicates.get(self, item_id).unwrap().decode((self, tcx)) . } . . fn get_explicit_item_bounds( . self, . item_id: DefIndex, . tcx: TyCtxt<'tcx>, . ) -> &'tcx [(ty::Predicate<'tcx>, Span)] { 50 ( 0.00%) self.root . .tables . .explicit_item_bounds . .get(self, item_id) 36 ( 0.00%) .map(|bounds| tcx.arena.alloc_from_iter(bounds.decode((self, tcx)))) . .unwrap_or_default() . } . . fn get_generics(self, item_id: DefIndex, sess: &Session) -> ty::Generics { 4,588 ( 0.00%) self.root.tables.generics.get(self, item_id).unwrap().decode((self, sess)) . } . . fn get_type(self, id: DefIndex, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { 11,590 ( 0.00%) self.root . .tables . .ty . .get(self, id) . .unwrap_or_else(|| panic!("Not a type: {:?}", id)) . .decode((self, tcx)) . } . . fn get_stability(self, id: DefIndex) -> Option { 890 ( 0.00%) self.root.tables.stability.get(self, id).map(|stab| stab.decode(self)) . } . . fn get_const_stability(self, id: DefIndex) -> Option { 10 ( 0.00%) self.root.tables.const_stability.get(self, id).map(|stab| stab.decode(self)) . } . . fn get_deprecation(self, id: DefIndex) -> Option { 995 ( 0.00%) self.root.tables.deprecation.get(self, id).map(|depr| depr.decode(self)) . } . 228 ( 0.00%) fn get_visibility(self, id: DefIndex) -> ty::Visibility { 9,576 ( 0.00%) self.root.tables.visibility.get(self, id).unwrap().decode(self) 152 ( 0.00%) } . . fn get_impl_data(self, id: DefIndex) -> ImplData { 57,672 ( 0.00%) match self.kind(id) { 48,060 ( 0.00%) EntryKind::Impl(data) => data.decode(self), . _ => bug!(), . } . } . . fn get_parent_impl(self, id: DefIndex) -> Option { 27,867 ( 0.00%) self.get_impl_data(id).parent_impl . } . . fn get_impl_polarity(self, id: DefIndex) -> ty::ImplPolarity { 222 ( 0.00%) self.get_impl_data(id).polarity . } . . fn get_impl_defaultness(self, id: DefIndex) -> hir::Defaultness { 92 ( 0.00%) self.get_impl_data(id).defaultness . } . . fn get_impl_constness(self, id: DefIndex) -> hir::Constness { 9 ( 0.00%) self.get_impl_data(id).constness . } . . fn get_trait_item_def_id(self, id: DefIndex) -> Option { 6,800 ( 0.00%) self.root.tables.trait_item_def_id.get(self, id).map(|d| d.decode(self)) . } . . fn get_coerce_unsized_info(self, id: DefIndex) -> Option { . self.get_impl_data(id).coerce_unsized_info . } . . fn get_impl_trait(self, id: DefIndex, tcx: TyCtxt<'tcx>) -> Option> { 112,984 ( 0.00%) self.root.tables.impl_trait_ref.get(self, id).map(|tr| tr.decode((self, tcx))) . } . . fn get_expn_that_defined(self, id: DefIndex, sess: &Session) -> ExpnId { 2,690 ( 0.00%) self.root.tables.expn_that_defined.get(self, id).unwrap().decode((self, sess)) . } . . fn get_const_param_default( . self, . tcx: TyCtxt<'tcx>, . id: DefIndex, . ) -> rustc_middle::ty::Const<'tcx> { . self.root.tables.const_defaults.get(self, id).unwrap().decode((self, tcx)) -- line 1026 ---------------------------------------- -- line 1028 ---------------------------------------- . . /// Iterates over all the stability attributes in the given crate. . fn get_lib_features(self, tcx: TyCtxt<'tcx>) -> &'tcx [(Symbol, Option)] { . tcx.arena.alloc_from_iter(self.root.lib_features.decode(self)) . } . . /// Iterates over the language items in the given crate. . fn get_lang_items(self, tcx: TyCtxt<'tcx>) -> &'tcx [(DefId, usize)] { 90 ( 0.00%) tcx.arena.alloc_from_iter( 60 ( 0.00%) self.root . .lang_items . .decode(self) 564 ( 0.00%) .map(|(def_index, index)| (self.local_def_id(def_index), index)), . ) . } . . /// Iterates over the diagnostic items in the given crate. . fn get_diagnostic_items(self) -> DiagnosticItems { . let mut id_to_name = FxHashMap::default(); 60 ( 0.00%) let name_to_id = self . .root . .diagnostic_items . .decode(self) . .map(|(name, def_index)| { 130 ( 0.00%) let id = self.local_def_id(def_index); 130 ( 0.00%) id_to_name.insert(id, name); . (name, id) . }) . .collect(); 270 ( 0.00%) DiagnosticItems { id_to_name, name_to_id } . } . . /// Iterates over all named children of the given module, . /// including both proper items and reexports. . /// Module here is understood in name resolution sense - it can be a `mod` item, . /// or a crate root, or an enum, or a trait. . fn for_each_module_child( . self, . id: DefIndex, . mut callback: impl FnMut(ModChild), . sess: &Session, . ) { 372 ( 0.00%) if let Some(data) = &self.root.proc_macro_data { . // If we are loading as a proc macro, we want to return . // the view of this crate as a proc macro crate. . if id == CRATE_DEF_INDEX { . for def_index in data.macros.decode(self) { . let raw_macro = self.raw_proc_macro(def_index); . let res = Res::Def( . DefKind::Macro(macro_kind(raw_macro)), . self.local_def_id(def_index), -- line 1078 ---------------------------------------- -- line 1085 ---------------------------------------- . span: ident.span, . }); . } . } . return; . } . . // Iterate over all children. 744 ( 0.00%) if let Some(children) = self.root.tables.children.get(self, id) { 1,488 ( 0.00%) for child_index in children.decode((self, sess)) { 11,328 ( 0.00%) if let Some(ident) = self.opt_item_ident(child_index, sess) { 2,322 ( 0.00%) let kind = self.def_kind(child_index); 1,548 ( 0.00%) if matches!(kind, DefKind::Macro(..)) { . // FIXME: Macros are currently encoded twice, once as items and once as . // reexports. We ignore the items here and only use the reexports. . continue; . } . let def_id = self.local_def_id(child_index); . let res = Res::Def(kind, def_id); . let vis = self.get_visibility(child_index); . let span = self.get_span(child_index, sess); . . callback(ModChild { ident, res, vis, span }); . . // For non-re-export structs and variants add their constructors to children. . // Re-export lists automatically contain constructors when necessary. 2,878 ( 0.00%) match kind { . DefKind::Struct => { 48 ( 0.00%) if let Some((ctor_def_id, ctor_kind)) = . self.get_ctor_def_id_and_kind(child_index) . { . let ctor_res = . Res::Def(DefKind::Ctor(CtorOf::Struct, ctor_kind), ctor_def_id); . let vis = self.get_visibility(ctor_def_id.index); . callback(ModChild { ident, res: ctor_res, vis, span }); . } . } . DefKind::Variant => { . // Braced variants, unlike structs, generate unusable names in . // value namespace, they are reserved for possible future use. . // It's ok to use the variant's id as a ctor id since an . // error will be reported on any use of such resolution anyway. 159 ( 0.00%) let (ctor_def_id, ctor_kind) = self . .get_ctor_def_id_and_kind(child_index) . .unwrap_or((def_id, CtorKind::Fictive)); . let ctor_res = . Res::Def(DefKind::Ctor(CtorOf::Variant, ctor_kind), ctor_def_id); . let mut vis = self.get_visibility(ctor_def_id.index); 53 ( 0.00%) if ctor_def_id == def_id && vis.is_public() { . // For non-exhaustive variants lower the constructor visibility to . // within the crate. We only need this for fictive constructors, . // for other constructors correct visibilities . // were already encoded in metadata. . let mut attrs = self.get_item_attrs(def_id.index, sess); . if attrs.any(|item| item.has_name(sym::non_exhaustive)) { . let crate_def_id = self.local_def_id(CRATE_DEF_INDEX); . vis = ty::Visibility::Restricted(crate_def_id); -- line 1141 ---------------------------------------- -- line 1144 ---------------------------------------- . callback(ModChild { ident, res: ctor_res, vis, span }); . } . _ => {} . } . } . } . } . 927 ( 0.00%) match self.kind(id) { 76 ( 0.00%) EntryKind::Mod(exports) => { 11,922 ( 0.00%) for exp in exports.decode((self, sess)) { . callback(exp); . } . } . EntryKind::Enum(..) | EntryKind::Trait(..) => {} . _ => bug!("`for_each_module_child` is called on a non-module: {:?}", self.def_kind(id)), . } . } . . fn is_ctfe_mir_available(self, id: DefIndex) -> bool { 248 ( 0.00%) self.root.tables.mir_for_ctfe.get(self, id).is_some() . } . . fn is_item_mir_available(self, id: DefIndex) -> bool { 1,028 ( 0.00%) self.root.tables.mir.get(self, id).is_some() . } . . fn module_expansion(self, id: DefIndex, sess: &Session) -> ExpnId { 3,339 ( 0.00%) match self.kind(id) { . EntryKind::Mod(_) | EntryKind::Enum(_) | EntryKind::Trait(_) => { . self.get_expn_that_defined(id, sess) . } . _ => panic!("Expected module, found {:?}", self.local_def_id(id)), . } . } . . fn get_optimized_mir(self, tcx: TyCtxt<'tcx>, id: DefIndex) -> Body<'tcx> { 1,280 ( 0.00%) self.root . .tables . .mir . .get(self, id) . .unwrap_or_else(|| { . bug!("get_optimized_mir: missing MIR for `{:?}`", self.local_def_id(id)) . }) . .decode((self, tcx)) . } . . fn get_mir_for_ctfe(self, tcx: TyCtxt<'tcx>, id: DefIndex) -> Body<'tcx> { 310 ( 0.00%) self.root . .tables . .mir_for_ctfe . .get(self, id) . .unwrap_or_else(|| { . bug!("get_mir_for_ctfe: missing MIR for `{:?}`", self.local_def_id(id)) . }) . .decode((self, tcx)) . } -- line 1200 ---------------------------------------- -- line 1216 ---------------------------------------- . .tables . .unused_generic_params . .get(self, id) . .map(|params| params.decode(self)) . .unwrap_or_default() . } . . fn get_promoted_mir(self, tcx: TyCtxt<'tcx>, id: DefIndex) -> IndexVec> { 55 ( 0.00%) self.root . .tables . .promoted_mir . .get(self, id) . .unwrap_or_else(|| { . bug!("get_promoted_mir: missing MIR for `{:?}`", self.local_def_id(id)) . }) . .decode((self, tcx)) . } -- line 1232 ---------------------------------------- -- line 1242 ---------------------------------------- . qualif, . _, . ) => qualif, . _ => bug!("mir_const_qualif: unexpected kind"), . } . } . . fn get_fn_has_self_parameter(self, id: DefIndex) -> bool { 750 ( 0.00%) match self.kind(id) { 600 ( 0.00%) EntryKind::AssocFn(data) => data.decode(self).has_self, . _ => false, . } . } . . fn get_associated_item_def_ids(self, tcx: TyCtxt<'tcx>, id: DefIndex) -> &'tcx [DefId] { 1,519 ( 0.00%) if let Some(children) = self.root.tables.children.get(self, id) { 651 ( 0.00%) tcx.arena.alloc_from_iter( 217 ( 0.00%) children.decode((self, tcx.sess)).map(|child_index| self.local_def_id(child_index)), . ) . } else { . &[] . } . } . 13,800 ( 0.00%) fn get_associated_item(self, id: DefIndex, sess: &Session) -> ty::AssocItem { 8,050 ( 0.00%) let def_key = self.def_key(id); . let parent = self.local_def_id(def_key.parent.unwrap()); . let ident = self.item_ident(id, sess); . 8,190 ( 0.00%) let (kind, container, has_self) = match self.kind(id) { 24 ( 0.00%) EntryKind::AssocConst(container, _, _) => (ty::AssocKind::Const, container, false), 1,086 ( 0.00%) EntryKind::AssocFn(data) => { . let data = data.decode(self); 7,602 ( 0.00%) (ty::AssocKind::Fn, data.container, data.has_self) . } 116 ( 0.00%) EntryKind::AssocType(container) => (ty::AssocKind::Type, container, false), . _ => bug!("cannot get associated-item of `{:?}`", def_key), . }; . 20,700 ( 0.00%) ty::AssocItem { . name: ident.name, . kind, . vis: self.get_visibility(id), . defaultness: container.defaultness(), . def_id: self.local_def_id(id), . trait_item_def_id: self.get_trait_item_def_id(id), . container: container.with_def_id(parent), . fn_has_self_parameter: has_self, . } 10,350 ( 0.00%) } . . fn get_item_variances(self, id: DefIndex) -> impl Iterator + 'a { 220 ( 0.00%) self.root.tables.variances.get(self, id).unwrap_or_else(Lazy::empty).decode(self) . } . . fn get_ctor_def_id_and_kind(self, node_id: DefIndex) -> Option<(DefId, CtorKind)> { 3,629 ( 0.00%) match self.kind(node_id) { . EntryKind::Struct(data, _) | EntryKind::Variant(data) => { 1,547 ( 0.00%) let vdata = data.decode(self); 898 ( 0.00%) vdata.ctor.map(|index| (self.local_def_id(index), vdata.ctor_kind)) . } . _ => None, . } 2,223 ( 0.00%) } . 672 ( 0.00%) fn get_item_attrs( . self, . id: DefIndex, . sess: &'a Session, . ) -> impl Iterator + 'a { 3,564 ( 0.00%) self.root . .tables . .attributes . .get(self, id) . .unwrap_or_else(|| { . // Structure and variant constructors don't have any attributes encoded for them, . // but we assume that someone passing a constructor ID actually wants to look at . // the attributes on the corresponding struct or variant. . let def_key = self.def_key(id); -- line 1320 ---------------------------------------- -- line 1322 ---------------------------------------- . let parent_id = def_key.parent.expect("no parent for a constructor"); . self.root . .tables . .attributes . .get(self, parent_id) . .expect("no encoded attributes for a structure or variant") . }) . .decode((self, sess)) 504 ( 0.00%) } . . fn get_struct_field_names( . self, . id: DefIndex, . sess: &'a Session, . ) -> impl Iterator> + 'a { 1,920 ( 0.00%) self.root . .tables . .children . .get(self, id) . .unwrap_or_else(Lazy::empty) . .decode(self) 13,560 ( 0.00%) .map(move |index| respan(self.get_span(index, sess), self.item_ident(index, sess).name)) . } . . fn get_struct_field_visibilities(self, id: DefIndex) -> impl Iterator + 'a { 210 ( 0.00%) self.root . .tables . .children . .get(self, id) . .unwrap_or_else(Lazy::empty) . .decode(self) 76 ( 0.00%) .map(move |field_index| self.get_visibility(field_index)) . } . . fn get_inherent_implementations_for_type( . self, . tcx: TyCtxt<'tcx>, . id: DefIndex, . ) -> &'tcx [DefId] { 80 ( 0.00%) tcx.arena.alloc_from_iter( 100 ( 0.00%) self.root . .tables . .inherent_impls . .get(self, id) . .unwrap_or_else(Lazy::empty) . .decode(self) 1,107 ( 0.00%) .map(|index| self.local_def_id(index)), . ) . } . . fn get_traits(self) -> impl Iterator + 'a { . self.root.traits.decode(self).map(move |index| self.local_def_id(index)) . } . . fn get_trait_impls(self) -> impl Iterator)> + 'a { -- line 1376 ---------------------------------------- -- line 1380 ---------------------------------------- . index: *trait_index, . }; . impls.decode(self).map(move |(impl_index, simplified_self_ty)| { . (trait_def_id, self.local_def_id(impl_index), simplified_self_ty) . }) . }) . } . 18,090 ( 0.00%) fn get_implementations_of_trait( . self, . tcx: TyCtxt<'tcx>, . trait_def_id: DefId, . ) -> &'tcx [(DefId, Option)] { 2,010 ( 0.00%) if self.trait_impls.is_empty() { . return &[]; . } . . // Do a reverse lookup beforehand to avoid touching the crate_num . // hash map in the loop below. 2,690 ( 0.00%) let key = match self.reverse_translate_def_id(trait_def_id) { . Some(def_id) => (def_id.krate.as_u32(), def_id.index), . None => return &[], . }; . . if let Some(impls) = self.trait_impls.get(&key) { 1,196 ( 0.00%) tcx.arena.alloc_from_iter( 598 ( 0.00%) impls . .decode(self) 9,932 ( 0.00%) .map(|(idx, simplified_self_ty)| (self.local_def_id(idx), simplified_self_ty)), . ) . } else { . &[] . } 16,080 ( 0.00%) } . . fn get_trait_of_item(self, id: DefIndex) -> Option { 1,496 ( 0.00%) let def_key = self.def_key(id); 1,870 ( 0.00%) match def_key.disambiguated_data.data { . DefPathData::TypeNs(..) | DefPathData::ValueNs(..) => (), . // Not an associated item . _ => return None, . } 3,330 ( 0.00%) def_key.parent.and_then(|parent_index| match self.kind(parent_index) { . EntryKind::Trait(_) | EntryKind::TraitAlias => Some(self.local_def_id(parent_index)), . _ => None, . }) . } . . fn get_native_libraries(self, sess: &'a Session) -> impl Iterator + 'a { 60 ( 0.00%) self.root.native_libraries.decode((self, sess)) . } . . fn get_proc_macro_quoted_span(self, index: usize, sess: &Session) -> Span { . self.root . .tables . .proc_macro_quoted_spans . .get(self, index) . .unwrap_or_else(|| panic!("Missing proc macro quoted span: {:?}", index)) -- line 1437 ---------------------------------------- -- line 1450 ---------------------------------------- . self.root.dylib_dependency_formats.decode(self).enumerate().flat_map(|(i, link)| { . let cnum = CrateNum::new(i + 1); . link.map(|link| (self.cnum_map[cnum], link)) . }), . ) . } . . fn get_missing_lang_items(self, tcx: TyCtxt<'tcx>) -> &'tcx [lang_items::LangItem] { 150 ( 0.00%) tcx.arena.alloc_from_iter(self.root.lang_items_missing.decode(self)) . } . . fn get_fn_param_names(self, tcx: TyCtxt<'tcx>, id: DefIndex) -> &'tcx [Ident] { . let param_names = match self.kind(id) { . EntryKind::Fn(data) | EntryKind::ForeignFn(data) => data.decode(self).param_names, . EntryKind::AssocFn(data) => data.decode(self).fn_data.param_names, . _ => Lazy::empty(), . }; . tcx.arena.alloc_from_iter(param_names.decode((self, tcx))) . } . . fn exported_symbols( . self, . tcx: TyCtxt<'tcx>, . ) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportLevel)] { 24 ( 0.00%) tcx.arena.alloc_from_iter(self.root.exported_symbols.decode((self, tcx))) . } . . fn get_rendered_const(self, id: DefIndex) -> String { . match self.kind(id) { . EntryKind::AnonConst(_, data) . | EntryKind::Const(_, data) . | EntryKind::AssocConst(_, _, data) => data.decode(self).0, . _ => bug!(), . } . } . . fn get_macro(self, id: DefIndex, sess: &Session) -> MacroDef { 120 ( 0.00%) match self.kind(id) { 20 ( 0.00%) EntryKind::MacroDef(macro_def) => macro_def.decode((self, sess)), . _ => bug!(), . } . } . . // This replicates some of the logic of the crate-local `is_const_fn_raw` query, because we . // don't serialize constness for tuple variant and tuple struct constructors. . fn is_const_fn_raw(self, id: DefIndex) -> bool { 162 ( 0.00%) let constness = match self.kind(id) { 30 ( 0.00%) EntryKind::AssocFn(data) => data.decode(self).fn_data.constness, 18 ( 0.00%) EntryKind::Fn(data) => data.decode(self).constness, . EntryKind::ForeignFn(data) => data.decode(self).constness, . EntryKind::Variant(..) | EntryKind::Struct(..) => hir::Constness::Const, . _ => hir::Constness::NotConst, . }; . constness == hir::Constness::Const . } . . fn asyncness(self, id: DefIndex) -> hir::IsAsync { -- line 1506 ---------------------------------------- -- line 1508 ---------------------------------------- . EntryKind::Fn(data) => data.decode(self).asyncness, . EntryKind::AssocFn(data) => data.decode(self).fn_data.asyncness, . EntryKind::ForeignFn(data) => data.decode(self).asyncness, . _ => bug!("asyncness: expected function kind"), . } . } . . fn is_foreign_item(self, id: DefIndex) -> bool { 3,498 ( 0.00%) match self.kind(id) { . EntryKind::ForeignImmStatic | EntryKind::ForeignMutStatic | EntryKind::ForeignFn(_) => { . true . } . _ => false, . } . } . . fn static_mutability(self, id: DefIndex) -> Option { 792 ( 0.00%) match self.kind(id) { . EntryKind::ImmStatic | EntryKind::ForeignImmStatic => Some(hir::Mutability::Not), . EntryKind::MutStatic | EntryKind::ForeignMutStatic => Some(hir::Mutability::Mut), . _ => None, . } . } . . fn generator_kind(self, id: DefIndex) -> Option { . match self.kind(id) { . EntryKind::Generator(data) => Some(data), . _ => None, . } . } . . fn fn_sig(self, id: DefIndex, tcx: TyCtxt<'tcx>) -> ty::PolyFnSig<'tcx> { 2,205 ( 0.00%) self.root.tables.fn_sig.get(self, id).unwrap().decode((self, tcx)) . } . . #[inline] 146,265 ( 0.01%) fn def_key(self, index: DefIndex) -> DefKey { 41,920 ( 0.00%) *self . .def_key_cache . .lock() . .entry(index) 24,300 ( 0.00%) .or_insert_with(|| self.root.tables.def_keys.get(self, index).unwrap().decode(self)) 167,160 ( 0.01%) } . . // Returns the path leading to the thing with this `id`. . fn def_path(self, id: DefIndex) -> DefPath { . debug!("def_path(cnum={:?}, id={:?})", self.cnum, id); 108 ( 0.00%) DefPath::make(self.cnum, id, |parent| self.def_key(parent)) . } . . fn def_path_hash_unlocked( . self, . index: DefIndex, . def_path_hashes: &mut FxHashMap, . ) -> DefPathHash { 12,244 ( 0.00%) *def_path_hashes.entry(index).or_insert_with(|| { 4,330 ( 0.00%) self.root.tables.def_path_hashes.get(self, index).unwrap().decode(self) . }) . } . . #[inline] 42,854 ( 0.00%) fn def_path_hash(self, index: DefIndex) -> DefPathHash { . let mut def_path_hashes = self.def_path_hash_cache.lock(); . self.def_path_hash_unlocked(index, &mut def_path_hashes) 48,976 ( 0.00%) } . . #[inline] . fn def_path_hash_to_def_index(self, hash: DefPathHash) -> DefIndex { . self.def_path_hash_map.def_path_hash_to_def_index(&hash) . } . . fn expn_hash_to_expn_id(self, sess: &Session, index_guess: u32, hash: ExpnHash) -> ExpnId { . debug_assert_eq!(ExpnId::from_hash(hash), None); -- line 1580 ---------------------------------------- -- line 1635 ---------------------------------------- . /// Proc macro crates don't currently export spans, so this function does not have . /// to work for them. . fn imported_source_files(self, sess: &Session) -> &'a [ImportedSourceFile] { . // Translate the virtual `/rustc/$hash` prefix back to a real directory . // that should hold actual sources, where possible. . // . // NOTE: if you update this, you might need to also update bootstrap's code for generating . // the `rust-src` component in `Src::run` in `src/bootstrap/dist.rs`. 102,586 ( 0.00%) let virtual_rust_source_base_dir = option_env!("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR") . .map(Path::new) . .filter(|_| { . // Only spend time on further checks if we have what to translate *to*. . sess.opts.real_rust_source_base_dir.is_some() . }) . .filter(|virtual_dir| { . // Don't translate away `/rustc/$hash` if we're still remapping to it, . // since that means we're still building `std`/`rustc` that need it, . // and we don't want the real path to leak into codegen/debuginfo. . !sess.opts.remap_path_prefix.iter().any(|(_from, to)| to == virtual_dir) . }); 102,586 ( 0.00%) let try_to_translate_virtual_to_real = |name: &mut rustc_span::FileName| { . debug!( . "try_to_translate_virtual_to_real(name={:?}): \ . virtual_rust_source_base_dir={:?}, real_rust_source_base_dir={:?}", . name, virtual_rust_source_base_dir, sess.opts.real_rust_source_base_dir, . ); . 3,700 ( 0.00%) if let Some(virtual_dir) = virtual_rust_source_base_dir { . if let Some(real_dir) = &sess.opts.real_rust_source_base_dir { . if let rustc_span::FileName::Real(old_name) = name { . if let rustc_span::RealFileName::Remapped { local_path: _, virtual_name } = . old_name . { . if let Ok(rest) = virtual_name.strip_prefix(virtual_dir) { . let virtual_name = virtual_name.clone(); . -- line 1670 ---------------------------------------- -- line 1709 ---------------------------------------- . *old_name = new_name; . } . } . } . } . } . }; . 102,496 ( 0.00%) self.cdata.source_map_import_info.get_or_init(|| { 42 ( 0.00%) let external_source_map = self.root.source_map.decode(self); . . external_source_map . .map(|source_file_to_import| { . // We can't reuse an existing SourceFile, so allocate a new one . // containing the information we need. . let rustc_span::SourceFile { 15,540 ( 0.00%) mut name, 4,440 ( 0.00%) src_hash, 740 ( 0.00%) start_pos, 1,480 ( 0.00%) end_pos, 3,700 ( 0.00%) mut lines, 3,700 ( 0.00%) mut multibyte_chars, 4,440 ( 0.00%) mut non_narrow_chars, 3,700 ( 0.00%) mut normalized_pos, 4,440 ( 0.00%) name_hash, . .. . } = source_file_to_import; . . // If this file is under $sysroot/lib/rustlib/src/ but has not been remapped . // during rust bootstrapping by `remap-debuginfo = true`, and the user . // wish to simulate that behaviour by -Z simulate-remapped-rust-src-base, . // then we change `name` to a similar state as if the rust was bootstrapped . // with `remap-debuginfo = true`. . // This is useful for testing so that tests about the effects of . // `try_to_translate_virtual_to_real` don't have to worry about how the . // compiler is bootstrapped. 1,480 ( 0.00%) if let Some(virtual_dir) = . &sess.opts.debugging_opts.simulate_remapped_rust_src_base . { . if let Some(real_dir) = &sess.opts.real_rust_source_base_dir { . if let rustc_span::FileName::Real(ref mut old_name) = name { . if let rustc_span::RealFileName::LocalPath(local) = old_name { . if let Ok(rest) = local.strip_prefix(real_dir) { . *old_name = rustc_span::RealFileName::Remapped { . local_path: None, -- line 1753 ---------------------------------------- -- line 1767 ---------------------------------------- . let source_length = (end_pos - start_pos).to_usize(); . . // Translate line-start positions and multibyte character . // position into frame of reference local to file. . // `SourceMap::new_imported_source_file()` will then translate those . // coordinates to their new global frame of reference when the . // offset of the SourceFile is known. . for pos in &mut lines { 826,106 ( 0.03%) *pos = *pos - start_pos; . } . for mbc in &mut multibyte_chars { 1,628 ( 0.00%) mbc.pos = mbc.pos - start_pos; . } . for swc in &mut non_narrow_chars { 924 ( 0.00%) *swc = *swc - start_pos; . } . for np in &mut normalized_pos { . np.pos = np.pos - start_pos; . } . 13,320 ( 0.00%) let local_version = sess.source_map().new_imported_source_file( 9,620 ( 0.00%) name, 5,180 ( 0.00%) src_hash, . name_hash, . source_length, 1,480 ( 0.00%) self.cnum, 3,700 ( 0.00%) lines, 4,440 ( 0.00%) multibyte_chars, 3,700 ( 0.00%) non_narrow_chars, 2,960 ( 0.00%) normalized_pos, . start_pos, . end_pos, . ); . debug!( . "CrateMetaData::imported_source_files alloc \ . source_file {:?} original (start_pos {:?} end_pos {:?}) \ . translated (start_pos {:?} end_pos {:?})", . local_version.name, -- line 1804 ---------------------------------------- -- line 1808 ---------------------------------------- . local_version.end_pos . ); . . ImportedSourceFile { . original_start_pos: start_pos, . original_end_pos: end_pos, . translated_source_file: local_version, . } 2,220 ( 0.00%) }) . .collect() . }) . } . } . . impl CrateMetadata { 360 ( 0.00%) crate fn new( . sess: &Session, . blob: MetadataBlob, . root: CrateRoot<'static>, . raw_proc_macros: Option<&'static [ProcMacro]>, . cnum: CrateNum, . cnum_map: CrateNumMap, . dep_kind: CrateDepKind, . source: CrateSource, . private_dep: bool, . host_hash: Option, . ) -> CrateMetadata { 90 ( 0.00%) let trait_impls = root . .impls . .decode((&blob, sess)) . .map(|trait_impls| (trait_impls.trait_id, trait_impls.impls)) . .collect(); . let alloc_decoding_state = 90 ( 0.00%) AllocDecodingState::new(root.interpret_alloc_index.decode(&blob).collect()); . let dependencies = Lock::new(cnum_map.iter().cloned().collect()); . . // Pre-decode the DefPathHash->DefIndex table. This is a cheap operation . // that does not copy any data. It just does some data verification. 30 ( 0.00%) let def_path_hash_map = root.def_path_hash_map.decode(&blob); . 690 ( 0.00%) CrateMetadata { 30 ( 0.00%) blob, 90 ( 0.00%) root, 120 ( 0.00%) trait_impls, . raw_proc_macros, . source_map_import_info: OnceCell::new(), 120 ( 0.00%) def_path_hash_map, . expn_hash_map: Default::default(), 210 ( 0.00%) alloc_decoding_state, . cnum, 120 ( 0.00%) cnum_map, 150 ( 0.00%) dependencies, . dep_kind: Lock::new(dep_kind), 360 ( 0.00%) source, . private_dep, . host_hash, . extern_crate: Lock::new(None), . hygiene_context: Default::default(), . def_key_cache: Default::default(), . def_path_hash_cache: Default::default(), . } 270 ( 0.00%) } . . crate fn dependencies(&self) -> LockGuard<'_, Vec> { . self.dependencies.borrow() . } . . crate fn add_dependency(&self, cnum: CrateNum) { . self.dependencies.borrow_mut().push(cnum); . } . . crate fn update_extern_crate(&self, new_extern_crate: ExternCrate) -> bool { . let mut extern_crate = self.extern_crate.borrow_mut(); . let update = Some(new_extern_crate.rank()) > extern_crate.as_ref().map(ExternCrate::rank); . if update { 150 ( 0.00%) *extern_crate = Some(new_extern_crate); . } . update . } . . crate fn source(&self) -> &CrateSource { 620 ( 0.00%) &self.source . } . . crate fn dep_kind(&self) -> CrateDepKind { . *self.dep_kind.lock() . } . . crate fn update_dep_kind(&self, f: impl FnOnce(CrateDepKind) -> CrateDepKind) { 319 ( 0.00%) self.dep_kind.with_lock(|dep_kind| *dep_kind = f(*dep_kind)) . } . . crate fn panic_strategy(&self) -> PanicStrategy { . self.root.panic_strategy . } . . crate fn needs_panic_runtime(&self) -> bool { . self.root.needs_panic_runtime -- line 1905 ---------------------------------------- -- line 1909 ---------------------------------------- . self.root.panic_runtime . } . . crate fn is_profiler_runtime(&self) -> bool { . self.root.profiler_runtime . } . . crate fn needs_allocator(&self) -> bool { 5 ( 0.00%) self.root.needs_allocator . } . . crate fn has_global_allocator(&self) -> bool { . self.root.has_global_allocator . } . . crate fn has_default_lib_allocator(&self) -> bool { . self.root.has_default_lib_allocator . } . . crate fn is_proc_macro_crate(&self) -> bool { . self.root.is_proc_macro_crate() . } . . crate fn name(&self) -> Symbol { 1,198 ( 0.00%) self.root.name . } . . crate fn stable_crate_id(&self) -> StableCrateId { . self.root.stable_crate_id . } . . crate fn hash(&self) -> Svh { . self.root.hash . } . . fn num_def_ids(&self) -> usize { . self.root.tables.def_keys.size() . } . . fn local_def_id(&self, index: DefIndex) -> DefId { 19,585 ( 0.00%) DefId { krate: self.cnum, index } . } . . // Translate a DefId from the current compilation environment to a DefId . // for an external crate. . fn reverse_translate_def_id(&self, did: DefId) -> Option { . for (local, &global) in self.cnum_map.iter_enumerated() { 6,947 ( 0.00%) if global == did.krate { . return Some(DefId { krate: local, index: did.index }); . } . } . . None . } . } . -- line 1964 ---------------------------------------- 1,007,901 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs -------------------------------------------------------------------------------- Ir -- line 36 ---------------------------------------- . use rustc_session::parse::ParseSess; . use rustc_span::source_map::{MultiSpan, Span, DUMMY_SP}; . use rustc_span::symbol::{kw, sym, Ident, Symbol}; . use tracing::debug; . . use std::ops::Range; . use std::{cmp, mem, slice}; . 6,296 ( 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); . } . } . } . }; . } . 176,939 ( 0.01%) #[derive(Clone)] . pub struct Parser<'a> { 6,947 ( 0.00%) pub sess: &'a ParseSess, . /// The current token. 6,248 ( 0.00%) pub token: Token, . /// The spacing for the current token 3,142 ( 0.00%) pub token_spacing: Spacing, . /// The previous token. 9,372 ( 0.00%) pub prev_token: Token, 3,160 ( 0.00%) pub capture_cfg: bool, 6,338 ( 0.00%) restrictions: Restrictions, 6,284 ( 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, 6,284 ( 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. 6,284 ( 0.00%) unmatched_angle_bracket_count: u32, 9,426 ( 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. 3,142 ( 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` 3,142 ( 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, . } . 13,249 ( 0.00%) #[derive(Clone)] . struct CaptureState { 12,568 ( 0.00%) capturing: Capturing, 3,142 ( 0.00%) replace_ranges: Vec, . inner_attr_ranges: FxHashMap, . } . . impl<'a> Drop for Parser<'a> { . fn drop(&mut self) { 15,489 ( 0.00%) emit_unclosed_delims(&mut self.unclosed_delims, &self.sess); . } . } . 127,537 ( 0.00%) #[derive(Clone)] . struct TokenCursor { . frame: TokenCursorFrame, 28,679 ( 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. 9,446 ( 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, . } . 58,695 ( 0.00%) #[derive(Clone)] . struct TokenCursorFrame { 13,839 ( 0.00%) delim: token::DelimToken, . span: DelimSpan, . open_delim: bool, 27,678 ( 0.00%) tree_cursor: tokenstream::Cursor, . close_delim: bool, . } . . impl TokenCursorFrame { . fn new(span: DelimSpan, delim: DelimToken, tts: TokenStream) -> Self { 9,305 ( 0.00%) TokenCursorFrame { . delim, . span, . open_delim: false, 26,108 ( 0.00%) tree_cursor: tts.into_trees(), . close_delim: false, . } . } . } . . impl TokenCursor { 1,888,980 ( 0.06%) fn next(&mut self) -> (Token, Spacing) { . loop { 936,421 ( 0.03%) let (tree, spacing) = if !self.frame.open_delim { 21,942 ( 0.00%) self.frame.open_delim = true; 109,710 ( 0.00%) TokenTree::open_tt(self.frame.span, self.frame.delim).into() 1,823,904 ( 0.06%) } else if let Some(tree) = self.frame.tree_cursor.next_with_spacing() { . tree 88,824 ( 0.00%) } else if !self.frame.close_delim { 20,928 ( 0.00%) self.frame.close_delim = true; 104,640 ( 0.00%) TokenTree::close_tt(self.frame.span, self.frame.delim).into() 41,856 ( 0.00%) } else if let Some(frame) = self.stack.pop() { 272,064 ( 0.01%) self.frame = frame; . continue; . } else { 46,008 ( 0.00%) (TokenTree::Token(Token::new(token::Eof, DUMMY_SP)), Spacing::Alone) . }; . 357,826 ( 0.01%) match tree { . TokenTree::Token(token) => { 1,259,320 ( 0.04%) return (token, spacing); . } . TokenTree::Delimited(sp, delim, tts) => { . let frame = TokenCursorFrame::new(sp, delim, tts); . self.stack.push(mem::replace(&mut self.frame, frame)); . } . } . } 1,259,320 ( 0.04%) } . 831,740 ( 0.03%) fn next_desugared(&mut self) -> (Token, Spacing) { 250,410 ( 0.01%) let (data, attr_style, sp) = match self.next() { 1,332 ( 0.00%) (Token { kind: token::DocComment(_, attr_style, data), span }, _) => { . (data, attr_style, span) . } 413,650 ( 0.01%) tok => return tok, . }; . . // Searches for the occurrences of `"#*` and returns the minimum number of `#`s . // required to wrap the text. . let mut num_of_hashes = 0; . let mut count = 0; 86,798 ( 0.00%) for ch in data.as_str().chars() { . count = match ch { . '"' => 1, 76 ( 0.00%) '#' if count > 0 => count + 1, . _ => 0, . }; . num_of_hashes = cmp::max(num_of_hashes, count); . } . 1,776 ( 0.00%) let delim_span = DelimSpan::from_single(sp); 2,220 ( 0.00%) let body = TokenTree::Delimited( . delim_span, . token::Bracket, 5,328 ( 0.00%) [ 3,108 ( 0.00%) TokenTree::token(token::Ident(sym::doc, false), sp), 1,776 ( 0.00%) TokenTree::token(token::Eq, sp), 3,552 ( 0.00%) TokenTree::token(TokenKind::lit(token::StrRaw(num_of_hashes), data, None), sp), . ] . .iter() . .cloned() . .collect::(), 444 ( 0.00%) ); . . self.stack.push(mem::replace( . &mut self.frame, . TokenCursorFrame::new( . delim_span, . token::NoDelim, 444 ( 0.00%) if attr_style == AttrStyle::Inner { . [TokenTree::token(token::Pound, sp), TokenTree::token(token::Not, sp), body] . .iter() . .cloned() . .collect::() . } else { 5,328 ( 0.00%) [TokenTree::token(token::Pound, sp), body] . .iter() . .cloned() . .collect::() . }, . ), . )); . 1,332 ( 0.00%) self.next() 748,566 ( 0.03%) } . } . 8,510 ( 0.00%) #[derive(Debug, Clone, PartialEq)] . enum TokenType { 6,808 ( 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 { 6 ( 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> { 276 ( 0.00%) Some(match token.kind { 552 ( 0.00%) _ if token.is_special_ident() => "reserved identifier", 552 ( 0.00%) _ if token.is_used_keyword() => "keyword", 552 ( 0.00%) _ if token.is_unused_keyword() => "reserved keyword", . token::DocComment(..) => "doc comment", . _ => return None, . }) . } . 966 ( 0.00%) pub(super) fn token_descr(token: &Token) -> String { 276 ( 0.00%) let token_str = pprust::token_to_string(token); . match token_descr_opt(token) { . Some(prefix) => format!("{} `{}`", prefix, token_str), 966 ( 0.00%) _ => format!("`{}`", token_str), . } 690 ( 0.00%) } . . impl<'a> Parser<'a> { 26,054 ( 0.00%) pub fn new( . sess: &'a ParseSess, . tokens: TokenStream, . desugar_doc_comments: bool, . subparser_name: Option<&'static str>, . ) -> Self { 1,861 ( 0.00%) let mut start_frame = TokenCursorFrame::new(DelimSpan::dummy(), token::NoDelim, tokens); 3,722 ( 0.00%) start_frame.open_delim = true; . start_frame.close_delim = true; . 57,691 ( 0.00%) let mut parser = Parser { . sess, 1,861 ( 0.00%) token: Token::dummy(), . token_spacing: Spacing::Alone, 1,861 ( 0.00%) prev_token: Token::dummy(), . capture_cfg: false, . restrictions: Restrictions::empty(), . expected_tokens: Vec::new(), . token_cursor: TokenCursor { 11,166 ( 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,722 ( 0.00%) parser.bump(); . . parser 16,749 ( 0.00%) } . . fn next_tok(&mut self, fallback_span: Span) -> (Token, Spacing) { . loop { 928,842 ( 0.03%) let (mut next, spacing) = if self.desugar_doc_comments { 332,696 ( 0.01%) self.token_cursor.next_desugared() . } else { 214,899 ( 0.01%) self.token_cursor.next() . }; 619,228 ( 0.02%) 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 154,807 ( 0.01%) self.token_cursor.break_last_token = false; 619,228 ( 0.02%) if next.span.is_dummy() { . // Tweak the location for better diagnostics, but keep syntactic context intact. 7,476 ( 0.00%) next.span = fallback_span.with_ctxt(next.span.ctxt()); . } 528,099 ( 0.02%) if matches!( 309,614 ( 0.01%) next.kind, . token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) . ) { . continue; . } 615,676 ( 0.02%) 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`. 27,054 ( 0.00%) pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> { 3,006 ( 0.00%) if self.expected_tokens.is_empty() { 1,896 ( 0.00%) if self.token == *t { 1,580 ( 0.00%) self.bump(); . Ok(false) . } else { . self.unexpected_try_recover(t) . } . } else { 32,280 ( 0.00%) self.expect_one_of(slice::from_ref(t), &[]) . } 45,090 ( 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. 38,040 ( 0.00%) pub fn expect_one_of( . &mut self, . edible: &[TokenKind], . inedible: &[TokenKind], . ) -> PResult<'a, bool /* recovered */> { 6,340 ( 0.00%) if edible.contains(&self.token.kind) { 8,187 ( 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) . } 47,550 ( 0.00%) } . . // Public for rustfmt usage. . pub fn parse_ident(&mut self) -> PResult<'a, Ident> { 17,620 ( 0.00%) self.parse_ident_common(true) . } . . fn ident_or_err(&mut self) -> PResult<'a, (Ident, /* is_raw */ bool)> { 13,587 ( 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(), . }) . } . 31,570 ( 0.00%) fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> { 4,510 ( 0.00%) let (ident, is_raw) = self.ident_or_err()?; 27,060 ( 0.00%) if !is_raw && ident.is_reserved() { . let mut err = self.expected_ident_found(); . if recover { . err.emit(); . } else { . return Err(err); . } . } 18,040 ( 0.00%) self.bump(); . Ok(ident) 45,100 ( 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. 370,979 ( 0.01%) fn check(&mut self, tok: &TokenKind) -> bool { 160,803 ( 0.01%) let is_present = self.token == *tok; 108,024 ( 0.00%) if !is_present { 224,794 ( 0.01%) self.expected_tokens.push(TokenType::Token(tok.clone())); . } . is_present 370,979 ( 0.01%) } . . /// Consumes a token 'tok' if it exists. Returns whether the given token was present. 56 ( 0.00%) pub fn eat(&mut self, tok: &TokenKind) -> bool { 72,952 ( 0.00%) let is_present = self.check(tok); 48,458 ( 0.00%) if is_present { 10,446 ( 0.00%) self.bump() . } . is_present 70 ( 0.00%) } . . /// If the next token is the given keyword, returns `true` without eating it. . /// An expectation is also added for diagnostics purposes. 48,295 ( 0.00%) fn check_keyword(&mut self, kw: Symbol) -> bool { 7,159 ( 0.00%) self.expected_tokens.push(TokenType::Keyword(kw)); 230,196 ( 0.01%) 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. 49,855 ( 0.00%) pub fn eat_keyword(&mut self, kw: Symbol) -> bool { 40,460 ( 0.00%) if self.check_keyword(kw) { 2,229 ( 0.00%) self.bump(); . true . } else { . false . } 49,855 ( 0.00%) } . . fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool { 2,390 ( 0.00%) if self.token.is_keyword(kw) { 572 ( 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. 355 ( 0.00%) fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> { . if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) } 284 ( 0.00%) } . . /// Is the given keyword `kw` followed by a non-reserved identifier? 27,936 ( 0.00%) fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool { 13,968 ( 0.00%) self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()) 31,428 ( 0.00%) } . 23,328 ( 0.00%) fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool { 8,848 ( 0.00%) if ok { . true . } else { 6,324 ( 0.00%) self.expected_tokens.push(typ); . false . } 23,328 ( 0.00%) } . . fn check_ident(&mut self) -> bool { 1,544 ( 0.00%) self.check_or_expected(self.token.is_ident(), TokenType::Ident) . } . 12,088 ( 0.00%) fn check_path(&mut self) -> bool { 24,950 ( 0.00%) self.check_or_expected(self.token.is_path_start(), TokenType::Path) 15,110 ( 0.00%) } . . fn check_type(&mut self) -> bool { 538 ( 0.00%) self.check_or_expected(self.token.can_begin_type(), TokenType::Type) . } . . fn check_const_arg(&mut self) -> bool { 496 ( 0.00%) self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const) . } . 2,637 ( 0.00%) fn check_inline_const(&self, dist: usize) -> bool { 1,465 ( 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, . }) 2,637 ( 0.00%) } . . /// Checks to see if the next token is either `+` or `+=`. . /// Otherwise returns `false`. . fn check_plus(&mut self) -> bool { 2,144 ( 0.00%) self.check_or_expected( 1,072 ( 0.00%) self.token.is_like_plus(), 1,072 ( 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. 21,888 ( 0.00%) fn break_and_eat(&mut self, expected: TokenKind) -> bool { 12,768 ( 0.00%) if self.token.kind == expected { 596 ( 0.00%) self.bump(); . return true; . } 7,630 ( 0.00%) match self.token.kind.break_two_token_op() { 63 ( 0.00%) Some((first, second)) if first == expected => { 36 ( 0.00%) let first_span = self.sess.source_map().start_point(self.token.span); 45 ( 0.00%) let second_span = self.token.span.with_lo(first_span.hi()); 81 ( 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` 9 ( 0.00%) self.token_cursor.break_last_token = true; . // Use the spacing of the glued token as the spacing . // of the unglued second token. 126 ( 0.00%) self.bump_with((Token::new(second, second_span), self.token_spacing)); . true . } . _ => { 4,551 ( 0.00%) self.expected_tokens.push(TokenType::Token(expected)); . false . } . } 22,484 ( 0.00%) } . . /// Eats `+` possibly breaking tokens like `+=` in process. . fn eat_plus(&mut self) -> bool { 48 ( 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, ()> { 420 ( 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, ()> { 12 ( 0.00%) if self.break_and_eat(token::BinOp(token::Or)) { Ok(()) } else { self.unexpected() } . } . . /// Eats `<` possibly breaking tokens like `<<` in process. 1,154 ( 0.00%) fn eat_lt(&mut self) -> bool { 5,253 ( 0.00%) let ate = self.break_and_eat(token::Lt); 3,383 ( 0.00%) if ate { . // See doc comment for `unmatched_angle_bracket_count`. 608 ( 0.00%) self.unmatched_angle_bracket_count += 1; 697 ( 0.00%) self.max_angle_bracket_count += 1; . debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count); . } . ate 1,154 ( 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, ()> { 480 ( 0.00%) if self.break_and_eat(token::Gt) { . // See doc comment for `unmatched_angle_bracket_count`. 240 ( 0.00%) if self.unmatched_angle_bracket_count > 0 { 160 ( 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 { 3,588 ( 0.00%) TokenExpectType::Expect => self.check(k), 30 ( 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) { 3,558 ( 0.00%) if let token::CloseDelim(..) | token::Eof = self.token.kind { . break; . } 2,631 ( 0.00%) if let Some(ref t) = sep.sep { 3,109 ( 0.00%) if first { . first = false; . } else { 1,344 ( 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; . } . } . } . } . } . } 1,270 ( 0.00%) if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) { . trailing = true; . break; . } . 1,273 ( 0.00%) let t = f(self)?; 1,245 ( 0.00%) v.push(t); . } . 2,168 ( 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)> { 2,647 ( 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. 3,150 ( 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 */)> { 1,419 ( 0.00%) let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?; 741 ( 0.00%) if !recovered { . self.eat(ket); . } 3,700 ( 0.00%) Ok((val, trailing)) 2,520 ( 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)> { 1,193 ( 0.00%) self.expect(bra)?; 2,520 ( 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( 528 ( 0.00%) &token::OpenDelim(delim), 741 ( 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. 2,001,064 ( 0.07%) fn bump_with(&mut self, (next_token, next_spacing): (Token, Spacing)) { . // Bumping after EOF is a bad sign, usually an infinite loop. 923,568 ( 0.03%) 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. 615,712 ( 0.02%) self.prev_token = mem::replace(&mut self.token, next_token); 153,928 ( 0.01%) self.token_spacing = next_spacing; . . // Diagnostics. 153,928 ( 0.01%) self.expected_tokens.clear(); . } . . /// Advance the parser by one token. 1,231,352 ( 0.04%) pub fn bump(&mut self) { 615,676 ( 0.02%) let next_token = self.next_tok(self.token.span); 923,514 ( 0.03%) self.bump_with(next_token); 1,231,352 ( 0.04%) } . . /// Look-ahead `dist` tokens of `self.token` and get access to that token there. . /// When `dist == 0` then the current token is looked at. 24 ( 0.00%) pub fn look_ahead(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R { 1,368 ( 0.00%) if dist == 0 { 472 ( 0.00%) return looker(&self.token); . } . 7,557 ( 0.00%) let frame = &self.token_cursor.frame; 7,990 ( 0.00%) if frame.delim != DelimToken::NoDelim { . let all_normal = (0..dist).all(|i| { 18,154 ( 0.00%) let token = frame.tree_cursor.look_ahead(i); 23,158 ( 0.00%) !matches!(token, Some(TokenTree::Delimited(_, DelimToken::NoDelim, _))) . }); . if all_normal { 29,643 ( 0.00%) return match frame.tree_cursor.look_ahead(dist - 1) { 9,666 ( 0.00%) Some(tree) => match tree { 4,403 ( 0.00%) TokenTree::Token(token) => looker(token), . TokenTree::Delimited(dspan, delim, _) => { 2,950 ( 0.00%) looker(&Token::new(token::OpenDelim(*delim), dspan.open)) . } . }, 7,721 ( 0.00%) None => looker(&Token::new(token::CloseDelim(frame.delim), frame.span.close)), . }; . } . } . . let mut cursor = self.token_cursor.clone(); . let mut i = 0; 2,171 ( 0.00%) let mut token = Token::dummy(); 214 ( 0.00%) while i < dist { 15,236 ( 0.00%) token = cursor.next().0; 6,754 ( 0.00%) if matches!( 4,328 ( 0.00%) token.kind, . token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) . ) { . continue; . } 110 ( 0.00%) i += 1; . } 138 ( 0.00%) return looker(&token); 18 ( 0.00%) } . . /// Returns whether any of the given keywords are `dist` tokens ahead of the current one. 5,481 ( 0.00%) fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool { 1,499 ( 0.00%) self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw))) 5,481 ( 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. 498 ( 0.00%) fn parse_unsafety(&mut self) -> Unsafe { . if self.eat_keyword(kw::Unsafe) { 20 ( 0.00%) Unsafe::Yes(self.prev_token.uninterpolated_span()) . } else { . Unsafe::No . } 1,992 ( 0.00%) } . . /// Parses constness: `const` or nothing. 16,304 ( 0.00%) fn parse_constness(&mut self) -> Const { . // Avoid const blocks to be parsed as const items 5,574 ( 0.00%) if self.look_ahead(1, |t| t != &token::OpenDelim(DelimToken::Brace)) . && self.eat_keyword(kw::Const) . { 695 ( 0.00%) Const::Yes(self.prev_token.uninterpolated_span()) . } else { . Const::No . } 28,532 ( 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 } 140 ( 0.00%) } . . /// Possibly parses mutability (`const` or `mut`). 30 ( 0.00%) 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 . } 30 ( 0.00%) } . . fn parse_field_name(&mut self) -> PResult<'a, Ident> { 172 ( 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 { 258 ( 0.00%) self.parse_ident_common(true) . } . } . . fn parse_mac_args(&mut self) -> PResult<'a, P> { 2,166 ( 0.00%) self.parse_mac_args_common(true).map(P) . } . . fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> { 2,430 ( 0.00%) self.parse_mac_args_common(false) . } . 13,815 ( 0.00%) fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> { 12,280 ( 0.00%) Ok( 12,503 ( 0.00%) if self.check(&token::OpenDelim(DelimToken::Paren)) 3,621 ( 0.00%) || self.check(&token::OpenDelim(DelimToken::Bracket)) 3,621 ( 0.00%) || self.check(&token::OpenDelim(DelimToken::Brace)) . { 4,016 ( 0.00%) match self.parse_token_tree() { 5,020 ( 0.00%) TokenTree::Delimited(dspan, delim, tokens) => . // We've confirmed above that there is a delimiter so unwrapping is OK. . { 2,008 ( 0.00%) MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens) . } . _ => unreachable!(), . } 1,062 ( 0.00%) } else if !delimited_only { . if self.eat(&token::Eq) { 351 ( 0.00%) let eq_span = self.prev_token.span; . . // Collect tokens because they are used during lowering to HIR. 351 ( 0.00%) let expr = self.parse_expr_force_collect()?; 351 ( 0.00%) let span = expr.span; . 1,755 ( 0.00%) let token_kind = token::Interpolated(Lrc::new(token::NtExpr(expr))); 3,159 ( 0.00%) MacArgs::Eq(eq_span, Token::new(token_kind, span)) . } else { . MacArgs::Empty . } . } else { . return self.unexpected(); . }, . ) 10,745 ( 0.00%) } . . fn parse_or_use_outer_attributes( . &mut self, . already_parsed_attrs: Option, . ) -> PResult<'a, AttrWrapper> { 6,422 ( 0.00%) if let Some(attrs) = already_parsed_attrs { . Ok(attrs) . } else { 3,316 ( 0.00%) self.parse_outer_attributes() . } . } . . /// Parses a single token tree from the input. 147,792 ( 0.01%) pub(crate) fn parse_token_tree(&mut self) -> TokenTree { 122,366 ( 0.00%) match self.token.kind { . token::OpenDelim(..) => { . let depth = self.token_cursor.stack.len(); . . // We keep advancing the token cursor until we hit . // the matching `CloseDelim` token. 186,540 ( 0.01%) 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. 140,224 ( 0.00%) self.bump(); . } . // We are still inside the frame corresponding . // to the delimited stream we captured, so grab . // the tokens from this frame. . let frame = &self.token_cursor.frame; 3,476 ( 0.00%) let stream = frame.tree_cursor.stream.clone(); 3,476 ( 0.00%) let span = frame.span; 1,738 ( 0.00%) let delim = frame.delim; . // Consume close delimiter 3,476 ( 0.00%) self.bump(); 8,690 ( 0.00%) TokenTree::Delimited(span, delim, stream) . } . token::CloseDelim(_) | token::Eof => unreachable!(), . _ => { 33,472 ( 0.00%) self.bump(); 83,680 ( 0.00%) TokenTree::Token(self.prev_token.clone()) . } . } 129,318 ( 0.00%) } . . /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF. . pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec> { . let mut tts = Vec::new(); . while self.token != token::Eof { . tts.push(self.parse_token_tree()); . } . Ok(tts) -- line 1234 ---------------------------------------- -- line 1244 ---------------------------------------- . } . TokenStream::new(result) . } . . /// Evaluates the closure with restrictions in place. . /// . /// Afters the closure is evaluated, restrictions are reset. . fn with_res(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T { 2,334 ( 0.00%) let old = self.restrictions; 3,200 ( 0.00%) self.restrictions = res; . let res = f(self); 3,060 ( 0.00%) self.restrictions = old; . res . } . 18,576 ( 0.00%) fn is_crate_vis(&self) -> bool { 11,610 ( 0.00%) self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep) 20,898 ( 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. 20,370 ( 0.00%) pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> { 4,094 ( 0.00%) maybe_whole!(self, NtVis, |x| x); . 2,035 ( 0.00%) self.expected_tokens.push(TokenType::Keyword(kw::Crate)); 8,140 ( 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". 1,922 ( 0.00%) return Ok(Visibility { 5,766 ( 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. 63 ( 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)`. 21 ( 0.00%) self.bump(); // `(` 14 ( 0.00%) self.bump(); // `crate` 21 ( 0.00%) self.expect(&token::CloseDelim(token::Paren))?; // `)` 7 ( 0.00%) let vis = VisibilityKind::Crate(CrateSugar::PubCrate); . return Ok(Visibility { 21 ( 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. . } . } . 318 ( 0.00%) Ok(Visibility { span: lo, kind: VisibilityKind::Public, tokens: None }) 18,333 ( 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 { 178 ( 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, . } . } . 4,650 ( 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, 471 ( 0.00%) |this, _attrs| Ok((f(this)?, TrailingToken::None)), . ) 4,650 ( 0.00%) } . . /// `::{` or `::*` 34,312 ( 0.00%) fn is_import_coupler(&mut self) -> bool { 17,156 ( 0.00%) self.check(&token::ModSep) . && self.look_ahead(1, |t| { 9,787 ( 0.00%) *t == token::OpenDelim(token::Brace) || *t == token::BinOp(token::Star) . }) 33,921 ( 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) . } . 40,024 ( 0.00%) pub fn emit_unclosed_delims(unclosed_delims: &mut Vec, sess: &ParseSess) { 20,012 ( 0.00%) *sess.reached_eof.borrow_mut() |= . unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none()); 20,012 ( 0.00%) for unmatched in unclosed_delims.drain(..) { . if let Some(mut e) = make_unclosed_delims_error(unmatched, sess) { . e.emit(); . } . } 40,024 ( 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 ---------------------------------------- 654,931 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/rustc_entry.rs -------------------------------------------------------------------------------- Ir -- line 26 ---------------------------------------- . /// } . /// . /// assert_eq!(letters[&'s'], 2); . /// assert_eq!(letters[&'t'], 3); . /// assert_eq!(letters[&'u'], 1); . /// assert_eq!(letters.get(&'y'), None); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 2,695,360 ( 0.09%) pub fn rustc_entry(&mut self, key: K) -> RustcEntry<'_, K, V, A> { . let hash = make_insert_hash(&self.hash_builder, &key); 572 ( 0.00%) if let Some(elem) = self.table.find(hash, |q| q.0.eq(&key)) { 249,063 ( 0.01%) RustcEntry::Occupied(RustcOccupiedEntry { 546,101 ( 0.02%) key: Some(key), . elem, . table: &mut self.table, . }) . } else { . // Ideally we would put this in VacantEntry::insert, but Entry is not . // generic over the BuildHasher and adding a generic parameter would be . // a breaking change. . self.reserve(1); . 364,557 ( 0.01%) RustcEntry::Vacant(RustcVacantEntry { . hash, 107,303 ( 0.00%) key, . table: &mut self.table, . }) . } 1,761,316 ( 0.06%) } . } . . /// A view into a single entry in a map, which may either be vacant or occupied. . /// . /// This `enum` is constructed from the [`entry`] method on [`HashMap`]. . /// . /// [`HashMap`]: struct.HashMap.html . /// [`entry`]: struct.HashMap.html#method.rustc_entry -- line 62 ---------------------------------------- -- line 405 ---------------------------------------- . /// if let RustcEntry::Occupied(o) = map.rustc_entry("poneyland") { . /// *o.into_mut() += 10; . /// } . /// . /// assert_eq!(map["poneyland"], 22); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn into_mut(self) -> &'a mut V { 18,623 ( 0.00%) unsafe { &mut self.elem.as_mut().1 } . } . . /// Sets the value of the entry, and returns the entry's old value. . /// . /// # Examples . /// . /// ``` . /// use hashbrown::HashMap; -- line 421 ---------------------------------------- -- line 568 ---------------------------------------- . /// let mut map: HashMap<&str, u32> = HashMap::new(); . /// . /// if let RustcEntry::Vacant(o) = map.rustc_entry("poneyland") { . /// o.insert(37); . /// } . /// assert_eq!(map["poneyland"], 37); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 6,778 ( 0.00%) pub fn insert(self, value: V) -> &'a mut V { . unsafe { 66,174 ( 0.00%) let bucket = self.table.insert_no_grow(self.hash, (self.key, value)); 4,595 ( 0.00%) &mut bucket.as_mut().1 . } 9,452 ( 0.00%) } . . /// Sets the value of the entry with the RustcVacantEntry's key, . /// and returns a RustcOccupiedEntry. . /// . /// # Examples . /// . /// ``` . /// use hashbrown::HashMap; -- line 589 ---------------------------------------- 472,787 ( 0.02%) -------------------------------------------------------------------------------- -- 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. 565,873 ( 0.02%) #[derive(Clone)] . enum TokenTreeOrTokenTreeSlice<'tt> { 47,655 ( 0.00%) Tt(TokenTree), 49,322 ( 0.00%) TtSeq(&'tt [TokenTree]), . } . . impl<'tt> TokenTreeOrTokenTreeSlice<'tt> { . /// Returns the number of constituent top-level token trees of `self` (top-level in that it . /// will not recursively descend into subtrees). . fn len(&self) -> usize { 996,088 ( 0.03%) match *self { 49,920 ( 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 { 153,328 ( 0.01%) match *self { 76,852 ( 0.00%) TtSeq(ref v) => v[index].clone(), 477,947 ( 0.02%) 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. 44,738 ( 0.00%) #[derive(Clone)] . struct MatcherTtFrame<'tt> { . /// The "parent" matcher that we are descending into. . elts: TokenTreeOrTokenTreeSlice<'tt>, . /// The position of the "dot" in `elts` at the time we descended. 22,369 ( 0.00%) idx: usize, . } . . type NamedMatchVec = SmallVec<[NamedMatch; 4]>; . . /// Represents a single "position" (aka "matcher position", aka "item"), as . /// described in the module documentation. . /// . /// Here: -- line 140 ---------------------------------------- -- line 147 ---------------------------------------- . /// position refers to. . /// . /// It is important to distinguish these two lifetimes because we have a . /// `SmallVec>` below, and the destructor of . /// that is considered to possibly access the data from its elements (it lacks . /// a `#[may_dangle]` attribute). As a result, the compiler needs to know that . /// all the elements in that `SmallVec` strictly outlive the root stack slot . /// lifetime. By separating `'tt` from `'root`, we can show that. 2,628,663 ( 0.09%) #[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 55,929 ( 0.00%) idx: usize, . . /// For each named metavar in the matcher, we keep track of token trees matched against the . /// metavar by the black box parser. In particular, there may be more than one match per . /// metavar if we are in a repetition (each repetition matches each of the variables). . /// Moreover, matchers and repetitions can be nested; the `matches` field is shared (hence the . /// `Rc`) among all "nested" matchers. `match_lo`, `match_cur`, and `match_hi` keep track of . /// the current position of the `self` matcher position in the shared `matches` list. . /// . /// Also, note that while we are descending into a sequence, matchers are given their own . /// `matches` vector. Only once we reach the end of a full repetition of the sequence do we add . /// all bound matches from the submatcher into the shared top-level `matches` vector. If `sep` . /// and `up` are `Some`, then `matches` is _not_ the shared top-level list. Instead, if one . /// wants the shared `matches`, one should use `up.matches`. 223,716 ( 0.01%) 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]`. 55,929 ( 0.00%) match_lo: usize, . /// The position in `matches` corresponding to the metavar we are currently trying to match . /// against the source token stream. `match_lo <= match_cur <= match_hi`. . match_cur: usize, . /// Similar to `match_lo` except `match_hi` is the position in `matches` of the _last_ metavar . /// in this matcher. 55,929 ( 0.00%) match_hi: usize, . . // The following fields are used if we are matching a repetition. If we aren't, they should be . // `None`. . /// The KleeneOp of this sequence if we are in a repetition. 55,929 ( 0.00%) seq_op: Option, . . /// The separator if we are in a repetition. . sep: Option, . . /// The "parent" matcher position if we are in a repetition. That is, the matcher position just . /// before we enter the sequence. 111,858 ( 0.00%) up: Option>, . . /// Specifically used to "unzip" token trees. By "unzip", we mean to unwrap the delimiters from . /// a delimited token tree (e.g., something wrapped in `(` `)`) or to get the contents of a doc . /// comment... . /// . /// When matching against matchers with nested delimited submatchers (e.g., `pat ( pat ( .. ) . /// pat ) pat`), we need to keep track of the matchers we are descending into. This stack does . /// that where the bottom of the stack is the outermost matcher. . /// Also, throughout the comments, this "descent" is often referred to as "unzipping"... . stack: SmallVec<[MatcherTtFrame<'tt>; 1]>, . } . . impl<'root, 'tt> MatcherPos<'root, 'tt> { . /// Adds `m` as a named match for the `idx`-th metavar. . fn push_match(&mut self, idx: usize, m: NamedMatch) { 280,100 ( 0.01%) 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. 223,716 ( 0.01%) fn clone(&self) -> Self { 111,858 ( 0.00%) MatcherPosHandle::Box(match *self { 16,962 ( 0.00%) MatcherPosHandle::Ref(ref r) => Box::new((**r).clone()), . MatcherPosHandle::Box(ref b) => b.clone(), . }) 335,574 ( 0.01%) } . } . . 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 { 92,224 ( 0.00%) ms.iter().fold(0, |count, elt| { 46,112 ( 0.00%) count 138,336 ( 0.00%) + match *elt { 19,170 ( 0.00%) TokenTree::Sequence(_, ref seq) => seq.num_captures, 2,731 ( 0.00%) TokenTree::Delimited(_, ref delim) => count_names(&delim.tts), . TokenTree::MetaVar(..) => 0, . TokenTree::MetaVarDecl(..) => 1, . TokenTree::Token(..) => 0, . } 115,280 ( 0.00%) }) . } . . /// `len` `Vec`s (initially shared and empty) that will store matches of metavars. . fn create_matches(len: usize) -> Box<[Lrc]> { 30,039 ( 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); 46,785 ( 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. 204,016 ( 0.01%) #[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`. 139,348 ( 0.00%) fn n_rec>( . sess: &ParseSess, . m: &TokenTree, . res: &mut I, . ret_val: &mut FxHashMap, . ) -> Result<(), (rustc_span::Span, String)> { 70,958 ( 0.00%) match *m { . TokenTree::Sequence(_, ref seq) => { 3,191 ( 0.00%) for next_m in &seq.tts { 30,750 ( 0.00%) n_rec(sess, next_m, res.by_ref(), ret_val)? . } . } . TokenTree::Delimited(_, ref delim) => { 1,874 ( 0.00%) for next_m in &delim.tts { 18,432 ( 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())); . } . } 22,854 ( 0.00%) TokenTree::MetaVarDecl(sp, bind_name, _) => match ret_val 15,236 ( 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(..) => (), . } . 12,668 ( 0.00%) Ok(()) 101,344 ( 0.00%) } . . let mut ret_val = FxHashMap::default(); . for m in ms { 39,263 ( 0.00%) match n_rec(sess, m, res.by_ref(), &mut ret_val) { . Ok(_) => {} . Err((sp, msg)) => return Error(sp, msg), . } . } . 6,309 ( 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 { 330,449 ( 0.01%) if let (Some((ident1, is_raw1)), Some((ident2, is_raw2))) = (t1.ident(), t2.ident()) { 3,346 ( 0.00%) ident1.name == ident2.name && is_raw1 == is_raw2 424,487 ( 0.01%) } else if let (Some(ident1), Some(ident2)) = (t1.lifetime(), t2.lifetime()) { . ident1.name == ident2.name . } else { 181,890 ( 0.01%) 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. 600,880 ( 0.02%) while let Some(mut item) = cur_items.pop() { . // When unzipped trees end, remove them. This corresponds to backtracking out of a . // delimited submatcher into which we already descended. In backtracking out again, we need . // to advance the "dot" past the delimiters in the outer matcher. 1,920,568 ( 0.07%) while item.idx >= item.top_elts.len() { 18,722 ( 0.00%) match item.stack.pop() { . Some(MatcherTtFrame { elts, idx }) => { 84,249 ( 0.00%) item.top_elts = elts; 37,444 ( 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`. 345,687 ( 0.01%) 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. 31,821 ( 0.00%) if item.up.is_some() { . // At this point, regardless of whether there is a separator, we should add all . // matches from the complete repetition of the sequence to the shared, top-level . // `matches` list (actually, `up.matches`, which could itself not be the top-level, . // but anyway...). Moreover, we add another item to `cur_items` in which the "dot" . // is at the end of the `up` matcher. This ensures that the "dot" in the `up` . // matcher is also advanced sufficiently. . // . // NOTE: removing the condition `idx == len` allows trailing separators. 52,108 ( 0.00%) if idx == len { . // Get the `up` matcher . let mut new_pos = item.up.clone().unwrap(); . . // Add matches from this repetition to the `matches` of `up` 52,062 ( 0.00%) for idx in item.match_lo..item.match_hi { 158,290 ( 0.01%) let sub = item.matches[idx].clone(); 94,974 ( 0.00%) new_pos.push_match(idx, MatchedSeq(sub)); . } . . // Move the "dot" past the repetition in `up` 52,037 ( 0.00%) new_pos.match_cur = item.match_hi; 156,186 ( 0.01%) new_pos.idx += 1; . cur_items.push(new_pos); . } . . // Check if we need a separator. 26,031 ( 0.00%) if idx == len && item.sep.is_some() { . // We have a separator, and it is the current token. We can advance past the . // separator token. 66 ( 0.00%) if item.sep.as_ref().map_or(false, |sep| token_name_eq(token, sep)) { 161 ( 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. 26,021 ( 0.00%) else if item.seq_op != Some(mbe::KleeneOp::ZeroOrOne) { 52,038 ( 0.00%) item.match_cur = item.match_lo; 104,076 ( 0.00%) item.idx = 0; . cur_items.push(item); . } . } . // If we are not in a repetition, then being at the end of a matcher means that we have . // reached the potential end of the input. . else { . eof_items.push(item); . } . } . // We are in the middle of a matcher. . else { . // Look at what token in the matcher we are trying to match the current token (`token`) . // against. Depending on that, we may generate new items. 1,023,755 ( 0.04%) match item.top_elts.get_tt(idx) { . // Need to descend into a sequence 47,697 ( 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. 20,694 ( 0.00%) if seq.kleene.op == mbe::KleeneOp::ZeroOrMore . || seq.kleene.op == mbe::KleeneOp::ZeroOrOne . { 20,646 ( 0.00%) let mut new_item = item.clone(); 41,292 ( 0.00%) new_item.match_cur += seq.num_captures; 51,615 ( 0.00%) new_item.idx += 1; 61,938 ( 0.00%) for idx in item.match_cur..item.match_cur + seq.num_captures { 33,918 ( 0.00%) new_item.push_match(idx, MatchedSeq(Lrc::new(smallvec![]))); . } . cur_items.push(new_item); . } . 10,347 ( 0.00%) let matches = create_matches(item.matches.len()); 124,164 ( 0.00%) cur_items.push(MatcherPosHandle::Box(Box::new(MatcherPos { 10,347 ( 0.00%) stack: smallvec![], . sep: seq.separator.clone(), 10,347 ( 0.00%) seq_op: Some(seq.kleene.op), . idx: 0, 51,735 ( 0.00%) matches, 20,694 ( 0.00%) match_lo: item.match_cur, . match_cur: item.match_cur, 20,694 ( 0.00%) match_hi: item.match_cur + seq.num_captures, . up: Some(item), 72,429 ( 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. 176,275 ( 0.01%) 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. 51,275 ( 0.00%) seq @ (TokenTree::Delimited(..) . | TokenTree::Token(Token { kind: DocComment(..), .. })) => { . let lower_elts = mem::replace(&mut item.top_elts, Tt(seq)); 10,255 ( 0.00%) let idx = item.idx; 71,785 ( 0.00%) item.stack.push(MatcherTtFrame { elts: lower_elts, idx }); 41,020 ( 0.00%) item.idx = 0; . cur_items.push(item); . } . . // We just matched a normal token. We can just advance the parser. 306,426 ( 0.01%) TokenTree::Token(t) if token_name_eq(&t, token) => { 259,294 ( 0.01%) 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(..) => {} . } 603,262 ( 0.02%) } 216,288 ( 0.01%) } . . // 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. 31,190 ( 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); 15,595 ( 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(); 67,222 ( 0.00%) assert!(next_items.is_empty()); . . // Process `cur_items` until either we have finished the input or we need to get some . // parsing from the black-box parser done. The result is that `next_items` will contain a . // bunch of possible next matcher positions in `next_items`. . match inner_parse_loop( . parser.sess, . &mut cur_items, . &mut next_items, -- line 648 ---------------------------------------- -- line 652 ---------------------------------------- . ) { . Success(_) => {} . Failure(token, msg) => return Failure(token, msg), . Error(sp, msg) => return Error(sp, msg), . ErrorReported => return ErrorReported, . } . . // inner parse loop handled all cur_items, so it's empty 67,222 ( 0.00%) assert!(cur_items.is_empty()); . . // We need to do some post processing after the `inner_parser_loop`. . // . // Error messages here could be improved with links to original rules. . . // If we reached the EOF, check that there is EXACTLY ONE possible matcher. Otherwise, . // either the parse is ambiguous (which should never happen) or there is a syntax error. 336,110 ( 0.01%) if parser.token == token::Eof { 2,808 ( 0.00%) if eof_items.len() == 1 { . let matches = 5,211 ( 0.00%) eof_items[0].matches.iter_mut().map(|dv| Lrc::make_mut(dv).pop().unwrap()); 2,103 ( 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 { 18 ( 0.00%) return Failure( 6 ( 0.00%) Token::new( . token::Eof, 8 ( 0.00%) if parser.token.span.is_dummy() { . parser.token.span . } else { . parser.token.span.shrink_to_hi() . }, . ), . "missing tokens in macro arguments", . ); . } . } . // Performance hack: eof_items may share matchers via Rc with other things that we want . // to modify. Dropping eof_items now may drop these refcounts to 1, preventing an . // unnecessary implicit clone later in Rc::make_mut. 266,076 ( 0.01%) drop(eof_items); . . // If there are no possible next positions AND we aren't waiting for the black-box parser, . // then there is a syntax error. 239,015 ( 0.01%) if bb_items.is_empty() && next_items.is_empty() { 31,408 ( 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. 108,244 ( 0.00%) else if (!bb_items.is_empty() && !next_items.is_empty()) || bb_items.len() > 1 { . let nts = bb_items . .iter() . .map(|item| match item.top_elts.get_tt(item.idx) { . TokenTree::MetaVarDecl(_, bind, Some(kind)) => format!("{} ('{}')", kind, bind), . _ => panic!(), . }) . .collect::>() . .join(" or "); -- line 712 ---------------------------------------- -- line 721 ---------------------------------------- . n => format!("built-in NTs {} or {} other options.", nts, n), . } . ), . ); . } . // Dump all possible `next_items` into `cur_items` for the next iteration. . else if !next_items.is_empty() { . // Now process the next token 111,126 ( 0.00%) cur_items.extend(next_items.drain(..)); 37,042 ( 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); . 54,122 ( 0.00%) let mut item = bb_items.pop().unwrap(); 216,428 ( 0.01%) if let TokenTree::MetaVarDecl(span, _, Some(kind)) = item.top_elts.get_tt(item.idx) { 27,061 ( 0.00%) let match_cur = item.match_cur; . // We use the span of the metavariable declaration to determine any . // edition-specific matching behavior for non-terminals. 162,397 ( 0.01%) let nt = match parser.to_mut().parse_nonterminal(kind) { . Err(mut err) => { . err.span_label( . span, . format!("while parsing argument for this `{}` macro fragment", kind), . ) . .emit(); . return ErrorReported; . } 162,366 ( 0.01%) Ok(nt) => nt, . }; 108,244 ( 0.00%) item.push_match(match_cur, MatchedNonterminal(Lrc::new(nt))); 108,244 ( 0.00%) item.idx += 1; 162,366 ( 0.01%) item.match_cur += 1; . } else { . unreachable!() . } . cur_items.push(item); . } . 128,206 ( 0.00%) assert!(!cur_items.is_empty()); . } 28,071 ( 0.00%) } 2,274,617 ( 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 . // . 2,711,642 ( 0.09%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 2,033,730 ( 0.07%) 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. 118,620 ( 0.00%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 177,930 ( 0.01%) 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) { 707,555 ( 0.02%) libc::free(ptr as *mut libc::c_void) . } . . #[inline] . unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { 165,000 ( 0.01%) if layout.align() <= MIN_ALIGN && layout.align() <= new_size { 330,000 ( 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 { 1 ( 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::()); 2 ( 0.00%) let ret = libc::posix_memalign(&mut out, align, layout.size()); 2 ( 0.00%) if ret != 0 { ptr::null_mut() } else { out as *mut u8 } . } . } . } 1 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/tokenstream.rs -------------------------------------------------------------------------------- Ir -- line 32 ---------------------------------------- . /// . /// If the syntax extension is an MBE macro, it will attempt to match its . /// LHS token tree against the provided token tree, and if it finds a . /// match, will transcribe the RHS token tree, splicing in any captured . /// `macro_parser::matched_nonterminals` into the `SubstNt`s it finds. . /// . /// The RHS of an MBE macro is the only place `SubstNt`s are substituted. . /// Nothing special happens to misnamed or misplaced `SubstNt`s. 1,468,479 ( 0.05%) #[derive(Debug, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)] . pub enum TokenTree { . /// A single token. 514,354 ( 0.02%) Token(Token), . /// A delimited sequence of token trees. 48,238 ( 0.00%) Delimited(DelimSpan, DelimToken, TokenStream), . } . . #[derive(Copy, Clone)] . pub enum CanSynthesizeMissingTokens { . Yes, . No, . } . -- line 53 ---------------------------------------- -- line 71 ---------------------------------------- . delim == delim2 && tts.eq_unspanned(&tts2) . } . _ => false, . } . } . . /// Retrieves the `TokenTree`'s span. . pub fn span(&self) -> Span { 4,410 ( 0.00%) match self { 1,614 ( 0.00%) TokenTree::Token(token) => token.span, 2,592 ( 0.00%) TokenTree::Delimited(sp, ..) => sp.entire(), . } 1,557 ( 0.00%) } . . /// Modify the `TokenTree`'s span in-place. . pub fn set_span(&mut self, span: Span) { 4,410 ( 0.00%) match self { 1,557 ( 0.00%) TokenTree::Token(token) => token.span = span, 1,296 ( 0.00%) TokenTree::Delimited(dspan, ..) => *dspan = DelimSpan::from_single(span), . } 2,205 ( 0.00%) } . 8,008 ( 0.00%) pub fn token(kind: TokenKind, span: Span) -> TokenTree { 203,512 ( 0.01%) TokenTree::Token(Token::new(kind, span)) 8,008 ( 0.00%) } . . /// Returns the opening delimiter as a token tree. 21,942 ( 0.00%) pub fn open_tt(span: DelimSpan, delim: DelimToken) -> TokenTree { 65,826 ( 0.00%) TokenTree::token(token::OpenDelim(delim), span.open) 21,942 ( 0.00%) } . . /// Returns the closing delimiter as a token tree. 20,928 ( 0.00%) pub fn close_tt(span: DelimSpan, delim: DelimToken) -> TokenTree { 62,784 ( 0.00%) TokenTree::token(token::CloseDelim(delim), span.close) 20,928 ( 0.00%) } . 2,424 ( 0.00%) pub fn uninterpolate(self) -> TokenTree { 1,616 ( 0.00%) match self { 7,272 ( 0.00%) TokenTree::Token(token) => TokenTree::Token(token.uninterpolate().into_owned()), . tt => tt, . } 3,232 ( 0.00%) } . } . . impl HashStable for TokenStream . where . CTX: crate::HashStableContext, . { 2,520 ( 0.00%) fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) { 6,160 ( 0.00%) for sub_tt in self.trees() { . sub_tt.hash_stable(hcx, hasher); . } 2,240 ( 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 { 8 ( 0.00%) pub fn new(inner: impl CreateTokenStream + 'static) -> LazyTokenStream { . LazyTokenStream(Lrc::new(Box::new(inner))) 8 ( 0.00%) } . . pub fn create_token_stream(&self) -> AttrAnnotatedTokenStream { 1,404 ( 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 { 19,184 ( 0.00%) pub fn new(tokens: Vec<(AttrAnnotatedTokenTree, Spacing)>) -> AttrAnnotatedTokenStream { . AttrAnnotatedTokenStream(Lrc::new(tokens)) 19,184 ( 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. 351 ( 0.00%) pub fn to_tokenstream(&self) -> TokenStream { 351 ( 0.00%) let trees: Vec<_> = self . .0 . .iter() 1,053 ( 0.00%) .flat_map(|tree| match &tree.0 { 702 ( 0.00%) AttrAnnotatedTokenTree::Token(inner) => { 1,755 ( 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) 702 ( 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); . 151,651 ( 0.01%) #[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 { 3,840 ( 0.00%) TokenStream::new(vec![(tree, Spacing::Alone)]) . } . } . . impl From for TreeAndSpacing { . fn from(tree: TokenTree) -> TreeAndSpacing { 90,814 ( 0.00%) (tree, Spacing::Alone) . } . } . . impl iter::FromIterator for TokenStream { . fn from_iter>(iter: I) -> Self { 888 ( 0.00%) TokenStream::new(iter.into_iter().map(Into::into).collect::>()) . } . } . . impl Eq for TokenStream {} . . impl PartialEq for TokenStream { . fn eq(&self, other: &TokenStream) -> bool { . self.trees().eq(other.trees()) -- line 399 ---------------------------------------- -- line 401 ---------------------------------------- . } . . impl TokenStream { . pub fn new(streams: Vec) -> TokenStream { . TokenStream(Lrc::new(streams)) . } . . pub fn is_empty(&self) -> bool { 428 ( 0.00%) self.0.is_empty() 428 ( 0.00%) } . . pub fn len(&self) -> usize { 189,638 ( 0.01%) self.0.len() 1,383 ( 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,454 ( 0.00%) self.clone().into_trees() 2,908 ( 0.00%) } . 24,523 ( 0.00%) pub fn into_trees(self) -> Cursor { . Cursor::new(self) 49,046 ( 0.00%) } . . /// Compares two `TokenStream`s, checking equality without regarding span information. . pub fn eq_unspanned(&self, other: &TokenStream) -> bool { . let mut t1 = self.trees(); . let mut t2 = other.trees(); . for (t1, t2) in iter::zip(&mut t1, &mut t2) { . if !t1.eq_unspanned(&t2) { . return false; . } . } . t1.next().is_none() && t2.next().is_none() . } . . pub fn map_enumerated TokenTree>(self, mut f: F) -> TokenStream { 607 ( 0.00%) TokenStream(Lrc::new( . self.0 . .iter() . .enumerate() 13,230 ( 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; . 19,419 ( 0.00%) fn next(&mut self) -> Option { 40,393 ( 0.00%) self.next_with_spacing().map(|(tree, _)| tree) 25,892 ( 0.00%) } . } . . impl Cursor { . fn new(stream: TokenStream) -> Self { . Cursor { stream, index: 0 } . } . 901,995 ( 0.03%) pub fn next_with_spacing(&mut self) -> Option { 560,616 ( 0.02%) if self.index < self.stream.len() { 278,840 ( 0.01%) self.index += 1; 940,933 ( 0.03%) Some(self.stream.0[self.index - 1].clone()) . } else { 91,960 ( 0.00%) None . } 1,082,394 ( 0.04%) } . . 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; . } . 12,048 ( 0.00%) pub fn look_ahead(&self, n: usize) -> Option<&TokenTree> { 24,096 ( 0.00%) self.stream.0[self.index..].get(n).map(|(tree, _)| tree) 24,096 ( 0.00%) } . } . 147,469 ( 0.01%) #[derive(Debug, Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)] . pub struct DelimSpan { . pub open: Span, . pub close: Span, . } . . impl DelimSpan { 797 ( 0.00%) pub fn from_single(sp: Span) -> Self { . DelimSpan { open: sp, close: sp } 1,594 ( 0.00%) } . 856 ( 0.00%) pub fn from_pair(open: Span, close: Span) -> Self { . DelimSpan { open, close } 428 ( 0.00%) } . . pub fn dummy() -> Self { . Self::from_single(DUMMY_SP) 7,740 ( 0.00%) } . 23,984 ( 0.00%) pub fn entire(self) -> Span { . self.open.with_hi(self.close.hi()) 17,988 ( 0.00%) } . } 50,765 ( 0.00%) -------------------------------------------------------------------------------- -- 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}; . 24,022 ( 0.00%) #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub enum CommentKind { . Line, . Block, . } . 333 ( 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. 68,378 ( 0.00%) #[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, . } . 8,903 ( 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. 64,345 ( 0.00%) #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub struct Lit { 2 ( 0.00%) pub kind: LitKind, 2 ( 0.00%) pub symbol: Symbol, 2 ( 0.00%) pub suffix: Option, . } . . impl fmt::Display for Lit { 190 ( 0.00%) fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 342 ( 0.00%) let Lit { kind, symbol, suffix } = *self; . match kind { . Byte => write!(f, "b'{}'", symbol)?, . Char => write!(f, "'{}'", symbol)?, . Str => write!(f, "\"{}\"", symbol)?, . StrRaw(n) => write!( . f, . "r{delim}\"{string}\"{delim}", . delim = "#".repeat(n as usize), -- line 87 ---------------------------------------- -- line 89 ---------------------------------------- . )?, . ByteStr => write!(f, "b\"{}\"", symbol)?, . ByteStrRaw(n) => write!( . f, . "br{delim}\"{string}\"{delim}", . delim = "#".repeat(n as usize), . string = symbol . )?, 114 ( 0.00%) Integer | Float | Bool | Err => write!(f, "{}", symbol)?, . } . 76 ( 0.00%) if let Some(suffix) = suffix { . write!(f, "{}", suffix)?; . } . . Ok(()) 190 ( 0.00%) } . } . . impl LitKind { . /// An English article for the literal token kind. . pub fn article(self) -> &'static str { . match self { . Integer | Err => "an", . _ => "a", -- line 113 ---------------------------------------- -- line 123 ---------------------------------------- . Float => "float", . Str | StrRaw(..) => "string", . ByteStr | ByteStrRaw(..) => "byte string", . Err => "error", . } . } . . crate fn may_have_suffix(self) -> bool { 4 ( 0.00%) matches!(self, Integer | Float | Err) . } . } . . impl Lit { . pub fn new(kind: LitKind, symbol: Symbol, suffix: Option) -> Lit { . Lit { kind, symbol, suffix } 3,926 ( 0.00%) } . } . 212 ( 0.00%) pub fn ident_can_begin_expr(name: Symbol, span: Span, is_raw: bool) -> bool { 371 ( 0.00%) let ident_token = Token::new(Ident(name, is_raw), span); . 110 ( 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) 265 ( 0.00%) } . . fn ident_can_begin_type(name: Symbol, span: Span, is_raw: bool) -> bool { 348 ( 0.00%) let ident_token = Token::new(Ident(name, is_raw), span); . 136 ( 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) . } . 6,113,420 ( 0.21%) #[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, 15,498 ( 0.00%) BinOp(BinOpToken), 135 ( 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., `{`). 31,119 ( 0.00%) OpenDelim(DelimToken), . /// A closing delimiter (e.g., `}`). 6,381 ( 0.00%) CloseDelim(DelimToken), . . /* Literals */ 80,635 ( 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. 44,549 ( 0.00%) 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. 87 ( 0.00%) Lifetime(Symbol), . 26,018 ( 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. 6,114 ( 0.00%) 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); . 738,326 ( 0.03%) #[derive(Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub struct Token { 60,012 ( 0.00%) pub kind: TokenKind, 24 ( 0.00%) pub span: Span, . } . . impl TokenKind { . pub fn lit(kind: LitKind, symbol: Symbol, suffix: Option) -> TokenKind { . Literal(Lit::new(kind, symbol, suffix)) 2,220 ( 0.00%) } . . // 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`. 1,526 ( 0.00%) pub fn break_two_token_op(&self) -> Option<(TokenKind, TokenKind)> { 6,185 ( 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), 1,517 ( 0.00%) _ => return None, . }) 1,526 ( 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 { 306 ( 0.00%) matches!(self, Gt | Ge | BinOp(Shr) | BinOpEq(Shr)) 63 ( 0.00%) } . } . . impl Token { 41,567 ( 0.00%) pub fn new(kind: TokenKind, span: Span) -> Self { 142,821 ( 0.00%) Token { kind, span } 41,567 ( 0.00%) } . . /// Some token that will be thrown away later. 5,892 ( 0.00%) pub fn dummy() -> Self { . Token::new(TokenKind::Question, DUMMY_SP) 5,892 ( 0.00%) } . . /// Recovers a `Token` from an `Ident`. This creates a raw identifier if necessary. . pub fn from_ast_ident(ident: Ident) -> Self { 1,064 ( 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. 4,072 ( 0.00%) pub fn take(&mut self) -> Self { . mem::replace(self, Token::dummy()) 4,072 ( 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,566 ( 0.00%) match &self.kind { . Interpolated(nt) => nt.span(), 783 ( 0.00%) _ => self.span, . } 783 ( 0.00%) } . . pub fn is_op(&self) -> bool { 12,216 ( 0.00%) !matches!( 4,072 ( 0.00%) self.kind, . OpenDelim(..) . | CloseDelim(..) . | Literal(..) . | DocComment(..) . | Ident(..) . | Lifetime(..) . | Interpolated(..) . | Eof . ) 4,072 ( 0.00%) } . . pub fn is_like_plus(&self) -> bool { 5,647 ( 0.00%) matches!(self.kind, BinOp(Plus) | BinOpEq(Plus)) 1,123 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of an expression. 136 ( 0.00%) pub fn can_begin_expr(&self) -> bool { 680 ( 0.00%) match self.uninterpolate().kind { 477 ( 0.00%) Ident(name, is_raw) => 159 ( 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 . // DotDotDot is no longer supported, but we need some way to display the error . DotDot | DotDotDot | DotDotEq | // range notation . Lt | BinOp(Shl) | // associated path . ModSep | // global path . Lifetime(..) | // labeled loop . Pound => true, // expression attributes 576 ( 0.00%) Interpolated(ref nt) => matches!(**nt, NtLiteral(..) | . NtExpr(..) | . NtBlock(..) | . NtPath(..)), . _ => false, . } 272 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of a type. 544 ( 0.00%) pub fn can_begin_type(&self) -> bool { 775 ( 0.00%) match self.uninterpolate().kind { 522 ( 0.00%) Ident(name, is_raw) => 58 ( 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 44 ( 0.00%) Interpolated(ref nt) => matches!(**nt, NtTy(..) | NtPath(..)), . _ => false, . } 816 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of a const param. . pub fn can_begin_const_arg(&self) -> bool { 310 ( 0.00%) match self.kind { . OpenDelim(Brace) => true, 32 ( 0.00%) Interpolated(ref nt) => matches!(**nt, NtExpr(..) | NtBlock(..) | NtLiteral(..)), 58 ( 0.00%) _ => self.can_begin_literal_maybe_minus(), . } 4 ( 0.00%) } . . /// 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) . || self == &Question . || self == &OpenDelim(Paren) -- line 421 ---------------------------------------- -- 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. 59 ( 0.00%) pub fn can_begin_literal_maybe_minus(&self) -> bool { 547 ( 0.00%) match self.uninterpolate().kind { . Literal(..) | BinOp(Minus) => true, 192 ( 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, . } 118 ( 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. 2,837 ( 0.00%) pub fn uninterpolate(&self) -> Cow<'_, Token> { 810,637 ( 0.03%) match &self.kind { 98,682 ( 0.00%) Interpolated(nt) => match **nt { 30,784 ( 0.00%) NtIdent(ident, is_raw) => { 76,960 ( 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), . } 2,837 ( 0.00%) } . . /// Returns an identifier if this token is an identifier. 155,481 ( 0.01%) pub fn ident(&self) -> Option<(Ident, /* is_raw */ bool)> { . let token = self.uninterpolate(); 467,115 ( 0.02%) match token.kind { 1,095,162 ( 0.04%) Ident(name, is_raw) => Some((Ident::new(name, token.span), is_raw)), . _ => None, . } 960,656 ( 0.03%) } . . /// Returns a lifetime identifier if this token is a lifetime. 121,449 ( 0.00%) pub fn lifetime(&self) -> Option { . let token = self.uninterpolate(); 243,328 ( 0.01%) match token.kind { 278 ( 0.00%) Lifetime(name) => Some(Ident::new(name, token.span)), . _ => None, . } 850,143 ( 0.03%) } . . /// Returns `true` if the token is an identifier. . pub fn is_ident(&self) -> bool { . self.ident().is_some() 984 ( 0.00%) } . . /// Returns `true` if the token is a lifetime. 215 ( 0.00%) pub fn is_lifetime(&self) -> bool { . self.lifetime().is_some() 430 ( 0.00%) } . . /// Returns `true` if the token is an identifier whose name is the given . /// string slice. 1,024 ( 0.00%) pub fn is_ident_named(&self, name: Symbol) -> bool { . self.ident().map_or(false, |(ident, _)| ident.name == name) 2,048 ( 0.00%) } . . /// Returns `true` if the token is an interpolated path. . fn is_path(&self) -> bool { 14,044 ( 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 -- line 516 ---------------------------------------- -- line 522 ---------------------------------------- . } . } . . false . } . . // Is the token an interpolated block (`$b:block`)? . pub fn is_whole_block(&self) -> bool { 38 ( 0.00%) if let Interpolated(ref nt) = self.kind { . if let NtBlock(..) = **nt { . return true; . } . } . false 19 ( 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) . } . 574 ( 0.00%) pub fn is_qpath_start(&self) -> bool { 7,740 ( 0.00%) self == &Lt || self == &BinOp(Shl) . } . 14,332 ( 0.00%) pub fn is_path_start(&self) -> bool { 19,852 ( 0.00%) self == &ModSep . || self.is_qpath_start() . || self.is_path() . || self.is_path_segment_keyword() 2,707 ( 0.00%) || self.is_ident() && !self.is_reserved_ident() 17,915 ( 0.00%) } . . /// Returns `true` if the token is a given keyword, `kw`. 68,062 ( 0.00%) pub fn is_keyword(&self, kw: Symbol) -> bool { . self.is_non_raw_ident_where(|id| id.name == kw) 136,124 ( 0.00%) } . 157 ( 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. 138 ( 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. 139 ( 0.00%) pub fn is_used_keyword(&self) -> bool { . self.is_non_raw_ident_where(Ident::is_used_keyword) 3 ( 0.00%) } . . /// Returns `true` if the token is a keyword reserved for possible future use. 138 ( 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`. 157 ( 0.00%) pub fn is_bool_lit(&self) -> bool { 314 ( 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. 312 ( 0.00%) pub fn is_non_raw_ident_where(&self, pred: impl FnOnce(Ident) -> bool) -> bool { 445,013 ( 0.02%) match self.ident() { 2,272 ( 0.00%) Some((id, false)) => pred(id), . _ => false, . } 390 ( 0.00%) } . 11,350 ( 0.00%) pub fn glue(&self, joint: &Token) -> Option { 5,675 ( 0.00%) let kind = match self.kind { 110 ( 0.00%) Eq => match joint.kind { . Eq => EqEq, . Gt => FatArrow, . _ => return None, . }, 15 ( 0.00%) Lt => match joint.kind { . Eq => Le, . Lt => BinOp(Shl), . Le => BinOpEq(Shl), . BinOp(Minus) => LArrow, . _ => return None, . }, 169 ( 0.00%) Gt => match joint.kind { . Eq => Ge, . Gt => BinOp(Shr), . Ge => BinOpEq(Shr), . _ => return None, . }, 2 ( 0.00%) Not => match joint.kind { . Eq => Ne, . _ => return None, . }, 355 ( 0.00%) BinOp(op) => match joint.kind { . Eq => BinOpEq(op), 11 ( 0.00%) BinOp(And) if op == And => AndAnd, . BinOp(Or) if op == Or => OrOr, 32 ( 0.00%) Gt if op == Minus => RArrow, . _ => return None, . }, 24 ( 0.00%) Dot => match joint.kind { . Dot => DotDot, . DotDot => DotDotDot, . _ => return None, . }, . DotDot => match joint.kind { . Dot => DotDotDot, . Eq => DotDotEq, . _ => return None, . }, 462 ( 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, . }; . 4,095 ( 0.00%) Some(Token::new(kind, self.span.to(joint.span))) 10,215 ( 0.00%) } . } . . impl PartialEq for Token { . fn eq(&self, rhs: &TokenKind) -> bool { 171,743 ( 0.01%) self.kind == *rhs . } . } . 364 ( 0.00%) #[derive(Clone, Encodable, Decodable)] . /// For interpolation during macro expansion. . pub enum Nonterminal { . NtItem(P), . NtBlock(P), . NtStmt(ast::Stmt), . NtPat(P), 104 ( 0.00%) NtExpr(P), . NtTy(P), . NtIdent(Ident, /* is_raw */ bool), . NtLifetime(Ident), . NtLiteral(P), . /// Stuff inside brackets for attributes . NtMeta(P), . NtPath(ast::Path), . NtVis(ast::Visibility), -- line 686 ---------------------------------------- -- 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. 292 ( 0.00%) pub fn from_symbol( . symbol: Symbol, . edition: impl FnOnce() -> Edition, . ) -> Option { 682 ( 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, . }) 292 ( 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 ---------------------------------------- 3,113,226 ( 0.11%) -------------------------------------------------------------------------------- -- 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 { 429,370 ( 0.01%) 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 { 22,516 ( 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) { 110,116 ( 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::() . ); 509,497 ( 0.02%) SmallVec { . capacity: 0, . data: SmallVecData::from_inline(MaybeUninit::uninit()), . } . } . . /// Construct an empty vector with enough capacity pre-allocated to store at least `n` . /// elements. . /// -- line 573 ---------------------------------------- -- line 597 ---------------------------------------- . /// . /// let vec = vec![1, 2, 3, 4, 5]; . /// let small_vec: SmallVec<[_; 3]> = SmallVec::from_vec(vec); . /// . /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]); . /// ``` . #[inline] . pub fn from_vec(mut vec: Vec) -> SmallVec { 292 ( 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); . 465 ( 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(), 3,885 ( 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 { 8,654 ( 0.00%) assert!(len <= A::size()); 25,962 ( 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 { 4,327 ( 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(); 31,050 ( 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 { . A::size() . } else { -- line 703 ---------------------------------------- -- 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 { 216,736 ( 0.01%) 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 { 1,739,770 ( 0.06%) 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 { 7,975,460 ( 0.27%) if self.spilled() { 2,959 ( 0.00%) let &mut (ptr, ref mut len_ptr) = self.data.heap_mut(); . (ptr, len_ptr, self.capacity) . } else { . ( . self.data.inline_mut(), . &mut self.capacity, . Self::inline_capacity(), . ) . } . } . } . . /// Returns `true` if the data has spilled into a separate heap-allocated buffer. . #[inline] . pub fn spilled(&self) -> bool { 5,416,102 ( 0.19%) 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] 28,105 ( 0.00%) pub fn push(&mut self, value: A::Item) { . unsafe { . let (mut ptr, mut len, cap) = self.triple_mut(); 966,954 ( 0.03%) if *len == cap { 367 ( 0.00%) self.reserve(1); 10,181 ( 0.00%) let &mut (heap_ptr, ref mut heap_len) = self.data.heap_mut(); . ptr = heap_ptr; . len = heap_len; . } 17,952 ( 0.00%) ptr::write(ptr.add(*len), value); 1,319,493 ( 0.05%) *len += 1; . } 22,484 ( 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(); 647,832 ( 0.02%) if *len_ptr == 0 { . return None; . } 198,967 ( 0.01%) let last_index = *len_ptr - 1; 226,028 ( 0.01%) *len_ptr = last_index; 20,671 ( 0.00%) Some(ptr::read(ptr.add(last_index))) . } 6 ( 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 900 ( 0.00%) pub fn try_grow(&mut self, new_cap: usize) -> Result<(), CollectionAllocErr> { . unsafe { 92 ( 0.00%) let (ptr, &mut len, cap) = self.triple_mut(); . let unspilled = !self.spilled(); 35,058 ( 0.00%) assert!(new_cap >= len); 35,058 ( 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); 35,058 ( 0.00%) } else if new_cap != cap { 34,171 ( 0.00%) let layout = layout_array::(new_cap)?; . debug_assert!(layout.size() > 0); . let new_alloc; 17,529 ( 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`. 5,087 ( 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(); . } 35,058 ( 0.00%) self.data = SmallVecData::from_heap(new_alloc, len); 50,871 ( 0.00%) self.capacity = new_cap; . } . Ok(()) . } 992 ( 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] 79,821 ( 0.00%) pub fn reserve(&mut self, additional: usize) { 451,593 ( 0.02%) infallible(self.try_reserve(additional)) 90,120 ( 0.00%) } . . /// Reserve capacity for `additional` more elements to be inserted. . /// . /// May reserve more space to avoid frequent reallocations. 1,741,967 ( 0.06%) 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() 1,629 ( 0.00%) let (_, &mut len, cap) = self.triple_mut(); 1,239,394 ( 0.04%) 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)?; 247 ( 0.00%) self.try_grow(new_cap) 1,931,730 ( 0.07%) } . . /// Reserve the minimum capacity for `additional` more elements to be inserted. . /// . /// Panics if the new capacity overflows `usize`. . pub fn reserve_exact(&mut self, additional: usize) { . infallible(self.try_reserve_exact(additional)) . } . . /// Reserve the minimum capacity for `additional` more elements to be inserted. . pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), CollectionAllocErr> { . let (_, &mut len, cap) = self.triple_mut(); 30,185 ( 0.00%) if cap - len >= additional { . return Ok(()); . } . let new_cap = len . .checked_add(additional) . .ok_or(CollectionAllocErr::CapacityOverflow)?; 1 ( 0.00%) self.try_grow(new_cap) 1 ( 0.00%) } . . /// Shrink the capacity of the vector as much as possible. . /// . /// When possible, this will move data from an external heap buffer to the vector's inline . /// storage. . pub fn shrink_to_fit(&mut self) { . if !self.spilled() { . return; -- line 981 ---------------------------------------- -- line 999 ---------------------------------------- . /// If `len` is greater than or equal to the vector's current length, this has no . /// effect. . /// . /// This does not re-allocate. If you want the vector's capacity to shrink, call . /// `shrink_to_fit` after truncating. . pub fn truncate(&mut self, len: usize) { . unsafe { . let (ptr, len_ptr, _) = self.triple_mut(); 12,794 ( 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. 24 ( 0.00%) pub fn remove(&mut self, index: usize) -> A::Item { . unsafe { . let (mut ptr, len_ptr, _) = self.triple_mut(); 355 ( 0.00%) let len = *len_ptr; 1,644 ( 0.00%) assert!(index < len); 5,467 ( 0.00%) *len_ptr = len - 1; . ptr = ptr.add(index); . let item = ptr::read(ptr); 1,096 ( 0.00%) ptr::copy(ptr.add(1), ptr, len - index - 1); . item . } 30 ( 0.00%) } . . /// Insert an element at position `index`, shifting all elements after it to the right. . /// . /// Panics if `index` is out of bounds. 5,201 ( 0.00%) pub fn insert(&mut self, index: usize, element: A::Item) { . self.reserve(1); . . unsafe { . let (mut ptr, len_ptr, _) = self.triple_mut(); 581 ( 0.00%) let len = *len_ptr; 1,054 ( 0.00%) assert!(index <= len); 2,108 ( 0.00%) *len_ptr = len + 1; . ptr = ptr.add(index); 1,054 ( 0.00%) ptr::copy(ptr, ptr.add(1), len - index); . ptr::write(ptr, element); . } 3,312 ( 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. 26,937 ( 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,752 ( 0.00%) if !f(&mut self[i]) { . del += 1; 2,432 ( 0.00%) } else if del > 0 { . self.swap(i - del, i); . } . } 5,986 ( 0.00%) self.truncate(len - del); 23,944 ( 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, . ); 310 ( 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`. 101,116 ( 0.00%) pub fn insert_from_slice(&mut self, index: usize, slice: &[A::Item]) { . self.reserve(slice.len()); . . let len = self.len(); 31,329 ( 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()); 20,886 ( 0.00%) self.set_len(len + slice.len()); . } 83,544 ( 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(); 24,868 ( 0.00%) self.insert_from_slice(len, slice); . } . } . . impl SmallVec . where . A::Item: Clone, . { . /// Resizes the vector so that its length is equal to `len`. -- line 1473 ---------------------------------------- -- line 1489 ---------------------------------------- . /// Creates a `SmallVec` with `n` copies of `elem`. . /// ``` . /// use smallvec::SmallVec; . /// . /// let v = SmallVec::<[char; 128]>::from_elem('d', 2); . /// assert_eq!(v, SmallVec::from_buf(['d', 'd'])); . /// ``` . pub fn from_elem(elem: A::Item, n: usize) -> Self { 2,160 ( 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); . } . } 3,213 ( 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 { 89,231 ( 0.00%) let (ptr, &mut len, _) = self.triple_mut(); . slice::from_raw_parts_mut(ptr, len) . } . } . } . . impl AsRef<[A::Item]> for SmallVec { . #[inline] . fn as_ref(&self) -> &[A::Item] { -- line 1538 ---------------------------------------- -- line 1716 ---------------------------------------- . SmallVec::extend_from_slice(self, other) . } . } . . impl FromIterator for SmallVec { . #[inline] . fn from_iter>(iterable: I) -> SmallVec { . let mut v = SmallVec::new(); 379,667 ( 0.01%) v.extend(iterable); . v . } . } . . impl Extend for SmallVec { 2,119,695 ( 0.07%) fn extend>(&mut self, iterable: I) { 283,835 ( 0.01%) let mut iter = iterable.into_iter(); . let (lower_size_bound, _) = iter.size_hint(); 14,968 ( 0.00%) self.reserve(lower_size_bound); . . unsafe { . let (ptr, len_ptr, cap) = self.triple_mut(); . let mut len = SetLenOnDrop::new(len_ptr); 1,187,851 ( 0.04%) while len.get() < cap { 433,615 ( 0.01%) if let Some(out) = iter.next() { . ptr::write(ptr.add(len.get()), out); . len.increment_len(1); . } else { . return; . } . } . } . 35,820 ( 0.00%) for elem in iter { 2,590 ( 0.00%) self.push(elem); . } 1,787,652 ( 0.06%) } . } . . 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 { 2,132,665 ( 0.07%) fn drop(&mut self) { . unsafe { 1,019,157 ( 0.03%) if self.spilled() { . let (ptr, len) = self.data.heap(); . Vec::from_raw_parts(ptr, len, self.capacity); . } else { . ptr::drop_in_place(&mut self[..]); . } . } 2,155,568 ( 0.07%) } . } . . #[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 { 534 ( 0.00%) fn drop(&mut self) { 18,983 ( 0.00%) for _ in self {} 496 ( 0.00%) } . } . . impl Iterator for IntoIter { . type Item = A::Item; . . #[inline] . fn next(&mut self) -> Option { 118,339 ( 0.00%) if self.current == self.end { 1,053 ( 0.00%) None . } else { . unsafe { . let current = self.current; 63,395 ( 0.00%) self.current += 1; 1,442 ( 0.00%) Some(ptr::read(self.data.as_ptr().add(current))) . } . } . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 4,827 ( 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); 8,868 ( 0.00%) IntoIter { 72,598 ( 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 { 227,143 ( 0.01%) local_len: *len, . len, . } . } . . #[inline] . fn get(&self) -> usize { . self.local_len . } . . #[inline] . fn increment_len(&mut self, increment: usize) { 205,741 ( 0.01%) self.local_len += increment; . } . } . . impl<'a> Drop for SetLenOnDrop<'a> { . #[inline] . fn drop(&mut self) { 362,066 ( 0.01%) *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 ---------------------------------------- 3,227,432 ( 0.11%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_serialize/src/opaque.rs -------------------------------------------------------------------------------- Ir -- line 14 ---------------------------------------- . . pub type EncodeResult = Result<(), !>; . . pub struct Encoder { . pub data: Vec, . } . . impl Encoder { 1 ( 0.00%) pub fn new(data: Vec) -> Encoder { 4 ( 0.00%) Encoder { data } 1 ( 0.00%) } . 1 ( 0.00%) pub fn into_inner(self) -> Vec { 4 ( 0.00%) self.data 1 ( 0.00%) } . . #[inline] . pub fn position(&self) -> usize { 15,392 ( 0.00%) self.data.len() . } . } . . macro_rules! write_leb128 { . ($enc:expr, $value:expr, $int_ty:ty, $fun:ident) => {{ . const MAX_ENCODED_LEN: usize = max_leb128_len!($int_ty); . let old_len = $enc.data.len(); . -- line 40 ---------------------------------------- -- line 67 ---------------------------------------- . . #[inline] . fn emit_unit(&mut self) -> EncodeResult { . Ok(()) . } . . #[inline] . fn emit_usize(&mut self, v: usize) -> EncodeResult { 428,806 ( 0.01%) write_leb128!(self, v, usize, write_usize_leb128) . } . . #[inline] . fn emit_u128(&mut self, v: u128) -> EncodeResult { 3,871 ( 0.00%) write_leb128!(self, v, u128, write_u128_leb128) . } . . #[inline] . fn emit_u64(&mut self, v: u64) -> EncodeResult { 917 ( 0.00%) write_leb128!(self, v, u64, write_u64_leb128) . } . . #[inline] . fn emit_u32(&mut self, v: u32) -> EncodeResult { 536,935 ( 0.02%) write_leb128!(self, v, u32, write_u32_leb128) . } . . #[inline] . fn emit_u16(&mut self, v: u16) -> EncodeResult { . self.data.extend_from_slice(&v.to_le_bytes()); . Ok(()) . } . -- line 98 ---------------------------------------- -- line 131 ---------------------------------------- . #[inline] . fn emit_i8(&mut self, v: i8) -> EncodeResult { . let as_u8: u8 = unsafe { std::mem::transmute(v) }; . self.emit_u8(as_u8) . } . . #[inline] . fn emit_bool(&mut self, v: bool) -> EncodeResult { 6,086 ( 0.00%) self.emit_u8(if v { 1 } else { 0 }) . } . . #[inline] . fn emit_f64(&mut self, v: f64) -> EncodeResult { . let as_u64: u64 = v.to_bits(); . self.emit_u64(as_u64) . } . -- line 147 ---------------------------------------- -- line 549 ---------------------------------------- . #[inline] . pub fn advance(&mut self, bytes: usize) { . self.position += bytes; . } . . #[inline] . pub fn read_raw_bytes(&mut self, bytes: usize) -> &'a [u8] { . let start = self.position; 30 ( 0.00%) self.position += bytes; 30 ( 0.00%) &self.data[start..self.position] . } . } . . macro_rules! read_leb128 { . ($dec:expr, $fun:ident) => {{ leb128::$fun($dec.data, &mut $dec.position) }}; . } . . impl<'a> serialize::Decoder for Decoder<'a> { . #[inline] . fn read_unit(&mut self) -> () { . () . } . . #[inline] . fn read_u128(&mut self) -> u128 { 1,608 ( 0.00%) read_leb128!(self, read_u128_leb128) . } . . #[inline] . fn read_u64(&mut self) -> u64 { 4,460 ( 0.00%) read_leb128!(self, read_u64_leb128) . } . . #[inline] 79,440 ( 0.00%) fn read_u32(&mut self) -> u32 { 345,000 ( 0.01%) read_leb128!(self, read_u32_leb128) 158,880 ( 0.01%) } . . #[inline] . fn read_u16(&mut self) -> u16 { 561,610 ( 0.02%) let bytes = [self.data[self.position], self.data[self.position + 1]]; 80,230 ( 0.00%) let value = u16::from_le_bytes(bytes); 160,524 ( 0.01%) self.position += 2; . value . } . . #[inline] . fn read_u8(&mut self) -> u8 { 2,501,962 ( 0.09%) let value = self.data[self.position]; 524,209 ( 0.02%) self.position += 1; . value . } . . #[inline] 439,365 ( 0.02%) fn read_usize(&mut self) -> usize { 439,429 ( 0.02%) read_leb128!(self, read_usize_leb128) 878,730 ( 0.03%) } . . #[inline] . fn read_i128(&mut self) -> i128 { . read_leb128!(self, read_i128_leb128) . } . . #[inline] . fn read_i64(&mut self) -> i64 { -- line 613 ---------------------------------------- -- line 637 ---------------------------------------- . #[inline] . fn read_isize(&mut self) -> isize { . read_leb128!(self, read_isize_leb128) . } . . #[inline] . fn read_bool(&mut self) -> bool { . let value = self.read_u8(); 32,894 ( 0.00%) value != 0 . } . . #[inline] . fn read_f64(&mut self) -> f64 { . let bits = self.read_u64(); . f64::from_bits(bits) . } . -- line 653 ---------------------------------------- -- line 660 ---------------------------------------- . #[inline] . fn read_char(&mut self) -> char { . let bits = self.read_u32(); . std::char::from_u32(bits).unwrap() . } . . #[inline] . fn read_str(&mut self) -> Cow<'_, str> { 61,093 ( 0.00%) let len = self.read_usize(); 357,504 ( 0.01%) let sentinel = self.data[self.position + len]; 89,424 ( 0.00%) assert!(sentinel == STR_SENTINEL); . let s = unsafe { . std::str::from_utf8_unchecked(&self.data[self.position..self.position + len]) . }; 223,560 ( 0.01%) self.position += len + 1; 47,865 ( 0.00%) Cow::Borrowed(s) . } . . #[inline] . fn read_raw_bytes_into(&mut self, s: &mut [u8]) { 866 ( 0.00%) let start = self.position; 4,439 ( 0.00%) self.position += s.len(); 866 ( 0.00%) s.copy_from_slice(&self.data[start..self.position]); . } . } . . // Specializations for contiguous byte sequences follow. The default implementations for slices . // encode and decode each element individually. This isn't necessary for `u8` slices when using . // opaque encoders and decoders, because each `u8` is unchanged by encoding and decoding. . // Therefore, we can use more efficient implementations that process the entire sequence at once. . -- line 690 ---------------------------------------- 1,144,004 ( 0.04%) -------------------------------------------------------------------------------- -- 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)] 18,164,355 ( 0.62%) 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 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 { 310 ( 0.00%) let z = read(x); . 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) { -- line 464 ---------------------------------------- -- 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 { 1,127,431 ( 0.04%) copy_nonoverlapping(src, tmp.as_mut_ptr(), 1); 2,327,096 ( 0.08%) 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 { 18,132,534 ( 0.62%) 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. 7,877 ( 0.00%) return wrapping_sub( 28,118 ( 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 { 407,955 ( 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 ---------------------------------------- 2,117,897 ( 0.07%) -------------------------------------------------------------------------------- The following files chosen for auto-annotation could not be found: -------------------------------------------------------------------------------- ./elf/../sysdeps/x86_64/dl-machine.h ./elf/dl-lookup.c ./malloc/malloc.c ./stdlib/msort.c ./string/../sysdeps/x86_64/multiarch/memchr-avx2.S ./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 ./string/../sysdeps/x86_64/multiarch/strlen-avx2.S /tmp/gcc-build/x86_64-unknown-linux-gnu/libstdc++-v3/libsupc++/../../../../gcc-5.5.0/libstdc++-v3/libsupc++/new_op.cc -------------------------------------------------------------------------------- Ir -------------------------------------------------------------------------------- 263,456,462 ( 9.04%) events annotated