-------------------------------------------------------------------------------- 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 pest 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 -C metadata=1493c4d44a970696 -C extra-filename=-1493c4d44a970696 --out-dir /usr/home/liquid/tmp/.tmpNkDeKs/target/release/deps -L dependency=/usr/home/liquid/tmp/.tmpNkDeKs/target/release/deps --extern ucd_trie=/usr/home/liquid/tmp/.tmpNkDeKs/target/release/deps/libucd_trie-7ba8a9349ced0e02.rmeta -Adeprecated -Aunknown-lints -Zincremental-verify-ich Data file: results/cgout-w-profiling-pest-2.1.3-Opt-Full Events recorded: Ir Events shown: Ir Event sort order: Ir Thresholds: 0.1 Include dirs: User annotated: Auto-annotation: on -------------------------------------------------------------------------------- Ir -------------------------------------------------------------------------------- 7,037,743,517 (100.0%) PROGRAM TOTALS -------------------------------------------------------------------------------- Ir file:function -------------------------------------------------------------------------------- 184,284,678 ( 2.62%) ./malloc/malloc.c:_int_malloc 171,653,322 ( 2.44%) ./malloc/malloc.c:_int_free 111,924,911 ( 1.59%) ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:__memcpy_avx_unaligned_erms 109,793,679 ( 1.56%) ./malloc/malloc.c:malloc 93,946,349 ( 1.33%) ???:llvm::FPPassManager::runOnFunction(llvm::Function&) 51,512,086 ( 0.73%) ./malloc/malloc.c:free 47,052,132 ( 0.67%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/transform/check_consts/qualifs.rs:rustc_const_eval::transform::check_consts::qualifs::in_operand::::qualif_local::{closure#0}> 41,080,976 ( 0.58%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::from_key_hashed_nocheck:: 37,544,624 ( 0.53%) ???:llvm::AnalysisManager::getResultImpl(llvm::AnalysisKey*, llvm::Function&) 37,275,487 ( 0.53%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::get:: 34,779,911 ( 0.49%) ./malloc/malloc.c:malloc_consolidate 34,777,455 ( 0.49%) ???:llvm::AnalysisManager::invalidate(llvm::Function&, llvm::PreservedAnalyses const&) 31,993,068 ( 0.45%) ???:llvm::InstCombinerImpl::run() 30,678,921 ( 0.44%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/mod.rs:::next_token 29,054,888 ( 0.41%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/util.rs:::is_trivially_unpin 28,030,100 ( 0.40%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs:::short_write_process_buffer:: 27,653,640 ( 0.39%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/util.rs:::is_freeze 25,793,289 ( 0.37%) ???:llvm::BitstreamCursor::readRecord(unsigned int, llvm::SmallVectorImpl&, llvm::StringRef*) 23,613,382 ( 0.34%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lexer/src/lib.rs:::advance_token 23,345,922 ( 0.33%) ???: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*) 22,153,259 ( 0.31%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/middle/region.rs:::temporary_scope 22,127,385 ( 0.31%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/tokentrees.rs:::parse_token_tree 21,981,302 ( 0.31%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/caching_source_map_view.rs:::span_data_to_lines_and_cols 21,754,240 ( 0.31%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/hir/map/mod.rs:::attrs 21,475,216 ( 0.31%) ./malloc/malloc.c:unlink_chunk.constprop.0 19,186,180 ( 0.27%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/hir/map/mod.rs:::find_parent_node 18,933,426 ( 0.27%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast_pretty/src/pp/ring.rs:>::pop_first 18,851,467 ( 0.27%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast_pretty/src/pp.rs:::advance_left 18,802,800 ( 0.27%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs:::short_write_process_buffer:: 18,481,409 ( 0.26%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::check 18,262,137 ( 0.26%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/mod.rs:::check_static_ptr 17,840,995 ( 0.25%) ???:llvm::AttributeList::addAttributes(llvm::LLVMContext&, unsigned int, llvm::AttrBuilder const&) const 17,628,665 ( 0.25%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:>::hash_stable 17,533,194 ( 0.25%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/vec_deque/mod.rs:>::push_back 17,203,972 ( 0.24%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/middle/region.rs:>>::get:: 16,928,378 ( 0.24%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/context.rs:::maybe_lint_level_root_bounded 16,793,787 ( 0.24%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::bump 16,514,279 ( 0.23%) ???:llvm::DomTreeBuilder::SemiNCAInfo >::CalculateFromScratch(llvm::DominatorTreeBase&, llvm::DomTreeBuilder::SemiNCAInfo >::BatchUpdateInfo*) 16,088,104 ( 0.23%) ???:llvm::SelectionDAG::Combine(llvm::CombineLevel, llvm::AAResults*, llvm::CodeGenOpt::Level) 16,084,875 ( 0.23%) ???:runCVP(llvm::Module&) [clone .llvm.11785992503873176614] 16,084,279 ( 0.23%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_build/src/thir/cx/expr.rs:::mirror_expr_inner 15,851,982 ( 0.23%) ./string/../sysdeps/x86_64/multiarch/memcmp-avx2-movbe.S:__memcmp_avx2_movbe 15,718,830 ( 0.22%) ???:computeKnownBits(llvm::Value const*, llvm::KnownBits&, unsigned int, (anonymous namespace)::Query const&) [clone .llvm.15619146473165121143] 15,495,961 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::next 15,134,278 ( 0.22%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs:>>::from_key_hashed_nocheck:: 15,080,215 ( 0.21%) ???:(anonymous namespace)::LazyValueInfoImpl::solve() [clone .llvm.4316243980339171764] 14,938,353 ( 0.21%) ???:llvm::ValueHandleBase::AddToUseList() 14,660,632 ( 0.21%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:::node_type_opt 14,369,940 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/mod.rs:::enter::, rustc_trait_selection::traits::structural_match::search_for_structural_match_violation::{closure#0}> 14,097,093 ( 0.20%) ???:llvm::BasicAAResult::alias(llvm::MemoryLocation const&, llvm::MemoryLocation const&, llvm::AAQueryInfo&) 14,025,119 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::clone 13,868,809 ( 0.20%) ./string/../sysdeps/x86_64/multiarch/memset-vec-unaligned-erms.S:__memset_avx2_erms 13,752,480 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/mod.rs:::new 13,568,428 ( 0.19%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, (), core::hash::BuildHasherDefault>>::from_hash::>::{closure#0}> 13,534,311 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/option.rs:::advance_left 13,332,084 ( 0.19%) ???:(anonymous namespace)::ModuleBitcodeWriter::writeConstants(unsigned int, unsigned int, bool) 13,102,246 ( 0.19%) ???:llvm::PMDataManager::verifyPreservedAnalysis(llvm::Pass*) 12,435,525 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_trait_selection/src/traits/structural_match.rs:::enter::, rustc_trait_selection::traits::structural_match::search_for_structural_match_violation::{closure#0}> 12,303,255 ( 0.17%) ???:(anonymous namespace)::LazyValueInfoImpl::getEdgeValue(llvm::Value*, llvm::BasicBlock*, llvm::BasicBlock*, llvm::Instruction*) [clone .llvm.4316243980339171764] 12,276,972 ( 0.17%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::insert 12,237,366 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs:>::hash_stable 12,236,760 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cell.rs:::attrs 12,185,657 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/tokenstream.rs:::next_with_spacing 12,166,228 ( 0.17%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>::reserve_rehash::>::{closure#0}> 12,157,669 ( 0.17%) ???:computeKnownBits(llvm::Value const*, llvm::APInt const&, llvm::KnownBits&, unsigned int, (anonymous namespace)::Query const&) 12,142,478 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/expr.rs:::parse_assoc_expr_with 11,938,019 ( 0.17%) ???:computeKnownBitsFromOperator(llvm::Operator const*, llvm::APInt const&, llvm::KnownBits&, unsigned int, (anonymous namespace)::Query const&) 11,879,395 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_build/src/thir/cx/expr.rs:::make_mirror_unadjusted 11,844,258 ( 0.17%) ???:llvm::coro::declaresIntrinsics(llvm::Module const&, std::initializer_list) 11,835,728 ( 0.17%) ???: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 11,822,935 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/mod.rs:::ty 11,783,659 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/regionck.rs:::visit_expr 11,455,291 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_build/src/build/expr/as_operand.rs:::as_operand 11,420,348 ( 0.16%) ???:llvm::TargetLibraryInfoImpl::getLibFunc(llvm::Function const&, llvm::LibFunc&) const 11,085,841 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lint/src/levels.rs:::push 10,972,970 ( 0.16%) ???:SimplifyICmpInst(unsigned int, llvm::Value*, llvm::Value*, llvm::SimplifyQuery const&, unsigned int) [clone .llvm.1619516508949622737] 10,958,498 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/tokentrees.rs:::push 10,821,304 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/../../stdarch/crates/core_arch/src/x86/sse2.rs:>>::from_key_hashed_nocheck:: 10,745,114 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/writeback.rs:::visit_node_id 10,580,607 ( 0.15%) ./string/../sysdeps/x86_64/multiarch/strcmp-avx2.S:__strncmp_avx2 10,309,248 ( 0.15%) ./elf/dl-lookup.c:_dl_lookup_symbol_x 10,283,344 ( 0.15%) ???:llvm::PassRegistry::enumerateWith(llvm::PassRegistrationListener*) 10,112,628 ( 0.14%) ???:llvm::DataLayout::getTypeSizeInBits(llvm::Type*) const 10,032,603 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/library/std/src/collections/hash/map.rs:>>::get:: 9,994,049 ( 0.14%) ./string/../sysdeps/x86_64/multiarch/strlen-avx2.S:__strlen_avx2 9,982,531 ( 0.14%) ???:llvm::removeUnreachableBlocks(llvm::Function&, llvm::DomTreeUpdater*, llvm::MemorySSAUpdater*) 9,751,424 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:rustc_const_eval::transform::check_consts::qualifs::in_rvalue::::qualif_local::{closure#0}> 9,742,791 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/expr.rs:::check_expr_with_expectation_and_args 9,646,341 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/expr.rs:::collect_tokens_for_expr::<::parse_dot_or_call_expr::{closure#0}>::{closure#0} 9,581,667 ( 0.14%) ???:void llvm::BitstreamWriter::EmitRecordWithAbbrevImpl(unsigned int, llvm::ArrayRef, llvm::StringRef, llvm::Optional) 9,497,160 ( 0.13%) ???:llvm::detail::PassModel>, llvm::PreservedAnalyses, llvm::AnalysisManager>::run(llvm::Function&, llvm::AnalysisManager&) 9,465,465 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::eq 9,317,251 ( 0.13%) ???:llvm::DataLayout::getAlignment(llvm::Type*, bool) const 9,214,326 ( 0.13%) /tmp/gcc-build/x86_64-unknown-linux-gnu/libstdc++-v3/libsupc++/../../../../gcc-5.5.0/libstdc++-v3/libsupc++/new_op.cc:operator new(unsigned long) 9,178,415 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lint/src/types.rs:::check_expr 9,130,588 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/operand.rs:>::const_val_to_op 9,048,207 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/operand.rs:>::eval_operand 8,940,711 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_borrowck/src/type_check/mod.rs:::visit_constant 8,866,447 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/transform/check_consts/qualifs.rs:rustc_const_eval::transform::check_consts::qualifs::in_operand:: as rustc_middle::mir::visit::Visitor>::visit_assign::{closure#0}> 8,737,065 ( 0.12%) ./malloc/malloc.c:realloc 8,704,141 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast_pretty/src/pp.rs:::scan_string 8,686,687 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs:::slice_write_process_buffer 8,649,162 ( 0.12%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/bitmask.rs:>>::from_key_hashed_nocheck:: 8,604,973 ( 0.12%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/bitmask.rs:>>::get:: 8,533,449 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_hir_pretty/src/lib.rs:::print_expr 8,450,558 ( 0.12%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, (core::result::Result, rustc_middle::ty::layout::LayoutError>, rustc_query_system::dep_graph::graph::DepNodeIndex), core::hash::BuildHasherDefault>>::from_key_hashed_nocheck::> 8,432,566 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_metadata/src/rmeta/encoder.rs:>::encode 8,415,261 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/std/src/sys/unix/alloc.rs:__rdl_alloc 8,402,303 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_passes/src/region.rs:::visit_expr 8,372,023 ( 0.12%) ???:llvm::ScopedNoAliasAAResult::alias(llvm::MemoryLocation const&, llvm::MemoryLocation const&, llvm::AAQueryInfo&) 8,368,229 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast_pretty/src/pp.rs:::check_stack 8,332,754 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:>::truncate 8,315,510 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/transform/check_consts/qualifs.rs:rustc_const_eval::transform::check_consts::qualifs::in_operand::::qualif_local::{closure#0}> 8,304,214 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/mem_categorization.rs:::cat_expr_unadjusted 8,292,558 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/coercion.rs:>::coerce 8,291,848 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/mod.rs:::const_for_ty 8,232,731 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs:::slice_write_process_buffer 8,180,653 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/flags.rs:::add_const 8,068,869 ( 0.11%) ???:llvm::SimplifyInstruction(llvm::Instruction*, llvm::SimplifyQuery const&, llvm::OptimizationRemarkEmitter*) 7,960,650 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_trait_selection/src/traits/query/type_op/mod.rs:> as rustc_trait_selection::traits::query::type_op::TypeOp>::fully_perform 7,922,004 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/vec_deque/mod.rs:::advance_left 7,873,183 ( 0.11%) ???:llvm::InstCombinerImpl::visitICmpInst(llvm::ICmpInst&) 7,829,460 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_hir/src/intravisit.rs:rustc_hir::intravisit::walk_expr:: 7,771,778 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/place.rs:>::place_field 7,768,675 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::bump_with 7,753,401 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_trait_selection/src/traits/structural_match.rs:::visit_ty 7,745,722 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/place.rs:>::force_allocation_maybe_sized 7,738,955 ( 0.11%) ???:llvm::LiveVariables::runOnBlock(llvm::MachineBasicBlock*, unsigned int) 7,735,770 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:core::ptr::drop_in_place::> 7,707,480 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::ident 7,704,938 ( 0.11%) ???:llvm::InlineFunction(llvm::CallBase&, llvm::InlineFunctionInfo&, llvm::AAResults*, bool, llvm::Function*) 7,679,687 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_privacy/src/lib.rs:::check_expr_pat_type 7,544,625 ( 0.11%) ???:llvm::InstCombinerImpl::SimplifyDemandedUseBits(llvm::Value*, llvm::APInt, llvm::KnownBits&, unsigned int, llvm::Instruction*) 7,516,429 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/place.rs:>::copy_op_no_validate 7,441,232 ( 0.11%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:)>>::remove_entry::>::{closure#0}> 7,396,982 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/vec_deque/mod.rs:::check_stack 7,394,969 ( 0.11%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>::insert::>::{closure#0}> 7,335,847 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/transform/check_consts/qualifs.rs:rustc_const_eval::transform::check_consts::qualifs::in_rvalue::::qualif_local::{closure#0}> 7,311,608 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/expand.rs:::filter_map_expr 7,297,692 ( 0.10%) ???:llvm::SHA1::hashBlock() 7,178,934 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_passes/src/check_attr.rs:::check_attributes 7,166,145 ( 0.10%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs:>>::get:: 7,150,032 ( 0.10%) ???:computeKnownBitsFromAssume(llvm::Value const*, llvm::KnownBits&, unsigned int, (anonymous namespace)::Query const&) 7,137,696 ( 0.10%) ???:llvm::X86TargetLowering::X86TargetLowering(llvm::X86TargetMachine const&, llvm::X86Subtarget const&) 7,105,490 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lint/src/early.rs: as rustc_ast::visit::Visitor>::visit_expr 7,097,159 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/place.rs:>::write_immediate_to_mplace_no_validate 7,093,560 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/symbol.rs:::as_str -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_build/src/build/expr/as_operand.rs -------------------------------------------------------------------------------- Ir -- line 15 ---------------------------------------- . /// please do *not* return it from functions to avoid bad . /// miscompiles. . crate fn as_local_operand( . &mut self, . block: BasicBlock, . expr: &Expr<'tcx>, . ) -> BlockAnd> { . let local_scope = self.local_scope(); 8,418 ( 0.00%) self.as_operand(block, Some(local_scope), expr, None) . } . . /// Returns an operand suitable for use until the end of the current scope expression and . /// suitable also to be passed as function arguments. . /// . /// The operand returned from this function will *not be valid* after an ExprKind::Scope is . /// passed, so please do *not* return it from functions to avoid bad miscompiles. Returns an . /// operand suitable for use as a call argument. This is almost always equivalent to -- line 31 ---------------------------------------- -- line 72 ---------------------------------------- . /// . /// See #68034 for more details. . crate fn as_local_call_operand( . &mut self, . block: BasicBlock, . expr: &Expr<'tcx>, . ) -> BlockAnd> { . let local_scope = self.local_scope(); 7,620 ( 0.00%) self.as_call_operand(block, Some(local_scope), expr) . } . . /// Compile `expr` into a value that can be used as an operand. . /// If `expr` is a place like `x`, this will introduce a . /// temporary `tmp = x`, so that we capture the value of `x` at . /// this time. . /// . /// If we end up needing to create a temporary, then we will use -- line 88 ---------------------------------------- -- line 89 ---------------------------------------- . /// `local_info` as its `LocalInfo`, unless `as_temporary` . /// has already assigned it a non-`None` `LocalInfo`. . /// Normally, you should use `None` for `local_info` . /// . /// The operand is known to be live until the end of `scope`. . /// . /// Like `as_local_call_operand`, except that the argument will . /// not be valid once `scope` ends. 2,834,790 ( 0.04%) crate fn as_operand( . &mut self, . mut block: BasicBlock, . scope: Option, . expr: &Expr<'tcx>, . local_info: Option>>, . ) -> BlockAnd> { . debug!("as_operand(block={:?}, expr={:?} local_info={:?})", block, expr, local_info); . let this = self; . 1,832,222 ( 0.03%) if let ExprKind::Scope { region_scope, lint_level, value } = expr.kind { 280,510 ( 0.00%) let source_info = this.source_info(expr.span); . let region_scope = (region_scope, source_info); . return this.in_scope(region_scope, lint_level, |this| { 1,823,315 ( 0.03%) this.as_operand(block, scope, &this.thir[value], local_info) . }); . } . . let category = Category::of(&expr.kind).unwrap(); . debug!("as_operand: category={:?} for={:?}", category, expr.kind); . match category { . Category::Constant => { 418,857 ( 0.01%) let constant = this.as_constant(expr); . block.and(Operand::Constant(Box::new(constant))) . } . Category::Place | Category::Rvalue(..) => { . let operand = unpack!(block = this.as_temp(block, scope, expr, Mutability::Mut)); 7,210 ( 0.00%) if this.local_decls[operand].local_info.is_none() { 7,210 ( 0.00%) this.local_decls[operand].local_info = local_info; . } 3,605 ( 0.00%) block.and(Operand::Move(Place::from(operand))) . } . } 2,554,916 ( 0.04%) } . 39,052 ( 0.00%) crate fn as_call_operand( . &mut self, . mut block: BasicBlock, . scope: Option, . expr: &Expr<'tcx>, . ) -> BlockAnd> { . debug!("as_call_operand(block={:?}, expr={:?})", block, expr); . let this = self; . 19,372 ( 0.00%) if let ExprKind::Scope { region_scope, lint_level, value } = expr.kind { 2,960 ( 0.00%) let source_info = this.source_info(expr.span); . let region_scope = (region_scope, source_info); . return this.in_scope(region_scope, lint_level, |this| { 16,280 ( 0.00%) this.as_call_operand(block, scope, &this.thir[value]) . }); . } . 1,524 ( 0.00%) let tcx = this.tcx; . 6,096 ( 0.00%) if tcx.features().unsized_fn_params { . let ty = expr.ty; . let span = expr.span; . let param_env = this.param_env; . . if !ty.is_sized(tcx.at(span), param_env) { . // !sized means !copy, so this is an unsized move . assert!(!ty.is_copy_modulo_regions(tcx.at(span), param_env)); . -- line 159 ---------------------------------------- -- line 171 ---------------------------------------- . projection: tcx.intern_place_elems(&[PlaceElem::Deref]), . }; . . return block.and(Operand::Move(place)); . } . } . } . 13,716 ( 0.00%) this.as_operand(block, scope, expr, None) 24,032 ( 0.00%) } . } 1,703,104 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/../../stdarch/crates/core_arch/src/x86/sse2.rs -------------------------------------------------------------------------------- Ir -- line 94 ---------------------------------------- . /// Adds packed 32-bit integers in `a` and `b`. . /// . /// [Intel's documentation](https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_add_epi32) . #[inline] . #[target_feature(enable = "sse2")] . #[cfg_attr(test, assert_instr(paddd))] . #[stable(feature = "simd_x86", since = "1.27.0")] . pub unsafe fn _mm_add_epi32(a: __m128i, b: __m128i) -> __m128i { 17 ( 0.00%) transmute(simd_add(a.as_i32x4(), b.as_i32x4())) . } . . /// Adds packed 64-bit integers in `a` and `b`. . /// . /// [Intel's documentation](https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_add_epi64) . #[inline] . #[target_feature(enable = "sse2")] . #[cfg_attr(test, assert_instr(paddq))] -- line 110 ---------------------------------------- -- line 790 ---------------------------------------- . /// Compares packed 8-bit integers in `a` and `b` for equality. . /// . /// [Intel's documentation](https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_cmpeq_epi8) . #[inline] . #[target_feature(enable = "sse2")] . #[cfg_attr(test, assert_instr(pcmpeqb))] . #[stable(feature = "simd_x86", since = "1.27.0")] . pub unsafe fn _mm_cmpeq_epi8(a: __m128i, b: __m128i) -> __m128i { 357,253 ( 0.01%) transmute::(simd_eq(a.as_i8x16(), b.as_i8x16())) . } . . /// Compares packed 16-bit integers in `a` and `b` for equality. . /// . /// [Intel's documentation](https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_cmpeq_epi16) . #[inline] . #[target_feature(enable = "sse2")] . #[cfg_attr(test, assert_instr(pcmpeqw))] -- line 806 ---------------------------------------- -- line 856 ---------------------------------------- . /// Compares packed 8-bit integers in `a` and `b` for less-than. . /// . /// [Intel's documentation](https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_cmplt_epi8) . #[inline] . #[target_feature(enable = "sse2")] . #[cfg_attr(test, assert_instr(pcmpgtb))] . #[stable(feature = "simd_x86", since = "1.27.0")] . pub unsafe fn _mm_cmplt_epi8(a: __m128i, b: __m128i) -> __m128i { 88,244 ( 0.00%) transmute::(simd_lt(a.as_i8x16(), b.as_i8x16())) . } . . /// Compares packed 16-bit integers in `a` and `b` for less-than. . /// . /// [Intel's documentation](https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_cmplt_epi16) . #[inline] . #[target_feature(enable = "sse2")] . #[cfg_attr(test, assert_instr(pcmpgtw))] -- line 872 ---------------------------------------- -- line 1174 ---------------------------------------- . /// `mem_addr` must be aligned on a 16-byte boundary. . /// . /// [Intel's documentation](https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_load_si128) . #[inline] . #[target_feature(enable = "sse2")] . #[cfg_attr(test, assert_instr(movaps))] . #[stable(feature = "simd_x86", since = "1.27.0")] . pub unsafe fn _mm_load_si128(mem_addr: *const __m128i) -> __m128i { 508,775 ( 0.01%) *mem_addr . } . . /// Loads 128-bits of integer data from memory into a new vector. . /// . /// `mem_addr` does not need to be aligned on any particular boundary. . /// . /// [Intel's documentation](https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_loadu_si128) . #[inline] -- line 1190 ---------------------------------------- -- line 1237 ---------------------------------------- . /// `mem_addr` does not need to be aligned on any particular boundary. . /// . /// [Intel's documentation](https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_storeu_si128) . #[inline] . #[target_feature(enable = "sse2")] . #[cfg_attr(test, assert_instr(movups))] // FIXME movdqu expected . #[stable(feature = "simd_x86", since = "1.27.0")] . pub unsafe fn _mm_storeu_si128(mem_addr: *mut __m128i, a: __m128i) { 16 ( 0.00%) storeudq(mem_addr as *mut i8, a); . } . . /// Stores the lower 64-bit integer `a` to a memory location. . /// . /// `mem_addr` does not need to be aligned on any particular boundary. . /// . /// [Intel's documentation](https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_storel_epi64) . #[inline] -- line 1253 ---------------------------------------- -- line 1373 ---------------------------------------- . /// Returns a mask of the most significant bit of each element in `a`. . /// . /// [Intel's documentation](https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_movemask_epi8) . #[inline] . #[target_feature(enable = "sse2")] . #[cfg_attr(test, assert_instr(pmovmskb))] . #[stable(feature = "simd_x86", since = "1.27.0")] . pub unsafe fn _mm_movemask_epi8(a: __m128i) -> i32 { 56,461,917 ( 0.80%) pmovmskb(a.as_i8x16()) . } . . /// Shuffles 32-bit integers in `a` using the control in `IMM8`. . /// . /// [Intel's documentation](https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_shuffle_epi32) . #[inline] . #[target_feature(enable = "sse2")] . #[cfg_attr(test, assert_instr(pshufd, IMM8 = 9))] -- line 1389 ---------------------------------------- -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs -------------------------------------------------------------------------------- Ir -- line 186 ---------------------------------------- . /// // use the values stored in map . /// ``` . pub struct HashMap { . pub(crate) hash_builder: S, . pub(crate) table: RawTable<(K, V), A>, . } . . impl Clone for HashMap { 424 ( 0.00%) fn clone(&self) -> Self { 760 ( 0.00%) HashMap { . hash_builder: self.hash_builder.clone(), 129 ( 0.00%) table: self.table.clone(), . } 477 ( 0.00%) } . . fn clone_from(&mut self, source: &Self) { . self.table.clone_from(&source.table); . . // Update hash_builder only if we successfully cloned all elements. . self.hash_builder.clone_from(&source.hash_builder); . } . } -- line 207 ---------------------------------------- -- line 210 ---------------------------------------- . /// instances of any functions like RawTable::reserve from being generated . #[cfg_attr(feature = "inline-more", inline)] . pub(crate) fn make_hasher(hash_builder: &S) -> impl Fn(&(Q, V)) -> u64 + '_ . where . K: Borrow, . Q: Hash, . S: BuildHasher, . { 477,468 ( 0.01%) move |val| make_hash::(hash_builder, &val.0) . } . . /// Ensures that a single closure type across uses of this which, in turn prevents multiple . /// instances of any functions like RawTable::reserve from being generated . #[cfg_attr(feature = "inline-more", inline)] . fn equivalent_key(k: &Q) -> impl Fn(&(K, V)) -> bool + '_ . where . K: Borrow, . Q: ?Sized + Eq, . { 1,983,056 ( 0.03%) move |x| k.eq(x.0.borrow()) . } . . /// Ensures that a single closure type across uses of this which, in turn prevents multiple . /// instances of any functions like RawTable::reserve from being generated . #[cfg_attr(feature = "inline-more", inline)] . fn equivalent(k: &Q) -> impl Fn(&K) -> bool + '_ . where . K: Borrow, . Q: ?Sized + Eq, . { 940,585 ( 0.01%) move |x| k.eq(x.borrow()) . } . . #[cfg(not(feature = "nightly"))] . #[cfg_attr(feature = "inline-more", inline)] . pub(crate) fn make_hash(hash_builder: &S, val: &Q) -> u64 . where . K: Borrow, . Q: Hash + ?Sized, -- line 248 ---------------------------------------- -- line 251 ---------------------------------------- . use core::hash::Hasher; . let mut state = hash_builder.build_hasher(); . val.hash(&mut state); . state.finish() . } . . #[cfg(feature = "nightly")] . #[cfg_attr(feature = "inline-more", inline)] 4 ( 0.00%) pub(crate) fn make_hash(hash_builder: &S, val: &Q) -> u64 . where . K: Borrow, . Q: Hash + ?Sized, . S: BuildHasher, . { . hash_builder.hash_one(val) 8 ( 0.00%) } . . #[cfg(not(feature = "nightly"))] . #[cfg_attr(feature = "inline-more", inline)] . pub(crate) fn make_insert_hash(hash_builder: &S, val: &K) -> u64 . where . K: Hash, . S: BuildHasher, . { -- line 274 ---------------------------------------- -- line 367 ---------------------------------------- . /// let s = DefaultHashBuilder::default(); . /// let mut map = HashMap::with_hasher(s); . /// map.insert(1, 2); . /// ``` . /// . /// [`BuildHasher`]: ../../std/hash/trait.BuildHasher.html . #[cfg_attr(feature = "inline-more", inline)] . pub const fn with_hasher(hash_builder: S) -> Self { 1,825,959 ( 0.03%) Self { . hash_builder, . table: RawTable::new(), . } . } . . /// Creates an empty `HashMap` with the specified capacity, using `hash_builder` . /// to hash the keys. . /// -- line 383 ---------------------------------------- -- line 437 ---------------------------------------- . /// use hashbrown::hash_map::DefaultHashBuilder; . /// . /// let s = DefaultHashBuilder::default(); . /// let mut map = HashMap::with_hasher(s); . /// map.insert(1, 2); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn with_hasher_in(hash_builder: S, alloc: A) -> Self { 115 ( 0.00%) Self { . hash_builder, . table: RawTable::new_in(alloc), . } . } . . /// Creates an empty `HashMap` with the specified capacity, using `hash_builder` . /// to hash the keys. It will be allocated with the given allocator. . /// -- line 453 ---------------------------------------- -- line 527 ---------------------------------------- . /// map.insert("c", 3); . /// . /// for key in map.keys() { . /// println!("{}", key); . /// } . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn keys(&self) -> Keys<'_, K, V> { 6 ( 0.00%) Keys { inner: self.iter() } . } . . /// An iterator visiting all values in arbitrary order. . /// The iterator element type is `&'a V`. . /// . /// # Examples . /// . /// ``` -- line 543 ---------------------------------------- -- line 663 ---------------------------------------- . /// . /// let mut a = HashMap::new(); . /// assert_eq!(a.len(), 0); . /// a.insert(1, "a"); . /// assert_eq!(a.len(), 1); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn len(&self) -> usize { 10,242 ( 0.00%) self.table.len() . } . . /// Returns `true` if the map contains no elements. . /// . /// # Examples . /// . /// ``` . /// use hashbrown::HashMap; -- line 679 ---------------------------------------- -- line 680 ---------------------------------------- . /// . /// let mut a = HashMap::new(); . /// assert!(a.is_empty()); . /// a.insert(1, "a"); . /// assert!(!a.is_empty()); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn is_empty(&self) -> bool { 473,470 ( 0.01%) self.len() == 0 . } . . /// Clears the map, returning all key-value pairs as an iterator. Keeps the . /// allocated memory for reuse. . /// . /// # Examples . /// . /// ``` -- line 696 ---------------------------------------- -- line 790 ---------------------------------------- . /// use hashbrown::HashMap; . /// . /// let mut a = HashMap::new(); . /// a.insert(1, "a"); . /// a.clear(); . /// assert!(a.is_empty()); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 6 ( 0.00%) pub fn clear(&mut self) { . self.table.clear(); 6 ( 0.00%) } . . /// Creates a consuming iterator visiting all the keys in arbitrary order. . /// The map cannot be used after calling this. . /// The iterator element type is `K`. . /// . /// # Examples . /// . /// ``` -- line 808 ---------------------------------------- -- line 963 ---------------------------------------- . /// } . /// . /// 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)] 488 ( 0.00%) pub fn entry(&mut self, key: K) -> Entry<'_, K, V, S, A> { . let hash = make_insert_hash::(&self.hash_builder, &key); . if let Some(elem) = self.table.find(hash, equivalent_key(&key)) { 125 ( 0.00%) Entry::Occupied(OccupiedEntry { . hash, . key: Some(key), . elem, . table: self, . }) . } else { 485 ( 0.00%) Entry::Vacant(VacantEntry { . hash, . key, . table: self, . }) . } 610 ( 0.00%) } . . /// Gets the given key's corresponding entry by reference in the map for in-place manipulation. . /// . /// # Examples . /// . /// ``` . /// use hashbrown::HashMap; . /// -- line 995 ---------------------------------------- -- line 1047 ---------------------------------------- . /// ``` . #[inline] . pub fn get(&self, k: &Q) -> Option<&V> . where . K: Borrow, . Q: Hash + Eq, . { . // Avoid `Option::map` because it bloats LLVM IR. 5,533,998 ( 0.08%) match self.get_inner(k) { . Some(&(_, ref v)) => Some(v), . None => None, . } . } . . /// Returns the key-value pair corresponding to the supplied key. . /// . /// The supplied key may be any borrowed form of the map's key type, but -- line 1063 ---------------------------------------- -- line 1091 ---------------------------------------- . } . . #[inline] . fn get_inner(&self, k: &Q) -> Option<&(K, V)> . where . K: Borrow, . Q: Hash + Eq, . { 5,035,324 ( 0.07%) if self.table.is_empty() { . None . } else { 2 ( 0.00%) let hash = make_hash::(&self.hash_builder, k); . self.table.get(hash, equivalent_key(k)) . } . } . . /// Returns the key-value pair corresponding to the supplied key, with a mutable reference to value. . /// . /// The supplied key may be any borrowed form of the map's key type, but . /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for -- line 1110 ---------------------------------------- -- line 1155 ---------------------------------------- . /// use hashbrown::HashMap; . /// . /// let mut map = HashMap::new(); . /// map.insert(1, "a"); . /// assert_eq!(map.contains_key(&1), true); . /// assert_eq!(map.contains_key(&2), false); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 518,621 ( 0.01%) pub fn contains_key(&self, k: &Q) -> bool . where . K: Borrow, . Q: Hash + Eq, . { . self.get_inner(k).is_some() 882,744 ( 0.01%) } . . /// Returns a mutable reference to the value corresponding to the key. . /// . /// The key may be any borrowed form of the map's key type, but . /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for . /// the key type. . /// . /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html -- line 1177 ---------------------------------------- -- line 1185 ---------------------------------------- . /// let mut map = HashMap::new(); . /// map.insert(1, "a"); . /// if let Some(x) = map.get_mut(&1) { . /// *x = "b"; . /// } . /// assert_eq!(map[&1], "b"); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 283 ( 0.00%) pub fn get_mut(&mut self, k: &Q) -> Option<&mut V> . where . K: Borrow, . Q: Hash + Eq, . { . // Avoid `Option::map` because it bloats LLVM IR. 1,335 ( 0.00%) match self.get_inner_mut(k) { . Some(&mut (_, ref mut v)) => Some(v), . None => None, . } 566 ( 0.00%) } . . #[inline] . fn get_inner_mut(&mut self, k: &Q) -> Option<&mut (K, V)> . where . K: Borrow, . Q: Hash + Eq, . { 445 ( 0.00%) if self.table.is_empty() { . None . } else { . let hash = make_hash::(&self.hash_builder, k); 324 ( 0.00%) self.table.get_mut(hash, equivalent_key(k)) . } . } . . /// Attempts to get mutable references to `N` values in the map at once. . /// . /// Returns an array of length `N` with the results of each query. For soundness, at most one . /// mutable reference will be returned to any value. `None` will be returned if any of the . /// keys are duplicates or missing. -- line 1223 ---------------------------------------- -- line 1495 ---------------------------------------- . /// assert_eq!(map.insert(37, "a"), None); . /// assert_eq!(map.is_empty(), false); . /// . /// map.insert(37, "b"); . /// assert_eq!(map.insert(37, "c"), Some("b")); . /// assert_eq!(map[&37], "c"); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 7,528,946 ( 0.11%) pub fn insert(&mut self, k: K, v: V) -> Option { . let hash = make_insert_hash::(&self.hash_builder, &k); 2,256 ( 0.00%) if let Some((_, item)) = self.table.get_mut(hash, equivalent_key(&k)) { 2 ( 0.00%) Some(mem::replace(item, v)) . } else { 2,125,808 ( 0.03%) self.table 1,817,109 ( 0.03%) .insert(hash, (k, v), make_hasher::(&self.hash_builder)); 118,953 ( 0.00%) None . } 7,370,775 ( 0.10%) } . . /// Insert a key-value pair into the map without checking . /// if the key already exists in the map. . /// . /// Returns a reference to the key and value just inserted. . /// . /// This operation is safe if a key does not exist in the map. . /// -- line 1520 ---------------------------------------- -- line 1592 ---------------------------------------- . /// use hashbrown::HashMap; . /// . /// let mut map = HashMap::new(); . /// map.insert(1, "a"); . /// assert_eq!(map.remove(&1), Some("a")); . /// assert_eq!(map.remove(&1), None); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 610,734 ( 0.01%) pub fn remove(&mut self, k: &Q) -> Option . where . K: Borrow, . Q: Hash + Eq, . { . // Avoid `Option::map` because it bloats LLVM IR. 1,423,214 ( 0.02%) match self.remove_entry(k) { 32,710 ( 0.00%) Some((_, v)) => Some(v), 455,280 ( 0.01%) None => None, . } 1,505,833 ( 0.02%) } . . /// Removes a key from the map, returning the stored key and value if the . /// key was previously in the map. . /// . /// The key may be any borrowed form of the map's key type, but . /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for . /// the key type. . /// -- line 1618 ---------------------------------------- -- line 1631 ---------------------------------------- . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn remove_entry(&mut self, k: &Q) -> Option<(K, V)> . where . K: Borrow, . Q: Hash + Eq, . { . let hash = make_hash::(&self.hash_builder, k); 605,622 ( 0.01%) self.table.remove_entry(hash, equivalent_key(k)) . } . } . . impl HashMap { . /// Creates a raw entry builder for the HashMap. . /// . /// Raw entries provide the lowest level of control for searching and . /// manipulating a map. They must be manually initialized with a hash and -- line 1647 ---------------------------------------- -- line 2209 ---------------------------------------- . /// Creates a `RawEntryMut` from the given key and its hash. . #[inline] . #[allow(clippy::wrong_self_convention)] . pub fn from_key_hashed_nocheck(self, hash: u64, k: &Q) -> RawEntryMut<'a, K, V, S, A> . where . K: Borrow, . Q: Eq, . { 1,856,116 ( 0.03%) self.from_hash(hash, equivalent(k)) . } . } . . impl<'a, K, V, S, A: Allocator + Clone> RawEntryBuilderMut<'a, K, V, S, A> { . /// Creates a `RawEntryMut` from the given hash. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::wrong_self_convention)] 4,925,415 ( 0.07%) pub fn from_hash(self, hash: u64, is_match: F) -> RawEntryMut<'a, K, V, S, A> . where . for<'b> F: FnMut(&'b K) -> bool, . { . self.search(hash, is_match) 5,252,022 ( 0.07%) } . . #[cfg_attr(feature = "inline-more", inline)] . fn search(self, hash: u64, mut is_match: F) -> RawEntryMut<'a, K, V, S, A> . where . for<'b> F: FnMut(&'b K) -> bool, . { 586,326 ( 0.01%) match self.map.table.find(hash, |(k, _)| is_match(k)) { 3,049,758 ( 0.04%) Some(elem) => RawEntryMut::Occupied(RawOccupiedEntryMut { . elem, . table: &mut self.map.table, . hash_builder: &self.map.hash_builder, . }), 281,489 ( 0.00%) None => RawEntryMut::Vacant(RawVacantEntryMut { . table: &mut self.map.table, . hash_builder: &self.map.hash_builder, . }), . } . } . } . . impl<'a, K, V, S, A: Allocator + Clone> RawEntryBuilder<'a, K, V, S, A> { -- line 2251 ---------------------------------------- -- line 2260 ---------------------------------------- . { . let hash = make_hash::(&self.map.hash_builder, k); . self.from_key_hashed_nocheck(hash, k) . } . . /// Access an entry by a key and its hash. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::wrong_self_convention)] 4,833,390 ( 0.07%) pub fn from_key_hashed_nocheck(self, hash: u64, k: &Q) -> Option<(&'a K, &'a V)> . where . K: Borrow, . Q: Eq, . { 3,281,990 ( 0.05%) self.from_hash(hash, equivalent(k)) 7,558,514 ( 0.11%) } . . #[cfg_attr(feature = "inline-more", inline)] . fn search(self, hash: u64, mut is_match: F) -> Option<(&'a K, &'a V)> . where . F: FnMut(&K) -> bool, . { 8,136,296 ( 0.12%) match self.map.table.get(hash, |(k, _)| is_match(k)) { . Some(&(ref key, ref value)) => Some((key, value)), . None => None, . } . } . . /// Access an entry by hash. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::wrong_self_convention)] -- line 2289 ---------------------------------------- -- line 2624 ---------------------------------------- . /// and returns a mutable reference to it. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::shadow_unrelated)] . pub fn insert_hashed_nocheck(self, hash: u64, key: K, value: V) -> (&'a mut K, &'a mut V) . where . K: Hash, . S: BuildHasher, . { 458,761 ( 0.01%) let &mut (ref mut k, ref mut v) = self.table.insert_entry( . hash, . (key, value), . make_hasher::(self.hash_builder), . ); . (k, v) . } . . /// Set the value of an entry with a custom hasher function. -- line 2640 ---------------------------------------- -- line 2974 ---------------------------------------- . /// map.insert("a", 1); . /// map.insert("b", 2); . /// map.insert("c", 3); . /// . /// // Not possible with .iter() . /// let vec: Vec<(&str, i32)> = map.into_iter().collect(); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 1,228 ( 0.00%) fn into_iter(self) -> IntoIter { 28,473 ( 0.00%) IntoIter { 16,356 ( 0.00%) inner: self.table.into_iter(), . } 3,684 ( 0.00%) } . } . . impl<'a, K, V> Iterator for Iter<'a, K, V> { . type Item = (&'a K, &'a V); . . #[cfg_attr(feature = "inline-more", inline)] . fn next(&mut self) -> Option<(&'a K, &'a V)> { . // Avoid `Option::map` because it bloats LLVM IR. 522,239 ( 0.01%) match self.inner.next() { . Some(x) => unsafe { . let r = x.as_ref(); 920 ( 0.00%) Some((&r.0, &r.1)) . }, . None => None, . } . } . #[cfg_attr(feature = "inline-more", inline)] . fn size_hint(&self) -> (usize, Option) { 217 ( 0.00%) self.inner.size_hint() . } . } . impl ExactSizeIterator for Iter<'_, K, V> { . #[cfg_attr(feature = "inline-more", inline)] . fn len(&self) -> usize { . self.inner.len() . } . } -- line 3013 ---------------------------------------- -- line 3018 ---------------------------------------- . type Item = (&'a K, &'a mut V); . . #[cfg_attr(feature = "inline-more", inline)] . fn next(&mut self) -> Option<(&'a K, &'a mut V)> { . // Avoid `Option::map` because it bloats LLVM IR. . match self.inner.next() { . Some(x) => unsafe { . let r = x.as_mut(); 4 ( 0.00%) Some((&r.0, &mut r.1)) . }, . None => None, . } . } . #[cfg_attr(feature = "inline-more", inline)] . fn size_hint(&self) -> (usize, Option) { . self.inner.size_hint() . } -- line 3034 ---------------------------------------- -- line 3051 ---------------------------------------- . } . } . . impl Iterator for IntoIter { . type Item = (K, V); . . #[cfg_attr(feature = "inline-more", inline)] . fn next(&mut self) -> Option<(K, V)> { 3,804 ( 0.00%) self.inner.next() . } . #[cfg_attr(feature = "inline-more", inline)] . fn size_hint(&self) -> (usize, Option) { . self.inner.size_hint() . } . } . impl ExactSizeIterator for IntoIter { . #[cfg_attr(feature = "inline-more", inline)] -- line 3067 ---------------------------------------- -- line 3076 ---------------------------------------- . f.debug_list().entries(self.iter()).finish() . } . } . . impl<'a, K, V> Iterator for Keys<'a, K, V> { . type Item = &'a K; . . #[cfg_attr(feature = "inline-more", inline)] 74 ( 0.00%) fn next(&mut self) -> Option<&'a K> { . // Avoid `Option::map` because it bloats LLVM IR. . match self.inner.next() { . Some((k, _)) => Some(k), . None => None, . } 148 ( 0.00%) } . #[cfg_attr(feature = "inline-more", inline)] . fn size_hint(&self) -> (usize, Option) { . self.inner.size_hint() . } . } . impl ExactSizeIterator for Keys<'_, K, V> { . #[cfg_attr(feature = "inline-more", inline)] . fn len(&self) -> usize { -- line 3098 ---------------------------------------- -- line 3819 ---------------------------------------- . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn insert(self, value: V) -> &'a mut V . where . K: Hash, . S: BuildHasher, . { . let table = &mut self.table.table; 26 ( 0.00%) let entry = table.insert_entry( . self.hash, . (self.key, value), . make_hasher::(&self.table.hash_builder), . ); . &mut entry.1 . } . . #[cfg_attr(feature = "inline-more", inline)] -- line 3835 ---------------------------------------- -- line 4557 ---------------------------------------- . /// keys with new values returned from the iterator. . impl Extend<(K, V)> for HashMap . where . K: Eq + Hash, . S: BuildHasher, . A: Allocator + Clone, . { . #[cfg_attr(feature = "inline-more", inline)] 25,618 ( 0.00%) fn extend>(&mut self, iter: T) { . // Keys may be already present or show multiple times in the iterator. . // Reserve the entire hint lower bound if the map is empty. . // Otherwise reserve half the hint (rounded up), so the map . // will only resize twice in the worst case. 20,203 ( 0.00%) let iter = iter.into_iter(); 16,757 ( 0.00%) let reserve = if self.is_empty() { . iter.size_hint().0 . } else { 19 ( 0.00%) (iter.size_hint().0 + 1) / 2 . }; . self.reserve(reserve); . iter.for_each(move |(k, v)| { 73,992 ( 0.00%) self.insert(k, v); . }); 16,260 ( 0.00%) } . . #[inline] . #[cfg(feature = "nightly")] . fn extend_one(&mut self, (k, v): (K, V)) { . self.insert(k, v); . } . . #[inline] -- line 4588 ---------------------------------------- 4,248,261 ( 0.06%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lint/src/types.rs -------------------------------------------------------------------------------- Ir -- line 166 ---------------------------------------- . } . } . overwritten . } . . // For `isize` & `usize`, be conservative with the warnings, so that the . // warnings are consistent between 32- and 64-bit platforms. . fn int_ty_range(int_ty: ty::IntTy) -> (i128, i128) { 15 ( 0.00%) match int_ty { . ty::IntTy::Isize => (i64::MIN.into(), i64::MAX.into()), . ty::IntTy::I8 => (i8::MIN.into(), i8::MAX.into()), . ty::IntTy::I16 => (i16::MIN.into(), i16::MAX.into()), . ty::IntTy::I32 => (i32::MIN.into(), i32::MAX.into()), . ty::IntTy::I64 => (i64::MIN.into(), i64::MAX.into()), . ty::IntTy::I128 => (i128::MIN, i128::MAX), . } . } . . fn uint_ty_range(uint_ty: ty::UintTy) -> (u128, u128) { 828,534 ( 0.01%) let max = match uint_ty { . ty::UintTy::Usize => u64::MAX.into(), . ty::UintTy::U8 => u8::MAX.into(), . ty::UintTy::U16 => u16::MAX.into(), . ty::UintTy::U32 => u32::MAX.into(), . ty::UintTy::U64 => u64::MAX.into(), . ty::UintTy::U128 => u128::MAX, . }; . (0, max) -- line 193 ---------------------------------------- -- line 317 ---------------------------------------- . fn lint_int_literal<'tcx>( . cx: &LateContext<'tcx>, . type_limits: &TypeLimits, . e: &'tcx hir::Expr<'tcx>, . lit: &hir::Lit, . t: ty::IntTy, . v: u128, . ) { 15 ( 0.00%) let int_type = t.normalize(cx.sess().target.pointer_width); 6 ( 0.00%) let (min, max) = int_ty_range(int_type); 6 ( 0.00%) let max = max as u128; 9 ( 0.00%) let negative = type_limits.negated_expr_id == Some(e.hir_id); . . // Detect literal value out of range [min, max] inclusive . // avoiding use of -min to prevent overflow/panic 12 ( 0.00%) if (negative && v > max + 1) || (!negative && v > max) { . if let Some(repr_str) = get_bin_hex_repr(cx, lit) { . report_bin_hex_error( . cx, . e, . attr::IntType::SignedInt(ty::ast_int_ty(t)), . repr_str, . v, . negative, -- line 340 ---------------------------------------- -- line 377 ---------------------------------------- . } . . fn lint_uint_literal<'tcx>( . cx: &LateContext<'tcx>, . e: &'tcx hir::Expr<'tcx>, . lit: &hir::Lit, . t: ty::UintTy, . ) { 414,267 ( 0.01%) let uint_type = t.normalize(cx.sess().target.pointer_width); 552,356 ( 0.01%) let (min, max) = uint_ty_range(uint_type); 690,445 ( 0.01%) let lit_val: u128 = match lit.node { . // _v is u8, within range by definition . ast::LitKind::Byte(_v) => return, 552,356 ( 0.01%) ast::LitKind::Int(v, _) => v, . _ => bug!(), . }; 552,356 ( 0.01%) if lit_val < min || lit_val > max { . let parent_id = cx.tcx.hir().get_parent_node(e.hir_id); . if let Node::Expr(par_e) = cx.tcx.hir().get(parent_id) { . match par_e.kind { . hir::ExprKind::Cast(..) => { . if let ty::Char = cx.typeck_results().expr_ty(par_e).kind() { . cx.struct_span_lint(OVERFLOWING_LITERALS, par_e.span, |lint| { . lint.build("only `u8` can be cast into `char`") . .span_suggestion( -- line 401 ---------------------------------------- -- line 448 ---------------------------------------- . } . . fn lint_literal<'tcx>( . cx: &LateContext<'tcx>, . type_limits: &TypeLimits, . e: &'tcx hir::Expr<'tcx>, . lit: &hir::Lit, . ) { 1,385,390 ( 0.02%) match *cx.typeck_results().node_type(e.hir_id).kind() { . ty::Int(t) => { 15 ( 0.00%) match lit.node { 21 ( 0.00%) ast::LitKind::Int(v, ast::LitIntType::Signed(_) | ast::LitIntType::Unsuffixed) => { . lint_int_literal(cx, type_limits, e, lit, t, v) . } . _ => bug!(), . }; . } 276,178 ( 0.00%) ty::Uint(t) => lint_uint_literal(cx, e, lit, t), . ty::Float(t) => { . let is_infinite = match lit.node { . ast::LitKind::Float(v, _) => match t { . ty::FloatTy::F32 => v.as_str().parse().map(f32::is_infinite), . ty::FloatTy::F64 => v.as_str().parse().map(f64::is_infinite), . }, . _ => bug!(), . }; -- line 473 ---------------------------------------- -- line 487 ---------------------------------------- . }); . } . } . _ => {} . } . } . . impl<'tcx> LateLintPass<'tcx> for TypeLimits { 1,310,202 ( 0.02%) fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx hir::Expr<'tcx>) { 1,018,314 ( 0.01%) match e.kind { . hir::ExprKind::Unary(hir::UnOp::Neg, ref expr) => { . // propagate negation, if the negation itself isn't negated . if self.negated_expr_id != Some(e.hir_id) { . self.negated_expr_id = Some(expr.hir_id); . } . } 183 ( 0.00%) hir::ExprKind::Binary(binop, ref l, ref r) => { 417 ( 0.00%) if is_comparison(binop) && !check_limits(cx, binop, &l, &r) { . cx.struct_span_lint(UNUSED_COMPARISONS, e.span, |lint| { . lint.build("comparison is useless due to type limits").emit() . }); . } . } 276,928 ( 0.00%) hir::ExprKind::Lit(ref lit) => lint_literal(cx, self, e, lit), . _ => {} . }; . . fn is_valid(binop: hir::BinOp, v: T, min: T, max: T) -> bool { 27 ( 0.00%) match binop.node { . hir::BinOpKind::Lt => v > min && v <= max, . hir::BinOpKind::Le => v >= min && v < max, . hir::BinOpKind::Gt => v >= min && v < max, . hir::BinOpKind::Ge => v > min && v <= max, . hir::BinOpKind::Eq | hir::BinOpKind::Ne => v >= min && v <= max, . _ => bug!(), . } . } -- line 523 ---------------------------------------- -- line 536 ---------------------------------------- . } . . fn check_limits( . cx: &LateContext<'_>, . binop: hir::BinOp, . l: &hir::Expr<'_>, . r: &hir::Expr<'_>, . ) -> bool { 555 ( 0.00%) let (lit, expr, swap) = match (&l.kind, &r.kind) { . (&hir::ExprKind::Lit(_), _) => (l, r, true), . (_, &hir::ExprKind::Lit(_)) => (r, l, false), . _ => return true, . }; . // Normalize the binop so that the literal is always on the RHS in . // the comparison . let norm_binop = if swap { rev_binop(binop) } else { binop }; 74 ( 0.00%) match *cx.typeck_results().node_type(expr.hir_id).kind() { 10 ( 0.00%) ty::Int(int_ty) => { . let (min, max) = int_ty_range(int_ty); . let lit_val: i128 = match lit.kind { 10 ( 0.00%) hir::ExprKind::Lit(ref li) => match li.node { . ast::LitKind::Int( . v, . ast::LitIntType::Signed(_) | ast::LitIntType::Unsuffixed, . ) => v as i128, . _ => return true, . }, . _ => bug!(), . }; . is_valid(norm_binop, lit_val, min, max) . } 42 ( 0.00%) ty::Uint(uint_ty) => { . let (min, max): (u128, u128) = uint_ty_range(uint_ty); . let lit_val: u128 = match lit.kind { 14 ( 0.00%) hir::ExprKind::Lit(ref li) => match li.node { . ast::LitKind::Int(v, _) => v, . _ => return true, . }, . _ => bug!(), . }; . is_valid(norm_binop, lit_val, min, max) . } . _ => true, . } . } . . fn is_comparison(binop: hir::BinOp) -> bool { 366 ( 0.00%) matches!( 183 ( 0.00%) binop.node, . hir::BinOpKind::Eq . | hir::BinOpKind::Lt . | hir::BinOpKind::Le . | hir::BinOpKind::Ne . | hir::BinOpKind::Ge . | hir::BinOpKind::Gt . ) . } 1,164,624 ( 0.02%) } . } . . declare_lint! { . /// The `improper_ctypes` lint detects incorrect use of types in foreign . /// modules. . /// . /// ### Example . /// -- line 601 ---------------------------------------- -- line 1268 ---------------------------------------- . . fn check_foreign_static(&mut self, id: hir::HirId, span: Span) { . let def_id = self.cx.tcx.hir().local_def_id(id); . let ty = self.cx.tcx.type_of(def_id); . self.check_type_for_ffi_and_report_errors(span, ty, true, false); . } . . fn is_internal_abi(&self, abi: SpecAbi) -> bool { 582 ( 0.00%) matches!( . abi, . SpecAbi::Rust | SpecAbi::RustCall | SpecAbi::RustIntrinsic | SpecAbi::PlatformIntrinsic . ) . } . } . . impl<'tcx> LateLintPass<'tcx> for ImproperCTypesDeclarations { . fn check_foreign_item(&mut self, cx: &LateContext<'_>, it: &hir::ForeignItem<'_>) { -- line 1284 ---------------------------------------- -- line 1306 ---------------------------------------- . kind: hir::intravisit::FnKind<'tcx>, . decl: &'tcx hir::FnDecl<'_>, . _: &'tcx hir::Body<'_>, . _: Span, . hir_id: hir::HirId, . ) { . use hir::intravisit::FnKind; . 1,255 ( 0.00%) let abi = match kind { . FnKind::ItemFn(_, _, header, ..) => header.abi, 191 ( 0.00%) FnKind::Method(_, sig, ..) => sig.header.abi, . _ => return, . }; . 582 ( 0.00%) let mut vis = ImproperCTypesVisitor { cx, mode: CItemKind::Definition }; . if !vis.is_internal_abi(abi) { . vis.check_foreign_fn(hir_id, decl); . } . } . } . . declare_lint_pass!(VariantSizeDifferences => [VARIANT_SIZE_DIFFERENCES]); . . impl<'tcx> LateLintPass<'tcx> for VariantSizeDifferences { 3,444 ( 0.00%) fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) { 984 ( 0.00%) if let hir::ItemKind::Enum(ref enum_definition, _) = it.kind { 20 ( 0.00%) let t = cx.tcx.type_of(it.def_id); 10 ( 0.00%) let ty = cx.tcx.erase_regions(t); 61 ( 0.00%) let layout = match cx.layout_of(ty) { 7 ( 0.00%) Ok(layout) => layout, . Err( . ty::layout::LayoutError::Unknown(_) . | ty::layout::LayoutError::SizeOverflow(_) . | ty::layout::LayoutError::NormalizationFailure(_, _), . ) => return, . }; 28 ( 0.00%) let Variants::Multiple { . tag_encoding: TagEncoding::Direct, tag, ref variants, .. . } = &layout.variants else { . return . }; . 7 ( 0.00%) let tag_size = tag.value.size(&cx.tcx).bytes(); . . debug!( . "enum `{}` is {} bytes large with layout:\n{:#?}", . t, . layout.size.bytes(), . layout . ); . 21 ( 0.00%) let (largest, slargest, largest_index) = iter::zip(enum_definition.variants, variants) . .map(|(variant, variant_layout)| { . // Subtract the size of the enum tag. . let bytes = variant_layout.size.bytes().saturating_sub(tag_size); . . debug!("- variant `{}` is {} bytes large", variant.ident, bytes); . bytes . }) . .enumerate() . .fold((0, 0, 0), |(l, s, li), (idx, size)| { 119 ( 0.00%) if size > l { . (size, l, idx) . } else if size > s { . (l, size, li) . } else { . (l, s, li) . } . }); . . // We only warn if the largest variant is at least thrice as large as . // the second-largest. 49 ( 0.00%) if largest > slargest * 3 && slargest > 0 { . cx.struct_span_lint( . VARIANT_SIZE_DIFFERENCES, . enum_definition.variants[largest_index].span, . |lint| { . lint.build(&format!( . "enum variant is more than three times \ . larger ({} bytes) than the next largest", . largest . )) . .emit() . }, . ); . } . } 3,936 ( 0.00%) } . } . . declare_lint! { . /// The `invalid_atomic_ordering` lint detects passing an `Ordering` . /// to an atomic operation that does not support that ordering. . /// . /// ### Example . /// -- line 1401 ---------------------------------------- -- line 1437 ---------------------------------------- . INVALID_ATOMIC_ORDERING, . Deny, . "usage of invalid atomic ordering in atomic operations and memory fences" . } . . declare_lint_pass!(InvalidAtomicOrdering => [INVALID_ATOMIC_ORDERING]); . . impl InvalidAtomicOrdering { 2,329,248 ( 0.03%) fn inherent_atomic_method_call<'hir>( . cx: &LateContext<'_>, . expr: &Expr<'hir>, . recognized_names: &[Symbol], // used for fast path calculation . ) -> Option<(Symbol, &'hir [Expr<'hir>])> { . const ATOMIC_TYPES: &[Symbol] = &[ . sym::AtomicBool, . sym::AtomicPtr, . sym::AtomicUsize, -- line 1453 ---------------------------------------- -- line 1459 ---------------------------------------- . sym::AtomicIsize, . sym::AtomicI8, . sym::AtomicI16, . sym::AtomicI32, . sym::AtomicI64, . sym::AtomicI128, . ]; . if_chain! { 582,312 ( 0.01%) if let ExprKind::MethodCall(ref method_path, args, _) = &expr.kind; 1,768 ( 0.00%) if recognized_names.contains(&method_path.ident.name); . if let Some(m_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id); . if let Some(impl_did) = cx.tcx.impl_of_method(m_def_id); . if let Some(adt) = cx.tcx.type_of(impl_did).ty_adt_def(); . // skip extension traits, only lint functions from the standard library . if cx.tcx.trait_id_of_impl(impl_did).is_none(); . . if let Some(parent) = cx.tcx.parent(adt.did); . if cx.tcx.is_diagnostic_item(sym::atomic_mod, parent); . if ATOMIC_TYPES.contains(&cx.tcx.item_name(adt.did)); . then { . return Some((method_path.ident.name, args)); . } . } 291,156 ( 0.00%) None 2,329,248 ( 0.03%) } . . fn matches_ordering(cx: &LateContext<'_>, did: DefId, orderings: &[Symbol]) -> bool { . let tcx = cx.tcx; . let atomic_ordering = tcx.get_diagnostic_item(sym::Ordering); . orderings.iter().any(|ordering| { . tcx.item_name(did) == *ordering && { . let parent = tcx.parent(did); . parent == atomic_ordering -- line 1491 ---------------------------------------- -- line 1502 ---------------------------------------- . None . } . } . . fn check_atomic_load_store(cx: &LateContext<'_>, expr: &Expr<'_>) { . use rustc_hir::def::{DefKind, Res}; . use rustc_hir::QPath; . if_chain! { 1,019,046 ( 0.01%) if let Some((method, args)) = Self::inherent_atomic_method_call(cx, expr, &[sym::load, sym::store]); . if let Some((ordering_arg, invalid_ordering)) = match method { . sym::load => Some((&args[1], sym::Release)), . sym::store => Some((&args[2], sym::Acquire)), . _ => None, . }; . . if let ExprKind::Path(QPath::Resolved(_, path)) = ordering_arg.kind; . if let Res::Def(DefKind::Ctor(..), ctor_id) = path.res; -- line 1518 ---------------------------------------- -- line 1531 ---------------------------------------- . } . }); . } . } . } . . fn check_memory_fence(cx: &LateContext<'_>, expr: &Expr<'_>) { . if_chain! { 291,156 ( 0.00%) if let ExprKind::Call(ref func, ref args) = expr.kind; 1,888 ( 0.00%) if let ExprKind::Path(ref func_qpath) = func.kind; 4,210 ( 0.00%) if let Some(def_id) = cx.qpath_res(func_qpath, func.hir_id).opt_def_id(); 2,718 ( 0.00%) if matches!(cx.tcx.get_diagnostic_name(def_id), Some(sym::fence | sym::compiler_fence)); . if let ExprKind::Path(ref ordering_qpath) = &args[0].kind; . if let Some(ordering_def_id) = cx.qpath_res(ordering_qpath, args[0].hir_id).opt_def_id(); . if Self::matches_ordering(cx, ordering_def_id, &[sym::Relaxed]); . then { . cx.struct_span_lint(INVALID_ATOMIC_ORDERING, args[0].span, |diag| { . diag.build("memory fences cannot have `Relaxed` ordering") . .help("consider using ordering modes `Acquire`, `Release`, `AcqRel` or `SeqCst`") . .emit(); . }); . } . } . } . . fn check_atomic_compare_exchange(cx: &LateContext<'_>, expr: &Expr<'_>) { . if_chain! { 1,310,202 ( 0.02%) if let Some((method, args)) = Self::inherent_atomic_method_call(cx, expr, &[sym::fetch_update, sym::compare_exchange, sym::compare_exchange_weak]); . if let Some((success_order_arg, failure_order_arg)) = match method { . sym::fetch_update => Some((&args[1], &args[2])), . sym::compare_exchange | sym::compare_exchange_weak => Some((&args[3], &args[4])), . _ => None, . }; . . if let Some(fail_ordering_def_id) = Self::opt_ordering_defid(cx, failure_order_arg); . then { -- line 1566 ---------------------------------------- -- line 1613 ---------------------------------------- . } . } . } . } . } . } . . impl<'tcx> LateLintPass<'tcx> for InvalidAtomicOrdering { 1,310,202 ( 0.02%) fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { . Self::check_atomic_load_store(cx, expr); . Self::check_memory_fence(cx, expr); . Self::check_atomic_compare_exchange(cx, expr); 1,164,624 ( 0.02%) } . } 157,912 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_privacy/src/lib.rs -------------------------------------------------------------------------------- Ir -- line 59 ---------------------------------------- . &mut self, . def_id: DefId, . kind: &str, . descr: &dyn fmt::Display, . ) -> ControlFlow; . . /// Not overridden, but used to actually visit types and traits. . fn skeleton(&mut self) -> DefIdVisitorSkeleton<'_, 'tcx, Self> { 1,525,091 ( 0.02%) DefIdVisitorSkeleton { . def_id_visitor: self, . visited_opaque_tys: Default::default(), . dummy: Default::default(), . } . } 1,089 ( 0.00%) fn visit(&mut self, ty_fragment: impl TypeFoldable<'tcx>) -> ControlFlow { . ty_fragment.visit_with(&mut self.skeleton()) 1,815 ( 0.00%) } 654 ( 0.00%) fn visit_trait(&mut self, trait_ref: TraitRef<'tcx>) -> ControlFlow { . self.skeleton().visit_trait(trait_ref) 654 ( 0.00%) } . fn visit_projection_ty( . &mut self, . projection: ty::ProjectionTy<'tcx>, . ) -> ControlFlow { 84 ( 0.00%) self.skeleton().visit_projection_ty(projection) . } . fn visit_predicates( . &mut self, . predicates: ty::GenericPredicates<'tcx>, . ) -> ControlFlow { 1,184 ( 0.00%) self.skeleton().visit_predicates(predicates) . } . } . . struct DefIdVisitorSkeleton<'v, 'tcx, V: ?Sized> { . def_id_visitor: &'v mut V, . visited_opaque_tys: FxHashSet, . dummy: PhantomData>, . } . . impl<'tcx, V> DefIdVisitorSkeleton<'_, 'tcx, V> . where . V: DefIdVisitor<'tcx> + ?Sized, . { . fn visit_trait(&mut self, trait_ref: TraitRef<'tcx>) -> ControlFlow { 109 ( 0.00%) let TraitRef { def_id, substs } = trait_ref; 13,835 ( 0.00%) self.def_id_visitor.visit_def_id(def_id, "trait", &trait_ref.print_only_trait_path())?; 109 ( 0.00%) if self.def_id_visitor.shallow() { ControlFlow::CONTINUE } else { substs.visit_with(self) } . } . 1,980 ( 0.00%) fn visit_projection_ty( . &mut self, . projection: ty::ProjectionTy<'tcx>, . ) -> ControlFlow { 1,584 ( 0.00%) let (trait_ref, assoc_substs) = 396 ( 0.00%) projection.trait_ref_and_own_substs(self.def_id_visitor.tcx()); . self.visit_trait(trait_ref)?; . if self.def_id_visitor.shallow() { . ControlFlow::CONTINUE . } else { . assoc_substs.iter().try_for_each(|subst| subst.visit_with(self)) . } 1,782 ( 0.00%) } . . fn visit_predicate(&mut self, predicate: ty::Predicate<'tcx>) -> ControlFlow { 549 ( 0.00%) match predicate.kind().skip_binder() { . ty::PredicateKind::Trait(ty::TraitPredicate { . trait_ref, . constness: _, . polarity: _, . }) => self.visit_trait(trait_ref), . ty::PredicateKind::Projection(ty::ProjectionPredicate { projection_ty, term }) => { 96 ( 0.00%) term.visit_with(self)?; 240 ( 0.00%) self.visit_projection_ty(projection_ty) . } . ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty, _region)) => { . ty.visit_with(self) . } . ty::PredicateKind::RegionOutlives(..) => ControlFlow::CONTINUE, . ty::PredicateKind::ConstEvaluatable(uv) . if self.def_id_visitor.tcx().features().generic_const_exprs => . { -- line 140 ---------------------------------------- -- line 157 ---------------------------------------- . ACNode::Leaf(leaf) => self.visit_const(leaf), . ACNode::Cast(_, _, ty) => self.visit_ty(ty), . ACNode::Binop(..) | ACNode::UnaryOp(..) | ACNode::FunctionCall(_, _) => { . ControlFlow::CONTINUE . } . }) . } . 8,288 ( 0.00%) fn visit_predicates( . &mut self, . predicates: ty::GenericPredicates<'tcx>, . ) -> ControlFlow { . let ty::GenericPredicates { parent: _, predicates } = predicates; . predicates.iter().try_for_each(|&(predicate, _span)| self.visit_predicate(predicate)) 9,472 ( 0.00%) } . } . . impl<'tcx, V> TypeVisitor<'tcx> for DefIdVisitorSkeleton<'_, 'tcx, V> . where . V: DefIdVisitor<'tcx> + ?Sized, . { . type BreakTy = V::BreakTy; . 1,745,495 ( 0.02%) fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow { 193,949 ( 0.00%) let tcx = self.def_id_visitor.tcx(); . // InternalSubsts are not visited here because they are visited below in `super_visit_with`. 967,301 ( 0.01%) match *ty.kind() { 54,904 ( 0.00%) ty::Adt(&ty::AdtDef { did: def_id, .. }, ..) . | ty::Foreign(def_id) . | ty::FnDef(def_id, ..) . | ty::Closure(def_id, ..) . | ty::Generator(def_id, ..) => { 246,676 ( 0.00%) self.def_id_visitor.visit_def_id(def_id, "type", &ty)?; . if self.def_id_visitor.shallow() { . return ControlFlow::CONTINUE; . } . // Default type visitor doesn't visit signatures of fn types. . // Something like `fn() -> Priv {my_func}` is considered a private type even if . // `my_func` is public, so we need to visit signatures. 56,265 ( 0.00%) if let ty::FnDef(..) = ty.kind() { . tcx.fn_sig(def_id).visit_with(self)?; . } . // Inherent static methods don't have self type in substs. . // Something like `fn() {my_method}` type of the method . // `impl Pub { pub fn my_method() {} }` is considered a private type, . // so we need to visit the self type additionally. 86,946 ( 0.00%) if let Some(assoc_item) = tcx.opt_associated_item(def_id) { 4,564 ( 0.00%) if let ty::ImplContainer(impl_def_id) = assoc_item.container { 1,110 ( 0.00%) tcx.type_of(impl_def_id).visit_with(self)?; . } . } . } 258 ( 0.00%) ty::Projection(proj) => { . if self.def_id_visitor.skip_assoc_tys() { . // Visitors searching for minimal visibility/reachability want to . // conservatively approximate associated types like `::Alias` . // as visible/reachable even if both `Type` and `Trait` are private. . // Ideally, associated types should be substituted in the same way as . // free type aliases, but this isn't done yet. . return ControlFlow::CONTINUE; . } . // This will also visit substs if necessary, so we don't need to recurse. 1,278 ( 0.00%) return self.visit_projection_ty(proj); . } 113 ( 0.00%) ty::Dynamic(predicates, ..) => { . // All traits in the list are considered the "primary" part of the type . // and are visited by shallow visitors. 925 ( 0.00%) for predicate in predicates { 806 ( 0.00%) let trait_ref = match predicate.skip_binder() { 666 ( 0.00%) ty::ExistentialPredicate::Trait(trait_ref) => trait_ref, 230 ( 0.00%) ty::ExistentialPredicate::Projection(proj) => proj.trait_ref(tcx), . ty::ExistentialPredicate::AutoTrait(def_id) => { . ty::ExistentialTraitRef { def_id, substs: InternalSubsts::empty() } . } . }; 222 ( 0.00%) let ty::ExistentialTraitRef { def_id, substs: _ } = trait_ref; 1,506 ( 0.00%) self.def_id_visitor.visit_def_id(def_id, "trait", &trait_ref)?; . } . } . ty::Opaque(def_id, ..) => { . // Skip repeated `Opaque`s to avoid infinite recursion. . if self.visited_opaque_tys.insert(def_id) { . // The intent is to treat `impl Trait1 + Trait2` identically to . // `dyn Trait1 + Trait2`. Therefore we ignore def-id of the opaque type itself . // (it either has no visibility, or its visibility is insignificant, like -- line 241 ---------------------------------------- -- line 270 ---------------------------------------- . ty::Bound(..) | ty::Placeholder(..) | ty::Infer(..) => { . bug!("unexpected type: {:?}", ty) . } . } . . if self.def_id_visitor.shallow() { . ControlFlow::CONTINUE . } else { 570,503 ( 0.01%) ty.super_visit_with(self) . } 1,730,241 ( 0.02%) } . . fn visit_const(&mut self, c: &'tcx Const<'tcx>) -> ControlFlow { 14,052 ( 0.00%) self.visit_ty(c.ty)?; 2,342 ( 0.00%) let tcx = self.def_id_visitor.tcx(); 16,394 ( 0.00%) if let Ok(Some(ct)) = AbstractConst::from_const(tcx, c) { . self.visit_abstract_const_expr(tcx, ct)?; . } . ControlFlow::CONTINUE . } . } . . fn min(vis1: ty::Visibility, vis2: ty::Visibility, tcx: TyCtxt<'_>) -> ty::Visibility { 494 ( 0.00%) if vis1.is_at_least(vis2, tcx) { vis2 } else { vis1 } . } . . //////////////////////////////////////////////////////////////////////////////// . /// Visitor used to determine if pub(restricted) is used anywhere in the crate. . /// . /// This is done so that `private_in_public` warnings can be turned into hard errors . /// in crates that have been updated to use pub(restricted). . //////////////////////////////////////////////////////////////////////////////// -- line 301 ---------------------------------------- -- line 303 ---------------------------------------- . tcx: TyCtxt<'tcx>, . has_pub_restricted: bool, . } . . impl<'tcx> Visitor<'tcx> for PubRestrictedVisitor<'tcx> { . type NestedFilter = nested_filter::All; . . fn nested_visit_map(&mut self) -> Self::Map { 1,091 ( 0.00%) self.tcx.hir() . } . fn visit_vis(&mut self, vis: &'tcx hir::Visibility<'tcx>) { 2,487 ( 0.00%) self.has_pub_restricted = self.has_pub_restricted || vis.node.is_pub_restricted(); . } . } . . //////////////////////////////////////////////////////////////////////////////// . /// Visitor used to determine impl visibility and reachability. . //////////////////////////////////////////////////////////////////////////////// . . struct FindMin<'a, 'tcx, VL: VisibilityLike> { -- line 322 ---------------------------------------- -- line 336 ---------------------------------------- . true . } . fn visit_def_id( . &mut self, . def_id: DefId, . _kind: &str, . _descr: &dyn fmt::Display, . ) -> ControlFlow { 3,623 ( 0.00%) self.min = VL::new_min(self, def_id); . ControlFlow::CONTINUE . } . } . . trait VisibilityLike: Sized { . const MAX: Self; . const SHALLOW: bool = false; . fn new_min(find: &FindMin<'_, '_, Self>, def_id: DefId) -> Self; . . // Returns an over-approximation (`skip_assoc_tys` = true) of visibility due to . // associated types for which we can't determine visibility precisely. 2,541 ( 0.00%) fn of_impl(def_id: LocalDefId, tcx: TyCtxt<'_>, access_levels: &AccessLevels) -> Self { 1,210 ( 0.00%) let mut find = FindMin { tcx, access_levels, min: Self::MAX }; 363 ( 0.00%) find.visit(tcx.type_of(def_id)); 1,089 ( 0.00%) if let Some(trait_ref) = tcx.impl_trait_ref(def_id) { 109 ( 0.00%) find.visit_trait(trait_ref); . } 290 ( 0.00%) find.min 2,904 ( 0.00%) } . } . impl VisibilityLike for ty::Visibility { . const MAX: Self = ty::Visibility::Public; 2,471 ( 0.00%) fn new_min(find: &FindMin<'_, '_, Self>, def_id: DefId) -> Self { 1,059 ( 0.00%) min(find.tcx.visibility(def_id), find.min, find.tcx) 3,530 ( 0.00%) } . } . impl VisibilityLike for Option { . const MAX: Self = Some(AccessLevel::Public); . // Type inference is very smart sometimes. . // It can make an impl reachable even some components of its type or trait are unreachable. . // E.g. methods of `impl ReachableTrait for ReachableTy { ... }` . // can be usable from other crates (#57264). So we skip substs when calculating reachability . // and consider an impl reachable if its "shallow" type and trait are reachable. . // . // The assumption we make here is that type-inference won't let you use an impl without knowing . // both "shallow" version of its self type and "shallow" version of its trait if it exists . // (which require reaching the `DefId`s in them). . const SHALLOW: bool = true; 1,374 ( 0.00%) fn new_min(find: &FindMin<'_, '_, Self>, def_id: DefId) -> Self { . cmp::min( 1,374 ( 0.00%) if let Some(def_id) = def_id.as_local() { 484 ( 0.00%) find.access_levels.map.get(&def_id).copied() . } else { . Self::MAX . }, 1,112 ( 0.00%) find.min, . ) 1,832 ( 0.00%) } . } . . //////////////////////////////////////////////////////////////////////////////// . /// The embargo visitor, used to determine the exports of the AST. . //////////////////////////////////////////////////////////////////////////////// . . struct EmbargoVisitor<'tcx> { . tcx: TyCtxt<'tcx>, -- line 400 ---------------------------------------- -- line 422 ---------------------------------------- . . struct ReachEverythingInTheInterfaceVisitor<'a, 'tcx> { . access_level: Option, . item_def_id: LocalDefId, . ev: &'a mut EmbargoVisitor<'tcx>, . } . . impl<'tcx> EmbargoVisitor<'tcx> { 7,656 ( 0.00%) fn get(&self, def_id: LocalDefId) -> Option { . self.access_levels.map.get(&def_id).copied() 7,656 ( 0.00%) } . . fn update_with_hir_id( . &mut self, . hir_id: hir::HirId, . level: Option, . ) -> Option { 594 ( 0.00%) let def_id = self.tcx.hir().local_def_id(hir_id); . self.update(def_id, level) . } . . /// Updates node level and returns the updated level. . fn update(&mut self, def_id: LocalDefId, level: Option) -> Option { 7,720 ( 0.00%) let old_level = self.get(def_id); . // Accessibility levels can only grow. . if level > old_level { . self.access_levels.map.insert(def_id, level.unwrap()); 263 ( 0.00%) self.changed = true; . level . } else { . old_level . } . } . . fn reach( . &mut self, -- line 457 ---------------------------------------- -- line 458 ---------------------------------------- . def_id: LocalDefId, . access_level: Option, . ) -> ReachEverythingInTheInterfaceVisitor<'_, 'tcx> { . ReachEverythingInTheInterfaceVisitor { . access_level: cmp::min(access_level, Some(AccessLevel::Reachable)), . item_def_id: def_id, . ev: self, . } 2,674 ( 0.00%) } . . // We have to make sure that the items that macros might reference . // are reachable, since they might be exported transitively. . fn update_reachability_from_macro(&mut self, local_def_id: LocalDefId, md: &MacroDef) { . // Non-opaque macros cannot make other items more accessible than they already are. . 8 ( 0.00%) let hir_id = self.tcx.hir().local_def_id_to_hir_id(local_def_id); 24 ( 0.00%) let attrs = self.tcx.hir().attrs(hir_id); 56 ( 0.00%) if attr::find_transparency(attrs, md.macro_rules).0 != Transparency::Opaque { . return; . } . . let item_def_id = local_def_id.to_def_id(); . let macro_module_def_id = . ty::DefIdTree::parent(self.tcx, item_def_id).unwrap().expect_local(); . if self.tcx.hir().opt_def_kind(macro_module_def_id) != Some(DefKind::Mod) { . // The macro's parent doesn't correspond to a `mod`, return early (#63164, #65252). -- line 483 ---------------------------------------- -- line 630 ---------------------------------------- . } . . impl<'tcx> Visitor<'tcx> for EmbargoVisitor<'tcx> { . type NestedFilter = nested_filter::All; . . /// We want to visit items in the context of their containing . /// module and so forth, so supply a crate for doing a deep walk. . fn nested_visit_map(&mut self) -> Self::Map { 2,182 ( 0.00%) self.tcx.hir() . } . 8,856 ( 0.00%) fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { 1,968 ( 0.00%) let item_level = match item.kind { . hir::ItemKind::Impl { .. } => { . let impl_level = 1,452 ( 0.00%) Option::::of_impl(item.def_id, self.tcx, &self.access_levels); 242 ( 0.00%) self.update(item.def_id, impl_level) . } 2,968 ( 0.00%) _ => self.get(item.def_id), . }; . . // Update levels of nested things. 5,036 ( 0.00%) match item.kind { . hir::ItemKind::Enum(ref def, _) => { 20 ( 0.00%) for variant in def.variants { 132 ( 0.00%) let variant_level = self.update_with_hir_id(variant.id, item_level); 176 ( 0.00%) if let Some(ctor_hir_id) = variant.data.ctor_hir_id() { . self.update_with_hir_id(ctor_hir_id, item_level); . } 88 ( 0.00%) for field in variant.data.fields() { 100 ( 0.00%) self.update_with_hir_id(field.hir_id, variant_level); . } . } . } . hir::ItemKind::Impl(ref impl_) => { 726 ( 0.00%) for impl_item_ref in impl_.items { 1,678 ( 0.00%) if impl_.of_trait.is_some() 416 ( 0.00%) || self.tcx.visibility(impl_item_ref.id.def_id) == ty::Visibility::Public . { 644 ( 0.00%) self.update(impl_item_ref.id.def_id, item_level); . } . } . } 12 ( 0.00%) hir::ItemKind::Trait(.., trait_item_refs) => { . for trait_item_ref in trait_item_refs { 4 ( 0.00%) self.update(trait_item_ref.id.def_id, item_level); . } . } . hir::ItemKind::Struct(ref def, _) | hir::ItemKind::Union(ref def, _) => { 96 ( 0.00%) if let Some(ctor_hir_id) = def.ctor_hir_id() { . self.update_with_hir_id(ctor_hir_id, item_level); . } 48 ( 0.00%) for field in def.fields() { 344 ( 0.00%) if field.vis.node.is_pub() { 24 ( 0.00%) self.update_with_hir_id(field.hir_id, item_level); . } . } . } . hir::ItemKind::Macro(ref macro_def) => { 16 ( 0.00%) self.update_reachability_from_macro(item.def_id, macro_def); . } . hir::ItemKind::ForeignMod { items, .. } => { . for foreign_item in items { . if self.tcx.visibility(foreign_item.id.def_id) == ty::Visibility::Public { . self.update(foreign_item.id.def_id, item_level); . } . } . } -- line 697 ---------------------------------------- -- line 704 ---------------------------------------- . | hir::ItemKind::TyAlias(..) . | hir::ItemKind::Mod(..) . | hir::ItemKind::TraitAlias(..) . | hir::ItemKind::Fn(..) . | hir::ItemKind::ExternCrate(..) => {} . } . . // Mark all items in interfaces of reachable items as reachable. 4,920 ( 0.00%) match item.kind { . // The interface is empty. . hir::ItemKind::Macro(..) | hir::ItemKind::ExternCrate(..) => {} . // All nested items are checked by `visit_item`. . hir::ItemKind::Mod(..) => {} . // Handled in the access level of in rustc_resolve . hir::ItemKind::Use(..) => {} . // The interface is empty. . hir::ItemKind::GlobalAsm(..) => {} -- line 720 ---------------------------------------- -- line 732 ---------------------------------------- . self.reach(item.def_id, exist_level).generics().predicates().ty(); . } . } . // Visit everything. . hir::ItemKind::Const(..) . | hir::ItemKind::Static(..) . | hir::ItemKind::Fn(..) . | hir::ItemKind::TyAlias(..) => { 388 ( 0.00%) if item_level.is_some() { 372 ( 0.00%) self.reach(item.def_id, item_level).generics().predicates().ty(); . } . } 8 ( 0.00%) hir::ItemKind::Trait(.., trait_item_refs) => { 4 ( 0.00%) if item_level.is_some() { 32 ( 0.00%) self.reach(item.def_id, item_level).generics().predicates(); . . for trait_item_ref in trait_item_refs { 4 ( 0.00%) let mut reach = self.reach(trait_item_ref.id.def_id, item_level); 8 ( 0.00%) reach.generics().predicates(); . 2 ( 0.00%) if trait_item_ref.kind == AssocItemKind::Type . && !trait_item_ref.defaultness.has_value() . { . // No type to visit. . } else { 4 ( 0.00%) reach.ty(); . } . } . } . } . hir::ItemKind::TraitAlias(..) => { . if item_level.is_some() { . self.reach(item.def_id, item_level).generics().predicates(); . } . } . // Visit everything except for private impl items. . hir::ItemKind::Impl(ref impl_) => { 242 ( 0.00%) if item_level.is_some() { 2,320 ( 0.00%) self.reach(item.def_id, item_level).generics().predicates().ty().trait_ref(); . 232 ( 0.00%) for impl_item_ref in impl_.items { 1,092 ( 0.00%) let impl_item_level = self.get(impl_item_ref.id.def_id); 1,432 ( 0.00%) if impl_item_level.is_some() { 2,940 ( 0.00%) self.reach(impl_item_ref.id.def_id, impl_item_level) . .generics() . .predicates() . .ty(); . } . } . } . } . . // Visit everything, but enum variants have their own levels. . hir::ItemKind::Enum(ref def, _) => { 20 ( 0.00%) if item_level.is_some() { 128 ( 0.00%) self.reach(item.def_id, item_level).generics().predicates(); . } 20 ( 0.00%) for variant in def.variants { 396 ( 0.00%) let variant_level = self.get(self.tcx.hir().local_def_id(variant.id)); 44 ( 0.00%) if variant_level.is_some() { 72 ( 0.00%) for field in variant.data.fields() { 216 ( 0.00%) self.reach(self.tcx.hir().local_def_id(field.hir_id), variant_level) . .ty(); . } . // Corner case: if the variant is reachable, but its . // enum is not, make the enum reachable as well. 72 ( 0.00%) self.update(item.def_id, variant_level); . } . } . } . // Visit everything, but foreign items have their own levels. . hir::ItemKind::ForeignMod { items, .. } => { . for foreign_item in items { . let foreign_item_level = self.get(foreign_item.id.def_id); . if foreign_item_level.is_some() { -- line 806 ---------------------------------------- -- line 808 ---------------------------------------- . .generics() . .predicates() . .ty(); . } . } . } . // Visit everything except for private fields. . hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => { 24 ( 0.00%) if item_level.is_some() { 176 ( 0.00%) self.reach(item.def_id, item_level).generics().predicates(); 44 ( 0.00%) for field in struct_def.fields() { 560 ( 0.00%) let def_id = self.tcx.hir().local_def_id(field.hir_id); 240 ( 0.00%) let field_level = self.get(def_id); 80 ( 0.00%) if field_level.is_some() { 30 ( 0.00%) self.reach(def_id, field_level).ty(); . } . } . } . } . } . . let orig_level = mem::replace(&mut self.prev_level, item_level); 2,952 ( 0.00%) intravisit::walk_item(self, item); 984 ( 0.00%) self.prev_level = orig_level; 7,872 ( 0.00%) } . . fn visit_block(&mut self, b: &'tcx hir::Block<'tcx>) { . // Blocks can have public items, for example impls, but they always . // start as completely private regardless of publicity of a function, . // constant, type, field, etc., in which this block resides. . let orig_level = mem::replace(&mut self.prev_level, None); . intravisit::walk_block(self, b); . self.prev_level = orig_level; . } . } . . impl ReachEverythingInTheInterfaceVisitor<'_, '_> { 5,292 ( 0.00%) fn generics(&mut self) -> &mut Self { 3,024 ( 0.00%) for param in &self.ev.tcx.generics_of(self.item_def_id).params { 2,468 ( 0.00%) match param.kind { . GenericParamDefKind::Lifetime => {} 196 ( 0.00%) GenericParamDefKind::Type { has_default, .. } => { 196 ( 0.00%) if has_default { . self.visit(self.ev.tcx.type_of(param.def_id)); . } . } . GenericParamDefKind::Const { has_default, .. } => { . self.visit(self.ev.tcx.type_of(param.def_id)); . if has_default { . self.visit(self.ev.tcx.const_param_default(param.def_id)); . } . } . } . } . self 6,804 ( 0.00%) } . 3,780 ( 0.00%) fn predicates(&mut self) -> &mut Self { 2,268 ( 0.00%) self.visit_predicates(self.ev.tcx.predicates_of(self.item_def_id)); . self 4,536 ( 0.00%) } . 3,600 ( 0.00%) fn ty(&mut self) -> &mut Self { 2,184 ( 0.00%) self.visit(self.ev.tcx.type_of(self.item_def_id)); . self 4,320 ( 0.00%) } . . fn trait_ref(&mut self) -> &mut Self { 1,392 ( 0.00%) if let Some(trait_ref) = self.ev.tcx.impl_trait_ref(self.item_def_id) { . self.visit_trait(trait_ref); . } . self . } . } . . impl<'tcx> DefIdVisitor<'tcx> for ReachEverythingInTheInterfaceVisitor<'_, 'tcx> { . fn tcx(&self) -> TyCtxt<'tcx> { 14,156 ( 0.00%) self.ev.tcx . } 15,680 ( 0.00%) fn visit_def_id( . &mut self, . def_id: DefId, . _kind: &str, . _descr: &dyn fmt::Display, . ) -> ControlFlow { 9,412 ( 0.00%) if let Some(def_id) = def_id.as_local() { 7,543 ( 0.00%) if let (ty::Visibility::Public, _) | (_, Some(AccessLevel::ReachableFromImplTrait)) = 1,914 ( 0.00%) (self.tcx().visibility(def_id.to_def_id()), self.access_level) . { . self.ev.update(def_id, self.access_level); . } . } . ControlFlow::CONTINUE 21,952 ( 0.00%) } . } . . ////////////////////////////////////////////////////////////////////////////////////// . /// Name privacy visitor, checks privacy and reports violations. . /// Most of name privacy checks are performed during the main resolution phase, . /// or later in type checking when field accesses and associated items are resolved. . /// This pass performs remaining checks for fields in struct expressions and patterns. . ////////////////////////////////////////////////////////////////////////////////////// -- line 909 ---------------------------------------- -- line 920 ---------------------------------------- . /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies). . #[track_caller] . fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> { . self.maybe_typeck_results . .expect("`NamePrivacyVisitor::typeck_results` called outside of body") . } . . // Checks that a field in a struct constructor (expression or pattern) is accessible. 11,470 ( 0.00%) fn check_field( . &mut self, . use_ctxt: Span, // syntax context of the field name at the use site . span: Span, // span of the field pattern, e.g., `x: 0` . def: &'tcx ty::AdtDef, // definition of the struct or enum . field: &'tcx ty::FieldDef, . in_update_syntax: bool, . ) { 2,294 ( 0.00%) if def.is_enum() { . return; . } . . // definition of the field . let ident = Ident::new(kw::Empty, use_ctxt); 2,066 ( 0.00%) let hir_id = self.tcx.hir().local_def_id_to_hir_id(self.current_item); 7,231 ( 0.00%) let def_id = self.tcx.adjust_ident_and_get_scope(ident, def.did, hir_id).1; 1,033 ( 0.00%) if !field.vis.is_accessible_from(def_id, self.tcx) { . let label = if in_update_syntax { . format!("field `{}` is private", field.name) . } else { . "private field".to_string() . }; . . struct_span_err!( . self.tcx.sess, -- line 952 ---------------------------------------- -- line 955 ---------------------------------------- . "field `{}` of {} `{}` is private", . field.name, . def.variant_descr(), . self.tcx.def_path_str(def.did) . ) . .span_label(span, label) . .emit(); . } 9,176 ( 0.00%) } . } . . impl<'tcx> Visitor<'tcx> for NamePrivacyVisitor<'tcx> { . type NestedFilter = nested_filter::All; . . /// We want to visit items in the context of their containing . /// module and so forth, so supply a crate for doing a deep walk. . fn nested_visit_map(&mut self) -> Self::Map { 671 ( 0.00%) self.tcx.hir() . } . . fn visit_mod(&mut self, _m: &'tcx hir::Mod<'tcx>, _s: Span, _n: hir::HirId) { . // Don't visit nested modules, since we run a separate visitor walk . // for each module in `privacy_access_levels` . } . . fn visit_nested_body(&mut self, body: hir::BodyId) { . let old_maybe_typeck_results = 2,139 ( 0.00%) self.maybe_typeck_results.replace(self.tcx.typeck_body(body)); 2,406 ( 0.00%) let body = self.tcx.hir().body(body); . self.visit_body(body); 403 ( 0.00%) self.maybe_typeck_results = old_maybe_typeck_results; . } . . fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { 492 ( 0.00%) let orig_current_item = mem::replace(&mut self.current_item, item.def_id); 1,457 ( 0.00%) intravisit::walk_item(self, item); 492 ( 0.00%) self.current_item = orig_current_item; . } . 1,310,202 ( 0.02%) fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) { 291,156 ( 0.00%) if let hir::ExprKind::Struct(qpath, fields, ref base) = expr.kind { 1,398 ( 0.00%) let res = self.typeck_results().qpath_res(qpath, expr.hir_id); 699 ( 0.00%) let adt = self.typeck_results().expr_ty(expr).ty_adt_def().unwrap(); 2,097 ( 0.00%) let variant = adt.variant_of_res(res); 932 ( 0.00%) if let Some(base) = *base { . // If the expression uses FRU we need to make sure all the unmentioned fields . // are checked for privacy (RFC 736). Rather than computing the set of . // unmentioned fields, just check them all. . for (vf_index, variant_field) in variant.fields.iter().enumerate() { . let field = fields.iter().find(|f| { . self.tcx.field_index(f.hir_id, self.typeck_results()) == vf_index . }); . let (use_ctxt, span) = match field { . Some(field) => (field.ident.span, field.span), . None => (base.span, base.span), . }; . self.check_field(use_ctxt, span, adt, variant_field, true); . } . } else { . for field in fields { 976 ( 0.00%) let use_ctxt = field.ident.span; 6,045 ( 0.00%) let index = self.tcx.field_index(field.hir_id, self.typeck_results()); 10,736 ( 0.00%) self.check_field(use_ctxt, field.span, adt, &variant.fields[index], false); . } . } . } . 1,455,780 ( 0.02%) intravisit::walk_expr(self, expr); . } . 10,776 ( 0.00%) fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) { 2,792 ( 0.00%) if let PatKind::Struct(ref qpath, fields, _) = pat.kind { 686 ( 0.00%) let res = self.typeck_results().qpath_res(qpath, pat.hir_id); 392 ( 0.00%) let adt = self.typeck_results().pat_ty(pat).ty_adt_def().unwrap(); 784 ( 0.00%) let variant = adt.variant_of_res(res); . for field in fields { 171 ( 0.00%) let use_ctxt = field.ident.span; 1,107 ( 0.00%) let index = self.tcx.field_index(field.hir_id, self.typeck_results()); 1,710 ( 0.00%) self.check_field(use_ctxt, field.span, adt, &variant.fields[index], false); . } . } . 12,123 ( 0.00%) intravisit::walk_pat(self, pat); . } . } . . //////////////////////////////////////////////////////////////////////////////////////////// . /// Type privacy visitor, checks types for privacy and reports violations. . /// Both explicitly written types and inferred types of expressions and patterns are checked. . /// Checks are performed on "semantic" types regardless of names and their hygiene. . //////////////////////////////////////////////////////////////////////////////////////////// -- line 1045 ---------------------------------------- -- line 1061 ---------------------------------------- . .expect("`TypePrivacyVisitor::typeck_results` called outside of body") . } . . fn item_is_accessible(&self, did: DefId) -> bool { . self.tcx.visibility(did).is_accessible_from(self.current_item.to_def_id(), self.tcx) . } . . // Take node-id of an expression or pattern and check its type for privacy. 1,030,932 ( 0.01%) fn check_expr_pat_type(&mut self, id: hir::HirId, span: Span) -> bool { 147,276 ( 0.00%) self.span = span; 147,276 ( 0.00%) let typeck_results = self.typeck_results(); . let result: ControlFlow<()> = try { 589,104 ( 0.01%) self.visit(typeck_results.node_type(id))?; 1,178,208 ( 0.02%) self.visit(typeck_results.node_substs(id))?; 1,325,484 ( 0.02%) if let Some(adjustments) = typeck_results.adjustments().get(id) { . adjustments.iter().try_for_each(|adjustment| self.visit(adjustment.target))?; . } . }; . result.is_break() 1,178,208 ( 0.02%) } . . fn check_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool { 32,034 ( 0.00%) let is_error = !self.item_is_accessible(def_id); . if is_error { . self.tcx . .sess . .struct_span_err(self.span, &format!("{} `{}` is private", kind, descr)) . .span_label(self.span, &format!("private {}", kind)) . .emit(); . } . is_error -- line 1091 ---------------------------------------- -- line 1093 ---------------------------------------- . } . . impl<'tcx> Visitor<'tcx> for TypePrivacyVisitor<'tcx> { . type NestedFilter = nested_filter::All; . . /// We want to visit items in the context of their containing . /// module and so forth, so supply a crate for doing a deep walk. . fn nested_visit_map(&mut self) -> Self::Map { 671 ( 0.00%) self.tcx.hir() . } . . fn visit_mod(&mut self, _m: &'tcx hir::Mod<'tcx>, _s: Span, _n: hir::HirId) { . // Don't visit nested modules, since we run a separate visitor walk . // for each module in `privacy_access_levels` . } . 4,010 ( 0.00%) fn visit_nested_body(&mut self, body: hir::BodyId) { . let old_maybe_typeck_results = 1,203 ( 0.00%) self.maybe_typeck_results.replace(self.tcx.typeck_body(body)); 2,406 ( 0.00%) let body = self.tcx.hir().body(body); . self.visit_body(body); 401 ( 0.00%) self.maybe_typeck_results = old_maybe_typeck_results; 3,208 ( 0.00%) } . . fn visit_generic_arg(&mut self, generic_arg: &'tcx hir::GenericArg<'tcx>) { 3,614 ( 0.00%) match generic_arg { 1,392 ( 0.00%) hir::GenericArg::Type(t) => self.visit_ty(t), . hir::GenericArg::Infer(inf) => self.visit_infer(inf), . hir::GenericArg::Lifetime(_) | hir::GenericArg::Const(_) => {} . } . } . 14,245 ( 0.00%) fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty<'tcx>) { 4,070 ( 0.00%) self.span = hir_ty.span; 6,105 ( 0.00%) if let Some(typeck_results) = self.maybe_typeck_results { . // Types in bodies. 882 ( 0.00%) if self.visit(typeck_results.node_type(hir_ty.hir_id)).is_break() { . return; . } . } else { . // Types in signatures. . // FIXME: This is very ineffective. Ideally each HIR type should be converted . // into a semantic type only once and the result should be cached somehow. 5,223 ( 0.00%) if self.visit(rustc_typeck::hir_ty_to_ty(self.tcx, hir_ty)).is_break() { . return; . } . } . 6,105 ( 0.00%) intravisit::walk_ty(self, hir_ty); 12,210 ( 0.00%) } . . fn visit_infer(&mut self, inf: &'tcx hir::InferArg) { . self.span = inf.span; . if let Some(typeck_results) = self.maybe_typeck_results { . if let Some(ty) = typeck_results.node_type_opt(inf.hir_id) { . if self.visit(ty).is_break() { . return; . } -- line 1150 ---------------------------------------- -- line 1152 ---------------------------------------- . // We don't do anything for const infers here. . } . } else { . bug!("visit_infer without typeck_results"); . } . intravisit::walk_inf(self, inf); . } . 1,768 ( 0.00%) fn visit_trait_ref(&mut self, trait_ref: &'tcx hir::TraitRef<'tcx>) { 663 ( 0.00%) self.span = trait_ref.path.span; 221 ( 0.00%) if self.maybe_typeck_results.is_none() { . // Avoid calling `hir_trait_to_predicates` in bodies, it will ICE. . // The traits' privacy in bodies is already checked as a part of trait object types. 221 ( 0.00%) let bounds = rustc_typeck::hir_trait_to_predicates( 221 ( 0.00%) self.tcx, . trait_ref, . // NOTE: This isn't really right, but the actual type doesn't matter here. It's . // just required by `ty::TraitRef`. 663 ( 0.00%) self.tcx.types.never, . ); . 1,989 ( 0.00%) for (trait_predicate, _, _) in bounds.trait_bounds { 1,547 ( 0.00%) if self.visit_trait(trait_predicate.skip_binder()).is_break() { . return; . } . } . 1,473 ( 0.00%) for (poly_predicate, _) in bounds.projection_bounds { 126 ( 0.00%) let pred = poly_predicate.skip_binder(); . let poly_pred_term = self.visit(pred.term); 84 ( 0.00%) if poly_pred_term.is_break() . || self.visit_projection_ty(pred.projection_ty).is_break() . { . return; . } . } . } . . intravisit::walk_trait_ref(self, trait_ref); 1,768 ( 0.00%) } . . // Check types of expressions 1,310,202 ( 0.02%) fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) { 1,310,202 ( 0.02%) if self.check_expr_pat_type(expr.hir_id, expr.span) { . // Do not check nested expressions if the error already happened. . return; . } 1,017,048 ( 0.01%) match expr.kind { 179 ( 0.00%) hir::ExprKind::Assign(_, rhs, _) | hir::ExprKind::Match(rhs, ..) => { . // Do not report duplicate errors for `x = y` and `match x { ... }`. 1,029 ( 0.00%) if self.check_expr_pat_type(rhs.hir_id, rhs.span) { . return; . } . } 442 ( 0.00%) hir::ExprKind::MethodCall(segment, ..) => { . // Method calls have to be checked specially. 884 ( 0.00%) self.span = segment.ident.span; 2,652 ( 0.00%) if let Some(def_id) = self.typeck_results().type_dependent_def_id(expr.hir_id) { 1,326 ( 0.00%) if self.visit(self.tcx.type_of(def_id)).is_break() { . return; . } . } else { . self.tcx . .sess . .delay_span_bug(expr.span, "no type-dependent def for method call"); . } . } . _ => {} . } . 436,734 ( 0.01%) intravisit::walk_expr(self, expr); 1,164,624 ( 0.02%) } . . // Prohibit access to associated items with insufficient nominal visibility. . // . // Additionally, until better reachability analysis for macros 2.0 is available, . // we prohibit access to private statics from other crates, this allows to give . // more code internal visibility at link time. (Access to private functions . // is already prohibited by type privacy for function types.) 43,480 ( 0.00%) fn visit_qpath(&mut self, qpath: &'tcx hir::QPath<'tcx>, id: hir::HirId, span: Span) { 8,696 ( 0.00%) let def = match qpath { 12,180 ( 0.00%) hir::QPath::Resolved(_, path) => match path.res { 12,060 ( 0.00%) Res::Def(kind, def_id) => Some((kind, def_id)), . _ => None, . }, 288 ( 0.00%) hir::QPath::TypeRelative(..) | hir::QPath::LangItem(..) => self . .maybe_typeck_results 2,538 ( 0.00%) .and_then(|typeck_results| typeck_results.type_dependent_def(id)), . }; . let def = def.filter(|(kind, _)| { 4,584 ( 0.00%) matches!( . kind, . DefKind::AssocFn | DefKind::AssocConst | DefKind::AssocTy | DefKind::Static . ) . }); . if let Some((kind, def_id)) = def { . let is_local_static = 1,328 ( 0.00%) if let DefKind::Static = kind { def_id.is_local() } else { false }; 720 ( 0.00%) if !self.item_is_accessible(def_id) && !is_local_static { . let sess = self.tcx.sess; . let sm = sess.source_map(); . let name = match qpath { . hir::QPath::Resolved(..) | hir::QPath::LangItem(..) => { . sm.span_to_snippet(qpath.span()).ok() . } . hir::QPath::TypeRelative(_, segment) => Some(segment.ident.to_string()), . }; -- line 1258 ---------------------------------------- -- line 1263 ---------------------------------------- . }; . sess.struct_span_err(span, &msg) . .span_label(span, &format!("private {}", kind)) . .emit(); . return; . } . } . 47,828 ( 0.00%) intravisit::walk_qpath(self, qpath, id, span); . } . . // Check types of patterns. . fn visit_pat(&mut self, pattern: &'tcx hir::Pat<'tcx>) { 8,676 ( 0.00%) if self.check_expr_pat_type(pattern.hir_id, pattern.span) { . // Do not check nested patterns if the error already happened. . return; . } . 4,632 ( 0.00%) intravisit::walk_pat(self, pattern); . } . 1,110 ( 0.00%) fn visit_local(&mut self, local: &'tcx hir::Local<'tcx>) { 666 ( 0.00%) if let Some(init) = local.init { 1,428 ( 0.00%) if self.check_expr_pat_type(init.hir_id, init.span) { . // Do not report duplicate errors for `let x = y`. . return; . } . } . . intravisit::walk_local(self, local); 816 ( 0.00%) } . . // Check types in item interfaces. . fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { 492 ( 0.00%) let orig_current_item = mem::replace(&mut self.current_item, item.def_id); . let old_maybe_typeck_results = self.maybe_typeck_results.take(); 1,457 ( 0.00%) intravisit::walk_item(self, item); 492 ( 0.00%) self.maybe_typeck_results = old_maybe_typeck_results; 494 ( 0.00%) self.current_item = orig_current_item; . } . } . . impl<'tcx> DefIdVisitor<'tcx> for TypePrivacyVisitor<'tcx> { . fn tcx(&self) -> TyCtxt<'tcx> { 374,440 ( 0.01%) self.tcx . } 240,255 ( 0.00%) fn visit_def_id( . &mut self, . def_id: DefId, . kind: &str, . descr: &dyn fmt::Display, . ) -> ControlFlow { . if self.check_def_id(def_id, kind, descr) { . ControlFlow::BREAK . } else { . ControlFlow::CONTINUE . } 144,153 ( 0.00%) } . } . . /////////////////////////////////////////////////////////////////////////////// . /// Obsolete visitors for checking for private items in public interfaces. . /// These visitors are supposed to be kept in frozen state and produce an . /// "old error node set". For backward compatibility the new visitor reports . /// warnings instead of hard errors when the erroneous node is not in this old set. . /////////////////////////////////////////////////////////////////////////////// -- line 1328 ---------------------------------------- -- line 1342 ---------------------------------------- . /// Whether we've recurred at all (i.e., if we're pointing at the . /// first type on which `visit_ty` was called). . at_outer_type: bool, . /// Whether that first type is a public path. . outer_type_is_public_path: bool, . } . . impl<'a, 'tcx> ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { 785 ( 0.00%) fn path_is_private_type(&self, path: &hir::Path<'_>) -> bool { 2,424 ( 0.00%) let did = match path.res { . Res::PrimTy(..) | Res::SelfTy(..) | Res::Err => return false, 2,994 ( 0.00%) res => res.def_id(), . }; . . // A path can only be private if: . // it's in this crate... 499 ( 0.00%) if let Some(did) = did.as_local() { . // .. and it corresponds to a private type in the AST (this returns . // `None` for type parameters). 1,603 ( 0.00%) match self.tcx.hir().find(self.tcx.hir().local_def_id_to_hir_id(did)) { 804 ( 0.00%) Some(Node::Item(item)) => !item.vis.node.is_pub(), . Some(_) | None => false, . } . } else { . false . } 1,570 ( 0.00%) } . . fn trait_is_public(&self, trait_id: LocalDefId) -> bool { . // FIXME: this would preferably be using `exported_items`, but all . // traits are exported currently (see `EmbargoVisitor.exported_trait`). . self.access_levels.is_public(trait_id) . } . . fn check_generic_bound(&mut self, bound: &hir::GenericBound<'_>) { 116 ( 0.00%) if let hir::GenericBound::Trait(ref trait_ref, _) = *bound { 64 ( 0.00%) if self.path_is_private_type(trait_ref.trait_ref.path) { . self.old_error_set.insert(trait_ref.trait_ref.hir_ref_id); . } . } . } . . fn item_is_public(&self, def_id: LocalDefId, vis: &hir::Visibility<'_>) -> bool { 567 ( 0.00%) self.access_levels.is_reachable(def_id) || vis.node.is_pub() . } . } . . impl<'a, 'b, 'tcx, 'v> Visitor<'v> for ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> { . fn visit_generic_arg(&mut self, generic_arg: &'v hir::GenericArg<'v>) { 606 ( 0.00%) match generic_arg { . hir::GenericArg::Type(t) => self.visit_ty(t), . hir::GenericArg::Infer(inf) => self.visit_ty(&inf.to_ty()), . hir::GenericArg::Lifetime(_) | hir::GenericArg::Const(_) => {} . } . } . . fn visit_ty(&mut self, ty: &hir::Ty<'_>) { 915 ( 0.00%) if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = ty.kind { 732 ( 0.00%) if self.inner.path_is_private_type(path) { . self.contains_private = true; . // Found what we're looking for, so let's stop working. . return; . } . } . if let hir::TyKind::Path(_) = ty.kind { 124 ( 0.00%) if self.at_outer_type { 120 ( 0.00%) self.outer_type_is_public_path = true; . } . } 302 ( 0.00%) self.at_outer_type = false; 364 ( 0.00%) intravisit::walk_ty(self, ty) 480 ( 0.00%) } . . // Don't want to recurse into `[, .. expr]`. . fn visit_expr(&mut self, _: &hir::Expr<'_>) {} . } . . impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { . type NestedFilter = nested_filter::All; . . /// We want to visit items in the context of their containing . /// module and so forth, so supply a crate for doing a deep walk. . fn nested_visit_map(&mut self) -> Self::Map { 740 ( 0.00%) self.tcx.hir() . } . 4,419 ( 0.00%) fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { 1,964 ( 0.00%) match item.kind { . // Contents of a private mod can be re-exported, so we need . // to check internals. . hir::ItemKind::Mod(_) => {} . . // An `extern {}` doesn't introduce a new privacy . // namespace (the contents have their own privacies). . hir::ItemKind::ForeignMod { .. } => {} . 4 ( 0.00%) hir::ItemKind::Trait(.., bounds, _) => { 10 ( 0.00%) if !self.trait_is_public(item.def_id) { . return; . } . . for bound in bounds.iter() { . self.check_generic_bound(bound) . } . } . -- line 1447 ---------------------------------------- -- line 1454 ---------------------------------------- . // `impl [... for] Private` is never visible. . let self_contains_private; . // `impl [... for] Public<...>`, but not `impl [... for] . // Vec` or `(Public,)`, etc. . let self_is_public_path; . . // Check the properties of the `Self` type: . { 484 ( 0.00%) let mut visitor = ObsoleteCheckTypeForPrivatenessVisitor { . inner: self, . contains_private: false, . at_outer_type: true, . outer_type_is_public_path: false, . }; 121 ( 0.00%) visitor.visit_ty(impl_.self_ty); . self_contains_private = visitor.contains_private; . self_is_public_path = visitor.outer_type_is_public_path; . } . . // Miscellaneous info about the impl: . . // `true` iff this is `impl Private for ...`. . let not_private_trait = impl_.of_trait.as_ref().map_or( . true, // no trait counts as public trait . |tr| { 327 ( 0.00%) if let Some(def_id) = tr.path.res.def_id().as_local() { 3 ( 0.00%) self.trait_is_public(def_id) . } else { . true // external traits must be public . } . }, . ); . . // `true` iff this is a trait impl or at least one method is public. . // . // `impl Public { $( fn ...() {} )* }` is not visible. . // . // This is required over just using the methods' privacy . // directly because we might have `impl> ...`, . // and we shouldn't warn about the generics if all the methods . // are private (because `T` won't be visible externally). . let trait_or_some_public_method = impl_.of_trait.is_some() 12 ( 0.00%) || impl_.items.iter().any(|impl_item_ref| { 92 ( 0.00%) let impl_item = self.tcx.hir().impl_item(impl_item_ref.id); 106 ( 0.00%) match impl_item.kind { . hir::ImplItemKind::Const(..) | hir::ImplItemKind::Fn(..) => { . self.access_levels.is_reachable(impl_item_ref.id.def_id) . } . hir::ImplItemKind::TyAlias(_) => false, . } . }); . 238 ( 0.00%) if !self_contains_private && not_private_trait && trait_or_some_public_method { . intravisit::walk_generics(self, &impl_.generics); . 236 ( 0.00%) match impl_.of_trait { . None => { 10 ( 0.00%) for impl_item_ref in impl_.items { . // This is where we choose whether to walk down . // further into the impl to check its items. We . // should only walk into public items so that we . // don't erroneously report errors for private . // types in private items. 558 ( 0.00%) let impl_item = self.tcx.hir().impl_item(impl_item_ref.id); 515 ( 0.00%) match impl_item.kind { . hir::ImplItemKind::Const(..) | hir::ImplItemKind::Fn(..) 288 ( 0.00%) if self 93 ( 0.00%) .item_is_public(impl_item.def_id, &impl_item.vis) => . { . intravisit::walk_impl_item(self, impl_item) . } . hir::ImplItemKind::TyAlias(..) => { . intravisit::walk_impl_item(self, impl_item) . } . _ => {} . } -- line 1529 ---------------------------------------- -- line 1538 ---------------------------------------- . // . // Those in 1. can only occur if the trait is in . // this crate and will've been warned about on the . // trait definition (there's no need to warn twice . // so we don't check the methods). . // . // Those in 2. are warned via walk_generics and this . // call here. 324 ( 0.00%) intravisit::walk_path(self, tr.path); . . // Those in 3. are warned with this call. 108 ( 0.00%) for impl_item_ref in impl_.items { 460 ( 0.00%) let impl_item = self.tcx.hir().impl_item(impl_item_ref.id); 757 ( 0.00%) if let hir::ImplItemKind::TyAlias(ty) = impl_item.kind { . self.visit_ty(ty); . } . } . } . } 9 ( 0.00%) } else if impl_.of_trait.is_none() && self_is_public_path { . // `impl Public { ... }`. Any public static . // methods will be visible as `Public::foo`. . let mut found_pub_static = false; 2 ( 0.00%) for impl_item_ref in impl_.items { 44 ( 0.00%) if self.access_levels.is_reachable(impl_item_ref.id.def_id) 22 ( 0.00%) || self.tcx.visibility(impl_item_ref.id.def_id) . == ty::Visibility::Public . { 45 ( 0.00%) let impl_item = self.tcx.hir().impl_item(impl_item_ref.id); 116 ( 0.00%) match impl_item_ref.kind { . AssocItemKind::Const => { . found_pub_static = true; . intravisit::walk_impl_item(self, impl_item); . } . AssocItemKind::Fn { has_self: false } => { . found_pub_static = true; . intravisit::walk_impl_item(self, impl_item); . } . _ => {} . } . } . } 4 ( 0.00%) if found_pub_static { 3 ( 0.00%) intravisit::walk_generics(self, &impl_.generics) . } . } . return; . } . . // `type ... = ...;` can contain private types, because . // we're introducing a new name. . hir::ItemKind::TyAlias(..) => return, . . // Not at all public, so we don't care. 1,951 ( 0.00%) _ if !self.item_is_public(item.def_id, &item.vis) => { . return; . } . . _ => {} . } . . // We've carefully constructed it so that if we're here, then . // any `visit_ty`'s will be called on things that are in . // public signatures, i.e., things that we're interested in for . // this visitor. 2,490 ( 0.00%) intravisit::walk_item(self, item); 1,936 ( 0.00%) } . 1,424 ( 0.00%) fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) { . for param in generics.params { 43 ( 0.00%) for bound in param.bounds { . self.check_generic_bound(bound); . } . } 178 ( 0.00%) for predicate in generics.where_clause.predicates { 42 ( 0.00%) match predicate { . hir::WherePredicate::BoundPredicate(bound_pred) => { 14 ( 0.00%) for bound in bound_pred.bounds.iter() { . self.check_generic_bound(bound) . } . } . hir::WherePredicate::RegionPredicate(_) => {} . hir::WherePredicate::EqPredicate(eq_pred) => { . self.visit_ty(eq_pred.rhs_ty); . } . } . } 1,424 ( 0.00%) } . . fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem<'tcx>) { . if self.access_levels.is_reachable(item.def_id) { . intravisit::walk_foreign_item(self, item) . } . } . . fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx>) { 2,597 ( 0.00%) if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = t.kind { 1,844 ( 0.00%) if self.path_is_private_type(path) { . self.old_error_set.insert(t.hir_id); . } . } 3,785 ( 0.00%) intravisit::walk_ty(self, t) . } . 160 ( 0.00%) fn visit_variant( . &mut self, . v: &'tcx hir::Variant<'tcx>, . g: &'tcx hir::Generics<'tcx>, . item_id: hir::HirId, . ) { 198 ( 0.00%) if self.access_levels.is_reachable(self.tcx.hir().local_def_id(v.id)) { 18 ( 0.00%) self.in_variant = true; . intravisit::walk_variant(self, v, g, item_id); 18 ( 0.00%) self.in_variant = false; . } 140 ( 0.00%) } . 275 ( 0.00%) fn visit_field_def(&mut self, s: &'tcx hir::FieldDef<'tcx>) { 324 ( 0.00%) if s.vis.node.is_pub() || self.in_variant { . intravisit::walk_field_def(self, s); . } 160 ( 0.00%) } . . // We don't need to introspect into these at all: an . // expression/block context can't possibly contain exported things. . // (Making them no-ops stops us from traversing the whole AST without . // having to be super careful about our `walk_...` calls above.) . fn visit_block(&mut self, _: &'tcx hir::Block<'tcx>) {} . fn visit_expr(&mut self, _: &'tcx hir::Expr<'tcx>) {} . } -- line 1667 ---------------------------------------- -- line 1679 ---------------------------------------- . /// The visitor checks that each component type is at least this visible. . required_visibility: ty::Visibility, . has_pub_restricted: bool, . has_old_errors: bool, . in_assoc_ty: bool, . } . . impl SearchInterfaceForPrivateItemsVisitor<'_> { 2,996 ( 0.00%) fn generics(&mut self) -> &mut Self { 1,284 ( 0.00%) for param in &self.tcx.generics_of(self.item_def_id).params { 563 ( 0.00%) match param.kind { . GenericParamDefKind::Lifetime => {} 64 ( 0.00%) GenericParamDefKind::Type { has_default, .. } => { 64 ( 0.00%) if has_default { . self.visit(self.tcx.type_of(param.def_id)); . } . } . // FIXME(generic_const_exprs): May want to look inside const here . GenericParamDefKind::Const { .. } => { . self.visit(self.tcx.type_of(param.def_id)); . } . } . } . self 3,424 ( 0.00%) } . 2,140 ( 0.00%) fn predicates(&mut self) -> &mut Self { . // N.B., we use `explicit_predicates_of` and not `predicates_of` . // because we don't want to report privacy errors due to where . // clauses that the compiler inferred. We only want to . // consider the ones that the user wrote. This is important . // for the inferred outlives rules; see . // `src/test/ui/rfc-2093-infer-outlives/privacy.rs`. 856 ( 0.00%) self.visit_predicates(self.tcx.explicit_predicates_of(self.item_def_id)); . self 2,568 ( 0.00%) } . . fn bounds(&mut self) -> &mut Self { . self.visit_predicates(ty::GenericPredicates { . parent: None, . predicates: self.tcx.explicit_item_bounds(self.item_def_id), . }); . self . } . 2,270 ( 0.00%) fn ty(&mut self) -> &mut Self { 908 ( 0.00%) self.visit(self.tcx.type_of(self.item_def_id)); . self 2,270 ( 0.00%) } . . fn check_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool { 7,415 ( 0.00%) if self.leaks_private_dep(def_id) { . self.tcx.struct_span_lint_hir( . lint::builtin::EXPORTED_PRIVATE_DEPENDENCIES, . self.tcx.hir().local_def_id_to_hir_id(self.item_def_id), . self.tcx.def_span(self.item_def_id.to_def_id()), . |lint| { . lint.build(&format!( . "{} `{}` from private dependency '{}' in public \ . interface", -- line 1738 ---------------------------------------- -- line 1740 ---------------------------------------- . descr, . self.tcx.crate_name(def_id.krate) . )) . .emit() . }, . ); . } . 3,316 ( 0.00%) let hir_id = match def_id.as_local() { 894 ( 0.00%) Some(def_id) => self.tcx.hir().local_def_id_to_hir_id(def_id), . None => return false, . }; . . let vis = self.tcx.visibility(def_id); 1,648 ( 0.00%) if !vis.is_at_least(self.required_visibility, self.tcx) { . let vis_descr = match vis { . ty::Visibility::Public => "public", . ty::Visibility::Invisible => "private", . ty::Visibility::Restricted(vis_def_id) => { . if vis_def_id == self.tcx.parent_module(hir_id).to_def_id() { . "private" . } else if vis_def_id.is_top_level_module() { . "crate-private" -- line 1762 ---------------------------------------- -- line 1792 ---------------------------------------- . false . } . . /// An item is 'leaked' from a private dependency if all . /// of the following are true: . /// 1. It's contained within a public type . /// 2. It comes from a private crate . fn leaks_private_dep(&self, item_id: DefId) -> bool { 4,584 ( 0.00%) let ret = self.required_visibility.is_public() && self.tcx.is_private_dep(item_id.krate); . . tracing::debug!("leaks_private_dep(item_id={:?})={}", item_id, ret); . ret . } . } . . impl<'tcx> DefIdVisitor<'tcx> for SearchInterfaceForPrivateItemsVisitor<'tcx> { . fn tcx(&self) -> TyCtxt<'tcx> { 3,041 ( 0.00%) self.tcx . } 24,448 ( 0.00%) fn visit_def_id( . &mut self, . def_id: DefId, . kind: &str, . descr: &dyn fmt::Display, . ) -> ControlFlow { . if self.check_def_id(def_id, kind, descr) { . ControlFlow::BREAK . } else { . ControlFlow::CONTINUE . } 13,752 ( 0.00%) } . } . . struct PrivateItemsInPublicInterfacesVisitor<'tcx> { . tcx: TyCtxt<'tcx>, . has_pub_restricted: bool, . old_error_set_ancestry: LocalDefIdSet, . } . . impl<'tcx> PrivateItemsInPublicInterfacesVisitor<'tcx> { . fn check( . &self, . def_id: LocalDefId, . required_visibility: ty::Visibility, . ) -> SearchInterfaceForPrivateItemsVisitor<'tcx> { 4,013 ( 0.00%) SearchInterfaceForPrivateItemsVisitor { 260 ( 0.00%) tcx: self.tcx, . item_def_id: def_id, . required_visibility, 552 ( 0.00%) has_pub_restricted: self.has_pub_restricted, . has_old_errors: self.old_error_set_ancestry.contains(&def_id), . in_assoc_ty: false, . } . } . 2,574 ( 0.00%) fn check_assoc_item( . &self, . def_id: LocalDefId, . assoc_item_kind: AssocItemKind, . defaultness: hir::Defaultness, . vis: ty::Visibility, . ) { . let mut check = self.check(def_id, vis); . 396 ( 0.00%) let (check_ty, is_assoc_ty) = match assoc_item_kind { . AssocItemKind::Const | AssocItemKind::Fn { .. } => (true, false), 12 ( 0.00%) AssocItemKind::Type => (defaultness.has_value(), true), . }; 396 ( 0.00%) check.in_assoc_ty = is_assoc_ty; 792 ( 0.00%) check.generics().predicates(); 12 ( 0.00%) if check_ty { 198 ( 0.00%) check.ty(); . } 1,584 ( 0.00%) } . } . . impl<'tcx> Visitor<'tcx> for PrivateItemsInPublicInterfacesVisitor<'tcx> { . type NestedFilter = nested_filter::OnlyBodies; . . fn nested_visit_map(&mut self) -> Self::Map { 205 ( 0.00%) self.tcx.hir() . } . 4,428 ( 0.00%) fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { 492 ( 0.00%) let tcx = self.tcx; 492 ( 0.00%) let item_visibility = tcx.visibility(item.def_id); . 2,460 ( 0.00%) match item.kind { . // Crates are always public. . hir::ItemKind::ExternCrate(..) => {} . // All nested items are checked by `visit_item`. . hir::ItemKind::Mod(..) => {} . // Checked in resolve. . hir::ItemKind::Use(..) => {} . // No subitems. . hir::ItemKind::Macro(..) | hir::ItemKind::GlobalAsm(..) => {} . // Subitems of these items have inherited publicity. . hir::ItemKind::Const(..) . | hir::ItemKind::Static(..) . | hir::ItemKind::Fn(..) . | hir::ItemKind::TyAlias(..) => { 1,164 ( 0.00%) self.check(item.def_id, item_visibility).generics().predicates().ty(); . } . hir::ItemKind::OpaqueTy(..) => { . // `ty()` for opaque types is the underlying type, . // it's not a part of interface, so we skip it. . self.check(item.def_id, item_visibility).generics().bounds(); . } 8 ( 0.00%) hir::ItemKind::Trait(.., trait_item_refs) => { 8 ( 0.00%) self.check(item.def_id, item_visibility).generics().predicates(); . . for trait_item_ref in trait_item_refs { 6 ( 0.00%) self.check_assoc_item( 1 ( 0.00%) trait_item_ref.id.def_id, . trait_item_ref.kind, . trait_item_ref.defaultness, . item_visibility, . ); . 7 ( 0.00%) if let AssocItemKind::Type = trait_item_ref.kind { . self.check(trait_item_ref.id.def_id, item_visibility).bounds(); . } . } . } . hir::ItemKind::TraitAlias(..) => { . self.check(item.def_id, item_visibility).generics().predicates(); . } . hir::ItemKind::Enum(ref def, _) => { 40 ( 0.00%) self.check(item.def_id, item_visibility).generics().predicates(); . 10 ( 0.00%) for variant in def.variants { 22 ( 0.00%) for field in variant.data.fields() { 228 ( 0.00%) self.check(self.tcx.hir().local_def_id(field.hir_id), item_visibility).ty(); . } . } . } . // Subitems of foreign modules have their own publicity. . hir::ItemKind::ForeignMod { items, .. } => { . for foreign_item in items { . let vis = tcx.visibility(foreign_item.id.def_id); . self.check(foreign_item.id.def_id, vis).generics().predicates().ty(); . } . } . // Subitems of structs and unions have their own publicity. . hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => { 48 ( 0.00%) self.check(item.def_id, item_visibility).generics().predicates(); . 36 ( 0.00%) for field in struct_def.fields() { 258 ( 0.00%) let def_id = tcx.hir().local_def_id(field.hir_id); . let field_visibility = tcx.visibility(def_id); 129 ( 0.00%) self.check(def_id, min(item_visibility, field_visibility, tcx)).ty(); . } . } . // An inherent impl is public when its type is public . // Subitems of inherent impls have their own publicity. . // A trait impl is public when both its type and its trait are public . // Subitems of trait impls have inherited publicity. . hir::ItemKind::Impl(ref impl_) => { 484 ( 0.00%) let impl_vis = ty::Visibility::of_impl(item.def_id, tcx, &Default::default()); . // check that private components do not appear in the generics or predicates of inherent impls . // this check is intentionally NOT performed for impls of traits, per #90586 242 ( 0.00%) if impl_.of_trait.is_none() { 60 ( 0.00%) self.check(item.def_id, impl_vis).generics().predicates(); . } 121 ( 0.00%) for impl_item_ref in impl_.items { 176 ( 0.00%) let impl_item_vis = if impl_.of_trait.is_none() { 104 ( 0.00%) min(tcx.visibility(impl_item_ref.id.def_id), impl_vis, tcx) . } else { . impl_vis . }; 1,078 ( 0.00%) self.check_assoc_item( 197 ( 0.00%) impl_item_ref.id.def_id, . impl_item_ref.kind, . impl_item_ref.defaultness, . impl_item_vis, . ); . } . } . } 3,936 ( 0.00%) } . } . . pub fn provide(providers: &mut Providers) { 8 ( 0.00%) *providers = Providers { . visibility, . privacy_access_levels, . check_private_in_public, . check_mod_privacy, . ..*providers . }; 1 ( 0.00%) } . 7,272 ( 0.00%) fn visibility(tcx: TyCtxt<'_>, def_id: DefId) -> ty::Visibility { 808 ( 0.00%) let def_id = def_id.expect_local(); . match tcx.resolutions(()).visibilities.get(&def_id) { 1,304 ( 0.00%) Some(vis) => *vis, . None => { . let hir_id = tcx.hir().local_def_id_to_hir_id(def_id); 1,766 ( 0.00%) match tcx.hir().get(hir_id) { . // Unique types created for closures participate in type privacy checking. . // They have visibilities inherited from the module they are defined in. . Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => { 102 ( 0.00%) ty::Visibility::Restricted(tcx.parent_module(hir_id).to_def_id()) . } . // - AST lowering may clone `use` items and the clones don't . // get their entries in the resolver's visibility table. . // - AST lowering also creates opaque type items with inherited visibilies. . // Visibility on them should have no effect, but to avoid the visibility . // query failing on some items, we provide it for opaque types as well. . Node::Item(hir::Item { 46 ( 0.00%) vis, . kind: hir::ItemKind::Use(..) | hir::ItemKind::OpaqueTy(..), . .. 276 ( 0.00%) }) => ty::Visibility::from_hir(vis, hir_id, tcx), . // Visibilities of trait impl items are inherited from their traits . // and are not filled in resolve. . Node::ImplItem(impl_item) => { 1,209 ( 0.00%) match tcx.hir().get_by_def_id(tcx.hir().get_parent_item(hir_id)) { . Node::Item(hir::Item { . kind: hir::ItemKind::Impl(hir::Impl { of_trait: Some(tr), .. }), . .. 93 ( 0.00%) }) => tr.path.res.opt_def_id().map_or_else( . || { . tcx.sess.delay_span_bug(tr.path.span, "trait without a def-id"); . ty::Visibility::Public . }, . |def_id| tcx.visibility(def_id), . ), . _ => span_bug!(impl_item.span, "the parent is not a trait impl"), . } -- line 2021 ---------------------------------------- -- line 2023 ---------------------------------------- . _ => span_bug!( . tcx.def_span(def_id), . "visibility table unexpectedly missing a def-id: {:?}", . def_id, . ), . } . } . } 6,464 ( 0.00%) } . 152 ( 0.00%) fn check_mod_privacy(tcx: TyCtxt<'_>, module_def_id: LocalDefId) { . // Check privacy of names not checked in previous compilation stages. . let mut visitor = 76 ( 0.00%) NamePrivacyVisitor { tcx, maybe_typeck_results: None, current_item: module_def_id }; 171 ( 0.00%) let (module, span, hir_id) = tcx.hir().get_module(module_def_id); . . intravisit::walk_mod(&mut visitor, module, hir_id); . . // Check privacy of explicitly written types and traits as well as . // inferred types of expressions and patterns. . let mut visitor = 114 ( 0.00%) TypePrivacyVisitor { tcx, maybe_typeck_results: None, current_item: module_def_id, span }; . intravisit::walk_mod(&mut visitor, module, hir_id); 152 ( 0.00%) } . 7 ( 0.00%) fn privacy_access_levels(tcx: TyCtxt<'_>, (): ()) -> &AccessLevels { . // Build up a set of all exported items in the AST. This is a set of all . // items which are reachable from external crates based on visibility. 9 ( 0.00%) let mut visitor = EmbargoVisitor { . tcx, . access_levels: tcx.resolutions(()).access_levels.clone(), . macro_reachable: Default::default(), . prev_level: Some(AccessLevel::Public), . changed: false, . }; . . loop { . tcx.hir().walk_toplevel_module(&mut visitor); 4 ( 0.00%) if visitor.changed { 3 ( 0.00%) visitor.changed = false; . } else { . break; . } . } . 1 ( 0.00%) tcx.arena.alloc(visitor.access_levels) 9 ( 0.00%) } . 8 ( 0.00%) fn check_private_in_public(tcx: TyCtxt<'_>, (): ()) { . let access_levels = tcx.privacy_access_levels(()); . 9 ( 0.00%) let mut visitor = ObsoleteVisiblePrivateTypesVisitor { . tcx, . access_levels, . in_variant: false, . old_error_set: Default::default(), . }; . tcx.hir().walk_toplevel_module(&mut visitor); . . let has_pub_restricted = { 5 ( 0.00%) let mut pub_restricted_visitor = PubRestrictedVisitor { tcx, has_pub_restricted: false }; . tcx.hir().walk_toplevel_module(&mut pub_restricted_visitor); 1 ( 0.00%) pub_restricted_visitor.has_pub_restricted . }; . . let mut old_error_set_ancestry = HirIdSet::default(); 9 ( 0.00%) for mut id in visitor.old_error_set.iter().copied() { . loop { . if !old_error_set_ancestry.insert(id) { . break; . } . let parent = tcx.hir().get_parent_node(id); . if parent == id { . break; . } . id = parent; . } . } . . // Check for private types and traits in public interfaces. 8 ( 0.00%) let mut visitor = PrivateItemsInPublicInterfacesVisitor { . tcx, . has_pub_restricted, . // Only definition IDs are ever searched in `old_error_set_ancestry`, . // so we can filter away all non-definition IDs at this point. . old_error_set_ancestry: old_error_set_ancestry . .into_iter() . .filter_map(|hir_id| tcx.hir().opt_local_def_id(hir_id)) . .collect(), . }; 6 ( 0.00%) tcx.hir().visit_all_item_likes(&mut DeepVisitor::new(&mut visitor)); 8 ( 0.00%) } 926,805 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/caching_source_map_view.rs -------------------------------------------------------------------------------- Ir -- line 27 ---------------------------------------- . impl CacheEntry { . #[inline] . fn update( . &mut self, . new_file_and_idx: Option<(Lrc, usize)>, . pos: BytePos, . time_stamp: usize, . ) { 17,253 ( 0.00%) if let Some((file, file_idx)) = new_file_and_idx { 4,474 ( 0.00%) self.file = file; 5,789 ( 0.00%) self.file_index = file_idx; . } . 11,611 ( 0.00%) let line_index = self.file.lookup_line(pos).unwrap(); . let line_bounds = self.file.line_bounds(line_index); 30,064 ( 0.00%) self.line_number = line_index + 1; 44,512 ( 0.00%) self.line = line_bounds; . self.touch(time_stamp); . } . . #[inline] . fn touch(&mut self, time_stamp: usize) { 638,795 ( 0.01%) self.time_stamp = time_stamp; . } . } . . #[derive(Clone)] . pub struct CachingSourceMapView<'sm> { . source_map: &'sm SourceMap, . line_cache: [CacheEntry; 3], . time_stamp: usize, . } . . impl<'sm> CachingSourceMapView<'sm> { 2,274 ( 0.00%) pub fn new(source_map: &'sm SourceMap) -> CachingSourceMapView<'sm> { . let files = source_map.files(); 1,137 ( 0.00%) let first_file = files[0].clone(); . let entry = CacheEntry { . time_stamp: 0, . line_number: 0, . line: BytePos(0)..BytePos(0), . file: first_file, . file_index: 0, . }; . 5,685 ( 0.00%) CachingSourceMapView { . source_map, 7,959 ( 0.00%) line_cache: [entry.clone(), entry.clone(), entry], . time_stamp: 0, . } 4,548 ( 0.00%) } . . pub fn byte_pos_to_line_and_col( . &mut self, . pos: BytePos, . ) -> Option<(Lrc, usize, BytePos)> { . self.time_stamp += 1; . . // Check if the position is in one of the cached lines -- line 85 ---------------------------------------- -- line 106 ---------------------------------------- . }; . . let cache_entry = &mut self.line_cache[oldest]; . cache_entry.update(new_file_and_idx, pos, self.time_stamp); . . Some((cache_entry.file.clone(), cache_entry.line_number, pos - cache_entry.line.start)) . } . 2,284,709 ( 0.03%) pub fn span_data_to_lines_and_cols( . &mut self, . span_data: &SpanData, . ) -> Option<(Lrc, usize, BytePos, usize, BytePos)> { 1,305,548 ( 0.02%) self.time_stamp += 1; . . // Check if lo and hi are in the cached lines. 326,387 ( 0.00%) let lo_cache_idx = self.cache_entry_index(span_data.lo); 326,387 ( 0.00%) let hi_cache_idx = self.cache_entry_index(span_data.hi); . 625,022 ( 0.01%) if lo_cache_idx != -1 && hi_cache_idx != -1 { . // Cache hit for span lo and hi. Check if they belong to the same file. . let result = { 624,816 ( 0.01%) let lo = &self.line_cache[lo_cache_idx as usize]; . let hi = &self.line_cache[hi_cache_idx as usize]; . 1,874,448 ( 0.03%) if lo.file_index != hi.file_index { . return None; . } . . ( 624,816 ( 0.01%) lo.file.clone(), . lo.line_number, . span_data.lo - lo.line.start, 312,408 ( 0.00%) hi.line_number, . span_data.hi - hi.line.start, . ) . }; . 312,408 ( 0.00%) self.line_cache[lo_cache_idx as usize].touch(self.time_stamp); 312,408 ( 0.00%) self.line_cache[hi_cache_idx as usize].touch(self.time_stamp); . 1,249,632 ( 0.02%) return Some(result); . } . . // No cache hit or cache hit for only one of span lo and hi. 27,752 ( 0.00%) let oldest = if lo_cache_idx != -1 || hi_cache_idx != -1 { . let avoid_idx = if lo_cache_idx != -1 { lo_cache_idx } else { hi_cache_idx }; . self.oldest_cache_entry_index_avoid(avoid_idx as usize) . } else { . self.oldest_cache_entry_index() . }; . . // If the entry doesn't point to the correct file, get the new file and index. . // Return early if the file containing beginning of span doesn't contain end of span. 111,556 ( 0.00%) let new_file_and_idx = if !file_contains(&self.line_cache[oldest].file, span_data.lo) { 11,840 ( 0.00%) let new_file_and_idx = self.file_for_position(span_data.lo)?; 14,208 ( 0.00%) if !file_contains(&new_file_and_idx.0, span_data.hi) { . return None; . } . 9,472 ( 0.00%) Some(new_file_and_idx) . } else { . let file = &self.line_cache[oldest].file; 34,833 ( 0.00%) if !file_contains(&file, span_data.hi) { . return None; . } . 34,833 ( 0.00%) None . }; . . // Update the cache entries. 69,895 ( 0.00%) let (lo_idx, hi_idx) = match (lo_cache_idx, hi_cache_idx) { . // Oldest cache entry is for span_data.lo line. . (-1, -1) => { . let lo = &mut self.line_cache[oldest]; . lo.update(new_file_and_idx, span_data.lo, self.time_stamp); . 36,717 ( 0.00%) if !lo.line.contains(&span_data.hi) { . let new_file_and_idx = Some((lo.file.clone(), lo.file_index)); . let next_oldest = self.oldest_cache_entry_index_avoid(oldest); . let hi = &mut self.line_cache[next_oldest]; . hi.update(new_file_and_idx, span_data.hi, self.time_stamp); . (oldest, next_oldest) . } else { . (oldest, oldest) . } . } . // Oldest cache entry is for span_data.lo line. . (-1, _) => { . let lo = &mut self.line_cache[oldest]; . lo.update(new_file_and_idx, span_data.lo, self.time_stamp); 206 ( 0.00%) let hi = &mut self.line_cache[hi_cache_idx as usize]; 309 ( 0.00%) hi.touch(self.time_stamp); . (oldest, hi_cache_idx as usize) . } . // Oldest cache entry is for span_data.hi line. . (_, -1) => { . let hi = &mut self.line_cache[oldest]; 1,637 ( 0.00%) hi.update(new_file_and_idx, span_data.hi, self.time_stamp); 3,274 ( 0.00%) let lo = &mut self.line_cache[lo_cache_idx as usize]; 6,548 ( 0.00%) lo.touch(self.time_stamp); . (lo_cache_idx as usize, oldest) . } . _ => { . panic!(); . } . }; . . let lo = &self.line_cache[lo_idx]; . let hi = &self.line_cache[hi_idx]; . . // Span lo and hi may equal line end when last line doesn't . // end in newline, hence the inclusive upper bounds below. 27,958 ( 0.00%) assert!(span_data.lo >= lo.line.start); 13,979 ( 0.00%) assert!(span_data.lo <= lo.line.end); 27,958 ( 0.00%) assert!(span_data.hi >= hi.line.start); 13,979 ( 0.00%) assert!(span_data.hi <= hi.line.end); 69,895 ( 0.00%) assert!(lo.file.contains(span_data.lo)); 41,937 ( 0.00%) assert!(lo.file.contains(span_data.hi)); 41,937 ( 0.00%) assert_eq!(lo.file_index, hi.file_index); . 41,937 ( 0.00%) Some(( 13,979 ( 0.00%) lo.file.clone(), . lo.line_number, . span_data.lo - lo.line.start, 13,979 ( 0.00%) hi.line_number, . span_data.hi - hi.line.start, . )) 2,937,483 ( 0.04%) } . . fn cache_entry_index(&self, pos: BytePos) -> isize { . for (idx, cache_entry) in self.line_cache.iter().enumerate() { 3,872,810 ( 0.06%) if cache_entry.line.contains(&pos) { . return idx as isize; . } . } . . -1 . } . . fn oldest_cache_entry_index(&self) -> usize { . let mut oldest = 0; . . for idx in 1..self.line_cache.len() { 73,434 ( 0.00%) if self.line_cache[idx].time_stamp < self.line_cache[oldest].time_stamp { . oldest = idx; . } . } . . oldest . } . . fn oldest_cache_entry_index_avoid(&self, avoid_idx: usize) -> usize { . let mut oldest = if avoid_idx != 0 { 0 } else { 1 }; . . for idx in 0..self.line_cache.len() { 17,005 ( 0.00%) if idx != avoid_idx 9,050 ( 0.00%) && self.line_cache[idx].time_stamp < self.line_cache[oldest].time_stamp . { . oldest = idx; . } . } . . oldest . } . 11,840 ( 0.00%) fn file_for_position(&self, pos: BytePos) -> Option<(Lrc, usize)> { 2,368 ( 0.00%) if !self.source_map.files().is_empty() { 4,736 ( 0.00%) let file_idx = self.source_map.lookup_source_file_idx(pos); . let file = &self.source_map.files()[file_idx]; . 18,944 ( 0.00%) if file_contains(file, pos) { . return Some((file.clone(), file_idx)); . } . } . . None 11,840 ( 0.00%) } . } . . #[inline] . fn file_contains(file: &SourceFile, pos: BytePos) -> bool { . // `SourceMap::lookup_source_file_idx` and `SourceFile::contains` both consider the position . // one past the end of a file to belong to it. Normally, that's what we want. But for the . // purposes of converting a byte position to a line and column number, we can't come up with a . // line and column number if the file is empty, because an empty file doesn't contain any -- line 290 ---------------------------------------- 3,474,151 ( 0.05%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs -------------------------------------------------------------------------------- Ir -- line 84 ---------------------------------------- . pub struct SessionGlobals { . symbol_interner: symbol::Interner, . span_interner: Lock, . hygiene_data: Lock, . source_map: Lock>>, . } . . impl SessionGlobals { 12 ( 0.00%) pub fn new(edition: Edition) -> SessionGlobals { 50 ( 0.00%) SessionGlobals { 2 ( 0.00%) symbol_interner: symbol::Interner::fresh(), . span_interner: Lock::new(span_encoding::SpanInterner::default()), 6 ( 0.00%) hygiene_data: Lock::new(hygiene::HygieneData::new(edition)), . source_map: Lock::new(None), . } 10 ( 0.00%) } . } . . #[inline] . pub fn create_session_globals_then(edition: Edition, f: impl FnOnce() -> R) -> R { 1 ( 0.00%) assert!( . !SESSION_GLOBALS.is_set(), . "SESSION_GLOBALS should never be overwritten! \ . Use another thread if you need another SessionGlobals" . ); 3 ( 0.00%) let session_globals = SessionGlobals::new(edition); 7 ( 0.00%) SESSION_GLOBALS.set(&session_globals, f) 1 ( 0.00%) } . . #[inline] . pub fn set_session_globals_then(session_globals: &SessionGlobals, f: impl FnOnce() -> R) -> R { . assert!( . !SESSION_GLOBALS.is_set(), . "SESSION_GLOBALS should never be overwritten! \ . Use another thread if you need another SessionGlobals" . ); -- line 119 ---------------------------------------- -- line 120 ---------------------------------------- . SESSION_GLOBALS.set(session_globals, f) . } . . #[inline] . pub fn create_default_session_if_not_set_then(f: F) -> R . where . F: FnOnce(&SessionGlobals) -> R, . { 4 ( 0.00%) create_session_if_not_set_then(edition::DEFAULT_EDITION, f) . } . . #[inline] . pub fn create_session_if_not_set_then(edition: Edition, f: F) -> R . where . F: FnOnce(&SessionGlobals) -> R, . { 1 ( 0.00%) if !SESSION_GLOBALS.is_set() { 3 ( 0.00%) let session_globals = SessionGlobals::new(edition); 11 ( 0.00%) SESSION_GLOBALS.set(&session_globals, || SESSION_GLOBALS.with(f)) 1 ( 0.00%) } else { . SESSION_GLOBALS.with(f) . } . } . . #[inline] . pub fn with_session_globals(f: F) -> R . where . F: FnOnce(&SessionGlobals) -> R, . { 408,409 ( 0.01%) SESSION_GLOBALS.with(f) . } . . #[inline] . pub fn create_default_session_globals_then(f: impl FnOnce() -> R) -> R { . create_session_globals_then(edition::DEFAULT_EDITION, f) . } . . // If this ever becomes non thread-local, `decode_syntax_context` . // and `decode_expn_id` will need to be updated to handle concurrent . // deserialization. . scoped_tls::scoped_thread_local!(static SESSION_GLOBALS: SessionGlobals); . . // FIXME: We should use this enum or something like it to get rid of the . // use of magic `/rust/1.x/...` paths across the board. 49 ( 0.00%) #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd)] 1,072 ( 0.00%) #[derive(Decodable)] . pub enum RealFileName { . LocalPath(PathBuf), . /// For remapped paths (namely paths into libstd that have been mapped . /// to the appropriate spot on the local host's file system, and local file . /// system paths that have been remapped with `FilePathMapping`), . Remapped { . /// `local_path` is the (host-dependent) local path to the file. This is . /// None if the file was imported from another crate -- line 173 ---------------------------------------- -- line 179 ---------------------------------------- . } . . impl Hash for RealFileName { . fn hash(&self, state: &mut H) { . // To prevent #70924 from happening again we should only hash the . // remapped (virtualized) path if that exists. This is because . // virtualized paths to sysroot crates (/rust/$hash or /rust/$version) . // remain stable even if the corresponding local_path changes 3,047 ( 0.00%) self.remapped_path_if_available().hash(state) . } . } . . // This is functionally identical to #[derive(Encodable)], with the exception of . // an added assert statement . impl Encodable for RealFileName { . fn encode(&self, encoder: &mut S) -> Result<(), S::Error> { 38 ( 0.00%) encoder.emit_enum(|encoder| match *self { . RealFileName::LocalPath(ref local_path) => { 152 ( 0.00%) encoder.emit_enum_variant("LocalPath", 0, 1, |encoder| { . encoder.emit_enum_variant_arg(true, |encoder| local_path.encode(encoder))?; . Ok(()) . }) . } . . RealFileName::Remapped { ref local_path, ref virtual_name } => encoder . .emit_enum_variant("Remapped", 1, 2, |encoder| { . // For privacy and build reproducibility, we must not embed host-dependant path in artifacts -- line 205 ---------------------------------------- -- line 224 ---------------------------------------- . p.as_ref().map(PathBuf::as_path) . } . } . } . . /// Returns the path suitable for reading from the file system on the local host, . /// if this information exists. . /// Avoid embedding this in build artifacts; see `remapped_path_if_available()` for that. 2 ( 0.00%) pub fn into_local_path(self) -> Option { 2 ( 0.00%) match self { . RealFileName::LocalPath(p) => Some(p), . RealFileName::Remapped { local_path: p, virtual_name: _ } => p, . } 3 ( 0.00%) } . . /// Returns the path suitable for embedding into build artifacts. This would still . /// be a local path if it has not been remapped. A remapped path will not correspond . /// to a valid file system path: see `local_path_if_available()` for something that . /// is more likely to return paths into the local host file system. . pub fn remapped_path_if_available(&self) -> &Path { 2,460 ( 0.00%) match self { . RealFileName::LocalPath(p) . | RealFileName::Remapped { local_path: _, virtual_name: p } => &p, . } 20 ( 0.00%) } . . /// Returns the path suitable for reading from the file system on the local host, . /// if this information exists. Otherwise returns the remapped name. . /// Avoid embedding this in build artifacts; see `remapped_path_if_available()` for that. . pub fn local_path_if_available(&self) -> &Path { 19 ( 0.00%) match self { . RealFileName::LocalPath(path) . | RealFileName::Remapped { local_path: None, virtual_name: path } . | RealFileName::Remapped { local_path: Some(path), virtual_name: _ } => path, . } . } . . pub fn to_string_lossy(&self, display_pref: FileNameDisplayPreference) -> Cow<'_, str> { 61 ( 0.00%) match display_pref { . FileNameDisplayPreference::Local => self.local_path_if_available().to_string_lossy(), . FileNameDisplayPreference::Remapped => { . self.remapped_path_if_available().to_string_lossy() . } . } . } . } . . /// Differentiates between real files and common virtual files. 6,319 ( 0.00%) #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash)] 6,719 ( 0.00%) #[derive(Decodable, Encodable)] . pub enum FileName { . Real(RealFileName), . /// Call to `quote!`. . QuoteExpansion(u64), . /// Command line. . Anon(u64), . /// Hack in `src/librustc_ast/parse.rs`. . // FIXME(jseyfried) -- line 281 ---------------------------------------- -- line 288 ---------------------------------------- . /// Custom sources for explicit parser calls from plugins and drivers. . Custom(String), . DocTest(PathBuf, isize), . /// Post-substitution inline assembly from LLVM. . InlineAsm(u64), . } . . impl From for FileName { 133 ( 0.00%) fn from(p: PathBuf) -> Self { 38 ( 0.00%) assert!(!p.to_string_lossy().ends_with('>')); 114 ( 0.00%) FileName::Real(RealFileName::LocalPath(p)) 133 ( 0.00%) } . } . 34 ( 0.00%) #[derive(Clone, Copy, Eq, PartialEq, Hash, Debug)] . pub enum FileNameDisplayPreference { . Remapped, . Local, . } . . pub struct FileNameDisplay<'a> { . inner: &'a FileName, . display_pref: FileNameDisplayPreference, . } . . impl fmt::Display for FileNameDisplay<'_> { 116 ( 0.00%) fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { . use FileName::*; 174 ( 0.00%) match *self.inner { . Real(ref name) => { 174 ( 0.00%) write!(fmt, "{}", name.to_string_lossy(self.display_pref)) . } . QuoteExpansion(_) => write!(fmt, ""), . MacroExpansion(_) => write!(fmt, ""), . Anon(_) => write!(fmt, ""), . ProcMacroSourceCode(_) => write!(fmt, ""), . CfgSpec(_) => write!(fmt, ""), . CliCrateAttr(_) => write!(fmt, ""), . Custom(ref s) => write!(fmt, "<{}>", s), . DocTest(ref path, _) => write!(fmt, "{}", path.display()), . InlineAsm(_) => write!(fmt, ""), . } 145 ( 0.00%) } . } . . impl FileNameDisplay<'_> { 128 ( 0.00%) pub fn to_string_lossy(&self) -> Cow<'_, str> { 96 ( 0.00%) match self.inner { 32 ( 0.00%) FileName::Real(ref inner) => inner.to_string_lossy(self.display_pref), . _ => Cow::from(format!("{}", self)), . } 128 ( 0.00%) } . } . . impl FileName { . pub fn is_real(&self) -> bool { . use FileName::*; 1,094 ( 0.00%) match *self { . Real(_) => true, . Anon(_) . | MacroExpansion(_) . | ProcMacroSourceCode(_) . | CfgSpec(_) . | CliCrateAttr(_) . | Custom(_) . | QuoteExpansion(_) . | DocTest(_, _) . | InlineAsm(_) => false, . } . } . 32 ( 0.00%) pub fn prefer_remapped(&self) -> FileNameDisplay<'_> { . FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Remapped } 64 ( 0.00%) } . . // This may include transient local filesystem information. . // Must not be embedded in build outputs. 19 ( 0.00%) pub fn prefer_local(&self) -> FileNameDisplay<'_> { . FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Local } 38 ( 0.00%) } . . pub fn display(&self, display_pref: FileNameDisplayPreference) -> FileNameDisplay<'_> { . FileNameDisplay { inner: self, display_pref } . } . . pub fn macro_expansion_source_code(src: &str) -> FileName { . let mut hasher = StableHasher::new(); . src.hash(&mut hasher); -- line 375 ---------------------------------------- -- line 423 ---------------------------------------- . /// that the length of the span is equal to `span.hi - span.lo`; there may be space in the . /// [`BytePos`] range between files. . /// . /// `SpanData` is public because `Span` uses a thread-local interner and can't be . /// sent to other threads, but some pieces of performance infra run in a separate thread. . /// Using `Span` is generally preferred. . #[derive(Clone, Copy, Hash, PartialEq, Eq)] . pub struct SpanData { 5 ( 0.00%) pub lo: BytePos, 5 ( 0.00%) pub hi: BytePos, . /// Information about where the macro came from, if this piece of . /// code was created by a macro expansion. 12 ( 0.00%) pub ctxt: SyntaxContext, 4 ( 0.00%) pub parent: Option, . } . . // Order spans by position in the file. . impl Ord for SpanData { . fn cmp(&self, other: &Self) -> Ordering { . let SpanData { . lo: s_lo, . hi: s_hi, -- line 444 ---------------------------------------- -- line 485 ---------------------------------------- . } . #[inline] . pub fn with_parent(&self, parent: Option) -> Span { . Span::new(self.lo, self.hi, self.ctxt, parent) . } . /// Returns `true` if this is a dummy span with any hygienic context. . #[inline] . pub fn is_dummy(self) -> bool { 1,194,605 ( 0.02%) self.lo.0 == 0 && self.hi.0 == 0 . } . /// Returns `true` if `self` fully encloses `other`. . pub fn contains(self, other: Self) -> bool { 1,230 ( 0.00%) self.lo <= other.lo && other.hi <= self.hi . } . } . . // The interner is pointed to by a thread local value which is only set on the main thread . // with parallelization is disabled. So we don't allow `Span` to transfer between threads . // to avoid panics and other errors, even though it would be memory safe to do so. . #[cfg(not(parallel_compiler))] . impl !Send for Span {} . #[cfg(not(parallel_compiler))] . impl !Sync for Span {} . . impl PartialOrd for Span { 43,152 ( 0.00%) fn partial_cmp(&self, rhs: &Self) -> Option { 32,364 ( 0.00%) PartialOrd::partial_cmp(&self.data(), &rhs.data()) 43,152 ( 0.00%) } . } . impl Ord for Span { . fn cmp(&self, rhs: &Self) -> Ordering { . Ord::cmp(&self.data(), &rhs.data()) . } . } . . /// A collection of `Span`s. -- line 520 ---------------------------------------- -- line 532 ---------------------------------------- . } . . impl Span { . #[inline] . pub fn lo(self) -> BytePos { . self.data().lo . } . #[inline] 61,857 ( 0.00%) pub fn with_lo(self, lo: BytePos) -> Span { . self.data().with_lo(lo) 41,238 ( 0.00%) } . #[inline] 2,136 ( 0.00%) pub fn hi(self) -> BytePos { . self.data().hi 2,136 ( 0.00%) } . #[inline] 9,828 ( 0.00%) pub fn with_hi(self, hi: BytePos) -> Span { . self.data().with_hi(hi) 6,552 ( 0.00%) } . #[inline] . pub fn ctxt(self) -> SyntaxContext { . self.data_untracked().ctxt . } . #[inline] 5,440 ( 0.00%) pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span { . self.data_untracked().with_ctxt(ctxt) 3,264 ( 0.00%) } . #[inline] . pub fn parent(self) -> Option { . self.data().parent . } . #[inline] . pub fn with_parent(self, ctxt: Option) -> Span { . self.data().with_parent(ctxt) . } -- line 566 ---------------------------------------- -- line 568 ---------------------------------------- . /// Returns `true` if this is a dummy span with any hygienic context. . #[inline] . pub fn is_dummy(self) -> bool { . self.data_untracked().is_dummy() . } . . /// Returns `true` if this span comes from a macro or desugaring. . #[inline] 12 ( 0.00%) pub fn from_expansion(self) -> bool { . self.ctxt() != SyntaxContext::root() 8 ( 0.00%) } . . /// Returns `true` if `span` originates in a derive-macro's expansion. . pub fn in_derive_expansion(self) -> bool { . matches!(self.ctxt().outer_expn_data().kind, ExpnKind::Macro(MacroKind::Derive, _)) . } . . /// Gate suggestions that would not be appropriate in a context the user didn't write. . pub fn can_be_used_for_suggestions(self) -> bool { -- line 586 ---------------------------------------- -- line 600 ---------------------------------------- . /// Returns a new span representing an empty span at the beginning of this span. . #[inline] . pub fn shrink_to_lo(self) -> Span { . let span = self.data_untracked(); . span.with_hi(span.lo) . } . /// Returns a new span representing an empty span at the end of this span. . #[inline] 117 ( 0.00%) pub fn shrink_to_hi(self) -> Span { . let span = self.data_untracked(); . span.with_lo(span.hi) 78 ( 0.00%) } . . #[inline] . /// Returns `true` if `hi == lo`. . pub fn is_empty(self) -> bool { . let span = self.data_untracked(); . span.hi == span.lo . } . . /// Returns `self` if `self` is not the dummy span, and `other` otherwise. . pub fn substitute_dummy(self, other: Span) -> Span { . if self.is_dummy() { other } else { self } . } . . /// Returns `true` if `self` fully encloses `other`. 3,690 ( 0.00%) pub fn contains(self, other: Span) -> bool { . let span = self.data(); . let other = other.data(); . span.contains(other) 2,460 ( 0.00%) } . . /// Returns `true` if `self` touches `other`. . pub fn overlaps(self, other: Span) -> bool { . let span = self.data(); . let other = other.data(); . span.lo < other.hi && other.lo < span.hi . } . -- line 638 ---------------------------------------- -- line 663 ---------------------------------------- . /// The `Span` for the tokens in the previous macro expansion from which `self` was generated, . /// if any. . pub fn parent_callsite(self) -> Option { . let expn_data = self.ctxt().outer_expn_data(); . if !expn_data.is_root() { Some(expn_data.call_site) } else { None } . } . . /// Walk down the expansion ancestors to find a span that's contained within `outer`. 2,350 ( 0.00%) pub fn find_ancestor_inside(mut self, outer: Span) -> Option { 1,175 ( 0.00%) while !outer.contains(self) { . self = self.parent_callsite()?; . } . Some(self) 2,585 ( 0.00%) } . . /// Edition of the crate from which this span came. 16,041 ( 0.00%) pub fn edition(self) -> edition::Edition { . self.ctxt().edition() 10,694 ( 0.00%) } . . #[inline] . pub fn rust_2015(self) -> bool { 3,239 ( 0.00%) self.edition() == edition::Edition::Edition2015 . } . . #[inline] . pub fn rust_2018(self) -> bool { 2,252 ( 0.00%) self.edition() >= edition::Edition::Edition2018 . } . . #[inline] . pub fn rust_2021(self) -> bool { 1,734 ( 0.00%) self.edition() >= edition::Edition::Edition2021 . } . . /// Returns the source callee. . /// . /// Returns `None` if the supplied span has no expansion trace, . /// else returns the `ExpnData` for the macro definition . /// corresponding to the source callsite. . pub fn source_callee(self) -> Option { -- line 703 ---------------------------------------- -- line 707 ---------------------------------------- . } . let expn_data = self.ctxt().outer_expn_data(); . if !expn_data.is_root() { Some(source_callee(expn_data)) } else { None } . } . . /// Checks if a span is "internal" to a macro in which `#[unstable]` . /// items can be used (that is, a macro marked with . /// `#[allow_internal_unstable]`). 4,005 ( 0.00%) pub fn allows_unstable(self, feature: Symbol) -> bool { 801 ( 0.00%) self.ctxt() . .outer_expn_data() . .allow_internal_unstable . .map_or(false, |features| features.iter().any(|&f| f == feature)) 3,204 ( 0.00%) } . . /// Checks if this span arises from a compiler desugaring of kind `kind`. 6,776 ( 0.00%) pub fn is_desugaring(self, kind: DesugaringKind) -> bool { 5,808 ( 0.00%) match self.ctxt().outer_expn_data().kind { . ExpnKind::Desugaring(k) => k == kind, . _ => false, . } 4,840 ( 0.00%) } . . /// Returns the compiler desugaring that created this span, or `None` . /// if this span is not from a desugaring. 315 ( 0.00%) pub fn desugaring_kind(self) -> Option { 378 ( 0.00%) match self.ctxt().outer_expn_data().kind { . ExpnKind::Desugaring(k) => Some(k), . _ => None, . } 252 ( 0.00%) } . . /// Checks if a span is "internal" to a macro in which `unsafe` . /// can be used without triggering the `unsafe_code` lint. . // (that is, a macro marked with `#[allow_internal_unsafe]`). 68 ( 0.00%) pub fn allows_unsafe(self) -> bool { 17 ( 0.00%) self.ctxt().outer_expn_data().allow_internal_unsafe 68 ( 0.00%) } . . pub fn macro_backtrace(mut self) -> impl Iterator { . let mut prev_span = DUMMY_SP; . std::iter::from_fn(move || { . loop { . let expn_data = self.ctxt().outer_expn_data(); . if expn_data.is_root() { . return None; -- line 752 ---------------------------------------- -- line 767 ---------------------------------------- . . /// Returns a `Span` that would enclose both `self` and `end`. . /// . /// ```text . /// ____ ___ . /// self lorem ipsum end . /// ^^^^^^^^^^^^^^^^^^^^ . /// ``` 1,796,080 ( 0.03%) pub fn to(self, end: Span) -> Span { . let span_data = self.data(); . let end_data = end.data(); . // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480). . // Return the macro span on its own to avoid weird diagnostic output. It is preferable to . // have an incomplete span than a completely nonsensical one. 325,684 ( 0.00%) if span_data.ctxt != end_data.ctxt { 876 ( 0.00%) if span_data.ctxt == SyntaxContext::root() { . return end; 808 ( 0.00%) } else if end_data.ctxt == SyntaxContext::root() { . return self; . } . // Both spans fall within a macro. . // FIXME(estebank): check if it is the *same* macro. . } . Span::new( . cmp::min(span_data.lo, end_data.lo), . cmp::max(span_data.hi, end_data.hi), . if span_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt }, 1,136,905 ( 0.02%) if span_data.parent == end_data.parent { span_data.parent } else { None }, . ) 1,469,520 ( 0.02%) } . . /// Returns a `Span` between the end of `self` to the beginning of `end`. . /// . /// ```text . /// ____ ___ . /// self lorem ipsum end . /// ^^^^^^^^^^^^^ . /// ``` 550 ( 0.00%) pub fn between(self, end: Span) -> Span { . let span = self.data(); . let end = end.data(); . Span::new( . span.hi, . end.lo, . if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt }, 350 ( 0.00%) if span.parent == end.parent { span.parent } else { None }, . ) 400 ( 0.00%) } . . /// Returns a `Span` from the beginning of `self` until the beginning of `end`. . /// . /// ```text . /// ____ ___ . /// self lorem ipsum end . /// ^^^^^^^^^^^^^^^^^ . /// ``` 2,431 ( 0.00%) pub fn until(self, end: Span) -> Span { . // Most of this function's body is copied from `to`. . // We can't just do `self.to(end.shrink_to_lo())`, . // because to also does some magic where it uses min/max so . // it can handle overlapping spans. Some advanced mis-use of . // `until` with different ctxts makes this visible. . let span_data = self.data(); . let end_data = end.data(); . // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480). . // Return the macro span on its own to avoid weird diagnostic output. It is preferable to . // have an incomplete span than a completely nonsensical one. 442 ( 0.00%) if span_data.ctxt != end_data.ctxt { . if span_data.ctxt == SyntaxContext::root() { . return end; . } else if end_data.ctxt == SyntaxContext::root() { . return self; . } . // Both spans fall within a macro. . // FIXME(estebank): check if it is the *same* macro. . } . Span::new( . span_data.lo, . end_data.lo, . if end_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt }, 1,547 ( 0.00%) if span_data.parent == end_data.parent { span_data.parent } else { None }, . ) 1,989 ( 0.00%) } . 693 ( 0.00%) pub fn from_inner(self, inner: InnerSpan) -> Span { . let span = self.data(); . Span::new( . span.lo + BytePos::from_usize(inner.start), . span.lo + BytePos::from_usize(inner.end), . span.ctxt, . span.parent, . ) 441 ( 0.00%) } . . /// Equivalent of `Span::def_site` from the proc macro API, . /// except that the location is taken from the `self` span. . pub fn with_def_site_ctxt(self, expn_id: ExpnId) -> Span { 1,970 ( 0.00%) self.with_ctxt_from_mark(expn_id, Transparency::Opaque) . } . . /// Equivalent of `Span::call_site` from the proc macro API, . /// except that the location is taken from the `self` span. . pub fn with_call_site_ctxt(self, expn_id: ExpnId) -> Span { 16 ( 0.00%) self.with_ctxt_from_mark(expn_id, Transparency::Transparent) . } . . /// Equivalent of `Span::mixed_site` from the proc macro API, . /// except that the location is taken from the `self` span. . pub fn with_mixed_site_ctxt(self, expn_id: ExpnId) -> Span { . self.with_ctxt_from_mark(expn_id, Transparency::SemiTransparent) . } . . /// Produces a span with the same location as `self` and context produced by a macro with the . /// given ID and transparency, assuming that macro was defined directly and not produced by . /// some other macro (which is the case for built-in and procedural macros). 11,916 ( 0.00%) pub fn with_ctxt_from_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span { . self.with_ctxt(SyntaxContext::root().apply_mark(expn_id, transparency)) 6,951 ( 0.00%) } . . #[inline] . pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span { . let span = self.data(); 23,130 ( 0.00%) span.with_ctxt(span.ctxt.apply_mark(expn_id, transparency)) . } . . #[inline] . pub fn remove_mark(&mut self) -> ExpnId { . let mut span = self.data(); . let mark = span.ctxt.remove_mark(); . *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark -- line 897 ---------------------------------------- -- line 901 ---------------------------------------- . pub fn adjust(&mut self, expn_id: ExpnId) -> Option { . let mut span = self.data(); . let mark = span.ctxt.adjust(expn_id); . *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark . } . . #[inline] 67,653 ( 0.00%) pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option { 45,102 ( 0.00%) let mut span = self.data(); 37,399 ( 0.00%) let mark = span.ctxt.normalize_to_macros_2_0_and_adjust(expn_id); 67,653 ( 0.00%) *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark 74,984 ( 0.00%) } . . #[inline] . pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option> { . let mut span = self.data(); . let mark = span.ctxt.glob_adjust(expn_id, glob_span); . *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark . } -- line 922 ---------------------------------------- -- line 929 ---------------------------------------- . ) -> Option> { . let mut span = self.data(); . let mark = span.ctxt.reverse_glob_adjust(expn_id, glob_span); . *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark . } . . #[inline] 35,664 ( 0.00%) pub fn normalize_to_macros_2_0(self) -> Span { . let span = self.data(); . span.with_ctxt(span.ctxt.normalize_to_macros_2_0()) 31,206 ( 0.00%) } . . #[inline] . pub fn normalize_to_macro_rules(self) -> Span { . let span = self.data(); . span.with_ctxt(span.ctxt.normalize_to_macro_rules()) . } . } . -- line 948 ---------------------------------------- -- line 958 ---------------------------------------- . . /// What label should we attach to this span (if any)? . pub label: Option, . } . . impl Default for Span { . fn default() -> Self { . DUMMY_SP 2 ( 0.00%) } . } . . impl Encodable for Span { . default fn encode(&self, s: &mut E) -> Result<(), E::Error> { . let span = self.data(); . s.emit_struct(false, |s| { . s.emit_struct_field("lo", true, |s| span.lo.encode(s))?; . s.emit_struct_field("hi", false, |s| span.hi.encode(s)) -- line 974 ---------------------------------------- -- line 990 ---------------------------------------- . /// any spans that are debug-printed during the closure's execution. . /// . /// Normally, the global `TyCtxt` is used to retrieve the `SourceMap` . /// (see `rustc_interface::callbacks::span_debug1`). However, some parts . /// of the compiler (e.g. `rustc_parse`) may debug-print `Span`s before . /// a `TyCtxt` is available. In this case, we fall back to . /// the `SourceMap` provided to this function. If that is not available, . /// we fall back to printing the raw `Span` field values. 9 ( 0.00%) pub fn with_source_map T>(source_map: Lrc, f: F) -> T { . with_session_globals(|session_globals| { 2 ( 0.00%) *session_globals.source_map.borrow_mut() = Some(source_map); . }); . struct ClearSourceMap; . impl Drop for ClearSourceMap { . fn drop(&mut self) { . with_session_globals(|session_globals| { 1 ( 0.00%) session_globals.source_map.borrow_mut().take(); . }); . } . } . . let _guard = ClearSourceMap; 4 ( 0.00%) f() 8 ( 0.00%) } . . pub fn debug_with_source_map( . span: Span, . f: &mut fmt::Formatter<'_>, . source_map: &SourceMap, . ) -> fmt::Result { . write!(f, "{} ({:?})", source_map.span_to_diagnostic_string(span), span.ctxt()) . } -- line 1021 ---------------------------------------- -- line 1048 ---------------------------------------- . . impl MultiSpan { . #[inline] . pub fn new() -> MultiSpan { . MultiSpan { primary_spans: vec![], span_labels: vec![] } . } . . pub fn from_span(primary_span: Span) -> MultiSpan { 4,065 ( 0.00%) MultiSpan { primary_spans: vec![primary_span], span_labels: vec![] } . } . . pub fn from_spans(mut vec: Vec) -> MultiSpan { . vec.sort(); 185 ( 0.00%) MultiSpan { primary_spans: vec, span_labels: vec![] } . } . . pub fn push_span_label(&mut self, span: Span, label: String) { . self.span_labels.push((span, label)); . } . . /// Selects the first primary span (if any). . pub fn primary_span(&self) -> Option { . self.primary_spans.first().cloned() 154 ( 0.00%) } . . /// Returns all primary spans. . pub fn primary_spans(&self) -> &[Span] { . &self.primary_spans . } . . /// Returns `true` if any of the primary spans are displayable. . pub fn has_primary_spans(&self) -> bool { -- line 1079 ---------------------------------------- -- line 1139 ---------------------------------------- . . /// Returns `true` if any of the span labels is displayable. . pub fn has_span_labels(&self) -> bool { . self.span_labels.iter().any(|(sp, _)| !sp.is_dummy()) . } . } . . impl From for MultiSpan { 4,065 ( 0.00%) fn from(span: Span) -> MultiSpan { . MultiSpan::from_span(span) 4,065 ( 0.00%) } . } . . impl From> for MultiSpan { 185 ( 0.00%) fn from(spans: Vec) -> MultiSpan { 148 ( 0.00%) MultiSpan::from_spans(spans) 185 ( 0.00%) } . } . . /// Identifies an offset of a multi-byte character in a `SourceFile`. 462 ( 0.00%) #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)] . pub struct MultiByteChar { . /// The absolute offset of the character in the `SourceMap`. . pub pos: BytePos, . /// The number of bytes, `>= 2`. . pub bytes: u8, . } . . /// Identifies an offset of a non-narrow character in a `SourceFile`. 463 ( 0.00%) #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)] . pub enum NonNarrowChar { . /// Represents a zero-width character. . ZeroWidth(BytePos), . /// Represents a wide (full-width) character. . Wide(BytePos), . /// Represents a tab character, represented visually with a width of 4 characters. . Tab(BytePos), . } . . impl NonNarrowChar { . fn new(pos: BytePos, width: usize) -> Self { 44 ( 0.00%) match width { . 0 => NonNarrowChar::ZeroWidth(pos), . 2 => NonNarrowChar::Wide(pos), . 4 => NonNarrowChar::Tab(pos), . _ => panic!("width {} given for non-narrow character", width), . } . } . . /// Returns the absolute offset of the character in the `SourceMap`. -- line 1188 ---------------------------------------- -- line 1201 ---------------------------------------- . } . } . } . . impl Add for NonNarrowChar { . type Output = Self; . . fn add(self, rhs: BytePos) -> Self { 556 ( 0.00%) match self { . NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs), . NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs), . NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs), . } . } . } . . impl Sub for NonNarrowChar { . type Output = Self; . 160 ( 0.00%) fn sub(self, rhs: BytePos) -> Self { 556 ( 0.00%) match self { . NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs), . NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs), . NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs), . } 480 ( 0.00%) } . } . . /// Identifies an offset of a character that was normalized away from `SourceFile`. . #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)] . pub struct NormalizedPos { . /// The absolute offset of the character in the `SourceMap`. . pub pos: BytePos, . /// The difference between original and normalized string at position. . pub diff: u32, . } . 57 ( 0.00%) #[derive(PartialEq, Eq, Clone, Debug)] . pub enum ExternalSource { . /// No external source has to be loaded, since the `SourceFile` represents a local crate. . Unneeded, . Foreign { . kind: ExternalSourceKind, . /// This SourceFile's byte-offset within the source_map of its original crate. . original_start_pos: BytePos, . /// The end of this SourceFile within the source_map of its original crate. -- line 1246 ---------------------------------------- -- line 1257 ---------------------------------------- . AbsentOk, . /// A failed attempt has been made to load the external source. . AbsentErr, . Unneeded, . } . . impl ExternalSource { . pub fn get_source(&self) -> Option<&Lrc> { 630 ( 0.00%) match self { . ExternalSource::Foreign { kind: ExternalSourceKind::Present(ref src), .. } => Some(src), . _ => None, . } . } . } . . #[derive(Debug)] . pub struct OffsetOverflowError; . 1,088 ( 0.00%) #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)] . pub enum SourceFileHashAlgorithm { . Md5, . Sha1, . Sha256, . } . . impl FromStr for SourceFileHashAlgorithm { . type Err = (); -- line 1283 ---------------------------------------- -- line 1290 ---------------------------------------- . _ => Err(()), . } . } . } . . rustc_data_structures::impl_stable_hash_via_hash!(SourceFileHashAlgorithm); . . /// The hash of the on-disk source file used for debug info. 114 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, Debug)] 2,176 ( 0.00%) #[derive(HashStable_Generic, Encodable, Decodable)] . pub struct SourceFileHash { . pub kind: SourceFileHashAlgorithm, . value: [u8; 32], . } . . impl SourceFileHash { . pub fn new(kind: SourceFileHashAlgorithm, src: &str) -> SourceFileHash { . let mut hash = SourceFileHash { kind, value: Default::default() }; . let len = hash.hash_len(); . let value = &mut hash.value[..len]; . let data = src.as_bytes(); . match kind { . SourceFileHashAlgorithm::Md5 => { 57 ( 0.00%) value.copy_from_slice(&Md5::digest(data)); . } . SourceFileHashAlgorithm::Sha1 => { . value.copy_from_slice(&Sha1::digest(data)); . } . SourceFileHashAlgorithm::Sha256 => { . value.copy_from_slice(&Sha256::digest(data)); . } . } -- line 1321 ---------------------------------------- -- line 1329 ---------------------------------------- . . /// The bytes of the hash. . pub fn hash_bytes(&self) -> &[u8] { . let len = self.hash_len(); . &self.value[..len] . } . . fn hash_len(&self) -> usize { 57 ( 0.00%) match self.kind { . SourceFileHashAlgorithm::Md5 => 16, . SourceFileHashAlgorithm::Sha1 => 20, . SourceFileHashAlgorithm::Sha256 => 32, . } . } . } . . /// A single source in the [`SourceMap`]. 1,102 ( 0.00%) #[derive(Clone)] . pub struct SourceFile { . /// The name of the file that the source came from. Source that doesn't . /// originate from files has names between angle brackets by convention . /// (e.g., ``). . pub name: FileName, . /// The complete source code. 19 ( 0.00%) pub src: Option>, . /// The source code's hash. . pub src_hash: SourceFileHash, . /// The external source code (used for external crates, which will have a `None` . /// value as `self.src`. . pub external_src: Lock, . /// The start position of this source in the `SourceMap`. . pub start_pos: BytePos, . /// The end position of this source in the `SourceMap`. -- line 1361 ---------------------------------------- -- line 1364 ---------------------------------------- . pub lines: Vec, . /// Locations of multi-byte characters in the source code. . pub multibyte_chars: Vec, . /// Width of characters that are not narrow in the source code. . pub non_narrow_chars: Vec, . /// Locations of characters removed during normalization. . pub normalized_pos: Vec, . /// A hash of the filename, used for speeding up hashing in incremental compilation. 19 ( 0.00%) pub name_hash: u128, . /// Indicates which crate this `SourceFile` was imported from. 19 ( 0.00%) pub cnum: CrateNum, . } . . impl Encodable for SourceFile { . fn encode(&self, s: &mut S) -> Result<(), S::Error> { . s.emit_struct(false, |s| { . s.emit_struct_field("name", true, |s| self.name.encode(s))?; . s.emit_struct_field("src_hash", false, |s| self.src_hash.encode(s))?; . s.emit_struct_field("start_pos", false, |s| self.start_pos.encode(s))?; . s.emit_struct_field("end_pos", false, |s| self.end_pos.encode(s))?; . s.emit_struct_field("lines", false, |s| { . let lines = &self.lines[..]; . // Store the length. . s.emit_u32(lines.len() as u32)?; . 76 ( 0.00%) if !lines.is_empty() { . // In order to preserve some space, we exploit the fact that . // the lines list is sorted and individual lines are . // probably not that long. Because of that we can store lines . // as a difference list, using as little space as possible . // for the differences. . let max_line_length = if lines.len() == 1 { . 0 . } else { -- line 1397 ---------------------------------------- -- line 1399 ---------------------------------------- . .array_windows() . .map(|&[fst, snd]| snd - fst) . .map(|bp| bp.to_usize()) . .max() . .unwrap() . }; . . let bytes_per_diff: u8 = match max_line_length { 38 ( 0.00%) 0..=0xFF => 1, . 0x100..=0xFFFF => 2, . _ => 4, . }; . . // Encode the number of bytes used per diff. . bytes_per_diff.encode(s)?; . . // Encode the first element. . lines[0].encode(s)?; . . let diff_iter = lines.array_windows().map(|&[fst, snd]| snd - fst); . 38 ( 0.00%) match bytes_per_diff { . 1 => { . for diff in diff_iter { . (diff.0 as u8).encode(s)? . } . } . 2 => { . for diff in diff_iter { . (diff.0 as u16).encode(s)? -- line 1428 ---------------------------------------- -- line 1436 ---------------------------------------- . _ => unreachable!(), . } . } . . Ok(()) . })?; . s.emit_struct_field("multibyte_chars", false, |s| self.multibyte_chars.encode(s))?; . s.emit_struct_field("non_narrow_chars", false, |s| self.non_narrow_chars.encode(s))?; 57 ( 0.00%) s.emit_struct_field("name_hash", false, |s| self.name_hash.encode(s))?; . s.emit_struct_field("normalized_pos", false, |s| self.normalized_pos.encode(s))?; 209 ( 0.00%) s.emit_struct_field("cnum", false, |s| self.cnum.encode(s)) . }) . } . } . . impl Decodable for SourceFile { 4,896 ( 0.00%) fn decode(d: &mut D) -> SourceFile { . d.read_struct(|d| { . let name: FileName = d.read_struct_field("name", |d| Decodable::decode(d)); . let src_hash: SourceFileHash = . d.read_struct_field("src_hash", |d| Decodable::decode(d)); . let start_pos: BytePos = d.read_struct_field("start_pos", |d| Decodable::decode(d)); . let end_pos: BytePos = d.read_struct_field("end_pos", |d| Decodable::decode(d)); . let lines: Vec = d.read_struct_field("lines", |d| { . let num_lines: u32 = Decodable::decode(d); 544 ( 0.00%) let mut lines = Vec::with_capacity(num_lines as usize); . . if num_lines > 0 { . // Read the number of bytes used per diff. . let bytes_per_diff: u8 = Decodable::decode(d); . . // Read the first element. . let mut line_start: BytePos = Decodable::decode(d); . lines.push(line_start); . . for _ in 1..num_lines { 893,018 ( 0.01%) let diff = match bytes_per_diff { . 1 => d.read_u8() as u32, . 2 => d.read_u16() as u32, . 4 => d.read_u32(), . _ => unreachable!(), . }; . . line_start = line_start + BytePos(diff); . -- line 1480 ---------------------------------------- -- line 1483 ---------------------------------------- . } . . lines . }); . let multibyte_chars: Vec = . d.read_struct_field("multibyte_chars", |d| Decodable::decode(d)); . let non_narrow_chars: Vec = . d.read_struct_field("non_narrow_chars", |d| Decodable::decode(d)); 1,088 ( 0.00%) let name_hash: u128 = d.read_struct_field("name_hash", |d| Decodable::decode(d)); . let normalized_pos: Vec = . d.read_struct_field("normalized_pos", |d| Decodable::decode(d)); . let cnum: CrateNum = d.read_struct_field("cnum", |d| Decodable::decode(d)); 5,984 ( 0.00%) SourceFile { 4,352 ( 0.00%) name, . start_pos, . end_pos, . src: None, 2,176 ( 0.00%) src_hash, . // Unused - the metadata decoder will construct . // a new SourceFile, filling in `external_src` properly . external_src: Lock::new(ExternalSource::Unneeded), 2,176 ( 0.00%) lines, 2,176 ( 0.00%) multibyte_chars, 2,176 ( 0.00%) non_narrow_chars, 2,176 ( 0.00%) normalized_pos, . name_hash, . cnum, . } . }) 4,896 ( 0.00%) } . } . . impl fmt::Debug for SourceFile { . fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { . write!(fmt, "SourceFile({:?})", self.name) . } . } . . impl SourceFile { 209 ( 0.00%) pub fn new( . name: FileName, . mut src: String, . start_pos: BytePos, . hash_kind: SourceFileHashAlgorithm, . ) -> Self { . // Compute the file hash before any normalization. . let src_hash = SourceFileHash::new(hash_kind, &src); 57 ( 0.00%) let normalized_pos = normalize_src(&mut src, start_pos); . . let name_hash = { . let mut hasher: StableHasher = StableHasher::new(); 38 ( 0.00%) name.hash(&mut hasher); . hasher.finish::() . }; 38 ( 0.00%) let end_pos = start_pos.to_usize() + src.len(); 57 ( 0.00%) assert!(end_pos <= u32::MAX as usize); . 228 ( 0.00%) let (lines, multibyte_chars, non_narrow_chars) = 38 ( 0.00%) analyze_source_file::analyze_source_file(&src, start_pos); . 323 ( 0.00%) SourceFile { . name, . src: Some(Lrc::new(src)), 209 ( 0.00%) src_hash, . external_src: Lock::new(ExternalSource::Unneeded), . start_pos, . end_pos: Pos::from_usize(end_pos), 76 ( 0.00%) lines, 76 ( 0.00%) multibyte_chars, 76 ( 0.00%) non_narrow_chars, 76 ( 0.00%) normalized_pos, . name_hash, . cnum: LOCAL_CRATE, . } 171 ( 0.00%) } . . /// Returns the `BytePos` of the beginning of the current line. . pub fn line_begin_pos(&self, pos: BytePos) -> BytePos { . let line_index = self.lookup_line(pos).unwrap(); . self.lines[line_index] . } . . /// Add externally loaded source. . /// If the hash of the input doesn't match or no input is supplied via None, . /// it is interpreted as an error and the corresponding enum variant is set. . /// The return value signifies whether some kind of source is present. 2,331 ( 0.00%) pub fn add_external_src(&self, get_src: F) -> bool . where . F: FnOnce() -> Option, . { 333 ( 0.00%) if matches!( 666 ( 0.00%) *self.external_src.borrow(), . ExternalSource::Foreign { kind: ExternalSourceKind::AbsentOk, .. } . ) { . let src = get_src(); . let mut external_src = self.external_src.borrow_mut(); . // Check that no-one else have provided the source while we were getting it . if let ExternalSource::Foreign { . kind: src_kind @ ExternalSourceKind::AbsentOk, .. . } = &mut *external_src -- line 1582 ---------------------------------------- -- line 1592 ---------------------------------------- . *src_kind = ExternalSourceKind::AbsentErr; . } . . false . } else { . self.src.is_some() || external_src.get_source().is_some() . } . } else { 333 ( 0.00%) self.src.is_some() || self.external_src.borrow().get_source().is_some() . } 2,997 ( 0.00%) } . . /// Gets a line from the list of pre-computed line-beginnings. . /// The line number here is 0-based. . pub fn get_line(&self, line_number: usize) -> Option> { . fn get_until_newline(src: &str, begin: usize) -> &str { . // We can't use `lines.get(line_number+1)` because we might . // be parsing when we call this function and thus the current . // line is the last one we have line info for. -- line 1610 ---------------------------------------- -- line 1627 ---------------------------------------- . Some(Cow::Owned(String::from(get_until_newline(src, begin)))) . } else { . None . } . } . . pub fn is_real_file(&self) -> bool { . self.name.is_real() 547 ( 0.00%) } . . pub fn is_imported(&self) -> bool { . self.src.is_none() 175,237 ( 0.00%) } . . pub fn count_lines(&self) -> usize { . self.lines.len() . } . . /// Finds the line containing the given position. The return value is the . /// index into the `lines` array of this `SourceFile`, not the 1-based line . /// number. If the source_file is empty or the position is located before the . /// first line, `None` is returned. . pub fn lookup_line(&self, pos: BytePos) -> Option { 19,925 ( 0.00%) match self.lines.binary_search(&pos) { . Ok(idx) => Some(idx), . Err(0) => None, . Err(idx) => Some(idx - 1), . } . } . . pub fn line_bounds(&self, line_index: usize) -> Range { 46,149 ( 0.00%) if self.is_empty() { . return self.start_pos..self.end_pos; . } . 31,701 ( 0.00%) assert!(line_index < self.lines.len()); 45,096 ( 0.00%) if line_index == (self.lines.len() - 1) { 106 ( 0.00%) self.lines[line_index]..self.end_pos . } else { 29,984 ( 0.00%) self.lines[line_index]..self.lines[line_index + 1] . } . } . . /// Returns whether or not the file contains the given `SourceMap` byte . /// position. The position one past the end of the file is considered to be . /// contained by the file. This implies that files for which `is_empty` . /// returns true still contain one byte position according to this function. . #[inline] -- line 1674 ---------------------------------------- -- line 1692 ---------------------------------------- . Err(i) if i == 0 => 0, . Err(i) => self.normalized_pos[i - 1].diff, . }; . . BytePos::from_u32(pos.0 - self.start_pos.0 + diff) . } . . /// Converts an absolute `BytePos` to a `CharPos` relative to the `SourceFile`. 106 ( 0.00%) pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos { . // The number of extra bytes due to multibyte chars in the `SourceFile`. . let mut total_extra_bytes = 0; . 318 ( 0.00%) for mbc in self.multibyte_chars.iter() { . debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos); 1,620 ( 0.00%) if mbc.pos < bpos { . // Every character is at least one byte, so we only . // count the actual extra bytes. 4,548 ( 0.00%) total_extra_bytes += mbc.bytes as u32 - 1; . // We should never see a byte position in the middle of a . // character. 3,790 ( 0.00%) assert!(bpos.to_u32() >= mbc.pos.to_u32() + mbc.bytes as u32); . } else { . break; . } . } . 636 ( 0.00%) assert!(self.start_pos.to_u32() + total_extra_bytes <= bpos.to_u32()); 530 ( 0.00%) CharPos(bpos.to_usize() - self.start_pos.to_usize() - total_extra_bytes as usize) 212 ( 0.00%) } . . /// Looks up the file's (1-based) line number and (0-based `CharPos`) column offset, for a . /// given `BytePos`. 371 ( 0.00%) pub fn lookup_file_pos(&self, pos: BytePos) -> (usize, CharPos) { 106 ( 0.00%) let chpos = self.bytepos_to_file_charpos(pos); 50 ( 0.00%) match self.lookup_line(pos) { . Some(a) => { . let line = a + 1; // Line numbers start at 1 53 ( 0.00%) let linebpos = self.lines[a]; 106 ( 0.00%) let linechpos = self.bytepos_to_file_charpos(linebpos); . let col = chpos - linechpos; . debug!("byte pos {:?} is on the line at byte pos {:?}", pos, linebpos); . debug!("char pos {:?} is on the line at char pos {:?}", chpos, linechpos); . debug!("byte is on line: {}", line); 53 ( 0.00%) assert!(chpos >= linechpos); . (line, col) . } . None => (0, chpos), . } 424 ( 0.00%) } . . /// Looks up the file's (1-based) line number, (0-based `CharPos`) column offset, and (0-based) . /// column offset when displayed, for a given `BytePos`. 424 ( 0.00%) pub fn lookup_file_pos_with_col_display(&self, pos: BytePos) -> (usize, CharPos, usize) { 159 ( 0.00%) let (line, col_or_chpos) = self.lookup_file_pos(pos); 106 ( 0.00%) if line > 0 { . let col = col_or_chpos; 53 ( 0.00%) let linebpos = self.lines[line - 1]; . let col_display = { . let start_width_idx = self . .non_narrow_chars . .binary_search_by_key(&linebpos, |x| x.pos()) . .unwrap_or_else(|x| x); . let end_width_idx = self . .non_narrow_chars . .binary_search_by_key(&pos, |x| x.pos()) . .unwrap_or_else(|x| x); 87 ( 0.00%) let special_chars = end_width_idx - start_width_idx; . let non_narrow: usize = self.non_narrow_chars[start_width_idx..end_width_idx] . .iter() . .map(|x| x.width()) . .sum(); 265 ( 0.00%) col.0 - special_chars + non_narrow . }; . (line, col, col_display) . } else { . let chpos = col_or_chpos; . let col_display = { . let end_width_idx = self . .non_narrow_chars . .binary_search_by_key(&pos, |x| x.pos()) . .unwrap_or_else(|x| x); . let non_narrow: usize = . self.non_narrow_chars[0..end_width_idx].iter().map(|x| x.width()).sum(); . chpos.0 - end_width_idx + non_narrow . }; . (0, chpos, col_display) . } 371 ( 0.00%) } . } . . /// Normalizes the source code and records the normalizations. 190 ( 0.00%) fn normalize_src(src: &mut String, start_pos: BytePos) -> Vec { . let mut normalized_pos = vec![]; . remove_bom(src, &mut normalized_pos); . normalize_newlines(src, &mut normalized_pos); . . // Offset all the positions by start_pos to match the final file positions. . for np in &mut normalized_pos { . np.pos.0 += start_pos.0; . } . . normalized_pos 171 ( 0.00%) } . . /// Removes UTF-8 BOM, if any. . fn remove_bom(src: &mut String, normalized_pos: &mut Vec) { 19 ( 0.00%) if src.starts_with('\u{feff}') { . src.drain(..3); . normalized_pos.push(NormalizedPos { pos: BytePos(0), diff: 3 }); . } . } . . /// Replaces `\r\n` with `\n` in-place in `src`. . /// . /// Returns error if there's a lone `\r` in the string. . fn normalize_newlines(src: &mut String, normalized_pos: &mut Vec) { 19 ( 0.00%) if !src.as_bytes().contains(&b'\r') { . return; . } . . // We replace `\r\n` with `\n` in-place, which doesn't break utf-8 encoding. . // While we *can* call `as_mut_vec` and do surgery on the live string . // directly, let's rather steal the contents of `src`. This makes the code . // safe even if a panic occurs. . -- line 1816 ---------------------------------------- -- line 1877 ---------------------------------------- . ( . $( . $(#[$attr:meta])* . $vis:vis struct $ident:ident($inner_vis:vis $inner_ty:ty); . )* . ) => { . $( . $(#[$attr])* 340,600 ( 0.00%) $vis struct $ident($inner_vis $inner_ty); . . impl Pos for $ident { . #[inline(always)] . fn from_usize(n: usize) -> $ident { 12,027 ( 0.00%) $ident(n as $inner_ty) . } . . #[inline(always)] . fn to_usize(&self) -> usize { 924,772 ( 0.01%) self.0 as usize . } . . #[inline(always)] . fn from_u32(n: u32) -> $ident { . $ident(n as $inner_ty) . } . . #[inline(always)] -- line 1903 ---------------------------------------- -- line 1906 ---------------------------------------- . } . } . . impl Add for $ident { . type Output = $ident; . . #[inline(always)] . fn add(self, rhs: $ident) -> $ident { 3,128,894 ( 0.04%) $ident(self.0 + rhs.0) . } . } . . impl Sub for $ident { . type Output = $ident; . . #[inline(always)] . fn sub(self, rhs: $ident) -> $ident { 6,214,042 ( 0.09%) $ident(self.0 - rhs.0) . } . } . )* . }; . } . . impl_pos! { . /// A byte offset. -- line 1931 ---------------------------------------- -- line 1939 ---------------------------------------- . /// Because of multibyte UTF-8 characters, a byte offset . /// is not equivalent to a character offset. The [`SourceMap`] will convert [`BytePos`] . /// values to `CharPos` values as necessary. . #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] . pub struct CharPos(pub usize); . } . . impl Encodable for BytePos { 65 ( 0.00%) fn encode(&self, s: &mut S) -> Result<(), S::Error> { . s.emit_u32(self.0) 78 ( 0.00%) } . } . . impl Decodable for BytePos { . fn decode(d: &mut D) -> BytePos { 256,672 ( 0.00%) BytePos(d.read_u32()) . } . } . . // _____________________________________________________________________________ . // Loc, SourceFileAndLine, SourceFileAndBytePos . // . . /// A source code location used for error reporting. -- line 1962 ---------------------------------------- -- line 2037 ---------------------------------------- . pub source_len: usize, . pub begin_pos: BytePos, . pub end_pos: BytePos, . } . . /// Range inside of a `Span` used for diagnostics when we only have access to relative positions. . #[derive(Copy, Clone, PartialEq, Eq, Debug)] . pub struct InnerSpan { 3 ( 0.00%) pub start: usize, . pub end: usize, . } . . impl InnerSpan { 322 ( 0.00%) pub fn new(start: usize, end: usize) -> InnerSpan { . InnerSpan { start, end } 161 ( 0.00%) } . } . . /// Requirements for a `StableHashingContext` to be used in this crate. . /// . /// This is a hack to allow using the [`HashStable_Generic`] derive macro . /// instead of implementing everything in rustc_middle. . pub trait HashStableContext { . fn def_path_hash(&self, def_id: DefId) -> DefPathHash; -- line 2060 ---------------------------------------- -- line 2079 ---------------------------------------- . /// offsets into the `SourceMap`). Instead, we hash the (file name, line, column) . /// triple, which stays the same even if the containing `SourceFile` has moved . /// within the `SourceMap`. . /// . /// Also note that we are hashing byte offsets for the column, not unicode . /// codepoint offsets. For the purpose of the hash that's sufficient. . /// Also, hashing filenames is expensive so we avoid doing it twice when the . /// span starts and ends in the same file, which is almost always the case. 2,289,133 ( 0.03%) fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) { . const TAG_VALID_SPAN: u8 = 0; . const TAG_INVALID_SPAN: u8 = 1; . const TAG_RELATIVE_SPAN: u8 = 2; . 342,287 ( 0.00%) if !ctx.hash_spans() { . return; . } . 1,946,846 ( 0.03%) let span = self.data_untracked(); 935,269 ( 0.01%) span.ctxt.hash_stable(ctx, hasher); 981,057 ( 0.01%) span.parent.hash_stable(ctx, hasher); . 654,670 ( 0.01%) if span.is_dummy() { . Hash::hash(&TAG_INVALID_SPAN, hasher); . return; . } . 652,774 ( 0.01%) if let Some(parent) = span.parent { . let def_span = ctx.def_span(parent).data_untracked(); . if def_span.contains(span) { . // This span is enclosed in a definition: only hash the relative position. . Hash::hash(&TAG_RELATIVE_SPAN, hasher); . (span.lo - def_span.lo).to_u32().hash_stable(ctx, hasher); . (span.hi - def_span.lo).to_u32().hash_stable(ctx, hasher); . return; . } . } . . // If this is not an empty or invalid span, we want to hash the last . // position that belongs to it, as opposed to hashing the first . // position past it. 1,305,548 ( 0.02%) let (file, line_lo, col_lo, line_hi, col_hi) = match ctx.span_data_to_lines_and_cols(&span) . { 652,774 ( 0.01%) Some(pos) => pos, . None => { . Hash::hash(&TAG_INVALID_SPAN, hasher); . return; . } . }; . . Hash::hash(&TAG_VALID_SPAN, hasher); . // We truncate the stable ID hash and line and column numbers. The chances -- line 2129 ---------------------------------------- -- line 2134 ---------------------------------------- . // hash only the length, for example, then two otherwise equal spans with . // different end locations will have the same hash. This can cause a problem . // during incremental compilation wherein a previous result for a query that . // depends on the end location of a span will be incorrectly reused when the . // end location of the span it depends on has changed (see issue #74890). A . // similar analysis applies if some query depends specifically on the length . // of the span, but we only hash the end location. So hash both. . 326,387 ( 0.00%) let col_lo_trunc = (col_lo.0 as u64) & 0xFF; . let line_lo_trunc = ((line_lo as u64) & 0xFF_FF_FF) << 8; . let col_hi_trunc = (col_hi.0 as u64) & 0xFF << 32; . let line_hi_trunc = ((line_hi as u64) & 0xFF_FF_FF) << 40; . let col_line = col_lo_trunc | line_lo_trunc | col_hi_trunc | line_hi_trunc; 326,387 ( 0.00%) let len = (span.hi - span.lo).0; . Hash::hash(&col_line, hasher); . Hash::hash(&len, hasher); 2,616,152 ( 0.04%) } . } 6,484,072 ( 0.09%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_hir/src/intravisit.rs -------------------------------------------------------------------------------- Ir -- line 48 ---------------------------------------- . } . } . . impl<'v, 'hir, V> ItemLikeVisitor<'hir> for DeepVisitor<'v, V> . where . V: Visitor<'hir>, . { . fn visit_item(&mut self, item: &'hir Item<'hir>) { 5,904 ( 0.00%) self.visitor.visit_item(item); . } . . fn visit_trait_item(&mut self, trait_item: &'hir TraitItem<'hir>) { 3 ( 0.00%) self.visitor.visit_trait_item(trait_item); . } . . fn visit_impl_item(&mut self, impl_item: &'hir ImplItem<'hir>) { 1,182 ( 0.00%) self.visitor.visit_impl_item(impl_item); . } . . fn visit_foreign_item(&mut self, foreign_item: &'hir ForeignItem<'hir>) { . self.visitor.visit_foreign_item(foreign_item); . } . } . . pub trait IntoVisitor<'hir> { -- line 72 ---------------------------------------- -- line 106 ---------------------------------------- . Method(Ident, &'a FnSig<'a>, Option<&'a Visibility<'a>>), . . /// `|x, y| {}` . Closure, . } . . impl<'a> FnKind<'a> { . pub fn header(&self) -> Option<&FnHeader> { 1,255 ( 0.00%) match *self { 100 ( 0.00%) FnKind::ItemFn(_, _, ref header, _) => Some(header), 573 ( 0.00%) FnKind::Method(_, ref sig, _) => Some(&sig.header), . FnKind::Closure => None, . } . } . . pub fn constness(self) -> Constness { 582 ( 0.00%) self.header().map_or(Constness::NotConst, |header| header.constness) 291 ( 0.00%) } . . pub fn asyncness(self) -> IsAsync { . self.header().map_or(IsAsync::NotAsync, |header| header.asyncness) . } . } . . /// An abstract representation of the HIR `rustc_middle::hir::map::Map`. . pub trait Map<'hir> { -- line 131 ---------------------------------------- -- line 248 ---------------------------------------- . /// Invoked when a nested item is encountered. By default does . /// nothing unless you override `nested_visit_map` to return other than . /// `None`, in which case it will walk the item. **You probably . /// don't want to override this method** -- instead, override . /// `nested_visit_map` or use the "shallow" or "deep" visit . /// patterns described on `itemlikevisit::ItemLikeVisitor`. The only . /// reason to override this method is if you want a nested pattern . /// but cannot supply a `Map`; see `nested_visit_map` for advice. 7,872 ( 0.00%) fn visit_nested_item(&mut self, id: ItemId) { . if Self::NestedFilter::INTER { 19,186 ( 0.00%) let item = self.nested_visit_map().item(id); 8,856 ( 0.00%) self.visit_item(item); . } 7,872 ( 0.00%) } . . /// Like `visit_nested_item()`, but for trait items. See . /// `visit_nested_item()` for advice on when to override this . /// method. 23 ( 0.00%) fn visit_nested_trait_item(&mut self, id: TraitItemId) { . if Self::NestedFilter::INTER { 39 ( 0.00%) let item = self.nested_visit_map().trait_item(id); 6 ( 0.00%) self.visit_trait_item(item); . } 23 ( 0.00%) } . . /// Like `visit_nested_item()`, but for impl items. See . /// `visit_nested_item()` for advice on when to override this . /// method. 3,152 ( 0.00%) fn visit_nested_impl_item(&mut self, id: ImplItemId) { . if Self::NestedFilter::INTER { 7,683 ( 0.00%) let item = self.nested_visit_map().impl_item(id); 1,773 ( 0.00%) self.visit_impl_item(item); . } 3,152 ( 0.00%) } . . /// Like `visit_nested_item()`, but for foreign items. See . /// `visit_nested_item()` for advice on when to override this . /// method. . fn visit_nested_foreign_item(&mut self, id: ForeignItemId) { . if Self::NestedFilter::INTER { . let item = self.nested_visit_map().foreign_item(id); . self.visit_foreign_item(item); . } . } . . /// Invoked to visit the body of a function, method or closure. Like . /// visit_nested_item, does nothing by default unless you override . /// `nested_visit_map` to return other than `None`, in which case it will walk . /// the body. 3,365 ( 0.00%) fn visit_nested_body(&mut self, id: BodyId) { . if Self::NestedFilter::INTRA { 36,957 ( 0.00%) let body = self.nested_visit_map().body(id); 1,296 ( 0.00%) self.visit_body(body); . } 3,365 ( 0.00%) } . . fn visit_param(&mut self, param: &'v Param<'v>) { . walk_param(self, param) . } . . /// Visits the top-level item and (optionally) nested items / impl items. See . /// `visit_nested_item` for details. . fn visit_item(&mut self, i: &'v Item<'v>) { 12,738 ( 0.00%) walk_item(self, i) . } . . fn visit_body(&mut self, b: &'v Body<'v>) { 4,531 ( 0.00%) walk_body(self, b); . } . . /// When invoking `visit_all_item_likes()`, you need to supply an . /// item-like visitor. This method converts an "intra-visit" . /// visitor into an item-like visitor that walks the entire tree. . /// If you use this, you probably don't want to process the . /// contents of nested item-like things, since the outer loop will . /// visit them as well. -- line 323 ---------------------------------------- -- line 332 ---------------------------------------- . } . fn visit_name(&mut self, _span: Span, _name: Symbol) { . // Nothing to do. . } . fn visit_ident(&mut self, ident: Ident) { . walk_ident(self, ident) . } . fn visit_mod(&mut self, m: &'v Mod<'v>, _s: Span, n: HirId) { 181 ( 0.00%) walk_mod(self, m, n) . } . fn visit_foreign_item(&mut self, i: &'v ForeignItem<'v>) { . walk_foreign_item(self, i) . } . fn visit_local(&mut self, l: &'v Local<'v>) { 2,220 ( 0.00%) walk_local(self, l) . } . fn visit_block(&mut self, b: &'v Block<'v>) { . walk_block(self, b) . } . fn visit_stmt(&mut self, s: &'v Stmt<'v>) { 15,624 ( 0.00%) walk_stmt(self, s) . } . fn visit_arm(&mut self, a: &'v Arm<'v>) { 2,488 ( 0.00%) walk_arm(self, a) . } . fn visit_pat(&mut self, p: &'v Pat<'v>) { 75,263 ( 0.00%) walk_pat(self, p) . } . fn visit_array_length(&mut self, len: &'v ArrayLen) { . walk_array_len(self, len) . } . fn visit_anon_const(&mut self, c: &'v AnonConst) { . walk_anon_const(self, c) . } . fn visit_expr(&mut self, ex: &'v Expr<'v>) { 5,439,120 ( 0.08%) walk_expr(self, ex) . } . fn visit_let_expr(&mut self, lex: &'v Let<'v>) { 810 ( 0.00%) walk_let_expr(self, lex) . } . fn visit_ty(&mut self, t: &'v Ty<'v>) { 111,770 ( 0.00%) walk_ty(self, t) . } . fn visit_generic_param(&mut self, p: &'v GenericParam<'v>) { 8,439 ( 0.00%) walk_generic_param(self, p) . } . fn visit_const_param_default(&mut self, _param: HirId, ct: &'v AnonConst) { . walk_const_param_default(self, ct) . } . fn visit_generics(&mut self, g: &'v Generics<'v>) { 2,304 ( 0.00%) walk_generics(self, g) . } . fn visit_where_predicate(&mut self, predicate: &'v WherePredicate<'v>) { 1,557 ( 0.00%) walk_where_predicate(self, predicate) . } . fn visit_fn_decl(&mut self, fd: &'v FnDecl<'v>) { 1,463 ( 0.00%) walk_fn_decl(self, fd) . } . fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v FnDecl<'v>, b: BodyId, s: Span, id: HirId) { 58,881 ( 0.00%) walk_fn(self, fk, fd, b, s, id) . } . fn visit_use(&mut self, path: &'v Path<'v>, hir_id: HirId) { . walk_use(self, path, hir_id) . } . fn visit_trait_item(&mut self, ti: &'v TraitItem<'v>) { 47 ( 0.00%) walk_trait_item(self, ti) . } . fn visit_trait_item_ref(&mut self, ii: &'v TraitItemRef) { 3 ( 0.00%) walk_trait_item_ref(self, ii) . } . fn visit_impl_item(&mut self, ii: &'v ImplItem<'v>) { 9,862 ( 0.00%) walk_impl_item(self, ii) . } . fn visit_foreign_item_ref(&mut self, ii: &'v ForeignItemRef) { . walk_foreign_item_ref(self, ii) . } . fn visit_impl_item_ref(&mut self, ii: &'v ImplItemRef) { 788 ( 0.00%) walk_impl_item_ref(self, ii) . } 1,199 ( 0.00%) fn visit_trait_ref(&mut self, t: &'v TraitRef<'v>) { 3,592 ( 0.00%) walk_trait_ref(self, t) 872 ( 0.00%) } . fn visit_param_bound(&mut self, bounds: &'v GenericBound<'v>) { 9,976 ( 0.00%) walk_param_bound(self, bounds) . } . fn visit_poly_trait_ref(&mut self, t: &'v PolyTraitRef<'v>, m: TraitBoundModifier) { 251 ( 0.00%) walk_poly_trait_ref(self, t, m) . } . fn visit_variant_data( . &mut self, . s: &'v VariantData<'v>, . _: Symbol, . _: &'v Generics<'v>, . _parent_id: HirId, . _: Span, . ) { 1,860 ( 0.00%) walk_struct_def(self, s) . } . fn visit_field_def(&mut self, s: &'v FieldDef<'v>) { 186 ( 0.00%) walk_field_def(self, s) . } . fn visit_enum_def( . &mut self, . enum_definition: &'v EnumDef<'v>, . generics: &'v Generics<'v>, . item_id: HirId, . _: Span, . ) { 492 ( 0.00%) walk_enum_def(self, enum_definition, generics, item_id) . } . fn visit_variant(&mut self, v: &'v Variant<'v>, g: &'v Generics<'v>, item_id: HirId) { 924 ( 0.00%) walk_variant(self, v, g, item_id) . } . fn visit_label(&mut self, label: &'v Label) { . walk_label(self, label) . } . fn visit_infer(&mut self, inf: &'v InferArg) { . walk_inf(self, inf); . } 19,753 ( 0.00%) fn visit_generic_arg(&mut self, generic_arg: &'v GenericArg<'v>) { 117,852 ( 0.00%) match generic_arg { 72 ( 0.00%) GenericArg::Lifetime(lt) => self.visit_lifetime(lt), 5,350 ( 0.00%) GenericArg::Type(ty) => self.visit_ty(ty), . GenericArg::Const(ct) => self.visit_anon_const(&ct.value), . GenericArg::Infer(inf) => self.visit_infer(inf), . } 15,017 ( 0.00%) } . fn visit_lifetime(&mut self, lifetime: &'v Lifetime) { . walk_lifetime(self, lifetime) . } . fn visit_qpath(&mut self, qpath: &'v QPath<'v>, id: HirId, span: Span) { 994,677 ( 0.01%) walk_qpath(self, qpath, id, span) . } 10,180 ( 0.00%) fn visit_path(&mut self, path: &'v Path<'v>, _id: HirId) { 101,810 ( 0.00%) walk_path(self, path) 11,938 ( 0.00%) } 10,361 ( 0.00%) fn visit_path_segment(&mut self, path_span: Span, path_segment: &'v PathSegment<'v>) { . walk_path_segment(self, path_span, path_segment) 11,076 ( 0.00%) } 44,607 ( 0.00%) fn visit_generic_args(&mut self, path_span: Span, generic_args: &'v GenericArgs<'v>) { 347 ( 0.00%) walk_generic_args(self, path_span, generic_args) 39,442 ( 0.00%) } . fn visit_assoc_type_binding(&mut self, type_binding: &'v TypeBinding<'v>) { 1,761 ( 0.00%) walk_assoc_type_binding(self, type_binding) . } . fn visit_attribute(&mut self, _id: HirId, _attr: &'v Attribute) {} . fn visit_vis(&mut self, vis: &'v Visibility<'v>) { 4,044 ( 0.00%) walk_vis(self, vis) . } . fn visit_associated_item_kind(&mut self, kind: &'v AssocItemKind) { . walk_associated_item_kind(self, kind); . } . fn visit_defaultness(&mut self, defaultness: &'v Defaultness) { . walk_defaultness(self, defaultness); . } . } . 133 ( 0.00%) pub fn walk_mod<'v, V: Visitor<'v>>(visitor: &mut V, module: &'v Mod<'v>, mod_hir_id: HirId) { . visitor.visit_id(mod_hir_id); 6,668 ( 0.00%) for &item_id in module.item_ids { 1,964 ( 0.00%) visitor.visit_nested_item(item_id); . } 152 ( 0.00%) } . 14,498 ( 0.00%) pub fn walk_body<'v, V: Visitor<'v>>(visitor: &mut V, body: &'v Body<'v>) { 16,717 ( 0.00%) walk_list!(visitor, visit_param, body.params); 30,278 ( 0.00%) visitor.visit_expr(&body.value); 7,296 ( 0.00%) } . 10,212 ( 0.00%) pub fn walk_local<'v, V: Visitor<'v>>(visitor: &mut V, local: &'v Local<'v>) { . // Intentionally visiting the expr first - the initialization expr . // dominates the local's definition. 13,536 ( 0.00%) walk_list!(visitor, visit_expr, &local.init); 888 ( 0.00%) visitor.visit_id(local.hir_id); 8,698 ( 0.00%) visitor.visit_pat(&local.pat); 7,684 ( 0.00%) walk_list!(visitor, visit_ty, &local.ty); 8,304 ( 0.00%) } . . pub fn walk_ident<'v, V: Visitor<'v>>(visitor: &mut V, ident: Ident) { . visitor.visit_name(ident.span, ident.name); . } . . pub fn walk_label<'v, V: Visitor<'v>>(visitor: &mut V, label: &'v Label) { . visitor.visit_ident(label.ident); . } . . pub fn walk_lifetime<'v, V: Visitor<'v>>(visitor: &mut V, lifetime: &'v Lifetime) { 2,583 ( 0.00%) visitor.visit_id(lifetime.hir_id); 1,731 ( 0.00%) match lifetime.name { 357 ( 0.00%) LifetimeName::Param(ParamName::Plain(ident)) => { . visitor.visit_ident(ident); . } . LifetimeName::Param(ParamName::Fresh(_)) . | LifetimeName::Param(ParamName::Error) . | LifetimeName::Static . | LifetimeName::Error . | LifetimeName::Implicit(_) . | LifetimeName::ImplicitObjectLifetimeDefault . | LifetimeName::Underscore => {} . } . } . 333 ( 0.00%) pub fn walk_poly_trait_ref<'v, V: Visitor<'v>>( . visitor: &mut V, . trait_ref: &'v PolyTraitRef<'v>, . _modifier: TraitBoundModifier, . ) { . walk_list!(visitor, visit_generic_param, trait_ref.bound_generic_params); 2,570 ( 0.00%) visitor.visit_trait_ref(&trait_ref.trait_ref); 296 ( 0.00%) } . 3,172 ( 0.00%) pub fn walk_trait_ref<'v, V: Visitor<'v>>(visitor: &mut V, trait_ref: &'v TraitRef<'v>) { 2,755 ( 0.00%) visitor.visit_id(trait_ref.hir_ref_id); 11,795 ( 0.00%) visitor.visit_path(&trait_ref.path, trait_ref.hir_ref_id) 3,624 ( 0.00%) } . . pub fn walk_param<'v, V: Visitor<'v>>(visitor: &mut V, param: &'v Param<'v>) { 1,768 ( 0.00%) visitor.visit_id(param.hir_id); 18,316 ( 0.00%) visitor.visit_pat(¶m.pat); . } . 120,831 ( 0.00%) pub fn walk_item<'v, V: Visitor<'v>>(visitor: &mut V, item: &'v Item<'v>) { 2,952 ( 0.00%) visitor.visit_vis(&item.vis); 1,476 ( 0.00%) visitor.visit_ident(item.ident); 67,220 ( 0.00%) match item.kind { 2 ( 0.00%) ItemKind::ExternCrate(orig_name) => { . visitor.visit_id(item.hir_id()); 4 ( 0.00%) if let Some(orig_name) = orig_name { . visitor.visit_name(item.span, orig_name); . } . } . ItemKind::Use(ref path, _) => { 4,566 ( 0.00%) visitor.visit_use(path, item.hir_id()); . } . ItemKind::Static(ref typ, _, body) | ItemKind::Const(ref typ, body) => { 279 ( 0.00%) visitor.visit_id(item.hir_id()); 3,627 ( 0.00%) visitor.visit_ty(typ); 6,882 ( 0.00%) visitor.visit_nested_body(body); . } 10,188 ( 0.00%) ItemKind::Fn(ref sig, ref generics, body_id) => visitor.visit_fn( 10,900 ( 0.00%) FnKind::ItemFn(item.ident, generics, sig.header, &item.vis), 2,796 ( 0.00%) &sig.decl, . body_id, 400 ( 0.00%) item.span, 1,200 ( 0.00%) item.hir_id(), . ), . ItemKind::Macro(_) => { . visitor.visit_id(item.hir_id()); . } 18 ( 0.00%) ItemKind::Mod(ref module) => { . // `visit_mod()` takes care of visiting the `Item`'s `HirId`. . visitor.visit_mod(module, item.span, item.hir_id()) . } . ItemKind::ForeignMod { abi: _, items } => { . visitor.visit_id(item.hir_id()); . walk_list!(visitor, visit_foreign_item_ref, items); . } . ItemKind::GlobalAsm(asm) => { . visitor.visit_id(item.hir_id()); . walk_inline_asm(visitor, asm); . } 6 ( 0.00%) ItemKind::TyAlias(ref ty, ref generics) => { 3 ( 0.00%) visitor.visit_id(item.hir_id()); 32 ( 0.00%) visitor.visit_ty(ty); 20 ( 0.00%) visitor.visit_generics(generics) . } . ItemKind::OpaqueTy(OpaqueTy { ref generics, bounds, .. }) => { . visitor.visit_id(item.hir_id()); . walk_generics(visitor, generics); . walk_list!(visitor, visit_param_bound, bounds); . } 91 ( 0.00%) ItemKind::Enum(ref enum_definition, ref generics) => { 90 ( 0.00%) visitor.visit_generics(generics); . // `visit_enum_def()` takes care of visiting the `Item`'s `HirId`. 71 ( 0.00%) visitor.visit_enum_def(enum_definition, generics, item.hir_id(), item.span) . } . ItemKind::Impl(Impl { . unsafety: _, . defaultness: _, . polarity: _, . constness: _, . defaultness_span: _, 847 ( 0.00%) ref generics, 218 ( 0.00%) ref of_trait, . ref self_ty, 4,356 ( 0.00%) items, . }) => { 363 ( 0.00%) visitor.visit_id(item.hir_id()); 726 ( 0.00%) visitor.visit_generics(generics); 4,260 ( 0.00%) walk_list!(visitor, visit_trait_ref, of_trait); 4,235 ( 0.00%) visitor.visit_ty(self_ty); . walk_list!(visitor, visit_impl_item_ref, items); . } . ItemKind::Struct(ref struct_definition, ref generics) . | ItemKind::Union(ref struct_definition, ref generics) => { 94 ( 0.00%) visitor.visit_generics(generics); 48 ( 0.00%) visitor.visit_id(item.hir_id()); 84 ( 0.00%) visitor.visit_variant_data( . struct_definition, 12 ( 0.00%) item.ident.name, . generics, . item.hir_id(), 12 ( 0.00%) item.span, . ); . } 261 ( 0.00%) ItemKind::Trait(.., ref generics, bounds, trait_item_refs) => { 6 ( 0.00%) visitor.visit_id(item.hir_id()); 16 ( 0.00%) visitor.visit_generics(generics); 20 ( 0.00%) walk_list!(visitor, visit_param_bound, bounds); . walk_list!(visitor, visit_trait_item_ref, trait_item_refs); . } . ItemKind::TraitAlias(ref generics, bounds) => { . visitor.visit_id(item.hir_id()); . visitor.visit_generics(generics); . walk_list!(visitor, visit_param_bound, bounds); . } . } 73,016 ( 0.00%) } . . fn walk_inline_asm<'v, V: Visitor<'v>>(visitor: &mut V, asm: &'v InlineAsm<'v>) { . for (op, _op_sp) in asm.operands { . match op { . InlineAsmOperand::In { expr, .. } . | InlineAsmOperand::InOut { expr, .. } . | InlineAsmOperand::Sym { expr, .. } => visitor.visit_expr(expr), . InlineAsmOperand::Out { expr, .. } => { -- line 657 ---------------------------------------- -- line 667 ---------------------------------------- . } . InlineAsmOperand::Const { anon_const } => visitor.visit_anon_const(anon_const), . } . } . } . . pub fn walk_use<'v, V: Visitor<'v>>(visitor: &mut V, path: &'v Path<'v>, hir_id: HirId) { . visitor.visit_id(hir_id); 9,200 ( 0.00%) visitor.visit_path(path, hir_id); . } . 307 ( 0.00%) pub fn walk_enum_def<'v, V: Visitor<'v>>( . visitor: &mut V, . enum_definition: &'v EnumDef<'v>, . generics: &'v Generics<'v>, . item_id: HirId, . ) { . visitor.visit_id(item_id); 796 ( 0.00%) walk_list!(visitor, visit_variant, enum_definition.variants, generics, item_id); 328 ( 0.00%) } . 1,892 ( 0.00%) pub fn walk_variant<'v, V: Visitor<'v>>( . visitor: &mut V, . variant: &'v Variant<'v>, . generics: &'v Generics<'v>, . parent_item_id: HirId, . ) { 88 ( 0.00%) visitor.visit_ident(variant.ident); 88 ( 0.00%) visitor.visit_id(variant.id); 154 ( 0.00%) visitor.visit_variant_data( . &variant.data, . variant.ident.name, . generics, . parent_item_id, 22 ( 0.00%) variant.span, . ); 546 ( 0.00%) walk_list!(visitor, visit_anon_const, &variant.disr_expr); 1,672 ( 0.00%) } . 477,634 ( 0.01%) pub fn walk_ty<'v, V: Visitor<'v>>(visitor: &mut V, typ: &'v Ty<'v>) { 85,112 ( 0.00%) visitor.visit_id(typ.hir_id); . 294,907 ( 0.00%) match typ.kind { 184 ( 0.00%) TyKind::Slice(ref ty) => visitor.visit_ty(ty), 174 ( 0.00%) TyKind::Ptr(ref mutable_type) => visitor.visit_ty(&mutable_type.ty), 8,915 ( 0.00%) TyKind::Rptr(ref lifetime, ref mutable_type) => { 742 ( 0.00%) visitor.visit_lifetime(lifetime); 3,068 ( 0.00%) visitor.visit_ty(&mutable_type.ty) . } . TyKind::Never => {} 1,338 ( 0.00%) TyKind::Tup(tuple_element_types) => { 390 ( 0.00%) walk_list!(visitor, visit_ty, tuple_element_types); . } . TyKind::BareFn(ref function_declaration) => { . walk_list!(visitor, visit_generic_param, function_declaration.generic_params); . visitor.visit_fn_decl(&function_declaration.decl); . } 43,298 ( 0.00%) TyKind::Path(ref qpath) => { 59,338 ( 0.00%) visitor.visit_qpath(qpath, typ.hir_id, typ.span); . } . TyKind::OpaqueDef(item_id, lifetimes) => { . visitor.visit_nested_item(item_id); . walk_list!(visitor, visit_generic_arg, lifetimes); . } . TyKind::Array(ref ty, ref length) => { . visitor.visit_ty(ty); . visitor.visit_array_length(length) . } 33 ( 0.00%) TyKind::TraitObject(bounds, ref lifetime, _syntax) => { . for bound in bounds { . visitor.visit_poly_trait_ref(bound, TraitBoundModifier::None); . } 10 ( 0.00%) visitor.visit_lifetime(lifetime); . } . TyKind::Typeof(ref expression) => visitor.visit_anon_const(expression), . TyKind::Infer | TyKind::Err => {} . } 70,256 ( 0.00%) } . . pub fn walk_inf<'v, V: Visitor<'v>>(visitor: &mut V, inf: &'v InferArg) { . visitor.visit_id(inf.hir_id); . } . 1,111,862 ( 0.02%) pub fn walk_qpath<'v, V: Visitor<'v>>( . visitor: &mut V, . qpath: &'v QPath<'v>, . id: HirId, . span: Span, . ) { 453,358 ( 0.01%) match *qpath { . QPath::Resolved(ref maybe_qself, ref path) => { 134,227 ( 0.00%) walk_list!(visitor, visit_ty, maybe_qself); 176,801 ( 0.00%) visitor.visit_path(path, id) . } . QPath::TypeRelative(ref qself, ref segment) => { 8,898 ( 0.00%) visitor.visit_ty(qself); 10,939 ( 0.00%) visitor.visit_path_segment(span, segment); . } . QPath::LangItem(..) => {} . } 946,850 ( 0.01%) } . 79,730 ( 0.00%) pub fn walk_path<'v, V: Visitor<'v>>(visitor: &mut V, path: &'v Path<'v>) { . for segment in path.segments { 32,328 ( 0.00%) visitor.visit_path_segment(path.span, segment); . } 92,920 ( 0.00%) } . 1,125 ( 0.00%) pub fn walk_path_segment<'v, V: Visitor<'v>>( . visitor: &mut V, . path_span: Span, . segment: &'v PathSegment<'v>, . ) { 24,505 ( 0.00%) visitor.visit_ident(segment.ident); 47,373 ( 0.00%) walk_list!(visitor, visit_id, segment.hir_id); 773,658 ( 0.01%) if let Some(ref args) = segment.args { 20,643 ( 0.00%) visitor.visit_generic_args(path_span, args); . } 1,350 ( 0.00%) } . 1,114 ( 0.00%) pub fn walk_generic_args<'v, V: Visitor<'v>>( . visitor: &mut V, . _path_span: Span, . generic_args: &'v GenericArgs<'v>, . ) { 9,903 ( 0.00%) walk_list!(visitor, visit_generic_arg, generic_args.args); 19,348 ( 0.00%) walk_list!(visitor, visit_assoc_type_binding, generic_args.bindings); 985 ( 0.00%) } . 5,056 ( 0.00%) pub fn walk_assoc_type_binding<'v, V: Visitor<'v>>( . visitor: &mut V, . type_binding: &'v TypeBinding<'v>, . ) { 84 ( 0.00%) visitor.visit_id(type_binding.hir_id); 63 ( 0.00%) visitor.visit_ident(type_binding.ident); 865 ( 0.00%) visitor.visit_generic_args(type_binding.span, type_binding.gen_args); 1,178 ( 0.00%) match type_binding.kind { 1,178 ( 0.00%) TypeBindingKind::Equality { ref term } => match term { 796 ( 0.00%) Term::Ty(ref ty) => visitor.visit_ty(ty), . Term::Const(ref c) => visitor.visit_anon_const(c), . }, . TypeBindingKind::Constraint { bounds } => walk_list!(visitor, visit_param_bound, bounds), . } 315 ( 0.00%) } . 406,709 ( 0.01%) pub fn walk_pat<'v, V: Visitor<'v>>(visitor: &mut V, pattern: &'v Pat<'v>) { 35,068 ( 0.00%) visitor.visit_id(pattern.hir_id); 232,510 ( 0.00%) match pattern.kind { 8,121 ( 0.00%) PatKind::TupleStruct(ref qpath, children, _) => { 3,519 ( 0.00%) visitor.visit_qpath(qpath, pattern.hir_id, pattern.span); 2,160 ( 0.00%) walk_list!(visitor, visit_pat, children); . } 714 ( 0.00%) PatKind::Path(ref qpath) => { 2,102 ( 0.00%) visitor.visit_qpath(qpath, pattern.hir_id, pattern.span); . } 9,717 ( 0.00%) PatKind::Struct(ref qpath, fields, _) => { 4,209 ( 0.00%) visitor.visit_qpath(qpath, pattern.hir_id, pattern.span); . for field in fields { 684 ( 0.00%) visitor.visit_id(field.hir_id); 684 ( 0.00%) visitor.visit_ident(field.ident); 7,928 ( 0.00%) visitor.visit_pat(&field.pat) . } . } 216 ( 0.00%) PatKind::Or(pats) => walk_list!(visitor, visit_pat, pats), . PatKind::Tuple(tuple_elements, _) => { 1,854 ( 0.00%) walk_list!(visitor, visit_pat, tuple_elements); . } . PatKind::Box(ref subpattern) | PatKind::Ref(ref subpattern, _) => { 1,118 ( 0.00%) visitor.visit_pat(subpattern) . } 3,496 ( 0.00%) PatKind::Binding(_, _hir_id, ident, ref optional_subpattern) => { . visitor.visit_ident(ident); 28,061 ( 0.00%) walk_list!(visitor, visit_pat, optional_subpattern); . } 616 ( 0.00%) PatKind::Lit(ref expression) => visitor.visit_expr(expression), . PatKind::Range(ref lower_bound, ref upper_bound, _) => { . walk_list!(visitor, visit_expr, lower_bound); . walk_list!(visitor, visit_expr, upper_bound); . } . PatKind::Wild => (), . PatKind::Slice(prepatterns, ref slice_pattern, postpatterns) => { . walk_list!(visitor, visit_pat, prepatterns); . walk_list!(visitor, visit_pat, slice_pattern); . walk_list!(visitor, visit_pat, postpatterns); . } . } 344,960 ( 0.00%) } . . pub fn walk_foreign_item<'v, V: Visitor<'v>>(visitor: &mut V, foreign_item: &'v ForeignItem<'v>) { . visitor.visit_id(foreign_item.hir_id()); . visitor.visit_vis(&foreign_item.vis); . visitor.visit_ident(foreign_item.ident); . . match foreign_item.kind { . ForeignItemKind::Fn(ref function_declaration, param_names, ref generics) => { -- line 861 ---------------------------------------- -- line 865 ---------------------------------------- . visitor.visit_ident(param_name); . } . } . ForeignItemKind::Static(ref typ, _) => visitor.visit_ty(typ), . ForeignItemKind::Type => (), . } . } . 26,520 ( 0.00%) pub fn walk_param_bound<'v, V: Visitor<'v>>(visitor: &mut V, bound: &'v GenericBound<'v>) { 9,506 ( 0.00%) match *bound { 258 ( 0.00%) GenericBound::Trait(ref typ, modifier) => { 1,120 ( 0.00%) visitor.visit_poly_trait_ref(typ, modifier); . } . GenericBound::LangItemTrait(_, span, hir_id, args) => { . visitor.visit_id(hir_id); . visitor.visit_generic_args(span, args); . } . GenericBound::Outlives(ref lifetime) => visitor.visit_lifetime(lifetime), . } 16,702 ( 0.00%) } . 31,144 ( 0.00%) pub fn walk_generic_param<'v, V: Visitor<'v>>(visitor: &mut V, param: &'v GenericParam<'v>) { 720 ( 0.00%) visitor.visit_id(param.hir_id); 360 ( 0.00%) match param.name { 540 ( 0.00%) ParamName::Plain(ident) => visitor.visit_ident(ident), . ParamName::Error | ParamName::Fresh(_) => {} . } 21,463 ( 0.00%) match param.kind { . GenericParamKind::Lifetime { .. } => {} 3,602 ( 0.00%) GenericParamKind::Type { ref default, .. } => walk_list!(visitor, visit_ty, default), . GenericParamKind::Const { ref ty, ref default } => { . visitor.visit_ty(ty); . if let Some(ref default) = default { . visitor.visit_const_param_default(param.hir_id, default); . } . } . } 5,005 ( 0.00%) walk_list!(visitor, visit_param_bound, param.bounds); 27,431 ( 0.00%) } . . pub fn walk_const_param_default<'v, V: Visitor<'v>>(visitor: &mut V, ct: &'v AnonConst) { . visitor.visit_anon_const(ct) . } . 11,995 ( 0.00%) pub fn walk_generics<'v, V: Visitor<'v>>(visitor: &mut V, generics: &'v Generics<'v>) { 4,164 ( 0.00%) walk_list!(visitor, visit_generic_param, generics.params); 12,270 ( 0.00%) walk_list!(visitor, visit_where_predicate, generics.where_clause.predicates); 10,662 ( 0.00%) } . 5,031 ( 0.00%) pub fn walk_where_predicate<'v, V: Visitor<'v>>( . visitor: &mut V, . predicate: &'v WherePredicate<'v>, . ) { 1,677 ( 0.00%) match *predicate { . WherePredicate::BoundPredicate(WhereBoundPredicate { . ref bounded_ty, 1,138 ( 0.00%) bounds, 1,158 ( 0.00%) bound_generic_params, . .. . }) => { 599 ( 0.00%) visitor.visit_ty(bounded_ty); . walk_list!(visitor, visit_param_bound, bounds); . walk_list!(visitor, visit_generic_param, bound_generic_params); . } . WherePredicate::RegionPredicate(WhereRegionPredicate { ref lifetime, bounds, .. }) => { . visitor.visit_lifetime(lifetime); . walk_list!(visitor, visit_param_bound, bounds); . } . WherePredicate::EqPredicate(WhereEqPredicate { . hir_id, ref lhs_ty, ref rhs_ty, .. . }) => { . visitor.visit_id(hir_id); . visitor.visit_ty(lhs_ty); . visitor.visit_ty(rhs_ty); . } . } 4,472 ( 0.00%) } . . pub fn walk_fn_ret_ty<'v, V: Visitor<'v>>(visitor: &mut V, ret_ty: &'v FnRetTy<'v>) { 17,194 ( 0.00%) if let FnRetTy::Return(ref output_ty) = *ret_ty { 9,150 ( 0.00%) visitor.visit_ty(output_ty) . } . } . 6,552 ( 0.00%) pub fn walk_fn_decl<'v, V: Visitor<'v>>(visitor: &mut V, function_declaration: &'v FnDecl<'v>) { 8,255 ( 0.00%) for ty in function_declaration.inputs { 2,721 ( 0.00%) visitor.visit_ty(ty) . } . walk_fn_ret_ty(visitor, &function_declaration.output) 3,536 ( 0.00%) } . . pub fn walk_fn_kind<'v, V: Visitor<'v>>(visitor: &mut V, function_kind: FnKind<'v>) { 12,108 ( 0.00%) match function_kind { . FnKind::ItemFn(_, generics, ..) => { 988 ( 0.00%) visitor.visit_generics(generics); . } . FnKind::Method(..) | FnKind::Closure => {} . } . } . 64,030 ( 0.00%) pub fn walk_fn<'v, V: Visitor<'v>>( . visitor: &mut V, . function_kind: FnKind<'v>, . function_declaration: &'v FnDecl<'v>, . body_id: BodyId, . _span: Span, . id: HirId, . ) { . visitor.visit_id(id); . visitor.visit_fn_decl(function_declaration); . walk_fn_kind(visitor, function_kind); 11,882 ( 0.00%) visitor.visit_nested_body(body_id) 36,792 ( 0.00%) } . 238 ( 0.00%) pub fn walk_trait_item<'v, V: Visitor<'v>>(visitor: &mut V, trait_item: &'v TraitItem<'v>) { 3 ( 0.00%) visitor.visit_ident(trait_item.ident); 3 ( 0.00%) visitor.visit_generics(&trait_item.generics); 189 ( 0.00%) match trait_item.kind { . TraitItemKind::Const(ref ty, default) => { . visitor.visit_id(trait_item.hir_id()); . visitor.visit_ty(ty); . walk_list!(visitor, visit_nested_body, default); . } 4 ( 0.00%) TraitItemKind::Fn(ref sig, TraitFn::Required(param_names)) => { 3 ( 0.00%) visitor.visit_id(trait_item.hir_id()); 27 ( 0.00%) visitor.visit_fn_decl(&sig.decl); 6 ( 0.00%) for ¶m_name in param_names { . visitor.visit_ident(param_name); . } . } . TraitItemKind::Fn(ref sig, TraitFn::Provided(body_id)) => { . visitor.visit_fn( . FnKind::Method(trait_item.ident, sig, None), . &sig.decl, . body_id, -- line 999 ---------------------------------------- -- line 1002 ---------------------------------------- . ); . } . TraitItemKind::Type(bounds, ref default) => { . visitor.visit_id(trait_item.hir_id()); . walk_list!(visitor, visit_param_bound, bounds); . walk_list!(visitor, visit_ty, default); . } . } 8 ( 0.00%) } . 8 ( 0.00%) pub fn walk_trait_item_ref<'v, V: Visitor<'v>>(visitor: &mut V, trait_item_ref: &'v TraitItemRef) { . // N.B., deliberately force a compilation error if/when new fields are added. 14 ( 0.00%) let TraitItemRef { id, ident, ref kind, span: _, ref defaultness } = *trait_item_ref; 7 ( 0.00%) visitor.visit_nested_trait_item(id); . visitor.visit_ident(ident); . visitor.visit_associated_item_kind(kind); . visitor.visit_defaultness(defaultness); 8 ( 0.00%) } . 46,711 ( 0.00%) pub fn walk_impl_item<'v, V: Visitor<'v>>(visitor: &mut V, impl_item: &'v ImplItem<'v>) { . // N.B., deliberately force a compilation error if/when new fields are added. 2,024 ( 0.00%) let ImplItem { def_id: _, ident, ref vis, ref defaultness, ref generics, ref kind, span: _ } = . *impl_item; . . visitor.visit_ident(ident); 197 ( 0.00%) visitor.visit_vis(vis); . visitor.visit_defaultness(defaultness); 1,935 ( 0.00%) visitor.visit_generics(generics); 26,750 ( 0.00%) match *kind { . ImplItemKind::Const(ref ty, body) => { . visitor.visit_id(impl_item.hir_id()); . visitor.visit_ty(ty); . visitor.visit_nested_body(body); . } 13,594 ( 0.00%) ImplItemKind::Fn(ref sig, body_id) => { 3,056 ( 0.00%) visitor.visit_fn( 17,647 ( 0.00%) FnKind::Method(impl_item.ident, sig, Some(&impl_item.vis)), 5,188 ( 0.00%) &sig.decl, . body_id, 764 ( 0.00%) impl_item.span, 2,292 ( 0.00%) impl_item.hir_id(), . ); . } . ImplItemKind::TyAlias(ref ty) => { 18 ( 0.00%) visitor.visit_id(impl_item.hir_id()); 258 ( 0.00%) visitor.visit_ty(ty); . } . } 34,807 ( 0.00%) } . . pub fn walk_foreign_item_ref<'v, V: Visitor<'v>>( . visitor: &mut V, . foreign_item_ref: &'v ForeignItemRef, . ) { . // N.B., deliberately force a compilation error if/when new fields are added. . let ForeignItemRef { id, ident, span: _ } = *foreign_item_ref; . visitor.visit_nested_foreign_item(id); . visitor.visit_ident(ident); . } . 1,576 ( 0.00%) pub fn walk_impl_item_ref<'v, V: Visitor<'v>>(visitor: &mut V, impl_item_ref: &'v ImplItemRef) { . // N.B., deliberately force a compilation error if/when new fields are added. 2,758 ( 0.00%) let ImplItemRef { id, ident, ref kind, span: _, ref defaultness, trait_item_def_id: _ } = . *impl_item_ref; 985 ( 0.00%) visitor.visit_nested_impl_item(id); . visitor.visit_ident(ident); . visitor.visit_associated_item_kind(kind); . visitor.visit_defaultness(defaultness); 1,576 ( 0.00%) } . 3,264 ( 0.00%) pub fn walk_struct_def<'v, V: Visitor<'v>>( . visitor: &mut V, . struct_definition: &'v VariantData<'v>, . ) { 2,122 ( 0.00%) walk_list!(visitor, visit_id, struct_definition.ctor_hir_id()); 3,097 ( 0.00%) walk_list!(visitor, visit_field_def, struct_definition.fields()); 2,890 ( 0.00%) } . 248 ( 0.00%) pub fn walk_field_def<'v, V: Visitor<'v>>(visitor: &mut V, field: &'v FieldDef<'v>) { 248 ( 0.00%) visitor.visit_id(field.hir_id); 186 ( 0.00%) visitor.visit_vis(&field.vis); 186 ( 0.00%) visitor.visit_ident(field.ident); 2,141 ( 0.00%) visitor.visit_ty(&field.ty); . } . 79,653 ( 0.00%) pub fn walk_block<'v, V: Visitor<'v>>(visitor: &mut V, block: &'v Block<'v>) { 2,496 ( 0.00%) visitor.visit_id(block.hir_id); 21,224 ( 0.00%) walk_list!(visitor, visit_stmt, block.stmts); 57,178 ( 0.00%) walk_list!(visitor, visit_expr, &block.expr); 23,932 ( 0.00%) } . 34,848 ( 0.00%) pub fn walk_stmt<'v, V: Visitor<'v>>(visitor: &mut V, statement: &'v Stmt<'v>) { 1,752 ( 0.00%) visitor.visit_id(statement.hir_id); 77,527 ( 0.00%) match statement.kind { 11,128 ( 0.00%) StmtKind::Local(ref local) => visitor.visit_local(local), 29 ( 0.00%) StmtKind::Item(item) => visitor.visit_nested_item(item), . StmtKind::Expr(ref expression) | StmtKind::Semi(ref expression) => { 18,554 ( 0.00%) visitor.visit_expr(expression) . } . } 19,292 ( 0.00%) } . . pub fn walk_array_len<'v, V: Visitor<'v>>(visitor: &mut V, len: &'v ArrayLen) { . match len { . &ArrayLen::Infer(hir_id, _span) => visitor.visit_id(hir_id), . ArrayLen::Body(c) => visitor.visit_anon_const(c), . } . } . . pub fn walk_anon_const<'v, V: Visitor<'v>>(visitor: &mut V, constant: &'v AnonConst) { . visitor.visit_id(constant.hir_id); . visitor.visit_nested_body(constant.body); . } . 690 ( 0.00%) pub fn walk_let_expr<'v, V: Visitor<'v>>(visitor: &mut V, let_expr: &'v Let<'v>) { . // match the visit order in walk_local 1,067 ( 0.00%) visitor.visit_expr(let_expr.init); 60 ( 0.00%) visitor.visit_id(let_expr.hir_id); 691 ( 0.00%) visitor.visit_pat(let_expr.pat); 1,653 ( 0.00%) walk_list!(visitor, visit_ty, let_expr.ty); 600 ( 0.00%) } . 44,838,077 ( 0.64%) pub fn walk_expr<'v, V: Visitor<'v>>(visitor: &mut V, expression: &'v Expr<'v>) { 9,614,536 ( 0.14%) visitor.visit_id(expression.hir_id); 24,745,165 ( 0.35%) match expression.kind { . ExprKind::Box(ref subexpression) => visitor.visit_expr(subexpression), . ExprKind::Array(subexpressions) => { 6,633,378 ( 0.09%) walk_list!(visitor, visit_expr, subexpressions); . } . ExprKind::ConstBlock(ref anon_const) => visitor.visit_anon_const(anon_const), . ExprKind::Repeat(ref element, ref count) => { . visitor.visit_expr(element); . visitor.visit_array_length(count) . } 19,820 ( 0.00%) ExprKind::Struct(ref qpath, fields, ref optional_base) => { 19,466 ( 0.00%) visitor.visit_qpath(qpath, expression.hir_id, expression.span); . for field in fields { 3,904 ( 0.00%) visitor.visit_id(field.hir_id); 2,928 ( 0.00%) visitor.visit_ident(field.ident); 66,785 ( 0.00%) visitor.visit_expr(&field.expr) . } 4,563 ( 0.00%) walk_list!(visitor, visit_expr, optional_base); . } . ExprKind::Tup(subexpressions) => { 12,918 ( 0.00%) walk_list!(visitor, visit_expr, subexpressions); . } 35,210 ( 0.00%) ExprKind::Call(ref callee_expression, arguments) => { 31,421 ( 0.00%) visitor.visit_expr(callee_expression); 45,132 ( 0.00%) walk_list!(visitor, visit_expr, arguments); . } 31,370 ( 0.00%) ExprKind::MethodCall(ref segment, arguments, _) => { 19,663 ( 0.00%) visitor.visit_path_segment(expression.span, segment); 46,368 ( 0.00%) walk_list!(visitor, visit_expr, arguments); . } 3,104 ( 0.00%) ExprKind::Binary(_, ref left_expression, ref right_expression) => { 15,415 ( 0.00%) visitor.visit_expr(left_expression); 7,159 ( 0.00%) visitor.visit_expr(right_expression) . } . ExprKind::AddrOf(_, _, ref subexpression) | ExprKind::Unary(_, ref subexpression) => { 5,100 ( 0.00%) visitor.visit_expr(subexpression) . } . ExprKind::Cast(ref subexpression, ref typ) | ExprKind::Type(ref subexpression, ref typ) => { 710 ( 0.00%) visitor.visit_expr(subexpression); 648 ( 0.00%) visitor.visit_ty(typ) . } 1,166 ( 0.00%) ExprKind::DropTemps(ref subexpression) => { 294 ( 0.00%) visitor.visit_expr(subexpression); . } 541 ( 0.00%) ExprKind::Let(ref let_expr) => visitor.visit_let_expr(let_expr), . ExprKind::If(ref cond, ref then, ref else_opt) => { 8,601 ( 0.00%) visitor.visit_expr(cond); 6,710 ( 0.00%) visitor.visit_expr(then); 1,523 ( 0.00%) walk_list!(visitor, visit_expr, else_opt); . } . ExprKind::Loop(ref block, ref opt_label, _, _) => { 19 ( 0.00%) walk_list!(visitor, visit_label, opt_label); 946 ( 0.00%) visitor.visit_block(block); . } 5,609 ( 0.00%) ExprKind::Match(ref subexpression, arms, _) => { 7,763 ( 0.00%) visitor.visit_expr(subexpression); 2,492 ( 0.00%) walk_list!(visitor, visit_arm, arms); . } 981 ( 0.00%) ExprKind::Closure(_, ref function_declaration, body, _fn_decl_span, _gen) => visitor . .visit_fn( 17 ( 0.00%) FnKind::Closure, 535 ( 0.00%) function_declaration, . body, 119 ( 0.00%) expression.span, 102 ( 0.00%) expression.hir_id, . ), . ExprKind::Block(ref block, ref opt_label) => { 605 ( 0.00%) walk_list!(visitor, visit_label, opt_label); 22,982 ( 0.00%) visitor.visit_block(block); . } 447 ( 0.00%) ExprKind::Assign(ref lhs, ref rhs, _) => { 480 ( 0.00%) visitor.visit_expr(rhs); 64 ( 0.00%) visitor.visit_expr(lhs) . } 280 ( 0.00%) ExprKind::AssignOp(_, ref left_expression, ref right_expression) => { 300 ( 0.00%) visitor.visit_expr(right_expression); 40 ( 0.00%) visitor.visit_expr(left_expression); . } 5,973 ( 0.00%) ExprKind::Field(ref subexpression, ident) => { 1,496 ( 0.00%) visitor.visit_expr(subexpression); . visitor.visit_ident(ident); . } 364 ( 0.00%) ExprKind::Index(ref main_expression, ref index_expression) => { 988 ( 0.00%) visitor.visit_expr(main_expression); 52 ( 0.00%) visitor.visit_expr(index_expression) . } 72,066 ( 0.00%) ExprKind::Path(ref qpath) => { 233,278 ( 0.00%) visitor.visit_qpath(qpath, expression.hir_id, expression.span); . } . ExprKind::Break(ref destination, ref opt_expr) => { 23 ( 0.00%) walk_list!(visitor, visit_label, &destination.label); 343 ( 0.00%) walk_list!(visitor, visit_expr, opt_expr); . } . ExprKind::Continue(ref destination) => { 1 ( 0.00%) walk_list!(visitor, visit_label, &destination.label); . } . ExprKind::Ret(ref optional_expression) => { 362 ( 0.00%) walk_list!(visitor, visit_expr, optional_expression); . } . ExprKind::InlineAsm(ref asm) => { . walk_inline_asm(visitor, asm); . } . ExprKind::Yield(ref subexpression, _) => { . visitor.visit_expr(subexpression); . } . ExprKind::Lit(_) | ExprKind::Err => {} . } 38,321,520 ( 0.54%) } . 12,220 ( 0.00%) pub fn walk_arm<'v, V: Visitor<'v>>(visitor: &mut V, arm: &'v Arm<'v>) { 828 ( 0.00%) visitor.visit_id(arm.hir_id); 13,848 ( 0.00%) visitor.visit_pat(&arm.pat); 45,198 ( 0.00%) if let Some(ref g) = arm.guard { . match g { . Guard::If(ref e) => visitor.visit_expr(e), . Guard::IfLet(ref pat, ref e) => { . visitor.visit_pat(pat); . visitor.visit_expr(e); . } . } . } 16,257 ( 0.00%) visitor.visit_expr(&arm.body); 4,968 ( 0.00%) } . 12,634 ( 0.00%) pub fn walk_vis<'v, V: Visitor<'v>>(visitor: &mut V, vis: &'v Visibility<'v>) { 38,635 ( 0.00%) if let VisibilityKind::Restricted { ref path, hir_id } = vis.node { . visitor.visit_id(hir_id); . visitor.visit_path(path, hir_id) . } 14,868 ( 0.00%) } . . pub fn walk_associated_item_kind<'v, V: Visitor<'v>>(_: &mut V, _: &'v AssocItemKind) { . // No visitable content here: this fn exists so you can call it if . // the right thing to do, should content be added in the future, . // would be to walk it. . } . . pub fn walk_defaultness<'v, V: Visitor<'v>>(_: &mut V, _: &'v Defaultness) { -- line 1263 ---------------------------------------- 1,655,034 ( 0.02%) -------------------------------------------------------------------------------- -- 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. 3,303,512 ( 0.05%) #[derive(Debug, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)] . pub enum TokenTree { . /// A single token. 1,257,263 ( 0.02%) Token(Token), . /// A delimited sequence of token trees. 11,962 ( 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 { 180 ( 0.00%) match self { 195 ( 0.00%) TokenTree::Token(token) => token.span, 152 ( 0.00%) TokenTree::Delimited(sp, ..) => sp.entire(), . } 52 ( 0.00%) } . . /// Modify the `TokenTree`'s span in-place. . pub fn set_span(&mut self, span: Span) { 180 ( 0.00%) match self { 52 ( 0.00%) TokenTree::Token(token) => token.span = span, 76 ( 0.00%) TokenTree::Delimited(dspan, ..) => *dspan = DelimSpan::from_single(span), . } 90 ( 0.00%) } . 286 ( 0.00%) pub fn token(kind: TokenKind, span: Span) -> TokenTree { 35,048 ( 0.00%) TokenTree::Token(Token::new(kind, span)) 286 ( 0.00%) } . . /// Returns the opening delimiter as a token tree. 4,297 ( 0.00%) pub fn open_tt(span: DelimSpan, delim: DelimToken) -> TokenTree { 12,891 ( 0.00%) TokenTree::token(token::OpenDelim(delim), span.open) 4,297 ( 0.00%) } . . /// Returns the closing delimiter as a token tree. 4,179 ( 0.00%) pub fn close_tt(span: DelimSpan, delim: DelimToken) -> TokenTree { 12,537 ( 0.00%) TokenTree::token(token::CloseDelim(delim), span.close) 4,179 ( 0.00%) } . 1,602 ( 0.00%) pub fn uninterpolate(self) -> TokenTree { 1,068 ( 0.00%) match self { 4,806 ( 0.00%) TokenTree::Token(token) => TokenTree::Token(token.uninterpolate().into_owned()), . tt => tt, . } 2,136 ( 0.00%) } . } . . impl HashStable for TokenStream . where . CTX: crate::HashStableContext, . { 4,779 ( 0.00%) fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) { 35,964 ( 0.00%) for sub_tt in self.trees() { . sub_tt.hash_stable(hcx, hasher); . } 4,248 ( 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 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 { 7,578 ( 0.00%) pub fn new(tokens: Vec<(AttrAnnotatedTokenTree, Spacing)>) -> AttrAnnotatedTokenStream { . AttrAnnotatedTokenStream(Lrc::new(tokens)) 7,578 ( 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. . pub fn to_tokenstream(&self) -> TokenStream { . let trees: Vec<_> = self -- line 206 ---------------------------------------- -- 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); . 323,737 ( 0.00%) #[derive(Clone, Copy, Debug, PartialEq, Encodable, Decodable)] . pub enum Spacing { . Alone, . Joint, . } . . impl TokenStream { . /// Given a `TokenStream` with a `Stream` of only two arguments, return a new `TokenStream` . /// separating the two arguments with a comma for diagnostic suggestions. -- line 332 ---------------------------------------- -- line 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 { 350 ( 0.00%) TokenStream::new(vec![(tree, Spacing::Alone)]) . } . } . . impl From for TreeAndSpacing { . fn from(tree: TokenTree) -> TreeAndSpacing { 14,635 ( 0.00%) (tree, Spacing::Alone) . } . } . . impl iter::FromIterator for TokenStream { . fn from_iter>(iter: I) -> Self { . TokenStream::new(iter.into_iter().map(Into::into).collect::>()) . } . } -- line 393 ---------------------------------------- -- line 401 ---------------------------------------- . } . . impl TokenStream { . pub fn new(streams: Vec) -> TokenStream { . TokenStream(Lrc::new(streams)) . } . . pub fn is_empty(&self) -> bool { 3,366 ( 0.00%) self.0.is_empty() 3,366 ( 0.00%) } . . pub fn len(&self) -> usize { 331,612 ( 0.00%) self.0.len() 43 ( 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,239 ( 0.00%) self.clone().into_trees() 2,478 ( 0.00%) } . 5,277 ( 0.00%) pub fn into_trees(self) -> Cursor { . Cursor::new(self) 10,554 ( 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 { 42 ( 0.00%) TokenStream(Lrc::new( . self.0 . .iter() . .enumerate() 540 ( 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; . 38,604 ( 0.00%) fn next(&mut self) -> Option { 73,651 ( 0.00%) self.next_with_spacing().map(|(tree, _)| tree) 51,472 ( 0.00%) } . } . . impl Cursor { . fn new(stream: TokenStream) -> Self { . Cursor { stream, index: 0 } . } . 1,593,290 ( 0.02%) pub fn next_with_spacing(&mut self) -> Option { 994,578 ( 0.01%) if self.index < self.stream.len() { 639,810 ( 0.01%) self.index += 1; 2,163,175 ( 0.03%) Some(self.stream.0[self.index - 1].clone()) . } else { 19,266 ( 0.00%) None . } 1,911,948 ( 0.03%) } . . 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; . } . 296,256 ( 0.00%) pub fn look_ahead(&self, n: usize) -> Option<&TokenTree> { 592,512 ( 0.01%) self.stream.0[self.index..].get(n).map(|(tree, _)| tree) 592,512 ( 0.01%) } . } . 26,091 ( 0.00%) #[derive(Debug, Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)] . pub struct DelimSpan { . pub open: Span, . pub close: Span, . } . . impl DelimSpan { 5 ( 0.00%) pub fn from_single(sp: Span) -> Self { . DelimSpan { open: sp, close: sp } 10 ( 0.00%) } . 6,730 ( 0.00%) pub fn from_pair(open: Span, close: Span) -> Self { . DelimSpan { open, close } 3,365 ( 0.00%) } . . pub fn dummy() -> Self { . Self::from_single(DUMMY_SP) 954 ( 0.00%) } . 2,112 ( 0.00%) pub fn entire(self) -> Span { . self.open.with_hi(self.close.hi()) 1,584 ( 0.00%) } . } 14,929 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast_pretty/src/pp/ring.rs -------------------------------------------------------------------------------- Ir -- line 22 ---------------------------------------- . RingBuffer { data: VecDeque::new(), offset: 0 } . } . . pub fn is_empty(&self) -> bool { . self.data.is_empty() . } . . pub fn push(&mut self, value: T) -> usize { 1,402,476 ( 0.02%) let index = self.offset + self.data.len(); 4,484,600 ( 0.06%) self.data.push_back(value); . index . } . . pub fn clear(&mut self) { 95 ( 0.00%) self.data.clear(); . } . . pub fn index_of_first(&self) -> usize { . self.offset . } . . pub fn first(&self) -> Option<&T> { . self.data.front() . } . . pub fn first_mut(&mut self) -> Option<&mut T> { . self.data.front_mut() . } . 3,506,190 ( 0.05%) pub fn pop_first(&mut self) -> Option { . let first = self.data.pop_front()?; 2,804,952 ( 0.04%) self.offset += 1; 4,207,428 ( 0.06%) Some(first) 4,908,666 ( 0.07%) } . . pub fn last(&self) -> Option<&T> { . self.data.back() . } . . pub fn last_mut(&mut self) -> Option<&mut T> { . self.data.back_mut() . } -- line 63 ---------------------------------------- 3,506,190 ( 0.05%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/expand.rs -------------------------------------------------------------------------------- Ir -- line 48 ---------------------------------------- . /// A fragment of AST that can be produced by a single macro expansion. . /// Can also serve as an input and intermediate result for macro expansion operations. . pub enum AstFragment { . OptExpr(Option>), . $($Kind($AstTy),)* . } . . /// "Discriminant" of an AST fragment. 63 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq)] . pub enum AstFragmentKind { . OptExpr, . $($Kind,)* . } . . impl AstFragmentKind { . pub fn name(self) -> &'static str { . match self { . AstFragmentKind::OptExpr => "expression", . $(AstFragmentKind::$Kind => $kind_name,)* . } . } . 210 ( 0.00%) fn make_from<'a>(self, result: Box) -> Option { 350 ( 0.00%) match self { . AstFragmentKind::OptExpr => 66 ( 0.00%) result.make_expr().map(Some).map(AstFragment::OptExpr), 81 ( 0.00%) $(AstFragmentKind::$Kind => result.$make_ast().map(AstFragment::$Kind),)* . } 210 ( 0.00%) } . } . . impl AstFragment { 164 ( 0.00%) pub fn add_placeholders(&mut self, placeholders: &[NodeId]) { 164 ( 0.00%) if placeholders.is_empty() { . return; . } 80 ( 0.00%) match self { 40 ( 0.00%) $($(AstFragment::$Kind(ast) => ast.extend(placeholders.iter().flat_map(|id| { . // We are repeating through arguments with `many`, to do that we have to . // mention some macro variable from those arguments even if it's not used. . macro _repeating($flat_map_ast_elt) {} 392 ( 0.00%) placeholder(AstFragmentKind::$Kind, *id, None).$make_ast() . })),)?)* . _ => panic!("unexpected AST fragment kind") . } 328 ( 0.00%) } . . pub fn make_opt_expr(self) -> Option> { 132 ( 0.00%) match self { 66 ( 0.00%) AstFragment::OptExpr(expr) => expr, . _ => panic!("AstFragment::make_* called on the wrong kind of fragment"), . } . } . . $(pub fn $make_ast(self) -> $AstTy { 574 ( 0.00%) match self { 834 ( 0.00%) AstFragment::$Kind(ast) => ast, . _ => panic!("AstFragment::make_* called on the wrong kind of fragment"), . } . })* . . fn make_ast(self) -> T::OutputTy { . T::fragment_to_output(self) . } . 328 ( 0.00%) pub fn mut_visit_with(&mut self, vis: &mut F) { 1,804 ( 0.00%) match self { . AstFragment::OptExpr(opt_expr) => { . visit_clobber(opt_expr, |opt_expr| { 132 ( 0.00%) if let Some(expr) = opt_expr { 165 ( 0.00%) vis.filter_map_expr(expr) . } else { . None . } . }); . } 432 ( 0.00%) $($(AstFragment::$Kind(ast) => vis.$mut_visit_ast(ast),)?)* 249 ( 0.00%) $($(AstFragment::$Kind(ast) => 1,795 ( 0.00%) ast.flat_map_in_place(|ast| vis.$flat_map_ast_elt(ast)),)?)* . } 66 ( 0.00%) } . 2,646 ( 0.00%) pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) { 1,668 ( 0.00%) match *self { . AstFragment::OptExpr(Some(ref expr)) => visitor.visit_expr(expr), . AstFragment::OptExpr(None) => {} 11 ( 0.00%) $($(AstFragment::$Kind(ref ast) => visitor.$visit_ast(ast),)?)* . $($(AstFragment::$Kind(ref ast) => for ast_elt in &ast[..] { 968 ( 0.00%) visitor.$visit_ast_elt(ast_elt, $($args)*); . })?)* . } 1,392 ( 0.00%) } . } . . impl<'a> MacResult for crate::mbe::macro_rules::ParserAnyMacro<'a> { 172 ( 0.00%) $(fn $make_ast(self: Box>) . -> Option<$AstTy> { 89 ( 0.00%) Some(self.make(AstFragmentKind::$Kind).$make_ast()) 132 ( 0.00%) })* . } . } . } . . ast_fragments! { . Expr(P) { "expression"; one fn visit_expr; fn visit_expr; fn make_expr; } . Pat(P) { "pattern"; one fn visit_pat; fn visit_pat; fn make_pat; } . Ty(P) { "type"; one fn visit_ty; fn visit_ty; fn make_ty; } -- line 154 ---------------------------------------- -- line 215 ---------------------------------------- . } . . impl AstFragmentKind { . crate fn dummy(self, span: Span) -> AstFragment { . self.make_from(DummyResult::any(span)).expect("couldn't create a dummy AST fragment") . } . . pub fn supports_macro_expansion(self) -> SupportsMacroExpansion { 438 ( 0.00%) match self { . AstFragmentKind::OptExpr . | AstFragmentKind::Expr . | AstFragmentKind::Stmts . | AstFragmentKind::Ty . | AstFragmentKind::Pat => SupportsMacroExpansion::Yes { supports_inner_attrs: false }, . AstFragmentKind::Items . | AstFragmentKind::TraitItems . | AstFragmentKind::ImplItems -- line 231 ---------------------------------------- -- line 234 ---------------------------------------- . AstFragmentKind::Arms . | AstFragmentKind::ExprFields . | AstFragmentKind::PatFields . | AstFragmentKind::GenericParams . | AstFragmentKind::Params . | AstFragmentKind::FieldDefs . | AstFragmentKind::Variants => SupportsMacroExpansion::No, . } 146 ( 0.00%) } . 228 ( 0.00%) fn expect_from_annotatables>( . self, . items: I, . ) -> AstFragment { . let mut items = items.into_iter(); 380 ( 0.00%) match self { . AstFragmentKind::Arms => { . AstFragment::Arms(items.map(Annotatable::expect_arm).collect()) . } . AstFragmentKind::ExprFields => { . AstFragment::ExprFields(items.map(Annotatable::expect_expr_field).collect()) . } . AstFragmentKind::PatFields => { . AstFragment::PatFields(items.map(Annotatable::expect_pat_field).collect()) -- line 257 ---------------------------------------- -- line 264 ---------------------------------------- . } . AstFragmentKind::FieldDefs => { . AstFragment::FieldDefs(items.map(Annotatable::expect_field_def).collect()) . } . AstFragmentKind::Variants => { . AstFragment::Variants(items.map(Annotatable::expect_variant).collect()) . } . AstFragmentKind::Items => { 380 ( 0.00%) AstFragment::Items(items.map(Annotatable::expect_item).collect()) . } . AstFragmentKind::ImplItems => { . AstFragment::ImplItems(items.map(Annotatable::expect_impl_item).collect()) . } . AstFragmentKind::TraitItems => { . AstFragment::TraitItems(items.map(Annotatable::expect_trait_item).collect()) . } . AstFragmentKind::ForeignItems => { -- line 280 ---------------------------------------- -- line 291 ---------------------------------------- . } . AstFragmentKind::Crate => { . AstFragment::Crate(items.next().expect("expected exactly one crate").expect_crate()) . } . AstFragmentKind::Pat | AstFragmentKind::Ty => { . panic!("patterns and types aren't annotatable") . } . } 228 ( 0.00%) } . } . . pub struct Invocation { . pub kind: InvocationKind, . pub fragment_kind: AstFragmentKind, . pub expansion_data: ExpansionData, . } . -- line 307 ---------------------------------------- -- line 326 ---------------------------------------- . . impl InvocationKind { . fn placeholder_visibility(&self) -> Option { . // HACK: For unnamed fields placeholders should have the same visibility as the actual . // fields because for tuple structs/variants resolve determines visibilities of their . // constructor using these field visibilities before attributes on them are are expanded. . // The assumption is that the attribute expansion cannot change field visibilities, . // and it holds because only inert attributes are supported in this position. 450 ( 0.00%) match self { . InvocationKind::Attr { item: Annotatable::FieldDef(field), .. } . | InvocationKind::Derive { item: Annotatable::FieldDef(field), .. } . if field.ident.is_none() => . { . Some(field.vis.clone()) . } 90 ( 0.00%) _ => None, . } . } . } . . impl Invocation { . pub fn span(&self) -> Span { 1,326 ( 0.00%) match &self.kind { 70 ( 0.00%) InvocationKind::Bang { span, .. } => *span, 20 ( 0.00%) InvocationKind::Attr { attr, .. } => attr.span, 56 ( 0.00%) InvocationKind::Derive { path, .. } => path.span, . } 146 ( 0.00%) } . } . . pub struct MacroExpander<'a, 'b> { . pub cx: &'a mut ExtCtxt<'b>, . monotonic: bool, // cf. `cx.monotonic_expander()` . } . . impl<'a, 'b> MacroExpander<'a, 'b> { . pub fn new(cx: &'a mut ExtCtxt<'b>, monotonic: bool) -> Self { . MacroExpander { cx, monotonic } . } . 10 ( 0.00%) pub fn expand_crate(&mut self, krate: ast::Crate) -> ast::Crate { 6 ( 0.00%) let file_path = match self.cx.source_map().span_to_filename(krate.span) { 11 ( 0.00%) FileName::Real(name) => name . .into_local_path() . .expect("attempting to resolve a file path in an external file"), . other => PathBuf::from(other.prefer_local().to_string()), . }; 4 ( 0.00%) let dir_path = file_path.parent().unwrap_or(&file_path).to_owned(); 3 ( 0.00%) self.cx.root_path = dir_path.clone(); 1 ( 0.00%) self.cx.current_expansion.module = Rc::new(ModuleData { 3 ( 0.00%) mod_path: vec![Ident::from_str(&self.cx.ecfg.crate_name)], 4 ( 0.00%) file_path_stack: vec![file_path], . dir_path, . }); 13 ( 0.00%) let krate = self.fully_expand_fragment(AstFragment::Crate(krate)).make_crate(); 1 ( 0.00%) assert_eq!(krate.id, ast::CRATE_NODE_ID); 2 ( 0.00%) self.cx.trace_macros_diag(); . krate 9 ( 0.00%) } . . // Recursively expand all macro invocations in this AST fragment. 162 ( 0.00%) pub fn fully_expand_fragment(&mut self, input_fragment: AstFragment) -> AstFragment { 18 ( 0.00%) let orig_expansion_data = self.cx.current_expansion.clone(); 54 ( 0.00%) let orig_force_mode = self.cx.force_mode; . . // Collect all macro invocations and replace them with placeholders. 144 ( 0.00%) let (mut fragment_with_placeholders, mut invocations) = 180 ( 0.00%) self.collect_invocations(input_fragment, &[]); . . // Optimization: if we resolve all imports now, . // we'll be able to immediately resolve most of imported macros. . self.resolve_imports(); . . // Resolve paths in all invocations and produce output expanded fragments for them, but . // do not insert them into our input AST fragment yet, only store in `expanded_fragments`. . // The output fragments also go through expansion recursively until no invocations are left. . // Unresolved macros produce dummy outputs as a recovery measure. . invocations.reverse(); . let mut expanded_fragments = Vec::new(); . let mut undetermined_invocations = Vec::new(); 108 ( 0.00%) let (mut progress, mut force) = (false, !self.monotonic); . loop { 1,022 ( 0.00%) let Some((invoc, ext)) = invocations.pop() else { . self.resolve_imports(); 18 ( 0.00%) if undetermined_invocations.is_empty() { . break; . } . invocations = mem::take(&mut undetermined_invocations); . force = !mem::replace(&mut progress, false); . if force && self.monotonic { . self.cx.sess.delay_span_bug( . invocations.last().unwrap().0.span(), . "expansion entered force mode without producing any errors", . ); . } . continue; . }; . 292 ( 0.00%) let ext = match ext { . Some(ext) => ext, . None => { 438 ( 0.00%) let eager_expansion_root = if self.monotonic { . invoc.expansion_data.id . } else { . orig_expansion_data.id . }; 1,314 ( 0.00%) match self.cx.resolver.resolve_macro_invocation( . &invoc, . eager_expansion_root, . force, . ) { . Ok(ext) => ext, . Err(Indeterminate) => { . // Cannot resolve, will retry this invocation later. . undetermined_invocations.push((invoc, None)); . continue; . } . } . } . }; . 146 ( 0.00%) let ExpansionData { depth, id: expn_id, .. } = invoc.expansion_data; 438 ( 0.00%) let depth = depth - orig_expansion_data.depth; 2,482 ( 0.00%) self.cx.current_expansion = invoc.expansion_data.clone(); 146 ( 0.00%) self.cx.force_mode = force; . 292 ( 0.00%) let fragment_kind = invoc.fragment_kind; 2,336 ( 0.00%) let (expanded_fragment, new_invocations) = match self.expand_invoc(invoc, &ext.kind) { 2,774 ( 0.00%) ExpandResult::Ready(fragment) => { . let mut derive_invocations = Vec::new(); 730 ( 0.00%) let derive_placeholders = self . .cx . .resolver . .take_derive_resolutions(expn_id) . .map(|derives| { . derive_invocations.reserve(derives.len()); . derives . .into_iter() 1,792 ( 0.00%) .map(|(path, item, _exts)| { . // FIXME: Consider using the derive resolutions (`_exts`) . // instead of enqueuing the derives to be resolved again later. 56 ( 0.00%) let expn_id = LocalExpnId::fresh_empty(); 672 ( 0.00%) derive_invocations.push(( 1,288 ( 0.00%) Invocation { 1,232 ( 0.00%) kind: InvocationKind::Derive { path, item }, . fragment_kind, . expansion_data: ExpansionData { . id: expn_id, 56 ( 0.00%) ..self.cx.current_expansion.clone() . }, . }, . None, . )); 112 ( 0.00%) NodeId::placeholder_from_expn_id(expn_id) 448 ( 0.00%) }) . .collect::>() . }) . .unwrap_or_default(); . 1,022 ( 0.00%) let (fragment, collected_invocations) = 1,898 ( 0.00%) self.collect_invocations(fragment, &derive_placeholders); . // We choose to expand any derive invocations associated with this macro invocation . // *before* any macro invocations collected from the output fragment . derive_invocations.extend(collected_invocations); 1,314 ( 0.00%) (fragment, derive_invocations) . } . ExpandResult::Retry(invoc) => { . if force { . self.cx.span_bug( . invoc.span(), . "expansion entered force mode but is still stuck", . ); . } else { -- line 498 ---------------------------------------- -- line 499 ---------------------------------------- . // Cannot expand, will retry this invocation later. . undetermined_invocations.push((invoc, Some(ext))); . continue; . } . } . }; . . progress = true; 438 ( 0.00%) if expanded_fragments.len() < depth { . expanded_fragments.push(Vec::new()); . } 1,022 ( 0.00%) expanded_fragments[depth - 1].push((expn_id, expanded_fragment)); . invocations.extend(new_invocations.into_iter().rev()); . } . 414 ( 0.00%) self.cx.current_expansion = orig_expansion_data; 18 ( 0.00%) self.cx.force_mode = orig_force_mode; . . // Finally incorporate all the expanded macros into the input AST fragment. . let mut placeholder_expander = PlaceholderExpander::default(); 8 ( 0.00%) while let Some(expanded_fragments) = expanded_fragments.pop() { 2,798 ( 0.00%) for (expn_id, expanded_fragment) in expanded_fragments.into_iter().rev() { . placeholder_expander 730 ( 0.00%) .add(NodeId::placeholder_from_expn_id(expn_id), expanded_fragment); . } . } 18 ( 0.00%) fragment_with_placeholders.mut_visit_with(&mut placeholder_expander); . fragment_with_placeholders 144 ( 0.00%) } . . fn resolve_imports(&mut self) { 126 ( 0.00%) if self.monotonic { 8 ( 0.00%) self.cx.resolver.resolve_imports(); . } . } . . /// Collects all macro invocations reachable at this time in this AST fragment, and replace . /// them with "placeholders" - dummy macro invocations with specially crafted `NodeId`s. . /// Then call into resolver that builds a skeleton ("reduced graph") of the fragment and . /// prepares data for resolving paths of macro invocations. 1,968 ( 0.00%) fn collect_invocations( . &mut self, . mut fragment: AstFragment, . extra_placeholders: &[NodeId], . ) -> (AstFragment, Vec<(Invocation, Option>)>) { . // Resolve `$crate`s in the fragment for pretty-printing. 656 ( 0.00%) self.cx.resolver.resolve_dollar_crates(); . . let mut invocations = { 984 ( 0.00%) let mut collector = InvocationCollector { . // Non-derive macro invocations cannot see the results of cfg expansion - they . // will either be removed along with the item, or invoked before the cfg/cfg_attr . // attribute is expanded. Therefore, we don't need to configure the tokens . // Derive macros *can* see the results of cfg-expansion - they are handled . // specially in `fully_expand_fragment` . cfg: StripUnconfigured { 164 ( 0.00%) sess: &self.cx.sess, 164 ( 0.00%) features: self.cx.ecfg.features, . config_tokens: false, . }, . cx: self.cx, . invocations: Vec::new(), 164 ( 0.00%) monotonic: self.monotonic, . }; . fragment.mut_visit_with(&mut collector); 656 ( 0.00%) fragment.add_placeholders(extra_placeholders); 656 ( 0.00%) collector.invocations . }; . 328 ( 0.00%) if self.monotonic { 441 ( 0.00%) self.cx . .resolver 294 ( 0.00%) .visit_ast_fragment_with_placeholders(self.cx.current_expansion.id, &fragment); . 441 ( 0.00%) if self.cx.sess.opts.debugging_opts.incremental_relative_spans { . for (invoc, _) in invocations.iter_mut() { . let expn_id = invoc.expansion_data.id; . let parent_def = self.cx.resolver.invocation_parent(expn_id); . let span = match &mut invoc.kind { . InvocationKind::Bang { ref mut span, .. } => span, . InvocationKind::Attr { attr, .. } => &mut attr.span, . InvocationKind::Derive { path, .. } => &mut path.span, . }; . *span = span.with_parent(Some(parent_def)); . } . } . } . 1,476 ( 0.00%) (fragment, invocations) 1,312 ( 0.00%) } . . fn error_recursion_limit_reached(&mut self) { . let expn_data = self.cx.current_expansion.id.expn_data(); . let suggested_limit = match self.cx.ecfg.recursion_limit { . Limit(0) => Limit(2), . limit => limit * 2, . }; . self.cx -- line 596 ---------------------------------------- -- line 620 ---------------------------------------- . } . . fn expand_invoc( . &mut self, . invoc: Invocation, . ext: &SyntaxExtensionKind, . ) -> ExpandResult { . let recursion_limit = 146 ( 0.00%) self.cx.reduced_recursion_limit.unwrap_or(self.cx.ecfg.recursion_limit); 146 ( 0.00%) if !recursion_limit.value_within_limit(self.cx.current_expansion.depth) { . if self.cx.reduced_recursion_limit.is_none() { . self.error_recursion_limit_reached(); . } . . // Reduce the recursion limit by half each time it triggers. . self.cx.reduced_recursion_limit = Some(recursion_limit / 2); . . return ExpandResult::Ready(invoc.fragment_kind.dummy(invoc.span())); . } . 292 ( 0.00%) let (fragment_kind, span) = (invoc.fragment_kind, invoc.span()); 3,066 ( 0.00%) ExpandResult::Ready(match invoc.kind { 910 ( 0.00%) InvocationKind::Bang { mac, .. } => match ext { . SyntaxExtensionKind::Bang(expander) => { . let tok_result = match expander.expand(self.cx, span, mac.args.inner_tokens()) { . Err(_) => return ExpandResult::Ready(fragment_kind.dummy(span)), . Ok(ts) => ts, . }; . self.parse_ast_fragment(tok_result, fragment_kind, &mac.path, span) . } . SyntaxExtensionKind::LegacyBang(expander) => { 350 ( 0.00%) let prev = self.cx.current_expansion.prior_type_ascription; 280 ( 0.00%) self.cx.current_expansion.prior_type_ascription = mac.prior_type_ascription; 560 ( 0.00%) let tok_result = expander.expand(self.cx, span, mac.args.inner_tokens()); 1,120 ( 0.00%) let result = if let Some(result) = fragment_kind.make_from(tok_result) { . result . } else { . self.error_wrong_fragment_kind(fragment_kind, &mac, span); . fragment_kind.dummy(span) . }; 280 ( 0.00%) self.cx.current_expansion.prior_type_ascription = prev; 280 ( 0.00%) result . } . _ => unreachable!(), 210 ( 0.00%) }, 920 ( 0.00%) InvocationKind::Attr { attr, pos, mut item, derives } => match ext { . SyntaxExtensionKind::Attr(expander) => { . self.gate_proc_macro_input(&item); . self.gate_proc_macro_attr_item(span, &item); . let tokens = match &item { . // FIXME: Collect tokens and use them instead of generating . // fake ones. These are unstable, so it needs to be . // fixed prior to stabilization . // Fake tokens when we are invoking an inner attribute, and -- line 673 ---------------------------------------- -- line 700 ---------------------------------------- . let inner_tokens = attr_item.args.inner_tokens(); . let tok_result = match expander.expand(self.cx, span, inner_tokens, tokens) { . Err(_) => return ExpandResult::Ready(fragment_kind.dummy(span)), . Ok(ts) => ts, . }; . self.parse_ast_fragment(tok_result, fragment_kind, &attr_item.path, span) . } . SyntaxExtensionKind::LegacyAttr(expander) => { 180 ( 0.00%) match validate_attr::parse_meta(&self.cx.sess.parse_sess, &attr) { 280 ( 0.00%) Ok(meta) => { 560 ( 0.00%) let items = match expander.expand(self.cx, span, &meta, item) { 100 ( 0.00%) ExpandResult::Ready(items) => items, . ExpandResult::Retry(item) => { . // Reassemble the original invocation for retrying. . return ExpandResult::Retry(Invocation { . kind: InvocationKind::Attr { attr, pos, item, derives }, . ..invoc . }); . } . }; 20 ( 0.00%) if fragment_kind == AstFragmentKind::Expr && items.is_empty() { . let msg = . "removing an expression is not supported in this position"; . self.cx.span_err(span, msg); . fragment_kind.dummy(span) . } else { 160 ( 0.00%) fragment_kind.expect_from_annotatables(items) . } 40 ( 0.00%) } . Err(mut err) => { . err.emit(); . fragment_kind.dummy(span) . } . } . } . SyntaxExtensionKind::NonMacroAttr => { . self.cx.expanded_inert_attrs.mark(&attr); . item.visit_attrs(|attrs| attrs.insert(pos, attr)); . fragment_kind.expect_from_annotatables(iter::once(item)) . } . _ => unreachable!(), 80 ( 0.00%) }, 1,512 ( 0.00%) InvocationKind::Derive { path, item } => match ext { . SyntaxExtensionKind::Derive(expander) . | SyntaxExtensionKind::LegacyDerive(expander) => { 112 ( 0.00%) if let SyntaxExtensionKind::Derive(..) = ext { . self.gate_proc_macro_input(&item); . } 448 ( 0.00%) let meta = ast::MetaItem { kind: MetaItemKind::Word, span, path }; 1,568 ( 0.00%) let items = match expander.expand(self.cx, span, &meta, item) { 224 ( 0.00%) ExpandResult::Ready(items) => items, . ExpandResult::Retry(item) => { . // Reassemble the original invocation for retrying. . return ExpandResult::Retry(Invocation { . kind: InvocationKind::Derive { path: meta.path, item }, . ..invoc . }); . } . }; 336 ( 0.00%) fragment_kind.expect_from_annotatables(items) 168 ( 0.00%) } . _ => unreachable!(), . }, . }) . } . . fn gate_proc_macro_attr_item(&self, span: Span, item: &Annotatable) { . let kind = match item { . Annotatable::Item(_) -- line 768 ---------------------------------------- -- line 852 ---------------------------------------- . err.emit(); . self.cx.trace_macros_diag(); . kind.dummy(span) . } . } . } . } . 387 ( 0.00%) pub fn parse_ast_fragment<'a>( . this: &mut Parser<'a>, . kind: AstFragmentKind, . ) -> PResult<'a, AstFragment> { 1,118 ( 0.00%) Ok(match kind { . AstFragmentKind::Items => { . let mut items = SmallVec::new(); 465 ( 0.00%) while let Some(item) = this.parse_item(ForceCollect::No)? { . items.push(item); . } 5 ( 0.00%) AstFragment::Items(items) . } . AstFragmentKind::TraitItems => { . let mut items = SmallVec::new(); . while let Some(item) = this.parse_trait_item(ForceCollect::No)? { . items.extend(item); . } . AstFragment::TraitItems(items) . } -- line 878 ---------------------------------------- -- line 888 ---------------------------------------- . while let Some(item) = this.parse_foreign_item(ForceCollect::No)? { . items.extend(item); . } . AstFragment::ForeignItems(items) . } . AstFragmentKind::Stmts => { . let mut stmts = SmallVec::new(); . // Won't make progress on a `}`. 12 ( 0.00%) while this.token != token::Eof && this.token != token::CloseDelim(token::Brace) { 12 ( 0.00%) if let Some(stmt) = this.parse_full_stmt(AttemptLocalParseRecovery::Yes)? { 10 ( 0.00%) stmts.push(stmt); . } . } 16 ( 0.00%) AstFragment::Stmts(stmts) . } 40 ( 0.00%) AstFragmentKind::Expr => AstFragment::Expr(this.parse_expr()?), . AstFragmentKind::OptExpr => { . if this.token != token::Eof { . AstFragment::OptExpr(Some(this.parse_expr()?)) . } else { . AstFragment::OptExpr(None) . } . } . AstFragmentKind::Ty => AstFragment::Ty(this.parse_ty()?), -- line 911 ---------------------------------------- -- line 918 ---------------------------------------- . AstFragmentKind::Arms . | AstFragmentKind::ExprFields . | AstFragmentKind::PatFields . | AstFragmentKind::GenericParams . | AstFragmentKind::Params . | AstFragmentKind::FieldDefs . | AstFragmentKind::Variants => panic!("unexpected AST fragment kind"), . }) 387 ( 0.00%) } . 516 ( 0.00%) pub fn ensure_complete_parse<'a>( . this: &mut Parser<'a>, . macro_path: &ast::Path, . kind_name: &str, . span: Span, . ) { 129 ( 0.00%) if this.token != token::Eof { . let token = pprust::token_to_string(&this.token); . let msg = format!("macro expansion ignores token `{}` and any following", token); . // Avoid emitting backtrace info twice. . let def_site_span = this.token.span.with_ctxt(SyntaxContext::root()); . let mut err = this.struct_span_err(def_site_span, &msg); . err.span_label(span, "caused by the macro expansion here"); . let msg = format!( . "the usage of `{}!` is likely invalid in {} context", -- line 942 ---------------------------------------- -- line 955 ---------------------------------------- . ";".to_owned(), . Applicability::MaybeIncorrect, . ); . } . _ => {} . } . err.emit(); . } 344 ( 0.00%) } . . /// Wraps a call to `noop_visit_*` / `noop_flat_map_*` . /// for an AST node that supports attributes . /// (see the `Annotatable` enum) . /// This method assigns a `NodeId`, and sets that `NodeId` . /// as our current 'lint node id'. If a macro call is found . /// inside this AST node, we will use this AST node's `NodeId` . /// to emit lints associated with that macro (allowing -- line 971 ---------------------------------------- -- line 1031 ---------------------------------------- . fn pre_flat_map_node_collect_attr(_cfg: &StripUnconfigured<'_>, _attr: &ast::Attribute) {} . fn post_flat_map_node_collect_bang(_output: &mut Self::OutputTy, _add_semicolon: AddSemicolon) { . } . fn wrap_flat_map_node_noop_flat_map( . node: Self, . collector: &mut InvocationCollector<'_, '_>, . noop_flat_map: impl FnOnce(Self, &mut InvocationCollector<'_, '_>) -> Self::OutputTy, . ) -> Result { 19,805 ( 0.00%) Ok(noop_flat_map(node, collector)) . } . } . . impl InvocationCollectorNode for P { . const KIND: AstFragmentKind = AstFragmentKind::Items; . fn to_annotatable(self) -> Annotatable { . Annotatable::Item(self) . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { 62 ( 0.00%) fragment.make_items() . } . fn id(&mut self) -> &mut NodeId { . &mut self.id . } . fn noop_flat_map(self, visitor: &mut V) -> Self::OutputTy { 1,338 ( 0.00%) noop_flat_map_item(self, visitor) . } . fn is_mac_call(&self) -> bool { 451 ( 0.00%) matches!(self.kind, ItemKind::MacCall(..)) . } 6 ( 0.00%) fn take_mac_call(self) -> (ast::MacCall, Self::AttrsTy, AddSemicolon) { . let node = self.into_inner(); 2 ( 0.00%) match node.kind { 13 ( 0.00%) ItemKind::MacCall(mac) => (mac, node.attrs, AddSemicolon::No), . _ => unreachable!(), . } 5 ( 0.00%) } 4,950 ( 0.00%) fn wrap_flat_map_node_noop_flat_map( . mut node: Self, . collector: &mut InvocationCollector<'_, '_>, . noop_flat_map: impl FnOnce(Self, &mut InvocationCollector<'_, '_>) -> Self::OutputTy, . ) -> Result { 900 ( 0.00%) if !matches!(node.kind, ItemKind::Mod(..)) { 2,568 ( 0.00%) return Ok(noop_flat_map(node, collector)); . } . . // Work around borrow checker not seeing through `P`'s deref. 242 ( 0.00%) let (ident, span, mut attrs) = (node.ident, node.span, mem::take(&mut node.attrs)); . let ItemKind::Mod(_, mod_kind) = &mut node.kind else { . unreachable!() . }; . . let ecx = &mut collector.cx; 44 ( 0.00%) let (file_path, dir_path, dir_ownership) = match mod_kind { . ModKind::Loaded(_, inline, _) => { . // Inline `mod foo { ... }`, but we still need to push directories. 56 ( 0.00%) let (dir_path, dir_ownership) = mod_dir_path( 8 ( 0.00%) &ecx.sess, 8 ( 0.00%) ident, . &attrs, 4 ( 0.00%) &ecx.current_expansion.module, 4 ( 0.00%) ecx.current_expansion.dir_ownership, 8 ( 0.00%) *inline, . ); 44 ( 0.00%) node.attrs = attrs; . (None, dir_path, dir_ownership) . } . ModKind::Unloaded => { . // We have an outline `mod foo;` so we need to parse the file. 36 ( 0.00%) let old_attrs_len = attrs.len(); 342 ( 0.00%) let ParsedExternalMod { items, inner_span, file_path, dir_path, dir_ownership } = 144 ( 0.00%) parse_external_mod( 36 ( 0.00%) &ecx.sess, 36 ( 0.00%) ident, . span, 18 ( 0.00%) &ecx.current_expansion.module, 18 ( 0.00%) ecx.current_expansion.dir_ownership, . &mut attrs, . ); . 90 ( 0.00%) if let Some(lint_store) = ecx.lint_store { 234 ( 0.00%) lint_store.pre_expansion_lint( 36 ( 0.00%) ecx.sess, 72 ( 0.00%) ecx.resolver.registered_tools(), 36 ( 0.00%) ecx.current_expansion.lint_node_id, . &attrs, . &items, 18 ( 0.00%) ident.name.as_str(), . ); . } . 216 ( 0.00%) *mod_kind = ModKind::Loaded(items, Inline::No, inner_span); 162 ( 0.00%) node.attrs = attrs; 36 ( 0.00%) if node.attrs.len() > old_attrs_len { . // If we loaded an out-of-line module and added some inner attributes, . // then we need to re-configure it and re-collect attributes for . // resolution and expansion. 12 ( 0.00%) return Err(node); . } . (Some(file_path), dir_path, dir_ownership) . } . }; . . // Set the module info before we flat map. 126 ( 0.00%) let mut module = ecx.current_expansion.module.with_dir_path(dir_path); 36 ( 0.00%) module.mod_path.push(ident); 36 ( 0.00%) if let Some(file_path) = file_path { . module.file_path_stack.push(file_path); . } . 36 ( 0.00%) let orig_module = mem::replace(&mut ecx.current_expansion.module, Rc::new(module)); . let orig_dir_ownership = 18 ( 0.00%) mem::replace(&mut ecx.current_expansion.dir_ownership, dir_ownership); . 90 ( 0.00%) let res = Ok(noop_flat_map(node, collector)); . 54 ( 0.00%) collector.cx.current_expansion.dir_ownership = orig_dir_ownership; 72 ( 0.00%) collector.cx.current_expansion.module = orig_module; 72 ( 0.00%) res 4,050 ( 0.00%) } . } . . struct TraitItemTag; . impl InvocationCollectorNode for AstLikeWrapper, TraitItemTag> { . type OutputTy = SmallVec<[P; 1]>; . const KIND: AstFragmentKind = AstFragmentKind::TraitItems; . fn to_annotatable(self) -> Annotatable { . Annotatable::TraitItem(self.wrapped) -- line 1157 ---------------------------------------- -- line 1158 ---------------------------------------- . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { . fragment.make_trait_items() . } . fn id(&mut self) -> &mut NodeId { . &mut self.wrapped.id . } . fn noop_flat_map(self, visitor: &mut V) -> Self::OutputTy { 2 ( 0.00%) noop_flat_map_assoc_item(self.wrapped, visitor) . } . fn is_mac_call(&self) -> bool { 1 ( 0.00%) matches!(self.wrapped.kind, AssocItemKind::MacCall(..)) . } . fn take_mac_call(self) -> (ast::MacCall, Self::AttrsTy, AddSemicolon) { . let item = self.wrapped.into_inner(); . match item.kind { . AssocItemKind::MacCall(mac) => (mac, item.attrs, AddSemicolon::No), . _ => unreachable!(), . } . } -- line 1177 ---------------------------------------- -- line 1186 ---------------------------------------- . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { . fragment.make_impl_items() . } . fn id(&mut self) -> &mut NodeId { . &mut self.wrapped.id . } . fn noop_flat_map(self, visitor: &mut V) -> Self::OutputTy { 394 ( 0.00%) noop_flat_map_assoc_item(self.wrapped, visitor) . } . fn is_mac_call(&self) -> bool { 197 ( 0.00%) matches!(self.wrapped.kind, AssocItemKind::MacCall(..)) . } . fn take_mac_call(self) -> (ast::MacCall, Self::AttrsTy, AddSemicolon) { . let item = self.wrapped.into_inner(); . match item.kind { . AssocItemKind::MacCall(mac) => (mac, item.attrs, AddSemicolon::No), . _ => unreachable!(), . } . } -- line 1205 ---------------------------------------- -- line 1238 ---------------------------------------- . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { . fragment.make_variants() . } . fn id(&mut self) -> &mut NodeId { . &mut self.id . } . fn noop_flat_map(self, visitor: &mut V) -> Self::OutputTy { 550 ( 0.00%) noop_flat_map_variant(self, visitor) . } . } . . impl InvocationCollectorNode for ast::FieldDef { . const KIND: AstFragmentKind = AstFragmentKind::FieldDefs; . fn to_annotatable(self) -> Annotatable { . Annotatable::FieldDef(self) . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { . fragment.make_field_defs() . } . fn id(&mut self) -> &mut NodeId { . &mut self.id . } . fn noop_flat_map(self, visitor: &mut V) -> Self::OutputTy { 1,178 ( 0.00%) noop_flat_map_field_def(self, visitor) . } . } . . impl InvocationCollectorNode for ast::PatField { . const KIND: AstFragmentKind = AstFragmentKind::PatFields; . fn to_annotatable(self) -> Annotatable { . Annotatable::PatField(self) . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { . fragment.make_pat_fields() . } . fn id(&mut self) -> &mut NodeId { . &mut self.id . } . fn noop_flat_map(self, visitor: &mut V) -> Self::OutputTy { 2,280 ( 0.00%) noop_flat_map_pat_field(self, visitor) . } . } . . impl InvocationCollectorNode for ast::ExprField { . const KIND: AstFragmentKind = AstFragmentKind::ExprFields; . fn to_annotatable(self) -> Annotatable { . Annotatable::ExprField(self) . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { . fragment.make_expr_fields() . } . fn id(&mut self) -> &mut NodeId { . &mut self.id . } . fn noop_flat_map(self, visitor: &mut V) -> Self::OutputTy { 14,010 ( 0.00%) noop_flat_map_expr_field(self, visitor) . } . } . . impl InvocationCollectorNode for ast::Param { . const KIND: AstFragmentKind = AstFragmentKind::Params; . fn to_annotatable(self) -> Annotatable { . Annotatable::Param(self) . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { . fragment.make_params() . } . fn id(&mut self) -> &mut NodeId { . &mut self.id . } . fn noop_flat_map(self, visitor: &mut V) -> Self::OutputTy { 6,660 ( 0.00%) noop_flat_map_param(self, visitor) . } . } . . impl InvocationCollectorNode for ast::GenericParam { . const KIND: AstFragmentKind = AstFragmentKind::GenericParams; . fn to_annotatable(self) -> Annotatable { . Annotatable::GenericParam(self) . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { . fragment.make_generic_params() . } . fn id(&mut self) -> &mut NodeId { . &mut self.id . } . fn noop_flat_map(self, visitor: &mut V) -> Self::OutputTy { 3,780 ( 0.00%) noop_flat_map_generic_param(self, visitor) . } . } . . impl InvocationCollectorNode for ast::Arm { . const KIND: AstFragmentKind = AstFragmentKind::Arms; . fn to_annotatable(self) -> Annotatable { . Annotatable::Arm(self) . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { . fragment.make_arms() . } . fn id(&mut self) -> &mut NodeId { . &mut self.id . } . fn noop_flat_map(self, visitor: &mut V) -> Self::OutputTy { 2,490 ( 0.00%) noop_flat_map_arm(self, visitor) . } . } . . impl InvocationCollectorNode for ast::Stmt { . type AttrsTy = ast::AttrVec; . const KIND: AstFragmentKind = AstFragmentKind::Stmts; . fn to_annotatable(self) -> Annotatable { . Annotatable::Stmt(P(self)) . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { 12 ( 0.00%) fragment.make_stmts() . } . fn id(&mut self) -> &mut NodeId { . &mut self.id . } . fn noop_flat_map(self, visitor: &mut V) -> Self::OutputTy { 4,284 ( 0.00%) noop_flat_map_stmt(self, visitor) . } . fn is_mac_call(&self) -> bool { 2,178 ( 0.00%) match &self.kind { . StmtKind::MacCall(..) => true, 1 ( 0.00%) StmtKind::Item(item) => matches!(item.kind, ItemKind::MacCall(..)), 134 ( 0.00%) StmtKind::Semi(expr) => matches!(expr.kind, ExprKind::MacCall(..)), . StmtKind::Expr(..) => unreachable!(), . StmtKind::Local(..) | StmtKind::Empty => false, . } . } 54 ( 0.00%) fn take_mac_call(self) -> (ast::MacCall, Self::AttrsTy, AddSemicolon) { . // We pull macro invocations (both attributes and fn-like macro calls) out of their . // `StmtKind`s and treat them as statement macro invocations, not as items or expressions. 90 ( 0.00%) let (add_semicolon, mac, attrs) = match self.kind { 6 ( 0.00%) StmtKind::MacCall(mac) => { 66 ( 0.00%) let ast::MacCallStmt { mac, style, attrs, .. } = mac.into_inner(); 54 ( 0.00%) (style == MacStmtStyle::Semicolon, mac, attrs) . } . StmtKind::Item(item) => match item.into_inner() { . ast::Item { kind: ItemKind::MacCall(mac), attrs, .. } => { . (mac.args.need_semicolon(), mac, attrs.into()) . } . _ => unreachable!(), . }, . StmtKind::Semi(expr) => match expr.into_inner() { . ast::Expr { kind: ExprKind::MacCall(mac), attrs, .. } => { . (mac.args.need_semicolon(), mac, attrs) . } . _ => unreachable!(), . }, . _ => unreachable!(), . }; 18 ( 0.00%) (mac, attrs, if add_semicolon { AddSemicolon::Yes } else { AddSemicolon::No }) 54 ( 0.00%) } 30 ( 0.00%) fn post_flat_map_node_collect_bang(stmts: &mut Self::OutputTy, add_semicolon: AddSemicolon) { . // If this is a macro invocation with a semicolon, then apply that . // semicolon to the final statement produced by expansion. 12 ( 0.00%) if matches!(add_semicolon, AddSemicolon::Yes) { 6 ( 0.00%) if let Some(stmt) = stmts.pop() { 42 ( 0.00%) stmts.push(stmt.add_trailing_semicolon()); . } . } 36 ( 0.00%) } . } . . impl InvocationCollectorNode for ast::Crate { . type OutputTy = ast::Crate; . const KIND: AstFragmentKind = AstFragmentKind::Crate; . fn to_annotatable(self) -> Annotatable { . Annotatable::Crate(self) . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { . fragment.make_crate() . } . fn id(&mut self) -> &mut NodeId { . &mut self.id . } . fn noop_visit(&mut self, visitor: &mut V) { 3 ( 0.00%) noop_visit_crate(self, visitor) . } . } . . impl InvocationCollectorNode for P { . type OutputTy = P; . const KIND: AstFragmentKind = AstFragmentKind::Ty; . fn to_annotatable(self) -> Annotatable { . unreachable!() -- line 1426 ---------------------------------------- -- line 1427 ---------------------------------------- . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { . fragment.make_ty() . } . fn id(&mut self) -> &mut NodeId { . &mut self.id . } . fn noop_visit(&mut self, visitor: &mut V) { 3,630 ( 0.00%) noop_visit_ty(self, visitor) . } . fn is_mac_call(&self) -> bool { 1,815 ( 0.00%) matches!(self.kind, ast::TyKind::MacCall(..)) . } . fn take_mac_call(self) -> (ast::MacCall, Self::AttrsTy, AddSemicolon) { . let node = self.into_inner(); . match node.kind { . TyKind::MacCall(mac) => (mac, Vec::new(), AddSemicolon::No), . _ => unreachable!(), . } . } -- line 1446 ---------------------------------------- -- line 1454 ---------------------------------------- . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { . fragment.make_pat() . } . fn id(&mut self) -> &mut NodeId { . &mut self.id . } . fn noop_visit(&mut self, visitor: &mut V) { 2,600 ( 0.00%) noop_visit_pat(self, visitor) . } . fn is_mac_call(&self) -> bool { 1,300 ( 0.00%) matches!(self.kind, PatKind::MacCall(..)) . } . fn take_mac_call(self) -> (ast::MacCall, Self::AttrsTy, AddSemicolon) { . let node = self.into_inner(); . match node.kind { . PatKind::MacCall(mac) => (mac, Vec::new(), AddSemicolon::No), . _ => unreachable!(), . } . } -- line 1473 ---------------------------------------- -- line 1476 ---------------------------------------- . impl InvocationCollectorNode for P { . type OutputTy = P; . type AttrsTy = ast::AttrVec; . const KIND: AstFragmentKind = AstFragmentKind::Expr; . fn to_annotatable(self) -> Annotatable { . Annotatable::Expr(self) . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { 60 ( 0.00%) fragment.make_expr() . } . fn id(&mut self) -> &mut NodeId { . &mut self.id . } . fn descr() -> &'static str { . "an expression" . } . fn noop_visit(&mut self, visitor: &mut V) { 13,704 ( 0.00%) noop_visit_expr(self, visitor) . } . fn is_mac_call(&self) -> bool { 4,598 ( 0.00%) matches!(self.kind, ExprKind::MacCall(..)) . } . fn take_mac_call(self) -> (ast::MacCall, Self::AttrsTy, AddSemicolon) { . let node = self.into_inner(); 60 ( 0.00%) match node.kind { 270 ( 0.00%) ExprKind::MacCall(mac) => (mac, node.attrs, AddSemicolon::No), . _ => unreachable!(), . } . } . } . . struct OptExprTag; . impl InvocationCollectorNode for AstLikeWrapper, OptExprTag> { . type OutputTy = Option>; . type AttrsTy = ast::AttrVec; . const KIND: AstFragmentKind = AstFragmentKind::OptExpr; . fn to_annotatable(self) -> Annotatable { . Annotatable::Expr(self.wrapped) . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { 66 ( 0.00%) fragment.make_opt_expr() . } . fn id(&mut self) -> &mut NodeId { . &mut self.wrapped.id . } . fn noop_flat_map(mut self, visitor: &mut V) -> Self::OutputTy { 281,104 ( 0.00%) noop_visit_expr(&mut self.wrapped, visitor); . Some(self.wrapped) . } . fn is_mac_call(&self) -> bool { 281,170 ( 0.00%) matches!(self.wrapped.kind, ast::ExprKind::MacCall(..)) . } . fn take_mac_call(self) -> (ast::MacCall, Self::AttrsTy, AddSemicolon) { . let node = self.wrapped.into_inner(); 66 ( 0.00%) match node.kind { 297 ( 0.00%) ExprKind::MacCall(mac) => (mac, node.attrs, AddSemicolon::No), . _ => unreachable!(), . } . } . fn pre_flat_map_node_collect_attr(cfg: &StripUnconfigured<'_>, attr: &ast::Attribute) { . cfg.maybe_emit_expr_attr_err(&attr); . } . } . -- line 1539 ---------------------------------------- -- line 1540 ---------------------------------------- . struct InvocationCollector<'a, 'b> { . cx: &'a mut ExtCtxt<'b>, . cfg: StripUnconfigured<'a>, . invocations: Vec<(Invocation, Option>)>, . monotonic: bool, . } . . impl<'a, 'b> InvocationCollector<'a, 'b> { 990 ( 0.00%) fn collect(&mut self, fragment_kind: AstFragmentKind, kind: InvocationKind) -> AstFragment { 180 ( 0.00%) let expn_id = LocalExpnId::fresh_empty(); . let vis = kind.placeholder_visibility(); 1,530 ( 0.00%) self.invocations.push(( 180 ( 0.00%) Invocation { 270 ( 0.00%) kind, . fragment_kind, . expansion_data: ExpansionData { . id: expn_id, 360 ( 0.00%) depth: self.cx.current_expansion.depth + 1, . ..self.cx.current_expansion.clone() . }, . }, . None, . )); 990 ( 0.00%) placeholder(fragment_kind, NodeId::placeholder_from_expn_id(expn_id), vis) 720 ( 0.00%) } . . fn collect_bang(&mut self, mac: ast::MacCall, kind: AstFragmentKind) -> AstFragment { . // cache the macro call span so that it can be . // easily adjusted for incremental compilation 70 ( 0.00%) let span = mac.span(); 1,050 ( 0.00%) self.collect(kind, InvocationKind::Bang { mac, span }) . } . . fn collect_attr( . &mut self, . (attr, pos, derives): (ast::Attribute, usize, Vec), . item: Annotatable, . kind: AstFragmentKind, . ) -> AstFragment { 620 ( 0.00%) self.collect(kind, InvocationKind::Attr { attr, pos, item, derives }) . } . . /// If `item` is an attribute invocation, remove the attribute and return it together with . /// its position and derives following it. We have to collect the derives in order to resolve . /// legacy derive helpers (helpers written before derives that introduce them). . fn take_first_attr( . &self, . item: &mut impl AstLike, . ) -> Option<(ast::Attribute, usize, Vec)> { 148,194 ( 0.00%) let mut attr = None; . 148,194 ( 0.00%) let mut cfg_pos = None; 294,064 ( 0.00%) let mut attr_pos = None; 4,648 ( 0.00%) for (pos, attr) in item.attrs().iter().enumerate() { 8,671 ( 0.00%) if !attr.is_doc_comment() && !self.cx.expanded_inert_attrs.is_marked(attr) { 566 ( 0.00%) let name = attr.ident().map(|ident| ident.name); 1,132 ( 0.00%) if name == Some(sym::cfg) || name == Some(sym::cfg_attr) { 36 ( 0.00%) cfg_pos = Some(pos); // a cfg attr found, no need to search anymore . break; 795 ( 0.00%) } else if attr_pos.is_none() . && !name.map_or(false, rustc_feature::is_builtin_attr_name) . { 60 ( 0.00%) attr_pos = Some(pos); // a non-cfg attr found, still may find a cfg attr . } . } . } . . item.visit_attrs(|attrs| { 594,298 ( 0.01%) attr = Some(match (cfg_pos, attr_pos) { 306 ( 0.00%) (Some(pos), _) => (attrs.remove(pos), pos, Vec::new()), . (_, Some(pos)) => { . let attr = attrs.remove(pos); . let following_derives = attrs[pos..] . .iter() . .filter(|a| a.has_name(sym::derive)) . .flat_map(|a| a.meta_item_list().unwrap_or_default()) . .filter_map(|nested_meta| match nested_meta { . NestedMetaItem::MetaItem(ast::MetaItem { -- line 1617 ---------------------------------------- -- line 1618 ---------------------------------------- . kind: MetaItemKind::Word, . path, . .. . }) => Some(path), . _ => None, . }) . .collect(); . 360 ( 0.00%) (attr, pos, following_derives) . } . _ => return, . }); . }); . . attr . } . . // Detect use of feature-gated or invalid attributes on macro invocations . // since they will not be detected after macro expansion. 490 ( 0.00%) fn check_attributes(&self, attrs: &[ast::Attribute], call: &ast::MacCall) { 210 ( 0.00%) let features = self.cx.ecfg.features.unwrap(); . let mut attrs = attrs.iter().peekable(); . let mut span: Option = None; . while let Some(attr) = attrs.next() { . rustc_ast_passes::feature_gate::check_attribute(attr, self.cx.sess, features); . validate_attr::check_meta(&self.cx.sess.parse_sess, attr); . . let current_span = if let Some(sp) = span { sp.to(attr.span) } else { attr.span }; . span = Some(current_span); -- line 1646 ---------------------------------------- -- line 1671 ---------------------------------------- . attr_name, . macro_name: pprust::path_to_string(&call.path), . invoc_span: call.path.span, . }, . ); . } . } . } 560 ( 0.00%) } . . fn expand_cfg_true( . &mut self, . node: &mut impl AstLike, . attr: ast::Attribute, . pos: usize, . ) -> bool { 36 ( 0.00%) let res = self.cfg.cfg_true(&attr); 36 ( 0.00%) if res { . // FIXME: `cfg(TRUE)` attributes do not currently remove themselves during expansion, . // and some tools like rustdoc and clippy rely on that. Find a way to remove them . // while keeping the tools working. . self.cx.expanded_inert_attrs.mark(&attr); . node.visit_attrs(|attrs| attrs.insert(pos, attr)); . } . res . } -- line 1696 ---------------------------------------- -- line 1701 ---------------------------------------- . }); . } . . fn flat_map_node>( . &mut self, . mut node: Node, . ) -> Node::OutputTy { . loop { 432,745 ( 0.01%) return match self.take_first_attr(&mut node) { 1,064 ( 0.00%) Some((attr, pos, derives)) => match attr.name_or_empty() { . sym::cfg => { 306 ( 0.00%) if self.expand_cfg_true(&mut node, attr, pos) { . continue; . } . Default::default() . } . sym::cfg_attr => { . self.expand_cfg_attr(&mut node, attr, pos); . continue; . } . _ => { . Node::pre_flat_map_node_collect_attr(&self.cfg, &attr); . self.collect_attr((attr, pos, derives), node.to_annotatable(), Node::KIND) . .make_ast::() . } . }, 141,369 ( 0.00%) None if node.is_mac_call() => { 380 ( 0.00%) let (mac, attrs, add_semicolon) = node.take_mac_call(); 75 ( 0.00%) self.check_attributes(&attrs, &mac); 360 ( 0.00%) let mut res = self.collect_bang(mac, Node::KIND).make_ast::(); 18 ( 0.00%) Node::post_flat_map_node_collect_bang(&mut res, add_semicolon); 48 ( 0.00%) res . } . None => { 2,700 ( 0.00%) match Node::wrap_flat_map_node_noop_flat_map(node, self, |mut node, this| { 1,861,555 ( 0.03%) assign_id!(this, node.id(), || node.noop_flat_map(this)) . }) { 17,389 ( 0.00%) Ok(output) => output, 8 ( 0.00%) Err(returned_node) => { 930 ( 0.00%) node = returned_node; . continue; . } . } . } . }; . } 16 ( 0.00%) } . . fn visit_node + DummyAstNode>( . &mut self, . node: &mut Node, . ) { . loop { 18,395 ( 0.00%) return match self.take_first_attr(node) { . Some((attr, pos, derives)) => match attr.name_or_empty() { . sym::cfg => { . let span = attr.span; . if self.expand_cfg_true(node, attr, pos) { . continue; . } . let msg = . format!("removing {} is not supported in this position", Node::descr()); -- line 1762 ---------------------------------------- -- line 1767 ---------------------------------------- . self.expand_cfg_attr(node, attr, pos); . continue; . } . _ => visit_clobber(node, |node| { . self.collect_attr((attr, pos, derives), node.to_annotatable(), Node::KIND) . .make_ast::() . }), . }, 7,713 ( 0.00%) None if node.is_mac_call() => { . visit_clobber(node, |node| { . // Do not clobber unless it's actually a macro (uncommon case). 240 ( 0.00%) let (mac, attrs, _) = node.take_mac_call(); 60 ( 0.00%) self.check_attributes(&attrs, &mac); 270 ( 0.00%) self.collect_bang(mac, Node::KIND).make_ast::() . }) . } . None => { 96,675 ( 0.00%) assign_id!(self, node.id(), || node.noop_visit(self)) . } . }; . } . } . } . . impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> { 6,766 ( 0.00%) fn flat_map_item(&mut self, node: P) -> SmallVec<[P; 1]> { . self.flat_map_node(node) 4,347 ( 0.00%) } . 16 ( 0.00%) fn flat_map_trait_item(&mut self, node: P) -> SmallVec<[P; 1]> { . self.flat_map_node(AstLikeWrapper::new(node, TraitItemTag)) 9 ( 0.00%) } . 3,184 ( 0.00%) fn flat_map_impl_item(&mut self, node: P) -> SmallVec<[P; 1]> { . self.flat_map_node(AstLikeWrapper::new(node, ImplItemTag)) 1,791 ( 0.00%) } . . fn flat_map_foreign_item( . &mut self, . node: P, . ) -> SmallVec<[P; 1]> { . self.flat_map_node(node) . } . 176 ( 0.00%) fn flat_map_variant(&mut self, node: ast::Variant) -> SmallVec<[ast::Variant; 1]> { 462 ( 0.00%) self.flat_map_node(node) 198 ( 0.00%) } . 496 ( 0.00%) fn flat_map_field_def(&mut self, node: ast::FieldDef) -> SmallVec<[ast::FieldDef; 1]> { 930 ( 0.00%) self.flat_map_node(node) 558 ( 0.00%) } . 1,216 ( 0.00%) fn flat_map_pat_field(&mut self, node: ast::PatField) -> SmallVec<[ast::PatField; 1]> { 1,824 ( 0.00%) self.flat_map_node(node) 1,216 ( 0.00%) } . 7,472 ( 0.00%) fn flat_map_expr_field(&mut self, node: ast::ExprField) -> SmallVec<[ast::ExprField; 1]> { 11,208 ( 0.00%) self.flat_map_node(node) 8,406 ( 0.00%) } . 3,552 ( 0.00%) fn flat_map_param(&mut self, node: ast::Param) -> SmallVec<[ast::Param; 1]> { 5,328 ( 0.00%) self.flat_map_node(node) 3,996 ( 0.00%) } . 1,440 ( 0.00%) fn flat_map_generic_param( . &mut self, . node: ast::GenericParam, . ) -> SmallVec<[ast::GenericParam; 1]> { 3,240 ( 0.00%) self.flat_map_node(node) 1,620 ( 0.00%) } . 1,328 ( 0.00%) fn flat_map_arm(&mut self, node: ast::Arm) -> SmallVec<[ast::Arm; 1]> { 1,992 ( 0.00%) self.flat_map_node(node) 1,494 ( 0.00%) } . 9,440 ( 0.00%) fn flat_map_stmt(&mut self, mut node: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> { . // FIXME: invocations in semicolon-less expressions positions are expanded as expressions, . // changing that requires some compatibility measures. 3,776 ( 0.00%) if node.is_expr() { . // The only way that we can end up with a `MacCall` expression statement, . // (as opposed to a `StmtKind::MacCall`) is if we have a macro as the . // traiing expression in a block (e.g. `fn foo() { my_macro!() }`). . // Record this information, so that we can report a more specific . // `SEMICOLON_IN_EXPRESSIONS_FROM_MACROS` lint if needed. . // See #78991 for an investigation of treating macros in this position . // as statements, rather than expressions, during parsing. 1,162 ( 0.00%) return match &node.kind { . StmtKind::Expr(expr) 1,162 ( 0.00%) if matches!(**expr, ast::Expr { kind: ExprKind::MacCall(..), .. }) => . { 26 ( 0.00%) self.cx.current_expansion.is_trailing_mac = true; . // Don't use `assign_id` for this statement - it may get removed . // entirely due to a `#[cfg]` on the contained expression 104 ( 0.00%) let res = noop_flat_map_stmt(node, self); 39 ( 0.00%) self.cx.current_expansion.is_trailing_mac = false; . res . } 13,632 ( 0.00%) _ => assign_id!(self, &mut node.id, || noop_flat_map_stmt(node, self)), . }; . } . 2,904 ( 0.00%) self.flat_map_node(node) 7,552 ( 0.00%) } . 13 ( 0.00%) fn visit_crate(&mut self, node: &mut ast::Crate) { . self.visit_node(node) 8 ( 0.00%) } . 14,520 ( 0.00%) fn visit_ty(&mut self, node: &mut P) { . self.visit_node(node) 14,520 ( 0.00%) } . 10,400 ( 0.00%) fn visit_pat(&mut self, node: &mut P) { . self.visit_node(node) 10,400 ( 0.00%) } . 41,382 ( 0.00%) fn visit_expr(&mut self, node: &mut P) { . // FIXME: Feature gating is performed inconsistently between `Expr` and `OptExpr`. . if let Some(attr) = node.attrs.first() { . self.cfg.maybe_emit_expr_attr_err(attr); . } . self.visit_node(node) 36,784 ( 0.00%) } . 2,389,945 ( 0.03%) fn filter_map_expr(&mut self, node: P) -> Option> { . self.flat_map_node(AstLikeWrapper::new(node, OptExprTag)) 1,124,680 ( 0.02%) } . . fn visit_block(&mut self, node: &mut P) { . let orig_dir_ownership = mem::replace( 404 ( 0.00%) &mut self.cx.current_expansion.dir_ownership, . DirOwnership::UnownedViaBlock, . ); . noop_visit_block(node, self); 1,449 ( 0.00%) self.cx.current_expansion.dir_ownership = orig_dir_ownership; . } . . fn visit_id(&mut self, id: &mut NodeId) { . // We may have already assigned a `NodeId` . // by calling `assign_id` 662,687 ( 0.01%) if self.monotonic && *id == ast::DUMMY_NODE_ID { 46,343 ( 0.00%) *id = self.cx.resolver.next_node_id(); . } . } . } . . pub struct ExpansionConfig<'feat> { . pub crate_name: String, . pub features: Option<&'feat Features>, . pub recursion_limit: Limit, . pub trace_mac: bool, . pub should_test: bool, // If false, strip `#[test]` nodes . pub span_debug: bool, // If true, use verbose debugging for `proc_macro::Span` . pub proc_macro_backtrace: bool, // If true, show backtraces for proc-macro panics . } . . impl<'feat> ExpansionConfig<'feat> { 12 ( 0.00%) pub fn default(crate_name: String) -> ExpansionConfig<'static> { 18 ( 0.00%) ExpansionConfig { 9 ( 0.00%) crate_name, . features: None, 6 ( 0.00%) recursion_limit: Limit::new(1024), . trace_mac: false, . should_test: false, . span_debug: false, . proc_macro_backtrace: false, . } 15 ( 0.00%) } . . fn proc_macro_hygiene(&self) -> bool { . self.features.map_or(false, |features| features.proc_macro_hygiene) . } . } 352,322 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/mod.rs -------------------------------------------------------------------------------- Ir -- line 108 ---------------------------------------- . suppress_errors: bool, . }, . } . . impl RegionckMode { . /// Indicates that the MIR borrowck will repeat these region . /// checks, so we should ignore errors if NLL is (unconditionally) . /// enabled. 384 ( 0.00%) pub fn for_item_body(tcx: TyCtxt<'_>) -> Self { . // FIXME(Centril): Once we actually remove `::Migrate` also make . // this always `true` and then proceed to eliminate the dead code. 384 ( 0.00%) match tcx.borrowck_mode() { . // If we're on Migrate mode, report AST region errors . BorrowckMode::Migrate => RegionckMode::Erase { suppress_errors: false }, . . // If we're on MIR, don't report AST region errors as they should be reported by NLL . BorrowckMode::Mir => RegionckMode::Erase { suppress_errors: true }, . } 768 ( 0.00%) } . } . . /// This type contains all the things within `InferCtxt` that sit within a . /// `RefCell` and are involved with taking/rolling back snapshots. Snapshot . /// operations are hot enough that we want only one call to `borrow_mut` per . /// call to `start_snapshot` and `rollback_to`. . pub struct InferCtxtInner<'tcx> { . /// Cache for projections. This cache is snapshotted along with the infcx. -- line 134 ---------------------------------------- -- line 202 ---------------------------------------- . /// type instantiations (`ty::Infer`) to the actual opaque . /// type (`ty::Opaque`). Used during fallback to map unconstrained . /// opaque type inference variables to their corresponding . /// opaque type. . pub opaque_types_vars: FxHashMap, Ty<'tcx>>, . } . . impl<'tcx> InferCtxtInner<'tcx> { 1,432,550 ( 0.02%) fn new() -> InferCtxtInner<'tcx> { 9,741,340 ( 0.14%) InferCtxtInner { . projection_cache: Default::default(), . type_variable_storage: type_variable::TypeVariableStorage::new(), . undo_log: InferCtxtUndoLogs::default(), . const_unification_storage: ut::UnificationTableStorage::new(), . int_unification_storage: ut::UnificationTableStorage::new(), . float_unification_storage: ut::UnificationTableStorage::new(), 859,530 ( 0.01%) region_constraint_storage: Some(RegionConstraintStorage::new()), . region_obligations: vec![], . opaque_types: Default::default(), . opaque_types_vars: Default::default(), . } 1,719,060 ( 0.02%) } . . #[inline] . pub fn region_obligations(&self) -> &[(hir::HirId, RegionObligation<'tcx>)] { . &self.region_obligations . } . . #[inline] . pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> { 1,971 ( 0.00%) self.projection_cache.with_log(&mut self.undo_log) . } . . #[inline] . fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> { 223,737 ( 0.00%) self.type_variable_storage.with_log(&mut self.undo_log) . } . . #[inline] . fn int_unification_table( . &mut self, . ) -> ut::UnificationTable< . ut::InPlace< . ty::IntVid, . &mut ut::UnificationStorage, . &mut InferCtxtUndoLogs<'tcx>, . >, . > { 5,335 ( 0.00%) self.int_unification_storage.with_log(&mut self.undo_log) . } . . #[inline] . fn float_unification_table( . &mut self, . ) -> ut::UnificationTable< . ut::InPlace< . ty::FloatVid, -- line 258 ---------------------------------------- -- line 268 ---------------------------------------- . &mut self, . ) -> ut::UnificationTable< . ut::InPlace< . ty::ConstVid<'tcx>, . &mut ut::UnificationStorage>, . &mut InferCtxtUndoLogs<'tcx>, . >, . > { 1,180 ( 0.00%) self.const_unification_storage.with_log(&mut self.undo_log) . } . . #[inline] . pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> { 72,513 ( 0.00%) self.region_constraint_storage . .as_mut() . .expect("region constraints already solved") 88,790 ( 0.00%) .with_log(&mut self.undo_log) . } . } . . pub struct InferCtxt<'a, 'tcx> { . pub tcx: TyCtxt<'tcx>, . . /// The `DefId` of the item in whose context we are performing inference or typeck. . /// It is used to check whether an opaque type use is a defining use. -- line 292 ---------------------------------------- -- line 361 ---------------------------------------- . /// item we are type-checking, and just consider those names as . /// part of the root universe. So this would only get incremented . /// when we enter into a higher-ranked (`for<..>`) type or trait . /// bound. . universe: Cell, . } . . /// See the `error_reporting` module for more details. 120,672 ( 0.00%) #[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable)] . pub enum ValuePairs<'tcx> { . Types(ExpectedFound>), . Regions(ExpectedFound>), . Consts(ExpectedFound<&'tcx ty::Const<'tcx>>), . TraitRefs(ExpectedFound>), . PolyTraitRefs(ExpectedFound>), . } . -- line 377 ---------------------------------------- -- line 383 ---------------------------------------- . pub struct TypeTrace<'tcx> { . cause: ObligationCause<'tcx>, . values: ValuePairs<'tcx>, . } . . /// The origin of a `r1 <= r2` constraint. . /// . /// See `error_reporting` module for more details 119,864 ( 0.00%) #[derive(Clone, Debug)] . pub enum SubregionOrigin<'tcx> { . /// Arose from a subtyping relation 6,209 ( 0.00%) Subtype(Box>), . . /// When casting `&'a T` to an `&'b Trait` object, . /// relating `'a` to `'b` . RelateObjectBound(Span), . . /// Some type parameter was instantiated with the given type, . /// and that type must outlive some region. 1,666 ( 0.00%) RelateParamBound(Span, Ty<'tcx>, Option), . . /// The given region parameter was instantiated with a region . /// that must outlive some other region. . RelateRegionParamBound(Span), . . /// Creating a pointer `b` to contents of another reference . Reborrow(Span), . . /// Creating a pointer `b` to contents of an upvar . ReborrowUpvar(Span, ty::UpvarId), . . /// Data with type `Ty<'tcx>` was borrowed 1,383 ( 0.00%) DataBorrowed(Ty<'tcx>, Span), . . /// (&'a &'b T) where a >= b 1,256 ( 0.00%) ReferenceOutlivesReferent(Ty<'tcx>, Span), . . /// Comparing the signature and requirements of an impl method against . /// the containing trait. . CompareImplMethodObligation { span: Span, impl_item_def_id: DefId, trait_item_def_id: DefId }, . . /// Comparing the signature and requirements of an impl associated type . /// against the containing trait . CompareImplTypeObligation { span: Span, impl_item_def_id: DefId, trait_item_def_id: DefId }, -- line 426 ---------------------------------------- -- line 554 ---------------------------------------- . defining_use_anchor: Option, . } . . pub trait TyCtxtInferExt<'tcx> { . fn infer_ctxt(self) -> InferCtxtBuilder<'tcx>; . } . . impl<'tcx> TyCtxtInferExt<'tcx> for TyCtxt<'tcx> { 286,510 ( 0.00%) fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> { 859,530 ( 0.01%) InferCtxtBuilder { tcx: self, defining_use_anchor: None, fresh_typeck_results: None } 286,510 ( 0.00%) } . } . . impl<'tcx> InferCtxtBuilder<'tcx> { . /// Used only by `rustc_typeck` during body type-checking/inference, . /// will initialize `in_progress_typeck_results` with fresh `TypeckResults`. . /// Will also change the scope for opaque type defining use checks to the given owner. 8,280 ( 0.00%) pub fn with_fresh_in_progress_typeck_results(mut self, table_owner: LocalDefId) -> Self { 10,120 ( 0.00%) self.fresh_typeck_results = Some(RefCell::new(ty::TypeckResults::new(table_owner))); 4,600 ( 0.00%) self.with_opaque_type_inference(table_owner) 6,440 ( 0.00%) } . . /// Whenever the `InferCtxt` should be able to handle defining uses of opaque types, . /// you need to call this function. Otherwise the opaque type will be treated opaquely. . /// . /// It is only meant to be called in two places, for typeck . /// (via `with_fresh_in_progress_typeck_results`) and for the inference context used . /// in mir borrowck. 802 ( 0.00%) pub fn with_opaque_type_inference(mut self, defining_use_anchor: LocalDefId) -> Self { 401 ( 0.00%) self.defining_use_anchor = Some(defining_use_anchor); 2,642 ( 0.00%) self 1,203 ( 0.00%) } . . /// Given a canonical value `C` as a starting point, create an . /// inference context that contains each of the bound values . /// within instantiated as a fresh variable. The `f` closure is . /// invoked with the new infcx, along with the instantiated value . /// `V` and a substitution `S`. This substitution `S` maps from . /// the bound values in `C` to their instantiated values in `V` . /// (in other words, `S(C) = V`). 17,504 ( 0.00%) pub fn enter_with_canonical( . &mut self, . span: Span, . canonical: &Canonical<'tcx, T>, . f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>, T, CanonicalVarValues<'tcx>) -> R, . ) -> R . where . T: TypeFoldable<'tcx>, . { . self.enter(|infcx| { 24,556 ( 0.00%) let (value, subst) = 1,436 ( 0.00%) infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical); 36,322 ( 0.00%) f(infcx, value, subst) . }) 18,977 ( 0.00%) } . 2,542,472 ( 0.04%) pub fn enter(&mut self, f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>) -> R) -> R { 1,133,499 ( 0.02%) let InferCtxtBuilder { tcx, defining_use_anchor, ref fresh_typeck_results } = *self; . let in_progress_typeck_results = fresh_typeck_results.as_ref(); 7,895,074 ( 0.11%) f(InferCtxt { . tcx, . defining_use_anchor, . in_progress_typeck_results, 286,510 ( 0.00%) inner: RefCell::new(InferCtxtInner::new()), . lexical_region_resolutions: RefCell::new(None), . selection_cache: Default::default(), . evaluation_cache: Default::default(), . reported_trait_errors: Default::default(), . reported_closure_mismatch: Default::default(), . tainted_by_errors_flag: Cell::new(false), 286,510 ( 0.00%) err_count_on_creation: tcx.sess.err_count(), . in_snapshot: Cell::new(false), . skip_leak_check: Cell::new(false), . universe: Cell::new(ty::UniverseIndex::ROOT), . }) 2,822,077 ( 0.04%) } . } . . impl<'tcx, T> InferOk<'tcx, T> { . pub fn unit(self) -> InferOk<'tcx, ()> { . InferOk { value: (), obligations: self.obligations } . } . . /// Extracts `value`, registering any obligations into `fulfill_cx`. . pub fn into_value_registering_obligations( . self, . infcx: &InferCtxt<'_, 'tcx>, . fulfill_cx: &mut dyn TraitEngine<'tcx>, . ) -> T { 561 ( 0.00%) let InferOk { value, obligations } = self; 2,398 ( 0.00%) for obligation in obligations { 403 ( 0.00%) fulfill_cx.register_predicate_obligation(infcx, obligation); . } . value . } . } . . impl<'tcx> InferOk<'tcx, ()> { 8,493 ( 0.00%) pub fn into_obligations(self) -> PredicateObligations<'tcx> { 33,972 ( 0.00%) self.obligations 8,493 ( 0.00%) } . } . . #[must_use = "once you start a snapshot, you should always consume it"] . pub struct CombinedSnapshot<'a, 'tcx> { . undo_snapshot: Snapshot<'tcx>, . region_constraints_snapshot: RegionSnapshot, . universe: ty::UniverseIndex, . was_in_snapshot: bool, -- line 662 ---------------------------------------- -- line 674 ---------------------------------------- . let canonical = self.canonicalize_query((a, b), &mut OriginalQueryValues::default()); . debug!("canonical consts: {:?}", &canonical.value); . . self.tcx.try_unify_abstract_consts(canonical.value) . } . . pub fn is_in_snapshot(&self) -> bool { . self.in_snapshot.get() 14,471 ( 0.00%) } . 122,576 ( 0.00%) pub fn freshen>(&self, t: T) -> T { 137,898 ( 0.00%) t.fold_with(&mut self.freshener()) 137,898 ( 0.00%) } . . /// Returns the origin of the type variable identified by `vid`, or `None` . /// if this is not a type variable. . /// . /// No attempt is made to resolve `ty`. 232 ( 0.00%) pub fn type_var_origin(&'a self, ty: Ty<'tcx>) -> Option { 464 ( 0.00%) match *ty.kind() { 116 ( 0.00%) ty::Infer(ty::TyVar(vid)) => { 464 ( 0.00%) Some(*self.inner.borrow_mut().type_variables().var_origin(vid)) . } . _ => None, . } 464 ( 0.00%) } . 15,322 ( 0.00%) pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> { . freshen::TypeFreshener::new(self, false) 15,322 ( 0.00%) } . . /// Like `freshener`, but does not replace `'static` regions. 51,531 ( 0.00%) pub fn freshener_keep_static<'b>(&'b self) -> TypeFreshener<'b, 'tcx> { . freshen::TypeFreshener::new(self, true) 51,531 ( 0.00%) } . 1,748 ( 0.00%) pub fn unsolved_variables(&self) -> Vec> { 874 ( 0.00%) let mut inner = self.inner.borrow_mut(); 874 ( 0.00%) let mut vars: Vec> = inner . .type_variables() . .unsolved_variables() . .into_iter() 230 ( 0.00%) .map(|t| self.tcx.mk_ty_var(t)) . .collect(); . vars.extend( . (0..inner.int_unification_table().len()) . .map(|i| ty::IntVid { index: i as u32 }) 168 ( 0.00%) .filter(|&vid| inner.int_unification_table().probe_value(vid).is_none()) . .map(|v| self.tcx.mk_int_var(v)), . ); . vars.extend( . (0..inner.float_unification_table().len()) . .map(|i| ty::FloatVid { index: i as u32 }) . .filter(|&vid| inner.float_unification_table().probe_value(vid).is_none()) . .map(|v| self.tcx.mk_float_var(v)), . ); . vars 3,059 ( 0.00%) } . 30,013 ( 0.00%) fn combine_fields( . &'a self, . trace: TypeTrace<'tcx>, . param_env: ty::ParamEnv<'tcx>, . ) -> CombineFields<'a, 'tcx> { 120,128 ( 0.00%) CombineFields { . infcx: self, 300,320 ( 0.00%) trace, . cause: None, . param_env, . obligations: PredicateObligations::new(), . } 30,013 ( 0.00%) } . . /// Clear the "currently in a snapshot" flag, invoke the closure, . /// then restore the flag to its original value. This flag is a . /// debugging measure designed to detect cases where we start a . /// snapshot, create type variables, and register obligations . /// which may involve those type variables in the fulfillment cx, . /// potentially leaving "dangling type variables" behind. . /// In such cases, an assertion will fail when attempting to -- line 753 ---------------------------------------- -- line 755 ---------------------------------------- . /// better than grovelling through megabytes of `RUSTC_LOG` output. . /// . /// HOWEVER, in some cases the flag is unhelpful. In particular, we . /// sometimes create a "mini-fulfilment-cx" in which we enroll . /// obligations. As long as this fulfillment cx is fully drained . /// before we return, this is not a problem, as there won't be any . /// escaping obligations in the main cx. In those cases, you can . /// use this function. 24 ( 0.00%) pub fn save_and_restore_in_snapshot_flag(&self, func: F) -> R . where . F: FnOnce(&Self) -> R, . { . let flag = self.in_snapshot.replace(false); 5,589 ( 0.00%) let result = func(self); . self.in_snapshot.set(flag); . result 27 ( 0.00%) } . 154,458 ( 0.00%) fn start_snapshot(&self) -> CombinedSnapshot<'a, 'tcx> { . debug!("start_snapshot()"); . . let in_snapshot = self.in_snapshot.replace(true); . . let mut inner = self.inner.borrow_mut(); . 463,374 ( 0.01%) CombinedSnapshot { . undo_snapshot: inner.undo_log.start_snapshot(), . region_constraints_snapshot: inner.unwrap_region_constraints().start_snapshot(), . universe: self.universe(), . was_in_snapshot: in_snapshot, . // Borrow typeck results "in progress" (i.e., during typeck) . // to ban writes from within a snapshot to them. 77,229 ( 0.00%) _in_progress_typeck_results: self . .in_progress_typeck_results . .map(|typeck_results| typeck_results.borrow()), . } 308,916 ( 0.00%) } . 247,786 ( 0.00%) #[instrument(skip(self, snapshot), level = "debug")] . fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) { . let CombinedSnapshot { 22,526 ( 0.00%) undo_snapshot, 22,526 ( 0.00%) region_constraints_snapshot, 22,526 ( 0.00%) universe, 22,526 ( 0.00%) was_in_snapshot, 45,052 ( 0.00%) _in_progress_typeck_results, . } = snapshot; . . self.in_snapshot.set(was_in_snapshot); . self.universe.set(universe); . . let mut inner = self.inner.borrow_mut(); 22,526 ( 0.00%) inner.rollback_to(undo_snapshot); . inner.unwrap_region_constraints().rollback_to(region_constraints_snapshot); . } . 820,545 ( 0.01%) #[instrument(skip(self, snapshot), level = "debug")] . fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) { . let CombinedSnapshot { 54,703 ( 0.00%) undo_snapshot, . region_constraints_snapshot: _, . universe: _, 54,703 ( 0.00%) was_in_snapshot, 109,406 ( 0.00%) _in_progress_typeck_results, . } = snapshot; . . self.in_snapshot.set(was_in_snapshot); . . self.inner.borrow_mut().commit(undo_snapshot); . } . . /// Executes `f` and commit the bindings. 38,393 ( 0.00%) #[instrument(skip(self, f), level = "debug")] 47,355 ( 0.00%) pub fn commit_unconditionally(&self, f: F) -> R . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R, . { 4,305 ( 0.00%) let snapshot = self.start_snapshot(); 14,891 ( 0.00%) let r = f(&snapshot); 30,135 ( 0.00%) self.commit_from(snapshot); 25,282 ( 0.00%) r . } . . /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`. 353,062 ( 0.01%) #[instrument(skip(self, f), level = "debug")] 434,968 ( 0.01%) pub fn commit_if_ok(&self, f: F) -> Result . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result, . { 64,544 ( 0.00%) let snapshot = self.start_snapshot(); 200,458 ( 0.00%) let r = f(&snapshot); . debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok()); 64,581 ( 0.00%) match r { . Ok(_) => { 365,148 ( 0.01%) self.commit_from(snapshot); . } . Err(_) => { 90,511 ( 0.00%) self.rollback_to("commit_if_ok -- error", snapshot); . } . } 368,823 ( 0.01%) r . } . . /// Execute `f` then unroll any bindings it creates. 95,299 ( 0.00%) #[instrument(skip(self, f), level = "debug")] 108,946 ( 0.00%) pub fn probe(&self, f: F) -> R . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R, . { 26,135 ( 0.00%) let snapshot = self.start_snapshot(); 41,349 ( 0.00%) let r = f(&snapshot); 122,802 ( 0.00%) self.rollback_to("probe", snapshot); 19,821 ( 0.00%) r . } . . /// If `should_skip` is true, then execute `f` then unroll any bindings it creates. . #[instrument(skip(self, f), level = "debug")] . pub fn probe_maybe_skip_leak_check(&self, should_skip: bool, f: F) -> R . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R, . { -- line 875 ---------------------------------------- -- line 884 ---------------------------------------- . r . } . . /// Scan the constraints produced since `snapshot` began and returns: . /// . /// - `None` -- if none of them involve "region outlives" constraints . /// - `Some(true)` -- if there are `'a: 'b` constraints where `'a` or `'b` is a placeholder . /// - `Some(false)` -- if there are `'a: 'b` constraints but none involve placeholders 11,020 ( 0.00%) pub fn region_constraints_added_in_snapshot( . &self, . snapshot: &CombinedSnapshot<'a, 'tcx>, . ) -> Option { 22,040 ( 0.00%) self.inner . .borrow_mut() . .unwrap_region_constraints() . .region_constraints_added_in_snapshot(&snapshot.undo_snapshot) 16,530 ( 0.00%) } . . pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) { . self.inner.borrow_mut().unwrap_region_constraints().add_given(sub, sup); . } . 336 ( 0.00%) pub fn can_sub(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx> . where . T: at::ToTrace<'tcx>, . { . let origin = &ObligationCause::dummy(); . self.probe(|_| { . self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| { . // Ignore obligations, since we are unrolling . // everything anyway. . }) . }) 252 ( 0.00%) } . 4,128 ( 0.00%) pub fn can_eq(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx> . where . T: at::ToTrace<'tcx>, . { . let origin = &ObligationCause::dummy(); . self.probe(|_| { . self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| { . // Ignore obligations, since we are unrolling . // everything anyway. . }) . }) 3,096 ( 0.00%) } . 51,710 ( 0.00%) #[instrument(skip(self), level = "debug")] . pub fn sub_regions( . &self, . origin: SubregionOrigin<'tcx>, . a: ty::Region<'tcx>, . b: ty::Region<'tcx>, . ) { 46,539 ( 0.00%) self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b); . } . . /// Require that the region `r` be equal to one of the regions in . /// the set `regions`. . #[instrument(skip(self), level = "debug")] . pub fn member_constraint( . &self, . opaque_type_def_id: DefId, -- line 947 ---------------------------------------- -- line 969 ---------------------------------------- . /// to `subtype_predicate` -- that is, "coercing" `a` to `b` winds up . /// actually requiring `a <: b`. This is of course a valid coercion, . /// but it's not as flexible as `FnCtxt::coerce` would be. . /// . /// (We may refactor this in the future, but there are a number of . /// practical obstacles. Among other things, `FnCtxt::coerce` presently . /// records adjustments that are required on the HIR in order to perform . /// the coercion, and we don't currently have a way to manage that.) 6 ( 0.00%) pub fn coerce_predicate( . &self, . cause: &ObligationCause<'tcx>, . param_env: ty::ParamEnv<'tcx>, . predicate: ty::PolyCoercePredicate<'tcx>, . ) -> Option> { 4 ( 0.00%) let subtype_predicate = predicate.map_bound(|p| ty::SubtypePredicate { . a_is_expected: false, // when coercing from `a` to `b`, `b` is expected . a: p.a, . b: p.b, . }); 10 ( 0.00%) self.subtype_predicate(cause, param_env, subtype_predicate) 8 ( 0.00%) } . 1,536 ( 0.00%) pub fn subtype_predicate( . &self, . cause: &ObligationCause<'tcx>, . param_env: ty::ParamEnv<'tcx>, . predicate: ty::PolySubtypePredicate<'tcx>, . ) -> Option> { . // Check for two unresolved inference variables, in which case we can . // make no progress. This is partly a micro-optimization, but it's . // also an opportunity to "sub-unify" the variables. This isn't -- line 999 ---------------------------------------- -- line 1002 ---------------------------------------- . // earlier that they are sub-unified). . // . // Note that we can just skip the binders here because . // type variables can't (at present, at . // least) capture any of the things bound by this binder. . // . // Note that this sub here is not just for diagnostics - it has semantic . // effects as well. 128 ( 0.00%) let r_a = self.shallow_resolve(predicate.skip_binder().a); 128 ( 0.00%) let r_b = self.shallow_resolve(predicate.skip_binder().b); 930 ( 0.00%) match (r_a.kind(), r_b.kind()) { 218 ( 0.00%) (&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => { . self.inner.borrow_mut().type_variables().sub(a_vid, b_vid); 218 ( 0.00%) return None; . } . _ => {} . } . . Some(self.commit_if_ok(|_snapshot| { 19 ( 0.00%) let ty::SubtypePredicate { a_is_expected, a, b } = . self.replace_bound_vars_with_placeholders(predicate); . 38 ( 0.00%) let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?; . . Ok(ok.unit()) . })) 1,152 ( 0.00%) } . 16,692 ( 0.00%) pub fn region_outlives_predicate( . &self, . cause: &traits::ObligationCause<'tcx>, . predicate: ty::PolyRegionOutlivesPredicate<'tcx>, . ) -> UnitResult<'tcx> { . self.commit_if_ok(|_snapshot| { . let ty::OutlivesPredicate(r_a, r_b) = . self.replace_bound_vars_with_placeholders(predicate); . let origin = SubregionOrigin::from_obligation_cause(cause, || { . RelateRegionParamBound(cause.span) . }); 13,910 ( 0.00%) self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b` . Ok(()) . }) 11,128 ( 0.00%) } . . /// Number of type variables created so far. 53 ( 0.00%) pub fn num_ty_vars(&self) -> usize { . self.inner.borrow_mut().type_variables().num_vars() 106 ( 0.00%) } . 12,762 ( 0.00%) pub fn next_ty_var_id(&self, origin: TypeVariableOrigin) -> TyVid { 63,810 ( 0.00%) self.inner.borrow_mut().type_variables().new_var(self.universe(), origin) 19,143 ( 0.00%) } . 12,330 ( 0.00%) pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> { 44,457 ( 0.00%) self.tcx.mk_ty_var(self.next_ty_var_id(origin)) 18,495 ( 0.00%) } . 848 ( 0.00%) pub fn next_ty_var_in_universe( . &self, . origin: TypeVariableOrigin, . universe: ty::UniverseIndex, . ) -> Ty<'tcx> { 4,664 ( 0.00%) let vid = self.inner.borrow_mut().type_variables().new_var(universe, origin); 424 ( 0.00%) self.tcx.mk_ty_var(vid) 1,272 ( 0.00%) } . . pub fn next_const_var( . &self, . ty: Ty<'tcx>, . origin: ConstVariableOrigin, . ) -> &'tcx ty::Const<'tcx> { . self.tcx.mk_const_var(self.next_const_var_id(origin), ty) . } -- line 1074 ---------------------------------------- -- line 1090 ---------------------------------------- . pub fn next_const_var_id(&self, origin: ConstVariableOrigin) -> ConstVid<'tcx> { . self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue { . origin, . val: ConstVariableValue::Unknown { universe: self.universe() }, . }) . } . . fn next_int_var_id(&self) -> IntVid { 275 ( 0.00%) self.inner.borrow_mut().int_unification_table().new_key(None) . } . 165 ( 0.00%) pub fn next_int_var(&self) -> Ty<'tcx> { . self.tcx.mk_int_var(self.next_int_var_id()) 220 ( 0.00%) } . . fn next_float_var_id(&self) -> FloatVid { . self.inner.borrow_mut().float_unification_table().new_key(None) . } . . pub fn next_float_var(&self) -> Ty<'tcx> { . self.tcx.mk_float_var(self.next_float_var_id()) . } . . /// Creates a fresh region variable with the next available index. . /// The variable will be created in the maximum universe created . /// thus far, allowing it to name any region created thus far. 6,726 ( 0.00%) pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> { 186,369 ( 0.00%) self.next_region_var_in_universe(origin, self.universe()) 13,452 ( 0.00%) } . . /// Creates a fresh region variable with the next available index . /// in the given universe; typically, you can use . /// `next_region_var` and just use the maximal universe. 74,924 ( 0.00%) pub fn next_region_var_in_universe( . &self, . origin: RegionVariableOrigin, . universe: ty::UniverseIndex, . ) -> ty::Region<'tcx> { . let region_var = 487,006 ( 0.01%) self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin); 187,310 ( 0.00%) self.tcx.mk_region(ty::ReVar(region_var)) 112,386 ( 0.00%) } . . /// Return the universe that the region `r` was created in. For . /// most regions (e.g., `'static`, named regions from the user, . /// etc) this is the root universe U0. For inference variables or . /// placeholders, however, it will return the universe which which . /// they are associated. 6,802 ( 0.00%) pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex { . self.inner.borrow_mut().unwrap_region_constraints().universe(r) 10,203 ( 0.00%) } . . /// Number of region variables created so far. 3,242 ( 0.00%) pub fn num_region_vars(&self) -> usize { . self.inner.borrow_mut().unwrap_region_constraints().num_region_vars() 4,863 ( 0.00%) } . . /// Just a convenient wrapper of `next_region_var` for using during NLL. 18,066 ( 0.00%) pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin) -> ty::Region<'tcx> { . self.next_region_var(RegionVariableOrigin::Nll(origin)) 36,132 ( 0.00%) } . . /// Just a convenient wrapper of `next_region_var` for using during NLL. 122 ( 0.00%) pub fn next_nll_region_var_in_universe( . &self, . origin: NllRegionVariableOrigin, . universe: ty::UniverseIndex, . ) -> ty::Region<'tcx> { 1,014 ( 0.00%) self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe) 244 ( 0.00%) } . 106,280 ( 0.00%) pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> { 55,601 ( 0.00%) match param.kind { . GenericParamDefKind::Lifetime => { . // Create a region inference variable for the given . // region parameter definition. 5,412 ( 0.00%) self.next_region_var(EarlyBoundRegion(span, param.name)).into() . } . GenericParamDefKind::Type { .. } => { . // Create a type inference variable for the given . // type parameter definition. The substitutions are . // for actual parameters that may be referred to by . // the default of this type parameter, if it exists. . // e.g., `struct Foo(...);` when . // used in a path such as `Foo::::new()` will . // use an inference variable for `C` with `[T, U]` . // as the substitutions for the default, `(T, U)`. 31,324 ( 0.00%) let ty_var_id = self.inner.borrow_mut().type_variables().new_var( . self.universe(), 39,155 ( 0.00%) TypeVariableOrigin { . kind: TypeVariableOriginKind::TypeParameterDefinition( 7,831 ( 0.00%) param.name, 7,831 ( 0.00%) Some(param.def_id), . ), . span, . }, . ); . 7,831 ( 0.00%) self.tcx.mk_ty_var(ty_var_id).into() . } . GenericParamDefKind::Const { .. } => { . let origin = ConstVariableOrigin { . kind: ConstVariableOriginKind::ConstParameterDefinition( . param.name, . param.def_id, . ), . span, . }; . let const_var_id = 462 ( 0.00%) self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue { . origin, . val: ConstVariableValue::Unknown { universe: self.universe() }, . }); 42 ( 0.00%) self.tcx.mk_const_var(const_var_id, self.tcx.type_of(param.def_id)).into() . } . } 336 ( 0.00%) } . . /// Given a set of generics defined on a type or impl, returns a substitution mapping each . /// type/region parameter to a fresh inference variable. 19,623 ( 0.00%) pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> { 101,661 ( 0.00%) InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param)) 13,082 ( 0.00%) } . . /// Returns `true` if errors have been reported since this infcx was . /// created. This is sometimes used as a heuristic to skip . /// reporting errors that often occur as a result of earlier . /// errors, but where it's hard to be 100% sure (e.g., unresolved . /// inference variables, regionck errors). 1,000 ( 0.00%) pub fn is_tainted_by_errors(&self) -> bool { . debug!( . "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \ . tainted_by_errors_flag={})", . self.tcx.sess.err_count(), . self.err_count_on_creation, . self.tainted_by_errors_flag.get() . ); . 25,262 ( 0.00%) if self.tcx.sess.err_count() > self.err_count_on_creation { . return true; // errors reported since this infcx was made . } . self.tainted_by_errors_flag.get() 1,500 ( 0.00%) } . . /// Set the "tainted by errors" flag to true. We call this when we . /// observe an error from a prior pass. . pub fn set_tainted_by_errors(&self) { . debug!("set_tainted_by_errors()"); . self.tainted_by_errors_flag.set(true) . } . . /// Process the region constraints and return any any errors that . /// result. After this, no more unification operations should be . /// done -- or the compiler will panic -- but it is legal to use . /// `resolve_vars_if_possible` as well as `fully_resolve`. 25,389 ( 0.00%) pub fn resolve_regions( . &self, . region_context: DefId, . outlives_env: &OutlivesEnvironment<'tcx>, . mode: RegionckMode, . ) -> Vec> { 68,913 ( 0.00%) let (var_infos, data) = { . let mut inner = self.inner.borrow_mut(); . let inner = &mut *inner; 3,627 ( 0.00%) assert!( 10,881 ( 0.00%) self.is_tainted_by_errors() || inner.region_obligations.is_empty(), . "region_obligations not empty: {:#?}", . inner.region_obligations . ); . inner . .region_constraint_storage . .take() . .expect("regions already resolved") . .with_log(&mut inner.undo_log) . .into_infos_and_data() 3,627 ( 0.00%) }; . . let region_rels = 3,627 ( 0.00%) &RegionRelations::new(self.tcx, region_context, outlives_env.free_region_map()); . 32,643 ( 0.00%) let (lexical_region_resolutions, errors) = 87,048 ( 0.00%) lexical_region_resolve::resolve(region_rels, var_infos, data, mode); . 14,508 ( 0.00%) let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions)); 3,627 ( 0.00%) assert!(old_value.is_none()); . . errors 32,643 ( 0.00%) } . . /// Process the region constraints and report any errors that . /// result. After this, no more unification operations should be . /// done -- or the compiler will panic -- but it is legal to use . /// `resolve_vars_if_possible` as well as `fully_resolve`. 36,270 ( 0.00%) pub fn resolve_regions_and_report_errors( . &self, . region_context: DefId, . outlives_env: &OutlivesEnvironment<'tcx>, . mode: RegionckMode, . ) { 7,254 ( 0.00%) let errors = self.resolve_regions(region_context, outlives_env, mode); . 10,881 ( 0.00%) if !self.is_tainted_by_errors() { . // As a heuristic, just skip reporting region errors . // altogether if other errors have been reported while . // this infcx was in use. This is totally hokey but . // otherwise we have a hard time separating legit region . // errors from silly ones. 7,254 ( 0.00%) self.report_region_errors(&errors); . } 18,135 ( 0.00%) } . . /// Obtains (and clears) the current set of region . /// constraints. The inference context is still usable: further . /// unifications will simply add new constraints. . /// . /// This method is not meant to be used with normal lexical region . /// resolution. Rather, it is used in the NLL mode as a kind of . /// interim hack: basically we run normal type-check and generate -- line 1307 ---------------------------------------- -- line 1319 ---------------------------------------- . } . . /// Gives temporary access to the region constraint data. . pub fn with_region_constraints( . &self, . op: impl FnOnce(&RegionConstraintData<'tcx>) -> R, . ) -> R { . let mut inner = self.inner.borrow_mut(); 7,504 ( 0.00%) op(inner.unwrap_region_constraints().data()) . } . . pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin { . let mut inner = self.inner.borrow_mut(); . let inner = &mut *inner; . inner . .region_constraint_storage . .as_mut() -- line 1335 ---------------------------------------- -- line 1338 ---------------------------------------- . .var_origin(vid) . } . . /// Takes ownership of the list of variable regions. This implies . /// that all the region constraints have already been taken, and . /// hence that `resolve_regions_and_report_errors` can never be . /// called. This is used only during NLL processing to "hand off" ownership . /// of the set of region variables into the NLL region context. 2,005 ( 0.00%) pub fn take_region_var_origins(&self) -> VarInfos { . let mut inner = self.inner.borrow_mut(); 7,619 ( 0.00%) let (var_infos, data) = inner . .region_constraint_storage . .take() . .expect("regions already resolved") . .with_log(&mut inner.undo_log) 401 ( 0.00%) .into_infos_and_data(); 401 ( 0.00%) assert!(data.is_empty()); . var_infos 3,208 ( 0.00%) } . . pub fn ty_to_string(&self, t: Ty<'tcx>) -> String { . self.resolve_vars_if_possible(t).to_string() . } . . /// If `TyVar(vid)` resolves to a type, return that type. Else, return the . /// universe index of `TyVar(vid)`. 3,646 ( 0.00%) pub fn probe_ty_var(&self, vid: TyVid) -> Result, ty::UniverseIndex> { . use self::type_variable::TypeVariableValue; . 10,938 ( 0.00%) match self.inner.borrow_mut().type_variables().probe(vid) { . TypeVariableValue::Known { value } => Ok(value), . TypeVariableValue::Unknown { universe } => Err(universe), . } 12,761 ( 0.00%) } . . /// Resolve any type variables found in `value` -- but only one . /// level. So, if the variable `?X` is bound to some type . /// `Foo`, then this would return `Foo` (but `?Y` may . /// itself be bound to a type). . /// . /// Useful when you only need to inspect the outermost level of . /// the type and don't care about nested types (or perhaps you . /// will be resolving them as well, e.g. in a loop). . pub fn shallow_resolve(&self, value: T) -> T . where . T: TypeFoldable<'tcx>, . { 402,806 ( 0.01%) value.fold_with(&mut ShallowResolver { infcx: self }) . } . 4,772 ( 0.00%) pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid { . self.inner.borrow_mut().type_variables().root_var(var) 7,158 ( 0.00%) } . . /// Where possible, replaces type/const variables in . /// `value` with their final value. Note that region variables . /// are unaffected. If a type/const variable has not been unified, it . /// is left as is. This is an idempotent operation that does . /// not affect inference state in any way and so you can do it . /// at will. 628 ( 0.00%) pub fn resolve_vars_if_possible(&self, value: T) -> T . where . T: TypeFoldable<'tcx>, . { 518,334 ( 0.01%) if !value.needs_infer() { 93,637 ( 0.00%) return value; // Avoid duplicated subst-folding. . } 97,629 ( 0.00%) let mut r = resolve::OpportunisticVarResolver::new(self); 117,489 ( 0.00%) value.fold_with(&mut r) 785 ( 0.00%) } . . /// Returns the first unresolved variable contained in `T`. In the . /// process of visiting `T`, this will resolve (where possible) . /// type variables in `T`, but it never constructs the final, . /// resolved type, so it's more efficient than . /// `resolve_vars_if_possible()`. . pub fn unresolved_type_vars(&self, value: &T) -> Option<(Ty<'tcx>, Option)> . where -- line 1415 ---------------------------------------- -- line 1490 ---------------------------------------- . expected: &'tcx ty::Const<'tcx>, . actual: &'tcx ty::Const<'tcx>, . err: TypeError<'tcx>, . ) -> DiagnosticBuilder<'tcx> { . let trace = TypeTrace::consts(cause, true, expected, actual); . self.report_and_explain_type_error(trace, &err) . } . 6,210 ( 0.00%) pub fn replace_bound_vars_with_fresh_vars( . &self, . span: Span, . lbrct: LateBoundRegionConversionTime, . value: ty::Binder<'tcx, T>, . ) -> (T, BTreeMap>) . where . T: TypeFoldable<'tcx>, . { . let fld_r = 56,886 ( 0.00%) |br: ty::BoundRegion| self.next_region_var(LateBoundRegion(span, br.kind, lbrct)); . let fld_t = |_| { . self.next_ty_var(TypeVariableOrigin { . kind: TypeVariableOriginKind::MiscVariable, . span, . }) . }; . let fld_c = |_, ty| { . self.next_const_var( . ty, . ConstVariableOrigin { kind: ConstVariableOriginKind::MiscVariable, span }, . ) . }; 121,723 ( 0.00%) self.tcx.replace_bound_vars(value, fld_r, fld_t, fld_c) 4,140 ( 0.00%) } . . /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method. 7,760 ( 0.00%) pub fn verify_generic_bound( . &self, . origin: SubregionOrigin<'tcx>, . kind: GenericKind<'tcx>, . a: ty::Region<'tcx>, . bound: VerifyBound<'tcx>, . ) { . debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound); . 2,910 ( 0.00%) self.inner . .borrow_mut() . .unwrap_region_constraints() 16,490 ( 0.00%) .verify_generic_bound(origin, kind, a, bound); 6,790 ( 0.00%) } . . /// Obtains the latest type of the given closure; this may be a . /// closure in the current function, in which case its . /// `ClosureKind` may not yet be known. 628 ( 0.00%) pub fn closure_kind(&self, closure_substs: SubstsRef<'tcx>) -> Option { 1,256 ( 0.00%) let closure_kind_ty = closure_substs.as_closure().kind_ty(); . let closure_kind_ty = self.shallow_resolve(closure_kind_ty); 942 ( 0.00%) closure_kind_ty.to_opt_closure_kind() . } . . /// Clears the selection, evaluation, and projection caches. This is useful when . /// repeatedly attempting to select an `Obligation` while changing only . /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing. . pub fn clear_caches(&self) { . self.selection_cache.clear(); . self.evaluation_cache.clear(); . self.inner.borrow_mut().projection_cache().clear(); . } . . pub fn universe(&self) -> ty::UniverseIndex { 517,054 ( 0.01%) self.universe.get() 357,257 ( 0.01%) } . . /// Creates and return a fresh universe that extends all previous . /// universes. Updates `self.universe` to that new universe. 384 ( 0.00%) pub fn create_next_universe(&self) -> ty::UniverseIndex { 584 ( 0.00%) let u = self.universe.get().next_universe(); . self.universe.set(u); . u 384 ( 0.00%) } . . /// Resolves and evaluates a constant. . /// . /// The constant can be located on a trait like `::C`, in which case the given . /// substitutions and environment are used to resolve the constant. Alternatively if the . /// constant has generic parameters in scope the substitutions are used to evaluate the value of . /// the constant. For example in `fn foo() { let _ = [0; bar::()]; }` the repeat count . /// constant `bar::()` requires a substitution for `T`, if the substitution for `T` is still -- line 1576 ---------------------------------------- -- line 1606 ---------------------------------------- . // variables, thus we don't need to substitute back the original values. . self.tcx.const_eval_resolve(param_env_erased, unevaluated, span) . } . . /// If `typ` is a type variable of some kind, resolve it one level . /// (but do not resolve types found in the result). If `typ` is . /// not a type variable, just return it unmodified. . // FIXME(eddyb) inline into `ShallowResolver::visit_ty`. 2,231,040 ( 0.03%) fn shallow_resolve_ty(&self, typ: Ty<'tcx>) -> Ty<'tcx> { 817,332 ( 0.01%) match *typ.kind() { . ty::Infer(ty::TyVar(v)) => { . // Not entirely obvious: if `typ` is a type variable, . // it can be resolved to an int/float variable, which . // can then be recursively resolved, hence the . // recursion. Note though that we prevent type . // variables from unifying to other type variables . // directly (though they may be embedded . // structurally), and we prevent cycles in any case, . // so this recursion should always be of very limited . // depth. . // . // Note: if these two lines are combined into one we get . // dynamic borrow errors on `self.inner`. 240,448 ( 0.00%) let known = self.inner.borrow_mut().type_variables().probe(v).known(); . known.map_or(typ, |t| self.shallow_resolve_ty(t)) . } . 5,916 ( 0.00%) ty::Infer(ty::IntVar(v)) => self . .inner . .borrow_mut() . .int_unification_table() . .probe_value(v) 1,452 ( 0.00%) .map(|v| v.to_type(self.tcx)) . .unwrap_or(typ), . . ty::Infer(ty::FloatVar(v)) => self . .inner . .borrow_mut() . .float_unification_table() . .probe_value(v) . .map(|v| v.to_type(self.tcx)) . .unwrap_or(typ), . . _ => typ, . } 2,509,920 ( 0.04%) } . . /// `ty_or_const_infer_var_changed` is equivalent to one of these two: . /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`) . /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`) . /// . /// However, `ty_or_const_infer_var_changed` is more efficient. It's always . /// inlined, despite being large, because it has only two call sites that . /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on` -- line 1659 ---------------------------------------- -- line 1662 ---------------------------------------- . #[inline(always)] . pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar<'tcx>) -> bool { . match infer_var { . TyOrConstInferVar::Ty(v) => { . use self::type_variable::TypeVariableValue; . . // If `inlined_probe` returns a `Known` value, it never equals . // `ty::Infer(ty::TyVar(v))`. 98,187 ( 0.00%) match self.inner.borrow_mut().type_variables().inlined_probe(v) { . TypeVariableValue::Unknown { .. } => false, . TypeVariableValue::Known { .. } => true, . } . } . . TyOrConstInferVar::TyInt(v) => { . // If `inlined_probe_value` returns a value it's always a . // `ty::Int(_)` or `ty::UInt(_)`, which never matches a . // `ty::Infer(_)`. 1,958 ( 0.00%) self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_some() . } . . TyOrConstInferVar::TyFloat(v) => { . // If `probe_value` returns a value it's always a . // `ty::Float(_)`, which never matches a `ty::Infer(_)`. . // . // Not `inlined_probe_value(v)` because this call site is colder. . self.inner.borrow_mut().float_unification_table().probe_value(v).is_some() -- line 1688 ---------------------------------------- -- line 1716 ---------------------------------------- . /// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`. . Const(ConstVid<'tcx>), . } . . impl<'tcx> TyOrConstInferVar<'tcx> { . /// Tries to extract an inference variable from a type or a constant, returns `None` . /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and . /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`). 2,214 ( 0.00%) pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option { . match arg.unpack() { . GenericArgKind::Type(ty) => Self::maybe_from_ty(ty), . GenericArgKind::Const(ct) => Self::maybe_from_const(ct), . GenericArgKind::Lifetime(_) => None, . } 2,214 ( 0.00%) } . . /// Tries to extract an inference variable from a type, returns `None` . /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`). 202 ( 0.00%) pub fn maybe_from_ty(ty: Ty<'tcx>) -> Option { 21,296 ( 0.00%) match *ty.kind() { 4,654 ( 0.00%) ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)), 70 ( 0.00%) ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)), . ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)), . _ => None, . } 202 ( 0.00%) } . . /// Tries to extract an inference variable from a constant, returns `None` . /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`). . pub fn maybe_from_const(ct: &'tcx ty::Const<'tcx>) -> Option { . match ct.val { . ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)), . _ => None, . } -- line 1749 ---------------------------------------- -- line 1755 ---------------------------------------- . } . . impl<'a, 'tcx> TypeFolder<'tcx> for ShallowResolver<'a, 'tcx> { . fn tcx<'b>(&'b self) -> TyCtxt<'tcx> { . self.infcx.tcx . } . . fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> { 498,480 ( 0.01%) self.infcx.shallow_resolve_ty(ty) . } . 952 ( 0.00%) fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> { 622 ( 0.00%) if let ty::Const { val: ty::ConstKind::Infer(InferConst::Var(vid)), .. } = ct { 365 ( 0.00%) self.infcx . .inner . .borrow_mut() . .const_unification_table() 219 ( 0.00%) .probe_value(*vid) . .val . .known() . .unwrap_or(ct) . } else { . ct . } 1,190 ( 0.00%) } . } . . impl<'tcx> TypeTrace<'tcx> { . pub fn span(&self) -> Span { 88 ( 0.00%) self.cause.span . } . . pub fn types( . cause: &ObligationCause<'tcx>, . a_is_expected: bool, . a: Ty<'tcx>, . b: Ty<'tcx>, . ) -> TypeTrace<'tcx> { -- line 1792 ---------------------------------------- -- line 1800 ---------------------------------------- . b: &'tcx ty::Const<'tcx>, . ) -> TypeTrace<'tcx> { . TypeTrace { cause: cause.clone(), values: Consts(ExpectedFound::new(a_is_expected, a, b)) } . } . } . . impl<'tcx> SubregionOrigin<'tcx> { . pub fn span(&self) -> Span { 220 ( 0.00%) match *self { 44 ( 0.00%) Subtype(ref a) => a.span(), . RelateObjectBound(a) => a, . RelateParamBound(a, ..) => a, . RelateRegionParamBound(a) => a, . Reborrow(a) => a, . ReborrowUpvar(a, _) => a, . DataBorrowed(_, a) => a, . ReferenceOutlivesReferent(_, a) => a, . CompareImplMethodObligation { span, .. } => span, -- line 1817 ---------------------------------------- -- line 1818 ---------------------------------------- . CompareImplTypeObligation { span, .. } => span, . } . } . . pub fn from_obligation_cause(cause: &traits::ObligationCause<'tcx>, default: F) -> Self . where . F: FnOnce() -> Self, . { 17,090 ( 0.00%) match *cause.code() { 2,143 ( 0.00%) traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => { 10,715 ( 0.00%) SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span) . } . . traits::ObligationCauseCode::CompareImplMethodObligation { . impl_item_def_id, . trait_item_def_id, . } => SubregionOrigin::CompareImplMethodObligation { . span: cause.span, . impl_item_def_id, -- line 1836 ---------------------------------------- 774,478 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/symbol.rs -------------------------------------------------------------------------------- Ir -- line 15 ---------------------------------------- . use std::str; . . use crate::{with_session_globals, Edition, Span, DUMMY_SP}; . . #[cfg(test)] . mod tests; . . // The proc macro code for this is in `compiler/rustc_macros/src/symbols.rs`. 8 ( 0.00%) symbols! { . // After modifying this list adjust `is_special`, `is_used_keyword`/`is_unused_keyword`, . // this should be rarely necessary though if the keywords are kept in alphabetic order. . Keywords { . // Special reserved identifiers used internally for elided lifetimes, . // unnamed method parameters, crate root module, error recovery etc. . Empty: "", . PathRoot: "{{root}}", . DollarCrate: "$crate", -- line 31 ---------------------------------------- -- line 1498 ---------------------------------------- . write_str, . writeln_macro, . x87_reg, . xer, . xmm_reg, . ymm_reg, . zmm_reg, . } 10 ( 0.00%) } . 90,366 ( 0.00%) #[derive(Copy, Clone, Eq, HashStable_Generic, Encodable, Decodable)] . pub struct Ident { . pub name: Symbol, . pub span: Span, . } . . impl Ident { . #[inline] . /// Constructs a new identifier from a symbol and a span. . pub const fn new(name: Symbol, span: Span) -> Ident { . Ident { name, span } 261,707 ( 0.00%) } . . /// Constructs a new identifier with a dummy span. . #[inline] . pub const fn with_dummy_span(name: Symbol) -> Ident { . Ident::new(name, DUMMY_SP) . } . . #[inline] . pub fn empty() -> Ident { . Ident::with_dummy_span(kw::Empty) . } . . /// Maps a string to an identifier with a dummy span. 3 ( 0.00%) pub fn from_str(string: &str) -> Ident { 3 ( 0.00%) Ident::with_dummy_span(Symbol::intern(string)) 12 ( 0.00%) } . . /// Maps a string and a span to an identifier. 496 ( 0.00%) pub fn from_str_and_span(string: &str, span: Span) -> Ident { 248 ( 0.00%) Ident::new(Symbol::intern(string), span) 496 ( 0.00%) } . . /// Replaces `lo` and `hi` with those from `span`, but keep hygiene context. 38,696 ( 0.00%) pub fn with_span_pos(self, span: Span) -> Ident { . Ident::new(self.name, span.with_ctxt(self.span.ctxt())) 24,185 ( 0.00%) } . 1,464 ( 0.00%) pub fn without_first_quote(self) -> Ident { 1,464 ( 0.00%) Ident::new(Symbol::intern(self.as_str().trim_start_matches('\'')), self.span) 915 ( 0.00%) } . . /// "Normalize" ident for use in comparisons using "item hygiene". . /// Identifiers with same string value become same if they came from the same macro 2.0 macro . /// (e.g., `macro` item, but not `macro_rules` item) and stay different if they came from . /// different macro 2.0 macros. . /// Technically, this operation strips all non-opaque marks from ident's syntactic context. 145,125 ( 0.00%) pub fn normalize_to_macros_2_0(self) -> Ident { . Ident::new(self.name, self.span.normalize_to_macros_2_0()) 112,875 ( 0.00%) } . . /// "Normalize" ident for use in comparisons using "local variable hygiene". . /// Identifiers with same string value become same if they came from the same non-transparent . /// macro (e.g., `macro` or `macro_rules!` items) and stay different if they came from different . /// non-transparent macros. . /// Technically, this operation strips all transparent marks from ident's syntactic context. 15,939 ( 0.00%) pub fn normalize_to_macro_rules(self) -> Ident { . Ident::new(self.name, self.span.normalize_to_macro_rules()) 12,397 ( 0.00%) } . . /// Access the underlying string. This is a slowish operation because it . /// requires locking the symbol interner. . /// . /// Note that the lifetime of the return value is a lie. See . /// `Symbol::as_str()` for details. . pub fn as_str(&self) -> &str { 454 ( 0.00%) self.name.as_str() . } . } . . impl PartialEq for Ident { 45,372 ( 0.00%) fn eq(&self, rhs: &Self) -> bool { 113,522 ( 0.00%) self.name == rhs.name && self.span.ctxt() == rhs.span.ctxt() 60,496 ( 0.00%) } . } . . impl Hash for Ident { . fn hash(&self, state: &mut H) { 50 ( 0.00%) self.name.hash(state); 23,964 ( 0.00%) self.span.ctxt().hash(state); . } . } . . impl fmt::Debug for Ident { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . fmt::Display::fmt(self, f)?; . fmt::Debug::fmt(&self.span.ctxt(), f) . } . } . . /// This implementation is supposed to be used in error messages, so it's expected to be identical . /// to printing the original identifier token written in source code (`token_to_string`), . /// except that AST identifiers don't keep the rawness flag, so we have to guess it. . impl fmt::Display for Ident { 720 ( 0.00%) fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 901 ( 0.00%) fmt::Display::fmt(&IdentPrinter::new(self.name, self.is_raw_guess(), None), f) 720 ( 0.00%) } . } . . /// This is the most general way to print identifiers. . /// AST pretty-printer is used as a fallback for turning AST structures into token streams for . /// proc macros. Additionally, proc macros may stringify their input and expect it survive the . /// stringification (especially true for proc macro derives written between Rust 1.15 and 1.30). . /// So we need to somehow pretty-print `$crate` in a way preserving at least some of its . /// hygiene data, most importantly name of the crate it refers to. -- line 1613 ---------------------------------------- -- line 1622 ---------------------------------------- . is_raw: bool, . /// Span used for retrieving the crate name to which `$crate` refers to, . /// if this field is `None` then the `$crate` conversion doesn't happen. . convert_dollar_crate: Option, . } . . impl IdentPrinter { . /// The most general `IdentPrinter` constructor. Do not use this. 154 ( 0.00%) pub fn new(symbol: Symbol, is_raw: bool, convert_dollar_crate: Option) -> IdentPrinter { 5,438 ( 0.00%) IdentPrinter { symbol, is_raw, convert_dollar_crate } 154 ( 0.00%) } . . /// This implementation is supposed to be used when printing identifiers . /// as a part of pretty-printing for larger AST pieces. . /// Do not use this either. 1,958 ( 0.00%) pub fn for_ast_ident(ident: Ident, is_raw: bool) -> IdentPrinter { 1,958 ( 0.00%) IdentPrinter::new(ident.name, is_raw, Some(ident.span)) 979 ( 0.00%) } . } . . impl fmt::Display for IdentPrinter { 6,570 ( 0.00%) fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 2,628 ( 0.00%) if self.is_raw { . f.write_str("r#")?; 1,314 ( 0.00%) } else if self.symbol == kw::DollarCrate { . if let Some(span) = self.convert_dollar_crate { . let converted = span.ctxt().dollar_crate_name(); . if !converted.is_path_segment_keyword() { . f.write_str("::")?; . } . return fmt::Display::fmt(&converted, f); . } . } -- line 1654 ---------------------------------------- -- line 1656 ---------------------------------------- . } . } . . /// An newtype around `Ident` that calls [Ident::normalize_to_macro_rules] on . /// construction. . // FIXME(matthewj, petrochenkov) Use this more often, add a similar . // `ModernIdent` struct and use that as well. . #[derive(Copy, Clone, Eq, PartialEq, Hash)] 4,044 ( 0.00%) pub struct MacroRulesNormalizedIdent(Ident); . . impl MacroRulesNormalizedIdent { . pub fn new(ident: Ident) -> Self { 916 ( 0.00%) Self(ident.normalize_to_macro_rules()) . } . } . . impl fmt::Debug for MacroRulesNormalizedIdent { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . fmt::Debug::fmt(&self.0, f) . } . } -- line 1676 ---------------------------------------- -- line 1686 ---------------------------------------- . /// Internally, a `Symbol` is implemented as an index, and all operations . /// (including hashing, equality, and ordering) operate on that index. The use . /// of `rustc_index::newtype_index!` means that `Option` only takes up 4 bytes, . /// because `rustc_index::newtype_index!` reserves the last 256 values for tagging purposes. . /// . /// Note that `Symbol` cannot directly be a `rustc_index::newtype_index!` because it . /// implements `fmt::Debug`, `Encodable`, and `Decodable` in special ways. . #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] 469,279 ( 0.01%) pub struct Symbol(SymbolIndex); . . rustc_index::newtype_index! { . struct SymbolIndex { .. } . } . . impl Symbol { . const fn new(n: u32) -> Self { . Symbol(SymbolIndex::from_u32(n)) 247,686 ( 0.00%) } . . /// Maps a string to its interned representation. 1,822,500 ( 0.03%) pub fn intern(string: &str) -> Self { . with_session_globals(|session_globals| session_globals.symbol_interner.intern(string)) 1,822,500 ( 0.03%) } . . /// Access the underlying string. This is a slowish operation because it . /// requires locking the symbol interner. . /// . /// Note that the lifetime of the return value is a lie. It's not the same . /// as `&self`, but actually tied to the lifetime of the underlying . /// interner. Interners are long-lived, and there are very few of them, and . /// this function is typically used for short-lived things, so in practice . /// it works out ok. 1,773,390 ( 0.03%) pub fn as_str(&self) -> &str { 591,130 ( 0.01%) with_session_globals(|session_globals| unsafe { . std::mem::transmute::<&str, &str>(session_globals.symbol_interner.get(*self)) . }) 2,364,520 ( 0.03%) } . . pub fn as_u32(self) -> u32 { . self.0.as_u32() . } . . pub fn is_empty(self) -> bool { . self == kw::Empty . } . . /// This method is supposed to be used in error messages, so it's expected to be . /// identical to printing the original identifier token written in source code . /// (`token_to_string`, `Ident::to_string`), except that symbols don't keep the rawness flag . /// or edition, so we have to guess the rawness using the global edition. 6 ( 0.00%) pub fn to_ident_string(self) -> String { . Ident::with_dummy_span(self).to_string() 6 ( 0.00%) } . } . . impl fmt::Debug for Symbol { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . fmt::Debug::fmt(self.as_str(), f) . } . } . . impl fmt::Display for Symbol { 277,868 ( 0.00%) fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 845,430 ( 0.01%) fmt::Display::fmt(self.as_str(), f) . } . } . . impl Encodable for Symbol { . fn encode(&self, s: &mut S) -> Result<(), S::Error> { 46,884 ( 0.00%) s.emit_str(self.as_str()) . } . } . . impl Decodable for Symbol { . #[inline] 34,008 ( 0.00%) fn decode(d: &mut D) -> Symbol { 95,412 ( 0.00%) Symbol::intern(&d.read_str()) . } . } . . impl HashStable for Symbol { . #[inline] 1,902 ( 0.00%) fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) { 31,144 ( 0.00%) self.as_str().hash_stable(hcx, hasher); 1,764 ( 0.00%) } . } . . impl ToStableHashKey for Symbol { . type KeyType = String; . #[inline] . fn to_stable_hash_key(&self, _: &CTX) -> String { . self.as_str().to_string() . } -- line 1778 ---------------------------------------- -- line 1785 ---------------------------------------- . // . // The `FxHashMap`+`Vec` pair could be replaced by `FxIndexSet`, but #75278 . // found that to regress performance up to 2% in some cases. This might be . // revisited after further improvements to `indexmap`. . // . // This type is private to prevent accidentally constructing more than one . // `Interner` on the same thread, which makes it easy to mixup `Symbol`s . // between `Interner`s. 2 ( 0.00%) #[derive(Default)] . struct InternerInner { . arena: DroplessArena, . names: FxHashMap<&'static str, Symbol>, . strings: Vec<&'static str>, . } . . impl Interner { . fn prefill(init: &[&'static str]) -> Self { 30 ( 0.00%) Interner(Lock::new(InternerInner { . strings: init.into(), . names: init.iter().copied().zip((0..).map(Symbol::new)).collect(), . ..Default::default() . })) . } . . #[inline] . fn intern(&self, string: &str) -> Symbol { . let mut inner = self.0.lock(); 376,384 ( 0.01%) if let Some(&name) = inner.names.get(string) { . return name; . } . 14,308 ( 0.00%) let name = Symbol::new(inner.strings.len() as u32); . . // SAFETY: we convert from `&str` to `&[u8]`, clone it into the arena, . // and immediately convert the clone back to `&[u8], all because there . // is no `inner.arena.alloc_str()` method. This is clearly safe. . let string: &str = . unsafe { str::from_utf8_unchecked(inner.arena.alloc_slice(string.as_bytes())) }; . . // SAFETY: we can extend the arena allocation to `'static` because we -- line 1824 ---------------------------------------- -- line 1831 ---------------------------------------- . // #91445 for details. . inner.names.insert(string, name); . name . } . . // Get the symbol as a string. `Symbol::as_str()` should be used in . // preference to this function. . fn get(&self, symbol: Symbol) -> &str { 1,773,390 ( 0.03%) self.0.lock().strings[symbol.0.as_usize()] . } . } . . // This module has a very short name because it's used a lot. . /// This module contains all the defined keyword `Symbol`s. . /// . /// Given that `kw` is imported, use them like `kw::keyword_name`. . /// For example `kw::Loop` or `kw::Break`. -- line 1847 ---------------------------------------- -- line 1863 ---------------------------------------- . . // Used from a macro in `librustc_feature/accepted.rs` . pub use super::kw::MacroRules as macro_rules; . . /// Get the symbol for an integer. . /// . /// The first few non-negative integers each have a static symbol and therefore . /// are fast. 552,427 ( 0.01%) pub fn integer + Copy + ToString>(n: N) -> Symbol { 552,325 ( 0.01%) if let Result::Ok(idx) = n.try_into() { 68 ( 0.00%) if idx < 10 { 495,372 ( 0.01%) return Symbol::new(super::SYMBOL_DIGITS_BASE + idx as u32); . } . } 14,277 ( 0.00%) Symbol::intern(&n.to_string()) 57,108 ( 0.00%) } . } . . impl Symbol { . fn is_special(self) -> bool { . self <= kw::Underscore . } . . fn is_used_keyword_always(self) -> bool { 462 ( 0.00%) self >= kw::As && self <= kw::While . } . . fn is_used_keyword_conditional(self, edition: impl FnOnce() -> Edition) -> bool { 37,206 ( 0.00%) (self >= kw::Async && self <= kw::Dyn) && edition() >= Edition::Edition2018 . } . . fn is_unused_keyword_always(self) -> bool { 462 ( 0.00%) self >= kw::Abstract && self <= kw::Yield . } . . fn is_unused_keyword_conditional(self, edition: impl FnOnce() -> Edition) -> bool { 154 ( 0.00%) self == kw::Try && edition() >= Edition::Edition2018 . } . . pub fn is_reserved(self, edition: impl Copy + FnOnce() -> Edition) -> bool { 63,652 ( 0.00%) self.is_special() . || self.is_used_keyword_always() . || self.is_unused_keyword_always() . || self.is_used_keyword_conditional(edition) . || self.is_unused_keyword_conditional(edition) . } . . /// A keyword or reserved identifier that can be used as a path segment. . pub fn is_path_segment_keyword(self) -> bool { 147,735 ( 0.00%) self == kw::Super . || self == kw::SelfLower . || self == kw::SelfUpper . || self == kw::Crate . || self == kw::PathRoot . || self == kw::DollarCrate . } . . /// Returns `true` if the symbol is `true` or `false`. . pub fn is_bool_lit(self) -> bool { 1,657 ( 0.00%) self == kw::True || self == kw::False 1,657 ( 0.00%) } . . /// Returns `true` if this symbol can be a raw identifier. . pub fn can_be_raw(self) -> bool { 4,174 ( 0.00%) self != kw::Empty && self != kw::Underscore && !self.is_path_segment_keyword() 1 ( 0.00%) } . } . . impl Ident { . // Returns `true` for reserved identifiers used internally for elided lifetimes, . // unnamed method parameters, crate root module, error recovery etc. . pub fn is_special(self) -> bool { . self.name.is_special() 154 ( 0.00%) } . . /// Returns `true` if the token is a keyword used in the language. 154 ( 0.00%) pub fn is_used_keyword(self) -> bool { . // Note: `span.edition()` is relatively expensive, don't call it unless necessary. 154 ( 0.00%) self.name.is_used_keyword_always() . || self.name.is_used_keyword_conditional(|| self.span.edition()) 308 ( 0.00%) } . . /// Returns `true` if the token is a keyword reserved for possible future use. 154 ( 0.00%) pub fn is_unused_keyword(self) -> bool { . // Note: `span.edition()` is relatively expensive, don't call it unless necessary. 154 ( 0.00%) self.name.is_unused_keyword_always() . || self.name.is_unused_keyword_conditional(|| self.span.edition()) 308 ( 0.00%) } . . /// Returns `true` if the token is either a special identifier or a keyword. 10,652 ( 0.00%) pub fn is_reserved(self) -> bool { . // Note: `span.edition()` is relatively expensive, don't call it unless necessary. . self.name.is_reserved(|| self.span.edition()) 21,304 ( 0.00%) } . . /// A keyword or reserved identifier that can be used as a path segment. . pub fn is_path_segment_keyword(self) -> bool { . self.name.is_path_segment_keyword() 21,105 ( 0.00%) } . . /// We see this identifier in a normal identifier position, like variable name or a type. . /// How was it written originally? Did it use the raw form? Let's try to guess. 1,903 ( 0.00%) pub fn is_raw_guess(self) -> bool { . self.name.can_be_raw() && self.is_reserved() 3,806 ( 0.00%) } . } 665,200 ( 0.01%) -------------------------------------------------------------------------------- -- 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 . // . 4,808,718 ( 0.07%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 3,606,537 ( 0.05%) 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. 170,960 ( 0.00%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 256,440 ( 0.00%) libc::calloc(layout.size(), 1) as *mut u8 . } else { . let ptr = self.alloc(layout); . if !ptr.is_null() { . ptr::write_bytes(ptr, 0, layout.size()); . } . ptr . } . } . . #[inline] . unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) { 1,244,909 ( 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 { 344,344 ( 0.00%) if layout.align() <= MIN_ALIGN && layout.align() <= new_size { 688,688 ( 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_trait_selection/src/traits/structural_match.rs -------------------------------------------------------------------------------- Ir -- line 42 ---------------------------------------- . /// reachable from a constant's type to implement the . /// structural-match traits, which essentially say that . /// the implementation of `PartialEq::eq` behaves *equivalently* to a . /// comparison against the unfolded structure. . /// . /// For more background on why Rust has this requirement, and issues . /// that arose when the requirement was not enforced completely, see . /// Rust RFC 1445, rust-lang/rust#61188, and rust-lang/rust#62307. 1,658,070 ( 0.02%) pub fn search_for_structural_match_violation<'tcx>( . span: Span, . tcx: TyCtxt<'tcx>, . ty: Ty<'tcx>, . ) -> Option> { . // FIXME: we should instead pass in an `infcx` from the outside. 1,658,070 ( 0.02%) tcx.infer_ctxt().enter(|infcx| { 11,330,145 ( 0.16%) ty.visit_with(&mut Search { infcx, span, seen: FxHashSet::default() }).break_value() . }) 1,934,415 ( 0.03%) } . . /// This method returns true if and only if `adt_ty` itself has been marked as . /// eligible for structural-match: namely, if it implements both . /// `StructuralPartialEq` and `StructuralEq` (which are respectively injected by . /// `#[derive(PartialEq)]` and `#[derive(Eq)]`). . /// . /// Note that this does *not* recursively check if the substructure of `adt_ty` . /// implements the traits. 11 ( 0.00%) fn type_marked_structural<'tcx>( . infcx: &InferCtxt<'_, 'tcx>, . adt_ty: Ty<'tcx>, . cause: ObligationCause<'tcx>, . ) -> bool { . let mut fulfillment_cx = traits::FulfillmentContext::new(); . // require `#[derive(PartialEq)]` . let structural_peq_def_id = 11 ( 0.00%) infcx.tcx.require_lang_item(LangItem::StructuralPeq, Some(cause.span)); 10 ( 0.00%) fulfillment_cx.register_bound( . infcx, . ty::ParamEnv::empty(), . adt_ty, . structural_peq_def_id, . cause.clone(), . ); . // for now, require `#[derive(Eq)]`. (Doing so is a hack to work around . // the type `for<'a> fn(&'a ())` failing to implement `Eq` itself.) . let structural_teq_def_id = 5 ( 0.00%) infcx.tcx.require_lang_item(LangItem::StructuralTeq, Some(cause.span)); 8 ( 0.00%) fulfillment_cx.register_bound( . infcx, . ty::ParamEnv::empty(), . adt_ty, . structural_teq_def_id, 4 ( 0.00%) cause, . ); . . // We deliberately skip *reporting* fulfillment errors (via . // `report_fulfillment_errors`), for two reasons: . // . // 1. The error messages would mention `std::marker::StructuralPartialEq` . // (a trait which is solely meant as an implementation detail . // for now), and . // . // 2. We are sometimes doing future-incompatibility lints for . // now, so we do not want unconditional errors here. 2 ( 0.00%) fulfillment_cx.select_all_or_error(infcx).is_empty() 9 ( 0.00%) } . . /// This implements the traversal over the structure of a given type to try to . /// find instances of ADTs (specifically structs or enums) that do not implement . /// the structural-match traits (`StructuralPartialEq` and `StructuralEq`). . struct Search<'a, 'tcx> { . span: Span, . . infcx: InferCtxt<'a, 'tcx>, -- line 114 ---------------------------------------- -- line 126 ---------------------------------------- . fn type_marked_structural(&self, adt_ty: Ty<'tcx>) -> bool { . adt_ty.is_structural_eq_shallow(self.tcx()) . } . } . . impl<'a, 'tcx> TypeVisitor<'tcx> for Search<'a, 'tcx> { . type BreakTy = NonStructuralMatchTy<'tcx>; . 2,768,120 ( 0.04%) fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow { . debug!("Search visiting ty: {:?}", ty); . 1,660,872 ( 0.02%) let (adt_def, substs) = match *ty.kind() { 550 ( 0.00%) ty::Adt(adt_def, substs) => (adt_def, substs), . ty::Param(_) => { . return ControlFlow::Break(NonStructuralMatchTy::Param); . } . ty::Dynamic(..) => { . return ControlFlow::Break(NonStructuralMatchTy::Dynamic); . } . ty::Foreign(_) => { . return ControlFlow::Break(NonStructuralMatchTy::Foreign); -- line 146 ---------------------------------------- -- line 190 ---------------------------------------- . // These primitive types are always structural match. . // . // `Never` is kind of special here, but as it is not inhabitable, this should be fine. . return ControlFlow::CONTINUE; . } . . ty::Array(..) | ty::Slice(_) | ty::Ref(..) | ty::Tuple(..) => { . // First check all contained types and then tell the caller to continue searching. 930 ( 0.00%) return ty.super_visit_with(self); . } . ty::Infer(_) | ty::Placeholder(_) | ty::Bound(..) => { . bug!("unexpected type during structural-match checking: {:?}", ty); . } . ty::Error(_) => { . self.tcx().sess.delay_span_bug(self.span, "ty::Error in structural-match check"); . // We still want to check other types after encountering an error, . // as this may still emit relevant errors. . return ControlFlow::CONTINUE; . } . }; . 1,100 ( 0.00%) if !self.seen.insert(adt_def.did) { . debug!("Search already seen adt_def: {:?}", adt_def); . return ControlFlow::CONTINUE; . } . 550 ( 0.00%) if !self.type_marked_structural(ty) { . debug!("Search found ty: {:?}", ty); . return ControlFlow::Break(NonStructuralMatchTy::Adt(&adt_def)); . } . . // structural-match does not care about the . // instantiation of the generics in an ADT (it . // instead looks directly at its fields outside . // this match), so we skip super_visit_with. -- line 224 ---------------------------------------- -- line 231 ---------------------------------------- . // even though we skip super_visit_with, we must recur on . // fields of ADT. . let tcx = self.tcx(); . adt_def.all_fields().map(|field| field.ty(tcx, substs)).try_for_each(|field_ty| { . let ty = self.tcx().normalize_erasing_regions(ty::ParamEnv::empty(), field_ty); . debug!("structural-match ADT: field_ty={:?}, ty={:?}", field_ty, ty); . ty.visit_with(self) . }) 2,491,308 ( 0.04%) } . } . . pub fn provide(providers: &mut Providers) { 2 ( 0.00%) providers.has_structural_eq_impls = |tcx, ty| { 5 ( 0.00%) tcx.infer_ctxt().enter(|infcx| { . let cause = ObligationCause::dummy(); 6 ( 0.00%) type_marked_structural(&infcx, ty, cause) 1 ( 0.00%) }) 1 ( 0.00%) }; . } 2,764,394 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/vec_deque/mod.rs -------------------------------------------------------------------------------- Ir -- line 126 ---------------------------------------- . self.extend(remainder.iter().cloned()); . } . } . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . unsafe impl<#[may_dangle] T, A: Allocator> Drop for VecDeque { 3,871 ( 0.00%) fn drop(&mut self) { . /// Runs the destructor for all items in the slice when it gets dropped (normally or . /// during unwinding). . struct Dropper<'a, T>(&'a mut [T]); . . impl<'a, T> Drop for Dropper<'a, T> { . fn drop(&mut self) { . unsafe { . ptr::drop_in_place(self.0); -- line 142 ---------------------------------------- -- line 146 ---------------------------------------- . . let (front, back) = self.as_mut_slices(); . unsafe { . let _back_dropper = Dropper(back); . // use drop for [T] . ptr::drop_in_place(front); . } . // RawVec handles deallocation 4,424 ( 0.00%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Default for VecDeque { . /// Creates an empty `VecDeque`. . #[inline] . fn default() -> VecDeque { . VecDeque::new() . } . } . . impl VecDeque { . /// Marginally more convenient . #[inline] . fn ptr(&self) -> *mut T { 1,404,673 ( 0.02%) self.buf.ptr() . } . . /// Marginally more convenient . #[inline] . fn cap(&self) -> usize { . if mem::size_of::() == 0 { . // For zero sized types, we are always at maximum capacity . MAXIMUM_ZST_CAPACITY . } else { 1,579,761 ( 0.02%) self.buf.capacity() . } . } . . /// Turn ptr into a slice . #[inline] . unsafe fn buffer_as_slice(&self) -> &[T] { . unsafe { slice::from_raw_parts(self.ptr(), self.cap()) } . } -- line 188 ---------------------------------------- -- line 191 ---------------------------------------- . #[inline] . unsafe fn buffer_as_mut_slice(&mut self) -> &mut [T] { . unsafe { slice::from_raw_parts_mut(self.ptr(), self.cap()) } . } . . /// Moves an element out of the buffer . #[inline] . unsafe fn buffer_read(&mut self, off: usize) -> T { 72,710 ( 0.00%) unsafe { ptr::read(self.ptr().add(off)) } . } . . /// Writes an element into the buffer, moving it. . #[inline] . unsafe fn buffer_write(&mut self, off: usize, value: T) { . unsafe { . ptr::write(self.ptr().add(off), value); . } . } . . /// Returns `true` if the buffer is at full capacity. . #[inline] . fn is_full(&self) -> bool { 3,442,287 ( 0.05%) self.cap() - self.len() == 1 . } . . /// Returns the index in the underlying buffer for a given logical element . /// index. . #[inline] . fn wrap_index(&self, idx: usize) -> usize { . wrap_index(idx, self.cap()) . } -- line 221 ---------------------------------------- -- line 452 ---------------------------------------- . // [o o . o o o o o ] . // T H . // B [. . . o o o o o o o . . . . . . ] . // H T . // [o o o o o . o o ] . // H T . // C [o o o o o . . . . . . . . . o o ] . 1,940 ( 0.00%) if self.tail <= self.head { . // A . // Nop 393 ( 0.00%) } else if self.head < old_capacity - self.tail { . // B . unsafe { 12 ( 0.00%) self.copy_nonoverlapping(old_capacity, 0, self.head); . } 180 ( 0.00%) self.head += old_capacity; . debug_assert!(self.head > self.tail); . } else { . // C 64 ( 0.00%) let new_tail = new_capacity - (old_capacity - self.tail); . unsafe { 2 ( 0.00%) self.copy_nonoverlapping(new_tail, self.tail, old_capacity - self.tail); . } 32 ( 0.00%) self.tail = new_tail; . debug_assert!(self.head < self.tail); . } . debug_assert!(self.head < self.cap()); . debug_assert!(self.tail < self.cap()); . debug_assert!(self.cap().count_ones() == 1); . } . } . -- line 484 ---------------------------------------- -- line 507 ---------------------------------------- . /// use std::collections::VecDeque; . /// . /// let vector: VecDeque = VecDeque::with_capacity(10); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[must_use] . pub fn with_capacity(capacity: usize) -> VecDeque { 4,196 ( 0.00%) Self::with_capacity_in(capacity, Global) . } . } . . impl VecDeque { . /// Creates an empty `VecDeque`. . /// . /// # Examples . /// -- line 523 ---------------------------------------- -- line 524 ---------------------------------------- . /// ``` . /// use std::collections::VecDeque; . /// . /// let vector: VecDeque = VecDeque::new(); . /// ``` . #[inline] . #[unstable(feature = "allocator_api", issue = "32838")] . pub fn new_in(alloc: A) -> VecDeque { 614 ( 0.00%) VecDeque::with_capacity_in(INITIAL_CAPACITY, alloc) . } . . /// Creates an empty `VecDeque` with space for at least `capacity` elements. . /// . /// # Examples . /// . /// ``` . /// use std::collections::VecDeque; . /// . /// let vector: VecDeque = VecDeque::with_capacity(10); . /// ``` . #[unstable(feature = "allocator_api", issue = "32838")] 9,620 ( 0.00%) pub fn with_capacity_in(capacity: usize, alloc: A) -> VecDeque { 7,960 ( 0.00%) assert!(capacity < 1_usize << usize::BITS - 1, "capacity overflow"); . // +1 since the ringbuffer always leaves one space empty . let cap = cmp::max(capacity + 1, MINIMUM_CAPACITY + 1).next_power_of_two(); . 13,218 ( 0.00%) VecDeque { tail: 0, head: 0, buf: RawVec::with_capacity_in(cap, alloc) } 14,430 ( 0.00%) } . . /// Provides a reference to the element at the given index. . /// . /// Element at index 0 is the front of the queue. . /// . /// # Examples . /// . /// ``` -- line 559 ---------------------------------------- -- line 562 ---------------------------------------- . /// let mut buf = VecDeque::new(); . /// buf.push_back(3); . /// buf.push_back(4); . /// buf.push_back(5); . /// assert_eq!(buf.get(1), Some(&4)); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn get(&self, index: usize) -> Option<&T> { 5,379,600 ( 0.08%) if index < self.len() { . let idx = self.wrap_add(self.tail, index); . unsafe { Some(&*self.ptr().add(idx)) } . } else { . None . } . } . . /// Provides a mutable reference to the element at the given index. -- line 578 ---------------------------------------- -- line 591 ---------------------------------------- . /// if let Some(elem) = buf.get_mut(1) { . /// *elem = 7; . /// } . /// . /// assert_eq!(buf[1], 7); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn get_mut(&mut self, index: usize) -> Option<&mut T> { 2,508,130 ( 0.04%) if index < self.len() { . let idx = self.wrap_add(self.tail, index); . unsafe { Some(&mut *self.ptr().add(idx)) } . } else { . None . } . } . . /// Swaps elements at indices `i` and `j`. -- line 607 ---------------------------------------- -- line 694 ---------------------------------------- . /// . /// let mut buf: VecDeque = [1].into(); . /// buf.reserve(10); . /// assert!(buf.capacity() >= 11); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn reserve(&mut self, additional: usize) { . let old_cap = self.cap(); 8 ( 0.00%) let used_cap = self.len() + 1; . let new_cap = used_cap . .checked_add(additional) . .and_then(|needed_cap| needed_cap.checked_next_power_of_two()) . .expect("capacity overflow"); . 16 ( 0.00%) if new_cap > old_cap { 24 ( 0.00%) self.buf.reserve_exact(used_cap, new_cap - used_cap); . unsafe { . self.handle_capacity_increase(old_cap); . } . } . } . . /// Tries to reserve the minimum capacity for exactly `additional` more elements to . /// be inserted in the given `VecDeque`. After calling `try_reserve_exact`, -- line 717 ---------------------------------------- -- line 924 ---------------------------------------- . /// buf.push_back(5); . /// buf.push_back(10); . /// buf.push_back(15); . /// assert_eq!(buf, [5, 10, 15]); . /// buf.truncate(1); . /// assert_eq!(buf, [5]); . /// ``` . #[stable(feature = "deque_extras", since = "1.16.0")] 760 ( 0.00%) pub fn truncate(&mut self, len: usize) { . /// Runs the destructor for all items in the slice when it gets dropped (normally or . /// during unwinding). . struct Dropper<'a, T>(&'a mut [T]); . . impl<'a, T> Drop for Dropper<'a, T> { . fn drop(&mut self) { . unsafe { . ptr::drop_in_place(self.0); -- line 940 ---------------------------------------- -- line 945 ---------------------------------------- . // Safe because: . // . // * Any slice passed to `drop_in_place` is valid; the second case has . // `len <= front.len()` and returning on `len > self.len()` ensures . // `begin <= back.len()` in the first case . // * The head of the VecDeque is moved before calling `drop_in_place`, . // so no value is dropped twice if `drop_in_place` panics . unsafe { 190 ( 0.00%) if len > self.len() { . return; . } . let num_dropped = self.len() - len; . let (front, back) = self.as_mut_slices(); 190 ( 0.00%) if len > front.len() { . let begin = len - front.len(); . let drop_back = back.get_unchecked_mut(begin..) as *mut _; . self.head = self.wrap_sub(self.head, num_dropped); . ptr::drop_in_place(drop_back); . } else { . let drop_back = back as *mut _; . let drop_front = front.get_unchecked_mut(len..) as *mut _; 95 ( 0.00%) self.head = self.wrap_sub(self.head, num_dropped); . . // Make sure the second half is dropped even when a destructor . // in the first one panics. . let _back_dropper = Dropper(&mut *drop_back); . ptr::drop_in_place(drop_front); . } . } 760 ( 0.00%) } . . /// Returns a reference to the underlying allocator. . #[unstable(feature = "allocator_api", issue = "32838")] . #[inline] . pub fn allocator(&self) -> &A { . self.buf.allocator() . } . -- line 982 ---------------------------------------- -- line 1085 ---------------------------------------- . /// vector.as_mut_slices().0[0] = 42; . /// vector.as_mut_slices().1[0] = 24; . /// assert_eq!(vector.as_slices(), (&[42, 10][..], &[24, 1][..])); . /// ``` . #[inline] . #[stable(feature = "deque_extras_15", since = "1.5.0")] . pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) { . unsafe { 4,780 ( 0.00%) let head = self.head; 4,780 ( 0.00%) let tail = self.tail; 5,855 ( 0.00%) let buf = self.buffer_as_mut_slice(); . RingSlices::ring_slices(buf, head, tail) . } . } . . /// Returns the number of elements in the `VecDeque`. . /// . /// # Examples . /// -- line 1103 ---------------------------------------- -- line 1106 ---------------------------------------- . /// . /// let mut v = VecDeque::new(); . /// assert_eq!(v.len(), 0); . /// v.push_back(1); . /// assert_eq!(v.len(), 1); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn len(&self) -> usize { 2,452,798 ( 0.03%) count(self.tail, self.head, self.cap()) . } . . /// Returns `true` if the `VecDeque` is empty. . /// . /// # Examples . /// . /// ``` . /// use std::collections::VecDeque; -- line 1122 ---------------------------------------- -- line 1123 ---------------------------------------- . /// . /// let mut v = VecDeque::new(); . /// assert!(v.is_empty()); . /// v.push_front(1); . /// assert!(!v.is_empty()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn is_empty(&self) -> bool { 4,709,429 ( 0.07%) self.tail == self.head . } . . fn range_tail_head(&self, range: R) -> (usize, usize) . where . R: RangeBounds, . { . let Range { start, end } = slice::range(range, ..self.len()); . let tail = self.wrap_add(self.tail, start); -- line 1139 ---------------------------------------- -- line 1307 ---------------------------------------- . /// let mut v = VecDeque::new(); . /// v.push_back(1); . /// v.clear(); . /// assert!(v.is_empty()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . pub fn clear(&mut self) { 190 ( 0.00%) self.truncate(0); . } . . /// Returns `true` if the `VecDeque` contains an element equal to the . /// given value. . /// . /// # Examples . /// . /// ``` -- line 1323 ---------------------------------------- -- line 1396 ---------------------------------------- . /// assert_eq!(d.back(), None); . /// . /// d.push_back(1); . /// d.push_back(2); . /// assert_eq!(d.back(), Some(&2)); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn back(&self) -> Option<&T> { 138,766 ( 0.00%) self.get(self.len().wrapping_sub(1)) . } . . /// Provides a mutable reference to the back element, or `None` if the . /// `VecDeque` is empty. . /// . /// # Examples . /// . /// ``` -- line 1412 ---------------------------------------- -- line 1441 ---------------------------------------- . /// d.push_back(2); . /// . /// assert_eq!(d.pop_front(), Some(1)); . /// assert_eq!(d.pop_front(), Some(2)); . /// assert_eq!(d.pop_front(), None); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn pop_front(&mut self) -> Option { 774,011 ( 0.01%) if self.is_empty() { . None . } else { . let tail = self.tail; 1,466,543 ( 0.02%) self.tail = self.wrap_add(self.tail, 1); 25,010 ( 0.00%) unsafe { Some(self.buffer_read(tail)) } . } . } . . /// Removes the last element from the `VecDeque` and returns it, or `None` if . /// it is empty. . /// . /// # Examples . /// -- line 1462 ---------------------------------------- -- line 1466 ---------------------------------------- . /// let mut buf = VecDeque::new(); . /// assert_eq!(buf.pop_back(), None); . /// buf.push_back(1); . /// buf.push_back(3); . /// assert_eq!(buf.pop_back(), Some(3)); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn pop_back(&mut self) -> Option { 408,157 ( 0.01%) if self.is_empty() { . None . } else { 674,987 ( 0.01%) self.head = self.wrap_sub(self.head, 1); . let head = self.head; . unsafe { Some(self.buffer_read(head)) } . } . } . . /// Prepends an element to the `VecDeque`. . /// . /// # Examples -- line 1485 ---------------------------------------- -- line 1513 ---------------------------------------- . /// use std::collections::VecDeque; . /// . /// let mut buf = VecDeque::new(); . /// buf.push_back(1); . /// buf.push_back(3); . /// assert_eq!(3, *buf.back().unwrap()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 2,804,952 ( 0.04%) pub fn push_back(&mut self, value: T) { 3,442,271 ( 0.05%) if self.is_full() { 851 ( 0.00%) self.grow(); . } . 477 ( 0.00%) let head = self.head; 1,147,898 ( 0.02%) self.head = self.wrap_add(self.head, 1); 446,183 ( 0.01%) unsafe { self.buffer_write(head, value) } 2,804,952 ( 0.04%) } . . #[inline] . fn is_contiguous(&self) -> bool { . // FIXME: Should we consider `head == 0` to mean . // that `self` is contiguous? . self.tail <= self.head . } . -- line 1537 ---------------------------------------- -- line 2209 ---------------------------------------- . self.truncate(idx); . } . } . . // Double the buffer size. This method is inline(never), so we expect it to only . // be called in cold paths. . // This may panic or abort . #[inline(never)] 2,862 ( 0.00%) fn grow(&mut self) { . // Extend or possibly remove this assertion when valid use-cases for growing the . // buffer without it being full emerge . debug_assert!(self.is_full()); . let old_cap = self.cap(); 1,431 ( 0.00%) self.buf.reserve_exact(old_cap, old_cap); 2,385 ( 0.00%) assert!(self.cap() == old_cap * 2); . unsafe { . self.handle_capacity_increase(old_cap); . } . debug_assert!(!self.is_full()); 2,862 ( 0.00%) } . . /// Modifies the `VecDeque` in-place so that `len()` is equal to `new_len`, . /// either by removing excess elements from the back or by appending . /// elements generated by calling `generator` to the back. . /// . /// # Examples . /// . /// ``` -- line 2236 ---------------------------------------- -- line 2751 ---------------------------------------- . } . } . . /// Returns the index in the underlying buffer for a given logical element index. . #[inline] . fn wrap_index(index: usize, size: usize) -> usize { . // size is always a power of 2 . debug_assert!(size.is_power_of_two()); 6,045,777 ( 0.09%) index & (size - 1) . } . . /// Calculate the number of elements left to be read in the buffer . #[inline] . fn count(tail: usize, head: usize, size: usize) -> usize { . // size is always a power of 2 10,194,600 ( 0.14%) (head.wrapping_sub(tail)) & (size - 1) . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl PartialEq for VecDeque { . fn eq(&self, other: &Self) -> bool { . if self.len() != other.len() { . return false; . } -- line 2774 ---------------------------------------- -- line 2902 ---------------------------------------- . . fn into_iter(self) -> IterMut<'a, T> { . self.iter_mut() . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Extend for VecDeque { 1,064 ( 0.00%) fn extend>(&mut self, iter: I) { . // This function should be the moral equivalent of: . // . // for item in iter.into_iter() { . // self.push_back(item); . // } . let mut iter = iter.into_iter(); . while let Some(element) = iter.next() { 1,149 ( 0.00%) if self.len() == self.capacity() { . let (lower, _) = iter.size_hint(); . self.reserve(lower.saturating_add(1)); . } . . let head = self.head; 269 ( 0.00%) self.head = self.wrap_add(self.head, 1); . unsafe { 144 ( 0.00%) self.buffer_write(head, element); . } . } 1,216 ( 0.00%) } . . #[inline] . fn extend_one(&mut self, elem: T) { . self.push_back(elem); . } . . #[inline] . fn extend_reserve(&mut self, additional: usize) { -- line 2937 ---------------------------------------- 1,954,961 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lexer/src/lib.rs -------------------------------------------------------------------------------- Ir -- line 38 ---------------------------------------- . #[derive(Debug)] . pub struct Token { . pub kind: TokenKind, . pub len: usize, . } . . impl Token { . fn new(kind: TokenKind, len: usize) -> Token { 4,100,148 ( 0.06%) Token { kind, len } . } . } . . /// Enum representing common lexeme types. . // perf note: Changing all `usize` to `u32` doesn't change performance. See #77629 91,390 ( 0.00%) #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] . pub enum TokenKind { . // Multi-char tokens: . /// "// comment" . LineComment { doc_style: Option }, . /// `/* block comment */` . /// . /// Block comments can be recursive, so the sequence like `/* /* */` . /// will not be considered terminated and will result in a parsing error. -- line 60 ---------------------------------------- -- line 192 ---------------------------------------- . /// Literal starts with "0x". . Hexadecimal, . /// Literal doesn't contain a prefix. . Decimal, . } . . /// `rustc` allows files to have a shebang, e.g. "#!/usr/bin/rustrun", . /// but shebang isn't a part of rust syntax. 133 ( 0.00%) pub fn strip_shebang(input: &str) -> Option { . // Shebang must start with `#!` literally, without any preceding whitespace. . // For simplicity we consider any line starting with `#!` a shebang, . // regardless of restrictions put on shebangs by specific platforms. . if let Some(input_tail) = input.strip_prefix("#!") { . // Ok, this is a shebang but if the next non-whitespace token is `[`, . // then it may be valid Rust code, so consider it Rust code. . let next_non_whitespace_token = tokenize(input_tail).map(|tok| tok.kind).find(|tok| { . !matches!( -- line 208 ---------------------------------------- -- line 213 ---------------------------------------- . ) . }); . if next_non_whitespace_token != Some(TokenKind::OpenBracket) { . // No other choice than to consider this a shebang. . return Some(2 + input_tail.lines().next().unwrap_or_default().len()); . } . } . None 152 ( 0.00%) } . . /// Parses the first token from the provided input string. 1,366,716 ( 0.02%) pub fn first_token(input: &str) -> Token { . debug_assert!(!input.is_empty()); 455,572 ( 0.01%) Cursor::new(input).advance_token() 1,822,288 ( 0.03%) } . . /// Creates an iterator that produces tokens from the input string. . pub fn tokenize(input: &str) -> impl Iterator + '_ { . let mut cursor = Cursor::new(input); . std::iter::from_fn(move || { . if cursor.is_eof() { . None . } else { -- line 235 ---------------------------------------- -- line 243 ---------------------------------------- . /// See [Rust language reference](https://doc.rust-lang.org/reference/whitespace.html) . /// for definitions of these classes. . pub fn is_whitespace(c: char) -> bool { . // This is Pattern_White_Space. . // . // Note that this set is stable (ie, it doesn't change with different . // Unicode versions), so it's ok to just hard-code the values. . 724,278 ( 0.01%) matches!( . c, . // Usual ASCII suspects . '\u{0009}' // \t . | '\u{000A}' // \n . | '\u{000B}' // vertical tab . | '\u{000C}' // form feed . | '\u{000D}' // \r . | '\u{0020}' // space -- line 259 ---------------------------------------- -- line 269 ---------------------------------------- . | '\u{2028}' // LINE SEPARATOR . | '\u{2029}' // PARAGRAPH SEPARATOR . ) . } . . /// True if `c` is valid as a first character of an identifier. . /// See [Rust language reference](https://doc.rust-lang.org/reference/identifiers.html) for . /// a formal definition of valid identifier name. 115 ( 0.00%) pub fn is_id_start(c: char) -> bool { . // This is XID_Start OR '_' (which formally is not a XID_Start). 278,136 ( 0.00%) c == '_' || unicode_xid::UnicodeXID::is_xid_start(c) 115 ( 0.00%) } . . /// True if `c` is valid as a non-first character of an identifier. . /// See [Rust language reference](https://doc.rust-lang.org/reference/identifiers.html) for . /// a formal definition of valid identifier name. . pub fn is_id_continue(c: char) -> bool { . unicode_xid::UnicodeXID::is_xid_continue(c) 128 ( 0.00%) } . . /// The passed string is lexically an identifier. 10 ( 0.00%) pub fn is_ident(string: &str) -> bool { . let mut chars = string.chars(); . if let Some(start) = chars.next() { . is_id_start(start) && chars.all(is_id_continue) . } else { . false . } 14 ( 0.00%) } . . impl Cursor<'_> { . /// Parses a token from the input string. 3,644,576 ( 0.05%) fn advance_token(&mut self) -> Token { . let first_char = self.bump().unwrap(); 1,397,338 ( 0.02%) let token_kind = match first_char { . // Slash, comment or block comment. 6,722 ( 0.00%) '/' => match self.first() { . '/' => self.line_comment(), . '*' => self.block_comment(), . _ => Slash, . }, . . // Whitespace sequence. . c if is_whitespace(c) => self.whitespace(), . . // Raw identifier, raw string literal or identifier. 944 ( 0.00%) 'r' => match (self.first(), self.second()) { . ('#', c1) if is_id_start(c1) => self.raw_ident(), . ('#', _) | ('"', _) => { 22 ( 0.00%) let (n_hashes, err) = self.raw_double_quoted_string(1); . let suffix_start = self.len_consumed(); 2 ( 0.00%) if err.is_none() { . self.eat_literal_suffix(); . } . let kind = RawStr { n_hashes, err }; 14 ( 0.00%) Literal { kind, suffix_start } . } . _ => self.ident_or_unknown_prefix(), . }, . . // Byte literal, byte string literal, raw byte string literal or identifier. 342 ( 0.00%) 'b' => match (self.first(), self.second()) { . ('\'', _) => { . self.bump(); . let terminated = self.single_quoted_string(); . let suffix_start = self.len_consumed(); . if terminated { . self.eat_literal_suffix(); . } . let kind = Byte { terminated }; -- line 338 ---------------------------------------- -- line 361 ---------------------------------------- . _ => self.ident_or_unknown_prefix(), . }, . . // Identifier (this should be checked after other variant that can . // start as identifier). . c if is_id_start(c) => self.ident_or_unknown_prefix(), . . // Numeric literal. 883,752 ( 0.01%) c @ '0'..='9' => { . let literal_kind = self.number(c); . let suffix_start = self.len_consumed(); . self.eat_literal_suffix(); 691,150 ( 0.01%) TokenKind::Literal { kind: literal_kind, suffix_start } . } . . // One-symbol tokens. 1,624 ( 0.00%) ';' => Semi, 280,186 ( 0.00%) ',' => Comma, 2,290 ( 0.00%) '.' => Dot, 3,524 ( 0.00%) '(' => OpenParen, 3,524 ( 0.00%) ')' => CloseParen, 1,520 ( 0.00%) '{' => OpenBrace, 1,520 ( 0.00%) '}' => CloseBrace, 1,686 ( 0.00%) '[' => OpenBracket, 1,686 ( 0.00%) ']' => CloseBracket, . '@' => At, 362 ( 0.00%) '#' => Pound, . '~' => Tilde, 24 ( 0.00%) '?' => Question, 5,964 ( 0.00%) ':' => Colon, 334 ( 0.00%) '$' => Dollar, 1,332 ( 0.00%) '=' => Eq, 674 ( 0.00%) '!' => Bang, 880 ( 0.00%) '<' => Lt, 1,440 ( 0.00%) '>' => Gt, 368 ( 0.00%) '-' => Minus, 2,064 ( 0.00%) '&' => And, 156 ( 0.00%) '|' => Or, 66 ( 0.00%) '+' => Plus, 76 ( 0.00%) '*' => Star, . '^' => Caret, . '%' => Percent, . . // Lifetime or character literal. 828 ( 0.00%) '\'' => self.lifetime_or_char(), . . // String literal. . '"' => { 1,284 ( 0.00%) let terminated = self.double_quoted_string(); . let suffix_start = self.len_consumed(); 856 ( 0.00%) if terminated { . self.eat_literal_suffix(); . } . let kind = Str { terminated }; 856 ( 0.00%) Literal { kind, suffix_start } . } . // Identifier starting with an emoji. Only lexed for graceful error recovery. . c if !c.is_ascii() && unic_emoji_char::is_emoji(c) => { . self.fake_ident_or_unknown_prefix() . } . _ => Unknown, . }; . Token::new(token_kind, self.len_consumed()) 4,100,148 ( 0.06%) } . . fn line_comment(&mut self) -> TokenKind { . debug_assert!(self.prev() == '/' && self.first() == '/'); . self.bump(); . 3,880 ( 0.00%) let doc_style = match self.first() { . // `//!` is an inner line doc comment. . '!' => Some(DocStyle::Inner), . // `////` (more than 3 slashes) is not considered a doc comment. 4,260 ( 0.00%) '/' if self.second() != '/' => Some(DocStyle::Outer), . _ => None, . }; . 53,666 ( 0.00%) self.eat_while(|c| c != '\n'); 5,040 ( 0.00%) LineComment { doc_style } . } . . fn block_comment(&mut self) -> TokenKind { . debug_assert!(self.prev() == '/' && self.first() == '*'); . self.bump(); . 4 ( 0.00%) let doc_style = match self.first() { . // `/*!` is an inner block doc comment. . '!' => Some(DocStyle::Inner), . // `/***` (more than 2 stars) is not considered a doc comment. . // `/**/` is not considered a doc comment. . '*' if !matches!(self.second(), '*' | '/') => Some(DocStyle::Outer), . _ => None, . }; . . let mut depth = 1usize; 302 ( 0.00%) while let Some(c) = self.bump() { . match c { . '/' if self.first() == '*' => { . self.bump(); . depth += 1; . } 2 ( 0.00%) '*' if self.first() == '/' => { . self.bump(); 2 ( 0.00%) depth -= 1; 2 ( 0.00%) if depth == 0 { . // This block comment is closed, so for a construction like "/* */ */" . // there will be a successfully parsed block comment "/* */" . // and " */" will be processed separately. . break; . } . } . _ => (), . } . } . 5 ( 0.00%) BlockComment { doc_style, terminated: depth == 0 } . } . . fn whitespace(&mut self) -> TokenKind { . debug_assert!(is_whitespace(self.prev())); . self.eat_while(is_whitespace); 150,166 ( 0.00%) Whitespace . } . . fn raw_ident(&mut self) -> TokenKind { . debug_assert!(self.prev() == 'r' && self.first() == '#' && is_id_start(self.second())); . // Eat "#" symbol. . self.bump(); . // Eat the identifier part of RawIdent. . self.eat_identifier(); . RawIdent . } . 45,695 ( 0.00%) fn ident_or_unknown_prefix(&mut self) -> TokenKind { . debug_assert!(is_id_start(self.prev())); . // Start is already eaten, eat the rest of identifier. 18,278 ( 0.00%) self.eat_while(is_id_continue); . // Known prefixes must have been handled earlier. So if . // we see a prefix here, it is definitely an unknown prefix. 18,278 ( 0.00%) match self.first() { . '#' | '"' | '\'' => UnknownPrefix, 9,139 ( 0.00%) c if !c.is_ascii() && unic_emoji_char::is_emoji(c) => { . self.fake_ident_or_unknown_prefix() . } 9,139 ( 0.00%) _ => Ident, . } 36,556 ( 0.00%) } . . fn fake_ident_or_unknown_prefix(&mut self) -> TokenKind { . // Start is already eaten, eat the rest of identifier. . self.eat_while(|c| { . unicode_xid::UnicodeXID::is_xid_continue(c) . || (!c.is_ascii() && unic_emoji_char::is_emoji(c)) . || c == '\u{200d}' . }); -- line 515 ---------------------------------------- -- line 519 ---------------------------------------- . '#' | '"' | '\'' => UnknownPrefix, . _ => InvalidIdent, . } . } . . fn number(&mut self, first_digit: char) -> LiteralKind { . debug_assert!('0' <= self.prev() && self.prev() <= '9'); . let mut base = Base::Decimal; 276,460 ( 0.00%) if first_digit == '0' { . // Attempt to parse encoding base. 449,075 ( 0.01%) let has_digits = match self.first() { . 'b' => { . base = Base::Binary; . self.bump(); . self.eat_decimal_digits() . } . 'o' => { . base = Base::Octal; . self.bump(); -- line 537 ---------------------------------------- -- line 538 ---------------------------------------- . self.eat_decimal_digits() . } . 'x' => { . base = Base::Hexadecimal; . self.bump(); . self.eat_hexadecimal_digits() . } . // Not a base prefix. 259,590 ( 0.00%) '0'..='9' | '_' | '.' | 'e' | 'E' => { . self.eat_decimal_digits(); . true . } . // Just a 0. . _ => return Int { base, empty_int: false }, . }; . // Base prefix was provided, but there were no digits . // after it, e.g. "0x". -- line 554 ---------------------------------------- -- line 555 ---------------------------------------- . if !has_digits { . return Int { base, empty_int: true }; . } . } else { . // No base prefix, parse number in the usual way. . self.eat_decimal_digits(); . }; . 310,200 ( 0.00%) match self.first() { . // Don't be greedy if this is actually an . // integer literal followed by field/method access or a range pattern . // (`0..2` and `12.foo()`) 24 ( 0.00%) '.' if self.second() != '.' && !is_id_start(self.second()) => { . // might have stuff after the ., and if it does, it needs to start . // with a number . self.bump(); . let mut empty_exponent = false; . if self.first().is_digit(10) { . self.eat_decimal_digits(); . match self.first() { . 'e' | 'E' => { -- line 575 ---------------------------------------- -- line 585 ---------------------------------------- . self.bump(); . let empty_exponent = !self.eat_float_exponent(); . Float { base, empty_exponent } . } . _ => Int { base, empty_int: false }, . } . } . 1,932 ( 0.00%) fn lifetime_or_char(&mut self) -> TokenKind { . debug_assert!(self.prev() == '\''); . 552 ( 0.00%) let can_be_a_lifetime = if self.second() == '\'' { . // It's surely not a lifetime. . false . } else { . // If the first symbol is valid for identifier, it can be a lifetime. . // Also check if it's a number for a better error reporting (so '0 will . // be reported as invalid lifetime and not as unterminated char literal). . is_id_start(self.first()) || self.first().is_digit(10) . }; . 9 ( 0.00%) if !can_be_a_lifetime { 75 ( 0.00%) let terminated = self.single_quoted_string(); . let suffix_start = self.len_consumed(); 50 ( 0.00%) if terminated { . self.eat_literal_suffix(); . } . let kind = Char { terminated }; 100 ( 0.00%) return Literal { kind, suffix_start }; . } . . // Either a lifetime or a character literal with . // length greater than 1. . . let starts_with_number = self.first().is_digit(10); . . // Skip the literal contents. . // First symbol can be a number (which isn't a valid identifier start), . // so skip it without any checks. . self.bump(); 502 ( 0.00%) self.eat_while(is_id_continue); . . // Check if after skipping literal contents we've met a closing . // single quote (which means that user attempted to create a . // string with single quotes). 502 ( 0.00%) if self.first() == '\'' { . self.bump(); . let kind = Char { terminated: true }; . Literal { kind, suffix_start: self.len_consumed() } . } else { 502 ( 0.00%) Lifetime { starts_with_number } . } 1,656 ( 0.00%) } . . fn single_quoted_string(&mut self) -> bool { . debug_assert!(self.prev() == '\''); . // Check if it's a one-symbol literal. 82 ( 0.00%) if self.second() == '\'' && self.first() != '\\' { . self.bump(); . self.bump(); . return true; . } . . // Literal has more than one symbol. . . // Parse until either quotes are terminated or error is detected. . loop { 99 ( 0.00%) match self.first() { . // Quotes are terminated, finish parsing. . '\'' => { . self.bump(); . return true; . } . // Probably beginning of the comment, which we don't want to include . // to the error report. . '/' => break, -- line 660 ---------------------------------------- -- line 670 ---------------------------------------- . // Skip the character. . _ => { . self.bump(); . } . } . } . // String was not terminated. . false 25 ( 0.00%) } . . /// Eats double-quoted string and returns true . /// if string is terminated. . fn double_quoted_string(&mut self) -> bool { . debug_assert!(self.prev() == '"'); . while let Some(c) = self.bump() { 25,682 ( 0.00%) match c { . '"' => { . return true; . } 464 ( 0.00%) '\\' if self.first() == '\\' || self.first() == '"' => { . // Bump again to skip escaped character. . self.bump(); . } . _ => (), . } . } . // End of file reached. . false 428 ( 0.00%) } . . /// Eats the double-quoted string and returns `n_hashes` and an error if encountered. 14 ( 0.00%) fn raw_double_quoted_string(&mut self, prefix_len: usize) -> (u16, Option) { . // Wrap the actual function to handle the error with too many hashes. . // This way, it eats the whole raw string. . let (n_hashes, err) = self.raw_string_unvalidated(prefix_len); . // Only up to 65535 `#`s are allowed in raw strings 2 ( 0.00%) match u16::try_from(n_hashes) { 14 ( 0.00%) Ok(num) => (num, err), . // We lie about the number of hashes here :P . Err(_) => (0, Some(RawStrError::TooManyDelimiters { found: n_hashes })), . } 16 ( 0.00%) } . . fn raw_string_unvalidated(&mut self, prefix_len: usize) -> (usize, Option) { . debug_assert!(self.prev() == 'r'); . let start_pos = self.len_consumed(); . let mut possible_terminator_offset = None; . let mut max_hashes = 0; . . // Count opening '#' symbols. . let mut eaten = 0; 8 ( 0.00%) while self.first() == '#' { 6 ( 0.00%) eaten += 1; . self.bump(); . } . let n_start_hashes = eaten; . . // Check that string is started. 8 ( 0.00%) match self.bump() { . Some('"') => (), . c => { . let c = c.unwrap_or(EOF_CHAR); . return (n_start_hashes, Some(RawStrError::InvalidStarter { bad_char: c })); . } . } . . // Skip the string contents and on each '#' character met, check if this is . // a raw string termination. . loop { 706 ( 0.00%) self.eat_while(|c| c != '"'); . 60 ( 0.00%) if self.is_eof() { . return ( . n_start_hashes, . Some(RawStrError::NoTerminator { . expected: n_start_hashes, . found: max_hashes, . possible_terminator_offset, . }), . ); -- line 749 ---------------------------------------- -- line 753 ---------------------------------------- . self.bump(); . . // Check that amount of closing '#' symbols . // is equal to the amount of opening ones. . // Note that this will not consume extra trailing `#` characters: . // `r###"abcde"####` is lexed as a `RawStr { n_hashes: 3 }` . // followed by a `#` token. . let mut n_end_hashes = 0; 248 ( 0.00%) while self.first() == '#' && n_end_hashes < n_start_hashes { 4 ( 0.00%) n_end_hashes += 1; . self.bump(); . } . 120 ( 0.00%) if n_end_hashes == n_start_hashes { . return (n_start_hashes, None); 116 ( 0.00%) } else if n_end_hashes > max_hashes { . // Keep track of possible terminators to give a hint about . // where there might be a missing terminator . possible_terminator_offset = . Some(self.len_consumed() - start_pos - n_end_hashes + prefix_len); . max_hashes = n_end_hashes; . } . } . } . . fn eat_decimal_digits(&mut self) -> bool { . let mut has_digits = false; . loop { 111,070 ( 0.00%) match self.first() { . '_' => { . self.bump(); . } 166,605 ( 0.00%) '0'..='9' => { . has_digits = true; . self.bump(); . } . _ => break, . } . } . has_digits 92,458 ( 0.00%) } . . fn eat_hexadecimal_digits(&mut self) -> bool { . let mut has_digits = false; . loop { 148,616 ( 0.00%) match self.first() { . '_' => { . self.bump(); . } 341,622 ( 0.00%) '0'..='9' | 'a'..='f' | 'A'..='F' => { . has_digits = true; . self.bump(); . } . _ => break, . } . } . has_digits 10,958 ( 0.00%) } . . /// Eats the float exponent. Returns true if at least one digit was met, . /// and returns false otherwise. . fn eat_float_exponent(&mut self) -> bool { . debug_assert!(self.prev() == 'e' || self.prev() == 'E'); . if self.first() == '-' || self.first() == '+' { . self.bump(); . } . self.eat_decimal_digits() . } . . // Eats the suffix of the literal, e.g. "_u8". . fn eat_literal_suffix(&mut self) { 277,370 ( 0.00%) self.eat_identifier(); . } . . // Eats the identifier. 416,055 ( 0.01%) fn eat_identifier(&mut self) { . if !is_id_start(self.first()) { . return; . } . self.bump(); . . self.eat_while(is_id_continue); 554,740 ( 0.01%) } . } 5,498,368 ( 0.08%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/bitmask.rs -------------------------------------------------------------------------------- Ir -- line 17 ---------------------------------------- . pub struct BitMask(pub BitMaskWord); . . #[allow(clippy::use_self)] . impl BitMask { . /// Returns a new `BitMask` with all bits inverted. . #[inline] . #[must_use] . pub fn invert(self) -> Self { 511,931 ( 0.01%) BitMask(self.0 ^ BITMASK_MASK) . } . . /// Flip the bit in the mask for the entry at the given index. . /// . /// Returns the bit's previous state. . #[inline] . #[allow(clippy::cast_ptr_alignment)] . #[cfg(feature = "raw")] -- line 33 ---------------------------------------- -- line 38 ---------------------------------------- . // The bit was set if the bit is now 0. . self.0 & mask == 0 . } . . /// Returns a new `BitMask` with the lowest bit removed. . #[inline] . #[must_use] . pub fn remove_lowest_bit(self) -> Self { 356,948 ( 0.01%) BitMask(self.0 & (self.0 - 1)) . } . /// Returns whether the `BitMask` has at least one set bit. . #[inline] . pub fn any_bit_set(self) -> bool { 3,696,097 ( 0.05%) self.0 != 0 . } . . /// Returns the first set bit in the `BitMask`, if there is one. . #[inline] . pub fn lowest_set_bit(self) -> Option { 43,392,547 ( 0.62%) if self.0 == 0 { . None . } else { . Some(unsafe { self.lowest_set_bit_nonzero() }) . } . } . . /// Returns the first set bit in the `BitMask`, if there is one. The . /// bitmask must not be empty. . #[inline] . #[cfg(feature = "nightly")] . pub unsafe fn lowest_set_bit_nonzero(self) -> usize { 17,433 ( 0.00%) intrinsics::cttz_nonzero(self.0) as usize / BITMASK_STRIDE . } . #[inline] . #[cfg(not(feature = "nightly"))] . pub unsafe fn lowest_set_bit_nonzero(self) -> usize { . self.trailing_zeros() . } . . /// Returns the number of trailing zeroes in the `BitMask`. -- line 77 ---------------------------------------- -- line 110 ---------------------------------------- . /// bits. . pub struct BitMaskIter(BitMask); . . impl Iterator for BitMaskIter { . type Item = usize; . . #[inline] . fn next(&mut self) -> Option { 7,182,050 ( 0.10%) let bit = self.0.lowest_set_bit()?; . self.0 = self.0.remove_lowest_bit(); . Some(bit) . } . } 55,881 ( 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}; . 28,464 ( 0.00%) #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub enum CommentKind { . Line, . Block, . } . 235 ( 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. 156,658 ( 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, . } . 3,521 ( 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. 295,492 ( 0.00%) #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub struct Lit { . pub kind: LitKind, . pub symbol: Symbol, . pub suffix: Option, . } . . impl fmt::Display for Lit { 690,140 ( 0.01%) fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 1,242,252 ( 0.02%) let Lit { kind, symbol, suffix } = *self; . match kind { . Byte => write!(f, "b'{}'", symbol)?, . Char => write!(f, "'{}'", symbol)?, 273 ( 0.00%) Str => write!(f, "\"{}\"", symbol)?, . StrRaw(n) => write!( . f, . "r{delim}\"{string}\"{delim}", . delim = "#".repeat(n as usize), . string = symbol . )?, . ByteStr => write!(f, "b\"{}\"", symbol)?, . ByteStrRaw(n) => write!( . f, . "br{delim}\"{string}\"{delim}", . delim = "#".repeat(n as usize), . string = symbol . )?, 413,811 ( 0.01%) Integer | Float | Bool | Err => write!(f, "{}", symbol)?, . } . 276,056 ( 0.00%) if let Some(suffix) = suffix { . write!(f, "{}", suffix)?; . } . . Ok(()) 690,140 ( 0.01%) } . } . . 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 130 ---------------------------------------- . crate fn may_have_suffix(self) -> bool { . matches!(self, Integer | Float | Err) . } . } . . impl Lit { . pub fn new(kind: LitKind, symbol: Symbol, suffix: Option) -> Lit { . Lit { kind, symbol, suffix } 968,748 ( 0.01%) } . } . 168 ( 0.00%) pub fn ident_can_begin_expr(name: Symbol, span: Span, is_raw: bool) -> bool { 294 ( 0.00%) let ident_token = Token::new(Ident(name, is_raw), span); . 124 ( 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) 210 ( 0.00%) } . . fn ident_can_begin_type(name: Symbol, span: Span, is_raw: bool) -> bool { 1,932 ( 0.00%) let ident_token = Token::new(Ident(name, is_raw), span); . 806 ( 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) . } . 28,137,251 ( 0.40%) #[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, 25,089 ( 0.00%) BinOp(BinOpToken), 60 ( 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., `{`). 43,602 ( 0.00%) OpenDelim(DelimToken), . /// A closing delimiter (e.g., `}`). 840,303 ( 0.01%) CloseDelim(DelimToken), . . /* Literals */ 424,638 ( 0.01%) 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. 20,318 ( 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. 1,401 ( 0.00%) Lifetime(Symbol), . 398 ( 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. 4,437 ( 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); . 1,390,885 ( 0.02%) #[derive(Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub struct Token { 12,789 ( 0.00%) pub kind: TokenKind, 48 ( 0.00%) pub span: Span, . } . . impl TokenKind { . pub fn lit(kind: LitKind, symbol: Symbol, suffix: Option) -> TokenKind { . Literal(Lit::new(kind, symbol, suffix)) . } . . // An approximation to proc-macro-style single-character operators used by rustc parser. . // If the operator token can be broken into two tokens, the first of which is single-character, . // then this function performs that operation, otherwise it returns `None`. 3,032 ( 0.00%) pub fn break_two_token_op(&self) -> Option<(TokenKind, TokenKind)> { 13,457 ( 0.00%) Some(match *self { . Le => (Lt, Eq), . EqEq => (Eq, Eq), . Ne => (Not, Eq), . Ge => (Gt, Eq), . AndAnd => (BinOp(And), BinOp(And)), . OrOr => (BinOp(Or), BinOp(Or)), . BinOp(Shl) => (Lt, Lt), . BinOp(Shr) => (Gt, Gt), -- line 271 ---------------------------------------- -- line 280 ---------------------------------------- . BinOpEq(Shl) => (Lt, Le), . BinOpEq(Shr) => (Gt, Ge), . DotDot => (Dot, Dot), . DotDotDot => (Dot, DotDot), . ModSep => (Colon, Colon), . RArrow => (BinOp(Minus), Gt), . LArrow => (Lt, BinOp(Minus)), . FatArrow => (Eq, Gt), 2,781 ( 0.00%) _ => return None, . }) 3,032 ( 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 { 1,688 ( 0.00%) matches!(self, Gt | Ge | BinOp(Shr) | BinOpEq(Shr)) 326 ( 0.00%) } . } . . impl Token { 307,365 ( 0.00%) pub fn new(kind: TokenKind, span: Span) -> Self { 930,685 ( 0.01%) Token { kind, span } 307,365 ( 0.00%) } . . /// Some token that will be thrown away later. 2,378 ( 0.00%) pub fn dummy() -> Self { . Token::new(TokenKind::Question, DUMMY_SP) 2,378 ( 0.00%) } . . /// Recovers a `Token` from an `Ident`. This creates a raw identifier if necessary. . pub fn from_ast_ident(ident: Ident) -> Self { 1,000 ( 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. 298,474 ( 0.00%) pub fn take(&mut self) -> Self { . mem::replace(self, Token::dummy()) 298,474 ( 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 { 2,100 ( 0.00%) match &self.kind { . Interpolated(nt) => nt.span(), 1,050 ( 0.00%) _ => self.span, . } 1,050 ( 0.00%) } . . pub fn is_op(&self) -> bool { 895,422 ( 0.01%) !matches!( 298,474 ( 0.00%) self.kind, . OpenDelim(..) . | CloseDelim(..) . | Literal(..) . | DocComment(..) . | Ident(..) . | Lifetime(..) . | Interpolated(..) . | Eof . ) 298,474 ( 0.00%) } . . pub fn is_like_plus(&self) -> bool { 10,872 ( 0.00%) matches!(self.kind, BinOp(Plus) | BinOpEq(Plus)) 2,126 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of an expression. 65 ( 0.00%) pub fn can_begin_expr(&self) -> bool { 325 ( 0.00%) match self.uninterpolate().kind { 378 ( 0.00%) Ident(name, is_raw) => 126 ( 0.00%) ident_can_begin_expr(name, self.span, is_raw), // value name or keyword . OpenDelim(..) | // tuple, array or block . Literal(..) | // literal . Not | // operator not . BinOp(Minus) | // unary minus . BinOp(Star) | // dereference . BinOp(Or) | OrOr | // closure . BinOp(And) | // reference . AndAnd | // double reference -- line 371 ---------------------------------------- -- line 376 ---------------------------------------- . Lifetime(..) | // labeled loop . Pound => true, // expression attributes . Interpolated(ref nt) => matches!(**nt, NtLiteral(..) | . NtExpr(..) | . NtBlock(..) | . NtPath(..)), . _ => false, . } 130 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of a type. 1,420 ( 0.00%) pub fn can_begin_type(&self) -> bool { 1,917 ( 0.00%) match self.uninterpolate().kind { 2,898 ( 0.00%) Ident(name, is_raw) => 322 ( 0.00%) ident_can_begin_type(name, self.span, is_raw), // type name or keyword . OpenDelim(Paren) | // tuple . OpenDelim(Bracket) | // array . Not | // never . BinOp(Star) | // raw pointer . BinOp(And) | // reference . AndAnd | // double reference . Question | // maybe bound in trait object . Lifetime(..) | // lifetime bound in trait object . Lt | BinOp(Shl) | // associated path . ModSep => true, // global path . Interpolated(ref nt) => matches!(**nt, NtTy(..) | NtPath(..)), . _ => false, . } 2,130 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of a const param. . pub fn can_begin_const_arg(&self) -> bool { 1,515 ( 0.00%) match self.kind { . OpenDelim(Brace) => true, . Interpolated(ref nt) => matches!(**nt, NtExpr(..) | NtBlock(..) | NtLiteral(..)), 303 ( 0.00%) _ => self.can_begin_literal_maybe_minus(), . } . } . . /// Returns `true` if the token can appear at the start of a generic bound. 3 ( 0.00%) pub fn can_begin_bound(&self) -> bool { 3 ( 0.00%) self.is_path_start() . || self.is_lifetime() . || self.is_keyword(kw::For) . || self == &Question . || self == &OpenDelim(Paren) 4 ( 0.00%) } . . /// Returns `true` if the token is any literal. . pub fn is_lit(&self) -> bool { . matches!(self.kind, Literal(..)) . } . . /// 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. 306 ( 0.00%) pub fn can_begin_literal_maybe_minus(&self) -> bool { 3,053 ( 0.00%) match self.uninterpolate().kind { . Literal(..) | BinOp(Minus) => true, 1,212 ( 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, . } 612 ( 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. 143,284 ( 0.00%) pub fn uninterpolate(&self) -> Cow<'_, Token> { 1,621,247 ( 0.02%) match &self.kind { 2,820 ( 0.00%) Interpolated(nt) => match **nt { 904 ( 0.00%) NtIdent(ident, is_raw) => { 2,260 ( 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), . } 143,284 ( 0.00%) } . . /// Returns an identifier if this token is an identifier. 440,442 ( 0.01%) pub fn ident(&self) -> Option<(Ident, /* is_raw */ bool)> { . let token = self.uninterpolate(); 995,087 ( 0.01%) match token.kind { 748,861 ( 0.01%) Ident(name, is_raw) => Some((Ident::new(name, token.span), is_raw)), . _ => None, . } 2,681,487 ( 0.04%) } . . /// Returns a lifetime identifier if this token is a lifetime. 1,025 ( 0.00%) pub fn lifetime(&self) -> Option { . let token = self.uninterpolate(); 5,550 ( 0.00%) match token.kind { 3,678 ( 0.00%) Lifetime(name) => Some(Ident::new(name, token.span)), . _ => None, . } 7,175 ( 0.00%) } . . /// Returns `true` if the token is an identifier. . pub fn is_ident(&self) -> bool { . self.ident().is_some() 1,756 ( 0.00%) } . . /// Returns `true` if the token is a lifetime. 1,750 ( 0.00%) pub fn is_lifetime(&self) -> bool { . self.lifetime().is_some() 3,500 ( 0.00%) } . . /// Returns `true` if the token is an identifier whose name is the given . /// string slice. 1,514 ( 0.00%) pub fn is_ident_named(&self, name: Symbol) -> bool { . self.ident().map_or(false, |(ident, _)| ident.name == name) 3,028 ( 0.00%) } . . /// Returns `true` if the token is an interpolated path. . fn is_path(&self) -> bool { 13,896 ( 0.00%) if let Interpolated(ref nt) = self.kind { . if let NtPath(..) = **nt { . return true; . } . } . false . } . . /// Would `maybe_whole_expr` in `parser.rs` return `Ok(..)`? -- line 515 ---------------------------------------- -- line 522 ---------------------------------------- . } . } . . false . } . . // Is the token an interpolated block (`$b:block`)? . pub fn is_whole_block(&self) -> bool { 140 ( 0.00%) if let Interpolated(ref nt) = self.kind { . if let NtBlock(..) = **nt { . return true; . } . } . false 70 ( 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) . } . 1,082 ( 0.00%) pub fn is_qpath_start(&self) -> bool { 8,030 ( 0.00%) self == &Lt || self == &BinOp(Shl) . } . 14,656 ( 0.00%) pub fn is_path_start(&self) -> bool { 21,114 ( 0.00%) self == &ModSep . || self.is_qpath_start() . || self.is_path() . || self.is_path_segment_keyword() 2,862 ( 0.00%) || self.is_ident() && !self.is_reserved_ident() 18,320 ( 0.00%) } . . /// Returns `true` if the token is a given keyword, `kw`. 44,279 ( 0.00%) pub fn is_keyword(&self, kw: Symbol) -> bool { . self.is_non_raw_ident_where(|id| id.name == kw) 88,558 ( 0.00%) } . 620 ( 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. 154 ( 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. 154 ( 0.00%) pub fn is_used_keyword(&self) -> bool { . self.is_non_raw_ident_where(Ident::is_used_keyword) . } . . /// Returns `true` if the token is a keyword reserved for possible future use. 154 ( 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`. 636 ( 0.00%) pub fn is_bool_lit(&self) -> bool { 1,272 ( 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. 20 ( 0.00%) pub fn is_non_raw_ident_where(&self, pred: impl FnOnce(Ident) -> bool) -> bool { 2,254,177 ( 0.03%) match self.ident() { 2,807 ( 0.00%) Some((id, false)) => pred(id), . _ => false, . } 25 ( 0.00%) } . 1,447,520 ( 0.02%) pub fn glue(&self, joint: &Token) -> Option { 723,760 ( 0.01%) let kind = match self.kind { 668 ( 0.00%) Eq => match joint.kind { . Eq => EqEq, . Gt => FatArrow, . _ => return None, . }, 28 ( 0.00%) Lt => match joint.kind { . Eq => Le, . Lt => BinOp(Shl), . Le => BinOpEq(Shl), . BinOp(Minus) => LArrow, . _ => return None, . }, 868 ( 0.00%) Gt => match joint.kind { . Eq => Ge, . Gt => BinOp(Shr), . Ge => BinOpEq(Shr), . _ => return None, . }, 46 ( 0.00%) Not => match joint.kind { . Eq => Ne, . _ => return None, . }, 2,405 ( 0.00%) BinOp(op) => match joint.kind { . Eq => BinOpEq(op), 22 ( 0.00%) BinOp(And) if op == And => AndAnd, 9 ( 0.00%) BinOp(Or) if op == Or => OrOr, 170 ( 0.00%) Gt if op == Minus => RArrow, . _ => return None, . }, 153 ( 0.00%) Dot => match joint.kind { . Dot => DotDot, . DotDot => DotDotDot, . _ => return None, . }, . DotDot => match joint.kind { . Dot => DotDotDot, . Eq => DotDotEq, . _ => return None, . }, 1,890 ( 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, . }; . 18,837 ( 0.00%) Some(Token::new(kind, self.span.to(joint.span))) 1,302,768 ( 0.02%) } . } . . impl PartialEq for Token { . fn eq(&self, rhs: &TokenKind) -> bool { 1,252,807 ( 0.02%) self.kind == *rhs . } . } . . #[derive(Clone, Encodable, Decodable)] . /// For interpolation during macro expansion. . pub enum Nonterminal { . NtItem(P), . NtBlock(P), -- line 675 ---------------------------------------- -- line 711 ---------------------------------------- . Path, . Vis, . TT, . } . . impl NonterminalKind { . /// The `edition` closure is used to get the edition for the given symbol. Doing . /// `span.edition()` is expensive, so we do it lazily. 300 ( 0.00%) pub fn from_symbol( . symbol: Symbol, . edition: impl FnOnce() -> Edition, . ) -> Option { 672 ( 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, . }) 300 ( 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 ---------------------------------------- 10,083,681 ( 0.14%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/mod.rs -------------------------------------------------------------------------------- Ir -- line 26 ---------------------------------------- . pub struct UnmatchedBrace { . pub expected_delim: token::DelimToken, . pub found_delim: Option, . pub found_span: Span, . pub unclosed_span: Option, . pub candidate_span: Option, . } . 266 ( 0.00%) crate fn parse_token_trees<'a>( . sess: &'a ParseSess, . src: &'a str, . start_pos: BytePos, . override_span: Option, . ) -> (PResult<'a, TokenStream>, Vec) { . StringReader { sess, start_pos, pos: start_pos, end_src_index: src.len(), src, override_span } . .into_token_trees() 171 ( 0.00%) } . . struct StringReader<'a> { . sess: &'a ParseSess, . /// Initial position, read-only. . start_pos: BytePos, . /// The absolute offset within the source_map of the current character. . pos: BytePos, . /// Stop reading src at this index. -- line 50 ---------------------------------------- -- line 51 ---------------------------------------- . end_src_index: usize, . /// Source text to tokenize. . src: &'a str, . override_span: Option, . } . . impl<'a> StringReader<'a> { . fn mk_sp(&self, lo: BytePos, hi: BytePos) -> Span { 314,381 ( 0.00%) self.override_span.unwrap_or_else(|| Span::with_root_ctxt(lo, hi)) . } . . /// Returns the next token, and info about preceding whitespace, if any. 2,136,561 ( 0.03%) fn next_token(&mut self) -> (Spacing, Token) { . let mut spacing = Spacing::Joint; . . // Skip `#!` at the start of the file 610,446 ( 0.01%) let start_src_index = self.src_index(self.pos); 915,669 ( 0.01%) let text: &str = &self.src[start_src_index..self.end_src_index]; . let is_beginning_of_file = self.pos == self.start_pos; 305,223 ( 0.00%) if is_beginning_of_file { 76 ( 0.00%) if let Some(shebang_len) = rustc_lexer::strip_shebang(text) { . self.pos = self.pos + BytePos::from_usize(shebang_len); . spacing = Spacing::Alone; . } . } . . // Skip trivial (whitespace & comments) tokens . loop { 605,959 ( 0.01%) let start_src_index = self.src_index(self.pos); 1,366,773 ( 0.02%) let text: &str = &self.src[start_src_index..self.end_src_index]; . 455,591 ( 0.01%) if text.is_empty() { . let span = self.mk_sp(self.pos, self.pos); 95 ( 0.00%) return (spacing, Token::new(token::Eof, span)); . } . 1,366,716 ( 0.02%) let token = rustc_lexer::first_token(text); . 911,144 ( 0.01%) let start = self.pos; 455,572 ( 0.01%) self.pos = self.pos + BytePos::from_usize(token.len); . . debug!("next_token: {:?}({:?})", token.kind, self.str_from(start)); . 3,650,492 ( 0.05%) match self.cook_lexer_token(token.kind, start) { 2,441,632 ( 0.03%) Some(kind) => { . let span = self.mk_sp(start, self.pos); 1,831,224 ( 0.03%) return (spacing, Token::new(kind, span)); . } . None => spacing = Spacing::Alone, . } . } 2,747,007 ( 0.04%) } . . /// Report a fatal lexical error with a given span. . fn fatal_span(&self, sp: Span, m: &str) -> FatalError { . self.sess.span_diagnostic.span_fatal(sp, m) . } . . /// Report a lexical error with a given span. . fn err_span(&self, sp: Span, m: &str) { -- line 110 ---------------------------------------- -- line 130 ---------------------------------------- . ) -> DiagnosticBuilder<'a> { . self.sess . .span_diagnostic . .struct_span_fatal(self.mk_sp(from_pos, to_pos), &format!("{}: {}", m, escaped_char(c))) . } . . /// Detect usages of Unicode codepoints changing the direction of the text on screen and loudly . /// complain about it. 1,414 ( 0.00%) fn lint_unicode_text_flow(&self, start: BytePos) { . // Opening delimiter of the length 2 is not included into the comment text. . let content_start = start + BytePos(2); . let content = self.str_from(content_start); . if contains_text_flow_control_chars(content) { . let span = self.mk_sp(start, self.pos); . self.sess.buffer_lint_with_diagnostic( . &TEXT_DIRECTION_CODEPOINT_IN_COMMENT, . span, . ast::CRATE_NODE_ID, . "unicode codepoint changing visible direction of text present in comment", . BuiltinLintDiagnostics::UnicodeTextFlow(span, content.to_string()), . ); . } 1,616 ( 0.00%) } . . /// Turns simple `rustc_lexer::TokenKind` enum into a rich . /// `rustc_ast::TokenKind`. This turns strings into interned . /// symbols and runs additional validation. . fn cook_lexer_token(&self, token: rustc_lexer::TokenKind, start: BytePos) -> Option { 2,277,860 ( 0.03%) Some(match token { 1,680 ( 0.00%) rustc_lexer::TokenKind::LineComment { doc_style } => { . // Skip non-doc comments 7,797 ( 0.00%) let doc_style = if let Some(doc_style) = doc_style { . doc_style . } else { . self.lint_unicode_text_flow(start); . return None; . }; . . // Opening delimiter of the length 3 is not included into the symbol. . let content_start = start + BytePos(3); . let content = self.str_from(content_start); 7,395 ( 0.00%) self.cook_doc_comment(content_start, content, CommentKind::Line, doc_style) . } 2 ( 0.00%) rustc_lexer::TokenKind::BlockComment { doc_style, terminated } => { 1 ( 0.00%) if !terminated { . let msg = match doc_style { . Some(_) => "unterminated block doc-comment", . None => "unterminated block comment", . }; . let last_bpos = self.pos; . self.sess.span_diagnostic.span_fatal_with_code( . self.mk_sp(start, last_bpos), . msg, . error_code!(E0758), . ); . } . . // Skip non-doc comments 1 ( 0.00%) let doc_style = if let Some(doc_style) = doc_style { . doc_style . } else { . self.lint_unicode_text_flow(start); . return None; . }; . . // Opening delimiter of the length 3 and closing delimiter of the length 2 . // are not included into the symbol. -- line 196 ---------------------------------------- -- line 198 ---------------------------------------- . let content_end = self.pos - BytePos(if terminated { 2 } else { 0 }); . let content = self.str_from_to(content_start, content_end); . self.cook_doc_comment(content_start, content, CommentKind::Block, doc_style) . } . rustc_lexer::TokenKind::Whitespace => return None, . rustc_lexer::TokenKind::Ident . | rustc_lexer::TokenKind::RawIdent . | rustc_lexer::TokenKind::UnknownPrefix => { 36,556 ( 0.00%) let is_raw_ident = token == rustc_lexer::TokenKind::RawIdent; 45,695 ( 0.00%) let is_unknown_prefix = token == rustc_lexer::TokenKind::UnknownPrefix; . let mut ident_start = start; 18,278 ( 0.00%) if is_raw_ident { . ident_start = ident_start + BytePos(2); . } 27,417 ( 0.00%) if is_unknown_prefix { . self.report_unknown_prefix(start); . } 45,695 ( 0.00%) let sym = nfc_normalize(self.str_from(ident_start)); . let span = self.mk_sp(start, self.pos); 36,556 ( 0.00%) self.sess.symbol_gallery.insert(sym, span); 18,278 ( 0.00%) if is_raw_ident { . if !sym.can_be_raw() { . self.err_span(span, &format!("`{}` cannot be a raw identifier", sym)); . } . self.sess.raw_identifier_spans.borrow_mut().push(span); . } 63,973 ( 0.00%) token::Ident(sym, is_raw_ident) . } . rustc_lexer::TokenKind::InvalidIdent . // Do not recover an identifier with emoji if the codepoint is a confusable . // with a recoverable substitution token, like `âž–`. . if UNICODE_ARRAY . .iter() . .find(|&&(c, _, _)| { . let sym = self.str_from(start); -- line 232 ---------------------------------------- -- line 234 ---------------------------------------- . }) . .is_none() => . { . let sym = nfc_normalize(self.str_from(start)); . let span = self.mk_sp(start, self.pos); . self.sess.bad_unicode_identifiers.borrow_mut().entry(sym).or_default().push(span); . token::Ident(sym, false) . } 2,218,960 ( 0.03%) rustc_lexer::TokenKind::Literal { kind, suffix_start } => { . let suffix_start = start + BytePos(suffix_start as u32); . let (kind, symbol) = self.cook_lexer_literal(start, suffix_start, kind); 416,055 ( 0.01%) let suffix = if suffix_start < self.pos { . let string = self.str_from(suffix_start); . if string == "_" { . self.sess . .span_diagnostic . .struct_span_warn( . self.mk_sp(suffix_start, self.pos), . "underscore literal suffix is not allowed", . ) -- line 253 ---------------------------------------- -- line 264 ---------------------------------------- . .emit(); . None . } else { . Some(Symbol::intern(string)) . } . } else { . None . }; 1,109,480 ( 0.02%) token::Literal(token::Lit { kind, symbol, suffix }) . } 502 ( 0.00%) rustc_lexer::TokenKind::Lifetime { starts_with_number } => { . // Include the leading `'` in the real identifier, for macro . // expansion purposes. See #12512 for the gory details of why . // this is necessary. . let lifetime_name = self.str_from(start); 251 ( 0.00%) if starts_with_number { . self.err_span_(start, self.pos, "lifetimes cannot start with a number"); . } 753 ( 0.00%) let ident = Symbol::intern(lifetime_name); 1,004 ( 0.00%) token::Lifetime(ident) . } . rustc_lexer::TokenKind::Semi => token::Semi, . rustc_lexer::TokenKind::Comma => token::Comma, . rustc_lexer::TokenKind::Dot => token::Dot, . rustc_lexer::TokenKind::OpenParen => token::OpenDelim(token::Paren), . rustc_lexer::TokenKind::CloseParen => token::CloseDelim(token::Paren), . rustc_lexer::TokenKind::OpenBrace => token::OpenDelim(token::Brace), . rustc_lexer::TokenKind::CloseBrace => token::CloseDelim(token::Brace), -- line 291 ---------------------------------------- -- line 324 ---------------------------------------- . err.help("source files must contain UTF-8 encoded text, unexpected null bytes might occur when a different encoding is used"); . } . err.emit(); . token? . } . }) . } . 17,748 ( 0.00%) fn cook_doc_comment( . &self, . content_start: BytePos, . content: &str, . comment_kind: CommentKind, . doc_style: DocStyle, . ) -> TokenKind { 1,479 ( 0.00%) if content.contains('\r') { . for (idx, _) in content.char_indices().filter(|&(_, c)| c == '\r') { . self.err_span_( . content_start + BytePos(idx as u32), . content_start + BytePos(idx as u32 + 1), . match comment_kind { . CommentKind::Line => "bare CR not allowed in doc-comment", . CommentKind::Block => "bare CR not allowed in block doc-comment", . }, -- line 347 ---------------------------------------- -- line 349 ---------------------------------------- . } . } . . let attr_style = match doc_style { . DocStyle::Outer => AttrStyle::Outer, . DocStyle::Inner => AttrStyle::Inner, . }; . 4,437 ( 0.00%) token::DocComment(comment_kind, attr_style, Symbol::intern(content)) 22,185 ( 0.00%) } . . fn cook_lexer_literal( . &self, . start: BytePos, . suffix_start: BytePos, . kind: rustc_lexer::LiteralKind, . ) -> (token::LitKind, Symbol) { . // prefix means `"` or `br"` or `r###"`, ... . let (lit_kind, mode, prefix_len, postfix_len) = match kind { 25 ( 0.00%) rustc_lexer::LiteralKind::Char { terminated } => { 25 ( 0.00%) if !terminated { . self.sess.span_diagnostic.span_fatal_with_code( . self.mk_sp(start, suffix_start), . "unterminated character literal", . error_code!(E0762), . ) . } . (token::Char, Mode::Char, 1, 1) // ' ' . } -- line 377 ---------------------------------------- -- line 380 ---------------------------------------- . self.sess.span_diagnostic.span_fatal_with_code( . self.mk_sp(start + BytePos(1), suffix_start), . "unterminated byte constant", . error_code!(E0763), . ) . } . (token::Byte, Mode::Byte, 2, 1) // b' ' . } 428 ( 0.00%) rustc_lexer::LiteralKind::Str { terminated } => { 428 ( 0.00%) if !terminated { . self.sess.span_diagnostic.span_fatal_with_code( . self.mk_sp(start, suffix_start), . "unterminated double quote string", . error_code!(E0765), . ) . } . (token::Str, Mode::Str, 1, 1) // " " . } -- line 397 ---------------------------------------- -- line 403 ---------------------------------------- . error_code!(E0766), . ) . } . (token::ByteStr, Mode::ByteStr, 2, 1) // b" " . } . rustc_lexer::LiteralKind::RawStr { n_hashes, err } => { . self.report_raw_str_error(start, err); . let n = u32::from(n_hashes); 10 ( 0.00%) (token::StrRaw(n_hashes), Mode::RawStr, 2 + n, 1 + n) // r##" "## . } . rustc_lexer::LiteralKind::RawByteStr { n_hashes, err } => { . self.report_raw_str_error(start, err); . let n = u32::from(n_hashes); . (token::ByteStrRaw(n_hashes), Mode::RawByteStr, 3 + n, 1 + n) // br##" "## . } 276,460 ( 0.00%) rustc_lexer::LiteralKind::Int { base, empty_int } => { 138,230 ( 0.00%) return if empty_int { . self.sess . .span_diagnostic . .struct_span_err_with_code( . self.mk_sp(start, suffix_start), . "no valid digits found for number", . error_code!(E0768), . ) . .emit(); . (token::Integer, sym::integer(0)) . } else { . self.validate_int_literal(base, start, suffix_start); 414,690 ( 0.01%) (token::Integer, self.symbol_from_to(start, suffix_start)) . }; . } . rustc_lexer::LiteralKind::Float { base, empty_exponent } => { . if empty_exponent { . self.err_span_(start, self.pos, "expected at least one digit in exponent"); . } . . match base { -- line 439 ---------------------------------------- -- line 452 ---------------------------------------- . } . . let id = self.symbol_from_to(start, suffix_start); . return (token::Float, id); . } . }; . let content_start = start + BytePos(prefix_len); . let content_end = suffix_start - BytePos(postfix_len); 1,365 ( 0.00%) let id = self.symbol_from_to(content_start, content_end); . self.validate_literal_escape(mode, content_start, content_end, prefix_len, postfix_len); . (lit_kind, id) . } . . #[inline] . fn src_index(&self, pos: BytePos) -> usize { . (pos - self.start_pos).to_usize() . } . . /// Slice of the source text from `start` up to but excluding `self.pos`, . /// meaning the slice does not include the character `self.ch`. . fn str_from(&self, start: BytePos) -> &str { 69,619 ( 0.00%) self.str_from_to(start, self.pos) . } . . /// As symbol_from, with an explicit endpoint. . fn symbol_from_to(&self, start: BytePos, end: BytePos) -> Symbol { . debug!("taking an ident from {:?} to {:?}", start, end); 973,070 ( 0.01%) Symbol::intern(self.str_from_to(start, end)) . } . . /// Slice of the source text spanning from `start` up to but excluding `end`. 150,211 ( 0.00%) fn str_from_to(&self, start: BytePos, end: BytePos) -> &str { . &self.src[self.src_index(start)..self.src_index(end)] 600,844 ( 0.01%) } . . fn report_raw_str_error(&self, start: BytePos, opt_err: Option) { 4 ( 0.00%) match opt_err { . Some(RawStrError::InvalidStarter { bad_char }) => { . self.report_non_started_raw_string(start, bad_char) . } . Some(RawStrError::NoTerminator { expected, found, possible_terminator_offset }) => self . .report_unterminated_raw_string(start, expected, possible_terminator_offset, found), . Some(RawStrError::TooManyDelimiters { found }) => { . self.report_too_many_hashes(start, found) . } -- line 496 ---------------------------------------- -- line 609 ---------------------------------------- . fn validate_literal_escape( . &self, . mode: Mode, . content_start: BytePos, . content_end: BytePos, . prefix_len: u32, . postfix_len: u32, . ) { 2,730 ( 0.00%) let lit_content = self.str_from_to(content_start, content_end); 59,162 ( 0.00%) unescape::unescape_literal(lit_content, mode, &mut |range, result| { . // Here we only check for errors. The actual unescaping is done later. 12,288 ( 0.00%) if let Err(err) = result { . let span_with_quotes = self . .mk_sp(content_start - BytePos(prefix_len), content_end + BytePos(postfix_len)); . let (start, end) = (range.start as u32, range.end as u32); . let lo = content_start + BytePos(start); . let hi = lo + BytePos(end - start); . let span = self.mk_sp(lo, hi); . emit_unescape_error( . &self.sess.span_diagnostic, -- line 628 ---------------------------------------- -- line 629 ---------------------------------------- . lit_content, . span_with_quotes, . span, . mode, . range, . err, . ); . } 55,296 ( 0.00%) }); . } . . fn validate_int_literal(&self, base: Base, content_start: BytePos, content_end: BytePos) { 552,920 ( 0.01%) let base = match base { . Base::Binary => 2, . Base::Octal => 8, . _ => return, . }; . let s = self.str_from_to(content_start + BytePos(2), content_end); . for (idx, c) in s.char_indices() { . let idx = idx as u32; . if c != '_' && c.to_digit(base).is_none() { -- line 649 ---------------------------------------- -- line 650 ---------------------------------------- . let lo = content_start + BytePos(2 + idx); . let hi = content_start + BytePos(2 + idx + c.len_utf8() as u32); . self.err_span_(lo, hi, &format!("invalid digit for a base {} literal", base)); . } . } . } . } . 82,251 ( 0.00%) pub fn nfc_normalize(string: &str) -> Symbol { . use unicode_normalization::{is_nfc_quick, IsNormalized, UnicodeNormalization}; 18,278 ( 0.00%) match is_nfc_quick(string.chars()) { 91,390 ( 0.00%) IsNormalized::Yes => Symbol::intern(string), . _ => { . let normalized_str: String = string.chars().nfc().collect(); . Symbol::intern(&normalized_str) . } . } . } 1,795,539 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/operand.rs -------------------------------------------------------------------------------- Ir -- line 41 ---------------------------------------- . fn from(val: ScalarMaybeUninit) -> Self { . Immediate::Scalar(val) . } . } . . impl From> for Immediate { . #[inline(always)] . fn from(val: Scalar) -> Self { 12 ( 0.00%) Immediate::Scalar(val.into()) . } . } . . impl<'tcx, Tag: Provenance> Immediate { . pub fn from_pointer(p: Pointer, cx: &impl HasDataLayout) -> Self { . Immediate::Scalar(ScalarMaybeUninit::from_pointer(p, cx)) . } . . pub fn from_maybe_pointer(p: Pointer>, cx: &impl HasDataLayout) -> Self { . Immediate::Scalar(ScalarMaybeUninit::from_maybe_pointer(p, cx)) . } . 748 ( 0.00%) pub fn new_slice(val: Scalar, len: u64, cx: &impl HasDataLayout) -> Self { 4,109 ( 0.00%) Immediate::ScalarPair(val.into(), Scalar::from_machine_usize(len, cx).into()) 1,122 ( 0.00%) } . . pub fn new_dyn_trait( . val: Scalar, . vtable: Pointer>, . cx: &impl HasDataLayout, . ) -> Self { . Immediate::ScalarPair(val.into(), ScalarMaybeUninit::from_maybe_pointer(vtable, cx)) . } . . #[inline] . pub fn to_scalar_or_uninit(self) -> ScalarMaybeUninit { 1,254 ( 0.00%) match self { 164 ( 0.00%) Immediate::Scalar(val) => val, . Immediate::ScalarPair(..) => bug!("Got a scalar pair where a scalar was expected"), . } . } . . #[inline] 4 ( 0.00%) pub fn to_scalar(self) -> InterpResult<'tcx, Scalar> { . self.to_scalar_or_uninit().check_init() 6 ( 0.00%) } . . #[inline] . pub fn to_scalar_pair(self) -> InterpResult<'tcx, (Scalar, Scalar)> { . match self { . Immediate::ScalarPair(val1, val2) => Ok((val1.check_init()?, val2.check_init()?)), . Immediate::Scalar(..) => { . bug!("Got a scalar where a scalar pair was expected") . } -- line 93 ---------------------------------------- -- line 159 ---------------------------------------- . fn deref(&self) -> &Immediate { . &self.imm . } . } . . /// An `Operand` is the result of computing a `mir::Operand`. It can be immediate, . /// or still in memory. The latter is an optimization, to delay reading that chunk of . /// memory and to avoid having to store arbitrary-sized data here. 505 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, HashStable, Hash, Debug)] . pub enum Operand { . Immediate(Immediate), . Indirect(MemPlace), . } . . #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] . pub struct OpTy<'tcx, Tag: Provenance = AllocId> { . op: Operand, // Keep this private; it helps enforce invariants. -- line 175 ---------------------------------------- -- line 185 ---------------------------------------- . fn deref(&self) -> &Operand { . &self.op . } . } . . impl<'tcx, Tag: Provenance> From> for OpTy<'tcx, Tag> { . #[inline(always)] . fn from(mplace: MPlaceTy<'tcx, Tag>) -> Self { 14,769 ( 0.00%) OpTy { op: Operand::Indirect(*mplace), layout: mplace.layout } . } . } . . impl<'tcx, Tag: Provenance> From<&'_ MPlaceTy<'tcx, Tag>> for OpTy<'tcx, Tag> { . #[inline(always)] . fn from(mplace: &MPlaceTy<'tcx, Tag>) -> Self { . OpTy { op: Operand::Indirect(**mplace), layout: mplace.layout } . } -- line 201 ---------------------------------------- -- line 206 ---------------------------------------- . fn from(val: ImmTy<'tcx, Tag>) -> Self { . OpTy { op: Operand::Immediate(val.imm), layout: val.layout } . } . } . . impl<'tcx, Tag: Provenance> ImmTy<'tcx, Tag> { . #[inline] . pub fn from_scalar(val: Scalar, layout: TyAndLayout<'tcx>) -> Self { 199 ( 0.00%) ImmTy { imm: val.into(), layout } . } . . #[inline] . pub fn from_immediate(imm: Immediate, layout: TyAndLayout<'tcx>) -> Self { . ImmTy { imm, layout } . } . . #[inline] . pub fn try_from_uint(i: impl Into, layout: TyAndLayout<'tcx>) -> Option { . Some(Self::from_scalar(Scalar::try_from_uint(i, layout.size)?, layout)) . } . #[inline] 28 ( 0.00%) pub fn from_uint(i: impl Into, layout: TyAndLayout<'tcx>) -> Self { 16 ( 0.00%) Self::from_scalar(Scalar::from_uint(i, layout.size), layout) 28 ( 0.00%) } . . #[inline] . pub fn try_from_int(i: impl Into, layout: TyAndLayout<'tcx>) -> Option { . Some(Self::from_scalar(Scalar::try_from_int(i, layout.size)?, layout)) . } . . #[inline] . pub fn from_int(i: impl Into, layout: TyAndLayout<'tcx>) -> Self { -- line 237 ---------------------------------------- -- line 248 ---------------------------------------- . . impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { . /// Try reading an immediate in memory; this is interesting particularly for `ScalarPair`. . /// Returns `None` if the layout does not permit loading this as a value. . fn try_read_immediate_from_mplace( . &self, . mplace: &MPlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, Option>> { 4,271 ( 0.00%) if mplace.layout.is_unsized() { . // Don't touch unsized . return Ok(None); . } . 12,219 ( 0.00%) let alloc = match self.get_alloc(mplace)? { 20,345 ( 0.00%) Some(ptr) => ptr, . None => { . return Ok(Some(ImmTy { . // zero-sized type 36 ( 0.00%) imm: Scalar::ZST.into(), . layout: mplace.layout, . })); . } . }; . 26,466 ( 0.00%) match mplace.layout.abi { . Abi::Scalar(..) => { 931 ( 0.00%) let scalar = alloc.read_scalar(alloc_range(Size::ZERO, mplace.layout.size))?; . Ok(Some(ImmTy { imm: scalar.into(), layout: mplace.layout })) . } 9,129 ( 0.00%) Abi::ScalarPair(a, b) => { . // We checked `ptr_align` above, so all fields will have the alignment they need. . // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`, . // which `ptr.offset(b_offset)` cannot possibly fail to satisfy. . let (a, b) = (a.value, b.value); . let (a_size, b_size) = (a.size(self), b.size(self)); . let b_offset = a_size.align_to(b.align(self).abi); 6,086 ( 0.00%) assert!(b_offset.bytes() > 0); // we later use the offset to tell apart the fields . let a_val = alloc.read_scalar(alloc_range(Size::ZERO, a_size))?; 9,129 ( 0.00%) let b_val = alloc.read_scalar(alloc_range(b_offset, b_size))?; 15,215 ( 0.00%) Ok(Some(ImmTy { imm: Immediate::ScalarPair(a_val, b_val), layout: mplace.layout })) . } . _ => Ok(None), . } . } . . /// Try returning an immediate for the operand. . /// If the layout does not permit loading this as an immediate, return where in memory . /// we can find the data. . /// Note that for a given layout, this operation will either always fail or always . /// succeed! Whether it succeeds depends on whether the layout can be represented . /// in an `Immediate`, not on which data is stored there currently. 1,312,785 ( 0.02%) pub fn try_read_immediate( . &self, . src: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, Result, MPlaceTy<'tcx, M::PointerTag>>> { 2,625,570 ( 0.04%) Ok(match src.try_as_mplace() { . Ok(ref mplace) => { 8,146 ( 0.00%) if let Some(val) = self.try_read_immediate_from_mplace(mplace)? { . Ok(val) . } else { . Err(*mplace) . } . } 1,417,920 ( 0.02%) Err(val) => Ok(val), . }) 1,312,785 ( 0.02%) } . . /// Read an immediate from a place, asserting that that is possible with the given layout. . #[inline(always)] . pub fn read_immediate( . &self, . op: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, ImmTy<'tcx, M::PointerTag>> { 26,648 ( 0.00%) if let Ok(imm) = self.try_read_immediate(op)? { 38,989 ( 0.00%) Ok(imm) . } else { . span_bug!(self.cur_span(), "primitive read failed for type: {:?}", op.layout.ty); . } . } . . /// Read a scalar from a place 451 ( 0.00%) pub fn read_scalar( . &self, . op: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, ScalarMaybeUninit> { 41 ( 0.00%) Ok(self.read_immediate(op)?.to_scalar_or_uninit()) 369 ( 0.00%) } . . /// Read a pointer from a place. . pub fn read_pointer( . &self, . op: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, Pointer>> { . Ok(self.scalar_to_ptr(self.read_scalar(op)?.check_init()?)) . } -- line 342 ---------------------------------------- -- line 345 ---------------------------------------- . pub fn read_str(&self, mplace: &MPlaceTy<'tcx, M::PointerTag>) -> InterpResult<'tcx, &str> { . let len = mplace.len(self)?; . let bytes = self.memory.read_bytes(mplace.ptr, Size::from_bytes(len))?; . let str = std::str::from_utf8(bytes).map_err(|err| err_ub!(InvalidStr(err)))?; . Ok(str) . } . . /// Projection functions 25,800 ( 0.00%) pub fn operand_field( . &self, . op: &OpTy<'tcx, M::PointerTag>, . field: usize, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { . let base = match op.try_as_mplace() { . Ok(ref mplace) => { . // We can reuse the mplace field computation logic for indirect operands. . let field = self.mplace_field(mplace, field)?; 28,336 ( 0.00%) return Ok(field.into()); . } 28 ( 0.00%) Err(value) => value, . }; . 20 ( 0.00%) let field_layout = op.layout.field(self, field); . if field_layout.is_zst() { . let immediate = Scalar::ZST.into(); . return Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout }); . } 12 ( 0.00%) let offset = op.layout.fields.offset(field); . let immediate = match *base { . // the field covers the entire type 52 ( 0.00%) _ if offset.bytes() == 0 && field_layout.size == op.layout.size => *base, . // extract fields from types with `ScalarPair` ABI . Immediate::ScalarPair(a, b) => { . let val = if offset.bytes() == 0 { a } else { b }; . Immediate::from(val) . } . Immediate::Scalar(val) => span_bug!( . self.cur_span(), . "field access on non aggregate {:#?}, {:#?}", . val, . op.layout . ), . }; 56 ( 0.00%) Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout }) 23,220 ( 0.00%) } . . pub fn operand_index( . &self, . op: &OpTy<'tcx, M::PointerTag>, . index: u64, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { . if let Ok(index) = usize::try_from(index) { . // We can just treat this as a field. -- line 397 ---------------------------------------- -- line 398 ---------------------------------------- . self.operand_field(op, index) . } else { . // Indexing into a big array. This must be an mplace. . let mplace = op.assert_mem_place(); . Ok(self.mplace_index(&mplace, index)?.into()) . } . } . 33 ( 0.00%) pub fn operand_downcast( . &self, . op: &OpTy<'tcx, M::PointerTag>, . variant: VariantIdx, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { . // Downcasts only change the layout 51 ( 0.00%) Ok(match op.try_as_mplace() { 10 ( 0.00%) Ok(ref mplace) => self.mplace_downcast(mplace, variant)?.into(), . Err(..) => { 6 ( 0.00%) let layout = op.layout.for_variant(self, variant); 28 ( 0.00%) OpTy { layout, ..*op } . } . }) 27 ( 0.00%) } . 76 ( 0.00%) pub fn operand_projection( . &self, . base: &OpTy<'tcx, M::PointerTag>, . proj_elem: mir::PlaceElem<'tcx>, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { . use rustc_middle::mir::ProjectionElem::*; 304 ( 0.00%) Ok(match proj_elem { 57 ( 0.00%) Field(field, _) => self.operand_field(base, field.index())?, . Downcast(_, variant) => self.operand_downcast(base, variant)?, . Deref => self.deref_operand(base)?.into(), . Subslice { .. } | ConstantIndex { .. } | Index(_) => { . // The rest should only occur as mplace, we do not use Immediates for types . // allowing such operations. This matches place_projection forcing an allocation. . let mplace = base.assert_mem_place(); . self.mplace_projection(&mplace, proj_elem)?.into() . } . }) 76 ( 0.00%) } . . /// Converts a repr(simd) operand into an operand where `place_index` accesses the SIMD elements. . /// Also returns the number of elements. . pub fn operand_to_simd( . &self, . base: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::PointerTag>, u64)> { . // Basically we just transmute this place into an array following simd_size_and_type. -- line 446 ---------------------------------------- -- line 449 ---------------------------------------- . self.mplace_to_simd(&base.assert_mem_place()) . } . . /// Read from a local. Will not actually access the local if reading from a ZST. . /// Will not access memory, instead an indirect `Operand` is returned. . /// . /// This is public because it is used by [priroda](https://github.com/oli-obk/priroda) to get an . /// OpTy from a local 60,552 ( 0.00%) pub fn access_local( . &self, . frame: &super::Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>, . local: mir::Local, . layout: Option>, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { . let layout = self.layout_of_local(frame, local, layout)?; 248 ( 0.00%) let op = if layout.is_zst() { . // Do not read from ZST, they might not be initialized 25 ( 0.00%) Operand::Immediate(Scalar::ZST.into()) . } else { 10,251 ( 0.00%) M::access_local(&self, frame, local)? . }; 40,131 ( 0.00%) Ok(OpTy { op, layout }) 48,119 ( 0.00%) } . . /// Every place can be read from, so we can turn them into an operand. . /// This will definitely return `Indirect` if the place is a `Ptr`, i.e., this . /// will never actually read from memory. . #[inline(always)] . pub fn place_to_op( . &self, . place: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { 1,538 ( 0.00%) let op = match **place { . Place::Ptr(mplace) => Operand::Indirect(mplace), . Place::Local { frame, local } => { 6,921 ( 0.00%) *self.access_local(&self.stack()[frame], local, None)? . } . }; 5,124 ( 0.00%) Ok(OpTy { op, layout: place.layout }) . } . . // Evaluate a place with the goal of reading from it. This lets us sometimes . // avoid allocations. 36,680 ( 0.00%) pub fn eval_place_to_op( . &self, . place: mir::Place<'tcx>, . layout: Option>, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { . // Do not use the layout passed in as argument if the base we are looking at . // here is not the entire place. 4,585 ( 0.00%) let layout = if place.projection.is_empty() { layout } else { None }; . 13,755 ( 0.00%) let base_op = self.access_local(self.frame(), place.local, layout)?; . . let op = place . .projection . .iter() 171 ( 0.00%) .try_fold(base_op, |op, elem| self.operand_projection(&op, elem))?; . . trace!("eval_place_to_op: got {:?}", *op); . // Sanity-check the type we ended up with. . debug_assert!(mir_assign_valid_types( . *self.tcx, . self.param_env, . self.layout_of(self.subst_from_current_frame_and_normalize_erasing_regions( . place.ty(&self.frame().body.local_decls, *self.tcx).ty . )?)?, . op.layout, . )); 6,366 ( 0.00%) Ok(op) 41,265 ( 0.00%) } . . /// Evaluate the operand, returning a place where you can then find the data. . /// If you already know the layout, you can save two table lookups . /// by passing it in here. . #[inline] 1,255,179 ( 0.02%) pub fn eval_operand( . &self, . mir_op: &mir::Operand<'tcx>, . layout: Option>, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { . use rustc_middle::mir::Operand::*; 284,881 ( 0.00%) let op = match *mir_op { . // FIXME: do some more logic on `move` to invalidate the old location 16,688 ( 0.00%) Copy(place) | Move(place) => self.eval_place_to_op(place, layout)?, . . Constant(ref constant) => { . let val = 2,084,245 ( 0.03%) self.subst_from_current_frame_and_normalize_erasing_regions(constant.literal)?; . // This can still fail: . // * During ConstProp, with `TooGeneric` or since the `requried_consts` were not all . // checked yet. . // * During CTFE, since promoteds in `const`/`static` initializer bodies can fail. . 2,338 ( 0.00%) self.mir_const_to_op(&val, layout)? . } . }; . trace!("{:?}: {:?}", mir_op, *op); 1,820,933 ( 0.03%) Ok(op) 836,787 ( 0.01%) } . . /// Evaluate a bunch of operands at once . pub(super) fn eval_operands( . &self, . ops: &[mir::Operand<'tcx>], . ) -> InterpResult<'tcx, Vec>> { . ops.iter().map(|op| self.eval_operand(op, None)).collect() . } . . // Used when the miri-engine runs into a constant and for extracting information from constants . // in patterns via the `const_eval` module . /// The `val` and `layout` are assumed to already be in our interpreter . /// "universe" (param_env). 1,660,284 ( 0.02%) pub fn const_to_op( . &self, . val: &ty::Const<'tcx>, . layout: Option>, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { 700,910 ( 0.01%) match val.val { . ty::ConstKind::Param(_) | ty::ConstKind::Bound(..) => throw_inval!(TooGeneric), . ty::ConstKind::Error(_) => throw_inval!(AlreadyReported(ErrorReported)), 368 ( 0.00%) ty::ConstKind::Unevaluated(uv) => { . let instance = self.resolve(uv.def, uv.substs)?; 1,012 ( 0.00%) Ok(self.eval_to_allocation(GlobalId { instance, promoted: uv.promoted })?.into()) . } . ty::ConstKind::Infer(..) | ty::ConstKind::Placeholder(..) => { . span_bug!(self.cur_span(), "const_to_op: Unexpected ConstKind {:?}", val) . } 1,393,968 ( 0.02%) ty::ConstKind::Value(val_val) => self.const_val_to_op(val_val, val.ty, layout), . } 1,245,213 ( 0.02%) } . 20,075 ( 0.00%) pub fn mir_const_to_op( . &self, . val: &mir::ConstantKind<'tcx>, . layout: Option>, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { 280,364 ( 0.00%) match val { 557,078 ( 0.01%) mir::ConstantKind::Ty(ct) => self.const_to_op(ct, layout), . mir::ConstantKind::Val(val, ty) => self.const_val_to_op(*val, ty, layout), . } 16,425 ( 0.00%) } . 1,400,900 ( 0.02%) crate fn const_val_to_op( . &self, . val_val: ConstValue<'tcx>, . ty: Ty<'tcx>, . layout: Option>, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { . // Other cases need layout. . let tag_scalar = |scalar| -> InterpResult<'tcx, _> { 838,842 ( 0.01%) Ok(match scalar { . Scalar::Ptr(ptr, size) => Scalar::Ptr(self.global_base_pointer(ptr)?, size), 418,326 ( 0.01%) Scalar::Int(int) => Scalar::Int(int), . }) . }; 417,756 ( 0.01%) let layout = from_known_layout(self.tcx, self.param_env, layout, || self.layout_of(ty))?; 420,836 ( 0.01%) let op = match val_val { 2 ( 0.00%) ConstValue::ByRef { alloc, offset } => { 2 ( 0.00%) let id = self.tcx.create_memory_alloc(alloc); . // We rely on mutability being set correctly in that allocation to prevent writes . // where none should happen. . let ptr = self.global_base_pointer(Pointer::new(id, offset))?; 4 ( 0.00%) Operand::Indirect(MemPlace::from_ptr(ptr.into(), layout.align.abi)) . } 1,259,809 ( 0.02%) ConstValue::Scalar(x) => Operand::Immediate(tag_scalar(x)?.into()), 846 ( 0.00%) ConstValue::Slice { data, start, end } => { . // We rely on mutability being set correctly in `data` to prevent writes . // where none should happen. . let ptr = Pointer::new( 846 ( 0.00%) self.tcx.create_memory_alloc(data), . Size::from_bytes(start), // offset: `start` . ); 4,301 ( 0.00%) Operand::Immediate(Immediate::new_slice( . Scalar::from_pointer(self.global_base_pointer(ptr)?, &*self.tcx), . u64::try_from(end.checked_sub(start).unwrap()).unwrap(), // len: `end - start` . self, . )) . } . }; 2,941,890 ( 0.04%) Ok(OpTy { op, layout }) 1,120,720 ( 0.02%) } . . /// Read discriminant, return the runtime value as well as the variant index. . /// Can also legally be called on non-enums (e.g. through the discriminant_value intrinsic)! 40 ( 0.00%) pub fn read_discriminant( . &self, . op: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, (Scalar, VariantIdx)> { . trace!("read_discriminant_value {:#?}", op.layout); . // Get type and layout of the discriminant. 48 ( 0.00%) let discr_layout = self.layout_of(op.layout.ty.discriminant_ty(*self.tcx))?; . trace!("discriminant type: {:?}", discr_layout.ty); . . // We use "discriminant" to refer to the value associated with a particular enum variant. . // This is not to be confused with its "variant index", which is just determining its position in the . // declared list of variants -- they can differ with explicitly assigned discriminants. . // We use "tag" to refer to how the discriminant is encoded in memory, which can be either . // straight-forward (`TagEncoding::Direct`) or with a niche (`TagEncoding::Niche`). 12 ( 0.00%) let (tag_scalar_layout, tag_encoding, tag_field) = match op.layout.variants { . Variants::Single { index } => { . let discr = match op.layout.ty.discriminant_for_variant(*self.tcx, index) { . Some(discr) => { . // This type actually has discriminants. . assert_eq!(discr.ty, discr_layout.ty); . Scalar::from_uint(discr.val, discr_layout.size) . } . None => { . // On a type without actual discriminants, variant is 0. . assert_eq!(index.as_u32(), 0); . Scalar::from_uint(index.as_u32(), discr_layout.size) . } . }; . return Ok((discr, index)); . } 8 ( 0.00%) Variants::Multiple { tag, ref tag_encoding, tag_field, .. } => { . (tag, tag_encoding, tag_field) . } . }; . . // There are *three* layouts that come into play here: . // - The discriminant has a type for typechecking. This is `discr_layout`, and is used for . // the `Scalar` we return. . // - The tag (encoded discriminant) has layout `tag_layout`. This is always an integer type, . // and used to interpret the value we read from the tag field. . // For the return value, a cast to `discr_layout` is performed. . // - The field storing the tag has a layout, which is very similar to `tag_layout` but . // may be a pointer. This is `tag_val.layout`; we just use it for sanity checks. . . // Get layout for tag. 24 ( 0.00%) let tag_layout = self.layout_of(tag_scalar_layout.value.to_int_ty(*self.tcx))?; . . // Read tag and sanity-check `tag_layout`. 28 ( 0.00%) let tag_val = self.read_immediate(&self.operand_field(op, tag_field)?)?; 8 ( 0.00%) assert_eq!(tag_layout.size, tag_val.layout.size); 32 ( 0.00%) assert_eq!(tag_layout.abi.is_signed(), tag_val.layout.abi.is_signed()); . let tag_val = tag_val.to_scalar()?; . trace!("tag value: {:?}", tag_val); . . // Figure out which discriminant and variant this corresponds to. 36 ( 0.00%) Ok(match *tag_encoding { . TagEncoding::Direct => { 40 ( 0.00%) let tag_bits = tag_val . .try_to_int() . .map_err(|dbg_val| err_ub!(InvalidTag(dbg_val)))? . .assert_bits(tag_layout.size); . // Cast bits from tag layout to discriminant layout. 16 ( 0.00%) let discr_val = self.cast_from_scalar(tag_bits, tag_layout, discr_layout.ty); 4 ( 0.00%) let discr_bits = discr_val.assert_bits(discr_layout.size); . // Convert discriminant to variant index, and catch invalid discriminants. 10 ( 0.00%) let index = match *op.layout.ty.kind() { 2 ( 0.00%) ty::Adt(adt, _) => { 30 ( 0.00%) adt.discriminants(*self.tcx).find(|(_, var)| var.val == discr_bits) . } . ty::Generator(def_id, substs, _) => { . let substs = substs.as_generator(); . substs . .discriminants(def_id, *self.tcx) . .find(|(_, var)| var.val == discr_bits) . } . _ => span_bug!(self.cur_span(), "tagged layout for non-adt non-generator"), . } . .ok_or_else(|| err_ub!(InvalidTag(Scalar::from_uint(tag_bits, tag_layout.size))))?; . // Return the cast value, and the index. 8 ( 0.00%) (discr_val, index.0) . } 12 ( 0.00%) TagEncoding::Niche { dataful_variant, ref niche_variants, niche_start } => { . // Compute the variant this niche value/"tag" corresponds to. With niche layout, . // discriminant (encoded in niche/tag) and variant index are the same. . let variants_start = niche_variants.start().as_u32(); 4 ( 0.00%) let variants_end = niche_variants.end().as_u32(); 8 ( 0.00%) let variant = match tag_val.try_to_int() { . Err(dbg_val) => { . // So this is a pointer then, and casting to an int failed. . // Can only happen during CTFE. . let ptr = self.scalar_to_ptr(tag_val); . // The niche must be just 0, and the ptr not null, then we know this is . // okay. Everything else, we conservatively reject. . let ptr_valid = niche_start == 0 . && variants_start == variants_end . && !self.memory.ptr_may_be_null(ptr); . if !ptr_valid { . throw_ub!(InvalidTag(dbg_val)) . } . dataful_variant . } . Ok(tag_bits) => { 34 ( 0.00%) let tag_bits = tag_bits.assert_bits(tag_layout.size); . // We need to use machine arithmetic to get the relative variant idx: . // variant_index_relative = tag_val - niche_start_val 12 ( 0.00%) let tag_val = ImmTy::from_uint(tag_bits, tag_layout); 14 ( 0.00%) let niche_start_val = ImmTy::from_uint(niche_start, tag_layout); . let variant_index_relative_val = 8 ( 0.00%) self.binary_op(mir::BinOp::Sub, &tag_val, &niche_start_val)?; 14 ( 0.00%) let variant_index_relative = variant_index_relative_val . .to_scalar()? 4 ( 0.00%) .assert_bits(tag_val.layout.size); . // Check if this is in the range that indicates an actual discriminant. 10 ( 0.00%) if variant_index_relative <= u128::from(variants_end - variants_start) { . let variant_index_relative = u32::try_from(variant_index_relative) . .expect("we checked that this fits into a u32"); . // Then computing the absolute variant idx should not overflow any more. . let variant_index = variants_start . .checked_add(variant_index_relative) . .expect("overflow computing absolute variant idx"); 2 ( 0.00%) let variants_len = op . .layout . .ty . .ty_adt_def() . .expect("tagged layout for non adt") . .variants . .len(); 4 ( 0.00%) assert!(usize::try_from(variant_index).unwrap() < variants_len); . VariantIdx::from_u32(variant_index) . } else { . dataful_variant . } . } . }; . // Compute the size of the scalar we need to return. . // No need to cast, because the variant index directly serves as discriminant and is . // encoded in the tag. 14 ( 0.00%) (Scalar::from_uint(variant.as_u32(), discr_layout.size), variant) . } . }) 36 ( 0.00%) } . } 2,518,043 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/hir/map/mod.rs -------------------------------------------------------------------------------- Ir -- line 17 ---------------------------------------- . use rustc_span::hygiene::MacroKind; . use rustc_span::source_map::Spanned; . use rustc_span::symbol::{kw, sym, Ident, Symbol}; . use rustc_span::Span; . use rustc_target::spec::abi::Abi; . use std::collections::VecDeque; . . fn fn_decl<'hir>(node: Node<'hir>) -> Option<&'hir FnDecl<'hir>> { 3,750 ( 0.00%) match node { . Node::Item(Item { kind: ItemKind::Fn(sig, _, _), .. }) . | Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(sig, _), .. }) . | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(sig, _), .. }) => Some(&sig.decl), . Node::Expr(Expr { kind: ExprKind::Closure(_, fn_decl, ..), .. }) . | Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, ..), .. }) => { . Some(fn_decl) . } . _ => None, . } . } . . pub fn fn_sig<'hir>(node: Node<'hir>) -> Option<&'hir FnSig<'hir>> { 744 ( 0.00%) match &node { . Node::Item(Item { kind: ItemKind::Fn(sig, _, _), .. }) . | Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(sig, _), .. }) . | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(sig, _), .. }) => Some(sig), . _ => None, . } . } . . pub fn associated_body<'hir>(node: Node<'hir>) -> Option { 63,728 ( 0.00%) match node { . Node::Item(Item { . kind: ItemKind::Const(_, body) | ItemKind::Static(.., body) | ItemKind::Fn(.., body), . .. . }) . | Node::TraitItem(TraitItem { . kind: . TraitItemKind::Const(_, Some(body)) | TraitItemKind::Fn(_, TraitFn::Provided(body)), . .. . }) . | Node::ImplItem(ImplItem { . kind: ImplItemKind::Const(_, body) | ImplItemKind::Fn(_, body), . .. . }) 10,940 ( 0.00%) | Node::Expr(Expr { kind: ExprKind::Closure(.., body, _, _), .. }) => Some(*body), . . Node::AnonConst(constant) => Some(constant.body), . . _ => None, . } . } . . fn is_body_owner<'hir>(node: Node<'hir>, hir_id: HirId) -> bool { -- line 69 ---------------------------------------- -- line 83 ---------------------------------------- . pub struct ParentHirIterator<'hir> { . current_id: HirId, . map: Map<'hir>, . } . . impl<'hir> Iterator for ParentHirIterator<'hir> { . type Item = (HirId, Node<'hir>); . 3,878 ( 0.00%) fn next(&mut self) -> Option { 570 ( 0.00%) if self.current_id == CRATE_HIR_ID { . return None; . } . loop { . // There are nodes that do not have entries, so we need to skip them. . let parent_id = self.map.get_parent_node(self.current_id); . 1,716 ( 0.00%) if parent_id == self.current_id { . self.current_id = CRATE_HIR_ID; . return None; . } . 1,160 ( 0.00%) self.current_id = parent_id; 4,582 ( 0.00%) if let Some(node) = self.map.find(parent_id) { 2,216 ( 0.00%) return Some((parent_id, node)); . } . // If this `HirId` doesn't have an entry, skip it and look for its `parent_id`. . } 4,986 ( 0.00%) } . } . . /// An iterator that walks up the ancestor tree of a given `HirId`. . /// Constructed using `tcx.hir().parent_owner_iter(hir_id)`. . pub struct ParentOwnerIterator<'hir> { . current_id: HirId, . map: Map<'hir>, . } . . impl<'hir> Iterator for ParentOwnerIterator<'hir> { . type Item = (LocalDefId, OwnerNode<'hir>); . 38,088 ( 0.00%) fn next(&mut self) -> Option { 12,696 ( 0.00%) if self.current_id.local_id.index() != 0 { 2,228 ( 0.00%) self.current_id.local_id = ItemLocalId::new(0); 8,912 ( 0.00%) if let Some(node) = self.map.tcx.hir_owner(self.current_id.owner) { . return Some((self.current_id.owner, node.node)); . } . } 2,004 ( 0.00%) if self.current_id == CRATE_HIR_ID { 4 ( 0.00%) return None; . } . loop { . // There are nodes that do not have entries, so we need to skip them. . let parent_id = self.map.def_key(self.current_id.owner).parent; . . let parent_id = parent_id.map_or(CRATE_HIR_ID.owner, |local_def_index| { . let def_id = LocalDefId { local_def_index }; . self.map.local_def_id_to_hir_id(def_id).owner . }); 4,004 ( 0.00%) self.current_id = HirId::make_owner(parent_id); . . // If this `HirId` doesn't have an entry, skip it and look for its `parent_id`. 4,004 ( 0.00%) if let Some(node) = self.map.tcx.hir_owner(self.current_id.owner) { . return Some((self.current_id.owner, node.node)); . } . } 33,856 ( 0.00%) } . } . . impl<'hir> Map<'hir> { 231 ( 0.00%) pub fn krate(&self) -> &'hir Crate<'hir> { 33 ( 0.00%) self.tcx.hir_crate(()) 264 ( 0.00%) } . 7 ( 0.00%) pub fn root_module(&self) -> &'hir Mod<'hir> { 1 ( 0.00%) match self.tcx.hir_owner(CRATE_DEF_ID).map(|o| o.node) { . Some(OwnerNode::Crate(item)) => item, . _ => bug!(), . } 8 ( 0.00%) } . . pub fn items(&self) -> impl Iterator> + 'hir { . let krate = self.krate(); . krate.owners.iter().filter_map(|owner| match owner.as_ref()?.node() { . OwnerNode::Item(item) => Some(item), . _ => None, . }) . } -- line 169 ---------------------------------------- -- line 184 ---------------------------------------- . . #[inline] . pub fn def_path_hash(self, def_id: LocalDefId) -> DefPathHash { . // Accessing the DefPathHash is ok, it is incr. comp. stable. . self.tcx.untracked_resolutions.definitions.def_path_hash(def_id) . } . . #[inline] 78,540 ( 0.00%) pub fn local_def_id(&self, hir_id: HirId) -> LocalDefId { 19,356 ( 0.00%) self.opt_local_def_id(hir_id).unwrap_or_else(|| { . bug!( . "local_def_id: no entry for `{:?}`, which has a map of `{:?}`", . hir_id, . self.find(hir_id) . ) . }) 58,905 ( 0.00%) } . . #[inline] 51,616 ( 0.00%) pub fn opt_local_def_id(&self, hir_id: HirId) -> Option { 14,124 ( 0.00%) if hir_id.local_id == ItemLocalId::new(0) { . Some(hir_id.owner) . } else { 4,560 ( 0.00%) self.tcx . .hir_owner_nodes(hir_id.owner)? . .local_id_to_def_id . .get(&hir_id.local_id) . .copied() . } 58,068 ( 0.00%) } . . #[inline] 303 ( 0.00%) pub fn local_def_id_to_hir_id(&self, def_id: LocalDefId) -> HirId { . // FIXME(#85914) is this access safe for incr. comp.? 4,302 ( 0.00%) self.tcx.untracked_resolutions.definitions.local_def_id_to_hir_id(def_id) 606 ( 0.00%) } . 7 ( 0.00%) pub fn iter_local_def_id(&self) -> impl Iterator + '_ { . // Create a dependency to the crate to be sure we reexcute this when the amount of . // definitions change. 1 ( 0.00%) self.tcx.ensure().hir_crate(()); . self.tcx.untracked_resolutions.definitions.iter_local_def_id() 9 ( 0.00%) } . 8,330 ( 0.00%) pub fn opt_def_kind(&self, local_def_id: LocalDefId) -> Option { . let hir_id = self.local_def_id_to_hir_id(local_def_id); 15,470 ( 0.00%) let def_kind = match self.find(hir_id)? { 1,968 ( 0.00%) Node::Item(item) => match item.kind { . ItemKind::Static(..) => DefKind::Static, . ItemKind::Const(..) => DefKind::Const, . ItemKind::Fn(..) => DefKind::Fn, . ItemKind::Macro(..) => DefKind::Macro(MacroKind::Bang), . ItemKind::Mod(..) => DefKind::Mod, . ItemKind::OpaqueTy(..) => DefKind::OpaqueTy, . ItemKind::TyAlias(..) => DefKind::TyAlias, . ItemKind::Enum(..) => DefKind::Enum, -- line 239 ---------------------------------------- -- line 247 ---------------------------------------- . ItemKind::GlobalAsm(..) => DefKind::GlobalAsm, . ItemKind::Impl { .. } => DefKind::Impl, . }, . Node::ForeignItem(item) => match item.kind { . ForeignItemKind::Fn(..) => DefKind::Fn, . ForeignItemKind::Static(..) => DefKind::Static, . ForeignItemKind::Type => DefKind::ForeignTy, . }, 2 ( 0.00%) Node::TraitItem(item) => match item.kind { . TraitItemKind::Const(..) => DefKind::AssocConst, . TraitItemKind::Fn(..) => DefKind::AssocFn, . TraitItemKind::Type(..) => DefKind::AssocTy, . }, 197 ( 0.00%) Node::ImplItem(item) => match item.kind { . ImplItemKind::Const(..) => DefKind::AssocConst, . ImplItemKind::Fn(..) => DefKind::AssocFn, . ImplItemKind::TyAlias(..) => DefKind::AssocTy, . }, . Node::Variant(_) => DefKind::Variant, . Node::Ctor(variant_data) => { . // FIXME(eddyb) is this even possible, if we have a `Node::Ctor`? 80 ( 0.00%) assert_ne!(variant_data.ctor_hir_id(), None); . 112 ( 0.00%) let ctor_of = match self.find(self.get_parent_node(hir_id)) { . Some(Node::Item(..)) => def::CtorOf::Struct, . Some(Node::Variant(..)) => def::CtorOf::Variant, . _ => unreachable!(), . }; 32 ( 0.00%) DefKind::Ctor(ctor_of, def::CtorKind::from_hir(variant_data)) 64 ( 0.00%) } . Node::AnonConst(_) => { . let inline = match self.find(self.get_parent_node(hir_id)) { . Some(Node::Expr(&Expr { . kind: ExprKind::ConstBlock(ref anon_const), .. . })) if anon_const.hir_id == hir_id => true, . _ => false, . }; . if inline { DefKind::InlineConst } else { DefKind::AnonConst } . } . Node::Field(_) => DefKind::Field, 85 ( 0.00%) Node::Expr(expr) => match expr.kind { . ExprKind::Closure(.., None) => DefKind::Closure, . ExprKind::Closure(.., Some(_)) => DefKind::Generator, . _ => bug!("def_kind: unsupported node: {}", self.node_to_string(hir_id)), . }, 540 ( 0.00%) Node::GenericParam(param) => match param.kind { . GenericParamKind::Lifetime { .. } => DefKind::LifetimeParam, . GenericParamKind::Type { .. } => DefKind::TyParam, . GenericParamKind::Const { .. } => DefKind::ConstParam, . }, . Node::Crate(_) => DefKind::Mod, . Node::Stmt(_) . | Node::PathSegment(_) . | Node::Ty(_) -- line 300 ---------------------------------------- -- line 304 ---------------------------------------- . | Node::Binding(_) . | Node::Local(_) . | Node::Param(_) . | Node::Arm(_) . | Node::Lifetime(_) . | Node::Visibility(_) . | Node::Block(_) => return None, . }; 3,952 ( 0.00%) Some(def_kind) 11,900 ( 0.00%) } . . pub fn def_kind(&self, local_def_id: LocalDefId) -> DefKind { . self.opt_def_kind(local_def_id) . .unwrap_or_else(|| bug!("def_kind: unsupported node: {:?}", local_def_id)) . } . 6,147,552 ( 0.09%) pub fn find_parent_node(&self, id: HirId) -> Option { 768,444 ( 0.01%) if id.local_id == ItemLocalId::from_u32(0) { . Some(self.tcx.hir_owner_parent(id.owner)) . } else { 1,529,768 ( 0.02%) let owner = self.tcx.hir_owner_nodes(id.owner)?; 764,884 ( 0.01%) let node = owner.nodes[id.local_id].as_ref()?; 2,294,652 ( 0.03%) let hir_id = HirId { owner: id.owner, local_id: node.parent }; . Some(hir_id) . } 6,147,552 ( 0.09%) } . 2,461 ( 0.00%) pub fn get_parent_node(&self, hir_id: HirId) -> HirId { 4,546,281 ( 0.06%) self.find_parent_node(hir_id).unwrap() 4,922 ( 0.00%) } . . /// Retrieves the `Node` corresponding to `id`, returning `None` if cannot be found. 375,072 ( 0.01%) pub fn find(&self, id: HirId) -> Option> { 46,884 ( 0.00%) if id.local_id == ItemLocalId::from_u32(0) { . let owner = self.tcx.hir_owner(id.owner)?; 33,649 ( 0.00%) Some(owner.node.into()) . } else { 25,946 ( 0.00%) let owner = self.tcx.hir_owner_nodes(id.owner)?; 12,973 ( 0.00%) let node = owner.nodes[id.local_id].as_ref()?; 38,919 ( 0.00%) Some(node.node) . } 375,072 ( 0.01%) } . . /// Retrieves the `Node` corresponding to `id`, returning `None` if cannot be found. . #[inline] . pub fn find_by_def_id(&self, id: LocalDefId) -> Option> { 9,647 ( 0.00%) self.find(self.local_def_id_to_hir_id(id)) . } . . /// Retrieves the `Node` corresponding to `id`, panicking if it cannot be found. 28,107 ( 0.00%) pub fn get(&self, id: HirId) -> Node<'hir> { 16,475 ( 0.00%) self.find(id).unwrap_or_else(|| bug!("couldn't find hir id {} in the HIR map", id)) 18,738 ( 0.00%) } . . /// Retrieves the `Node` corresponding to `id`, panicking if it cannot be found. . #[inline] . pub fn get_by_def_id(&self, id: LocalDefId) -> Node<'hir> { . self.find_by_def_id(id).unwrap_or_else(|| bug!("couldn't find {:?} in the HIR map", id)) . } . 782 ( 0.00%) pub fn get_if_local(&self, id: DefId) -> Option> { 391 ( 0.00%) id.as_local().and_then(|id| self.find(self.local_def_id_to_hir_id(id))) 782 ( 0.00%) } . . pub fn get_generics(&self, id: LocalDefId) -> Option<&'hir Generics<'hir>> { . let node = self.tcx.hir_owner(id)?; . match node.node { . OwnerNode::ImplItem(impl_item) => Some(&impl_item.generics), . OwnerNode::TraitItem(trait_item) => Some(&trait_item.generics), . OwnerNode::Item(Item { . kind: -- line 374 ---------------------------------------- -- line 381 ---------------------------------------- . | ItemKind::TraitAlias(generics, _) . | ItemKind::Impl(Impl { generics, .. }), . .. . }) => Some(generics), . _ => None, . } . } . 94,773 ( 0.00%) pub fn item(&self, id: ItemId) -> &'hir Item<'hir> { 27,078 ( 0.00%) self.tcx.hir_owner(id.def_id).unwrap().node.expect_item() 108,312 ( 0.00%) } . 182 ( 0.00%) pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> { 52 ( 0.00%) self.tcx.hir_owner(id.def_id).unwrap().node.expect_trait_item() 208 ( 0.00%) } . 39,403 ( 0.00%) pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> { 11,258 ( 0.00%) self.tcx.hir_owner(id.def_id).unwrap().node.expect_impl_item() 45,032 ( 0.00%) } . . pub fn foreign_item(&self, id: ForeignItemId) -> &'hir ForeignItem<'hir> { . self.tcx.hir_owner(id.def_id).unwrap().node.expect_foreign_item() . } . 92,974 ( 0.00%) pub fn body(&self, id: BodyId) -> &'hir Body<'hir> { 26,564 ( 0.00%) self.tcx.hir_owner_nodes(id.hir_id.owner).unwrap().bodies[&id.hir_id.local_id] 106,256 ( 0.00%) } . 2,250 ( 0.00%) pub fn fn_decl_by_hir_id(&self, hir_id: HirId) -> Option<&'hir FnDecl<'hir>> { 2,250 ( 0.00%) if let Some(node) = self.find(hir_id) { . fn_decl(node) . } else { . bug!("no node for hir_id `{}`", hir_id) . } 1,500 ( 0.00%) } . 279 ( 0.00%) pub fn fn_sig_by_hir_id(&self, hir_id: HirId) -> Option<&'hir FnSig<'hir>> { 279 ( 0.00%) if let Some(node) = self.find(hir_id) { . fn_sig(node) . } else { . bug!("no node for hir_id `{}`", hir_id) . } 279 ( 0.00%) } . . pub fn enclosing_body_owner(&self, hir_id: HirId) -> HirId { . for (parent, _) in self.parent_iter(hir_id) { . if let Some(body) = self.maybe_body_owned_by(parent) { . return self.body_owner(body); . } . } . . bug!("no `enclosing_body_owner` for hir_id `{}`", hir_id); . } . . /// Returns the `HirId` that corresponds to the definition of . /// which this is the body of, i.e., a `fn`, `const` or `static` . /// item (possibly associated), a closure, or a `hir::AnonConst`. 64,640 ( 0.00%) pub fn body_owner(&self, BodyId { hir_id }: BodyId) -> HirId { . let parent = self.get_parent_node(hir_id); 48,480 ( 0.00%) assert!(self.find(parent).map_or(false, |n| is_body_owner(n, hir_id))); . parent 64,640 ( 0.00%) } . 20,060 ( 0.00%) pub fn body_owner_def_id(&self, id: BodyId) -> LocalDefId { 32,260 ( 0.00%) self.local_def_id(self.body_owner(id)) 20,060 ( 0.00%) } . . /// Given a `HirId`, returns the `BodyId` associated with it, . /// if the node is a body owner, otherwise returns `None`. 2,680 ( 0.00%) pub fn maybe_body_owned_by(&self, hir_id: HirId) -> Option { 8,842 ( 0.00%) self.find(hir_id).map(associated_body).flatten() 8,040 ( 0.00%) } . . /// Given a body owner's id, returns the `BodyId` associated with it. 7,218 ( 0.00%) pub fn body_owned_by(&self, id: HirId) -> BodyId { . self.maybe_body_owned_by(id).unwrap_or_else(|| { . span_bug!( . self.span(id), . "body_owned_by: {} has no associated body", . self.node_to_string(id) . ); . }) 5,614 ( 0.00%) } . 291 ( 0.00%) pub fn body_param_names(&self, id: BodyId) -> impl Iterator + 'hir { 2,565 ( 0.00%) self.body(id).params.iter().map(|arg| match arg.pat.kind { 846 ( 0.00%) PatKind::Binding(_, _, ident, _) => ident, . _ => Ident::empty(), . }) 873 ( 0.00%) } . . /// Returns the `BodyOwnerKind` of this `LocalDefId`. . /// . /// Panics if `LocalDefId` does not have an associated body. 14,388 ( 0.00%) pub fn body_owner_kind(&self, id: HirId) -> BodyOwnerKind { 40,204 ( 0.00%) match self.get(id) { . Node::Item(&Item { kind: ItemKind::Const(..), .. }) . | Node::TraitItem(&TraitItem { kind: TraitItemKind::Const(..), .. }) . | Node::ImplItem(&ImplItem { kind: ImplItemKind::Const(..), .. }) . | Node::AnonConst(_) => BodyOwnerKind::Const, . Node::Ctor(..) . | Node::Item(&Item { kind: ItemKind::Fn(..), .. }) . | Node::TraitItem(&TraitItem { kind: TraitItemKind::Fn(..), .. }) . | Node::ImplItem(&ImplItem { kind: ImplItemKind::Fn(..), .. }) => BodyOwnerKind::Fn, . Node::Item(&Item { kind: ItemKind::Static(_, m, _), .. }) => BodyOwnerKind::Static(m), . Node::Expr(&Expr { kind: ExprKind::Closure(..), .. }) => BodyOwnerKind::Closure, . node => bug!("{:#?} is not a body node", node), . } 14,388 ( 0.00%) } . . /// Returns the `ConstContext` of the body associated with this `LocalDefId`. . /// . /// Panics if `LocalDefId` does not have an associated body. . /// . /// This should only be used for determining the context of a body, a return . /// value of `Some` does not always suggest that the owner of the body is `const`, . /// just that it has to be checked as if it were. 19,248 ( 0.00%) pub fn body_const_context(&self, did: LocalDefId) -> Option { . let hir_id = self.local_def_id_to_hir_id(did); 28,872 ( 0.00%) let ccx = match self.body_owner_kind(hir_id) { . BodyOwnerKind::Const => ConstContext::Const, . BodyOwnerKind::Static(mt) => ConstContext::Static(mt), . 1,746 ( 0.00%) BodyOwnerKind::Fn if self.tcx.is_constructor(did.to_def_id()) => return None, 1,746 ( 0.00%) BodyOwnerKind::Fn if self.tcx.is_const_fn_raw(did.to_def_id()) => ConstContext::ConstFn, . BodyOwnerKind::Fn 3,492 ( 0.00%) if self.tcx.has_attr(did.to_def_id(), sym::default_method_body_is_const) => . { . ConstContext::ConstFn . } . BodyOwnerKind::Fn | BodyOwnerKind::Closure => return None, . }; . . Some(ccx) 21,654 ( 0.00%) } . . /// Returns an iterator of the `DefId`s for all body-owners in this . /// crate. If you would prefer to iterate over the bodies . /// themselves, you can do `self.hir().krate().body_ids.iter()`. 21 ( 0.00%) pub fn body_owners(self) -> impl Iterator + 'hir { 3 ( 0.00%) self.krate() . .owners . .iter_enumerated() . .flat_map(move |(owner, owner_info)| { 3,570 ( 0.00%) let bodies = &owner_info.as_ref()?.nodes.bodies; . Some(bodies.iter().map(move |&(local_id, _)| { 17 ( 0.00%) let hir_id = HirId { owner, local_id }; . let body_id = BodyId { hir_id }; 3,959 ( 0.00%) self.body_owner_def_id(body_id) . })) . }) . .flatten() 15 ( 0.00%) } . 10 ( 0.00%) pub fn par_body_owners(self, f: F) { . use rustc_data_structures::sync::{par_iter, ParallelIterator}; . #[cfg(parallel_compiler)] . use rustc_rayon::iter::IndexedParallelIterator; . 3 ( 0.00%) par_iter(&self.krate().owners.raw).enumerate().for_each(|(owner, owner_info)| { . let owner = LocalDefId::new(owner); 7,140 ( 0.00%) if let Some(owner_info) = owner_info { . par_iter(owner_info.nodes.bodies.range(..)).for_each(|(local_id, _)| { . let hir_id = HirId { owner, local_id: *local_id }; . let body_id = BodyId { hir_id }; 3,609 ( 0.00%) f(self.body_owner_def_id(body_id)) . }) . } . }); 8 ( 0.00%) } . . pub fn ty_param_owner(&self, id: HirId) -> LocalDefId { . match self.get(id) { . Node::Item(&Item { kind: ItemKind::Trait(..) | ItemKind::TraitAlias(..), .. }) => { . id.expect_owner() . } . Node::GenericParam(_) => self.get_parent_item(id), . _ => bug!("ty_param_owner: {} not a type parameter", self.node_to_string(id)), -- line 558 ---------------------------------------- -- line 564 ---------------------------------------- . Node::Item(&Item { kind: ItemKind::Trait(..) | ItemKind::TraitAlias(..), .. }) => { . kw::SelfUpper . } . Node::GenericParam(param) => param.name.ident().name, . _ => bug!("ty_param_name: {} not a type parameter", self.node_to_string(id)), . } . } . 747 ( 0.00%) pub fn trait_impls(&self, trait_did: DefId) -> &'hir [LocalDefId] { 83 ( 0.00%) self.tcx.all_local_trait_impls(()).get(&trait_did).map_or(&[], |xs| &xs[..]) 747 ( 0.00%) } . . /// Gets the attributes on the crate. This is preferable to . /// invoking `krate.attrs` because it registers a tighter . /// dep-graph access. . pub fn krate_attrs(&self) -> &'hir [ast::Attribute] { 26 ( 0.00%) self.attrs(CRATE_HIR_ID) . } . 455 ( 0.00%) pub fn get_module(&self, module: LocalDefId) -> (&'hir Mod<'hir>, Span, HirId) { . let hir_id = HirId::make_owner(module); 325 ( 0.00%) match self.tcx.hir_owner(module).map(|o| o.node) { 108 ( 0.00%) Some(OwnerNode::Item(&Item { span, kind: ItemKind::Mod(ref m), .. })) => { . (m, span, hir_id) . } 33 ( 0.00%) Some(OwnerNode::Crate(item)) => (item, item.inner, hir_id), . node => panic!("not a module: {:?}", node), . } 585 ( 0.00%) } . . /// Walks the contents of a crate. See also `Crate::visit_all_items`. 11 ( 0.00%) pub fn walk_toplevel_module(self, visitor: &mut impl Visitor<'hir>) { 30 ( 0.00%) let (top_mod, span, hir_id) = self.get_module(CRATE_DEF_ID); . visitor.visit_mod(top_mod, span, hir_id); 8 ( 0.00%) } . . /// Walks the attributes in a crate. 20 ( 0.00%) pub fn walk_attributes(self, visitor: &mut impl Visitor<'hir>) { 2 ( 0.00%) let krate = self.krate(); . for (owner, info) in krate.owners.iter_enumerated() { 4,760 ( 0.00%) if let Some(info) = info { . for (local_id, attrs) in info.attrs.map.iter() { . let id = HirId { owner, local_id: *local_id }; . for a in *attrs { 8,665 ( 0.00%) visitor.visit_attribute(id, a) . } . } . } . } 16 ( 0.00%) } . . /// Visits all items in the crate in some deterministic (but . /// unspecified) order. If you just need to process every item, . /// but don't care about nesting, this method is the best choice. . /// . /// If you do care about nesting -- usually because your algorithm . /// follows lexical scoping rules -- then you want a different . /// approach. You should override `visit_nested_item` in your . /// visitor and then call `intravisit::walk_crate` instead. 160 ( 0.00%) pub fn visit_all_item_likes(&self, visitor: &mut V) . where . V: itemlikevisit::ItemLikeVisitor<'hir>, . { 23 ( 0.00%) let krate = self.krate(); 83 ( 0.00%) for owner in krate.owners.iter().filter_map(Option::as_ref) { 24,876 ( 0.00%) match owner.node() { 27,060 ( 0.00%) OwnerNode::Item(item) => visitor.visit_item(item), . OwnerNode::ForeignItem(item) => visitor.visit_foreign_item(item), 591 ( 0.00%) OwnerNode::ImplItem(item) => visitor.visit_impl_item(item), . OwnerNode::TraitItem(item) => visitor.visit_trait_item(item), . OwnerNode::Crate(_) => {} . } . } 160 ( 0.00%) } . . /// A parallel version of `visit_all_item_likes`. . pub fn par_visit_all_item_likes(&self, visitor: &V) . where . V: itemlikevisit::ParItemLikeVisitor<'hir> + Sync + Send, . { 1 ( 0.00%) let krate = self.krate(); 2 ( 0.00%) par_for_each_in(&krate.owners.raw, |owner| match owner.as_ref().map(OwnerInfo::node) { 492 ( 0.00%) Some(OwnerNode::Item(item)) => visitor.visit_item(item), . Some(OwnerNode::ForeignItem(item)) => visitor.visit_foreign_item(item), 197 ( 0.00%) Some(OwnerNode::ImplItem(item)) => visitor.visit_impl_item(item), 1 ( 0.00%) Some(OwnerNode::TraitItem(item)) => visitor.visit_trait_item(item), . Some(OwnerNode::Crate(_)) | None => {} . }) . } . 1,634 ( 0.00%) pub fn visit_item_likes_in_module(&self, module: LocalDefId, visitor: &mut V) . where . V: ItemLikeVisitor<'hir>, . { 209 ( 0.00%) let module = self.tcx.hir_module_items(module); . 228 ( 0.00%) for id in module.items.iter() { 22,140 ( 0.00%) visitor.visit_item(self.item(*id)); . } . 228 ( 0.00%) for id in module.trait_items.iter() { 40 ( 0.00%) visitor.visit_trait_item(self.trait_item(*id)); . } . 228 ( 0.00%) for id in module.impl_items.iter() { 7,683 ( 0.00%) visitor.visit_impl_item(self.impl_item(*id)); . } . 228 ( 0.00%) for id in module.foreign_items.iter() { . visitor.visit_foreign_item(self.foreign_item(*id)); . } 1,672 ( 0.00%) } . 46 ( 0.00%) pub fn for_each_module(&self, f: impl Fn(LocalDefId)) { . let mut queue = VecDeque::new(); . queue.push_back(CRATE_DEF_ID); . 152 ( 0.00%) while let Some(id) = queue.pop_front() { . f(id); 57 ( 0.00%) let items = self.tcx.hir_module_items(id); 608 ( 0.00%) queue.extend(items.submodules.iter().copied()) . } 40 ( 0.00%) } . . #[cfg(not(parallel_compiler))] . #[inline] . pub fn par_for_each_module(&self, f: impl Fn(LocalDefId)) { 4 ( 0.00%) self.for_each_module(f) . } . . #[cfg(parallel_compiler)] . pub fn par_for_each_module(&self, f: impl Fn(LocalDefId) + Sync) { . use rustc_data_structures::sync::{par_iter, ParallelIterator}; . par_iter_submodules(self.tcx, CRATE_DEF_ID, &f); . . fn par_iter_submodules(tcx: TyCtxt<'_>, module: LocalDefId, f: &F) -- line 699 ---------------------------------------- -- line 703 ---------------------------------------- . (*f)(module); . let items = tcx.hir_module_items(module); . par_iter(&items.submodules[..]).for_each(|&sm| par_iter_submodules(tcx, sm, f)); . } . } . . /// Returns an iterator for the nodes in the ancestor tree of the `current_id` . /// until the crate root is reached. Prefer this over your own loop using `get_parent_node`. 554 ( 0.00%) pub fn parent_iter(self, current_id: HirId) -> ParentHirIterator<'hir> { . ParentHirIterator { current_id, map: self } 2,224 ( 0.00%) } . . /// Returns an iterator for the nodes in the ancestor tree of the `current_id` . /// until the crate root is reached. Prefer this over your own loop using `get_parent_node`. . pub fn parent_owner_iter(self, current_id: HirId) -> ParentOwnerIterator<'hir> { . ParentOwnerIterator { current_id, map: self } 12,554 ( 0.00%) } . . /// Checks if the node is left-hand side of an assignment. . pub fn is_lhs(&self, id: HirId) -> bool { . match self.find(self.get_parent_node(id)) { . Some(Node::Expr(expr)) => match expr.kind { . ExprKind::Assign(lhs, _rhs, _span) => lhs.hir_id == id, . _ => false, . }, -- line 727 ---------------------------------------- -- line 752 ---------------------------------------- . /// ``` . /// fn foo(x: usize) -> bool { . /// loop { . /// true // If `get_return_block` gets passed the `id` corresponding . /// } // to this, it will return `None`. . /// false . /// } . /// ``` 18 ( 0.00%) pub fn get_return_block(&self, id: HirId) -> Option { 2 ( 0.00%) let mut iter = self.parent_iter(id).peekable(); . let mut ignore_tail = false; 8 ( 0.00%) if let Some(node) = self.find(id) { 8 ( 0.00%) if let Node::Expr(Expr { kind: ExprKind::Ret(_), .. }) = node { . // When dealing with `return` statements, we don't care about climbing only tail . // expressions. . ignore_tail = true; . } . } 28 ( 0.00%) while let Some((hir_id, node)) = iter.next() { 112 ( 0.00%) if let (Some((_, next_node)), false) = (iter.peek(), ignore_tail) { . match next_node { . Node::Block(Block { expr: None, .. }) => return None, . // The current node is not the tail expression of its parent. . Node::Block(Block { expr: Some(e), .. }) if hir_id != e.hir_id => return None, . _ => {} . } . } 120 ( 0.00%) match node { . Node::Item(_) . | Node::ForeignItem(_) . | Node::TraitItem(_) . | Node::Expr(Expr { kind: ExprKind::Closure(..), .. }) . | Node::ImplItem(_) => return Some(hir_id), . // Ignore `return`s on the first iteration . Node::Expr(Expr { kind: ExprKind::Loop(..) | ExprKind::Ret(..), .. }) . | Node::Local(_) => { . return None; . } . _ => {} . } . } . None 20 ( 0.00%) } . . /// Retrieves the `HirId` for `id`'s parent item, or `id` itself if no . /// parent item is in this map. The "parent item" is the closest parent node . /// in the HIR which is recorded by the map and is an item, either an item . /// in a module, trait, or impl. 3,594 ( 0.00%) pub fn get_parent_item(&self, hir_id: HirId) -> LocalDefId { 32,346 ( 0.00%) if let Some((def_id, _node)) = self.parent_owner_iter(hir_id).next() { . def_id . } else { . CRATE_DEF_ID . } 7,188 ( 0.00%) } . . /// Returns the `HirId` of `id`'s nearest module parent, or `id` itself if no . /// module parent is in this map. . pub(super) fn get_module_parent_node(&self, hir_id: HirId) -> LocalDefId { 4,714 ( 0.00%) for (def_id, node) in self.parent_owner_iter(hir_id) { 2,538 ( 0.00%) if let OwnerNode::Item(&Item { kind: ItemKind::Mod(_), .. }) = node { . return def_id; . } . } . CRATE_DEF_ID . } . . /// When on an if expression, a match arm tail expression or a match arm, give back . /// the enclosing `if` or `match` expression. -- line 820 ---------------------------------------- -- line 885 ---------------------------------------- . } . } . bug!( . "expected foreign mod or inlined parent, found {}", . self.node_to_string(HirId::make_owner(parent)) . ) . } . 15,652 ( 0.00%) pub fn expect_item(&self, id: LocalDefId) -> &'hir Item<'hir> { 6,708 ( 0.00%) match self.tcx.hir_owner(id) { . Some(Owner { node: OwnerNode::Item(item), .. }) => item, . _ => bug!("expected item, found {}", self.node_to_string(HirId::make_owner(id))), . } 17,888 ( 0.00%) } . 2,758 ( 0.00%) pub fn expect_impl_item(&self, id: LocalDefId) -> &'hir ImplItem<'hir> { 1,182 ( 0.00%) match self.tcx.hir_owner(id) { . Some(Owner { node: OwnerNode::ImplItem(item), .. }) => item, . _ => bug!("expected impl item, found {}", self.node_to_string(HirId::make_owner(id))), . } 3,152 ( 0.00%) } . 14 ( 0.00%) pub fn expect_trait_item(&self, id: LocalDefId) -> &'hir TraitItem<'hir> { 6 ( 0.00%) match self.tcx.hir_owner(id) { . Some(Owner { node: OwnerNode::TraitItem(item), .. }) => item, . _ => bug!("expected trait item, found {}", self.node_to_string(HirId::make_owner(id))), . } 16 ( 0.00%) } . . pub fn expect_variant(&self, id: HirId) -> &'hir Variant<'hir> { . match self.find(id) { . Some(Node::Variant(variant)) => variant, . _ => bug!("expected variant, found {}", self.node_to_string(id)), . } . } . -- line 920 ---------------------------------------- -- line 929 ---------------------------------------- . . pub fn expect_expr(&self, id: HirId) -> &'hir Expr<'hir> { . match self.find(id) { . Some(Node::Expr(expr)) => expr, . _ => bug!("expected expr, found {}", self.node_to_string(id)), . } . } . 8,694 ( 0.00%) pub fn opt_name(&self, id: HirId) -> Option { 2,934 ( 0.00%) Some(match self.get(id) { . Node::Item(i) => i.ident.name, . Node::ForeignItem(fi) => fi.ident.name, . Node::ImplItem(ii) => ii.ident.name, . Node::TraitItem(ti) => ti.ident.name, . Node::Variant(v) => v.ident.name, . Node::Field(f) => f.ident.name, . Node::Lifetime(lt) => lt.name.ident().name, 2,844 ( 0.00%) Node::GenericParam(param) => param.name.ident().name, 36 ( 0.00%) Node::Binding(&Pat { kind: PatKind::Binding(_, _, l, _), .. }) => l.name, . Node::Ctor(..) => self.name(HirId::make_owner(self.get_parent_item(id))), . _ => return None, . }) 4,830 ( 0.00%) } . 7,656 ( 0.00%) pub fn name(&self, id: HirId) -> Symbol { 2,916 ( 0.00%) match self.opt_name(id) { . Some(name) => name, . None => bug!("no name for {}", self.node_to_string(id)), . } 5,742 ( 0.00%) } . . /// Given a node ID, gets a list of attributes associated with the AST . /// corresponding to the node-ID. 9,517,480 ( 0.14%) pub fn attrs(&self, id: HirId) -> &'hir [ast::Attribute] { 1,359,640 ( 0.02%) self.tcx.hir_attrs(id.owner).get(id.local_id) 10,877,120 ( 0.15%) } . . /// Gets the span of the definition of the specified HIR node. . /// This is used by `tcx.get_span` 4,134 ( 0.00%) pub fn span(&self, hir_id: HirId) -> Span { 26,694 ( 0.00%) self.opt_span(hir_id) . .unwrap_or_else(|| bug!("hir::map::Map::span: id not in map: {:?}", hir_id)) 4,134 ( 0.00%) } . 61,012 ( 0.00%) pub fn opt_span(&self, hir_id: HirId) -> Option { 61,012 ( 0.00%) let span = match self.find(hir_id)? { . Node::Param(param) => param.span, 2,150 ( 0.00%) Node::Item(item) => match &item.kind { . ItemKind::Fn(sig, _, _) => sig.span, 1,350 ( 0.00%) _ => item.span, . }, . Node::ForeignItem(foreign_item) => foreign_item.span, 2 ( 0.00%) Node::TraitItem(trait_item) => match &trait_item.kind { 2 ( 0.00%) TraitItemKind::Fn(sig, _) => sig.span, . _ => trait_item.span, . }, 1,540 ( 0.00%) Node::ImplItem(impl_item) => match &impl_item.kind { 1,528 ( 0.00%) ImplItemKind::Fn(sig, _) => sig.span, 12 ( 0.00%) _ => impl_item.span, . }, 44 ( 0.00%) Node::Variant(variant) => variant.span, 124 ( 0.00%) Node::Field(field) => field.span, . Node::AnonConst(constant) => self.body(constant.body).value.span, . Node::Expr(expr) => expr.span, . Node::Stmt(stmt) => stmt.span, . Node::PathSegment(seg) => seg.ident.span, . Node::Ty(ty) => ty.span, . Node::TraitRef(tr) => tr.path.span, . Node::Binding(pat) => pat.span, . Node::Pat(pat) => pat.span, . Node::Arm(arm) => arm.span, . Node::Block(block) => block.span, 196 ( 0.00%) Node::Ctor(..) => match self.find(self.get_parent_node(hir_id))? { . Node::Item(item) => item.span, . Node::Variant(variant) => variant.span, . _ => unreachable!(), . }, . Node::Lifetime(lifetime) => lifetime.span, . Node::GenericParam(param) => param.span, . Node::Visibility(&Spanned { . node: VisibilityKind::Restricted { ref path, .. }, . .. . }) => path.span, . Node::Infer(i) => i.span, . Node::Visibility(v) => bug!("unexpected Visibility {:?}", v), . Node::Local(local) => local.span, 4 ( 0.00%) Node::Crate(item) => item.inner, . }; . Some(span) 87,160 ( 0.00%) } . . /// Like `hir.span()`, but includes the body of function items . /// (instead of just the function header) . pub fn span_with_body(&self, hir_id: HirId) -> Span { . match self.find(hir_id) { . Some(Node::TraitItem(item)) => item.span, . Some(Node::ImplItem(impl_item)) => impl_item.span, . Some(Node::Item(item)) => item.span, . Some(_) => self.span(hir_id), . _ => bug!("hir::map::Map::span_with_body: id not in map: {:?}", hir_id), . } . } . 210 ( 0.00%) pub fn span_if_local(&self, id: DefId) -> Option { 1,988 ( 0.00%) id.as_local().and_then(|id| self.opt_span(self.local_def_id_to_hir_id(id))) 315 ( 0.00%) } . . pub fn res_span(&self, res: Res) -> Option { . match res { . Res::Err => None, . Res::Local(id) => Some(self.span(id)), . res => self.span_if_local(res.opt_def_id()?), . } . } -- line 1042 ---------------------------------------- -- line 1062 ---------------------------------------- . } . . impl<'hir> intravisit::Map<'hir> for Map<'hir> { . fn find(&self, hir_id: HirId) -> Option> { . self.find(hir_id) . } . . fn body(&self, id: BodyId) -> &'hir Body<'hir> { 7,956 ( 0.00%) self.body(id) . } . . fn item(&self, id: ItemId) -> &'hir Item<'hir> { 6,394 ( 0.00%) self.item(id) . } . . fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> { 14 ( 0.00%) self.trait_item(id) . } . . fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> { 2,758 ( 0.00%) self.impl_item(id) . } . . fn foreign_item(&self, id: ForeignItemId) -> &'hir ForeignItem<'hir> { . self.foreign_item(id) . } . } . 7 ( 0.00%) pub(super) fn crate_hash(tcx: TyCtxt<'_>, crate_num: CrateNum) -> Svh { . debug_assert_eq!(crate_num, LOCAL_CRATE); . let krate = tcx.hir_crate(()); 3 ( 0.00%) let hir_body_hash = krate.hir_hash; . . let upstream_crates = upstream_crates(tcx); . . // We hash the final, remapped names of all local source files so we . // don't have to include the path prefix remapping commandline args. . // If we included the full mapping in the SVH, we could only have . // reproducible builds by compiling from the same directory. So we just . // hash the result of the mapping instead of the mapping itself. 2 ( 0.00%) let mut source_file_names: Vec<_> = tcx . .sess . .source_map() . .files() . .iter() . .filter(|source_file| source_file.cnum == LOCAL_CRATE) 56 ( 0.00%) .map(|source_file| source_file.name_hash) . .collect(); . . source_file_names.sort_unstable(); . . let mut hcx = tcx.create_stable_hashing_context(); . let mut stable_hasher = StableHasher::new(); . hir_body_hash.hash_stable(&mut hcx, &mut stable_hasher); . upstream_crates.hash_stable(&mut hcx, &mut stable_hasher); . source_file_names.hash_stable(&mut hcx, &mut stable_hasher); 3 ( 0.00%) if tcx.sess.opts.debugging_opts.incremental_relative_spans { . let definitions = &tcx.untracked_resolutions.definitions; . let mut owner_spans: Vec<_> = krate . .owners . .iter_enumerated() . .filter_map(|(def_id, info)| { . let _ = info.as_ref()?; . let def_path_hash = definitions.def_path_hash(def_id); . let span = definitions.def_span(def_id); . debug_assert_eq!(span.parent(), None); . Some((def_path_hash, span)) . }) . .collect(); . owner_spans.sort_unstable_by_key(|bn| bn.0); . owner_spans.hash_stable(&mut hcx, &mut stable_hasher); . } 3 ( 0.00%) tcx.sess.opts.dep_tracking_hash(true).hash_stable(&mut hcx, &mut stable_hasher); 2 ( 0.00%) tcx.sess.local_stable_crate_id().hash_stable(&mut hcx, &mut stable_hasher); . . let crate_hash: Fingerprint = stable_hasher.finish(); 1 ( 0.00%) Svh::new(crate_hash.to_smaller_hash()) 9 ( 0.00%) } . . fn upstream_crates(tcx: TyCtxt<'_>) -> Vec<(StableCrateId, Svh)> { . let mut upstream_crates: Vec<_> = tcx . .crates(()) . .iter() . .map(|&cnum| { 100 ( 0.00%) let stable_crate_id = tcx.resolutions(()).cstore.stable_crate_id(cnum); 20 ( 0.00%) let hash = tcx.crate_hash(cnum); . (stable_crate_id, hash) . }) . .collect(); . upstream_crates.sort_unstable_by_key(|&(stable_crate_id, _)| stable_crate_id); . upstream_crates . } . . fn hir_id_to_string(map: &Map<'_>, id: HirId) -> String { -- line 1155 ---------------------------------------- -- line 1238 ---------------------------------------- . Some(Node::Lifetime(_)) => node_str("lifetime"), . Some(Node::GenericParam(ref param)) => format!("generic_param {:?}{}", param, id_str), . Some(Node::Visibility(ref vis)) => format!("visibility {:?}{}", vis, id_str), . Some(Node::Crate(..)) => String::from("root_crate"), . None => format!("unknown node{}", id_str), . } . } . 171 ( 0.00%) pub(super) fn hir_module_items(tcx: TyCtxt<'_>, module_id: LocalDefId) -> ModuleItems { 114 ( 0.00%) let mut collector = ModuleCollector { . tcx, . submodules: Vec::default(), . items: Vec::default(), . trait_items: Vec::default(), . impl_items: Vec::default(), . foreign_items: Vec::default(), . }; . 95 ( 0.00%) let (hir_mod, span, hir_id) = tcx.hir().get_module(module_id); . collector.visit_mod(hir_mod, span, hir_id); . 304 ( 0.00%) let ModuleCollector { submodules, items, trait_items, impl_items, foreign_items, .. } = . collector; 209 ( 0.00%) return ModuleItems { 76 ( 0.00%) submodules: submodules.into_boxed_slice(), 76 ( 0.00%) items: items.into_boxed_slice(), 76 ( 0.00%) trait_items: trait_items.into_boxed_slice(), 76 ( 0.00%) impl_items: impl_items.into_boxed_slice(), 76 ( 0.00%) foreign_items: foreign_items.into_boxed_slice(), . }; . . struct ModuleCollector<'tcx> { . tcx: TyCtxt<'tcx>, . submodules: Vec, . items: Vec, . trait_items: Vec, . impl_items: Vec, . foreign_items: Vec, . } . . impl<'hir> Visitor<'hir> for ModuleCollector<'hir> { . type NestedFilter = nested_filter::All; . . fn nested_visit_map(&mut self) -> Self::Map { 1,072 ( 0.00%) self.tcx.hir() . } . 2,460 ( 0.00%) fn visit_item(&mut self, item: &'hir Item<'hir>) { 1,476 ( 0.00%) self.items.push(item.item_id()); 984 ( 0.00%) if let ItemKind::Mod(..) = item.kind { . // If this declares another module, do not recurse inside it. 18 ( 0.00%) self.submodules.push(item.def_id); . } else { 2,844 ( 0.00%) intravisit::walk_item(self, item) . } 72 ( 0.00%) } . . fn visit_trait_item(&mut self, item: &'hir TraitItem<'hir>) { 3 ( 0.00%) self.trait_items.push(item.trait_item_id()); 3 ( 0.00%) intravisit::walk_trait_item(self, item) . } . . fn visit_impl_item(&mut self, item: &'hir ImplItem<'hir>) { 591 ( 0.00%) self.impl_items.push(item.impl_item_id()); 591 ( 0.00%) intravisit::walk_impl_item(self, item) . } . . fn visit_foreign_item(&mut self, item: &'hir ForeignItem<'hir>) { . self.foreign_items.push(item.foreign_item_id()); . intravisit::walk_foreign_item(self, item) . } . } 152 ( 0.00%) } 1,765,729 ( 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}; . 423,818 ( 0.01%) 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); . } . } . } . }; . } . 7,772 ( 0.00%) #[derive(Clone)] . pub struct Parser<'a> { 266 ( 0.00%) pub sess: &'a ParseSess, . /// The current token. 190 ( 0.00%) pub token: Token, . /// The spacing for the current token 128 ( 0.00%) pub token_spacing: Spacing, . /// The previous token. 285 ( 0.00%) pub prev_token: Token, 161 ( 0.00%) pub capture_cfg: bool, 355 ( 0.00%) restrictions: Restrictions, 256 ( 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, 256 ( 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. 256 ( 0.00%) unmatched_angle_bracket_count: u32, 384 ( 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. 128 ( 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` 128 ( 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, . } . 555 ( 0.00%) #[derive(Clone)] . struct CaptureState { 512 ( 0.00%) capturing: Capturing, 128 ( 0.00%) replace_ranges: Vec, . inner_attr_ranges: FxHashMap, . } . . impl<'a> Drop for Parser<'a> { . fn drop(&mut self) { 1,192 ( 0.00%) emit_unclosed_delims(&mut self.unclosed_delims, &self.sess); . } . } . 52,920 ( 0.00%) #[derive(Clone)] . struct TokenCursor { . frame: TokenCursorFrame, 12,295 ( 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. 3,824 ( 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, . } . 23,780 ( 0.00%) #[derive(Clone)] . struct TokenCursorFrame { 6,565 ( 0.00%) delim: token::DelimToken, . span: DelimSpan, . open_delim: bool, 13,130 ( 0.00%) tree_cursor: tokenstream::Cursor, . close_delim: bool, . } . . impl TokenCursorFrame { . fn new(span: DelimSpan, delim: DelimToken, tts: TokenStream) -> Self { 1,155 ( 0.00%) TokenCursorFrame { . delim, . span, . open_delim: false, 4,759 ( 0.00%) tree_cursor: tts.into_trees(), . close_delim: false, . } . } . } . . impl TokenCursor { 3,751,596 ( 0.05%) fn next(&mut self) -> (Token, Spacing) { . loop { 1,593,008 ( 0.02%) let (tree, spacing) = if !self.frame.open_delim { 4,297 ( 0.00%) self.frame.open_delim = true; 21,485 ( 0.00%) TokenTree::open_tt(self.frame.span, self.frame.delim).into() 3,741,173 ( 0.05%) } else if let Some(tree) = self.frame.tree_cursor.next_with_spacing() { . tree 17,306 ( 0.00%) } else if !self.frame.close_delim { 4,179 ( 0.00%) self.frame.close_delim = true; 20,895 ( 0.00%) TokenTree::close_tt(self.frame.span, self.frame.delim).into() 8,358 ( 0.00%) } else if let Some(frame) = self.stack.pop() { 54,327 ( 0.00%) self.frame = frame; . continue; . } else { 5,310 ( 0.00%) (TokenTree::Token(Token::new(token::Eof, DUMMY_SP)), Spacing::Alone) . }; . 633,860 ( 0.01%) match tree { . TokenTree::Token(token) => { 2,501,064 ( 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)); . } . } . } 2,501,064 ( 0.04%) } . 31,030 ( 0.00%) fn next_desugared(&mut self) -> (Token, Spacing) { 9,309 ( 0.00%) let (data, attr_style, sp) = match self.next() { . (Token { kind: token::DocComment(_, attr_style, data), span }, _) => { . (data, attr_style, span) . } 15,515 ( 0.00%) tok => return tok, . }; . . // Searches for the occurrences of `"#*` and returns the minimum number of `#`s . // required to wrap the text. . let mut num_of_hashes = 0; . let mut count = 0; . for ch in data.as_str().chars() { . count = match ch { -- line 298 ---------------------------------------- -- line 332 ---------------------------------------- . .iter() . .cloned() . .collect::() . }, . ), . )); . . self.next() 27,927 ( 0.00%) } . } . 13,420 ( 0.00%) #[derive(Debug, Clone, PartialEq)] . enum TokenType { 10,736 ( 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 { 69 ( 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> { 308 ( 0.00%) Some(match token.kind { 616 ( 0.00%) _ if token.is_special_ident() => "reserved identifier", 616 ( 0.00%) _ if token.is_used_keyword() => "keyword", 616 ( 0.00%) _ if token.is_unused_keyword() => "reserved keyword", . token::DocComment(..) => "doc comment", . _ => return None, . }) . } . 1,078 ( 0.00%) pub(super) fn token_descr(token: &Token) -> String { 308 ( 0.00%) let token_str = pprust::token_to_string(token); . match token_descr_opt(token) { . Some(prefix) => format!("{} `{}`", prefix, token_str), 1,078 ( 0.00%) _ => format!("`{}`", token_str), . } 770 ( 0.00%) } . . impl<'a> Parser<'a> { 3,234 ( 0.00%) pub fn new( . sess: &'a ParseSess, . tokens: TokenStream, . desugar_doc_comments: bool, . subparser_name: Option<&'static str>, . ) -> Self { 231 ( 0.00%) let mut start_frame = TokenCursorFrame::new(DelimSpan::dummy(), token::NoDelim, tokens); 462 ( 0.00%) start_frame.open_delim = true; . start_frame.close_delim = true; . 7,161 ( 0.00%) let mut parser = Parser { . sess, 231 ( 0.00%) token: Token::dummy(), . token_spacing: Spacing::Alone, 231 ( 0.00%) prev_token: Token::dummy(), . capture_cfg: false, . restrictions: Restrictions::empty(), . expected_tokens: Vec::new(), . token_cursor: TokenCursor { 1,386 ( 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. 462 ( 0.00%) parser.bump(); . . parser 2,079 ( 0.00%) } . . fn next_tok(&mut self, fallback_span: Span) -> (Token, Spacing) { . loop { 1,864,098 ( 0.03%) let (mut next, spacing) = if self.desugar_doc_comments { 12,412 ( 0.00%) self.token_cursor.next_desugared() . } else { 922,740 ( 0.01%) self.token_cursor.next() . }; 1,242,732 ( 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 310,683 ( 0.00%) self.token_cursor.break_last_token = false; 1,242,732 ( 0.02%) if next.span.is_dummy() { . // Tweak the location for better diagnostics, but keep syntactic context intact. 1,012 ( 0.00%) next.span = fallback_span.with_ctxt(next.span.ctxt()); . } 944,586 ( 0.01%) if matches!( 621,366 ( 0.01%) next.kind, . token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) . ) { . continue; . } 1,242,732 ( 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`. 1,263,537 ( 0.02%) pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> { 140,393 ( 0.00%) if self.expected_tokens.is_empty() { 2,016 ( 0.00%) if self.token == *t { 1,680 ( 0.00%) self.bump(); . Ok(false) . } else { . self.unexpected_try_recover(t) . } . } else { 1,680,684 ( 0.02%) self.expect_one_of(slice::from_ref(t), &[]) . } 2,105,895 ( 0.03%) } . . /// 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. 1,694,484 ( 0.02%) pub fn expect_one_of( . &mut self, . edible: &[TokenKind], . inedible: &[TokenKind], . ) -> PResult<'a, bool /* recovered */> { 282,414 ( 0.00%) if edible.contains(&self.token.kind) { 422,232 ( 0.01%) 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) . } 2,118,105 ( 0.03%) } . . // Public for rustfmt usage. . pub fn parse_ident(&mut self) -> PResult<'a, Ident> { 23,849 ( 0.00%) self.parse_ident_common(true) . } . . fn ident_or_err(&mut self) -> PResult<'a, (Ident, /* is_raw */ bool)> { 19,980 ( 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(), . }) . } . 46,060 ( 0.00%) fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> { 6,580 ( 0.00%) let (ident, is_raw) = self.ident_or_err()?; 39,480 ( 0.00%) if !is_raw && ident.is_reserved() { . let mut err = self.expected_ident_found(); . if recover { . err.emit(); . } else { . return Err(err); . } . } 26,320 ( 0.00%) self.bump(); . Ok(ident) 65,800 ( 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. 5,409,586 ( 0.08%) fn check(&mut self, tok: &TokenKind) -> bool { 2,323,504 ( 0.03%) let is_present = self.token == *tok; 1,551,220 ( 0.02%) if !is_present { 3,805,727 ( 0.05%) self.expected_tokens.push(TokenType::Token(tok.clone())); . } . is_present 5,409,586 ( 0.08%) } . . /// Consumes a token 'tok' if it exists. Returns whether the given token was present. 232 ( 0.00%) pub fn eat(&mut self, tok: &TokenKind) -> bool { 945,959 ( 0.01%) let is_present = self.check(tok); 630,005 ( 0.01%) if is_present { 17,744 ( 0.00%) self.bump() . } . is_present 290 ( 0.00%) } . . /// If the next token is the given keyword, returns `true` without eating it. . /// An expectation is also added for diagnostics purposes. 15,830 ( 0.00%) fn check_keyword(&mut self, kw: Symbol) -> bool { 5,146 ( 0.00%) self.expected_tokens.push(TokenType::Keyword(kw)); 125,327 ( 0.00%) self.token.is_keyword(kw) . } . . /// If the next token is the given keyword, eats it and returns `true`. . /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes. . // Public for rustfmt usage. 34,130 ( 0.00%) pub fn eat_keyword(&mut self, kw: Symbol) -> bool { 27,388 ( 0.00%) if self.check_keyword(kw) { 3,505 ( 0.00%) self.bump(); . true . } else { . false . } 34,130 ( 0.00%) } . . fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool { 5,342 ( 0.00%) if self.token.is_keyword(kw) { 1,127 ( 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. 420 ( 0.00%) fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> { . if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) } 336 ( 0.00%) } . . /// Is the given keyword `kw` followed by a non-reserved identifier? 23,664 ( 0.00%) fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool { 11,832 ( 0.00%) self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()) 26,622 ( 0.00%) } . 31,338 ( 0.00%) fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool { 11,908 ( 0.00%) if ok { . true . } else { 6,044 ( 0.00%) self.expected_tokens.push(typ); . false . } 31,338 ( 0.00%) } . . fn check_ident(&mut self) -> bool { 6,301 ( 0.00%) self.check_or_expected(self.token.is_ident(), TokenType::Ident) . } . 11,016 ( 0.00%) fn check_path(&mut self) -> bool { 24,460 ( 0.00%) self.check_or_expected(self.token.is_path_start(), TokenType::Path) 13,770 ( 0.00%) } . . fn check_type(&mut self) -> bool { 2,664 ( 0.00%) self.check_or_expected(self.token.can_begin_type(), TokenType::Type) . } . . fn check_const_arg(&mut self) -> bool { 2,424 ( 0.00%) self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const) . } . 6,228 ( 0.00%) fn check_inline_const(&self, dist: usize) -> bool { 3,460 ( 0.00%) self.is_keyword_ahead(dist, &[kw::Const]) . && self.look_ahead(dist + 1, |t| match t.kind { . token::Interpolated(ref nt) => matches!(**nt, token::NtBlock(..)), . token::OpenDelim(DelimToken::Brace) => true, . _ => false, . }) 6,228 ( 0.00%) } . . /// Checks to see if the next token is either `+` or `+=`. . /// Otherwise returns `false`. . fn check_plus(&mut self) -> bool { 3,704 ( 0.00%) self.check_or_expected( 1,852 ( 0.00%) self.token.is_like_plus(), 1,852 ( 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. 56,772 ( 0.00%) fn break_and_eat(&mut self, expected: TokenKind) -> bool { 33,117 ( 0.00%) if self.token.kind == expected { 3,398 ( 0.00%) self.bump(); . return true; . } 15,160 ( 0.00%) match self.token.kind.break_two_token_op() { 1,009 ( 0.00%) Some((first, second)) if first == expected => { 256 ( 0.00%) let first_span = self.sess.source_map().start_point(self.token.span); 320 ( 0.00%) let second_span = self.token.span.with_lo(first_span.hi()); 576 ( 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` 64 ( 0.00%) self.token_cursor.break_last_token = true; . // Use the spacing of the glued token as the spacing . // of the unglued second token. 896 ( 0.00%) self.bump_with((Token::new(second, second_span), self.token_spacing)); . true . } . _ => { 8,904 ( 0.00%) self.expected_tokens.push(TokenType::Token(expected)); . false . } . } 54,638 ( 0.00%) } . . /// Eats `+` possibly breaking tokens like `+=` in process. . fn eat_plus(&mut self) -> bool { 332 ( 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, ()> { 5,340 ( 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, ()> { 138 ( 0.00%) if self.break_and_eat(token::BinOp(token::Or)) { Ok(()) } else { self.unexpected() } . } . . /// Eats `<` possibly breaking tokens like `<<` in process. 2,398 ( 0.00%) fn eat_lt(&mut self) -> bool { 10,666 ( 0.00%) let ate = self.break_and_eat(token::Lt); 6,973 ( 0.00%) if ate { . // See doc comment for `unmatched_angle_bracket_count`. 1,684 ( 0.00%) self.unmatched_angle_bracket_count += 1; 1,779 ( 0.00%) self.max_angle_bracket_count += 1; . debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count); . } . ate 2,398 ( 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, ()> { 2,526 ( 0.00%) if self.break_and_eat(token::Gt) { . // See doc comment for `unmatched_angle_bracket_count`. 1,263 ( 0.00%) if self.unmatched_angle_bracket_count > 0 { 842 ( 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 { 836,574 ( 0.01%) TokenExpectType::Expect => self.check(k), 369 ( 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) { 698,517 ( 0.01%) if let token::CloseDelim(..) | token::Eof = self.token.kind { . break; . } 283,247 ( 0.00%) if let Some(ref t) = sep.sep { 421,367 ( 0.01%) if first { . first = false; . } else { 1,104,036 ( 0.02%) 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; . } . } . } . } . } . } 279,048 ( 0.00%) if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) { . trailing = true; . break; . } . 140,048 ( 0.00%) let t = f(self)?; 1,646 ( 0.00%) v.push(t); . } . 7,356 ( 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)> { 7,452 ( 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. 8,160 ( 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 */)> { 4,473 ( 0.00%) let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?; 2,791 ( 0.00%) if !recovered { . self.eat(ket); . } 10,098 ( 0.00%) Ok((val, trailing)) 6,528 ( 0.00%) } . . /// Parses a sequence, including the closing delimiter. The function . /// `f` must consume tokens until reaching the next separator or . /// closing bracket. . fn parse_unspanned_seq( . &mut self, . bra: &TokenKind, . ket: &TokenKind, . sep: SeqSep, . f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, . ) -> PResult<'a, (Vec, bool)> { 3,015 ( 0.00%) self.expect(bra)?; 6,528 ( 0.00%) self.parse_seq_to_end(ket, sep, f) . } . . fn parse_delim_comma_seq( . &mut self, . delim: DelimToken, . f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, . ) -> PResult<'a, (Vec, bool)> { . self.parse_unspanned_seq( 1,248 ( 0.00%) &token::OpenDelim(delim), 1,691 ( 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. 4,039,711 ( 0.06%) fn bump_with(&mut self, (next_token, next_spacing): (Token, Spacing)) { . // Bumping after EOF is a bad sign, usually an infinite loop. 1,864,482 ( 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. 1,242,988 ( 0.02%) self.prev_token = mem::replace(&mut self.token, next_token); 310,747 ( 0.00%) self.token_spacing = next_spacing; . . // Diagnostics. 310,747 ( 0.00%) self.expected_tokens.clear(); . } . . /// Advance the parser by one token. 2,485,464 ( 0.04%) pub fn bump(&mut self) { 1,242,732 ( 0.02%) let next_token = self.next_tok(self.token.span); 1,864,098 ( 0.03%) self.bump_with(next_token); 2,485,464 ( 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. 392 ( 0.00%) pub fn look_ahead(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R { 2,566 ( 0.00%) if dist == 0 { 1,016 ( 0.00%) return looker(&self.token); . } . 148,468 ( 0.00%) let frame = &self.token_cursor.frame; 149,761 ( 0.00%) if frame.delim != DelimToken::NoDelim { . let all_normal = (0..dist).all(|i| { 443,968 ( 0.01%) let token = frame.tree_cursor.look_ahead(i); 591,774 ( 0.01%) !matches!(token, Some(TokenTree::Delimited(_, DelimToken::NoDelim, _))) . }); . if all_normal { 739,687 ( 0.01%) return match frame.tree_cursor.look_ahead(dist - 1) { 293,539 ( 0.00%) Some(tree) => match tree { 146,402 ( 0.00%) TokenTree::Token(token) => looker(token), . TokenTree::Delimited(dspan, delim, _) => { 3,105 ( 0.00%) looker(&Token::new(token::OpenDelim(*delim), dspan.open)) . } . }, 8,126 ( 0.00%) None => looker(&Token::new(token::CloseDelim(frame.delim), frame.span.close)), . }; . } . } . . let mut cursor = self.token_cursor.clone(); . let mut i = 0; 1,912 ( 0.00%) let mut token = Token::dummy(); 2,450 ( 0.00%) while i < dist { 14,654 ( 0.00%) token = cursor.next().0; 6,332 ( 0.00%) if matches!( 3,900 ( 0.00%) token.kind, . token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) . ) { . continue; . } 1,225 ( 0.00%) i += 1; . } 227 ( 0.00%) return looker(&token); 441 ( 0.00%) } . . /// Returns whether any of the given keywords are `dist` tokens ahead of the current one. 10,323 ( 0.00%) fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool { 3,024 ( 0.00%) self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw))) 10,323 ( 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. 754 ( 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 . } 3,016 ( 0.00%) } . . /// Parses constness: `const` or nothing. 6,200 ( 0.00%) fn parse_constness(&mut self) -> Const { . // Avoid const blocks to be parsed as const items 1,926 ( 0.00%) if self.look_ahead(1, |t| t != &token::OpenDelim(DelimToken::Brace)) . && self.eat_keyword(kw::Const) . { 465 ( 0.00%) Const::Yes(self.prev_token.uninterpolated_span()) . } else { . Const::No . } 10,850 ( 0.00%) } . . /// Parses inline const expressions. . fn parse_const_block(&mut self, span: Span, pat: bool) -> PResult<'a, P> { . if pat { . self.sess.gated_spans.gate(sym::inline_const_pat, span); . } else { . self.sess.gated_spans.gate(sym::inline_const, span); . } -- line 1104 ---------------------------------------- -- line 1108 ---------------------------------------- . id: DUMMY_NODE_ID, . value: self.mk_expr(blk.span, ExprKind::Block(blk, None), AttrVec::new()), . }; . let blk_span = anon_const.value.span; . Ok(self.mk_expr(span.to(blk_span), ExprKind::ConstBlock(anon_const), AttrVec::new())) . } . . /// Parses mutability (`mut` or nothing). 16 ( 0.00%) fn parse_mutability(&mut self) -> Mutability { . if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not } 1,788 ( 0.00%) } . . /// Possibly parses mutability (`const` or `mut`). 36 ( 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 . } 36 ( 0.00%) } . . fn parse_field_name(&mut self) -> PResult<'a, Ident> { 1,254 ( 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 { 1,881 ( 0.00%) self.parse_ident_common(true) . } . } . . fn parse_mac_args(&mut self) -> PResult<'a, P> { 505 ( 0.00%) self.parse_mac_args_common(true).map(P) . } . . fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> { 540 ( 0.00%) self.parse_mac_args_common(false) . } . 3,582 ( 0.00%) fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> { 3,184 ( 0.00%) Ok( 2,574 ( 0.00%) if self.check(&token::OpenDelim(DelimToken::Paren)) 468 ( 0.00%) || self.check(&token::OpenDelim(DelimToken::Bracket)) 408 ( 0.00%) || self.check(&token::OpenDelim(DelimToken::Brace)) . { 1,096 ( 0.00%) match self.parse_token_tree() { 1,370 ( 0.00%) TokenTree::Delimited(dspan, delim, tokens) => . // We've confirmed above that there is a delimiter so unwrapping is OK. . { 548 ( 0.00%) MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens) . } . _ => unreachable!(), . } 248 ( 0.00%) } else if !delimited_only { . if self.eat(&token::Eq) { . let eq_span = self.prev_token.span; . . // Collect tokens because they are used during lowering to HIR. . let expr = self.parse_expr_force_collect()?; . let span = expr.span; . . let token_kind = token::Interpolated(Lrc::new(token::NtExpr(expr))); -- line 1172 ---------------------------------------- -- line 1173 ---------------------------------------- . MacArgs::Eq(eq_span, Token::new(token_kind, span)) . } else { . MacArgs::Empty . } . } else { . return self.unexpected(); . }, . ) 2,786 ( 0.00%) } . . fn parse_or_use_outer_attributes( . &mut self, . already_parsed_attrs: Option, . ) -> PResult<'a, AttrWrapper> { 424,588 ( 0.01%) if let Some(attrs) = already_parsed_attrs { . Ok(attrs) . } else { 282,300 ( 0.00%) self.parse_outer_attributes() . } . } . . /// Parses a single token tree from the input. 5,144 ( 0.00%) pub(crate) fn parse_token_tree(&mut self) -> TokenTree { 2,993 ( 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. 21,602 ( 0.00%) while !(depth == self.token_cursor.stack.len() . && matches!(self.token.kind, token::CloseDelim(_))) . { . // Advance one token at a time, so `TokenCursor::next()` . // can capture these tokens if necessary. 15,624 ( 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; 754 ( 0.00%) let stream = frame.tree_cursor.stream.clone(); 754 ( 0.00%) let span = frame.span; 377 ( 0.00%) let delim = frame.delim; . // Consume close delimiter 754 ( 0.00%) self.bump(); 1,885 ( 0.00%) TokenTree::Delimited(span, delim, stream) . } . token::CloseDelim(_) | token::Eof => unreachable!(), . _ => { 532 ( 0.00%) self.bump(); 1,330 ( 0.00%) TokenTree::Token(self.prev_token.clone()) . } . } 4,501 ( 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) . } . 8 ( 0.00%) pub fn parse_tokens(&mut self) -> TokenStream { . let mut result = Vec::new(); . loop { 12 ( 0.00%) match self.token.kind { . token::Eof | token::CloseDelim(..) => break, 3 ( 0.00%) _ => result.push(self.parse_token_tree().into()), . } . } 6 ( 0.00%) TokenStream::new(result) 8 ( 0.00%) } . . /// 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 { 141,358 ( 0.00%) let old = self.restrictions; 142,140 ( 0.00%) self.restrictions = res; . let res = f(self); 141,963 ( 0.00%) self.restrictions = old; . res . } . 11,672 ( 0.00%) fn is_crate_vis(&self) -> bool { 7,295 ( 0.00%) self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep) 13,131 ( 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. 9,180 ( 0.00%) pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> { 1,836 ( 0.00%) maybe_whole!(self, NtVis, |x| x); . 918 ( 0.00%) self.expected_tokens.push(TokenType::Keyword(kw::Crate)); 3,672 ( 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". 597 ( 0.00%) return Ok(Visibility { 1,791 ( 0.00%) span: self.token.span.shrink_to_lo(), . kind: VisibilityKind::Inherited, . tokens: None, . }); . } 321 ( 0.00%) let lo = self.prev_token.span; . 1,605 ( 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. 171 ( 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)`. 57 ( 0.00%) self.bump(); // `(` 38 ( 0.00%) self.bump(); // `crate` 57 ( 0.00%) self.expect(&token::CloseDelim(token::Paren))?; // `)` 19 ( 0.00%) let vis = VisibilityKind::Crate(CrateSugar::PubCrate); . return Ok(Visibility { 57 ( 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. . } . } . 906 ( 0.00%) Ok(Visibility { span: lo, kind: VisibilityKind::Public, tokens: None }) 8,262 ( 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 { 297 ( 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, . } . } . 140 ( 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, 14 ( 0.00%) |this, _attrs| Ok((f(this)?, TrailingToken::None)), . ) 140 ( 0.00%) } . . /// `::{` or `::*` 37,880 ( 0.00%) fn is_import_coupler(&mut self) -> bool { 18,940 ( 0.00%) self.check(&token::ModSep) . && self.look_ahead(1, |t| { 11,935 ( 0.00%) *t == token::OpenDelim(token::Brace) || *t == token::BinOp(token::Star) . }) 37,404 ( 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) . } . 2,872 ( 0.00%) pub fn emit_unclosed_delims(unclosed_delims: &mut Vec, sess: &ParseSess) { 1,436 ( 0.00%) *sess.reached_eof.borrow_mut() |= . unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none()); 1,436 ( 0.00%) for unmatched in unclosed_delims.drain(..) { . if let Some(mut e) = make_unclosed_delims_error(unmatched, sess) { . e.emit(); . } . } 2,872 ( 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 ---------------------------------------- 1,858,357 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/option.rs -------------------------------------------------------------------------------- Ir -- line 504 ---------------------------------------- . use crate::panicking::{panic, panic_str}; . use crate::pin::Pin; . use crate::{ . convert, hint, mem, . ops::{self, ControlFlow, Deref, DerefMut}, . }; . . /// The `Option` type. See [the module level documentation](self) for more. 3,793,193 ( 0.05%) #[derive(Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)] . #[rustc_diagnostic_item = "Option"] . #[stable(feature = "rust1", since = "1.0.0")] . pub enum Option { . /// No value. . #[lang = "None"] . #[stable(feature = "rust1", since = "1.0.0")] . None, . /// Some value of type `T`. . #[lang = "Some"] . #[stable(feature = "rust1", since = "1.0.0")] 1,877 ( 0.00%) Some(#[stable(feature = "rust1", since = "1.0.0")] T), . } . . ///////////////////////////////////////////////////////////////////////////// . // Type implementation . ///////////////////////////////////////////////////////////////////////////// . . impl Option { . ///////////////////////////////////////////////////////////////////////// -- line 531 ---------------------------------------- -- line 543 ---------------------------------------- . /// let x: Option = None; . /// assert_eq!(x.is_some(), false); . /// ``` . #[must_use = "if you intended to assert that this has a value, consider `.unwrap()` instead"] . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_option", since = "1.48.0")] . pub const fn is_some(&self) -> bool { 5,964,182 ( 0.08%) matches!(*self, Some(_)) . } . . /// Returns `true` if the option is a [`Some`] wrapping a value matching the predicate. . /// . /// # Examples . /// . /// ``` . /// #![feature(is_some_with)] -- line 559 ---------------------------------------- -- line 616 ---------------------------------------- . /// // then consume *that* with `map`, leaving `text` on the stack. . /// let text_length: Option = text.as_ref().map(|s| s.len()); . /// println!("still can print text: {:?}", text); . /// ``` . #[inline] . #[rustc_const_stable(feature = "const_option", since = "1.48.0")] . #[stable(feature = "rust1", since = "1.0.0")] . pub const fn as_ref(&self) -> Option<&T> { 7,487,998 ( 0.11%) match *self { . Some(ref x) => Some(x), . None => None, . } . } . . /// Converts from `&mut Option` to `Option<&mut T>`. . /// . /// # Examples -- line 632 ---------------------------------------- -- line 638 ---------------------------------------- . /// None => {}, . /// } . /// assert_eq!(x, Some(42)); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] . pub const fn as_mut(&mut self) -> Option<&mut T> { 1,843,414 ( 0.03%) match *self { . Some(ref mut x) => Some(x), . None => None, . } . } . . /// Converts from [Pin]<[&]Option\> to Option<[Pin]<[&]T>>. . /// . /// [&]: reference "shared reference" -- line 654 ---------------------------------------- -- line 705 ---------------------------------------- . /// let x: Option<&str> = None; . /// x.expect("fruits are healthy"); // panics with `fruits are healthy` . /// ``` . #[inline] . #[track_caller] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] . pub const fn expect(self, msg: &str) -> T { 2,350,355 ( 0.03%) match self { 389,838 ( 0.01%) Some(val) => val, . None => expect_failed(msg), . } . } . . /// Returns the contained [`Some`] value, consuming the `self` value. . /// . /// Because this function may panic, its use is generally discouraged. . /// Instead, prefer to use pattern matching and handle the [`None`] -- line 722 ---------------------------------------- -- line 742 ---------------------------------------- . /// let x: Option<&str> = None; . /// assert_eq!(x.unwrap(), "air"); // fails . /// ``` . #[inline] . #[track_caller] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] . pub const fn unwrap(self) -> T { 8,372,157 ( 0.12%) match self { 11,058,890 ( 0.16%) Some(val) => val, . None => panic("called `Option::unwrap()` on a `None` value"), . } . } . . /// Returns the contained [`Some`] value or a provided default. . /// . /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing . /// the result of a function call, it is recommended to use [`unwrap_or_else`], -- line 759 ---------------------------------------- -- line 769 ---------------------------------------- . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn unwrap_or(self, default: T) -> T . where . T: ~const Drop, . { 6,300,922 ( 0.09%) match self { . Some(x) => x, 1,756 ( 0.00%) None => default, . } 15,919 ( 0.00%) } . . /// Returns the contained [`Some`] value or computes it from a closure. . /// . /// # Examples . /// . /// ``` . /// let k = 10; . /// assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4); . /// assert_eq!(None.unwrap_or_else(|| 2 * k), 20); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] 220 ( 0.00%) pub const fn unwrap_or_else(self, f: F) -> T . where . F: ~const FnOnce() -> T, . F: ~const Drop, . { 3,510,156 ( 0.05%) match self { 77,319 ( 0.00%) Some(x) => x, 5,818 ( 0.00%) None => f(), . } 1,843 ( 0.00%) } . . /// Returns the contained [`Some`] value or a default. . /// . /// Consumes the `self` argument then, if [`Some`], returns the contained . /// value, otherwise if [`None`], returns the [default value] for that . /// type. . /// . /// # Examples -- line 812 ---------------------------------------- -- line 831 ---------------------------------------- . /// [`FromStr`]: crate::str::FromStr . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn unwrap_or_default(self) -> T . where . T: ~const Default, . { 3,632 ( 0.00%) match self { 3,901 ( 0.00%) Some(x) => x, . None => Default::default(), . } 155 ( 0.00%) } . . /// Returns the contained [`Some`] value, consuming the `self` value, . /// without checking that the value is not [`None`]. . /// . /// # Safety . /// . /// Calling this method on [`None`] is *[undefined behavior]*. . /// -- line 851 ---------------------------------------- -- line 892 ---------------------------------------- . /// // `Option::map` takes self *by value*, consuming `maybe_some_string` . /// let maybe_some_len = maybe_some_string.map(|s| s.len()); . /// . /// assert_eq!(maybe_some_len, Some(13)); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] 2,583 ( 0.00%) pub const fn map(self, f: F) -> Option . where . F: ~const FnOnce(T) -> U, . F: ~const Drop, . { 3,350,507 ( 0.05%) match self { 6,393,003 ( 0.09%) Some(x) => Some(f(x)), 93,843 ( 0.00%) None => None, . } 69,172 ( 0.00%) } . . /// Calls the provided closure with a reference to the contained value (if [`Some`]). . /// . /// # Examples . /// . /// ``` . /// #![feature(result_option_inspect)] . /// -- line 917 ---------------------------------------- -- line 960 ---------------------------------------- . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn map_or(self, default: U, f: F) -> U . where . F: ~const FnOnce(T) -> U, . F: ~const Drop, . U: ~const Drop, . { 1,233,553 ( 0.02%) match self { 29,399 ( 0.00%) Some(t) => f(t), 4,360 ( 0.00%) None => default, . } . } . . /// Computes a default function result (if none), or . /// applies a different function to the contained value (if any). . /// . /// # Examples . /// -- line 978 ---------------------------------------- -- line 990 ---------------------------------------- . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn map_or_else(self, default: D, f: F) -> U . where . D: ~const FnOnce() -> U, . D: ~const Drop, . F: ~const FnOnce(T) -> U, . F: ~const Drop, . { 30,430 ( 0.00%) match self { 11,330 ( 0.00%) Some(t) => f(t), . None => default(), . } . } . . /// Transforms the `Option` into a [`Result`], mapping [`Some(v)`] to . /// [`Ok(v)`] and [`None`] to [`Err(err)`]. . /// . /// Arguments passed to `ok_or` are eagerly evaluated; if you are passing the -- line 1007 ---------------------------------------- -- line 1024 ---------------------------------------- . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn ok_or(self, err: E) -> Result . where . E: ~const Drop, . { 416,344 ( 0.01%) match self { 1,332 ( 0.00%) Some(v) => Ok(v), 666 ( 0.00%) None => Err(err), . } . } . . /// Transforms the `Option` into a [`Result`], mapping [`Some(v)`] to . /// [`Ok(v)`] and [`None`] to [`Err(err())`]. . /// . /// [`Ok(v)`]: Ok . /// [`Err(err())`]: Err -- line 1042 ---------------------------------------- -- line 1049 ---------------------------------------- . /// assert_eq!(x.ok_or_else(|| 0), Ok("foo")); . /// . /// let x: Option<&str> = None; . /// assert_eq!(x.ok_or_else(|| 0), Err(0)); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] 8 ( 0.00%) pub const fn ok_or_else(self, err: F) -> Result . where . F: ~const FnOnce() -> E, . F: ~const Drop, . { 39,336 ( 0.00%) match self { 38,713 ( 0.00%) Some(v) => Ok(v), 12,944 ( 0.00%) None => Err(err()), . } 10 ( 0.00%) } . . /// Converts from `Option` (or `&Option`) to `Option<&T::Target>`. . /// . /// Leaves the original Option in-place, creating a new one with a reference . /// to the original one, additionally coercing the contents via [`Deref`]. . /// . /// # Examples . /// -- line 1074 ---------------------------------------- -- line 1080 ---------------------------------------- . /// assert_eq!(x.as_deref(), None); . /// ``` . #[stable(feature = "option_deref", since = "1.40.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn as_deref(&self) -> Option<&T::Target> . where . T: ~const Deref, . { 10,915 ( 0.00%) match self.as_ref() { . Some(t) => Some(t.deref()), . None => None, . } . } . . /// Converts from `Option` (or `&mut Option`) to `Option<&mut T::Target>`. . /// . /// Leaves the original `Option` in-place, creating a new one containing a mutable reference to -- line 1096 ---------------------------------------- -- line 1213 ---------------------------------------- . /// assert_eq!(Some(2).and_then(sq).and_then(sq), Some(16)); . /// assert_eq!(Some(2).and_then(sq).and_then(nope), None); . /// assert_eq!(Some(2).and_then(nope).and_then(sq), None); . /// assert_eq!(None.and_then(sq).and_then(sq), None); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] 893 ( 0.00%) pub const fn and_then(self, f: F) -> Option . where . F: ~const FnOnce(T) -> Option, . F: ~const Drop, . { 784,662 ( 0.01%) match self { 8,235 ( 0.00%) Some(x) => f(x), . None => None, . } 16,813 ( 0.00%) } . . /// Returns [`None`] if the option is [`None`], otherwise calls `predicate` . /// with the wrapped value and returns: . /// . /// - [`Some(t)`] if `predicate` returns `true` (where `t` is the wrapped . /// value), and . /// - [`None`] if `predicate` returns `false`. . /// -- line 1238 ---------------------------------------- -- line 1257 ---------------------------------------- . #[stable(feature = "option_filter", since = "1.27.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn filter

(self, predicate: P) -> Self . where . T: ~const Drop, . P: ~const FnOnce(&T) -> bool, . P: ~const Drop, . { 3,486 ( 0.00%) if let Some(x) = self { 2,147 ( 0.00%) if predicate(&x) { 273 ( 0.00%) return Some(x); . } . } . None 276 ( 0.00%) } . . /// Returns the option if it contains a value, otherwise returns `optb`. . /// . /// Arguments passed to `or` are eagerly evaluated; if you are passing the . /// result of a function call, it is recommended to use [`or_else`], which is . /// lazily evaluated. . /// . /// [`or_else`]: Option::or_else -- line 1279 ---------------------------------------- -- line 1299 ---------------------------------------- . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn or(self, optb: Option) -> Option . where . T: ~const Drop, . { 5,593 ( 0.00%) match self { 4,466 ( 0.00%) Some(x) => Some(x), . None => optb, . } . } . . /// Returns the option if it contains a value, otherwise calls `f` and . /// returns the result. . /// . /// # Examples -- line 1316 ---------------------------------------- -- line 1326 ---------------------------------------- . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn or_else(self, f: F) -> Option . where . F: ~const FnOnce() -> Option, . F: ~const Drop, . { 1,403,529 ( 0.02%) match self { 10,340 ( 0.00%) Some(x) => Some(x), . None => f(), . } . } . . /// Returns [`Some`] if exactly one of `self`, `optb` is [`Some`], otherwise returns [`None`]. . /// . /// # Examples . /// -- line 1343 ---------------------------------------- -- line 1431 ---------------------------------------- . /// ``` . #[inline] . #[stable(feature = "option_entry", since = "1.20.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn get_or_insert(&mut self, value: T) -> &mut T . where . T: ~const Drop, . { 59,373 ( 0.00%) if let None = *self { 138,461 ( 0.00%) *self = Some(value); . } . . // SAFETY: a `None` variant for `self` would have been replaced by a `Some` . // variant in the code above. . unsafe { self.as_mut().unwrap_unchecked() } . } . . /// Inserts the default value into the option if it is [`None`], then -- line 1448 ---------------------------------------- -- line 1499 ---------------------------------------- . #[inline] . #[stable(feature = "option_entry", since = "1.20.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn get_or_insert_with(&mut self, f: F) -> &mut T . where . F: ~const FnOnce() -> T, . F: ~const Drop, . { 630,493 ( 0.01%) if let None = *self { . // the compiler isn't smart enough to know that we are not dropping a `T` . // here and wants us to ensure `T` can be dropped at compile time. 6 ( 0.00%) mem::forget(mem::replace(self, Some(f()))) . } . . // SAFETY: a `None` variant for `self` would have been replaced by a `Some` . // variant in the code above. . unsafe { self.as_mut().unwrap_unchecked() } . } . . ///////////////////////////////////////////////////////////////////////// -- line 1518 ---------------------------------------- -- line 1558 ---------------------------------------- . /// let old = x.replace(3); . /// assert_eq!(x, Some(3)); . /// assert_eq!(old, None); . /// ``` . #[inline] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] . #[stable(feature = "option_replace", since = "1.31.0")] . pub const fn replace(&mut self, value: T) -> Option { 1,768 ( 0.00%) mem::replace(self, Some(value)) . } . . /// Returns `true` if the option is a [`Some`] value containing the given value. . /// . /// # Examples . /// . /// ``` . /// #![feature(option_result_contains)] -- line 1574 ---------------------------------------- -- line 1712 ---------------------------------------- . #[stable(feature = "copied", since = "1.35.0")] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] . pub const fn copied(self) -> Option . where . T: Copy, . { . // FIXME: this implementation, which sidesteps using `Option::map` since it's not const . // ready yet, should be reverted when possible to avoid code repetition 29,809 ( 0.00%) match self { 445,835 ( 0.01%) Some(&v) => Some(v), 2,048 ( 0.00%) None => None, . } 15 ( 0.00%) } . . /// Maps an `Option<&T>` to an `Option` by cloning the contents of the . /// option. . /// . /// # Examples . /// . /// ``` . /// let x = 12; -- line 1732 ---------------------------------------- -- line 1733 ---------------------------------------- . /// let opt_x = Some(&x); . /// assert_eq!(opt_x, Some(&12)); . /// let cloned = opt_x.cloned(); . /// assert_eq!(cloned, Some(12)); . /// ``` . #[must_use = "`self` will be dropped if the result is not used"] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_cloned", issue = "91582")] 13,022 ( 0.00%) pub const fn cloned(self) -> Option . where . T: ~const Clone, . { 113,970 ( 0.00%) match self { 981,489 ( 0.01%) Some(t) => Some(t.clone()), 8,253 ( 0.00%) None => None, . } 29,692 ( 0.00%) } . } . . impl Option<&mut T> { . /// Maps an `Option<&mut T>` to an `Option` by copying the contents of the . /// option. . /// . /// # Examples . /// -- line 1757 ---------------------------------------- -- line 1843 ---------------------------------------- . ///////////////////////////////////////////////////////////////////////////// . // Trait implementations . ///////////////////////////////////////////////////////////////////////////// . . #[stable(feature = "rust1", since = "1.0.0")] . impl Clone for Option { . #[inline] . fn clone(&self) -> Self { 1,513,653 ( 0.02%) match self { 43,552 ( 0.00%) Some(x) => Some(x.clone()), 1,768 ( 0.00%) None => None, . } 455,211 ( 0.01%) } . . #[inline] . fn clone_from(&mut self, source: &Self) { . match (self, source) { . (Some(to), Some(from)) => to.clone_from(from), . (to, from) => *to = from.clone(), . } . } -- line 1863 ---------------------------------------- -- line 2006 ---------------------------------------- . . #[inline] . fn next(&mut self) -> Option { . self.opt.take() . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 32,781 ( 0.00%) match self.opt { . Some(_) => (1, Some(1)), . None => (0, Some(0)), . } . } . } . . impl DoubleEndedIterator for Item { . #[inline] -- line 2022 ---------------------------------------- -- line 2136 ---------------------------------------- . type Item = A; . . #[inline] . fn next(&mut self) -> Option { . self.inner.next() . } . #[inline] . fn size_hint(&self) -> (usize, Option) { 17 ( 0.00%) self.inner.size_hint() . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl DoubleEndedIterator for IntoIter { . #[inline] . fn next_back(&mut self) -> Option { . self.inner.next_back() -- line 2152 ---------------------------------------- -- line 2241 ---------------------------------------- . #[rustc_const_unstable(feature = "const_convert", issue = "88674")] . impl const ops::Try for Option { . type Output = T; . type Residual = Option; . . #[inline] . fn from_output(output: Self::Output) -> Self { . Some(output) 2,210 ( 0.00%) } . . #[inline] . fn branch(self) -> ControlFlow { 2,813,483 ( 0.04%) match self { 30,693 ( 0.00%) Some(v) => ControlFlow::Continue(v), . None => ControlFlow::Break(None), . } . } . } . . #[unstable(feature = "try_trait_v2", issue = "84277")] . #[rustc_const_unstable(feature = "const_convert", issue = "88674")] . impl const ops::FromResidual for Option { . #[inline] . fn from_residual(residual: Option) -> Self { . match residual { 337,807 ( 0.00%) None => None, . } . } . } . . #[unstable(feature = "try_trait_v2_residual", issue = "91285")] . impl ops::Residual for Option { . type TryType = Option; . } -- line 2274 ---------------------------------------- 10,505,715 ( 0.15%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/mod.rs -------------------------------------------------------------------------------- Ir -- line 90 ---------------------------------------- . &self.local_decls . } . } . . /// A streamlined trait that you can implement to create a pass; the . /// pass will be named after the type, and it will consist of a main . /// loop that goes over each available MIR and applies `run_pass`. . pub trait MirPass<'tcx> { 79,562 ( 0.00%) fn name(&self) -> Cow<'_, str> { . let name = std::any::type_name::(); 2,156 ( 0.00%) if let Some(tail) = name.rfind(':') { 9,929 ( 0.00%) Cow::from(&name[tail + 1..]) . } else { . Cow::from(name) . } 52,466 ( 0.00%) } . . /// Returns `true` if this pass is enabled with the current combination of compiler flags. . fn is_enabled(&self, _sess: &Session) -> bool { . true 19,108 ( 0.00%) } . . fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>); . . /// If this pass causes the MIR to enter a new phase, return that phase. . fn phase_change(&self) -> Option { . None 25,640 ( 0.00%) } . . fn is_mir_dump_enabled(&self) -> bool { . true 30,406 ( 0.00%) } . } . . /// The various "big phases" that MIR goes through. . /// . /// These phases all describe dialects of MIR. Since all MIR uses the same datastructures, the . /// dialects forbid certain variants or values in certain phases. . /// . /// Note: Each phase's validation checks all invariants of the *previous* phases' dialects. A phase . /// that changes the dialect documents what invariants must be upheld *after* that phase finishes. . /// . /// Warning: ordering of variants is significant. 15,501 ( 0.00%) #[derive(Copy, Clone, TyEncodable, TyDecodable, Debug, PartialEq, Eq, PartialOrd, Ord)] . #[derive(HashStable)] . pub enum MirPhase { . Build = 0, . // FIXME(oli-obk): it's unclear whether we still need this phase (and its corresponding query). . // We used to have this for pre-miri MIR based const eval. . Const = 1, . /// This phase checks the MIR for promotable elements and takes them out of the main MIR body . /// by creating a new MIR body per promoted element. After this phase (and thus the termination -- line 141 ---------------------------------------- -- line 157 ---------------------------------------- . impl MirPhase { . /// Gets the index of the current MirPhase within the set of all `MirPhase`s. . pub fn phase_index(&self) -> usize { . *self as usize . } . } . . /// Where a specific `mir::Body` comes from. 3,090 ( 0.00%) #[derive(Copy, Clone, Debug, PartialEq, Eq)] 3,250 ( 0.00%) #[derive(HashStable, TyEncodable, TyDecodable, TypeFoldable)] . pub struct MirSource<'tcx> { . pub instance: InstanceDef<'tcx>, . . /// If `Some`, this is a promoted rvalue within the parent function. . pub promoted: Option, . } . . impl<'tcx> MirSource<'tcx> { 413 ( 0.00%) pub fn item(def_id: DefId) -> Self { 2,065 ( 0.00%) MirSource { . instance: InstanceDef::Item(ty::WithOptConstParam::unknown(def_id)), . promoted: None, . } 413 ( 0.00%) } . 10 ( 0.00%) pub fn from_instance(instance: InstanceDef<'tcx>) -> Self { 50 ( 0.00%) MirSource { instance, promoted: None } 10 ( 0.00%) } . . pub fn with_opt_param(self) -> ty::WithOptConstParam { 926 ( 0.00%) self.instance.with_opt_param() 926 ( 0.00%) } . . #[inline] . pub fn def_id(&self) -> DefId { 45,580 ( 0.00%) self.instance.def_id() . } . } . . #[derive(Clone, TyEncodable, TyDecodable, Debug, HashStable, TypeFoldable)] . pub struct GeneratorInfo<'tcx> { . /// The yield type of the function, if it is a generator. . pub yield_ty: Option>, . -- line 200 ---------------------------------------- -- line 205 ---------------------------------------- . pub generator_layout: Option>, . . /// If this is a generator then record the type of source expression that caused this generator . /// to be created. . pub generator_kind: GeneratorKind, . } . . /// The lowered representation of a single function. 64,665 ( 0.00%) #[derive(Clone, TyEncodable, TyDecodable, Debug, HashStable, TypeFoldable)] . pub struct Body<'tcx> { . /// A list of basic blocks. References to basic block use a newtyped index type [`BasicBlock`] . /// that indexes into this vector. . basic_blocks: IndexVec>, . . /// Records how far through the "desugaring and optimization" process this particular . /// MIR has traversed. This is particularly useful when inlining, since in that context . /// we instantiate the promoted constants and add them to our promoted vector -- but those . /// promoted items have already been optimized, whereas ours have not. This field allows . /// us to see the difference and forego optimization on the inlined promoted items. 1,112 ( 0.00%) pub phase: MirPhase, . . pub source: MirSource<'tcx>, . . /// A list of source scopes; these are referenced by statements . /// and used for debuginfo. Indexed by a `SourceScope`. 1,236 ( 0.00%) pub source_scopes: IndexVec>, . 1,236 ( 0.00%) pub generator: Option>>, . . /// Declarations of locals. . /// . /// The first local is the return value pointer, followed by `arg_count` . /// locals for the function arguments, followed by any user-declared . /// variables and temporaries. . pub local_decls: LocalDecls<'tcx>, . -- line 240 ---------------------------------------- -- line 242 ---------------------------------------- . pub user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>, . . /// The number of arguments this function takes. . /// . /// Starting at local 1, `arg_count` locals will be provided by the caller . /// and can be assumed to be initialized. . /// . /// If this MIR was built for a constant, this will be 0. 618 ( 0.00%) pub arg_count: usize, . . /// Mark an argument local (which must be a tuple) as getting passed as . /// its individual components at the LLVM level. . /// . /// This is used for the "rust-call" ABI. 1,236 ( 0.00%) pub spread_arg: Option, . . /// Debug information pertaining to user variables, including captures. 618 ( 0.00%) pub var_debug_info: Vec>, . . /// A span representing this MIR, for error reporting. . pub span: Span, . . /// Constants that are required to evaluate successfully for this MIR to be well-formed. . /// We hold in this field all the constants we are not able to evaluate yet. . pub required_consts: Vec>, . -- line 267 ---------------------------------------- -- line 275 ---------------------------------------- . /// fn test() { . /// let _ = [0; std::mem::size_of::<*mut T>()]; . /// } . /// ``` . /// . /// **WARNING**: Do not change this flags after the MIR was originally created, even if an optimization . /// removed the last mention of all generic params. We do not want to rely on optimizations and . /// potentially allow things like `[u8; std::mem::size_of::() * 0]` due to this. 618 ( 0.00%) pub is_polymorphic: bool, . . predecessor_cache: PredecessorCache, . is_cyclic: GraphIsCyclicCache, . } . . impl<'tcx> Body<'tcx> { 10,260 ( 0.00%) pub fn new( . source: MirSource<'tcx>, . basic_blocks: IndexVec>, . source_scopes: IndexVec>, . local_decls: LocalDecls<'tcx>, . user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>, . arg_count: usize, . var_debug_info: Vec>, . span: Span, . generator_kind: Option, . ) -> Self { . // We need `arg_count` locals, and one for the return place. 855 ( 0.00%) assert!( 855 ( 0.00%) local_decls.len() > arg_count, . "expected at least {} locals, got {}", . arg_count + 1, . local_decls.len() . ); . 17,100 ( 0.00%) let mut body = Body { . phase: MirPhase::Build, . source, . basic_blocks, . source_scopes, . generator: generator_kind.map(|generator_kind| { . Box::new(GeneratorInfo { . yield_ty: None, . generator_drop: None, . generator_layout: None, . generator_kind, . }) . }), 3,420 ( 0.00%) local_decls, 3,420 ( 0.00%) user_type_annotations, . arg_count, . spread_arg: None, 3,420 ( 0.00%) var_debug_info, . span, . required_consts: Vec::new(), . is_polymorphic: false, . predecessor_cache: PredecessorCache::new(), . is_cyclic: GraphIsCyclicCache::new(), . }; 855 ( 0.00%) body.is_polymorphic = body.has_param_types_or_consts(); . body 7,695 ( 0.00%) } . . /// Returns a partially initialized MIR body containing only a list of basic blocks. . /// . /// The returned MIR contains no `LocalDecl`s (even for the return place) or source scopes. It . /// is only useful for testing but cannot be `#[cfg(test)]` because it is used in a different . /// crate. . pub fn new_cfg_only(basic_blocks: IndexVec>) -> Self { . let mut body = Body { -- line 343 ---------------------------------------- -- line 368 ---------------------------------------- . . #[inline] . pub fn basic_blocks_mut(&mut self) -> &mut IndexVec> { . // Because the user could mutate basic block terminators via this reference, we need to . // invalidate the caches. . // . // FIXME: Use a finer-grained API for this, so only transformations that alter terminators . // invalidate the caches. 3,834 ( 0.00%) self.predecessor_cache.invalidate(); . self.is_cyclic.invalidate(); . &mut self.basic_blocks . } . . #[inline] . pub fn basic_blocks_and_local_decls_mut( . &mut self, . ) -> (&mut IndexVec>, &mut LocalDecls<'tcx>) { -- line 384 ---------------------------------------- -- line 397 ---------------------------------------- . ) { . self.predecessor_cache.invalidate(); . self.is_cyclic.invalidate(); . (&mut self.basic_blocks, &mut self.local_decls, &mut self.var_debug_info) . } . . /// Returns `true` if a cycle exists in the control-flow graph that is reachable from the . /// `START_BLOCK`. 7,160 ( 0.00%) pub fn is_cfg_cyclic(&self) -> bool { . self.is_cyclic.is_cyclic(self) 10,740 ( 0.00%) } . . #[inline] . pub fn local_kind(&self, local: Local) -> LocalKind { . let index = local.as_usize(); 63,468 ( 0.00%) if index == 0 { . debug_assert!( . self.local_decls[local].mutability == Mutability::Mut, . "return place should be mutable" . ); . . LocalKind::ReturnPointer 222,090 ( 0.00%) } else if index < self.arg_count + 1 { . LocalKind::Arg . } else if self.local_decls[local].is_user_variable() { . LocalKind::Var . } else { . LocalKind::Temp . } . } . . /// Returns an iterator over all user-declared mutable locals. . #[inline] . pub fn mut_vars_iter<'a>(&'a self) -> impl Iterator + 'a { 1,203 ( 0.00%) (self.arg_count + 1..self.local_decls.len()).filter_map(move |index| { . let local = Local::new(index); . let decl = &self.local_decls[local]; 1,875 ( 0.00%) if decl.is_user_variable() && decl.mutability == Mutability::Mut { . Some(local) . } else { . None . } . }) . } . . /// Returns an iterator over all user-declared mutable arguments and locals. . #[inline] . pub fn mut_vars_and_args_iter<'a>(&'a self) -> impl Iterator + 'a { . (1..self.local_decls.len()).filter_map(move |index| { . let local = Local::new(index); . let decl = &self.local_decls[local]; 34,165 ( 0.00%) if (decl.is_user_variable() || index < self.arg_count + 1) . && decl.mutability == Mutability::Mut . { . Some(local) . } else { . None . } . }) . } . . /// Returns an iterator over all function arguments. . #[inline] . pub fn args_iter(&self) -> impl Iterator + ExactSizeIterator { 16,842 ( 0.00%) (1..self.arg_count + 1).map(Local::new) . } . . /// Returns an iterator over all user-defined variables and compiler-generated temporaries (all . /// locals that are neither arguments nor the return place). . #[inline] . pub fn vars_and_temps_iter( . &self, . ) -> impl DoubleEndedIterator + ExactSizeIterator { 2,094 ( 0.00%) (self.arg_count + 1..self.local_decls.len()).map(Local::new) . } . . #[inline] . pub fn drain_vars_and_temps<'a>(&'a mut self) -> impl Iterator> + 'a { . self.local_decls.drain(self.arg_count + 1..) . } . . /// Changes a statement to a nop. This is both faster than deleting instructions and avoids -- line 478 ---------------------------------------- -- line 479 ---------------------------------------- . /// invalidating statement indices in `Location`s. . pub fn make_statement_nop(&mut self, location: Location) { . let block = &mut self.basic_blocks[location.block]; . debug_assert!(location.statement_index < block.statements.len()); . block.statements[location.statement_index].make_nop() . } . . /// Returns the source info associated with `location`. 300,110 ( 0.00%) pub fn source_info(&self, location: Location) -> &SourceInfo { . let block = &self[location.block]; . let stmts = &block.statements; 150,055 ( 0.00%) let idx = location.statement_index; 750,275 ( 0.01%) if idx < stmts.len() { 433,047 ( 0.01%) &stmts[idx].source_info . } else { 11,412 ( 0.00%) assert_eq!(idx, stmts.len()); 11,412 ( 0.00%) &block.terminator().source_info . } 300,110 ( 0.00%) } . . /// Returns the return type; it always return first element from `local_decls` array. . #[inline] . pub fn return_ty(&self) -> Ty<'tcx> { 3,017 ( 0.00%) self.local_decls[RETURN_PLACE].ty . } . . /// Gets the location of the terminator for the given block. . #[inline] . pub fn terminator_loc(&self, bb: BasicBlock) -> Location { 40,065 ( 0.00%) Location { block: bb, statement_index: self[bb].statements.len() } . } . . pub fn stmt_at(&self, location: Location) -> Either<&Statement<'tcx>, &Terminator<'tcx>> { . let Location { block, statement_index } = location; . let block_data = &self.basic_blocks[block]; . block_data . .statements . .get(statement_index) -- line 516 ---------------------------------------- -- line 520 ---------------------------------------- . . #[inline] . pub fn predecessors(&self) -> &Predecessors { . self.predecessor_cache.compute(&self.basic_blocks) . } . . #[inline] . pub fn dominators(&self) -> Dominators { 3,000 ( 0.00%) dominators(self) . } . . #[inline] . pub fn yield_ty(&self) -> Option> { . self.generator.as_ref().and_then(|generator| generator.yield_ty) . } . . #[inline] -- line 536 ---------------------------------------- -- line 571 ---------------------------------------- . . impl<'tcx> IndexMut for Body<'tcx> { . #[inline] . fn index_mut(&mut self, index: BasicBlock) -> &mut BasicBlockData<'tcx> { . &mut self.basic_blocks_mut()[index] . } . } . 39,073 ( 0.00%) #[derive(Copy, Clone, Debug, HashStable, TypeFoldable)] . pub enum ClearCrossCrate { . Clear, . Set(T), . } . . impl ClearCrossCrate { . pub fn as_ref(&self) -> ClearCrossCrate<&T> { 589,459 ( 0.01%) match self { . ClearCrossCrate::Clear => ClearCrossCrate::Clear, . ClearCrossCrate::Set(v) => ClearCrossCrate::Set(v), . } . } . . pub fn assert_crate_local(self) -> T { 149,103 ( 0.00%) match self { . ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"), . ClearCrossCrate::Set(v) => v, . } 3,786 ( 0.00%) } . } . . const TAG_CLEAR_CROSS_CRATE_CLEAR: u8 = 0; . const TAG_CLEAR_CROSS_CRATE_SET: u8 = 1; . . impl<'tcx, E: TyEncoder<'tcx>, T: Encodable> Encodable for ClearCrossCrate { . #[inline] . fn encode(&self, e: &mut E) -> Result<(), E::Error> { -- line 606 ---------------------------------------- -- line 637 ---------------------------------------- . } . } . . /// Grouped information about the source code origin of a MIR entity. . /// Intended to be inspected by diagnostics and debuginfo. . /// Most passes can work with it as a whole, within a single function. . // The unofficial Cranelift backend, at least as of #65828, needs `SourceInfo` to implement `Eq` and . // `Hash`. Please ping @bjorn3 if removing them. 229,181 ( 0.00%) #[derive(Copy, Clone, Debug, Eq, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)] . pub struct SourceInfo { . /// The source span for the AST pertaining to this MIR entity. . pub span: Span, . . /// The source scope, keeping track of which bindings can be . /// seen by debuginfo, active lint levels, `unsafe {...}`, etc. . pub scope: SourceScope, . } -- line 653 ---------------------------------------- -- line 657 ---------------------------------------- . pub fn outermost(span: Span) -> Self { . SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE } . } . } . . /////////////////////////////////////////////////////////////////////////// . // Borrow kinds . 53,923 ( 0.00%) #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, TyEncodable, TyDecodable)] . #[derive(Hash, HashStable)] . pub enum BorrowKind { . /// Data must be immutable and is aliasable. . Shared, . . /// The immediately borrowed place must be immutable, but projections from . /// it don't need to be. For example, a shallow borrow of `a.b` doesn't . /// conflict with a mutable borrow of `a.b.c`. -- line 673 ---------------------------------------- -- line 725 ---------------------------------------- . /// simplicity, we don't give users the way to express this . /// borrow, it's just used when translating closures. . Unique, . . /// Data is mutable and not aliasable. . Mut { . /// `true` if this borrow arose from method-call auto-ref . /// (i.e., `adjustment::Adjust::Borrow`). 1,224 ( 0.00%) allow_two_phase_borrow: bool, . }, . } . . impl BorrowKind { . pub fn allows_two_phase_borrow(&self) -> bool { 4,215 ( 0.00%) match *self { . BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => false, . BorrowKind::Mut { allow_two_phase_borrow } => allow_two_phase_borrow, . } 843 ( 0.00%) } . . pub fn describe_mutability(&self) -> String { . match *self { . BorrowKind::Shared | BorrowKind::Shallow | BorrowKind::Unique => { . "immutable".to_string() . } . BorrowKind::Mut { .. } => "mutable".to_string(), . } -- line 751 ---------------------------------------- -- line 777 ---------------------------------------- . /// Compiler-introduced temporary. . Temp, . /// Function argument. . Arg, . /// Location of function's return value. . ReturnPointer, . } . 8,686 ( 0.00%) #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)] . pub struct VarBindingForm<'tcx> { . /// Is variable bound via `x`, `mut x`, `ref x`, or `ref mut x`? 2,196 ( 0.00%) pub binding_mode: ty::BindingMode, . /// If an explicit type was provided for this variable binding, . /// this holds the source Span of that type. . /// . /// NOTE: if you want to change this to a `HirId`, be wary that . /// doing so breaks incremental compilation (as of this writing), . /// while a `Span` does not cause our tests to fail. . pub opt_ty_info: Option, . /// Place of the RHS of the =, or the subject of the `match` where this -- line 796 ---------------------------------------- -- line 799 ---------------------------------------- . /// (a) the right-hand side isn't evaluated as a place expression. . /// (b) it gives a way to separate this case from the remaining cases . /// for diagnostics. . pub opt_match_place: Option<(Option>, Span)>, . /// The span of the pattern in which this variable was bound. . pub pat_span: Span, . } . 6,160 ( 0.00%) #[derive(Clone, Debug, TyEncodable, TyDecodable)] . pub enum BindingForm<'tcx> { . /// This is a binding for a non-`self` binding, or a `self` that has an explicit type. . Var(VarBindingForm<'tcx>), . /// Binding for a `self`/`&self`/`&mut self` binding where the type is implicit. 1,368 ( 0.00%) ImplicitSelf(ImplicitSelfKind), . /// Reference used in a guard expression to ensure immutability. . RefForGuard, . } . . /// Represents what type of implicit self a function has, if any. . #[derive(Clone, Copy, PartialEq, Debug, TyEncodable, TyDecodable, HashStable)] . pub enum ImplicitSelfKind { . /// Represents a `fn x(self);`. -- line 820 ---------------------------------------- -- line 853 ---------------------------------------- . /// `BlockTailInfo` is attached to the `LocalDecl` for temporaries . /// created during evaluation of expressions in a block tail . /// expression; that is, a block like `{ STMT_1; STMT_2; EXPR }`. . /// . /// It is used to improve diagnostics when such temporaries are . /// involved in borrow_check errors, e.g., explanations of where the . /// temporaries come from, when their destructors are run, and/or how . /// one might revise the code to satisfy the borrow checker's rules. 11,770 ( 0.00%) #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)] . pub struct BlockTailInfo { . /// If `true`, then the value resulting from evaluating this tail . /// expression is ignored by the block's expression context. . /// . /// Examples include `{ ...; tail };` and `let _ = { ...; tail };` . /// but not e.g., `let _x = { ...; tail };` . pub tail_result_is_ignored: bool, . -- line 869 ---------------------------------------- -- line 870 ---------------------------------------- . /// `Span` of the tail expression. . pub span: Span, . } . . /// A MIR local. . /// . /// This can be a binding declared by the user, a temporary inserted by the compiler, a function . /// argument, or the return place. 180,736 ( 0.00%) #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)] . pub struct LocalDecl<'tcx> { . /// Whether this is a mutable binding (i.e., `let x` or `let mut x`). . /// . /// Temporaries and the return place are always mutable. 45,954 ( 0.00%) pub mutability: Mutability, . . // FIXME(matthewjasper) Don't store in this in `Body` . pub local_info: Option>>, . . /// `true` if this is an internal local. . /// . /// These locals are not based on types in the source code and are only used . /// for a few desugarings at the moment. -- line 891 ---------------------------------------- -- line 894 ---------------------------------------- . /// across a suspension point against the type components of the generator . /// which type checking knows are live across a suspension point. We need to . /// flag drop flags to avoid triggering this check as they are introduced . /// after typeck. . /// . /// This should be sound because the drop flags are fully algebraic, and . /// therefore don't affect the auto-trait or outlives properties of the . /// generator. 35,656 ( 0.00%) pub internal: bool, . . /// If this local is a temporary and `is_block_tail` is `Some`, . /// then it is a temporary created for evaluation of some . /// subexpression of some block's tail expression (with no . /// intervening statement context). . // FIXME(matthewjasper) Don't store in this in `Body` . pub is_block_tail: Option, . . /// The type of this local. 35,676 ( 0.00%) pub ty: Ty<'tcx>, . . /// If the user manually ascribed a type to this variable, . /// e.g., via `let x: T`, then we carry that type here. The MIR . /// borrow checker needs this information since it can affect . /// region inference. . // FIXME(matthewjasper) Don't store in this in `Body` . pub user_ty: Option>, . -- line 920 ---------------------------------------- -- line 1005 ---------------------------------------- . static_assert_size!(LocalDecl<'_>, 56); . . /// Extra information about a some locals that's used for diagnostics and for . /// classifying variables into local variables, statics, etc, which is needed e.g. . /// for unsafety checking. . /// . /// Not used for non-StaticRef temporaries, the return place, or anonymous . /// function parameters. 77,876 ( 0.00%) #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)] . pub enum LocalInfo<'tcx> { . /// A user-defined local variable or function parameter . /// . /// The `BindingForm` is solely used for local diagnostics when generating . /// warnings/errors when compiling the current crate, and therefore it need . /// not be visible across crates. . User(ClearCrossCrate>), . /// A temporary created that references the static with the given `DefId`. . StaticRef { def_id: DefId, is_thread_local: bool }, . /// A temporary created that references the const with the given `DefId` 540 ( 0.00%) ConstRef { def_id: DefId }, . /// A temporary created during the creation of an aggregate . /// (e.g. a temporary for `foo` in `MyStruct { my_field: foo }`) . AggregateTemp, . } . . impl<'tcx> LocalDecl<'tcx> { . /// Returns `true` only if local is a binding that can itself be . /// made mutable via the addition of the `mut` keyword, namely -- line 1032 ---------------------------------------- -- line 1064 ---------------------------------------- . ))) . ) . } . . /// Returns `true` if this variable is a named variable or function . /// parameter declared by the user. . #[inline] . pub fn is_user_variable(&self) -> bool { 118,134 ( 0.00%) matches!(self.local_info, Some(box LocalInfo::User(_))) . } . . /// Returns `true` if this is a reference to a variable bound in a `match` . /// expression that is used to access said variable for the guard of the . /// match arm. . pub fn is_ref_for_guard(&self) -> bool { . matches!( . self.local_info, . Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::RefForGuard))) . ) . } . . /// Returns `Some` if this is a reference to a static item that is used to . /// access that static. . pub fn is_ref_to_static(&self) -> bool { 44,403 ( 0.00%) matches!(self.local_info, Some(box LocalInfo::StaticRef { .. })) 13,265 ( 0.00%) } . . /// Returns `Some` if this is a reference to a thread-local static item that is used to . /// access that static. . pub fn is_ref_to_thread_local(&self) -> bool { 13,905 ( 0.00%) match self.local_info { . Some(box LocalInfo::StaticRef { is_thread_local, .. }) => is_thread_local, . _ => false, . } 3,483 ( 0.00%) } . . /// Returns `true` is the local is from a compiler desugaring, e.g., . /// `__next` from a `for` loop. . #[inline] . pub fn from_compiler_desugaring(&self) -> bool { . self.source_info.span.desugaring_kind().is_some() . } . -- line 1106 ---------------------------------------- -- line 1108 ---------------------------------------- . #[inline] . pub fn new(ty: Ty<'tcx>, span: Span) -> Self { . Self::with_source_info(ty, SourceInfo::outermost(span)) . } . . /// Like `LocalDecl::new`, but takes a `SourceInfo` instead of a `Span`. . #[inline] . pub fn with_source_info(ty: Ty<'tcx>, source_info: SourceInfo) -> Self { 43,482 ( 0.00%) LocalDecl { . mutability: Mutability::Mut, . local_info: None, . internal: false, . is_block_tail: None, . ty, . user_ty: None, . source_info, . } . } . . /// Converts `self` into same `LocalDecl` except tagged as internal. . #[inline] . pub fn internal(mut self) -> Self { . self.internal = true; 469 ( 0.00%) self . } . . /// Converts `self` into same `LocalDecl` except tagged as immutable. . #[inline] . pub fn immutable(mut self) -> Self { . self.mutability = Mutability::Not; . self . } . . /// Converts `self` into same `LocalDecl` except tagged as internal temporary. . #[inline] . pub fn block_tail(mut self, info: BlockTailInfo) -> Self { 1,602 ( 0.00%) assert!(self.is_block_tail.is_none()); 4,806 ( 0.00%) self.is_block_tail = Some(info); 22,428 ( 0.00%) self . } . } . 12,889 ( 0.00%) #[derive(Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable)] . pub enum VarDebugInfoContents<'tcx> { . /// NOTE(eddyb) There's an unenforced invariant that this `Place` is . /// based on a `Local`, not a `Static`, and contains no indexing. . Place(Place<'tcx>), . Const(Constant<'tcx>), . } . . impl<'tcx> Debug for VarDebugInfoContents<'tcx> { -- line 1158 ---------------------------------------- -- line 1160 ---------------------------------------- . match self { . VarDebugInfoContents::Const(c) => write!(fmt, "{}", c), . VarDebugInfoContents::Place(p) => write!(fmt, "{:?}", p), . } . } . } . . /// Debug information pertaining to a user variable. 34,023 ( 0.00%) #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)] . pub struct VarDebugInfo<'tcx> { . pub name: Symbol, . . /// Source info of the user variable, including the scope . /// within which the variable is visible (to debuginfo) . /// (see `LocalDecl`'s `source_info` field for more details). . pub source_info: SourceInfo, . -- line 1176 ---------------------------------------- -- line 1209 ---------------------------------------- . DEBUG_FORMAT = "bb{}", . const START_BLOCK = 0, . } . } . . impl BasicBlock { . pub fn start_location(self) -> Location { . Location { block: self, statement_index: 0 } 45,957 ( 0.00%) } . } . . /////////////////////////////////////////////////////////////////////////// . // BasicBlockData and Terminator . . /// See [`BasicBlock`] for documentation on what basic blocks are at a high level. 194,230 ( 0.00%) #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)] . pub struct BasicBlockData<'tcx> { . /// List of statements in this block. 2,394 ( 0.00%) pub statements: Vec>, . . /// Terminator for this block. . /// . /// N.B., this should generally ONLY be `None` during construction. . /// Therefore, you should generally access it via the . /// `terminator()` or `terminator_mut()` methods. The only . /// exception is that certain passes, such as `simplify_cfg`, swap . /// out the terminator temporarily with `None` while they continue -- line 1235 ---------------------------------------- -- line 1239 ---------------------------------------- . /// If true, this block lies on an unwind path. This is used . /// during codegen where distinct kinds of basic blocks may be . /// generated (particularly for MSVC cleanup). Unwind blocks must . /// only branch to other unwind blocks. . pub is_cleanup: bool, . } . . /// Information about an assertion failure. 1,037 ( 0.00%) #[derive(Clone, TyEncodable, TyDecodable, Hash, HashStable, PartialEq, PartialOrd)] . pub enum AssertKind { . BoundsCheck { len: O, index: O }, . Overflow(BinOp, O, O), . OverflowNeg(O), . DivisionByZero(O), . RemainderByZero(O), . ResumedAfterReturn(GeneratorKind), . ResumedAfterPanic(GeneratorKind), -- line 1255 ---------------------------------------- -- line 1287 ---------------------------------------- . pub type AssertMessage<'tcx> = AssertKind>; . . pub type Successors<'a> = . iter::Chain, slice::Iter<'a, BasicBlock>>; . pub type SuccessorsMut<'a> = . iter::Chain, slice::IterMut<'a, BasicBlock>>; . . impl<'tcx> BasicBlockData<'tcx> { 3,497 ( 0.00%) pub fn new(terminator: Option>) -> BasicBlockData<'tcx> { 55,952 ( 0.00%) BasicBlockData { statements: vec![], terminator, is_cleanup: false } 3,497 ( 0.00%) } . . /// Accessor for terminator. . /// . /// Terminator may not be None after construction of the basic block is complete. This accessor . /// provides a convenience way to reach the terminator. . #[inline] . pub fn terminator(&self) -> &Terminator<'tcx> { 75,916 ( 0.00%) self.terminator.as_ref().expect("invalid terminator state") . } . . #[inline] . pub fn terminator_mut(&mut self) -> &mut Terminator<'tcx> { 34,052 ( 0.00%) self.terminator.as_mut().expect("invalid terminator state") . } . . pub fn retain_statements(&mut self, mut f: F) . where . F: FnMut(&mut Statement<'_>) -> bool, . { . for s in &mut self.statements { . if !f(s) { . s.make_nop(); . } . } . } . 25,190 ( 0.00%) pub fn expand_statements(&mut self, mut f: F) . where . F: FnMut(&mut Statement<'tcx>) -> Option, . I: iter::TrustedLen>, . { . // Gather all the iterators we'll need to splice in, and their positions. . let mut splices: Vec<(usize, I)> = vec![]; . let mut extra_stmts = 0; . for (i, s) in self.statements.iter_mut().enumerate() { 17,836 ( 0.00%) if let Some(mut new_stmts) = f(s) { 330 ( 0.00%) if let Some(first) = new_stmts.next() { . // We can already store the first new statement. 3,768 ( 0.00%) *s = first; . . // Save the other statements for optimized splicing. . let remaining = new_stmts.size_hint().0; 1,256 ( 0.00%) if remaining > 0 { 2,912 ( 0.00%) splices.push((i + 1 + extra_stmts, new_stmts)); 832 ( 0.00%) extra_stmts += remaining; . } . } else { 18 ( 0.00%) s.make_nop(); . } 663 ( 0.00%) } . } . . // Splice in the new statements, from the end of the block. . // FIXME(eddyb) This could be more efficient with a "gap buffer" . // where a range of elements ("gap") is left uninitialized, with . // splicing adding new elements to the end of that gap and moving . // existing elements from before the gap to the end of the gap. . // For now, this is safe code, emulating a gap but initializing it. 7,156 ( 0.00%) let mut gap = self.statements.len()..self.statements.len() + extra_stmts; 7,557 ( 0.00%) self.statements.resize( . gap.end, 10,076 ( 0.00%) Statement { source_info: SourceInfo::outermost(DUMMY_SP), kind: StatementKind::Nop }, . ); 11,648 ( 0.00%) for (splice_start, new_stmts) in splices.into_iter().rev() { 832 ( 0.00%) let splice_end = splice_start + new_stmts.size_hint().0; 5,282 ( 0.00%) while gap.end > splice_end { 3,912 ( 0.00%) gap.start -= 1; . gap.end -= 1; . self.statements.swap(gap.start, gap.end); . } 1,664 ( 0.00%) self.statements.splice(splice_start..splice_end, new_stmts); . gap.end = splice_start; . } 20,152 ( 0.00%) } . . pub fn visitable(&self, index: usize) -> &dyn MirVisitable<'tcx> { . if index < self.statements.len() { &self.statements[index] } else { &self.terminator } . } . } . . impl AssertKind { . /// Getting a description does not require `O` to be printable, and does not -- line 1379 ---------------------------------------- -- line 1501 ---------------------------------------- . _ => write!(f, "{}", self.description()), . } . } . } . . /////////////////////////////////////////////////////////////////////////// . // Statements . 496,289 ( 0.01%) #[derive(Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable)] . pub struct Statement<'tcx> { . pub source_info: SourceInfo, . pub kind: StatementKind<'tcx>, . } . . // `Statement` is used a lot. Make sure it doesn't unintentionally get bigger. . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . static_assert_size!(Statement<'_>, 32); . . impl Statement<'_> { . /// Changes a statement to a nop. This is both faster than deleting instructions and avoids . /// invalidating statement indices in `Location`s. 898 ( 0.00%) pub fn make_nop(&mut self) { 898 ( 0.00%) self.kind = StatementKind::Nop 898 ( 0.00%) } . . /// Changes a statement to a nop and returns the original statement. . #[must_use = "If you don't need the statement, use `make_nop` instead"] 637 ( 0.00%) pub fn replace_nop(&mut self) -> Self { 637 ( 0.00%) Statement { 2,548 ( 0.00%) source_info: self.source_info, . kind: mem::replace(&mut self.kind, StatementKind::Nop), . } 637 ( 0.00%) } . } . 553,913 ( 0.01%) #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, Hash, HashStable, TypeFoldable)] . pub enum StatementKind<'tcx> { . /// Write the RHS Rvalue to the LHS Place. 10,461 ( 0.00%) Assign(Box<(Place<'tcx>, Rvalue<'tcx>)>), . . /// This represents all the reading that a pattern match may do . /// (e.g., inspecting constants and discriminant values), and the . /// kind of pattern it comes from. This is in order to adapt potential . /// error messages to these specific patterns. . /// . /// Note that this also is emitted for regular `let` bindings to ensure that locals that are . /// never accessed still get some sanity checks for, e.g., `let x: ! = ..;` 293 ( 0.00%) FakeRead(Box<(FakeReadCause, Place<'tcx>)>), . . /// Write the discriminant for a variant to the enum Place. 432 ( 0.00%) SetDiscriminant { place: Box>, variant_index: VariantIdx }, . . /// Start a live range for the storage of the local. 22,662 ( 0.00%) StorageLive(Local), . . /// End the current live range for the storage of the local. 23,412 ( 0.00%) StorageDead(Local), . . /// Retag references in the given place, ensuring they got fresh tags. This is . /// part of the Stacked Borrows model. These statements are currently only interpreted . /// by miri and only generated when "-Z mir-emit-retag" is passed. . /// See . /// for more details. . Retag(RetagKind, Box>), . -- line 1565 ---------------------------------------- -- line 1719 ---------------------------------------- . } . . #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, Hash, HashStable, TypeFoldable)] . pub struct Coverage { . pub kind: CoverageKind, . pub code_region: Option, . } . 39 ( 0.00%) #[derive(Clone, Debug, PartialEq, TyEncodable, TyDecodable, Hash, HashStable, TypeFoldable)] . pub struct CopyNonOverlapping<'tcx> { . pub src: Operand<'tcx>, . pub dst: Operand<'tcx>, . /// Number of elements to copy from src to dest, not bytes. . pub count: Operand<'tcx>, . } . . /////////////////////////////////////////////////////////////////////////// . // Places . . /// A path to a value; something that can be evaluated without . /// changing or disturbing program state. 39,125 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, HashStable)] . pub struct Place<'tcx> { 2,933 ( 0.00%) pub local: Local, . . /// projection out of a place (access a field, deref a pointer, etc) . pub projection: &'tcx List>, . } . . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . static_assert_size!(Place<'_>, 16); . 165,290 ( 0.00%) #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] 110,304 ( 0.00%) #[derive(TyEncodable, TyDecodable, HashStable)] . pub enum ProjectionElem { . Deref, 20,847 ( 0.00%) Field(Field, T), 52 ( 0.00%) Index(V), . . /// These indices are generated by slice patterns. Easiest to explain . /// by example: . /// . /// ``` . /// [X, _, .._, _, _] => { offset: 0, min_length: 4, from_end: false }, . /// [_, X, .._, _, _] => { offset: 1, min_length: 4, from_end: false }, . /// [_, _, .._, X, _] => { offset: 2, min_length: 4, from_end: true }, . /// [_, _, .._, _, X] => { offset: 1, min_length: 4, from_end: true }, . /// ``` . ConstantIndex { . /// index or -index (in Python terms), depending on from_end 10 ( 0.00%) offset: u64, . /// The thing being indexed must be at least this long. For arrays this . /// is always the exact length. . min_length: u64, . /// Counting backwards from end? This is always false when indexing an . /// array. . from_end: bool, . }, . -- line 1777 ---------------------------------------- -- line 1788 ---------------------------------------- . from_end: bool, . }, . . /// "Downcast" to a variant of an ADT. Currently, we only introduce . /// this for ADTs with more than one variant. It may be better to . /// just introduce it always, or always for enums. . /// . /// The included Symbol is the name of the variant, used for printing MIR. 4,990 ( 0.00%) Downcast(Option, VariantIdx), . } . . impl ProjectionElem { . /// Returns `true` if the target of this projection may refer to a different region of memory . /// than the base. . fn is_indirect(&self) -> bool { 1,746 ( 0.00%) match self { . Self::Deref => true, . . Self::Field(_, _) . | Self::Index(_) . | Self::ConstantIndex { .. } . | Self::Subslice { .. } . | Self::Downcast(_, _) => false, . } -- line 1811 ---------------------------------------- -- line 1838 ---------------------------------------- . pub struct Field { . derive [HashStable] . DEBUG_FORMAT = "field[{}]" . } . } . . #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] . pub struct PlaceRef<'tcx> { 5,876 ( 0.00%) pub local: Local, 1,484 ( 0.00%) pub projection: &'tcx [PlaceElem<'tcx>], . } . . impl<'tcx> Place<'tcx> { . // FIXME change this to a const fn by also making List::empty a const fn. . pub fn return_place() -> Place<'tcx> { . Place { local: RETURN_PLACE, projection: List::empty() } 3,999 ( 0.00%) } . . /// Returns `true` if this `Place` contains a `Deref` projection. . /// . /// If `Place::is_indirect` returns false, the caller knows that the `Place` refers to the . /// same region of memory as its base. . pub fn is_indirect(&self) -> bool { 11,557 ( 0.00%) self.projection.iter().any(|elem| elem.is_indirect()) 11,557 ( 0.00%) } . . /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or . /// a single deref of a local. . #[inline(always)] . pub fn local_or_deref_local(&self) -> Option { . self.as_ref().local_or_deref_local() . } . -- line 1870 ---------------------------------------- -- line 1872 ---------------------------------------- . /// projections, return `Some(_X)`. . #[inline(always)] . pub fn as_local(&self) -> Option { . self.as_ref().as_local() . } . . #[inline] . pub fn as_ref(&self) -> PlaceRef<'tcx> { 413,718 ( 0.01%) PlaceRef { local: self.local, projection: &self.projection } . } . . /// Iterate over the projections in evaluation order, i.e., the first element is the base with . /// its projection and then subsequently more projections are added. . /// As a concrete example, given the place a.b.c, this would yield: . /// - (a, .b) . /// - (a.b, .c) . /// -- line 1888 ---------------------------------------- -- line 1896 ---------------------------------------- . (base, proj) . }) . } . } . . impl From for Place<'_> { . fn from(local: Local) -> Self { . Place { local, projection: List::empty() } 174,933 ( 0.00%) } . } . . impl<'tcx> PlaceRef<'tcx> { . /// Finds the innermost `Local` from this `Place`, *if* it is either a local itself or . /// a single deref of a local. . pub fn local_or_deref_local(&self) -> Option { . match *self { . PlaceRef { local, projection: [] } -- line 1912 ---------------------------------------- -- line 1915 ---------------------------------------- . } . } . . /// If this place represents a local variable like `_X` with no . /// projections, return `Some(_X)`. . #[inline] . pub fn as_local(&self) -> Option { . match *self { 93,878 ( 0.00%) PlaceRef { local, projection: [] } => Some(local), . _ => None, . } . } . . #[inline] . pub fn last_projection(&self) -> Option<(PlaceRef<'tcx>, PlaceElem<'tcx>)> { 191,526 ( 0.00%) if let &[ref proj_base @ .., elem] = self.projection { 3,686 ( 0.00%) Some((PlaceRef { local: self.local, projection: proj_base }, elem)) . } else { . None . } . } . } . . impl Debug for Place<'_> { . fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result { -- line 1939 ---------------------------------------- -- line 2024 ---------------------------------------- . trace!(?data); . match &data.local_data { . ClearCrossCrate::Set(data) => Some(data.lint_root), . ClearCrossCrate::Clear => None, . } . } . } . 36,969 ( 0.00%) #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)] . pub struct SourceScopeData<'tcx> { 124 ( 0.00%) pub span: Span, . pub parent_scope: Option, . . /// Whether this scope is the root of a scope tree of another body, . /// inlined into this body by the MIR inliner. . /// `ty::Instance` is the callee, and the `Span` is the call site. . pub inlined: Option<(ty::Instance<'tcx>, Span)>, . . /// Nearest (transitive) parent scope (if any) which is inlined. . /// This is an optimization over walking up `parent_scope` . /// until a scope with `inlined: Some(...)` is found. 372 ( 0.00%) pub inlined_parent_scope: Option, . . /// Crate-local information for this source scope, that can't (and . /// needn't) be tracked across crates. . pub local_data: ClearCrossCrate, . } . 7,631 ( 0.00%) #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)] . pub struct SourceScopeLocalData { . /// An `HirId` with lint levels equivalent to this scope's lint levels. . pub lint_root: hir::HirId, . /// The unsafe block that contains this node. . pub safety: Safety, . } . . /////////////////////////////////////////////////////////////////////////// . // Operands . . /// These are values that can appear inside an rvalue. They are intentionally . /// limited to prevent rvalues from being nested in one another. 3,790,140 ( 0.05%) #[derive(Clone, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)] . pub enum Operand<'tcx> { . /// Copy: The value must be available for use afterwards. . /// . /// This implies that the type of the place must be `Copy`; this is true . /// by construction during build, but also checked by the MIR type checker. 10,159 ( 0.00%) Copy(Place<'tcx>), . . /// Move: The value (including old borrows of it) will not be used again. . /// . /// Safe for values of all types (modulo future developments towards `?Move`). . /// Correct usage patterns are enforced by the borrow checker for safe code. . /// `Copy` may be converted to `Move` to enable "last-use" optimizations. 32,037 ( 0.00%) Move(Place<'tcx>), . . /// Synthesizes a constant value. 141,794 ( 0.00%) Constant(Box>), . } . . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . static_assert_size!(Operand<'_>, 24); . . impl<'tcx> Debug for Operand<'tcx> { . fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result { . use self::Operand::*; -- line 2089 ---------------------------------------- -- line 2094 ---------------------------------------- . } . } . } . . impl<'tcx> Operand<'tcx> { . /// Convenience helper to make a constant that refers to the fn . /// with given `DefId` and substs. Since this is used to synthesize . /// MIR, assumes `user_ty` is None. 88 ( 0.00%) pub fn function_handle( . tcx: TyCtxt<'tcx>, . def_id: DefId, . substs: SubstsRef<'tcx>, . span: Span, . ) -> Self { . let ty = tcx.type_of(def_id).subst(tcx, substs); 22 ( 0.00%) Operand::Constant(Box::new(Constant { . span, . user_ty: None, . literal: ConstantKind::Ty(ty::Const::zero_sized(tcx, ty)), . })) 99 ( 0.00%) } . . pub fn is_move(&self) -> bool { 576 ( 0.00%) matches!(self, Operand::Move(..)) 288 ( 0.00%) } . . /// Convenience helper to make a literal-like constant from a given scalar value. . /// Since this is used to synthesize MIR, assumes `user_ty` is None. . pub fn const_from_scalar( . tcx: TyCtxt<'tcx>, . ty: Ty<'tcx>, . val: Scalar, . span: Span, -- line 2126 ---------------------------------------- -- line 2149 ---------------------------------------- . Operand::Copy(_) | Operand::Constant(_) => self.clone(), . Operand::Move(place) => Operand::Copy(place), . } . } . . /// Returns the `Place` that is the target of this `Operand`, or `None` if this `Operand` is a . /// constant. . pub fn place(&self) -> Option> { 6,356 ( 0.00%) match self { . Operand::Copy(place) | Operand::Move(place) => Some(*place), . Operand::Constant(_) => None, . } 1,589 ( 0.00%) } . . /// Returns the `Constant` that is the target of this `Operand`, or `None` if this `Operand` is a . /// place. . pub fn constant(&self) -> Option<&Constant<'tcx>> { 136 ( 0.00%) match self { . Operand::Constant(x) => Some(&**x), . Operand::Copy(_) | Operand::Move(_) => None, . } 68 ( 0.00%) } . } . . /////////////////////////////////////////////////////////////////////////// . /// Rvalues . 251,357 ( 0.00%) #[derive(Clone, TyEncodable, TyDecodable, Hash, HashStable, PartialEq)] . pub enum Rvalue<'tcx> { . /// x (either a move or copy, depending on type of x) . Use(Operand<'tcx>), . . /// [x; 32] . Repeat(Operand<'tcx>, &'tcx ty::Const<'tcx>), . . /// &x or &mut x 20,875 ( 0.00%) Ref(Region<'tcx>, BorrowKind, Place<'tcx>), . . /// Accessing a thread local static. This is inherently a runtime operation, even if llvm . /// treats it as an access to a static. This `Rvalue` yields a reference to the thread local . /// static. . ThreadLocalRef(DefId), . . /// Create a raw pointer to the given place . /// Can be generated by raw address of expressions (`&raw const x`), . /// or when casting a reference to a raw pointer. 90 ( 0.00%) AddressOf(Mutability, Place<'tcx>), . . /// length of a `[X]` or `[X;n]` value 23 ( 0.00%) Len(Place<'tcx>), . 2,478 ( 0.00%) Cast(CastKind, Operand<'tcx>, Ty<'tcx>), . 942 ( 0.00%) BinaryOp(BinOp, Box<(Operand<'tcx>, Operand<'tcx>)>), 112 ( 0.00%) CheckedBinaryOp(BinOp, Box<(Operand<'tcx>, Operand<'tcx>)>), . . NullaryOp(NullOp, Ty<'tcx>), 12 ( 0.00%) UnaryOp(UnOp, Operand<'tcx>), . . /// Read the discriminant of an ADT. . /// . /// Undefined (i.e., no effort is made to make it defined, but there’s no reason why it cannot . /// be defined to return, say, a 0) if ADT is not an enum. 721 ( 0.00%) Discriminant(Place<'tcx>), . . /// Creates an aggregate value, like a tuple or struct. This is . /// only needed because we want to distinguish `dest = Foo { x: . /// ..., y: ... }` from `dest.x = ...; dest.y = ...;` in the case . /// that `Foo` has a destructor. These rvalues can be optimized . /// away after type-checking and before lowering. 4,939 ( 0.00%) Aggregate(Box>, Vec>), . . /// Transmutes a `*mut u8` into shallow-initialized `Box`. . /// . /// This is different a normal transmute because dataflow analysis will treat the box . /// as initialized but its content as uninitialized. . ShallowInitBox(Operand<'tcx>, Ty<'tcx>), . } . . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . static_assert_size!(Rvalue<'_>, 40); . 8,352 ( 0.00%) #[derive(Clone, Copy, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)] . pub enum CastKind { . Misc, . Pointer(PointerCast), . } . 15,420 ( 0.00%) #[derive(Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)] . pub enum AggregateKind<'tcx> { . /// The type is of the element 1,806 ( 0.00%) Array(Ty<'tcx>), . Tuple, . . /// The second field is the variant index. It's equal to 0 for struct . /// and union expressions. The fourth field is . /// active field number and is present only for union expressions . /// -- e.g., for a union expression `SomeUnion { c: .. }`, the . /// active field index would identity the field `c` 1,860 ( 0.00%) Adt(DefId, VariantIdx, SubstsRef<'tcx>, Option, Option), . 68 ( 0.00%) Closure(DefId, SubstsRef<'tcx>), . Generator(DefId, SubstsRef<'tcx>, hir::Movability), . } . . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . static_assert_size!(AggregateKind<'_>, 48); . 980 ( 0.00%) #[derive(Copy, Clone, Debug, PartialEq, PartialOrd, Eq, TyEncodable, TyDecodable, Hash, HashStable)] . pub enum BinOp { . /// The `+` operator (addition) . Add, . /// The `-` operator (subtraction) . Sub, . /// The `*` operator (multiplication) . Mul, . /// The `/` operator (division) -- line 2265 ---------------------------------------- -- line 2302 ---------------------------------------- . . impl BinOp { . pub fn is_checkable(self) -> bool { . use self::BinOp::*; . matches!(self, Add | Sub | Mul | Shl | Shr) . } . } . 18 ( 0.00%) #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)] . pub enum NullOp { . /// Returns the size of a value of that type . SizeOf, . /// Returns the minimum alignment of a type . AlignOf, . } . 68 ( 0.00%) #[derive(Copy, Clone, Debug, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable)] . pub enum UnOp { . /// The `!` operator for logical inversion . Not, . /// The `-` operator for negation . Neg, . } . . impl<'tcx> Debug for Rvalue<'tcx> { -- line 2326 ---------------------------------------- -- line 2485 ---------------------------------------- . . /////////////////////////////////////////////////////////////////////////// . /// Constants . /// . /// Two constants are equal if they are the same constant. Note that . /// this does not necessarily mean that they are `==` in Rust. In . /// particular, one must be wary of `NaN`! . 580,921 ( 0.01%) #[derive(Clone, Copy, PartialEq, TyEncodable, TyDecodable, Hash, HashStable)] . pub struct Constant<'tcx> { . pub span: Span, . . /// Optional user-given type: for something like . /// `collect::>`, this would be present and would . /// indicate that `Vec<_>` was explicitly specified. . /// . /// Needed for NLL to impose user-given type constraints. . pub user_ty: Option, . . pub literal: ConstantKind<'tcx>, . } . 1,691,659 ( 0.02%) #[derive(Clone, Copy, PartialEq, Eq, TyEncodable, TyDecodable, Hash, HashStable, Debug)] . #[derive(Lift)] . pub enum ConstantKind<'tcx> { . /// This constant came from the type system 7,900 ( 0.00%) Ty(&'tcx ty::Const<'tcx>), . /// This constant cannot go back into the type system, as it represents . /// something the type system cannot handle (e.g. pointers). . Val(interpret::ConstValue<'tcx>, Ty<'tcx>), . } . . impl<'tcx> Constant<'tcx> { 4,151,075 ( 0.06%) pub fn check_static_ptr(&self, tcx: TyCtxt<'_>) -> Option { 4,148,845 ( 0.06%) match self.literal.const_for_ty()?.val.try_to_scalar() { . Some(Scalar::Ptr(ptr, _size)) => match tcx.global_alloc(ptr.provenance) { . GlobalAlloc::Static(def_id) => { . assert!(!tcx.is_thread_local_static(def_id)); . Some(def_id) . } . _ => None, . }, . _ => None, . } 6,641,720 ( 0.09%) } . #[inline] . pub fn ty(&self) -> Ty<'tcx> { 4,542 ( 0.00%) self.literal.ty() . } . } . . impl<'tcx> From<&'tcx ty::Const<'tcx>> for ConstantKind<'tcx> { . #[inline] . fn from(ct: &'tcx ty::Const<'tcx>) -> Self { . Self::Ty(ct) . } . } . . impl<'tcx> ConstantKind<'tcx> { . /// Returns `None` if the constant is not trivially safe for use in the type system. . pub fn const_for_ty(&self) -> Option<&'tcx ty::Const<'tcx>> { 5,806,354 ( 0.08%) match self { . ConstantKind::Ty(c) => Some(c), . ConstantKind::Val(..) => None, . } 2,072,962 ( 0.03%) } . . pub fn ty(&self) -> Ty<'tcx> { 4,729,174 ( 0.07%) match self { . ConstantKind::Ty(c) => c.ty, . ConstantKind::Val(_, ty) => ty, . } 2,364,587 ( 0.03%) } . . #[inline] . pub fn try_to_value(self) -> Option> { 6 ( 0.00%) match self { 3 ( 0.00%) ConstantKind::Ty(c) => c.val.try_to_value(), . ConstantKind::Val(val, _) => Some(val), . } . } . . #[inline] . pub fn try_to_scalar(self) -> Option { . self.try_to_value()?.try_to_scalar() . } -- line 2570 ---------------------------------------- -- line 2586 ---------------------------------------- . . #[inline] . pub fn try_eval_bits( . &self, . tcx: TyCtxt<'tcx>, . param_env: ty::ParamEnv<'tcx>, . ty: Ty<'tcx>, . ) -> Option { 30 ( 0.00%) match self { 30 ( 0.00%) Self::Ty(ct) => ct.try_eval_bits(tcx, param_env, ty), . Self::Val(val, t) => { . assert_eq!(*t, ty); . let size = . tcx.layout_of(param_env.with_reveal_all_normalized(tcx).and(ty)).ok()?.size; . val.try_to_bits(size) . } . } . } -- line 2603 ---------------------------------------- -- line 2606 ---------------------------------------- . pub fn try_eval_bool(&self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> Option { . match self { . Self::Ty(ct) => ct.try_eval_bool(tcx, param_env), . Self::Val(val, _) => val.try_to_bool(), . } . } . . #[inline] 12 ( 0.00%) pub fn try_eval_usize(&self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> Option { 6 ( 0.00%) match self { 3 ( 0.00%) Self::Ty(ct) => ct.try_eval_usize(tcx, param_env), . Self::Val(val, _) => val.try_to_machine_usize(tcx), . } 9 ( 0.00%) } . } . . /// A collection of projections into user types. . /// . /// They are projections because a binding can occur a part of a . /// parent pattern that has been ascribed a type. . /// . /// Its a collection because there can be multiple type ascriptions on -- line 2627 ---------------------------------------- -- line 2646 ---------------------------------------- . /// following two projected types: . /// . /// * base: `S`, projection: `(base.0).1` . /// * base: `(i32, &'static str)`, projection: `base.1` . /// . /// The first will lead to the constraint `w: &'1 str` (for some . /// inferred region `'1`). The second will lead to the constraint `w: . /// &'static str`. 3,268 ( 0.00%) #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable)] . pub struct UserTypeProjections { 2,597 ( 0.00%) pub contents: Vec<(UserTypeProjection, Span)>, . } . . impl<'tcx> UserTypeProjections { 468 ( 0.00%) pub fn none() -> Self { 468 ( 0.00%) UserTypeProjections { contents: vec![] } 468 ( 0.00%) } . . pub fn is_empty(&self) -> bool { . self.contents.is_empty() 434 ( 0.00%) } . . pub fn projections_and_spans( . &self, . ) -> impl Iterator + ExactSizeIterator { . self.contents.iter() . } . . pub fn projections(&self) -> impl Iterator + ExactSizeIterator { . self.contents.iter().map(|&(ref user_type, _span)| user_type) . } . 324 ( 0.00%) pub fn push_projection(mut self, user_ty: &UserTypeProjection, span: Span) -> Self { 108 ( 0.00%) self.contents.push((user_ty.clone(), span)); 144 ( 0.00%) self 324 ( 0.00%) } . . fn map_projections( . mut self, . mut f: impl FnMut(UserTypeProjection) -> UserTypeProjection, . ) -> Self { . self.contents = self.contents.into_iter().map(|(proj, span)| (f(proj), span)).collect(); 1,796 ( 0.00%) self . } . . pub fn index(self) -> Self { . self.map_projections(|pat_ty_proj| pat_ty_proj.index()) . } . . pub fn subslice(self, from: u64, to: u64) -> Self { . self.map_projections(|pat_ty_proj| pat_ty_proj.subslice(from, to)) . } . 234 ( 0.00%) pub fn deref(self) -> Self { 312 ( 0.00%) self.map_projections(|pat_ty_proj| pat_ty_proj.deref()) 312 ( 0.00%) } . 736 ( 0.00%) pub fn leaf(self, field: Field) -> Self { 1,104 ( 0.00%) self.map_projections(|pat_ty_proj| pat_ty_proj.leaf(field)) 736 ( 0.00%) } . 935 ( 0.00%) pub fn variant(self, adt_def: &'tcx AdtDef, variant_index: VariantIdx, field: Field) -> Self { 1,683 ( 0.00%) self.map_projections(|pat_ty_proj| pat_ty_proj.variant(adt_def, variant_index, field)) 748 ( 0.00%) } . } . . /// Encodes the effect of a user-supplied type annotation on the . /// subcomponents of a pattern. The effect is determined by applying the . /// given list of proejctions to some underlying base type. Often, . /// the projection element list `projs` is empty, in which case this . /// directly encodes a type in `base`. But in the case of complex patterns with . /// subpatterns and bindings, we want to apply only a *part* of the type to a variable, -- line 2717 ---------------------------------------- -- line 2719 ---------------------------------------- . /// . /// Examples: . /// . /// * `let x: T = ...` -- here, the `projs` vector is empty. . /// . /// * `let (x, _): T = ...` -- here, the `projs` vector would contain . /// `field[0]` (aka `.0`), indicating that the type of `s` is . /// determined by finding the type of the `.0` field from `T`. 144 ( 0.00%) #[derive(Clone, Debug, TyEncodable, TyDecodable, Hash, HashStable, PartialEq)] . pub struct UserTypeProjection { . pub base: UserTypeAnnotationIndex, . pub projs: Vec, . } . . impl Copy for ProjectionKind {} . . impl UserTypeProjection { -- line 2735 ---------------------------------------- -- line 2870 ---------------------------------------- . fn start_node(&self) -> Self::Node { . START_BLOCK . } . } . . impl<'tcx> graph::WithSuccessors for Body<'tcx> { . #[inline] . fn successors(&self, node: Self::Node) -> >::Iter { 12,411 ( 0.00%) self.basic_blocks[node].terminator().successors().cloned() . } . } . . impl<'a, 'b> graph::GraphSuccessors<'b> for Body<'a> { . type Item = BasicBlock; . type Iter = iter::Cloned>; . } . -- line 2886 ---------------------------------------- -- line 2897 ---------------------------------------- . } . . /// `Location` represents the position of the start of the statement; or, if . /// `statement_index` equals the number of statements, then the start of the . /// terminator. . #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, HashStable)] . pub struct Location { . /// The block that the location is within. 42,527 ( 0.00%) pub block: BasicBlock, . 19,250 ( 0.00%) pub statement_index: usize, . } . . impl fmt::Debug for Location { . fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { . write!(fmt, "{:?}[{}]", self.block, self.statement_index) . } . } . -- line 2915 ---------------------------------------- -- line 2952 ---------------------------------------- . return true; . } . } . . false . } . . pub fn dominates(&self, other: Location, dominators: &Dominators) -> bool { 9,570 ( 0.00%) if self.block == other.block { 6,586 ( 0.00%) self.statement_index <= other.statement_index . } else { 5,968 ( 0.00%) dominators.is_dominated_by(other.block, self.block) . } 3,293 ( 0.00%) } . } 9,352,762 ( 0.13%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/tokentrees.rs -------------------------------------------------------------------------------- Ir -- line 8 ---------------------------------------- . }; . use rustc_ast_pretty::pprust::token_to_string; . use rustc_data_structures::fx::FxHashMap; . use rustc_errors::PResult; . use rustc_span::Span; . . impl<'a> StringReader<'a> { . pub(super) fn into_token_trees(self) -> (PResult<'a, TokenStream>, Vec) { 361 ( 0.00%) let mut tt_reader = TokenTreesReader { . string_reader: self, 19 ( 0.00%) token: Token::dummy(), . open_braces: Vec::new(), . unmatched_braces: Vec::new(), . matching_delim_spans: Vec::new(), . last_unclosed_found_span: None, . last_delim_empty_block_spans: FxHashMap::default(), . matching_block_spans: Vec::new(), . }; 19 ( 0.00%) let res = tt_reader.parse_all_token_trees(); 114 ( 0.00%) (res, tt_reader.unmatched_braces) . } . } . . struct TokenTreesReader<'a> { . string_reader: StringReader<'a>, . token: Token, . /// Stack of open delimiters and their spans. Used for error message. . open_braces: Vec<(token::DelimToken, Span)>, -- line 35 ---------------------------------------- -- line 43 ---------------------------------------- . last_delim_empty_block_spans: FxHashMap, . /// Collect the spans of braces (Open, Close). Used only . /// for detecting if blocks are empty and only braces. . matching_block_spans: Vec<(Span, Span)>, . } . . impl<'a> TokenTreesReader<'a> { . // Parse a stream of tokens into a list of `TokenTree`s, up to an `Eof`. 152 ( 0.00%) fn parse_all_token_trees(&mut self) -> PResult<'a, TokenStream> { . let mut buf = TokenStreamBuilder::default(); . . self.bump(); 8,414 ( 0.00%) while self.token != token::Eof { 33,504 ( 0.00%) buf.push(self.parse_token_tree()?); . } . . Ok(buf.into_token_stream()) 171 ( 0.00%) } . . // Parse a stream of tokens into a list of `TokenTree`s, up to a `CloseDelim`. . fn parse_token_trees_until_close_delim(&mut self) -> TokenStream { . let mut buf = TokenStreamBuilder::default(); . loop { 602,032 ( 0.01%) if let token::CloseDelim(..) = self.token.kind { . return buf.into_token_stream(); . } . 1,488,255 ( 0.02%) match self.parse_token_tree() { 2,678,859 ( 0.04%) Ok(tree) => buf.push(tree), . Err(mut e) => { . e.emit(); . return buf.into_token_stream(); . } . } . } . } . 2,716,551 ( 0.04%) fn parse_token_tree(&mut self) -> PResult<'a, TreeAndSpacing> { 603,678 ( 0.01%) let sm = self.string_reader.sess.source_map(); . 2,703,091 ( 0.04%) match self.token.kind { . token::Eof => { . let msg = "this file contains an unclosed delimiter"; . let mut err = . self.string_reader.sess.span_diagnostic.struct_span_err(self.token.span, msg); . for &(_, sp) in &self.open_braces { . err.span_label(sp, "unclosed delimiter"); . self.unmatched_braces.push(UnmatchedBrace { . expected_delim: token::DelimToken::Brace, -- line 91 ---------------------------------------- -- line 113 ---------------------------------------- . err.span_label( . *close_sp, . "...as it matches this but it has different indentation", . ); . } . } . Err(err) . } 3,365 ( 0.00%) token::OpenDelim(delim) => { . // The span for beginning of the delimited section 3,365 ( 0.00%) let pre_span = self.token.span; . . // Parse the open delimiter. 23,555 ( 0.00%) self.open_braces.push((delim, self.token.span)); . self.bump(); . . // Parse the token trees within the delimiters. . // We stop at any delimiter so we can try to recover if the user . // uses an incorrect delimiter. 3,365 ( 0.00%) let tts = self.parse_token_trees_until_close_delim(); . . // Expand to cover the entire delimited token tree 16,825 ( 0.00%) let delim_span = DelimSpan::from_pair(pre_span, self.token.span); . 6,730 ( 0.00%) match self.token.kind { . // Correct delimiter. 6,730 ( 0.00%) token::CloseDelim(d) if d == delim => { . let (open_brace, open_brace_span) = self.open_braces.pop().unwrap(); 6,730 ( 0.00%) let close_brace_span = self.token.span; . 10,095 ( 0.00%) if tts.is_empty() { 1,995 ( 0.00%) let empty_block_span = open_brace_span.to(close_brace_span); 2,660 ( 0.00%) if !sm.is_multiline(empty_block_span) { . // Only track if the block is in the form of `{}`, otherwise it is . // likely that it was written on purpose. . self.last_delim_empty_block_spans.insert(delim, empty_block_span); . } . } . . //only add braces 13,460 ( 0.00%) if let (DelimToken::Brace, DelimToken::Brace) = (open_brace, delim) { . self.matching_block_spans.push((open_brace_span, close_brace_span)); . } . 3,365 ( 0.00%) if self.open_braces.is_empty() { . // Clear up these spans to avoid suggesting them as we've found . // properly matched delimiters so far for an entire block. . self.matching_delim_spans.clear(); . } else { . self.matching_delim_spans.push(( . open_brace, . open_brace_span, . close_brace_span, -- line 165 ---------------------------------------- -- line 218 ---------------------------------------- . token::Eof => { . // Silently recover, the EOF token will be seen again . // and an error emitted then. Thus we don't pop from . // self.open_braces here. . } . _ => {} . } . 23,555 ( 0.00%) Ok(TokenTree::Delimited(delim_span, delim, tts).into()) . } . token::CloseDelim(delim) => { . // An unexpected closing delimiter (i.e., there is no . // matching opening delimiter). . let token_str = token_to_string(&self.token); . let msg = format!("unexpected closing delimiter: `{}`", token_str); . let mut err = . self.string_reader.sess.span_diagnostic.struct_span_err(self.token.span, &msg); -- line 234 ---------------------------------------- -- line 253 ---------------------------------------- . err.span_label(parent.1, "...matches this closing brace"); . } . } . . err.span_label(self.token.span, "unexpected closing delimiter"); . Err(err) . } . _ => { 1,492,370 ( 0.02%) let tt = TokenTree::Token(self.token.take()); . let mut spacing = self.bump(); 596,948 ( 0.01%) if !self.token.is_op() { . spacing = Alone; . } 1,790,844 ( 0.03%) Ok((tt, spacing)) . } . } 2,414,712 ( 0.03%) } . . fn bump(&mut self) -> Spacing { 2,730,125 ( 0.04%) let (spacing, token) = self.string_reader.next_token(); 1,509,366 ( 0.02%) self.token = token; . spacing . } . } . 3,365 ( 0.00%) #[derive(Default)] . struct TokenStreamBuilder { . buf: Vec, . } . . impl TokenStreamBuilder { 3,923,907 ( 0.06%) fn push(&mut self, (tree, joint): TreeAndSpacing) { 2,370,985 ( 0.03%) if let Some((TokenTree::Token(prev_token), Joint)) = self.buf.last() { 289,504 ( 0.00%) if let TokenTree::Token(token) = &tree { 440,052 ( 0.01%) if let Some(glued) = prev_token.glue(token) { . self.buf.pop(); 17,388 ( 0.00%) self.buf.push((TokenTree::Token(glued), joint)); . return; . } . } . } 1,501,950 ( 0.02%) self.buf.push((tree, joint)) 2,414,712 ( 0.03%) } . . fn into_token_stream(self) -> TokenStream { 33,821 ( 0.00%) TokenStream::new(self.buf) . } . } 638,048 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/place.rs -------------------------------------------------------------------------------- Ir -- line 14 ---------------------------------------- . use rustc_target::abi::{HasDataLayout, Size, VariantIdx, Variants}; . . use super::{ . alloc_range, mir_assign_valid_types, AllocId, AllocRef, AllocRefMut, CheckInAllocMsg, . ConstAlloc, ImmTy, Immediate, InterpCx, InterpResult, LocalValue, Machine, MemoryKind, OpTy, . Operand, Pointer, PointerArithmetic, Provenance, Scalar, ScalarMaybeUninit, . }; . 71,964 ( 0.00%) #[derive(Copy, Clone, Hash, PartialEq, Eq, HashStable, Debug)] . /// Information required for the sound usage of a `MemPlace`. . pub enum MemPlaceMeta { . /// The unsized payload (e.g. length for slices or vtable pointer for trait objects). . Meta(Scalar), . /// `Sized` types or unsized `extern type` . None, . /// The address of this place may not be taken. This protects the `MemPlace` from coming from . /// a ZST Operand without a backing allocation and being converted to an integer address. This -- line 30 ---------------------------------------- -- line 33 ---------------------------------------- . Poison, . } . . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . rustc_data_structures::static_assert_size!(MemPlaceMeta, 24); . . impl MemPlaceMeta { . pub fn unwrap_meta(self) -> Scalar { 20,114 ( 0.00%) match self { 14,220 ( 0.00%) Self::Meta(s) => s, . Self::None | Self::Poison => { . bug!("expected wide pointer extra data (e.g. slice length or trait object vtable)") . } . } . } . fn has_meta(self) -> bool { 143,147 ( 0.00%) match self { . Self::Meta(_) => true, . Self::None | Self::Poison => false, . } . } . } . . #[derive(Copy, Clone, Hash, PartialEq, Eq, HashStable, Debug)] . pub struct MemPlace { . /// The pointer can be a pure integer, with the `None` tag. 196 ( 0.00%) pub ptr: Pointer>, 392 ( 0.00%) pub align: Align, . /// Metadata for unsized places. Interpretation is up to the type. . /// Must not be present for sized types, but can be missing for unsized types . /// (e.g., `extern type`). . pub meta: MemPlaceMeta, . } . . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . rustc_data_structures::static_assert_size!(MemPlace, 48); -- line 68 ---------------------------------------- -- line 93 ---------------------------------------- . type Target = Place; . #[inline(always)] . fn deref(&self) -> &Place { . &self.place . } . } . . /// A MemPlace with its layout. Constructing it is only possible in this module. 1,372 ( 0.00%) #[derive(Copy, Clone, Hash, Eq, PartialEq, Debug)] . pub struct MPlaceTy<'tcx, Tag: Provenance = AllocId> { . mplace: MemPlace, . pub layout: TyAndLayout<'tcx>, . } . . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . rustc_data_structures::static_assert_size!(MPlaceTy<'_>, 64); . -- line 109 ---------------------------------------- -- line 113 ---------------------------------------- . fn deref(&self) -> &MemPlace { . &self.mplace . } . } . . impl<'tcx, Tag: Provenance> From> for PlaceTy<'tcx, Tag> { . #[inline(always)] . fn from(mplace: MPlaceTy<'tcx, Tag>) -> Self { 11,656 ( 0.00%) PlaceTy { place: Place::Ptr(mplace.mplace), layout: mplace.layout } . } . } . . impl MemPlace { . #[inline(always)] . pub fn from_ptr(ptr: Pointer>, align: Align) -> Self { . MemPlace { ptr, align, meta: MemPlaceMeta::None } . } -- line 129 ---------------------------------------- -- line 132 ---------------------------------------- . pub fn map_provenance(self, f: impl FnOnce(Option) -> Option) -> Self { . MemPlace { ptr: self.ptr.map_provenance(f), ..self } . } . . /// Turn a mplace into a (thin or wide) pointer, as a reference, pointing to the same space. . /// This is the inverse of `ref_to_mplace`. . #[inline(always)] . pub fn to_ref(self, cx: &impl HasDataLayout) -> Immediate { 13,975 ( 0.00%) match self.meta { 9,625 ( 0.00%) MemPlaceMeta::None => Immediate::from(Scalar::from_maybe_pointer(self.ptr, cx)), . MemPlaceMeta::Meta(meta) => { 175 ( 0.00%) Immediate::ScalarPair(Scalar::from_maybe_pointer(self.ptr, cx).into(), meta.into()) . } . MemPlaceMeta::Poison => bug!( . "MPlaceTy::dangling may never be used to produce a \ . place that will have the address of its pointee taken" . ), . } . } . -- line 151 ---------------------------------------- -- line 163 ---------------------------------------- . }) . } . } . . impl<'tcx, Tag: Provenance> MPlaceTy<'tcx, Tag> { . /// Produces a MemPlace that works for ZST but nothing else . #[inline] . pub fn dangling(layout: TyAndLayout<'tcx>) -> Self { 8 ( 0.00%) let align = layout.align.abi; . let ptr = Pointer::new(None, Size::from_bytes(align.bytes())); // no provenance, absolute address . // `Poison` this to make sure that the pointer value `ptr` is never observable by the program. . MPlaceTy { mplace: MemPlace { ptr, align, meta: MemPlaceMeta::Poison }, layout } . } . . #[inline] . pub fn offset( . &self, . offset: Size, . meta: MemPlaceMeta, . layout: TyAndLayout<'tcx>, . cx: &impl HasDataLayout, . ) -> InterpResult<'tcx, Self> { 1,550,136 ( 0.02%) Ok(MPlaceTy { mplace: self.mplace.offset(offset, meta, cx)?, layout }) . } . . #[inline] . pub fn from_aligned_ptr(ptr: Pointer>, layout: TyAndLayout<'tcx>) -> Self { 544 ( 0.00%) MPlaceTy { mplace: MemPlace::from_ptr(ptr, layout.align.abi), layout } . } . . #[inline] 2,953 ( 0.00%) pub(super) fn len(&self, cx: &impl HasDataLayout) -> InterpResult<'tcx, u64> { 18,922 ( 0.00%) if self.layout.is_unsized() { . // We need to consult `meta` metadata 29,508 ( 0.00%) match self.layout.ty.kind() { 10,053 ( 0.00%) ty::Slice(..) | ty::Str => self.mplace.meta.unwrap_meta().to_machine_usize(cx), . _ => bug!("len not supported on unsized type {:?}", self.layout.ty), . } . } else { . // Go through the layout. There are lots of types that support a length, . // e.g., SIMD types. (But not all repr(simd) types even have FieldsShape::Array!) 20 ( 0.00%) match self.layout.fields { 20 ( 0.00%) FieldsShape::Array { count, .. } => Ok(count), . _ => bug!("len not supported on sized type {:?}", self.layout.ty), . } . } 5,906 ( 0.00%) } . . #[inline] . pub(super) fn vtable(&self) -> Scalar { . match self.layout.ty.kind() { . ty::Dynamic(..) => self.mplace.meta.unwrap_meta(), . _ => bug!("vtable not supported on type {:?}", self.layout.ty), . } . } -- line 217 ---------------------------------------- -- line 218 ---------------------------------------- . } . . // These are defined here because they produce a place. . impl<'tcx, Tag: Provenance> OpTy<'tcx, Tag> { . #[inline(always)] . /// Note: do not call `as_ref` on the resulting place. This function should only be used to . /// read from the resulting mplace, not to get its address back. . pub fn try_as_mplace(&self) -> Result, ImmTy<'tcx, Tag>> { 306,398 ( 0.00%) match **self { 134,423 ( 0.00%) Operand::Indirect(mplace) => Ok(MPlaceTy { mplace, layout: self.layout }), 8 ( 0.00%) Operand::Immediate(_) if self.layout.is_zst() => Ok(MPlaceTy::dangling(self.layout)), 992,580 ( 0.01%) Operand::Immediate(imm) => Err(ImmTy::from_immediate(imm, self.layout)), . } . } . . #[inline(always)] . /// Note: do not call `as_ref` on the resulting place. This function should only be used to . /// read from the resulting mplace, not to get its address back. . pub fn assert_mem_place(&self) -> MPlaceTy<'tcx, Tag> { . self.try_as_mplace().unwrap() -- line 237 ---------------------------------------- -- line 263 ---------------------------------------- . M: Machine<'mir, 'tcx, PointerTag = Tag>, . { . /// Take a value, which represents a (thin or wide) reference, and make it a place. . /// Alignment is just based on the type. This is the inverse of `MemPlace::to_ref()`. . /// . /// Only call this if you are sure the place is "valid" (aligned and inbounds), or do not . /// want to ever use the place for memory access! . /// Generally prefer `deref_operand`. 44,220 ( 0.00%) pub fn ref_to_mplace( . &self, . val: &ImmTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> { . let pointee_type = 13,266 ( 0.00%) val.layout.ty.builtin_deref(true).expect("`ref_to_mplace` called on non-ptr type").ty; 13,266 ( 0.00%) let layout = self.layout_of(pointee_type)?; 22,110 ( 0.00%) let (ptr, meta) = match **val { 2,764 ( 0.00%) Immediate::Scalar(ptr) => (ptr, MemPlaceMeta::None), 21,280 ( 0.00%) Immediate::ScalarPair(ptr, meta) => (ptr, MemPlaceMeta::Meta(meta.check_init()?)), . }; . . let mplace = MemPlace { . ptr: self.scalar_to_ptr(ptr.check_init()?), . // We could use the run-time alignment here. For now, we do not, because . // the point of tracking the alignment here is to make sure that the *static* . // alignment information emitted with the loads is correct. The run-time . // alignment can only be more restrictive. 4,422 ( 0.00%) align: layout.align.abi, . meta, . }; 75,174 ( 0.00%) Ok(MPlaceTy { mplace, layout }) 39,798 ( 0.00%) } . . /// Take an operand, representing a pointer, and dereference it to a place -- that . /// will always be a MemPlace. Lives in `place.rs` because it creates a place. 8,052 ( 0.00%) pub fn deref_operand( . &self, . src: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> { 2,196 ( 0.00%) let val = self.read_immediate(src)?; . trace!("deref to {} on {:?}", val.layout.ty, *val); 1,464 ( 0.00%) let mplace = self.ref_to_mplace(&val)?; 3,660 ( 0.00%) self.check_mplace_access(mplace, CheckInAllocMsg::DerefTest)?; 8,052 ( 0.00%) Ok(mplace) 6,588 ( 0.00%) } . . #[inline] . pub(super) fn get_alloc( . &self, . place: &MPlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, Option>> { . assert!(!place.layout.is_unsized()); 4,073 ( 0.00%) assert!(!place.meta.has_meta()); 4,073 ( 0.00%) let size = place.layout.size; 36,657 ( 0.00%) self.memory.get(place.ptr, size, place.align) . } . . #[inline] . pub(super) fn get_alloc_mut( . &mut self, . place: &MPlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, Option>> { 139,078 ( 0.00%) assert!(!place.layout.is_unsized()); 139,072 ( 0.00%) assert!(!place.meta.has_meta()); 139,072 ( 0.00%) let size = place.layout.size; 834,432 ( 0.01%) self.memory.get_mut(place.ptr, size, place.align) . } . . /// Check if this mplace is dereferenceable and sufficiently aligned. . fn check_mplace_access( . &self, . mplace: MPlaceTy<'tcx, M::PointerTag>, . msg: CheckInAllocMsg, . ) -> InterpResult<'tcx> { . let (size, align) = self . .size_and_align_of_mplace(&mplace)? 732 ( 0.00%) .unwrap_or((mplace.layout.size, mplace.layout.align.abi)); 732 ( 0.00%) assert!(mplace.mplace.align <= align, "dynamic alignment less strict than static one?"); 732 ( 0.00%) let align = M::enforce_alignment(&self.memory.extra).then_some(align); 2,196 ( 0.00%) self.memory.check_ptr_access_align(mplace.ptr, size, align.unwrap_or(Align::ONE), msg)?; . Ok(()) . } . . /// Offset a pointer to project to a field of a struct/union. Unlike `place_field`, this is . /// always possible without allocating, so it can take `&self`. Also return the field's layout. . /// This supports both struct and array fields. . /// . /// This also works for arrays, but then the `usize` index type is restricting. . /// For indexing into arrays, use `mplace_index`. . #[inline(always)] . pub fn mplace_field( . &self, . base: &MPlaceTy<'tcx, M::PointerTag>, . field: usize, . ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> { 568,865 ( 0.01%) let offset = base.layout.fields.offset(field); 426,837 ( 0.01%) let field_layout = base.layout.field(self, field); . . // Offset may need adjustment for unsized fields. 713,373 ( 0.01%) let (meta, offset) = if field_layout.is_unsized() { . // Re-use parent metadata to determine dynamic field layout. . // With custom DSTS, this *will* execute user-defined code, but the same . // happens at run-time so that's okay. . match self.size_and_align_of(&base.meta, &field_layout)? { . Some((_, align)) => (base.meta, offset.align_to(align)), . None => { . // For unsized types with an extern type tail we perform no adjustments. . // NOTE: keep this in sync with `PlaceRef::project_field` in the codegen backend. -- line 369 ---------------------------------------- -- line 374 ---------------------------------------- . } else { . // base.meta could be present; we might be accessing a sized field of an unsized . // struct. . (MemPlaceMeta::None, offset) . }; . . // We do not look at `base.layout.align` nor `field_layout.align`, unlike . // codegen -- mostly to see if we can get away with that 3,240 ( 0.00%) base.offset(offset, meta, field_layout, self) . } . . /// Index into an array. . #[inline(always)] . pub fn mplace_index( . &self, . base: &MPlaceTy<'tcx, M::PointerTag>, . index: u64, -- line 390 ---------------------------------------- -- line 409 ---------------------------------------- . "`mplace_index` called on non-array type {:?}", . base.layout.ty . ), . } . } . . // Iterates over all fields of an array. Much more efficient than doing the . // same by repeatedly calling `mplace_array`. 29,530 ( 0.00%) pub(super) fn mplace_array_fields<'a>( . &self, . base: &'a MPlaceTy<'tcx, Tag>, . ) -> InterpResult<'tcx, impl Iterator>> + 'a> . { 11,812 ( 0.00%) let len = base.len(self)?; // also asserts that we have a type where this makes sense 8,859 ( 0.00%) let stride = match base.layout.fields { 2,953 ( 0.00%) FieldsShape::Array { stride, .. } => stride, . _ => span_bug!(self.cur_span(), "mplace_array_fields: expected an array layout"), . }; 5,906 ( 0.00%) let layout = base.layout.field(self, 0); 2,953 ( 0.00%) let dl = &self.tcx.data_layout; . // `Size` multiplication 859,699 ( 0.01%) Ok((0..len).map(move |i| base.offset(stride * i, MemPlaceMeta::None, layout, dl))) 26,577 ( 0.00%) } . . fn mplace_subslice( . &self, . base: &MPlaceTy<'tcx, M::PointerTag>, . from: u64, . to: u64, . from_end: bool, . ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> { -- line 439 ---------------------------------------- -- line 476 ---------------------------------------- . } . . pub(crate) fn mplace_downcast( . &self, . base: &MPlaceTy<'tcx, M::PointerTag>, . variant: VariantIdx, . ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> { . // Downcasts only change the layout 2 ( 0.00%) assert!(!base.meta.has_meta()); 9 ( 0.00%) Ok(MPlaceTy { layout: base.layout.for_variant(self, variant), ..*base }) . } . . /// Project into an mplace . pub(super) fn mplace_projection( . &self, . base: &MPlaceTy<'tcx, M::PointerTag>, . proj_elem: mir::PlaceElem<'tcx>, . ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> { -- line 493 ---------------------------------------- -- line 542 ---------------------------------------- . assert_eq!(layout.size, base.layout.size); . Ok((MPlaceTy { layout, ..*base }, len)) . } . . /// Gets the place of a field inside the place, and also the field's type. . /// Just a convenience function, but used quite a bit. . /// This is the only projection that might have a side-effect: We cannot project . /// into the field of a local `ScalarPair`, we have to first allocate it. 1,391,600 ( 0.02%) pub fn place_field( . &mut self, . base: &PlaceTy<'tcx, M::PointerTag>, . field: usize, . ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> { . // FIXME: We could try to be smarter and avoid allocation for fields that span the . // entire place. 139,154 ( 0.00%) let mplace = self.force_allocation(base)?; 1,669,848 ( 0.02%) Ok(self.mplace_field(&mplace, field)?.into()) 1,113,280 ( 0.02%) } . . pub fn place_index( . &mut self, . base: &PlaceTy<'tcx, M::PointerTag>, . index: u64, . ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> { . let mplace = self.force_allocation(base)?; . Ok(self.mplace_index(&mplace, index)?.into()) -- line 567 ---------------------------------------- -- line 568 ---------------------------------------- . } . . pub fn place_downcast( . &self, . base: &PlaceTy<'tcx, M::PointerTag>, . variant: VariantIdx, . ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> { . // Downcast just changes the layout 608 ( 0.00%) Ok(match base.place { . Place::Ptr(mplace) => { . self.mplace_downcast(&MPlaceTy { mplace, layout: base.layout }, variant)?.into() . } . Place::Local { .. } => { 525 ( 0.00%) let layout = base.layout.for_variant(self, variant); 76 ( 0.00%) PlaceTy { layout, ..*base } . } . }) . } . . /// Projects into a place. . pub fn place_projection( . &mut self, . base: &PlaceTy<'tcx, M::PointerTag>, . &proj_elem: &mir::ProjectionElem>, . ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> { . use rustc_middle::mir::ProjectionElem::*; 27,980 ( 0.00%) Ok(match proj_elem { 5,245 ( 0.00%) Field(field, _) => self.place_field(base, field.index())?, . Downcast(_, variant) => self.place_downcast(base, variant)?, 5,856 ( 0.00%) Deref => self.deref_operand(&self.place_to_op(base)?)?.into(), . // For the other variants, we have to force an allocation. . // This matches `operand_projection`. . Subslice { .. } | ConstantIndex { .. } | Index(_) => { . let mplace = self.force_allocation(base)?; . self.mplace_projection(&mplace, proj_elem)?.into() . } . }) . } -- line 605 ---------------------------------------- -- line 611 ---------------------------------------- . base: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::PointerTag>, u64)> { . let mplace = self.force_allocation(base)?; . self.mplace_to_simd(&mplace) . } . . /// Computes a place. You should only use this if you intend to write into this . /// place; for reading, a more efficient alternative is `eval_place_for_read`. 61,304 ( 0.00%) pub fn eval_place( . &mut self, . place: mir::Place<'tcx>, . ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> { 37,990 ( 0.00%) let mut place_ty = PlaceTy { . // This works even for dead/uninitialized locals; we check further when writing . place: Place::Local { frame: self.frame_idx(), local: place.local }, . layout: self.layout_of_local(self.frame(), place.local, None)?, . }; . 3,788 ( 0.00%) for elem in place.projection.iter() { 1,851 ( 0.00%) place_ty = self.place_projection(&place_ty, &elem)? . } . . trace!("{:?}", self.dump_place(place_ty.place)); . // Sanity-check the type we ended up with. . debug_assert!(mir_assign_valid_types( . *self.tcx, . self.param_env, . self.layout_of(self.subst_from_current_frame_and_normalize_erasing_regions( . place.ty(&self.frame().body.local_decls, *self.tcx).ty . )?)?, . place_ty.layout, . )); 135,990 ( 0.00%) Ok(place_ty) 61,304 ( 0.00%) } . . /// Write an immediate to a place . #[inline(always)] . pub fn write_immediate( . &mut self, . src: Immediate, . dest: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx> { 21,527 ( 0.00%) self.write_immediate_no_validate(src, dest)?; . . if M::enforce_validity(self) { . // Data got changed, better make sure it matches the type! . self.validate_operand(&self.place_to_op(dest)?)?; . } . . Ok(()) . } -- line 661 ---------------------------------------- -- line 672 ---------------------------------------- . . /// Write a pointer to a place . #[inline(always)] . pub fn write_pointer( . &mut self, . ptr: impl Into>>, . dest: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx> { 126 ( 0.00%) self.write_scalar(Scalar::from_maybe_pointer(ptr.into(), self), dest) . } . . /// Write an immediate to a place. . /// If you use this you are responsible for validating that things got copied at the . /// right type. 141,048 ( 0.00%) fn write_immediate_no_validate( . &mut self, . src: Immediate, . dest: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx> { . if cfg!(debug_assertions) { . // This is a very common path, avoid some checks in release mode . assert!(!dest.layout.is_unsized(), "Cannot write unsized data"); . match src { -- line 694 ---------------------------------------- -- line 705 ---------------------------------------- . // FIXME: Can we check anything here? . } . } . } . trace!("write_immediate: {:?} <- {:?}: {}", *dest, src, dest.layout.ty); . . // See if we can avoid an allocation. This is the counterpart to `try_read_immediate`, . // but not factored as a separate function. 283,740 ( 0.00%) let mplace = match dest.place { 6,323 ( 0.00%) Place::Local { frame, local } => { 2,882 ( 0.00%) match M::access_local_mut(self, frame, local)? { . Ok(local) => { . // Local can be updated in-place. 27,052 ( 0.00%) *local = LocalValue::Live(Operand::Immediate(src)); . return Ok(()); . } . Err(mplace) => { . // The local is in memory, go on below. . mplace . } . } . } 834,381 ( 0.01%) Place::Ptr(mplace) => mplace, // already referring to memory . }; 1,251,570 ( 0.02%) let dest = MPlaceTy { mplace, layout: dest.layout }; . . // This is already in memory, write there. 1,529,487 ( 0.02%) self.write_immediate_to_mplace_no_validate(src, &dest) 282,096 ( 0.00%) } . . /// Write an immediate to memory. . /// If you use this you are responsible for validating that things got copied at the . /// right type. 1,390,720 ( 0.02%) fn write_immediate_to_mplace_no_validate( . &mut self, . value: Immediate, . dest: &MPlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx> { . // Note that it is really important that the type here is the right one, and matches the . // type things are read at. In case `src_val` is a `ScalarPair`, we don't do any magic here . // to handle padding properly, which is only correct if we never look at this data with the . // wrong type. . . // Invalid places are a thing: the return place of a diverging function 139,072 ( 0.00%) let tcx = *self.tcx; 278,144 ( 0.00%) let mut alloc = match self.get_alloc_mut(dest)? { 695,345 ( 0.01%) Some(a) => a, . None => return Ok(()), // zero-sized access . }; . . // FIXME: We should check that there are dest.layout.size many bytes available in . // memory. The code below is not sufficient, with enough padding it might not . // cover all the bytes! 278,138 ( 0.00%) match value { . Immediate::Scalar(scalar) => { 276,798 ( 0.00%) match dest.layout.abi { . Abi::Scalar(_) => {} // fine . _ => span_bug!( . self.cur_span(), . "write_immediate_to_mplace: invalid Scalar layout: {:#?}", . dest.layout . ), . } 1,245,591 ( 0.02%) alloc.write_scalar(alloc_range(Size::ZERO, dest.layout.size), scalar) . } . Immediate::ScalarPair(a_val, b_val) => { . // We checked `ptr_align` above, so all fields will have the alignment they need. . // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`, . // which `ptr.offset(b_offset)` cannot possibly fail to satisfy. 1,340 ( 0.00%) let (a, b) = match dest.layout.abi { 2,016 ( 0.00%) Abi::ScalarPair(a, b) => (a.value, b.value), . _ => span_bug!( . self.cur_span(), . "write_immediate_to_mplace: invalid ScalarPair layout: {:#?}", . dest.layout . ), . }; . let (a_size, b_size) = (a.size(&tcx), b.size(&tcx)); . let b_offset = a_size.align_to(b.align(&tcx).abi); . . // It is tempting to verify `b_offset` against `layout.fields.offset(1)`, . // but that does not work: We could be a newtype around a pair, then the . // fields do not match the `ScalarPair` components. . 6,700 ( 0.00%) alloc.write_scalar(alloc_range(Size::ZERO, a_size), a_val)?; 5,360 ( 0.00%) alloc.write_scalar(alloc_range(b_offset, b_size), b_val) . } . } 1,112,576 ( 0.02%) } . . /// Copies the data from an operand to a place. This does not support transmuting! . /// Use `copy_op_transmute` if the layouts could disagree. . #[inline(always)] . pub fn copy_op( . &mut self, . src: &OpTy<'tcx, M::PointerTag>, . dest: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx> { 834,638 ( 0.01%) self.copy_op_no_validate(src, dest)?; . . if M::enforce_validity(self) { . // Data got changed, better make sure it matches the type! . self.validate_operand(&self.place_to_op(dest)?)?; . } . . Ok(()) . } . . /// Copies the data from an operand to a place. This does not support transmuting! . /// Use `copy_op_transmute` if the layouts could disagree. . /// Also, if you use this you are responsible for validating that things get copied at the . /// right type. 1,113,072 ( 0.02%) fn copy_op_no_validate( . &mut self, . src: &OpTy<'tcx, M::PointerTag>, . dest: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx> { . // We do NOT compare the types for equality, because well-typed code can . // actually "transmute" `&mut T` to `&T` in an assignment without a cast. 2,512,860 ( 0.04%) if !mir_assign_valid_types(*self.tcx, self.param_env, src.layout, dest.layout) { . span_bug!( . self.cur_span(), . "type mismatch when copying!\nsrc: {:?},\ndest: {:?}", . src.layout.ty, . dest.layout.ty, . ); . } . . // Let us see if the layout is simple so we take a shortcut, avoid force_allocation. 698,486 ( 0.01%) let src = match self.try_read_immediate(src)? { . Ok(src_val) => { 139,753 ( 0.00%) assert!(!src.layout.is_unsized(), "cannot have unsized immediates"); . // Yay, we got a value that we can write directly. . // FIXME: Add a check to make sure that if `src` is indirect, . // it does not overlap with `dest`. 1,807,559 ( 0.03%) return self.write_immediate_no_validate(*src_val, dest); . } 744 ( 0.00%) Err(mplace) => mplace, . }; . // Slow path, this does not fit into an immediate. Just memcpy. . trace!("copy_op: {:?} <- {:?}: {}", *dest, src, dest.layout.ty); . . // This interprets `src.meta` with the `dest` local's layout, if an unsized local . // is being initialized! 1,209 ( 0.00%) let (dest, size) = self.force_allocation_maybe_sized(dest, src.meta)?; . let size = size.unwrap_or_else(|| { 279 ( 0.00%) assert!( . !dest.layout.is_unsized(), . "Cannot copy into already initialized unsized place" . ); 93 ( 0.00%) dest.layout.size . }); 93 ( 0.00%) assert_eq!(src.meta, dest.meta, "Can only copy between equally-sized instances"); . 93 ( 0.00%) self.memory 279 ( 0.00%) .copy(src.ptr, src.align, dest.ptr, dest.align, size, /*nonoverlapping*/ true) 1,113,072 ( 0.02%) } . . /// Copies the data from an operand to a place. The layouts may disagree, but they must . /// have the same size. 1,872 ( 0.00%) pub fn copy_op_transmute( . &mut self, . src: &OpTy<'tcx, M::PointerTag>, . dest: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx> { 4,212 ( 0.00%) if mir_assign_valid_types(*self.tcx, self.param_env, src.layout, dest.layout) { . // Fast path: Just use normal `copy_op` . return self.copy_op(src, dest); . } . // We still require the sizes to match. . if src.layout.size != dest.layout.size { . // FIXME: This should be an assert instead of an error, but if we transmute within an . // array length computation, `typeck` may not have yet been run and errored out. In fact . // most likey we *are* running `typeck` right now. Investigate whether we can bail out -- line 878 ---------------------------------------- -- line 916 ---------------------------------------- . /// Ensures that a place is in memory, and returns where it is. . /// If the place currently refers to a local that doesn't yet have a matching allocation, . /// create such an allocation. . /// This is essentially `force_to_memplace`. . /// . /// This supports unsized types and returns the computed size to avoid some . /// redundant computation when copying; use `force_allocation` for a simpler, sized-only . /// version. 1,265,652 ( 0.02%) pub fn force_allocation_maybe_sized( . &mut self, . place: &PlaceTy<'tcx, M::PointerTag>, . meta: MemPlaceMeta, . ) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::PointerTag>, Option)> { 1,406,232 ( 0.02%) let (mplace, size) = match place.place { 140,589 ( 0.00%) Place::Local { frame, local } => { 280,773 ( 0.00%) match M::access_local_mut(self, frame, local)? { 9,999 ( 0.00%) Ok(&mut local_val) => { . // We need to make an allocation. . . // We need the layout of the local. We can NOT use the layout we got, . // that might e.g., be an inner field of a struct with `Scalar` layout, . // that has different alignment than the outer field. . let local_layout = 6,677 ( 0.00%) self.layout_of_local(&self.stack()[frame], local, None)?; . // We also need to support unsized types, and hence cannot use `allocate`. 4,070 ( 0.00%) let (size, align) = self . .size_and_align_of(&meta, &local_layout)? . .expect("Cannot allocate for non-dyn-sized type"); 7,403 ( 0.00%) let ptr = self.memory.allocate(size, align, MemoryKind::Stack)?; . let mplace = MemPlace { ptr: ptr.into(), align, meta }; 5,555 ( 0.00%) if let LocalValue::Live(Operand::Immediate(value)) = local_val { . // Preserve old value. . // We don't have to validate as we can assume the local . // was already valid for its type. . let mplace = MPlaceTy { mplace, layout: local_layout }; . self.write_immediate_to_mplace_no_validate(value, &mplace)?; . } . // Now we can call `access_mut` again, asserting it goes well, . // and actually overwrite things. 19,987 ( 0.00%) *M::access_local_mut(self, frame, local).unwrap().unwrap() = . LocalValue::Live(Operand::Indirect(mplace)); 7,777 ( 0.00%) (mplace, Some(size)) . } 1,386,808 ( 0.02%) Err(mplace) => (mplace, None), // this already was an indirect local . } . } 10,719 ( 0.00%) Place::Ptr(mplace) => (mplace, None), . }; . // Return with the original layout, so that the caller can go on 1,687,464 ( 0.02%) Ok((MPlaceTy { mplace, layout: place.layout }, size)) 1,125,024 ( 0.02%) } . . #[inline(always)] . pub fn force_allocation( . &mut self, . place: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> { 1,260,660 ( 0.02%) Ok(self.force_allocation_maybe_sized(place, MemPlaceMeta::None)?.0) . } . 2,160 ( 0.00%) pub fn allocate( . &mut self, . layout: TyAndLayout<'tcx>, . kind: MemoryKind, . ) -> InterpResult<'static, MPlaceTy<'tcx, M::PointerTag>> { 3,402 ( 0.00%) let ptr = self.memory.allocate(layout.size, layout.align.abi, kind)?; 1,620 ( 0.00%) Ok(MPlaceTy::from_aligned_ptr(ptr.into(), layout)) 1,890 ( 0.00%) } . . /// Returns a wide MPlace of type `&'static [mut] str` to a new 1-aligned allocation. 250 ( 0.00%) pub fn allocate_str( . &mut self, . str: &str, . kind: MemoryKind, . mutbl: Mutability, . ) -> MPlaceTy<'tcx, M::PointerTag> { 225 ( 0.00%) let ptr = self.memory.allocate_bytes(str.as_bytes(), Align::ONE, kind, mutbl); . let meta = Scalar::from_machine_usize(u64::try_from(str.len()).unwrap(), self); . let mplace = . MemPlace { ptr: ptr.into(), align: Align::ONE, meta: MemPlaceMeta::Meta(meta) }; . . let ty = self.tcx.mk_ref( 25 ( 0.00%) self.tcx.lifetimes.re_static, 25 ( 0.00%) ty::TypeAndMut { ty: self.tcx.types.str_, mutbl }, . ); 75 ( 0.00%) let layout = self.layout_of(ty).unwrap(); 250 ( 0.00%) MPlaceTy { mplace, layout } 200 ( 0.00%) } . . /// Writes the discriminant of the given variant. 990 ( 0.00%) pub fn write_discriminant( . &mut self, . variant_index: VariantIdx, . dest: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx> { . // This must be an enum or generator. 360 ( 0.00%) match dest.layout.ty.kind() { 180 ( 0.00%) ty::Adt(adt, _) => assert!(adt.is_enum()), . ty::Generator(..) => {} . _ => span_bug!( . self.cur_span(), . "write_discriminant called on non-variant-type (neither enum nor generator)" . ), . } . // Layout computation excludes uninhabited variants from consideration . // therefore there's no way to represent those variants in the given layout. . // Essentially, uninhabited variants do not have a tag that corresponds to their . // discriminant, so we cannot do anything here. . // When evaluating we will always error before even getting here, but ConstProp 'executes' . // dead code, so we cannot ICE here. 625 ( 0.00%) if dest.layout.for_variant(self, variant_index).abi.is_uninhabited() { . throw_ub!(UninhabitedEnumVariantWritten) . } . 450 ( 0.00%) match dest.layout.variants { . Variants::Single { index } => { . assert_eq!(index, variant_index); . } . Variants::Multiple { . tag_encoding: TagEncoding::Direct, 204 ( 0.00%) tag: tag_layout, 68 ( 0.00%) tag_field, . .. . } => { . // No need to validate that the discriminant here because the . // `TyAndLayout::for_variant()` call earlier already checks the variant is valid. . . let discr_val = 272 ( 0.00%) dest.layout.ty.discriminant_for_variant(*self.tcx, variant_index).unwrap().val; . . // raw discriminants for enums are isize or bigger during . // their computation, but the in-memory tag is the smallest possible . // representation . let size = tag_layout.value.size(self); . let tag_val = size.truncate(discr_val); . 272 ( 0.00%) let tag_dest = self.place_field(dest, tag_field)?; . self.write_scalar(Scalar::from_uint(tag_val, size), &tag_dest)?; . } . Variants::Multiple { . tag_encoding: . TagEncoding::Niche { dataful_variant, ref niche_variants, niche_start }, . tag: tag_layout, . tag_field, . .. . } => { . // No need to validate that the discriminant here because the . // `TyAndLayout::for_variant()` call earlier already checks the variant is valid. . 22 ( 0.00%) if variant_index != dataful_variant { . let variants_start = niche_variants.start().as_u32(); . let variant_index_relative = variant_index . .as_u32() . .checked_sub(variants_start) . .expect("overflow computing relative variant idx"); . // We need to use machine arithmetic when taking into account `niche_start`: . // tag_val = variant_index_relative + niche_start_val 33 ( 0.00%) let tag_layout = self.layout_of(tag_layout.value.to_int_ty(*self.tcx))?; . let niche_start_val = ImmTy::from_uint(niche_start, tag_layout); . let variant_index_relative_val = . ImmTy::from_uint(variant_index_relative, tag_layout); . let tag_val = self.binary_op( . mir::BinOp::Add, . &variant_index_relative_val, . &niche_start_val, . )?; . // Write result. 45 ( 0.00%) let niche_dest = self.place_field(dest, tag_field)?; . self.write_immediate(*tag_val, &niche_dest)?; . } . } . } . . Ok(()) 720 ( 0.00%) } . 2,034 ( 0.00%) pub fn raw_const_to_mplace( . &self, . raw: ConstAlloc<'tcx>, . ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> { . // This must be an allocation in `tcx` 678 ( 0.00%) let _ = self.tcx.global_alloc(raw.alloc_id); . let ptr = self.global_base_pointer(Pointer::from(raw.alloc_id))?; 954 ( 0.00%) let layout = self.layout_of(raw.ty)?; 1,356 ( 0.00%) Ok(MPlaceTy::from_aligned_ptr(ptr.into(), layout)) 1,582 ( 0.00%) } . . /// Turn a place with a `dyn Trait` type into a place with the actual dynamic type. . /// Also return some more information so drop doesn't have to run the same code twice. . pub(super) fn unpack_dyn_trait( . &self, . mplace: &MPlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, (ty::Instance<'tcx>, MPlaceTy<'tcx, M::PointerTag>)> { . let vtable = self.scalar_to_ptr(mplace.vtable()); // also sanity checks the type -- line 1109 ---------------------------------------- 1,475,170 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_hir_pretty/src/lib.rs -------------------------------------------------------------------------------- Ir -- line 37 ---------------------------------------- . ImplItem(hir::ImplItemId), . ForeignItem(hir::ForeignItemId), . Body(hir::BodyId), . BodyParamPat(hir::BodyId, usize), . } . . pub trait PpAnn { . fn nested(&self, _state: &mut State<'_>, _nested: Nested) {} 279,795 ( 0.00%) fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {} . fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {} . } . . pub struct NoAnn; . impl PpAnn for NoAnn {} . pub const NO_ANN: &dyn PpAnn = &NoAnn; . . /// Identical to the `PpAnn` implementation for `hir::Crate`, -- line 53 ---------------------------------------- -- line 124 ---------------------------------------- . } . } . . impl<'a> PrintState<'a> for State<'a> { . fn comments(&mut self) -> &mut Option> { . &mut self.comments . } . 7,371 ( 0.00%) fn print_ident(&mut self, ident: Ident) { 6,552 ( 0.00%) self.word(IdentPrinter::for_ast_ident(ident, ident.is_raw_guess()).to_string()); 4,914 ( 0.00%) self.ann.post(self, AnnNode::Name(&ident.name)) 4,095 ( 0.00%) } . . fn print_generic_args(&mut self, _: &ast::GenericArgs, _colons_before_params: bool) { . panic!("AST generic args printed by HIR pretty-printer"); . } . } . . pub const INDENT_UNIT: usize = 4; . -- line 143 ---------------------------------------- -- line 173 ---------------------------------------- . s: pp::Printer::new(), . comments: Some(Comments::new(sm, filename, input)), . attrs, . ann, . } . } . . fn attrs(&self, id: hir::HirId) -> &'a [ast::Attribute] { 418,464 ( 0.01%) (self.attrs)(id) . } . } . 1,023 ( 0.00%) pub fn to_string(ann: &dyn PpAnn, f: F) -> String . where . F: FnOnce(&mut State<'_>), . { 419,301 ( 0.01%) let mut printer = State { s: pp::Printer::new(), comments: None, attrs: &|_| &[], ann }; . f(&mut printer); 558 ( 0.00%) printer.s.eof() 744 ( 0.00%) } . . pub fn visibility_qualified>>(vis: &hir::Visibility<'_>, w: S) -> String { . to_string(NO_ANN, |s| { . s.print_visibility(vis); . s.word(w) . }) . } . -- line 200 ---------------------------------------- -- line 249 ---------------------------------------- . self.end(); // close the outer-box . } . } . . pub fn bclose(&mut self, span: rustc_span::Span) { . self.bclose_maybe_open(span, true) . } . 7,029 ( 0.00%) pub fn commasep_cmnt(&mut self, b: Breaks, elts: &[T], mut op: F, mut get_span: G) . where . F: FnMut(&mut State<'_>, &T), . G: FnMut(&T) -> rustc_span::Span, . { 2,281 ( 0.00%) self.rbox(0, b); . let len = elts.len(); . let mut i = 0; . for elt in elts { 416,268 ( 0.01%) self.maybe_print_comment(get_span(elt).hi()); . op(self, elt); . i += 1; 277,512 ( 0.00%) if i < len { . self.word(","); . self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi())); 552,500 ( 0.01%) self.space_if_not_bol(); . } . } 6,024 ( 0.00%) self.end(); . } . . pub fn commasep_exprs(&mut self, b: Breaks, exprs: &[hir::Expr<'_>]) { 1,796,685 ( 0.03%) self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span) . } . . pub fn print_mod(&mut self, _mod: &hir::Mod<'_>, attrs: &[ast::Attribute]) { . self.print_inner_attributes(attrs); . for &item_id in _mod.item_ids { . self.ann.nested(self, Nested::Item(item_id)); . } . } -- line 287 ---------------------------------------- -- line 1128 ---------------------------------------- . fn cond_needs_par(expr: &hir::Expr<'_>) -> bool { . match expr.kind { . hir::ExprKind::Break(..) | hir::ExprKind::Closure(..) | hir::ExprKind::Ret(..) => true, . _ => contains_exterior_struct_lit(expr), . } . } . . fn print_expr_vec(&mut self, exprs: &[hir::Expr<'_>]) { 1,644 ( 0.00%) self.ibox(INDENT_UNIT); . self.word("["); . self.commasep_exprs(Inconsistent, exprs); . self.word("]"); . self.end() . } . . fn print_expr_anon_const(&mut self, anon_const: &hir::AnonConst) { . self.ibox(INDENT_UNIT); -- line 1144 ---------------------------------------- -- line 1158 ---------------------------------------- . } . . fn print_expr_struct( . &mut self, . qpath: &hir::QPath<'_>, . fields: &[hir::ExprField<'_>], . wth: &Option<&hir::Expr<'_>>, . ) { 273 ( 0.00%) self.print_qpath(qpath, true); . self.word("{"); . self.commasep_cmnt( . Consistent, . fields, . |s, field| { 1,638 ( 0.00%) s.ibox(INDENT_UNIT); 1,092 ( 0.00%) if !field.is_shorthand { 2,184 ( 0.00%) s.print_ident(field.ident); . s.word_space(":"); . } 1,638 ( 0.00%) s.print_expr(&field.expr); 1,638 ( 0.00%) s.end() . }, 4,368 ( 0.00%) |f| f.span, . ); 273 ( 0.00%) match *wth { . Some(ref expr) => { . self.ibox(INDENT_UNIT); . if !fields.is_empty() { . self.word(","); . self.space(); . } . self.word(".."); . self.print_expr(&expr); . self.end(); . } . _ => { 91 ( 0.00%) if !fields.is_empty() { . self.word(",") . } . } . } . self.word("}"); . } . . fn print_expr_tup(&mut self, exprs: &[hir::Expr<'_>]) { 182 ( 0.00%) self.popen(); . self.commasep_exprs(Inconsistent, exprs); 182 ( 0.00%) if exprs.len() == 1 { . self.word(","); . } . self.pclose() . } . . fn print_expr_call(&mut self, func: &hir::Expr<'_>, args: &[hir::Expr<'_>]) { . let prec = match func.kind { . hir::ExprKind::Field(..) => parser::PREC_FORCE_PAREN, -- line 1213 ---------------------------------------- -- line 1269 ---------------------------------------- . . fn print_expr_addr_of( . &mut self, . kind: hir::BorrowKind, . mutability: hir::Mutability, . expr: &hir::Expr<'_>, . ) { . self.word("&"); 639 ( 0.00%) match kind { . hir::BorrowKind::Ref => self.print_mutability(mutability, false), . hir::BorrowKind::Raw => { . self.word_nbsp("raw"); . self.print_mutability(mutability, true); . } . } . self.print_expr_maybe_paren(expr, parser::PREC_PREFIX) . } . . fn print_literal(&mut self, lit: &hir::Lit) { 828,168 ( 0.01%) self.maybe_print_comment(lit.span.lo()); 552,112 ( 0.01%) self.word(lit.node.to_lit_token().to_string()) . } . . fn print_inline_asm(&mut self, asm: &hir::InlineAsm<'_>) { . enum AsmArg<'a> { . Template(String), . Operand(&'a hir::InlineAsmOperand<'a>), . Options(ast::InlineAsmOptions), . } -- line 1297 ---------------------------------------- -- line 1394 ---------------------------------------- . s.word(opt); . }); . s.pclose(); . } . }); . self.pclose(); . } . 1,255,392 ( 0.02%) pub fn print_expr(&mut self, expr: &hir::Expr<'_>) { 836,928 ( 0.01%) self.maybe_print_comment(expr.span.lo()); 278,976 ( 0.00%) self.print_outer_attributes(self.attrs(expr.hir_id)); 418,464 ( 0.01%) self.ibox(INDENT_UNIT); 836,928 ( 0.01%) self.ann.pre(self, AnnNode::Expr(expr)); 697,440 ( 0.01%) match expr.kind { . hir::ExprKind::Box(ref expr) => { . self.word_space("box"); . self.print_expr_maybe_paren(expr, parser::PREC_PREFIX); . } . hir::ExprKind::Array(ref exprs) => { 1,096 ( 0.00%) self.print_expr_vec(exprs); . } . hir::ExprKind::ConstBlock(ref anon_const) => { . self.print_expr_anon_const(anon_const); . } . hir::ExprKind::Repeat(ref element, ref count) => { . self.print_expr_repeat(&element, count); . } 364 ( 0.00%) hir::ExprKind::Struct(ref qpath, fields, ref wth) => { 91 ( 0.00%) self.print_expr_struct(qpath, fields, wth); . } . hir::ExprKind::Tup(ref exprs) => { 182 ( 0.00%) self.print_expr_tup(exprs); . } . hir::ExprKind::Call(ref func, ref args) => { . self.print_expr_call(&func, args); . } . hir::ExprKind::MethodCall(ref segment, ref args, _) => { . self.print_expr_method_call(segment, args); . } . hir::ExprKind::Binary(op, ref lhs, ref rhs) => { . self.print_expr_binary(op, &lhs, &rhs); . } . hir::ExprKind::Unary(op, ref expr) => { . self.print_expr_unary(op, &expr); . } 2,556 ( 0.00%) hir::ExprKind::AddrOf(k, m, ref expr) => { 639 ( 0.00%) self.print_expr_addr_of(k, m, &expr); . } . hir::ExprKind::Lit(ref lit) => { . self.print_literal(&lit); . } . hir::ExprKind::Cast(ref expr, ref ty) => { . let prec = AssocOp::As.precedence() as i8; . self.print_expr_maybe_paren(&expr, prec); . self.space(); -- line 1448 ---------------------------------------- -- line 1546 ---------------------------------------- . self.print_ident(ident); . } . hir::ExprKind::Index(ref expr, ref index) => { . self.print_expr_maybe_paren(&expr, parser::PREC_POSTFIX); . self.word("["); . self.print_expr(&index); . self.word("]"); . } 455 ( 0.00%) hir::ExprKind::Path(ref qpath) => self.print_qpath(qpath, true), . hir::ExprKind::Break(destination, ref opt_expr) => { . self.word("break"); . if let Some(label) = destination.label { . self.space(); . self.print_ident(label.ident); . } . if let Some(ref expr) = *opt_expr { . self.space(); -- line 1562 ---------------------------------------- -- line 1586 ---------------------------------------- . self.print_expr_maybe_paren(&expr, parser::PREC_JUMP); . } . hir::ExprKind::Err => { . self.popen(); . self.word("/*ERROR*/"); . self.pclose(); . } . } 836,928 ( 0.01%) self.ann.post(self, AnnNode::Expr(expr)); 278,976 ( 0.00%) self.end() 1,115,904 ( 0.02%) } . . pub fn print_local_decl(&mut self, loc: &hir::Local<'_>) { . self.print_pat(&loc.pat); . if let Some(ref ty) = loc.ty { . self.word_space(":"); . self.print_type(&ty); . } . } . . pub fn print_name(&mut self, name: Symbol) { . self.print_ident(Ident::with_dummy_span(name)) . } . 1,820 ( 0.00%) pub fn print_path(&mut self, path: &hir::Path<'_>, colons_before_params: bool) { 1,092 ( 0.00%) self.maybe_print_comment(path.span.lo()); . 182 ( 0.00%) for (i, segment) in path.segments.iter().enumerate() { . if i > 0 { . self.word("::") . } 910 ( 0.00%) if segment.ident.name != kw::PathRoot { 1,092 ( 0.00%) self.print_ident(segment.ident); 1,820 ( 0.00%) self.print_generic_args(segment.args(), segment.infer_args, colons_before_params); . } . } 1,456 ( 0.00%) } . . pub fn print_path_segment(&mut self, segment: &hir::PathSegment<'_>) { . if segment.ident.name != kw::PathRoot { . self.print_ident(segment.ident); . self.print_generic_args(segment.args(), segment.infer_args, false); . } . } . 1,820 ( 0.00%) pub fn print_qpath(&mut self, qpath: &hir::QPath<'_>, colons_before_params: bool) { 1,092 ( 0.00%) match *qpath { 2,002 ( 0.00%) hir::QPath::Resolved(None, ref path) => self.print_path(path, colons_before_params), . hir::QPath::Resolved(Some(ref qself), ref path) => { . self.word("<"); . self.print_type(qself); . self.space(); . self.word_space("as"); . . for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() { . if i > 0 { -- line 1641 ---------------------------------------- -- line 1684 ---------------------------------------- . hir::QPath::LangItem(lang_item, span, _) => { . self.word("#[lang = \""); . self.print_ident(Ident::new(lang_item.name(), span)); . self.word("\"]"); . } . } . } . 2,457 ( 0.00%) fn print_generic_args( . &mut self, . generic_args: &hir::GenericArgs<'_>, . infer_args: bool, . colons_before_params: bool, . ) { 546 ( 0.00%) if generic_args.parenthesized { . self.word("("); . self.commasep(Inconsistent, generic_args.inputs(), |s, ty| s.print_type(&ty)); . self.word(")"); . . self.space_if_not_bol(); . self.word_space("->"); . self.print_type(generic_args.bindings[0].ty()); . } else { 2,457 ( 0.00%) let start = if colons_before_params { "::<" } else { "<" }; . let empty = Cell::new(true); . let start_or_comma = |this: &mut Self| { . if empty.get() { . empty.set(false); . this.word(start) . } else { . this.word_space(",") . } . }; . . let mut nonelided_generic_args: bool = false; 273 ( 0.00%) let elide_lifetimes = generic_args.args.iter().all(|arg| match arg { . GenericArg::Lifetime(lt) => lt.is_elided(), . _ => { . nonelided_generic_args = true; . true . } . }); . . if nonelided_generic_args { -- line 1727 ---------------------------------------- -- line 1741 ---------------------------------------- . . // FIXME(eddyb): this would leak into error messages (e.g., . // "non-exhaustive patterns: `Some::<..>(_)` not covered"). . if infer_args && false { . start_or_comma(self); . self.word(".."); . } . 273 ( 0.00%) for binding in generic_args.bindings.iter() { . start_or_comma(self); . self.print_ident(binding.ident); . self.print_generic_args(binding.gen_args, false, false); . self.space(); . match generic_args.bindings[0].kind { . hir::TypeBindingKind::Equality { ref term } => { . self.word_space("="); . match term { -- line 1757 ---------------------------------------- -- line 1760 ---------------------------------------- . } . } . hir::TypeBindingKind::Constraint { bounds } => { . self.print_bounds(":", bounds); . } . } . } . 819 ( 0.00%) if !empty.get() { . self.word(">") . } . } 2,184 ( 0.00%) } . . pub fn print_pat(&mut self, pat: &hir::Pat<'_>) { . self.maybe_print_comment(pat.span.lo()); . self.ann.pre(self, AnnNode::Pat(pat)); . // Pat isn't normalized, but the beauty of it . // is that it doesn't matter . match pat.kind { . PatKind::Wild => self.word("_"), -- line 1780 ---------------------------------------- -- line 2232 ---------------------------------------- . self.word_space("="); . self.print_type(rhs_ty); . } . } . } . } . . pub fn print_mutability(&mut self, mutbl: hir::Mutability, print_const: bool) { 639 ( 0.00%) match mutbl { . hir::Mutability::Mut => self.word_nbsp("mut"), . hir::Mutability::Not => { . if print_const { . self.word_nbsp("const") . } . } . } . } -- line 2248 ---------------------------------------- 287,279 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast_pretty/src/pp.rs -------------------------------------------------------------------------------- Ir -- line 166 ---------------------------------------- . String(Cow<'static, str>), . Break(BreakToken), . Begin(BeginToken), . End, . } . . impl Token { . pub fn is_hardbreak_tok(&self) -> bool { 276,250 ( 0.00%) matches!(self, Token::Break(BreakToken { offset: 0, blank_space: SIZE_INFINITY })) . } . } . . #[derive(Copy, Clone)] . enum PrintFrame { . Fits, . Broken { offset: isize, breaks: Breaks }, . } -- line 182 ---------------------------------------- -- line 213 ---------------------------------------- . . #[derive(Clone)] . struct BufEntry { . token: Token, . size: isize, . } . . impl Printer { 372 ( 0.00%) pub fn new() -> Self { . let linewidth = 78; 5,593 ( 0.00%) Printer { . out: String::new(), . margin: linewidth as isize, . space: linewidth as isize, . buf: RingBuffer::new(), . left_total: 0, . right_total: 0, . scan_stack: VecDeque::new(), . print_stack: Vec::new(), . pending_indentation: 0, . last_printed: None, . } 465 ( 0.00%) } . . pub fn last_token(&self) -> Option<&Token> { . self.last_token_still_buffered().or_else(|| self.last_printed.as_ref()) . } . . pub fn last_token_still_buffered(&self) -> Option<&Token> { . self.buf.last().map(|last| &last.token) . } . . /// Be very careful with this! . pub fn replace_last_token_still_buffered(&mut self, token: Token) { . self.buf.last_mut().unwrap().token = token; . } . . fn scan_eof(&mut self) { 246 ( 0.00%) if !self.scan_stack.is_empty() { 190 ( 0.00%) self.check_stack(0); 190 ( 0.00%) self.advance_left(); . } . } . . fn scan_begin(&mut self, token: BeginToken) { 141,327 ( 0.00%) if self.scan_stack.is_empty() { 190 ( 0.00%) self.left_total = 1; . self.right_total = 1; . self.buf.clear(); . } 565,308 ( 0.01%) let right = self.buf.push(BufEntry { token: Token::Begin(token), size: -self.right_total }); . self.scan_stack.push_back(right); . } . . fn scan_end(&mut self) { 141,327 ( 0.00%) if self.scan_stack.is_empty() { . self.print_end(); . } else { . let right = self.buf.push(BufEntry { token: Token::End, size: -1 }); . self.scan_stack.push_back(right); . } . } . . fn scan_break(&mut self, token: BreakToken) { 138,671 ( 0.00%) if self.scan_stack.is_empty() { . self.left_total = 1; . self.right_total = 1; . self.buf.clear(); . } else { 277,342 ( 0.00%) self.check_stack(0); . } 554,684 ( 0.01%) let right = self.buf.push(BufEntry { token: Token::Break(token), size: -self.right_total }); . self.scan_stack.push_back(right); 416,013 ( 0.01%) self.right_total += token.blank_space; . } . 2,520,576 ( 0.04%) fn scan_string(&mut self, string: Cow<'static, str>) { 280,064 ( 0.00%) if self.scan_stack.is_empty() { . self.print_string(&string); . } else { . let len = string.len() as isize; 279,913 ( 0.00%) self.buf.push(BufEntry { token: Token::String(string), size: len }); 839,739 ( 0.01%) self.right_total += len; . self.check_stream(); . } 2,239,304 ( 0.03%) } . . fn check_stream(&mut self) { 1,235,422 ( 0.02%) while self.right_total - self.left_total > self.space { 69,462 ( 0.00%) if *self.scan_stack.front().unwrap() == self.buf.index_of_first() { . self.scan_stack.pop_front().unwrap(); 13,168 ( 0.00%) self.buf.first_mut().unwrap().size = SIZE_INFINITY; . } 46,308 ( 0.00%) self.advance_left(); 23,154 ( 0.00%) if self.buf.is_empty() { . break; . } . } . } . 1,096,471 ( 0.02%) fn advance_left(&mut self) { 1,448,784 ( 0.02%) while self.buf.first().unwrap().size >= 0 { 2,103,714 ( 0.03%) let left = self.buf.pop_first().unwrap(); . . match &left.token { . Token::String(string) => { 839,739 ( 0.01%) self.left_total += string.len() as isize; . self.print_string(string); . } . Token::Break(token) => { 416,013 ( 0.01%) self.left_total += token.blank_space; . self.print_break(*token, left.size); . } 7,086 ( 0.00%) Token::Begin(token) => self.print_begin(*token, left.size), . Token::End => self.print_end(), . } . 5,609,904 ( 0.08%) self.last_printed = Some(left.token); . 701,238 ( 0.01%) if self.buf.is_empty() { . break; . } . } 185,992 ( 0.00%) } . 1,248,894 ( 0.02%) fn check_stack(&mut self, mut depth: usize) { 828,865 ( 0.01%) while let Some(&index) = self.scan_stack.back() { . let mut entry = &mut self.buf[index]; 1,766,113 ( 0.03%) match entry.token { . Token::Begin(_) => { 280,102 ( 0.00%) if depth == 0 { . break; . } . self.scan_stack.pop_back().unwrap(); 416,895 ( 0.01%) entry.size += self.right_total; 138,965 ( 0.00%) depth -= 1; . } . Token::End => { . // paper says + not =, but that makes no sense. . self.scan_stack.pop_back().unwrap(); 141,327 ( 0.00%) entry.size = 1; 282,654 ( 0.00%) depth += 1; . } . _ => { . self.scan_stack.pop_back().unwrap(); 383,595 ( 0.01%) entry.size += self.right_total; 383,031 ( 0.01%) if depth == 0 { . break; . } . } . } . } 1,110,128 ( 0.02%) } . . fn get_top(&self) -> PrintFrame { 416,013 ( 0.01%) *self . .print_stack . .last() . .unwrap_or(&PrintFrame::Broken { offset: 0, breaks: Breaks::Inconsistent }) . } . . fn print_begin(&mut self, token: BeginToken, size: isize) { 423,981 ( 0.01%) if size > self.space { 11,810 ( 0.00%) let col = self.margin - self.space + token.offset; . self.print_stack.push(PrintFrame::Broken { offset: col, breaks: token.breaks }); . } else { . self.print_stack.push(PrintFrame::Fits); . } . } . . fn print_end(&mut self) { . self.print_stack.pop().unwrap(); . } . . fn print_break(&mut self, token: BreakToken, size: isize) { . let break_offset = 830,024 ( 0.01%) match self.get_top() { . PrintFrame::Fits => None, . PrintFrame::Broken { offset, breaks: Breaks::Consistent } => Some(offset), . PrintFrame::Broken { offset, breaks: Breaks::Inconsistent } => { . if size > self.space { Some(offset) } else { None } . } . }; . if let Some(offset) = break_offset { . self.out.push('\n'); 32,673 ( 0.00%) self.pending_indentation = offset + token.offset; 43,564 ( 0.00%) self.space = self.margin - (offset + token.offset); . } else { 383,340 ( 0.01%) self.pending_indentation += token.blank_space; 511,120 ( 0.01%) self.space -= token.blank_space; . } . } . . fn print_string(&mut self, string: &str) { . // Write the pending indent. A more concise way of doing this would be: . // . // write!(self.out, "{: >n$}", "", n = self.pending_indentation as usize)?; . // . // But that is significantly slower. This code is sufficiently hot, and indents can get . // sufficiently large, that the difference is significant on some workloads. 280,064 ( 0.00%) self.out.reserve(self.pending_indentation as usize); 418 ( 0.00%) self.out.extend(iter::repeat(' ').take(self.pending_indentation as usize)); 280,064 ( 0.00%) self.pending_indentation = 0; . . self.out.push_str(string); 1,400,169 ( 0.02%) self.space -= string.len() as isize; . } . . // Convenience functions to talk to the printer. . . /// "raw box" 5,872 ( 0.00%) pub fn rbox(&mut self, indent: usize, breaks: Breaks) { . self.scan_begin(BeginToken { offset: indent as isize, breaks }) 4,404 ( 0.00%) } . . /// Inconsistent breaking box 843,558 ( 0.01%) pub fn ibox(&mut self, indent: usize) { . self.rbox(indent, Breaks::Inconsistent) 702,965 ( 0.01%) } . . /// Consistent breaking box . pub fn cbox(&mut self, indent: usize) { . self.rbox(indent, Breaks::Consistent) . } . 1,109,368 ( 0.02%) pub fn break_offset(&mut self, n: usize, off: isize) { . self.scan_break(BreakToken { offset: off, blank_space: n as isize }) 832,026 ( 0.01%) } . 565,308 ( 0.01%) pub fn end(&mut self) { . self.scan_end() 565,308 ( 0.01%) } . 1,230 ( 0.00%) pub fn eof(mut self) -> String { . self.scan_eof(); 984 ( 0.00%) self.out 1,230 ( 0.00%) } . . pub fn word>>(&mut self, wrd: S) { . let string = wrd.into(); 1,962,139 ( 0.03%) self.scan_string(string) . } . . fn spaces(&mut self, n: usize) { 554,138 ( 0.01%) self.break_offset(n, 0) . } . . crate fn zerobreak(&mut self) { . self.spaces(0) . } . . pub fn space(&mut self) { . self.spaces(1) . } . . pub fn hardbreak(&mut self) { . self.spaces(SIZE_INFINITY as usize) . } . . pub fn is_beginning_of_line(&self) -> bool { 276,250 ( 0.00%) match self.last_token() { . Some(last_token) => last_token.is_hardbreak_tok(), . None => true, . } . } . . pub fn hardbreak_tok_offset(off: isize) -> Token { . Token::Break(BreakToken { offset: off, blank_space: SIZE_INFINITY }) . } -- line 481 ---------------------------------------- 5,629,422 ( 0.08%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/writeback.rs -------------------------------------------------------------------------------- Ir -- line 30 ---------------------------------------- . // the final TypeckResults since all of the types should have been . // inferred once typeck is done. . // When type inference is running however, having to update the typeck . // typeck results every time a new type is inferred would be unreasonably slow, . // so instead all of the replacement happens at the end in . // resolve_type_vars_in_body, which creates a new TypeTables which . // doesn't contain any inference types. . impl<'a, 'tcx> FnCtxt<'a, 'tcx> { 3,456 ( 0.00%) pub fn resolve_type_vars_in_body( . &self, . body: &'tcx hir::Body<'tcx>, . ) -> &'tcx ty::TypeckResults<'tcx> { 3,840 ( 0.00%) let item_id = self.tcx.hir().body_owner(body.id()); 2,304 ( 0.00%) let item_def_id = self.tcx.hir().local_def_id(item_id); . . // This attribute causes us to dump some writeback information . // in the form of errors, which is used for unit tests. . let rustc_dump_user_substs = 2,304 ( 0.00%) self.tcx.has_attr(item_def_id.to_def_id(), sym::rustc_dump_user_substs); . . let mut wbcx = WritebackCx::new(self, body, rustc_dump_user_substs); 1,536 ( 0.00%) for param in body.params { 3,807 ( 0.00%) wbcx.visit_node_id(param.pat.span, param.hir_id); . } . // Type only exists for constants and statics, not functions. 4,224 ( 0.00%) match self.tcx.hir().body_owner_kind(item_id) { . hir::BodyOwnerKind::Const | hir::BodyOwnerKind::Static(_) => { 465 ( 0.00%) wbcx.visit_node_id(body.value.span, item_id); . } . hir::BodyOwnerKind::Closure | hir::BodyOwnerKind::Fn => (), . } . wbcx.visit_body(body); 384 ( 0.00%) wbcx.visit_min_capture_map(); 384 ( 0.00%) wbcx.eval_closure_size(); 384 ( 0.00%) wbcx.visit_fake_reads_map(); 384 ( 0.00%) wbcx.visit_closures(); 384 ( 0.00%) wbcx.visit_liberated_fn_sigs(); 384 ( 0.00%) wbcx.visit_fru_field_types(); 1,152 ( 0.00%) wbcx.visit_opaque_types(body.value.span); 384 ( 0.00%) wbcx.visit_coercion_casts(); 384 ( 0.00%) wbcx.visit_user_provided_tys(); 384 ( 0.00%) wbcx.visit_user_provided_sigs(); 384 ( 0.00%) wbcx.visit_generator_interior_types(); . . let used_trait_imports = 768 ( 0.00%) mem::take(&mut self.typeck_results.borrow_mut().used_trait_imports); . debug!("used_trait_imports({:?}) = {:?}", item_def_id, used_trait_imports); 768 ( 0.00%) wbcx.typeck_results.used_trait_imports = used_trait_imports; . 1,920 ( 0.00%) wbcx.typeck_results.treat_byte_string_as_slice = 384 ( 0.00%) mem::take(&mut self.typeck_results.borrow_mut().treat_byte_string_as_slice); . 1,152 ( 0.00%) if self.is_tainted_by_errors() { . // FIXME(eddyb) keep track of `ErrorReported` from where the error was emitted. . wbcx.typeck_results.tainted_by_errors = Some(ErrorReported); . } . . debug!("writeback: typeck results for {:?} are {:#?}", item_def_id, wbcx.typeck_results); . 768 ( 0.00%) self.tcx.arena.alloc(wbcx.typeck_results) 3,456 ( 0.00%) } . } . . /////////////////////////////////////////////////////////////////////////// . // The Writeback context. This visitor walks the HIR, checking the . // fn-specific typeck results to find references to types or regions. It . // resolves those regions to remove inference variables and writes the . // final result back into the master typeck results in the tcx. Here and . // there, it applies a few ad-hoc checks that were not convenient to -- line 98 ---------------------------------------- -- line 109 ---------------------------------------- . } . . impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { . fn new( . fcx: &'cx FnCtxt<'cx, 'tcx>, . body: &'tcx hir::Body<'tcx>, . rustc_dump_user_substs: bool, . ) -> WritebackCx<'cx, 'tcx> { 768 ( 0.00%) let owner = body.id().hir_id.owner; . 3,456 ( 0.00%) WritebackCx { . fcx, 1,536 ( 0.00%) typeck_results: ty::TypeckResults::new(owner), . body, . rustc_dump_user_substs, . } . } . . fn tcx(&self) -> TyCtxt<'tcx> { 890 ( 0.00%) self.fcx.tcx . } . . fn write_ty_to_typeck_results(&mut self, hir_id: hir::HirId, ty: Ty<'tcx>) { . debug!("write_ty_to_typeck_results({:?}, {:?})", hir_id, ty); 445,800 ( 0.01%) assert!(!ty.needs_infer() && !ty.has_placeholders() && !ty.has_free_regions()); 594,336 ( 0.01%) self.typeck_results.node_types_mut().insert(hir_id, ty); . } . . // Hacky hack: During type-checking, we treat *all* operators . // as potentially overloaded. But then, during writeback, if . // we observe that something like `a+b` is (known to be) . // operating on scalars, we clear the overload. . fn fix_scalar_builtin_expr(&mut self, e: &hir::Expr<'_>) { 1,019,688 ( 0.01%) match e.kind { 6 ( 0.00%) hir::ExprKind::Unary(hir::UnOp::Neg | hir::UnOp::Not, inner) => { 24 ( 0.00%) let inner_ty = self.fcx.node_ty(inner.hir_id); . let inner_ty = self.fcx.resolve_vars_if_possible(inner_ty); . . if inner_ty.is_scalar() { 6 ( 0.00%) let mut typeck_results = self.fcx.typeck_results.borrow_mut(); 36 ( 0.00%) typeck_results.type_dependent_defs_mut().remove(e.hir_id); 12 ( 0.00%) typeck_results.node_substs_mut().remove(e.hir_id); . } . } . hir::ExprKind::Binary(ref op, lhs, rhs) | hir::ExprKind::AssignOp(ref op, lhs, rhs) => { 1,015 ( 0.00%) let lhs_ty = self.fcx.node_ty(lhs.hir_id); . let lhs_ty = self.fcx.resolve_vars_if_possible(lhs_ty); . 812 ( 0.00%) let rhs_ty = self.fcx.node_ty(rhs.hir_id); . let rhs_ty = self.fcx.resolve_vars_if_possible(rhs_ty); . . if lhs_ty.is_scalar() && rhs_ty.is_scalar() { 152 ( 0.00%) let mut typeck_results = self.fcx.typeck_results.borrow_mut(); 760 ( 0.00%) typeck_results.type_dependent_defs_mut().remove(e.hir_id); 152 ( 0.00%) typeck_results.node_substs_mut().remove(e.hir_id); . 344 ( 0.00%) match e.kind { . hir::ExprKind::Binary(..) => { 528 ( 0.00%) if !op.node.is_by_value() { 61 ( 0.00%) let mut adjustments = typeck_results.adjustments_mut(); 366 ( 0.00%) if let Some(a) = adjustments.get_mut(lhs.hir_id) { . a.pop(); . } 244 ( 0.00%) if let Some(a) = adjustments.get_mut(rhs.hir_id) { . a.pop(); . } . } . } . hir::ExprKind::AssignOp(..) 100 ( 0.00%) if let Some(a) = typeck_results.adjustments_mut().get_mut(lhs.hir_id) => . { . a.pop(); . } . _ => {} . } . } . } . _ => {} -- line 186 ---------------------------------------- -- line 187 ---------------------------------------- . } . } . . // Similar to operators, indexing is always assumed to be overloaded . // Here, correct cases where an indexing expression can be simplified . // to use builtin indexing because the index type is known to be . // usize-ish . fn fix_index_builtin_expr(&mut self, e: &hir::Expr<'_>) { 291,725 ( 0.00%) if let hir::ExprKind::Index(ref base, ref index) = e.kind { 52 ( 0.00%) let mut typeck_results = self.fcx.typeck_results.borrow_mut(); . . // All valid indexing looks like this; might encounter non-valid indexes at this point. 52 ( 0.00%) let base_ty = typeck_results 26 ( 0.00%) .expr_ty_adjusted_opt(base) . .map(|t| self.fcx.resolve_vars_if_possible(t).kind()); . if base_ty.is_none() { . // When encountering `return [0][0]` outside of a `fn` body we can encounter a base . // that isn't in the type table. We assume more relevant errors have already been . // emitted, so we delay an ICE if none have. (#64638) . self.tcx().sess.delay_span_bug(e.span, &format!("bad base: `{:?}`", base)); . } 52 ( 0.00%) if let Some(ty::Ref(_, base_ty, _)) = base_ty { 104 ( 0.00%) let index_ty = typeck_results.expr_ty_adjusted_opt(index).unwrap_or_else(|| { . // When encountering `return [0][0]` outside of a `fn` body we would attempt . // to access an unexistend index. We assume that more relevant errors will . // already have been emitted, so we only gate on this with an ICE if no . // error has been emitted. (#64638) . self.fcx.tcx.ty_error_with_message( . e.span, . &format!("bad index {:?} for base: `{:?}`", index, base), . ) . }); . let index_ty = self.fcx.resolve_vars_if_possible(index_ty); . 86 ( 0.00%) if base_ty.builtin_index().is_some() && index_ty == self.fcx.tcx.types.usize { . // Remove the method call record 24 ( 0.00%) typeck_results.type_dependent_defs_mut().remove(e.hir_id); 24 ( 0.00%) typeck_results.node_substs_mut().remove(e.hir_id); . 40 ( 0.00%) if let Some(a) = typeck_results.adjustments_mut().get_mut(base.hir_id) { . // Discard the need for a mutable borrow . . // Extra adjustment made when indexing causes a drop . // of size information - we need to get rid of it . // Since this is "after" the other adjustment to be . // discarded, we do an extra `pop()` 8 ( 0.00%) if let Some(Adjustment { . kind: Adjust::Pointer(PointerCast::Unsize), .. . }) = a.pop() . { . // So the borrow discard actually happens here . a.pop(); . } . } . } -- line 241 ---------------------------------------- -- line 248 ---------------------------------------- . // Impl of Visitor for Resolver . // . // This is the master code which walks the AST. It delegates most of . // the heavy lifting to the generic visit and resolve functions . // below. In general, a function is made into a `visitor` if it must . // traffic in node-ids or update typeck results in the type context etc. . . impl<'cx, 'tcx> Visitor<'tcx> for WritebackCx<'cx, 'tcx> { 1,310,202 ( 0.02%) fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) { 145,578 ( 0.00%) self.fix_scalar_builtin_expr(e); . self.fix_index_builtin_expr(e); . 727,890 ( 0.01%) self.visit_node_id(e.span, e.hir_id); . 582,312 ( 0.01%) match e.kind { 34 ( 0.00%) hir::ExprKind::Closure(_, _, body, _, _) => { 102 ( 0.00%) let body = self.fcx.tcx.hir().body(body); 34 ( 0.00%) for param in body.params { 95 ( 0.00%) self.visit_node_id(e.span, param.hir_id); . } . . self.visit_body(body); . } 233 ( 0.00%) hir::ExprKind::Struct(_, fields, _) => { . for field in fields { 3,904 ( 0.00%) self.visit_field_id(field.hir_id); . } . } . hir::ExprKind::Field(..) => { 1,870 ( 0.00%) self.visit_field_id(e.hir_id); . } . hir::ExprKind::ConstBlock(anon_const) => { . self.visit_node_id(e.span, anon_const.hir_id); . . let body = self.tcx().hir().body(anon_const.body); . self.visit_body(body); . } . _ => {} . } . 436,734 ( 0.01%) intravisit::walk_expr(self, e); 1,164,624 ( 0.02%) } . 5,616 ( 0.00%) fn visit_block(&mut self, b: &'tcx hir::Block<'tcx>) { 2,496 ( 0.00%) self.visit_node_id(b.span, b.hir_id); . intravisit::walk_block(self, b); 792 ( 0.00%) } . 12,123 ( 0.00%) fn visit_pat(&mut self, p: &'tcx hir::Pat<'tcx>) { 4,987 ( 0.00%) match p.kind { . hir::PatKind::Binding(..) => { 1,748 ( 0.00%) let typeck_results = self.fcx.typeck_results.borrow(); 2,622 ( 0.00%) if let Some(bm) = 6,992 ( 0.00%) typeck_results.extract_binding_mode(self.tcx().sess, p.hir_id, p.span) . { 2,622 ( 0.00%) self.typeck_results.pat_binding_modes_mut().insert(p.hir_id, bm); . } . } 98 ( 0.00%) hir::PatKind::Struct(_, fields, _) => { . for field in fields { 684 ( 0.00%) self.visit_field_id(field.hir_id); . } . } . _ => {} . }; . 5,388 ( 0.00%) self.visit_pat_adjustments(p.span, p.hir_id); . 6,735 ( 0.00%) self.visit_node_id(p.span, p.hir_id); 4,041 ( 0.00%) intravisit::walk_pat(self, p); 10,776 ( 0.00%) } . 1,776 ( 0.00%) fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) { . intravisit::walk_local(self, l); 1,332 ( 0.00%) let var_ty = self.fcx.local_ty(l.span, l.hir_id).decl_ty; . let var_ty = self.resolve(var_ty, &l.span); . self.write_ty_to_typeck_results(l.hir_id, var_ty); . } . 1,834 ( 0.00%) fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty<'tcx>) { 326 ( 0.00%) intravisit::walk_ty(self, hir_ty); 1,176 ( 0.00%) let ty = self.fcx.node_ty(hir_ty.hir_id); 262 ( 0.00%) let ty = self.resolve(ty, &hir_ty.span); . self.write_ty_to_typeck_results(hir_ty.hir_id, ty); . } . . fn visit_infer(&mut self, inf: &'tcx hir::InferArg) { . intravisit::walk_inf(self, inf); . // Ignore cases where the inference is a const. . if let Some(ty) = self.fcx.node_ty_opt(inf.hir_id) { . let ty = self.resolve(ty, &inf.span); . self.write_ty_to_typeck_results(inf.hir_id, ty); . } . } . } . . impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { 2,688 ( 0.00%) fn eval_closure_size(&mut self) { . let mut res: FxHashMap> = Default::default(); 1,152 ( 0.00%) for (closure_def_id, data) in self.fcx.typeck_results.borrow().closure_size_eval.iter() { . let closure_hir_id = . self.tcx().hir().local_def_id_to_hir_id(closure_def_id.expect_local()); . . let data = self.resolve(*data, &closure_hir_id); . . res.insert(*closure_def_id, data); . } . 3,840 ( 0.00%) self.typeck_results.closure_size_eval = res; 3,072 ( 0.00%) } 2,688 ( 0.00%) fn visit_min_capture_map(&mut self) { . let mut min_captures_wb = ty::MinCaptureInformationMap::with_capacity_and_hasher( 768 ( 0.00%) self.fcx.typeck_results.borrow().closure_min_captures.len(), . Default::default(), . ); . for (closure_def_id, root_min_captures) in 768 ( 0.00%) self.fcx.typeck_results.borrow().closure_min_captures.iter() . { . let mut root_var_map_wb = ty::RootVariableMinCaptureList::with_capacity_and_hasher( . root_min_captures.len(), . Default::default(), . ); . for (var_hir_id, min_list) in root_min_captures.iter() { . let min_list_wb = min_list . .iter() . .map(|captured_place| { 27 ( 0.00%) let locatable = captured_place.info.path_expr_id.unwrap_or_else(|| { . self.tcx().hir().local_def_id_to_hir_id(closure_def_id.expect_local()) . }); . . self.resolve(captured_place.clone(), &locatable) . }) . .collect(); 18 ( 0.00%) root_var_map_wb.insert(*var_hir_id, min_list_wb); . } 16 ( 0.00%) min_captures_wb.insert(*closure_def_id, root_var_map_wb); . } . 3,456 ( 0.00%) self.typeck_results.closure_min_captures = min_captures_wb; 3,072 ( 0.00%) } . 2,688 ( 0.00%) fn visit_fake_reads_map(&mut self) { . let mut resolved_closure_fake_reads: FxHashMap< . DefId, . Vec<(HirPlace<'tcx>, FakeReadCause, hir::HirId)>, . > = Default::default(); . for (closure_def_id, fake_reads) in 768 ( 0.00%) self.fcx.typeck_results.borrow().closure_fake_reads.iter() . { . let mut resolved_fake_reads = Vec::<(HirPlace<'tcx>, FakeReadCause, hir::HirId)>::new(); . for (place, cause, hir_id) in fake_reads.iter() { . let locatable = . self.tcx().hir().local_def_id_to_hir_id(closure_def_id.expect_local()); . . let resolved_fake_read = self.resolve(place.clone(), &locatable); . resolved_fake_reads.push((resolved_fake_read, *cause, *hir_id)); . } 34 ( 0.00%) resolved_closure_fake_reads.insert(*closure_def_id, resolved_fake_reads); . } 3,456 ( 0.00%) self.typeck_results.closure_fake_reads = resolved_closure_fake_reads; 3,072 ( 0.00%) } . 2,688 ( 0.00%) fn visit_closures(&mut self) { 768 ( 0.00%) let fcx_typeck_results = self.fcx.typeck_results.borrow(); 1,152 ( 0.00%) assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner); . let common_hir_owner = fcx_typeck_results.hir_owner; . 384 ( 0.00%) for (id, origin) in fcx_typeck_results.closure_kind_origins().iter() { 2 ( 0.00%) let hir_id = hir::HirId { owner: common_hir_owner, local_id: *id }; 2 ( 0.00%) let place_span = origin.0; . let place = self.resolve(origin.1.clone(), &place_span); 10 ( 0.00%) self.typeck_results.closure_kind_origins_mut().insert(hir_id, (place_span, place)); . } 3,072 ( 0.00%) } . 2,688 ( 0.00%) fn visit_coercion_casts(&mut self) { 768 ( 0.00%) let fcx_typeck_results = self.fcx.typeck_results.borrow(); 384 ( 0.00%) let fcx_coercion_casts = fcx_typeck_results.coercion_casts(); 768 ( 0.00%) assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner); . . for local_id in fcx_coercion_casts { 24 ( 0.00%) self.typeck_results.set_coercion_cast(*local_id); . } 3,072 ( 0.00%) } . 3,072 ( 0.00%) fn visit_user_provided_tys(&mut self) { 768 ( 0.00%) let fcx_typeck_results = self.fcx.typeck_results.borrow(); 1,536 ( 0.00%) assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner); . let common_hir_owner = fcx_typeck_results.hir_owner; . . let mut errors_buffer = Vec::new(); 996 ( 0.00%) for (&local_id, c_ty) in fcx_typeck_results.user_provided_types().iter() { . let hir_id = hir::HirId { owner: common_hir_owner, local_id }; . . if cfg!(debug_assertions) && c_ty.needs_infer() { . span_bug!( . hir_id.to_span(self.fcx.tcx), . "writeback: `{:?}` has inference variables", . c_ty . ); . }; . 2,754 ( 0.00%) self.typeck_results.user_provided_types_mut().insert(hir_id, *c_ty); . 2,052 ( 0.00%) if let ty::UserType::TypeOf(_, user_substs) = c_ty.value { 576 ( 0.00%) if self.rustc_dump_user_substs { . // This is a unit-testing mechanism. . let span = self.tcx().hir().span(hir_id); . // We need to buffer the errors in order to guarantee a consistent . // order when emitting them. . let err = self . .tcx() . .sess . .struct_span_err(span, &format!("user substs: {:?}", user_substs)); . err.buffer(&mut errors_buffer); . } . } . } . 384 ( 0.00%) if !errors_buffer.is_empty() { . errors_buffer.sort_by_key(|diag| diag.span.primary_span()); . for diag in errors_buffer.drain(..) { . self.tcx().sess.diagnostic().emit_diagnostic(&diag); . } . } 3,072 ( 0.00%) } . 2,688 ( 0.00%) fn visit_user_provided_sigs(&mut self) { 768 ( 0.00%) let fcx_typeck_results = self.fcx.typeck_results.borrow(); 768 ( 0.00%) assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner); . 34 ( 0.00%) for (&def_id, c_sig) in fcx_typeck_results.user_provided_sigs.iter() { . if cfg!(debug_assertions) && c_sig.needs_infer() { . span_bug!( . self.fcx.tcx.hir().span_if_local(def_id).unwrap(), . "writeback: `{:?}` has inference variables", . c_sig . ); . }; . 102 ( 0.00%) self.typeck_results.user_provided_sigs.insert(def_id, *c_sig); . } 3,072 ( 0.00%) } . 1,920 ( 0.00%) fn visit_generator_interior_types(&mut self) { 768 ( 0.00%) let fcx_typeck_results = self.fcx.typeck_results.borrow(); 768 ( 0.00%) assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner); 2,304 ( 0.00%) self.typeck_results.generator_interior_types = 768 ( 0.00%) fcx_typeck_results.generator_interior_types.clone(); 2,304 ( 0.00%) } . 6,144 ( 0.00%) #[instrument(skip(self, span), level = "debug")] . fn visit_opaque_types(&mut self, span: Span) { 384 ( 0.00%) let opaque_types = self.fcx.infcx.inner.borrow().opaque_types.clone(); 1,536 ( 0.00%) for (opaque_type_key, opaque_defn) in opaque_types { . let hir_id = . self.tcx().hir().local_def_id_to_hir_id(opaque_type_key.def_id.expect_local()); . let instantiated_ty = self.resolve(opaque_defn.concrete_ty, &hir_id); . . debug_assert!(!instantiated_ty.has_escaping_bound_vars()); . . let opaque_type_key = self.fcx.fully_resolve(opaque_type_key).unwrap(); . -- line 510 ---------------------------------------- -- line 552 ---------------------------------------- . // in some other location, or we'll end up emitting an error due . // to the lack of defining usage . if !skip_add { . self.typeck_results.concrete_opaque_types.insert(opaque_type_key.def_id); . } . } . } . 9,126 ( 0.00%) fn visit_field_id(&mut self, hir_id: hir::HirId) { 7,605 ( 0.00%) if let Some(index) = self.fcx.typeck_results.borrow_mut().field_indices_mut().remove(hir_id) . { 4,563 ( 0.00%) self.typeck_results.field_indices_mut().insert(hir_id, index); . } 10,647 ( 0.00%) } . 2,665,512 ( 0.04%) #[instrument(skip(self, span), level = "debug")] . fn visit_node_id(&mut self, span: Span, hir_id: hir::HirId) { . // Export associated path extensions and method resolutions. 592,336 ( 0.01%) if let Some(def) = 444,252 ( 0.01%) self.fcx.typeck_results.borrow_mut().type_dependent_defs_mut().remove(hir_id) . { 1,636 ( 0.00%) self.typeck_results.type_dependent_defs_mut().insert(hir_id, def); . } . . // Resolve any borrowings for the node with id `node_id` . self.visit_adjustments(span, hir_id); . . // Resolve the type of the node with id `node_id` 592,336 ( 0.01%) let n_ty = self.fcx.node_ty(hir_id); . let n_ty = self.resolve(n_ty, &span); . self.write_ty_to_typeck_results(hir_id, n_ty); . debug!(?n_ty); . . // Resolve any substitutions 888,504 ( 0.01%) if let Some(substs) = self.fcx.typeck_results.borrow().node_substs_opt(hir_id) { . let substs = self.resolve(substs, &span); . debug!("write_substs_to_tcx({:?}, {:?})", hir_id, substs); . assert!(!substs.needs_infer() && !substs.has_placeholders()); 1,960 ( 0.00%) self.typeck_results.node_substs_mut().insert(hir_id, substs); . } . } . . #[instrument(skip(self, span), level = "debug")] . fn visit_adjustments(&mut self, span: Span, hir_id: hir::HirId) { 444,252 ( 0.01%) let adjustment = self.fcx.typeck_results.borrow_mut().adjustments_mut().remove(hir_id); 740,420 ( 0.01%) match adjustment { . None => { . debug!("no adjustments for node"); . } . . Some(adjustment) => { 4,596 ( 0.00%) let resolved_adjustment = self.resolve(adjustment, &span); . debug!(?resolved_adjustment); 13,788 ( 0.00%) self.typeck_results.adjustments_mut().insert(hir_id, resolved_adjustment); . } . } . } . . #[instrument(skip(self, span), level = "debug")] . fn visit_pat_adjustments(&mut self, span: Span, hir_id: hir::HirId) { 4,041 ( 0.00%) let adjustment = self.fcx.typeck_results.borrow_mut().pat_adjustments_mut().remove(hir_id); 2,694 ( 0.00%) match adjustment { . None => { . debug!("no pat_adjustments for node"); . } . . Some(adjustment) => { . let resolved_adjustment = self.resolve(adjustment, &span); . debug!(?resolved_adjustment); . self.typeck_results.pat_adjustments_mut().insert(hir_id, resolved_adjustment); . } . } . } . 3,072 ( 0.00%) fn visit_liberated_fn_sigs(&mut self) { 768 ( 0.00%) let fcx_typeck_results = self.fcx.typeck_results.borrow(); 1,536 ( 0.00%) assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner); . let common_hir_owner = fcx_typeck_results.hir_owner; . 1,616 ( 0.00%) for (&local_id, &fn_sig) in fcx_typeck_results.liberated_fn_sigs().iter() { 924 ( 0.00%) let hir_id = hir::HirId { owner: common_hir_owner, local_id }; . let fn_sig = self.resolve(fn_sig, &hir_id); 924 ( 0.00%) self.typeck_results.liberated_fn_sigs_mut().insert(hir_id, fn_sig); . } 3,072 ( 0.00%) } . 3,072 ( 0.00%) fn visit_fru_field_types(&mut self) { 768 ( 0.00%) let fcx_typeck_results = self.fcx.typeck_results.borrow(); 1,536 ( 0.00%) assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner); . let common_hir_owner = fcx_typeck_results.hir_owner; . 384 ( 0.00%) for (&local_id, ftys) in fcx_typeck_results.fru_field_types().iter() { . let hir_id = hir::HirId { owner: common_hir_owner, local_id }; . let ftys = self.resolve(ftys.clone(), &hir_id); . self.typeck_results.fru_field_types_mut().insert(hir_id, ftys); . } 3,072 ( 0.00%) } . . fn resolve(&mut self, x: T, span: &dyn Locatable) -> T . where . T: TypeFoldable<'tcx>, . { 302,094 ( 0.00%) let mut resolver = Resolver::new(self.fcx, span, self.body); 2,131 ( 0.00%) let x = x.fold_with(&mut resolver); . if cfg!(debug_assertions) && x.needs_infer() { . span_bug!(span.to_span(self.fcx.tcx), "writeback: `{:?}` has inference variables", x); . } . . // We may have introduced e.g. `ty::Error`, if inference failed, make sure . // to mark the `TypeckResults` as tainted in that case, so that downstream . // users of the typeck results don't produce extra errors, or worse, ICEs. 317,337 ( 0.00%) if resolver.replaced_with_error { . // FIXME(eddyb) keep track of `ErrorReported` from where the error was emitted. . self.typeck_results.tainted_by_errors = Some(ErrorReported); . } . . x . } . } . -- line 671 ---------------------------------------- -- line 698 ---------------------------------------- . } . . impl<'cx, 'tcx> Resolver<'cx, 'tcx> { . fn new( . fcx: &'cx FnCtxt<'cx, 'tcx>, . span: &'cx dyn Locatable, . body: &'tcx hir::Body<'tcx>, . ) -> Resolver<'cx, 'tcx> { 1,516,846 ( 0.02%) Resolver { tcx: fcx.tcx, infcx: fcx, span, body, replaced_with_error: false } . } . . fn report_type_error(&self, t: Ty<'tcx>) { . if !self.tcx.sess.has_errors() { . self.infcx . .emit_inference_failure_err( . Some(self.body.id()), . self.span.to_span(self.tcx), -- line 714 ---------------------------------------- -- line 736 ---------------------------------------- . } . . struct EraseEarlyRegions<'tcx> { . tcx: TyCtxt<'tcx>, . } . . impl<'tcx> TypeFolder<'tcx> for EraseEarlyRegions<'tcx> { . fn tcx<'b>(&'b self) -> TyCtxt<'tcx> { 10,038 ( 0.00%) self.tcx . } . fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> { 160,349 ( 0.00%) if ty.has_type_flags(ty::TypeFlags::HAS_FREE_REGIONS) { 15,551 ( 0.00%) ty.super_fold_with(self) . } else { . ty . } . } . fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> { 21,836 ( 0.00%) if let ty::ReLateBound(..) = r { r } else { self.tcx.lifetimes.re_erased } . } . } . . impl<'cx, 'tcx> TypeFolder<'tcx> for Resolver<'cx, 'tcx> { . fn tcx<'a>(&'a self) -> TyCtxt<'tcx> { 1,181 ( 0.00%) self.tcx . } . 1,391,697 ( 0.02%) fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { 463,899 ( 0.01%) match self.infcx.fully_resolve(t) { . Ok(t) => { . // Do not anonymize late-bound regions . // (e.g. keep `for<'a>` named `for<'a>`). . // This allows NLL to generate error messages that . // refer to the higher-ranked lifetime names written by the user. 309,266 ( 0.00%) EraseEarlyRegions { tcx: self.infcx.tcx }.fold_ty(t) . } . Err(_) => { . debug!("Resolver::fold_ty: input type `{:?}` not fully resolvable", t); . self.report_type_error(t); . self.replaced_with_error = true; . self.tcx().ty_error() . } . } 1,237,064 ( 0.02%) } . . fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> { . debug_assert!(!r.is_late_bound(), "Should not be resolving bound region."); 7,817 ( 0.00%) self.tcx.lifetimes.re_erased . } . . fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> { . match self.infcx.fully_resolve(ct) { . Ok(ct) => self.infcx.tcx.erase_regions(ct), . Err(_) => { . debug!("Resolver::fold_const: input const `{:?}` not fully resolvable", ct); . self.report_const_error(ct); -- line 791 ---------------------------------------- 1,957,762 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_borrowck/src/type_check/mod.rs -------------------------------------------------------------------------------- Ir -- line 118 ---------------------------------------- . /// - `promoted` -- map of promoted constants within `body` . /// - `universal_regions` -- the universal regions from `body`s function signature . /// - `location_table` -- MIR location map of `body` . /// - `borrow_set` -- information about borrows occurring in `body` . /// - `all_facts` -- when using Polonius, this is the generated set of Polonius facts . /// - `flow_inits` -- results of a maybe-init dataflow analysis . /// - `move_data` -- move-data constructed when performing the maybe-init dataflow analysis . /// - `elements` -- MIR region map 4,812 ( 0.00%) pub(crate) fn type_check<'mir, 'tcx>( . infcx: &InferCtxt<'_, 'tcx>, . param_env: ty::ParamEnv<'tcx>, . body: &Body<'tcx>, . promoted: &IndexVec>, . universal_regions: &Rc>, . location_table: &LocationTable, . borrow_set: &BorrowSet<'tcx>, . all_facts: &mut Option, . flow_inits: &mut ResultsCursor<'mir, 'tcx, MaybeInitializedPlaces<'mir, 'tcx>>, . move_data: &MoveData<'tcx>, . elements: &Rc, . upvars: &[Upvar<'tcx>], . ) -> MirTypeckResults<'tcx> { 3,609 ( 0.00%) let implicit_region_bound = infcx.tcx.mk_region(ty::ReVar(universal_regions.fr_fn_body)); . let mut universe_causes = FxHashMap::default(); . universe_causes.insert(ty::UniverseIndex::from_u32(0), UniverseInfo::other()); 8,822 ( 0.00%) let mut constraints = MirTypeckRegionConstraints { . placeholder_indices: PlaceholderIndices::default(), . placeholder_index_to_region: IndexVec::default(), 401 ( 0.00%) liveness_constraints: LivenessValues::new(elements.clone()), . outlives_constraints: OutlivesConstraintSet::default(), . member_constraints: MemberConstraintSet::default(), . closure_bounds_mapping: Default::default(), . type_tests: Vec::default(), 1,604 ( 0.00%) universe_causes, . }; . . let CreateResult { 802 ( 0.00%) universal_region_relations, 1,604 ( 0.00%) region_bound_pairs, 1,604 ( 0.00%) normalized_inputs_and_output, 2,005 ( 0.00%) } = free_region_relations::create( . infcx, . param_env, . Some(implicit_region_bound), . universal_regions, . &mut constraints, . ); . 802 ( 0.00%) for u in ty::UniverseIndex::ROOT..infcx.universe() { . let info = UniverseInfo::other(); . constraints.universe_causes.insert(u, info); . } . 3,609 ( 0.00%) let mut borrowck_context = BorrowCheckContext { 401 ( 0.00%) universal_regions, . location_table, . borrow_set, . all_facts, . constraints: &mut constraints, . upvars, . }; . . let opaque_type_values = type_check_internal( -- line 180 ---------------------------------------- -- line 243 ---------------------------------------- . } else { . Some((opaque_type_key, decl)) . } . }) . .collect() . }, . ); . 4,812 ( 0.00%) MirTypeckResults { constraints, universal_region_relations, opaque_type_values } 3,208 ( 0.00%) } . . #[instrument( . skip(infcx, body, promoted, region_bound_pairs, borrowck_context, extra), . level = "debug" . )] . fn type_check_internal<'a, 'tcx, R>( . infcx: &'a InferCtxt<'a, 'tcx>, . param_env: ty::ParamEnv<'tcx>, -- line 260 ---------------------------------------- -- line 270 ---------------------------------------- . body, . param_env, . region_bound_pairs, . implicit_region_bound, . borrowck_context, . ); . let errors_reported = { . let mut verifier = TypeVerifier::new(&mut checker, body, promoted); 401 ( 0.00%) verifier.visit_body(&body); 401 ( 0.00%) verifier.errors_reported . }; . 401 ( 0.00%) if !errors_reported { . // if verifier failed, don't do further checks to avoid ICEs 401 ( 0.00%) checker.typeck_mir(body); . } . 5,213 ( 0.00%) extra(checker) . } . . fn translate_outlives_facts(typeck: &mut TypeChecker<'_, '_>) { . let cx = &mut typeck.borrowck_context; 1,604 ( 0.00%) if let Some(facts) = cx.all_facts { . let _prof_timer = typeck.infcx.tcx.prof.generic_activity("polonius_fact_generation"); . let location_table = cx.location_table; . facts.subset_base.extend(cx.constraints.outlives_constraints.outlives().iter().flat_map( . |constraint: &OutlivesConstraint<'_>| { . if let Some(from_location) = constraint.locations.from_location() { . Either::Left(iter::once(( . constraint.sup, . constraint.sub, -- line 300 ---------------------------------------- -- line 334 ---------------------------------------- . body: &'b Body<'tcx>, . promoted: &'b IndexVec>, . last_span: Span, . errors_reported: bool, . } . . impl<'a, 'b, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'tcx> { . fn visit_span(&mut self, span: &Span) { 682,582 ( 0.01%) if !span.is_dummy() { 170,629 ( 0.00%) self.last_span = *span; . } . } . 185,372 ( 0.00%) fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) { . self.sanitize_place(place, location, context); 134,816 ( 0.00%) } . 1,681,272 ( 0.02%) fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) { . self.super_constant(constant, location); 1,120,848 ( 0.02%) let ty = self.sanitize_type(constant, constant.literal.ty()); . 1,260,954 ( 0.02%) self.cx.infcx.tcx.for_each_free_region(&ty, |live_region| { . let live_region_vid = . self.cx.borrowck_context.universal_regions.to_region_vid(live_region); 3,850 ( 0.00%) self.cx . .borrowck_context . .constraints . .liveness_constraints 3,850 ( 0.00%) .add_element(live_region_vid, location); . }); . 560,424 ( 0.01%) if let Some(annotation_index) = constant.user_ty { 1,773 ( 0.00%) if let Err(terr) = self.cx.relate_type_and_user_type( 394 ( 0.00%) constant.literal.ty(), . ty::Variance::Invariant, 394 ( 0.00%) &UserTypeProjection { base: annotation_index, projs: vec![] }, 394 ( 0.00%) location.to_locations(), . ConstraintCategory::Boring, . ) { . let annotation = &self.cx.user_type_annotations[annotation_index]; . span_mirbug!( . self, . constant, . "bad constant user type {:?} vs {:?}: {:?}", . annotation, . constant.literal.ty(), . terr, . ); . } . } else { . let tcx = self.tcx(); 419,727 ( 0.01%) let maybe_uneval = match constant.literal { 419,727 ( 0.01%) ConstantKind::Ty(ct) => match ct.val { 490 ( 0.00%) ty::ConstKind::Unevaluated(uv) => Some(uv), . _ => None, . }, . _ => None, . }; 980 ( 0.00%) if let Some(uv) = maybe_uneval { 980 ( 0.00%) if let Some(promoted) = uv.promoted { . let check_err = |verifier: &mut TypeVerifier<'a, 'b, 'tcx>, . promoted: &Body<'tcx>, . ty, . san_ty| { 372 ( 0.00%) if let Err(terr) = verifier.cx.eq_types( . ty, . san_ty, 248 ( 0.00%) location.to_locations(), . ConstraintCategory::Boring, . ) { . span_mirbug!( . verifier, . promoted, . "bad promoted type ({:?}: {:?}): {:?}", . ty, . san_ty, . terr . ); . }; . }; . 248 ( 0.00%) if !self.errors_reported { 124 ( 0.00%) let promoted_body = &self.promoted[promoted]; 496 ( 0.00%) self.sanitize_promoted(promoted_body, location); . . let promoted_ty = promoted_body.return_ty(); . check_err(self, promoted_body, ty, promoted_ty); . } . } else { 2,562 ( 0.00%) if let Err(terr) = self.cx.fully_perform_op( 732 ( 0.00%) location.to_locations(), . ConstraintCategory::Boring, 2,562 ( 0.00%) self.cx.param_env.and(type_op::ascribe_user_type::AscribeUserType::new( 732 ( 0.00%) constant.literal.ty(), . uv.def.did, 1,464 ( 0.00%) UserSubsts { substs: uv.substs, user_self_ty: None }, . )), . ) { . span_mirbug!( . self, . constant, . "bad constant type {:?} ({:?})", . constant, . terr . ); . } . } 557,676 ( 0.01%) } else if let Some(static_def_id) = constant.check_static_ptr(tcx) { . let unnormalized_ty = tcx.type_of(static_def_id); . let locations = location.to_locations(); . let normalized_ty = self.cx.normalize(unnormalized_ty, locations); . let literal_ty = constant.literal.ty().builtin_deref(true).unwrap().ty; . . if let Err(terr) = self.cx.eq_types( . literal_ty, . normalized_ty, . locations, . ConstraintCategory::Boring, . ) { . span_mirbug!(self, constant, "bad static type {:?} ({:?})", constant, terr); . } . } . 562,003 ( 0.01%) if let ty::FnDef(def_id, substs) = *constant.literal.ty().kind() { 1,578 ( 0.00%) let instantiated_predicates = tcx.predicates_of(def_id).instantiate(tcx, substs); 1,578 ( 0.00%) self.cx.normalize_and_prove_instantiated_predicates( . def_id, 4,734 ( 0.00%) instantiated_predicates, 1,578 ( 0.00%) location.to_locations(), . ); . } . } 1,120,848 ( 0.02%) } . 71,104 ( 0.00%) fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) { . self.super_rvalue(rvalue, location); 19,392 ( 0.00%) let rval_ty = rvalue.ty(self.body, self.tcx()); 77,568 ( 0.00%) self.sanitize_type(rvalue, rval_ty); . } . 102,780 ( 0.00%) fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) { . self.super_local_decl(local, local_decl); 51,390 ( 0.00%) self.sanitize_type(local_decl, local_decl.ty); . 30,834 ( 0.00%) if let Some(user_ty) = &local_decl.user_ty { . for (user_ty, span) in user_ty.projections_and_spans() { . let ty = if !local_decl.is_nonref_binding() { . // If we have a binding of the form `let ref x: T = ..` . // then remove the outermost reference so we can check the . // type annotation for the remaining type. . if let ty::Ref(_, rty, _) = local_decl.ty.kind() { . rty . } else { -- line 486 ---------------------------------------- -- line 504 ---------------------------------------- . local, . local_decl.ty, . local_decl.user_ty, . terr, . ); . } . } . } 82,224 ( 0.00%) } . 3,675 ( 0.00%) fn visit_body(&mut self, body: &Body<'tcx>) { 1,575 ( 0.00%) self.sanitize_type(&"return type", body.return_ty()); . for local_decl in &body.local_decls { 51,390 ( 0.00%) self.sanitize_type(local_decl, local_decl.ty); . } 1,050 ( 0.00%) if self.errors_reported { . return; . } . self.super_body(body); 4,200 ( 0.00%) } . } . . impl<'a, 'b, 'tcx> TypeVerifier<'a, 'b, 'tcx> { . fn new( . cx: &'a mut TypeChecker<'b, 'tcx>, . body: &'b Body<'tcx>, . promoted: &'b IndexVec>, . ) -> Self { 3,609 ( 0.00%) TypeVerifier { body, promoted, cx, last_span: body.span, errors_reported: false } . } . . fn tcx(&self) -> TyCtxt<'tcx> { 457,211 ( 0.01%) self.cx.infcx.tcx . } . 1,684,860 ( 0.02%) fn sanitize_type(&mut self, parent: &dyn fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> { 336,972 ( 0.00%) if ty.has_escaping_bound_vars() || ty.references_error() { . span_mirbug_and_err!(self, parent, "bad type {:?}", ty) . } else { . ty . } 1,179,402 ( 0.02%) } . . /// Checks that the types internal to the `place` match up with . /// what would be expected. . fn sanitize_place( . &mut self, . place: &Place<'tcx>, . location: Location, . context: PlaceContext, . ) -> PlaceTy<'tcx> { . debug!("sanitize_place: {:?}", place); . 67,408 ( 0.00%) let mut place_ty = PlaceTy::from_ty(self.body.local_decls[place.local].ty); . 23,864 ( 0.00%) for elem in place.projection.iter() { 3,506 ( 0.00%) if place_ty.variant_index.is_none() { 3,328 ( 0.00%) if place_ty.ty.references_error() { . assert!(self.errors_reported); . return PlaceTy::from_ty(self.tcx().ty_error()); . } . } . place_ty = self.sanitize_projection(place_ty, elem, place, location); . } . 49,076 ( 0.00%) if let PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) = context { . let tcx = self.tcx(); . let trait_ref = ty::TraitRef { 5,210 ( 0.00%) def_id: tcx.require_lang_item(LangItem::Copy, Some(self.last_span)), 2,605 ( 0.00%) substs: tcx.mk_substs_trait(place_ty.ty, &[]), . }; . . // To have a `Copy` operand, the type `T` of the . // value must be `Copy`. Note that we prove that `T: Copy`, . // rather than using the `is_copy_modulo_regions` . // test. This is important because . // `is_copy_modulo_regions` ignores the resulting region . // obligations and assumes they pass. This can result in . // bounds from `Copy` impls being unsoundly ignored (e.g., . // #29149). Note that we decide to use `Copy` before knowing . // whether the bounds fully apply: in effect, the rule is . // that if a value of some type could implement `Copy`, then . // it must. 1,563 ( 0.00%) self.cx.prove_trait_ref( . trait_ref, . location.to_locations(), . ConstraintCategory::CopyBound, . ); . } . . place_ty . } -- line 595 ---------------------------------------- -- line 598 ---------------------------------------- . // Determine the constraints from the promoted MIR by running the type . // checker on the promoted MIR, then transfer the constraints back to . // the main MIR, changing the locations to the provided location. . . let parent_body = mem::replace(&mut self.body, promoted_body); . . // Use new sets of constraints and closure bounds so that we can . // modify their locations. 124 ( 0.00%) let all_facts = &mut None; . let mut constraints = Default::default(); . let mut closure_bounds = Default::default(); . let mut liveness_constraints = 248 ( 0.00%) LivenessValues::new(Rc::new(RegionValueElements::new(&promoted_body))); . // Don't try to add borrow_region facts for the promoted MIR . . let mut swap_constraints = |this: &mut Self| { 496 ( 0.00%) mem::swap(this.cx.borrowck_context.all_facts, all_facts); . mem::swap( 496 ( 0.00%) &mut this.cx.borrowck_context.constraints.outlives_constraints, . &mut constraints, . ); . mem::swap( 496 ( 0.00%) &mut this.cx.borrowck_context.constraints.closure_bounds_mapping, . &mut closure_bounds, . ); . mem::swap( 496 ( 0.00%) &mut this.cx.borrowck_context.constraints.liveness_constraints, . &mut liveness_constraints, . ); . }; . 124 ( 0.00%) swap_constraints(self); . 372 ( 0.00%) self.visit_body(&promoted_body); . 248 ( 0.00%) if !self.errors_reported { . // if verifier failed, don't do further checks to avoid ICEs 372 ( 0.00%) self.cx.typeck_mir(promoted_body); . } . 124 ( 0.00%) self.body = parent_body; . // Merge the outlives constraints back in, at the given location. 124 ( 0.00%) swap_constraints(self); . . let locations = location.to_locations(); . for constraint in constraints.outlives().iter() { . let mut constraint = constraint.clone(); . constraint.locations = locations; 9,954 ( 0.00%) if let ConstraintCategory::Return(_) . | ConstraintCategory::UseAsConst . | ConstraintCategory::UseAsStatic = constraint.category . { . // "Returning" from a promoted is an assignment to a . // temporary from the user's point of view. . constraint.category = ConstraintCategory::Boring; . } . self.cx.borrowck_context.constraints.outlives_constraints.push(constraint) . } . for region in liveness_constraints.rows() { . // If the region is live at at least one location in the promoted MIR, . // then add a liveness constraint to the main MIR for this region . // at the location provided as an argument to this method 1,743 ( 0.00%) if liveness_constraints.get_elements(region).next().is_some() { 1,020 ( 0.00%) self.cx . .borrowck_context . .constraints . .liveness_constraints . .add_element(region, location); . } . } . 124 ( 0.00%) if !closure_bounds.is_empty() { . let combined_bounds_mapping = . closure_bounds.into_iter().flat_map(|(_, value)| value).collect(); . let existing = self . .cx . .borrowck_context . .constraints . .closure_bounds_mapping . .insert(location, combined_bounds_mapping); . assert!(existing.is_none(), "Multiple promoteds/closures at the same location."); . } 496 ( 0.00%) } . . fn sanitize_projection( . &mut self, . base: PlaceTy<'tcx>, . pi: PlaceElem<'tcx>, . place: &Place<'tcx>, . location: Location, . ) -> PlaceTy<'tcx> { . debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place); . let tcx = self.tcx(); 3,506 ( 0.00%) let base_ty = base.ty; 17,530 ( 0.00%) match pi { . ProjectionElem::Deref => { 7,467 ( 0.00%) let deref_ty = base_ty.builtin_deref(true); . PlaceTy::from_ty(deref_ty.map(|t| t.ty).unwrap_or_else(|| { . span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty) . })) . } 4 ( 0.00%) ProjectionElem::Index(i) => { 16 ( 0.00%) let index_ty = Place::from(i).ty(self.body, tcx).ty; 4 ( 0.00%) if index_ty != tcx.types.usize { . PlaceTy::from_ty(span_mirbug_and_err!(self, i, "index by non-usize {:?}", i)) . } else { 4 ( 0.00%) PlaceTy::from_ty(base_ty.builtin_index().unwrap_or_else(|| { . span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty) . })) . } . } . ProjectionElem::ConstantIndex { .. } => { . // consider verifying in-bounds . PlaceTy::from_ty(base_ty.builtin_index().unwrap_or_else(|| { . span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty) -- line 712 ---------------------------------------- -- line 720 ---------------------------------------- . } . ty::Slice(..) => { . assert!(from_end, "slice subslices should use from_end"); . base_ty . } . _ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty), . }) . } 534 ( 0.00%) ProjectionElem::Downcast(maybe_name, index) => match base_ty.kind() { 534 ( 0.00%) ty::Adt(adt_def, _substs) if adt_def.is_enum() => { 534 ( 0.00%) if index.as_usize() >= adt_def.variants.len() { . PlaceTy::from_ty(span_mirbug_and_err!( . self, . place, . "cast to variant #{:?} but enum only has {:?}", . index, . adt_def.variants.len() . )) . } else { -- line 738 ---------------------------------------- -- line 752 ---------------------------------------- . ) . } else { . span_mirbug_and_err!(self, place, "can't downcast {:?}", base_ty) . }; . PlaceTy::from_ty(ty) . } . }, . ProjectionElem::Field(field, fty) => { 4,175 ( 0.00%) let fty = self.sanitize_type(place, fty); 11,690 ( 0.00%) let fty = self.cx.normalize(fty, location); . match self.field_ty(place, base, field, location) { . Ok(ty) => { 6,680 ( 0.00%) let ty = self.cx.normalize(ty, location); 1,670 ( 0.00%) if let Err(terr) = self.cx.eq_types( . ty, . fty, . location.to_locations(), . ConstraintCategory::Boring, . ) { . span_mirbug!( . self, . place, -- line 773 ---------------------------------------- -- line 800 ---------------------------------------- . &mut self, . parent: &dyn fmt::Debug, . base_ty: PlaceTy<'tcx>, . field: Field, . location: Location, . ) -> Result, FieldAccessError> { . let tcx = self.tcx(); . 835 ( 0.00%) let (variant, substs) = match base_ty { 712 ( 0.00%) PlaceTy { ty, variant_index: Some(variant_index) } => match *ty.kind() { 356 ( 0.00%) ty::Adt(adt_def, substs) => (&adt_def.variants[variant_index], substs), . ty::Generator(def_id, substs, _) => { . let mut variants = substs.as_generator().state_tys(def_id, tcx); . let mut variant = match variants.nth(variant_index.into()) { . Some(v) => v, . None => bug!( . "variant_index of generator out of range: {:?}/{:?}", . variant_index, . substs.as_generator().state_tys(def_id, tcx).count() -- line 818 ---------------------------------------- -- line 820 ---------------------------------------- . }; . return match variant.nth(field.index()) { . Some(ty) => Ok(ty), . None => Err(FieldAccessError::OutOfRange { field_count: variant.count() }), . }; . } . _ => bug!("can't have downcast of non-adt non-generator type"), . }, 2,628 ( 0.00%) PlaceTy { ty, variant_index: None } => match *ty.kind() { 1,752 ( 0.00%) ty::Adt(adt_def, substs) if !adt_def.is_enum() => { . (&adt_def.variants[VariantIdx::new(0)], substs) . } 18 ( 0.00%) ty::Closure(_, substs) => { 162 ( 0.00%) return match substs . .as_closure() . .tupled_upvars_ty() . .tuple_element_ty(field.index()) . { . Some(ty) => Ok(ty), . None => Err(FieldAccessError::OutOfRange { . field_count: substs.as_closure().upvar_tys().count(), . }), -- line 841 ---------------------------------------- -- line 846 ---------------------------------------- . // accessible without a variant index. . return match substs.as_generator().prefix_tys().nth(field.index()) { . Some(ty) => Ok(ty), . None => Err(FieldAccessError::OutOfRange { . field_count: substs.as_generator().prefix_tys().count(), . }), . }; . } 201 ( 0.00%) ty::Tuple(tys) => { 201 ( 0.00%) return match tys.get(field.index()) { 804 ( 0.00%) Some(&ty) => Ok(ty.expect_ty()), . None => Err(FieldAccessError::OutOfRange { field_count: tys.len() }), . }; . } . _ => { . return Ok(span_mirbug_and_err!( . self, . parent, . "can't project out of {:?}", . base_ty . )); . } . }, . }; . 616 ( 0.00%) if let Some(field) = variant.fields.get(field.index()) { 6,160 ( 0.00%) Ok(self.cx.normalize(field.ty(tcx, substs), location)) . } else { . Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() }) . } . } . } . . /// The MIR type checker. Visits the MIR and enforces all the . /// constraints needed for it to be valid and well-typed. Along the -- line 880 ---------------------------------------- -- line 943 ---------------------------------------- . FxHashMap>, . . crate universe_causes: FxHashMap>, . . crate type_tests: Vec>, . } . . impl<'tcx> MirTypeckRegionConstraints<'tcx> { 1,740 ( 0.00%) fn placeholder_region( . &mut self, . infcx: &InferCtxt<'_, 'tcx>, . placeholder: ty::PlaceholderRegion, . ) -> ty::Region<'tcx> { . let placeholder_index = self.placeholder_indices.insert(placeholder); 348 ( 0.00%) match self.placeholder_index_to_region.get(placeholder_index) { 128 ( 0.00%) Some(&v) => v, . None => { 440 ( 0.00%) let origin = NllRegionVariableOrigin::Placeholder(placeholder); 990 ( 0.00%) let region = infcx.next_nll_region_var_in_universe(origin, placeholder.universe); . self.placeholder_index_to_region.push(region); . region . } . } 1,392 ( 0.00%) } . } . . /// The `Locations` type summarizes *where* region constraints are . /// required to hold. Normally, this is at a particular point which . /// created the obligation, but for constraints that the user gave, we . /// want the constraint to hold at all points. 40,817 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] . pub enum Locations { . /// Indicates that a type constraint should always be true. This . /// is particularly important in the new borrowck analysis for . /// things like the type of the return slot. Consider this . /// example: . /// . /// ``` . /// fn foo<'a>(x: &'a u32) -> &'a u32 { -- line 981 ---------------------------------------- -- line 1020 ---------------------------------------- . match self { . Locations::All(_) => None, . Locations::Single(from_location) => Some(*from_location), . } . } . . /// Gets a span representing the location. . pub fn span(&self, body: &Body<'_>) -> Span { 14 ( 0.00%) match self { 2 ( 0.00%) Locations::All(span) => *span, 25 ( 0.00%) Locations::Single(l) => body.source_info(*l).span, . } . } . } . . impl<'a, 'tcx> TypeChecker<'a, 'tcx> { . fn new( . infcx: &'a InferCtxt<'a, 'tcx>, . body: &'a Body<'tcx>, . param_env: ty::ParamEnv<'tcx>, . region_bound_pairs: &'a RegionBoundPairs<'tcx>, . implicit_region_bound: ty::Region<'tcx>, . borrowck_context: &'a mut BorrowCheckContext<'a, 'tcx>, . ) -> Self { 5,213 ( 0.00%) let mut checker = Self { . infcx, . last_span: DUMMY_SP, . body, 401 ( 0.00%) user_type_annotations: &body.user_type_annotations, . param_env, . region_bound_pairs, . implicit_region_bound, . borrowck_context, . reported_errors: Default::default(), . }; . checker.check_user_type_annotations(); . checker . } . . fn unsized_feature_enabled(&self) -> bool { 16,675 ( 0.00%) let features = self.tcx().features(); 33,350 ( 0.00%) features.unsized_locals || features.unsized_fn_params . } . . /// Equate the inferred type and the annotated type for user type annotations . fn check_user_type_annotations(&mut self) { . debug!( . "check_user_type_annotations: user_type_annotations={:?}", . self.user_type_annotations . ); 324 ( 0.00%) for user_annotation in self.user_type_annotations { 648 ( 0.00%) let CanonicalUserTypeAnnotation { span, ref user_ty, inferred_ty } = *user_annotation; 1,944 ( 0.00%) let inferred_ty = self.normalize(inferred_ty, Locations::All(span)); 648 ( 0.00%) let annotation = self.instantiate_canonical_with_fresh_inference_vars(span, user_ty); 648 ( 0.00%) match annotation { 72 ( 0.00%) UserType::Ty(mut ty) => { 216 ( 0.00%) ty = self.normalize(ty, Locations::All(span)); . 72 ( 0.00%) if let Err(terr) = self.eq_types( . ty, 36 ( 0.00%) inferred_ty, . Locations::All(span), . ConstraintCategory::BoringNoLocation, . ) { . span_mirbug!( . self, . user_annotation, . "bad user type ({:?} = {:?}): {:?}", . ty, . inferred_ty, . terr . ); . } . 252 ( 0.00%) self.prove_predicate( 108 ( 0.00%) ty::Binder::dummy(ty::PredicateKind::WellFormed(inferred_ty.into())) . .to_predicate(self.tcx()), 72 ( 0.00%) Locations::All(span), . ConstraintCategory::TypeAnnotation, . ); . } 2,304 ( 0.00%) UserType::TypeOf(def_id, user_substs) => { 2,592 ( 0.00%) if let Err(terr) = self.fully_perform_op( 576 ( 0.00%) Locations::All(span), . ConstraintCategory::BoringNoLocation, 1,440 ( 0.00%) self.param_env.and(type_op::ascribe_user_type::AscribeUserType::new( 288 ( 0.00%) inferred_ty, . def_id, 576 ( 0.00%) user_substs, . )), . ) { . span_mirbug!( . self, . user_annotation, . "bad user type AscribeUserType({:?}, {:?} {:?}, type_of={:?}): {:?}", . inferred_ty, . def_id, -- line 1116 ---------------------------------------- -- line 1128 ---------------------------------------- . fn push_region_constraints( . &mut self, . locations: Locations, . category: ConstraintCategory, . data: &QueryRegionConstraints<'tcx>, . ) { . debug!("constraints generated: {:#?}", data); . 2,689 ( 0.00%) constraint_conversion::ConstraintConversion::new( 1 ( 0.00%) self.infcx, 5,339 ( 0.00%) self.borrowck_context.universal_regions, 2,670 ( 0.00%) self.region_bound_pairs, . Some(self.implicit_region_bound), 638 ( 0.00%) self.param_env, . locations, . category, 2,670 ( 0.00%) &mut self.borrowck_context.constraints, . ) . .convert_all(data); . } . . /// Try to relate `sub <: sup` . fn sub_types( . &mut self, . sub: Ty<'tcx>, . sup: Ty<'tcx>, . locations: Locations, . category: ConstraintCategory, . ) -> Fallible<()> { . // Use this order of parameters because the sup type is usually the . // "expected" type in diagnostics. 1,508,900 ( 0.02%) self.relate_types(sup, ty::Variance::Contravariant, sub, locations, category) . } . . #[instrument(skip(self, category), level = "debug")] . fn eq_types( . &mut self, . expected: Ty<'tcx>, . found: Ty<'tcx>, . locations: Locations, . category: ConstraintCategory, . ) -> Fallible<()> { 21,065 ( 0.00%) self.relate_types(expected, ty::Variance::Invariant, found, locations, category) . } . 4,896 ( 0.00%) #[instrument(skip(self), level = "debug")] . fn relate_type_and_user_type( . &mut self, . a: Ty<'tcx>, . v: ty::Variance, . user_ty: &UserTypeProjection, . locations: Locations, . category: ConstraintCategory, . ) -> Fallible<()> { 1,152 ( 0.00%) let annotated_type = self.user_type_annotations[user_ty.base].inferred_ty; . let mut curr_projected_ty = PlaceTy::from_ty(annotated_type); . 864 ( 0.00%) let tcx = self.infcx.tcx; . . for proj in &user_ty.projs { . let projected_ty = curr_projected_ty.projection_ty_core( . tcx, . self.param_env, . proj, . |this, field, &()| { . let ty = this.field_ty(tcx, field); -- line 1193 ---------------------------------------- -- line 1197 ---------------------------------------- . curr_projected_ty = projected_ty; . } . debug!( . "user_ty base: {:?} freshened: {:?} projs: {:?} yields: {:?}", . user_ty.base, annotated_type, user_ty.projs, curr_projected_ty . ); . . let ty = curr_projected_ty.ty; 4,608 ( 0.00%) self.relate_types(ty, v.xform(ty::Variance::Contravariant), a, locations, category)?; . . Ok(()) . } . . /// Equates a type `anon_ty` that may contain opaque types whose . /// values are to be inferred by the MIR. . /// . /// The type `revealed_ty` contains the same type as `anon_ty`, but with the -- line 1213 ---------------------------------------- -- line 1231 ---------------------------------------- . /// . /// In terms of our function parameters: . /// . /// * `anon_ty` would be `Box>` where `Foo` is an opaque type . /// scoped to this function (note that it is parameterized by the . /// generics of `foo`). Note that `anon_ty` is not just the opaque type, . /// but the entire return type (which may contain opaque types within it). . /// * `revealed_ty` would be `Box<(T, u32)>` 7,942 ( 0.00%) #[instrument(skip(self), level = "debug")] . fn eq_opaque_type_and_type( . &mut self, . revealed_ty: Ty<'tcx>, . anon_ty: Ty<'tcx>, . locations: Locations, . category: ConstraintCategory, . ) -> Fallible<()> { . // Fast path for the common case. 418 ( 0.00%) if !anon_ty.has_opaque_types() { 836 ( 0.00%) if let Err(terr) = self.eq_types(anon_ty, revealed_ty, locations, category) { . span_mirbug!( . self, . locations, . "eq_opaque_type_and_type: `{:?}=={:?}` failed with `{:?}`", . revealed_ty, . anon_ty, . terr . ); -- line 1257 ---------------------------------------- -- line 1328 ---------------------------------------- . || "opaque_type_map".to_string(), . ), . )?; . } . Ok(()) . } . . fn tcx(&self) -> TyCtxt<'tcx> { 118,162 ( 0.00%) self.infcx.tcx . } . . #[instrument(skip(self, body, location), level = "debug")] . fn check_stmt(&mut self, body: &Body<'tcx>, stmt: &Statement<'tcx>, location: Location) { . let tcx = self.tcx(); 57,744 ( 0.00%) match stmt.kind { 6,464 ( 0.00%) StatementKind::Assign(box (ref place, ref rv)) => { . // Assignments to temporaries are not "interesting"; . // they are not caused by the user, but rather artifacts . // of lowering. Assignments to other sorts of places *are* interesting . // though. 25,796 ( 0.00%) let category = match place.as_local() { . Some(RETURN_PLACE) => { 936 ( 0.00%) let defining_ty = &self.borrowck_context.universal_regions.defining_ty; 468 ( 0.00%) if defining_ty.is_const() { 744 ( 0.00%) if tcx.is_static(defining_ty.def_id()) { . ConstraintCategory::UseAsStatic . } else { . ConstraintCategory::UseAsConst . } . } else { . ConstraintCategory::Return(ReturnConstraint::Normal) . } . } . Some(l) 8,278 ( 0.00%) if matches!( 12,510 ( 0.00%) body.local_decls[l].local_info, . Some(box LocalInfo::AggregateTemp) . ) => . { . ConstraintCategory::Usage . } . Some(l) if !body.local_decls[l].is_user_variable() => { . ConstraintCategory::Boring . } -- line 1371 ---------------------------------------- -- line 1373 ---------------------------------------- . }; . debug!( . "assignment category: {:?} {:?}", . category, . place.as_local().map(|l| &body.local_decls[l]) . ); . . let place_ty = place.ty(body, tcx).ty; 77,568 ( 0.00%) let place_ty = self.normalize(place_ty, location); 6,464 ( 0.00%) let rv_ty = rv.ty(body, tcx); 38,784 ( 0.00%) let rv_ty = self.normalize(rv_ty, location); 12,928 ( 0.00%) if let Err(terr) = . self.sub_types(rv_ty, place_ty, location.to_locations(), category) . { . span_mirbug!( . self, . stmt, . "bad assignment ({:?} = {:?}): {:?}", . place_ty, . rv_ty, . terr . ); . } . 465 ( 0.00%) if let Some(annotation_index) = self.rvalue_user_ty(rv) { 728 ( 0.00%) if let Err(terr) = self.relate_type_and_user_type( 91 ( 0.00%) rv_ty, . ty::Variance::Invariant, 364 ( 0.00%) &UserTypeProjection { base: annotation_index, projs: vec![] }, . location.to_locations(), . ConstraintCategory::Boring, . ) { . let annotation = &self.user_type_annotations[annotation_index]; . span_mirbug!( . self, . stmt, . "bad user type on rvalue ({:?} = {:?}): {:?}", . annotation, . rv_ty, . terr . ); . } . } . 45,248 ( 0.00%) self.check_rvalue(body, rv, location); 6,464 ( 0.00%) if !self.unsized_feature_enabled() { . let trait_ref = ty::TraitRef { 71,104 ( 0.00%) def_id: tcx.require_lang_item(LangItem::Sized, Some(self.last_span)), 32,320 ( 0.00%) substs: tcx.mk_substs_trait(place_ty, &[]), . }; 19,392 ( 0.00%) self.prove_trait_ref( . trait_ref, . location.to_locations(), . ConstraintCategory::SizedBound, . ); . } . } . StatementKind::SetDiscriminant { ref place, variant_index } => { . let place_type = place.ty(body, tcx).ty; -- line 1431 ---------------------------------------- -- line 1488 ---------------------------------------- . #[instrument(skip(self, body, term_location), level = "debug")] . fn check_terminator( . &mut self, . body: &Body<'tcx>, . term: &Terminator<'tcx>, . term_location: Location, . ) { . let tcx = self.tcx(); 16,125 ( 0.00%) match term.kind { . TerminatorKind::Goto { .. } . | TerminatorKind::Resume . | TerminatorKind::Abort . | TerminatorKind::Return . | TerminatorKind::GeneratorDrop . | TerminatorKind::Unreachable . | TerminatorKind::Drop { .. } . | TerminatorKind::FalseEdge { .. } . | TerminatorKind::FalseUnwind { .. } . | TerminatorKind::InlineAsm { .. } => { . // no checks needed for these . } . . TerminatorKind::DropAndReplace { ref place, ref value, target: _, unwind: _ } => { 7 ( 0.00%) let place_ty = place.ty(body, tcx).ty; 7 ( 0.00%) let rv_ty = value.ty(body, tcx); . . let locations = term_location.to_locations(); 14 ( 0.00%) if let Err(terr) = . self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment) . { . span_mirbug!( . self, . term, . "bad DropAndReplace ({:?} = {:?}): {:?}", . place_ty, . rv_ty, . terr . ); . } . } 1,004 ( 0.00%) TerminatorKind::SwitchInt { ref discr, switch_ty, .. } => { 753 ( 0.00%) self.check_operand(discr, term_location); . 251 ( 0.00%) let discr_ty = discr.ty(body, tcx); 502 ( 0.00%) if let Err(terr) = self.sub_types( . discr_ty, . switch_ty, . term_location.to_locations(), . ConstraintCategory::Assignment, . ) { . span_mirbug!( . self, . term, . "bad SwitchInt ({:?} on {:?}): {:?}", . switch_ty, . discr_ty, . terr . ); . } 280 ( 0.00%) if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() { . span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty); . } . // FIXME: check the values . } 5,628 ( 0.00%) TerminatorKind::Call { ref func, ref args, ref destination, from_hir_call, .. } => { 4,690 ( 0.00%) self.check_operand(func, term_location); . for arg in args { 7,620 ( 0.00%) self.check_operand(arg, term_location); . } . 938 ( 0.00%) let func_ty = func.ty(body, tcx); . debug!("check_terminator: call, func_ty={:?}", func_ty); 3,752 ( 0.00%) let sig = match func_ty.kind() { 3,752 ( 0.00%) ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx), . _ => { . span_mirbug!(self, term, "call to non-function {:?}", func_ty); . return; . } . }; 9,380 ( 0.00%) let (sig, map) = self.infcx.replace_bound_vars_with_fresh_vars( 2,814 ( 0.00%) term.source_info.span, . LateBoundRegionConversionTime::FnCall, . sig, . ); 1,876 ( 0.00%) let sig = self.normalize(sig, term_location); 3,752 ( 0.00%) self.check_call_dest(body, term, &sig, destination, term_location); . . self.prove_predicates( 938 ( 0.00%) sig.inputs_and_output . .iter() 4,924 ( 0.00%) .map(|ty| ty::Binder::dummy(ty::PredicateKind::WellFormed(ty.into()))), . term_location.to_locations(), . ConstraintCategory::Boring, . ); . . // The ordinary liveness rules will ensure that all . // regions in the type of the callee are live here. We . // then further constrain the late-bound regions that . // were instantiated at the call site to be live as . // well. The resulting is that all the input (and . // output) types in the signature must be live, since . // all the inputs that fed into it were live. 7,690 ( 0.00%) for &late_bound_region in map.values() { . let region_vid = 2,062 ( 0.00%) self.borrowck_context.universal_regions.to_region_vid(late_bound_region); 2,062 ( 0.00%) self.borrowck_context . .constraints . .liveness_constraints . .add_element(region_vid, term_location); . } . 1,876 ( 0.00%) self.check_call_inputs(body, term, &sig, args, term_location, from_hir_call); . } 8 ( 0.00%) TerminatorKind::Assert { ref cond, ref msg, .. } => { 12 ( 0.00%) self.check_operand(cond, term_location); . 8 ( 0.00%) let cond_ty = cond.ty(body, tcx); 4 ( 0.00%) if cond_ty != tcx.types.bool { . span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty); . } . 24 ( 0.00%) if let AssertKind::BoundsCheck { ref len, ref index } = *msg { 4 ( 0.00%) if len.ty(body, tcx) != tcx.types.usize { . span_mirbug!(self, len, "bounds-check length non-usize {:?}", len) . } 4 ( 0.00%) if index.ty(body, tcx) != tcx.types.usize { . span_mirbug!(self, index, "bounds-check index non-usize {:?}", index) . } . } . } . TerminatorKind::Yield { ref value, .. } => { . self.check_operand(value, term_location); . . let value_ty = value.ty(body, tcx); -- line 1621 ---------------------------------------- -- line 1647 ---------------------------------------- . &mut self, . body: &Body<'tcx>, . term: &Terminator<'tcx>, . sig: &ty::FnSig<'tcx>, . destination: &Option<(Place<'tcx>, BasicBlock)>, . term_location: Location, . ) { . let tcx = self.tcx(); 3,752 ( 0.00%) match *destination { . Some((ref dest, _target_block)) => { . let dest_ty = dest.ty(body, tcx).ty; 5,502 ( 0.00%) let dest_ty = self.normalize(dest_ty, term_location); 4,585 ( 0.00%) let category = match dest.as_local() { . Some(RETURN_PLACE) => { 1,274 ( 0.00%) if let BorrowCheckContext { . universal_regions: . UniversalRegions { . defining_ty: . DefiningTy::Const(def_id, _) . | DefiningTy::InlineConst(def_id, _), . .. . }, . .. -- line 1669 ---------------------------------------- -- line 1673 ---------------------------------------- . ConstraintCategory::UseAsStatic . } else { . ConstraintCategory::UseAsConst . } . } else { . ConstraintCategory::Return(ReturnConstraint::Normal) . } . } 537 ( 0.00%) Some(l) if !body.local_decls[l].is_user_variable() => { . ConstraintCategory::Boring . } . _ => ConstraintCategory::Assignment, . }; . . let locations = term_location.to_locations(); . 6,419 ( 0.00%) if let Err(terr) = self.sub_types(sig.output(), dest_ty, locations, category) { . span_mirbug!( . self, . term, . "call dest mismatch ({:?} <- {:?}): {:?}", . dest_ty, . sig.output(), . terr . ); . } . . // When `unsized_fn_params` and `unsized_locals` are both not enabled, . // this check is done at `check_local`. 917 ( 0.00%) if self.unsized_feature_enabled() { . let span = term.source_info.span; . self.ensure_place_sized(dest_ty, span); . } . } . None => { 21 ( 0.00%) if !self . .tcx() 63 ( 0.00%) .conservative_is_privately_uninhabited(self.param_env.and(sig.output())) . { . span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig); . } . } . } . } . . fn check_call_inputs( -- line 1718 ---------------------------------------- -- line 1720 ---------------------------------------- . body: &Body<'tcx>, . term: &Terminator<'tcx>, . sig: &ty::FnSig<'tcx>, . args: &[Operand<'tcx>], . term_location: Location, . from_hir_call: bool, . ) { . debug!("check_call_inputs({:?}, {:?})", sig, args); 6,566 ( 0.00%) if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.c_variadic) { . span_mirbug!(self, term, "call to {:?} with wrong # of args", sig); . } 4,924 ( 0.00%) for (n, (fn_arg, op_arg)) in iter::zip(sig.inputs(), args).enumerate() { . let op_arg_ty = op_arg.ty(body, self.tcx()); 6,096 ( 0.00%) let op_arg_ty = self.normalize(op_arg_ty, term_location); . let category = if from_hir_call { . ConstraintCategory::CallArgument . } else { . ConstraintCategory::Boring . }; 3,048 ( 0.00%) if let Err(terr) = 3,048 ( 0.00%) self.sub_types(op_arg_ty, fn_arg, term_location.to_locations(), category) . { . span_mirbug!( . self, . term, . "bad arg #{:?} ({:?} <- {:?}): {:?}", . n, . fn_arg, . op_arg_ty, . terr . ); . } . } . } . . fn check_iscleanup(&mut self, body: &Body<'tcx>, block_data: &BasicBlockData<'tcx>) { 2,059 ( 0.00%) let is_cleanup = block_data.is_cleanup; 9,675 ( 0.00%) self.last_span = block_data.terminator().source_info.span; 19,350 ( 0.00%) match block_data.terminator().kind { 433 ( 0.00%) TerminatorKind::Goto { target } => { 1,732 ( 0.00%) self.assert_iscleanup(body, block_data, target, is_cleanup) . } 251 ( 0.00%) TerminatorKind::SwitchInt { ref targets, .. } => { 251 ( 0.00%) for target in targets.all_targets() { 3,468 ( 0.00%) self.assert_iscleanup(body, block_data, *target, is_cleanup); . } . } . TerminatorKind::Resume => { 280 ( 0.00%) if !is_cleanup { . span_mirbug!(self, block_data, "resume on non-cleanup block!") . } . } . TerminatorKind::Abort => { . if !is_cleanup { . span_mirbug!(self, block_data, "abort on non-cleanup block!") . } . } . TerminatorKind::Return => { 525 ( 0.00%) if is_cleanup { . span_mirbug!(self, block_data, "return on cleanup block") . } . } . TerminatorKind::GeneratorDrop { .. } => { . if is_cleanup { . span_mirbug!(self, block_data, "generator_drop in cleanup block") . } . } -- line 1786 ---------------------------------------- -- line 1792 ---------------------------------------- . if let Some(drop) = drop { . self.assert_iscleanup(body, block_data, drop, is_cleanup); . } . } . TerminatorKind::Unreachable => {} . TerminatorKind::Drop { target, unwind, .. } . | TerminatorKind::DropAndReplace { target, unwind, .. } . | TerminatorKind::Assert { target, cleanup: unwind, .. } => { 3,020 ( 0.00%) self.assert_iscleanup(body, block_data, target, is_cleanup); 1,208 ( 0.00%) if let Some(unwind) = unwind { 297 ( 0.00%) if is_cleanup { . span_mirbug!(self, block_data, "unwind on cleanup block") . } . self.assert_iscleanup(body, block_data, unwind, true); . } . } 938 ( 0.00%) TerminatorKind::Call { ref destination, cleanup, .. } => { 4,627 ( 0.00%) if let &Some((_, target)) = destination { 1,834 ( 0.00%) self.assert_iscleanup(body, block_data, target, is_cleanup); . } 2,814 ( 0.00%) if let Some(cleanup) = cleanup { 938 ( 0.00%) if is_cleanup { . span_mirbug!(self, block_data, "cleanup on cleanup block") . } . self.assert_iscleanup(body, block_data, cleanup, true); . } . } 226 ( 0.00%) TerminatorKind::FalseEdge { real_target, imaginary_target } => { 678 ( 0.00%) self.assert_iscleanup(body, block_data, real_target, is_cleanup); 565 ( 0.00%) self.assert_iscleanup(body, block_data, imaginary_target, is_cleanup); . } 38 ( 0.00%) TerminatorKind::FalseUnwind { real_target, unwind } => { 95 ( 0.00%) self.assert_iscleanup(body, block_data, real_target, is_cleanup); 38 ( 0.00%) if let Some(unwind) = unwind { 19 ( 0.00%) if is_cleanup { . span_mirbug!(self, block_data, "cleanup in cleanup block via false unwind"); . } . self.assert_iscleanup(body, block_data, unwind, true); . } . } . TerminatorKind::InlineAsm { destination, cleanup, .. } => { . if let Some(target) = destination { . self.assert_iscleanup(body, block_data, target, is_cleanup); -- line 1834 ---------------------------------------- -- line 1838 ---------------------------------------- . span_mirbug!(self, block_data, "cleanup on cleanup block") . } . self.assert_iscleanup(body, block_data, cleanup, true); . } . } . } . } . 36,279 ( 0.00%) fn assert_iscleanup( . &mut self, . body: &Body<'tcx>, . ctxt: &dyn fmt::Debug, . bb: BasicBlock, . iscleanuppad: bool, . ) { 24,186 ( 0.00%) if body[bb].is_cleanup != iscleanuppad { . span_mirbug!(self, ctxt, "cleanuppad mismatch: {:?} should be {:?}", bb, iscleanuppad); . } 20,155 ( 0.00%) } . . fn check_local(&mut self, body: &Body<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) { . match body.local_kind(local) { . LocalKind::ReturnPointer | LocalKind::Arg => { . // return values of normal functions are required to be . // sized by typeck, but return values of ADT constructors are . // not because we don't include a `Self: Sized` bounds on them. . // -- line 1864 ---------------------------------------- -- line 1866 ---------------------------------------- . // - maybe we should make that a warning. . return; . } . LocalKind::Var | LocalKind::Temp => {} . } . . // When `unsized_fn_params` or `unsized_locals` is enabled, only function calls . // and nullary ops are checked in `check_call_dest`. 9,294 ( 0.00%) if !self.unsized_feature_enabled() { 18,588 ( 0.00%) let span = local_decl.source_info.span; 9,294 ( 0.00%) let ty = local_decl.ty; 18,588 ( 0.00%) self.ensure_place_sized(ty, span); . } . } . 83,646 ( 0.00%) fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) { . let tcx = self.tcx(); . . // Erase the regions from `ty` to get a global type. The . // `Sized` bound in no way depends on precise regions, so this . // shouldn't affect `is_sized`. . let erased_ty = tcx.erase_regions(ty); 55,764 ( 0.00%) if !erased_ty.is_sized(tcx.at(span), self.param_env) { . // in current MIR construction, all non-control-flow rvalue . // expressions evaluate through `as_temp` or `into` a return . // slot or local, so to find all unsized rvalues it is enough . // to check all temps, return slots and locals. . if self.reported_errors.replace((ty, span)).is_none() { . let mut diag = struct_span_err!( . self.tcx().sess, . span, -- line 1896 ---------------------------------------- -- line 1901 ---------------------------------------- . ); . . // While this is located in `nll::typeck` this error is not . // an NLL error, it's a required check to prevent creation . // of unsized rvalues in a call expression. . diag.emit(); . } . } 55,764 ( 0.00%) } . . fn aggregate_field_ty( . &mut self, . ak: &AggregateKind<'tcx>, . field_index: usize, . location: Location, . ) -> Result, FieldAccessError> { . let tcx = self.tcx(); . 696,240 ( 0.01%) match *ak { 9,486 ( 0.00%) AggregateKind::Adt(adt_did, variant_index, substs, _, active_field_index) => { . let def = tcx.adt_def(adt_did); . let variant = &def.variants[variant_index]; . let adj_field_index = active_field_index.unwrap_or(field_index); 1,054 ( 0.00%) if let Some(field) = variant.fields.get(adj_field_index) { 9,486 ( 0.00%) Ok(self.normalize(field.ty(tcx, substs), location)) . } else { . Err(FieldAccessError::OutOfRange { field_count: variant.fields.len() }) . } . } 9 ( 0.00%) AggregateKind::Closure(_, substs) => { 108 ( 0.00%) match substs.as_closure().upvar_tys().nth(field_index) { . Some(ty) => Ok(ty), . None => Err(FieldAccessError::OutOfRange { . field_count: substs.as_closure().upvar_tys().count(), . }), . } . } . AggregateKind::Generator(_, substs, _) => { . // It doesn't make sense to look at a field beyond the prefix; -- line 1939 ---------------------------------------- -- line 1941 ---------------------------------------- . // aggregate rvalues. . match substs.as_generator().prefix_tys().nth(field_index) { . Some(ty) => Ok(ty), . None => Err(FieldAccessError::OutOfRange { . field_count: substs.as_generator().prefix_tys().count(), . }), . } . } 138,185 ( 0.00%) AggregateKind::Array(ty) => Ok(ty), . AggregateKind::Tuple => { . unreachable!("This should have been covered in check_rvalues"); . } . } . } . 1,010,996 ( 0.01%) fn check_operand(&mut self, op: &Operand<'tcx>, location: Location) { 288,856 ( 0.00%) if let Operand::Constant(constant) = op { 419,769 ( 0.01%) let maybe_uneval = match constant.literal { 419,769 ( 0.01%) ConstantKind::Ty(ct) => match ct.val { 307 ( 0.00%) ty::ConstKind::Unevaluated(uv) => Some(uv), . _ => None, . }, . _ => None, . }; 614 ( 0.00%) if let Some(uv) = maybe_uneval { 307 ( 0.00%) if uv.promoted.is_none() { . let tcx = self.tcx(); 1,281 ( 0.00%) let def_id = uv.def.def_id_for_type_of(); 732 ( 0.00%) if tcx.def_kind(def_id) == DefKind::InlineConst { . let predicates = self.prove_closure_bounds( . tcx, . def_id.expect_local(), . uv.substs, . location, . ); . self.normalize_and_prove_instantiated_predicates( . def_id, . predicates, . location.to_locations(), . ); . } . } . } . } 1,155,424 ( 0.02%) } . 84,032 ( 0.00%) fn check_rvalue(&mut self, body: &Body<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) { . let tcx = self.tcx(); . 32,756 ( 0.00%) match rvalue { . Rvalue::Aggregate(ak, ops) => { . for op in ops { 697,695 ( 0.01%) self.check_operand(op, location); . } 2,444 ( 0.00%) self.check_aggregate_rvalue(&body, rvalue, ak, ops, location) . } . . Rvalue::Repeat(operand, len) => { . self.check_operand(operand, location); . . // If the length cannot be evaluated we must assume that the length can be larger . // than 1. . // If the length is larger than 1, the repeat expression will need to copy the -- line 2003 ---------------------------------------- -- line 2071 ---------------------------------------- . . self.prove_trait_ref( . trait_ref, . location.to_locations(), . ConstraintCategory::SizedBound, . ); . } . 2,744 ( 0.00%) Rvalue::Cast(cast_kind, op, ty) => { 2,744 ( 0.00%) self.check_operand(op, location); . 8,878 ( 0.00%) match cast_kind { . CastKind::Pointer(PointerCast::ReifyFnPointer) => { 376 ( 0.00%) let fn_sig = op.ty(body, tcx).fn_sig(tcx); . . // The type that we see in the fcx is like . // `foo::<'a, 'b>`, where `foo` is the path to a . // function definition. When we extract the . // signature, it comes from the `fn_sig` query, . // and hence may contain unnormalized results. 517 ( 0.00%) let fn_sig = self.normalize(fn_sig, location); . 47 ( 0.00%) let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig); . 94 ( 0.00%) if let Err(terr) = self.eq_types( 47 ( 0.00%) ty, . ty_fn_ptr_from, . location.to_locations(), . ConstraintCategory::Cast, . ) { . span_mirbug!( . self, . rvalue, . "equating {:?} with {:?} yields {:?}", -- line 2104 ---------------------------------------- -- line 2158 ---------------------------------------- . ty_fn_ptr_from, . ty, . terr . ); . } . } . . CastKind::Pointer(PointerCast::Unsize) => { 1,905 ( 0.00%) let &ty = ty; . let trait_ref = ty::TraitRef { 6,985 ( 0.00%) def_id: tcx 635 ( 0.00%) .require_lang_item(LangItem::CoerceUnsized, Some(self.last_span)), 7,620 ( 0.00%) substs: tcx.mk_substs_trait(op.ty(body, tcx), &[ty.into()]), . }; . 5,715 ( 0.00%) self.prove_trait_ref( . trait_ref, . location.to_locations(), . ConstraintCategory::Cast, . ); . } . . CastKind::Pointer(PointerCast::MutToConstPointer) => { . let ty_from = match op.ty(body, tcx).kind() { -- line 2181 ---------------------------------------- -- line 2290 ---------------------------------------- . ty_elem, . ty_to, . terr . ) . } . } . . CastKind::Misc => { 4 ( 0.00%) let ty_from = op.ty(body, tcx); 16 ( 0.00%) let cast_ty_from = CastTy::from_ty(ty_from); 12 ( 0.00%) let cast_ty_to = CastTy::from_ty(ty); 52 ( 0.00%) match (cast_ty_from, cast_ty_to) { . (None, _) . | (_, None | Some(CastTy::FnPtr)) . | (Some(CastTy::Float), Some(CastTy::Ptr(_))) . | (Some(CastTy::Ptr(_) | CastTy::FnPtr), Some(CastTy::Float)) => { . span_mirbug!(self, rvalue, "Invalid cast {:?} -> {:?}", ty_from, ty,) . } . ( . Some(CastTy::Int(_)), -- line 2309 ---------------------------------------- -- line 2312 ---------------------------------------- . | (Some(CastTy::Float), Some(CastTy::Int(_) | CastTy::Float)) . | (Some(CastTy::Ptr(_)), Some(CastTy::Int(_) | CastTy::Ptr(_))) . | (Some(CastTy::FnPtr), Some(CastTy::Int(_) | CastTy::Ptr(_))) => (), . } . } . } . } . 3,047 ( 0.00%) Rvalue::Ref(region, _borrow_kind, borrowed_place) => { 18,282 ( 0.00%) self.add_reborrow_constraint(&body, location, region, borrowed_place); . } . . Rvalue::BinaryOp( . BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge, 195 ( 0.00%) box (left, right), . ) => { 325 ( 0.00%) self.check_operand(left, location); 325 ( 0.00%) self.check_operand(right, location); . 65 ( 0.00%) let ty_left = left.ty(body, tcx); 195 ( 0.00%) match ty_left.kind() { . // Types with regions are comparable if they have a common super-type. . ty::RawPtr(_) | ty::FnPtr(_) => { . let ty_right = right.ty(body, tcx); . let common_ty = self.infcx.next_ty_var(TypeVariableOrigin { . kind: TypeVariableOriginKind::MiscVariable, . span: body.source_info(location).span, . }); . self.sub_types( -- line 2340 ---------------------------------------- -- line 2360 ---------------------------------------- . ty_right, . terr . ) . } . } . // For types with no regions we can just check that the . // both operands have the same type. . ty::Int(_) | ty::Uint(_) | ty::Bool | ty::Char | ty::Float(_) 325 ( 0.00%) if ty_left == right.ty(body, tcx) => {} . // Other types are compared by trait methods, not by . // `Rvalue::BinaryOp`. . _ => span_mirbug!( . self, . rvalue, . "unexpected comparison types {:?} and {:?}", . ty_left, . right.ty(body, tcx) . ), . } . } . . Rvalue::Use(operand) | Rvalue::UnaryOp(_, operand) => { 2,536 ( 0.00%) self.check_operand(operand, location); . } . . Rvalue::BinaryOp(_, box (left, right)) . | Rvalue::CheckedBinaryOp(_, box (left, right)) => { 176 ( 0.00%) self.check_operand(left, location); 88 ( 0.00%) self.check_operand(right, location); . } . . Rvalue::AddressOf(..) . | Rvalue::ThreadLocalRef(..) . | Rvalue::Len(..) . | Rvalue::Discriminant(..) => {} . } 41,216 ( 0.00%) } . . /// If this rvalue supports a user-given type annotation, then . /// extract and return it. This represents the final type of the . /// rvalue and will be unified with the inferred type. . fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option { 25,856 ( 0.00%) match rvalue { . Rvalue::Use(_) . | Rvalue::ThreadLocalRef(_) . | Rvalue::Repeat(..) . | Rvalue::Ref(..) . | Rvalue::AddressOf(..) . | Rvalue::Len(..) . | Rvalue::Cast(..) . | Rvalue::ShallowInitBox(..) . | Rvalue::BinaryOp(..) . | Rvalue::CheckedBinaryOp(..) . | Rvalue::NullaryOp(..) . | Rvalue::UnaryOp(..) . | Rvalue::Discriminant(..) => None, . 3,666 ( 0.00%) Rvalue::Aggregate(aggregate, _) => match **aggregate { 1,395 ( 0.00%) AggregateKind::Adt(_, _, _, user_ty, _) => user_ty, . AggregateKind::Array(_) => None, . AggregateKind::Tuple => None, . AggregateKind::Closure(_, _) => None, . AggregateKind::Generator(_, _, _) => None, . }, . } . } . -- line 2426 ---------------------------------------- -- line 2431 ---------------------------------------- . aggregate_kind: &AggregateKind<'tcx>, . operands: &[Operand<'tcx>], . location: Location, . ) { . let tcx = self.tcx(); . . self.prove_aggregate_predicates(aggregate_kind, location); . 1,222 ( 0.00%) if *aggregate_kind == AggregateKind::Tuple { . // tuple rvalue field type is always the type of the op. Nothing to check here. . return; . } . 139,248 ( 0.00%) for (i, operand) in operands.iter().enumerate() { 27 ( 0.00%) let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) { 278,496 ( 0.00%) Ok(field_ty) => field_ty, . Err(FieldAccessError::OutOfRange { field_count }) => { . span_mirbug!( . self, . rvalue, . "accessed field #{} but variant only has {}", . i, . field_count . ); . continue; . } . }; . let operand_ty = operand.ty(body, tcx); 835,488 ( 0.01%) let operand_ty = self.normalize(operand_ty, location); . 278,496 ( 0.00%) if let Err(terr) = self.sub_types( . operand_ty, 139,248 ( 0.00%) field_ty, . location.to_locations(), . ConstraintCategory::Boring, . ) { . span_mirbug!( . self, . rvalue, . "{:?} is not a subtype of {:?}: {:?}", . operand_ty, -- line 2471 ---------------------------------------- -- line 2486 ---------------------------------------- . fn add_reborrow_constraint( . &mut self, . body: &Body<'tcx>, . location: Location, . borrow_region: ty::Region<'tcx>, . borrowed_place: &Place<'tcx>, . ) { . // These constraints are only meaningful during borrowck: 3,047 ( 0.00%) let BorrowCheckContext { borrow_set, location_table, all_facts, constraints, .. } = . self.borrowck_context; . . // In Polonius mode, we also push a `loan_issued_at` fact . // linking the loan to the region (in some cases, though, . // there is no loan associated with this borrow expression -- . // that occurs when we are borrowing an unsafe place, for . // example). 18,282 ( 0.00%) if let Some(all_facts) = all_facts { . let _prof_timer = self.infcx.tcx.prof.generic_activity("polonius_fact_generation"); . if let Some(borrow_index) = borrow_set.get_index_of(&location) { . let region_vid = borrow_region.to_region_vid(); . all_facts.loan_issued_at.push(( . region_vid, . borrow_index, . location_table.mid_index(location), . )); -- line 2510 ---------------------------------------- -- line 2516 ---------------------------------------- . // *p`, where the `p` has type `&'b mut Foo`, for example, we . // need to ensure that `'b: 'a`. . . debug!( . "add_reborrow_constraint({:?}, {:?}, {:?})", . location, borrow_region, borrowed_place . ); . 3,047 ( 0.00%) let mut cursor = borrowed_place.projection.as_ref(); 3,047 ( 0.00%) let tcx = self.infcx.tcx; 6,094 ( 0.00%) let field = path_utils::is_upvar_field_projection( . tcx, 6,094 ( 0.00%) &self.borrowck_context.upvars, . borrowed_place.as_ref(), . body, . ); 6,094 ( 0.00%) let category = if let Some(field) = field { 9 ( 0.00%) let var_hir_id = self.borrowck_context.upvars[field.index()].place.get_root_variable(); . // FIXME(project-rfc-2229#8): Use Place for better diagnostics . ConstraintCategory::ClosureUpvar(var_hir_id) . } else { . ConstraintCategory::Boring . }; . 16,298 ( 0.00%) while let [proj_base @ .., elem] = cursor { . cursor = proj_base; . . debug!("add_reborrow_constraint - iteration {:?}", elem); . 15,712 ( 0.00%) match elem { . ProjectionElem::Deref => { 4,246 ( 0.00%) let base_ty = Place::ty_from(borrowed_place.local, proj_base, body, tcx).ty; . . debug!("add_reborrow_constraint - base_ty = {:?}", base_ty); 10,503 ( 0.00%) match base_ty.kind() { . ty::Ref(ref_region, _, mutbl) => { 2,067 ( 0.00%) constraints.outlives_constraints.push(OutlivesConstraint { 4,134 ( 0.00%) sup: ref_region.to_region_vid(), . sub: borrow_region.to_region_vid(), . locations: location.to_locations(), . category, . variance_info: ty::VarianceDiagInfo::default(), . }); . 5,975 ( 0.00%) match mutbl { . hir::Mutability::Not => { . // Immutable reference. We don't need the base . // to be valid for the entire lifetime of . // the borrow. . break; . } . hir::Mutability::Mut => { . // Mutable reference. We *do* need the base -- line 2568 ---------------------------------------- -- line 2588 ---------------------------------------- . // ``` . } . } . } . ty::RawPtr(..) => { . // deref of raw pointer, guaranteed to be valid . break; . } 112 ( 0.00%) ty::Adt(def, _) if def.is_box() => { . // deref of `Box`, need the base to be valid - propagate . } . _ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place), . } . } . ProjectionElem::Field(..) . | ProjectionElem::Downcast(..) . | ProjectionElem::Index(..) -- line 2604 ---------------------------------------- -- line 2617 ---------------------------------------- . ) { . let tcx = self.tcx(); . . debug!( . "prove_aggregate_predicates(aggregate_kind={:?}, location={:?})", . aggregate_kind, location . ); . 14,888 ( 0.00%) let (def_id, instantiated_predicates) = match aggregate_kind { . AggregateKind::Adt(adt_did, _, substs, _, _) => { 3,720 ( 0.00%) (*adt_did, tcx.predicates_of(*adt_did).instantiate(tcx, substs)) . } . . // For closures, we have some **extra requirements** we . // . // have to check. In particular, in their upvars and . // signatures, closures often reference various regions . // from the surrounding function -- we call those the . // closure's free regions. When we borrow-check (and hence -- line 2635 ---------------------------------------- -- line 2644 ---------------------------------------- . // . // Despite the opacity of the previous parapgrah, this is . // actually relatively easy to understand in terms of the . // desugaring. A closure gets desugared to a struct, and . // these extra requirements are basically like where . // clauses on the struct. . AggregateKind::Closure(def_id, substs) . | AggregateKind::Generator(def_id, substs, _) => { 204 ( 0.00%) (*def_id, self.prove_closure_bounds(tcx, def_id.expect_local(), substs, location)) . } . . AggregateKind::Array(_) | AggregateKind::Tuple => { 1,480 ( 0.00%) (CRATE_DEF_ID.to_def_id(), ty::InstantiatedPredicates::empty()) . } . }; . 1,222 ( 0.00%) self.normalize_and_prove_instantiated_predicates( . def_id, 3,666 ( 0.00%) instantiated_predicates, . location.to_locations(), . ); . } . 153 ( 0.00%) fn prove_closure_bounds( . &mut self, . tcx: TyCtxt<'tcx>, . def_id: LocalDefId, . substs: SubstsRef<'tcx>, . location: Location, . ) -> ty::InstantiatedPredicates<'tcx> { 52 ( 0.00%) if let Some(ref closure_region_requirements) = tcx.mir_borrowck(def_id).closure_requirements . { 1 ( 0.00%) let closure_constraints = QueryRegionConstraints { 6 ( 0.00%) outlives: closure_region_requirements.apply_requirements( . tcx, . def_id.to_def_id(), . substs, . ), . . // Presently, closures never propagate member . // constraints to their parents -- they are enforced . // locally. This is largely a non-issue as member -- line 2685 ---------------------------------------- -- line 2688 ---------------------------------------- . // closures. . member_constraints: vec![], . }; . . let bounds_mapping = closure_constraints . .outlives . .iter() . .enumerate() 3 ( 0.00%) .filter_map(|(idx, constraint)| { . let ty::OutlivesPredicate(k1, r2) = 2 ( 0.00%) constraint.no_bound_vars().unwrap_or_else(|| { . bug!("query_constraint {:?} contained bound vars", constraint,); . }); . . match k1.unpack() { . GenericArgKind::Lifetime(r1) => { . // constraint is r1: r2 . let r1_vid = self.borrowck_context.universal_regions.to_region_vid(r1); . let r2_vid = self.borrowck_context.universal_regions.to_region_vid(r2); . let outlives_requirements = . &closure_region_requirements.outlives_requirements[idx]; . Some(( . (r1_vid, r2_vid), 1 ( 0.00%) (outlives_requirements.category, outlives_requirements.blame_span), . )) . } . GenericArgKind::Type(_) | GenericArgKind::Const(_) => None, . } . }) . .collect(); . . let existing = self . .borrowck_context . .constraints . .closure_bounds_mapping . .insert(location, bounds_mapping); 1 ( 0.00%) assert!(existing.is_none(), "Multiple closures at the same location."); . . self.push_region_constraints( . location.to_locations(), . ConstraintCategory::ClosureBounds, . &closure_constraints, . ); . } . 51 ( 0.00%) tcx.predicates_of(def_id).instantiate(tcx, substs) 136 ( 0.00%) } . 7,875 ( 0.00%) #[instrument(skip(self, body), level = "debug")] . fn typeck_mir(&mut self, body: &Body<'tcx>) { 2,100 ( 0.00%) self.last_span = body.span; . debug!(?body.span); . . for (local, local_decl) in body.local_decls.iter_enumerated() { . self.check_local(&body, local, local_decl); . } . . for (block, block_data) in body.basic_blocks().iter_enumerated() { . let mut location = Location { block, statement_index: 0 }; . for stmt in &block_data.statements { 57,744 ( 0.00%) if !stmt.source_info.span.is_dummy() { 57,612 ( 0.00%) self.last_span = stmt.source_info.span; . } . self.check_stmt(body, stmt, location); 4,646 ( 0.00%) location.statement_index += 1; . } . . self.check_terminator(&body, block_data.terminator(), location); . self.check_iscleanup(&body, block_data); . } . } . } . -- line 2760 ---------------------------------------- -- line 2765 ---------------------------------------- . impl NormalizeLocation for Locations { . fn to_locations(self) -> Locations { . self . } . } . . impl NormalizeLocation for Location { . fn to_locations(self) -> Locations { 489,500 ( 0.01%) Locations::Single(self) . } . } . . #[derive(Debug, Default)] . struct ObligationAccumulator<'tcx> { . obligations: PredicateObligations<'tcx>, . } . -- line 2781 ---------------------------------------- 498,358 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_metadata/src/rmeta/encoder.rs -------------------------------------------------------------------------------- Ir -- line 83 ---------------------------------------- . if $self.is_proc_macro { . return Lazy::empty(); . } . }; . } . . macro_rules! encoder_methods { . ($($name:ident($ty:ty);)*) => { 32,716 ( 0.00%) $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> { . self.opaque.$name(value) 39,352 ( 0.00%) })* . } . } . . impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> { . type Error = ::Error; . . #[inline] . fn emit_unit(&mut self) -> Result<(), Self::Error> { -- line 101 ---------------------------------------- -- line 125 ---------------------------------------- . emit_raw_bytes(&[u8]); . } . } . . impl<'a, 'tcx, T: Encodable>> Encodable> . for Lazy . { . fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { 3,281 ( 0.00%) e.emit_lazy_distance(*self) . } . } . . impl<'a, 'tcx, T: Encodable>> Encodable> . for Lazy<[T]> . { 95 ( 0.00%) fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { . e.emit_usize(self.meta)?; 682 ( 0.00%) if self.meta == 0 { . return Ok(()); . } 1,963 ( 0.00%) e.emit_lazy_distance(*self) 30 ( 0.00%) } . } . . impl<'a, 'tcx, I: Idx, T: Encodable>> Encodable> . for Lazy> . where . Option: FixedSizeEncoding, . { . fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { . e.emit_usize(self.meta)?; 144 ( 0.00%) e.emit_lazy_distance(*self) . } . } . . impl<'a, 'tcx> Encodable> for CrateNum { 25,613 ( 0.00%) fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { 26,055 ( 0.00%) if *self != LOCAL_CRATE && s.is_proc_macro { . panic!("Attempted to encode non-local CrateNum {:?} for proc-macro crate", self); . } . s.emit_u32(self.as_u32()) 21,954 ( 0.00%) } . } . . impl<'a, 'tcx> Encodable> for DefIndex { 6,105 ( 0.00%) fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { . s.emit_u32(self.as_u32()) 7,326 ( 0.00%) } . } . . impl<'a, 'tcx> Encodable> for ExpnIndex { . fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { . s.emit_u32(self.as_u32()) . } . } . . impl<'a, 'tcx> Encodable> for SyntaxContext { 877,900 ( 0.01%) fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { 526,740 ( 0.01%) rustc_span::hygiene::raw_encode_syntax_context(*self, &s.hygiene_ctxt, s) 1,053,480 ( 0.01%) } . } . . impl<'a, 'tcx> Encodable> for ExpnId { . fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { 1,197 ( 0.00%) if self.krate == LOCAL_CRATE { . // We will only write details for local expansions. Non-local expansions will fetch . // data from the corresponding crate's metadata. . // FIXME(#43047) FIXME(#74731) We may eventually want to avoid relying on external . // metadata from proc-macro crates. 4,708 ( 0.00%) s.hygiene_ctxt.schedule_expn_data_for_encoding(*self); . } 3,284 ( 0.00%) self.krate.encode(s)?; . self.local_id.encode(s) . } . } . . impl<'a, 'tcx> Encodable> for Span { 1,399,648 ( 0.02%) fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { 1,049,736 ( 0.01%) let span = self.data(); . . // Don't serialize any `SyntaxContext`s from a proc-macro crate, . // since we don't load proc-macro dependencies during serialization. . // This means that any hygiene information from macros used *within* . // a proc-macro crate (e.g. invoking a macro that expands to a proc-macro . // definition) will be lost. . // . // This can show up in two ways: -- line 211 ---------------------------------------- -- line 228 ---------------------------------------- . // None of these user-visible effects should result in any . // cross-crate inconsistencies (getting one behavior in the same . // crate, and a different behavior in another crate) due to the . // limited surface that proc-macros can expose. . // . // IMPORTANT: If this is ever changed, be sure to update . // `rustc_span::hygiene::raw_encode_expn_id` to handle . // encoding `ExpnData` for proc-macro crates. 349,912 ( 0.00%) if s.is_proc_macro { . SyntaxContext::root().encode(s)?; . } else { 174,956 ( 0.00%) span.ctxt.encode(s)?; . } . 174,956 ( 0.00%) if self.is_dummy() { . return TAG_PARTIAL_SPAN.encode(s); . } . . // The Span infrastructure should make sure that this invariant holds: . debug_assert!(span.lo <= span.hi); . 872,384 ( 0.01%) if !s.source_file_cache.0.contains(span.lo) { 1,946 ( 0.00%) let source_map = s.tcx.sess.source_map(); 3,892 ( 0.00%) let source_file_index = source_map.lookup_source_file_idx(span.lo); 1,946 ( 0.00%) s.source_file_cache = 3,892 ( 0.00%) (source_map.files()[source_file_index].clone(), source_file_index); . } . 527,896 ( 0.01%) if !s.source_file_cache.0.contains(span.hi) { . // Unfortunately, macro expansion still sometimes generates Spans . // that malformed in this way. . return TAG_PARTIAL_SPAN.encode(s); . } . . let source_files = s.required_source_files.as_mut().expect("Already encoded SourceMap!"); . // Record the fact that we need to encode the data for this `SourceFile` 174,668 ( 0.00%) source_files.insert(s.source_file_cache.1); . . // There are two possible cases here: . // 1. This span comes from a 'foreign' crate - e.g. some crate upstream of the . // crate we are writing metadata for. When the metadata for *this* crate gets . // deserialized, the deserializer will need to know which crate it originally came . // from. We use `TAG_VALID_SPAN_FOREIGN` to indicate that a `CrateNum` should . // be deserialized after the rest of the span data, which tells the deserializer . // which crate contains the source map information. -- line 272 ---------------------------------------- -- line 274 ---------------------------------------- . // write `TAG_VALID_SPAN_LOCAL` to let the deserializer know that it should use . // our own source map information. . // . // If we're a proc-macro crate, we always treat this as a local `Span`. . // In `encode_source_map`, we serialize foreign `SourceFile`s into our metadata . // if we're a proc-macro crate. . // This allows us to avoid loading the dependencies of proc-macro crates: all of . // the information we need to decode `Span`s is stored in the proc-macro crate. 1,048,008 ( 0.01%) let (tag, lo, hi) = if s.source_file_cache.0.is_imported() && !s.is_proc_macro { . // To simplify deserialization, we 'rebase' this span onto the crate it originally came from . // (the crate that 'owns' the file it references. These rebased 'lo' and 'hi' values . // are relative to the source map information for the 'foreign' crate whose CrateNum . // we write into the metadata. This allows `imported_source_files` to binary . // search through the 'foreign' crate's source map information, using the . // deserialized 'lo' and 'hi' values directly. . // . // All of this logic ensures that the final result of deserialization is a 'normal' . // Span that can be used without any additional trouble. . let external_start_pos = { . // Introduce a new scope so that we drop the 'lock()' temporary 6,648 ( 0.00%) match &*s.source_file_cache.0.external_src.lock() { 2,216 ( 0.00%) ExternalSource::Foreign { original_start_pos, .. } => *original_start_pos, . src => panic!("Unexpected external source {:?}", src), . } . }; 6,648 ( 0.00%) let lo = (span.lo - s.source_file_cache.0.start_pos) + external_start_pos; 2,216 ( 0.00%) let hi = (span.hi - s.source_file_cache.0.start_pos) + external_start_pos; . . (TAG_VALID_SPAN_FOREIGN, lo, hi) . } else { 517,356 ( 0.01%) (TAG_VALID_SPAN_LOCAL, span.lo, span.hi) . }; . . tag.encode(s)?; . lo.encode(s)?; . . // Encode length which is usually less than span.hi and profits more . // from the variable-length integer encoding that we use. . let len = hi - lo; . len.encode(s)?; . 349,336 ( 0.00%) if tag == TAG_VALID_SPAN_FOREIGN { . // This needs to be two lines to avoid holding the `s.source_file_cache` . // while calling `cnum.encode(s)` 8,864 ( 0.00%) let cnum = s.source_file_cache.0.cnum; 6,648 ( 0.00%) cnum.encode(s)?; . } . . Ok(()) 1,399,648 ( 0.02%) } . } . . impl<'a, 'tcx> TyEncoder<'tcx> for EncodeContext<'a, 'tcx> { . const CLEAR_CROSS_CRATE: bool = true; . . fn position(&self) -> usize { . self.opaque.position() . } -- line 331 ---------------------------------------- -- line 361 ---------------------------------------- . } . . /// Helper trait to allow overloading `EncodeContext::lazy` for iterators. . trait EncodeContentsForLazy<'a, 'tcx, T: ?Sized + LazyMeta> { . fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> T::Meta; . } . . impl<'a, 'tcx, T: Encodable>> EncodeContentsForLazy<'a, 'tcx, T> for &T { 9,942 ( 0.00%) fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) { 4,470 ( 0.00%) self.encode(ecx).unwrap() . } . } . . impl<'a, 'tcx, T: Encodable>> EncodeContentsForLazy<'a, 'tcx, T> for T { 18,225 ( 0.00%) fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) { 10,068 ( 0.00%) self.encode(ecx).unwrap() 10,750 ( 0.00%) } . } . . impl<'a, 'tcx, I, T: Encodable>> EncodeContentsForLazy<'a, 'tcx, [T]> for I . where . I: IntoIterator, . I::Item: EncodeContentsForLazy<'a, 'tcx, T>, . { 1,099 ( 0.00%) fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> usize { 8,151 ( 0.00%) self.into_iter().map(|value| value.encode_contents_for_lazy(ecx)).count() 1,413 ( 0.00%) } . } . . // Shorthand for `$self.$tables.$table.set($def_id.index, $self.lazy($value))`, which would . // normally need extra variables to avoid errors about multiple mutable borrows. . macro_rules! record { . ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{ . { . let value = $value; . let lazy = $self.lazy(value); . $self.$tables.$table.set($def_id.index, lazy); . } . }}; . } . . impl<'a, 'tcx> EncodeContext<'a, 'tcx> { 4,620 ( 0.00%) fn emit_lazy_distance( . &mut self, . lazy: Lazy, . ) -> Result<(), ::Error> { . let pos = lazy.position.get(); 2,882 ( 0.00%) let distance = match self.lazy_state { . LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"), 869 ( 0.00%) LazyState::NodeStart(start) => { . let start = start.get(); 1,738 ( 0.00%) assert!(pos <= start); . start - pos . } 55 ( 0.00%) LazyState::Previous(last_pos) => { 55 ( 0.00%) assert!( . last_pos <= lazy.position, . "make sure that the calls to `lazy*` \ . are in the same order as the metadata fields", . ); 165 ( 0.00%) lazy.position.get() - last_pos.get() . } . }; 1,848 ( 0.00%) self.lazy_state = LazyState::Previous(NonZeroUsize::new(pos).unwrap()); . self.emit_usize(distance) 4,620 ( 0.00%) } . 9,897 ( 0.00%) fn lazy( . &mut self, . value: impl EncodeContentsForLazy<'a, 'tcx, T>, . ) -> Lazy { . let pos = NonZeroUsize::new(self.position()).unwrap(); . 12,737 ( 0.00%) assert_eq!(self.lazy_state, LazyState::NoNode); 36,950 ( 0.00%) self.lazy_state = LazyState::NodeStart(pos); 25,449 ( 0.00%) let meta = value.encode_contents_for_lazy(self); 15,644 ( 0.00%) self.lazy_state = LazyState::NoNode; . 26,649 ( 0.00%) assert!(pos.get() <= self.position()); . . Lazy::from_position_and_meta(pos, meta) 14,458 ( 0.00%) } . . fn encode_info_for_items(&mut self) { 9 ( 0.00%) self.encode_info_for_mod(CRATE_DEF_ID, self.tcx.hir().root_module()); . . // Proc-macro crates only export proc-macro items, which are looked . // up using `proc_macro_data` 2 ( 0.00%) if self.is_proc_macro { . return; . } . 6 ( 0.00%) self.tcx.hir().visit_all_item_likes(&mut self.as_deep_visitor()); . } . . fn encode_def_path_table(&mut self) { 4 ( 0.00%) let table = self.tcx.resolutions(()).definitions.def_path_table(); 2 ( 0.00%) if self.is_proc_macro { . for def_index in std::iter::once(CRATE_DEF_INDEX) . .chain(self.tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index)) . { . let def_key = self.lazy(table.def_key(def_index)); . let def_path_hash = self.lazy(table.def_path_hash(def_index)); . self.tables.def_keys.set(def_index, def_key); . self.tables.def_path_hashes.set(def_index, def_path_hash); . } . } else { 5 ( 0.00%) for (def_index, def_key, def_path_hash) in table.enumerated_keys_and_path_hashes() { . let def_key = self.lazy(def_key); . let def_path_hash = self.lazy(def_path_hash); 4,760 ( 0.00%) self.tables.def_keys.set(def_index, def_key); 4,760 ( 0.00%) self.tables.def_path_hashes.set(def_index, def_path_hash); . } . } . } . . fn encode_def_path_hash_map(&mut self) -> Lazy> { . self.lazy(DefPathHashMapRef::BorrowedFromTcx( 2 ( 0.00%) self.tcx.resolutions(()).definitions.def_path_hash_to_def_index_map(), . )) . } . . fn encode_source_map(&mut self) -> Lazy<[rustc_span::SourceFile]> { 2 ( 0.00%) let source_map = self.tcx.sess.source_map(); 3 ( 0.00%) let all_source_files = source_map.files(); . . // By replacing the `Option` with `None`, we ensure that we can't . // accidentally serialize any more `Span`s after the source map encoding . // is done. . let required_source_files = self.required_source_files.take().unwrap(); . . let adapted = all_source_files . .iter() . .enumerate() . .filter(|(idx, source_file)| { . // Only serialize `SourceFile`s that were used . // during the encoding of a `Span` 1,115 ( 0.00%) required_source_files.contains(*idx) && . // Don't serialize imported `SourceFile`s, unless . // we're in a proc-macro crate. 140 ( 0.00%) (!source_file.is_imported() || self.is_proc_macro) . }) . .map(|(_, source_file)| { 57 ( 0.00%) let mut adapted = match source_file.name { . FileName::Real(ref realname) => { 38 ( 0.00%) let mut adapted = (**source_file).clone(); 304 ( 0.00%) adapted.name = FileName::Real(match realname { . RealFileName::LocalPath(path_to_file) => { . // Prepend path of working directory onto potentially . // relative paths, because they could become relative . // to a wrong directory. . // We include `working_dir` as part of the crate hash, . // so it's okay for us to use it as part of the encoded . // metadata. 38 ( 0.00%) let working_dir = &self.tcx.sess.opts.working_dir; 38 ( 0.00%) match working_dir { . RealFileName::LocalPath(absolute) => { . // Although neither working_dir or the file name were subject . // to path remapping, the concatenation between the two may . // be. Hence we need to do a remapping here. . let joined = Path::new(absolute).join(path_to_file); 133 ( 0.00%) let (joined, remapped) = 209 ( 0.00%) source_map.path_mapping().map_prefix(joined); 38 ( 0.00%) if remapped { . RealFileName::Remapped { . local_path: None, . virtual_name: joined, . } . } else { . RealFileName::LocalPath(joined) . } . } -- line 532 ---------------------------------------- -- line 544 ---------------------------------------- . RealFileName::Remapped { local_path: _, virtual_name } => { . RealFileName::Remapped { . // We do not want any local path to be exported into metadata . local_path: None, . virtual_name: virtual_name.clone(), . } . } . }); 38 ( 0.00%) adapted.name_hash = { . let mut hasher: StableHasher = StableHasher::new(); 19 ( 0.00%) adapted.name.hash(&mut hasher); . hasher.finish::() . }; 19 ( 0.00%) Lrc::new(adapted) . } . . // expanded code, not from a file . _ => source_file.clone(), . }; . . // We're serializing this `SourceFile` into our crate metadata, . // so mark it as coming from this crate. . // This also ensures that we don't try to deserialize the . // `CrateNum` for a proc-macro dependency - since proc macro . // dependencies aren't loaded when we deserialize a proc-macro, . // trying to remap the `CrateNum` would fail. 38 ( 0.00%) if self.is_proc_macro { . Lrc::make_mut(&mut adapted).cnum = LOCAL_CRATE; . } . adapted . }) . .collect::>(); . . self.lazy(adapted.iter().map(|rc| &**rc)) . } . 8 ( 0.00%) fn encode_crate_root(&mut self) -> Lazy> { . let mut i = self.position(); . . // Encode the crate deps . let crate_deps = self.encode_crate_deps(); . let dylib_dependency_formats = self.encode_dylib_dependency_formats(); 5 ( 0.00%) let dep_bytes = self.position() - i; . . // Encode the lib features. . i = self.position(); . let lib_features = self.encode_lib_features(); 7 ( 0.00%) let lib_feature_bytes = self.position() - i; . . // Encode the language items. . i = self.position(); . let lang_items = self.encode_lang_items(); . let lang_items_missing = self.encode_lang_items_missing(); 5 ( 0.00%) let lang_item_bytes = self.position() - i; . . // Encode the diagnostic items. . i = self.position(); . let diagnostic_items = self.encode_diagnostic_items(); 5 ( 0.00%) let diagnostic_item_bytes = self.position() - i; . . // Encode the native libraries used . i = self.position(); . let native_libraries = self.encode_native_libraries(); 4 ( 0.00%) let native_lib_bytes = self.position() - i; . . let foreign_modules = self.encode_foreign_modules(); . . // Encode DefPathTable . i = self.position(); . self.encode_def_path_table(); 5 ( 0.00%) let def_path_table_bytes = self.position() - i; . . // Encode the def IDs of traits, for rustdoc and diagnostics. . i = self.position(); . let traits = self.encode_traits(); 5 ( 0.00%) let traits_bytes = self.position() - i; . . // Encode the def IDs of impls, for coherence checking. . i = self.position(); . let impls = self.encode_impls(); 5 ( 0.00%) let impls_bytes = self.position() - i; . 3 ( 0.00%) let tcx = self.tcx; . . // Encode MIR. . i = self.position(); . self.encode_mir(); 5 ( 0.00%) let mir_bytes = self.position() - i; . . // Encode the items. . i = self.position(); . self.encode_def_ids(); . self.encode_info_for_items(); 4 ( 0.00%) let item_bytes = self.position() - i; . . // Encode the allocation index . let interpret_alloc_index = { . let mut interpret_alloc_index = Vec::new(); . let mut n = 0; . trace!("beginning to encode alloc ids"); . loop { . let new_n = self.interpret_allocs.len(); . // if we have found new ids, serialize those, too 2 ( 0.00%) if n == new_n { . // otherwise, abort . break; . } . trace!("encoding {} further alloc ids", new_n - n); . for idx in n..new_n { . let id = self.interpret_allocs[idx]; . let pos = self.position() as u32; . interpret_alloc_index.push(pos); . interpret::specialized_encode_alloc_id(self, tcx, id).unwrap(); . } . n = new_n; . } 6 ( 0.00%) self.lazy(interpret_alloc_index) . }; . . // Encode the proc macro data. This affects 'tables', . // so we need to do this before we encode the tables . i = self.position(); . let proc_macro_data = self.encode_proc_macros(); 4 ( 0.00%) let proc_macro_data_bytes = self.position() - i; . . i = self.position(); 4 ( 0.00%) let tables = self.tables.encode(&mut self.opaque); 4 ( 0.00%) let tables_bytes = self.position() - i; . . // Encode exported symbols info. This is prefetched in `encode_metadata` so we encode . // this as late as possible to give the prefetching as much time as possible to complete. . i = self.position(); . let exported_symbols = tcx.exported_symbols(LOCAL_CRATE); . let exported_symbols = self.encode_exported_symbols(&exported_symbols); 4 ( 0.00%) let exported_symbols_bytes = self.position() - i; . . // Encode the hygiene data, . // IMPORTANT: this *must* be the last thing that we encode (other than `SourceMap`). The process . // of encoding other items (e.g. `optimized_mir`) may cause us to load . // data from the incremental cache. If this causes us to deserialize a `Span`, . // then we may load additional `SyntaxContext`s into the global `HygieneData`. . // Therefore, we need to encode the hygiene data last to ensure that we encode . // any `SyntaxContext`s that might be used. . i = self.position(); . let (syntax_contexts, expn_data, expn_hashes) = self.encode_hygiene(); 5 ( 0.00%) let hygiene_bytes = self.position() - i; . . i = self.position(); . let def_path_hash_map = self.encode_def_path_hash_map(); 1 ( 0.00%) let def_path_hash_map_bytes = self.position() - i; . . // Encode source_map. This needs to be done last, . // since encoding `Span`s tells us which `SourceFiles` we actually . // need to encode. . i = self.position(); . let source_map = self.encode_source_map(); 4 ( 0.00%) let source_map_bytes = self.position() - i; . 3 ( 0.00%) let attrs = tcx.hir().krate_attrs(); 7 ( 0.00%) let has_default_lib_allocator = tcx.sess.contains_name(&attrs, sym::default_lib_allocator); . 118 ( 0.00%) let root = self.lazy(CrateRoot { . name: tcx.crate_name(LOCAL_CRATE), 3 ( 0.00%) extra_filename: tcx.sess.opts.cg.extra_filename.clone(), 1 ( 0.00%) triple: tcx.sess.opts.target_triple.clone(), . hash: tcx.crate_hash(LOCAL_CRATE), . stable_crate_id: tcx.def_path_hash(LOCAL_CRATE.as_def_id()).stable_crate_id(), 3 ( 0.00%) panic_strategy: tcx.sess.panic_strategy(), 3 ( 0.00%) panic_in_drop_strategy: tcx.sess.opts.debugging_opts.panic_in_drop, 2 ( 0.00%) edition: tcx.sess.edition(), . has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE), . has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE), . has_default_lib_allocator, . proc_macro_data, 6 ( 0.00%) compiler_builtins: tcx.sess.contains_name(&attrs, sym::compiler_builtins), 6 ( 0.00%) needs_allocator: tcx.sess.contains_name(&attrs, sym::needs_allocator), 6 ( 0.00%) needs_panic_runtime: tcx.sess.contains_name(&attrs, sym::needs_panic_runtime), 6 ( 0.00%) no_builtins: tcx.sess.contains_name(&attrs, sym::no_builtins), 5 ( 0.00%) panic_runtime: tcx.sess.contains_name(&attrs, sym::panic_runtime), 5 ( 0.00%) profiler_runtime: tcx.sess.contains_name(&attrs, sym::profiler_runtime), 2 ( 0.00%) symbol_mangling_version: tcx.sess.opts.get_symbol_mangling_version(), . . crate_deps, . dylib_dependency_formats, . lib_features, . lang_items, . diagnostic_items, . lang_items_missing, . native_libraries, . foreign_modules, . source_map, . traits, . impls, . exported_symbols, . interpret_alloc_index, 2 ( 0.00%) tables, . syntax_contexts, . expn_data, . expn_hashes, . def_path_hash_map, . }); . 1 ( 0.00%) let total_bytes = self.position(); . 4 ( 0.00%) if tcx.sess.meta_stats() { . let mut zero_bytes = 0; . for e in self.opaque.data.iter() { . if *e == 0 { . zero_bytes += 1; . } . } . . eprintln!("metadata stats:"); -- line 756 ---------------------------------------- -- line 770 ---------------------------------------- . eprintln!(" item bytes: {}", item_bytes); . eprintln!(" table bytes: {}", tables_bytes); . eprintln!(" hygiene bytes: {}", hygiene_bytes); . eprintln!(" zero bytes: {}", zero_bytes); . eprintln!(" total bytes: {}", total_bytes); . } . . root 9 ( 0.00%) } . } . . fn should_encode_visibility(def_kind: DefKind) -> bool { . match def_kind { . DefKind::Mod . | DefKind::Struct . | DefKind::Union . | DefKind::Enum -- line 786 ---------------------------------------- -- line 853 ---------------------------------------- . /// Whether we should encode MIR. . /// . /// Computing, optimizing and encoding the MIR is a relatively expensive operation. . /// We want to avoid this work when not required. Therefore: . /// - we only compute `mir_for_ctfe` on items with const-eval semantics; . /// - we skip `optimized_mir` for check runs. . /// . /// Return a pair, resp. for CTFE and for LLVM. 3,663 ( 0.00%) fn should_encode_mir(tcx: TyCtxt<'_>, def_id: LocalDefId) -> (bool, bool) { 2,035 ( 0.00%) match tcx.def_kind(def_id) { . // Constructors . DefKind::Ctor(_, _) => { 36 ( 0.00%) let mir_opt_base = tcx.sess.opts.output_types.should_codegen() . || tcx.sess.opts.debugging_opts.always_encode_mir; . (true, mir_opt_base) . } . // Constants . DefKind::AnonConst . | DefKind::InlineConst . | DefKind::AssocConst . | DefKind::Static . | DefKind::Const => (true, false), . // Full-fledged functions . DefKind::AssocFn | DefKind::Fn => { . let generics = tcx.generics_of(def_id); 1,474 ( 0.00%) let needs_inline = (generics.requires_monomorphization(tcx) 310 ( 0.00%) || tcx.codegen_fn_attrs(def_id).requests_inline()) 534 ( 0.00%) && tcx.sess.opts.output_types.should_codegen(); . // The function has a `const` modifier or is annotated with `default_method_body_is_const`. 291 ( 0.00%) let is_const_fn = tcx.is_const_fn_raw(def_id.to_def_id()) 1,455 ( 0.00%) || tcx.has_attr(def_id.to_def_id(), sym::default_method_body_is_const); . let always_encode_mir = tcx.sess.opts.debugging_opts.always_encode_mir; 582 ( 0.00%) (is_const_fn, needs_inline || always_encode_mir) . } . // Closures can't be const fn. . DefKind::Closure => { . let generics = tcx.generics_of(def_id); 68 ( 0.00%) let needs_inline = (generics.requires_monomorphization(tcx) . || tcx.codegen_fn_attrs(def_id).requests_inline()) 34 ( 0.00%) && tcx.sess.opts.output_types.should_codegen(); . let always_encode_mir = tcx.sess.opts.debugging_opts.always_encode_mir; 34 ( 0.00%) (false, needs_inline || always_encode_mir) . } . // Generators require optimized MIR to compute layout. . DefKind::Generator => (false, true), . // The others don't have MIR. . _ => (false, false), . } 3,663 ( 0.00%) } . . fn should_encode_variances(def_kind: DefKind) -> bool { . match def_kind { . DefKind::Struct . | DefKind::Union . | DefKind::Enum . | DefKind::Variant . | DefKind::Fn -- line 909 ---------------------------------------- -- line 969 ---------------------------------------- . | DefKind::LifetimeParam . | DefKind::GlobalAsm . | DefKind::ExternCrate => false, . } . } . . impl<'a, 'tcx> EncodeContext<'a, 'tcx> { . fn encode_def_ids(&mut self) { 2 ( 0.00%) if self.is_proc_macro { . return; . } 1 ( 0.00%) let tcx = self.tcx; 3 ( 0.00%) let hir = tcx.hir(); 45 ( 0.00%) for local_id in hir.iter_local_def_id() { . let def_id = local_id.to_def_id(); . let def_kind = tcx.opt_def_kind(local_id); 7,140 ( 0.00%) let def_kind = if let Some(def_kind) = def_kind { def_kind } else { continue }; 15,808 ( 0.00%) record!(self.tables.def_kind[def_id] <- match def_kind { . // Replace Ctor by the enclosing object to avoid leaking details in children crates. . DefKind::Ctor(CtorOf::Struct, _) => DefKind::Struct, . DefKind::Ctor(CtorOf::Variant, _) => DefKind::Variant, . def_kind => def_kind, . }); 2,964 ( 0.00%) record!(self.tables.span[def_id] <- tcx.def_span(def_id)); 11,856 ( 0.00%) record!(self.tables.attributes[def_id] <- tcx.get_attrs(def_id)); 7,904 ( 0.00%) record!(self.tables.expn_that_defined[def_id] <- self.tcx.expn_that_defined(def_id)); . if should_encode_visibility(def_kind) { 4,734 ( 0.00%) record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id)); . } . if should_encode_stability(def_kind) { . self.encode_stability(def_id); . self.encode_const_stability(def_id); 4,656 ( 0.00%) self.encode_deprecation(def_id); . } . if should_encode_variances(def_kind) { 704 ( 0.00%) let v = self.tcx.variances_of(def_id); 2,464 ( 0.00%) record!(self.tables.variances[def_id] <- v); . } . if should_encode_generics(def_kind) { . let g = tcx.generics_of(def_id); 3,080 ( 0.00%) record!(self.tables.generics[def_id] <- g); 9,240 ( 0.00%) record!(self.tables.explicit_predicates[def_id] <- self.tcx.explicit_predicates_of(def_id)); 770 ( 0.00%) let inferred_outlives = self.tcx.inferred_outlives_of(def_id); 908 ( 0.00%) if !inferred_outlives.is_empty() { 9 ( 0.00%) record!(self.tables.inferred_outlives[def_id] <- inferred_outlives); . } . } 6,916 ( 0.00%) if let DefKind::Trait | DefKind::TraitAlias = def_kind { 28 ( 0.00%) record!(self.tables.super_predicates[def_id] <- self.tcx.super_predicates_of(def_id)); . } . } . let inherent_impls = tcx.crate_inherent_impls(()); . for (def_id, implementations) in inherent_impls.inherent_impls.iter() { 11 ( 0.00%) if implementations.is_empty() { . continue; . } 99 ( 0.00%) record!(self.tables.inherent_impls[def_id.to_def_id()] <- implementations.iter().map(|&def_id| { 12 ( 0.00%) assert!(def_id.is_local()); . def_id.index . })); . } . } . 4,564 ( 0.00%) fn encode_item_type(&mut self, def_id: DefId) { . debug!("EncodeContext::encode_item_type({:?})", def_id); 3,912 ( 0.00%) record!(self.tables.ty[def_id] <- self.tcx.type_of(def_id)); 5,216 ( 0.00%) } . . fn encode_enum_variant_info(&mut self, def: &ty::AdtDef, index: VariantIdx) { . let tcx = self.tcx; . let variant = &def.variants[index]; 88 ( 0.00%) let def_id = variant.def_id; . debug!("EncodeContext::encode_enum_variant_info({:?})", def_id); . 132 ( 0.00%) let data = VariantData { 22 ( 0.00%) ctor_kind: variant.ctor_kind, . discr: variant.discr, 22 ( 0.00%) ctor: variant.ctor_def_id.map(|did| did.index), 22 ( 0.00%) is_non_exhaustive: variant.is_field_list_non_exhaustive(), . }; . . record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data))); . record!(self.tables.children[def_id] <- variant.fields.iter().map(|f| { 19 ( 0.00%) assert!(f.did.is_local()); . f.did.index . })); 22 ( 0.00%) self.encode_ident_span(def_id, variant.ident(tcx)); 22 ( 0.00%) self.encode_item_type(def_id); 22 ( 0.00%) if variant.ctor_kind == CtorKind::Fn { . // FIXME(eddyb) encode signature only in `encode_enum_variant_ctor`. 24 ( 0.00%) if let Some(ctor_def_id) = variant.ctor_def_id { . record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(ctor_def_id)); . } . } . } . . fn encode_enum_variant_ctor(&mut self, def: &ty::AdtDef, index: VariantIdx) { . let tcx = self.tcx; . let variant = &def.variants[index]; 80 ( 0.00%) let def_id = variant.ctor_def_id.unwrap(); . debug!("EncodeContext::encode_enum_variant_ctor({:?})", def_id); . . // FIXME(eddyb) encode only the `CtorKind` for constructors. . let data = VariantData { 16 ( 0.00%) ctor_kind: variant.ctor_kind, . discr: variant.discr, . ctor: Some(def_id.index), 16 ( 0.00%) is_non_exhaustive: variant.is_field_list_non_exhaustive(), . }; . 64 ( 0.00%) record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data))); 48 ( 0.00%) self.encode_item_type(def_id); 16 ( 0.00%) if variant.ctor_kind == CtorKind::Fn { . record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); . } . } . 190 ( 0.00%) fn encode_info_for_mod(&mut self, local_def_id: LocalDefId, md: &hir::Mod<'_>) { 38 ( 0.00%) let tcx = self.tcx; . let def_id = local_def_id.to_def_id(); . debug!("EncodeContext::encode_info_for_mod({:?})", def_id); . . // If we are encoding a proc-macro crates, `encode_info_for_mod` will . // only ever get called for the crate root. We still want to encode . // the crate root for consistency with other crates (some of the resolver . // code uses it). However, we skip encoding anything relating to child . // items - we encode information about proc-macros later on. 57 ( 0.00%) let reexports = if !self.is_proc_macro { 38 ( 0.00%) match tcx.module_reexports(local_def_id) { . Some(exports) => self.lazy(exports), . _ => Lazy::empty(), . } . } else { . Lazy::empty() . }; . 76 ( 0.00%) record!(self.tables.kind[def_id] <- EntryKind::Mod(reexports)); 38 ( 0.00%) if self.is_proc_macro { . // Encode this here because we don't do it in encode_def_ids. . record!(self.tables.expn_that_defined[def_id] <- tcx.expn_that_defined(local_def_id)); . } else { . let direct_children = md.item_ids.iter().map(|item_id| item_id.def_id.local_def_index); . // Foreign items are planted into their parent modules from name resolution point of view. 38 ( 0.00%) let tcx = self.tcx; . let foreign_item_children = md . .item_ids . .iter() 2,455 ( 0.00%) .filter_map(|item_id| match tcx.hir().item(*item_id).kind { . hir::ItemKind::ForeignMod { items, .. } => { . Some(items.iter().map(|fi_ref| fi_ref.id.def_id.local_def_index)) . } . _ => None, . }) . .flatten(); . 133 ( 0.00%) record!(self.tables.children[def_id] <- direct_children.chain(foreign_item_children)); . } 152 ( 0.00%) } . . fn encode_field( . &mut self, . adt_def: &ty::AdtDef, . variant_index: VariantIdx, . field_index: usize, . ) { . let variant = &adt_def.variants[variant_index]; . let field = &variant.fields[field_index]; . . let def_id = field.did; . debug!("EncodeContext::encode_field({:?})", def_id); . . record!(self.tables.kind[def_id] <- EntryKind::Field); 124 ( 0.00%) self.encode_ident_span(def_id, field.ident(self.tcx)); 186 ( 0.00%) self.encode_item_type(def_id); . } . . fn encode_struct_ctor(&mut self, adt_def: &ty::AdtDef, def_id: DefId) { . debug!("EncodeContext::encode_struct_ctor({:?})", def_id); . let tcx = self.tcx; . let variant = adt_def.non_enum_variant(); . . let data = VariantData { -- line 1150 ---------------------------------------- -- line 1166 ---------------------------------------- . let bounds = self.tcx.explicit_item_bounds(def_id); . if !bounds.is_empty() { . record!(self.tables.explicit_item_bounds[def_id] <- bounds); . } . } . . fn encode_info_for_trait_item(&mut self, def_id: DefId) { . debug!("EncodeContext::encode_info_for_trait_item({:?})", def_id); 1 ( 0.00%) let tcx = self.tcx; . 7 ( 0.00%) let ast_item = tcx.hir().expect_trait_item(def_id.expect_local()); . let trait_item = tcx.associated_item(def_id); . 5 ( 0.00%) let container = match trait_item.defaultness { . hir::Defaultness::Default { has_value: true } => AssocContainer::TraitWithDefault, . hir::Defaultness::Default { has_value: false } => AssocContainer::TraitRequired, . hir::Defaultness::Final => span_bug!(ast_item.span, "traits cannot have final items"), . }; . 6 ( 0.00%) match trait_item.kind { . ty::AssocKind::Const => { . let rendered = rustc_hir_pretty::to_string( . &(&self.tcx.hir() as &dyn intravisit::Map<'_>), . |s| s.print_trait_item(ast_item), . ); . let rendered_const = self.lazy(RenderedConst(rendered)); . . record!(self.tables.kind[def_id] <- EntryKind::AssocConst( . container, . Default::default(), . rendered_const, . )); . } . ty::AssocKind::Fn => { 2 ( 0.00%) let fn_data = if let hir::TraitItemKind::Fn(m_sig, m) = &ast_item.kind { 2 ( 0.00%) let param_names = match *m { . hir::TraitFn::Required(ref names) => self.encode_fn_param_names(names), . hir::TraitFn::Provided(body) => self.encode_fn_param_names_for_body(body), . }; . FnData { . asyncness: m_sig.header.asyncness, . constness: hir::Constness::NotConst, . param_names, . } -- line 1209 ---------------------------------------- -- line 1217 ---------------------------------------- . }))); . } . ty::AssocKind::Type => { . self.encode_explicit_item_bounds(def_id); . record!(self.tables.kind[def_id] <- EntryKind::AssocType(container)); . } . } . self.encode_ident_span(def_id, ast_item.ident); 3 ( 0.00%) match trait_item.kind { . ty::AssocKind::Const | ty::AssocKind::Fn => { . self.encode_item_type(def_id); . } . ty::AssocKind::Type => { . if trait_item.defaultness.has_value() { . self.encode_item_type(def_id); . } . } . } 1 ( 0.00%) if trait_item.kind == ty::AssocKind::Fn { . record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); . } . } . . fn encode_info_for_impl_item(&mut self, def_id: DefId) { . debug!("EncodeContext::encode_info_for_impl_item({:?})", def_id); 394 ( 0.00%) let tcx = self.tcx; . 1,182 ( 0.00%) let ast_item = self.tcx.hir().expect_impl_item(def_id.expect_local()); 197 ( 0.00%) let impl_item = self.tcx.associated_item(def_id); . 788 ( 0.00%) let container = match impl_item.defaultness { . hir::Defaultness::Default { has_value: true } => AssocContainer::ImplDefault, . hir::Defaultness::Final => AssocContainer::ImplFinal, . hir::Defaultness::Default { has_value: false } => { . span_bug!(ast_item.span, "impl items always have values (currently)") . } . }; . 1,182 ( 0.00%) match impl_item.kind { . ty::AssocKind::Const => { . if let hir::ImplItemKind::Const(_, body_id) = ast_item.kind { . let qualifs = self.tcx.at(ast_item.span).mir_const_qualif(def_id); . . record!(self.tables.kind[def_id] <- EntryKind::AssocConst( . container, . qualifs, . self.encode_rendered_const_for_body(body_id)) . ); . } else { . bug!() . } . } . ty::AssocKind::Fn => { 382 ( 0.00%) let fn_data = if let hir::ImplItemKind::Fn(ref sig, body) = ast_item.kind { . FnData { . asyncness: sig.header.asyncness, . // Can be inside `impl const Trait`, so using sig.header.constness is not reliable 191 ( 0.00%) constness: if self.tcx.is_const_fn_raw(def_id) { . hir::Constness::Const . } else { . hir::Constness::NotConst . }, . param_names: self.encode_fn_param_names_for_body(body), . } . } else { . bug!() -- line 1282 ---------------------------------------- -- line 1286 ---------------------------------------- . container, . has_self: impl_item.fn_has_self_parameter, . }))); . } . ty::AssocKind::Type => { . record!(self.tables.kind[def_id] <- EntryKind::AssocType(container)); . } . } 591 ( 0.00%) self.encode_ident_span(def_id, impl_item.ident(self.tcx)); 985 ( 0.00%) self.encode_item_type(def_id); 788 ( 0.00%) if let Some(trait_item_def_id) = impl_item.trait_item_def_id { . record!(self.tables.trait_item_def_id[def_id] <- trait_item_def_id); . } 197 ( 0.00%) if impl_item.kind == ty::AssocKind::Fn { . record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); . } . } . 800 ( 0.00%) fn encode_fn_param_names_for_body(&mut self, body_id: hir::BodyId) -> Lazy<[Ident]> { 1,837 ( 0.00%) self.lazy(self.tcx.hir().body_param_names(body_id)) 800 ( 0.00%) } . . fn encode_fn_param_names(&mut self, param_names: &[Ident]) -> Lazy<[Ident]> { . self.lazy(param_names.iter()) . } . . fn encode_mir(&mut self) { 3 ( 0.00%) if self.is_proc_macro { . return; . } . . let keys_and_jobs = self . .tcx . .mir_keys(()) . .iter() . .filter_map(|&def_id| { 2,035 ( 0.00%) let (encode_const, encode_opt) = should_encode_mir(self.tcx, def_id); 2,103 ( 0.00%) if encode_const || encode_opt { 588 ( 0.00%) Some((def_id, encode_const, encode_opt)) . } else { . None . } 814 ( 0.00%) }) . .collect::>(); 1,475 ( 0.00%) for (def_id, encode_const, encode_opt) in keys_and_jobs.into_iter() { . debug_assert!(encode_const || encode_opt); . . debug!("EntryBuilder::encode_mir({:?})", def_id); 294 ( 0.00%) if encode_opt { 804 ( 0.00%) record!(self.tables.mir[def_id.to_def_id()] <- self.tcx.optimized_mir(def_id)); . } 294 ( 0.00%) if encode_const { 396 ( 0.00%) record!(self.tables.mir_for_ctfe[def_id.to_def_id()] <- self.tcx.mir_for_ctfe(def_id)); . . // FIXME(generic_const_exprs): this feels wrong to have in `encode_mir` 99 ( 0.00%) let abstract_const = self.tcx.thir_abstract_const(def_id); 396 ( 0.00%) if let Ok(Some(abstract_const)) = abstract_const { . record!(self.tables.thir_abstract_consts[def_id.to_def_id()] <- abstract_const); . } . } 1,176 ( 0.00%) record!(self.tables.promoted_mir[def_id.to_def_id()] <- self.tcx.promoted_mir(def_id)); . . let instance = . ty::InstanceDef::Item(ty::WithOptConstParam::unknown(def_id.to_def_id())); 294 ( 0.00%) let unused = self.tcx.unused_generic_params(instance); 294 ( 0.00%) if !unused.is_empty() { . record!(self.tables.unused_generic_params[def_id.to_def_id()] <- unused); . } . } . } . . fn encode_stability(&mut self, def_id: DefId) { . debug!("EncodeContext::encode_stability({:?})", def_id); . . // The query lookup can take a measurable amount of time in crates with many items. Check if . // the stability attributes are even enabled before using their queries. 6,208 ( 0.00%) if self.feat.staged_api || self.tcx.sess.opts.debugging_opts.force_unstable_if_unmarked { . if let Some(stab) = self.tcx.lookup_stability(def_id) { . record!(self.tables.stability[def_id] <- stab) . } . } . } . . fn encode_const_stability(&mut self, def_id: DefId) { . debug!("EncodeContext::encode_const_stability({:?})", def_id); . . // The query lookup can take a measurable amount of time in crates with many items. Check if . // the stability attributes are even enabled before using their queries. 5,432 ( 0.00%) if self.feat.staged_api || self.tcx.sess.opts.debugging_opts.force_unstable_if_unmarked { . if let Some(stab) = self.tcx.lookup_const_stability(def_id) { . record!(self.tables.const_stability[def_id] <- stab) . } . } . } . 4,656 ( 0.00%) fn encode_deprecation(&mut self, def_id: DefId) { . debug!("EncodeContext::encode_deprecation({:?})", def_id); 3,880 ( 0.00%) if let Some(depr) = self.tcx.lookup_deprecation(def_id) { 9 ( 0.00%) record!(self.tables.deprecation[def_id] <- depr); . } 3,875 ( 0.00%) } . 558 ( 0.00%) fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> Lazy { 279 ( 0.00%) let hir = self.tcx.hir(); 186 ( 0.00%) let body = hir.body(body_id); 744 ( 0.00%) let rendered = rustc_hir_pretty::to_string(&(&hir as &dyn intravisit::Map<'_>), |s| { 279 ( 0.00%) s.print_expr(&body.value) . }); 186 ( 0.00%) let rendered_const = &RenderedConst(rendered); . self.lazy(rendered_const) 651 ( 0.00%) } . 3,249 ( 0.00%) fn encode_info_for_item(&mut self, def_id: DefId, item: &'tcx hir::Item<'tcx>) { . let tcx = self.tcx; . . debug!("EncodeContext::encode_info_for_item({:?})", def_id); . . self.encode_ident_span(def_id, item.ident); . 2,166 ( 0.00%) let entry_kind = match item.kind { . hir::ItemKind::Static(_, hir::Mutability::Mut, _) => EntryKind::MutStatic, . hir::ItemKind::Static(_, hir::Mutability::Not, _) => EntryKind::ImmStatic, 279 ( 0.00%) hir::ItemKind::Const(_, body_id) => { 279 ( 0.00%) let qualifs = self.tcx.at(item.span).mir_const_qualif(def_id); 651 ( 0.00%) EntryKind::Const(qualifs, self.encode_rendered_const_for_body(body_id)) . } 200 ( 0.00%) hir::ItemKind::Fn(ref sig, .., body) => { . let data = FnData { 100 ( 0.00%) asyncness: sig.header.asyncness, 100 ( 0.00%) constness: sig.header.constness, 200 ( 0.00%) param_names: self.encode_fn_param_names_for_body(body), . }; . . EntryKind::Fn(self.lazy(data)) . } 4 ( 0.00%) hir::ItemKind::Macro(ref macro_def) => { . EntryKind::MacroDef(self.lazy(macro_def.clone())) . } . hir::ItemKind::Mod(ref m) => { 216 ( 0.00%) return self.encode_info_for_mod(item.def_id, m); . } . hir::ItemKind::ForeignMod { .. } => EntryKind::ForeignMod, . hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm, . hir::ItemKind::TyAlias(..) => EntryKind::Type, . hir::ItemKind::OpaqueTy(..) => { . self.encode_explicit_item_bounds(def_id); . EntryKind::OpaqueTy . } 60 ( 0.00%) hir::ItemKind::Enum(..) => EntryKind::Enum(self.tcx.adt_def(def_id).repr), . hir::ItemKind::Struct(ref struct_def, _) => { 24 ( 0.00%) let adt_def = self.tcx.adt_def(def_id); 36 ( 0.00%) let variant = adt_def.non_enum_variant(); . . // Encode def_ids for each field and method . // for methods, write all the stuff get_trait_method . // needs to know 48 ( 0.00%) let ctor = struct_def . .ctor_hir_id() . .map(|ctor_hir_id| self.tcx.hir().local_def_id(ctor_hir_id).local_def_index); . . EntryKind::Struct( . self.lazy(VariantData { 12 ( 0.00%) ctor_kind: variant.ctor_kind, 48 ( 0.00%) discr: variant.discr, . ctor, . is_non_exhaustive: variant.is_field_list_non_exhaustive(), . }), 36 ( 0.00%) adt_def.repr, . ) . } . hir::ItemKind::Union(..) => { . let adt_def = self.tcx.adt_def(def_id); . let variant = adt_def.non_enum_variant(); . . EntryKind::Union( . self.lazy(VariantData { -- line 1461 ---------------------------------------- -- line 1462 ---------------------------------------- . ctor_kind: variant.ctor_kind, . discr: variant.discr, . ctor: None, . is_non_exhaustive: variant.is_field_list_non_exhaustive(), . }), . adt_def.repr, . ) . } 484 ( 0.00%) hir::ItemKind::Impl(hir::Impl { defaultness, constness, .. }) => { 460 ( 0.00%) let trait_ref = self.tcx.impl_trait_ref(def_id); 242 ( 0.00%) let polarity = self.tcx.impl_polarity(def_id); 242 ( 0.00%) let parent = if let Some(trait_ref) = trait_ref { 109 ( 0.00%) let trait_def = self.tcx.trait_def(trait_ref.def_id); 654 ( 0.00%) trait_def.ancestors(self.tcx, def_id).ok().and_then(|mut an| { 654 ( 0.00%) an.nth(1).and_then(|node| match node { . specialization_graph::Node::Impl(parent) => Some(parent), . _ => None, . }) . }) . } else { . None . }; . . // if this is an impl of `CoerceUnsized`, create its . // "unsized info", else just store None . let coerce_unsized_info = trait_ref.and_then(|t| { 654 ( 0.00%) if Some(t.def_id) == self.tcx.lang_items().coerce_unsized_trait() { . Some(self.tcx.at(item.span).coerce_unsized_info(def_id)) . } else { . None . } . }); . . let data = ImplData { . polarity, -- line 1496 ---------------------------------------- -- line 1498 ---------------------------------------- . constness, . parent_impl: parent, . coerce_unsized_info, . }; . . EntryKind::Impl(self.lazy(data)) . } . hir::ItemKind::Trait(..) => { 4 ( 0.00%) let trait_def = self.tcx.trait_def(def_id); . let data = TraitData { 2 ( 0.00%) unsafety: trait_def.unsafety, 4 ( 0.00%) paren_sugar: trait_def.paren_sugar, 10 ( 0.00%) has_auto_impl: self.tcx.trait_is_auto(def_id), 2 ( 0.00%) is_marker: trait_def.is_marker, 2 ( 0.00%) skip_array_during_method_dispatch: trait_def.skip_array_during_method_dispatch, 2 ( 0.00%) specialization_kind: trait_def.specialization_kind, . must_implement_one_of: trait_def.must_implement_one_of.clone(), . }; . . EntryKind::Trait(self.lazy(data)) . } . hir::ItemKind::TraitAlias(..) => EntryKind::TraitAlias, . hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => { . bug!("cannot encode info for item {:?}", item) . } . }; . record!(self.tables.kind[def_id] <- entry_kind); . // FIXME(eddyb) there should be a nicer way to do this. 1,715 ( 0.00%) match item.kind { . hir::ItemKind::Enum(..) => record!(self.tables.children[def_id] <- 20 ( 0.00%) self.tcx.adt_def(def_id).variants.iter().map(|v| { 22 ( 0.00%) assert!(v.def_id.is_local()); . v.def_id.index . }) . ), . hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => { . record!(self.tables.children[def_id] <- 36 ( 0.00%) self.tcx.adt_def(def_id).non_enum_variant().fields.iter().map(|f| { 43 ( 0.00%) assert!(f.did.is_local()); . f.did.index . }) . ) . } . hir::ItemKind::Impl { .. } | hir::ItemKind::Trait(..) => { 246 ( 0.00%) let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id); . record!(self.tables.children[def_id] <- . associated_item_def_ids.iter().map(|&def_id| { 198 ( 0.00%) assert!(def_id.is_local()); . def_id.index . }) . ); . } . _ => {} . } 831 ( 0.00%) match item.kind { . hir::ItemKind::Static(..) . | hir::ItemKind::Const(..) . | hir::ItemKind::Fn(..) . | hir::ItemKind::TyAlias(..) . | hir::ItemKind::OpaqueTy(..) . | hir::ItemKind::Enum(..) . | hir::ItemKind::Struct(..) . | hir::ItemKind::Union(..) 1,348 ( 0.00%) | hir::ItemKind::Impl { .. } => self.encode_item_type(def_id), . _ => {} . } 1,023 ( 0.00%) if let hir::ItemKind::Fn(..) = item.kind { 400 ( 0.00%) record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); . } 786 ( 0.00%) if let hir::ItemKind::Impl { .. } = item.kind { 605 ( 0.00%) if let Some(trait_ref) = self.tcx.impl_trait_ref(def_id) { 545 ( 0.00%) record!(self.tables.impl_trait_ref[def_id] <- trait_ref); . } . } 2,744 ( 0.00%) } . . fn encode_info_for_generic_param(&mut self, def_id: DefId, kind: EntryKind, encode_type: bool) { 348 ( 0.00%) record!(self.tables.kind[def_id] <- kind); 116 ( 0.00%) if encode_type { . self.encode_item_type(def_id); . } . } . . fn encode_info_for_closure(&mut self, hir_id: hir::HirId) { 102 ( 0.00%) let def_id = self.tcx.hir().local_def_id(hir_id); . debug!("EncodeContext::encode_info_for_closure({:?})", def_id); . . // NOTE(eddyb) `tcx.type_of(def_id)` isn't used because it's fully generic, . // including on the signature, which is inferred in `typeck. 51 ( 0.00%) let ty = self.tcx.typeck(def_id).node_type(hir_id); . 51 ( 0.00%) match ty.kind() { . ty::Generator(..) => { . let data = self.tcx.generator_kind(def_id).unwrap(); . record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::Generator(data)); . } . . ty::Closure(..) => { . record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::Closure); . } . . _ => bug!("closure that is neither generator nor closure"), . } 68 ( 0.00%) self.encode_item_type(def_id.to_def_id()); 68 ( 0.00%) if let ty::Closure(def_id, substs) = *ty.kind() { 153 ( 0.00%) record!(self.tables.fn_sig[def_id] <- substs.as_closure().sig()); . } . } . . fn encode_info_for_anon_const(&mut self, id: hir::HirId) { . let def_id = self.tcx.hir().local_def_id(id); . debug!("EncodeContext::encode_info_for_anon_const({:?})", def_id); . let body_id = self.tcx.hir().body_owned_by(id); . let const_data = self.encode_rendered_const_for_body(body_id); . let qualifs = self.tcx.mir_const_qualif(def_id); . . record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::AnonConst(qualifs, const_data)); . self.encode_item_type(def_id.to_def_id()); . } . . fn encode_native_libraries(&mut self) -> Lazy<[NativeLib]> { 2 ( 0.00%) empty_proc_macro!(self); 2 ( 0.00%) let used_libraries = self.tcx.native_libraries(LOCAL_CRATE); . self.lazy(used_libraries.iter()) . } . . fn encode_foreign_modules(&mut self) -> Lazy<[ForeignModule]> { 5 ( 0.00%) empty_proc_macro!(self); 2 ( 0.00%) let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE); . self.lazy(foreign_modules.iter().map(|(_, m)| m).cloned()) . } . . fn encode_hygiene(&mut self) -> (SyntaxContextTable, ExpnDataTable, ExpnHashTable) { . let mut syntax_contexts: TableBuilder<_, _> = Default::default(); . let mut expn_data_table: TableBuilder<_, _> = Default::default(); . let mut expn_hash_table: TableBuilder<_, _> = Default::default(); . 2 ( 0.00%) let _: Result<(), !> = self.hygiene_ctxt.encode( 8 ( 0.00%) &mut (&mut *self, &mut syntax_contexts, &mut expn_data_table, &mut expn_hash_table), . |(this, syntax_contexts, _, _), index, ctxt_data| { . syntax_contexts.set(index, this.lazy(ctxt_data)); . Ok(()) . }, . |(this, _, expn_data_table, expn_hash_table), index, expn_data, hash| { . if let Some(index) = index.as_local() { 456 ( 0.00%) expn_data_table.set(index.as_raw(), this.lazy(expn_data)); 456 ( 0.00%) expn_hash_table.set(index.as_raw(), this.lazy(hash)); . } . Ok(()) . }, . ); . . ( . syntax_contexts.encode(&mut self.opaque), . expn_data_table.encode(&mut self.opaque), . expn_hash_table.encode(&mut self.opaque), . ) . } . . fn encode_proc_macros(&mut self) -> Option { 6 ( 0.00%) let is_proc_macro = self.tcx.sess.crate_types().contains(&CrateType::ProcMacro); . if is_proc_macro { . let tcx = self.tcx; . let hir = tcx.hir(); . . let proc_macro_decls_static = tcx.proc_macro_decls_static(()).unwrap().local_def_index; . let stability = tcx.lookup_stability(DefId::local(CRATE_DEF_INDEX)).copied(); . let macros = . self.lazy(tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index)); -- line 1666 ---------------------------------------- -- line 1725 ---------------------------------------- . . Some(ProcMacroData { proc_macro_decls_static, stability, macros }) . } else { . None . } . } . . fn encode_crate_deps(&mut self) -> Lazy<[CrateDep]> { 7 ( 0.00%) empty_proc_macro!(self); . 1 ( 0.00%) let deps = self . .tcx . .crates(()) . .iter() . .map(|&cnum| { . let dep = CrateDep { 20 ( 0.00%) name: self.tcx.crate_name(cnum), 20 ( 0.00%) hash: self.tcx.crate_hash(cnum), 20 ( 0.00%) host_hash: self.tcx.crate_host_hash(cnum), 20 ( 0.00%) kind: self.tcx.dep_kind(cnum), 20 ( 0.00%) extra_filename: self.tcx.extra_filename(cnum), . }; 100 ( 0.00%) (cnum, dep) . }) . .collect::>(); . . { . // Sanity-check the crate numbers . let mut expected_cnum = 1; 40 ( 0.00%) for &(n, _) in &deps { 50 ( 0.00%) assert_eq!(n, CrateNum::new(expected_cnum)); . expected_cnum += 1; . } . } . . // We're just going to write a list of crate 'name-hash-version's, with . // the assumption that they are numbered 1 to n. . // FIXME (#2166): This is not nearly enough to support correct versioning . // but is enough to get transitive crate dependencies working. . self.lazy(deps.iter().map(|&(_, ref dep)| dep)) . } . . fn encode_lib_features(&mut self) -> Lazy<[(Symbol, Option)]> { 2 ( 0.00%) empty_proc_macro!(self); 1 ( 0.00%) let tcx = self.tcx; . let lib_features = tcx.lib_features(()); 2 ( 0.00%) self.lazy(lib_features.to_vec()) . } . . fn encode_diagnostic_items(&mut self) -> Lazy<[(Symbol, DefIndex)]> { 3 ( 0.00%) empty_proc_macro!(self); 1 ( 0.00%) let tcx = self.tcx; . let diagnostic_items = &tcx.diagnostic_items(LOCAL_CRATE).name_to_id; . self.lazy(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index))) . } . . fn encode_lang_items(&mut self) -> Lazy<[(DefIndex, usize)]> { 4 ( 0.00%) empty_proc_macro!(self); 1 ( 0.00%) let tcx = self.tcx; 1 ( 0.00%) let lang_items = tcx.lang_items(); 2 ( 0.00%) let lang_items = lang_items.items().iter(); . self.lazy(lang_items.enumerate().filter_map(|(i, &opt_def_id)| { 568 ( 0.00%) if let Some(def_id) = opt_def_id { . if def_id.is_local() { . return Some((def_id.index, i)); . } . } . None . })) . } . . fn encode_lang_items_missing(&mut self) -> Lazy<[lang_items::LangItem]> { 2 ( 0.00%) empty_proc_macro!(self); 1 ( 0.00%) let tcx = self.tcx; 1 ( 0.00%) self.lazy(&tcx.lang_items().missing) . } . . fn encode_traits(&mut self) -> Lazy<[DefIndex]> { 3 ( 0.00%) empty_proc_macro!(self); 1 ( 0.00%) self.lazy(self.tcx.traits_in_crate(LOCAL_CRATE).iter().map(|def_id| def_id.index)) . } . . /// Encodes an index, mapping each trait to its (local) implementations. . fn encode_impls(&mut self) -> Lazy<[TraitImpls]> { . debug!("EncodeContext::encode_traits_and_impls()"); 2 ( 0.00%) empty_proc_macro!(self); 2 ( 0.00%) let tcx = self.tcx; 5 ( 0.00%) let mut visitor = ImplsVisitor { tcx, impls: FxHashMap::default() }; 4 ( 0.00%) tcx.hir().visit_all_item_likes(&mut visitor); . . let mut all_impls: Vec<_> = visitor.impls.into_iter().collect(); . . // Bring everything into deterministic order for hashing 17 ( 0.00%) all_impls.sort_by_cached_key(|&(trait_def_id, _)| tcx.def_path_hash(trait_def_id)); . . let all_impls: Vec<_> = all_impls . .into_iter() 255 ( 0.00%) .map(|(trait_def_id, mut impls)| { . // Bring everything into deterministic order for hashing 11 ( 0.00%) impls.sort_by_cached_key(|&(index, _)| { 103 ( 0.00%) tcx.hir().def_path_hash(LocalDefId { local_def_index: index }) . }); . 68 ( 0.00%) TraitImpls { . trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index), 51 ( 0.00%) impls: self.lazy(&impls), . } 136 ( 0.00%) }) . .collect(); . . self.lazy(&all_impls) . } . . // Encodes all symbols exported from this crate into the metadata. . // . // This pass is seeded off the reachability list calculated in the . // middle::reachable module but filters out items that either don't have a . // symbol associated with them (they weren't translated) or if they're an FFI . // definition (as that's not defined in this crate). . fn encode_exported_symbols( . &mut self, . exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportLevel)], . ) -> Lazy<[(ExportedSymbol<'tcx>, SymbolExportLevel)]> { 2 ( 0.00%) empty_proc_macro!(self); . // The metadata symbol name is special. It should not show up in . // downstream crates. 9 ( 0.00%) let metadata_symbol_name = SymbolName::new(self.tcx, &metadata_symbol_name(self.tcx)); . . self.lazy( . exported_symbols . .iter() 224 ( 0.00%) .filter(|&&(ref exported_symbol, _)| match *exported_symbol { . ExportedSymbol::NoDefId(symbol_name) => symbol_name != metadata_symbol_name, . _ => true, . }) . .cloned(), . ) . } . . fn encode_dylib_dependency_formats(&mut self) -> Lazy<[Option]> { 2 ( 0.00%) empty_proc_macro!(self); 2 ( 0.00%) let formats = self.tcx.dependency_formats(()); 4 ( 0.00%) for (ty, arr) in formats.iter() { 2 ( 0.00%) if *ty != CrateType::Dylib { . continue; . } . return self.lazy(arr.iter().map(|slot| match *slot { . Linkage::NotLinked | Linkage::IncludedFromDylib => None, . . Linkage::Dynamic => Some(LinkagePreference::RequireDynamic), . Linkage::Static => Some(LinkagePreference::RequireStatic), . })); -- line 1876 ---------------------------------------- -- line 1914 ---------------------------------------- . } . } . . // FIXME(eddyb) make metadata encoding walk over all definitions, instead of HIR. . impl<'a, 'tcx> Visitor<'tcx> for EncodeContext<'a, 'tcx> { . type NestedFilter = nested_filter::OnlyBodies; . . fn nested_visit_map(&mut self) -> Self::Map { 401 ( 0.00%) self.tcx.hir() . } 1,310,202 ( 0.02%) fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) { 145,578 ( 0.00%) intravisit::walk_expr(self, ex); . self.encode_info_for_expr(ex); 1,164,624 ( 0.02%) } . fn visit_anon_const(&mut self, c: &'tcx AnonConst) { . intravisit::walk_anon_const(self, c); . self.encode_info_for_anon_const(c.hir_id); . } . fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { 1,476 ( 0.00%) intravisit::walk_item(self, item); 984 ( 0.00%) match item.kind { . hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {} // ignore these 1,444 ( 0.00%) _ => self.encode_info_for_item(item.def_id.to_def_id(), item), . } 1,968 ( 0.00%) self.encode_addl_info_for_item(item); . } . fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem<'tcx>) { . intravisit::walk_foreign_item(self, ni); . self.encode_info_for_foreign_item(ni.def_id.to_def_id(), ni); . } 3,996 ( 0.00%) fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) { . intravisit::walk_generics(self, generics); . self.encode_info_for_generics(generics); 3,552 ( 0.00%) } . } . . impl<'a, 'tcx> EncodeContext<'a, 'tcx> { 154 ( 0.00%) fn encode_fields(&mut self, adt_def: &ty::AdtDef) { . for (variant_index, variant) in adt_def.variants.iter_enumerated() { . for (field_index, _field) in variant.fields.iter().enumerate() { . self.encode_field(adt_def, variant_index, field_index); . } . } 176 ( 0.00%) } . . fn encode_info_for_generics(&mut self, generics: &hir::Generics<'tcx>) { . for param in generics.params { 1,080 ( 0.00%) let def_id = self.tcx.hir().local_def_id(param.hir_id); 1,280 ( 0.00%) match param.kind { . GenericParamKind::Lifetime { .. } => continue, . GenericParamKind::Type { default, .. } => { . self.encode_info_for_generic_param( . def_id.to_def_id(), . EntryKind::TypeParam, . default.is_some(), . ); . } -- line 1970 ---------------------------------------- -- line 1975 ---------------------------------------- . record!(self.tables.const_defaults[def_id] <- self.tcx.const_param_default(def_id)) . } . } . } . } . } . . fn encode_info_for_expr(&mut self, expr: &hir::Expr<'_>) { 291,156 ( 0.00%) if let hir::ExprKind::Closure(..) = expr.kind { . self.encode_info_for_closure(expr.hir_id); . } . } . . fn encode_ident_span(&mut self, def_id: DefId, ident: Ident) { . record!(self.tables.ident_span[def_id] <- ident.span); . } . . /// In some cases, along with the item itself, we also . /// encode some sub-items. Usually we want some info from the item . /// so it's easier to do that here then to wait until we would encounter . /// normally in the visitor walk. 4,428 ( 0.00%) fn encode_addl_info_for_item(&mut self, item: &hir::Item<'_>) { 2,460 ( 0.00%) match item.kind { . hir::ItemKind::Static(..) . | hir::ItemKind::Const(..) . | hir::ItemKind::Fn(..) . | hir::ItemKind::Macro(..) . | hir::ItemKind::Mod(..) . | hir::ItemKind::ForeignMod { .. } . | hir::ItemKind::GlobalAsm(..) . | hir::ItemKind::ExternCrate(..) . | hir::ItemKind::Use(..) . | hir::ItemKind::TyAlias(..) . | hir::ItemKind::OpaqueTy(..) . | hir::ItemKind::TraitAlias(..) => { . // no sub-item recording needed in these cases . } . hir::ItemKind::Enum(..) => { 10 ( 0.00%) let def = self.tcx.adt_def(item.def_id.to_def_id()); 20 ( 0.00%) self.encode_fields(def); . . for (i, variant) in def.variants.iter_enumerated() { . self.encode_enum_variant_info(def, i); . 66 ( 0.00%) if let Some(_ctor_def_id) = variant.ctor_def_id { . self.encode_enum_variant_ctor(def, i); . } . } . } . hir::ItemKind::Struct(ref struct_def, _) => { 12 ( 0.00%) let def = self.tcx.adt_def(item.def_id.to_def_id()); 24 ( 0.00%) self.encode_fields(def); . . // If the struct has a constructor, encode it. 48 ( 0.00%) if let Some(ctor_hir_id) = struct_def.ctor_hir_id() { . let ctor_def_id = self.tcx.hir().local_def_id(ctor_hir_id); . self.encode_struct_ctor(def, ctor_def_id.to_def_id()); . } . } . hir::ItemKind::Union(..) => { . let def = self.tcx.adt_def(item.def_id.to_def_id()); . self.encode_fields(def); . } . hir::ItemKind::Impl { .. } => { 788 ( 0.00%) for &trait_item_def_id in 121 ( 0.00%) self.tcx.associated_item_def_ids(item.def_id.to_def_id()).iter() . { . self.encode_info_for_impl_item(trait_item_def_id); . } . } . hir::ItemKind::Trait(..) => { 5 ( 0.00%) for &item_def_id in self.tcx.associated_item_def_ids(item.def_id.to_def_id()).iter() . { . self.encode_info_for_trait_item(item_def_id); . } . } . } 3,936 ( 0.00%) } . } . . struct ImplsVisitor<'tcx> { . tcx: TyCtxt<'tcx>, . impls: FxHashMap)>>, . } . . impl<'tcx, 'v> ItemLikeVisitor<'v> for ImplsVisitor<'tcx> { 3,444 ( 0.00%) fn visit_item(&mut self, item: &hir::Item<'_>) { 984 ( 0.00%) match item.kind { . hir::ItemKind::Impl(..) => { 460 ( 0.00%) if let Some(trait_ref) = self.tcx.impl_trait_ref(item.def_id.to_def_id()) { 654 ( 0.00%) let simplified_self_ty = fast_reject::simplify_type( . self.tcx, . trait_ref.self_ty(), . SimplifyParams::No, . StripReferences::No, . ); . . self.impls . .entry(trait_ref.def_id) . .or_default() . .push((item.def_id.local_def_index, simplified_self_ty)); . } . } . _ => {} . } 3,936 ( 0.00%) } . . fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem<'v>) {} . . fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem<'v>) { . // handled in `visit_item` above . } . . fn visit_foreign_item(&mut self, _foreign_item: &'v hir::ForeignItem<'v>) {} -- line 2088 ---------------------------------------- -- line 2146 ---------------------------------------- . } . . #[inline] . pub fn raw_data(&self) -> &[u8] { . &self.raw_data . } . } . 10 ( 0.00%) pub fn encode_metadata(tcx: TyCtxt<'_>) -> EncodedMetadata { 5 ( 0.00%) let _prof_timer = tcx.prof.verbose_generic_activity("generate_crate_metadata"); . . // Since encoding metadata is not in a query, and nothing is cached, . // there's no need to do dep-graph tracking for any of it. . tcx.dep_graph.assert_ignored(); . 7 ( 0.00%) join( 3 ( 0.00%) || encode_metadata_impl(tcx), . || { 5 ( 0.00%) if tcx.sess.threads() == 1 { . return; . } . // Prefetch some queries used by metadata encoding. . // This is not necessary for correctness, but is only done for performance reasons. . // It can be removed if it turns out to cause trouble or be detrimental to performance. . join(|| prefetch_mir(tcx), || tcx.exported_symbols(LOCAL_CRATE)); . }, . ) . .0 9 ( 0.00%) } . 9 ( 0.00%) fn encode_metadata_impl(tcx: TyCtxt<'_>) -> EncodedMetadata { 1 ( 0.00%) let mut encoder = opaque::Encoder::new(vec![]); . encoder.emit_raw_bytes(METADATA_HEADER).unwrap(); . . // Will be filled with the root position after encoding everything. . encoder.emit_raw_bytes(&[0, 0, 0, 0]).unwrap(); . 2 ( 0.00%) let source_map_files = tcx.sess.source_map().files(); 3 ( 0.00%) let source_file_cache = (source_map_files[0].clone(), 0); 2 ( 0.00%) let required_source_files = Some(GrowableBitSet::with_capacity(source_map_files.len())); . drop(source_map_files); . . let hygiene_ctxt = HygieneEncodeContext::default(); . 35 ( 0.00%) let mut ecx = EncodeContext { 4 ( 0.00%) opaque: encoder, . tcx, 2 ( 0.00%) feat: tcx.features(), . tables: Default::default(), . lazy_state: LazyState::NoNode, . type_shorthands: Default::default(), . predicate_shorthands: Default::default(), 4 ( 0.00%) source_file_cache, . interpret_allocs: Default::default(), 4 ( 0.00%) required_source_files, 2 ( 0.00%) is_proc_macro: tcx.sess.crate_types().contains(&CrateType::ProcMacro), . hygiene_ctxt: &hygiene_ctxt, . }; . . // Encode the rustc version string in a predictable location. . rustc_version().encode(&mut ecx).unwrap(); . . // Encode all the entries and extra information in the crate, . // culminating in the `CrateRoot` which points to all of it. 1 ( 0.00%) let root = ecx.encode_crate_root(); . 7 ( 0.00%) let mut result = ecx.opaque.into_inner(); . . // Encode the root position. . let header = METADATA_HEADER.len(); . let pos = root.position.get(); 3 ( 0.00%) result[header + 0] = (pos >> 24) as u8; 3 ( 0.00%) result[header + 1] = (pos >> 16) as u8; 1 ( 0.00%) result[header + 2] = (pos >> 8) as u8; 5 ( 0.00%) result[header + 3] = (pos >> 0) as u8; . . // Record metadata size for self-profiling . tcx.prof.artifact_size("crate_metadata", "crate_metadata", result.len() as u64); . 5 ( 0.00%) EncodedMetadata { raw_data: result } 12 ( 0.00%) } . . pub fn provide(providers: &mut Providers) { 2 ( 0.00%) *providers = Providers { . traits_in_crate: |tcx, cnum| { 1 ( 0.00%) assert_eq!(cnum, LOCAL_CRATE); . 1 ( 0.00%) #[derive(Default)] . struct TraitsVisitor { . traits: Vec, . } . impl ItemLikeVisitor<'_> for TraitsVisitor { . fn visit_item(&mut self, item: &hir::Item<'_>) { 1,968 ( 0.00%) if let hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) = item.kind { 2 ( 0.00%) self.traits.push(item.def_id.to_def_id()); . } . } . fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem<'_>) {} . fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem<'_>) {} . fn visit_foreign_item(&mut self, _foreign_item: &hir::ForeignItem<'_>) {} . } . . let mut visitor = TraitsVisitor::default(); 4 ( 0.00%) tcx.hir().visit_all_item_likes(&mut visitor); . // Bring everything into deterministic order. 2 ( 0.00%) visitor.traits.sort_by_cached_key(|&def_id| tcx.def_path_hash(def_id)); . tcx.arena.alloc_slice(&visitor.traits) . }, . . ..*providers . }; . } 401,019 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_passes/src/region.rs -------------------------------------------------------------------------------- Ir -- line 71 ---------------------------------------- . } . . /// Records the lifetime of a local variable as `cx.var_parent` . fn record_var_lifetime( . visitor: &mut RegionResolutionVisitor<'_>, . var_id: hir::ItemLocalId, . _sp: Span, . ) { 2,622 ( 0.00%) match visitor.cx.var_parent { . None => { . // this can happen in extern fn declarations like . // . // extern fn isalnum(c: c_int) -> c_int . } 3,496 ( 0.00%) Some((parent_scope, _)) => visitor.scope_tree.record_var_scope(var_id, parent_scope), . } . } . . fn resolve_block<'tcx>(visitor: &mut RegionResolutionVisitor<'tcx>, blk: &'tcx hir::Block<'tcx>) { . debug!("resolve_block(blk.hir_id={:?})", blk.hir_id); . 3,744 ( 0.00%) let prev_cx = visitor.cx; . . // We treat the tail expression in the block (if any) somewhat . // differently from the statements. The issue has to do with . // temporary lifetimes. Consider the following: . // . // quux({ . // let inner = ... (&bar()) ...; . // -- line 100 ---------------------------------------- -- line 111 ---------------------------------------- . // tail expression for the block are assigned lifetimes so that . // they will be cleaned up as part of the terminating scope . // *surrounding* the block expression. Here, the terminating . // scope for the block expression is the `quux(..)` call; so . // those temporaries will only be cleaned up *after* both . // `other_argument()` has run and also the call to `quux(..)` . // itself has returned. . 1,872 ( 0.00%) visitor.enter_node_scope_with_dtor(blk.hir_id.local_id); 3,120 ( 0.00%) visitor.cx.var_parent = visitor.cx.parent; . . { . // This block should be kept approximately in sync with . // `intravisit::walk_block`. (We manually walk the block, rather . // than call `walk_block`, in order to maintain precise . // index information.) . 624 ( 0.00%) for (i, statement) in blk.stmts.iter().enumerate() { 876 ( 0.00%) match statement.kind { . hir::StmtKind::Local(..) | hir::StmtKind::Item(..) => { . // Each declaration introduces a subscope for bindings . // introduced by the declaration; this subscope covers a . // suffix of the block. Each subscope in a block has the . // previous subscope in the block as a parent, except for . // the first such subscope, which has the block itself as a . // parent. . visitor.enter_scope(Scope { . id: blk.hir_id.local_id, . data: ScopeData::Remainder(FirstStatementIndex::new(i)), . }); 1,115 ( 0.00%) visitor.cx.var_parent = visitor.cx.parent; . } . hir::StmtKind::Expr(..) | hir::StmtKind::Semi(..) => {} . } . visitor.visit_stmt(statement) . } 1,674 ( 0.00%) walk_list!(visitor, visit_expr, &blk.expr); . } . 3,120 ( 0.00%) visitor.cx = prev_cx; . } . . fn resolve_arm<'tcx>(visitor: &mut RegionResolutionVisitor<'tcx>, arm: &'tcx hir::Arm<'tcx>) { 828 ( 0.00%) let prev_cx = visitor.cx; . 207 ( 0.00%) visitor.enter_scope(Scope { id: arm.hir_id.local_id, data: ScopeData::Node }); 828 ( 0.00%) visitor.cx.var_parent = visitor.cx.parent; . 414 ( 0.00%) visitor.terminating_scopes.insert(arm.body.hir_id.local_id); . 621 ( 0.00%) if let Some(hir::Guard::If(ref expr)) = arm.guard { . visitor.terminating_scopes.insert(expr.hir_id.local_id); . } . . intravisit::walk_arm(visitor, arm); . 828 ( 0.00%) visitor.cx = prev_cx; . } . . fn resolve_pat<'tcx>(visitor: &mut RegionResolutionVisitor<'tcx>, pat: &'tcx hir::Pat<'tcx>) { 1,347 ( 0.00%) visitor.record_child_scope(Scope { id: pat.hir_id.local_id, data: ScopeData::Node }); . . // If this is a binding then record the lifetime of that binding. 2,694 ( 0.00%) if let PatKind::Binding(..) = pat.kind { . record_var_lifetime(visitor, pat.hir_id.local_id, pat.span); . } . . debug!("resolve_pat - pre-increment {} pat = {:?}", visitor.expr_and_pat_count, pat); . 4,041 ( 0.00%) intravisit::walk_pat(visitor, pat); . 5,388 ( 0.00%) visitor.expr_and_pat_count += 1; . . debug!("resolve_pat - post-increment {} pat = {:?}", visitor.expr_and_pat_count, pat); . } . . fn resolve_stmt<'tcx>(visitor: &mut RegionResolutionVisitor<'tcx>, stmt: &'tcx hir::Stmt<'tcx>) { 876 ( 0.00%) let stmt_id = stmt.hir_id.local_id; . debug!("resolve_stmt(stmt.id={:?})", stmt_id); . . // Every statement will clean up the temporaries created during . // execution of that statement. Therefore each statement has an . // associated destruction scope that represents the scope of the . // statement plus its destructors, and thus the scope for which . // regions referenced by the destructors need to survive. . visitor.terminating_scopes.insert(stmt_id); . 1,752 ( 0.00%) let prev_parent = visitor.cx.parent; 1,314 ( 0.00%) visitor.enter_node_scope_with_dtor(stmt_id); . . intravisit::walk_stmt(visitor, stmt); . 1,752 ( 0.00%) visitor.cx.parent = prev_parent; . } . . fn resolve_expr<'tcx>(visitor: &mut RegionResolutionVisitor<'tcx>, expr: &'tcx hir::Expr<'tcx>) { . debug!("resolve_expr - pre-increment {} expr = {:?}", visitor.expr_and_pat_count, expr); . 582,312 ( 0.01%) let prev_cx = visitor.cx; 291,156 ( 0.00%) visitor.enter_node_scope_with_dtor(expr.hir_id.local_id); . . { . let terminating_scopes = &mut visitor.terminating_scopes; . let mut terminating = |id: hir::ItemLocalId| { . terminating_scopes.insert(id); . }; 583,384 ( 0.01%) match expr.kind { . // Conditional or repeating scopes are always terminating . // scopes, meaning that temporaries cannot outlive them. . // This ensures fixed size stacks. . hir::ExprKind::Binary( . source_map::Spanned { node: hir::BinOpKind::And, .. }, . _, . ref r, . ) -- line 225 ---------------------------------------- -- line 229 ---------------------------------------- . ref r, . ) => { . // For shortcircuiting operators, mark the RHS as a terminating . // scope since it only executes conditionally. . terminating(r.hir_id.local_id); . } . . hir::ExprKind::If(_, ref then, Some(ref otherwise)) => { 126 ( 0.00%) terminating(then.hir_id.local_id); . terminating(otherwise.hir_id.local_id); . } . . hir::ExprKind::If(_, ref then, None) => { 39 ( 0.00%) terminating(then.hir_id.local_id); . } . . hir::ExprKind::Loop(ref body, _, _, _) => { 57 ( 0.00%) terminating(body.hir_id.local_id); . } . . hir::ExprKind::DropTemps(ref expr) => { . // `DropTemps(expr)` does not denote a conditional scope. . // Rather, we want to achieve the same behavior as `{ let _t = expr; _t }`. 196 ( 0.00%) terminating(expr.hir_id.local_id); . } . . hir::ExprKind::AssignOp(..) . | hir::ExprKind::Index(..) . | hir::ExprKind::Unary(..) . | hir::ExprKind::Call(..) . | hir::ExprKind::MethodCall(..) => { . // FIXME(https://github.com/rust-lang/rfcs/issues/811) Nested method calls -- line 260 ---------------------------------------- -- line 276 ---------------------------------------- . // . // record_superlifetime(new_cx, expr.callee_id); . } . . _ => {} . } . } . 20 ( 0.00%) let prev_pessimistic = visitor.pessimistic_yield; . . // Ordinarily, we can rely on the visit order of HIR intravisit . // to correspond to the actual execution order of statements. . // However, there's a weird corner case with compound assignment . // operators (e.g. `a += b`). The evaluation order depends on whether . // or not the operator is overloaded (e.g. whether or not a trait . // like AddAssign is implemented). . -- line 292 ---------------------------------------- -- line 328 ---------------------------------------- . // about what types could possibly live across yield points, . // but we will never fail to detect that a type does actually . // live across a yield point. The latter part is critical - . // we're already overly conservative about what types will live . // across yield points, as the generated MIR will determine . // when things are actually live. However, for typecheck to work . // properly, we can't miss any types. . 873,672 ( 0.01%) match expr.kind { . // Manually recurse over closures and inline consts, because they are the only . // case of nested bodies that share the parent environment. 34 ( 0.00%) hir::ExprKind::Closure(.., body, _, _) . | hir::ExprKind::ConstBlock(hir::AnonConst { body, .. }) => { 68 ( 0.00%) let body = visitor.tcx.hir().body(body); 51 ( 0.00%) visitor.visit_body(body); . } . hir::ExprKind::AssignOp(_, ref left_expr, ref right_expr) => { . debug!( . "resolve_expr - enabling pessimistic_yield, was previously {}", . prev_pessimistic . ); . 20 ( 0.00%) let start_point = visitor.fixup_scopes.len(); 20 ( 0.00%) visitor.pessimistic_yield = true; . . // If the actual execution order turns out to be right-to-left, . // then we're fine. However, if the actual execution order is left-to-right, . // then we'll assign too low a count to any `yield` expressions . // we encounter in 'right_expression' - they should really occur after all of the . // expressions in 'left_expression'. 100 ( 0.00%) visitor.visit_expr(&right_expr); 20 ( 0.00%) visitor.pessimistic_yield = prev_pessimistic; . . debug!("resolve_expr - restoring pessimistic_yield to {}", prev_pessimistic); 80 ( 0.00%) visitor.visit_expr(&left_expr); . debug!("resolve_expr - fixing up counts to {}", visitor.expr_and_pat_count); . . // Remove and process any scopes pushed by the visitor . let target_scopes = visitor.fixup_scopes.drain(start_point..); . 100 ( 0.00%) for scope in target_scopes { . let mut yield_data = . visitor.scope_tree.yield_in_scope.get_mut(&scope).unwrap().last_mut().unwrap(); . let count = yield_data.expr_and_pat_count; . let span = yield_data.span; . . // expr_and_pat_count never decreases. Since we recorded counts in yield_in_scope . // before walking the left-hand side, it should be impossible for the recorded . // count to be greater than the left-hand side count. -- line 376 ---------------------------------------- -- line 388 ---------------------------------------- . scope, count, new_count, span . ); . . yield_data.expr_and_pat_count = new_count; . } . } . . hir::ExprKind::If(ref cond, ref then, Some(ref otherwise)) => { 252 ( 0.00%) let expr_cx = visitor.cx; 126 ( 0.00%) visitor.enter_scope(Scope { id: then.hir_id.local_id, data: ScopeData::IfThen }); 315 ( 0.00%) visitor.cx.var_parent = visitor.cx.parent; 252 ( 0.00%) visitor.visit_expr(cond); 189 ( 0.00%) visitor.visit_expr(then); 252 ( 0.00%) visitor.cx = expr_cx; 189 ( 0.00%) visitor.visit_expr(otherwise); . } . . hir::ExprKind::If(ref cond, ref then, None) => { 156 ( 0.00%) let expr_cx = visitor.cx; 78 ( 0.00%) visitor.enter_scope(Scope { id: then.hir_id.local_id, data: ScopeData::IfThen }); 195 ( 0.00%) visitor.cx.var_parent = visitor.cx.parent; 156 ( 0.00%) visitor.visit_expr(cond); 117 ( 0.00%) visitor.visit_expr(then); 156 ( 0.00%) visitor.cx = expr_cx; . } . 436,317 ( 0.01%) _ => intravisit::walk_expr(visitor, expr), . } . 582,312 ( 0.01%) visitor.expr_and_pat_count += 1; . . debug!("resolve_expr post-increment {}, expr = {:?}", visitor.expr_and_pat_count, expr); . 291,156 ( 0.00%) if let hir::ExprKind::Yield(_, source) = &expr.kind { . // Mark this expr's scope and all parent scopes as containing `yield`. . let mut scope = Scope { id: expr.hir_id.local_id, data: ScopeData::Node }; . loop { . let span = match expr.kind { . hir::ExprKind::Yield(expr, hir::YieldSource::Await { .. }) => { . expr.span.shrink_to_hi().to(expr.span) . } . _ => expr.span, -- line 429 ---------------------------------------- -- line 449 ---------------------------------------- . ScopeData::CallSite => break, . _ => scope = superscope, . }, . None => break, . } . } . } . 727,890 ( 0.01%) visitor.cx = prev_cx; . } . . fn resolve_local<'tcx>( . visitor: &mut RegionResolutionVisitor<'tcx>, . pat: Option<&'tcx hir::Pat<'tcx>>, . init: Option<&'tcx hir::Expr<'tcx>>, . ) { . debug!("resolve_local(pat={:?}, init={:?})", pat, init); . 93 ( 0.00%) let blk_scope = visitor.cx.var_parent.map(|(p, _)| p); . . // As an exception to the normal rules governing temporary . // lifetimes, initializers in a let have a temporary lifetime . // of the enclosing block. This means that e.g., a program . // like the following is legal: . // . // let ref x = HashMap::new(); . // -- line 475 ---------------------------------------- -- line 517 ---------------------------------------- . // rvalue). For example: . // . // let ref x = [&a(), &b()]; . // . // Here, the expression `[...]` has an extended lifetime due to rule . // A, but the inner rvalues `a()` and `b()` have an extended lifetime . // due to rule C. . 444 ( 0.00%) if let Some(expr) = init { 1,503 ( 0.00%) record_rvalue_scope_if_borrow_expr(visitor, &expr, blk_scope); . . if let Some(pat) = pat { 816 ( 0.00%) if is_binding_pat(pat) { . record_rvalue_scope(visitor, &expr, blk_scope); . } . } . } . . // Make sure we visit the initializer first, so expr_and_pat_count remains correct . if let Some(expr) = init { 1,095 ( 0.00%) visitor.visit_expr(expr); . } . if let Some(pat) = pat { 2,220 ( 0.00%) visitor.visit_pat(pat); . } . . /// Returns `true` if `pat` match the `P&` non-terminal. . /// . /// ```text . /// P& = ref X . /// | StructName { ..., P&, ... } . /// | VariantName(..., P&, ...) . /// | [ ..., P&, ... ] . /// | ( ..., P&, ... ) . /// | ... "|" P& "|" ... . /// | box P& . /// ``` 824 ( 0.00%) fn is_binding_pat(pat: &hir::Pat<'_>) -> bool { . // Note that the code below looks for *explicit* refs only, that is, it won't . // know about *implicit* refs as introduced in #42640. . // . // This is not a problem. For example, consider . // . // let (ref x, ref y) = (Foo { .. }, Bar { .. }); . // . // Due to the explicit refs on the left hand side, the below code would signal -- line 562 ---------------------------------------- -- line 570 ---------------------------------------- . // . // in place of . // . // let Foo { ref x, .. } = Foo { ... }; . // . // In the former case (the implicit ref version), the temporary is created by the . // & expression, and its lifetime would be extended to the end of the block (due . // to a different rule, not the below code). 948 ( 0.00%) match pat.kind { . PatKind::Binding(hir::BindingAnnotation::Ref, ..) . | PatKind::Binding(hir::BindingAnnotation::RefMut, ..) => true, . . PatKind::Struct(_, ref field_pats, _) => { . field_pats.iter().any(|fp| is_binding_pat(&fp.pat)) . } . . PatKind::Slice(ref pats1, ref pats2, ref pats3) => { . pats1.iter().any(|p| is_binding_pat(&p)) . || pats2.iter().any(|p| is_binding_pat(&p)) . || pats3.iter().any(|p| is_binding_pat(&p)) . } . . PatKind::Or(ref subpats) . | PatKind::TupleStruct(_, ref subpats, _) 6 ( 0.00%) | PatKind::Tuple(ref subpats, _) => subpats.iter().any(|p| is_binding_pat(&p)), . . PatKind::Box(ref subpat) => is_binding_pat(&subpat), . . PatKind::Ref(_, _) . | PatKind::Binding( . hir::BindingAnnotation::Unannotated | hir::BindingAnnotation::Mutable, . .., . ) . | PatKind::Wild . | PatKind::Path(_) . | PatKind::Lit(_) . | PatKind::Range(_, _, _) => false, . } 824 ( 0.00%) } . . /// If `expr` matches the `E&` grammar, then records an extended rvalue scope as appropriate: . /// . /// ```text . /// E& = & ET . /// | StructName { ..., f: E&, ... } . /// | [ ..., E&, ... ] . /// | ( ..., E&, ... ) . /// | {...; E&} . /// | box E& . /// | E& as ... . /// | ( E& ) . /// ``` 1,676,604 ( 0.02%) fn record_rvalue_scope_if_borrow_expr<'tcx>( . visitor: &mut RegionResolutionVisitor<'tcx>, . expr: &hir::Expr<'_>, . blk_id: Option, . ) { 558,904 ( 0.01%) match expr.kind { . hir::ExprKind::AddrOf(_, _, ref subexpr) => { 6,600 ( 0.00%) record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id); . record_rvalue_scope(visitor, &subexpr, blk_id); . } 91 ( 0.00%) hir::ExprKind::Struct(_, fields, _) => { . for field in fields { 2,730 ( 0.00%) record_rvalue_scope_if_borrow_expr(visitor, &field.expr, blk_id); . } . } . hir::ExprKind::Array(subexprs) | hir::ExprKind::Tup(subexprs) => { . for subexpr in subexprs { 691,070 ( 0.01%) record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id); . } . } . hir::ExprKind::Cast(ref subexpr, _) => { . record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id) . } . hir::ExprKind::Block(ref block, _) => { 36 ( 0.00%) if let Some(ref subexpr) = block.expr { . record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id); . } . } . _ => {} . } 1,117,736 ( 0.02%) } . . /// Applied to an expression `expr` if `expr` -- or something owned or partially owned by . /// `expr` -- is going to be indirectly referenced by a variable in a let statement. In that . /// case, the "temporary lifetime" or `expr` is extended to be the block enclosing the `let` . /// statement. . /// . /// More formally, if `expr` matches the grammar `ET`, record the rvalue scope of the matching . /// `` as `blk_id`: -- line 660 ---------------------------------------- -- line 675 ---------------------------------------- . ) { . let mut expr = expr; . loop { . // Note: give all the expressions matching `ET` with the . // extended temporary lifetime, not just the innermost rvalue, . // because in codegen if we must compile e.g., `*rvalue()` . // into a temporary, we request the temporary scope of the . // outer expression. 3,335 ( 0.00%) visitor.scope_tree.record_rvalue_scope(expr.hir_id.local_id, blk_scope); . 2,668 ( 0.00%) match expr.kind { . hir::ExprKind::AddrOf(_, _, ref subexpr) . | hir::ExprKind::Unary(hir::UnOp::Deref, ref subexpr) 4 ( 0.00%) | hir::ExprKind::Field(ref subexpr, _) . | hir::ExprKind::Index(ref subexpr, _) => { 11 ( 0.00%) expr = &subexpr; . } . _ => { . return; . } . } . } . } . } . . impl<'tcx> RegionResolutionVisitor<'tcx> { . /// Records the current parent (if any) as the parent of `child_scope`. . /// Returns the depth of `child_scope`. . fn record_child_scope(&mut self, child_scope: Scope) -> ScopeDepth { 301,437 ( 0.00%) let parent = self.cx.parent; 1,056,942 ( 0.02%) self.scope_tree.record_scope_parent(child_scope, parent); . // If `child_scope` has no parent, it must be the root node, and so has . // a depth of 1. Otherwise, its depth is one more than its parent's. 297,930 ( 0.00%) parent.map_or(1, |(_p, d)| d + 1) . } . . /// Records the current parent (if any) as the parent of `child_scope`, . /// and sets `child_scope` as the new current parent. . fn enter_scope(&mut self, child_scope: Scope) { . let child_depth = self.record_child_scope(child_scope); 448,448 ( 0.01%) self.cx.parent = Some((child_scope, child_depth)); . } . 1,026,480 ( 0.01%) fn enter_node_scope_with_dtor(&mut self, id: hir::ItemLocalId) { . // If node was previously marked as a terminating scope during the . // recursive visit of its parent node in the AST, then we need to . // account for the destruction scope representing the scope of . // the destructors that run immediately after it completes. 293,280 ( 0.00%) if self.terminating_scopes.contains(&id) { 1,375 ( 0.00%) self.enter_scope(Scope { id, data: ScopeData::Destruction }); . } 146,640 ( 0.00%) self.enter_scope(Scope { id, data: ScopeData::Node }); 879,840 ( 0.01%) } . } . . impl<'tcx> Visitor<'tcx> for RegionResolutionVisitor<'tcx> { 5,616 ( 0.00%) fn visit_block(&mut self, b: &'tcx Block<'tcx>) { . resolve_block(self, b); 4,992 ( 0.00%) } . 3,609 ( 0.00%) fn visit_body(&mut self, body: &'tcx hir::Body<'tcx>) { 1,203 ( 0.00%) let body_id = body.id(); 3,208 ( 0.00%) let owner_id = self.tcx.hir().body_owner(body_id); . . debug!( . "visit_body(id={:?}, span={:?}, body.id={:?}, cx.parent={:?})", . owner_id, . self.tcx.sess.source_map().span_to_diagnostic_string(body.value.span), . body_id, . self.cx.parent . ); . . // Save all state that is specific to the outer function . // body. These will be restored once down below, once we've . // visited the body. . let outer_ec = mem::replace(&mut self.expr_and_pat_count, 0); 1,604 ( 0.00%) let outer_cx = self.cx; 401 ( 0.00%) let outer_ts = mem::take(&mut self.terminating_scopes); . // The 'pessimistic yield' flag is set to true when we are . // processing a `+=` statement and have to make pessimistic . // control flow assumptions. This doesn't apply to nested . // bodies within the `+=` statements. See #69307. . let outer_pessimistic_yield = mem::replace(&mut self.pessimistic_yield, false); 802 ( 0.00%) self.terminating_scopes.insert(body.value.hir_id.local_id); . 401 ( 0.00%) self.enter_scope(Scope { id: body.value.hir_id.local_id, data: ScopeData::CallSite }); 401 ( 0.00%) self.enter_scope(Scope { id: body.value.hir_id.local_id, data: ScopeData::Arguments }); . . // The arguments and `self` are parented to the fn. 802 ( 0.00%) self.cx.var_parent = self.cx.parent.take(); 2,807 ( 0.00%) for param in body.params { 2,210 ( 0.00%) self.visit_pat(¶m.pat); . } . . // The body of the every fn is a root scope. 1,604 ( 0.00%) self.cx.parent = self.cx.var_parent; 4,411 ( 0.00%) if self.tcx.hir().body_owner_kind(owner_id).is_fn_or_closure() { 1,232 ( 0.00%) self.visit_expr(&body.value) . } else { . // Only functions have an outer terminating (drop) scope, while . // temporaries in constant initializers may be 'static, but only . // according to rvalue lifetime semantics, using the same . // syntactical rules used for let initializers. . // . // e.g., in `let x = &f();`, the temporary holding the result from . // the `f()` call lives for the entirety of the surrounding block. -- line 780 ---------------------------------------- -- line 784 ---------------------------------------- . // ever get lifted) that the value *could* have a destructor, but . // it'd get leaked instead of the destructor running during the . // evaluation of `X` (if at all allowed by CTFE). . // . // However, `const Y: ... = g(&f());`, like `let y = g(&f());`, . // would *not* let the `f()` temporary escape into an outer scope . // (i.e., `'static`), which means that after `g` returns, it drops, . // and all the associated destruction scope rules apply. 93 ( 0.00%) self.cx.var_parent = None; . resolve_local(self, None, Some(&body.value)); . } . 401 ( 0.00%) if body.generator_kind.is_some() { . self.scope_tree.body_expr_count.insert(body_id, self.expr_and_pat_count); . } . . // Restore context we had at the start. 401 ( 0.00%) self.expr_and_pat_count = outer_ec; 1,604 ( 0.00%) self.cx = outer_cx; 2,005 ( 0.00%) self.terminating_scopes = outer_ts; 401 ( 0.00%) self.pessimistic_yield = outer_pessimistic_yield; 3,208 ( 0.00%) } . 1,863 ( 0.00%) fn visit_arm(&mut self, a: &'tcx Arm<'tcx>) { . resolve_arm(self, a); 1,656 ( 0.00%) } 12,123 ( 0.00%) fn visit_pat(&mut self, p: &'tcx Pat<'tcx>) { . resolve_pat(self, p); 10,776 ( 0.00%) } . fn visit_stmt(&mut self, s: &'tcx Stmt<'tcx>) { . resolve_stmt(self, s); . } 1,310,202 ( 0.02%) fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) { . resolve_expr(self, ex); 1,164,624 ( 0.02%) } 1,776 ( 0.00%) fn visit_local(&mut self, l: &'tcx Local<'tcx>) { 444 ( 0.00%) resolve_local(self, Some(&l.pat), l.init); . } . } . 5,530 ( 0.00%) fn region_scope_tree(tcx: TyCtxt<'_>, def_id: DefId) -> &ScopeTree { 1,659 ( 0.00%) let typeck_root_def_id = tcx.typeck_root_def_id(def_id); 1,659 ( 0.00%) if typeck_root_def_id != def_id { . return tcx.region_scope_tree(typeck_root_def_id); . } . . let id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local()); 2,680 ( 0.00%) let scope_tree = if let Some(body_id) = tcx.hir().maybe_body_owned_by(id) { 7,296 ( 0.00%) let mut visitor = RegionResolutionVisitor { . tcx, . scope_tree: ScopeTree::default(), . expr_and_pat_count: 0, . cx: Context { parent: None, var_parent: None }, . terminating_scopes: Default::default(), . pessimistic_yield: false, . fixup_scopes: vec![], . }; . 1,536 ( 0.00%) let body = tcx.hir().body(body_id); 1,152 ( 0.00%) visitor.scope_tree.root_body = Some(body.value.hir_id); 768 ( 0.00%) visitor.visit_body(body); 11,520 ( 0.00%) visitor.scope_tree . } else { . ScopeTree::default() . }; . 536 ( 0.00%) tcx.arena.alloc(scope_tree) 4,977 ( 0.00%) } . . pub fn provide(providers: &mut Providers) { 2 ( 0.00%) *providers = Providers { region_scope_tree, ..*providers }; . } 2,132,842 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_build/src/thir/cx/expr.rs -------------------------------------------------------------------------------- Ir -- line 18 ---------------------------------------- . use rustc_middle::ty::{self, AdtKind, Ty, UpvarSubsts, UserType}; . use rustc_span::def_id::DefId; . use rustc_span::Span; . use rustc_target::abi::VariantIdx; . . impl<'tcx> Cx<'tcx> { . crate fn mirror_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) -> ExprId { . // `mirror_expr` is recursing very deep. Make sure the stack doesn't overflow. 30,191 ( 0.00%) ensure_sufficient_stack(|| self.mirror_expr_inner(expr)) . } . 792 ( 0.00%) crate fn mirror_exprs(&mut self, exprs: &'tcx [hir::Expr<'tcx>]) -> Box<[ExprId]> { 419,367 ( 0.01%) exprs.iter().map(|expr| self.mirror_expr_inner(expr)).collect() 1,584 ( 0.00%) } . 1,309,392 ( 0.02%) pub(super) fn mirror_expr_inner(&mut self, hir_expr: &'tcx hir::Expr<'tcx>) -> ExprId { 1,018,416 ( 0.01%) let temp_lifetime = self.region_scope_tree.temporary_scope(hir_expr.hir_id.local_id); . let expr_scope = . region::Scope { id: hir_expr.hir_id.local_id, data: region::ScopeData::Node }; . . debug!("Expr::make_mirror(): id={}, span={:?}", hir_expr.hir_id, hir_expr.span); . 581,952 ( 0.01%) let mut expr = self.make_mirror_unadjusted(hir_expr); . 872,928 ( 0.01%) let adjustment_span = match self.adjustment_span { 5,290 ( 0.00%) Some((hir_id, span)) if hir_id == hir_expr.hir_id => Some(span), . _ => None, . }; . . // Now apply adjustments, if any. 581,952 ( 0.01%) for adjustment in self.typeck_results.expr_adjustments(hir_expr) { . debug!("make_mirror: expr={:?} applying adjustment={:?}", expr, adjustment); 8,624 ( 0.00%) let span = expr.span; 29,869 ( 0.00%) expr = 76,806 ( 0.00%) self.apply_adjustment(hir_expr, expr, adjustment, adjustment_span.unwrap_or(span)); . } . . // Next, wrap this up in the expr's scope. 1,891,344 ( 0.03%) expr = Expr { . temp_lifetime, 143,332 ( 0.00%) ty: expr.ty, 145,488 ( 0.00%) span: hir_expr.span, . kind: ExprKind::Scope { . region_scope: expr_scope, 2,618,784 ( 0.04%) value: self.thir.exprs.push(expr), 290,976 ( 0.00%) lint_level: LintLevel::Explicit(hir_expr.hir_id), . }, . }; . . // Finally, create a destruction scope, if any. 436,464 ( 0.01%) if let Some(region_scope) = 290,976 ( 0.00%) self.region_scope_tree.opt_destruction_scope(hir_expr.hir_id.local_id) . { 11,016 ( 0.00%) expr = Expr { . temp_lifetime, . ty: expr.ty, 918 ( 0.00%) span: hir_expr.span, . kind: ExprKind::Scope { . region_scope, 12,852 ( 0.00%) value: self.thir.exprs.push(expr), . lint_level: LintLevel::Inherited, . }, . }; . } . . // OK, all done! 3,200,736 ( 0.05%) self.thir.exprs.push(expr) 1,309,392 ( 0.02%) } . . fn apply_adjustment( . &mut self, . hir_expr: &'tcx hir::Expr<'tcx>, . mut expr: Expr<'tcx>, . adjustment: &Adjustment<'tcx>, . mut span: Span, . ) -> Expr<'tcx> { 8,534 ( 0.00%) let Expr { temp_lifetime, .. } = expr; . . // Adjust the span from the block, to the last expression of the . // block. This is a better span when returning a mutable reference . // with too short a lifetime. The error message will use the span . // from the assignment to the return place, which should only point . // at the returned value, not the entire function body. . // . // fn return_short_lived<'a>(x: &'a mut i32) -> &'static mut i32 { . // x . // // ^ error message points at this expression. . // } . let mut adjust_span = |expr: &mut Expr<'tcx>| { 4,788 ( 0.00%) if let ExprKind::Block { body } = &expr.kind { 3 ( 0.00%) if let Some(last_expr) = body.expr { 3 ( 0.00%) span = self.thir[last_expr].span; 2 ( 0.00%) expr.span = span; . } . } . }; . 38,929 ( 0.00%) let kind = match adjustment.kind { . Adjust::Pointer(PointerCast::Unsize) => { . adjust_span(&mut expr); 10,795 ( 0.00%) ExprKind::Pointer { cast: PointerCast::Unsize, source: self.thir.exprs.push(expr) } . } 799 ( 0.00%) Adjust::Pointer(cast) => ExprKind::Pointer { cast, source: self.thir.exprs.push(expr) }, 1,326 ( 0.00%) Adjust::NeverToAny => ExprKind::NeverToAny { source: self.thir.exprs.push(expr) }, . Adjust::Deref(None) => { . adjust_span(&mut expr); 29,903 ( 0.00%) ExprKind::Deref { arg: self.thir.exprs.push(expr) } . } 100 ( 0.00%) Adjust::Deref(Some(deref)) => { . // We don't need to do call adjust_span here since . // deref coercions always start with a built-in deref. 125 ( 0.00%) let call = deref.method_call(self.tcx(), expr.ty); . 150 ( 0.00%) expr = Expr { . temp_lifetime, 25 ( 0.00%) ty: self . .tcx 50 ( 0.00%) .mk_ref(deref.region, ty::TypeAndMut { ty: expr.ty, mutbl: deref.mutbl }), . span, . kind: ExprKind::Borrow { . borrow_kind: deref.mutbl.to_borrow_kind(), 375 ( 0.00%) arg: self.thir.exprs.push(expr), . }, . }; . 525 ( 0.00%) let expr = Box::new([self.thir.exprs.push(expr)]); . 325 ( 0.00%) self.overloaded_place(hir_expr, adjustment.target, Some(call), expr, deref.span) . } 6,820 ( 0.00%) Adjust::Borrow(AutoBorrow::Ref(_, m)) => ExprKind::Borrow { . borrow_kind: m.to_borrow_kind(), 23,870 ( 0.00%) arg: self.thir.exprs.push(expr), . }, . Adjust::Borrow(AutoBorrow::RawPtr(mutability)) => { 324 ( 0.00%) ExprKind::AddressOf { mutability, arg: self.thir.exprs.push(expr) } . } . }; . 81,073 ( 0.00%) Expr { temp_lifetime, ty: adjustment.target, span, kind } . } . 1,454,880 ( 0.02%) fn make_mirror_unadjusted(&mut self, expr: &'tcx hir::Expr<'tcx>) -> Expr<'tcx> { 581,952 ( 0.01%) let expr_ty = self.typeck_results().expr_ty(expr); 145,488 ( 0.00%) let expr_span = expr.span; 727,440 ( 0.01%) let temp_lifetime = self.region_scope_tree.temporary_scope(expr.hir_id.local_id); . 875,752 ( 0.01%) let kind = match expr.kind { . // Here comes the interesting stuff: 1,326 ( 0.00%) hir::ExprKind::MethodCall(segment, ref args, fn_span) => { . // Rewrite a.b(c) into UFCS form like Trait::b(a, c) 3,094 ( 0.00%) let expr = self.method_callee(expr, segment.ident.span, None); . // When we apply adjustments to the receiver, use the span of . // the overall method call for better diagnostics. args[0] . // is guaranteed to exist, since a method call always has a receiver. 1,768 ( 0.00%) let old_adjustment_span = self.adjustment_span.replace((args[0].hir_id, expr_span)); . tracing::info!("Using method span: {:?}", expr.span); 442 ( 0.00%) let args = self.mirror_exprs(args); 884 ( 0.00%) self.adjustment_span = old_adjustment_span; 3,094 ( 0.00%) ExprKind::Call { 442 ( 0.00%) ty: expr.ty, 6,188 ( 0.00%) fun: self.thir.exprs.push(expr), . args, . from_hir_call: true, . fn_span, . } . } . . hir::ExprKind::Call(ref fun, ref args) => { 1,888 ( 0.00%) if self.typeck_results().is_method_call(expr) { . // The callee is something implementing Fn, FnMut, or FnOnce. . // Find the actual method implementation being called and . // build the appropriate UFCS call expression with the . // callee-object as expr parameter. . . // rewrite f(u, v) into FnOnce::call_once(f, (u, v)) . 152 ( 0.00%) let method = self.method_callee(expr, fun.span, None); . 79 ( 0.00%) let arg_tys = args.iter().map(|e| self.typeck_results().expr_ty_adjusted(e)); . let tupled_args = Expr { 38 ( 0.00%) ty: self.tcx.mk_tup(arg_tys), . temp_lifetime, 19 ( 0.00%) span: expr.span, 76 ( 0.00%) kind: ExprKind::Tuple { fields: self.mirror_exprs(args) }, . }; 247 ( 0.00%) let tupled_args = self.thir.exprs.push(tupled_args); . 95 ( 0.00%) ExprKind::Call { 38 ( 0.00%) ty: method.ty, 361 ( 0.00%) fun: self.thir.exprs.push(method), 76 ( 0.00%) args: Box::new([self.mirror_expr(fun), tupled_args]), . from_hir_call: true, 38 ( 0.00%) fn_span: expr.span, . } . } else { . let adt_data = 2,265 ( 0.00%) if let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = fun.kind { . // Tuple-like ADTs are represented as ExprKind::Call. We convert them here. 1,441 ( 0.00%) expr_ty.ty_adt_def().and_then(|adt_def| match path.res { 152 ( 0.00%) Res::Def(DefKind::Ctor(_, CtorKind::Fn), ctor_id) => { 304 ( 0.00%) Some((adt_def, adt_def.variant_index_with_ctor_id(ctor_id))) . } . Res::SelfCtor(..) => Some((adt_def, VariantIdx::new(0))), . _ => None, . }) . } else { . None . }; 456 ( 0.00%) if let Some((adt_def, index)) = adt_data { 380 ( 0.00%) let substs = self.typeck_results().node_substs(fun.hir_id); 228 ( 0.00%) let user_provided_types = self.typeck_results().user_provided_types(); . let user_ty = 380 ( 0.00%) user_provided_types.get(fun.hir_id).copied().map(|mut u_ty| { . if let UserType::TypeOf(ref mut did, _) = &mut u_ty.value { . *did = adt_def.did; . } . u_ty . }); . debug!("make_mirror_unadjusted: (call) user_ty={:?}", user_ty); . 76 ( 0.00%) let field_refs = args . .iter() . .enumerate() . .map(|(idx, e)| FieldExpr { . name: Field::new(idx), . expr: self.mirror_expr(e), . }) . .collect(); . ExprKind::Adt(Box::new(Adt { -- line 246 ---------------------------------------- -- line 247 ---------------------------------------- . adt_def, . substs, . variant_index: index, . fields: field_refs, . user_ty, . base: None, . })) . } else { 1,508 ( 0.00%) ExprKind::Call { 2,037 ( 0.00%) ty: self.typeck_results().node_type(fun.hir_id), 377 ( 0.00%) fun: self.mirror_expr(fun), 1,508 ( 0.00%) args: self.mirror_exprs(args), . from_hir_call: true, 377 ( 0.00%) fn_span: expr.span, . } . } . } . } . . hir::ExprKind::AddrOf(hir::BorrowKind::Ref, mutbl, ref arg) => { 5,065 ( 0.00%) ExprKind::Borrow { borrow_kind: mutbl.to_borrow_kind(), arg: self.mirror_expr(arg) } . } . . hir::ExprKind::AddrOf(hir::BorrowKind::Raw, mutability, ref arg) => { . ExprKind::AddressOf { mutability, arg: self.mirror_expr(arg) } . } . 8,470 ( 0.00%) hir::ExprKind::Block(ref blk, _) => ExprKind::Block { body: self.mirror_block(blk) }, . . hir::ExprKind::Assign(ref lhs, ref rhs, _) => { 192 ( 0.00%) ExprKind::Assign { lhs: self.mirror_expr(lhs), rhs: self.mirror_expr(rhs) } . } . 20 ( 0.00%) hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => { 80 ( 0.00%) if self.typeck_results().is_method_call(expr) { . let lhs = self.mirror_expr(lhs); . let rhs = self.mirror_expr(rhs); . self.overloaded_operator(expr, Box::new([lhs, rhs])) . } else { 100 ( 0.00%) ExprKind::AssignOp { 60 ( 0.00%) op: bin_op(op.node), 20 ( 0.00%) lhs: self.mirror_expr(lhs), 20 ( 0.00%) rhs: self.mirror_expr(rhs), . } . } . } . 138,450 ( 0.00%) hir::ExprKind::Lit(ref lit) => ExprKind::Literal { 553,800 ( 0.01%) literal: self.const_eval_literal(&lit.node, expr_ty, lit.span, false), . user_ty: None, . const_id: None, . }, . 183 ( 0.00%) hir::ExprKind::Binary(op, ref lhs, ref rhs) => { 732 ( 0.00%) if self.typeck_results().is_method_call(expr) { 51 ( 0.00%) let lhs = self.mirror_expr(lhs); 51 ( 0.00%) let rhs = self.mirror_expr(rhs); . self.overloaded_operator(expr, Box::new([lhs, rhs])) . } else { . // FIXME overflow 454 ( 0.00%) match op.node { 148 ( 0.00%) hir::BinOpKind::And => ExprKind::LogicalOp { . op: LogicalOp::And, 37 ( 0.00%) lhs: self.mirror_expr(lhs), 37 ( 0.00%) rhs: self.mirror_expr(rhs), . }, 40 ( 0.00%) hir::BinOpKind::Or => ExprKind::LogicalOp { . op: LogicalOp::Or, 10 ( 0.00%) lhs: self.mirror_expr(lhs), 10 ( 0.00%) rhs: self.mirror_expr(rhs), . }, . _ => { 340 ( 0.00%) let op = bin_op(op.node); 425 ( 0.00%) ExprKind::Binary { . op, 85 ( 0.00%) lhs: self.mirror_expr(lhs), 85 ( 0.00%) rhs: self.mirror_expr(rhs), . } . } . } . } . } . . hir::ExprKind::Index(ref lhs, ref index) => { 130 ( 0.00%) if self.typeck_results().is_method_call(expr) { . let lhs = self.mirror_expr(lhs); . let index = self.mirror_expr(index); 286 ( 0.00%) self.overloaded_place(expr, expr_ty, None, Box::new([lhs, index]), expr.span) . } else { 16 ( 0.00%) ExprKind::Index { lhs: self.mirror_expr(lhs), index: self.mirror_expr(index) } . } . } . . hir::ExprKind::Unary(hir::UnOp::Deref, ref arg) => { 1,280 ( 0.00%) if self.typeck_results().is_method_call(expr) { . let arg = self.mirror_expr(arg); 18 ( 0.00%) self.overloaded_place(expr, expr_ty, None, Box::new([arg]), expr.span) . } else { 762 ( 0.00%) ExprKind::Deref { arg: self.mirror_expr(arg) } . } . } . . hir::ExprKind::Unary(hir::UnOp::Not, ref arg) => { 30 ( 0.00%) if self.typeck_results().is_method_call(expr) { . let arg = self.mirror_expr(arg); . self.overloaded_operator(expr, Box::new([arg])) . } else { 18 ( 0.00%) ExprKind::Unary { op: UnOp::Not, arg: self.mirror_expr(arg) } . } . } . . hir::ExprKind::Unary(hir::UnOp::Neg, ref arg) => { . if self.typeck_results().is_method_call(expr) { . let arg = self.mirror_expr(arg); . self.overloaded_operator(expr, Box::new([arg])) . } else if let hir::ExprKind::Lit(ref lit) = arg.kind { -- line 362 ---------------------------------------- -- line 365 ---------------------------------------- . user_ty: None, . const_id: None, . } . } else { . ExprKind::Unary { op: UnOp::Neg, arg: self.mirror_expr(arg) } . } . } . 466 ( 0.00%) hir::ExprKind::Struct(ref qpath, ref fields, ref base) => match expr_ty.kind() { 466 ( 0.00%) ty::Adt(adt, substs) => match adt.adt_kind() { . AdtKind::Struct | AdtKind::Union => { 669 ( 0.00%) let user_provided_types = self.typeck_results().user_provided_types(); 892 ( 0.00%) let user_ty = user_provided_types.get(expr.hir_id).copied(); . debug!("make_mirror_unadjusted: (struct/union) user_ty={:?}", user_ty); 892 ( 0.00%) ExprKind::Adt(Box::new(Adt { 446 ( 0.00%) adt_def: adt, . variant_index: VariantIdx::new(0), 446 ( 0.00%) substs, . user_ty, 446 ( 0.00%) fields: self.field_refs(fields), 892 ( 0.00%) base: base.as_ref().map(|base| FruInfo { . base: self.mirror_expr(base), . field_types: self.typeck_results().fru_field_types()[expr.hir_id] . .iter() . .copied() . .collect(), . }), . })) . } . AdtKind::Enum => { 60 ( 0.00%) let res = self.typeck_results().qpath_res(qpath, expr.hir_id); 40 ( 0.00%) match res { 30 ( 0.00%) Res::Def(DefKind::Variant, variant_id) => { 10 ( 0.00%) assert!(base.is_none()); . 30 ( 0.00%) let index = adt.variant_index_with_id(variant_id); . let user_provided_types = 40 ( 0.00%) self.typeck_results().user_provided_types(); 40 ( 0.00%) let user_ty = user_provided_types.get(expr.hir_id).copied(); . debug!("make_mirror_unadjusted: (variant) user_ty={:?}", user_ty); . ExprKind::Adt(Box::new(Adt { 10 ( 0.00%) adt_def: adt, . variant_index: index, 20 ( 0.00%) substs, . user_ty, 20 ( 0.00%) fields: self.field_refs(fields), . base: None, . })) . } . _ => { . span_bug!(expr.span, "unexpected res: {:?}", res); . } . } . } . }, . _ => { . span_bug!(expr.span, "unexpected type for struct literal: {:?}", expr_ty); . } . }, . . hir::ExprKind::Closure(..) => { 51 ( 0.00%) let closure_ty = self.typeck_results().expr_ty(expr); 51 ( 0.00%) let (def_id, substs, movability) = match *closure_ty.kind() { . ty::Closure(def_id, substs) => (def_id, UpvarSubsts::Closure(substs), None), . ty::Generator(def_id, substs, movability) => { . (def_id, UpvarSubsts::Generator(substs), Some(movability)) . } . _ => { . span_bug!(expr.span, "closure expr w/o closure type: {:?}", closure_ty); . } . }; . 102 ( 0.00%) let upvars = self . .typeck_results . .closure_min_captures_flattened(def_id) . .zip(substs.upvar_tys()) . .map(|(captured_place, ty)| { 45 ( 0.00%) let upvars = self.capture_upvar(expr, captured_place, ty); 126 ( 0.00%) self.thir.exprs.push(upvars) . }) . .collect(); . . // Convert the closure fake reads, if any, from hir `Place` to ExprRef 17 ( 0.00%) let fake_reads = match self.typeck_results.closure_fake_reads.get(&def_id) { . Some(fake_reads) => fake_reads . .iter() . .map(|(place, cause, hir_id)| { . let expr = self.convert_captured_hir_place(expr, place.clone()); . (self.thir.exprs.push(expr), *cause, *hir_id) . }) . .collect(), . None => Vec::new(), . }; . 323 ( 0.00%) ExprKind::Closure { closure_id: def_id, substs, upvars, movability, fake_reads } . } . 2,232 ( 0.00%) hir::ExprKind::Path(ref qpath) => { 8,928 ( 0.00%) let res = self.typeck_results().qpath_res(qpath, expr.hir_id); 8,928 ( 0.00%) self.convert_path_expr(expr, res) . } . . hir::ExprKind::InlineAsm(ref asm) => ExprKind::InlineAsm { . template: asm.template, . operands: asm . .operands . .iter() . .map(|(op, _op_sp)| { -- line 472 ---------------------------------------- -- line 581 ---------------------------------------- . let count = match ty.kind() { . ty::Array(_, ct) => ct, . _ => span_bug!(expr.span, "unexpected repeat expr ty: {:?}", ty), . }; . . ExprKind::Repeat { value: self.mirror_expr(v), count } . } . hir::ExprKind::Ret(ref v) => { 69 ( 0.00%) ExprKind::Return { value: v.as_ref().map(|v| self.mirror_expr(v)) } . } 69 ( 0.00%) hir::ExprKind::Break(dest, ref value) => match dest.target_id { 115 ( 0.00%) Ok(target_id) => ExprKind::Break { . label: region::Scope { id: target_id.local_id, data: region::ScopeData::Node }, . value: value.as_ref().map(|value| self.mirror_expr(value)), . }, . Err(err) => bug!("invalid loop id for break: {}", err), . }, 3 ( 0.00%) hir::ExprKind::Continue(dest) => match dest.target_id { 4 ( 0.00%) Ok(loop_id) => ExprKind::Continue { . label: region::Scope { id: loop_id.local_id, data: region::ScopeData::Node }, . }, . Err(err) => bug!("invalid loop id for continue: {}", err), . }, 120 ( 0.00%) hir::ExprKind::Let(let_expr) => ExprKind::Let { 15 ( 0.00%) expr: self.mirror_expr(let_expr.init), 45 ( 0.00%) pat: self.pattern_from_hir(let_expr.pat), . }, 1,122 ( 0.00%) hir::ExprKind::If(cond, then, else_opt) => ExprKind::If { . if_then_scope: region::Scope { 102 ( 0.00%) id: then.hir_id.local_id, . data: region::ScopeData::IfThen, . }, . cond: self.mirror_expr(cond), . then: self.mirror_expr(then), . else_opt: else_opt.map(|el| self.mirror_expr(el)), . }, 575 ( 0.00%) hir::ExprKind::Match(ref discr, ref arms, _) => ExprKind::Match { 115 ( 0.00%) scrutinee: self.mirror_expr(discr), 736 ( 0.00%) arms: arms.iter().map(|a| self.convert_arm(a)).collect(), . }, . hir::ExprKind::Loop(ref body, ..) => { 95 ( 0.00%) let block_ty = self.typeck_results().node_type(body.hir_id); 114 ( 0.00%) let temp_lifetime = self.region_scope_tree.temporary_scope(body.hir_id.local_id); 76 ( 0.00%) let block = self.mirror_block(body); 285 ( 0.00%) let body = self.thir.exprs.push(Expr { . ty: block_ty, . temp_lifetime, 19 ( 0.00%) span: block.span, 152 ( 0.00%) kind: ExprKind::Block { body: block }, . }); 57 ( 0.00%) ExprKind::Loop { body } . } 1,496 ( 0.00%) hir::ExprKind::Field(ref source, ..) => ExprKind::Field { 374 ( 0.00%) lhs: self.mirror_expr(source), 2,244 ( 0.00%) name: Field::new(self.tcx.field_index(expr.hir_id, self.typeck_results)), . }, . hir::ExprKind::Cast(ref source, ref cast_ty) => { . // Check for a user-given type annotation on this `cast` 40 ( 0.00%) let user_provided_types = self.typeck_results.user_provided_types(); 60 ( 0.00%) let user_ty = user_provided_types.get(cast_ty.hir_id); . . debug!( . "cast({:?}) has ty w/ hir_id {:?} and user provided ty {:?}", . expr, cast_ty.hir_id, user_ty, . ); . . // Check to see if this cast is a "coercion cast", where the cast is actually done . // using a coercion (or is a no-op). 60 ( 0.00%) let cast = if self.typeck_results().is_coercion_cast(source.hir_id) { . // Convert the lexpr to a vexpr. 6 ( 0.00%) ExprKind::Use { source: self.mirror_expr(source) } 12 ( 0.00%) } else if self.typeck_results().expr_ty(source).is_region_ptr() { . // Special cased so that we can type check that the element . // type of the source matches the pointed to type of the . // destination. . ExprKind::Pointer { . source: self.mirror_expr(source), . cast: PointerCast::ArrayToPointer, . } . } else { -- line 660 ---------------------------------------- -- line 664 ---------------------------------------- . // enum's layout (or its tag type) to compute it during const eval . // Example: . // enum Foo { . // A, . // B = A as isize + 4, . // } . // The correct solution would be to add symbolic computations to miri, . // so we wouldn't have to compute and store the actual value 16 ( 0.00%) let var = if let hir::ExprKind::Path(ref qpath) = source.kind { 24 ( 0.00%) let res = self.typeck_results().qpath_res(qpath, source.hir_id); 28 ( 0.00%) self.typeck_results().node_type(source.hir_id).ty_adt_def().and_then( . |adt_def| match res { . Res::Def( . DefKind::Ctor(CtorOf::Variant, CtorKind::Const), . variant_ctor_id, . ) => { . let idx = adt_def.variant_index_with_ctor_id(variant_ctor_id); . let (d, o) = adt_def.discriminant_def_for_variant(idx); . use rustc_middle::ty::util::IntTypeExt; -- line 682 ---------------------------------------- -- line 686 ---------------------------------------- . } . _ => None, . }, . ) . } else { . None . }; . 12 ( 0.00%) let source = if let Some((did, offset, var_ty)) = var { . let mk_const = |literal| Expr { . temp_lifetime, . ty: var_ty, . span: expr.span, . kind: ExprKind::Literal { literal, user_ty: None, const_id: None }, . }; . let offset = self.thir.exprs.push(mk_const(ty::Const::from_bits( . self.tcx, -- line 702 ---------------------------------------- -- line 723 ---------------------------------------- . ty: var_ty, . span: expr.span, . kind: bin, . }) . } . None => offset, . } . } else { 4 ( 0.00%) self.mirror_expr(source) . }; . . ExprKind::Cast { source: source } . }; . 20 ( 0.00%) if let Some(user_ty) = user_ty { . // NOTE: Creating a new Expr and wrapping a Cast inside of it may be . // inefficient, revisit this when performance becomes an issue. . let cast_expr = self.thir.exprs.push(Expr { . temp_lifetime, . ty: expr_ty, . span: expr.span, . kind: cast, . }); . debug!("make_mirror_unadjusted: (cast) user_ty={:?}", user_ty); . . ExprKind::ValueTypeAscription { source: cast_expr, user_ty: Some(*user_ty) } . } else { 40 ( 0.00%) cast . } . } . hir::ExprKind::Type(ref source, ref ty) => { . let user_provided_types = self.typeck_results.user_provided_types(); . let user_ty = user_provided_types.get(ty.hir_id).copied(); . debug!("make_mirror_unadjusted: (type) user_ty={:?}", user_ty); . let mirrored = self.mirror_expr(source); . if source.is_syntactic_place_expr() { . ExprKind::PlaceTypeAscription { source: mirrored, user_ty } . } else { . ExprKind::ValueTypeAscription { source: mirrored, user_ty } . } . } . hir::ExprKind::DropTemps(ref source) => { 392 ( 0.00%) ExprKind::Use { source: self.mirror_expr(source) } . } . hir::ExprKind::Box(ref value) => ExprKind::Box { value: self.mirror_expr(value) }, . hir::ExprKind::Array(ref fields) => { 2,925 ( 0.00%) ExprKind::Array { fields: self.mirror_exprs(fields) } . } 680 ( 0.00%) hir::ExprKind::Tup(ref fields) => ExprKind::Tuple { fields: self.mirror_exprs(fields) }, . . hir::ExprKind::Yield(ref v, _) => ExprKind::Yield { value: self.mirror_expr(v) }, . hir::ExprKind::Err => unreachable!(), . }; . 4,946,592 ( 0.07%) Expr { temp_lifetime, ty: expr_ty, span: expr.span, kind } 1,163,904 ( 0.02%) } . 10,296 ( 0.00%) fn user_substs_applied_to_res( . &mut self, . hir_id: hir::HirId, . res: Res, . ) -> Option> { . debug!("user_substs_applied_to_res: res={:?}", res); 6,864 ( 0.00%) let user_provided_type = match res { . // A reference to something callable -- e.g., a fn, method, or . // a tuple-struct or tuple-variant. This has the type of a . // `Fn` but with the user-given substitutions. . Res::Def(DefKind::Fn, _) . | Res::Def(DefKind::AssocFn, _) . | Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) . | Res::Def(DefKind::Const, _) . | Res::Def(DefKind::AssocConst, _) => { 8,008 ( 0.00%) self.typeck_results().user_provided_types().get(hir_id).copied() . } . . // A unit struct/variant which is used as a value (e.g., . // `None`). This has the type of the enum/struct that defines . // this variant -- but with the substitutions given by the . // user. . Res::Def(DefKind::Ctor(_, CtorKind::Const), _) => { . self.user_substs_applied_to_ty_of_hir_id(hir_id) -- line 803 ---------------------------------------- -- line 805 ---------------------------------------- . . // `Self` is used in expression as a tuple struct constructor or a unit struct constructor . Res::SelfCtor(_) => self.user_substs_applied_to_ty_of_hir_id(hir_id), . . _ => bug!("user_substs_applied_to_res: unexpected res {:?} at {:?}", res, hir_id), . }; . debug!("user_substs_applied_to_res: user_provided_type={:?}", user_provided_type); . user_provided_type 6,864 ( 0.00%) } . 7,293 ( 0.00%) fn method_callee( . &mut self, . expr: &hir::Expr<'_>, . span: Span, . overloaded_callee: Option<(DefId, SubstsRef<'tcx>)>, . ) -> Expr<'tcx> { 3,366 ( 0.00%) let temp_lifetime = self.region_scope_tree.temporary_scope(expr.hir_id.local_id); 4,488 ( 0.00%) let (def_id, substs, user_ty) = match overloaded_callee { . Some((def_id, substs)) => (def_id, substs, None), . None => { . let (kind, def_id) = 4,824 ( 0.00%) self.typeck_results().type_dependent_def(expr.hir_id).unwrap_or_else(|| { . span_bug!(expr.span, "no type-dependent def for method callee") . }); 8,040 ( 0.00%) let user_ty = self.user_substs_applied_to_res(expr.hir_id, Res::Def(kind, def_id)); . debug!("method_callee: user_ty={:?}", user_ty); 8,040 ( 0.00%) (def_id, self.typeck_results().node_substs(expr.hir_id), user_ty) . } . }; . let ty = self.tcx().mk_fn_def(def_id, substs); 7,293 ( 0.00%) Expr { . temp_lifetime, . ty, . span, . kind: ExprKind::Literal { . literal: ty::Const::zero_sized(self.tcx(), ty), 3,366 ( 0.00%) user_ty, . const_id: None, . }, . } 4,488 ( 0.00%) } . 1,863 ( 0.00%) fn convert_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) -> ArmId { 1,656 ( 0.00%) let arm = Arm { 621 ( 0.00%) pattern: self.pattern_from_hir(&arm.pat), . guard: arm.guard.as_ref().map(|g| match g { . hir::Guard::If(ref e) => Guard::If(self.mirror_expr(e)), . hir::Guard::IfLet(ref pat, ref e) => { . Guard::IfLet(self.pattern_from_hir(pat), self.mirror_expr(e)) . } . }), 207 ( 0.00%) body: self.mirror_expr(arm.body), 414 ( 0.00%) lint_level: LintLevel::Explicit(arm.hir_id), . scope: region::Scope { id: arm.hir_id.local_id, data: region::ScopeData::Node }, 207 ( 0.00%) span: arm.span, . }; 3,105 ( 0.00%) self.thir.arms.push(arm) 1,863 ( 0.00%) } . . fn convert_path_expr(&mut self, expr: &'tcx hir::Expr<'tcx>, res: Res) -> ExprKind<'tcx> { 15,624 ( 0.00%) let substs = self.typeck_results().node_substs(expr.hir_id); 16,404 ( 0.00%) match res { . // A regular function, constructor function or a constant. . Res::Def(DefKind::Fn, _) . | Res::Def(DefKind::AssocFn, _) . | Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) . | Res::SelfCtor(..) => { 4,250 ( 0.00%) let user_ty = self.user_substs_applied_to_res(expr.hir_id, res); . debug!("convert_path_expr: user_ty={:?}", user_ty); 425 ( 0.00%) ExprKind::Literal { . literal: ty::Const::zero_sized( 850 ( 0.00%) self.tcx, 1,275 ( 0.00%) self.typeck_results().node_type(expr.hir_id), . ), 3,400 ( 0.00%) user_ty, . const_id: None, . } . } . . Res::Def(DefKind::ConstParam, def_id) => { . let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id.expect_local()); . let item_id = self.tcx.hir().get_parent_node(hir_id); . let item_def_id = self.tcx.hir().local_def_id(item_id); -- line 887 ---------------------------------------- -- line 895 ---------------------------------------- . ty: self.typeck_results().node_type(expr.hir_id), . }), . user_ty: None, . const_id: Some(def_id), . } . } . . Res::Def(DefKind::Const, def_id) | Res::Def(DefKind::AssocConst, def_id) => { 1,647 ( 0.00%) let user_ty = self.user_substs_applied_to_res(expr.hir_id, res); . debug!("convert_path_expr: (const) user_ty={:?}", user_ty); 915 ( 0.00%) ExprKind::Literal { 2,196 ( 0.00%) literal: self.tcx.mk_const(ty::Const { . val: ty::ConstKind::Unevaluated(ty::Unevaluated::new( . ty::WithOptConstParam::unknown(def_id), . substs, . )), 549 ( 0.00%) ty: self.typeck_results().node_type(expr.hir_id), . }), 1,464 ( 0.00%) user_ty, . const_id: Some(def_id), . } . } . 780 ( 0.00%) Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id) => { 780 ( 0.00%) let user_provided_types = self.typeck_results.user_provided_types(); 624 ( 0.00%) let user_provided_type = user_provided_types.get(expr.hir_id).copied(); . debug!("convert_path_expr: user_provided_type={:?}", user_provided_type); 624 ( 0.00%) let ty = self.typeck_results().node_type(expr.hir_id); 312 ( 0.00%) match ty.kind() { . // A unit struct/variant which is used as a value. . // We return a completely different ExprKind here to account for this special case. . ty::Adt(adt_def, substs) => ExprKind::Adt(Box::new(Adt { 156 ( 0.00%) adt_def, 780 ( 0.00%) variant_index: adt_def.variant_index_with_ctor_id(def_id), 156 ( 0.00%) substs, . user_ty: user_provided_type, . fields: Box::new([]), . base: None, . })), . _ => bug!("unexpected ty: {:?}", ty), . } . } . -- line 937 ---------------------------------------- -- line 953 ---------------------------------------- . def_id: id, . } . }; . ExprKind::Deref { . arg: self.thir.exprs.push(Expr { ty, temp_lifetime, span: expr.span, kind }), . } . } . 11,744 ( 0.00%) Res::Local(var_hir_id) => self.convert_var(var_hir_id), . . _ => span_bug!(expr.span, "res `{:?}` not yet implemented", res), . } . } . 14,770 ( 0.00%) fn convert_var(&mut self, var_hir_id: hir::HirId) -> ExprKind<'tcx> { . // We want upvars here not captures. . // Captures will be handled in MIR. . let is_upvar = self . .tcx . .upvars_mentioned(self.body_owner) . .map_or(false, |upvars| upvars.contains_key(&var_hir_id)); . . debug!( . "convert_var({:?}): is_upvar={}, body_owner={:?}", . var_hir_id, is_upvar, self.body_owner . ); . 16 ( 0.00%) if is_upvar { 63 ( 0.00%) ExprKind::UpvarRef { closure_def_id: self.body_owner, var_hir_id } . } else { 4,404 ( 0.00%) ExprKind::VarRef { id: var_hir_id } . } 11,816 ( 0.00%) } . 561 ( 0.00%) fn overloaded_operator( . &mut self, . expr: &'tcx hir::Expr<'tcx>, . args: Box<[ExprId]>, . ) -> ExprKind<'tcx> { 357 ( 0.00%) let fun = self.method_callee(expr, expr.span, None); 765 ( 0.00%) let fun = self.thir.exprs.push(fun); 357 ( 0.00%) ExprKind::Call { 255 ( 0.00%) ty: self.thir[fun].ty, . fun, . args, . from_hir_call: false, . fn_span: expr.span, . } 408 ( 0.00%) } . 686 ( 0.00%) fn overloaded_place( . &mut self, . expr: &'tcx hir::Expr<'tcx>, . place_ty: Ty<'tcx>, . overloaded_callee: Option<(DefId, SubstsRef<'tcx>)>, . args: Box<[ExprId]>, . span: Span, . ) -> ExprKind<'tcx> { . // For an overloaded *x or x[y] expression of type T, the method . // call returns an &T and we must add the deref so that the types . // line up (this is because `*x` and `x[y]` represent places): . . // Reconstruct the output assuming it's a reference with the . // same region and mutability as the receiver. This holds for . // `Deref(Mut)::Deref(_mut)` and `Index(Mut)::index(_mut)`. 392 ( 0.00%) let (region, mutbl) = match *self.thir[args[0]].ty.kind() { 98 ( 0.00%) ty::Ref(region, _, mutbl) => (region, mutbl), . _ => span_bug!(span, "overloaded_place: receiver is not a reference"), . }; 49 ( 0.00%) let ref_ty = self.tcx.mk_ref(region, ty::TypeAndMut { ty: place_ty, mutbl }); . . // construct the complete expression `foo()` for the overloaded call, . // which will yield the &T type 196 ( 0.00%) let temp_lifetime = self.region_scope_tree.temporary_scope(expr.hir_id.local_id); 294 ( 0.00%) let fun = self.method_callee(expr, span, overloaded_callee); 686 ( 0.00%) let fun = self.thir.exprs.push(fun); 294 ( 0.00%) let fun_ty = self.thir[fun].ty; 686 ( 0.00%) let ref_expr = self.thir.exprs.push(Expr { . temp_lifetime, . ty: ref_ty, . span, . kind: ExprKind::Call { ty: fun_ty, fun, args, from_hir_call: false, fn_span: span }, . }); . . // construct and return a deref wrapper `*foo()` 98 ( 0.00%) ExprKind::Deref { arg: ref_expr } 392 ( 0.00%) } . 99 ( 0.00%) fn convert_captured_hir_place( . &mut self, . closure_expr: &'tcx hir::Expr<'tcx>, . place: HirPlace<'tcx>, . ) -> Expr<'tcx> { 36 ( 0.00%) let temp_lifetime = self.region_scope_tree.temporary_scope(closure_expr.hir_id.local_id); . let var_ty = place.base_ty; . . // The result of capture analysis in `rustc_typeck/check/upvar.rs`represents a captured path . // as it's seen for use within the closure and not at the time of closure creation. . // . // That is we see expect to see it start from a captured upvar and not something that is local . // to the closure's parent. 18 ( 0.00%) let var_hir_id = match place.base { 18 ( 0.00%) HirPlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id, . base => bug!("Expected an upvar, found {:?}", base), . }; . 153 ( 0.00%) let mut captured_place_expr = Expr { . temp_lifetime, . ty: var_ty, 9 ( 0.00%) span: closure_expr.span, 45 ( 0.00%) kind: self.convert_var(var_hir_id), . }; . . for proj in place.projections.iter() { . let kind = match proj.kind { . HirProjectionKind::Deref => { . ExprKind::Deref { arg: self.thir.exprs.push(captured_place_expr) } . } . HirProjectionKind::Field(field, ..) => { -- line 1071 ---------------------------------------- -- line 1082 ---------------------------------------- . } . }; . . captured_place_expr = . Expr { temp_lifetime, ty: proj.ty, span: closure_expr.span, kind }; . } . . captured_place_expr 81 ( 0.00%) } . 90 ( 0.00%) fn capture_upvar( . &mut self, . closure_expr: &'tcx hir::Expr<'tcx>, . captured_place: &'tcx ty::CapturedPlace<'tcx>, . upvar_ty: Ty<'tcx>, . ) -> Expr<'tcx> { . let upvar_capture = captured_place.info.capture_kind; . let captured_place_expr = 63 ( 0.00%) self.convert_captured_hir_place(closure_expr, captured_place.place.clone()); 27 ( 0.00%) let temp_lifetime = self.region_scope_tree.temporary_scope(closure_expr.hir_id.local_id); . 18 ( 0.00%) match upvar_capture { 30 ( 0.00%) ty::UpvarCapture::ByValue => captured_place_expr, . ty::UpvarCapture::ByRef(upvar_borrow) => { 35 ( 0.00%) let borrow_kind = match upvar_borrow { . ty::BorrowKind::ImmBorrow => BorrowKind::Shared, . ty::BorrowKind::UniqueImmBorrow => BorrowKind::Unique, . ty::BorrowKind::MutBorrow => BorrowKind::Mut { allow_two_phase_borrow: false }, . }; 49 ( 0.00%) Expr { . temp_lifetime, . ty: upvar_ty, 7 ( 0.00%) span: closure_expr.span, . kind: ExprKind::Borrow { . borrow_kind, 105 ( 0.00%) arg: self.thir.exprs.push(captured_place_expr), . }, . } . } . } 81 ( 0.00%) } . . /// Converts a list of named fields (i.e., for struct-like struct/enum ADTs) into FieldExpr. . fn field_refs(&mut self, fields: &'tcx [hir::ExprField<'tcx>]) -> Box<[FieldExpr]> { . fields . .iter() . .map(|field| FieldExpr { 2,928 ( 0.00%) name: Field::new(self.tcx.field_index(field.hir_id, self.typeck_results)), . expr: self.mirror_expr(field.expr), . }) . .collect() . } . } . . trait ToBorrowKind { . fn to_borrow_kind(&self) -> BorrowKind; . } . . impl ToBorrowKind for AutoBorrowMutability { . fn to_borrow_kind(&self) -> BorrowKind { . use rustc_middle::ty::adjustment::AllowTwoPhase; 11,935 ( 0.00%) match *self { . AutoBorrowMutability::Mut { allow_two_phase_borrow } => BorrowKind::Mut { . allow_two_phase_borrow: match allow_two_phase_borrow { . AllowTwoPhase::Yes => true, . AllowTwoPhase::No => false, . }, . }, . AutoBorrowMutability::Not => BorrowKind::Shared, . } . } . } . . impl ToBorrowKind for hir::Mutability { . fn to_borrow_kind(&self) -> BorrowKind { 50 ( 0.00%) match *self { . hir::Mutability::Mut => BorrowKind::Mut { allow_two_phase_borrow: false }, . hir::Mutability::Not => BorrowKind::Shared, . } . } . } . 210 ( 0.00%) fn bin_op(op: hir::BinOpKind) -> BinOp { 945 ( 0.00%) match op { . hir::BinOpKind::Add => BinOp::Add, . hir::BinOpKind::Sub => BinOp::Sub, . hir::BinOpKind::Mul => BinOp::Mul, . hir::BinOpKind::Div => BinOp::Div, . hir::BinOpKind::Rem => BinOp::Rem, . hir::BinOpKind::BitXor => BinOp::BitXor, . hir::BinOpKind::BitAnd => BinOp::BitAnd, . hir::BinOpKind::BitOr => BinOp::BitOr, -- line 1173 ---------------------------------------- -- line 1176 ---------------------------------------- . hir::BinOpKind::Eq => BinOp::Eq, . hir::BinOpKind::Lt => BinOp::Lt, . hir::BinOpKind::Le => BinOp::Le, . hir::BinOpKind::Ne => BinOp::Ne, . hir::BinOpKind::Ge => BinOp::Ge, . hir::BinOpKind::Gt => BinOp::Gt, . _ => bug!("no equivalent for ast binop {:?}", op), . } 210 ( 0.00%) } 2,166,210 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/context.rs -------------------------------------------------------------------------------- Ir -- line 118 ---------------------------------------- . stability: InternedSet<'tcx, attr::Stability>, . . /// `#[rustc_const_stable]` and `#[rustc_const_unstable]` attributes . const_stability: InternedSet<'tcx, attr::ConstStability>, . } . . impl<'tcx> CtxtInterners<'tcx> { . fn new(arena: &'tcx WorkerLocal>) -> CtxtInterners<'tcx> { 17 ( 0.00%) CtxtInterners { . arena, . type_: Default::default(), . type_list: Default::default(), . substs: Default::default(), . region: Default::default(), . poly_existential_predicates: Default::default(), . canonical_var_infos: Default::default(), . predicate: Default::default(), -- line 134 ---------------------------------------- -- line 143 ---------------------------------------- . stability: Default::default(), . const_stability: Default::default(), . } . } . . /// Interns a type. . #[allow(rustc::usage_of_ty_tykind)] . #[inline(never)] 2,105,520 ( 0.03%) fn intern_ty(&self, kind: TyKind<'tcx>) -> Ty<'tcx> { . self.type_ 1,315,950 ( 0.02%) .intern(kind, |kind| { 56,766 ( 0.00%) let flags = super::flags::FlagComputation::for_kind(&kind); . . let ty_struct = TyS { 113,532 ( 0.00%) kind, . flags: flags.flags, . outer_exclusive_binder: flags.outer_exclusive_binder, . }; . . Interned(self.arena.alloc(ty_struct)) . }) . .0 2,368,710 ( 0.03%) } . . #[inline(never)] 535,672 ( 0.01%) fn intern_predicate( . &self, . kind: Binder<'tcx, PredicateKind<'tcx>>, . ) -> &'tcx PredicateInner<'tcx> { . self.predicate 468,713 ( 0.01%) .intern(kind, |kind| { 95,172 ( 0.00%) let flags = super::flags::FlagComputation::for_predicate(kind); . . let predicate_struct = PredicateInner { . kind, . flags: flags.flags, . outer_exclusive_binder: flags.outer_exclusive_binder, . }; . . Interned(self.arena.alloc(predicate_struct)) . }) . .0 602,631 ( 0.01%) } . } . . pub struct CommonTypes<'tcx> { . pub unit: Ty<'tcx>, . pub bool: Ty<'tcx>, . pub char: Ty<'tcx>, . pub isize: Ty<'tcx>, . pub i8: Ty<'tcx>, -- line 193 ---------------------------------------- -- line 237 ---------------------------------------- . /// safely used as a key in the maps of a TypeckResults. For that to be . /// the case, the HirId must have the same `owner` as all the other IDs in . /// this table (signified by `hir_owner`). Otherwise the HirId . /// would be in a different frame of reference and using its `local_id` . /// would result in lookup errors, or worse, in silently wrong data being . /// stored/returned. . #[inline] . fn validate_hir_id_for_typeck_results(hir_owner: LocalDefId, hir_id: hir::HirId) { 2,262,395 ( 0.03%) if hir_id.owner != hir_owner { . invalid_hir_id_for_typeck_results(hir_owner, hir_id); . } . } . . #[cold] . #[inline(never)] . fn invalid_hir_id_for_typeck_results(hir_owner: LocalDefId, hir_id: hir::HirId) { . ty::tls::with(|tcx| { -- line 253 ---------------------------------------- -- line 261 ---------------------------------------- . } . . impl<'a, V> LocalTableInContext<'a, V> { . pub fn contains_key(&self, id: hir::HirId) -> bool { . validate_hir_id_for_typeck_results(self.hir_owner, id); . self.data.contains_key(&id.local_id) . } . 1,520,891 ( 0.02%) pub fn get(&self, id: hir::HirId) -> Option<&V> { 304,295 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, id); 304,295 ( 0.00%) self.data.get(&id.local_id) 1,216,904 ( 0.02%) } . . pub fn iter(&self) -> hash_map::Iter<'_, hir::ItemLocalId, V> { . self.data.iter() . } . } . . impl<'a, V> ::std::ops::Index for LocalTableInContext<'a, V> { . type Output = V; . 1,848 ( 0.00%) fn index(&self, key: hir::HirId) -> &V { . self.get(key).expect("LocalTableInContext: key not found") 1,232 ( 0.00%) } . } . . pub struct LocalTableInContextMut<'a, V> { . hir_owner: LocalDefId, . data: &'a mut ItemLocalMap, . } . . impl<'a, V> LocalTableInContextMut<'a, V> { -- line 292 ---------------------------------------- -- line 507 ---------------------------------------- . pub treat_byte_string_as_slice: ItemLocalSet, . . /// Contains the data for evaluating the effect of feature `capture_disjoint_fields` . /// on closure size. . pub closure_size_eval: FxHashMap>, . } . . impl<'tcx> TypeckResults<'tcx> { 7,824 ( 0.00%) pub fn new(hir_owner: LocalDefId) -> TypeckResults<'tcx> { 92,584 ( 0.00%) TypeckResults { . hir_owner, . type_dependent_defs: Default::default(), . field_indices: Default::default(), . user_provided_types: Default::default(), . user_provided_sigs: Default::default(), . node_types: Default::default(), . node_substs: Default::default(), . adjustments: Default::default(), -- line 524 ---------------------------------------- -- line 532 ---------------------------------------- . tainted_by_errors: None, . concrete_opaque_types: Default::default(), . closure_min_captures: Default::default(), . closure_fake_reads: Default::default(), . generator_interior_types: ty::Binder::dummy(Default::default()), . treat_byte_string_as_slice: Default::default(), . closure_size_eval: Default::default(), . } 7,824 ( 0.00%) } . . /// Returns the final resolution of a `QPath` in an `Expr` or `Pat` node. 33,051 ( 0.00%) pub fn qpath_res(&self, qpath: &hir::QPath<'_>, id: hir::HirId) -> Res { 22,034 ( 0.00%) match *qpath { 58,932 ( 0.00%) hir::QPath::Resolved(_, ref path) => path.res, . hir::QPath::TypeRelative(..) | hir::QPath::LangItem(..) => self . .type_dependent_def(id) 7,170 ( 0.00%) .map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)), . } 55,085 ( 0.00%) } . 195 ( 0.00%) pub fn type_dependent_defs( . &self, . ) -> LocalTableInContext<'_, Result<(DefKind, DefId), ErrorReported>> { 1,696 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.type_dependent_defs } 195 ( 0.00%) } . 2,498 ( 0.00%) pub fn type_dependent_def(&self, id: HirId) -> Option<(DefKind, DefId)> { 5,073 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, id); . self.type_dependent_defs.get(&id.local_id).cloned().and_then(|r| r.ok()) 4,996 ( 0.00%) } . 5,520 ( 0.00%) pub fn type_dependent_def_id(&self, id: HirId) -> Option { . self.type_dependent_def(id).map(|(_, def_id)| def_id) 5,520 ( 0.00%) } . 149,998 ( 0.00%) pub fn type_dependent_defs_mut( . &mut self, . ) -> LocalTableInContextMut<'_, Result<(DefKind, DefId), ErrorReported>> { 149,998 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.type_dependent_defs } 149,998 ( 0.00%) } . . pub fn field_indices(&self) -> LocalTableInContext<'_, usize> { 4,465 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.field_indices } 595 ( 0.00%) } . . pub fn field_indices_mut(&mut self) -> LocalTableInContextMut<'_, usize> { 9,126 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.field_indices } 4,563 ( 0.00%) } . . pub fn user_provided_types(&self) -> LocalTableInContext<'_, CanonicalUserType<'tcx>> { 4,854 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.user_provided_types } 2,427 ( 0.00%) } . . pub fn user_provided_types_mut( . &mut self, . ) -> LocalTableInContextMut<'_, CanonicalUserType<'tcx>> { 1,224 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.user_provided_types } 612 ( 0.00%) } . . pub fn node_types(&self) -> LocalTableInContext<'_, Ty<'tcx>> { 303,136 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.node_types } 151,568 ( 0.00%) } . . pub fn node_types_mut(&mut self) -> LocalTableInContextMut<'_, Ty<'tcx>> { 597,366 ( 0.01%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.node_types } 298,683 ( 0.00%) } . 3,505,944 ( 0.05%) pub fn node_type(&self, id: hir::HirId) -> Ty<'tcx> { 584,324 ( 0.01%) self.node_type_opt(id).unwrap_or_else(|| { . bug!("node_type: no type for node `{}`", tls::with(|tcx| tcx.hir().node_to_string(id))) . }) 2,921,620 ( 0.04%) } . 733,020 ( 0.01%) pub fn node_type_opt(&self, id: hir::HirId) -> Option> { 733,020 ( 0.01%) validate_hir_id_for_typeck_results(self.hir_owner, id); . self.node_types.get(&id.local_id).cloned() 1,466,040 ( 0.02%) } . . pub fn node_substs_mut(&mut self) -> LocalTableInContextMut<'_, SubstsRef<'tcx>> { 4,476 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.node_substs } 2,238 ( 0.00%) } . 152,420 ( 0.00%) pub fn node_substs(&self, id: hir::HirId) -> SubstsRef<'tcx> { 152,420 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, id); . self.node_substs.get(&id.local_id).cloned().unwrap_or_else(|| InternalSubsts::empty()) 304,840 ( 0.00%) } . 148,084 ( 0.00%) pub fn node_substs_opt(&self, id: hir::HirId) -> Option> { 148,084 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, id); . self.node_substs.get(&id.local_id).cloned() 296,168 ( 0.00%) } . . // Returns the type of a pattern as a monotype. Like @expr_ty, this function . // doesn't provide type parameter substitutions. . pub fn pat_ty(&self, pat: &hir::Pat<'_>) -> Ty<'tcx> { 3,316 ( 0.00%) self.node_type(pat.hir_id) . } . . // Returns the type of an expression as a monotype. . // . // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression. That is, in . // some cases, we insert `Adjustment` annotations such as auto-deref or . // auto-ref. The type returned by this function does not consider such . // adjustments. See `expr_ty_adjusted()` instead. . // . // NB (2): This type doesn't provide type parameter substitutions; e.g., if you . // ask for the type of "id" in "id(3)", it will return "fn(&isize) -> isize" . // instead of "fn(ty) -> T with T = isize". . pub fn expr_ty(&self, expr: &hir::Expr<'_>) -> Ty<'tcx> { 590,189 ( 0.01%) self.node_type(expr.hir_id) . } . . pub fn expr_ty_opt(&self, expr: &hir::Expr<'_>) -> Option> { 592,358 ( 0.01%) self.node_type_opt(expr.hir_id) . } . . pub fn adjustments(&self) -> LocalTableInContext<'_, Vec>> { 294,734 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.adjustments } 147,367 ( 0.00%) } . . pub fn adjustments_mut( . &mut self, . ) -> LocalTableInContextMut<'_, Vec>> { 307,094 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.adjustments } 153,547 ( 0.00%) } . 294,135 ( 0.00%) pub fn expr_adjustments(&self, expr: &hir::Expr<'_>) -> &[ty::adjustment::Adjustment<'tcx>] { 588,270 ( 0.01%) validate_hir_id_for_typeck_results(self.hir_owner, expr.hir_id); . self.adjustments.get(&expr.hir_id.local_id).map_or(&[], |a| &a[..]) 588,270 ( 0.01%) } . . /// Returns the type of `expr`, considering any `Adjustment` . /// entry recorded for that expression. 2,555 ( 0.00%) pub fn expr_ty_adjusted(&self, expr: &hir::Expr<'_>) -> Ty<'tcx> { 511 ( 0.00%) self.expr_adjustments(expr).last().map_or_else(|| self.expr_ty(expr), |adj| adj.target) 1,232 ( 0.00%) } . 535 ( 0.00%) pub fn expr_ty_adjusted_opt(&self, expr: &hir::Expr<'_>) -> Option> { 107 ( 0.00%) self.expr_adjustments(expr).last().map(|adj| adj.target).or_else(|| self.expr_ty_opt(expr)) 324 ( 0.00%) } . 1,501 ( 0.00%) pub fn is_method_call(&self, expr: &hir::Expr<'_>) -> bool { . // Only paths and method calls/overloaded operators have . // entries in type_dependent_defs, ignore the former here. 3,002 ( 0.00%) if let hir::ExprKind::Path(_) = expr.kind { . return false; . } . 3,602 ( 0.00%) matches!(self.type_dependent_defs().get(expr.hir_id), Some(Ok((DefKind::AssocFn, _)))) 3,002 ( 0.00%) } . 7,902 ( 0.00%) pub fn extract_binding_mode(&self, s: &Session, id: HirId, sp: Span) -> Option { . self.pat_binding_modes().get(id).copied().or_else(|| { . s.delay_span_bug(sp, "missing binding mode"); . None . }) 10,536 ( 0.00%) } . . pub fn pat_binding_modes(&self) -> LocalTableInContext<'_, BindingMode> { 6,696 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.pat_binding_modes } 2,031 ( 0.00%) } . . pub fn pat_binding_modes_mut(&mut self) -> LocalTableInContextMut<'_, BindingMode> { 3,496 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.pat_binding_modes } 1,748 ( 0.00%) } . . pub fn pat_adjustments(&self) -> LocalTableInContext<'_, Vec>> { 8,826 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.pat_adjustments } 4,413 ( 0.00%) } . . pub fn pat_adjustments_mut(&mut self) -> LocalTableInContextMut<'_, Vec>> { 2,694 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.pat_adjustments } 1,347 ( 0.00%) } . . /// For a given closure, returns the iterator of `ty::CapturedPlace`s that are captured . /// by the closure. 1,940 ( 0.00%) pub fn closure_min_captures_flattened( . &self, . closure_def_id: DefId, . ) -> impl Iterator> { . self.closure_min_captures . .get(&closure_def_id) . .map(|closure_min_captures| closure_min_captures.values().flat_map(|v| v.iter())) . .into_iter() . .flatten() 2,425 ( 0.00%) } . . pub fn closure_kind_origins(&self) -> LocalTableInContext<'_, (Span, HirPlace<'tcx>)> { 768 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.closure_kind_origins } 384 ( 0.00%) } . . pub fn closure_kind_origins_mut( . &mut self, . ) -> LocalTableInContextMut<'_, (Span, HirPlace<'tcx>)> { 4 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.closure_kind_origins } 2 ( 0.00%) } . . pub fn liberated_fn_sigs(&self) -> LocalTableInContext<'_, ty::FnSig<'tcx>> { 2,000 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.liberated_fn_sigs } 1,000 ( 0.00%) } . . pub fn liberated_fn_sigs_mut(&mut self) -> LocalTableInContextMut<'_, ty::FnSig<'tcx>> { 1,232 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.liberated_fn_sigs } 616 ( 0.00%) } . . pub fn fru_field_types(&self) -> LocalTableInContext<'_, Vec>> { 768 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.fru_field_types } 384 ( 0.00%) } . . pub fn fru_field_types_mut(&mut self) -> LocalTableInContextMut<'_, Vec>> { . LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.fru_field_types } . } . 30 ( 0.00%) pub fn is_coercion_cast(&self, hir_id: hir::HirId) -> bool { 10 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, hir_id); . self.coercion_casts.contains(&hir_id.local_id) 20 ( 0.00%) } . . pub fn set_coercion_cast(&mut self, id: ItemLocalId) { . self.coercion_casts.insert(id); . } . . pub fn coercion_casts(&self) -> &ItemLocalSet { 384 ( 0.00%) &self.coercion_casts 384 ( 0.00%) } . } . . impl<'a, 'tcx> HashStable> for TypeckResults<'tcx> { . fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) { . let ty::TypeckResults { . hir_owner, . ref type_dependent_defs, . ref field_indices, -- line 764 ---------------------------------------- -- line 819 ---------------------------------------- . const START_INDEX = 0, . } . } . . /// Mapping of type annotation indices to canonical user type annotations. . pub type CanonicalUserTypeAnnotations<'tcx> = . IndexVec>; . 264 ( 0.00%) #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)] . pub struct CanonicalUserTypeAnnotation<'tcx> { . pub user_ty: CanonicalUserType<'tcx>, . pub span: Span, 324 ( 0.00%) pub inferred_ty: Ty<'tcx>, . } . . /// Canonicalized user type annotation. . pub type CanonicalUserType<'tcx> = Canonical<'tcx, UserType<'tcx>>; . . impl<'tcx> CanonicalUserType<'tcx> { . /// Returns `true` if this represents a substitution of the form `[?0, ?1, ?2]`, . /// i.e., each thing is mapped to a canonical variable with the same index. 793 ( 0.00%) pub fn is_identity(&self) -> bool { 1,586 ( 0.00%) match self.value { . UserType::Ty(_) => false, . UserType::TypeOf(_, user_substs) => { 793 ( 0.00%) if user_substs.user_self_ty.is_some() { . return false; . } . . iter::zip(user_substs.substs, BoundVar::new(0)..).all(|(kind, cvar)| { . match kind.unpack() { 1,336 ( 0.00%) GenericArgKind::Type(ty) => match ty.kind() { . ty::Bound(debruijn, b) => { . // We only allow a `ty::INNERMOST` index in substitutions. 655 ( 0.00%) assert_eq!(*debruijn, ty::INNERMOST); . cvar == b.var . } . _ => false, . }, . 282 ( 0.00%) GenericArgKind::Lifetime(r) => match r { . ty::ReLateBound(debruijn, br) => { . // We only allow a `ty::INNERMOST` index in substitutions. . assert_eq!(*debruijn, ty::INNERMOST); . cvar == br.var . } . _ => false, . }, . -- line 867 ---------------------------------------- -- line 872 ---------------------------------------- . cvar == b . } . _ => false, . }, . } . }) . } . } 1,586 ( 0.00%) } . } . . /// A user-given type annotation attached to a constant. These arise . /// from constants that are named via paths, like `Foo::::new` and . /// so forth. 1,944 ( 0.00%) #[derive(Copy, Clone, Debug, PartialEq, TyEncodable, TyDecodable)] 9,115 ( 0.00%) #[derive(HashStable, TypeFoldable, Lift)] . pub enum UserType<'tcx> { . Ty(Ty<'tcx>), . . /// The canonical type is the result of `type_of(def_id)` with the . /// given substitutions applied. . TypeOf(DefId, UserSubsts<'tcx>), . } . . impl<'tcx> CommonTypes<'tcx> { . fn new(interners: &CtxtInterners<'tcx>) -> CommonTypes<'tcx> { 111 ( 0.00%) let mk = |ty| interners.intern_ty(ty); . . CommonTypes { . unit: mk(Tuple(List::empty())), . bool: mk(Bool), . char: mk(Char), . never: mk(Never), . isize: mk(Int(ty::IntTy::Isize)), . i8: mk(Int(ty::IntTy::I8)), -- line 906 ---------------------------------------- -- line 921 ---------------------------------------- . . trait_object_dummy_self: mk(Infer(ty::FreshTy(0))), . } . } . } . . impl<'tcx> CommonLifetimes<'tcx> { . fn new(interners: &CtxtInterners<'tcx>) -> CommonLifetimes<'tcx> { 67 ( 0.00%) let mk = |r| interners.region.intern(r, |r| Interned(interners.arena.alloc(r))).0; . . CommonLifetimes { 5 ( 0.00%) re_root_empty: mk(RegionKind::ReEmpty(ty::UniverseIndex::ROOT)), 5 ( 0.00%) re_static: mk(RegionKind::ReStatic), 5 ( 0.00%) re_erased: mk(RegionKind::ReErased), . } . } . } . . impl<'tcx> CommonConsts<'tcx> { . fn new(interners: &CtxtInterners<'tcx>, types: &CommonTypes<'tcx>) -> CommonConsts<'tcx> { 6 ( 0.00%) let mk_const = |c| interners.const_.intern(c, |c| Interned(interners.arena.alloc(c))).0; . . CommonConsts { . unit: mk_const(ty::Const { . val: ty::ConstKind::Value(ConstValue::Scalar(Scalar::ZST)), . ty: types.unit, . }), . } . } -- line 949 ---------------------------------------- -- line 1045 ---------------------------------------- . . /// Stores memory for globals (statics/consts). . pub(crate) alloc_map: Lock>, . . output_filenames: Arc, . } . . impl<'tcx> TyCtxt<'tcx> { 19,760 ( 0.00%) pub fn typeck_opt_const_arg( . self, . def: ty::WithOptConstParam, . ) -> &'tcx TypeckResults<'tcx> { 7,904 ( 0.00%) if let Some(param_did) = def.const_param_did { . self.typeck_const_arg((def.did, param_did)) . } else { . self.typeck(def.did) . } 15,808 ( 0.00%) } . 1,203 ( 0.00%) pub fn alloc_steal_thir(self, thir: Thir<'tcx>) -> &'tcx Steal> { 401 ( 0.00%) self.arena.alloc(Steal::new(thir)) 1,604 ( 0.00%) } . 8,020 ( 0.00%) pub fn alloc_steal_mir(self, mir: Body<'tcx>) -> &'tcx Steal> { 1,604 ( 0.00%) self.arena.alloc(Steal::new(mir)) 11,228 ( 0.00%) } . 1,604 ( 0.00%) pub fn alloc_steal_promoted( . self, . promoted: IndexVec>, . ) -> &'tcx Steal>> { 401 ( 0.00%) self.arena.alloc(Steal::new(promoted)) 2,005 ( 0.00%) } . 792 ( 0.00%) pub fn alloc_adt_def( . self, . did: DefId, . kind: AdtKind, . variants: IndexVec, . repr: ReprOptions, . ) -> &'tcx ty::AdtDef { 1,408 ( 0.00%) self.intern_adt_def(ty::AdtDef::new(self, did, kind, variants, repr)) 352 ( 0.00%) } . . /// Allocates a read-only byte or string literal for `mir::interpret`. . pub fn allocate_bytes(self, bytes: &[u8]) -> interpret::AllocId { . // Create an allocation that just contains these bytes. . let alloc = interpret::Allocation::from_bytes_byte_aligned_immutable(bytes); . let alloc = self.intern_const_alloc(alloc); . self.create_memory_alloc(alloc) . } . . /// Returns a range of the start/end indices specified with the . /// `rustc_layout_scalar_valid_range` attribute. . // FIXME(eddyb) this is an awkward spot for this method, maybe move it? 8,800 ( 0.00%) pub fn layout_scalar_valid_range(self, def_id: DefId) -> (Bound, Bound) { 4,400 ( 0.00%) let attrs = self.get_attrs(def_id); 18,700 ( 0.00%) let get = |name| { 4,400 ( 0.00%) let attr = match attrs.iter().find(|a| a.has_name(name)) { . Some(attr) => attr, . None => return Bound::Unbounded, . }; . debug!("layout_scalar_valid_range: attr={:?}", attr); 376 ( 0.00%) if let Some( . &[ . ast::NestedMetaItem::Literal(ast::Lit { 188 ( 0.00%) kind: ast::LitKind::Int(a, _), .. . }), . ], 94 ( 0.00%) ) = attr.meta_item_list().as_deref() . { . Bound::Included(a) . } else { . self.sess . .delay_span_bug(attr.span, "invalid rustc_layout_scalar_valid_range attribute"); . Bound::Unbounded . } 22,000 ( 0.00%) }; 6,600 ( 0.00%) ( 6,600 ( 0.00%) get(sym::rustc_layout_scalar_valid_range_start), 3,300 ( 0.00%) get(sym::rustc_layout_scalar_valid_range_end), . ) 8,800 ( 0.00%) } . . pub fn lift>(self, value: T) -> Option { . value.lift_to_tcx(self) . } . . /// Creates a type context and call the closure with a `TyCtxt` reference . /// to the context. The closure enforces that the type context and any interned . /// value (types, substs, etc.) can only be used while `ty::tls` has a valid . /// reference to the context, to allow formatting values that need it. 23 ( 0.00%) pub fn create_global_ctxt( . s: &'tcx Session, . lint_store: Lrc, . arena: &'tcx WorkerLocal>, . resolutions: ty::ResolverOutputs, . krate: &'tcx hir::Crate<'tcx>, . dep_graph: DepGraph, . on_disk_cache: Option<&'tcx dyn OnDiskCache<'tcx>>, . queries: &'tcx dyn query::QueryEngine<'tcx>, . query_kinds: &'tcx [DepKindStruct], . crate_name: &str, . output_filenames: OutputFilenames, . ) -> GlobalCtxt<'tcx> { 1 ( 0.00%) let data_layout = TargetDataLayout::parse(&s.target).unwrap_or_else(|err| { . s.fatal(&err); . }); . let interners = CtxtInterners::new(arena); . let common_types = CommonTypes::new(&interners); . let common_lifetimes = CommonLifetimes::new(&interners); . let common_consts = CommonConsts::new(&interners, &common_types); . 127 ( 0.00%) GlobalCtxt { . sess: s, 6 ( 0.00%) lint_store, . arena, 2 ( 0.00%) interners, 5 ( 0.00%) dep_graph, 4 ( 0.00%) untracked_resolutions: resolutions, 2 ( 0.00%) prof: s.prof.clone(), . types: common_types, . lifetimes: common_lifetimes, . consts: common_consts, . untracked_crate: krate, . on_disk_cache, . queries, . query_caches: query::QueryCaches::default(), . query_kinds, . ty_rcache: Default::default(), . pred_rcache: Default::default(), . selection_cache: Default::default(), . evaluation_cache: Default::default(), 1 ( 0.00%) crate_name: Symbol::intern(crate_name), . data_layout, . alloc_map: Lock::new(interpret::AllocMap::new()), . output_filenames: Arc::new(output_filenames), . } 9 ( 0.00%) } . . crate fn query_kind(self, k: DepKind) -> &'tcx DepKindStruct { . &self.query_kinds[k as usize] . } . . /// Constructs a `TyKind::Error` type and registers a `delay_span_bug` to ensure it gets used. . #[track_caller] . pub fn ty_error(self) -> Ty<'tcx> { -- line 1191 ---------------------------------------- -- line 1217 ---------------------------------------- . ty: Ty<'tcx>, . span: S, . msg: &str, . ) -> &'tcx Const<'tcx> { . self.sess.delay_span_bug(span, msg); . self.mk_const(ty::Const { val: ty::ConstKind::Error(DelaySpanBugEmitted(())), ty }) . } . 12,733 ( 0.00%) pub fn consider_optimizing String>(self, msg: T) -> bool { 1,819 ( 0.00%) let cname = self.crate_name(LOCAL_CRATE); 13,787 ( 0.00%) self.sess.consider_optimizing(cname.as_str(), msg) 14,552 ( 0.00%) } . . /// Obtain all lang items of this crate and all dependencies (recursively) 540,533 ( 0.01%) pub fn lang_items(self) -> &'tcx rustc_hir::lang_items::LanguageItems { . self.get_lang_items(()) 694,971 ( 0.01%) } . . /// Obtain the given diagnostic item's `DefId`. Use `is_diagnostic_item` if you just want to . /// compare against another `DefId`, since `is_diagnostic_item` is cheaper. 133 ( 0.00%) pub fn get_diagnostic_item(self, name: Symbol) -> Option { . self.all_diagnostic_items(()).name_to_id.get(&name).copied() 152 ( 0.00%) } . . /// Obtain the diagnostic item's name 10,206 ( 0.00%) pub fn get_diagnostic_name(self, id: DefId) -> Option { . self.diagnostic_items(id.krate).id_to_name.get(&id).copied() 11,664 ( 0.00%) } . . /// Check whether the diagnostic item with the given `name` has the given `DefId`. 20,622 ( 0.00%) pub fn is_diagnostic_item(self, name: Symbol, did: DefId) -> bool { . self.diagnostic_items(did.krate).name_to_id.get(&name) == Some(&did) 23,568 ( 0.00%) } . 5,446 ( 0.00%) pub fn stability(self) -> &'tcx stability::Index<'tcx> { . self.stability_index(()) 7,002 ( 0.00%) } . 237,832 ( 0.00%) pub fn features(self) -> &'tcx rustc_feature::Features { . self.features_query(()) 271,808 ( 0.00%) } . 4,085 ( 0.00%) pub fn def_key(self, id: DefId) -> rustc_hir::definitions::DefKey { . // Accessing the DefKey is ok, since it is part of DefPathHash. 37,561 ( 0.00%) if let Some(id) = id.as_local() { . self.untracked_resolutions.definitions.def_key(id) . } else { 44,829 ( 0.00%) self.untracked_resolutions.cstore.def_key(id) . } 1,280 ( 0.00%) } . . /// Converts a `DefId` into its fully expanded `DefPath` (every . /// `DefId` is really just an interned `DefPath`). . /// . /// Note that if `id` is not local to this crate, the result will . /// be a non-local `DefPath`. 46 ( 0.00%) pub fn def_path(self, id: DefId) -> rustc_hir::definitions::DefPath { . // Accessing the DefPath is ok, since it is part of DefPathHash. 69 ( 0.00%) if let Some(id) = id.as_local() { 18 ( 0.00%) self.untracked_resolutions.definitions.def_path(id) . } else { 85 ( 0.00%) self.untracked_resolutions.cstore.def_path(id) . } 69 ( 0.00%) } . . #[inline] . pub fn def_path_hash(self, def_id: DefId) -> rustc_hir::definitions::DefPathHash { . // Accessing the DefPathHash is ok, it is incr. comp. stable. 3,761 ( 0.00%) if let Some(def_id) = def_id.as_local() { . self.untracked_resolutions.definitions.def_path_hash(def_id) . } else { 1,720 ( 0.00%) self.untracked_resolutions.cstore.def_path_hash(def_id) . } . } . . #[inline] . pub fn stable_crate_id(self, crate_num: CrateNum) -> StableCrateId { . if crate_num == LOCAL_CRATE { . self.sess.local_stable_crate_id() . } else { -- line 1296 ---------------------------------------- -- line 1353 ---------------------------------------- . &(format!("{:08x}", stable_crate_id.to_u64()))[..4], . self.def_path(def_id).to_string_no_crate_verbose() . ) . } . . /// Note that this is *untracked* and should only be used within the query . /// system if the result is otherwise tracked through queries . pub fn cstore_untracked(self) -> &'tcx ty::CrateStoreDyn { 55,964 ( 0.00%) &*self.untracked_resolutions.cstore 27,982 ( 0.00%) } . . /// Note that this is *untracked* and should only be used within the query . /// system if the result is otherwise tracked through queries . pub fn definitions_untracked(self) -> &'tcx hir::definitions::Definitions { . &self.untracked_resolutions.definitions . } . . #[inline(always)] . pub fn create_stable_hashing_context(self) -> StableHashingContext<'tcx> { 615 ( 0.00%) let resolutions = &self.gcx.untracked_resolutions; 2,553 ( 0.00%) StableHashingContext::new(self.sess, &resolutions.definitions, &*resolutions.cstore) . } . . #[inline(always)] . pub fn create_no_span_stable_hashing_context(self) -> StableHashingContext<'tcx> { . let resolutions = &self.gcx.untracked_resolutions; . StableHashingContext::ignore_spans( . self.sess, . &resolutions.definitions, -- line 1381 ---------------------------------------- -- line 1390 ---------------------------------------- . /// If `true`, we should use the MIR-based borrowck, but also . /// fall back on the AST borrowck if the MIR-based one errors. . pub fn migrate_borrowck(self) -> bool { . self.borrowck_mode().migrate() . } . . /// What mode(s) of borrowck should we run? AST? MIR? both? . /// (Also considers the `#![feature(nll)]` setting.) 768 ( 0.00%) pub fn borrowck_mode(self) -> BorrowckMode { . // Here are the main constraints we need to deal with: . // . // 1. An opts.borrowck_mode of `BorrowckMode::Migrate` is . // synonymous with no `-Z borrowck=...` flag at all. . // . // 2. We want to allow developers on the Nightly channel . // to opt back into the "hard error" mode for NLL, . // (which they can do via specifying `#![feature(nll)]` -- line 1406 ---------------------------------------- -- line 1413 ---------------------------------------- . // errors. (To simplify the code here, it now even overrides . // a user's attempt to specify `-Z borrowck=compare`, which . // we arguably do not need anymore and should remove.) . // . // * Otherwise, if no `-Z borrowck=...` then use migrate mode . // . // * Otherwise, use the behavior requested via `-Z borrowck=...` . 1,152 ( 0.00%) if self.features().nll { . return BorrowckMode::Mir; . } . 384 ( 0.00%) self.sess.opts.borrowck_mode 1,536 ( 0.00%) } . . /// If `true`, we should use lazy normalization for constants, otherwise . /// we still evaluate them eagerly. . #[inline] . pub fn lazy_normalization(self) -> bool { 4 ( 0.00%) let features = self.features(); . // Note: We only use lazy normalization for generic const expressions. . features.generic_const_exprs . } . . #[inline] . pub fn local_crate_exports_generics(self) -> bool { . debug_assert!(self.sess.opts.share_generics()); . -- line 1440 ---------------------------------------- -- line 1540 ---------------------------------------- . // FIXME(#42706) -- in some cases, we could do better here. . return true; . } . false . } . . /// Determines whether identifiers in the assembly have strict naming rules. . /// Currently, only NVPTX* targets need it. 1,350 ( 0.00%) pub fn has_strict_asm_symbol_naming(self) -> bool { 1,350 ( 0.00%) self.sess.target.arch.contains("nvptx") 2,700 ( 0.00%) } . . /// Returns `&'static core::panic::Location<'static>`. 372 ( 0.00%) pub fn caller_location_ty(self) -> Ty<'tcx> { . self.mk_imm_ref( 62 ( 0.00%) self.lifetimes.re_static, . self.type_of(self.require_lang_item(LangItem::PanicLocation, None)) 124 ( 0.00%) .subst(self, self.mk_substs([self.lifetimes.re_static.into()].iter())), . ) 372 ( 0.00%) } . . /// Returns a displayable description and article for the given `def_id` (e.g. `("a", "struct")`). 3,795 ( 0.00%) pub fn article_and_description(self, def_id: DefId) -> (&'static str, &'static str) { 2,760 ( 0.00%) match self.def_kind(def_id) { . DefKind::Generator => match self.generator_kind(def_id).unwrap() { . rustc_hir::GeneratorKind::Async(..) => ("an", "async closure"), . rustc_hir::GeneratorKind::Gen => ("a", "generator"), . }, 6,210 ( 0.00%) def_kind => (def_kind.article(), def_kind.descr(def_id)), . } 3,105 ( 0.00%) } . 6,601 ( 0.00%) pub fn type_length_limit(self) -> Limit { . self.limits(()).type_length_limit 7,544 ( 0.00%) } . 210,252 ( 0.00%) pub fn recursion_limit(self) -> Limit { . self.limits(()).recursion_limit 240,288 ( 0.00%) } . 32,564 ( 0.00%) pub fn move_size_limit(self) -> Limit { . self.limits(()).move_size_limit 37,216 ( 0.00%) } . 3,339 ( 0.00%) pub fn const_eval_limit(self) -> Limit { . self.limits(()).const_eval_limit 3,816 ( 0.00%) } . . pub fn all_traits(self) -> impl Iterator + 'tcx { . iter::once(LOCAL_CRATE) . .chain(self.crates(()).iter().copied()) . .flat_map(move |cnum| self.traits_in_crate(cnum).iter().copied()) . } . } . -- line 1594 ---------------------------------------- -- line 1614 ---------------------------------------- . fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option; . } . . macro_rules! nop_lift { . ($set:ident; $ty:ty => $lifted:ty) => { . impl<'a, 'tcx> Lift<'tcx> for $ty { . type Lifted = $lifted; . fn lift_to_tcx(self, tcx: TyCtxt<'tcx>) -> Option { 768 ( 0.00%) if tcx.interners.$set.contains_pointer_to(&Interned(self)) { . Some(unsafe { mem::transmute(self) }) . } else { . None . } . } . } . }; . } -- line 1630 ---------------------------------------- -- line 1684 ---------------------------------------- . /// This is the implicit state of rustc. It contains the current . /// `TyCtxt` and query. It is updated when creating a local interner or . /// executing a new query. Whenever there's a `TyCtxt` value available . /// you should also have access to an `ImplicitCtxt` through the functions . /// in this module. . #[derive(Clone)] . pub struct ImplicitCtxt<'a, 'tcx> { . /// The current `TyCtxt`. 2 ( 0.00%) pub tcx: TyCtxt<'tcx>, . . /// The current query job, if any. This is updated by `JobOwner::start` in . /// `ty::query::plumbing` when executing a query. . pub query: Option>, . . /// Where to store diagnostics for the current query job, if any. . /// This is updated by `JobOwner::start` in `ty::query::plumbing` when executing a query. . pub diagnostics: Option<&'a Lock>>, -- line 1700 ---------------------------------------- -- line 1703 ---------------------------------------- . pub layout_depth: usize, . . /// The current dep graph task. This is used to add dependencies to queries . /// when executing them. . pub task_deps: TaskDepsRef<'a>, . } . . impl<'a, 'tcx> ImplicitCtxt<'a, 'tcx> { 5 ( 0.00%) pub fn new(gcx: &'tcx GlobalCtxt<'tcx>) -> Self { . let tcx = TyCtxt { gcx }; 25 ( 0.00%) ImplicitCtxt { . tcx, . query: None, . diagnostics: None, . layout_depth: 0, . task_deps: TaskDepsRef::Ignore, . } 5 ( 0.00%) } . } . . /// Sets Rayon's thread-local variable, which is preserved for Rayon jobs . /// to `value` during the call to `f`. It is restored to its previous value after. . /// This is used to set the pointer to the new `ImplicitCtxt`. . #[cfg(parallel_compiler)] . #[inline] . fn set_tlv R, R>(value: usize, f: F) -> R { -- line 1728 ---------------------------------------- -- line 1745 ---------------------------------------- . . /// Sets TLV to `value` during the call to `f`. . /// It is restored to its previous value after. . /// This is used to set the pointer to the new `ImplicitCtxt`. . #[cfg(not(parallel_compiler))] . #[inline] . fn set_tlv R, R>(value: usize, f: F) -> R { . let old = get_tlv(); 76,214 ( 0.00%) let _reset = rustc_data_structures::OnDrop(move || TLV.with(|tlv| tlv.set(old))); . TLV.with(|tlv| tlv.set(value)); . f() . } . . /// Gets the pointer to the current `ImplicitCtxt`. . #[cfg(not(parallel_compiler))] . #[inline] . fn get_tlv() -> usize { -- line 1761 ---------------------------------------- -- line 1763 ---------------------------------------- . } . . /// Sets `context` as the new current `ImplicitCtxt` for the duration of the function `f`. . #[inline] . pub fn enter_context<'a, 'tcx, F, R>(context: &ImplicitCtxt<'a, 'tcx>, f: F) -> R . where . F: FnOnce(&ImplicitCtxt<'a, 'tcx>) -> R, . { 1 ( 0.00%) set_tlv(context as *const _ as usize, || f(&context)) . } . . /// Allows access to the current `ImplicitCtxt` in a closure if one is available. . #[inline] . pub fn with_context_opt(f: F) -> R . where . F: for<'a, 'tcx> FnOnce(Option<&ImplicitCtxt<'a, 'tcx>>) -> R, . { . let context = get_tlv(); 320,646 ( 0.00%) if context == 0 { . f(None) . } else { . // We could get an `ImplicitCtxt` pointer from another thread. . // Ensure that `ImplicitCtxt` is `Sync`. . sync::assert_sync::>(); . . unsafe { f(Some(&*(context as *const ImplicitCtxt<'_, '_>))) } . } -- line 1789 ---------------------------------------- -- line 1791 ---------------------------------------- . . /// Allows access to the current `ImplicitCtxt`. . /// Panics if there is no `ImplicitCtxt` available. . #[inline] . pub fn with_context(f: F) -> R . where . F: for<'a, 'tcx> FnOnce(&ImplicitCtxt<'a, 'tcx>) -> R, . { 470 ( 0.00%) with_context_opt(|opt_context| f(opt_context.expect("no ImplicitCtxt stored in tls"))) . } . . /// Allows access to the current `ImplicitCtxt` whose tcx field is the same as the tcx argument . /// passed in. This means the closure is given an `ImplicitCtxt` with the same `'tcx` lifetime . /// as the `TyCtxt` passed in. . /// This will panic if you pass it a `TyCtxt` which is different from the current . /// `ImplicitCtxt`'s `tcx` field. . #[inline] . pub fn with_related_context<'tcx, F, R>(tcx: TyCtxt<'tcx>, f: F) -> R . where . F: FnOnce(&ImplicitCtxt<'_, 'tcx>) -> R, . { . with_context(|context| unsafe { 155,599 ( 0.00%) assert!(ptr_eq(context.tcx.gcx, tcx.gcx)); . let context: &ImplicitCtxt<'_, '_> = mem::transmute(context); 153,828 ( 0.00%) f(context) . }) . } . . /// Allows access to the `TyCtxt` in the current `ImplicitCtxt`. . /// Panics if there is no `ImplicitCtxt` available. . #[inline] . pub fn with(f: F) -> R . where -- line 1823 ---------------------------------------- -- line 1981 ---------------------------------------- . fn into_pointer(&self) -> *const () { . self.0 as *const _ as *const () . } . } . . #[allow(rustc::usage_of_ty_tykind)] . impl<'tcx> Borrow> for Interned<'tcx, TyS<'tcx>> { . fn borrow<'a>(&'a self) -> &'a TyKind<'tcx> { 242,643 ( 0.00%) &self.0.kind() . } . } . . impl<'tcx> PartialEq for Interned<'tcx, TyS<'tcx>> { . fn eq(&self, other: &Interned<'tcx, TyS<'tcx>>) -> bool { . // The `Borrow` trait requires that `x.borrow() == y.borrow()` equals . // `x == y`. . self.0.kind() == other.0.kind() -- line 1997 ---------------------------------------- -- line 1998 ---------------------------------------- . } . } . . impl<'tcx> Eq for Interned<'tcx, TyS<'tcx>> {} . . impl<'tcx> Hash for Interned<'tcx, TyS<'tcx>> { . fn hash(&self, s: &mut H) { . // The `Borrow` trait requires that `x.borrow().hash(s) == x.hash(s)`. 86,772 ( 0.00%) self.0.kind().hash(s) . } . } . . impl<'tcx> Borrow>> for Interned<'tcx, PredicateInner<'tcx>> { . fn borrow<'a>(&'a self) -> &'a Binder<'tcx, PredicateKind<'tcx>> { 53,295 ( 0.00%) &self.0.kind . } . } . . impl<'tcx> PartialEq for Interned<'tcx, PredicateInner<'tcx>> { . fn eq(&self, other: &Interned<'tcx, PredicateInner<'tcx>>) -> bool { . // The `Borrow` trait requires that `x.borrow() == y.borrow()` equals . // `x == y`. . self.0.kind == other.0.kind -- line 2020 ---------------------------------------- -- line 2021 ---------------------------------------- . } . } . . impl<'tcx> Eq for Interned<'tcx, PredicateInner<'tcx>> {} . . impl<'tcx> Hash for Interned<'tcx, PredicateInner<'tcx>> { . fn hash(&self, s: &mut H) { . // The `Borrow` trait requires that `x.borrow().hash(s) == x.hash(s)`. 28,668 ( 0.00%) self.0.kind.hash(s) . } . } . . impl<'tcx, T> Borrow<[T]> for Interned<'tcx, List> { . fn borrow<'a>(&'a self) -> &'a [T] { 223,706 ( 0.00%) &self.0[..] . } . } . . impl<'tcx, T: PartialEq> PartialEq for Interned<'tcx, List> { . fn eq(&self, other: &Interned<'tcx, List>) -> bool { . // The `Borrow` trait requires that `x.borrow() == y.borrow()` equals . // `x == y`. . self.0[..] == other.0[..] -- line 2043 ---------------------------------------- -- line 2044 ---------------------------------------- . } . } . . impl<'tcx, T: Eq> Eq for Interned<'tcx, List> {} . . impl<'tcx, T: Hash> Hash for Interned<'tcx, List> { . fn hash(&self, s: &mut H) { . // The `Borrow` trait requires that `x.borrow().hash(s) == x.hash(s)`. 37,240 ( 0.00%) self.0[..].hash(s) . } . } . . macro_rules! direct_interners { . ($($name:ident: $method:ident($ty:ty),)+) => { . $(impl<'tcx> Borrow<$ty> for Interned<'tcx, $ty> { . fn borrow<'a>(&'a self) -> &'a $ty { 94,779 ( 0.00%) &self.0 . } . } . . impl<'tcx> PartialEq for Interned<'tcx, $ty> { . fn eq(&self, other: &Self) -> bool { . // The `Borrow` trait requires that `x.borrow() == y.borrow()` . // equals `x == y`. . self.0 == other.0 -- line 2068 ---------------------------------------- -- line 2070 ---------------------------------------- . } . . impl<'tcx> Eq for Interned<'tcx, $ty> {} . . impl<'tcx> Hash for Interned<'tcx, $ty> { . fn hash(&self, s: &mut H) { . // The `Borrow` trait requires that `x.borrow().hash(s) == . // x.hash(s)`. 36,483 ( 0.00%) self.0.hash(s) . } . } . . impl<'tcx> TyCtxt<'tcx> { 826,265 ( 0.01%) pub fn $method(self, v: $ty) -> &'tcx $ty { 440,846 ( 0.01%) self.interners.$name.intern(v, |v| { 9,114 ( 0.00%) Interned(self.interners.arena.alloc(v)) . }).0 926,577 ( 0.01%) } . })+ . } . } . . direct_interners! { . region: mk_region(RegionKind), . const_: mk_const(Const<'tcx>), . const_allocation: intern_const_alloc(Allocation), -- line 2095 ---------------------------------------- -- line 2097 ---------------------------------------- . adt_def: intern_adt_def(AdtDef), . stability: intern_stability(attr::Stability), . const_stability: intern_const_stability(attr::ConstStability), . } . . macro_rules! slice_interners { . ($($field:ident: $method:ident($ty:ty)),+ $(,)?) => ( . impl<'tcx> TyCtxt<'tcx> { 2,491,082 ( 0.04%) $(pub fn $method(self, v: &[$ty]) -> &'tcx List<$ty> { . self.interners.$field.intern_ref(v, || { . Interned(List::from_arena(&*self.arena, v)) . }).0 2,227,284 ( 0.03%) })+ . } . ); . } . . slice_interners!( . type_list: _intern_type_list(Ty<'tcx>), . substs: _intern_substs(GenericArg<'tcx>), . canonical_var_infos: _intern_canonical_var_infos(CanonicalVarInfo<'tcx>), -- line 2117 ---------------------------------------- -- line 2188 ---------------------------------------- . self.mk_fn_sig(params_iter, s.output(), s.c_variadic, unsafety, abi::Abi::Rust) . }) . } . . /// Same a `self.mk_region(kind)`, but avoids accessing the interners if . /// `*r == kind`. . #[inline] . pub fn reuse_or_mk_region(self, r: Region<'tcx>, kind: RegionKind) -> Region<'tcx> { 86,772 ( 0.00%) if *r == kind { r } else { self.mk_region(kind) } . } . . #[allow(rustc::usage_of_ty_tykind)] . #[inline] . pub fn mk_ty(self, st: TyKind<'tcx>) -> Ty<'tcx> { 1,885,777 ( 0.03%) self.interners.intern_ty(st) . } . . #[inline] . pub fn mk_predicate(self, binder: Binder<'tcx, PredicateKind<'tcx>>) -> Predicate<'tcx> { 735,374 ( 0.01%) let inner = self.interners.intern_predicate(binder); . Predicate { inner } . } . . #[inline] 1,382,608 ( 0.02%) pub fn reuse_or_mk_predicate( . self, . pred: Predicate<'tcx>, . binder: Binder<'tcx, PredicateKind<'tcx>>, . ) -> Predicate<'tcx> { 135,761 ( 0.00%) if pred.kind() != binder { self.mk_predicate(binder) } else { pred } 1,382,608 ( 0.02%) } . . pub fn mk_mach_int(self, tm: IntTy) -> Ty<'tcx> { 104 ( 0.00%) match tm { . IntTy::Isize => self.types.isize, . IntTy::I8 => self.types.i8, . IntTy::I16 => self.types.i16, . IntTy::I32 => self.types.i32, . IntTy::I64 => self.types.i64, . IntTy::I128 => self.types.i128, . } 104 ( 0.00%) } . . pub fn mk_mach_uint(self, tm: UintTy) -> Ty<'tcx> { 417 ( 0.00%) match tm { . UintTy::Usize => self.types.usize, . UintTy::U8 => self.types.u8, . UintTy::U16 => self.types.u16, . UintTy::U32 => self.types.u32, . UintTy::U64 => self.types.u64, . UintTy::U128 => self.types.u128, . } 417 ( 0.00%) } . . pub fn mk_mach_float(self, tm: FloatTy) -> Ty<'tcx> { . match tm { . FloatTy::F32 => self.types.f32, . FloatTy::F64 => self.types.f64, . } . } . . #[inline] . pub fn mk_static_str(self) -> Ty<'tcx> { 516 ( 0.00%) self.mk_imm_ref(self.lifetimes.re_static, self.types.str_) . } . . #[inline] . pub fn mk_adt(self, def: &'tcx AdtDef, substs: SubstsRef<'tcx>) -> Ty<'tcx> { . // Take a copy of substs so that we own the vectors inside. . self.mk_ty(Adt(def, substs)) . } . . #[inline] . pub fn mk_foreign(self, def_id: DefId) -> Ty<'tcx> { . self.mk_ty(Foreign(def_id)) . } . 24 ( 0.00%) fn mk_generic_adt(self, wrapper_def_id: DefId, ty_param: Ty<'tcx>) -> Ty<'tcx> { . let adt_def = self.adt_def(wrapper_def_id); . let substs = 45 ( 0.00%) InternalSubsts::for_item(self, wrapper_def_id, |param, substs| match param.kind { . GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => bug!(), 3 ( 0.00%) GenericParamDefKind::Type { has_default, .. } => { 12 ( 0.00%) if param.index == 0 { . ty_param.into() . } else { 3 ( 0.00%) assert!(has_default); 9 ( 0.00%) self.type_of(param.def_id).subst(self, substs).into() . } . } . }); 3 ( 0.00%) self.mk_ty(Adt(adt_def, substs)) 24 ( 0.00%) } . . #[inline] . pub fn mk_box(self, ty: Ty<'tcx>) -> Ty<'tcx> { 15 ( 0.00%) let def_id = self.require_lang_item(LangItem::OwnedBox, None); 12 ( 0.00%) self.mk_generic_adt(def_id, ty) . } . . #[inline] . pub fn mk_lang_item(self, ty: Ty<'tcx>, item: LangItem) -> Option> { . let def_id = self.lang_items().require(item).ok()?; . Some(self.mk_generic_adt(def_id, ty)) . } . -- line 2293 ---------------------------------------- -- line 2329 ---------------------------------------- . } . . #[inline] . pub fn mk_imm_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> { . self.mk_ptr(TypeAndMut { ty, mutbl: hir::Mutability::Not }) . } . . #[inline] 14,333 ( 0.00%) pub fn mk_array(self, ty: Ty<'tcx>, n: u64) -> Ty<'tcx> { . self.mk_ty(Array(ty, ty::Const::from_usize(self, n))) 14,960 ( 0.00%) } . . #[inline] . pub fn mk_slice(self, ty: Ty<'tcx>) -> Ty<'tcx> { . self.mk_ty(Slice(ty)) . } . . #[inline] . pub fn intern_tup(self, ts: &[Ty<'tcx>]) -> Ty<'tcx> { 284 ( 0.00%) let kinds: Vec<_> = ts.iter().map(|&t| GenericArg::from(t)).collect(); 362 ( 0.00%) self.mk_ty(Tuple(self.intern_substs(&kinds))) . } . . pub fn mk_tup], Ty<'tcx>>>(self, iter: I) -> I::Output { 10,034 ( 0.00%) iter.intern_with(|ts| { 5,025 ( 0.00%) let kinds: Vec<_> = ts.iter().map(|&t| GenericArg::from(t)).collect(); 12,284 ( 0.00%) self.mk_ty(Tuple(self.intern_substs(&kinds))) 8,928 ( 0.00%) }) . } . . #[inline] . pub fn mk_unit(self) -> Ty<'tcx> { 910 ( 0.00%) self.types.unit . } . . #[inline] . pub fn mk_diverging_default(self) -> Ty<'tcx> { 16 ( 0.00%) if self.features().never_type_fallback { self.types.never } else { self.types.unit } . } . . #[inline] . pub fn mk_fn_def(self, def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> { . self.mk_ty(FnDef(def_id, substs)) . } . . #[inline] . pub fn mk_fn_ptr(self, fty: PolyFnSig<'tcx>) -> Ty<'tcx> { 1,248 ( 0.00%) self.mk_ty(FnPtr(fty)) . } . . #[inline] . pub fn mk_dynamic( . self, . obj: &'tcx List>>, . reg: ty::Region<'tcx>, . ) -> Ty<'tcx> { -- line 2384 ---------------------------------------- -- line 2412 ---------------------------------------- . . #[inline] . pub fn mk_ty_var(self, v: TyVid) -> Ty<'tcx> { . self.mk_ty_infer(TyVar(v)) . } . . #[inline] . pub fn mk_const_var(self, v: ConstVid<'tcx>, ty: Ty<'tcx>) -> &'tcx Const<'tcx> { 252 ( 0.00%) self.mk_const(ty::Const { val: ty::ConstKind::Infer(InferConst::Var(v)), ty }) . } . . #[inline] . pub fn mk_int_var(self, v: IntVid) -> Ty<'tcx> { . self.mk_ty_infer(IntVar(v)) . } . . #[inline] -- line 2428 ---------------------------------------- -- line 2445 ---------------------------------------- . self.mk_ty(Param(ParamTy { index, name })) . } . . #[inline] . pub fn mk_const_param(self, index: u32, name: Symbol, ty: Ty<'tcx>) -> &'tcx Const<'tcx> { . self.mk_const(ty::Const { val: ty::ConstKind::Param(ParamConst { index, name }), ty }) . } . 12,103 ( 0.00%) pub fn mk_param_from_def(self, param: &ty::GenericParamDef) -> GenericArg<'tcx> { 7,381 ( 0.00%) match param.kind { . GenericParamDefKind::Lifetime => { 3,792 ( 0.00%) self.mk_region(ty::ReEarlyBound(param.to_early_bound_region_data())).into() . } 2,194 ( 0.00%) GenericParamDefKind::Type { .. } => self.mk_ty_param(param.index, param.name).into(), . GenericParamDefKind::Const { .. } => { . self.mk_const_param(param.index, param.name, self.type_of(param.def_id)).into() . } . } 12,103 ( 0.00%) } . . #[inline] . pub fn mk_opaque(self, def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> { . self.mk_ty(Opaque(def_id, substs)) . } . 1,529 ( 0.00%) pub fn mk_place_field(self, place: Place<'tcx>, f: Field, ty: Ty<'tcx>) -> Place<'tcx> { 1,529 ( 0.00%) self.mk_place_elem(place, PlaceElem::Field(f, ty)) 3,058 ( 0.00%) } . 47 ( 0.00%) pub fn mk_place_deref(self, place: Place<'tcx>) -> Place<'tcx> { 141 ( 0.00%) self.mk_place_elem(place, PlaceElem::Deref) 94 ( 0.00%) } . 254 ( 0.00%) pub fn mk_place_downcast( . self, . place: Place<'tcx>, . adt_def: &'tcx AdtDef, . variant_index: VariantIdx, . ) -> Place<'tcx> { 254 ( 0.00%) self.mk_place_elem( . place, 508 ( 0.00%) PlaceElem::Downcast(Some(adt_def.variants[variant_index].name), variant_index), . ) 508 ( 0.00%) } . . pub fn mk_place_downcast_unnamed( . self, . place: Place<'tcx>, . variant_index: VariantIdx, . ) -> Place<'tcx> { . self.mk_place_elem(place, PlaceElem::Downcast(None, variant_index)) . } -- line 2496 ---------------------------------------- -- line 2497 ---------------------------------------- . . pub fn mk_place_index(self, place: Place<'tcx>, index: Local) -> Place<'tcx> { . self.mk_place_elem(place, PlaceElem::Index(index)) . } . . /// This method copies `Place`'s projection, add an element and reintern it. Should not be used . /// to build a full `Place` it's just a convenient way to grab a projection and modify it in . /// flight. 16,857 ( 0.00%) pub fn mk_place_elem(self, place: Place<'tcx>, elem: PlaceElem<'tcx>) -> Place<'tcx> { . let mut projection = place.projection.to_vec(); . projection.push(elem); . . Place { local: place.local, projection: self.intern_place_elems(&projection) } 18,730 ( 0.00%) } . 2,828 ( 0.00%) pub fn intern_poly_existential_predicates( . self, . eps: &[ty::Binder<'tcx, ExistentialPredicate<'tcx>>], . ) -> &'tcx List>> { 404 ( 0.00%) assert!(!eps.is_empty()); . assert!( . eps.array_windows() 430 ( 0.00%) .all(|[a, b]| a.skip_binder().stable_cmp(self, &b.skip_binder()) . != Ordering::Greater) . ); 1,616 ( 0.00%) self._intern_poly_existential_predicates(eps) 3,232 ( 0.00%) } . . pub fn intern_predicates(self, preds: &[Predicate<'tcx>]) -> &'tcx List> { . // FIXME consider asking the input slice to be sorted to avoid . // re-interning permutations, in which case that would be asserted . // here. 6,969 ( 0.00%) if preds.is_empty() { . // The macro-generated method below asserts we don't intern an empty slice. . List::empty() . } else { 3,978 ( 0.00%) self._intern_predicates(preds) . } 6,048 ( 0.00%) } . . pub fn intern_type_list(self, ts: &[Ty<'tcx>]) -> &'tcx List> { 31,350 ( 0.00%) if ts.is_empty() { List::empty() } else { self._intern_type_list(ts) } 2,348 ( 0.00%) } . . pub fn intern_substs(self, ts: &[GenericArg<'tcx>]) -> &'tcx List> { 405,942 ( 0.01%) if ts.is_empty() { List::empty() } else { self._intern_substs(ts) } 15,236 ( 0.00%) } . . pub fn intern_projs(self, ps: &[ProjectionKind]) -> &'tcx List { . if ps.is_empty() { List::empty() } else { self._intern_projs(ps) } . } . . pub fn intern_place_elems(self, ts: &[PlaceElem<'tcx>]) -> &'tcx List> { 18,791 ( 0.00%) if ts.is_empty() { List::empty() } else { self._intern_place_elems(ts) } 14,702 ( 0.00%) } . . pub fn intern_canonical_var_infos( . self, . ts: &[CanonicalVarInfo<'tcx>], . ) -> CanonicalVarInfos<'tcx> { 20,751 ( 0.00%) if ts.is_empty() { List::empty() } else { self._intern_canonical_var_infos(ts) } 710 ( 0.00%) } . . pub fn intern_bound_variable_kinds( . self, . ts: &[ty::BoundVariableKind], . ) -> &'tcx List { 8,929 ( 0.00%) if ts.is_empty() { List::empty() } else { self._intern_bound_variable_kinds(ts) } 13,948 ( 0.00%) } . . pub fn mk_fn_sig( . self, . inputs: I, . output: I::Item, . c_variadic: bool, . unsafety: hir::Unsafety, . abi: abi::Abi, . ) -> , ty::FnSig<'tcx>>>::Output . where . I: Iterator, ty::FnSig<'tcx>>>, . { . inputs.chain(iter::once(output)).intern_with(|xs| ty::FnSig { 2,436 ( 0.00%) inputs_and_output: self.intern_type_list(xs), 464 ( 0.00%) c_variadic, 667 ( 0.00%) unsafety, 522 ( 0.00%) abi, 160 ( 0.00%) }) . } . . pub fn mk_poly_existential_predicates< . I: InternAs< . [ty::Binder<'tcx, ExistentialPredicate<'tcx>>], . &'tcx List>>, . >, . >( . self, . iter: I, . ) -> I::Output { 1,662 ( 0.00%) iter.intern_with(|xs| self.intern_poly_existential_predicates(xs)) . } . . pub fn mk_predicates], &'tcx List>>>( . self, . iter: I, . ) -> I::Output { 6 ( 0.00%) iter.intern_with(|xs| self.intern_predicates(xs)) . } . . pub fn mk_type_list], &'tcx List>>>(self, iter: I) -> I::Output { 15,637 ( 0.00%) iter.intern_with(|xs| self.intern_type_list(xs)) . } . 75 ( 0.00%) pub fn mk_substs], &'tcx List>>>( . self, . iter: I, . ) -> I::Output { 265,224 ( 0.00%) iter.intern_with(|xs| self.intern_substs(xs)) 100 ( 0.00%) } . . pub fn mk_place_elems], &'tcx List>>>( . self, . iter: I, . ) -> I::Output { 91,627 ( 0.00%) iter.intern_with(|xs| self.intern_place_elems(xs)) . } . 16,871 ( 0.00%) pub fn mk_substs_trait(self, self_ty: Ty<'tcx>, rest: &[GenericArg<'tcx>]) -> SubstsRef<'tcx> { . self.mk_substs(iter::once(self_ty.into()).chain(rest.iter().cloned())) 33,742 ( 0.00%) } . . pub fn mk_bound_variable_kinds< . I: InternAs<[ty::BoundVariableKind], &'tcx List>, . >( . self, . iter: I, . ) -> I::Output { 48,020 ( 0.00%) iter.intern_with(|xs| self.intern_bound_variable_kinds(xs)) . } . . /// Walks upwards from `id` to find a node which might change lint levels with attributes. . /// It stops at `bound` and just returns it if reached. 2,049,026 ( 0.03%) pub fn maybe_lint_level_root_bounded(self, mut id: HirId, bound: HirId) -> HirId { 2,049,026 ( 0.03%) let hir = self.hir(); . loop { 3,134,322 ( 0.04%) if id == bound { . return bound; . } . 3,760,536 ( 0.05%) if hir.attrs(id).iter().any(|attr| Level::from_symbol(attr.name_or_empty()).is_some()) { . return id; . } . let next = hir.get_parent_node(id); 2,256,168 ( 0.03%) if next == id { . bug!("lint traversal reached the root of the crate"); . } . id = next; . } 2,927,180 ( 0.04%) } . 9,816 ( 0.00%) pub fn lint_level_at_node( . self, . lint: &'static Lint, . mut id: hir::HirId, . ) -> (Level, LintLevelSource) { . let sets = self.lint_levels(()); . loop { 64,257 ( 0.00%) if let Some(pair) = sets.level_and_source(lint, id, self.sess) { . return pair; . } 5,231 ( 0.00%) let next = self.hir().get_parent_node(id); 15,693 ( 0.00%) if next == id { . bug!("lint traversal reached the root of the crate"); . } . id = next; . } 9,816 ( 0.00%) } . 518 ( 0.00%) pub fn struct_span_lint_hir( . self, . lint: &'static Lint, . hir_id: HirId, . span: impl Into, . decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>), . ) { 4,983 ( 0.00%) let (level, src) = self.lint_level_at_node(lint, hir_id); 1,391 ( 0.00%) struct_lint_level(self.sess, lint, level, src, Some(span.into()), decorate); 296 ( 0.00%) } . . pub fn struct_lint_node( . self, . lint: &'static Lint, . id: HirId, . decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>), . ) { . let (level, src) = self.lint_level_at_node(lint, id); . struct_lint_level(self.sess, lint, level, src, None, decorate); . } . 4,459 ( 0.00%) pub fn in_scope_traits(self, id: HirId) -> Option<&'tcx [TraitCandidate]> { 1,274 ( 0.00%) let map = self.in_scope_traits_map(id.owner)?; . let candidates = map.get(&id.local_id)?; 1,274 ( 0.00%) Some(&*candidates) 5,096 ( 0.00%) } . 10,451 ( 0.00%) pub fn named_region(self, id: HirId) -> Option { . debug!(?id, "named_region"); . self.named_region_map(id.owner).and_then(|map| map.get(&id.local_id).cloned()) 13,437 ( 0.00%) } . 1,179 ( 0.00%) pub fn is_late_bound(self, id: HirId) -> bool { . self.is_late_bound_map(id.owner) 64 ( 0.00%) .map_or(false, |(owner, set)| owner == id.owner && set.contains(&id.local_id)) 1,048 ( 0.00%) } . 8,288 ( 0.00%) pub fn object_lifetime_defaults(self, id: HirId) -> Option> { . self.object_lifetime_defaults_map(id.owner) 10,656 ( 0.00%) } . 5,985 ( 0.00%) pub fn late_bound_vars(self, id: HirId) -> &'tcx List { . self.mk_bound_variable_kinds( . self.late_bound_vars_map(id.owner) . .and_then(|map| map.get(&id.local_id).cloned()) . .unwrap_or_else(|| { . bug!("No bound vars found for {:?} ({:?})", self.hir().node_to_string(id), id) . }) . .iter(), . ) 5,985 ( 0.00%) } . . pub fn lifetime_scope(self, id: HirId) -> Option { . self.lifetime_scope_map(id.owner).and_then(|mut map| map.remove(&id.local_id)) . } . . /// Whether the `def_id` counts as const fn in the current crate, considering all active . /// feature gates 390 ( 0.00%) pub fn is_const_fn(self, def_id: DefId) -> bool { 39 ( 0.00%) if self.is_const_fn_raw(def_id) { 10 ( 0.00%) match self.lookup_const_stability(def_id) { 20 ( 0.00%) Some(stability) if stability.level.is_unstable() => { . // has a `rustc_const_unstable` attribute, check whether the user enabled the . // corresponding feature gate. 8 ( 0.00%) self.features() . .declared_lib_features . .iter() . .any(|&(sym, _)| sym == stability.feature) . } . // functions without const stability are either stable user written . // const fn or the user is using feature gates and we thus don't . // care what they do . _ => true, . } . } else { . false . } 351 ( 0.00%) } . } . . impl<'tcx> TyCtxtAt<'tcx> { . /// Constructs a `TyKind::Error` type and registers a `delay_span_bug` to ensure it gets used. . #[track_caller] . pub fn ty_error(self) -> Ty<'tcx> { . self.tcx.ty_error_with_message(self.span, "TyKind::Error constructed but no error reported") . } -- line 2759 ---------------------------------------- -- line 2774 ---------------------------------------- . } . . impl InternAs<[T], R> for I . where . E: InternIteratorElement, . I: Iterator, . { . type Output = E::Output; 145,304 ( 0.00%) fn intern_with(self, f: F) -> Self::Output . where . F: FnOnce(&[T]) -> R, . { 883,925 ( 0.01%) E::intern_with(self, f) 109,485 ( 0.00%) } . } . . pub trait InternIteratorElement: Sized { . type Output; . fn intern_with, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output; . } . . impl InternIteratorElement for T { . type Output = R; 154,242 ( 0.00%) fn intern_with, F: FnOnce(&[T]) -> R>( . mut iter: I, . f: F, . ) -> Self::Output { . // This code is hot enough that it's worth specializing for the most . // common length lists, to avoid the overhead of `SmallVec` creation. . // Lengths 0, 1, and 2 typically account for ~95% of cases. If . // `size_hint` is incorrect a panic will occur via an `unwrap` or an . // `assert`. 194,563 ( 0.00%) match iter.size_hint() { . (0, Some(0)) => { 6 ( 0.00%) assert!(iter.next().is_none()); . f(&[]) . } . (1, Some(1)) => { . let t0 = iter.next().unwrap(); 1 ( 0.00%) assert!(iter.next().is_none()); 24,576 ( 0.00%) f(&[t0]) . } . (2, Some(2)) => { . let t0 = iter.next().unwrap(); . let t1 = iter.next().unwrap(); 224 ( 0.00%) assert!(iter.next().is_none()); 24,179 ( 0.00%) f(&[t0, t1]) . } 980 ( 0.00%) _ => f(&iter.collect::>()), . } 123,815 ( 0.00%) } . } . . impl<'a, T, R> InternIteratorElement for &'a T . where . T: Clone + 'a, . { . type Output = R; 4,022 ( 0.00%) fn intern_with, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output { . // This code isn't hot. 64 ( 0.00%) f(&iter.cloned().collect::>()) 3,276 ( 0.00%) } . } . . impl InternIteratorElement for Result { . type Output = Result; 264,200 ( 0.00%) fn intern_with, F: FnOnce(&[T]) -> R>( . mut iter: I, . f: F, . ) -> Self::Output { . // This code is hot enough that it's worth specializing for the most . // common length lists, to avoid the overhead of `SmallVec` creation. . // Lengths 0, 1, and 2 typically account for ~95% of cases. If . // `size_hint` is incorrect a panic will occur via an `unwrap` or an . // `assert`, unless a failure happens first, in which case the result . // will be an error anyway. 214,210 ( 0.00%) Ok(match iter.size_hint() { . (0, Some(0)) => { . assert!(iter.next().is_none()); . f(&[]) . } . (1, Some(1)) => { 924 ( 0.00%) let t0 = iter.next().unwrap()?; . assert!(iter.next().is_none()); 17,270 ( 0.00%) f(&[t0]) . } . (2, Some(2)) => { 509 ( 0.00%) let t0 = iter.next().unwrap()?; 509 ( 0.00%) let t1 = iter.next().unwrap()?; 489 ( 0.00%) assert!(iter.next().is_none()); 25,142 ( 0.00%) f(&[t0, t1]) . } 2,552 ( 0.00%) _ => f(&iter.collect::, _>>()?), . }) 297,611 ( 0.00%) } . } . . // We are comparing types with different invariant lifetimes, so `ptr::eq` . // won't work for us. . fn ptr_eq(t: *const T, u: *const U) -> bool { 155,599 ( 0.00%) t as *const () == u as *const () . } . . pub fn provide(providers: &mut ty::query::Providers) { 2 ( 0.00%) providers.in_scope_traits_map = . |tcx, id| tcx.hir_crate(()).owners[id].as_ref().map(|owner_info| &owner_info.trait_map); 3 ( 0.00%) providers.resolutions = |tcx, ()| &tcx.untracked_resolutions; 2 ( 0.00%) providers.module_reexports = . |tcx, id| tcx.resolutions(()).reexport_map.get(&id).map(|v| &v[..]); 2 ( 0.00%) providers.crate_name = |tcx, id| { 1 ( 0.00%) assert_eq!(id, LOCAL_CRATE); 1 ( 0.00%) tcx.crate_name . }; 2 ( 0.00%) providers.maybe_unused_trait_import = . |tcx, id| tcx.resolutions(()).maybe_unused_trait_imports.contains(&id); 2 ( 0.00%) providers.maybe_unused_extern_crates = . |tcx, ()| &tcx.resolutions(()).maybe_unused_extern_crates[..]; 2 ( 0.00%) providers.names_imported_by_glob_use = |tcx, id| { . tcx.arena.alloc(tcx.resolutions(()).glob_map.get(&id).cloned().unwrap_or_default()) . }; . 11 ( 0.00%) providers.lookup_stability = |tcx, id| tcx.stability().local_stability(id.expect_local()); 2 ( 0.00%) providers.lookup_const_stability = . |tcx, id| tcx.stability().local_const_stability(id.expect_local()); 2 ( 0.00%) providers.lookup_deprecation_entry = 6,208 ( 0.00%) |tcx, id| tcx.stability().local_deprecation_entry(id.expect_local()); 2 ( 0.00%) providers.extern_mod_stmt_cnum = . |tcx, id| tcx.resolutions(()).extern_crate_map.get(&id).cloned(); 3 ( 0.00%) providers.output_filenames = |tcx, ()| tcx.output_filenames.clone(); 3 ( 0.00%) providers.features_query = |tcx, ()| tcx.sess.features_untracked(); 2 ( 0.00%) providers.is_panic_runtime = |tcx, cnum| { 1 ( 0.00%) assert_eq!(cnum, LOCAL_CRATE); 7 ( 0.00%) tcx.sess.contains_name(tcx.hir().krate_attrs(), sym::panic_runtime) . }; 2 ( 0.00%) providers.is_compiler_builtins = |tcx, cnum| { 1 ( 0.00%) assert_eq!(cnum, LOCAL_CRATE); 7 ( 0.00%) tcx.sess.contains_name(tcx.hir().krate_attrs(), sym::compiler_builtins) . }; 2 ( 0.00%) providers.has_panic_handler = |tcx, cnum| { 1 ( 0.00%) assert_eq!(cnum, LOCAL_CRATE); . // We want to check if the panic handler was defined in this crate 3 ( 0.00%) tcx.lang_items().panic_impl().map_or(false, |did| did.is_local()) . }; . } 3,155,157 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/middle/region.rs -------------------------------------------------------------------------------- Ir -- line 77 ---------------------------------------- . // . // FIXME(pnkfelix): this currently derives `PartialOrd` and `Ord` to . // placate the same deriving in `ty::FreeRegion`, but we may want to . // actually attach a more meaningful ordering to scopes than the one . // generated via deriving here. . #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Copy, TyEncodable, TyDecodable)] . #[derive(HashStable)] . pub struct Scope { 149,052 ( 0.00%) pub id: hir::ItemLocalId, 3,413,886 ( 0.05%) pub data: ScopeData, . } . . impl fmt::Debug for Scope { . fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { . match self.data { . ScopeData::Node => write!(fmt, "Node({:?})", self.id), . ScopeData::CallSite => write!(fmt, "CallSite({:?})", self.id), . ScopeData::Arguments => write!(fmt, "Arguments({:?})", self.id), -- line 94 ---------------------------------------- -- line 99 ---------------------------------------- . "Remainder {{ block: {:?}, first_statement_index: {}}}", . self.id, . fsi.as_u32(), . ), . } . } . } . 16,064,697 ( 0.23%) #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Debug, Copy, TyEncodable, TyDecodable)] . #[derive(HashStable)] . pub enum ScopeData { . Node, . . /// Scope of the call-site for a function or closure . /// (outlives the arguments as well as the body). . CallSite, . -- line 115 ---------------------------------------- -- line 159 ---------------------------------------- . /// . /// N.B., likely to be replaced as API is refined; e.g., pnkfelix . /// anticipates `fn entry_node_id` and `fn each_exit_node_id`. . pub fn item_local_id(&self) -> hir::ItemLocalId { . self.id . } . . pub fn hir_id(&self, scope_tree: &ScopeTree) -> Option { 6,329 ( 0.00%) scope_tree . .root_body . .map(|hir_id| hir::HirId { owner: hir_id.owner, local_id: self.item_local_id() }) . } . . /// Returns the span of this `Scope`. Note that in general the . /// returned span may not correspond to the span of any `NodeId` in . /// the AST. 44,303 ( 0.00%) pub fn span(&self, tcx: TyCtxt<'_>, scope_tree: &ScopeTree) -> Span { 12,658 ( 0.00%) let hir_id = match self.hir_id(scope_tree) { . Some(hir_id) => hir_id, . None => return DUMMY_SP, . }; 25,316 ( 0.00%) let span = tcx.hir().span(hir_id); 25,316 ( 0.00%) if let ScopeData::Remainder(first_statement_index) = self.data { 2,688 ( 0.00%) if let Node::Block(ref blk) = tcx.hir().get(hir_id) { . // Want span for scope starting after the . // indexed statement and ending at end of . // `blk`; reuse span of `blk` and shift `lo` . // forward to end of indexed statement. . // . // (This is the special case alluded to in the . // doc-comment for this method) . 3,584 ( 0.00%) let stmt_span = blk.stmts[first_statement_index.index()].span; . . // To avoid issues with macro-generated spans, the span . // of the statement must be nested in that of the block. 863 ( 0.00%) if span.lo() <= stmt_span.lo() && stmt_span.lo() <= span.hi() { 1,588 ( 0.00%) return span.with_lo(stmt_span.lo()); . } . } . } . span 56,961 ( 0.00%) } . } . . pub type ScopeDepth = u32; . . /// The region scope tree encodes information about region relationships. . #[derive(Default, Debug)] . pub struct ScopeTree { . /// If not empty, this body is the root of this region hierarchy. -- line 209 ---------------------------------------- -- line 321 ---------------------------------------- . /// The `Span` of the yield. . pub span: Span, . /// The number of expressions and patterns appearing before the `yield` in the body, plus one. . pub expr_and_pat_count: usize, . pub source: hir::YieldSource, . } . . impl ScopeTree { 904,176 ( 0.01%) pub fn record_scope_parent(&mut self, child: Scope, parent: Option<(Scope, ScopeDepth)>) { . debug!("{:?}.parent = {:?}", child, parent); . 301,392 ( 0.00%) if let Some(p) = parent { . let prev = self.parent_map.insert(child, p); 149,856 ( 0.00%) assert!(prev.is_none()); . } . . // Record the destruction scopes for later so we can query them. 301,392 ( 0.00%) if let ScopeData::Destruction = child.data { . self.destruction_scopes.insert(child.item_local_id(), child); . } 597,284 ( 0.01%) } . 293,100 ( 0.00%) pub fn opt_destruction_scope(&self, n: hir::ItemLocalId) -> Option { . self.destruction_scopes.get(&n).cloned() 293,100 ( 0.00%) } . . pub fn record_var_scope(&mut self, var: hir::ItemLocalId, lifetime: Scope) { . debug!("record_var_scope(sub={:?}, sup={:?})", var, lifetime); 874 ( 0.00%) assert!(var != lifetime.item_local_id()); . self.var_map.insert(var, lifetime); . } . . pub fn record_rvalue_scope(&mut self, var: hir::ItemLocalId, lifetime: Option) { . debug!("record_rvalue_scope(sub={:?}, sup={:?})", var, lifetime); 2,668 ( 0.00%) if let Some(lifetime) = lifetime { . assert!(var != lifetime.item_local_id()); . } . self.rvalue_scopes.insert(var, lifetime); . } . . /// Returns the narrowest scope that encloses `id`, if any. . pub fn opt_encl_scope(&self, id: Scope) -> Option { . self.parent_map.get(&id).cloned().map(|(p, _)| p) . } . . /// Returns the lifetime of the local variable `var_id` 1,752 ( 0.00%) pub fn var_scope(&self, var_id: hir::ItemLocalId) -> Scope { . self.var_map . .get(&var_id) . .cloned() . .unwrap_or_else(|| bug!("no enclosing scope for id {:?}", var_id)) 1,752 ( 0.00%) } . . /// Returns the scope when the temp created by `expr_id` will be cleaned up. 2,041,361 ( 0.03%) pub fn temporary_scope(&self, expr_id: hir::ItemLocalId) -> Option { . // Check for a designated rvalue scope. 4,020 ( 0.00%) if let Some(&s) = self.rvalue_scopes.get(&expr_id) { . debug!("temporary_scope({:?}) = {:?} [custom]", expr_id, s); . return s; . } . . // Otherwise, locate the innermost terminating scope . // if there's one. Static items, for instance, won't . // have an enclosing scope, hence no scope will be . // returned. 290,283 ( 0.00%) let mut id = Scope { id: expr_id, data: ScopeData::Node }; . 9,742,320 ( 0.14%) while let Some(&(p, _)) = self.parent_map.get(&id) { 3,154,821 ( 0.04%) match p.data { . ScopeData::Destruction => { . debug!("temporary_scope({:?}) = {:?} [enclosing]", expr_id, id); . return Some(id); . } 1,142,946 ( 0.02%) _ => id = p, . } . } . . debug!("temporary_scope({:?}) = None", expr_id); . None 2,332,984 ( 0.03%) } . . /// Returns `true` if `subscope` is equal to or is lexically nested inside `superscope`, and . /// `false` otherwise. . /// . /// Used by clippy. . pub fn is_subscope_of(&self, subscope: Scope, superscope: Scope) -> bool { . let mut s = subscope; . debug!("is_subscope_of({:?}, {:?})", subscope, superscope); -- line 408 ---------------------------------------- 5,999,769 ( 0.09%) -------------------------------------------------------------------------------- -- 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")] 276,176 ( 0.00%) pub fn from_str_radix(src: &str, radix: u32) -> Result { 138,088 ( 0.00%) from_str_radix(src, radix) 414,264 ( 0.01%) } . . /// 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 { 198,165 ( 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 { 423,211 ( 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 { 1,535,096 ( 0.02%) 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 { 29,783,061 ( 0.42%) 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`. 2,241,660 ( 0.03%) 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`. 39,330 ( 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 424 ( 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 { 283,920 ( 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 { 321,915 ( 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 { 19,976,947 ( 0.28%) 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 { 9,041,172 ( 0.13%) 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 { 17,764,733 ( 0.25%) 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 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)] 10 ( 0.00%) pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) { 4,156,910 ( 0.06%) let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT); . (a as Self, b) 20 ( 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 1587 ---------------------------------------- . #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));")] . #[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)] 2 ( 0.00%) pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) { 626,512 ( 0.01%) let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT); . (a as Self, b) 4 ( 0.00%) } . . /// 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. . /// . /// # Examples -- line 1606 ---------------------------------------- -- line 1674 ---------------------------------------- . /// 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)] . pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) { 3,850,423 ( 0.05%) let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT); . (a as Self, b) . } . . /// 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 -- line 1690 ---------------------------------------- -- 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 { 168 ( 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 { 7,596 ( 0.00%) if self <= 1 { return 0; } . 20,520 ( 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. 61,424 ( 0.00%) let z = unsafe { intrinsics::ctlz_nonzero(p) }; 20,584 ( 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 { 33,400 ( 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 ---------------------------------------- 376,111 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lint/src/levels.rs -------------------------------------------------------------------------------- Ir -- line 20 ---------------------------------------- . Level, Lint, LintId, . }; . use rustc_session::parse::feature_err; . use rustc_session::Session; . use rustc_span::symbol::{sym, Symbol}; . use rustc_span::{source_map::MultiSpan, Span, DUMMY_SP}; . use tracing::debug; . 9 ( 0.00%) fn lint_levels(tcx: TyCtxt<'_>, (): ()) -> LintLevelMap { . let store = unerased_lint_store(tcx); . let levels = 6 ( 0.00%) LintLevelsBuilder::new(tcx.sess, false, &store, &tcx.resolutions(()).registered_tools); 13 ( 0.00%) let mut builder = LintLevelMapBuilder { levels, tcx }; 3 ( 0.00%) let krate = tcx.hir().krate(); . 2 ( 0.00%) builder.levels.id_to_set.reserve(krate.owners.len() + 1); . 8 ( 0.00%) let push = builder.levels.push(tcx.hir().attrs(hir::CRATE_HIR_ID), true); . builder.levels.register_id(hir::CRATE_HIR_ID); . tcx.hir().walk_toplevel_module(&mut builder); . builder.levels.pop(push); . 16 ( 0.00%) builder.levels.build_map() 9 ( 0.00%) } . . pub struct LintLevelsBuilder<'s> { . sess: &'s Session, . sets: LintLevelSets, . id_to_set: FxHashMap, . cur: LintStackIndex, . warn_about_weird_lints: bool, . store: &'s LintStore, -- line 51 ---------------------------------------- -- line 53 ---------------------------------------- . } . . pub struct BuilderPush { . prev: LintStackIndex, . pub changed: bool, . } . . impl<'s> LintLevelsBuilder<'s> { 273 ( 0.00%) pub fn new( . sess: &'s Session, . warn_about_weird_lints: bool, . store: &'s LintStore, . registered_tools: &'s RegisteredTools, . ) -> Self { 231 ( 0.00%) let mut builder = LintLevelsBuilder { . sess, 21 ( 0.00%) sets: LintLevelSets::new(), . cur: COMMAND_LINE, . id_to_set: Default::default(), . warn_about_weird_lints, . store, . registered_tools, . }; . builder.process_command_line(sess, store); 63 ( 0.00%) assert_eq!(builder.sets.list.len(), 1); . builder 189 ( 0.00%) } . . pub(crate) fn sess(&self) -> &Session { 8,446 ( 0.00%) self.sess . } . . pub(crate) fn lint_store(&self) -> &LintStore { . self.store . } . . fn process_command_line(&mut self, sess: &Session, store: &LintStore) { . let mut specs = FxHashMap::default(); 42 ( 0.00%) self.sets.lint_cap = sess.opts.lint_cap.unwrap_or(Level::Forbid); . 42 ( 0.00%) for &(ref lint_name, level) in &sess.opts.lint_opts { 210 ( 0.00%) store.check_lint_name_cmdline(sess, &lint_name, level, self.registered_tools); . let orig_level = level; 84 ( 0.00%) let lint_flag_val = Symbol::intern(lint_name); . 210 ( 0.00%) let ids = match store.find_lints(&lint_name) { 168 ( 0.00%) Ok(ids) => ids, . Err(_) => continue, // errors handled in check_lint_name_cmdline above . }; 126 ( 0.00%) for id in ids { . // ForceWarn and Forbid cannot be overriden . if let Some((Level::ForceWarn | Level::Forbid, _)) = specs.get(&id) { . continue; . } . 168 ( 0.00%) self.check_gated_lint(id, DUMMY_SP); . let src = LintLevelSource::CommandLine(lint_flag_val, orig_level); 84 ( 0.00%) specs.insert(id, (level, src)); . } . } . 168 ( 0.00%) self.cur = self.sets.list.push(LintSet { specs, parent: COMMAND_LINE }); . } . . /// Attempts to insert the `id` to `level_src` map entry. If unsuccessful . /// (e.g. if a forbid was already inserted on the same scope), then emits a . /// diagnostic with no change to `specs`. 2,783 ( 0.00%) fn insert_spec( . &mut self, . specs: &mut FxHashMap, . id: LintId, 1,518 ( 0.00%) (level, src): LevelAndSource, . ) { 1,265 ( 0.00%) let (old_level, old_src) = 1,771 ( 0.00%) self.sets.get_lint_level(id.lint, self.cur, Some(&specs), &self.sess); . // Setting to a non-forbid level is an error if the lint previously had . // a forbid level. Note that this is not necessarily true even with a . // `#[forbid(..)]` attribute present, as that is overriden by `--cap-lints`. . // . // This means that this only errors if we're truly lowering the lint . // level from forbid. 253 ( 0.00%) if level != Level::Forbid { 1,012 ( 0.00%) if let Level::Forbid = old_level { . // Backwards compatibility check: . // . // We used to not consider `forbid(lint_group)` . // as preventing `allow(lint)` for some lint `lint` in . // `lint_group`. For now, issue a future-compatibility . // warning for this case. . let id_name = id.lint.name_lower(); . let fcw_warning = match old_src { -- line 143 ---------------------------------------- -- line 202 ---------------------------------------- . if !fcw_warning { . return; . } . } . } . if let Level::ForceWarn = old_level { . specs.insert(id, (old_level, old_src)); . } else { 1,012 ( 0.00%) specs.insert(id, (level, src)); . } 2,024 ( 0.00%) } . . /// Pushes a list of AST lint attributes onto this context. . /// . /// This function will return a `BuilderPush` object which should be passed . /// to `pop` when this scope for the attributes provided is exited. . /// . /// This function will perform a number of tasks: . /// . /// * It'll validate all lint-related attributes in `attrs` . /// * It'll mark all lint-related attributes as used . /// * Lint levels will be updated based on the attributes provided . /// * Lint attributes are validated, e.g., a `#[forbid]` can't be switched to . /// `#[allow]` . /// . /// Don't forget to call `pop`! 3,528,960 ( 0.05%) pub(crate) fn push(&mut self, attrs: &[ast::Attribute], is_crate_node: bool) -> BuilderPush { . let mut specs = FxHashMap::default(); 882,240 ( 0.01%) let sess = self.sess; 441,120 ( 0.01%) let bad_attr = |span| struct_span_err!(sess, span, E0452, "malformed lint attribute input"); . for attr in attrs { 35,742 ( 0.00%) let Some(level) = Level::from_symbol(attr.name_or_empty()) else { . continue . }; . 1,359 ( 0.00%) let Some(mut metas) = attr.meta_item_list() else { . continue . }; . 151 ( 0.00%) if metas.is_empty() { . // FIXME (#55112): issue unused-attributes lint for `#[level()]` . continue; . } . . // Before processing the lint names, look for a reason (RFC 2383) . // at the end. . let mut reason = None; 151 ( 0.00%) let tail_li = &metas[metas.len() - 1]; 453 ( 0.00%) if let Some(item) = tail_li.meta_item() { 755 ( 0.00%) match item.kind { . ast::MetaItemKind::Word => {} // actual lint names handled later . ast::MetaItemKind::NameValue(ref name_value) => { . if item.path == sym::reason { . // FIXME (#55112): issue unused-attributes lint if we thereby . // don't have any lint names (`#[level(reason = "foo")]`) . if let ast::LitKind::Str(rationale, _) = name_value.kind { . if !self.sess.features_untracked().lint_reasons { . feature_err( -- line 259 ---------------------------------------- -- line 279 ---------------------------------------- . } . } . ast::MetaItemKind::List(_) => { . bad_attr(item.span).span_label(item.span, "bad attribute argument").emit(); . } . } . } . 3,322 ( 0.00%) for li in metas { 604 ( 0.00%) let sp = li.span(); 302 ( 0.00%) let mut meta_item = match li { 2,718 ( 0.00%) ast::NestedMetaItem::MetaItem(meta_item) if meta_item.is_word() => meta_item, . _ => { . let mut err = bad_attr(sp); . let mut add_label = true; . if let Some(item) = li.meta_item() { . if let ast::MetaItemKind::NameValue(_) = item.kind { . if item.path == sym::reason { . err.span_label(sp, "reason in lint attribute must come last"); . add_label = false; -- line 298 ---------------------------------------- -- line 301 ---------------------------------------- . } . if add_label { . err.span_label(sp, "bad attribute argument"); . } . err.emit(); . continue; . } . }; 453 ( 0.00%) let tool_ident = if meta_item.path.segments.len() > 1 { 72 ( 0.00%) Some(meta_item.path.segments.remove(0).ident) . } else { 133 ( 0.00%) None . }; 151 ( 0.00%) let tool_name = tool_ident.map(|ident| ident.name); 453 ( 0.00%) let name = pprust::path_to_string(&meta_item.path); . let lint_result = 755 ( 0.00%) self.store.check_lint_name(&name, tool_name, self.registered_tools); 525 ( 0.00%) match &lint_result { . CheckLintNameResult::Ok(ids) => { . let src = LintLevelSource::Node( . meta_item.path.segments.last().expect("empty lint name").ident.name, . sp, . reason, . ); 639 ( 0.00%) for &id in *ids { 1,265 ( 0.00%) self.check_gated_lint(id, attr.span); 3,036 ( 0.00%) self.insert_spec(&mut specs, id, (level, src)); . } . } . . CheckLintNameResult::Tool(result) => { 90 ( 0.00%) match *result { . Ok(ids) => { . let complete_name = . &format!("{}::{}", tool_ident.unwrap().name, name); . let src = LintLevelSource::Node( . Symbol::intern(complete_name), . sp, . reason, . ); -- line 340 ---------------------------------------- -- line 454 ---------------------------------------- . } . db.emit(); . }); . } . } . // If this lint was renamed, apply the new lint instead of ignoring the attribute. . // This happens outside of the match because the new lint should be applied even if . // we don't warn about the name change. 755 ( 0.00%) if let CheckLintNameResult::Warning(_, Some(new_name)) = lint_result { . // Ignore any errors or warnings that happen because the new name is inaccurate . // NOTE: `new_name` already includes the tool name, so we don't have to add it again. . if let CheckLintNameResult::Ok(ids) = . self.store.check_lint_name(&new_name, None, self.registered_tools) . { . let src = LintLevelSource::Node(Symbol::intern(&new_name), sp, reason); . for &id in ids { . self.check_gated_lint(id, attr.span); . self.insert_spec(&mut specs, id, (level, src)); . } . } else { . panic!("renamed lint does not exist: {}", new_name); . } . } 604 ( 0.00%) } . } . 882,240 ( 0.01%) if !is_crate_node { 500 ( 0.00%) for (id, &(level, ref src)) in specs.iter() { 750 ( 0.00%) if !id.lint.crate_level_only { . continue; . } . . let LintLevelSource::Node(lint_attr_name, lint_attr_span, _) = *src else { . continue . }; . . let lint = builtin::UNUSED_ATTRIBUTES; -- line 490 ---------------------------------------- -- line 505 ---------------------------------------- . db.emit(); . }, . ); . // don't set a separate error for every lint in the group . break; . } . } . 441,120 ( 0.01%) let prev = self.cur; 441,120 ( 0.01%) if !specs.is_empty() { 798 ( 0.00%) self.cur = self.sets.list.push(LintSet { specs, parent: prev }); . } . . BuilderPush { prev, changed: prev != self.cur } 3,970,080 ( 0.06%) } . . /// Checks if the lint is gated on a feature that is not enabled. 2,065 ( 0.00%) fn check_gated_lint(&self, lint_id: LintId, span: Span) { 885 ( 0.00%) if let Some(feature) = lint_id.lint.feature_gate { . if !self.sess.features_untracked().enabled(feature) { . feature_err( . &self.sess.parse_sess, . feature, . span, . &format!("the `{}` lint is unstable", lint_id.lint.name_lower()), . ) . .emit(); . } . } 2,360 ( 0.00%) } . . /// Called after `push` when the scope of a set of attributes are exited. . pub fn pop(&mut self, push: BuilderPush) { 579,011 ( 0.01%) self.cur = push.prev; 293,896 ( 0.00%) } . . /// Find the lint level for a lint. 130 ( 0.00%) pub fn lint_level(&self, lint: &'static Lint) -> (Level, LintLevelSource) { 541 ( 0.00%) self.sets.get_lint_level(lint, self.cur, None, self.sess) 195 ( 0.00%) } . . /// Used to emit a lint-related diagnostic based on the current state of . /// this lint context. 763 ( 0.00%) pub fn struct_lint( . &self, . lint: &'static Lint, . span: Option, . decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>), . ) { 592 ( 0.00%) let (level, src) = self.lint_level(lint); 82 ( 0.00%) struct_lint_level(self.sess, lint, level, src, span, decorate) 487 ( 0.00%) } . . /// Registers the ID provided with the current set of lints stored in . /// this context. . pub fn register_id(&mut self, id: HirId) { 128 ( 0.00%) self.id_to_set.insert(id, self.cur); . } . . pub fn build_map(self) -> LintLevelMap { 8 ( 0.00%) LintLevelMap { sets: self.sets, id_to_set: self.id_to_set } . } . } . . struct LintLevelMapBuilder<'tcx> { . levels: LintLevelsBuilder<'tcx>, . tcx: TyCtxt<'tcx>, . } . . impl LintLevelMapBuilder<'_> { . fn with_lint_attrs(&mut self, id: hir::HirId, f: F) . where . F: FnOnce(&mut Self), . { . let is_crate_hir = id == hir::CRATE_HIR_ID; 870,048 ( 0.01%) let attrs = self.tcx.hir().attrs(id); 870,738 ( 0.01%) let push = self.levels.push(attrs, is_crate_hir); 145,180 ( 0.00%) if push.changed { . self.levels.register_id(id); . } . f(self); . self.levels.pop(push); . } . } . . impl<'tcx> intravisit::Visitor<'tcx> for LintLevelMapBuilder<'tcx> { . type NestedFilter = nested_filter::All; . . fn nested_visit_map(&mut self) -> Self::Map { 1,091 ( 0.00%) self.tcx.hir() . } . . fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) { 884 ( 0.00%) self.with_lint_attrs(param.hir_id, |builder| { . intravisit::walk_param(builder, param); . }); . } . . fn visit_item(&mut self, it: &'tcx hir::Item<'tcx>) { 492 ( 0.00%) self.with_lint_attrs(it.hir_id(), |builder| { 1,476 ( 0.00%) intravisit::walk_item(builder, it); . }); . } . . fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>) { . self.with_lint_attrs(it.hir_id(), |builder| { . intravisit::walk_foreign_item(builder, it); . }) . } . . fn visit_stmt(&mut self, e: &'tcx hir::Stmt<'tcx>) { . // We will call `with_lint_attrs` when we walk . // the `StmtKind`. The outer statement itself doesn't . // define the lint levels. 1,314 ( 0.00%) intravisit::walk_stmt(self, e); . } . 756 ( 0.00%) fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) { 286,966 ( 0.00%) self.with_lint_attrs(e.hir_id, |builder| { 570,516 ( 0.01%) intravisit::walk_expr(builder, e); . }) 672 ( 0.00%) } . . fn visit_field_def(&mut self, s: &'tcx hir::FieldDef<'tcx>) { 186 ( 0.00%) self.with_lint_attrs(s.hir_id, |builder| { . intravisit::walk_field_def(builder, s); . }) . } . . fn visit_variant( . &mut self, . v: &'tcx hir::Variant<'tcx>, . g: &'tcx hir::Generics<'tcx>, . item_id: hir::HirId, . ) { 44 ( 0.00%) self.with_lint_attrs(v.id, |builder| { . intravisit::walk_variant(builder, v, g, item_id); . }) . } . . fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) { 444 ( 0.00%) self.with_lint_attrs(l.hir_id, |builder| { 888 ( 0.00%) intravisit::walk_local(builder, l); . }) . } . . fn visit_arm(&mut self, a: &'tcx hir::Arm<'tcx>) { 414 ( 0.00%) self.with_lint_attrs(a.hir_id, |builder| { 828 ( 0.00%) intravisit::walk_arm(builder, a); . }) . } . . fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) { 1 ( 0.00%) self.with_lint_attrs(trait_item.hir_id(), |builder| { 3 ( 0.00%) intravisit::walk_trait_item(builder, trait_item); . }); . } . . fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) { 197 ( 0.00%) self.with_lint_attrs(impl_item.hir_id(), |builder| { 591 ( 0.00%) intravisit::walk_impl_item(builder, impl_item); . }); . } . } . . pub fn provide(providers: &mut Providers) { 2 ( 0.00%) providers.lint_levels = lint_levels; . } 444,931 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_trait_selection/src/traits/query/type_op/mod.rs -------------------------------------------------------------------------------- Ir -- line 72 ---------------------------------------- . /// it might do things like invoke `sub_regions`, which would be . /// bad, because it would create subregion relationships that are . /// not captured in the return value. . fn perform_query( . tcx: TyCtxt<'tcx>, . canonicalized: Canonicalized<'tcx, ParamEnvAnd<'tcx, Self>>, . ) -> Fallible>; . 1,601,871 ( 0.02%) fn fully_perform_into( . query_key: ParamEnvAnd<'tcx, Self>, . infcx: &InferCtxt<'_, 'tcx>, . output_query_region_constraints: &mut QueryRegionConstraints<'tcx>, . ) -> Fallible<( . Self::QueryResponse, . Option>>, . PredicateObligations<'tcx>, . Certainty, . )> { 232,917 ( 0.00%) if let Some(result) = QueryTypeOp::try_fast_path(infcx.tcx, &query_key) { 839,421 ( 0.01%) return Ok((result, None, vec![], Certainty::Proven)); . } . . // FIXME(#33684) -- We need to use . // `canonicalize_query_keep_static` here because of things . // like the subtype query, which go awry around . // `'static` otherwise. 12,666 ( 0.00%) let mut canonical_var_values = OriginalQueryValues::default(); 654 ( 0.00%) let old_param_env = query_key.param_env; . let canonical_self = 9,433 ( 0.00%) infcx.canonicalize_query_keep_static(query_key, &mut canonical_var_values); 64,574 ( 0.00%) let canonical_result = Self::perform_query(infcx.tcx, canonical_self)?; . 82,051 ( 0.00%) let InferOk { value, obligations } = infcx . .instantiate_nll_query_response_and_region_obligations( . &ObligationCause::dummy(), . old_param_env, . &canonical_var_values, . canonical_result, . output_query_region_constraints, . )?; . 105,537 ( 0.00%) Ok((value, Some(canonical_self), obligations, canonical_result.value.certainty)) 1,556,508 ( 0.02%) } . } . . impl<'tcx, Q> TypeOp<'tcx> for ParamEnvAnd<'tcx, Q> . where . Q: QueryTypeOp<'tcx>, . { . type Output = Q::QueryResponse; . 1,395,016 ( 0.02%) fn fully_perform(self, infcx: &InferCtxt<'_, 'tcx>) -> Fallible> { . let mut region_constraints = QueryRegionConstraints::default(); 1,058,301 ( 0.02%) let (output, canonicalized_query, mut obligations, _) = 188,832 ( 0.00%) Q::fully_perform_into(self, infcx, &mut region_constraints)?; . . // Typically, instantiating NLL query results does not . // create obligations. However, in some cases there . // are unresolved type variables, and unify them *can* . // create obligations. In that case, we have to go . // fulfill them. We do this via a (recursive) query. 174,392 ( 0.00%) while !obligations.is_empty() { . trace!("{:#?}", obligations); . let mut progress = false; 555 ( 0.00%) for obligation in std::mem::take(&mut obligations) { 160 ( 0.00%) let obligation = infcx.resolve_vars_if_possible(obligation); 640 ( 0.00%) match ProvePredicate::fully_perform_into( 160 ( 0.00%) obligation.param_env.and(ProvePredicate::new(obligation.predicate)), . infcx, . &mut region_constraints, . ) { 160 ( 0.00%) Ok(((), _, new, certainty)) => { . obligations.extend(new); . progress = true; 80 ( 0.00%) if let Certainty::Ambiguous = certainty { . obligations.push(obligation); . } . } . Err(_) => obligations.push(obligation), . } . } 30 ( 0.00%) if !progress { . return Err(NoSolution); . } . } . . // Promote the final query-region-constraints into a . // (optional) ref-counted vector: . let region_constraints = 697,508 ( 0.01%) if region_constraints.is_empty() { None } else { Some(Rc::new(region_constraints)) }; . 2,249,401 ( 0.03%) Ok(TypeOpOutput { output, constraints: region_constraints, canonicalized_query }) 1,743,770 ( 0.02%) } . } 1,219,684 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/expr.rs -------------------------------------------------------------------------------- Ir -- line 56 ---------------------------------------- . } . . pub fn check_expr_has_type_or_error( . &self, . expr: &'tcx hir::Expr<'tcx>, . expected: Ty<'tcx>, . extend_err: impl Fn(&mut DiagnosticBuilder<'_>), . ) -> Ty<'tcx> { 177 ( 0.00%) self.check_expr_meets_expectation_or_error(expr, ExpectHasType(expected), extend_err) . } . . fn check_expr_meets_expectation_or_error( . &self, . expr: &'tcx hir::Expr<'tcx>, . expected: Expectation<'tcx>, . extend_err: impl Fn(&mut DiagnosticBuilder<'_>), . ) -> Ty<'tcx> { . let expected_ty = expected.to_option(&self).unwrap_or(self.tcx.types.bool); . let mut ty = self.check_expr_with_expectation(expr, expected); . . // While we don't allow *arbitrary* coercions here, we *do* allow . // coercions from ! to `expected`. 250 ( 0.00%) if ty.is_never() { 14 ( 0.00%) assert!( 42 ( 0.00%) !self.typeck_results.borrow().adjustments().contains_key(expr.hir_id), . "expression with never type wound up being adjusted" . ); 35 ( 0.00%) let adj_ty = self.next_ty_var(TypeVariableOrigin { . kind: TypeVariableOriginKind::AdjustmentType, 7 ( 0.00%) span: expr.span, . }); 21 ( 0.00%) self.apply_adjustments( . expr, 14 ( 0.00%) vec![Adjustment { kind: Adjust::NeverToAny, target: adj_ty }], . ); . ty = adj_ty; . } . 1,954 ( 0.00%) if let Some(mut err) = self.demand_suptype_diag(expr.span, expected_ty, ty) { . let expr = expr.peel_drop_temps(); . self.suggest_deref_ref_or_into(&mut err, expr, expected_ty, ty, None); . extend_err(&mut err); . err.emit(); . } . ty . } . 15,867 ( 0.00%) pub(super) fn check_expr_coercable_to_type( . &self, . expr: &'tcx hir::Expr<'tcx>, . expected: Ty<'tcx>, . expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>, . ) -> Ty<'tcx> { . let ty = self.check_expr_with_hint(expr, expected); . // checks don't need two phase . self.demand_coerce(expr, ty, expected, expected_ty_expr, AllowTwoPhase::No) 12,341 ( 0.00%) } . . pub(super) fn check_expr_with_hint( . &self, . expr: &'tcx hir::Expr<'tcx>, . expected: Ty<'tcx>, . ) -> Ty<'tcx> { 329 ( 0.00%) self.check_expr_with_expectation(expr, ExpectHasType(expected)) . } . . fn check_expr_with_expectation_and_needs( . &self, . expr: &'tcx hir::Expr<'tcx>, . expected: Expectation<'tcx>, . needs: Needs, . ) -> Ty<'tcx> { . let ty = self.check_expr_with_expectation(expr, expected); . . // If the expression is used in a place whether mutable place is required . // e.g. LHS of assignment, perform the conversion. 1,100 ( 0.00%) if let Needs::MutPlace = needs { 183 ( 0.00%) self.convert_place_derefs_to_mutable(expr); . } . . ty . } . . pub(super) fn check_expr(&self, expr: &'tcx hir::Expr<'tcx>) -> Ty<'tcx> { . self.check_expr_with_expectation(expr, NoExpectation) . } -- line 141 ---------------------------------------- -- line 159 ---------------------------------------- . /// that there are actually multiple representations for `Error`, so avoid . /// that when err needs to be handled differently. . #[instrument(skip(self, expr), level = "debug")] . pub(super) fn check_expr_with_expectation( . &self, . expr: &'tcx hir::Expr<'tcx>, . expected: Expectation<'tcx>, . ) -> Ty<'tcx> { 1,008,133 ( 0.01%) self.check_expr_with_expectation_and_args(expr, expected, &[]) . } . . /// Same as `check_expr_with_expectation`, but allows us to pass in the arguments of a . /// `ExprKind::Call` when evaluating its callee when it is an `ExprKind::Path`. 1,892,514 ( 0.03%) pub(super) fn check_expr_with_expectation_and_args( . &self, . expr: &'tcx hir::Expr<'tcx>, . expected: Expectation<'tcx>, . args: &'tcx [hir::Expr<'tcx>], . ) -> Ty<'tcx> { 582,312 ( 0.01%) if self.tcx().sess.verbose() { . // make this code only run with -Zverbose because it is probably slow . if let Ok(lint_str) = self.tcx.sess.source_map().span_to_snippet(expr.span) { . if !lint_str.contains('\n') { . debug!("expr text: {}", lint_str); . } else { . let mut lines = lint_str.lines(); . if let Some(line0) = lines.next() { . let remaining_lines = lines.count(); -- line 186 ---------------------------------------- -- line 189 ---------------------------------------- . } . } . } . } . . // True if `expr` is a `Try::from_ok(())` that is a result of desugaring a try block . // without the final expr (e.g. `try { return; }`). We don't want to generate an . // unreachable_code lint for it since warnings for autogenerated code are confusing. 291,156 ( 0.00%) let is_try_block_generated_unit_expr = match expr.kind { 2,360 ( 0.00%) ExprKind::Call(_, args) if expr.span.is_desugaring(DesugaringKind::TryBlock) => { . args.len() == 1 && args[0].span.is_desugaring(DesugaringKind::TryBlock) . } . . _ => false, . }; . . // Warn for expressions after diverging siblings. . if !is_try_block_generated_unit_expr { 1,019,046 ( 0.01%) self.warn_if_unreachable(expr.hir_id, expr.span, "expression"); . } . . // Hide the outer diverging and has_errors flags. . let old_diverges = self.diverges.replace(Diverges::Maybe); . let old_has_errors = self.has_errors.replace(false); . 295,772 ( 0.00%) let ty = ensure_sufficient_stack(|| match &expr.kind { . hir::ExprKind::Path( . qpath @ hir::QPath::Resolved(..) | qpath @ hir::QPath::TypeRelative(..), 13,668 ( 0.00%) ) => self.check_expr_path(qpath, expr, args), 716,500 ( 0.01%) _ => self.check_expr_kind(expr, expected), . }); . . // Warn for non-block expressions with diverging children. 582,312 ( 0.01%) match expr.kind { . ExprKind::Block(..) . | ExprKind::If(..) . | ExprKind::Let(..) . | ExprKind::Loop(..) . | ExprKind::Match(..) => {} . // If `expr` is a result of desugaring the try block and is an ok-wrapped . // diverging expression (e.g. it arose from desugaring of `try { return }`), . // we skip issuing a warning because it is autogenerated code. 2,360 ( 0.00%) ExprKind::Call(..) if expr.span.is_desugaring(DesugaringKind::TryBlock) => {} 2,360 ( 0.00%) ExprKind::Call(callee, _) => self.warn_if_unreachable(expr.hir_id, callee.span, "call"), 442 ( 0.00%) ExprKind::MethodCall(segment, ..) => { 1,326 ( 0.00%) self.warn_if_unreachable(expr.hir_id, segment.ident.span, "call") . } 862,848 ( 0.01%) _ => self.warn_if_unreachable(expr.hir_id, expr.span, "expression"), . } . . // Any expression that produces a value of type `!` must have diverged 145,578 ( 0.00%) if ty.is_never() { 101 ( 0.00%) self.diverges.set(self.diverges.get() | Diverges::always(expr.span)); . } . . // Record the type, which applies it effects. . // We need to do this after the warning above, so that . // we don't warn for the diverging expression itself. 727,890 ( 0.01%) self.write_ty(expr.hir_id, ty); . . // Combine the diverging and has_error flags. . self.diverges.set(self.diverges.get() | old_diverges); 145,578 ( 0.00%) self.has_errors.set(self.has_errors.get() | old_has_errors); . . debug!("type of {} is...", self.tcx.hir().node_to_string(expr.hir_id)); . debug!("... {:?}, expected is {:?}", ty, expected); . . ty 1,310,202 ( 0.02%) } . 2,849,048 ( 0.04%) #[instrument(skip(self, expr), level = "debug")] . fn check_expr_kind( . &self, . expr: &'tcx hir::Expr<'tcx>, . expected: Expectation<'tcx>, . ) -> Ty<'tcx> { . trace!("expr={:#?}", expr); . 143,300 ( 0.00%) let tcx = self.tcx; 859,860 ( 0.01%) match expr.kind { . ExprKind::Box(subexpr) => self.check_expr_box(subexpr, expected), . ExprKind::Lit(ref lit) => self.check_lit(&lit, expected), 2,562 ( 0.00%) ExprKind::Binary(op, lhs, rhs) => self.check_binop(expr, op, lhs, rhs), 96 ( 0.00%) ExprKind::Assign(lhs, rhs, ref span) => { . self.check_expr_assign(expr, expected, lhs, rhs, span) . } 280 ( 0.00%) ExprKind::AssignOp(op, lhs, rhs) => self.check_binop_assign(expr, op, lhs, rhs), 786 ( 0.00%) ExprKind::Unary(unop, oprnd) => self.check_expr_unary(unop, oprnd, expected, expr), 9,117 ( 0.00%) ExprKind::AddrOf(kind, mutbl, oprnd) => { . self.check_expr_addr_of(kind, mutbl, oprnd, expected, expr) . } 60 ( 0.00%) ExprKind::Path(QPath::LangItem(lang_item, _, hir_id)) => { . self.check_lang_item_path(lang_item, expr, hir_id) . } . ExprKind::Path(ref qpath) => self.check_expr_path(qpath, expr, &[]), . ExprKind::InlineAsm(asm) => self.check_expr_asm(asm), . ExprKind::Break(destination, ref expr_opt) => { 92 ( 0.00%) self.check_expr_break(destination, expr_opt.as_deref(), expr) . } . ExprKind::Continue(destination) => { 1 ( 0.00%) if destination.target_id.is_ok() { 2 ( 0.00%) tcx.types.never . } else { . // There was an error; make type-check fail. . tcx.ty_error() . } . } . ExprKind::Ret(ref expr_opt) => self.check_expr_return(expr_opt.as_deref(), expr), 15 ( 0.00%) ExprKind::Let(let_expr) => self.check_expr_let(let_expr), 38 ( 0.00%) ExprKind::Loop(body, _, source, _) => { . self.check_expr_loop(body, source, expected, expr) . } 345 ( 0.00%) ExprKind::Match(discrim, arms, match_src) => { 805 ( 0.00%) self.check_match(expr, &discrim, arms, expected, match_src) . } 51 ( 0.00%) ExprKind::Closure(capture, decl, body_id, _, gen) => { 204 ( 0.00%) self.check_expr_closure(expr, capture, &decl, body_id, gen, expected) . } 6,655 ( 0.00%) ExprKind::Block(body, _) => self.check_block_with_expected(&body, expected), 3,776 ( 0.00%) ExprKind::Call(callee, args) => self.check_call(expr, &callee, args, expected), 442 ( 0.00%) ExprKind::MethodCall(segment, args, _) => { . self.check_method_call(expr, segment, args, expected) . } 30 ( 0.00%) ExprKind::Cast(e, t) => self.check_expr_cast(e, t, expr), . ExprKind::Type(e, t) => { . let ty = self.to_ty_saving_user_provided_ty(&t); . self.check_expr_eq_type(&e, ty); . ty . } 510 ( 0.00%) ExprKind::If(cond, then_expr, opt_else_expr) => { 102 ( 0.00%) self.check_then_else(cond, then_expr, opt_else_expr, expr.span, expected) . } 98 ( 0.00%) ExprKind::DropTemps(e) => self.check_expr_with_expectation(e, expected), 1,170 ( 0.00%) ExprKind::Array(args) => self.check_expr_array(args, expected, expr), . ExprKind::ConstBlock(ref anon_const) => { . self.check_expr_const_block(anon_const, expected, expr) . } . ExprKind::Repeat(element, ref count) => { . self.check_expr_repeat(element, count, expected, expr) . } 408 ( 0.00%) ExprKind::Tup(elts) => self.check_expr_tuple(elts, expected, expr), 1,165 ( 0.00%) ExprKind::Struct(qpath, fields, ref base_expr) => { . self.check_expr_struct(expr, expected, qpath, fields, base_expr) . } 4,862 ( 0.00%) ExprKind::Field(base, field) => self.check_field(expr, &base, field), 78 ( 0.00%) ExprKind::Index(base, idx) => self.check_expr_index(base, idx, expr), . ExprKind::Yield(value, ref src) => self.check_expr_yield(value, expr, src), . hir::ExprKind::Err => tcx.ty_error(), . } . } . . fn check_expr_box(&self, expr: &'tcx hir::Expr<'tcx>, expected: Expectation<'tcx>) -> Ty<'tcx> { . let expected_inner = expected.to_option(self).map_or(NoExpectation, |ty| match ty.kind() { . ty::Adt(def, _) if def.is_box() => Expectation::rvalue_hint(self, ty.boxed_ty()), -- line 342 ---------------------------------------- -- line 350 ---------------------------------------- . fn check_expr_unary( . &self, . unop: hir::UnOp, . oprnd: &'tcx hir::Expr<'tcx>, . expected: Expectation<'tcx>, . expr: &'tcx hir::Expr<'tcx>, . ) -> Ty<'tcx> { . let tcx = self.tcx; 262 ( 0.00%) let expected_inner = match unop { . hir::UnOp::Not | hir::UnOp::Neg => expected, . hir::UnOp::Deref => NoExpectation, . }; 524 ( 0.00%) let mut oprnd_t = self.check_expr_with_expectation(&oprnd, expected_inner); . 262 ( 0.00%) if !oprnd_t.references_error() { 1,834 ( 0.00%) oprnd_t = self.structurally_resolved_type(expr.span, oprnd_t); 536 ( 0.00%) match unop { . hir::UnOp::Deref => { . if let Some(ty) = self.lookup_derefing(expr, oprnd, oprnd_t) { . oprnd_t = ty; . } else { . let mut err = type_error_struct!( . tcx.sess, . expr.span, . oprnd_t, -- line 374 ---------------------------------------- -- line 382 ---------------------------------------- . { . tcx.sess.parse_sess.expr_parentheses_needed(&mut err, *sp); . } . err.emit(); . oprnd_t = tcx.ty_error(); . } . } . hir::UnOp::Not => { 24 ( 0.00%) let result = self.check_user_unop(expr, oprnd_t, unop); . // If it's builtin, we can reuse the type, this helps inference. 36 ( 0.00%) if !(oprnd_t.is_integral() || *oprnd_t.kind() == ty::Bool) { . oprnd_t = result; . } . } . hir::UnOp::Neg => { . let result = self.check_user_unop(expr, oprnd_t, unop); . // If it's builtin, we can reuse the type, this helps inference. . if !oprnd_t.is_numeric() { . oprnd_t = result; -- line 400 ---------------------------------------- -- line 409 ---------------------------------------- . &self, . kind: hir::BorrowKind, . mutbl: hir::Mutability, . oprnd: &'tcx hir::Expr<'tcx>, . expected: Expectation<'tcx>, . expr: &'tcx hir::Expr<'tcx>, . ) -> Ty<'tcx> { . let hint = expected.only_has_type(self).map_or(NoExpectation, |ty| { 4,510 ( 0.00%) match ty.kind() { . ty::Ref(_, ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) => { 3,528 ( 0.00%) if oprnd.is_syntactic_place_expr() { . // Places may legitimately have unsized types. . // For example, dereferences of a fat pointer and . // the last field of a struct can be unsized. . ExpectHasType(ty) . } else { 4,452 ( 0.00%) Expectation::rvalue_hint(self, ty) . } . } . _ => NoExpectation, . } 2,706 ( 0.00%) }); . let ty = . self.check_expr_with_expectation_and_needs(&oprnd, hint, Needs::maybe_mut_place(mutbl)); . . let tm = ty::TypeAndMut { ty, mutbl }; 1,013 ( 0.00%) match kind { 1,013 ( 0.00%) _ if tm.ty.references_error() => self.tcx.ty_error(), . hir::BorrowKind::Raw => { . self.check_named_place_expr(oprnd); . self.tcx.mk_ptr(tm) . } . hir::BorrowKind::Ref => { . // Note: at this point, we cannot say what the best lifetime . // is to use for resulting pointer. We want to use the . // shortest lifetime possible so as to avoid spurious borrowck -- line 444 ---------------------------------------- -- line 448 ---------------------------------------- . // type inference is complete. . // . // Therefore, here we simply generate a region variable. The . // region inferencer will then select a suitable value. . // Finally, borrowck will infer the value of the region again, . // this time with enough precision to check that the value . // whose address was taken can actually be made to live as long . // as it needs to live. 5,065 ( 0.00%) let region = self.next_region_var(infer::AddrOfRegion(expr.span)); 1,013 ( 0.00%) self.tcx.mk_ref(region, tm) . } . } . } . . /// Does this expression refer to a place that either: . /// * Is based on a local or static. . /// * Contains a dereference . /// Note that the adjustments for the children of `expr` should already -- line 465 ---------------------------------------- -- line 489 ---------------------------------------- . } . . fn check_lang_item_path( . &self, . lang_item: hir::LangItem, . expr: &'tcx hir::Expr<'tcx>, . hir_id: Option, . ) -> Ty<'tcx> { 360 ( 0.00%) self.resolve_lang_item_path(lang_item, expr.span, expr.hir_id, hir_id).1 . } . 25,058 ( 0.00%) pub(crate) fn check_expr_path( . &self, . qpath: &'tcx hir::QPath<'tcx>, . expr: &'tcx hir::Expr<'tcx>, . args: &'tcx [hir::Expr<'tcx>], . ) -> Ty<'tcx> { 2,278 ( 0.00%) let tcx = self.tcx; 25,058 ( 0.00%) let (res, opt_ty, segs) = 22,780 ( 0.00%) self.resolve_ty_and_res_fully_qualified_call(qpath, expr.hir_id, expr.span); 10,732 ( 0.00%) let ty = match res { . Res::Err => { . self.set_tainted_by_errors(); . tcx.ty_error() . } . Res::Def(DefKind::Ctor(_, CtorKind::Fictive), _) => { . report_unexpected_variant_res(tcx, res, expr.span); . tcx.ty_error() . } 41,004 ( 0.00%) _ => self.instantiate_value_path(segs, opt_ty, res, expr.span, expr.hir_id).0, . }; . 6,834 ( 0.00%) if let ty::FnDef(..) = ty.kind() { 1,413 ( 0.00%) let fn_sig = ty.fn_sig(tcx); 1,884 ( 0.00%) if !tcx.features().unsized_fn_params { . // We want to remove some Sized bounds from std functions, . // but don't want to expose the removal to stable Rust. . // i.e., we don't want to allow . // . // ```rust . // drop as fn(str); . // ``` . // . // to work in stable even if the Sized bound on `drop` is relaxed. . for i in 0..fn_sig.inputs().skip_binder().len() { . // We just want to check sizedness, so instead of introducing . // placeholder lifetimes with probing, we just replace higher lifetimes . // with fresh vars. 665 ( 0.00%) let span = args.get(i).map(|a| a.span).unwrap_or(expr.span); . let input = self . .replace_bound_vars_with_fresh_vars( . span, . infer::LateBoundRegionConversionTime::FnCall, . fn_sig.input(i), . ) . .0; 3,040 ( 0.00%) self.require_type_is_sized_deferred( . input, . span, 2,280 ( 0.00%) traits::SizedArgumentType(None), . ); . } . } . // Here we want to prevent struct constructors from returning unsized types. . // There were two cases this happened: fn pointer coercion in stable . // and usual function call in presence of unsized_locals. . // Also, as we just want to check sizedness, instead of introducing . // placeholder lifetimes with probing, we just replace higher lifetimes -- line 556 ---------------------------------------- -- line 557 ---------------------------------------- . // with fresh vars. . let output = self . .replace_bound_vars_with_fresh_vars( . expr.span, . infer::LateBoundRegionConversionTime::FnCall, . fn_sig.output(), . ) . .0; 2,826 ( 0.00%) self.require_type_is_sized_deferred(output, expr.span, traits::SizedReturnType); . } . . // We always require that the type provided as the value for . // a type parameter outlives the moment of instantiation. 9,112 ( 0.00%) let substs = self.typeck_results.borrow().node_substs(expr.hir_id); . self.add_wf_bounds(substs, expr); . . ty 18,224 ( 0.00%) } . . fn check_expr_break( . &self, . destination: hir::Destination, . expr_opt: Option<&'tcx hir::Expr<'tcx>>, . expr: &'tcx hir::Expr<'tcx>, . ) -> Ty<'tcx> { 23 ( 0.00%) let tcx = self.tcx; 138 ( 0.00%) if let Ok(target_id) = destination.target_id { . let (e_ty, cause); 69 ( 0.00%) if let Some(e) = expr_opt { . // If this is a break with a value, we need to type-check . // the expression. Get an expected type from the loop context. . let opt_coerce_to = { . // We should release `enclosing_breakables` before the `check_expr_with_hint` . // below, so can't move this block of code to the enclosing scope and share . // `ctxt` with the second `encloding_breakables` borrow below. . let mut enclosing_breakables = self.enclosing_breakables.borrow_mut(); . match enclosing_breakables.opt_find_breakable(target_id) { -- line 593 ---------------------------------------- -- line 609 ---------------------------------------- . . // Recurse without `enclosing_breakables` borrowed. . e_ty = self.check_expr_with_hint(e, coerce_to); . cause = self.misc(e.span); . } else { . // Otherwise, this is a break *without* a value. That's . // always legal, and is equivalent to `break ()`. . e_ty = tcx.mk_unit(); 69 ( 0.00%) cause = self.misc(expr.span); . } . . // Now that we have type-checked `expr_opt`, borrow . // the `enclosing_loops` field and let's coerce the . // type of `expr_opt` into what is expected. . let mut enclosing_breakables = self.enclosing_breakables.borrow_mut(); 115 ( 0.00%) let ctxt = match enclosing_breakables.opt_find_breakable(target_id) { . Some(ctxt) => ctxt, . None => { . // Avoid ICE when `break` is inside a closure (#65383). . return tcx.ty_error_with_message( . expr.span, . "break was outside loop, but no error was emitted", . ); . } . }; . 46 ( 0.00%) if let Some(ref mut coerce) = ctxt.coerce { . if let Some(ref e) = expr_opt { . coerce.coerce(self, &cause, e, e_ty); . } else { . assert!(e_ty.is_unit()); . let ty = coerce.expected_ty(); . coerce.coerce_forced_unit( . self, . &cause, -- line 643 ---------------------------------------- -- line 664 ---------------------------------------- . } else { . // If `ctxt.coerce` is `None`, we can just ignore . // the type of the expression. This is because . // either this was a break *without* a value, in . // which case it is always a legal type (`()`), or . // else an error would have been flagged by the . // `loops` pass for using break with an expression . // where you are not supposed to. 23 ( 0.00%) assert!(expr_opt.is_none() || self.tcx.sess.has_errors()); . } . . // If we encountered a `break`, then (no surprise) it may be possible to break from the . // loop... unless the value being returned from the loop diverges itself, e.g. . // `break return 5` or `break loop {}`. 138 ( 0.00%) ctxt.may_break |= !self.diverges.get().is_always(); . . // the type of a `break` is always `!`, since it diverges . tcx.types.never . } else { . // Otherwise, we failed to find the enclosing loop; . // this can only happen if the `break` was not . // inside a loop at all, which is caught by the . // loop-checking pass. -- line 686 ---------------------------------------- -- line 708 ---------------------------------------- . } . } . . fn check_expr_return( . &self, . expr_opt: Option<&'tcx hir::Expr<'tcx>>, . expr: &'tcx hir::Expr<'tcx>, . ) -> Ty<'tcx> { 23 ( 0.00%) if self.ret_coercion.is_none() { . let mut err = ReturnStmtOutsideOfFnBody { . span: expr.span, . encl_body_span: None, . encl_fn_span: None, . }; . . let encl_item_id = self.tcx.hir().get_parent_item(expr.hir_id); . -- line 724 ---------------------------------------- -- line 756 ---------------------------------------- . . self.tcx.sess.emit_err(err); . . if let Some(e) = expr_opt { . // We still have to type-check `e` (issue #86188), but calling . // `check_return_expr` only works inside fn bodies. . self.check_expr(e); . } 46 ( 0.00%) } else if let Some(e) = expr_opt { 21 ( 0.00%) if self.ret_coercion_span.get().is_none() { 80 ( 0.00%) self.ret_coercion_span.set(Some(e.span)); . } 84 ( 0.00%) self.check_return_expr(e, true); . } else { . let mut coercion = self.ret_coercion.as_ref().unwrap().borrow_mut(); 2 ( 0.00%) if self.ret_coercion_span.get().is_none() { 5 ( 0.00%) self.ret_coercion_span.set(Some(expr.span)); . } . let cause = self.cause(expr.span, ObligationCauseCode::ReturnNoExpression); 12 ( 0.00%) if let Some((fn_decl, _)) = self.get_fn_decl(expr.hir_id) { . coercion.coerce_forced_unit( . self, . &cause, 4 ( 0.00%) &mut |db| { . let span = fn_decl.output.span(); . if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) { . db.span_label( . span, . format!("expected `{}` because of this return type", snippet), . ); . } . }, . true, . ); . } else { . coercion.coerce_forced_unit(self, &cause, &mut |_| (), true); . } . } 69 ( 0.00%) self.tcx.types.never . } . . /// `explicit_return` is `true` if we're checkng an explicit `return expr`, . /// and `false` if we're checking a trailing expression. 2,632 ( 0.00%) pub(super) fn check_return_expr( . &self, . return_expr: &'tcx hir::Expr<'tcx>, . explicit_return: bool, . ) { . let ret_coercion = self.ret_coercion.as_ref().unwrap_or_else(|| { . span_bug!(return_expr.span, "check_return_expr called outside fn body") . }); . . let ret_ty = ret_coercion.borrow().expected_ty(); . let return_expr_ty = self.check_expr_with_hint(return_expr, ret_ty); 329 ( 0.00%) let mut span = return_expr.span; . // Use the span of the trailing expression for our cause, . // not the span of the entire function 658 ( 0.00%) if !explicit_return { 912 ( 0.00%) if let ExprKind::Block(body, _) = return_expr.kind { 888 ( 0.00%) if let Some(last_expr) = body.expr { 289 ( 0.00%) span = last_expr.span; . } . } . } . ret_coercion.borrow_mut().coerce( . self, 658 ( 0.00%) &self.cause(span, ObligationCauseCode::ReturnValue(return_expr.hir_id)), . return_expr, . return_expr_ty, . ); 2,632 ( 0.00%) } . 572 ( 0.00%) pub(crate) fn check_lhs_assignable( . &self, . lhs: &'tcx hir::Expr<'tcx>, . err_code: &'static str, . op_span: Span, . ) { 208 ( 0.00%) if lhs.is_syntactic_place_expr() { . return; . } . . // FIXME: Make this use SessionDiagnostic once error codes can be dynamically set. . let mut err = self.tcx.sess.struct_span_err_with_code( . op_span, . "invalid left-hand side of assignment", . DiagnosticId::Error(err_code.into()), -- line 842 ---------------------------------------- -- line 880 ---------------------------------------- . | hir::Node::Crate(_) => break, . _ => { . parent = self.tcx.hir().get_parent_node(parent); . } . } . } . . err.emit(); 416 ( 0.00%) } . . // A generic function for checking the 'then' and 'else' clauses in an 'if' . // or 'if-else' expression. . fn check_then_else( . &self, . cond_expr: &'tcx hir::Expr<'tcx>, . then_expr: &'tcx hir::Expr<'tcx>, . opt_else_expr: Option<&'tcx hir::Expr<'tcx>>, . sp: Span, . orig_expected: Expectation<'tcx>, . ) -> Ty<'tcx> { . let cond_ty = self.check_expr_has_type_or_error(cond_expr, self.tcx.types.bool, |_| {}); . 510 ( 0.00%) self.warn_if_unreachable( 204 ( 0.00%) cond_expr.hir_id, 102 ( 0.00%) then_expr.span, . "block in `if` or `while` expression", . ); . 204 ( 0.00%) let cond_diverges = self.diverges.get(); . self.diverges.set(Diverges::Maybe); . . let expected = orig_expected.adjust_for_branches(self); . let then_ty = self.check_expr_with_expectation(then_expr, expected); . let then_diverges = self.diverges.get(); . self.diverges.set(Diverges::Maybe); . . // We've already taken the expected type's preferences -- line 916 ---------------------------------------- -- line 919 ---------------------------------------- . // `expected` if it represents a *hard* constraint . // (`only_has_type`); otherwise, we just go with a . // fresh type variable. . let coerce_to_ty = expected.coercion_target_type(self, sp); . let mut coerce: DynamicCoerceMany<'_> = CoerceMany::new(coerce_to_ty); . . coerce.coerce(self, &self.misc(sp), then_expr, then_ty); . 204 ( 0.00%) if let Some(else_expr) = opt_else_expr { 126 ( 0.00%) let else_ty = if sp.desugaring_kind() == Some(DesugaringKind::LetElse) { . // todo introduce `check_expr_with_expectation(.., Expectation::LetElse)` . // for errors that point to the offending expression rather than the entire block. . // We could use `check_expr_eq_type(.., tcx.types.never)`, but then there is no . // way to detect that the expected type originated from let-else and provide . // a customized error. . let else_ty = self.check_expr(else_expr); . let cause = self.cause(else_expr.span, ObligationCauseCode::LetElse); . -- line 936 ---------------------------------------- -- line 943 ---------------------------------------- . else_ty . } . } else { . self.check_expr_with_expectation(else_expr, expected) . }; . let else_diverges = self.diverges.get(); . . let opt_suggest_box_span = 504 ( 0.00%) self.opt_suggest_box_span(else_expr.span, else_ty, orig_expected); . let if_cause = . self.if_cause(sp, then_expr, else_expr, then_ty, else_ty, opt_suggest_box_span); . . coerce.coerce(self, &if_cause, else_expr, else_ty); . . // We won't diverge unless both branches do (or the condition does). 1,071 ( 0.00%) self.diverges.set(cond_diverges | then_diverges & else_diverges); . } else { . self.if_fallback_coercion(sp, then_expr, &mut coerce); . . // If the condition is false we can't diverge. . self.diverges.set(cond_diverges); . } . 1,326 ( 0.00%) let result_ty = coerce.complete(self); 102 ( 0.00%) if cond_ty.references_error() { self.tcx.ty_error() } else { result_ty } . } . . /// Type check assignment expression `expr` of form `lhs = rhs`. . /// The expected type is `()` and is passed to the function for the purposes of diagnostics. . fn check_expr_assign( . &self, . expr: &'tcx hir::Expr<'tcx>, . expected: Expectation<'tcx>, . lhs: &'tcx hir::Expr<'tcx>, . rhs: &'tcx hir::Expr<'tcx>, . span: &Span, . ) -> Ty<'tcx> { 32 ( 0.00%) let expected_ty = expected.coercion_target_type(self, expr.span); 64 ( 0.00%) if expected_ty == self.tcx.types.bool { . // The expected type is `bool` but this will result in `()` so we can reasonably . // say that the user intended to write `lhs == rhs` instead of `lhs = rhs`. . // The likely cause of this is `if foo = bar { .. }`. . let actual_ty = self.tcx.mk_unit(); . let mut err = self.demand_suptype_diag(expr.span, expected_ty, actual_ty).unwrap(); . let lhs_ty = self.check_expr(&lhs); . let rhs_ty = self.check_expr(&rhs); . let (applicability, eq) = if self.can_coerce(rhs_ty, lhs_ty) { -- line 989 ---------------------------------------- -- line 1019 ---------------------------------------- . if lhs_ty.references_error() || rhs_ty.references_error() { . err.delay_as_bug() . } else { . err.emit(); . } . return self.tcx.ty_error(); . } . 192 ( 0.00%) self.check_lhs_assignable(lhs, "E0070", *span); . . let lhs_ty = self.check_expr_with_needs(&lhs, Needs::MutPlace); 192 ( 0.00%) let rhs_ty = self.check_expr_coercable_to_type(&rhs, lhs_ty, Some(lhs)); . 192 ( 0.00%) self.require_type_is_sized(lhs_ty, lhs.span, traits::AssignmentLhsSized); . 64 ( 0.00%) if lhs_ty.references_error() || rhs_ty.references_error() { . self.tcx.ty_error() . } else { . self.tcx.mk_unit() . } . } . . fn check_expr_let(&self, let_expr: &'tcx hir::Let<'tcx>) -> Ty<'tcx> { . // for let statements, this is done in check_stmt 15 ( 0.00%) let init = let_expr.init; 105 ( 0.00%) self.warn_if_unreachable(init.hir_id, init.span, "block in `let` expression"); . // otherwise check exactly as a let statement 30 ( 0.00%) self.check_decl(let_expr.into()); . // but return a bool, for this is a boolean expression 45 ( 0.00%) self.tcx.types.bool . } . . fn check_expr_loop( . &self, . body: &'tcx hir::Block<'tcx>, . source: hir::LoopSource, . expected: Expectation<'tcx>, . expr: &'tcx hir::Expr<'tcx>, . ) -> Ty<'tcx> { 38 ( 0.00%) let coerce = match source { . // you can only use break with a value from a normal `loop { }` . hir::LoopSource::Loop => { 5 ( 0.00%) let coerce_to = expected.coercion_target_type(self, body.span); . Some(CoerceMany::new(coerce_to)) . } . . hir::LoopSource::While | hir::LoopSource::ForLoop => None, . }; . . let ctxt = BreakableCtxt { . coerce, . may_break: false, // Will get updated if/when we find a `break`. . }; . 323 ( 0.00%) let (ctxt, ()) = self.with_breakable_ctxt(expr.hir_id, ctxt, || { 57 ( 0.00%) self.check_block_no_value(&body); . }); . 38 ( 0.00%) if ctxt.may_break { . // No way to know whether it's diverging because . // of a `break` or an outer `break` or `return`. . self.diverges.set(Diverges::Maybe); . } . . // If we permit break with a value, then result type is . // the LUB of the breaks (possibly ! if none); else, it . // is nil. This makes sense because infinite loops . // (which would have type !) are only possible iff we . // permit break with a value [1]. 1 ( 0.00%) if ctxt.coerce.is_none() && !ctxt.may_break { . // [1] . self.tcx.sess.delay_span_bug(body.span, "no coercion, but loop may not break"); . } 12 ( 0.00%) ctxt.coerce.map(|c| c.complete(self)).unwrap_or_else(|| self.tcx.mk_unit()) . } . . /// Checks a method call. . fn check_method_call( . &self, . expr: &'tcx hir::Expr<'tcx>, . segment: &hir::PathSegment<'_>, . args: &'tcx [hir::Expr<'tcx>], . expected: Expectation<'tcx>, . ) -> Ty<'tcx> { 884 ( 0.00%) let rcvr = &args[0]; . let rcvr_t = self.check_expr(&rcvr); . // no need to check for bot/err -- callee does that 1,768 ( 0.00%) let rcvr_t = self.structurally_resolved_type(args[0].span, rcvr_t); 442 ( 0.00%) let span = segment.ident.span; . 7,072 ( 0.00%) let method = match self.lookup_method(rcvr_t, segment, span, expr, rcvr, args) { 884 ( 0.00%) Ok(method) => { . // We could add a "consider `foo::`" suggestion here, but I wasn't able to . // trigger this codepath causing `structuraly_resolved_type` to emit an error. . 4,862 ( 0.00%) self.write_method_call(expr.hir_id, method); 2,210 ( 0.00%) Ok(method) . } . Err(error) => { . if segment.ident.name != kw::Empty { . if let Some(mut err) = self.report_method_error( . span, . rcvr_t, . segment.ident, . SelfSource::MethodCall(&args[0]), -- line 1123 ---------------------------------------- -- line 1127 ---------------------------------------- . err.emit(); . } . } . Err(()) . } . }; . . // Call the generic checker. 6,188 ( 0.00%) self.check_method_argument_types( . span, . expr, 2,652 ( 0.00%) method, . &args[1..], . DontTupleArguments, . expected, . ) . } . . fn check_expr_cast( . &self, . e: &'tcx hir::Expr<'tcx>, . t: &'tcx hir::Ty<'tcx>, . expr: &'tcx hir::Expr<'tcx>, . ) -> Ty<'tcx> { . // Find the type of `e`. Supply hints based on the type we are casting to, . // if appropriate. 40 ( 0.00%) let t_cast = self.to_ty_saving_user_provided_ty(t); . let t_cast = self.resolve_vars_if_possible(t_cast); . let t_expr = self.check_expr_with_expectation(e, ExpectCastableToType(t_cast)); . let t_expr = self.resolve_vars_if_possible(t_expr); . . // Eagerly check for some obvious errors. 20 ( 0.00%) if t_expr.references_error() || t_cast.references_error() { . self.tcx.ty_error() . } else { . // Defer other checks until we're done type checking. . let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut(); 30 ( 0.00%) match cast::CastCheck::new(self, e, t_expr, t_cast, t.span, expr.span) { . Ok(cast_check) => { . debug!( . "check_expr_cast: deferring cast from {:?} to {:?}: {:?}", . t_cast, t_expr, cast_check, . ); . deferred_cast_checks.push(cast_check); . t_cast . } -- line 1172 ---------------------------------------- -- line 1176 ---------------------------------------- . } . . fn check_expr_array( . &self, . args: &'tcx [hir::Expr<'tcx>], . expected: Expectation<'tcx>, . expr: &'tcx hir::Expr<'tcx>, . ) -> Ty<'tcx> { 585 ( 0.00%) let element_ty = if !args.is_empty() { 1,458 ( 0.00%) let coerce_to = expected . .to_option(self) 1,458 ( 0.00%) .and_then(|uty| match *uty.kind() { . ty::Array(ty, _) | ty::Slice(ty) => Some(ty), . _ => None, . }) . .unwrap_or_else(|| { . self.next_ty_var(TypeVariableOrigin { . kind: TypeVariableOriginKind::TypeInference, . span: expr.span, . }) . }); . let mut coerce = CoerceMany::with_coercion_sites(coerce_to, args); 486 ( 0.00%) assert_eq!(self.diverges.get(), Diverges::Maybe); . for e in args { . let e_ty = self.check_expr_with_hint(e, coerce_to); 138,185 ( 0.00%) let cause = self.misc(e.span); 829,110 ( 0.01%) coerce.coerce(self, &cause, e, e_ty); . } 5,832 ( 0.00%) coerce.complete(self) . } else { 396 ( 0.00%) self.next_ty_var(TypeVariableOrigin { . kind: TypeVariableOriginKind::TypeInference, 99 ( 0.00%) span: expr.span, . }) . }; 4,005 ( 0.00%) self.tcx.mk_array(element_ty, args.len() as u64) . } . . fn check_expr_const_block( . &self, . anon_const: &'tcx hir::AnonConst, . expected: Expectation<'tcx>, . _expr: &'tcx hir::Expr<'tcx>, . ) -> Ty<'tcx> { -- line 1219 ---------------------------------------- -- line 1270 ---------------------------------------- . } . . fn check_expr_tuple( . &self, . elts: &'tcx [hir::Expr<'tcx>], . expected: Expectation<'tcx>, . expr: &'tcx hir::Expr<'tcx>, . ) -> Ty<'tcx> { 272 ( 0.00%) let flds = expected.only_has_type(self).and_then(|ty| { 112 ( 0.00%) let ty = self.resolve_vars_with_obligations(ty); 224 ( 0.00%) match ty.kind() { 98 ( 0.00%) ty::Tuple(flds) => Some(&flds[..]), . _ => None, . } . }); . 944 ( 0.00%) let elt_ts_iter = elts.iter().enumerate().map(|(i, e)| match flds { 392 ( 0.00%) Some(fs) if i < fs.len() => { 686 ( 0.00%) let ety = fs[i].expect_ty(); 1,274 ( 0.00%) self.check_expr_coercable_to_type(&e, ety, None); . ety . } 36 ( 0.00%) _ => self.check_expr_with_expectation(&e, NoExpectation), . }); 272 ( 0.00%) let tuple = self.tcx.mk_tup(elt_ts_iter); 136 ( 0.00%) if tuple.references_error() { . self.tcx.ty_error() . } else { 952 ( 0.00%) self.require_type_is_sized(tuple, expr.span, traits::TupleInitializerSized); . tuple . } . } . . fn check_expr_struct( . &self, . expr: &hir::Expr<'_>, . expected: Expectation<'tcx>, . qpath: &QPath<'_>, . fields: &'tcx [hir::ExprField<'tcx>], . base_expr: &'tcx Option<&'tcx hir::Expr<'tcx>>, . ) -> Ty<'tcx> { . // Find the relevant variant 2,330 ( 0.00%) let (variant, adt_ty) = if let Some(variant_ty) = self.check_struct_path(qpath, expr.hir_id) . { . variant_ty . } else { . self.check_struct_fields_on_error(fields, base_expr); . return self.tcx.ty_error(); . }; . . // Prohibit struct expressions when non-exhaustive flag is set. . let adt = adt_ty.ty_adt_def().expect("`check_struct_path` returned non-ADT type"); 633 ( 0.00%) if !adt.did.is_local() && variant.is_field_list_non_exhaustive() { . self.tcx . .sess . .emit_err(StructExprNonExhaustive { span: expr.span, what: adt.variant_descr() }); . } . 3,262 ( 0.00%) self.check_expr_struct_fields( . adt_ty, . expected, . expr.hir_id, 699 ( 0.00%) qpath.span(), . variant, . fields, . base_expr, 466 ( 0.00%) expr.span, . ); . 1,631 ( 0.00%) self.require_type_is_sized(adt_ty, expr.span, traits::StructInitializerSized); . adt_ty . } . 3,262 ( 0.00%) fn check_expr_struct_fields( . &self, . adt_ty: Ty<'tcx>, . expected: Expectation<'tcx>, . expr_id: hir::HirId, . span: Span, . variant: &'tcx ty::VariantDef, . ast_fields: &'tcx [hir::ExprField<'tcx>], . base_expr: &'tcx Option<&'tcx hir::Expr<'tcx>>, . expr_span: Span, . ) { 466 ( 0.00%) let tcx = self.tcx; . . let adt_ty_hint = self 466 ( 0.00%) .expected_inputs_for_expected_output(span, expected, adt_ty, &[adt_ty]) . .get(0) . .cloned() . .unwrap_or(adt_ty); . // re-link the regions that EIfEO can erase. . self.demand_eqtype(span, adt_ty_hint, adt_ty); . 466 ( 0.00%) let (substs, adt_kind, kind_name) = match adt_ty.kind() { 466 ( 0.00%) ty::Adt(adt, substs) => (substs, adt.adt_kind(), adt.variant_descr()), . _ => span_bug!(span, "non-ADT passed to check_expr_struct_fields"), . }; . . let mut remaining_fields = variant . .fields . .iter() . .enumerate() 5,856 ( 0.00%) .map(|(i, field)| (field.ident(tcx).normalize_to_macros_2_0(), (i, field))) . .collect::>(); . . let mut seen_fields = FxHashMap::default(); . . let mut error_happened = false; . . // Type-check each field. . for field in ast_fields { 11,536 ( 0.00%) let ident = tcx.adjust_ident(field.ident, variant.def_id); 2,928 ( 0.00%) let field_type = if let Some((i, v_field)) = remaining_fields.remove(&ident) { 2,928 ( 0.00%) seen_fields.insert(ident, field.span); . self.write_field_index(field.hir_id, i); . . // We don't look at stability attributes on . // struct-like enums (yet...), but it's definitely not . // a bug to have constructed one. 976 ( 0.00%) if adt_kind != AdtKind::Enum { 8,613 ( 0.00%) tcx.check_stability(v_field.did, Some(expr_id), field.span, None); . } . 2,928 ( 0.00%) self.field_ty(field.span, v_field, substs) . } else { . error_happened = true; . if let Some(prev_span) = seen_fields.get(&ident) { . tcx.sess.emit_err(FieldMultiplySpecifiedInInitializer { . span: field.ident.span, . prev_span: *prev_span, . ident, . }); -- line 1402 ---------------------------------------- -- line 1406 ---------------------------------------- . ); . } . . tcx.ty_error() . }; . . // Make sure to give a type to the field even if there's . // an error, so we can continue type-checking. 4,880 ( 0.00%) self.check_expr_coercable_to_type(&field.expr, field_type, None); . } . . // Make sure the programmer specified correct number of fields. . if kind_name == "union" { . if ast_fields.len() != 1 { . struct_span_err!( . tcx.sess, . span, -- line 1422 ---------------------------------------- -- line 1425 ---------------------------------------- . ) . .emit(); . } . } . . // If check_expr_struct_fields hit an error, do not attempt to populate . // the fields with the base_expr. This could cause us to hit errors later . // when certain fields are assumed to exist that in fact do not. 466 ( 0.00%) if error_happened { . return; . } . 699 ( 0.00%) if let Some(base_expr) = base_expr { . // FIXME: We are currently creating two branches here in order to maintain . // consistency. But they should be merged as much as possible. . let fru_tys = if self.tcx.features().type_changing_struct_update { . let base_ty = self.check_expr(base_expr); . match adt_ty.kind() { . ty::Adt(adt, substs) if adt.is_struct() => { . match base_ty.kind() { . ty::Adt(base_adt, base_subs) if adt == base_adt => { -- line 1445 ---------------------------------------- -- line 1528 ---------------------------------------- . return self . .tcx . .sess . .emit_err(FunctionalRecordUpdateOnNonStruct { span: base_expr.span }); . } . } . }; . self.typeck_results.borrow_mut().fru_field_types_mut().insert(expr_id, fru_tys); 233 ( 0.00%) } else if kind_name != "union" && !remaining_fields.is_empty() { . let inaccessible_remaining_fields = remaining_fields.iter().any(|(_, (_, field))| { . !field.vis.is_accessible_from(tcx.parent_module(expr_id).to_def_id(), tcx) . }); . . if inaccessible_remaining_fields { . self.report_inaccessible_fields(adt_ty, span); . } else { . self.report_missing_fields(adt_ty, span, remaining_fields); . } . } 2,330 ( 0.00%) } . . fn check_struct_fields_on_error( . &self, . fields: &'tcx [hir::ExprField<'tcx>], . base_expr: &'tcx Option<&'tcx hir::Expr<'tcx>>, . ) { . for field in fields { . self.check_expr(&field.expr); -- line 1555 ---------------------------------------- -- line 1805 ---------------------------------------- . names.iter().take(limit).map(|n| format!("`{}`", n)).collect::>().join(", "); . if names.len() > limit { . display = format!("{} ... and {} others", display, names.len() - limit); . } . display . } . . // Check field access expressions 4,488 ( 0.00%) fn check_field( . &self, . expr: &'tcx hir::Expr<'tcx>, . base: &'tcx hir::Expr<'tcx>, . field: Ident, . ) -> Ty<'tcx> { . debug!("check_field(expr: {:?}, base: {:?}, field: {:?})", expr, base, field); . let expr_t = self.check_expr(base); 1,870 ( 0.00%) let expr_t = self.structurally_resolved_type(base.span, expr_t); 748 ( 0.00%) let mut private_candidate = None; 374 ( 0.00%) let mut autoderef = self.autoderef(expr.span, expr_t); 2,704 ( 0.00%) while let Some((base_t, _)) = autoderef.next() { . debug!("base_t: {:?}", base_t); 2,584 ( 0.00%) match base_t.kind() { 1,194 ( 0.00%) ty::Adt(base_def, substs) if !base_def.is_enum() => { . debug!("struct named {:?}", base_t); 3,184 ( 0.00%) let (ident, def_scope) = 4,776 ( 0.00%) self.tcx.adjust_ident_and_get_scope(field, base_def.did, self.body_id); 796 ( 0.00%) let fields = &base_def.non_enum_variant().fields; . if let Some(index) = fields . .iter() 12,468 ( 0.00%) .position(|f| f.ident(self.tcx).normalize_to_macros_2_0() == ident) . { . let field = &fields[index]; 990 ( 0.00%) let field_ty = self.field_ty(expr.span, field, substs); . // Save the index of all fields regardless of their visibility in case . // of error recovery. . self.write_field_index(expr.hir_id, index); . let adjustments = self.adjust_steps(&autoderef); 330 ( 0.00%) if field.vis.is_accessible_from(def_scope, self.tcx) { 3,300 ( 0.00%) self.apply_adjustments(base, adjustments); 5,940 ( 0.00%) self.register_predicates(autoderef.into_obligations()); . 4,620 ( 0.00%) self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span, None); . return field_ty; . } . private_candidate = Some((adjustments, base_def.did, field_ty)); . } . } . ty::Tuple(tys) => { 88 ( 0.00%) let fstr = field.as_str(); 132 ( 0.00%) if let Ok(index) = fstr.parse::() { 88 ( 0.00%) if fstr == index.to_string() { 132 ( 0.00%) if let Some(field_ty) = tys.get(index) { . let adjustments = self.adjust_steps(&autoderef); 396 ( 0.00%) self.apply_adjustments(base, adjustments); 792 ( 0.00%) self.register_predicates(autoderef.into_obligations()); . . self.write_field_index(expr.hir_id, index); 176 ( 0.00%) return field_ty.expect_ty(); . } . } . } . } . _ => {} . } . } . self.structurally_resolved_type(autoderef.span(), autoderef.final_ty(false)); -- line 1870 ---------------------------------------- -- line 1890 ---------------------------------------- . E0610, . "`{}` is a primitive type and therefore doesn't have fields", . expr_t . ) . .emit(); . } . . self.tcx().ty_error() 4,114 ( 0.00%) } . . fn suggest_await_on_field_access( . &self, . err: &mut DiagnosticBuilder<'_>, . field_ident: Ident, . base: &'tcx hir::Expr<'tcx>, . ty: Ty<'tcx>, . ) { -- line 1906 ---------------------------------------- -- line 2301 ---------------------------------------- . &self, . base: &'tcx hir::Expr<'tcx>, . idx: &'tcx hir::Expr<'tcx>, . expr: &'tcx hir::Expr<'tcx>, . ) -> Ty<'tcx> { . let base_t = self.check_expr(&base); . let idx_t = self.check_expr(&idx); . 26 ( 0.00%) if base_t.references_error() { . base_t 26 ( 0.00%) } else if idx_t.references_error() { . idx_t . } else { 156 ( 0.00%) let base_t = self.structurally_resolved_type(base.span, base_t); 52 ( 0.00%) match self.lookup_indexing(expr, base, base_t, idx, idx_t) { . Some((index_ty, element_ty)) => { . // two-phase not needed because index_ty is never mutable . self.demand_coerce(idx, idx_t, index_ty, None, AllowTwoPhase::No); . element_ty . } . None => { . let mut err = type_error_struct!( . self.tcx.sess, -- line 2323 ---------------------------------------- 1,466,355 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/transform/check_consts/qualifs.rs -------------------------------------------------------------------------------- Ir -- line 82 ---------------------------------------- . /// promotion of temporaries must not change program behavior; if the promoted could be . /// written to, that would be a problem. . pub struct HasMutInterior; . . impl Qualif for HasMutInterior { . const ANALYSIS_NAME: &'static str = "flow_has_mut_interior"; . . fn in_qualifs(qualifs: &ConstQualifs) -> bool { 363 ( 0.00%) qualifs.has_mut_interior . } . . fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool { 8,286,264 ( 0.12%) !ty.is_freeze(cx.tcx.at(DUMMY_SP), cx.param_env) . } . . fn in_adt_inherently<'tcx>( . cx: &ConstCx<'_, 'tcx>, . adt: &'tcx AdtDef, . _: SubstsRef<'tcx>, . ) -> bool { . // Exactly one type, `UnsafeCell`, has the `HasMutInterior` qualif inherently. . // It arises structurally for all other types. 4,495 ( 0.00%) Some(adt.did) == cx.tcx.lang_items().unsafe_cell_type() . } . } . . /// Constant containing an ADT that implements `Drop`. . /// This must be ruled out because implicit promotion would remove side-effects . /// that occur as part of dropping that value. N.B., the implicit promotion has . /// to reject const Drop implementations because even if side-effects are ruled . /// out through other means, the execution of the drop could diverge. . pub struct NeedsDrop; . . impl Qualif for NeedsDrop { . const ANALYSIS_NAME: &'static str = "flow_needs_drop"; . const IS_CLEARED_ON_MOVE: bool = true; . . fn in_qualifs(qualifs: &ConstQualifs) -> bool { 91 ( 0.00%) qualifs.needs_drop . } . 2,210,016 ( 0.03%) fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool { 552,504 ( 0.01%) ty.needs_drop(cx.tcx, cx.param_env) 2,486,268 ( 0.04%) } . . fn in_adt_inherently<'tcx>( . cx: &ConstCx<'_, 'tcx>, . adt: &'tcx AdtDef, . _: SubstsRef<'tcx>, . ) -> bool { 921 ( 0.00%) adt.has_dtor(cx.tcx) . } . } . . /// Constant containing an ADT that implements non-const `Drop`. . /// This must be ruled out because we cannot run `Drop` during compile-time. . pub struct NeedsNonConstDrop; . . impl Qualif for NeedsNonConstDrop { -- line 140 ---------------------------------------- -- line 141 ---------------------------------------- . const ANALYSIS_NAME: &'static str = "flow_needs_nonconst_drop"; . const IS_CLEARED_ON_MOVE: bool = true; . const ALLOW_PROMOTED: bool = true; . . fn in_qualifs(qualifs: &ConstQualifs) -> bool { . qualifs.needs_non_const_drop . } . 837 ( 0.00%) fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool { . // Avoid selecting for simple cases, such as builtin types. 372 ( 0.00%) if ty::util::is_trivially_const_drop(ty) { . return false; . } . . let Some(drop_trait) = cx.tcx.lang_items().drop_trait() else { . // there is no way to define a type that needs non-const drop . // without having the lang item present. . return false; . }; -- line 159 ---------------------------------------- -- line 196 ---------------------------------------- . let mut fcx = FulfillmentContext::new(); . for nested in impl_src.nested_obligations() { . fcx.register_predicate_obligation(&infcx, nested); . } . . // If we had any errors, then it's bad . !fcx.select_all_or_error(&infcx).is_empty() . }) 837 ( 0.00%) } . . fn in_adt_inherently<'tcx>( . cx: &ConstCx<'_, 'tcx>, . adt: &'tcx AdtDef, . _: SubstsRef<'tcx>, . ) -> bool { . adt.has_non_const_dtor(cx.tcx) . } -- line 212 ---------------------------------------- -- line 214 ---------------------------------------- . . /// A constant that cannot be used as part of a pattern in a `match` expression. . pub struct CustomEq; . . impl Qualif for CustomEq { . const ANALYSIS_NAME: &'static str = "flow_custom_eq"; . . fn in_qualifs(qualifs: &ConstQualifs) -> bool { 182 ( 0.00%) qualifs.custom_eq . } . . fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool { . // If *any* component of a composite data type does not implement `Structural{Partial,}Eq`, . // we know that at least some values of that type are not structural-match. I say "some" . // because that component may be part of an enum variant (e.g., . // `Option::::Some`), in which case some values of this type may be . // structural-match (`Option::None`). 1,105,231 ( 0.02%) traits::search_for_structural_match_violation(cx.body.span, cx.tcx, ty).is_some() . } . 1,274 ( 0.00%) fn in_adt_inherently<'tcx>( . cx: &ConstCx<'_, 'tcx>, . adt: &'tcx AdtDef, . substs: SubstsRef<'tcx>, . ) -> bool { 182 ( 0.00%) let ty = cx.tcx.mk_ty(ty::Adt(adt, substs)); . !ty.is_structural_eq_shallow(cx.tcx) 1,456 ( 0.00%) } . } . . // FIXME: Use `mir::visit::Visitor` for the `in_*` functions if/when it supports early return. . . /// Returns `true` if this `Rvalue` contains qualif `Q`. 218,020 ( 0.00%) pub fn in_rvalue<'tcx, Q, F>( . cx: &ConstCx<'_, 'tcx>, . in_local: &mut F, . rvalue: &Rvalue<'tcx>, . ) -> bool . where . Q: Qualif, . F: FnMut(Local) -> bool, . { 109,010 ( 0.00%) match rvalue { . Rvalue::ThreadLocalRef(_) | Rvalue::NullaryOp(..) => { . Q::in_any_value_of_ty(cx, rvalue.ty(cx.body, cx.tcx)) . } . . Rvalue::Discriminant(place) | Rvalue::Len(place) => { . in_place::(cx, in_local, place.as_ref()) . } . . Rvalue::Use(operand) . | Rvalue::Repeat(operand, _) . | Rvalue::UnaryOp(_, operand) . | Rvalue::Cast(_, operand, _) 13,459 ( 0.00%) | Rvalue::ShallowInitBox(operand, _) => in_operand::(cx, in_local, operand), . . Rvalue::BinaryOp(_, box (lhs, rhs)) | Rvalue::CheckedBinaryOp(_, box (lhs, rhs)) => { . in_operand::(cx, in_local, lhs) || in_operand::(cx, in_local, rhs) . } . 17,350 ( 0.00%) Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => { . // Special-case reborrows to be more like a copy of the reference. 6,924 ( 0.00%) if let Some((place_base, ProjectionElem::Deref)) = place.as_ref().last_projection() { 3,462 ( 0.00%) let base_ty = place_base.ty(cx.body, cx.tcx).ty; 6,924 ( 0.00%) if let ty::Ref(..) = base_ty.kind() { 18,948 ( 0.00%) return in_place::(cx, in_local, place_base); . } . } . 27,084 ( 0.00%) in_place::(cx, in_local, place.as_ref()) . } . . Rvalue::Aggregate(kind, operands) => { . // Return early if we know that the struct or enum being constructed is always . // qualified. 32,150 ( 0.00%) if let AggregateKind::Adt(adt_did, _, substs, ..) = **kind { 1,388 ( 0.00%) let def = cx.tcx.adt_def(adt_did); 2,787 ( 0.00%) if Q::in_adt_inherently(cx, def, substs) { . return true; . } 1,206 ( 0.00%) if def.is_union() && Q::in_any_value_of_ty(cx, rvalue.ty(cx.body, cx.tcx)) { . return true; . } . } . . // Otherwise, proceed structurally... 8,851,364 ( 0.13%) operands.iter().any(|o| in_operand::(cx, in_local, o)) . } . } 120,548 ( 0.00%) } . . /// Returns `true` if this `Place` contains qualif `Q`. 180,484 ( 0.00%) pub fn in_place<'tcx, Q, F>(cx: &ConstCx<'_, 'tcx>, in_local: &mut F, place: PlaceRef<'tcx>) -> bool . where . Q: Qualif, . F: FnMut(Local) -> bool, . { 5,751 ( 0.00%) let mut place = place; . while let Some((place_base, elem)) = place.last_projection() { . match elem { . ProjectionElem::Index(index) if in_local(index) => return true, . . ProjectionElem::Deref . | ProjectionElem::Field(_, _) . | ProjectionElem::ConstantIndex { .. } . | ProjectionElem::Subslice { .. } -- line 320 ---------------------------------------- -- line 327 ---------------------------------------- . if !Q::in_any_value_of_ty(cx, proj_ty) { . return false; . } . . place = place_base; . } . . assert!(place.projection.is_empty()); 3,195 ( 0.00%) in_local(place.local) 29,248 ( 0.00%) } . . /// Returns `true` if this `Operand` contains qualif `Q`. 17,180,697 ( 0.24%) pub fn in_operand<'tcx, Q, F>( . cx: &ConstCx<'_, 'tcx>, . in_local: &mut F, . operand: &Operand<'tcx>, . ) -> bool . where . Q: Qualif, . F: FnMut(Local) -> bool, . { 3,879,630 ( 0.06%) let constant = match operand { . Operand::Copy(place) | Operand::Move(place) => { 52,640 ( 0.00%) return in_place::(cx, in_local, place.as_ref()); . } . . Operand::Constant(c) => c, . }; . . // Check the qualifs of the value of `const` items. 9,665,815 ( 0.14%) if let Some(ct) = constant.literal.const_for_ty() { 3,866,326 ( 0.05%) if let ty::ConstKind::Unevaluated(ty::Unevaluated { def, substs: _, promoted }) = ct.val { . // Use qualifs of the type for the promoted. Promoteds in MIR body should be possible . // only for `NeedsNonConstDrop` with precise drop checking. This is the only const . // check performed after the promotion. Verify that with an assertion. 636 ( 0.00%) assert!(promoted.is_none() || Q::ALLOW_PROMOTED); . // Don't peek inside trait associated constants. 727 ( 0.00%) if promoted.is_none() && cx.tcx.trait_of_item(def.did).is_none() { 6,269 ( 0.00%) let qualifs = if let Some((did, param_did)) = def.as_const_arg() { . cx.tcx.at(constant.span).mir_const_qualif_const_arg((did, param_did)) . } else { . cx.tcx.at(constant.span).mir_const_qualif(def.did) . }; . 636 ( 0.00%) if !Q::in_qualifs(&qualifs) { . return false; . } . . // Just in case the type is more specific than . // the definition, e.g., impl associated const . // with type parameters, take it into account. . } . } . } . // Otherwise use the qualifs of the type. 4,693,895 ( 0.07%) Q::in_any_value_of_ty(cx, constant.literal.ty()) 15,494,452 ( 0.22%) } 92,516 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs -------------------------------------------------------------------------------- Ir -- line 91 ---------------------------------------- . // maximum of number bytes needed to fill an 8-byte-sized element on which . // SipHash operates. Note that for variable-sized copies which are known to be . // less than 8 bytes, this function will perform more work than necessary unless . // the compiler is able to optimize the extra work away. . #[inline] . unsafe fn copy_nonoverlapping_small(src: *const u8, dst: *mut u8, count: usize) { . debug_assert!(count <= 8); . 128,655 ( 0.00%) if count == 8 { . ptr::copy_nonoverlapping(src, dst, 8); . return; . } . . let mut i = 0; 214,836 ( 0.00%) if i + 3 < count { . ptr::copy_nonoverlapping(src.add(i), dst.add(i), 4); . i += 4; . } . 459,817 ( 0.01%) if i + 1 < count { . ptr::copy_nonoverlapping(src.add(i), dst.add(i), 2); 56,641 ( 0.00%) i += 2 . } . 214,836 ( 0.00%) if i < count { 125,269 ( 0.00%) *dst.add(i) = *src.add(i); . i += 1; . } . . debug_assert_eq!(i, count); . } . . // # Implementation . // -- line 124 ---------------------------------------- -- line 201 ---------------------------------------- . . hasher . } . . // A specialized write function for values with size <= 8. . #[inline] . fn short_write(&mut self, x: T) { . let size = mem::size_of::(); 1,949,483 ( 0.03%) let nbuf = self.nbuf; . debug_assert!(size <= 8); . debug_assert!(nbuf < BUFFER_SIZE); . debug_assert!(nbuf + size < BUFFER_WITH_SPILL_SIZE); . 13,194,712 ( 0.19%) if nbuf + size < BUFFER_SIZE { . unsafe { . // The memcpy call is optimized away because the size is known. . let dst = (self.buf.as_mut_ptr() as *mut u8).add(nbuf); . ptr::copy_nonoverlapping(&x as *const _ as *const u8, dst, size); . } . 4,194,644 ( 0.06%) self.nbuf = nbuf + size; . . return; . } . 423,899 ( 0.01%) unsafe { self.short_write_process_buffer(x) } . } . . // A specialized write function for values with size <= 8 that should only . // be called when the write would cause the buffer to fill. . // . // SAFETY: the write of `x` into `self.buf` starting at byte offset . // `self.nbuf` must cause `self.buf` to become fully initialized (and not . // overflow) if it wasn't already. . #[inline(never)] 181,031 ( 0.00%) unsafe fn short_write_process_buffer(&mut self, x: T) { . let size = mem::size_of::(); 181,031 ( 0.00%) let nbuf = self.nbuf; . debug_assert!(size <= 8); . debug_assert!(nbuf < BUFFER_SIZE); . debug_assert!(nbuf + size >= BUFFER_SIZE); . debug_assert!(nbuf + size < BUFFER_WITH_SPILL_SIZE); . . // Copy first part of input into end of buffer, possibly into spill . // element. The memcpy call is optimized away because the size is known. . let dst = (self.buf.as_mut_ptr() as *mut u8).add(nbuf); . ptr::copy_nonoverlapping(&x as *const _ as *const u8, dst, size); . . // Process buffer. . for i in 0..BUFFER_CAPACITY { 1,810,310 ( 0.03%) let elem = self.buf.get_unchecked(i).assume_init().to_le(); 1,448,248 ( 0.02%) self.state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut self.state); 1,629,279 ( 0.02%) self.state.v0 ^= elem; . } . . // Copy remaining input into start of buffer by copying size - 1 . // elements from spill (at most size - 1 bytes could have overflowed . // into the spill). The memcpy call is optimized away because the size . // is known. And the whole copy is optimized away for size == 1. . let src = self.buf.get_unchecked(BUFFER_SPILL_INDEX) as *const _ as *const u8; . ptr::copy_nonoverlapping(src, self.buf.as_mut_ptr() as *mut u8, size - 1); . . // This function should only be called when the write fills the buffer. . // Therefore, when size == 1, the new `self.nbuf` must be zero. The size . // is statically known, so the branch is optimized away. 891,207 ( 0.01%) self.nbuf = if size == 1 { 0 } else { nbuf + size - BUFFER_SIZE }; 724,124 ( 0.01%) self.processed += BUFFER_SIZE; 362,062 ( 0.01%) } . . // A write function for byte slices. . #[inline] . fn slice_write(&mut self, msg: &[u8]) { . let length = msg.len(); 147,066 ( 0.00%) let nbuf = self.nbuf; . debug_assert!(nbuf < BUFFER_SIZE); . 817,185 ( 0.01%) if nbuf + length < BUFFER_SIZE { . unsafe { . let dst = (self.buf.as_mut_ptr() as *mut u8).add(nbuf); . 46,636 ( 0.00%) if length <= 8 { . copy_nonoverlapping_small(msg.as_ptr(), dst, length); . } else { . // This memcpy is *not* optimized away. . ptr::copy_nonoverlapping(msg.as_ptr(), dst, length); . } . } . 207,730 ( 0.00%) self.nbuf = nbuf + length; . . return; . } . 152,411 ( 0.00%) unsafe { self.slice_write_process_buffer(msg) } . } . . // A write function for byte slices that should only be called when the . // write would cause the buffer to fill. . // . // SAFETY: `self.buf` must be initialized up to the byte offset `self.nbuf`, . // and `msg` must contain enough bytes to initialize the rest of the element . // containing the byte offset `self.nbuf`. . #[inline(never)] 238,900 ( 0.00%) unsafe fn slice_write_process_buffer(&mut self, msg: &[u8]) { . let length = msg.len(); 47,780 ( 0.00%) let nbuf = self.nbuf; . debug_assert!(nbuf < BUFFER_SIZE); . debug_assert!(nbuf + length >= BUFFER_SIZE); . . // Always copy first part of input into current element of buffer. . // This function should only be called when the write fills the buffer, . // so we know that there is enough input to fill the current element. 143,340 ( 0.00%) let valid_in_elem = nbuf % ELEM_SIZE; 47,780 ( 0.00%) let needed_in_elem = ELEM_SIZE - valid_in_elem; . . let src = msg.as_ptr(); . let dst = (self.buf.as_mut_ptr() as *mut u8).add(nbuf); . copy_nonoverlapping_small(src, dst, needed_in_elem); . . // Process buffer. . . // Using `nbuf / ELEM_SIZE + 1` rather than `(nbuf + needed_in_elem) / . // ELEM_SIZE` to show the compiler that this loop's upper bound is > 0. . // We know that is true, because last step ensured we have a full . // element in the buffer. 95,560 ( 0.00%) let last = nbuf / ELEM_SIZE + 1; . . for i in 0..last { 347,471 ( 0.00%) let elem = self.buf.get_unchecked(i).assume_init().to_le(); 395,251 ( 0.01%) self.state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut self.state); 694,942 ( 0.01%) self.state.v0 ^= elem; . } . . // Process the remaining element-sized chunks of input. . let mut processed = needed_in_elem; 95,560 ( 0.00%) let input_left = length - processed; 139,428 ( 0.00%) let elems_left = input_left / ELEM_SIZE; . let extra_bytes_left = input_left % ELEM_SIZE; . . for _ in 0..elems_left { 46,792 ( 0.00%) let elem = (msg.as_ptr().add(processed) as *const u64).read_unaligned().to_le(); 46,792 ( 0.00%) self.state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut self.state); 46,792 ( 0.00%) self.state.v0 ^= elem; 93,584 ( 0.00%) processed += ELEM_SIZE; . } . . // Copy remaining input into start of buffer. . let src = msg.as_ptr().add(processed); . let dst = self.buf.as_mut_ptr() as *mut u8; . copy_nonoverlapping_small(src, dst, extra_bytes_left); . 47,780 ( 0.00%) self.nbuf = extra_bytes_left; 238,900 ( 0.00%) self.processed += nbuf + processed; 286,680 ( 0.00%) } . . #[inline] . pub fn finish128(mut self) -> (u64, u64) { . debug_assert!(self.nbuf < BUFFER_SIZE); . . // Process full elements in buffer. 20,838 ( 0.00%) let last = self.nbuf / ELEM_SIZE; . . // Since we're consuming self, avoid updating members for a potential . // performance gain. 27,784 ( 0.00%) let mut state = self.state; . . for i in 0..last { 18,210 ( 0.00%) let elem = unsafe { self.buf.get_unchecked(i).assume_init().to_le() }; 18,210 ( 0.00%) state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut state); 18,210 ( 0.00%) state.v0 ^= elem; . } . . // Get remaining partial element. 13,892 ( 0.00%) let elem = if self.nbuf % ELEM_SIZE != 0 { . unsafe { . // Ensure element is initialized by writing zero bytes. At most . // `ELEM_SIZE - 1` are required given the above check. It's safe . // to write this many because we have the spill and we maintain . // `self.nbuf` such that this write will start before the spill. . let dst = (self.buf.as_mut_ptr() as *mut u8).add(self.nbuf); . ptr::write_bytes(dst, 0, ELEM_SIZE - 1); 6,264 ( 0.00%) self.buf.get_unchecked(last).assume_init().to_le() . } . } else { . 0 . }; . . // Finalize the hash. 19,652 ( 0.00%) let length = self.processed + self.nbuf; 12,880 ( 0.00%) let b: u64 = ((length as u64 & 0xff) << 56) | elem; . 6,440 ( 0.00%) state.v3 ^= b; . Sip24Rounds::c_rounds(&mut state); 6,440 ( 0.00%) state.v0 ^= b; . 6,440 ( 0.00%) state.v2 ^= 0xee; . Sip24Rounds::d_rounds(&mut state); 21,686 ( 0.00%) let _0 = state.v0 ^ state.v1 ^ state.v2 ^ state.v3; . 8,802 ( 0.00%) state.v1 ^= 0xdd; . Sip24Rounds::d_rounds(&mut state); 8,802 ( 0.00%) let _1 = state.v0 ^ state.v1 ^ state.v2 ^ state.v3; . . (_0, _1) . } . } . . impl Hasher for SipHasher128 { . #[inline] . fn write_u8(&mut self, i: u8) { -- line 414 ---------------------------------------- -- line 471 ---------------------------------------- . } . . #[derive(Debug, Clone, Default)] . struct Sip24Rounds; . . impl Sip24Rounds { . #[inline] . fn c_rounds(state: &mut State) { 7,793,015 ( 0.11%) compress!(state); 9,054,150 ( 0.13%) compress!(state); . } . . #[inline] . fn d_rounds(state: &mut State) { 43,364 ( 0.00%) compress!(state); 43,364 ( 0.00%) compress!(state); 43,364 ( 0.00%) compress!(state); 36,926 ( 0.00%) compress!(state); . } . } 1,229,291 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/util.rs -------------------------------------------------------------------------------- Ir -- line 41 ---------------------------------------- . write!(fmt, "{}", x) . } . _ => write!(fmt, "{}", self.val), . } . } . } . . fn int_size_and_signed<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> (Size, bool) { 3,399 ( 0.00%) let (int, signed) = match *ty.kind() { 7,931 ( 0.00%) Int(ity) => (Integer::from_int_ty(&tcx, ity), true), . Uint(uty) => (Integer::from_uint_ty(&tcx, uty), false), . _ => bug!("non integer discriminant"), . }; . (int.size(), signed) . } . . impl<'tcx> Discr<'tcx> { . /// Adds `1` to the value and wraps around if the maximum for the type is reached. 3,235 ( 0.00%) pub fn wrap_incr(self, tcx: TyCtxt<'tcx>) -> Self { 6,014 ( 0.00%) self.checked_add(tcx, 1).0 1,294 ( 0.00%) } 10,197 ( 0.00%) pub fn checked_add(self, tcx: TyCtxt<'tcx>, n: u128) -> (Self, bool) { . let (size, signed) = int_size_and_signed(tcx, self.ty); . let (val, oflo) = if signed { . let min = size.signed_int_min(); . let max = size.signed_int_max(); . let val = size.sign_extend(self.val) as i128; 4,532 ( 0.00%) assert!(n < (i128::MAX as u128)); . let n = n as i128; 7,931 ( 0.00%) let oflo = val > max - n; 4,532 ( 0.00%) let val = if oflo { min + (n - (max - val) - 1) } else { val + n }; . // zero the upper bits . let val = val as u128; . let val = size.truncate(val); . (val, oflo) . } else { . let max = size.unsigned_int_max(); . let val = self.val; . let oflo = val > max - n; . let val = if oflo { n - (max - val) - 1 } else { val + n }; . (val, oflo) . }; 4,532 ( 0.00%) (Self { val, ty: self.ty }, oflo) 10,197 ( 0.00%) } . } . . pub trait IntTypeExt { . fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx>; . fn disr_incr<'tcx>(&self, tcx: TyCtxt<'tcx>, val: Option>) -> Option>; . fn initial_discriminant<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Discr<'tcx>; . } . . impl IntTypeExt for attr::IntType { . fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { 9,050 ( 0.00%) match *self { . SignedInt(ast::IntTy::I8) => tcx.types.i8, . SignedInt(ast::IntTy::I16) => tcx.types.i16, . SignedInt(ast::IntTy::I32) => tcx.types.i32, . SignedInt(ast::IntTy::I64) => tcx.types.i64, . SignedInt(ast::IntTy::I128) => tcx.types.i128, . SignedInt(ast::IntTy::Isize) => tcx.types.isize, . UnsignedInt(ast::UintTy::U8) => tcx.types.u8, . UnsignedInt(ast::UintTy::U16) => tcx.types.u16, . UnsignedInt(ast::UintTy::U32) => tcx.types.u32, . UnsignedInt(ast::UintTy::U64) => tcx.types.u64, . UnsignedInt(ast::UintTy::U128) => tcx.types.u128, . UnsignedInt(ast::UintTy::Usize) => tcx.types.usize, . } 657 ( 0.00%) } . . fn initial_discriminant<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Discr<'tcx> { . Discr { val: 0, ty: self.to_ty(tcx) } 2,916 ( 0.00%) } . 44 ( 0.00%) fn disr_incr<'tcx>(&self, tcx: TyCtxt<'tcx>, val: Option>) -> Option> { 80 ( 0.00%) if let Some(val) = val { 24 ( 0.00%) assert_eq!(self.to_ty(tcx), val.ty); 108 ( 0.00%) let (new, oflo) = val.checked_add(tcx, 1); 12 ( 0.00%) if oflo { None } else { Some(new) } . } else { . Some(self.initial_discriminant(tcx)) . } 44 ( 0.00%) } . } . . impl<'tcx> TyCtxt<'tcx> { . /// Creates a hash of the type `Ty` which will be the same no matter what crate . /// context it's calculated within. This is used by the `type_id` intrinsic. 7 ( 0.00%) pub fn type_id_hash(self, ty: Ty<'tcx>) -> u64 { . let mut hasher = StableHasher::new(); . let mut hcx = self.create_stable_hashing_context(); . . // We want the type_id be independent of the types free regions, so we . // erase them. The erase_regions() call will also anonymize bound . // regions, which is desirable too. . let ty = self.erase_regions(ty); . . hcx.while_hashing_spans(false, |hcx| { . hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| { . ty.hash_stable(hcx, &mut hasher); . }); . }); . hasher.finish() 9 ( 0.00%) } . 154 ( 0.00%) pub fn has_error_field(self, ty: Ty<'tcx>) -> bool { 88 ( 0.00%) if let ty::Adt(def, substs) = *ty.kind() { . for field in def.all_fields() { 186 ( 0.00%) let field_ty = field.ty(self, substs); 186 ( 0.00%) if let Error(_) = field_ty.kind() { . return true; . } . } . } . false 176 ( 0.00%) } . . /// Attempts to returns the deeply last field of nested structures, but . /// does not apply any normalization in its search. Returns the same type . /// if input `ty` is not a structure at all. 15,408 ( 0.00%) pub fn struct_tail_without_normalization(self, ty: Ty<'tcx>) -> Ty<'tcx> { . let tcx = self; . tcx.struct_tail_with_normalize(ty, |ty| ty) 13,696 ( 0.00%) } . . /// Returns the deeply last field of nested structures, or the same type if . /// not a structure at all. Corresponds to the only possible unsized field, . /// and its type can be used to determine unsizing strategy. . /// . /// Should only be called if `ty` has no inference variables and does not . /// need its lifetimes preserved (e.g. as part of codegen); otherwise . /// normalization attempt may cause compiler bugs. 43,670 ( 0.00%) pub fn struct_tail_erasing_lifetimes( . self, . ty: Ty<'tcx>, . param_env: ty::ParamEnv<'tcx>, . ) -> Ty<'tcx> { . let tcx = self; . tcx.struct_tail_with_normalize(ty, |ty| tcx.normalize_erasing_regions(param_env, ty)) 35,730 ( 0.00%) } . . /// Returns the deeply last field of nested structures, or the same type if . /// not a structure at all. Corresponds to the only possible unsized field, . /// and its type can be used to determine unsizing strategy. . /// . /// This is parameterized over the normalization strategy (i.e. how to . /// handle `::Assoc` and `impl Trait`); pass the identity . /// function to indicate no normalization should take place. . /// . /// See also `struct_tail_erasing_lifetimes`, which is suitable for use . /// during codegen. 82 ( 0.00%) pub fn struct_tail_with_normalize( . self, . mut ty: Ty<'tcx>, . mut normalize: impl FnMut(Ty<'tcx>) -> Ty<'tcx>, . ) -> Ty<'tcx> { 28,468 ( 0.00%) let recursion_limit = self.recursion_limit(); . for iteration in 0.. { 6,169 ( 0.00%) if !recursion_limit.value_within_limit(iteration) { . return self.ty_error_with_message( . DUMMY_SP, . &format!("reached the recursion limit finding the struct tail for {}", ty), . ); . } 42,497 ( 0.00%) match *ty.kind() { 549 ( 0.00%) ty::Adt(def, substs) => { 1,098 ( 0.00%) if !def.is_struct() { . break; . } 534 ( 0.00%) match def.non_enum_variant().fields.last() { 1,416 ( 0.00%) Some(f) => ty = f.ty(self, substs), . None => break, . } . } . 19 ( 0.00%) ty::Tuple(tys) if let Some((&last_ty, _)) = tys.split_last() => { . ty = last_ty.expect_ty(); . } . . ty::Tuple(_) => break, . . ty::Projection(_) | ty::Opaque(..) => { . let normalized = normalize(ty); . if ty == normalized { -- line 224 ---------------------------------------- -- line 229 ---------------------------------------- . } . . _ => { . break; . } . } . } . ty 63 ( 0.00%) } . . /// Same as applying `struct_tail` on `source` and `target`, but only . /// keeps going as long as the two types are instances of the same . /// structure definitions. . /// For `(Foo>, Foo)`, the result will be `(Foo, Trait)`, . /// whereas struct_tail produces `T`, and `Trait`, respectively. . /// . /// Should only be called if the types have no inference variables and do . /// not need their lifetimes preserved (e.g., as part of codegen); otherwise, . /// normalization attempt may cause compiler bugs. 8,970 ( 0.00%) pub fn struct_lockstep_tails_erasing_lifetimes( . self, . source: Ty<'tcx>, . target: Ty<'tcx>, . param_env: ty::ParamEnv<'tcx>, . ) -> (Ty<'tcx>, Ty<'tcx>) { . let tcx = self; . tcx.struct_lockstep_tails_with_normalize(source, target, |ty| { . tcx.normalize_erasing_regions(param_env, ty) . }) 5,980 ( 0.00%) } . . /// Same as applying `struct_tail` on `source` and `target`, but only . /// keeps going as long as the two types are instances of the same . /// structure definitions. . /// For `(Foo>, Foo)`, the result will be `(Foo, Trait)`, . /// whereas struct_tail produces `T`, and `Trait`, respectively. . /// . /// See also `struct_lockstep_tails_erasing_lifetimes`, which is suitable for use -- line 266 ---------------------------------------- -- line 268 ---------------------------------------- . pub fn struct_lockstep_tails_with_normalize( . self, . source: Ty<'tcx>, . target: Ty<'tcx>, . normalize: impl Fn(Ty<'tcx>) -> Ty<'tcx>, . ) -> (Ty<'tcx>, Ty<'tcx>) { . let (mut a, mut b) = (source, target); . loop { 7,176 ( 0.00%) match (&a.kind(), &b.kind()) { . (&Adt(a_def, a_substs), &Adt(b_def, b_substs)) . if a_def == b_def && a_def.is_struct() => . { . if let Some(f) = a_def.non_enum_variant().fields.last() { . a = f.ty(self, a_substs); . b = f.ty(self, b_substs); . } else { . break; -- line 284 ---------------------------------------- -- line 310 ---------------------------------------- . . _ => break, . } . } . (a, b) . } . . /// Calculate the destructor of a given type. 900 ( 0.00%) pub fn calculate_dtor( . self, . adt_did: DefId, . validate: impl Fn(Self, DefId) -> Result<(), ErrorReported>, . ) -> Option { 375 ( 0.00%) let drop_trait = self.lang_items().drop_trait()?; . self.ensure().coherent_trait(drop_trait); . 75 ( 0.00%) let ty = self.type_of(adt_did); 717 ( 0.00%) let (did, constness) = self.find_map_relevant_impl(drop_trait, ty, |impl_did| { 36 ( 0.00%) if let Some(item_id) = self.associated_item_def_ids(impl_did).first() { . if validate(self, impl_did).is_ok() { 42 ( 0.00%) return Some((*item_id, self.impl_constness(impl_did))); . } . } . None 78 ( 0.00%) })?; . . Some(ty::Destructor { did, constness }) 750 ( 0.00%) } . . /// Returns the set of types that are required to be alive in . /// order to run the destructor of `def` (see RFCs 769 and . /// 1238). . /// . /// Note that this returns only the constraints for the . /// destructor of `def` itself. For the destructors of the . /// contents, you need `adt_dtorck_constraint`. 759 ( 0.00%) pub fn destructor_constraints(self, def: &'tcx ty::AdtDef) -> Vec> { 357 ( 0.00%) let dtor = match def.destructor(self) { . None => { . debug!("destructor_constraints({:?}) - no dtor", def.did); . return vec![]; . } . Some(dtor) => dtor.did, . }; . . let impl_def_id = self.associated_item(dtor).container.id(); -- line 355 ---------------------------------------- -- line 371 ---------------------------------------- . // . // impl<#[may_dangle] P0, P1, P2> Drop for S . // . // We want to return the parameters (X, Y). For that, we match . // up the item-substs with the substs on the impl ADT, . // , and then look up which of the impl substs refer to . // parameters marked as pure. . 12 ( 0.00%) let impl_substs = match *self.type_of(impl_def_id).kind() { 42 ( 0.00%) ty::Adt(def_, substs) if def_ == def => substs, . _ => bug!(), . }; . 12 ( 0.00%) let item_substs = match *self.type_of(def.did).kind() { 42 ( 0.00%) ty::Adt(def_, substs) if def_ == def => substs, . _ => bug!(), . }; . . let result = iter::zip(item_substs, impl_substs) . .filter(|&(_, k)| { 22 ( 0.00%) match k.unpack() { . GenericArgKind::Lifetime(&ty::RegionKind::ReEarlyBound(ref ebr)) => { . !impl_generics.region_param(ebr, self).pure_wrt_drop . } . GenericArgKind::Type(&ty::TyS { kind: ty::Param(ref pt), .. }) => { 33 ( 0.00%) !impl_generics.type_param(pt, self).pure_wrt_drop . } . GenericArgKind::Const(&ty::Const { . val: ty::ConstKind::Param(ref pc), .. . }) => !impl_generics.const_param(pc, self).pure_wrt_drop, . GenericArgKind::Lifetime(_) . | GenericArgKind::Type(_) . | GenericArgKind::Const(_) => { . // Not a type, const or region param: this should be reported -- line 404 ---------------------------------------- -- line 405 ---------------------------------------- . // as an error. . false . } . } . }) . .map(|(item_param, _)| item_param) . .collect(); . debug!("destructor_constraint({:?}) = {:?}", def.did, result); 30 ( 0.00%) result 678 ( 0.00%) } . . /// Returns `true` if `def_id` refers to a closure (e.g., `|x| x * 2`). Note . /// that closures have a `DefId`, but the closure *expression* also . /// has a `HirId` that is located within the context where the . /// closure appears (and, sadly, a corresponding `NodeId`, since . /// those are not yet phased out). The parent of the closure's . /// `DefId` will also be the context where it appears. 1,444 ( 0.00%) pub fn is_closure(self, def_id: DefId) -> bool { 7,556 ( 0.00%) matches!(self.def_kind(def_id), DefKind::Closure | DefKind::Generator) 2,888 ( 0.00%) } . . /// Returns `true` if `def_id` refers to a definition that does not have its own . /// type-checking context, i.e. closure, generator or inline const. 802 ( 0.00%) pub fn is_typeck_child(self, def_id: DefId) -> bool { 12,916 ( 0.00%) matches!( 13,802 ( 0.00%) self.def_kind(def_id), . DefKind::Closure | DefKind::Generator | DefKind::InlineConst . ) 1,604 ( 0.00%) } . . /// Returns `true` if `def_id` refers to a trait (i.e., `trait Foo { ... }`). 1,637 ( 0.00%) pub fn is_trait(self, def_id: DefId) -> bool { 1,637 ( 0.00%) self.def_kind(def_id) == DefKind::Trait 3,274 ( 0.00%) } . . /// Returns `true` if `def_id` refers to a trait alias (i.e., `trait Foo = ...;`), . /// and `false` otherwise. 3,887 ( 0.00%) pub fn is_trait_alias(self, def_id: DefId) -> bool { 3,887 ( 0.00%) self.def_kind(def_id) == DefKind::TraitAlias 7,774 ( 0.00%) } . . /// Returns `true` if this `DefId` refers to the implicit constructor for . /// a tuple struct like `struct Foo(u32)`, and `false` otherwise. 707 ( 0.00%) pub fn is_constructor(self, def_id: DefId) -> bool { 10,851 ( 0.00%) matches!(self.def_kind(def_id), DefKind::Ctor(..)) 1,414 ( 0.00%) } . . /// Given the `DefId`, returns the `DefId` of the innermost item that . /// has its own type-checking context or "inference enviornment". . /// . /// For example, a closure has its own `DefId`, but it is type-checked . /// with the containing item. Similarly, an inline const block has its . /// own `DefId` but it is type-checked together with the containing item. . /// . /// Therefore, when we fetch the . /// `typeck` the closure, for example, we really wind up . /// fetching the `typeck` the enclosing fn item. 30,870 ( 0.00%) pub fn typeck_root_def_id(self, def_id: DefId) -> DefId { . let mut def_id = def_id; . while self.is_typeck_child(def_id) { . def_id = self.parent(def_id).unwrap_or_else(|| { . bug!("closure {:?} has no parent", def_id); . }); . } . def_id 24,696 ( 0.00%) } . . /// Given the `DefId` and substs a closure, creates the type of . /// `self` argument that the closure expects. For example, for a . /// `Fn` closure, this would return a reference type `&T` where . /// `T = closure_ty`. . /// . /// Returns `None` if this closure's kind has not yet been inferred. . /// This should only be possible during type checking. . /// . /// Note that the return value is a late-bound region and hence . /// wrapped in a binder. 513 ( 0.00%) pub fn closure_env_ty( . self, . closure_def_id: DefId, . closure_substs: SubstsRef<'tcx>, . env_region: ty::RegionKind, . ) -> Option> { . let closure_ty = self.mk_closure(closure_def_id, closure_substs); . let closure_kind_ty = closure_substs.as_closure().kind_ty(); 171 ( 0.00%) let closure_kind = closure_kind_ty.to_opt_closure_kind()?; 216 ( 0.00%) let env_ty = match closure_kind { 42 ( 0.00%) ty::ClosureKind::Fn => self.mk_imm_ref(self.mk_region(env_region), closure_ty), 231 ( 0.00%) ty::ClosureKind::FnMut => self.mk_mut_ref(self.mk_region(env_region), closure_ty), . ty::ClosureKind::FnOnce => closure_ty, . }; . Some(env_ty) 456 ( 0.00%) } . . /// Returns `true` if the node pointed to by `def_id` is a `static` item. 5,110 ( 0.00%) pub fn is_static(self, def_id: DefId) -> bool { . self.static_mutability(def_id).is_some() 5,840 ( 0.00%) } . . /// Returns `true` if this is a `static` item with the `#[thread_local]` attribute. . pub fn is_thread_local_static(self, def_id: DefId) -> bool { . self.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) . } . . /// Returns `true` if the node pointed to by `def_id` is a mutable `static` item. . pub fn is_mutable_static(self, def_id: DefId) -> bool { -- line 510 ---------------------------------------- -- line 597 ---------------------------------------- . self.found_recursion = def_id == *self.primary_def_id.as_ref().unwrap(); . None . } . } . } . . impl<'tcx> TypeFolder<'tcx> for OpaqueTypeExpander<'tcx> { . fn tcx(&self) -> TyCtxt<'tcx> { 224 ( 0.00%) self.tcx . } . . fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { 596 ( 0.00%) if let ty::Opaque(def_id, substs) = t.kind { . self.expand_opaque_ty(def_id, substs).unwrap_or(t) 298 ( 0.00%) } else if t.has_opaque_types() { . t.super_fold_with(self) . } else { . t . } . } . } . . impl<'tcx> ty::TyS<'tcx> { -- line 619 ---------------------------------------- -- line 658 ---------------------------------------- . . /// Checks whether values of this type `T` are *moved* or *copied* . /// when referenced -- this amounts to a check for whether `T: . /// Copy`, but note that we **don't** consider lifetimes when . /// doing this check. This means that we may generate MIR which . /// does copies even when the type actually doesn't satisfy the . /// full requirements for the `Copy` trait (cc #29149) -- this . /// winds up being reported as an error during NLL borrow check. 5,875 ( 0.00%) pub fn is_copy_modulo_regions( . &'tcx self, . tcx_at: TyCtxtAt<'tcx>, . param_env: ty::ParamEnv<'tcx>, . ) -> bool { . tcx_at.is_copy_raw(param_env.and(self)) 4,700 ( 0.00%) } . . /// Checks whether values of this type `T` have a size known at . /// compile time (i.e., whether `T: Sized`). Lifetimes are ignored . /// for the purposes of this check, so it can be an . /// over-approximation in generic contexts, where one can have . /// strange rules like `>::Bar: Sized` that . /// actually carry lifetime requirements. 103,725 ( 0.00%) pub fn is_sized(&'tcx self, tcx_at: TyCtxtAt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool { 57,625 ( 0.00%) self.is_trivially_sized(tcx_at.tcx) || tcx_at.is_sized_raw(param_env.and(self)) 69,150 ( 0.00%) } . . /// Checks whether values of this type `T` implement the `Freeze` . /// trait -- frozen types are those that do not contain an . /// `UnsafeCell` anywhere. This is a language concept used to . /// distinguish "true immutability", which is relevant to . /// optimization as well as the rules around static values. Note . /// that the `Freeze` trait is not exposed to end users and is . /// effectively an implementation detail. 12,444,138 ( 0.18%) pub fn is_freeze(&'tcx self, tcx_at: TyCtxtAt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool { 6,913,410 ( 0.10%) self.is_trivially_freeze() || tcx_at.is_freeze_raw(param_env.and(self)) 8,296,092 ( 0.12%) } . . /// Fast path helper for testing if a type is `Freeze`. . /// . /// Returning true means the type is known to be `Freeze`. Returning . /// `false` means nothing -- could be `Freeze`, might not be. . fn is_trivially_freeze(&self) -> bool { . match self.kind() { . ty::Int(_) -- line 701 ---------------------------------------- -- line 723 ---------------------------------------- . | ty::Opaque(..) . | ty::Param(_) . | ty::Placeholder(_) . | ty::Projection(_) => false, . } . } . . /// Checks whether values of this type `T` implement the `Unpin` trait. 1,341 ( 0.00%) pub fn is_unpin(&'tcx self, tcx_at: TyCtxtAt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool { 745 ( 0.00%) self.is_trivially_unpin() || tcx_at.is_unpin_raw(param_env.and(self)) 894 ( 0.00%) } . . /// Fast path helper for testing if a type is `Unpin`. . /// . /// Returning true means the type is known to be `Unpin`. Returning . /// `false` means nothing -- could be `Unpin`, might not be. 6,914,425 ( 0.10%) fn is_trivially_unpin(&self) -> bool { 6,923,110 ( 0.10%) match self.kind() { . ty::Int(_) . | ty::Uint(_) . | ty::Float(_) . | ty::Bool . | ty::Char . | ty::Str . | ty::Never . | ty::Ref(..) . | ty::RawPtr(_) . | ty::FnDef(..) . | ty::Error(_) . | ty::FnPtr(_) => true, . ty::Tuple(_) => self.tuple_fields().all(Self::is_trivially_unpin), 3,474 ( 0.00%) ty::Slice(elem_ty) | ty::Array(elem_ty, _) => elem_ty.is_trivially_unpin(), . ty::Adt(..) . | ty::Bound(..) . | ty::Closure(..) . | ty::Dynamic(..) . | ty::Foreign(_) . | ty::Generator(..) . | ty::GeneratorWitness(_) . | ty::Infer(_) . | ty::Opaque(..) . | ty::Param(_) . | ty::Placeholder(_) . | ty::Projection(_) => false, . } 9,680,195 ( 0.14%) } . . /// If `ty.needs_drop(...)` returns `true`, then `ty` is definitely . /// non-copy and *might* have a destructor attached; if it returns . /// `false`, then `ty` definitely has no destructor (i.e., no drop glue). . /// . /// (Note that this implies that if `ty` has a destructor attached, . /// then `needs_drop` will definitely return `true` for `ty`.) . /// . /// Note that this method is used to check eligible types in unions. . #[inline] 83,840 ( 0.00%) pub fn needs_drop(&'tcx self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool { . // Avoid querying in simple cases. 1,718,048 ( 0.02%) match needs_drop_components(self, &tcx.data_layout) { . Err(AlwaysRequiresDrop) => true, 1,139,772 ( 0.02%) Ok(components) => { . let query_ty = match *components { 576,528 ( 0.01%) [] => return false, . // If we've got a single component, call the query with that . // to increase the chance that we hit the query cache. 3,318 ( 0.00%) [component_ty] => component_ty, . _ => self, . }; . . // This doesn't depend on regions, so try to minimize distinct . // query keys used. . // If normalization fails, we just use `query_ty`. . let query_ty = 124 ( 0.00%) tcx.try_normalize_erasing_regions(param_env, query_ty).unwrap_or(query_ty); . 62 ( 0.00%) tcx.needs_drop_raw(param_env.and(query_ty)) . } . } 75,456 ( 0.00%) } . . /// Checks if `ty` has has a significant drop. . /// . /// Note that this method can return false even if `ty` has a destructor . /// attached; even if that is the case then the adt has been marked with . /// the attribute `rustc_insignificant_dtor`. . /// . /// Note that this method is used to check for change in drop order for -- line 809 ---------------------------------------- -- line 854 ---------------------------------------- . /// . /// This function is "shallow" because it may return `true` for a composite type whose fields . /// are not `StructuralEq`. For example, `[T; 4]` has structural equality regardless of `T` . /// because equality for arrays is determined by the equality of each array element. If you . /// want to know whether a given call to `PartialEq::eq` will proceed structurally all the way . /// down, you will need to use a type visitor. . #[inline] . pub fn is_structural_eq_shallow(&'tcx self, tcx: TyCtxt<'tcx>) -> bool { 2,192 ( 0.00%) match self.kind() { . // Look for an impl of both `PartialStructuralEq` and `StructuralEq`. . Adt(..) => tcx.has_structural_eq_impls(self), . . // Primitive types that satisfy `Eq`. . Bool | Char | Int(_) | Uint(_) | Str | Never => true, . . // Composite types that satisfy `Eq` when all of their fields do. . // -- line 870 ---------------------------------------- -- line 888 ---------------------------------------- . // FIXME(ecstaticmorse): Maybe we should `bug` here? This should probably only be . // called for known, fully-monomorphized types. . Projection(_) | Opaque(..) | Param(_) | Bound(..) | Placeholder(_) | Infer(_) => false, . . Foreign(_) | GeneratorWitness(..) | Error(_) => false, . } . } . 610 ( 0.00%) pub fn same_type(a: Ty<'tcx>, b: Ty<'tcx>) -> bool { 488 ( 0.00%) match (&a.kind(), &b.kind()) { . (&Adt(did_a, substs_a), &Adt(did_b, substs_b)) => { 610 ( 0.00%) if did_a != did_b { . return false; . } . . substs_a.types().zip(substs_b.types()).all(|(a, b)| Self::same_type(a, b)) . } . _ => a == b, . } 732 ( 0.00%) } . . /// Peel off all reference types in this type until there are none left. . /// . /// This method is idempotent, i.e. `ty.peel_refs().peel_refs() == ty.peel_refs()`. . /// . /// # Examples . /// . /// - `u8` -> `u8` . /// - `&'a mut u8` -> `u8` . /// - `&'a &'b u8` -> `u8` . /// - `&'a *const &'b u8 -> *const &'b u8` 633 ( 0.00%) pub fn peel_refs(&'tcx self) -> Ty<'tcx> { . let mut ty = self; 2,048 ( 0.00%) while let Ref(_, inner_ty, _) = ty.kind() { 261 ( 0.00%) ty = inner_ty; . } . ty 633 ( 0.00%) } . . pub fn outer_exclusive_binder(&'tcx self) -> DebruijnIndex { 1,137 ( 0.00%) self.outer_exclusive_binder 1,137 ( 0.00%) } . } . . pub enum ExplicitSelf<'tcx> { . ByValue, . ByReference(ty::Region<'tcx>, hir::Mutability), . ByRawPointer(hir::Mutability), . ByBox, . Other, -- line 937 ---------------------------------------- -- line 976 ---------------------------------------- . _ => Other, . } . } . } . . /// Returns a list of types such that the given type needs drop if and only if . /// *any* of the returned types need drop. Returns `Err(AlwaysRequiresDrop)` if . /// this type always needs drop. 2,001,489 ( 0.03%) pub fn needs_drop_components<'tcx>( . ty: Ty<'tcx>, . target_layout: &TargetDataLayout, . ) -> Result; 2]>, AlwaysRequiresDrop> { 1,715,567 ( 0.02%) match ty.kind() { . ty::Infer(ty::FreshIntTy(_)) . | ty::Infer(ty::FreshFloatTy(_)) . | ty::Bool . | ty::Int(_) . | ty::Uint(_) . | ty::Float(_) . | ty::Never . | ty::FnDef(..) -- line 996 ---------------------------------------- -- line 999 ---------------------------------------- . | ty::GeneratorWitness(..) . | ty::RawPtr(_) . | ty::Ref(..) . | ty::Str => Ok(SmallVec::new()), . . // Foreign types can never have destructors. . ty::Foreign(..) => Ok(SmallVec::new()), . 2 ( 0.00%) ty::Dynamic(..) | ty::Error(_) => Err(AlwaysRequiresDrop), . 1 ( 0.00%) ty::Slice(ty) => needs_drop_components(ty, target_layout), . ty::Array(elem_ty, size) => { 228 ( 0.00%) match needs_drop_components(elem_ty, target_layout) { 184 ( 0.00%) Ok(v) if v.is_empty() => Ok(v), 160 ( 0.00%) res => match size.val.try_to_bits(target_layout.pointer_size) { . // Arrays of size zero don't need drop, even if their element . // type does. . Some(0) => Ok(SmallVec::new()), 80 ( 0.00%) Some(_) => res, . // We don't know which of the cases above we are in, so . // return the whole type and let the caller decide what to . // do. . None => Ok(smallvec![ty]), . }, . } . } . // If any field needs drop, then the whole tuple does. 770 ( 0.00%) ty::Tuple(..) => ty.tuple_fields().try_fold(SmallVec::new(), move |mut acc, elem| { 2,592 ( 0.00%) acc.extend(needs_drop_components(elem, target_layout)?); 1,728 ( 0.00%) Ok(acc) . }), . . // These require checking for `Copy` bounds or `Adt` destructors. . ty::Adt(..) . | ty::Projection(..) . | ty::Param(_) . | ty::Bound(..) . | ty::Placeholder(..) . | ty::Opaque(..) . | ty::Infer(_) . | ty::Closure(..) 7,468 ( 0.00%) | ty::Generator(..) => Ok(smallvec![ty]), . } 1,715,562 ( 0.02%) } . 558 ( 0.00%) pub fn is_trivially_const_drop<'tcx>(ty: Ty<'tcx>) -> bool { 372 ( 0.00%) match *ty.kind() { . ty::Bool . | ty::Char . | ty::Int(_) . | ty::Uint(_) . | ty::Float(_) . | ty::Infer(ty::IntVar(_)) . | ty::Infer(ty::FloatVar(_)) . | ty::Str -- line 1053 ---------------------------------------- -- line 1070 ---------------------------------------- . // Not trivial because they have components, and instead of looking inside, . // we'll just perform trait selection. . ty::Closure(..) | ty::Generator(..) | ty::GeneratorWitness(_) | ty::Adt(..) => false, . . ty::Array(ty, _) | ty::Slice(ty) => is_trivially_const_drop(ty), . . ty::Tuple(tys) => tys.iter().all(|ty| is_trivially_const_drop(ty.expect_ty())), . } 744 ( 0.00%) } . . // Does the equivalent of . // ``` . // let v = self.iter().map(|p| p.fold_with(folder)).collect::>(); . // folder.tcx().intern_*(&v) . // ``` 315,640 ( 0.00%) pub fn fold_list<'tcx, F, T>( . list: &'tcx ty::List, . folder: &mut F, . intern: impl FnOnce(TyCtxt<'tcx>, &[T]) -> &'tcx ty::List, . ) -> Result<&'tcx ty::List, F::Error> . where . F: FallibleTypeFolder<'tcx>, . T: TypeFoldable<'tcx> + PartialEq + Copy, . { . let mut iter = list.iter(); . // Look for the first element that changed 201,262 ( 0.00%) match iter.by_ref().enumerate().find_map(|(i, t)| match t.try_fold_with(folder) { 352,655 ( 0.01%) Ok(new_t) if new_t == t => None, . new_t => Some((i, new_t)), . }) { . Some((i, Ok(new_t))) => { . // An element changed, prepare to intern the resulting list . let mut new_list = SmallVec::<[_; 8]>::with_capacity(list.len()); . new_list.extend_from_slice(&list[..i]); . new_list.push(new_t); . for t in iter { . new_list.push(t.try_fold_with(folder)?) . } 8,769 ( 0.00%) Ok(intern(folder.tcx(), &new_list)) . } . Some((_, Err(err))) => { . return Err(err); . } . None => Ok(list), . } 321,096 ( 0.00%) } . . #[derive(Copy, Clone, Debug, HashStable, TyEncodable, TyDecodable)] . pub struct AlwaysRequiresDrop; . . /// Normalizes all opaque types in the given value, replacing them . /// with their underlying types. 156 ( 0.00%) pub fn normalize_opaque_types<'tcx>( . tcx: TyCtxt<'tcx>, . val: &'tcx List>, . ) -> &'tcx List> { 273 ( 0.00%) let mut visitor = OpaqueTypeExpander { . seen_opaque_tys: FxHashSet::default(), . expanded_cache: FxHashMap::default(), . primary_def_id: None, . found_recursion: false, . found_any_recursion: false, . check_recursion: false, . tcx, . }; . val.fold_with(&mut visitor) 195 ( 0.00%) } . . pub fn provide(providers: &mut ty::query::Providers) { 2 ( 0.00%) *providers = ty::query::Providers { normalize_opaque_types, ..*providers } . } 6,539,964 ( 0.09%) -------------------------------------------------------------------------------- -- 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)] 85,045,466 ( 1.21%) 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 366 ---------------------------------------- . let mut tmp = MaybeUninit::::uninit(); . . // Perform the swap . // SAFETY: the caller must guarantee that `x` and `y` are . // valid for writes and properly aligned. `tmp` cannot be . // overlapping either `x` or `y` because `tmp` was just allocated . // on the stack as a separate allocated object. . unsafe { 38 ( 0.00%) copy_nonoverlapping(x, tmp.as_mut_ptr(), 1); 38 ( 0.00%) copy(y, x, 1); // `x` and `y` may overlap . copy_nonoverlapping(tmp.as_ptr(), y, 1); . } . } . . /// Swaps `count * size_of::()` bytes between the two regions of memory . /// beginning at `x` and `y`. The two regions must *not* overlap. . /// . /// # Safety -- line 383 ---------------------------------------- -- line 448 ---------------------------------------- . return; . } . } . . // Direct swapping, for the cases not going through the block optimization. . // SAFETY: the caller must guarantee that `x` and `y` are valid . // for writes, properly aligned, and non-overlapping. . unsafe { 236 ( 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 { 945,994 ( 0.01%) copy_nonoverlapping(src, tmp.as_mut_ptr(), 1); 8,716,780 ( 0.12%) 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 { 58,875,886 ( 0.84%) 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. 11,667 ( 0.00%) return wrapping_sub( 40,952 ( 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 { 2,306,152 ( 0.03%) 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 ---------------------------------------- 7,694,444 ( 0.11%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cell.rs -------------------------------------------------------------------------------- Ir -- line 346 ---------------------------------------- . /// . /// let c = Cell::new(5); . /// . /// c.set(10); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn set(&self, val: T) { 698 ( 0.00%) let old = self.replace(val); 1,612 ( 0.00%) drop(old); . } . . /// Swaps the values of two `Cell`s. . /// Difference with `std::mem::swap` is that this function doesn't require `&mut` reference. . /// . /// # Examples . /// . /// ``` -- line 363 ---------------------------------------- -- line 434 ---------------------------------------- . /// . /// let five = c.get(); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn get(&self) -> T { . // SAFETY: This can cause data races if called from a separate thread, . // but `Cell` is `!Sync` so this won't happen. 127,242 ( 0.00%) unsafe { *self.value.get() } . } . . /// Updates the contained value using a function and returns the new value. . /// . /// # Examples . /// . /// ``` . /// #![feature(cell_update)] -- line 450 ---------------------------------------- -- line 689 ---------------------------------------- . . #[inline(always)] . fn is_writing(x: BorrowFlag) -> bool { . x < UNUSED . } . . #[inline(always)] . fn is_reading(x: BorrowFlag) -> bool { 961,420 ( 0.01%) x > UNUSED . } . . impl RefCell { . /// Creates a new `RefCell` containing `value`. . /// . /// # Examples . /// . /// ``` -- line 705 ---------------------------------------- -- line 706 ---------------------------------------- . /// use std::cell::RefCell; . /// . /// let c = RefCell::new(5); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_refcell_new", since = "1.24.0")] . #[inline] . pub const fn new(value: T) -> RefCell { 1,430,999 ( 0.02%) RefCell { 593,319 ( 0.01%) value: UnsafeCell::new(value), . borrow: Cell::new(UNUSED), . #[cfg(feature = "debug_refcell")] . borrowed_at: Cell::new(None), . } . } . . /// Consumes the `RefCell`, returning the wrapped value. . /// -- line 723 ---------------------------------------- -- line 731 ---------------------------------------- . /// let five = c.into_inner(); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_cell_into_inner", issue = "78729")] . #[inline] . pub const fn into_inner(self) -> T { . // Since this function takes `self` (the `RefCell`) by value, the . // compiler statically verifies that it is not currently borrowed. 2,468 ( 0.00%) self.value.into_inner() . } . . /// Replaces the wrapped value with a new one, returning the old value, . /// without deinitializing either one. . /// . /// This function corresponds to [`std::mem::replace`](../mem/fn.replace.html). . /// . /// # Panics -- line 747 ---------------------------------------- -- line 845 ---------------------------------------- . /// let c = RefCell::new(5); . /// . /// let m = c.borrow_mut(); . /// let b = c.borrow(); // this causes a panic . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . #[track_caller] 2,860 ( 0.00%) pub fn borrow(&self) -> Ref<'_, T> { . self.try_borrow().expect("already mutably borrowed") 8,580 ( 0.00%) } . . /// Immutably borrows the wrapped value, returning an error if the value is currently mutably . /// borrowed. . /// . /// The borrow lasts until the returned `Ref` exits scope. Multiple immutable borrows can be . /// taken out at the same time. . /// . /// This is the non-panicking variant of [`borrow`](#method.borrow). -- line 863 ---------------------------------------- -- line 937 ---------------------------------------- . /// let c = RefCell::new(5); . /// let m = c.borrow(); . /// . /// let b = c.borrow_mut(); // this causes a panic . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . #[track_caller] 14,000 ( 0.00%) pub fn borrow_mut(&self) -> RefMut<'_, T> { . self.try_borrow_mut().expect("already borrowed") 42,000 ( 0.00%) } . . /// Mutably borrows the wrapped value, returning an error if the value is currently borrowed. . /// . /// The borrow lasts until the returned `RefMut` or all `RefMut`s derived . /// from it exit scope. The value cannot be borrowed while this borrow is . /// active. . /// . /// This is the non-panicking variant of [`borrow_mut`](#method.borrow_mut). -- line 955 ---------------------------------------- -- line 975 ---------------------------------------- . match BorrowRefMut::new(&self.borrow) { . Some(b) => { . #[cfg(feature = "debug_refcell")] . { . self.borrowed_at.set(Some(crate::panic::Location::caller())); . } . . // SAFETY: `BorrowRef` guarantees unique access. 543 ( 0.00%) Ok(RefMut { value: unsafe { &mut *self.value.get() }, borrow: b }) . } . None => Err(BorrowMutError { . // If a borrow occurred, then we must already have an outstanding borrow, . // so `borrowed_at` will be `Some` . #[cfg(feature = "debug_refcell")] . location: self.borrowed_at.get().unwrap(), . }), . } -- line 991 ---------------------------------------- -- line 1254 ---------------------------------------- . . struct BorrowRef<'b> { . borrow: &'b Cell, . } . . impl<'b> BorrowRef<'b> { . #[inline] . fn new(borrow: &'b Cell) -> Option> { 1,192,744 ( 0.02%) let b = borrow.get().wrapping_add(1); 776,841 ( 0.01%) if !is_reading(b) { . // Incrementing borrow can result in a non-reading value (<= 0) in these cases: . // 1. It was < 0, i.e. there are writing borrows, so we can't allow a read borrow . // due to Rust's reference aliasing rules . // 2. It was isize::MAX (the max amount of reading borrows) and it overflowed . // into isize::MIN (the max amount of writing borrows) so we can't allow . // an additional read borrow because isize can't represent so many read borrows . // (this can only happen if you mem::forget more than a small constant amount of . // `Ref`s, which is not good practice) -- line 1271 ---------------------------------------- -- line 1279 ---------------------------------------- . Some(BorrowRef { borrow }) . } . } . } . . impl Drop for BorrowRef<'_> { . #[inline] . fn drop(&mut self) { 700,334 ( 0.01%) let borrow = self.borrow.get(); . debug_assert!(is_reading(borrow)); 1,403,965 ( 0.02%) self.borrow.set(borrow - 1); . } . } . . impl Clone for BorrowRef<'_> { . #[inline] . fn clone(&self) -> Self { . // Since this Ref exists, we know the borrow flag . // is a reading borrow. -- line 1297 ---------------------------------------- -- line 1645 ---------------------------------------- . . struct BorrowRefMut<'b> { . borrow: &'b Cell, . } . . impl Drop for BorrowRefMut<'_> { . #[inline] . fn drop(&mut self) { 6,105,728 ( 0.09%) let borrow = self.borrow.get(); . debug_assert!(is_writing(borrow)); 12,143,591 ( 0.17%) self.borrow.set(borrow + 1); . } . } . . impl<'b> BorrowRefMut<'b> { . #[inline] . fn new(borrow: &'b Cell) -> Option> { . // NOTE: Unlike BorrowRefMut::clone, new is called to create the initial . // mutable reference, and so there must currently be no existing . // references. Thus, while clone increments the mutable refcount, here . // we explicitly only allow going from UNUSED to UNUSED - 1. 14,154,275 ( 0.20%) match borrow.get() { . UNUSED => { . borrow.set(UNUSED - 1); . Some(BorrowRefMut { borrow }) . } . _ => None, . } . } . -- line 1674 ---------------------------------------- -- line 1711 ---------------------------------------- . self.value . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl DerefMut for RefMut<'_, T> { . #[inline] . fn deref_mut(&mut self) -> &mut T { 521 ( 0.00%) self.value . } . } . . #[unstable(feature = "coerce_unsized", issue = "27732")] . impl<'b, T: ?Sized + Unsize, U: ?Sized> CoerceUnsized> for RefMut<'b, T> {} . . #[stable(feature = "std_guard_impls", since = "1.20.0")] . impl fmt::Display for RefMut<'_, T> { -- line 1727 ---------------------------------------- -- line 1909 ---------------------------------------- . /// ``` . #[inline(always)] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_unsafecell_get", since = "1.32.0")] . pub const fn get(&self) -> *mut T { . // We can just cast the pointer from `UnsafeCell` to `T` because of . // #[repr(transparent)]. This exploits libstd's special status, there is . // no guarantee for user code that this will work in future versions of the compiler! 7,845,556 ( 0.11%) self as *const UnsafeCell as *const T as *mut T . } . . /// Returns a mutable reference to the underlying data. . /// . /// This call borrows the `UnsafeCell` mutably (at compile-time) which . /// guarantees that we possess the only reference. . /// . /// # Examples -- line 1925 ---------------------------------------- 11,995,249 ( 0.17%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lint/src/early.rs -------------------------------------------------------------------------------- Ir -- line 34 ---------------------------------------- . }) } . . pub struct EarlyContextAndPass<'a, T: EarlyLintPass> { . context: EarlyContext<'a>, . pass: T, . } . . impl<'a, T: EarlyLintPass> EarlyContextAndPass<'a, T> { 2,789,442 ( 0.04%) fn check_id(&mut self, id: ast::NodeId) { 2,170,462 ( 0.03%) for early_lint in self.context.buffered.take(id) { 260 ( 0.00%) let BufferedEarlyLint { span, msg, node_id: _, lint_id, diagnostic } = early_lint; . self.context.lookup_with_diagnostics( . lint_id.lint, 65 ( 0.00%) Some(span), . |lint| lint.build(&msg).emit(), 650 ( 0.00%) diagnostic, . ); . } 2,479,504 ( 0.04%) } . . /// Merge the lints specified by any lint attributes into the . /// current lint context, call the provided function, then reset the . /// lints in effect to their previous state. . fn with_lint_attrs(&mut self, id: ast::NodeId, attrs: &'a [ast::Attribute], f: F) . where . F: FnOnce(&mut Self), . { . let is_crate_node = id == ast::CRATE_NODE_ID; 2,056,907 ( 0.03%) let push = self.context.builder.push(attrs, is_crate_node); 882,381 ( 0.01%) self.check_id(id); . self.enter_attrs(attrs); . f(self); . self.exit_attrs(attrs); 3,190,748 ( 0.05%) self.context.builder.pop(push); . } . . fn enter_attrs(&mut self, attrs: &'a [ast::Attribute]) { . debug!("early context: enter_attrs({:?})", attrs); 1,618,145 ( 0.02%) run_early_pass!(self, enter_lint_attrs, attrs); . } . . fn exit_attrs(&mut self, attrs: &'a [ast::Attribute]) { . debug!("early context: exit_attrs({:?})", attrs); 1,469,018 ( 0.02%) run_early_pass!(self, exit_lint_attrs, attrs); . } . } . . impl<'a, T: EarlyLintPass> ast_visit::Visitor<'a> for EarlyContextAndPass<'a, T> { . fn visit_param(&mut self, param: &'a ast::Param) { . self.with_lint_attrs(param.id, ¶m.attrs, |cx| { 2,888 ( 0.00%) run_early_pass!(cx, check_param, param); 2,166 ( 0.00%) ast_visit::walk_param(cx, param); . }); . } . . fn visit_item(&mut self, it: &'a ast::Item) { 820 ( 0.00%) self.with_lint_attrs(it.id, &it.attrs, |cx| { 3,280 ( 0.00%) run_early_pass!(cx, check_item, it); 2,460 ( 0.00%) ast_visit::walk_item(cx, it); 3,280 ( 0.00%) run_early_pass!(cx, check_item_post, it); . }) . } . . fn visit_foreign_item(&mut self, it: &'a ast::ForeignItem) { . self.with_lint_attrs(it.id, &it.attrs, |cx| { . run_early_pass!(cx, check_foreign_item, it); . ast_visit::walk_foreign_item(cx, it); . run_early_pass!(cx, check_foreign_item_post, it); . }) . } . . fn visit_pat(&mut self, p: &'a ast::Pat) { 8,998 ( 0.00%) run_early_pass!(self, check_pat, p); 6,108 ( 0.00%) self.check_id(p.id); 6,108 ( 0.00%) ast_visit::walk_pat(self, p); 7,910 ( 0.00%) run_early_pass!(self, check_pat_post, p); . } . . fn visit_anon_const(&mut self, c: &'a ast::AnonConst) { . run_early_pass!(self, check_anon_const, c); . self.check_id(c.id); . ast_visit::walk_anon_const(self, c); . } . 2,588,400 ( 0.04%) fn visit_expr(&mut self, e: &'a ast::Expr) { 287,786 ( 0.00%) self.with_lint_attrs(e.id, &e.attrs, |cx| { 1,151,144 ( 0.02%) run_early_pass!(cx, check_expr, e); 863,358 ( 0.01%) ast_visit::walk_expr(cx, e); . }) . } . . fn visit_expr_field(&mut self, f: &'a ast::ExprField) { . self.with_lint_attrs(f.id, &f.attrs, |cx| { . ast_visit::walk_expr_field(cx, f); . }) . } . 15,939 ( 0.00%) fn visit_stmt(&mut self, s: &'a ast::Stmt) { . // Add the statement's lint attributes to our . // current state when checking the statement itself. . // This allows us to handle attributes like . // `#[allow(unused_doc_comments)]`, which apply to . // sibling attributes on the same target . // . // Note that statements get their attributes from . // the AST struct that they wrap (e.g. an item) 8,855 ( 0.00%) self.with_lint_attrs(s.id, s.attrs(), |cx| { 7,084 ( 0.00%) run_early_pass!(cx, check_stmt, s); 5,313 ( 0.00%) cx.check_id(s.id); . }); . // The visitor for the AST struct wrapped . // by the statement (e.g. `Item`) will call . // `with_lint_attrs`, so do this walk . // outside of the above `with_lint_attrs` call 17,710 ( 0.00%) ast_visit::walk_stmt(self, s); . } . . fn visit_fn(&mut self, fk: ast_visit::FnKind<'a>, span: Span, id: ast::NodeId) { 9,199 ( 0.00%) run_early_pass!(self, check_fn, fk, span, id); 1,851 ( 0.00%) self.check_id(id); 6,673 ( 0.00%) ast_visit::walk_fn(self, fk, span); . . // Explicitly check for lints associated with 'closure_id', since . // it does not have a corresponding AST node . if let ast_visit::FnKind::Fn(_, _, sig, _, _) = fk { 998 ( 0.00%) if let ast::Async::Yes { closure_id, .. } = sig.header.asyncness { . self.check_id(closure_id); . } . } 8,721 ( 0.00%) run_early_pass!(self, check_fn_post, fk, span, id); . } . . fn visit_variant_data(&mut self, s: &'a ast::VariantData) { 300 ( 0.00%) run_early_pass!(self, check_struct_def, s); 288 ( 0.00%) if let Some(ctor_hir_id) = s.ctor_id() { 108 ( 0.00%) self.check_id(ctor_hir_id); . } 216 ( 0.00%) ast_visit::walk_struct_def(self, s); 313 ( 0.00%) run_early_pass!(self, check_struct_def_post, s); . } . . fn visit_field_def(&mut self, s: &'a ast::FieldDef) { . self.with_lint_attrs(s.id, &s.attrs, |cx| { 496 ( 0.00%) run_early_pass!(cx, check_field_def, s); 372 ( 0.00%) ast_visit::walk_field_def(cx, s); . }) . } . 423 ( 0.00%) fn visit_variant(&mut self, v: &'a ast::Variant) { 47 ( 0.00%) self.with_lint_attrs(v.id, &v.attrs, |cx| { 188 ( 0.00%) run_early_pass!(cx, check_variant, v); 141 ( 0.00%) ast_visit::walk_variant(cx, v); 188 ( 0.00%) run_early_pass!(cx, check_variant_post, v); . }) . } . . fn visit_ty(&mut self, t: &'a ast::Ty) { 9,795 ( 0.00%) run_early_pass!(self, check_ty, t); 7,467 ( 0.00%) self.check_id(t.id); 16,733 ( 0.00%) ast_visit::walk_ty(self, t); . } . . fn visit_ident(&mut self, ident: Ident) { 57,125 ( 0.00%) run_early_pass!(self, check_ident, ident); . } . . fn visit_local(&mut self, l: &'a ast::Local) { 442 ( 0.00%) self.with_lint_attrs(l.id, &l.attrs, |cx| { 1,768 ( 0.00%) run_early_pass!(cx, check_local, l); 1,326 ( 0.00%) ast_visit::walk_local(cx, l); . }) . } . . fn visit_block(&mut self, b: &'a ast::Block) { 4,564 ( 0.00%) run_early_pass!(self, check_block, b); 2,982 ( 0.00%) self.check_id(b.id); . ast_visit::walk_block(self, b); 6,167 ( 0.00%) run_early_pass!(self, check_block_post, b); . } . . fn visit_arm(&mut self, a: &'a ast::Arm) { . self.with_lint_attrs(a.id, &a.attrs, |cx| { 992 ( 0.00%) run_early_pass!(cx, check_arm, a); 744 ( 0.00%) ast_visit::walk_arm(cx, a); . }) . } . . fn visit_expr_post(&mut self, e: &'a ast::Expr) { 1,296,247 ( 0.02%) run_early_pass!(self, check_expr_post, e); . . // Explicitly check for lints associated with 'closure_id', since . // it does not have a corresponding AST node 1,439,006 ( 0.02%) match e.kind { . ast::ExprKind::Closure(_, ast::Async::Yes { closure_id, .. }, ..) . | ast::ExprKind::Async(_, closure_id, ..) => self.check_id(closure_id), . _ => {} . } . } . . fn visit_generic_arg(&mut self, arg: &'a ast::GenericArg) { 3,240 ( 0.00%) run_early_pass!(self, check_generic_arg, arg); 2,430 ( 0.00%) ast_visit::walk_generic_arg(self, arg); . } . . fn visit_generic_param(&mut self, param: &'a ast::GenericParam) { 1,276 ( 0.00%) run_early_pass!(self, check_generic_param, param); 1,276 ( 0.00%) ast_visit::walk_generic_param(self, param); . } . . fn visit_generics(&mut self, g: &'a ast::Generics) { 3,452 ( 0.00%) run_early_pass!(self, check_generics, g); . ast_visit::walk_generics(self, g); . } . . fn visit_where_predicate(&mut self, p: &'a ast::WherePredicate) { 168 ( 0.00%) run_early_pass!(self, check_where_predicate, p); 168 ( 0.00%) ast_visit::walk_where_predicate(self, p); . } . . fn visit_poly_trait_ref(&mut self, t: &'a ast::PolyTraitRef, m: &'a ast::TraitBoundModifier) { 780 ( 0.00%) run_early_pass!(self, check_poly_trait_ref, t, m); 163 ( 0.00%) ast_visit::walk_poly_trait_ref(self, t, m); . } . . fn visit_assoc_item(&mut self, item: &'a ast::AssocItem, ctxt: ast_visit::AssocCtxt) { 344 ( 0.00%) self.with_lint_attrs(item.id, &item.attrs, |cx| match ctxt { . ast_visit::AssocCtxt::Trait => { 8 ( 0.00%) run_early_pass!(cx, check_trait_item, item); 8 ( 0.00%) ast_visit::walk_assoc_item(cx, item, ctxt); 9 ( 0.00%) run_early_pass!(cx, check_trait_item_post, item); . } . ast_visit::AssocCtxt::Impl => { 1,368 ( 0.00%) run_early_pass!(cx, check_impl_item, item); 1,368 ( 0.00%) ast_visit::walk_assoc_item(cx, item, ctxt); 1,710 ( 0.00%) run_early_pass!(cx, check_impl_item_post, item); . } . }); . } . . fn visit_lifetime(&mut self, lt: &'a ast::Lifetime) { 1,466 ( 0.00%) run_early_pass!(self, check_lifetime, lt); 2,767 ( 0.00%) self.check_id(lt.id); . } . . fn visit_path(&mut self, p: &'a ast::Path, id: ast::NodeId) { 37,427 ( 0.00%) run_early_pass!(self, check_path, p, id); 22,406 ( 0.00%) self.check_id(id); . ast_visit::walk_path(self, p); . } . . fn visit_attribute(&mut self, attr: &'a ast::Attribute) { 13,516 ( 0.00%) run_early_pass!(self, check_attribute, attr); . } . . fn visit_mac_def(&mut self, mac: &'a ast::MacroDef, id: ast::NodeId) { 28 ( 0.00%) run_early_pass!(self, check_mac_def, mac, id); 32 ( 0.00%) self.check_id(id); . } . . fn visit_mac_call(&mut self, mac: &'a ast::MacCall) { 740 ( 0.00%) run_early_pass!(self, check_mac, mac); . ast_visit::walk_mac(self, mac); . } . } . . struct EarlyLintPassObjects<'a> { . lints: &'a mut [EarlyLintPassObject], . } . -- line 302 ---------------------------------------- -- line 337 ---------------------------------------- . fn check<'b>(self, cx: &mut EarlyContextAndPass<'b, impl EarlyLintPass>) . where . 'a: 'b; . } . . impl<'a> EarlyCheckNode<'a> for &'a ast::Crate { . fn id(self) -> ast::NodeId { . ast::CRATE_NODE_ID 4 ( 0.00%) } . fn attrs<'b>(self) -> &'b [ast::Attribute] . where . 'a: 'b, . { . &self.attrs 2 ( 0.00%) } . fn check<'b>(self, cx: &mut EarlyContextAndPass<'b, impl EarlyLintPass>) . where . 'a: 'b, . { 6 ( 0.00%) run_early_pass!(cx, check_crate, self); 3 ( 0.00%) ast_visit::walk_crate(cx, self); 6 ( 0.00%) run_early_pass!(cx, check_crate_post, self); . } . } . . impl<'a> EarlyCheckNode<'a> for (ast::NodeId, &'a [ast::Attribute], &'a [P]) { . fn id(self) -> ast::NodeId { 18 ( 0.00%) self.0 18 ( 0.00%) } . fn attrs<'b>(self) -> &'b [ast::Attribute] . where . 'a: 'b, . { 36 ( 0.00%) self.1 18 ( 0.00%) } 162 ( 0.00%) fn check<'b>(self, cx: &mut EarlyContextAndPass<'b, impl EarlyLintPass>) . where . 'a: 'b, . { . walk_list!(cx, visit_attribute, self.1); 18 ( 0.00%) walk_list!(cx, visit_item, self.2); 144 ( 0.00%) } . } . . fn early_lint_node<'a>( . sess: &Session, . warn_about_weird_lints: bool, . lint_store: &LintStore, . registered_tools: &RegisteredTools, . buffered: LintBuffer, . pass: impl EarlyLintPass, . check_node: impl EarlyCheckNode<'a>, . ) -> LintBuffer { 16 ( 0.00%) let mut cx = EarlyContextAndPass { 121 ( 0.00%) context: EarlyContext::new( . sess, . warn_about_weird_lints, . lint_store, . registered_tools, 80 ( 0.00%) buffered, . ), 4 ( 0.00%) pass, . }; . 456 ( 0.00%) cx.with_lint_attrs(check_node.id(), check_node.attrs(), |cx| check_node.check(cx)); 80 ( 0.00%) cx.context.buffered . } . 220 ( 0.00%) pub fn check_ast_node<'a>( . sess: &Session, . pre_expansion: bool, . lint_store: &LintStore, . registered_tools: &RegisteredTools, . lint_buffer: Option, . builtin_lints: impl EarlyLintPass, . check_node: impl EarlyCheckNode<'a>, . ) { . let passes = 120 ( 0.00%) if pre_expansion { &lint_store.pre_expansion_passes } else { &lint_store.early_passes }; . let mut passes: Vec<_> = passes.iter().map(|p| (p)()).collect(); 20 ( 0.00%) let mut buffered = lint_buffer.unwrap_or_default(); . 40 ( 0.00%) if !sess.opts.debugging_opts.no_interleave_lints { 80 ( 0.00%) buffered = early_lint_node( . sess, . pre_expansion, . lint_store, . registered_tools, . buffered, 4 ( 0.00%) builtin_lints, . check_node, . ); . 20 ( 0.00%) if !passes.is_empty() { . buffered = early_lint_node( . sess, . false, . lint_store, . registered_tools, . buffered, . EarlyLintPassObjects { lints: &mut passes[..] }, . check_node, -- line 438 ---------------------------------------- -- line 453 ---------------------------------------- . ) . }); . } . } . . // All of the buffered lints should have been emitted at this point. . // If not, that means that we somehow buffered a lint for a node id . // that was not lint-checked (perhaps it doesn't exist?). This is a bug. 220 ( 0.00%) for (id, lints) in buffered.map { . for early_lint in lints { . sess.delay_span_bug( . early_lint.span, . &format!( . "failed to process buffered lint here (dummy = {})", . id == ast::DUMMY_NODE_ID . ), . ); . } . } 162 ( 0.00%) } 3,665 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/mem_categorization.rs -------------------------------------------------------------------------------- Ir -- line 67 ---------------------------------------- . . crate trait HirNode { . fn hir_id(&self) -> hir::HirId; . fn span(&self) -> Span; . } . . impl HirNode for hir::Expr<'_> { . fn hir_id(&self) -> hir::HirId { 836 ( 0.00%) self.hir_id . } . fn span(&self) -> Span { . self.span . } . } . . impl HirNode for hir::Pat<'_> { . fn hir_id(&self) -> hir::HirId { -- line 83 ---------------------------------------- -- line 96 ---------------------------------------- . body_owner: LocalDefId, . upvars: Option<&'tcx FxIndexMap>, . } . . crate type McResult = Result; . . impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> { . /// Creates a `MemCategorizationContext`. 1,373,715 ( 0.02%) crate fn new( . infcx: &'a InferCtxt<'a, 'tcx>, . param_env: ty::ParamEnv<'tcx>, . body_owner: LocalDefId, . typeck_results: &'a ty::TypeckResults<'tcx>, . ) -> MemCategorizationContext<'a, 'tcx> { 763,175 ( 0.01%) MemCategorizationContext { . typeck_results, . infcx, . param_env, . body_owner, 152,635 ( 0.00%) upvars: infcx.tcx.upvars_mentioned(body_owner), . } 1,373,715 ( 0.02%) } . . crate fn tcx(&self) -> TyCtxt<'tcx> { 493 ( 0.00%) self.infcx.tcx . } . . crate fn type_is_copy_modulo_regions(&self, ty: Ty<'tcx>, span: Span) -> bool { 760 ( 0.00%) self.infcx.type_is_copy_modulo_regions(self.param_env, ty, span) . } . . fn resolve_vars_if_possible(&self, value: T) -> T . where . T: TypeFoldable<'tcx>, . { . self.infcx.resolve_vars_if_possible(value) . } . . fn is_tainted_by_errors(&self) -> bool { . self.infcx.is_tainted_by_errors() . } . 3,300 ( 0.00%) fn resolve_type_vars_or_error( . &self, . id: hir::HirId, . ty: Option>, . ) -> McResult> { 297,078 ( 0.00%) match ty { . Some(ty) => { . let ty = self.resolve_vars_if_possible(ty); 298,178 ( 0.00%) if ty.references_error() || ty.is_ty_var() { . debug!("resolve_type_vars_or_error: error from {:?}", ty); . Err(()) . } else { . Ok(ty) . } . } . // FIXME . None if self.is_tainted_by_errors() => Err(()), -- line 154 ---------------------------------------- -- line 155 ---------------------------------------- . None => { . bug!( . "no type for node {}: {} in mem_categorization", . id, . self.tcx().hir().node_to_string(id) . ); . } . } 2,750 ( 0.00%) } . . crate fn node_ty(&self, hir_id: hir::HirId) -> McResult> { 3,960 ( 0.00%) self.resolve_type_vars_or_error(hir_id, self.typeck_results.node_type_opt(hir_id)) . } . . fn expr_ty(&self, expr: &hir::Expr<'_>) -> McResult> { 1,332,506 ( 0.02%) self.resolve_type_vars_or_error(expr.hir_id, self.typeck_results.expr_ty_opt(expr)) . } . . crate fn expr_ty_adjusted(&self, expr: &hir::Expr<'_>) -> McResult> { 605 ( 0.00%) self.resolve_type_vars_or_error(expr.hir_id, self.typeck_results.expr_ty_adjusted_opt(expr)) . } . . /// Returns the type of value that this pattern matches against. . /// Some non-obvious cases: . /// . /// - a `ref x` binding matches against a value of type `T` and gives . /// `x` the type `&T`; we return `T`. . /// - a pattern with implicit derefs (thanks to default binding . /// modes #42640) may look like `Some(x)` but in fact have . /// implicit deref patterns attached (e.g., it is really . /// `&Some(x)`). In that case, we return the "outermost" type . /// (e.g., `&Option). 3,072 ( 0.00%) crate fn pat_ty_adjusted(&self, pat: &hir::Pat<'_>) -> McResult> { . // Check for implicit `&` types wrapping the pattern; note . // that these are never attached to binding patterns, so . // actually this is somewhat "disjoint" from the code below . // that aims to account for `ref x`. 4,992 ( 0.00%) if let Some(vec) = self.typeck_results.pat_adjustments().get(pat.hir_id) { . if let Some(first_ty) = vec.first() { . debug!("pat_ty(pat={:?}) found adjusted ty `{:?}`", pat, first_ty); . return Ok(first_ty); . } . } . . self.pat_ty_unadjusted(pat) 3,072 ( 0.00%) } . . /// Like `pat_ty`, but ignores implicit `&` patterns. . fn pat_ty_unadjusted(&self, pat: &hir::Pat<'_>) -> McResult> { 768 ( 0.00%) let base_ty = self.node_ty(pat.hir_id)?; . debug!("pat_ty(pat={:?}) base_ty={:?}", pat, base_ty); . . // This code detects whether we are looking at a `ref x`, . // and if so, figures out what the type *being borrowed* is. 768 ( 0.00%) let ret_ty = match pat.kind { . PatKind::Binding(..) => { 2,160 ( 0.00%) let bm = *self . .typeck_results . .pat_binding_modes() . .get(pat.hir_id) . .expect("missing binding mode"); . 540 ( 0.00%) if let ty::BindByReference(_) = bm { . // a bind-by-ref means that the base_ty will be the type of the ident itself, . // but what we want here is the type of the underlying value being borrowed. . // So peel off one-level, turning the &T into T. 850 ( 0.00%) match base_ty.builtin_deref(false) { . Some(t) => t.ty, . None => { . debug!("By-ref binding of non-derefable type {:?}", base_ty); . return Err(()); . } . } . } else { . base_ty -- line 229 ---------------------------------------- -- line 231 ---------------------------------------- . } . _ => base_ty, . }; . debug!("pat_ty(pat={:?}) ret_ty={:?}", pat, ret_ty); . . Ok(ret_ty) . } . 5,950 ( 0.00%) crate fn cat_expr(&self, expr: &hir::Expr<'_>) -> McResult> { . // This recursion helper avoids going through *too many* . // adjustments, since *only* non-overloaded deref recurses. . fn helper<'a, 'tcx>( . mc: &MemCategorizationContext<'a, 'tcx>, . expr: &hir::Expr<'_>, . adjustments: &[adjustment::Adjustment<'tcx>], . ) -> McResult> { 4,628 ( 0.00%) match adjustments.split_last() { 5,331 ( 0.00%) None => mc.cat_expr_unadjusted(expr), . Some((adjustment, previous)) => { 3,722 ( 0.00%) mc.cat_expr_adjusted_with(expr, || helper(mc, expr, previous), adjustment) . } . } . } . 6,914 ( 0.00%) helper(self, expr, self.typeck_results.expr_adjustments(expr)) 5,100 ( 0.00%) } . 49,324 ( 0.00%) crate fn cat_expr_adjusted( . &self, . expr: &hir::Expr<'_>, . previous: PlaceWithHirId<'tcx>, . adjustment: &adjustment::Adjustment<'tcx>, . ) -> McResult> { 35,872 ( 0.00%) self.cat_expr_adjusted_with(expr, || Ok(previous), adjustment) 40,356 ( 0.00%) } . 4,125 ( 0.00%) fn cat_expr_adjusted_with( . &self, . expr: &hir::Expr<'_>, . previous: F, . adjustment: &adjustment::Adjustment<'tcx>, . ) -> McResult> . where . F: FnOnce() -> McResult>, . { . debug!("cat_expr_adjusted_with({:?}): {:?}", adjustment, expr); 9,343 ( 0.00%) let target = self.resolve_vars_if_possible(adjustment.target); 9,718 ( 0.00%) match adjustment.kind { 2,144 ( 0.00%) adjustment::Adjust::Deref(overloaded) => { . // Equivalent to *expr or something similar. 6,096 ( 0.00%) let base = if let Some(deref) = overloaded { . let ref_ty = self . .tcx() 50 ( 0.00%) .mk_ref(deref.region, ty::TypeAndMut { ty: target, mutbl: deref.mutbl }); 50 ( 0.00%) self.cat_rvalue(expr.hir_id, expr.span, ref_ty) . } else { 19,174 ( 0.00%) previous()? . }; 40,686 ( 0.00%) self.cat_deref(expr, base) . } . . adjustment::Adjust::NeverToAny . | adjustment::Adjust::Pointer(_) . | adjustment::Adjust::Borrow(_) => { . // Result is an rvalue. 29,865 ( 0.00%) Ok(self.cat_rvalue(expr.hir_id, expr.span, target)) . } . } 4,433 ( 0.00%) } . 1,331,901 ( 0.02%) crate fn cat_expr_unadjusted(&self, expr: &hir::Expr<'_>) -> McResult> { . debug!("cat_expr: id={} expr={:?}", expr.hir_id, expr); . . let expr_ty = self.expr_ty(expr)?; 740,829 ( 0.01%) match expr.kind { . hir::ExprKind::Unary(hir::UnOp::Deref, ref e_base) => { 2,180 ( 0.00%) if self.typeck_results.is_method_call(expr) { . self.cat_overloaded_place(expr, e_base) . } else { 1,728 ( 0.00%) let base = self.cat_expr(e_base)?; 4,752 ( 0.00%) self.cat_deref(expr, base) . } . } . . hir::ExprKind::Field(ref base, _) => { 2,090 ( 0.00%) let base = self.cat_expr(base)?; . debug!("cat_expr(cat_field): id={} expr={:?} base={:?}", expr.hir_id, expr, base); . 2,090 ( 0.00%) let field_idx = self . .typeck_results . .field_indices() 1,254 ( 0.00%) .get(expr.hir_id) . .cloned() . .expect("Field index not found"); . 836 ( 0.00%) Ok(self.cat_projection( . expr, 3,344 ( 0.00%) base, . expr_ty, . ProjectionKind::Field(field_idx as u32, VariantIdx::new(0)), . )) . } . . hir::ExprKind::Index(ref base, _) => { 255 ( 0.00%) if self.typeck_results.is_method_call(expr) { . // If this is an index implemented by a method call, then it . // will include an implicit deref of the result. . // The call to index() returns a `&T` value, which . // is an rvalue. That is what we will be . // dereferencing. . self.cat_overloaded_place(expr, base) . } else { . let base = self.cat_expr(base)?; . Ok(self.cat_projection(expr, base, expr_ty, ProjectionKind::Index)) . } . } . 3,295 ( 0.00%) hir::ExprKind::Path(ref qpath) => { 16,475 ( 0.00%) let res = self.typeck_results.qpath_res(qpath, expr.hir_id); 46,130 ( 0.00%) self.cat_res(expr.hir_id, expr.span, expr_ty, res) . } . . hir::ExprKind::Type(ref e, _) => self.cat_expr(e), . . hir::ExprKind::AddrOf(..) . | hir::ExprKind::Call(..) . | hir::ExprKind::Assign(..) . | hir::ExprKind::AssignOp(..) -- line 358 ---------------------------------------- -- line 374 ---------------------------------------- . | hir::ExprKind::Lit(..) . | hir::ExprKind::ConstBlock(..) . | hir::ExprKind::Break(..) . | hir::ExprKind::Continue(..) . | hir::ExprKind::Struct(..) . | hir::ExprKind::Repeat(..) . | hir::ExprKind::InlineAsm(..) . | hir::ExprKind::Box(..) 1,006,523 ( 0.01%) | hir::ExprKind::Err => Ok(self.cat_rvalue(expr.hir_id, expr.span, expr_ty)), . } 1,331,901 ( 0.02%) } . 36,553 ( 0.00%) crate fn cat_res( . &self, . hir_id: hir::HirId, . span: Span, . expr_ty: Ty<'tcx>, . res: Res, . ) -> McResult> { . debug!("cat_res: id={:?} expr={:?} def={:?}", hir_id, expr_ty, res); . 22,389 ( 0.00%) match res { . Res::Def( . DefKind::Ctor(..) . | DefKind::Const . | DefKind::ConstParam . | DefKind::AssocConst . | DefKind::Fn . | DefKind::AssocFn, . _, . ) . | Res::SelfCtor(..) => Ok(self.cat_rvalue(hir_id, span, expr_ty)), . . Res::Def(DefKind::Static, _) => { . Ok(PlaceWithHirId::new(hir_id, expr_ty, PlaceBase::StaticItem, Vec::new())) . } . 9,804 ( 0.00%) Res::Local(var_id) => { 2,503 ( 0.00%) if self.upvars.map_or(false, |upvars| upvars.contains_key(&var_id)) { . self.cat_upvar(hir_id, var_id) . } else { 24,230 ( 0.00%) Ok(PlaceWithHirId::new(hir_id, expr_ty, PlaceBase::Local(var_id), Vec::new())) . } . } . . def => span_bug!(span, "unexpected definition in memory categorization: {:?}", def), . } 26,584 ( 0.00%) } . . /// Categorize an upvar. . /// . /// Note: the actual upvar access contains invisible derefs of closure . /// environment and upvar reference as appropriate. Only regionck cares . /// about these dereferences, so we let it compute them as needed. . fn cat_upvar(&self, hir_id: hir::HirId, var_id: hir::HirId) -> McResult> { 28 ( 0.00%) let closure_expr_def_id = self.body_owner; . . let upvar_id = ty::UpvarId { . var_path: ty::UpvarPath { hir_id: var_id }, . closure_expr_id: closure_expr_def_id, . }; 56 ( 0.00%) let var_ty = self.node_ty(var_id)?; . 392 ( 0.00%) let ret = PlaceWithHirId::new(hir_id, var_ty, PlaceBase::Upvar(upvar_id), Vec::new()); . . debug!("cat_upvar ret={:?}", ret); . Ok(ret) . } . . crate fn cat_rvalue( . &self, . hir_id: hir::HirId, . span: Span, . expr_ty: Ty<'tcx>, . ) -> PlaceWithHirId<'tcx> { . debug!("cat_rvalue hir_id={:?}, expr_ty={:?}, span={:?}", hir_id, expr_ty, span); 888,038 ( 0.01%) let ret = PlaceWithHirId::new(hir_id, expr_ty, PlaceBase::Rvalue, Vec::new()); . debug!("cat_rvalue ret={:?}", ret); . ret . } . 4,598 ( 0.00%) crate fn cat_projection( . &self, . node: &N, . base_place: PlaceWithHirId<'tcx>, . ty: Ty<'tcx>, . kind: ProjectionKind, . ) -> PlaceWithHirId<'tcx> { 2,767 ( 0.00%) let mut projections = base_place.place.projections; 441 ( 0.00%) projections.push(Projection { kind, ty }); 4,477 ( 0.00%) let ret = PlaceWithHirId::new( . node.hir_id(), 418 ( 0.00%) base_place.place.base_ty, 836 ( 0.00%) base_place.place.base, 2,944 ( 0.00%) projections, . ); . debug!("cat_field ret {:?}", ret); . ret 3,344 ( 0.00%) } . 605 ( 0.00%) fn cat_overloaded_place( . &self, . expr: &hir::Expr<'_>, . base: &hir::Expr<'_>, . ) -> McResult> { . debug!("cat_overloaded_place(expr={:?}, base={:?})", expr, base); . . // Reconstruct the output assuming it's a reference with the . // same region and mutability as the receiver. This holds for . // `Deref(Mut)::Deref(_mut)` and `Index(Mut)::index(_mut)`. 110 ( 0.00%) let place_ty = self.expr_ty(expr)?; 110 ( 0.00%) let base_ty = self.expr_ty_adjusted(base)?; . 165 ( 0.00%) let (region, mutbl) = match *base_ty.kind() { 110 ( 0.00%) ty::Ref(region, _, mutbl) => (region, mutbl), . _ => span_bug!(expr.span, "cat_overloaded_place: base is not a reference"), . }; . let ref_ty = self.tcx().mk_ref(region, ty::TypeAndMut { ty: place_ty, mutbl }); . 110 ( 0.00%) let base = self.cat_rvalue(expr.hir_id, expr.span, ref_ty); 770 ( 0.00%) self.cat_deref(expr, base) 440 ( 0.00%) } . 27,090 ( 0.00%) fn cat_deref( . &self, . node: &impl HirNode, . base_place: PlaceWithHirId<'tcx>, . ) -> McResult> { . debug!("cat_deref: base_place={:?}", base_place); . 5,418 ( 0.00%) let base_curr_ty = base_place.place.ty(); 13,545 ( 0.00%) let deref_ty = match base_curr_ty.builtin_deref(true) { . Some(mt) => mt.ty, . None => { . debug!("explicit deref of non-derefable type: {:?}", base_curr_ty); . return Err(()); . } . }; 10,836 ( 0.00%) let mut projections = base_place.place.projections; . projections.push(Projection { kind: ProjectionKind::Deref, ty: deref_ty }); . 13,545 ( 0.00%) let ret = PlaceWithHirId::new( . node.hir_id(), 2,709 ( 0.00%) base_place.place.base_ty, 5,418 ( 0.00%) base_place.place.base, 10,836 ( 0.00%) projections, . ); . debug!("cat_deref ret {:?}", ret); 21,672 ( 0.00%) Ok(ret) 18,963 ( 0.00%) } . . crate fn cat_pattern( . &self, . place: PlaceWithHirId<'tcx>, . pat: &hir::Pat<'_>, . mut op: F, . ) -> McResult<()> . where . F: FnMut(&PlaceWithHirId<'tcx>, &hir::Pat<'_>), . { 11,537 ( 0.00%) self.cat_pattern_(place, pat, &mut op) . } . . /// Returns the variant index for an ADT used within a Struct or TupleStruct pattern . /// Here `pat_hir_id` is the HirId of the pattern itself. 1,992 ( 0.00%) fn variant_index_for_adt( . &self, . qpath: &hir::QPath<'_>, . pat_hir_id: hir::HirId, . span: Span, . ) -> McResult { 1,162 ( 0.00%) let res = self.typeck_results.qpath_res(qpath, pat_hir_id); 664 ( 0.00%) let ty = self.typeck_results.node_type(pat_hir_id); 332 ( 0.00%) let adt_def = match ty.kind() { . ty::Adt(adt_def, _) => adt_def, . _ => { . self.tcx() . .sess . .delay_span_bug(span, "struct or tuple struct pattern not applied to an ADT"); . return Err(()); . } . }; . 1,294 ( 0.00%) match res { 405 ( 0.00%) Res::Def(DefKind::Variant, variant_id) => Ok(adt_def.variant_index_with_id(variant_id)), 132 ( 0.00%) Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_id) => { 198 ( 0.00%) Ok(adt_def.variant_index_with_ctor_id(variant_ctor_id)) . } . Res::Def(DefKind::Ctor(CtorOf::Struct, ..), _) . | Res::Def(DefKind::Struct | DefKind::Union | DefKind::TyAlias | DefKind::AssocTy, _) . | Res::SelfCtor(..) . | Res::SelfTy(..) => { . // Structs and Unions have only have one variant. . Ok(VariantIdx::new(0)) . } . _ => bug!("expected ADT path, found={:?}", res), . } 1,328 ( 0.00%) } . . /// Returns the total number of fields in an ADT variant used within a pattern. . /// Here `pat_hir_id` is the HirId of the pattern itself. . fn total_fields_in_adt_variant( . &self, . pat_hir_id: hir::HirId, . variant_index: VariantIdx, . span: Span, . ) -> McResult { 132 ( 0.00%) let ty = self.typeck_results.node_type(pat_hir_id); 132 ( 0.00%) match ty.kind() { 198 ( 0.00%) ty::Adt(adt_def, _) => Ok(adt_def.variants[variant_index].fields.len()), . _ => { . self.tcx() . .sess . .delay_span_bug(span, "struct or tuple struct pattern not applied to an ADT"); . Err(()) . } . } . } . . /// Returns the total number of fields in a tuple used within a Tuple pattern. . /// Here `pat_hir_id` is the HirId of the pattern itself. . fn total_fields_in_tuple(&self, pat_hir_id: hir::HirId, span: Span) -> McResult { 300 ( 0.00%) let ty = self.typeck_results.node_type(pat_hir_id); 150 ( 0.00%) match ty.kind() { 75 ( 0.00%) ty::Tuple(substs) => Ok(substs.len()), . _ => { . self.tcx().sess.delay_span_bug(span, "tuple pattern not applied to a tuple"); . Err(()) . } . } . } . . // FIXME(#19596) This is a workaround, but there should be a better way to do this 14,685 ( 0.00%) fn cat_pattern_( . &self, . mut place_with_id: PlaceWithHirId<'tcx>, . pat: &hir::Pat<'_>, . op: &mut F, . ) -> McResult<()> . where . F: FnMut(&PlaceWithHirId<'tcx>, &hir::Pat<'_>), . { -- line 615 ---------------------------------------- -- line 649 ---------------------------------------- . // Some(x, ) => { ... }, . // _ => { ... }, . // } . // ``` . // . // Then we see that to get the same result, we must start with . // `deref { deref { place_foo }}` instead of `place_foo` since the pattern is now `Some(x,)` . // and not `&&Some(x,)`, even though its assigned type is that of `&&Some(x,)`. 10,680 ( 0.00%) for _ in 0..self.typeck_results.pat_adjustments().get(pat.hir_id).map_or(0, |v| v.len()) { . debug!("cat_pattern: applying adjustment to place_with_id={:?}", place_with_id); . place_with_id = self.cat_deref(pat, place_with_id)?; . } 17,355 ( 0.00%) let place_with_id = place_with_id; // lose mutability . debug!("cat_pattern: applied adjustment derefs to get place_with_id={:?}", place_with_id); . . // Invoke the callback, but only now, after the `place_with_id` has adjusted. . // . // To see that this makes sense, consider `match &Some(3) { Some(x) => { ... }}`. In that . // case, the initial `place_with_id` will be that for `&Some(3)` and the pattern is `Some(x)`. We . // don't want to call `op` with these incompatible values. As written, what happens instead . // is that `op` is called with the adjusted place (that for `*&Some(3)`) and the pattern . // `Some(x)` (which matches). Recursing once more, `*&Some(3)` and the pattern `Some(x)` . // result in the place `Downcast(*&Some(3)).0` associated to `x` and invoke `op` with . // that (where the `ref` on `x` is implied). . op(&place_with_id, pat); . 9,342 ( 0.00%) match pat.kind { 375 ( 0.00%) PatKind::Tuple(subpats, dots_pos) => { . // (p1, ..., pN) 300 ( 0.00%) let total_fields = self.total_fields_in_tuple(pat.hir_id, pat.span)?; . . for (i, subpat) in subpats.iter().enumerate_and_adjust(total_fields, dots_pos) { 560 ( 0.00%) let subpat_ty = self.pat_ty_adjusted(subpat)?; . let projection_kind = ProjectionKind::Field(i as u32, VariantIdx::new(0)); . let sub_place = 224 ( 0.00%) self.cat_projection(pat, place_with_id.clone(), subpat_ty, projection_kind); 1,680 ( 0.00%) self.cat_pattern_(sub_place, subpat, op)?; . } . } . 396 ( 0.00%) PatKind::TupleStruct(ref qpath, subpats, dots_pos) => { . // S(p1, ..., pN) 660 ( 0.00%) let variant_index = self.variant_index_for_adt(qpath, pat.hir_id, pat.span)?; . let total_fields = 264 ( 0.00%) self.total_fields_in_adt_variant(pat.hir_id, variant_index, pat.span)?; . . for (i, subpat) in subpats.iter().enumerate_and_adjust(total_fields, dots_pos) { 380 ( 0.00%) let subpat_ty = self.pat_ty_adjusted(subpat)?; . let projection_kind = ProjectionKind::Field(i as u32, variant_index); . let sub_place = 152 ( 0.00%) self.cat_projection(pat, place_with_id.clone(), subpat_ty, projection_kind); 1,140 ( 0.00%) self.cat_pattern_(sub_place, subpat, op)?; . } . } . 300 ( 0.00%) PatKind::Struct(ref qpath, field_pats, _) => { . // S { f1: p1, ..., fN: pN } . 999 ( 0.00%) let variant_index = self.variant_index_for_adt(qpath, pat.hir_id, pat.span)?; . . for fp in field_pats { 1,062 ( 0.00%) let field_ty = self.pat_ty_adjusted(fp.pat)?; 1,062 ( 0.00%) let field_index = self . .typeck_results . .field_indices() 354 ( 0.00%) .get(fp.hir_id) . .cloned() . .expect("no index for a field"); . 354 ( 0.00%) let field_place = self.cat_projection( . pat, . place_with_id.clone(), . field_ty, . ProjectionKind::Field(field_index as u32, variant_index), . ); 2,655 ( 0.00%) self.cat_pattern_(field_place, fp.pat, op)?; . } . } . 6 ( 0.00%) PatKind::Or(pats) => { 18 ( 0.00%) for pat in pats { 84 ( 0.00%) self.cat_pattern_(place_with_id.clone(), pat, op)?; . } . } . . PatKind::Binding(.., Some(ref subpat)) => { . self.cat_pattern_(place_with_id, subpat, op)?; . } . . PatKind::Box(ref subpat) | PatKind::Ref(ref subpat, _) => { . // box p1, &p1, &mut p1. we can ignore the mutability of . // PatKind::Ref since that information is already contained . // in the type. 1,170 ( 0.00%) let subplace = self.cat_deref(pat, place_with_id)?; 936 ( 0.00%) self.cat_pattern_(subplace, subpat, op)?; . } . . PatKind::Slice(before, ref slice, after) => { . let element_ty = match place_with_id.place.ty().builtin_index() { . Some(ty) => ty, . None => { . debug!("explicit index of non-indexable type {:?}", place_with_id); . return Err(()); -- line 751 ---------------------------------------- -- line 780 ---------------------------------------- . | PatKind::Lit(..) . | PatKind::Range(..) . | PatKind::Wild => { . // always ok . } . } . . Ok(()) 10,680 ( 0.00%) } . } 1,071,446 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_passes/src/check_attr.rs -------------------------------------------------------------------------------- Ir -- line 23 ---------------------------------------- . use rustc_span::symbol::{sym, Symbol}; . use rustc_span::{MultiSpan, Span, DUMMY_SP}; . use std::collections::hash_map::Entry; . . pub(crate) fn target_from_impl_item<'tcx>( . tcx: TyCtxt<'tcx>, . impl_item: &hir::ImplItem<'_>, . ) -> Target { 1,970 ( 0.00%) match impl_item.kind { . hir::ImplItemKind::Const(..) => Target::AssocConst, . hir::ImplItemKind::Fn(..) => { 1,910 ( 0.00%) let parent_hir_id = tcx.hir().get_parent_item(impl_item.hir_id()); 1,528 ( 0.00%) let containing_item = tcx.hir().expect_item(parent_hir_id); 764 ( 0.00%) let containing_impl_is_for_trait = match &containing_item.kind { . hir::ItemKind::Impl(impl_) => impl_.of_trait.is_some(), . _ => bug!("parent of an ImplItem must be an Impl"), . }; 1,146 ( 0.00%) if containing_impl_is_for_trait { . Target::Method(MethodKind::Trait { body: true }) . } else { . Target::Method(MethodKind::Inherent) . } . } . hir::ImplItemKind::TyAlias(..) => Target::AssocTy, . } . } -- line 48 ---------------------------------------- -- line 54 ---------------------------------------- . } . . struct CheckAttrVisitor<'tcx> { . tcx: TyCtxt<'tcx>, . } . . impl CheckAttrVisitor<'_> { . /// Checks any attribute. 1,474,040 ( 0.02%) fn check_attributes( . &self, . hir_id: HirId, . span: &Span, . target: Target, . item: Option>, . ) { . let mut doc_aliases = FxHashMap::default(); . let mut is_valid = true; 147,404 ( 0.00%) let mut specified_inline = None; . let mut seen = FxHashMap::default(); 1,179,232 ( 0.02%) let attrs = self.tcx.hir().attrs(hir_id); . for attr in attrs { 22,141 ( 0.00%) let attr_is_valid = match attr.name_or_empty() { . sym::inline => self.check_inline(hir_id, attr, span, target), . sym::non_exhaustive => self.check_non_exhaustive(hir_id, attr, span, target), . sym::marker => self.check_marker(hir_id, attr, span, target), . sym::target_feature => self.check_target_feature(hir_id, attr, span, target), . sym::track_caller => { . self.check_track_caller(hir_id, &attr.span, attrs, span, target) . } . sym::doc => self.check_doc_attrs( -- line 83 ---------------------------------------- -- line 116 ---------------------------------------- . sym::rustc_pass_by_value => self.check_pass_by_value(&attr, span, target), . sym::rustc_const_unstable . | sym::rustc_const_stable . | sym::unstable . | sym::stable . | sym::rustc_promotable => self.check_stability_promotable(&attr, span, target), . _ => true, . }; 5,181 ( 0.00%) is_valid &= attr_is_valid; . . // lint-only checks 19,895 ( 0.00%) match attr.name_or_empty() { . sym::cold => self.check_cold(hir_id, attr, span, target), . sym::link => self.check_link(hir_id, attr, span, target), . sym::link_name => self.check_link_name(hir_id, attr, span, target), . sym::link_section => self.check_link_section(hir_id, attr, span, target), . sym::no_mangle => self.check_no_mangle(hir_id, attr, span, target), . sym::deprecated | sym::rustc_deprecated => { . self.check_deprecated(hir_id, attr, span, target) . } 2 ( 0.00%) sym::macro_use | sym::macro_escape => self.check_macro_use(hir_id, attr, target), . sym::path => self.check_generic_attr(hir_id, attr, target, &[Target::Mod]), . sym::plugin_registrar => self.check_plugin_registrar(hir_id, attr, target), . sym::macro_export => self.check_macro_export(hir_id, attr, target), . sym::ignore | sym::should_panic | sym::proc_macro_derive => { . self.check_generic_attr(hir_id, attr, target, &[Target::Fn]) . } . sym::automatically_derived => { 560 ( 0.00%) self.check_generic_attr(hir_id, attr, target, &[Target::Impl]) . } . sym::no_implicit_prelude => { . self.check_generic_attr(hir_id, attr, target, &[Target::Mod]) . } . _ => {} . } . 1,727 ( 0.00%) let builtin = attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name)); . 3,507 ( 0.00%) if hir_id != CRATE_HIR_ID { 753 ( 0.00%) if let Some(BuiltinAttribute { type_: AttributeType::CrateLevel, .. }) = 1,673 ( 0.00%) attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name)) . { . self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| { . let msg = match attr.style { . ast::AttrStyle::Outer => { . "crate-level attribute should be an inner attribute: add an exclamation \ . mark: `#![foo]`" . } . ast::AttrStyle::Inner => "crate-level attribute should be in the root module", . }; . lint.build(msg).emit() . }); . } . } . 3,958 ( 0.00%) if let Some(BuiltinAttribute { duplicates, .. }) = builtin { 756 ( 0.00%) check_duplicates(self.tcx, attr, hir_id, *duplicates, &mut seen); . } . . // Warn on useless empty attributes. 15,392 ( 0.00%) if matches!( 1,727 ( 0.00%) attr.name_or_empty(), . sym::macro_use . | sym::allow . | sym::warn . | sym::deny . | sym::forbid . | sym::feature . | sym::repr . | sym::target_feature 225 ( 0.00%) ) && attr.meta_item_list().map_or(false, |list| list.is_empty()) . { . self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| { . lint.build("unused attribute") . .span_suggestion( . attr.span, . "remove this attribute", . String::new(), . Applicability::MachineApplicable, -- line 194 ---------------------------------------- -- line 197 ---------------------------------------- . "attribute `{}` with an empty list has no effect", . attr.name_or_empty() . )) . .emit(); . }); . } . } . 738 ( 0.00%) if !is_valid { . return; . } . 294,808 ( 0.00%) if matches!(target, Target::Closure | Target::Fn | Target::Method(_) | Target::ForeignFn) { 1,854 ( 0.00%) self.tcx.ensure().codegen_fn_attrs(self.tcx.hir().local_def_id(hir_id)); . } . . self.check_repr(attrs, span, target, item, hir_id); . self.check_used(attrs, target); 1,179,232 ( 0.02%) } . . fn inline_attr_str_error_with_macro_def(&self, hir_id: HirId, attr: &Attribute, sym: &str) { . self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| { . lint.build(&format!( . "`#[{}]` is ignored on struct fields, match arms and macro defs", . sym, . )) . .warn( -- line 223 ---------------------------------------- -- line 246 ---------------------------------------- . for more information", . ) . .emit(); . }); . } . . /// Checks if an `#[inline]` is applied to a function or a closure. Returns `true` if valid. . fn check_inline(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) -> bool { 475 ( 0.00%) match target { . Target::Fn . | Target::Closure . | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true, . Target::Method(MethodKind::Trait { body: false }) | Target::ForeignFn => { . self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| { . lint.build("`#[inline]` is ignored on function prototypes").emit() . }); . true -- line 262 ---------------------------------------- -- line 295 ---------------------------------------- . ) . .span_label(*span, "not a function or closure") . .emit(); . false . } . } . } . 728 ( 0.00%) fn check_generic_attr( . &self, . hir_id: HirId, . attr: &Attribute, . target: Target, . allowed_targets: &[Target], . ) { . if !allowed_targets.iter().any(|t| t == &target) { . let name = attr.name_or_empty(); -- line 311 ---------------------------------------- -- line 324 ---------------------------------------- . b.push_str(&(allowed_target.to_string() + "s")); . b . }); . self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| { . lint.build(&format!("`#[{name}]` only has an effect on {}", supported_names)) . .emit(); . }); . } 392 ( 0.00%) } . . /// Checks if `#[naked]` is applied to a function definition. . fn check_naked(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) -> bool { . match target { . Target::Fn . | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true, . // FIXME(#80564): We permit struct fields, match arms and macro defs to have an . // `#[allow_internal_unstable]` attribute with just a lint, because we previously -- line 340 ---------------------------------------- -- line 818 ---------------------------------------- . . /// Checks that an attribute is used at the crate level. Returns `true` if valid. . fn check_attr_crate_level( . &self, . attr: &Attribute, . meta: &NestedMetaItem, . hir_id: HirId, . ) -> bool { 2 ( 0.00%) if hir_id != CRATE_HIR_ID { . self.tcx.struct_span_lint_hir( . INVALID_DOC_ATTRIBUTES, . hir_id, . meta.span(), . |lint| { . let mut err = lint.build( . "this attribute can only be applied at the crate level", . ); -- line 834 ---------------------------------------- -- line 906 ---------------------------------------- . attr: &Attribute, . hir_id: HirId, . target: Target, . specified_inline: &mut Option<(bool, Span)>, . aliases: &mut FxHashMap, . ) -> bool { . let mut is_valid = true; . 168 ( 0.00%) if let Some(list) = attr.meta().and_then(|mi| mi.meta_item_list().map(|l| l.to_vec())) { . for meta in &list { 48 ( 0.00%) if let Some(i_meta) = meta.meta_item() { 72 ( 0.00%) match i_meta.name_or_empty() { . sym::alias . if !self.check_attr_not_crate_level(&meta, hir_id, "alias") . || !self.check_doc_alias(&meta, hir_id, target, aliases) => . { . is_valid = false . } . . sym::keyword -- line 925 ---------------------------------------- -- line 1059 ---------------------------------------- . }, . ); . is_valid = false; . } . } . } . . is_valid 36 ( 0.00%) } . . /// Warns against some misuses of `#[pass_by_value]` . fn check_pass_by_value(&self, attr: &Attribute, span: &Span, target: Target) -> bool { . match target { . Target::Struct | Target::Enum | Target::TyAlias => true, . _ => { . self.tcx . .sess -- line 1075 ---------------------------------------- -- line 1672 ---------------------------------------- . hint_spans, . E0692, . "transparent {} cannot have other repr hints", . target . ) . .emit(); . } . // Warn on repr(u8, u16), repr(C, simd), and c-like-enum-repr(C, u8) 1,179,232 ( 0.02%) if (int_reprs > 1) . || (is_simd && is_c) 589,616 ( 0.01%) || (int_reprs == 1 . && is_c . && item.map_or(false, |item| { . if let ItemLike::Item(item) = item { . return is_c_like_enum(item); . } . return false; . })) . { -- line 1690 ---------------------------------------- -- line 1698 ---------------------------------------- . .emit(); . }, . ); . } . } . . fn check_used(&self, attrs: &[Attribute], target: Target) { . for attr in attrs { 252 ( 0.00%) if attr.has_name(sym::used) && target != Target::Static { . self.tcx . .sess . .span_err(attr.span, "attribute must be applied to a `static` variable"); . } . } . } . . /// Outputs an error for `#[allow_internal_unstable]` which can only be applied to macros. -- line 1714 ---------------------------------------- -- line 1823 ---------------------------------------- . .emit(); . false . } . _ => true, . } . } . . fn check_deprecated(&self, hir_id: HirId, attr: &Attribute, _span: &Span, target: Target) { 2 ( 0.00%) match target { . Target::Closure | Target::Expression | Target::Statement | Target::Arm => { . self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| { . lint.build("attribute is ignored here").emit(); . }); . } . _ => {} . } . } . . fn check_macro_use(&self, hir_id: HirId, attr: &Attribute, target: Target) { 2 ( 0.00%) let name = attr.name_or_empty(); 2 ( 0.00%) match target { . Target::ExternCrate | Target::Mod => {} . _ => { . self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| { . lint.build(&format!( . "`#[{name}]` only has an effect on `extern crate` and modules" . )) . .emit(); . }); -- line 1851 ---------------------------------------- -- line 1869 ---------------------------------------- . } . } . } . . impl<'tcx> Visitor<'tcx> for CheckAttrVisitor<'tcx> { . type NestedFilter = nested_filter::OnlyBodies; . . fn nested_visit_map(&mut self) -> Self::Map { 401 ( 0.00%) self.tcx.hir() . } . 4,428 ( 0.00%) fn visit_item(&mut self, item: &'tcx Item<'tcx>) { . // Historically we've run more checks on non-exported than exported macros, . // so this lets us continue to run them while maintaining backwards compatibility. . // In the long run, the checks should be harmonized. 984 ( 0.00%) if let ItemKind::Macro(ref macro_def) = item.kind { 4 ( 0.00%) let def_id = item.def_id.to_def_id(); 40 ( 0.00%) if macro_def.macro_rules && !self.tcx.has_attr(def_id, sym::macro_export) { . check_non_exported_macro_for_invalid_attrs(self.tcx, item); . } . } . 984 ( 0.00%) let target = Target::from_item(item); 4,920 ( 0.00%) self.check_attributes(item.hir_id(), &item.span, target, Some(ItemLike::Item(item))); 1,476 ( 0.00%) intravisit::walk_item(self, item) 3,936 ( 0.00%) } . . fn visit_generic_param(&mut self, generic_param: &'tcx hir::GenericParam<'tcx>) { 360 ( 0.00%) let target = Target::from_generic_param(generic_param); 1,620 ( 0.00%) self.check_attributes(generic_param.hir_id, &generic_param.span, target, None); 540 ( 0.00%) intravisit::walk_generic_param(self, generic_param) . } . . fn visit_trait_item(&mut self, trait_item: &'tcx TraitItem<'tcx>) { 2 ( 0.00%) let target = Target::from_trait_item(trait_item); 8 ( 0.00%) self.check_attributes(trait_item.hir_id(), &trait_item.span, target, None); 3 ( 0.00%) intravisit::walk_trait_item(self, trait_item) . } . . fn visit_field_def(&mut self, struct_field: &'tcx hir::FieldDef<'tcx>) { 496 ( 0.00%) self.check_attributes(struct_field.hir_id, &struct_field.span, Target::Field, None); . intravisit::walk_field_def(self, struct_field); . } . . fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) { 1,656 ( 0.00%) self.check_attributes(arm.hir_id, &arm.span, Target::Arm, None); 621 ( 0.00%) intravisit::walk_arm(self, arm); . } . . fn visit_foreign_item(&mut self, f_item: &'tcx ForeignItem<'tcx>) { . let target = Target::from_foreign_item(f_item); . self.check_attributes( . f_item.hir_id(), . &f_item.span, . target, . Some(ItemLike::ForeignItem(f_item)), . ); . intravisit::walk_foreign_item(self, f_item) . } . 1,182 ( 0.00%) fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) { . let target = target_from_impl_item(self.tcx, impl_item); 1,576 ( 0.00%) self.check_attributes(impl_item.hir_id(), &impl_item.span, target, None); 591 ( 0.00%) intravisit::walk_impl_item(self, impl_item) 985 ( 0.00%) } . . fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) { . // When checking statements ignore expressions, they will be checked later. 2,025 ( 0.00%) if let hir::StmtKind::Local(ref l) = stmt.kind { 1,776 ( 0.00%) self.check_attributes(l.hir_id, &stmt.span, Target::Statement, None); . } . intravisit::walk_stmt(self, stmt) . } . . fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) { 143,394 ( 0.00%) let target = match expr.kind { . hir::ExprKind::Closure(..) => Target::Closure, . _ => Target::Expression, . }; . 1,151,244 ( 0.02%) self.check_attributes(expr.hir_id, &expr.span, target, None); 435,231 ( 0.01%) intravisit::walk_expr(self, expr) . } . . fn visit_variant( . &mut self, . variant: &'tcx hir::Variant<'tcx>, . generics: &'tcx hir::Generics<'tcx>, . item_id: HirId, . ) { 154 ( 0.00%) self.check_attributes(variant.id, &variant.span, Target::Variant, None); . intravisit::walk_variant(self, variant, generics, item_id) . } . . fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) { 3,094 ( 0.00%) self.check_attributes(param.hir_id, ¶m.span, Target::Param, None); . . intravisit::walk_param(self, param); . } . } . . fn is_c_like_enum(item: &Item<'_>) -> bool { . if let ItemKind::Enum(ref def, _) = item.kind { . for variant in def.variants { -- line 1972 ---------------------------------------- -- line 1999 ---------------------------------------- . sym::test_case, . sym::global_allocator, . sym::bench, . ]; . . for attr in attrs { . // This function should only be called with crate attributes . // which are inner attributes always but lets check to make sure 54 ( 0.00%) if attr.style == AttrStyle::Inner { . for attr_to_check in ATTRS_TO_CHECK { 11 ( 0.00%) if attr.has_name(*attr_to_check) { . let mut err = tcx.sess.struct_span_err( . attr.span, . &format!( . "`{}` attribute cannot be used at crate level", . attr_to_check.to_ident_string() . ), . ); . // Only emit an error with a suggestion if we can create a -- line 2017 ---------------------------------------- -- line 2028 ---------------------------------------- . err.emit() . } . } . } . } . } . . fn check_non_exported_macro_for_invalid_attrs(tcx: TyCtxt<'_>, item: &Item<'_>) { 5 ( 0.00%) let attrs = tcx.hir().attrs(item.hir_id()); . . for attr in attrs { . if attr.has_name(sym::inline) { . struct_span_err!( . tcx.sess, . attr.span, . E0518, . "attribute should be applied to function or closure", . ) . .span_label(attr.span, "not a function or closure") . .emit(); . } . } . } . 171 ( 0.00%) fn check_mod_attrs(tcx: TyCtxt<'_>, module_def_id: LocalDefId) { 19 ( 0.00%) let check_attr_visitor = &mut CheckAttrVisitor { tcx }; 114 ( 0.00%) tcx.hir().visit_item_likes_in_module(module_def_id, &mut check_attr_visitor.as_deep_visitor()); 19 ( 0.00%) if module_def_id.is_top_level_module() { 7 ( 0.00%) check_attr_visitor.check_attributes(CRATE_HIR_ID, &DUMMY_SP, Target::Mod, None); 4 ( 0.00%) check_invalid_crate_level_attr(tcx, tcx.hir().krate_attrs()); . } 152 ( 0.00%) } . . pub(crate) fn provide(providers: &mut Providers) { 2 ( 0.00%) *providers = Providers { check_mod_attrs, ..*providers }; . } . . fn check_duplicates( . tcx: TyCtxt<'_>, . attr: &Attribute, . hir_id: HirId, . duplicates: AttributeDuplicates, . seen: &mut FxHashMap, . ) { . use AttributeDuplicates::*; 1,263 ( 0.00%) if matches!(duplicates, WarnFollowingWordOnly) && !attr.is_word() { . return; . } . match duplicates { . DuplicatesOk => {} . WarnFollowing | FutureWarnFollowing | WarnFollowingWordOnly | FutureWarnPreceding => { 165 ( 0.00%) match seen.entry(attr.name_or_empty()) { . Entry::Occupied(mut entry) => { . let (this, other) = if matches!(duplicates, FutureWarnPreceding) { . let to_remove = entry.insert(attr.span); . (to_remove, attr.span) . } else { . (attr.span, *entry.get()) . }; . tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, this, |lint| { -- line 2087 ---------------------------------------- -- line 2098 ---------------------------------------- . being phased out; it will become a hard error in \ . a future release!", . ); . } . db.emit(); . }); . } . Entry::Vacant(entry) => { 165 ( 0.00%) entry.insert(attr.span); . } . } . } . ErrorFollowing | ErrorPreceding => match seen.entry(attr.name_or_empty()) { . Entry::Occupied(mut entry) => { . let (this, other) = if matches!(duplicates, ErrorPreceding) { . let to_remove = entry.insert(attr.span); . (to_remove, attr.span) -- line 2114 ---------------------------------------- 1,052,843 ( 0.01%) -------------------------------------------------------------------------------- -- 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 { 3,896,845 ( 0.06%) 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)); 113,404 ( 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::()); 89,319,270 ( 1.27%) 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" . ); . 295,480 ( 0.00%) self.stride += Group::WIDTH; 295,480 ( 0.00%) self.pos += self.stride; 246,214 ( 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. 118,552 ( 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. 235,160 ( 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. 73,464 ( 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 { 318,973 ( 0.00%) if bucket_mask < 8 { . // For tables with 1/2/4/8 buckets, we always reserve one empty slot. . // Keep in mind that the bucket mask is one less than the bucket count. . bucket_mask . } else { . // For larger tables we reserve 12.5% of the slots as empty. 96,993 ( 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 = 236,510 ( 0.00%) size.checked_mul(buckets)?.checked_add(ctrl_align - 1)? & !(ctrl_align - 1); 318,745 ( 0.00%) let len = ctrl_offset.checked_add(buckets + Group::WIDTH)?; . . Some(( . unsafe { Layout::from_size_align_unchecked(len, ctrl_align) }, . ctrl_offset, . )) . } . } . -- line 263 ---------------------------------------- -- line 337 ---------------------------------------- . } . } . #[cfg_attr(feature = "inline-more", inline)] . pub unsafe fn drop(&self) { . self.as_ptr().drop_in_place(); . } . #[inline] . pub unsafe fn read(&self) -> T { 3,042 ( 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 { 384 ( 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 { 225 ( 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 { 8,436 ( 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")] 17,260 ( 0.00%) pub unsafe fn erase_no_drop(&mut self, item: &Bucket) { 17,260 ( 0.00%) let index = self.bucket_index(item); . self.table.erase(index); 34,520 ( 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. 6,154 ( 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 { 28,366 ( 0.00%) self.erase_no_drop(&item); 92 ( 0.00%) item.read() . } . . /// Finds and removes an element from the table, returning it. . #[cfg_attr(feature = "inline-more", inline)] 1,840,095 ( 0.03%) pub fn remove_entry(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option { . // Avoid `Option::map` because it bloats LLVM IR. 3,584 ( 0.00%) match self.find(hash, eq) { 6,826 ( 0.00%) Some(bucket) => Some(unsafe { self.remove(bucket) }), 949,070 ( 0.01%) None => None, . } 2,910,786 ( 0.04%) } . . /// 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) { 11,500 ( 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) { 298,712 ( 0.00%) if additional > self.table.growth_left { . // Avoid `Result::unwrap_or_else` because it bloats LLVM IR. 198,860 ( 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)] 473,388 ( 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 . }, . ) . } 304,280 ( 0.00%) } . . /// Allocates a new table of a different size and moves the contents of the . /// current table into it. . fn resize( . &mut self, . capacity: usize, . hasher: impl Fn(&T) -> u64, . fallibility: Fallibility, -- line 706 ---------------------------------------- -- line 714 ---------------------------------------- . ) . } . } . . /// Inserts a new element into the table, and returns its raw bucket. . /// . /// This does not check if the given element already exists in the table. . #[cfg_attr(feature = "inline-more", inline)] 4,458,966 ( 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. 5,006 ( 0.00%) let old_ctrl = *self.table.ctrl(index); 3,790,827 ( 0.05%) 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 . } 3,317,843 ( 0.05%) } . . /// 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)] 651,768 ( 0.01%) pub fn insert_entry(&mut self, hash: u64, value: T, hasher: impl Fn(&T) -> u64) -> &mut T { 174 ( 0.00%) unsafe { self.insert(hash, value, hasher).as_mut() } 488,826 ( 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,160 ( 0.00%) pub unsafe fn insert_no_grow(&mut self, hash: u64, value: T) -> Bucket { 324,182 ( 0.00%) let (index, old_ctrl) = self.table.prepare_insert_slot(hash); 8,767 ( 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. 674,206 ( 0.01%) self.table.growth_left -= special_is_empty(old_ctrl) as usize; . . bucket.write(value); 530,354 ( 0.01%) self.table.items += 1; . bucket 2,204 ( 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,807 ( 0.00%) pub fn find(&self, hash: u64, mut eq: impl FnMut(&T) -> bool) -> Option> { 693,957 ( 0.01%) let result = self.table.find_inner(hash, &mut |index| unsafe { 427,690 ( 0.01%) eq(self.bucket(index).as_ref()) 547,808 ( 0.01%) }); . . // Avoid `Option::map` because it bloats LLVM IR. . match result { 136,919 ( 0.00%) Some(index) => Some(unsafe { self.bucket(index) }), . None => None, . } 27,984 ( 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. 289,183 ( 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,134 ( 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. 11,534 ( 0.00%) match self.find(hash, eq) { . Some(bucket) => Some(unsafe { bucket.as_mut() }), . None => None, . } 1,296 ( 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 { 5,044,910 ( 0.07%) self.len() == 0 . } . . /// Returns the number of buckets in the table. . #[inline] . pub fn buckets(&self) -> usize { . self.table.bucket_mask + 1 . } . . /// Returns an iterator over every element in the table. It is up to . /// the caller to ensure that the `RawTable` outlives the `RawIter`. . /// Because we cannot make the `next` method unsafe on the `RawIter` . /// struct, we have to make the `iter` method unsafe. . #[inline] . pub unsafe fn iter(&self) -> RawIter { 6 ( 0.00%) let data = Bucket::from_base_index(self.data_end(), 0); . RawIter { . iter: RawIterRange::new(self.table.ctrl.as_ptr(), data, self.table.buckets()), 928,099 ( 0.01%) 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(); 7,732 ( 0.00%) let allocation = self.into_allocation(); 5,799 ( 0.00%) RawIntoIter { 9,665 ( 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)> { 3,161 ( 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(( 539 ( 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 { 5,708,261 ( 0.08%) 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)] 416,225 ( 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()); . } . 99,356 ( 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)); 229,884 ( 0.00%) Ok(Self { . ctrl, 97,635 ( 0.00%) bucket_mask: buckets - 1, . items: 0, . growth_left: bucket_mask_to_capacity(buckets - 1), . alloc, . }) 303,026 ( 0.00%) } . . #[inline] 24,968 ( 0.00%) fn fallible_with_capacity( . alloc: A, . table_layout: TableLayout, . capacity: usize, . fallibility: Fallibility, . ) -> Result { 6,530 ( 0.00%) if capacity == 0 { 5,078 ( 0.00%) Ok(Self::new_in(alloc)) . } else { . unsafe { . let buckets = . capacity_to_buckets(capacity).ok_or_else(|| fallibility.capacity_overflow())?; . 189,029 ( 0.00%) let result = Self::new_uninitialized(alloc, table_layout, buckets, fallibility)?; . result.ctrl(0).write_bytes(EMPTY, result.num_ctrl_bytes()); . 13,037 ( 0.00%) Ok(result) . } . } 24,968 ( 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] 112,331 ( 0.00%) unsafe fn prepare_insert_slot(&self, hash: u64) -> (usize, u8) { . let index = self.find_insert_slot(hash); 112,331 ( 0.00%) let old_ctrl = *self.ctrl(index); . self.set_ctrl_h2(index, hash); . (index, old_ctrl) 224,662 ( 0.00%) } . . /// Searches for an empty or deleted bucket which is suitable for inserting . /// a new element. . /// . /// There must be at least 1 empty bucket in the table. . #[inline] . fn find_insert_slot(&self, hash: u64) -> usize { . let mut probe_seq = self.probe_seq(hash); . loop { . unsafe { . let group = Group::load(self.ctrl(probe_seq.pos)); 2,431,237 ( 0.03%) if let Some(bit) = group.match_empty_or_deleted().lowest_set_bit() { 7,161,086 ( 0.10%) 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). 3,333,866 ( 0.05%) 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); . 75,904 ( 0.00%) loop { . let group = unsafe { Group::load(self.ctrl(probe_seq.pos)) }; . 11,591,601 ( 0.16%) for bit in group.match_byte(h2_hash) { 22,546,849 ( 0.32%) let index = (probe_seq.pos + bit) & self.bucket_mask; . 13,267,718 ( 0.19%) if likely(eq(index)) { . return Some(index); . } . } . 3,630,592 ( 0.05%) 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(); 10,271,640 ( 0.15%) 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 { 59,308,094 ( 0.84%) 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) { 4,735,814 ( 0.07%) self.growth_left -= special_is_empty(old_ctrl) as usize; . self.set_ctrl_h2(index, hash); 3,788,616 ( 0.05%) 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] | . // --------------------------------------------- 7,034,567 ( 0.10%) let index2 = ((index.wrapping_sub(Group::WIDTH)) & self.bucket_mask) + Group::WIDTH; . 2,344,513 ( 0.03%) *self.ctrl(index) = ctrl; 2,345,362 ( 0.03%) *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 { 1,533,053 ( 0.02%) self.bucket_mask + 1 . } . . #[inline] . fn num_ctrl_bytes(&self) -> usize { 242,498 ( 0.00%) self.bucket_mask + 1 + Group::WIDTH . } . . #[inline] . fn is_empty_singleton(&self) -> bool { 8,988,154 ( 0.13%) 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. 3,180 ( 0.00%) let mut new_table = RawTableInner::fallible_with_capacity( . self.alloc.clone(), . table_layout, . capacity, . fallibility, . )?; 126,638 ( 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_| { 58,162 ( 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. 116,329 ( 0.00%) let new_items = match self.items.checked_add(additional) { . Some(new_items) => new_items, . None => return Err(fallibility.capacity_overflow()), . }; 116,324 ( 0.00%) let full_capacity = bucket_mask_to_capacity(self.bucket_mask); 242,898 ( 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( 58,162 ( 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> { 7,981 ( 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() { 1,510,133 ( 0.02%) 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); . 58,162 ( 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( 35,352 ( 0.00%) NonNull::new_unchecked(self.ctrl.as_ptr().sub(ctrl_offset)), . layout, . ); . } . . /// Marks all table buckets as empty without dropping their contents. . #[inline] . fn clear_no_drop(&mut self) { 12,833 ( 0.00%) if !self.is_empty_singleton() { . unsafe { . self.ctrl(0).write_bytes(EMPTY, self.num_ctrl_bytes()); . } . } 17,551 ( 0.00%) self.items = 0; 12,840 ( 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))); 103,679 ( 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. 414,716 ( 0.01%) let ctrl = if empty_before.leading_zeros() + empty_after.trailing_zeros() >= Group::WIDTH { . DELETED . } else { 517,155 ( 0.01%) self.growth_left += 1; . EMPTY . }; . self.set_ctrl(index, ctrl); 414,716 ( 0.01%) self.items -= 1; . } . } . . impl Clone for RawTable { 1,040 ( 0.00%) fn clone(&self) -> Self { 183 ( 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) . } . } 1,170 ( 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; 90 ( 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)] 7,302,810 ( 0.10%) fn drop(&mut self) { 4,198,674 ( 0.06%) if !self.table.is_empty_singleton() { . unsafe { . self.drop_elements(); . self.free_buckets(); . } . } 8,309,092 ( 0.12%) } . } . #[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)] 7,732 ( 0.00%) fn into_iter(self) -> RawIntoIter { . unsafe { . let iter = self.iter(); . self.into_iter_from(iter) . } 9,665 ( 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 { 901,203 ( 0.01%) if let Some(index) = self.current_group.lowest_set_bit() { 170,605 ( 0.00%) self.current_group = self.current_group.remove_lowest_bit(); 301,737 ( 0.00%) return Some(self.data.next_n(index)); . } . 1,071,459 ( 0.02%) 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). 19,122 ( 0.00%) self.current_group = Group::load_aligned(self.next_ctrl).match_full(); 33,353 ( 0.00%) self.data = self.data.next_n(Group::WIDTH); 23,159 ( 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) { 1,409 ( 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)] 173,927 ( 0.00%) fn next(&mut self) -> Option> { 363,822 ( 0.01%) if let Some(b) = self.iter.next() { 938,429 ( 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 . } 347,854 ( 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)] 3,220 ( 0.00%) fn drop(&mut self) { . unsafe { . // Drop all remaining elements . self.iter.drop_elements(); . . // Free the table 14,534 ( 0.00%) if let Some((ptr, layout)) = self.allocation { . self.alloc.deallocate(ptr, layout); . } . } 1,030 ( 0.00%) } . } . #[cfg(not(feature = "nightly"))] . impl Drop for RawIntoIter { . #[cfg_attr(feature = "inline-more", inline)] . fn drop(&mut self) { . unsafe { . // Drop all remaining elements . self.iter.drop_elements(); -- line 2203 ---------------------------------------- -- line 2209 ---------------------------------------- . } . } . } . . impl Iterator for RawIntoIter { . type Item = T; . . #[cfg_attr(feature = "inline-more", inline)] 1,547 ( 0.00%) fn next(&mut self) -> Option { 636 ( 0.00%) unsafe { Some(self.iter.next()?.read()) } 3,808 ( 0.00%) } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 4 ( 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)] 352 ( 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. 44 ( 0.00%) self.orig_table . .as_ptr() . .copy_from_nonoverlapping(&*self.table, 1); . } 352 ( 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 ---------------------------------------- 31,864,052 ( 0.45%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/expr.rs -------------------------------------------------------------------------------- Ir -- line 71 ---------------------------------------- . AlreadyParsed(P), . } . . impl From> for LhsExpr { . /// Converts `Some(attrs)` into `LhsExpr::AttributesParsed(attrs)` . /// and `None` into `LhsExpr::NotYetParsed`. . /// . /// This conversion does not allocate. 92 ( 0.00%) fn from(o: Option) -> Self { 144,997 ( 0.00%) if let Some(attrs) = o { LhsExpr::AttributesParsed(attrs) } else { LhsExpr::NotYetParsed } 92 ( 0.00%) } . } . . impl From> for LhsExpr { . /// Converts the `expr: P` into `LhsExpr::AlreadyParsed(expr)`. . /// . /// This conversion does not allocate. . fn from(expr: P) -> Self { . LhsExpr::AlreadyParsed(expr) -- line 89 ---------------------------------------- -- line 96 ---------------------------------------- . pub fn parse_expr(&mut self) -> PResult<'a, P> { . self.current_closure.take(); . . self.parse_expr_res(Restrictions::empty(), None) . } . . /// Parses an expression, forcing tokens to be collected . pub fn parse_expr_force_collect(&mut self) -> PResult<'a, P> { 28 ( 0.00%) self.collect_tokens_no_attrs(|this| this.parse_expr()) . } . . pub fn parse_anon_const_expr(&mut self) -> PResult<'a, AnonConst> { . self.parse_expr().map(|value| AnonConst { id: DUMMY_NODE_ID, value }) . } . 7,024 ( 0.00%) fn parse_expr_catch_underscore(&mut self) -> PResult<'a, P> { 1,756 ( 0.00%) match self.parse_expr() { . Ok(expr) => Ok(expr), . Err(mut err) => match self.token.ident() { . Some((Ident { name: kw::Underscore, .. }, false)) . if self.look_ahead(1, |t| t == &token::Comma) => . { . // Special-case handling of `foo(_, _, _)` . err.emit(); . self.bump(); . Ok(self.mk_expr(self.prev_token.span, ExprKind::Err, AttrVec::new())) . } . _ => Err(err), . }, . } 8,780 ( 0.00%) } . . /// Parses a sequence of expressions delimited by parentheses. . fn parse_paren_expr_seq(&mut self) -> PResult<'a, Vec>> { 4,574 ( 0.00%) self.parse_paren_comma_seq(|p| p.parse_expr_catch_underscore()).map(|(r, _)| r) . } . . /// Parses an expression, subject to the given restrictions. . #[inline] . pub(super) fn parse_expr_res( . &mut self, . r: Restrictions, . already_parsed_attrs: Option, -- line 138 ---------------------------------------- -- line 144 ---------------------------------------- . /// . /// This parses an expression accounting for associativity and precedence of the operators in . /// the expression. . #[inline] . fn parse_assoc_expr( . &mut self, . already_parsed_attrs: Option, . ) -> PResult<'a, P> { 559,204 ( 0.01%) self.parse_assoc_expr_with(0, already_parsed_attrs.into()) . } . . /// Parses an associative expression with operators of at least `min_prec` precedence. 1,269,279 ( 0.02%) pub(super) fn parse_assoc_expr_with( . &mut self, . min_prec: usize, . lhs: LhsExpr, . ) -> PResult<'a, P> { 705,350 ( 0.01%) let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs { 1,648 ( 0.00%) expr . } else { 281,238 ( 0.00%) let attrs = match lhs { 282,183 ( 0.00%) LhsExpr::AttributesParsed(attrs) => Some(attrs), . _ => None, . }; 140,619 ( 0.00%) if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind) { 8 ( 0.00%) return self.parse_prefix_range_expr(attrs); . } else { 1,687,404 ( 0.02%) self.parse_prefix_expr(attrs)? . } . }; 282,058 ( 0.00%) let last_type_ascription_set = self.last_type_ascription.is_some(); . . if !self.should_continue_as_assoc_expr(&lhs) { 483 ( 0.00%) self.last_type_ascription = None; . return Ok(lhs); . } . . self.expected_tokens.push(TokenType::Operator); 864 ( 0.00%) while let Some(op) = self.check_assoc_op() { . // Adjust the span for interpolated LHS to point to the `$lhs` token . // and not to what it refers to. 1,296 ( 0.00%) let lhs_span = match self.prev_token.kind { . TokenKind::Interpolated(..) => self.prev_token.span, . _ => lhs.span, . }; . 432 ( 0.00%) let cur_op_span = self.token.span; 1,728 ( 0.00%) let restrictions = if op.node.is_assign_like() { . self.restrictions & Restrictions::NO_STRUCT_LITERAL . } else { . self.restrictions . }; 648 ( 0.00%) let prec = op.node.precedence(); 432 ( 0.00%) if prec < min_prec { . break; . } . // Check for deprecated `...` syntax 792 ( 0.00%) if self.token == token::DotDotDot && op.node == AssocOp::DotDotEq { . self.err_dotdotdot_syntax(self.token.span); . } . 792 ( 0.00%) if self.token == token::LArrow { . self.err_larrow_operator(self.token.span); . } . 198 ( 0.00%) self.bump(); 792 ( 0.00%) if op.node.is_comparison() { . if let Some(expr) = self.check_no_chained_comparison(&lhs, &op)? { . return Ok(expr); . } . } . . // Look for JS' `===` and `!==` and recover 270 ( 0.00%) if (op.node == AssocOp::Equal || op.node == AssocOp::NotEqual) 72 ( 0.00%) && self.token.kind == token::Eq . && self.prev_token.span.hi() == self.token.span.lo() . { . let sp = op.span.to(self.token.span); . let sugg = match op.node { . AssocOp::Equal => "==", . AssocOp::NotEqual => "!=", . _ => unreachable!(), . }; -- line 226 ---------------------------------------- -- line 231 ---------------------------------------- . sugg.to_string(), . Applicability::MachineApplicable, . ) . .emit(); . self.bump(); . } . . // Look for PHP's `<>` and recover 44 ( 0.00%) if op.node == AssocOp::Less 8 ( 0.00%) && self.token.kind == token::Gt . && self.prev_token.span.hi() == self.token.span.lo() . { . let sp = op.span.to(self.token.span); . self.struct_span_err(sp, "invalid comparison operator `<>`") . .span_suggestion_short( . sp, . "`<>` is not a valid comparison operator, use `!=`", . "!=".to_string(), . Applicability::MachineApplicable, . ) . .emit(); . self.bump(); . } . . // Look for C++'s `<=>` and recover 12 ( 0.00%) if op.node == AssocOp::LessEqual 12 ( 0.00%) && self.token.kind == token::Gt . && self.prev_token.span.hi() == self.token.span.lo() . { . let sp = op.span.to(self.token.span); . self.struct_span_err(sp, "invalid comparison operator `<=>`") . .span_label( . sp, . "`<=>` is not a valid comparison operator, use `std::cmp::Ordering`", . ) . .emit(); . self.bump(); . } . 396 ( 0.00%) let op = op.node; . // Special cases: . if op == AssocOp::As { 50 ( 0.00%) lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?; . continue; . } else if op == AssocOp::Colon { . lhs = self.parse_assoc_op_ascribe(lhs, lhs_span)?; . continue; . } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq { . // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to . // generalise it to the Fixity::None code. 100 ( 0.00%) lhs = self.parse_range_expr(prec, lhs, op, cur_op_span)?; . break; . } . 163 ( 0.00%) let fixity = op.fixity(); 489 ( 0.00%) let prec_adjustment = match fixity { . Fixity::Right => 0, . Fixity::Left => 1, . // We currently have no non-associative operators that are not handled above by . // the special cases. The code is here only for future convenience. . Fixity::None => 1, . }; 326 ( 0.00%) let rhs = self.with_res(restrictions - Restrictions::STMT_EXPR, |this| { 815 ( 0.00%) this.parse_assoc_expr_with(prec + prec_adjustment, LhsExpr::NotYetParsed) . })?; . . let span = self.mk_expr_sp(&lhs, lhs_span, rhs.span); 1,563 ( 0.00%) lhs = match op { . AssocOp::Add . | AssocOp::Subtract . | AssocOp::Multiply . | AssocOp::Divide . | AssocOp::Modulus . | AssocOp::LAnd . | AssocOp::LOr . | AssocOp::BitXor -- line 306 ---------------------------------------- -- line 309 ---------------------------------------- . | AssocOp::ShiftLeft . | AssocOp::ShiftRight . | AssocOp::Equal . | AssocOp::Less . | AssocOp::LessEqual . | AssocOp::NotEqual . | AssocOp::Greater . | AssocOp::GreaterEqual => { 214 ( 0.00%) let ast_op = op.to_ast_binop().unwrap(); . let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs); . self.mk_expr(span, binary, AttrVec::new()) . } . AssocOp::Assign => { . self.mk_expr(span, ExprKind::Assign(lhs, rhs, cur_op_span), AttrVec::new()) . } . AssocOp::AssignOp(k) => { . let aop = match k { -- line 325 ---------------------------------------- -- line 337 ---------------------------------------- . let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs); . self.mk_expr(span, aopexpr, AttrVec::new()) . } . AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => { . self.span_bug(span, "AssocOp should have been handled by special case") . } . }; . 326 ( 0.00%) if let Fixity::None = fixity { . break; . } . } 140,868 ( 0.00%) if last_type_ascription_set { . self.last_type_ascription = None; . } 281,736 ( 0.00%) Ok(lhs) 2,397,147 ( 0.03%) } . . fn should_continue_as_assoc_expr(&mut self, lhs: &Expr) -> bool { 987,525 ( 0.01%) match (self.expr_is_complete(lhs), AssocOp::from_token(&self.token)) { . // Semi-statement forms are odd: . // See https://github.com/rust-lang/rust/issues/29071 . (true, None) => false, . (false, _) => true, // Continue parsing the expression. . // An exhaustive check is done in the following block, but these are checked first . // because they *are* ambiguous but also reasonable looking incorrect syntax, so we . // want to keep their span info to improve diagnostics in these cases in a later stage. . (true, Some(AssocOp::Multiply)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3` -- line 364 ---------------------------------------- -- line 401 ---------------------------------------- . err.emit(); . } . . /// Possibly translate the current token to an associative operator. . /// The method does not advance the current token. . /// . /// Also performs recovery for `and` / `or` which are mistaken for `&&` and `||` respectively. . fn check_assoc_op(&self) -> Option> { 1,551,707 ( 0.02%) let (op, span) = match (AssocOp::from_token(&self.token), self.token.ident()) { . // When parsing const expressions, stop parsing when encountering `>`. . ( . Some( . AssocOp::ShiftRight . | AssocOp::Greater . | AssocOp::GreaterEqual . | AssocOp::AssignOp(token::BinOpToken::Shr), . ), . _, 19 ( 0.00%) ) if self.restrictions.contains(Restrictions::CONST_EXPR) => { . return None; . } 432 ( 0.00%) (Some(op), _) => (op, self.token.span), . (None, Some((Ident { name: sym::and, span }, false))) => { . self.error_bad_logical_op("and", "&&", "conjunction"); . (AssocOp::LAnd, span) . } . (None, Some((Ident { name: sym::or, span }, false))) => { . self.error_bad_logical_op("or", "||", "disjunction"); . (AssocOp::LOr, span) . } -- line 430 ---------------------------------------- -- line 443 ---------------------------------------- . Applicability::MachineApplicable, . ) . .note("unlike in e.g., python and PHP, `&&` and `||` are used for logical operators") . .emit(); . } . . /// Checks if this expression is a successfully parsed statement. . fn expr_is_complete(&self, e: &Expr) -> bool { 282,324 ( 0.00%) self.restrictions.contains(Restrictions::STMT_EXPR) 3,583 ( 0.00%) && !classify::expr_requires_semi_to_be_stmt(e) . } . . /// Parses `x..y`, `x..=y`, and `x..`/`x..=`. . /// The other two variants are handled in `parse_prefix_range_expr` below. . fn parse_range_expr( . &mut self, . prec: usize, . lhs: P, . op: AssocOp, . cur_op_span: Span, . ) -> PResult<'a, P> { . let rhs = if self.is_at_start_of_range_notation_rhs() { 135 ( 0.00%) Some(self.parse_assoc_expr_with(prec + 1, LhsExpr::NotYetParsed)?) . } else { 20 ( 0.00%) None . }; 30 ( 0.00%) let rhs_span = rhs.as_ref().map_or(cur_op_span, |x| x.span); . let span = self.mk_expr_sp(&lhs, lhs.span, rhs_span); . let limits = . if op == AssocOp::DotDot { RangeLimits::HalfOpen } else { RangeLimits::Closed }; 75 ( 0.00%) let range = self.mk_range(Some(lhs), rhs, limits); . Ok(self.mk_expr(span, range, AttrVec::new())) . } . . fn is_at_start_of_range_notation_rhs(&self) -> bool { 110 ( 0.00%) if self.token.can_begin_expr() { . // Parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`. 85 ( 0.00%) if self.token == token::OpenDelim(token::Brace) { . return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL); . } . true . } else { . false . } . } . . /// Parses prefix-forms of range notation: `..expr`, `..`, `..=expr`. . fn parse_prefix_range_expr(&mut self, attrs: Option) -> PResult<'a, P> { . // Check for deprecated `...` syntax. 10 ( 0.00%) if self.token == token::DotDotDot { . self.err_dotdotdot_syntax(self.token.span); . } . . debug_assert!( . [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind), . "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq", . self.token . ); . 6 ( 0.00%) let limits = match self.token.kind { . token::DotDot => RangeLimits::HalfOpen, . _ => RangeLimits::Closed, . }; 4 ( 0.00%) let op = AssocOp::from_token(&self.token); . // FIXME: `parse_prefix_range_expr` is called when the current . // token is `DotDot`, `DotDotDot`, or `DotDotEq`. If we haven't already . // parsed attributes, then trying to parse them here will always fail. . // We should figure out how we want attributes on range expressions to work. 8 ( 0.00%) let attrs = self.parse_or_use_outer_attributes(attrs)?; . self.collect_tokens_for_expr(attrs, |this, attrs| { 4 ( 0.00%) let lo = this.token.span; 4 ( 0.00%) this.bump(); . let (span, opt_end) = if this.is_at_start_of_range_notation_rhs() { . // RHS must be parsed with more associativity than the dots. 20 ( 0.00%) this.parse_assoc_expr_with(op.unwrap().precedence() + 1, LhsExpr::NotYetParsed) 10 ( 0.00%) .map(|x| (lo.to(x.span), Some(x)))? . } else { . (lo, None) . }; 6 ( 0.00%) let range = this.mk_range(None, opt_end, limits); 14 ( 0.00%) Ok(this.mk_expr(span, range, attrs.into())) . }) . } . . /// Parses a prefix-unary-operator expr. 989,359 ( 0.01%) fn parse_prefix_expr(&mut self, attrs: Option) -> PResult<'a, P> { 1,130,696 ( 0.02%) let attrs = self.parse_or_use_outer_attributes(attrs)?; 706,685 ( 0.01%) let lo = self.token.span; . . macro_rules! make_it { . ($this:ident, $attrs:expr, |this, _| $body:expr) => { 6,471 ( 0.00%) $this.collect_tokens_for_expr($attrs, |$this, attrs| { 12,105 ( 0.00%) let (hi, ex) = $body?; 11,520 ( 0.00%) Ok($this.mk_expr(lo.to(hi), ex, attrs.into())) 7,191 ( 0.00%) }) . }; . } . . let this = self; . . // Note: when adding new unary operators, don't forget to adjust TokenKind::can_begin_expr() 850,974 ( 0.01%) match this.token.uninterpolate().kind { 3 ( 0.00%) token::Not => make_it!(this, attrs, |this, _| this.parse_unary_expr(lo, UnOp::Not)), // `!expr` . token::Tilde => make_it!(this, attrs, |this, _| this.recover_tilde_expr(lo)), // `~expr` . token::BinOp(token::Minus) => { . make_it!(this, attrs, |this, _| this.parse_unary_expr(lo, UnOp::Neg)) . } // `-expr` . token::BinOp(token::Star) => { 6 ( 0.00%) make_it!(this, attrs, |this, _| this.parse_unary_expr(lo, UnOp::Deref)) . } // `*expr` . token::BinOp(token::And) | token::AndAnd => { 1,422 ( 0.00%) make_it!(this, attrs, |this, _| this.parse_borrow_expr(lo)) . } . token::BinOp(token::Plus) if this.look_ahead(1, |tok| tok.is_numeric_lit()) => { . let mut err = this.struct_span_err(lo, "leading `+` is not supported"); . err.span_label(lo, "unexpected `+`"); . . // a block on the LHS might have been intended to be an expression instead . if let Some(sp) = this.sess.ambiguous_block_expr_parse.borrow().get(&lo) { . this.sess.expr_parentheses_needed(&mut err, *sp); -- line 562 ---------------------------------------- -- line 568 ---------------------------------------- . Applicability::MachineApplicable, . ); . } . err.emit(); . . this.bump(); . this.parse_prefix_expr(None) . } // `+expr` 6,056 ( 0.00%) token::Ident(..) if this.token.is_keyword(kw::Box) => { . make_it!(this, attrs, |this, _| this.parse_box_expr(lo)) . } . token::Ident(..) if this.is_mistaken_not_ident_negation() => { . make_it!(this, attrs, |this, _| this.recover_not_expr(lo)) . } . _ => return this.parse_dot_or_call_expr(Some(attrs)), . } 1,413,370 ( 0.02%) } . . fn parse_prefix_expr_common(&mut self, lo: Span) -> PResult<'a, (Span, P)> { 18 ( 0.00%) self.bump(); 36 ( 0.00%) let expr = self.parse_prefix_expr(None); 9 ( 0.00%) let (span, expr) = self.interpolated_or_expr_span(expr)?; 18 ( 0.00%) Ok((lo.to(span), expr)) . } . . fn parse_unary_expr(&mut self, lo: Span, op: UnOp) -> PResult<'a, (Span, ExprKind)> { . let (span, expr) = self.parse_prefix_expr_common(lo)?; . Ok((span, self.mk_unary(op, expr))) . } . . // Recover on `!` suggesting for bitwise negation instead. -- line 598 ---------------------------------------- -- line 619 ---------------------------------------- . fn is_mistaken_not_ident_negation(&self) -> bool { . let token_cannot_continue_expr = |t: &Token| match t.uninterpolate().kind { . // These tokens can start an expression after `!`, but . // can't continue an expression after an ident . token::Ident(name, is_raw) => token::ident_can_begin_expr(name, t.span, is_raw), . token::Literal(..) | token::Pound => true, . _ => t.is_whole_expr(), . }; 6,056 ( 0.00%) self.token.is_ident_named(sym::not) && self.look_ahead(1, token_cannot_continue_expr) . } . . /// Recover on `not expr` in favor of `!expr`. . fn recover_not_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> { . // Emit the error... . let not_token = self.look_ahead(1, |t| t.clone()); . self.struct_span_err( . not_token.span, -- line 635 ---------------------------------------- -- line 651 ---------------------------------------- . . /// Returns the span of expr, if it was not interpolated or the span of the interpolated token. . fn interpolated_or_expr_span( . &self, . expr: PResult<'a, P>, . ) -> PResult<'a, (Span, P)> { . expr.map(|e| { . ( 566,068 ( 0.01%) match self.prev_token.kind { . TokenKind::Interpolated(..) => self.prev_token.span, . _ => e.span, . }, . e, . ) . }) . } . 140 ( 0.00%) fn parse_assoc_op_cast( . &mut self, . lhs: P, . lhs_span: Span, . expr_kind: fn(P, P) -> ExprKind, . ) -> PResult<'a, P> { . let mk_expr = |this: &mut Self, lhs: P, rhs: P| { . this.mk_expr( . this.mk_expr_sp(&lhs, lhs_span, rhs.span), 30 ( 0.00%) expr_kind(lhs, rhs), . AttrVec::new(), . ) . }; . . // Save the state of the parser before parsing type normally, in case there is a . // LessThan comparison after this cast. 20 ( 0.00%) let parser_snapshot_before_type = self.clone(); 30 ( 0.00%) let cast_expr = match self.parse_as_cast_ty() { . Ok(rhs) => mk_expr(self, lhs, rhs), . Err(mut type_err) => { . // Rewind to before attempting to parse the type with generics, to recover . // from situations like `x as usize < y` in which we first tried to parse . // `usize < y` as a type with generic arguments. . let parser_snapshot_after_type = mem::replace(self, parser_snapshot_before_type); . . // Check for typo of `'a: loop { break 'a }` with a missing `'`. -- line 693 ---------------------------------------- -- line 779 ---------------------------------------- . *self = parser_snapshot_after_type; . return Err(type_err); . } . } . } . }; . . self.parse_and_disallow_postfix_after_cast(cast_expr) 120 ( 0.00%) } . . /// Parses a postfix operators such as `.`, `?`, or index (`[]`) after a cast, . /// then emits an error and returns the newly parsed tree. . /// The resulting parse tree for `&x as T[0]` has a precedence of `((&x) as T)[0]`. . fn parse_and_disallow_postfix_after_cast( . &mut self, . cast_expr: P, . ) -> PResult<'a, P> { . // Save the memory location of expr before parsing any following postfix operators. . // This will be compared with the memory location of the output expression. . // If they different we can assume we parsed another expression because the existing expression is not reallocated. . let addr_before = &*cast_expr as *const _ as usize; . let span = cast_expr.span; 60 ( 0.00%) let with_postfix = self.parse_dot_or_call_expr_with_(cast_expr, span)?; . let changed = addr_before != &*with_postfix as *const _ as usize; . . // Check if an illegal postfix operator has been added after the cast. . // If the resulting expression is not a cast, or has a different memory location, it is an illegal postfix operator. 60 ( 0.00%) if !matches!(with_postfix.kind, ExprKind::Cast(_, _) | ExprKind::Type(_, _)) || changed { . let msg = format!( . "casts cannot be followed by {}", . match with_postfix.kind { . ExprKind::Index(_, _) => "indexing", . ExprKind::Try(_) => "`?`", . ExprKind::Field(_, _) => "a field access", . ExprKind::MethodCall(_, _, _) => "a method call", . ExprKind::Call(_, _) => "a function call", -- line 814 ---------------------------------------- -- line 844 ---------------------------------------- . let lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type)?; . self.sess.gated_spans.gate(sym::type_ascription, lhs.span); . Ok(lhs) . } . . /// Parse `& mut? ` or `& raw [ const | mut ] `. . fn parse_borrow_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> { . self.expect_and()?; 3,555 ( 0.00%) let has_lifetime = self.token.is_lifetime() && self.look_ahead(1, |t| t != &token::Colon); . let lifetime = has_lifetime.then(|| self.expect_lifetime()); // For recovery, see below. . let (borrow_kind, mutbl) = self.parse_borrow_modifiers(lo); 2,844 ( 0.00%) let expr = self.parse_prefix_expr(None); 1,422 ( 0.00%) let (hi, expr) = self.interpolated_or_expr_span(expr)?; 711 ( 0.00%) let span = lo.to(hi); 1,422 ( 0.00%) if let Some(lt) = lifetime { . self.error_remove_borrow_lifetime(span, lt.ident.span); . } . Ok((span, ExprKind::AddrOf(borrow_kind, mutbl, expr))) . } . . fn error_remove_borrow_lifetime(&self, span: Span, lt_span: Span) { . self.struct_span_err(span, "borrow expressions cannot be annotated with lifetimes") . .span_label(lt_span, "annotated with lifetime here") -- line 866 ---------------------------------------- -- line 870 ---------------------------------------- . String::new(), . Applicability::MachineApplicable, . ) . .emit(); . } . . /// Parse `mut?` or `raw [ const | mut ]`. . fn parse_borrow_modifiers(&mut self, lo: Span) -> (ast::BorrowKind, ast::Mutability) { 1,422 ( 0.00%) if self.check_keyword(kw::Raw) && self.look_ahead(1, Token::is_mutability) { . // `raw [ const | mut ]`. . let found_raw = self.eat_keyword(kw::Raw); . assert!(found_raw); . let mutability = self.parse_const_or_mut().unwrap(); . self.sess.gated_spans.gate(sym::raw_ref_op, lo.to(self.prev_token.span)); . (ast::BorrowKind::Raw, mutability) . } else { . // `mut?` -- line 886 ---------------------------------------- -- line 889 ---------------------------------------- . } . . /// Parses `a.b` or `a(13)` or `a[4]` or just `a`. . fn parse_dot_or_call_expr(&mut self, attrs: Option) -> PResult<'a, P> { . let attrs = self.parse_or_use_outer_attributes(attrs)?; . self.collect_tokens_for_expr(attrs, |this, attrs| { . let base = this.parse_bottom_expr(); . let (span, base) = this.interpolated_or_expr_span(base)?; 562,468 ( 0.01%) this.parse_dot_or_call_expr_with(base, span, attrs) . }) . } . 60 ( 0.00%) pub(super) fn parse_dot_or_call_expr_with( . &mut self, . e0: P, . lo: Span, . mut attrs: Vec, . ) -> PResult<'a, P> { . // Stitch the list of outer attributes onto the return value. . // A little bit ugly, but the best way given the current code . // structure 987,113 ( 0.01%) self.parse_dot_or_call_expr_with_(e0, lo).map(|expr| { 987,143 ( 0.01%) expr.map(|mut expr| { 141,019 ( 0.00%) attrs.extend::>(expr.attrs.into()); 282,038 ( 0.00%) expr.attrs = attrs.into(); 1,974,266 ( 0.03%) expr . }) . }) 80 ( 0.00%) } . 4,371,899 ( 0.06%) fn parse_dot_or_call_expr_with_(&mut self, mut e: P, lo: Span) -> PResult<'a, P> { . loop { . if self.eat(&token::Question) { . // `expr?` 48 ( 0.00%) e = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Try(e), AttrVec::new()); . continue; . } . if self.eat(&token::Dot) { . // expr.f 3,736 ( 0.00%) e = self.parse_dot_suffix_expr(lo, e)?; . continue; . } 1,540 ( 0.00%) if self.expr_is_complete(&e) { . return Ok(e); . } 284,936 ( 0.00%) e = match self.token.kind { 720 ( 0.00%) token::OpenDelim(token::Paren) => self.parse_fn_call_expr(lo, e), 52 ( 0.00%) token::OpenDelim(token::Bracket) => self.parse_index_expr(lo, e)?, 140,868 ( 0.00%) _ => return Ok(e), . } . } 1,269,261 ( 0.02%) } . . fn look_ahead_type_ascription_as_field(&mut self) -> bool { 1,443 ( 0.00%) self.look_ahead(1, |t| t.is_ident()) . && self.look_ahead(2, |t| t == &token::Colon) . && self.look_ahead(3, |t| t.can_begin_expr()) . } . . fn parse_dot_suffix_expr(&mut self, lo: Span, base: P) -> PResult<'a, P> { 10,442 ( 0.00%) match self.token.uninterpolate().kind { . token::Ident(..) => self.parse_dot_suffix(base, lo), 144 ( 0.00%) token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) => { 216 ( 0.00%) Ok(self.parse_tuple_field_access_expr(lo, base, symbol, suffix, None)) . } . token::Literal(token::Lit { kind: token::Float, symbol, suffix }) => { . Ok(self.parse_tuple_field_access_expr_float(lo, base, symbol, suffix)) . } . _ => { . self.error_unexpected_after_dot(); . Ok(base) . } -- line 960 ---------------------------------------- -- line 1071 ---------------------------------------- . // See the FIXME about `TokenCursor` above. . self.error_unexpected_after_dot(); . base . } . _ => panic!("unexpected components in a float token: {:?}", components), . } . } . 312 ( 0.00%) fn parse_tuple_field_access_expr( . &mut self, . lo: Span, . base: P, . field: Symbol, . suffix: Option, . next_token: Option<(Token, Spacing)>, . ) -> P { 48 ( 0.00%) match next_token { . Some(next_token) => self.bump_with(next_token), 72 ( 0.00%) None => self.bump(), . } 24 ( 0.00%) let span = self.prev_token.span; 96 ( 0.00%) let field = ExprKind::Field(base, Ident::new(field, span)); 144 ( 0.00%) self.expect_no_suffix(span, "a tuple index", suffix); 72 ( 0.00%) self.mk_expr(lo.to(span), field, AttrVec::new()) 192 ( 0.00%) } . . /// Parse a function call expression, `expr(...)`. . fn parse_fn_call_expr(&mut self, lo: Span, fun: P) -> P { 1,200 ( 0.00%) let snapshot = if self.token.kind == token::OpenDelim(token::Paren) . && self.look_ahead_type_ascription_as_field() . { . Some((self.clone(), fun.kind.clone())) . } else { 720 ( 0.00%) None . }; 240 ( 0.00%) let open_paren = self.token.span; . 480 ( 0.00%) let mut seq = self.parse_paren_expr_seq().map(|args| { 720 ( 0.00%) self.mk_expr(lo.to(self.prev_token.span), self.mk_call(fun, args), AttrVec::new()) . }); . if let Some(expr) = . self.maybe_recover_struct_lit_bad_delims(lo, open_paren, &mut seq, snapshot) . { . return expr; . } 1,200 ( 0.00%) self.recover_seq_parse_error(token::Paren, lo, seq) . } . . /// If we encounter a parser state that looks like the user has written a `struct` literal with . /// parentheses instead of braces, recover the parser state and provide suggestions. . #[instrument(skip(self, seq, snapshot), level = "trace")] . fn maybe_recover_struct_lit_bad_delims( . &mut self, . lo: Span, . open_paren: Span, . seq: &mut PResult<'a, P>, . snapshot: Option<(Self, ExprKind)>, . ) -> Option> { 2,400 ( 0.00%) match (seq.as_mut(), snapshot) { . (Err(ref mut err), Some((mut snapshot, ExprKind::Path(None, path)))) => { . let name = pprust::path_to_string(&path); . snapshot.bump(); // `(` . match snapshot.parse_struct_fields(path, false, token::Paren) { . Ok((fields, ..)) if snapshot.eat(&token::CloseDelim(token::Paren)) => { . // We are certain we have `Enum::Foo(a: 3, b: 4)`, suggest . // `Enum::Foo { a: 3, b: 4 }` or `Enum::Foo(3, 4)`. . *self = snapshot; -- line 1137 ---------------------------------------- -- line 1165 ---------------------------------------- . } . return Some(self.mk_expr_err(span)); . } . Ok(_) => {} . Err(mut err) => err.emit(), . } . } . _ => {} 720 ( 0.00%) } . None . } . . /// Parse an indexing expression `expr[...]`. . fn parse_index_expr(&mut self, lo: Span, base: P) -> PResult<'a, P> { 52 ( 0.00%) self.bump(); // `[` 52 ( 0.00%) let index = self.parse_expr()?; 78 ( 0.00%) self.expect(&token::CloseDelim(token::Bracket))?; 78 ( 0.00%) Ok(self.mk_expr(lo.to(self.prev_token.span), self.mk_index(base, index), AttrVec::new())) . } . . /// Assuming we have just parsed `.`, continue parsing into an expression. . fn parse_dot_suffix(&mut self, self_arg: P, lo: Span) -> PResult<'a, P> { 1,820 ( 0.00%) if self.token.uninterpolated_span().rust_2018() && self.eat_keyword(kw::Await) { . return Ok(self.mk_await_expr(self_arg, lo)); . } . 910 ( 0.00%) let fn_span_lo = self.token.span; 5,460 ( 0.00%) let mut segment = self.parse_path_segment(PathStyle::Expr, None)?; 4,550 ( 0.00%) self.check_trailing_angle_brackets(&segment, &[&token::OpenDelim(token::Paren)]); . self.check_turbofish_missing_angle_brackets(&mut segment); . 4,550 ( 0.00%) if self.check(&token::OpenDelim(token::Paren)) { . // Method call `expr.f()` 576 ( 0.00%) let mut args = self.parse_paren_expr_seq()?; 2,304 ( 0.00%) args.insert(0, self_arg); . 1,728 ( 0.00%) let fn_span = fn_span_lo.to(self.prev_token.span); 1,728 ( 0.00%) let span = lo.to(self.prev_token.span); 2,880 ( 0.00%) Ok(self.mk_expr(span, ExprKind::MethodCall(segment, args, fn_span), AttrVec::new())) . } else { . // Field access `expr.f` 668 ( 0.00%) if let Some(args) = segment.args { . self.struct_span_err( . args.span(), . "field expressions cannot have generic arguments", . ) . .emit(); . } . 1,002 ( 0.00%) let span = lo.to(self.prev_token.span); 1,670 ( 0.00%) Ok(self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), AttrVec::new())) . } . } . . /// At the bottom (top?) of the precedence hierarchy, . /// Parses things like parenthesized exprs, macros, `return`, etc. . /// . /// N.B., this does not parse outer attributes, and is private because it only works . /// correctly if called from `parse_dot_or_call_expr()`. . fn parse_bottom_expr(&mut self) -> PResult<'a, P> { 282,310 ( 0.00%) maybe_recover_from_interpolated_ty_qpath!(self, true); 422,047 ( 0.01%) maybe_whole_expr!(self); . . // Outer attributes are already parsed and will be . // added to the return value after the fact. . // . // Therefore, prevent sub-parser from parsing . // attributes by giving them an empty "already-parsed" list. 140,603 ( 0.00%) let attrs = AttrVec::new(); . . // Note: when adding new syntax here, don't forget to adjust `TokenKind::can_begin_expr()`. 2,352 ( 0.00%) let lo = self.token.span; 421,809 ( 0.01%) if let token::Literal(_) = self.token.kind { . // This match arm is a special-case of the `_` match arm below and . // could be removed without changing functionality, but it's faster . // to have it here, especially for programs with large constants. 553,004 ( 0.01%) self.parse_lit_expr(attrs) 11,760 ( 0.00%) } else if self.check(&token::OpenDelim(token::Paren)) { 351 ( 0.00%) self.parse_tuple_parens_expr(attrs) 11,175 ( 0.00%) } else if self.check(&token::OpenDelim(token::Brace)) { 456 ( 0.00%) self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs) 21,675 ( 0.00%) } else if self.check(&token::BinOp(token::Or)) || self.check(&token::OrOr) { 84 ( 0.00%) self.parse_closure_expr(attrs) 10,785 ( 0.00%) } else if self.check(&token::OpenDelim(token::Bracket)) { 2,760 ( 0.00%) self.parse_array_or_repeat_expr(attrs, token::Bracket) 6,420 ( 0.00%) } else if self.check_path() { 5,564 ( 0.00%) self.parse_path_start_expr(attrs) 2,130 ( 0.00%) } else if self.check_keyword(kw::Move) || self.check_keyword(kw::Static) { 8 ( 0.00%) self.parse_closure_expr(attrs) 1,060 ( 0.00%) } else if self.eat_keyword(kw::If) { 320 ( 0.00%) self.parse_if_expr(attrs) 660 ( 0.00%) } else if self.check_keyword(kw::For) { 55 ( 0.00%) if self.choose_generics_over_qpath(1) { . // NOTE(Centril, eddyb): DO NOT REMOVE! Beyond providing parser recovery, . // this is an insurance policy in case we allow qpaths in (tuple-)struct patterns. . // When `for ::Proj in $expr $block` is wanted, . // you can disambiguate in favor of a pattern with `(...)`. . self.recover_quantified_closure_expr(attrs) . } else { 55 ( 0.00%) assert!(self.eat_keyword(kw::For)); 77 ( 0.00%) self.parse_for_expr(None, self.prev_token.span, attrs) . } 605 ( 0.00%) } else if self.eat_keyword(kw::While) { 49 ( 0.00%) self.parse_while_expr(None, self.prev_token.span, attrs) 456 ( 0.00%) } else if let Some(label) = self.eat_label() { . self.parse_labeled_expr(label, attrs, true) 570 ( 0.00%) } else if self.eat_keyword(kw::Loop) { 7 ( 0.00%) self.parse_loop_expr(None, self.prev_token.span, attrs) 565 ( 0.00%) } else if self.eat_keyword(kw::Continue) { 5 ( 0.00%) let kind = ExprKind::Continue(self.eat_label()); 4 ( 0.00%) Ok(self.mk_expr(lo.to(self.prev_token.span), kind, attrs)) 448 ( 0.00%) } else if self.eat_keyword(kw::Match) { 82 ( 0.00%) let match_sp = self.prev_token.span; 328 ( 0.00%) self.parse_match_expr(attrs).map_err(|mut err| { . err.span_label(match_sp, "while parsing this match expression"); . err . }) 284 ( 0.00%) } else if self.eat_keyword(kw::Unsafe) { 104 ( 0.00%) self.parse_block_expr(None, lo, BlockCheckMode::Unsafe(ast::UserProvided), attrs) 232 ( 0.00%) } else if self.check_inline_const(0) { . self.parse_const_block(lo.to(self.token.span), false) 174 ( 0.00%) } else if self.is_do_catch_block() { . self.recover_do_catch(attrs) 174 ( 0.00%) } else if self.is_try_block() { . self.expect_keyword(kw::Try)?; . self.parse_try_block(lo, attrs) 232 ( 0.00%) } else if self.eat_keyword(kw::Return) { 76 ( 0.00%) self.parse_return_expr(attrs) 156 ( 0.00%) } else if self.eat_keyword(kw::Break) { 20 ( 0.00%) self.parse_break_expr(attrs) 136 ( 0.00%) } else if self.eat_keyword(kw::Yield) { . self.parse_yield_expr(attrs) 136 ( 0.00%) } else if self.eat_keyword(kw::Let) { 60 ( 0.00%) self.parse_let_expr(attrs) 76 ( 0.00%) } else if self.eat_keyword(kw::Underscore) { . Ok(self.mk_expr(self.prev_token.span, ExprKind::Underscore, attrs)) 19 ( 0.00%) } else if !self.unclosed_delims.is_empty() && self.check(&token::Semi) { . // Don't complain about bare semicolons after unclosed braces . // recovery in order to keep the error count down. Fixing the . // delimiters will possibly also fix the bare semicolon found in . // expression context. For example, silence the following error: . // . // error: expected expression, found `;` . // --> file.rs:2:13 . // | . // 2 | foo(bar(; . // | ^ expected expression . self.bump(); . Ok(self.mk_expr_err(self.token.span)) 38 ( 0.00%) } else if self.token.uninterpolated_span().rust_2018() { . // `Span::rust_2018()` is somewhat expensive; don't get it repeatedly. . if self.check_keyword(kw::Async) { . if self.is_async_block() { . // Check for `async {` and `async move {`. . self.parse_async_block(attrs) . } else { . self.parse_closure_expr(attrs) . } . } else if self.eat_keyword(kw::Await) { . self.recover_incorrect_await_syntax(lo, self.prev_token.span, attrs) . } else { . self.parse_lit_expr(attrs) . } . } else { 76 ( 0.00%) self.parse_lit_expr(attrs) . } . } . 1,382,700 ( 0.02%) fn parse_lit_expr(&mut self, attrs: AttrVec) -> PResult<'a, P> { 276,540 ( 0.00%) let lo = self.token.span; 553,080 ( 0.01%) match self.parse_opt_lit() { 829,620 ( 0.01%) Some(literal) => { 1,244,430 ( 0.02%) let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Lit(literal), attrs); 1,382,700 ( 0.02%) self.maybe_recover_from_bad_qpath(expr, true) . } . None => self.try_macro_suggestion(), . } . } . . fn parse_tuple_parens_expr(&mut self, attrs: AttrVec) -> PResult<'a, P> { 234 ( 0.00%) let lo = self.token.span; 351 ( 0.00%) self.expect(&token::OpenDelim(token::Paren))?; . let (es, trailing_comma) = match self.parse_seq_to_end( . &token::CloseDelim(token::Paren), . SeqSep::trailing_allowed(token::Comma), 446 ( 0.00%) |p| p.parse_expr_catch_underscore(), . ) { . Ok(x) => x, . Err(err) => return Ok(self.recover_seq_parse_error(token::Paren, lo, Err(err))), . }; 585 ( 0.00%) let kind = if es.len() == 1 && !trailing_comma { . // `(e)` is parenthesized `e`. 33 ( 0.00%) ExprKind::Paren(es.into_iter().next().unwrap()) . } else { . // `(e,)` is a tuple with only one field, `e`. 530 ( 0.00%) ExprKind::Tup(es) . }; 351 ( 0.00%) let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs); 351 ( 0.00%) self.maybe_recover_from_bad_qpath(expr, true) . } . 6,072 ( 0.00%) fn parse_array_or_repeat_expr( . &mut self, . attrs: AttrVec, . close_delim: token::DelimToken, . ) -> PResult<'a, P> { 1,656 ( 0.00%) let lo = self.token.span; 552 ( 0.00%) self.bump(); // `[` or other open delim . 1,656 ( 0.00%) let close = &token::CloseDelim(close_delim); . let kind = if self.eat(close) { . // Empty vector 99 ( 0.00%) ExprKind::Array(Vec::new()) . } else { . // Non-empty vector 906 ( 0.00%) let first_expr = self.parse_expr()?; . if self.eat(&token::Semi) { . // Repeating array syntax: `[ 0; 512 ]` . let count = self.parse_anon_const_expr()?; . self.expect(close)?; . ExprKind::Repeat(first_expr, count) . } else if self.eat(&token::Comma) { . // Vector with two or more elements. . let sep = SeqSep::trailing_allowed(token::Comma); . let (remaining_exprs, _) = self.parse_seq_to_end(close, sep, |p| p.parse_expr())?; 451 ( 0.00%) let mut exprs = vec![first_expr]; . exprs.extend(remaining_exprs); 2,255 ( 0.00%) ExprKind::Array(exprs) . } else { . // Vector with one element 4 ( 0.00%) self.expect(close)?; 10 ( 0.00%) ExprKind::Array(vec![first_expr]) . } . }; 1,656 ( 0.00%) let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs); 1,656 ( 0.00%) self.maybe_recover_from_bad_qpath(expr, true) 5,520 ( 0.00%) } . 13,910 ( 0.00%) fn parse_path_start_expr(&mut self, attrs: AttrVec) -> PResult<'a, P> { 11,128 ( 0.00%) let (qself, path) = if self.eat_lt() { . let (qself, path) = self.parse_qpath(PathStyle::Expr)?; . (Some(qself), path) . } else { 2,782 ( 0.00%) (None, self.parse_path(PathStyle::Expr)?) . }; 1,391 ( 0.00%) let lo = path.span; . . // `!`, as an operator, is prefix, so we know this isn't that. 19,215 ( 0.00%) let (hi, kind) = if self.eat(&token::Not) { . // MACRO INVOCATION expression 64 ( 0.00%) if qself.is_some() { . self.struct_span_err(path.span, "macros cannot use qualified paths").emit(); . } 384 ( 0.00%) let mac = MacCall { 448 ( 0.00%) path, . args: self.parse_mac_args()?, . prior_type_ascription: self.last_type_ascription, . }; 1,408 ( 0.00%) (self.prev_token.span, ExprKind::MacCall(mac)) 6,635 ( 0.00%) } else if self.check(&token::OpenDelim(token::Brace)) { 220 ( 0.00%) if let Some(expr) = self.maybe_parse_struct_expr(qself.as_ref(), &path, &attrs) { 110 ( 0.00%) if qself.is_some() { . self.sess.gated_spans.gate(sym::more_qualified_paths, path.span); . } . return expr; . } else { . (path.span, ExprKind::Path(qself, path)) . } . } else { . (path.span, ExprKind::Path(qself, path)) . }; . 2,562 ( 0.00%) let expr = self.mk_expr(lo.to(hi), kind, attrs); 3,843 ( 0.00%) self.maybe_recover_from_bad_qpath(expr, true) 16,472 ( 0.00%) } . . /// Parse `'label: $expr`. The label is already parsed. . fn parse_labeled_expr( . &mut self, . label: Label, . attrs: AttrVec, . mut consume_colon: bool, . ) -> PResult<'a, P> { -- line 1447 ---------------------------------------- -- line 1507 ---------------------------------------- . .note("following RFC #2388, the new non-placeholder syntax is `try`") . .emit(); . . self.parse_try_block(lo, attrs) . } . . /// Parse an expression if the token can begin one. . fn parse_expr_opt(&mut self) -> PResult<'a, Option>> { 113 ( 0.00%) Ok(if self.token.can_begin_expr() { Some(self.parse_expr()?) } else { None }) . } . . /// Parse `"return" expr?`. 190 ( 0.00%) fn parse_return_expr(&mut self, attrs: AttrVec) -> PResult<'a, P> { 19 ( 0.00%) let lo = self.prev_token.span; 38 ( 0.00%) let kind = ExprKind::Ret(self.parse_expr_opt()?); 57 ( 0.00%) let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs); 114 ( 0.00%) self.maybe_recover_from_bad_qpath(expr, true) 190 ( 0.00%) } . . /// Parse `"break" (('label (:? expr)?) | expr?)` with `"break"` token already eaten. . /// If the label is followed immediately by a `:` token, the label and `:` are . /// parsed as part of the expression (i.e. a labeled loop). The language team has . /// decided in #87026 to require parentheses as a visual aid to avoid confusion if . /// the break expression of an unlabeled break is a labeled loop (as in . /// `break 'lbl: loop {}`); a labeled break with an unlabeled loop as its value . /// expression only gets a warning for compatibility reasons; and a labeled break . /// with a labeled loop does not even get a warning because there is no ambiguity. 50 ( 0.00%) fn parse_break_expr(&mut self, attrs: AttrVec) -> PResult<'a, P> { 10 ( 0.00%) let lo = self.prev_token.span; . let mut label = self.eat_label(); . let kind = if label.is_some() && self.token == token::Colon { . // The value expression can be a labeled loop, see issue #86948, e.g.: . // `loop { break 'label: loop { break 'label 42; }; }` . let lexpr = self.parse_labeled_expr(label.take().unwrap(), AttrVec::new(), true)?; . self.struct_span_err( . lexpr.span, . "parentheses are required around this expression to avoid confusion with a labeled break expression", -- line 1543 ---------------------------------------- -- line 1547 ---------------------------------------- . vec![ . (lexpr.span.shrink_to_lo(), "(".to_string()), . (lexpr.span.shrink_to_hi(), ")".to_string()), . ], . Applicability::MachineApplicable, . ) . .emit(); . Some(lexpr) 10 ( 0.00%) } else if self.token != token::OpenDelim(token::Brace) . || !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL) . { . let expr = self.parse_expr_opt()?; . if let Some(ref expr) = expr { . if label.is_some() . && matches!( . expr.kind, . ExprKind::While(_, _, None) -- line 1563 ---------------------------------------- -- line 1570 ---------------------------------------- . BREAK_WITH_LABEL_AND_LOOP, . lo.to(expr.span), . ast::CRATE_NODE_ID, . "this labeled break expression is easy to confuse with an unlabeled break with a labeled value expression", . BuiltinLintDiagnostics::BreakWithLabelAndLoop(expr.span), . ); . } . } 10 ( 0.00%) expr . } else { . None . }; 15 ( 0.00%) let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Break(label, kind), attrs); 25 ( 0.00%) self.maybe_recover_from_bad_qpath(expr, true) 50 ( 0.00%) } . . /// Parse `"yield" expr?`. . fn parse_yield_expr(&mut self, attrs: AttrVec) -> PResult<'a, P> { . let lo = self.prev_token.span; . let kind = ExprKind::Yield(self.parse_expr_opt()?); . let span = lo.to(self.prev_token.span); . self.sess.gated_spans.gate(sym::generators, span); . let expr = self.mk_expr(span, kind, attrs); -- line 1592 ---------------------------------------- -- line 1607 ---------------------------------------- . symbol_unescaped, . }), . _ => Err(Some(lit)), . }, . None => Err(None), . } . } . 1,764 ( 0.00%) pub(super) fn parse_lit(&mut self) -> PResult<'a, Lit> { 196 ( 0.00%) self.parse_opt_lit().ok_or_else(|| { 308 ( 0.00%) if let token::Interpolated(inner) = &self.token.kind { . let expr = match inner.as_ref() { . token::NtExpr(expr) => Some(expr), . token::NtLiteral(expr) => Some(expr), . _ => None, . }; . if let Some(expr) = expr { . if matches!(expr.kind, ExprKind::Err) { . self.diagnostic() . .delay_span_bug(self.token.span, &"invalid interpolated expression"); . return self.diagnostic().struct_dummy(); . } . } . } 1,694 ( 0.00%) let msg = format!("unexpected token: {}", super::token_descr(&self.token)); 154 ( 0.00%) self.struct_span_err(self.token.span, &msg) . }) 1,372 ( 0.00%) } . . /// Matches `lit = true | false | token_lit`. . /// Returns `None` if the next token is not a literal. 1,246,194 ( 0.02%) pub(super) fn parse_opt_lit(&mut self) -> Option { 138,466 ( 0.00%) let mut recovered = None; 830,796 ( 0.01%) if self.token == token::Dot { . // Attempt to recover `.4` as `0.4`. We don't currently have any syntax where . // dot would follow an optional literal, so we do this unconditionally. . recovered = self.look_ahead(1, |next_token| { . if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = . next_token.kind . { . if self.token.span.hi() == next_token.span.lo() { . let s = String::from("0.") + symbol.as_str(); -- line 1648 ---------------------------------------- -- line 1654 ---------------------------------------- . }); . if let Some(token) = &recovered { . self.bump(); . self.error_float_lits_must_have_int_part(&token); . } . } . . let token = recovered.as_ref().unwrap_or(&self.token); 415,860 ( 0.01%) match Lit::from_token(token) { 829,872 ( 0.01%) Ok(lit) => { 276,624 ( 0.00%) self.bump(); 829,872 ( 0.01%) Some(lit) . } 154 ( 0.00%) Err(LitError::NotLiteral) => None, . Err(err) => { . let span = token.span; . let lit = match token.kind { . token::Literal(lit) => lit, . _ => unreachable!(), . }; . self.bump(); . self.report_lit_error(err, lit, span); -- line 1675 ---------------------------------------- -- line 1676 ---------------------------------------- . // Pack possible quotes and prefixes from the original literal into . // the error literal's symbol so they can be pretty-printed faithfully. . let suffixless_lit = token::Lit::new(lit.kind, lit.symbol, None); . let symbol = Symbol::intern(&suffixless_lit.to_string()); . let lit = token::Lit::new(token::Err, symbol, lit.suffix); . Some(Lit::from_lit_token(lit, span).unwrap_or_else(|_| unreachable!())) . } . } 1,107,728 ( 0.02%) } . . fn error_float_lits_must_have_int_part(&self, token: &Token) { . self.struct_span_err(token.span, "float literals must have an integer part") . .span_suggestion( . token.span, . "must have an integer part", . pprust::token_to_string(token).into(), . Applicability::MachineApplicable, -- line 1692 ---------------------------------------- -- line 1759 ---------------------------------------- . .emit(); . } . LitError::IntTooLarge => { . self.struct_span_err(span, "integer literal is too large").emit(); . } . } . } . 168 ( 0.00%) pub(super) fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option) { 48 ( 0.00%) if let Some(suf) = suffix { . let mut err = if kind == "a tuple index" . && [sym::i32, sym::u32, sym::isize, sym::usize].contains(&suf) . { . // #59553: warn instead of reject out of hand to allow the fix to percolate . // through the ecosystem when people fix their macros . let mut err = self . .sess . .span_diagnostic -- line 1776 ---------------------------------------- -- line 1791 ---------------------------------------- . ); . err . } else { . self.struct_span_err(sp, &format!("suffixes on {} are invalid", kind)) . }; . err.span_label(sp, format!("invalid suffix `{}`", suf)); . err.emit(); . } 144 ( 0.00%) } . . /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`). . /// Keep this in sync with `Token::can_begin_literal_maybe_minus`. 248 ( 0.00%) pub fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P> { 62 ( 0.00%) maybe_whole_expr!(self); . 31 ( 0.00%) let lo = self.token.span; . let minus_present = self.eat(&token::BinOp(token::Minus)); 62 ( 0.00%) let lit = self.parse_lit()?; 31 ( 0.00%) let expr = self.mk_expr(lit.span, ExprKind::Lit(lit), AttrVec::new()); . 62 ( 0.00%) if minus_present { . Ok(self.mk_expr( . lo.to(self.prev_token.span), . self.mk_unary(UnOp::Neg, expr), . AttrVec::new(), . )) . } else { . Ok(expr) . } 279 ( 0.00%) } . . fn is_array_like_block(&mut self) -> bool { 212 ( 0.00%) self.look_ahead(1, |t| matches!(t.kind, TokenKind::Ident(..) | TokenKind::Literal(_))) . && self.look_ahead(2, |t| t == &token::Comma) . && self.look_ahead(3, |t| t.can_begin_expr()) . } . . /// Emits a suggestion if it looks like the user meant an array but . /// accidentally used braces, causing the code to be interpreted as a block . /// expression. . fn maybe_suggest_brackets_instead_of_braces( -- line 1831 ---------------------------------------- -- line 1855 ---------------------------------------- . Err(mut e) => { . e.cancel(); . None . } . } . } . . /// Parses a block or unsafe block. 980 ( 0.00%) pub(super) fn parse_block_expr( . &mut self, . opt_label: Option

(&mut self, mut predicate: P) -> Option . where . Self: Sized, . P: FnMut(&Self::Item) -> bool, . { 13,154 ( 0.00%) while let Some(x) = self.next() { 36,202 ( 0.00%) if predicate(&x) { . return Some(x); . } . } . None 472 ( 0.00%) } . . // We override the default implementation, which uses `try_fold`, . // because this simple implementation generates less LLVM IR and is . // faster to compile. . #[inline] . fn find_map(&mut self, mut f: F) -> Option . where . Self: Sized, . F: FnMut(Self::Item) -> Option, . { 29,630 ( 0.00%) while let Some(x) = self.next() { 396,371 ( 0.01%) if let Some(y) = f(x) { 20,850 ( 0.00%) return Some(y); . } . } . None 3,824 ( 0.00%) } . . // We override the default implementation, which uses `try_fold`, . // because this simple implementation generates less LLVM IR and is . // faster to compile. Also, the `assume` avoids a bounds check. . #[inline] . #[rustc_inherit_overflow_checks] . fn position

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

(&mut self, mut predicate: P) -> Option where . P: FnMut(Self::Item) -> bool, . Self: Sized + ExactSizeIterator + DoubleEndedIterator . { . let n = len!(self); . let mut i = n; 36,404 ( 0.00%) while let Some(x) = self.next_back() { 490,365 ( 0.01%) i -= 1; 403,876 ( 0.01%) if predicate(x) { . // SAFETY: `i` must be lower than `n` since it starts at `n` . // and is only decreasing. . unsafe { assume(i < n) }; . return Some(i); . } . } . None . } -- line 326 ---------------------------------------- -- line 332 ---------------------------------------- . // the returned references is guaranteed to refer to an element . // of the slice and thus guaranteed to be valid. . // . // Also note that the caller also guarantees that we're never . // called with the same index again, and that no other methods . // that will access this subslice are called, so it is valid . // for the returned reference to be mutable in the case of . // `IterMut` 57,004 ( 0.00%) unsafe { & $( $mut_ )? * self.ptr.as_ptr().add(idx) } . } . . $($extra)* . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl<'a, T> DoubleEndedIterator for $name<'a, T> { . #[inline] -- line 348 ---------------------------------------- -- line 349 ---------------------------------------- . fn next_back(&mut self) -> Option<$elem> { . // could be implemented with slices, but this avoids bounds checks . . // SAFETY: `assume` calls are safe since a slice's start pointer must be non-null, . // and slices over non-ZSTs must also have a non-null end pointer. . // The call to `next_back_unchecked!` is safe since we check if the iterator is . // empty first. . unsafe { 1,090 ( 0.00%) assume(!self.ptr.as_ptr().is_null()); . if mem::size_of::() != 0 { 1,111 ( 0.00%) assume(!self.end.is_null()); . } 1,486,934 ( 0.02%) if is_empty!(self) { . None . } else { . Some(next_back_unchecked!(self)) . } . } . } . . #[inline] -- line 369 ---------------------------------------- 13,977,544 ( 0.20%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/regionck.rs -------------------------------------------------------------------------------- Ir -- line 125 ---------------------------------------- . /// fn foo<'a, 'b, T>(x: &'a &'b [T]) { } . /// ``` . /// . /// we can assume in the caller's body that `'b: 'a` and that `T: . /// 'b` (and hence, transitively, that `T: 'a`). This method would . /// add those assumptions into the outlives-environment. . /// . /// Tests: `src/test/ui/regions/regions-free-region-ordering-*.rs` 14,736 ( 0.00%) fn add_implied_bounds<'a>( . &mut self, . infcx: &InferCtxt<'a, 'tcx>, . fn_sig_tys: FxHashSet>, . body_id: hir::HirId, . span: Span, . ) { . debug!("add_implied_bounds()"); . 26,164 ( 0.00%) for ty in fn_sig_tys { . let ty = infcx.resolve_vars_if_possible(ty); . debug!("add_implied_bounds: ty = {}", ty); 23,796 ( 0.00%) let implied_bounds = infcx.implied_outlives_bounds(self.param_env, body_id, ty, span); . self.add_outlives_bounds(Some(infcx), implied_bounds) . } 9,824 ( 0.00%) } . } . . /////////////////////////////////////////////////////////////////////////// . // PUBLIC ENTRY POINTS . . impl<'a, 'tcx> FnCtxt<'a, 'tcx> { 837 ( 0.00%) pub fn regionck_expr(&self, body: &'tcx hir::Body<'tcx>) { 651 ( 0.00%) let subject = self.tcx.hir().body_owner_def_id(body.id()); 186 ( 0.00%) let id = body.value.hir_id; 651 ( 0.00%) let mut rcx = RegionCtxt::new(self, id, Subject(subject), self.param_env); . . // There are no add'l implied bounds when checking a . // standalone expr (e.g., the `E` in a type like `[u32; E]`). 465 ( 0.00%) rcx.outlives_environment.save_implied_bounds(id); . 93 ( 0.00%) if !self.errors_reported_since_creation() { . // regionck assumes typeck succeeded . rcx.visit_body(body); . rcx.visit_region_obligations(id); . } 186 ( 0.00%) rcx.resolve_regions_and_report_errors(RegionckMode::for_item_body(self.tcx)); 837 ( 0.00%) } . . /// Region checking during the WF phase for items. `wf_tys` are the . /// types from which we should derive implied bounds, if any. 7,548 ( 0.00%) pub fn regionck_item(&self, item_id: hir::HirId, span: Span, wf_tys: FxHashSet>) { . debug!("regionck_item(item.id={:?}, wf_tys={:?})", item_id, wf_tys); 2,516 ( 0.00%) let subject = self.tcx.hir().local_def_id(item_id); 4,403 ( 0.00%) let mut rcx = RegionCtxt::new(self, item_id, Subject(subject), self.param_env); 6,919 ( 0.00%) rcx.outlives_environment.add_implied_bounds(self, wf_tys, item_id, span); 2,516 ( 0.00%) rcx.outlives_environment.save_implied_bounds(item_id); . rcx.visit_region_obligations(item_id); . rcx.resolve_regions_and_report_errors(RegionckMode::default()); 5,661 ( 0.00%) } . . /// Region check a function body. Not invoked on closures, but . /// only on the "root" fn item (in which closures may be . /// embedded). Walks the function body and adds various add'l . /// constraints that are needed for region inference. This is . /// separated both to isolate "pure" region constraints from the . /// rest of type check and because sometimes we need type . /// inference to have completed before we can determine which . /// constraints to add. 3,783 ( 0.00%) pub(crate) fn regionck_fn( . &self, . fn_id: hir::HirId, . body: &'tcx hir::Body<'tcx>, . span: Span, . wf_tys: FxHashSet>, . ) { . debug!("regionck_fn(id={})", fn_id); 1,746 ( 0.00%) let subject = self.tcx.hir().body_owner_def_id(body.id()); 582 ( 0.00%) let hir_id = body.value.hir_id; 1,455 ( 0.00%) let mut rcx = RegionCtxt::new(self, hir_id, Subject(subject), self.param_env); . // We need to add the implied bounds from the function signature 3,492 ( 0.00%) rcx.outlives_environment.add_implied_bounds(self, wf_tys, fn_id, span); 1,164 ( 0.00%) rcx.outlives_environment.save_implied_bounds(fn_id); . 291 ( 0.00%) if !self.errors_reported_since_creation() { . // regionck assumes typeck succeeded 3,201 ( 0.00%) rcx.visit_fn_body(fn_id, body, self.tcx.hir().span(fn_id)); . } . 582 ( 0.00%) rcx.resolve_regions_and_report_errors(RegionckMode::for_item_body(self.tcx)); 2,619 ( 0.00%) } . } . . /////////////////////////////////////////////////////////////////////////// . // INTERNALS . . pub struct RegionCtxt<'a, 'tcx> { . pub fcx: &'a FnCtxt<'a, 'tcx>, . -- line 221 ---------------------------------------- -- line 229 ---------------------------------------- . . // id of AST node being analyzed (the subject of the analysis). . subject_def_id: LocalDefId, . } . . impl<'a, 'tcx> Deref for RegionCtxt<'a, 'tcx> { . type Target = FnCtxt<'a, 'tcx>; . fn deref(&self) -> &Self::Target { 455,412 ( 0.01%) self.fcx . } . } . . pub struct Subject(LocalDefId); . . impl<'a, 'tcx> RegionCtxt<'a, 'tcx> { 11,143 ( 0.00%) pub fn new( . fcx: &'a FnCtxt<'a, 'tcx>, . initial_body_id: hir::HirId, . Subject(subject): Subject, . param_env: ty::ParamEnv<'tcx>, . ) -> RegionCtxt<'a, 'tcx> { 1,013 ( 0.00%) let region_scope_tree = fcx.tcx.region_scope_tree(subject); 2,026 ( 0.00%) let outlives_environment = OutlivesEnvironment::new(param_env); 7,091 ( 0.00%) RegionCtxt { . fcx, . region_scope_tree, . body_id: initial_body_id, . body_owner: subject, . subject_def_id: subject, 4,052 ( 0.00%) outlives_environment, . } 9,117 ( 0.00%) } . . /// Try to resolve the type for the given node, returning `t_err` if an error results. Note that . /// we never care about the details of the error, the same error will be detected and reported . /// in the writeback phase. . /// . /// Note one important point: we do not attempt to resolve *region variables* here. This is . /// because regionck is essentially adding constraints to those region variables and so may yet . /// influence how they are resolved. -- line 268 ---------------------------------------- -- line 283 ---------------------------------------- . /// of b will be `&.i32` and then `*b` will require that `` be bigger than the let and . /// the `*b` expression, so we will effectively resolve `` to be the block B. . pub fn resolve_type(&self, unresolved_ty: Ty<'tcx>) -> Ty<'tcx> { . self.resolve_vars_if_possible(unresolved_ty) . } . . /// Try to resolve the type for the given node. . fn resolve_node_type(&self, id: hir::HirId) -> Ty<'tcx> { 1,941 ( 0.00%) let t = self.node_ty(id); 1,601 ( 0.00%) self.resolve_type(t) . } . . /// This is the "main" function when region-checking a function item or a . /// closure within a function item. It begins by updating various fields . /// (e.g., `outlives_environment`) to be appropriate to the function and . /// then adds constraints derived from the function body. . /// . /// Note that it does **not** restore the state of the fields that . /// it updates! This is intentional, since -- for the main . /// function -- we wish to be able to read the final . /// `outlives_environment` and other fields from the caller. For . /// closures, however, we save and restore any "scoped state" . /// before we invoke this function. (See `visit_fn` in the . /// `intravisit::Visitor` impl below.) 4,312 ( 0.00%) fn visit_fn_body( . &mut self, . id: hir::HirId, // the id of the fn itself . body: &'tcx hir::Body<'tcx>, . span: Span, . ) { . // When we enter a function, we can derive . debug!("visit_fn_body(id={:?})", id); . 1,232 ( 0.00%) let body_id = body.id(); 616 ( 0.00%) self.body_id = body_id.hir_id; 2,156 ( 0.00%) self.body_owner = self.tcx.hir().body_owner_def_id(body_id); . . let fn_sig = { 3,080 ( 0.00%) match self.typeck_results.borrow().liberated_fn_sigs().get(id) { 616 ( 0.00%) Some(f) => *f, . None => { . bug!("No fn-sig entry for id={:?}", id); . } . } . }; . . // Collect the types from which we create inferred bounds. . // For the return type, if diverging, substitute `bool` just . // because it will have no effect. . // . // FIXME(#27579) return types should not be implied bounds . let fn_sig_tys: FxHashSet<_> = 1,540 ( 0.00%) fn_sig.inputs().iter().cloned().chain(Some(fn_sig.output())).collect(); . 4,004 ( 0.00%) self.outlives_environment.add_implied_bounds(self.fcx, fn_sig_tys, body_id.hir_id, span); 1,540 ( 0.00%) self.outlives_environment.save_implied_bounds(body_id.hir_id); 616 ( 0.00%) self.link_fn_params(body.params); . self.visit_body(body); . self.visit_region_obligations(body_id.hir_id); 2,464 ( 0.00%) } . . fn visit_inline_const(&mut self, id: hir::HirId, body: &'tcx hir::Body<'tcx>) { . debug!("visit_inline_const(id={:?})", id); . . // Save state of current function. We will restore afterwards. . let old_body_id = self.body_id; . let old_body_owner = self.body_owner; . let env_snapshot = self.outlives_environment.push_snapshot_pre_typeck_child(); -- line 350 ---------------------------------------- -- line 365 ---------------------------------------- . } . . fn visit_region_obligations(&mut self, hir_id: hir::HirId) { . debug!("visit_region_obligations: hir_id={:?}", hir_id); . . // region checking can introduce new pending obligations . // which, when processed, might generate new region . // obligations. So make sure we process those. 1,030 ( 0.00%) self.select_all_obligations_or_error(); . } . . fn resolve_regions_and_report_errors(&self, mode: RegionckMode) { 3,039 ( 0.00%) self.infcx.process_registered_region_obligations( 2,026 ( 0.00%) self.outlives_environment.region_bound_pairs_map(), 2,026 ( 0.00%) Some(self.tcx.lifetimes.re_root_empty), 1,013 ( 0.00%) self.param_env, . ); . 5,065 ( 0.00%) self.fcx.resolve_regions_and_report_errors( 1,013 ( 0.00%) self.subject_def_id.to_def_id(), . &self.outlives_environment, . mode, . ); . } . . fn constrain_bindings_in_pat(&mut self, pat: &hir::Pat<'_>) { . debug!("regionck::visit_pat(pat={:?})", pat); . pat.each_binding(|_, hir_id, span, _| { 416 ( 0.00%) let typ = self.resolve_node_type(hir_id); 832 ( 0.00%) let body_id = self.body_id; 1,664 ( 0.00%) dropck::check_drop_obligations(self, typ, span, body_id); . }) . } . } . . impl<'a, 'tcx> Visitor<'tcx> for RegionCtxt<'a, 'tcx> { . // (..) FIXME(#3238) should use visit_pat, not visit_arm/visit_local, . // However, right now we run into an issue whereby some free . // regions are not properly related if they appear within the -- line 403 ---------------------------------------- -- line 416 ---------------------------------------- . ) { . assert!( . matches!(fk, intravisit::FnKind::Closure), . "visit_fn invoked for something other than a closure" . ); . . // Save state of current function before invoking . // `visit_fn_body`. We will restore afterwards. 34 ( 0.00%) let old_body_id = self.body_id; 34 ( 0.00%) let old_body_owner = self.body_owner; 68 ( 0.00%) let env_snapshot = self.outlives_environment.push_snapshot_pre_typeck_child(); . 102 ( 0.00%) let body = self.tcx.hir().body(body_id); 102 ( 0.00%) self.visit_fn_body(hir_id, body, span); . . // Restore state from previous function. 68 ( 0.00%) self.outlives_environment.pop_snapshot_post_typeck_child(env_snapshot); 34 ( 0.00%) self.body_id = old_body_id; 34 ( 0.00%) self.body_owner = old_body_owner; . } . . //visit_pat: visit_pat, // (..) see above . . fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) { . // see above 1,449 ( 0.00%) self.constrain_bindings_in_pat(arm.pat); . intravisit::walk_arm(self, arm); . } . 1,776 ( 0.00%) fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) { . // see above 1,554 ( 0.00%) self.constrain_bindings_in_pat(l.pat); . self.link_local(l); . intravisit::walk_local(self, l); 1,554 ( 0.00%) } . 1,164,624 ( 0.02%) fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) { . // Check any autoderefs or autorefs that appear. . let cmt_result = self.constrain_adjustments(expr); . . // If necessary, constrain destructors in this expression. This will be . // the adjusted form if there is an adjustment. 293,454 ( 0.00%) match cmt_result { 1,310,202 ( 0.02%) Ok(head_cmt) => { . self.check_safety_of_rvalue_destructor_if_necessary(&head_cmt, expr.span); . } . Err(..) => { . self.tcx.sess.delay_span_bug(expr.span, "cat_expr Errd"); . } . } . 1,020,842 ( 0.01%) match expr.kind { . hir::ExprKind::AddrOf(hir::BorrowKind::Ref, m, ref base) => { . self.link_addr_of(expr, m, base); . . intravisit::walk_expr(self, expr); . } . . hir::ExprKind::Match(ref discr, arms, _) => { . self.link_match(discr, arms); -- line 475 ---------------------------------------- -- line 479 ---------------------------------------- . . hir::ExprKind::ConstBlock(anon_const) => { . let body = self.tcx.hir().body(anon_const.body); . self.visit_inline_const(anon_const.hir_id, body); . } . . _ => intravisit::walk_expr(self, expr), . } 1,164,624 ( 0.02%) } . } . . impl<'a, 'tcx> RegionCtxt<'a, 'tcx> { . /// Creates a temporary `MemCategorizationContext` and pass it to the closure. . fn with_mc(&self, f: F) -> R . where . F: for<'b> FnOnce(mc::MemCategorizationContext<'b, 'tcx>) -> R, . { 1,559,923 ( 0.02%) f(mc::MemCategorizationContext::new( . &self.infcx, . self.outlives_environment.param_env, . self.body_owner, 152,618 ( 0.00%) &self.typeck_results.borrow(), . )) . } . . /// Invoked on any adjustments that occur. Checks that if this is a region pointer being . /// dereferenced, the lifetime of the pointer includes the deref expr. . fn constrain_adjustments( . &mut self, . expr: &hir::Expr<'_>, . ) -> mc::McResult> { . debug!("constrain_adjustments(expr={:?})", expr); . 291,156 ( 0.00%) let mut place = self.with_mc(|mc| mc.cat_expr_unadjusted(expr))?; . 145,578 ( 0.00%) let typeck_results = self.typeck_results.borrow(); 145,578 ( 0.00%) let adjustments = typeck_results.expr_adjustments(expr); 145,578 ( 0.00%) if adjustments.is_empty() { 1,289,520 ( 0.02%) return Ok(place); . } . . debug!("constrain_adjustments: adjustments={:?}", adjustments); . . // If necessary, constrain destructors in the unadjusted form of this . // expression. . self.check_safety_of_rvalue_destructor_if_necessary(&place, expr.span); . . for adjustment in adjustments { . debug!("constrain_adjustments: adjustment={:?}, place={:?}", adjustment, place); . 18,641 ( 0.00%) if let adjustment::Adjust::Deref(Some(deref)) = adjustment.kind { 125 ( 0.00%) self.link_region( 25 ( 0.00%) expr.span, . deref.region, 100 ( 0.00%) ty::BorrowKind::from_mutbl(deref.mutbl), . &place, . ); . } . 5,333 ( 0.00%) if let adjustment::Adjust::Borrow(ref autoref) = adjustment.kind { . self.link_autoref(expr, &place, autoref); . } . 66,195 ( 0.00%) place = self.with_mc(|mc| mc.cat_expr_adjusted(expr, place, adjustment))?; . } . 22,980 ( 0.00%) Ok(place) . } . . fn check_safety_of_rvalue_destructor_if_necessary( . &mut self, . place_with_id: &PlaceWithHirId<'tcx>, . span: Span, . ) { 295,752 ( 0.00%) if let PlaceBase::Rvalue = place_with_id.place.base { 145,486 ( 0.00%) if place_with_id.place.projections.is_empty() { 148,960 ( 0.00%) let typ = self.resolve_type(place_with_id.place.ty()); 290,900 ( 0.00%) let body_id = self.body_id; 581,800 ( 0.01%) dropck::check_drop_obligations(self, typ, span, body_id); . } . } . } . /// Adds constraints to inference such that `T: 'a` holds (or . /// reports an error if it cannot). . /// . /// # Parameters . /// -- line 565 ---------------------------------------- -- line 567 ---------------------------------------- . /// - `ty`, the type `T` . /// - `region`, the region `'a` . pub fn type_must_outlive( . &self, . origin: infer::SubregionOrigin<'tcx>, . ty: Ty<'tcx>, . region: ty::Region<'tcx>, . ) { 9,177 ( 0.00%) self.infcx.register_region_obligation( 9,177 ( 0.00%) self.body_id, 24,472 ( 0.00%) RegionObligation { sub_region: region, sup_type: ty, origin }, . ); . } . . /// Computes the guarantor for an expression `&base` and then ensures that the lifetime of the . /// resulting pointer is linked to the lifetime of its guarantor (if any). . fn link_addr_of( . &mut self, . expr: &hir::Expr<'_>, . mutability: hir::Mutability, . base: &hir::Expr<'_>, . ) { . debug!("link_addr_of(expr={:?}, base={:?})", expr, base); . 11,143 ( 0.00%) let cmt = ignore_err!(self.with_mc(|mc| mc.cat_expr(base))); . . debug!("link_addr_of: cmt={:?}", cmt); . 3,039 ( 0.00%) self.link_region_from_node_type(expr.span, expr.hir_id, mutability, &cmt); . } . . /// Computes the guarantors for any ref bindings in a `let` and . /// then ensures that the lifetime of the resulting pointer is . /// linked to the lifetime of the initialization expression. . fn link_local(&self, local: &hir::Local<'_>) { . debug!("regionck::for_local()"); 666 ( 0.00%) let init_expr = match local.init { . None => { . return; . } . Some(expr) => &*expr, . }; 2,040 ( 0.00%) let discr_cmt = ignore_err!(self.with_mc(|mc| mc.cat_expr(init_expr))); 1,632 ( 0.00%) self.link_pattern(discr_cmt, local.pat); . } . . /// Computes the guarantors for any ref bindings in a match and . /// then ensures that the lifetime of the resulting pointer is . /// linked to the lifetime of its guarantor (if any). . fn link_match(&self, discr: &hir::Expr<'_>, arms: &[hir::Arm<'_>]) { . debug!("regionck::for_match()"); 1,150 ( 0.00%) let discr_cmt = ignore_err!(self.with_mc(|mc| mc.cat_expr(discr))); . debug!("discr_cmt={:?}", discr_cmt); . for arm in arms { 828 ( 0.00%) self.link_pattern(discr_cmt.clone(), arm.pat); . } . } . . /// Computes the guarantors for any ref bindings in a match and . /// then ensures that the lifetime of the resulting pointer is . /// linked to the lifetime of its guarantor (if any). . fn link_fn_params(&self, params: &[hir::Param<'_>]) { . for param in params { 1,768 ( 0.00%) let param_ty = self.node_ty(param.hir_id); . let param_cmt = 884 ( 0.00%) self.with_mc(|mc| mc.cat_rvalue(param.hir_id, param.pat.span, param_ty)); . debug!("param_ty={:?} param_cmt={:?} param={:?}", param_ty, param_cmt, param); 5,304 ( 0.00%) self.link_pattern(param_cmt, param.pat); . } . } . . /// Link lifetimes of any ref bindings in `root_pat` to the pointers found . /// in the discriminant, if needed. 5,118 ( 0.00%) fn link_pattern(&self, discr_cmt: PlaceWithHirId<'tcx>, root_pat: &hir::Pat<'_>) { . debug!("link_pattern(discr_cmt={:?}, root_pat={:?})", discr_cmt, root_pat); . ignore_err!(self.with_mc(|mc| { 2,559 ( 0.00%) mc.cat_pattern(discr_cmt, root_pat, |sub_cmt, hir::Pat { kind, span, hir_id, .. }| { . // `ref x` pattern 2,574 ( 0.00%) if let PatKind::Binding(..) = kind { 3,602 ( 0.00%) if let Some(ty::BindByReference(mutbl)) = 12,012 ( 0.00%) mc.typeck_results.extract_binding_mode(self.tcx.sess, *hir_id, *span) . { . self.link_region_from_node_type(*span, *hir_id, mutbl, sub_cmt); . } . } . }) . })); 5,118 ( 0.00%) } . . /// Link lifetime of borrowed pointer resulting from autoref to lifetimes in the value being . /// autoref'd. . fn link_autoref( . &self, . expr: &hir::Expr<'_>, . expr_cmt: &PlaceWithHirId<'tcx>, . autoref: &adjustment::AutoBorrow<'tcx>, . ) { . debug!("link_autoref(autoref={:?}, expr_cmt={:?})", autoref, expr_cmt); . 3,738 ( 0.00%) match *autoref { 3,702 ( 0.00%) adjustment::AutoBorrow::Ref(r, m) => { 18,510 ( 0.00%) self.link_region(expr.span, r, ty::BorrowKind::from_mutbl(m.into()), expr_cmt); . } . . adjustment::AutoBorrow::RawPtr(_) => {} . } . } . . /// Like `link_region()`, except that the region is extracted from the type of `id`, . /// which must be some reference (`&T`, `&str`, etc). -- line 676 ---------------------------------------- -- line 682 ---------------------------------------- . cmt_borrowed: &PlaceWithHirId<'tcx>, . ) { . debug!( . "link_region_from_node_type(id={:?}, mutbl={:?}, cmt_borrowed={:?})", . id, mutbl, cmt_borrowed . ); . . let rptr_ty = self.resolve_node_type(id); 2,366 ( 0.00%) if let ty::Ref(r, _, _) = rptr_ty.kind() { . debug!("rptr_ty={}", rptr_ty); 8,621 ( 0.00%) self.link_region(span, r, ty::BorrowKind::from_mutbl(mutbl), cmt_borrowed); . } . } . . /// Informs the inference engine that `borrow_cmt` is being borrowed with . /// kind `borrow_kind` and lifetime `borrow_region`. . /// In order to ensure borrowck is satisfied, this may create constraints . /// between regions, as explained in `link_reborrowed_region()`. 33,649 ( 0.00%) fn link_region( . &self, . span: Span, . borrow_region: ty::Region<'tcx>, . borrow_kind: ty::BorrowKind, . borrow_place: &PlaceWithHirId<'tcx>, . ) { 9,177 ( 0.00%) let origin = infer::DataBorrowed(borrow_place.place.ty(), span); 18,354 ( 0.00%) self.type_must_outlive(origin, borrow_place.place.ty(), borrow_region); . 17,351 ( 0.00%) for pointer_ty in borrow_place.place.deref_tys() { . debug!( . "link_region(borrow_region={:?}, borrow_kind={:?}, pointer_ty={:?})", . borrow_region, borrow_kind, borrow_place . ); 6,282 ( 0.00%) match *pointer_ty.kind() { . ty::RawPtr(_) => return, 17,991 ( 0.00%) ty::Ref(ref_region, _, ref_mutability) => { 1,999 ( 0.00%) if self.link_reborrowed_region(span, borrow_region, ref_region, ref_mutability) . { . return; . } . } 57 ( 0.00%) _ => assert!(pointer_ty.is_box(), "unexpected built-in deref type {}", pointer_ty), . } . } 2,630 ( 0.00%) if let PlaceBase::Upvar(upvar_id) = borrow_place.place.base { . self.link_upvar_region(span, borrow_region, upvar_id); . } 24,472 ( 0.00%) } . . /// This is the most complicated case: the path being borrowed is . /// itself the referent of a borrowed pointer. Let me give an . /// example fragment of code to make clear(er) the situation: . /// . /// ```ignore (incomplete Rust code) . /// let r: &'a mut T = ...; // the original reference "r" has lifetime 'a . /// ... -- line 737 ---------------------------------------- -- line 764 ---------------------------------------- . fn link_reborrowed_region( . &self, . span: Span, . borrow_region: ty::Region<'tcx>, . ref_region: ty::Region<'tcx>, . ref_mutability: hir::Mutability, . ) -> bool { . debug!("link_reborrowed_region: {:?} <= {:?}", borrow_region, ref_region); 9,995 ( 0.00%) self.sub_regions(infer::Reborrow(span), borrow_region, ref_region); . . // Decide whether we need to recurse and link any regions within . // the `ref_cmt`. This is concerned for the case where the value . // being reborrowed is in fact a borrowed pointer found within . // another borrowed pointer. For example: . // . // let p: &'b &'a mut T = ...; . // ... -- line 780 ---------------------------------------- -- line 834 ---------------------------------------- . borrow_region: ty::Region<'tcx>, . upvar_id: ty::UpvarId, . ) { . debug!("link_upvar_region(borrorw_region={:?}, upvar_id={:?}", borrow_region, upvar_id); . // A by-reference upvar can't be borrowed for longer than the . // upvar is borrowed from the environment. . let closure_local_def_id = upvar_id.closure_expr_id; . let mut all_captures_are_imm_borrow = true; 2 ( 0.00%) for captured_place in self . .typeck_results . .borrow() . .closure_min_captures . .get(&closure_local_def_id.to_def_id()) . .and_then(|root_var_min_cap| root_var_min_cap.get(&upvar_id.var_path.hir_id)) . .into_iter() . .flatten() . { 10 ( 0.00%) match captured_place.info.capture_kind { . ty::UpvarCapture::ByRef(upvar_borrow) => { 2 ( 0.00%) self.sub_regions( 14 ( 0.00%) infer::ReborrowUpvar(span, upvar_id), . borrow_region, 2 ( 0.00%) captured_place.region.unwrap(), . ); 12 ( 0.00%) if let ty::ImmBorrow = upvar_borrow { . debug!("link_upvar_region: capture by shared ref"); . } else { . all_captures_are_imm_borrow = false; . } . } . ty::UpvarCapture::ByValue => { . all_captures_are_imm_borrow = false; . } . } . } 4 ( 0.00%) if all_captures_are_imm_borrow { . return; . } 2 ( 0.00%) let fn_hir_id = self.tcx.hir().local_def_id_to_hir_id(closure_local_def_id); . let ty = self.resolve_node_type(fn_hir_id); . debug!("link_upvar_region: ty={:?}", ty); . . // A closure capture can't be borrowed for longer than the . // reference to the closure. 4 ( 0.00%) if let ty::Closure(_, substs) = ty.kind() { 12 ( 0.00%) match self.infcx.closure_kind(substs) { . Some(ty::ClosureKind::Fn | ty::ClosureKind::FnMut) => { . // Region of environment pointer 14 ( 0.00%) let env_region = self.tcx.mk_region(ty::ReFree(ty::FreeRegion { 2 ( 0.00%) scope: upvar_id.closure_expr_id.to_def_id(), . bound_region: ty::BrEnv, . })); 4 ( 0.00%) self.sub_regions( 18 ( 0.00%) infer::ReborrowUpvar(span, upvar_id), . borrow_region, . env_region, . ); . } . Some(ty::ClosureKind::FnOnce) => {} . None => { . span_bug!(span, "Have not inferred closure kind before regionck"); . } -- line 895 ---------------------------------------- 1,206,261 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/coercion.rs -------------------------------------------------------------------------------- Ir -- line 73 ---------------------------------------- . /// See #47489 and #48598 . /// See docs on the "AllowTwoPhase" type for a more detailed discussion . allow_two_phase: AllowTwoPhase, . } . . impl<'a, 'tcx> Deref for Coerce<'a, 'tcx> { . type Target = FnCtxt<'a, 'tcx>; . fn deref(&self) -> &Self::Target { 51,114 ( 0.00%) &self.fcx . } . } . . type CoerceResult<'tcx> = InferResult<'tcx, (Vec>, Ty<'tcx>)>; . . /// Coercing a mutable reference to an immutable works, while . /// coercing `&T` to `&mut T` should be forbidden. . fn coerce_mutbls<'tcx>( . from_mutbl: hir::Mutability, . to_mutbl: hir::Mutability, . ) -> RelateResult<'tcx, ()> { 6,621 ( 0.00%) match (from_mutbl, to_mutbl) { . (hir::Mutability::Mut, hir::Mutability::Mut | hir::Mutability::Not) . | (hir::Mutability::Not, hir::Mutability::Not) => Ok(()), . (hir::Mutability::Not, hir::Mutability::Mut) => Err(TypeError::Mutability), . } . } . . /// Do not require any adjustments, i.e. coerce `x -> x`. . fn identity(_: Ty<'_>) -> Vec> { . vec![] . } . . fn simple<'tcx>(kind: Adjust<'tcx>) -> impl FnOnce(Ty<'tcx>) -> Vec> { 307 ( 0.00%) move |target| vec![Adjustment { kind, target }] . } . . /// This always returns `Ok(...)`. . fn success<'tcx>( . adj: Vec>, . target: Ty<'tcx>, . obligations: traits::PredicateObligations<'tcx>, . ) -> CoerceResult<'tcx> { 11,941 ( 0.00%) Ok(InferOk { value: (adj, target), obligations }) . } . . impl<'f, 'tcx> Coerce<'f, 'tcx> { . fn new( . fcx: &'f FnCtxt<'f, 'tcx>, . cause: ObligationCause<'tcx>, . allow_two_phase: AllowTwoPhase, . ) -> Self { 35,948 ( 0.00%) Coerce { fcx, cause, allow_two_phase, use_lub: false } . } . 84,337 ( 0.00%) fn unify(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> InferResult<'tcx, Ty<'tcx>> { . debug!("unify(a: {:?}, b: {:?}, use_lub: {})", a, b, self.use_lub); . self.commit_if_ok(|_| { 15,334 ( 0.00%) if self.use_lub { 236 ( 0.00%) self.at(&self.cause, self.fcx.param_env).lub(b, a) . } else { 15,098 ( 0.00%) self.at(&self.cause, self.fcx.param_env) . .sup(b, a) . .map(|InferOk { value: (), obligations }| InferOk { value: a, obligations }) . } . }) 61,336 ( 0.00%) } . . /// Unify two types (using sub or lub) and produce a specific coercion. 11,828 ( 0.00%) fn unify_and(&self, a: Ty<'tcx>, b: Ty<'tcx>, f: F) -> CoerceResult<'tcx> . where . F: FnOnce(Ty<'tcx>) -> Vec>, . { 18,643 ( 0.00%) self.unify(&a, &b) 15,730 ( 0.00%) .and_then(|InferOk { value: ty, obligations }| success(f(ty), ty, obligations)) 8,871 ( 0.00%) } . 95,025 ( 0.00%) #[instrument(skip(self))] . fn coerce(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> { . // First, remove any resolved type variables (at the top level, at least): 4,525 ( 0.00%) let a = self.shallow_resolve(a); 4,525 ( 0.00%) let b = self.shallow_resolve(b); . debug!("Coerce.tys({:?} => {:?})", a, b); . . // Just ignore error types. 9,050 ( 0.00%) if a.references_error() || b.references_error() { . return success(vec![], self.fcx.tcx.ty_error(), vec![]); . } . . // Coercing from `!` to any type is allowed: 4,525 ( 0.00%) if a.is_never() { . return success(simple(Adjust::NeverToAny)(b), b, vec![]); . } . . // Coercing *from* an unresolved inference variable means that . // we have no information about the source type. This will always . // ultimately fall back to some form of subtyping. 4,576 ( 0.00%) if a.is_ty_var() { . return self.coerce_from_inference_variable(a, b, identity); . } . . // Consider coercing the subtype to a DST . // . // NOTE: this is wrapped in a `commit_if_ok` because it creates . // a "spurious" type variable, and we don't want to have that . // type variable in memory if the coercion fails. . let unsize = self.commit_if_ok(|_| self.coerce_unsized(a, b)); 16,514 ( 0.00%) match unsize { . Ok(_) => { . debug!("coerce: unsize successful"); 9,525 ( 0.00%) return unsize; . } . Err(TypeError::ObjectUnsafeCoercion(did)) => { . debug!("coerce: unsize not object safe"); . return Err(TypeError::ObjectUnsafeCoercion(did)); . } . Err(error) => { . debug!(?error, "coerce: unsize failed"); . } . } . . // Examine the supertype and consider auto-borrowing. 17,517 ( 0.00%) match *b.kind() { 18 ( 0.00%) ty::RawPtr(mt_b) => { 108 ( 0.00%) return self.coerce_unsafe_ptr(a, b, mt_b.mutbl); . } 1,538 ( 0.00%) ty::Ref(r_b, _, mutbl_b) => { 4,614 ( 0.00%) return self.coerce_borrowed_pointer(a, b, r_b, mutbl_b); . } . _ => {} . } . 20,976 ( 0.00%) match *a.kind() { . ty::FnDef(..) => { . // Function items are coercible to any closure . // type; function pointers are not (that would . // require double indirection). . // Additionally, we permit coercion of function . // items to drop the unsafe qualifier. 288 ( 0.00%) self.coerce_from_fn_item(a, b) . } . ty::FnPtr(a_f) => { . // We permit coercion of fn pointers to drop the . // unsafe qualifier. . self.coerce_from_fn_pointer(a, a_f, b) . } 57 ( 0.00%) ty::Closure(closure_def_id_a, substs_a) => { . // Non-capturing closures are coercible to . // function pointers or unsafe function pointers. . // It cannot convert closures that require unsafe. 152 ( 0.00%) self.coerce_closure_to_fn(a, closure_def_id_a, substs_a, b) . } . _ => { . // Otherwise, just use unification rules. 14,785 ( 0.00%) self.unify_and(a, b, identity) . } . } 9,050 ( 0.00%) } . . /// Coercing *from* an inference variable. In this case, we have no information . /// about the source type, so we can't really do a true coercion and we always . /// fall back to subtyping (`unify_and`). . fn coerce_from_inference_variable( . &self, . a: Ty<'tcx>, . b: Ty<'tcx>, . make_adjustments: impl FnOnce(Ty<'tcx>) -> Vec>, . ) -> CoerceResult<'tcx> { . debug!("coerce_from_inference_variable(a={:?}, b={:?})", a, b); 8 ( 0.00%) assert!(a.is_ty_var() && self.infcx.shallow_resolve(a) == a); 8 ( 0.00%) assert!(self.infcx.shallow_resolve(b) == b); . 12 ( 0.00%) if b.is_ty_var() { . // Two unresolved type variables: create a `Coerce` predicate. 6 ( 0.00%) let target_ty = if self.use_lub { . self.infcx.next_ty_var(TypeVariableOrigin { . kind: TypeVariableOriginKind::LatticeVariable, . span: self.cause.span, . }) . } else { . b . }; . . let mut obligations = Vec::with_capacity(2); . for &source_ty in &[a, b] { 4 ( 0.00%) if source_ty != target_ty { . obligations.push(Obligation::new( . self.cause.clone(), 2 ( 0.00%) self.param_env, 8 ( 0.00%) ty::Binder::dummy(ty::PredicateKind::Coerce(ty::CoercePredicate { . a: source_ty, . b: target_ty, . })) . .to_predicate(self.tcx()), . )); . } . } . . debug!( . "coerce_from_inference_variable: two inference variables, target_ty={:?}, obligations={:?}", . target_ty, obligations . ); . let adjustments = make_adjustments(target_ty); 12 ( 0.00%) InferResult::Ok(InferOk { value: (adjustments, target_ty), obligations }) . } else { . // One unresolved type variable: just apply subtyping, we may be able . // to do something useful. . self.unify_and(a, b, make_adjustments) . } . } . . /// Reborrows `&mut A` to `&mut B` and `&(mut) A` to `&B`. . /// To match `A` with `B`, autoderef will be performed, . /// calling `deref`/`deref_mut` where necessary. 7,690 ( 0.00%) fn coerce_borrowed_pointer( . &self, . a: Ty<'tcx>, . b: Ty<'tcx>, . r_b: ty::Region<'tcx>, . mutbl_b: hir::Mutability, . ) -> CoerceResult<'tcx> { . debug!("coerce_borrowed_pointer(a={:?}, b={:?})", a, b); . . // If we have a parameter of type `&M T_a` and the value . // provided is `expr`, we will be adding an implicit borrow, . // meaning that we convert `f(expr)` to `f(&M *expr)`. Therefore, . // to type check, we will construct the type that `&M*expr` would . // yield. . 1,538 ( 0.00%) let (r_a, mt_a) = match *a.kind() { 2,307 ( 0.00%) ty::Ref(r_a, ty, mutbl) => { . let mt_a = ty::TypeAndMut { ty, mutbl }; . coerce_mutbls(mt_a.mutbl, mutbl_b)?; . (r_a, mt_a) . } . _ => return self.unify_and(a, b, identity), . }; . 1,538 ( 0.00%) let span = self.cause.span; . . let mut first_error = None; . let mut r_borrow_var = None; . let mut autoderef = self.autoderef(span, a); . let mut found = None; . 3,088 ( 0.00%) for (referent_ty, autoderefs) in autoderef.by_ref() { 3,088 ( 0.00%) if autoderefs == 0 { . // Don't let this pass, otherwise it would cause . // &T to autoref to &&T. . continue; . } . . // At this point, we have deref'd `a` to `referent_ty`. So . // imagine we are coercing from `&'a mut Vec` to `&'b mut [T]`. . // In the autoderef loop for `&'a mut Vec`, we would get -- line 326 ---------------------------------------- -- line 386 ---------------------------------------- . // this extra edge causes the region `'a` to be inferred to something . // too big, which then results in borrowck errors.) . // - We could track the innermost shared reference, but there is already . // code in regionck that has the job of creating links between . // the region of a borrow and the regions in the thing being . // borrowed (here, `'a` and `'x`), and it knows how to handle . // all the various cases. So instead we just make a region variable . // and let regionck figure it out. 1,550 ( 0.00%) let r = if !self.use_lub { . r_b // [2] above 6 ( 0.00%) } else if autoderefs == 1 { . r_a // [3] above . } else { 1 ( 0.00%) if r_borrow_var.is_none() { . // create var lazily, at most once . let coercion = Coercion(span); 5 ( 0.00%) let r = self.next_region_var(coercion); . r_borrow_var = Some(r); // [4] above . } . r_borrow_var.unwrap() . }; 775 ( 0.00%) let derefd_ty_a = self.tcx.mk_ref( . r, . TypeAndMut { . ty: referent_ty, . mutbl: mutbl_b, // [1] above . }, . ); 5,425 ( 0.00%) match self.unify(derefd_ty_a, b) { . Ok(ok) => { 3,076 ( 0.00%) found = Some(ok); . break; . } 18 ( 0.00%) Err(err) => { 6 ( 0.00%) if first_error.is_none() { 30 ( 0.00%) first_error = Some(err); . } . } . } . } . . // Extract type or return an error. We return the first error . // we got, which should be from relating the "base" type . // (e.g., in example above, the failure from relating `Vec` . // to the target type), since that should be the least . // confusing. 6,152 ( 0.00%) let InferOk { value: ty, mut obligations } = match found { . Some(d) => d, . None => { . let err = first_error.expect("coerce_borrowed_pointer had no error"); . debug!("coerce_borrowed_pointer: failed with err = {:?}", err); . return Err(err); . } . }; . 1,854 ( 0.00%) if ty == a && mt_a.mutbl == hir::Mutability::Not && autoderef.step_count() == 1 { . // As a special case, if we would produce `&'a *x`, that's . // a total no-op. We end up with the type `&'a T` just as . // we started with. In that case, just skip it . // altogether. This is just an optimization. . // . // Note that for `&mut`, we DO want to reborrow -- . // otherwise, this would be a move, which might be an . // error. For example `foo(self.x)` where `self` and . // `self.x` both have `&mut `type would be a move of . // `self.x`, but we auto-coerce it to `foo(&mut *self.x)`, . // which is a borrow. 434 ( 0.00%) assert_eq!(mutbl_b, hir::Mutability::Not); // can only coerce &T -> &U 868 ( 0.00%) return success(vec![], ty, obligations); . } . 3,864 ( 0.00%) let InferOk { value: mut adjustments, obligations: o } = 552 ( 0.00%) self.adjust_steps_as_infer_ok(&autoderef); . obligations.extend(o); 10,488 ( 0.00%) obligations.extend(autoderef.into_obligations()); . . // Now apply the autoref. We have to extract the region out of . // the final ref type we got. 1,104 ( 0.00%) let r_borrow = match ty.kind() { . ty::Ref(r_borrow, _, _) => r_borrow, . _ => span_bug!(span, "expected a ref type, got {:?}", ty), . }; 2,208 ( 0.00%) let mutbl = match mutbl_b { . hir::Mutability::Not => AutoBorrowMutability::Not, . hir::Mutability::Mut => { . AutoBorrowMutability::Mut { allow_two_phase_borrow: self.allow_two_phase } . } . }; . adjustments.push(Adjustment { 552 ( 0.00%) kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mutbl)), . target: ty, . }); . . debug!("coerce_borrowed_pointer: succeeded ty={:?} adjustments={:?}", ty, adjustments); . 4,416 ( 0.00%) success(adjustments, ty, obligations) 6,152 ( 0.00%) } . . // &[T; n] or &mut [T; n] -> &[T] . // or &mut [T; n] -> &mut [T] . // or &Concrete -> &Trait, etc. . #[instrument(skip(self), level = "debug")] . fn coerce_unsized(&self, mut source: Ty<'tcx>, mut target: Ty<'tcx>) -> CoerceResult<'tcx> { . source = self.shallow_resolve(source); . target = self.shallow_resolve(target); -- line 490 ---------------------------------------- -- line 506 ---------------------------------------- . // would need to be generic over the self-type (`impl CoerceUnsized for T`) . // or generic over the `CoerceUnsized` type parameter (`impl CoerceUnsized for . // SomeType`). . // . // However, these are exactly the kinds of impls which are forbidden by . // the compiler! Therefore, we can be sure that coercion will always fail . // when either the source or target type is a type variable. This allows us . // to skip performing any trait selection, and immediately bail out. 4,552 ( 0.00%) if source.is_ty_var() { . debug!("coerce_unsized: source is a TyVar, bailing out"); . return Err(TypeError::Mismatch); . } 5,678 ( 0.00%) if target.is_ty_var() { . debug!("coerce_unsized: target is a TyVar, bailing out"); . return Err(TypeError::Mismatch); . } . . let traits = 46,128 ( 0.00%) (self.tcx.lang_items().unsize_trait(), self.tcx.lang_items().coerce_unsized_trait()); 15,376 ( 0.00%) let (Some(unsize_did), Some(coerce_unsized_did)) = traits else { . debug!("missing Unsize or CoerceUnsized traits"); . return Err(TypeError::Mismatch); . }; . . // Note, we want to avoid unnecessary unsizing. We don't want to coerce to . // a DST unless we have to. This currently comes out in the wash since . // we can't unify [T] with U. But to properly support DST, we need to allow . // that, at which point we will need extra checks on the target here. . . // Handle reborrows before selecting `Source: CoerceUnsized`. 11,984 ( 0.00%) let reborrow = match (source.kind(), target.kind()) { 4,206 ( 0.00%) (&ty::Ref(_, ty_a, mutbl_a), &ty::Ref(_, _, mutbl_b)) => { . coerce_mutbls(mutbl_a, mutbl_b)?; . 1,402 ( 0.00%) let coercion = Coercion(self.cause.span); 7,010 ( 0.00%) let r_borrow = self.next_region_var(coercion); . let mutbl = match mutbl_b { . hir::Mutability::Not => AutoBorrowMutability::Not, . hir::Mutability::Mut => AutoBorrowMutability::Mut { . // We don't allow two-phase borrows here, at least for initial . // implementation. If it happens that this coercion is a function argument, . // the reborrow in coerce_borrowed_ptr will pick it up. . allow_two_phase_borrow: AllowTwoPhase::No, . }, . }; . Some(( . Adjustment { kind: Adjust::Deref(None), target: ty_a }, . Adjustment { . kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mutbl)), 1,402 ( 0.00%) target: self . .tcx . .mk_ref(r_borrow, ty::TypeAndMut { mutbl: mutbl_b, ty: ty_a }), . }, . )) . } 54 ( 0.00%) (&ty::Ref(_, ty_a, mt_a), &ty::RawPtr(ty::TypeAndMut { mutbl: mt_b, .. })) => { . coerce_mutbls(mt_a, mt_b)?; . . Some(( . Adjustment { kind: Adjust::Deref(None), target: ty_a }, . Adjustment { . kind: Adjust::Borrow(AutoBorrow::RawPtr(mt_b)), 18 ( 0.00%) target: self.tcx.mk_ptr(ty::TypeAndMut { mutbl: mt_b, ty: ty_a }), . }, . )) . } . _ => None, . }; . let coerce_source = reborrow.as_ref().map_or(source, |&(_, ref r)| r.target); . . // Setup either a subtyping or a LUB relationship between . // the `CoerceUnsized` target type and the expected type. . // We only have the latter, so we use an inference variable . // for the former and let type inference do the rest. . let origin = TypeVariableOrigin { . kind: TypeVariableOriginKind::MiscVariable, 3,844 ( 0.00%) span: self.cause.span, . }; 19,220 ( 0.00%) let coerce_target = self.next_ty_var(origin); 15,376 ( 0.00%) let mut coercion = self.unify_and(coerce_target, target, |target| { . let unsize = Adjustment { kind: Adjust::Pointer(PointerCast::Unsize), target }; 7,688 ( 0.00%) match reborrow { 12,120 ( 0.00%) None => vec![unsize], 19,880 ( 0.00%) Some((ref deref, ref autoref)) => vec![deref.clone(), autoref.clone(), unsize], . } . })?; . 3,844 ( 0.00%) let mut selcx = traits::SelectionContext::new(self); . . // Create an obligation for `Source: CoerceUnsized`. . let cause = ObligationCause::new( 7,688 ( 0.00%) self.cause.span, 7,688 ( 0.00%) self.body_id, . ObligationCauseCode::Coercion { source, target }, . ); . . // Use a FIFO queue for this custom fulfillment procedure. . // . // A Vec (or SmallVec) is not a natural choice for a queue. However, . // this code path is hot, and this queue usually has a max length of 1 . // and almost never more than 3. By using a SmallVec we avoid an . // allocation, at the (very small) cost of (occasionally) having to . // shift subsequent elements down when removing the front element. 53,816 ( 0.00%) let mut queue: SmallVec<[_; 4]> = smallvec![traits::predicate_for_trait_def( 7,688 ( 0.00%) self.tcx, 3,844 ( 0.00%) self.fcx.param_env, 19,220 ( 0.00%) cause, . coerce_unsized_did, . 0, . coerce_source, 19,220 ( 0.00%) &[coerce_target.into()] . )]; . . let mut has_unsized_tuple_coercion = false; . let mut has_trait_upcasting_coercion = false; . . // Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid . // emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where . // inference might unify those two inner type variables later. . let traits = [coerce_unsized_did, unsize_did]; 14,780 ( 0.00%) while !queue.is_empty() { . let obligation = queue.remove(0); . debug!("coerce_unsized resolve step: {:?}", obligation); 6,755 ( 0.00%) let bound_predicate = obligation.predicate.kind(); 33,775 ( 0.00%) let trait_pred = match bound_predicate.skip_binder() { 32,694 ( 0.00%) ty::PredicateKind::Trait(trait_pred) if traits.contains(&trait_pred.def_id()) => { 48,105 ( 0.00%) if unsize_did == trait_pred.def_id() { 9,006 ( 0.00%) let self_ty = trait_pred.self_ty(); 6,004 ( 0.00%) let unsize_ty = trait_pred.trait_ref.substs[1].expect_ty(); 7,505 ( 0.00%) if let (ty::Dynamic(ref data_a, ..), ty::Dynamic(ref data_b, ..)) = . (self_ty.kind(), unsize_ty.kind()) . { . if data_a.principal_def_id() != data_b.principal_def_id() { . debug!("coerce_unsized: found trait upcasting coercion"); . has_trait_upcasting_coercion = true; . } . } 9,006 ( 0.00%) if let ty::Tuple(..) = unsize_ty.kind() { . debug!("coerce_unsized: found unsized tuple coercion"); . has_unsized_tuple_coercion = true; . } . } 10,690 ( 0.00%) bound_predicate.rebind(trait_pred) . } . _ => { 8,460 ( 0.00%) coercion.obligations.push(obligation); . continue; . } . }; 58,795 ( 0.00%) match selcx.select(&obligation.with(trait_pred)) { . // Uncertain or unimplemented. . Ok(None) => { 2,197 ( 0.00%) if trait_pred.def_id() == unsize_did { 1,014 ( 0.00%) let trait_pred = self.resolve_vars_if_possible(trait_pred); 338 ( 0.00%) let self_ty = trait_pred.skip_binder().self_ty(); 1,014 ( 0.00%) let unsize_ty = trait_pred.skip_binder().trait_ref.substs[1].expect_ty(); . debug!("coerce_unsized: ambiguous unsize case for {:?}", trait_pred); 338 ( 0.00%) match (&self_ty.kind(), &unsize_ty.kind()) { . (ty::Infer(ty::TyVar(v)), ty::Dynamic(..)) . if self.type_var_is_sized(*v) => . { . debug!("coerce_unsized: have sized infer {:?}", v); . coercion.obligations.push(obligation); . // `$0: Unsize` where we know that `$0: Sized`, try going . // for unsizing. . } -- line 671 ---------------------------------------- -- line 679 ---------------------------------------- . } . } else { . debug!("coerce_unsized: early return - ambiguous"); . return Err(TypeError::Mismatch); . } . } . Err(traits::Unimplemented) => { . debug!("coerce_unsized: early return - can't prove obligation"); 18,240 ( 0.00%) return Err(TypeError::Mismatch); . } . . // Object safety violations or miscellaneous. . Err(err) => { . self.report_selection_error(obligation.clone(), &obligation, &err, false); . // Treat this like an obligation and follow through . // with the unsizing - the lack of a coercion should . // be silent, as it causes a type mismatch later. . } . 40,584 ( 0.00%) Ok(Some(impl_source)) => queue.extend(impl_source.nested_obligations()), . } 6,418 ( 0.00%) } . 1,270 ( 0.00%) if has_unsized_tuple_coercion && !self.tcx.features().unsized_tuple_coercion { . feature_err( . &self.tcx.sess.parse_sess, . sym::unsized_tuple_coercion, . self.cause.span, . "unsized tuple coercion is not stable enough for use and is subject to change", . ) . .emit(); . } . 1,270 ( 0.00%) if has_trait_upcasting_coercion && !self.tcx().features().trait_upcasting { . feature_err( . &self.tcx.sess.parse_sess, . sym::trait_upcasting, . self.cause.span, . "trait upcasting coercion is experimental", . ) . .emit(); . } . 6,985 ( 0.00%) Ok(coercion) . } . . fn coerce_from_safe_fn( . &self, . a: Ty<'tcx>, . fn_ty_a: ty::PolyFnSig<'tcx>, . b: Ty<'tcx>, . to_unsafe: F, . normal: G, . ) -> CoerceResult<'tcx> . where . F: FnOnce(Ty<'tcx>) -> Vec>, . G: FnOnce(Ty<'tcx>) -> Vec>, . { 94 ( 0.00%) if let ty::FnPtr(fn_ty_b) = b.kind() { 188 ( 0.00%) if let (hir::Unsafety::Normal, hir::Unsafety::Unsafe) = 94 ( 0.00%) (fn_ty_a.unsafety(), fn_ty_b.unsafety()) . { . let unsafe_a = self.tcx.safe_to_unsafe_fn_ty(fn_ty_a); . return self.unify_and(unsafe_a, b, to_unsafe); . } . } . self.unify_and(a, b, normal) . } . -- line 747 ---------------------------------------- -- line 762 ---------------------------------------- . a, . fn_ty_a, . b, . simple(Adjust::Pointer(PointerCast::UnsafeFnPointer)), . identity, . ) . } . 480 ( 0.00%) fn coerce_from_fn_item(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> { . //! Attempts to coerce from the type of a Rust function item . //! into a closure or a `proc`. . . let b = self.shallow_resolve(b); 240 ( 0.00%) let InferOk { value: b, mut obligations } = 48 ( 0.00%) self.normalize_associated_types_in_as_infer_ok(self.cause.span, b); . debug!("coerce_from_fn_item(a={:?}, b={:?})", a, b); . 96 ( 0.00%) match b.kind() { . ty::FnPtr(b_sig) => { 188 ( 0.00%) let a_sig = a.fn_sig(self.tcx); . // Intrinsics are not coercible to function pointers 94 ( 0.00%) if a_sig.abi() == Abi::RustIntrinsic || a_sig.abi() == Abi::PlatformIntrinsic { . return Err(TypeError::IntrinsicCast); . } . . // Safe `#[target_feature]` functions are not assignable to safe fn pointers (RFC 2396). 282 ( 0.00%) if let ty::FnDef(def_id, _) = *a.kind() { 188 ( 0.00%) if b_sig.unsafety() == hir::Unsafety::Normal 47 ( 0.00%) && !self.tcx.codegen_fn_attrs(def_id).target_features.is_empty() . { . return Err(TypeError::TargetFeatureCast(def_id)); . } . } . 329 ( 0.00%) let InferOk { value: a_sig, obligations: o1 } = 188 ( 0.00%) self.normalize_associated_types_in_as_infer_ok(self.cause.span, a_sig); . obligations.extend(o1); . 47 ( 0.00%) let a_fn_pointer = self.tcx.mk_fn_ptr(a_sig); 188 ( 0.00%) let InferOk { value, obligations: o2 } = self.coerce_from_safe_fn( . a_fn_pointer, 235 ( 0.00%) a_sig, . b, . |unsafe_ty| { . vec![ . Adjustment { . kind: Adjust::Pointer(PointerCast::ReifyFnPointer), . target: a_fn_pointer, . }, . Adjustment { -- line 811 ---------------------------------------- -- line 813 ---------------------------------------- . target: unsafe_ty, . }, . ] . }, . simple(Adjust::Pointer(PointerCast::ReifyFnPointer)), . )?; . . obligations.extend(o2); 705 ( 0.00%) Ok(InferOk { value, obligations }) . } . _ => self.unify_and(a, b, identity), . } 384 ( 0.00%) } . 266 ( 0.00%) fn coerce_closure_to_fn( . &self, . a: Ty<'tcx>, . closure_def_id_a: DefId, . substs_a: SubstsRef<'tcx>, . b: Ty<'tcx>, . ) -> CoerceResult<'tcx> { . //! Attempts to coerce from the type of a non-capturing closure . //! into a function pointer. . //! . . let b = self.shallow_resolve(b); . 38 ( 0.00%) match b.kind() { . // At this point we haven't done capture analysis, which means . // that the ClosureSubsts just contains an inference variable instead . // of tuple of captured types. . // . // All we care here is if any variable is being captured and not the exact paths, . // so we check `upvars_mentioned` for root variables being captured. . ty::FnPtr(fn_ty) . if self -- line 848 ---------------------------------------- -- line 864 ---------------------------------------- . self.unify_and( . pointer_ty, . b, . simple(Adjust::Pointer(PointerCast::ClosureFnPointer(unsafety))), . ) . } . _ => self.unify_and(a, b, identity), . } 152 ( 0.00%) } . 198 ( 0.00%) fn coerce_unsafe_ptr( . &self, . a: Ty<'tcx>, . b: Ty<'tcx>, . mutbl_b: hir::Mutability, . ) -> CoerceResult<'tcx> { . debug!("coerce_unsafe_ptr(a={:?}, b={:?})", a, b); . 90 ( 0.00%) let (is_ref, mt_a) = match *a.kind() { 54 ( 0.00%) ty::Ref(_, ty, mutbl) => (true, ty::TypeAndMut { ty, mutbl }), . ty::RawPtr(mt) => (false, mt), . _ => return self.unify_and(a, b, identity), . }; 18 ( 0.00%) coerce_mutbls(mt_a.mutbl, mutbl_b)?; . . // Check that the types which they point at are compatible. 18 ( 0.00%) let a_unsafe = self.tcx.mk_ptr(ty::TypeAndMut { mutbl: mutbl_b, ty: mt_a.ty }); . // Although references and unsafe ptrs have the same . // representation, we still register an Adjust::DerefRef so that . // regionck knows that the region for `a` must be valid here. 36 ( 0.00%) if is_ref { . self.unify_and(a_unsafe, b, |target| { 144 ( 0.00%) vec![ . Adjustment { kind: Adjust::Deref(None), target: mt_a.ty }, . Adjustment { kind: Adjust::Borrow(AutoBorrow::RawPtr(mutbl_b)), target }, . ] . }) . } else if mt_a.mutbl != mutbl_b { . self.unify_and(a_unsafe, b, simple(Adjust::Pointer(PointerCast::MutToConstPointer))) . } else { . self.unify_and(a_unsafe, b, identity) . } 144 ( 0.00%) } . } . . impl<'a, 'tcx> FnCtxt<'a, 'tcx> { . /// Attempt to coerce an expression to a type, and return the . /// adjusted type of the expression, if successful. . /// Adjustments are only recorded if the coercion succeeded. . /// The expressions *must not* have any pre-existing adjustments. 62,174 ( 0.00%) pub fn try_coerce( . &self, . expr: &hir::Expr<'_>, . expr_ty: Ty<'tcx>, . target: Ty<'tcx>, . allow_two_phase: AllowTwoPhase, . cause: Option>, . ) -> RelateResult<'tcx, Ty<'tcx>> { 13,323 ( 0.00%) let source = self.resolve_vars_with_obligations(expr_ty); . debug!("coercion::try({:?}: {:?} -> {:?})", expr, source, target); . . let cause = 4,441 ( 0.00%) cause.unwrap_or_else(|| self.cause(expr.span, ObligationCauseCode::ExprAssignable)); . let coerce = Coerce::new(self, cause, allow_two_phase); 53,272 ( 0.00%) let ok = self.commit_if_ok(|_| coerce.coerce(source, target))?; . 17,748 ( 0.00%) let (adjustments, _) = self.register_infer_ok_obligations(ok); 44,370 ( 0.00%) self.apply_adjustments(expr, adjustments); 13,311 ( 0.00%) Ok(if expr_ty.references_error() { self.tcx.ty_error() } else { target }) 39,969 ( 0.00%) } . . /// Same as `try_coerce()`, but without side-effects. . /// . /// Returns false if the coercion creates any obligations that result in . /// errors. . pub fn can_coerce(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> bool { . let source = self.resolve_vars_with_obligations(expr_ty); . debug!("coercion::can_with_predicates({:?} -> {:?})", source, target); -- line 941 ---------------------------------------- -- line 967 ---------------------------------------- . } . . /// Given some expressions, their known unified type and another expression, . /// tries to unify the types, potentially inserting coercions on any of the . /// provided expressions and returns their LUB (aka "common supertype"). . /// . /// This is really an internal helper. From outside the coercion . /// module, you should instantiate a `CoerceMany` instance. 1,792,375 ( 0.03%) fn try_find_coercion_lub( . &self, . cause: &ObligationCause<'tcx>, . exprs: &[E], . prev_ty: Ty<'tcx>, . new: &hir::Expr<'_>, . new_ty: Ty<'tcx>, . ) -> RelateResult<'tcx, Ty<'tcx>> . where . E: AsCoercionSite, . { 827,250 ( 0.01%) let prev_ty = self.resolve_vars_with_obligations(prev_ty); 413,625 ( 0.01%) let new_ty = self.resolve_vars_with_obligations(new_ty); . debug!( . "coercion::try_find_coercion_lub({:?}, {:?}, exprs={:?} exprs)", . prev_ty, . new_ty, . exprs.len() . ); . . // The following check fixes #88097, where the compiler erroneously . // attempted to coerce a closure type to itself via a function pointer. 137,875 ( 0.00%) if prev_ty == new_ty { 137,731 ( 0.00%) return Ok(prev_ty); . } . . // Special-case that coercion alone cannot handle: . // Function items or non-capturing closures of differing IDs or InternalSubsts. 672 ( 0.00%) let (a_sig, b_sig) = { 672 ( 0.00%) let is_capturing_closure = |ty| { 336 ( 0.00%) if let &ty::Closure(closure_def_id, _substs) = ty { . self.tcx.upvars_mentioned(closure_def_id.expect_local()).is_some() . } else { . false . } 672 ( 0.00%) }; 944 ( 0.00%) if is_capturing_closure(prev_ty.kind()) || is_capturing_closure(new_ty.kind()) { . (None, None) . } else { 504 ( 0.00%) match (prev_ty.kind(), new_ty.kind()) { . (ty::FnDef(..), ty::FnDef(..)) => { . // Don't reify if the function types have a LUB, i.e., they . // are the same function and their parameters have a LUB. . match self . .commit_if_ok(|_| self.at(cause, self.param_env).lub(prev_ty, new_ty)) . { . // We have a LUB of prev_ty and new_ty, just return it. . Ok(ok) => return Ok(self.register_infer_ok_obligations(ok)), -- line 1022 ---------------------------------------- -- line 1048 ---------------------------------------- . substs_b.as_closure().sig(), . hir::Unsafety::Normal, . )), . ), . _ => (None, None), . } . } . }; 336 ( 0.00%) if let (Some(a_sig), Some(b_sig)) = (a_sig, b_sig) { . // Intrinsics are not coercible to function pointers. . if a_sig.abi() == Abi::RustIntrinsic . || a_sig.abi() == Abi::PlatformIntrinsic . || b_sig.abi() == Abi::RustIntrinsic . || b_sig.abi() == Abi::PlatformIntrinsic . { . return Err(TypeError::IntrinsicCast); . } -- line 1064 ---------------------------------------- -- line 1094 ---------------------------------------- . } . . // Configure a Coerce instance to compute the LUB. . // We don't allow two-phase borrows on any autorefs this creates since we . // probably aren't processing function arguments here and even if we were, . // they're going to get autorefed again anyway and we can apply 2-phase borrows . // at that time. . let mut coerce = Coerce::new(self, cause.clone(), AllowTwoPhase::No); 84 ( 0.00%) coerce.use_lub = true; . . // First try to coerce the new expression to the type of the previous ones, . // but only if the new expression has no coercion already applied to it. . let mut first_error = None; 672 ( 0.00%) if !self.typeck_results.borrow().adjustments().contains_key(new.hir_id) { 5,197 ( 0.00%) let result = self.commit_if_ok(|_| coerce.coerce(new_ty, prev_ty)); 168 ( 0.00%) match result { . Ok(ok) => { 672 ( 0.00%) let (adjustments, target) = self.register_infer_ok_obligations(ok); 672 ( 0.00%) self.apply_adjustments(new, adjustments); . debug!( . "coercion::try_find_coercion_lub: was able to coerce from previous type {:?} to new type {:?}", . prev_ty, new_ty, . ); 168 ( 0.00%) return Ok(target); . } . Err(e) => first_error = Some(e), . } . } . . // Then try to coerce the previous expressions to the type of the new one. . // This requires ensuring there are no coercions applied to *any* of the . // previous expressions, other than noop reborrows (ignoring lifetimes). -- line 1125 ---------------------------------------- -- line 1175 ---------------------------------------- . let (adjustments, target) = self.register_infer_ok_obligations(ok); . for expr in exprs { . let expr = expr.as_coercion_site(); . self.apply_adjustments(expr, adjustments.clone()); . } . Ok(target) . } . } 1,240,875 ( 0.02%) } . } . . /// CoerceMany encapsulates the pattern you should use when you have . /// many expressions that are all getting coerced to a common . /// type. This arises, for example, when you have a match (the result . /// of each arm is coerced to a common type). It also arises in less . /// obvious places, such as when you have many `break foo` expressions . /// that target the same loop, or the various `return` expressions in -- line 1191 ---------------------------------------- -- line 1253 ---------------------------------------- . /// expected to pass each element in the slice to `coerce(...)` in . /// order. This is used with arrays in particular to avoid . /// needlessly cloning the slice. . pub fn with_coercion_sites(expected_ty: Ty<'tcx>, coercion_sites: &'exprs [E]) -> Self { . Self::make(expected_ty, Expressions::UpFront(coercion_sites)) . } . . fn make(expected_ty: Ty<'tcx>, expressions: Expressions<'tcx, 'exprs, E>) -> Self { 4,346 ( 0.00%) CoerceMany { expected_ty, final_ty: None, expressions, pushed: 0 } . } . . /// Returns the "expected type" with which this coercion was . /// constructed. This represents the "downward propagated" type . /// that was given to us at the start of typing whatever construct . /// we are typing (e.g., the match expression). . /// . /// Typically, this is used as the expected type when -- line 1269 ---------------------------------------- -- line 1281 ---------------------------------------- . self.final_ty.unwrap_or(self.expected_ty) . } . . /// Indicates that the value generated by `expression`, which is . /// of type `expression_ty`, is one of the possibilities that we . /// could coerce from. This will record `expression`, and later . /// calls to `coerce` may come back and add adjustments and things . /// if necessary. 1,658,220 ( 0.02%) pub fn coerce<'a>( . &mut self, . fcx: &FnCtxt<'a, 'tcx>, . cause: &ObligationCause<'tcx>, . expression: &'tcx hir::Expr<'tcx>, . expression_ty: Ty<'tcx>, . ) { 7,628 ( 0.00%) self.coerce_inner(fcx, cause, Some(expression), expression_ty, None, false) 1,105,480 ( 0.02%) } . . /// Indicates that one of the inputs is a "forced unit". This . /// occurs in a case like `if foo { ... };`, where the missing else . /// generates a "forced unit". Another example is a `loop { break; . /// }`, where the `break` has no argument expression. We treat . /// these cases slightly differently for error-reporting . /// purposes. Note that these tend to correspond to cases where . /// the `()` expression is implicit in the source, and hence we do -- line 1305 ---------------------------------------- -- line 1310 ---------------------------------------- . /// removing a `;`). . pub fn coerce_forced_unit<'a>( . &mut self, . fcx: &FnCtxt<'a, 'tcx>, . cause: &ObligationCause<'tcx>, . augment_error: &mut dyn FnMut(&mut DiagnosticBuilder<'_>), . label_unit_as_expected: bool, . ) { 970 ( 0.00%) self.coerce_inner( . fcx, . cause, . None, 108 ( 0.00%) fcx.tcx.mk_unit(), . Some(augment_error), . label_unit_as_expected, . ) . } . . /// The inner coercion "engine". If `expression` is `None`, this . /// is a forced-unit case, and hence `expression_ty` must be . /// `Nil`. 28,014 ( 0.00%) #[instrument(skip(self, fcx, augment_error, label_expression_as_expected), level = "debug")] . crate fn coerce_inner<'a>( . &mut self, . fcx: &FnCtxt<'a, 'tcx>, . cause: &ObligationCause<'tcx>, . expression: Option<&'tcx hir::Expr<'tcx>>, . mut expression_ty: Ty<'tcx>, . augment_error: Option<&mut dyn FnMut(&mut DiagnosticBuilder<'_>)>, . label_expression_as_expected: bool, . ) { . // Incorporate whatever type inference information we have . // until now; in principle we might also want to process . // pending obligations, but doing so should only improve . // compatibility (hopefully that is true) by helping us . // uncover never types better. 139,587 ( 0.00%) if expression_ty.is_ty_var() { . expression_ty = fcx.infcx.shallow_resolve(expression_ty); . } . . // If we see any error types, just propagate that error . // upwards. 558,076 ( 0.01%) if expression_ty.references_error() || self.merged_ty().references_error() { . self.final_ty = Some(fcx.tcx.ty_error()); . return; . } . . // Handle the actual type unification etc. 4,002 ( 0.00%) let result = if let Some(expression) = expression { 418,233 ( 0.01%) if self.pushed == 0 { . // Special-case the first expression we are coercing. . // To be honest, I'm not entirely sure why we do this. . // We don't allow two-phase borrows, see comment in try_find_coercion_lub for why 13,824 ( 0.00%) fcx.try_coerce( . expression, . expression_ty, . self.expected_ty, . AllowTwoPhase::No, 6,144 ( 0.00%) Some(cause.clone()), . ) . } else { 275,750 ( 0.00%) match self.expressions { 168 ( 0.00%) Expressions::Dynamic(ref exprs) => fcx.try_find_coercion_lub( . cause, . exprs, . self.merged_ty(), . expression, . expression_ty, . ), 826,838 ( 0.01%) Expressions::UpFront(ref coercion_sites) => fcx.try_find_coercion_lub( . cause, 413,373 ( 0.01%) &coercion_sites[0..self.pushed], . self.merged_ty(), . expression, . expression_ty, . ), . } . } . } else { . // this is a hack for cases where we default to `()` because -- line 1389 ---------------------------------------- -- line 1394 ---------------------------------------- . // . // we wind up with a second match arm that is like `_ => . // ()`. That is the case we are considering here. We take . // a different path to get the right "expected, found" . // message and so forth (and because we know that . // `expression_ty` will be unit). . // . // Another example is `break` with no argument expression. 108 ( 0.00%) assert!(expression_ty.is_unit(), "if let hack without unit type"); 216 ( 0.00%) fcx.at(cause, fcx.param_env) . .eq_exp(label_expression_as_expected, expression_ty, self.merged_ty()) . .map(|infer_ok| { . fcx.register_infer_ok_obligations(infer_ok); . expression_ty . }) . }; . 279,106 ( 0.00%) match result { 139,627 ( 0.00%) Ok(v) => { 139,411 ( 0.00%) self.final_ty = Some(v); . if let Some(e) = expression { 278,822 ( 0.00%) match self.expressions { . Expressions::Dynamic(ref mut buffer) => buffer.push(e), 277,834 ( 0.00%) Expressions::UpFront(coercion_sites) => { . // if the user gave us an array to validate, check that we got . // the next expression in the list, as expected 554,936 ( 0.01%) assert_eq!( 416,751 ( 0.01%) coercion_sites[self.pushed].as_coercion_site().hir_id, . e.hir_id . ); . } . } 558,138 ( 0.01%) self.pushed += 1; . } . } . Err(coercion_error) => { . let (expected, found) = if label_expression_as_expected { . // In the case where this is a "forced unit", like . // `break`, we want to call the `()` "expected" . // since it is implied by the syntax. . // (Note: not all force-units work this way.)" -- line 1434 ---------------------------------------- -- line 1707 ---------------------------------------- . if let ty::Dynamic(..) = ty.kind() { . return true; . } . } . } . false . } . 2,816 ( 0.00%) pub fn complete<'a>(self, fcx: &FnCtxt<'a, 'tcx>) -> Ty<'tcx> { 4,908 ( 0.00%) if let Some(final_ty) = self.final_ty { . final_ty . } else { . // If we only had inputs that were of type `!` (or no . // inputs at all), then the final type is `!`. 66 ( 0.00%) assert_eq!(self.pushed, 0); 33 ( 0.00%) fcx.tcx.types.never . } 3,520 ( 0.00%) } . } . . /// Something that can be converted into an expression to which we can . /// apply a coercion. . pub trait AsCoercionSite { . fn as_coercion_site(&self) -> &hir::Expr<'_>; . } . -- line 1732 ---------------------------------------- -- line 1736 ---------------------------------------- . } . } . . impl<'a, T> AsCoercionSite for &'a T . where . T: AsCoercionSite, . { . fn as_coercion_site(&self) -> &hir::Expr<'_> { 525 ( 0.00%) (**self).as_coercion_site() . } . } . . impl AsCoercionSite for ! { . fn as_coercion_site(&self) -> &hir::Expr<'_> { . unreachable!() . } . } . . impl AsCoercionSite for hir::Arm<'_> { . fn as_coercion_site(&self) -> &hir::Expr<'_> { 414 ( 0.00%) &self.body . } . } 713,176 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/flags.rs -------------------------------------------------------------------------------- Ir -- line 11 ---------------------------------------- . } . . impl FlagComputation { . fn new() -> FlagComputation { . FlagComputation { flags: TypeFlags::empty(), outer_exclusive_binder: ty::INNERMOST } . } . . #[allow(rustc::usage_of_ty_tykind)] 198,681 ( 0.00%) pub fn for_kind(kind: &ty::TyKind<'_>) -> FlagComputation { 28,383 ( 0.00%) let mut result = FlagComputation::new(); . result.add_kind(kind); . result 283,830 ( 0.00%) } . 79,310 ( 0.00%) pub fn for_predicate<'tcx>(binder: ty::Binder<'tcx, ty::PredicateKind<'_>>) -> FlagComputation { . let mut result = FlagComputation::new(); . result.add_predicate(binder); . result 111,034 ( 0.00%) } . 579,342 ( 0.01%) pub fn for_const(c: &ty::Const<'_>) -> TypeFlags { 720,743 ( 0.01%) let mut result = FlagComputation::new(); 706,209 ( 0.01%) result.add_const(c); 290,923 ( 0.00%) result.flags 579,342 ( 0.01%) } . 897 ( 0.00%) pub fn for_unevaluated_const(uv: ty::Unevaluated<'_>) -> TypeFlags { 897 ( 0.00%) let mut result = FlagComputation::new(); 897 ( 0.00%) result.add_unevaluated_const(uv); . result.flags 1,794 ( 0.00%) } . . fn add_flags(&mut self, flags: TypeFlags) { 931,134 ( 0.01%) self.flags = self.flags | flags; . } . . /// indicates that `self` refers to something at binding level `binder` . fn add_bound_var(&mut self, binder: ty::DebruijnIndex) { 3,365 ( 0.00%) let exclusive_binder = binder.shifted_in(1); . self.add_exclusive_binder(exclusive_binder); . } . . /// indicates that `self` refers to something *inside* binding . /// level `binder` -- not bound by `binder`, but bound by the next . /// binder internal to it . fn add_exclusive_binder(&mut self, exclusive_binder: ty::DebruijnIndex) { 983,964 ( 0.01%) self.outer_exclusive_binder = self.outer_exclusive_binder.max(exclusive_binder); . } . . /// Adds the flags/depth from a set of types that appear within the current type, but within a . /// region binder. . fn bound_computation(&mut self, value: ty::Binder<'_, T>, f: F) . where . F: FnOnce(&mut Self, T), . { 16,109 ( 0.00%) let mut computation = FlagComputation::new(); . 16,109 ( 0.00%) if !value.bound_vars().is_empty() { 346 ( 0.00%) computation.flags = computation.flags | TypeFlags::HAS_RE_LATE_BOUND; . } . . f(&mut computation, value.skip_binder()); . 15,365 ( 0.00%) self.add_flags(computation.flags); . . // The types that contributed to `computation` occurred within . // a region binder, so subtract one from the region depth . // within when adding the depth to `self`. 15,365 ( 0.00%) let outer_exclusive_binder = computation.outer_exclusive_binder; 16,079 ( 0.00%) if outer_exclusive_binder > ty::INNERMOST { 3,448 ( 0.00%) self.add_exclusive_binder(outer_exclusive_binder.shifted_out(1)); . } // otherwise, this binder captures nothing . } . . #[allow(rustc::usage_of_ty_tykind)] . fn add_kind(&mut self, kind: &ty::TyKind<'_>) { 141,915 ( 0.00%) match kind { . &ty::Bool . | &ty::Char . | &ty::Int(_) . | &ty::Float(_) . | &ty::Uint(_) . | &ty::Never . | &ty::Str . | &ty::Foreign(..) => {} -- line 95 ---------------------------------------- -- line 116 ---------------------------------------- . self.add_ty(substs.yield_ty()); . self.add_ty(substs.tupled_upvars_ty()); . } . . &ty::GeneratorWitness(ts) => { . self.bound_computation(ts, |flags, ts| flags.add_tys(ts)); . } . 294 ( 0.00%) &ty::Closure(_, substs) => { . let substs = substs.as_closure(); . let should_remove_further_specializable = . !self.flags.contains(TypeFlags::STILL_FURTHER_SPECIALIZABLE); 294 ( 0.00%) self.add_substs(substs.parent_substs()); . if should_remove_further_specializable { . self.flags -= TypeFlags::STILL_FURTHER_SPECIALIZABLE; . } . 294 ( 0.00%) self.add_ty(substs.sig_as_fn_ptr_ty()); 294 ( 0.00%) self.add_ty(substs.kind_ty()); 294 ( 0.00%) self.add_ty(substs.tupled_upvars_ty()); . } . 11 ( 0.00%) &ty::Bound(debruijn, _) => { . self.add_bound_var(debruijn); . } . . &ty::Placeholder(..) => { . self.add_flags(TypeFlags::HAS_TY_PLACEHOLDER); . self.add_flags(TypeFlags::STILL_FURTHER_SPECIALIZABLE); . } . . &ty::Infer(infer) => { . self.add_flags(TypeFlags::STILL_FURTHER_SPECIALIZABLE); 350 ( 0.00%) match infer { . ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => { . self.add_flags(TypeFlags::HAS_TY_FRESH) . } . . ty::TyVar(_) | ty::IntVar(_) | ty::FloatVar(_) => { . self.add_flags(TypeFlags::HAS_TY_INFER) . } . } . } . . &ty::Adt(_, substs) => { . self.add_substs(substs); . } . 759 ( 0.00%) &ty::Projection(data) => { . self.add_flags(TypeFlags::HAS_TY_PROJECTION); . self.add_projection_ty(data); . } . 23 ( 0.00%) &ty::Opaque(_, substs) => { . self.add_flags(TypeFlags::HAS_TY_OPAQUE); . self.add_substs(substs); . } . 615 ( 0.00%) &ty::Dynamic(obj, r) => { 494 ( 0.00%) for predicate in obj.iter() { 578 ( 0.00%) self.bound_computation(predicate, |computation, predicate| match predicate { 410 ( 0.00%) ty::ExistentialPredicate::Trait(tr) => computation.add_substs(tr.substs), . ty::ExistentialPredicate::Projection(p) => { . computation.add_existential_projection(&p); . } . ty::ExistentialPredicate::AutoTrait(_) => {} . }); . } . . self.add_region(r); . } . 780 ( 0.00%) &ty::Array(tt, len) => { 390 ( 0.00%) self.add_ty(tt); 780 ( 0.00%) self.add_const(len); . } . . &ty::Slice(tt) => self.add_ty(tt), . . &ty::RawPtr(ref m) => { . self.add_ty(m.ty); . } . 26,822 ( 0.00%) &ty::Ref(r, ty, _) => { . self.add_region(r); 13,411 ( 0.00%) self.add_ty(ty); . } . . &ty::Tuple(ref substs) => { 2,134 ( 0.00%) self.add_substs(substs); . } . . &ty::FnDef(_, substs) => { . self.add_substs(substs); . } . 2,236 ( 0.00%) &ty::FnPtr(fn_sig) => self.bound_computation(fn_sig, |computation, fn_sig| { . computation.add_tys(fn_sig.inputs()); 1,118 ( 0.00%) computation.add_ty(fn_sig.output()); . }), . } . } . . fn add_predicate(&mut self, binder: ty::Binder<'_, ty::PredicateKind<'_>>) { 95,172 ( 0.00%) self.bound_computation(binder, |computation, atom| computation.add_predicate_atom(atom)); . } . . fn add_predicate_atom(&mut self, atom: ty::PredicateKind<'_>) { 79,310 ( 0.00%) match atom { . ty::PredicateKind::Trait(trait_pred) => { 19,084 ( 0.00%) self.add_substs(trait_pred.trait_ref.substs); . } . ty::PredicateKind::RegionOutlives(ty::OutlivesPredicate(a, b)) => { . self.add_region(a); . self.add_region(b); . } . ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty, region)) => { 1,339 ( 0.00%) self.add_ty(ty); . self.add_region(region); . } . ty::PredicateKind::Subtype(ty::SubtypePredicate { a_is_expected: _, a, b }) => { . self.add_ty(a); . self.add_ty(b); . } . ty::PredicateKind::Coerce(ty::CoercePredicate { a, b }) => { . self.add_ty(a); . self.add_ty(b); . } . ty::PredicateKind::Projection(ty::ProjectionPredicate { projection_ty, term }) => { . self.add_projection_ty(projection_ty); 1,050 ( 0.00%) match term { 525 ( 0.00%) Term::Ty(ty) => self.add_ty(ty), . Term::Const(c) => self.add_const(c), . } . } 11,145 ( 0.00%) ty::PredicateKind::WellFormed(arg) => { 11,145 ( 0.00%) self.add_substs(slice::from_ref(&arg)); . } . ty::PredicateKind::ObjectSafe(_def_id) => {} . ty::PredicateKind::ClosureKind(_def_id, substs, _kind) => { 345 ( 0.00%) self.add_substs(substs); . } . ty::PredicateKind::ConstEvaluatable(uv) => { . self.add_unevaluated_const(uv); . } . ty::PredicateKind::ConstEquate(expected, found) => { . self.add_const(expected); . self.add_const(found); . } -- line 264 ---------------------------------------- -- line 269 ---------------------------------------- . } . . fn add_ty(&mut self, ty: Ty<'_>) { . self.add_flags(ty.flags()); . self.add_exclusive_binder(ty.outer_exclusive_binder); . } . . fn add_tys(&mut self, tys: &[Ty<'_>]) { 2,198 ( 0.00%) for &ty in tys { 2,198 ( 0.00%) self.add_ty(ty); . } . } . . fn add_region(&mut self, r: ty::Region<'_>) { . self.add_flags(r.type_flags()); 21,763 ( 0.00%) if let ty::ReLateBound(debruijn, _) = *r { . self.add_bound_var(debruijn); . } . } . 1,719,592 ( 0.02%) fn add_const(&mut self, c: &ty::Const<'_>) { 859,796 ( 0.01%) self.add_ty(c.ty); 2,149,490 ( 0.03%) match c.val { 3,064 ( 0.00%) ty::ConstKind::Unevaluated(unevaluated) => self.add_unevaluated_const(unevaluated), . ty::ConstKind::Infer(infer) => { . self.add_flags(TypeFlags::STILL_FURTHER_SPECIALIZABLE); 182 ( 0.00%) match infer { . InferConst::Fresh(_) => self.add_flags(TypeFlags::HAS_CT_FRESH), . InferConst::Var(_) => self.add_flags(TypeFlags::HAS_CT_INFER), . } . } . ty::ConstKind::Bound(debruijn, _) => { . self.add_bound_var(debruijn); . } . ty::ConstKind::Param(_) => { -- line 303 ---------------------------------------- -- line 306 ---------------------------------------- . } . ty::ConstKind::Placeholder(_) => { . self.add_flags(TypeFlags::HAS_CT_PLACEHOLDER); . self.add_flags(TypeFlags::STILL_FURTHER_SPECIALIZABLE); . } . ty::ConstKind::Value(_) => {} . ty::ConstKind::Error(_) => self.add_flags(TypeFlags::HAS_ERROR), . } 1,719,592 ( 0.02%) } . . fn add_unevaluated_const

(&mut self, ct: ty::Unevaluated<'_, P>) { 7,922 ( 0.00%) self.add_substs(ct.substs); . self.add_flags(TypeFlags::HAS_CT_PROJECTION); . } . . fn add_existential_projection(&mut self, projection: &ty::ExistentialProjection<'_>) { 60 ( 0.00%) self.add_substs(projection.substs); 60 ( 0.00%) match projection.term { 30 ( 0.00%) ty::Term::Ty(ty) => self.add_ty(ty), . ty::Term::Const(ct) => self.add_const(ct), . } . } . . fn add_projection_ty(&mut self, projection_ty: ty::ProjectionTy<'_>) { 525 ( 0.00%) self.add_substs(projection_ty.substs); . } . 213,703 ( 0.00%) fn add_substs(&mut self, substs: &[GenericArg<'_>]) { . for kind in substs { 36,796 ( 0.00%) match kind.unpack() { 61,316 ( 0.00%) GenericArgKind::Type(ty) => self.add_ty(ty), . GenericArgKind::Lifetime(lt) => self.add_region(lt), 200 ( 0.00%) GenericArgKind::Const(ct) => self.add_const(ct), . } . } 244,232 ( 0.00%) } . } 110,999 ( 0.00%) -------------------------------------------------------------------------------- The following files chosen for auto-annotation could not be found: -------------------------------------------------------------------------------- ./elf/dl-lookup.c ./malloc/malloc.c ./string/../sysdeps/x86_64/multiarch/memcmp-avx2-movbe.S ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S ./string/../sysdeps/x86_64/multiarch/memset-vec-unaligned-erms.S ./string/../sysdeps/x86_64/multiarch/strcmp-avx2.S ./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 -------------------------------------------------------------------------------- 2,443,205,973 (34.72%) events annotated