-------------------------------------------------------------------------------- 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 unicode_xid src/lib.rs --error-format=json --json=diagnostic-rendered-ansi,artifacts,future-incompat --crate-type lib --emit=dep-info,metadata,link -C embed-bitcode=no -C debuginfo=2 --cfg feature="default" -C metadata=cf4128ab003ab4fb -C extra-filename=-cf4128ab003ab4fb --out-dir /usr/home/liquid/tmp/.tmpXhdusK/target/debug/deps -L dependency=/usr/home/liquid/tmp/.tmpXhdusK/target/debug/deps -Adeprecated -Aunknown-lints -Zincremental-verify-ich Data file: results/cgout-w-profiling-unicode-xid-0.2.2-Debug-Full Events recorded: Ir Events shown: Ir Event sort order: Ir Thresholds: 0.1 Include dirs: User annotated: Auto-annotation: on -------------------------------------------------------------------------------- Ir -------------------------------------------------------------------------------- 272,770,139 (100.0%) PROGRAM TOTALS -------------------------------------------------------------------------------- Ir file:function -------------------------------------------------------------------------------- 10,308,762 ( 3.78%) ./elf/dl-lookup.c:_dl_lookup_symbol_x 8,815,193 ( 3.23%) ./malloc/malloc.c:_int_malloc 7,770,967 ( 2.85%) ./malloc/malloc.c:_int_free 5,157,780 ( 1.89%) ./malloc/malloc.c:malloc 4,844,816 ( 1.78%) ./elf/dl-lookup.c:do_lookup_x 4,603,253 ( 1.69%) ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:__memcpy_avx_unaligned_erms 4,141,271 ( 1.52%) ./elf/../sysdeps/x86_64/dl-machine.h:_dl_relocate_object 2,298,966 ( 0.84%) ./malloc/malloc.c:free 2,139,033 ( 0.78%) ./elf/do-rel.h:_dl_relocate_object 2,039,726 ( 0.75%) ???:SetImpliedBits(llvm::FeatureBitset&, llvm::FeatureBitset const&, llvm::ArrayRef) 1,990,381 ( 0.73%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_serialize/src/opaque.rs:>::decode 1,859,771 ( 0.68%) ???:llvm::PassRegistry::enumerateWith(llvm::PassRegistrationListener*) 1,831,725 ( 0.67%) ???:llvm::FPPassManager::runOnFunction(llvm::Function&) 1,683,687 ( 0.62%) ./malloc/malloc.c:malloc_consolidate 1,671,154 ( 0.61%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:>::decode 1,619,973 ( 0.59%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:>::decode 1,561,217 ( 0.57%) ???:llvm::X86TargetLowering::X86TargetLowering(llvm::X86TargetMachine const&, llvm::X86Subtarget const&) 1,483,999 ( 0.54%) ./string/../sysdeps/x86_64/multiarch/memset-vec-unaligned-erms.S:__memset_avx2_erms 1,335,670 ( 0.49%) ???:llvm::TargetLoweringBase::computeRegisterProperties(llvm::TargetRegisterInfo const*) 965,623 ( 0.35%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::from_key_hashed_nocheck:: 937,842 ( 0.34%) ./malloc/malloc.c:unlink_chunk.constprop.0 873,946 ( 0.32%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/mod.rs:::next_token 866,236 ( 0.32%) ./elf/dl-lookup.c:check_match 851,620 ( 0.31%) ???:llvm::StringMapImpl::LookupBucketFor(llvm::StringRef) 810,594 ( 0.30%) ./string/../sysdeps/x86_64/multiarch/memcmp-avx2-movbe.S:__memcmp_avx2_movbe 797,582 ( 0.29%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::get:: 723,023 ( 0.27%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:, >::decode::{closure#0}>, ::imported_source_files::{closure#3}::{closure#0}> as core::iter::traits::iterator::Iterator>::fold::<(), core::iter::traits::iterator::Iterator::for_each::call as alloc::vec::spec_extend::SpecExtend, >::decode::{closure#0}>, ::imported_source_files::{closure#3}::{closure#0}>>>::spec_extend::{closure#0}>::{closure#0}> 720,640 ( 0.26%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:::new_imported_source_file 719,048 ( 0.26%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:::new_imported_source_file 718,348 ( 0.26%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lexer/src/unescape.rs:rustc_lexer::unescape::scan_escape 660,981 ( 0.24%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/operand.rs:>::try_read_immediate 611,496 ( 0.22%) ???:(anonymous namespace)::GetCFGOnlyPasses::passEnumerate(llvm::PassInfo const*) [clone .llvm.764396836974782617] 605,074 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lexer/src/lib.rs:::advance_token 602,660 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::check 597,106 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/tokentrees.rs:::parse_token_tree 591,111 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast_pretty/src/pp/ring.rs:>::pop_first 582,602 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/caching_source_map_view.rs:::span_data_to_lines_and_cols 579,311 ( 0.21%) ???:llvm::SelectionDAG::Combine(llvm::CombineLevel, llvm::AAResults*, llvm::CodeGenOpt::Level) 564,543 ( 0.21%) ./malloc/malloc.c:realloc 553,669 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast_pretty/src/pp.rs:::advance_left 548,548 ( 0.20%) ???:llvm::X86_MC::initLLVMToSEHAndCVRegMapping(llvm::MCRegisterInfo*) 547,385 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/vec_deque/mod.rs:>::push_back 542,788 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/coercion.rs:::coerce 535,408 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/char/mod.rs:::next 531,238 ( 0.19%) ./string/../sysdeps/x86_64/strcmp.S:strcmp 528,304 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/hir/map/mod.rs:::attrs 520,505 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_metadata/src/rmeta/decoder.rs:, >::decode::{closure#0}>, ::imported_source_files::{closure#3}::{closure#0}> as core::iter::traits::iterator::Iterator>::fold::<(), core::iter::traits::iterator::Iterator::for_each::call as alloc::vec::spec_extend::SpecExtend, >::decode::{closure#0}>, ::imported_source_files::{closure#3}::{closure#0}>>>::spec_extend::{closure#0}>::{closure#0}> 519,225 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs:::short_write_process_buffer:: 518,052 ( 0.19%) ???:llvm::raw_svector_ostream::write_impl(char const*, unsigned long) 510,812 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/middle/region.rs:::temporary_scope 498,401 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/library/std/src/sys/unix/alloc.rs:__rdl_alloc 487,843 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::next 479,637 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:, >::decode::{closure#0}>, ::imported_source_files::{closure#3}::{closure#0}> as core::iter::traits::iterator::Iterator>::fold::<(), core::iter::traits::iterator::Iterator::for_each::call as alloc::vec::spec_extend::SpecExtend, >::decode::{closure#0}>, ::imported_source_files::{closure#3}::{closure#0}>>>::spec_extend::{closure#0}>::{closure#0}> 475,386 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::bump 455,200 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_build/src/thir/cx/expr.rs:::mirror_expr_inner 444,776 ( 0.16%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, (), core::hash::BuildHasherDefault>>::from_hash::>::{closure#0}> 441,308 ( 0.16%) ???:llvm::PMTopLevelManager::AUFoldingSetNode::Profile(llvm::FoldingSetNodeID&, llvm::AnalysisUsage const&) 428,438 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/interpret/allocation.rs:::read_scalar:: 425,182 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/option.rs:::advance_left 417,438 ( 0.15%) ./string/../sysdeps/x86_64/multiarch/strlen-avx2.S:__strlen_avx2 415,588 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_metadata/src/rmeta/encoder.rs:>::encode 413,838 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/context.rs:::maybe_lint_level_root_bounded 411,488 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/freshen.rs:::fold_ty 407,811 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:>::hash_stable 407,089 ( 0.15%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/rustc-hash-1.1.0/src/lib.rs:<&str as core::hash::Hash>::hash:: 405,464 ( 0.15%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>::reserve_rehash::>::{closure#0}> 399,894 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::clone 395,634 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/hir/map/mod.rs:::find_parent_node 393,440 ( 0.14%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:::node_type_opt 383,778 ( 0.14%) ???:llvm::PMDataManager::verifyPreservedAnalysis(llvm::Pass*) 381,611 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/mod.rs:::lookup_source_file_idx 381,210 ( 0.14%) /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}> 375,640 ( 0.14%) ???:(anonymous namespace)::Verifier::visitMDNode(llvm::MDNode const&, (anonymous namespace)::Verifier::AreDebugLocsAllowed) 371,338 ( 0.14%) /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::> 368,508 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/middle/region.rs:>>::get:: 367,538 ( 0.13%) ???:llvm::AttributeList::addAttributes(llvm::LLVMContext&, unsigned int, llvm::AttrBuilder const&) const 364,427 ( 0.13%) ./malloc/malloc.c:_int_realloc 362,501 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/layout.rs:<&rustc_middle::ty::TyS as rustc_target::abi::TyAbiInterface<_>>::ty_and_layout_field::field_ty_or_layout::> 360,950 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/expr.rs:::parse_assoc_expr_with 360,061 ( 0.13%) ???:(anonymous namespace)::Verifier::visitInstruction(llvm::Instruction&) 359,576 ( 0.13%) ???:llvm::LegacyLegalizerInfo::computeTables() 357,928 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/layout.rs:<&rustc_middle::ty::TyS as rustc_target::abi::TyAbiInterface>>::ty_and_layout_field 355,744 ( 0.13%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs:>>::from_key_hashed_nocheck:: 349,115 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_dataflow/src/drop_flag_effects.rs:rustc_mir_dataflow::drop_flag_effects::on_all_children_bits::is_terminal_path 348,347 ( 0.13%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::insert 348,300 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs:::short_write_process_buffer:: 346,592 ( 0.13%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs:>, (), core::hash::BuildHasherDefault>>::from_hash::>>::{closure#0}> 339,108 ( 0.12%) ???:llvm::DenseMapBase, llvm::detail::DenseMapPair >, llvm::MCRegister, int, llvm::DenseMapInfo, llvm::detail::DenseMapPair >::moveFromOldBuckets(llvm::detail::DenseMapPair*, llvm::detail::DenseMapPair*) 338,125 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_build/src/build/expr/as_operand.rs:::as_operand 334,892 ( 0.12%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, (), core::hash::BuildHasherDefault>>::from_hash::, rustc_middle::ty::context::Interned>::{closure#0}> 334,534 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/regionck.rs:::visit_expr 333,592 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/tokenstream.rs:::next_with_spacing 331,827 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_build/src/thir/cx/expr.rs:::make_mirror_unadjusted 331,368 ( 0.12%) /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} 329,760 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/interpret/allocation.rs:::get_bytes_internal:: 328,780 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/validity.rs:>::try_visit_primitive 328,669 ( 0.12%) ???:llvm::PMDataManager::removeNotPreservedAnalysis(llvm::Pass*) 322,777 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::eq 320,996 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/sty.rs:::is_trivially_sized 320,185 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lint/src/levels.rs:::push 319,130 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/mod.rs:::shallow_resolve_ty 315,476 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/context.rs:::_intern_substs 312,674 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/undo_log.rs:>::reverse 310,504 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/undo_log.rs:::rollback_to 309,483 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:::_intern_substs 309,022 ( 0.11%) ???:(anonymous namespace)::RegAllocFast::allocateBasicBlock(llvm::MachineBasicBlock&) 308,901 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/validity.rs:>::aggregate_field_path_elem 306,294 ( 0.11%) ???:llvm::MCObjectStreamer::emitBytes(llvm::StringRef) 305,212 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/writeback.rs:::visit_node_id 302,625 ( 0.11%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/md-5-0.9.1/src/utils.rs:md5::utils::compress 301,830 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/interpret/allocation.rs:::get_relocations:: 297,171 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cell.rs:::attrs 291,953 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/place.rs:>::force_allocation_maybe_sized 289,932 ( 0.11%) ???:llvm::PMTopLevelManager::setLastUser(llvm::ArrayRef, llvm::Pass*) 288,074 ( 0.11%) ./malloc/malloc.c:calloc 285,849 ( 0.10%) ???:llvm::StringMapImpl::RehashTable(unsigned int) 283,896 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs:>::hash_stable 281,442 ( 0.10%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>, (), core::hash::BuildHasherDefault>>::from_hash::>>::{closure#0}> 281,206 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/expr.rs:::check_expr_with_expectation_and_args -------------------------------------------------------------------------------- -- 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, . { 7,853 ( 0.00%) 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. 15 ( 0.00%) #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd)] 620 ( 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 1,594 ( 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> { 4 ( 0.00%) encoder.emit_enum(|encoder| match *self { . RealFileName::LocalPath(ref local_path) => { 16 ( 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 { 1,416 ( 0.00%) match self { . RealFileName::LocalPath(p) . | RealFileName::Remapped { local_path: _, virtual_name: p } => &p, . } 3 ( 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 { 2 ( 0.00%) match self { . RealFileName::LocalPath(path) . | RealFileName::Remapped { local_path: None, virtual_name: path } . | RealFileName::Remapped { local_path: Some(path), virtual_name: _ } => path, . } . } . 40 ( 0.00%) pub fn to_string_lossy(&self, display_pref: FileNameDisplayPreference) -> Cow<'_, str> { 96 ( 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() . } . } 60 ( 0.00%) } . } . . /// Differentiates between real files and common virtual files. 3,311 ( 0.00%) #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash)] 3,761 ( 0.00%) #[derive(Decodable, Encodable)] . pub enum FileName { . Real(RealFileName), . /// Call to `quote!`. 1 ( 0.00%) QuoteExpansion(u64), . /// Command line. . Anon(u64), . /// Hack in `src/librustc_ast/parse.rs`. . // FIXME(jseyfried) . MacroExpansion(u64), . ProcMacroSourceCode(u64), . /// Strings provided as `--cfg [cfgspec]` stored in a `crate_cfg`. . CfgSpec(u64), -- line 285 ---------------------------------------- -- 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 { 14 ( 0.00%) fn from(p: PathBuf) -> Self { 4 ( 0.00%) assert!(!p.to_string_lossy().ends_with('>')); 12 ( 0.00%) FileName::Real(RealFileName::LocalPath(p)) 14 ( 0.00%) } . } . 16 ( 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<'_> { 212 ( 0.00%) fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { . use FileName::*; 318 ( 0.00%) match *self.inner { . Real(ref name) => { 318 ( 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, ""), . } 265 ( 0.00%) } . } . . impl FileNameDisplay<'_> { 12 ( 0.00%) pub fn to_string_lossy(&self) -> Cow<'_, str> { 9 ( 0.00%) match self.inner { 3 ( 0.00%) FileName::Real(ref inner) => inner.to_string_lossy(self.display_pref), . _ => Cow::from(format!("{}", self)), . } 12 ( 0.00%) } . } . . impl FileName { . pub fn is_real(&self) -> bool { . use FileName::*; 732 ( 0.00%) match *self { . Real(_) => true, . Anon(_) . | MacroExpansion(_) . | ProcMacroSourceCode(_) . | CfgSpec(_) . | CliCrateAttr(_) . | Custom(_) . | QuoteExpansion(_) . | DocTest(_, _) . | InlineAsm(_) => false, . } . } . 54 ( 0.00%) pub fn prefer_remapped(&self) -> FileNameDisplay<'_> { . FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Remapped } 108 ( 0.00%) } . . // This may include transient local filesystem information. . // Must not be embedded in build outputs. 2 ( 0.00%) pub fn prefer_local(&self) -> FileNameDisplay<'_> { . FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Local } 4 ( 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 383 ---------------------------------------- . } . . pub fn proc_macro_source_code(src: &str) -> FileName { . let mut hasher = StableHasher::new(); . src.hash(&mut hasher); . FileName::ProcMacroSourceCode(hasher.finish()) . } . 5 ( 0.00%) pub fn cfg_spec_source_code(src: &str) -> FileName { . let mut hasher = StableHasher::new(); . src.hash(&mut hasher); 2 ( 0.00%) FileName::QuoteExpansion(hasher.finish()) 5 ( 0.00%) } . . pub fn cli_crate_attr_source_code(src: &str) -> FileName { . let mut hasher = StableHasher::new(); . src.hash(&mut hasher); . FileName::CliCrateAttr(hasher.finish()) . } . . pub fn doc_test_source_code(path: PathBuf, line: isize) -> FileName { -- line 403 ---------------------------------------- -- 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 { 1 ( 0.00%) pub lo: BytePos, 1 ( 0.00%) pub hi: BytePos, . /// Information about where the macro came from, if this piece of . /// code was created by a macro expansion. 3 ( 0.00%) pub ctxt: SyntaxContext, 1 ( 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 { 42,835 ( 0.02%) self.lo.0 == 0 && self.hi.0 == 0 . } . /// Returns `true` if `self` fully encloses `other`. . pub fn contains(self, other: Self) -> bool { 21 ( 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 { 2,616 ( 0.00%) fn partial_cmp(&self, rhs: &Self) -> Option { 1,962 ( 0.00%) PartialOrd::partial_cmp(&self.data(), &rhs.data()) 2,616 ( 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] 12,888 ( 0.00%) pub fn with_lo(self, lo: BytePos) -> Span { . self.data().with_lo(lo) 8,592 ( 0.00%) } . #[inline] 308 ( 0.00%) pub fn hi(self) -> BytePos { . self.data().hi 308 ( 0.00%) } . #[inline] 747 ( 0.00%) pub fn with_hi(self, hi: BytePos) -> Span { . self.data().with_hi(hi) 498 ( 0.00%) } . #[inline] . pub fn ctxt(self) -> SyntaxContext { . self.data_untracked().ctxt . } . #[inline] 90 ( 0.00%) pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span { . self.data_untracked().with_ctxt(ctxt) 54 ( 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 618 ---------------------------------------- . } . . /// 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`. 63 ( 0.00%) pub fn contains(self, other: Span) -> bool { . let span = self.data(); . let other = other.data(); . span.contains(other) 42 ( 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 671 ---------------------------------------- . pub fn find_ancestor_inside(mut self, outer: Span) -> Option { . while !outer.contains(self) { . self = self.parent_callsite()?; . } . Some(self) . } . . /// Edition of the crate from which this span came. 249 ( 0.00%) pub fn edition(self) -> edition::Edition { . self.ctxt().edition() 166 ( 0.00%) } . . #[inline] . pub fn rust_2015(self) -> bool { 64 ( 0.00%) self.edition() == edition::Edition::Edition2015 . } . . #[inline] . pub fn rust_2018(self) -> bool { 18 ( 0.00%) self.edition() >= edition::Edition::Edition2018 . } . . #[inline] . pub fn rust_2021(self) -> bool { 7 ( 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]`). 5 ( 0.00%) pub fn allows_unstable(self, feature: Symbol) -> bool { 1 ( 0.00%) self.ctxt() . .outer_expn_data() . .allow_internal_unstable . .map_or(false, |features| features.iter().any(|&f| f == feature)) 4 ( 0.00%) } . . /// Checks if this span arises from a compiler desugaring of kind `kind`. 56 ( 0.00%) pub fn is_desugaring(self, kind: DesugaringKind) -> bool { 48 ( 0.00%) match self.ctxt().outer_expn_data().kind { . ExpnKind::Desugaring(k) => k == kind, . _ => false, . } 40 ( 0.00%) } . . /// Returns the compiler desugaring that created this span, or `None` . /// if this span is not from a desugaring. 10 ( 0.00%) pub fn desugaring_kind(self) -> Option { 12 ( 0.00%) match self.ctxt().outer_expn_data().kind { . ExpnKind::Desugaring(k) => Some(k), . _ => None, . } 8 ( 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]`). . pub fn allows_unsafe(self) -> bool { . self.ctxt().outer_expn_data().allow_internal_unsafe . } . -- line 745 ---------------------------------------- -- line 767 ---------------------------------------- . . /// Returns a `Span` that would enclose both `self` and `end`. . /// . /// ```text . /// ____ ___ . /// self lorem ipsum end . /// ^^^^^^^^^^^^^^^^^^^^ . /// ``` 49,830 ( 0.02%) 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. 9,060 ( 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( . 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 }, 31,710 ( 0.01%) if span_data.parent == end_data.parent { span_data.parent } else { None }, . ) 40,770 ( 0.01%) } . . /// Returns a `Span` between the end of `self` to the beginning of `end`. . /// . /// ```text . /// ____ ___ . /// self lorem ipsum end . /// ^^^^^^^^^^^^^ . /// ``` 11 ( 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 }, 7 ( 0.00%) if span.parent == end.parent { span.parent } else { None }, . ) 8 ( 0.00%) } . . /// Returns a `Span` from the beginning of `self` until the beginning of `end`. . /// . /// ```text . /// ____ ___ . /// self lorem ipsum end . /// ^^^^^^^^^^^^^^^^^ . /// ``` 44 ( 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. 8 ( 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 }, 28 ( 0.00%) if span_data.parent == end_data.parent { span_data.parent } else { None }, . ) 36 ( 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, . ) . } . . /// 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 { 2 ( 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 { 2 ( 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). 24 ( 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)) 14 ( 0.00%) } . . #[inline] . pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span { . let span = self.data(); . span.with_ctxt(span.ctxt.apply_mark(expn_id, transparency)) . } . . #[inline] -- line 892 ---------------------------------------- -- 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] 603 ( 0.00%) pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option { 402 ( 0.00%) let mut span = self.data(); 331 ( 0.00%) let mark = span.ctxt.normalize_to_macros_2_0_and_adjust(expn_id); 603 ( 0.00%) *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark 666 ( 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] 504 ( 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()) 441 ( 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 { 115 ( 0.00%) MultiSpan { primary_spans: vec![primary_span], span_labels: vec![] } . } . . pub fn from_spans(mut vec: Vec) -> MultiSpan { . vec.sort(); . 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() 10 ( 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 { 115 ( 0.00%) fn from(span: Span) -> MultiSpan { . MultiSpan::from_span(span) 115 ( 0.00%) } . } . . impl From> for MultiSpan { . fn from(spans: Vec) -> MultiSpan { . MultiSpan::from_spans(spans) . } . } . -- line 1157 ---------------------------------------- -- line 1160 ---------------------------------------- . 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`. 268 ( 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), . } -- line 1176 ---------------------------------------- -- line 1201 ---------------------------------------- . } . } . } . . impl Add for NonNarrowChar { . type Output = Self; . . fn add(self, rhs: BytePos) -> Self { 466 ( 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; . 134 ( 0.00%) fn sub(self, rhs: BytePos) -> Self { 466 ( 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), . } 402 ( 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, . } . 6 ( 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 1267 ---------------------------------------- . _ => None, . } . } . } . . #[derive(Debug)] . pub struct OffsetOverflowError; . 626 ( 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. 12 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, Debug)] 1,252 ( 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 => { 9 ( 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 1324 ---------------------------------------- . . /// Check if the stored hash matches the hash of the string. . pub fn matches(&self, src: &str) -> bool { . Self::new(self.kind, src) == *self . } . . /// The bytes of the hash. . pub fn hash_bytes(&self) -> &[u8] { 8 ( 0.00%) let len = self.hash_len(); 8 ( 0.00%) &self.value[..len] 8 ( 0.00%) } . . fn hash_len(&self) -> usize { 25 ( 0.00%) match self.kind { . SourceFileHashAlgorithm::Md5 => 16, . SourceFileHashAlgorithm::Sha1 => 20, . SourceFileHashAlgorithm::Sha256 => 32, . } . } . } . . /// A single source in the [`SourceMap`]. 116 ( 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. 2 ( 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. 2 ( 0.00%) pub name_hash: u128, . /// Indicates which crate this `SourceFile` was imported from. 2 ( 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)?; . 8 ( 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 { 4 ( 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); . 4 ( 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))?; 6 ( 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))?; 22 ( 0.00%) s.emit_struct_field("cnum", false, |s| self.cnum.encode(s)) . }) . } . } . . impl Decodable for SourceFile { 2,817 ( 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); 313 ( 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 { 636,706 ( 0.23%) 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)); 626 ( 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)); 3,443 ( 0.00%) SourceFile { 2,504 ( 0.00%) name, . start_pos, . end_pos, . src: None, 1,252 ( 0.00%) src_hash, . // Unused - the metadata decoder will construct . // a new SourceFile, filling in `external_src` properly . external_src: Lock::new(ExternalSource::Unneeded), 1,252 ( 0.00%) lines, 1,252 ( 0.00%) multibyte_chars, 1,252 ( 0.00%) non_narrow_chars, 1,252 ( 0.00%) normalized_pos, . name_hash, . cnum, . } . }) 2,817 ( 0.00%) } . } . . impl fmt::Debug for SourceFile { . fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { . write!(fmt, "SourceFile({:?})", self.name) . } . } . . impl SourceFile { 33 ( 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); 9 ( 0.00%) let normalized_pos = normalize_src(&mut src, start_pos); . . let name_hash = { . let mut hasher: StableHasher = StableHasher::new(); 6 ( 0.00%) name.hash(&mut hasher); . hasher.finish::() . }; 6 ( 0.00%) let end_pos = start_pos.to_usize() + src.len(); 9 ( 0.00%) assert!(end_pos <= u32::MAX as usize); . 36 ( 0.00%) let (lines, multibyte_chars, non_narrow_chars) = 6 ( 0.00%) analyze_source_file::analyze_source_file(&src, start_pos); . 51 ( 0.00%) SourceFile { . name, . src: Some(Lrc::new(src)), 33 ( 0.00%) src_hash, . external_src: Lock::new(ExternalSource::Unneeded), . start_pos, . end_pos: Pos::from_usize(end_pos), 12 ( 0.00%) lines, 12 ( 0.00%) multibyte_chars, 12 ( 0.00%) non_narrow_chars, 12 ( 0.00%) normalized_pos, . name_hash, . cnum: LOCAL_CRATE, . } 27 ( 0.00%) } . . /// Returns the `BytePos` of the beginning of the current line. 750 ( 0.00%) pub fn line_begin_pos(&self, pos: BytePos) -> BytePos { . let line_index = self.lookup_line(pos).unwrap(); 375 ( 0.00%) self.lines[line_index] 750 ( 0.00%) } . . /// 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. 56 ( 0.00%) pub fn add_external_src(&self, get_src: F) -> bool . where . F: FnOnce() -> Option, . { 8 ( 0.00%) if matches!( 16 ( 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 { 8 ( 0.00%) self.src.is_some() || self.external_src.borrow().get_source().is_some() . } 72 ( 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() 366 ( 0.00%) } . . pub fn is_imported(&self) -> bool { . self.src.is_none() 9,008 ( 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 { 2,232 ( 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 { 4,424 ( 0.00%) if self.is_empty() { . return self.start_pos..self.end_pos; . } . 2,968 ( 0.00%) assert!(line_index < self.lines.len()); 4,413 ( 0.00%) if line_index == (self.lines.len() - 1) { 13 ( 0.00%) self.lines[line_index]..self.end_pos . } else { 2,932 ( 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`. 8 ( 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; . 24 ( 0.00%) for mbc in self.multibyte_chars.iter() { . debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos); 12 ( 0.00%) if mbc.pos < bpos { . // Every character is at least one byte, so we only . // count the actual extra bytes. . total_extra_bytes += mbc.bytes as u32 - 1; . // We should never see a byte position in the middle of a . // character. . assert!(bpos.to_u32() >= mbc.pos.to_u32() + mbc.bytes as u32); . } else { . break; . } . } . 48 ( 0.00%) assert!(self.start_pos.to_u32() + total_extra_bytes <= bpos.to_u32()); 40 ( 0.00%) CharPos(bpos.to_usize() - self.start_pos.to_usize() - total_extra_bytes as usize) 16 ( 0.00%) } . . /// Looks up the file's (1-based) line number and (0-based `CharPos`) column offset, for a . /// given `BytePos`. 28 ( 0.00%) pub fn lookup_file_pos(&self, pos: BytePos) -> (usize, CharPos) { 8 ( 0.00%) let chpos = self.bytepos_to_file_charpos(pos); 3 ( 0.00%) match self.lookup_line(pos) { . Some(a) => { . let line = a + 1; // Line numbers start at 1 4 ( 0.00%) let linebpos = self.lines[a]; 8 ( 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); 4 ( 0.00%) assert!(chpos >= linechpos); . (line, col) . } . None => (0, chpos), . } 32 ( 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`. 32 ( 0.00%) pub fn lookup_file_pos_with_col_display(&self, pos: BytePos) -> (usize, CharPos, usize) { 12 ( 0.00%) let (line, col_or_chpos) = self.lookup_file_pos(pos); 8 ( 0.00%) if line > 0 { . let col = col_or_chpos; 4 ( 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); . 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(); 20 ( 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) . } 28 ( 0.00%) } . } . . /// Normalizes the source code and records the normalizations. 30 ( 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 27 ( 0.00%) } . . /// Removes UTF-8 BOM, if any. . fn remove_bom(src: &mut String, normalized_pos: &mut Vec) { 3 ( 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) { 3 ( 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])* 13,137 ( 0.00%) $vis struct $ident($inner_vis $inner_ty); . . impl Pos for $ident { . #[inline(always)] . fn from_usize(n: usize) -> $ident { 1,468 ( 0.00%) $ident(n as $inner_ty) . } . . #[inline(always)] . fn to_usize(&self) -> usize { 27,665 ( 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 { 1,014,264 ( 0.37%) $ident(self.0 + rhs.0) . } . } . . impl Sub for $ident { . type Output = $ident; . . #[inline(always)] . fn sub(self, rhs: $ident) -> $ident { 657,826 ( 0.24%) $ident(self.0 - rhs.0) . } . } . )* . }; . } . . impl_pos! { . /// A byte offset. -- line 1931 ---------------------------------------- -- line 1946 ---------------------------------------- . impl Encodable for BytePos { . fn encode(&self, s: &mut S) -> Result<(), S::Error> { . s.emit_u32(self.0) . } . } . . impl Decodable for BytePos { . fn decode(d: &mut D) -> BytePos { 16,658 ( 0.01%) BytePos(d.read_u32()) . } . } . . // _____________________________________________________________________________ . // Loc, SourceFileAndLine, SourceFileAndBytePos . // . . /// A source code location used for error reporting. -- line 1962 ---------------------------------------- -- 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. 53,011 ( 0.02%) 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; . 7,871 ( 0.00%) if !ctx.hash_spans() { . return; . } . 45,140 ( 0.02%) let span = self.data_untracked(); 21,837 ( 0.01%) span.ctxt.hash_stable(ctx, hasher); 22,719 ( 0.01%) span.parent.hash_stable(ctx, hasher); . 15,183 ( 0.01%) if span.is_dummy() { . Hash::hash(&TAG_INVALID_SPAN, hasher); . return; . } . 15,072 ( 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. 30,144 ( 0.01%) let (file, line_lo, col_lo, line_hi, col_hi) = match ctx.span_data_to_lines_and_cols(&span) . { 15,072 ( 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. . 7,536 ( 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; 7,536 ( 0.00%) let len = (span.hi - span.lo).0; . Hash::hash(&col_line, hasher); . Hash::hash(&len, hasher); 60,584 ( 0.02%) } . } 860,170 ( 0.32%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/sty.rs -------------------------------------------------------------------------------- Ir -- line 21 ---------------------------------------- . use rustc_target::spec::abi; . use std::borrow::Cow; . use std::cmp::Ordering; . use std::marker::PhantomData; . use std::ops::Range; . use ty::util::IntTypeExt; . . #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] 1 ( 0.00%) #[derive(HashStable, TypeFoldable, Lift)] . pub struct TypeAndMut<'tcx> { 96 ( 0.00%) pub ty: Ty<'tcx>, 480 ( 0.00%) pub mutbl: hir::Mutability, . } . . #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, TyEncodable, TyDecodable, Copy)] . #[derive(HashStable)] . /// A "free" region `fr` can be interpreted as "some region . /// at least as big as the scope `fr.scope`". . pub struct FreeRegion { 17 ( 0.00%) pub scope: DefId, 42 ( 0.00%) pub bound_region: BoundRegionKind, . } . 1,205 ( 0.00%) #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, TyEncodable, TyDecodable, Copy)] 6 ( 0.00%) #[derive(HashStable)] . pub enum BoundRegionKind { . /// An anonymous region parameter for a given fn (&T) 99 ( 0.00%) BrAnon(u32), . . /// Named region parameters for functions (a in &'a T) . /// . /// The `DefId` is needed to distinguish free regions in . /// the event of shadowing. . BrNamed(DefId, Symbol), . . /// Anonymous region for the implicit env pointer parameter . /// to a closure . BrEnv, . } . 6 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, Debug, PartialOrd, Ord)] . #[derive(HashStable)] . pub struct BoundRegion { 243 ( 0.00%) pub var: BoundVar, 205 ( 0.00%) pub kind: BoundRegionKind, . } . . impl BoundRegionKind { . pub fn is_named(&self) -> bool { . match *self { . BoundRegionKind::BrNamed(_, name) => name != kw::UnderscoreLifetime, . _ => false, . } . } . } . . /// Defines the kinds of types. . /// . /// N.B., if you change this, you'll probably want to change the corresponding . /// AST structure in `rustc_ast/src/ast.rs` as well. 316,727 ( 0.12%) #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable, Debug)] 2,726 ( 0.00%) #[derive(HashStable)] . #[rustc_diagnostic_item = "TyKind"] . pub enum TyKind<'tcx> { . /// The primitive boolean type. Written as `bool`. . Bool, . . /// The primitive character type; holds a Unicode scalar value . /// (a non-surrogate code point). Written as `char`. . Char, -- line 90 ---------------------------------------- -- line 99 ---------------------------------------- . Float(ty::FloatTy), . . /// Algebraic data types (ADT). For example: structures, enumerations and unions. . /// . /// InternalSubsts here, possibly against intuition, *may* contain `Param`s. . /// That is, even after substitution it is possible that there are type . /// variables. This happens when the `Adt` corresponds to an ADT . /// definition and not a concrete use of it. 865 ( 0.00%) Adt(&'tcx AdtDef, SubstsRef<'tcx>), . . /// An unsized FFI type that is opaque to Rust. Written as `extern type T`. . Foreign(DefId), . . /// The pointee of a string slice. Written as `str`. . Str, . . /// An array with the given length. Written as `[T; n]`. 222 ( 0.00%) Array(Ty<'tcx>, &'tcx ty::Const<'tcx>), . . /// The pointee of an array slice. Written as `[T]`. . Slice(Ty<'tcx>), . . /// A raw pointer. Written as `*mut T` or `*const T` . RawPtr(TypeAndMut<'tcx>), . . /// A reference; a pointer with an associated lifetime. Written as . /// `&'a mut T` or `&'a T`. 5,838 ( 0.00%) Ref(Region<'tcx>, Ty<'tcx>, hir::Mutability), . . /// The anonymous type of a function declaration/definition. Each . /// function has a unique type, which is output (for a function . /// named `foo` returning an `i32`) as `fn() -> i32 {foo}`. . /// . /// For example the type of `bar` here: . /// . /// ```rust -- line 134 ---------------------------------------- -- line 180 ---------------------------------------- . /// The substitutions are for the generics of the function in question. . /// After typeck, the concrete type can be found in the `types` map. . Opaque(DefId, SubstsRef<'tcx>), . . /// A type parameter; for example, `T` in `fn f(x: T) {}`. . Param(ParamTy), . . /// Bound type variable, used only when preparing a trait query. 15 ( 0.00%) Bound(ty::DebruijnIndex, BoundTy), . . /// A placeholder type - universally quantified higher-ranked type. . Placeholder(ty::PlaceholderType), . . /// A type variable used during type checking. . Infer(InferTy), . . /// A placeholder for a type which could not be computed; this is -- line 196 ---------------------------------------- -- line 330 ---------------------------------------- . pub closure_kind_ty: T, . pub closure_sig_as_fn_ptr_ty: T, . pub tupled_upvars_ty: T, . } . . impl<'tcx> ClosureSubsts<'tcx> { . /// Construct `ClosureSubsts` from `ClosureSubstsParts`, containing `Substs` . /// for the closure parent, alongside additional closure-specific components. 1 ( 0.00%) pub fn new( . tcx: TyCtxt<'tcx>, . parts: ClosureSubstsParts<'tcx, Ty<'tcx>>, . ) -> ClosureSubsts<'tcx> { . ClosureSubsts { . substs: tcx.mk_substs( 2 ( 0.00%) parts.parent_substs.iter().copied().chain( 4 ( 0.00%) [parts.closure_kind_ty, parts.closure_sig_as_fn_ptr_ty, parts.tupled_upvars_ty] . .iter() . .map(|&ty| ty.into()), . ), . ), . } 2 ( 0.00%) } . . /// Divides the closure substs into their respective components. . /// The ordering assumed here must match that used by `ClosureSubsts::new` above. 40 ( 0.00%) fn split(self) -> ClosureSubstsParts<'tcx, GenericArg<'tcx>> { . match self.substs[..] { 206 ( 0.00%) [ 62 ( 0.00%) ref parent_substs @ .., 69 ( 0.00%) closure_kind_ty, 21 ( 0.00%) closure_sig_as_fn_ptr_ty, 53 ( 0.00%) tupled_upvars_ty, 160 ( 0.00%) ] => ClosureSubstsParts { . parent_substs, . closure_kind_ty, . closure_sig_as_fn_ptr_ty, . tupled_upvars_ty, . }, . _ => bug!("closure substs missing synthetics"), . } 120 ( 0.00%) } . . /// Returns `true` only if enough of the synthetic types are known to . /// allow using all of the methods on `ClosureSubsts` without panicking. . /// . /// Used primarily by `ty::print::pretty` to be able to handle closure . /// types that haven't had their synthetic types substituted in. . pub fn is_valid(self) -> bool { . self.substs.len() >= 3 -- line 378 ---------------------------------------- -- line 383 ---------------------------------------- . pub fn parent_substs(self) -> &'tcx [GenericArg<'tcx>] { . self.split().parent_substs . } . . /// Returns an iterator over the list of types of captured paths by the closure. . /// In case there was a type error in figuring out the types of the captured path, an . /// empty iterator is returned. . #[inline] 18 ( 0.00%) pub fn upvar_tys(self) -> impl Iterator> + 'tcx { 25 ( 0.00%) match self.tupled_upvars_ty().kind() { . TyKind::Error(_) => None, 14 ( 0.00%) TyKind::Tuple(..) => Some(self.tupled_upvars_ty().tuple_fields()), . TyKind::Infer(_) => bug!("upvar_tys called before capture types are inferred"), . ty => bug!("Unexpected representation of upvar types tuple {:?}", ty), . } . .into_iter() . .flatten() 12 ( 0.00%) } . . /// Returns the tuple type representing the upvars for this closure. . #[inline] . pub fn tupled_upvars_ty(self) -> Ty<'tcx> { 195 ( 0.00%) self.split().tupled_upvars_ty.expect_ty() . } . . /// Returns the closure kind for this closure; may return a type . /// variable during inference. To get the closure kind during . /// inference, use `infcx.closure_kind(substs)`. 13 ( 0.00%) pub fn kind_ty(self) -> Ty<'tcx> { . self.split().closure_kind_ty.expect_ty() 26 ( 0.00%) } . . /// Returns the `fn` pointer type representing the closure signature for this . /// closure. . // FIXME(eddyb) this should be unnecessary, as the shallowly resolved . // type is known at the time of the creation of `ClosureSubsts`, . // see `rustc_typeck::check::closure`. . pub fn sig_as_fn_ptr_ty(self) -> Ty<'tcx> { . self.split().closure_sig_as_fn_ptr_ty.expect_ty() . } . . /// Returns the closure kind for this closure; only usable outside . /// of an inference context, because in that context we know that . /// there are no type variables. . /// . /// If you have an inference context, use `infcx.closure_kind()`. 1 ( 0.00%) pub fn kind(self) -> ty::ClosureKind { 2 ( 0.00%) self.kind_ty().to_opt_closure_kind().unwrap() 2 ( 0.00%) } . . /// Extracts the signature from the closure. 10 ( 0.00%) pub fn sig(self) -> ty::PolyFnSig<'tcx> { . let ty = self.sig_as_fn_ptr_ty(); 20 ( 0.00%) match ty.kind() { 40 ( 0.00%) ty::FnPtr(sig) => *sig, . _ => bug!("closure_sig_as_fn_ptr_ty is not a fn-ptr: {:?}", ty.kind()), . } 30 ( 0.00%) } . } . . /// Similar to `ClosureSubsts`; see the above documentation for more. . #[derive(Copy, Clone, Debug, TypeFoldable)] . pub struct GeneratorSubsts<'tcx> { . pub substs: SubstsRef<'tcx>, . } . -- line 448 ---------------------------------------- -- line 676 ---------------------------------------- . } . . impl<'tcx> UpvarSubsts<'tcx> { . /// Returns an iterator over the list of types of captured paths by the closure/generator. . /// In case there was a type error in figuring out the types of the captured path, an . /// empty iterator is returned. . #[inline] . pub fn upvar_tys(self) -> impl Iterator> + 'tcx { 4 ( 0.00%) let tupled_tys = match self { 5 ( 0.00%) UpvarSubsts::Closure(substs) => substs.as_closure().tupled_upvars_ty(), . UpvarSubsts::Generator(substs) => substs.as_generator().tupled_upvars_ty(), . }; . 8 ( 0.00%) match tupled_tys.kind() { . TyKind::Error(_) => None, 7 ( 0.00%) TyKind::Tuple(..) => Some(self.tupled_upvars_ty().tuple_fields()), . TyKind::Infer(_) => bug!("upvar_tys called before capture types are inferred"), . ty => bug!("Unexpected representation of upvar types tuple {:?}", ty), . } . .into_iter() . .flatten() . } . . #[inline] . pub fn tupled_upvars_ty(self) -> Ty<'tcx> { 6 ( 0.00%) match self { 8 ( 0.00%) UpvarSubsts::Closure(substs) => substs.as_closure().tupled_upvars_ty(), . UpvarSubsts::Generator(substs) => substs.as_generator().tupled_upvars_ty(), . } . } . } . . /// An inline const is modeled like . /// . /// const InlineConst<'l0...'li, T0...Tj, R>: R; -- line 710 ---------------------------------------- -- line 886 ---------------------------------------- . /// T: Foo . /// . /// This would be represented by a trait-reference where the `DefId` is the . /// `DefId` for the trait `Foo` and the substs define `T` as parameter 0, . /// and `U` as parameter 1. . /// . /// Trait references also appear in object types like `Foo`, but in . /// that case the `Self` parameter is absent from the substitutions. 867 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] 13,814 ( 0.01%) #[derive(HashStable, TypeFoldable)] . pub struct TraitRef<'tcx> { . pub def_id: DefId, 32,785 ( 0.01%) pub substs: SubstsRef<'tcx>, . } . . impl<'tcx> TraitRef<'tcx> { 17 ( 0.00%) pub fn new(def_id: DefId, substs: SubstsRef<'tcx>) -> TraitRef<'tcx> { . TraitRef { def_id, substs } 68 ( 0.00%) } . . /// Returns a `TraitRef` of the form `P0: Foo` where `Pi` . /// are the parameters defined on trait. 36 ( 0.00%) pub fn identity(tcx: TyCtxt<'tcx>, def_id: DefId) -> Binder<'tcx, TraitRef<'tcx>> { 16 ( 0.00%) ty::Binder::dummy(TraitRef { . def_id, 24 ( 0.00%) substs: InternalSubsts::identity_for_item(tcx, def_id), . }) 32 ( 0.00%) } . . #[inline] . pub fn self_ty(&self) -> Ty<'tcx> { . self.substs.type_at(0) . } . 24 ( 0.00%) pub fn from_method( . tcx: TyCtxt<'tcx>, . trait_id: DefId, . substs: SubstsRef<'tcx>, . ) -> ty::TraitRef<'tcx> { . let defs = tcx.generics_of(trait_id); . 3 ( 0.00%) ty::TraitRef { def_id: trait_id, substs: tcx.intern_substs(&substs[..defs.params.len()]) } 33 ( 0.00%) } . } . . pub type PolyTraitRef<'tcx> = Binder<'tcx, TraitRef<'tcx>>; . . impl<'tcx> PolyTraitRef<'tcx> { . pub fn self_ty(&self) -> Binder<'tcx, Ty<'tcx>> { . self.map_bound_ref(|tr| tr.self_ty()) . } . . pub fn def_id(&self) -> DefId { 42 ( 0.00%) self.skip_binder().def_id 14 ( 0.00%) } . 12 ( 0.00%) pub fn to_poly_trait_predicate(&self) -> ty::PolyTraitPredicate<'tcx> { 24 ( 0.00%) self.map_bound(|trait_ref| ty::TraitPredicate { . trait_ref, . constness: ty::BoundConstness::NotConst, . polarity: ty::ImplPolarity::Positive, . }) 12 ( 0.00%) } . } . . /// An existential reference to a trait, where `Self` is erased. . /// For example, the trait object `Trait<'a, 'b, X, Y>` is: . /// . /// exists T. T: Trait<'a, 'b, X, Y> . /// . /// The substitutions don't include the erased `Self`, only trait -- line 956 ---------------------------------------- -- line 999 ---------------------------------------- . /// we convert the principal trait-ref into a normal trait-ref, . /// you must give *some* self type. A common choice is `mk_err()` . /// or some placeholder type. . pub fn with_self_ty(&self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ty::PolyTraitRef<'tcx> { . self.map_bound(|trait_ref| trait_ref.with_self_ty(tcx, self_ty)) . } . } . 623 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] 25 ( 0.00%) #[derive(HashStable)] . pub enum BoundVariableKind { . Ty(BoundTyKind), . Region(BoundRegionKind), . Const, . } . . /// Binder is a binder for higher-ranked lifetimes or types. It is part of the . /// compiler's representation for things like `for<'a> Fn(&'a isize)` . /// (which would be represented by the type `PolyTraitRef == . /// Binder<'tcx, TraitRef>`). Note that when we instantiate, . /// erase, or otherwise "discharge" these bound vars, we change the . /// type from `Binder<'tcx, T>` to just `T` (see . /// e.g., `liberate_late_bound_regions`). . /// . /// `Decodable` and `Encodable` are implemented for `Binder` using the `impl_binder_encode_decode!` macro. 32 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] 13,651 ( 0.01%) pub struct Binder<'tcx, T>(T, &'tcx List); . . impl<'tcx, T> Binder<'tcx, T> . where . T: TypeFoldable<'tcx>, . { . /// Wraps `value` in a binder, asserting that `value` does not . /// contain any bound vars that would be bound by the . /// binder. This is commonly used to 'inject' a value T into a . /// different binding level. 280 ( 0.00%) pub fn dummy(value: T) -> Binder<'tcx, T> { 6,393 ( 0.00%) assert!(!value.has_escaping_bound_vars()); 13,034 ( 0.00%) Binder(value, ty::List::empty()) 280 ( 0.00%) } . . pub fn bind_with_vars(value: T, vars: &'tcx List) -> Binder<'tcx, T> { . if cfg!(debug_assertions) { . let mut validator = ValidateBoundVars::new(vars); . value.visit_with(&mut validator); . } 454 ( 0.00%) Binder(value, vars) . } . } . . impl<'tcx, T> Binder<'tcx, T> { . /// Skips the binder and returns the "bound" value. This is a . /// risky thing to do because it's easy to get confused about . /// De Bruijn indices and the like. It is usually better to . /// discharge the binder using `no_bound_vars` or -- line 1053 ---------------------------------------- -- line 1059 ---------------------------------------- . /// accounting. . /// . /// Some examples where `skip_binder` is reasonable: . /// . /// - extracting the `DefId` from a PolyTraitRef; . /// - comparing the self type of a PolyTraitRef to see if it is equal to . /// a type parameter `X`, since the type `X` does not reference any regions . pub fn skip_binder(self) -> T { 22,797 ( 0.01%) self.0 . } . . pub fn bound_vars(&self) -> &'tcx List { 11 ( 0.00%) self.1 . } . . pub fn as_ref(&self) -> Binder<'tcx, &T> { 21 ( 0.00%) Binder(&self.0, self.1) . } . . pub fn map_bound_ref_unchecked(&self, f: F) -> Binder<'tcx, U> . where . F: FnOnce(&T) -> U, . { . let value = f(&self.0); . Binder(value, self.1) -- line 1083 ---------------------------------------- -- line 1085 ---------------------------------------- . . pub fn map_bound_ref>(&self, f: F) -> Binder<'tcx, U> . where . F: FnOnce(&T) -> U, . { . self.as_ref().map_bound(f) . } . 8 ( 0.00%) pub fn map_bound>(self, f: F) -> Binder<'tcx, U> . where . F: FnOnce(T) -> U, . { 290 ( 0.00%) let value = f(self.0); . if cfg!(debug_assertions) { . let mut validator = ValidateBoundVars::new(self.1); . value.visit_with(&mut validator); . } 54,224 ( 0.02%) Binder(value, self.1) 8 ( 0.00%) } . . pub fn try_map_bound, E>(self, f: F) -> Result, E> . where . F: FnOnce(T) -> Result, . { . let value = f(self.0)?; . if cfg!(debug_assertions) { . let mut validator = ValidateBoundVars::new(self.1); . value.visit_with(&mut validator); . } 76 ( 0.00%) Ok(Binder(value, self.1)) . } . . /// Wraps a `value` in a binder, using the same bound variables as the . /// current `Binder`. This should not be used if the new value *changes* . /// the bound variables. Note: the (old or new) value itself does not . /// necessarily need to *name* all the bound variables. . /// . /// This currently doesn't do anything different than `bind`, because we -- line 1122 ---------------------------------------- -- line 1126 ---------------------------------------- . pub fn rebind(&self, value: U) -> Binder<'tcx, U> . where . U: TypeFoldable<'tcx>, . { . if cfg!(debug_assertions) { . let mut validator = ValidateBoundVars::new(self.bound_vars()); . value.visit_with(&mut validator); . } 118 ( 0.00%) Binder(value, self.1) . } . . /// Unwraps and returns the value within, but only if it contains . /// no bound vars at all. (In other words, if this binder -- . /// and indeed any enclosing binder -- doesn't bind anything at . /// all.) Otherwise, returns `None`. . /// . /// (One could imagine having a method that just unwraps a single -- line 1142 ---------------------------------------- -- line 1143 ---------------------------------------- . /// binder, but permits late-bound vars bound by enclosing . /// binders, but that would require adjusting the debruijn . /// indices, and given the shallow binding structure we often use, . /// would not be that useful.) . pub fn no_bound_vars(self) -> Option . where . T: TypeFoldable<'tcx>, . { 1,026 ( 0.00%) if self.0.has_escaping_bound_vars() { None } else { Some(self.skip_binder()) } 15 ( 0.00%) } . . /// Splits the contents into two things that share the same binder . /// level as the original, returning two distinct binders. . /// . /// `f` should consider bound regions at depth 1 to be free, and . /// anything it produces with bound regions at depth 1 will be . /// bound in the resulting return values. . pub fn split(self, f: F) -> (Binder<'tcx, U>, Binder<'tcx, V>) -- line 1160 ---------------------------------------- -- line 1170 ---------------------------------------- . pub fn transpose(self) -> Option> { . let bound_vars = self.1; . self.0.map(|v| Binder(v, bound_vars)) . } . } . . /// Represents the projection of an associated type. In explicit UFCS . /// form this would be written `>::N`. 24 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] 184 ( 0.00%) #[derive(HashStable, TypeFoldable)] . pub struct ProjectionTy<'tcx> { . /// The parameters of the associated item. 79 ( 0.00%) pub substs: SubstsRef<'tcx>, . . /// The `DefId` of the `TraitItem` for the associated type `N`. . /// . /// Note that this is not the `DefId` of the `TraitRef` containing this . /// associated type, which is in `tcx.associated_item(item_def_id).container`. 111 ( 0.00%) pub item_def_id: DefId, . } . . impl<'tcx> ProjectionTy<'tcx> { 84 ( 0.00%) pub fn trait_def_id(&self, tcx: TyCtxt<'tcx>) -> DefId { 24 ( 0.00%) tcx.associated_item(self.item_def_id).container.id() 96 ( 0.00%) } . . /// Extracts the underlying trait reference and own substs from this projection. . /// For example, if this is a projection of `::Item<'a>`, . /// then this function would return a `T: Iterator` trait reference and `['a]` as the own substs . pub fn trait_ref_and_own_substs( . &self, . tcx: TyCtxt<'tcx>, . ) -> (ty::TraitRef<'tcx>, &'tcx [ty::GenericArg<'tcx>]) { -- line 1202 ---------------------------------------- -- line 1210 ---------------------------------------- . . /// Extracts the underlying trait reference from this projection. . /// For example, if this is a projection of `::Item`, . /// then this function would return a `T: Iterator` trait reference. . /// . /// WARNING: This will drop the substs for generic associated types . /// consider calling [Self::trait_ref_and_own_substs] to get those . /// as well. 99 ( 0.00%) pub fn trait_ref(&self, tcx: TyCtxt<'tcx>) -> ty::TraitRef<'tcx> { 11 ( 0.00%) let def_id = self.trait_def_id(tcx); 11 ( 0.00%) ty::TraitRef { def_id, substs: self.substs.truncate_to(tcx, tcx.generics_of(def_id)) } 121 ( 0.00%) } . 26 ( 0.00%) pub fn self_ty(&self) -> Ty<'tcx> { 78 ( 0.00%) self.substs.type_at(0) 52 ( 0.00%) } . } . . #[derive(Copy, Clone, Debug, TypeFoldable)] . pub struct GenSig<'tcx> { . pub resume_ty: Ty<'tcx>, . pub yield_ty: Ty<'tcx>, . pub return_ty: Ty<'tcx>, . } -- line 1233 ---------------------------------------- -- line 1235 ---------------------------------------- . pub type PolyGenSig<'tcx> = Binder<'tcx, GenSig<'tcx>>; . . /// Signature of a function type, which we have arbitrarily . /// decided to use to refer to the input/output types. . /// . /// - `inputs`: is the list of arguments and their modes. . /// - `output`: is the return type. . /// - `c_variadic`: indicates whether this is a C-variadic function. 1,133 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] 242 ( 0.00%) #[derive(HashStable, TypeFoldable)] . pub struct FnSig<'tcx> { 58 ( 0.00%) pub inputs_and_output: &'tcx List>, 544 ( 0.00%) pub c_variadic: bool, 72 ( 0.00%) pub unsafety: hir::Unsafety, 816 ( 0.00%) pub abi: abi::Abi, . } . . impl<'tcx> FnSig<'tcx> { 229 ( 0.00%) pub fn inputs(&self) -> &'tcx [Ty<'tcx>] { 1,510 ( 0.00%) &self.inputs_and_output[..self.inputs_and_output.len() - 1] 458 ( 0.00%) } . 130 ( 0.00%) pub fn output(&self) -> Ty<'tcx> { 1,323 ( 0.00%) self.inputs_and_output[self.inputs_and_output.len() - 1] 260 ( 0.00%) } . . // Creates a minimal `FnSig` to be used when encountering a `TyKind::Error` in a fallible . // method. . fn fake() -> FnSig<'tcx> { . FnSig { . inputs_and_output: List::empty(), . c_variadic: false, . unsafety: hir::Unsafety::Normal, -- line 1267 ---------------------------------------- -- line 1270 ---------------------------------------- . } . } . . pub type PolyFnSig<'tcx> = Binder<'tcx, FnSig<'tcx>>; . . impl<'tcx> PolyFnSig<'tcx> { . #[inline] . pub fn inputs(&self) -> Binder<'tcx, &'tcx [Ty<'tcx>]> { 42 ( 0.00%) self.map_bound_ref_unchecked(|fn_sig| fn_sig.inputs()) . } . #[inline] . pub fn input(&self, index: usize) -> ty::Binder<'tcx, Ty<'tcx>> { 42 ( 0.00%) self.map_bound_ref(|fn_sig| fn_sig.inputs()[index]) . } . pub fn inputs_and_output(&self) -> ty::Binder<'tcx, &'tcx List>> { . self.map_bound_ref(|fn_sig| fn_sig.inputs_and_output) 6 ( 0.00%) } . #[inline] . pub fn output(&self) -> ty::Binder<'tcx, Ty<'tcx>> { 35 ( 0.00%) self.map_bound_ref(|fn_sig| fn_sig.output()) . } . pub fn c_variadic(&self) -> bool { 12 ( 0.00%) self.skip_binder().c_variadic 6 ( 0.00%) } . pub fn unsafety(&self) -> hir::Unsafety { 12 ( 0.00%) self.skip_binder().unsafety 6 ( 0.00%) } . pub fn abi(&self) -> abi::Abi { 292 ( 0.00%) self.skip_binder().abi 73 ( 0.00%) } . } . . pub type CanonicalPolyFnSig<'tcx> = Canonical<'tcx, Binder<'tcx, FnSig<'tcx>>>; . 4 ( 0.00%) #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] 44 ( 0.00%) #[derive(HashStable)] . pub struct ParamTy { . pub index: u32, . pub name: Symbol, . } . . impl<'tcx> ParamTy { . pub fn new(index: u32, name: Symbol) -> ParamTy { . ParamTy { index, name } -- line 1313 ---------------------------------------- -- line 1321 ---------------------------------------- . pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { . tcx.mk_ty_param(self.index, self.name) . } . } . . #[derive(Copy, Clone, Hash, TyEncodable, TyDecodable, Eq, PartialEq, Ord, PartialOrd)] . #[derive(HashStable)] . pub struct ParamConst { 10 ( 0.00%) pub index: u32, 10 ( 0.00%) pub name: Symbol, . } . . impl ParamConst { . pub fn new(index: u32, name: Symbol) -> ParamConst { . ParamConst { index, name } . } . . pub fn for_def(def: &ty::GenericParamDef) -> ParamConst { -- line 1338 ---------------------------------------- -- line 1440 ---------------------------------------- . /// the inference variable is supposed to satisfy the relation . /// *for every value of the placeholder region*. To ensure that doesn't . /// happen, you can use `leak_check`. This is more clearly explained . /// by the [rustc dev guide]. . /// . /// [1]: https://smallcultfollowing.com/babysteps/blog/2013/10/29/intermingled-parameter-lists/ . /// [2]: https://smallcultfollowing.com/babysteps/blog/2013/11/04/intermingled-parameter-lists/ . /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/hrtb.html 17,955 ( 0.01%) #[derive(Clone, PartialEq, Eq, Hash, Copy, TyEncodable, TyDecodable, PartialOrd, Ord)] 30 ( 0.00%) pub enum RegionKind { . /// Region bound in a type or fn declaration which will be . /// substituted 'early' -- that is, at the same time when type . /// parameters are substituted. . ReEarlyBound(EarlyBoundRegion), . . /// Region bound in a function scope, which will be substituted when the . /// function is called. 410 ( 0.00%) ReLateBound(ty::DebruijnIndex, BoundRegion), . . /// When checking a function body, the types of all arguments and so forth . /// that refer to bound region parameters are modified to refer to free . /// region parameters. . ReFree(FreeRegion), . . /// Static data that has an "infinite" lifetime. Top in the region lattice. . ReStatic, -- line 1465 ---------------------------------------- -- line 1478 ---------------------------------------- . /// regions visible from `U`, but not less than regions not visible . /// from `U`. . ReEmpty(ty::UniverseIndex), . . /// Erased region, used by trait selection, in MIR and during codegen. . ReErased, . } . 198 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, Debug, PartialOrd, Ord)] . pub struct EarlyBoundRegion { . pub def_id: DefId, 133 ( 0.00%) pub index: u32, 35 ( 0.00%) pub name: Symbol, . } . . /// A **`const`** **v**ariable **ID**. . #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] . pub struct ConstVid<'tcx> { 5 ( 0.00%) pub index: u32, . pub phantom: PhantomData<&'tcx ()>, . } . . rustc_index::newtype_index! { . /// A **region** (lifetime) **v**ariable **ID**. . pub struct RegionVid { . DEBUG_FORMAT = custom, . } -- line 1504 ---------------------------------------- -- line 1513 ---------------------------------------- . rustc_index::newtype_index! { . pub struct BoundVar { .. } . } . . #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] . #[derive(HashStable)] . pub struct BoundTy { . pub var: BoundVar, 15 ( 0.00%) pub kind: BoundTyKind, . } . 303 ( 0.00%) #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] . #[derive(HashStable)] . pub enum BoundTyKind { . Anon, . Param(Symbol), . } . . impl From for BoundTy { . fn from(var: BoundVar) -> Self { -- line 1532 ---------------------------------------- -- line 1616 ---------------------------------------- . RegionKind::RePlaceholder(placeholder) => placeholder.name.is_named(), . RegionKind::ReEmpty(_) => false, . RegionKind::ReErased => false, . } . } . . #[inline] . pub fn is_late_bound(&self) -> bool { 1 ( 0.00%) matches!(*self, ty::ReLateBound(..)) . } . . #[inline] . pub fn is_placeholder(&self) -> bool { . matches!(*self, ty::RePlaceholder(..)) . } . . #[inline] . pub fn bound_at_or_above_binder(&self, index: ty::DebruijnIndex) -> bool { 341 ( 0.00%) match *self { . ty::ReLateBound(debruijn, _) => debruijn >= index, . _ => false, . } . } . . pub fn type_flags(&self) -> TypeFlags { . let mut flags = TypeFlags::empty(); . 1,239 ( 0.00%) match *self { . ty::ReVar(..) => { . flags = flags | TypeFlags::HAS_FREE_REGIONS; . flags = flags | TypeFlags::HAS_FREE_LOCAL_REGIONS; . flags = flags | TypeFlags::HAS_RE_INFER; . } . ty::RePlaceholder(..) => { . flags = flags | TypeFlags::HAS_FREE_REGIONS; . flags = flags | TypeFlags::HAS_FREE_LOCAL_REGIONS; -- line 1651 ---------------------------------------- -- line 1669 ---------------------------------------- . ty::ReErased => { . flags = flags | TypeFlags::HAS_RE_ERASED; . } . } . . debug!("type_flags({:?}) = {:?}", self, flags); . . flags 31 ( 0.00%) } . . /// Given an early-bound or free region, returns the `DefId` where it was bound. . /// For example, consider the regions in this snippet of code: . /// . /// ``` . /// impl<'a> Foo { . /// ^^ -- early bound, declared on an impl . /// -- line 1685 ---------------------------------------- -- line 1713 ---------------------------------------- . . #[inline(always)] . pub fn flags(&self) -> TypeFlags { . self.flags . } . . #[inline] . pub fn is_unit(&self) -> bool { 18 ( 0.00%) match self.kind() { . Tuple(ref tys) => tys.is_empty(), . _ => false, . } . } . . #[inline] . pub fn is_never(&self) -> bool { 15,487 ( 0.01%) matches!(self.kind(), Never) . } . . #[inline] . pub fn is_primitive(&self) -> bool { . self.kind().is_primitive() . } . . #[inline] -- line 1737 ---------------------------------------- -- line 1741 ---------------------------------------- . . #[inline] . pub fn is_ref(&self) -> bool { . matches!(self.kind(), Ref(..)) . } . . #[inline] . pub fn is_ty_var(&self) -> bool { 14,214 ( 0.01%) matches!(self.kind(), Infer(TyVar(_))) . } . . #[inline] . pub fn ty_vid(&self) -> Option { 2,912 ( 0.00%) match self.kind() { 12 ( 0.00%) &Infer(TyVar(vid)) => Some(vid), . _ => None, . } . } . . #[inline] . pub fn is_ty_infer(&self) -> bool { 3 ( 0.00%) matches!(self.kind(), Infer(_)) . } . . #[inline] . pub fn is_phantom_data(&self) -> bool { . if let Adt(def, _) = self.kind() { def.is_phantom_data() } else { false } . } . . #[inline] -- line 1770 ---------------------------------------- -- line 1802 ---------------------------------------- . #[inline] . pub fn is_simd(&self) -> bool { . match self.kind() { . Adt(def, _) => def.repr.simd(), . _ => false, . } . } . 4 ( 0.00%) pub fn sequence_element_type(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { 8 ( 0.00%) match self.kind() { . Array(ty, _) | Slice(ty) => ty, . Str => tcx.mk_mach_uint(ty::UintTy::U8), . _ => bug!("`sequence_element_type` called on non-sequence value: {}", self), . } 4 ( 0.00%) } . . pub fn simd_size_and_type(&self, tcx: TyCtxt<'tcx>) -> (u64, Ty<'tcx>) { . match self.kind() { . Adt(def, substs) => { . assert!(def.repr.simd(), "`simd_size_and_type` called on non-SIMD type"); . let variant = def.non_enum_variant(); . let f0_ty = variant.fields[0].ty(tcx, substs); . -- line 1824 ---------------------------------------- -- line 1861 ---------------------------------------- . match self.kind() { . Ref(_, _, mutability) => Some(*mutability), . _ => None, . } . } . . #[inline] . pub fn is_unsafe_ptr(&self) -> bool { 105 ( 0.00%) matches!(self.kind(), RawPtr(_)) . } . . /// Tests if this is any kind of primitive pointer type (reference, raw pointer, fn pointer). . #[inline] . pub fn is_any_ptr(&self) -> bool { . self.is_region_ptr() || self.is_unsafe_ptr() || self.is_fn_ptr() . } . . #[inline] . pub fn is_box(&self) -> bool { 11,202 ( 0.00%) match self.kind() { 11 ( 0.00%) Adt(def, _) => def.is_box(), . _ => false, . } . } . . /// Panics if called on any type other than `Box`. . pub fn boxed_ty(&self) -> Ty<'tcx> { . match self.kind() { . Adt(def, substs) if def.is_box() => substs.type_at(0), -- line 1889 ---------------------------------------- -- line 1891 ---------------------------------------- . } . } . . /// A scalar type is one that denotes an atomic datum, with no sub-components. . /// (A RawPtr is scalar because it represents a non-managed pointer, so its . /// contents are abstract to rustc.) . #[inline] . pub fn is_scalar(&self) -> bool { 86 ( 0.00%) matches!( 202 ( 0.00%) self.kind(), . Bool | Char . | Int(_) . | Float(_) . | Uint(_) . | FnDef(..) . | FnPtr(_) . | RawPtr(_) . | Infer(IntVar(_) | FloatVar(_)) . ) . } . . /// Returns `true` if this type is a floating point type. . #[inline] . pub fn is_floating_point(&self) -> bool { 30 ( 0.00%) matches!(self.kind(), Float(_) | Infer(FloatVar(_))) . } . . #[inline] . pub fn is_trait(&self) -> bool { . matches!(self.kind(), Dynamic(..)) . } . . #[inline] . pub fn is_enum(&self) -> bool { . matches!(self.kind(), Adt(adt_def, _) if adt_def.is_enum()) . } . . #[inline] . pub fn is_union(&self) -> bool { 14 ( 0.00%) matches!(self.kind(), Adt(adt_def, _) if adt_def.is_union()) . } . . #[inline] . pub fn is_closure(&self) -> bool { . matches!(self.kind(), Closure(..)) . } . . #[inline] . pub fn is_generator(&self) -> bool { 12 ( 0.00%) matches!(self.kind(), Generator(..)) . } . . #[inline] . pub fn is_integral(&self) -> bool { 195 ( 0.00%) matches!(self.kind(), Infer(IntVar(_)) | Int(_) | Uint(_)) . } . . #[inline] . pub fn is_fresh_ty(&self) -> bool { . matches!(self.kind(), Infer(FreshTy(_))) . } . . #[inline] . pub fn is_fresh(&self) -> bool { 39 ( 0.00%) matches!(self.kind(), Infer(FreshTy(_) | FreshIntTy(_) | FreshFloatTy(_))) . } . . #[inline] . pub fn is_char(&self) -> bool { . matches!(self.kind(), Char) . } . . #[inline] . pub fn is_numeric(&self) -> bool { . self.is_integral() || self.is_floating_point() . } . . #[inline] . pub fn is_signed(&self) -> bool { 16 ( 0.00%) matches!(self.kind(), Int(_)) . } . . #[inline] . pub fn is_ptr_sized_integral(&self) -> bool { . matches!(self.kind(), Int(ty::IntTy::Isize) | Uint(ty::UintTy::Usize)) . } . . #[inline] -- line 1978 ---------------------------------------- -- line 1979 ---------------------------------------- . pub fn has_concrete_skeleton(&self) -> bool { . !matches!(self.kind(), Param(_) | Infer(_) | Error(_)) . } . . /// Returns the type and mutability of `*ty`. . /// . /// The parameter `explicit` indicates if this is an *explicit* dereference. . /// Some types -- notably unsafe ptrs -- can only be dereferenced explicitly. 2,802 ( 0.00%) pub fn builtin_deref(&self, explicit: bool) -> Option> { 19,599 ( 0.01%) match self.kind() { 10 ( 0.00%) Adt(def, _) if def.is_box() => { . Some(TypeAndMut { ty: self.boxed_ty(), mutbl: hir::Mutability::Not }) . } 262 ( 0.00%) Ref(_, ty, mutbl) => Some(TypeAndMut { ty, mutbl: *mutbl }), 4 ( 0.00%) RawPtr(mt) if explicit => Some(*mt), . _ => None, . } 5,604 ( 0.00%) } . . /// Returns the type of `ty[i]`. . pub fn builtin_index(&self) -> Option> { . match self.kind() { . Array(ty, _) | Slice(ty) => Some(ty), . _ => None, . } . } . 632 ( 0.00%) pub fn fn_sig(&self, tcx: TyCtxt<'tcx>) -> PolyFnSig<'tcx> { 316 ( 0.00%) match self.kind() { 237 ( 0.00%) FnDef(def_id, substs) => tcx.fn_sig(*def_id).subst(tcx, substs), . FnPtr(f) => *f, . Error(_) => { . // ignore errors (#54954) . ty::Binder::dummy(FnSig::fake()) . } . Closure(..) => bug!( . "to get the signature of a closure, use `substs.as_closure().sig()` not `fn_sig()`", . ), . _ => bug!("Ty::fn_sig() called on non-fn type: {:?}", self), . } 711 ( 0.00%) } . . #[inline] . pub fn is_fn(&self) -> bool { 84 ( 0.00%) matches!(self.kind(), FnDef(..) | FnPtr(_)) . } . . #[inline] . pub fn is_fn_ptr(&self) -> bool { . matches!(self.kind(), FnPtr(_)) . } . . #[inline] . pub fn is_impl_trait(&self) -> bool { . matches!(self.kind(), Opaque(..)) . } . . #[inline] . pub fn ty_adt_def(&self) -> Option<&'tcx AdtDef> { 4,128 ( 0.00%) match self.kind() { . Adt(adt, _) => Some(adt), . _ => None, . } . } . . /// Iterates over tuple fields. . /// Panics when called on anything but a tuple. 15 ( 0.00%) pub fn tuple_fields(&self) -> impl DoubleEndedIterator> { 2,772 ( 0.00%) match self.kind() { 1,415 ( 0.00%) Tuple(substs) => substs.iter().map(|field| field.expect_ty()), . _ => bug!("tuple_fields called on non-tuple"), . } 30 ( 0.00%) } . . /// Get the `i`-th element of a tuple. . /// Panics when called on anything but a tuple. 5 ( 0.00%) pub fn tuple_element_ty(&self, i: usize) -> Option> { 10 ( 0.00%) match self.kind() { 10 ( 0.00%) Tuple(substs) => substs.iter().nth(i).map(|field| field.expect_ty()), . _ => bug!("tuple_fields called on non-tuple"), . } 10 ( 0.00%) } . . /// If the type contains variants, returns the valid range of variant indices. . // . // FIXME: This requires the optimized MIR in the case of generators. . #[inline] . pub fn variant_range(&self, tcx: TyCtxt<'tcx>) -> Option> { . match self.kind() { . TyKind::Adt(adt, _) => Some(adt.variant_range()), -- line 2068 ---------------------------------------- -- line 2073 ---------------------------------------- . } . } . . /// If the type contains variants, returns the variant for `variant_index`. . /// Panics if `variant_index` is out of range. . // . // FIXME: This requires the optimized MIR in the case of generators. . #[inline] 110 ( 0.00%) pub fn discriminant_for_variant( . &self, . tcx: TyCtxt<'tcx>, . variant_index: VariantIdx, . ) -> Option> { 67 ( 0.00%) match self.kind() { 28 ( 0.00%) TyKind::Adt(adt, _) if adt.variants.is_empty() => { . // This can actually happen during CTFE, see . // https://github.com/rust-lang/rust/issues/89765. . None . } 14 ( 0.00%) TyKind::Adt(adt, _) if adt.is_enum() => { . Some(adt.discriminant_for_variant(tcx, variant_index)) . } . TyKind::Generator(def_id, substs, _) => { . Some(substs.as_generator().discriminant_for_variant(*def_id, tcx, variant_index)) . } . _ => None, . } 88 ( 0.00%) } . . /// Returns the type of the discriminant of this type. 70 ( 0.00%) pub fn discriminant_ty(&'tcx self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { 35 ( 0.00%) match self.kind() { 56 ( 0.00%) ty::Adt(adt, _) if adt.is_enum() => adt.repr.discr_type().to_ty(tcx), . ty::Generator(_, substs, _) => substs.as_generator().discr_ty(tcx), . . ty::Param(_) | ty::Projection(_) | ty::Opaque(..) | ty::Infer(ty::TyVar(_)) => { . let assoc_items = tcx.associated_item_def_ids( . tcx.require_lang_item(hir::LangItem::DiscriminantKind, None), . ); . tcx.mk_projection(assoc_items[0], tcx.intern_substs(&[self.into()])) . } -- line 2113 ---------------------------------------- -- line 2135 ---------------------------------------- . | ty::Infer(IntVar(_) | FloatVar(_)) => tcx.types.u8, . . ty::Bound(..) . | ty::Placeholder(_) . | ty::Infer(FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => { . bug!("`discriminant_ty` applied to unexpected type: {:?}", self) . } . } 56 ( 0.00%) } . . /// Returns the type of metadata for (potentially fat) pointers to this type. 18 ( 0.00%) pub fn ptr_metadata_ty( . &'tcx self, . tcx: TyCtxt<'tcx>, . normalize: impl FnMut(Ty<'tcx>) -> Ty<'tcx>, . ) -> Ty<'tcx> { 18 ( 0.00%) let tail = tcx.struct_tail_with_normalize(self, normalize); 10 ( 0.00%) match tail.kind() { . // Sized types . ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) . | ty::Uint(_) . | ty::Int(_) . | ty::Bool . | ty::Float(_) . | ty::FnDef(..) . | ty::FnPtr(_) -- line 2160 ---------------------------------------- -- line 2170 ---------------------------------------- . | ty::Foreign(..) . // If returned by `struct_tail_without_normalization` this is a unit struct . // without any fields, or not a struct, and therefore is Sized. . | ty::Adt(..) . // If returned by `struct_tail_without_normalization` this is the empty tuple, . // a.k.a. unit type, which is Sized . | ty::Tuple(..) => tcx.types.unit, . 4 ( 0.00%) ty::Str | ty::Slice(_) => tcx.types.usize, . ty::Dynamic(..) => { . let dyn_metadata = tcx.lang_items().dyn_metadata().unwrap(); . tcx.type_of(dyn_metadata).subst(tcx, &[tail.into()]) . }, . . ty::Projection(_) . | ty::Param(_) . | ty::Opaque(..) . | ty::Infer(ty::TyVar(_)) . | ty::Bound(..) . | ty::Placeholder(..) . | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => { . bug!("`ptr_metadata_ty` applied to unexpected type: {:?}", tail) . } . } 16 ( 0.00%) } . . /// When we create a closure, we record its kind (i.e., what trait . /// it implements) into its `ClosureSubsts` using a type . /// parameter. This is kind of a phantom type, except that the . /// most convenient thing for us to are the integral types. This . /// function converts such a special type into the closure . /// kind. To go the other way, use . /// `tcx.closure_kind_ty(closure_kind)`. . /// . /// Note that during type checking, we use an inference variable . /// to represent the closure kind, because it has not yet been . /// inferred. Once upvar inference (in `rustc_typeck/src/check/upvar.rs`) . /// is complete, that type variable will be unified. 36 ( 0.00%) pub fn to_opt_closure_kind(&self) -> Option { 72 ( 0.00%) match self.kind() { 72 ( 0.00%) Int(int_ty) => match int_ty { . ty::IntTy::I8 => Some(ty::ClosureKind::Fn), . ty::IntTy::I16 => Some(ty::ClosureKind::FnMut), . ty::IntTy::I32 => Some(ty::ClosureKind::FnOnce), . _ => bug!("cannot convert type `{:?}` to a closure kind", self), . }, . . // "Bound" types appear in canonical queries when the . // closure type is not yet known . Bound(..) | Infer(_) => None, . . Error(_) => Some(ty::ClosureKind::Fn), . . _ => bug!("cannot convert type `{:?}` to a closure kind", self), . } 36 ( 0.00%) } . . /// Fast path helper for testing if a type is `Sized`. . /// . /// Returning true means the type is known to be sized. Returning . /// `false` means nothing -- could be sized, might not be. . /// . /// Note that we could never rely on the fact that a type such as `[_]` is . /// trivially `!Sized` because we could be in a type environment with a . /// bound such as `[_]: Copy`. A function with such a bound obviously never . /// can be called, but that doesn't mean it shouldn't typecheck. This is why . /// this method doesn't return `Option`. 112,662 ( 0.04%) pub fn is_trivially_sized(&self, tcx: TyCtxt<'tcx>) -> bool { 75,108 ( 0.03%) match self.kind() { . ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) . | ty::Uint(_) . | ty::Int(_) . | ty::Bool . | ty::Float(_) . | ty::FnDef(..) . | ty::FnPtr(_) . | ty::RawPtr(..) -- line 2246 ---------------------------------------- -- line 2250 ---------------------------------------- . | ty::GeneratorWitness(..) . | ty::Array(..) . | ty::Closure(..) . | ty::Never . | ty::Error(_) => true, . . ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => false, . 20,520 ( 0.01%) ty::Tuple(tys) => tys.iter().all(|ty| ty.expect_ty().is_trivially_sized(tcx)), . 36 ( 0.00%) ty::Adt(def, _substs) => def.sized_constraint(tcx).is_empty(), . . ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => false, . . ty::Infer(ty::TyVar(_)) => false, . . ty::Bound(..) . | ty::Placeholder(..) . | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => { . bug!("`is_trivially_sized` applied to unexpected type: {:?}", self) . } . } 112,662 ( 0.04%) } . } . . /// Extra information about why we ended up with a particular variance. . /// This is only used to add more information to error messages, and . /// has no effect on soundness. While choosing the 'wrong' `VarianceDiagInfo` . /// may lead to confusing notes in error messages, it will never cause . /// a miscompilation or unsoundness. . /// -- line 2280 ---------------------------------------- -- line 2295 ---------------------------------------- . /// (e.g. `0` for `*mut T`, `1` for `MyStruct<'CovariantParam, 'InvariantParam>`) . param_index: u32, . }, . } . . impl<'tcx> VarianceDiagInfo<'tcx> { . /// Mirrors `Variance::xform` - used to 'combine' the existing . /// and new `VarianceDiagInfo`s when our variance changes. 180 ( 0.00%) pub fn xform(self, other: VarianceDiagInfo<'tcx>) -> VarianceDiagInfo<'tcx> { . // For now, just use the first `VarianceDiagInfo::Invariant` that we see 270 ( 0.00%) match self { . VarianceDiagInfo::None => other, . VarianceDiagInfo::Invariant { .. } => self, . } 90 ( 0.00%) } . } 269,640 ( 0.10%) -------------------------------------------------------------------------------- -- 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> { 72 ( 0.00%) pub fn resolve_type_vars_in_body( . &self, . body: &'tcx hir::Body<'tcx>, . ) -> &'tcx ty::TypeckResults<'tcx> { 80 ( 0.00%) let item_id = self.tcx.hir().body_owner(body.id()); 48 ( 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 = 48 ( 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); 32 ( 0.00%) for param in body.params { 54 ( 0.00%) wbcx.visit_node_id(param.pat.span, param.hir_id); . } . // Type only exists for constants and statics, not functions. 88 ( 0.00%) match self.tcx.hir().body_owner_kind(item_id) { . hir::BodyOwnerKind::Const | hir::BodyOwnerKind::Static(_) => { 15 ( 0.00%) wbcx.visit_node_id(body.value.span, item_id); . } . hir::BodyOwnerKind::Closure | hir::BodyOwnerKind::Fn => (), . } . wbcx.visit_body(body); 8 ( 0.00%) wbcx.visit_min_capture_map(); 8 ( 0.00%) wbcx.eval_closure_size(); 8 ( 0.00%) wbcx.visit_fake_reads_map(); 8 ( 0.00%) wbcx.visit_closures(); 8 ( 0.00%) wbcx.visit_liberated_fn_sigs(); 8 ( 0.00%) wbcx.visit_fru_field_types(); 24 ( 0.00%) wbcx.visit_opaque_types(body.value.span); 8 ( 0.00%) wbcx.visit_coercion_casts(); 8 ( 0.00%) wbcx.visit_user_provided_tys(); 8 ( 0.00%) wbcx.visit_user_provided_sigs(); 8 ( 0.00%) wbcx.visit_generator_interior_types(); . . let used_trait_imports = 16 ( 0.00%) mem::take(&mut self.typeck_results.borrow_mut().used_trait_imports); . debug!("used_trait_imports({:?}) = {:?}", item_def_id, used_trait_imports); 16 ( 0.00%) wbcx.typeck_results.used_trait_imports = used_trait_imports; . 40 ( 0.00%) wbcx.typeck_results.treat_byte_string_as_slice = 8 ( 0.00%) mem::take(&mut self.typeck_results.borrow_mut().treat_byte_string_as_slice); . 24 ( 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); . 16 ( 0.00%) self.tcx.arena.alloc(wbcx.typeck_results) 72 ( 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> { 16 ( 0.00%) let owner = body.id().hir_id.owner; . 72 ( 0.00%) WritebackCx { . fcx, 32 ( 0.00%) typeck_results: ty::TypeckResults::new(owner), . body, . rustc_dump_user_substs, . } . } . . fn tcx(&self) -> TyCtxt<'tcx> { 8 ( 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); 12,684 ( 0.00%) assert!(!ty.needs_infer() && !ty.has_placeholders() && !ty.has_free_regions()); 16,912 ( 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<'_>) { 29,330 ( 0.01%) match e.kind { . hir::ExprKind::Unary(hir::UnOp::Neg | hir::UnOp::Not, inner) => { . 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() { . let mut typeck_results = self.fcx.typeck_results.borrow_mut(); . typeck_results.type_dependent_defs_mut().remove(e.hir_id); . typeck_results.node_substs_mut().remove(e.hir_id); . } . } . hir::ExprKind::Binary(ref op, lhs, rhs) | hir::ExprKind::AssignOp(ref op, lhs, rhs) => { 140 ( 0.00%) let lhs_ty = self.fcx.node_ty(lhs.hir_id); . let lhs_ty = self.fcx.resolve_vars_if_possible(lhs_ty); . 112 ( 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() { 28 ( 0.00%) let mut typeck_results = self.fcx.typeck_results.borrow_mut(); 140 ( 0.00%) typeck_results.type_dependent_defs_mut().remove(e.hir_id); 28 ( 0.00%) typeck_results.node_substs_mut().remove(e.hir_id); . 56 ( 0.00%) match e.kind { . hir::ExprKind::Binary(..) => { 112 ( 0.00%) if !op.node.is_by_value() { 15 ( 0.00%) let mut adjustments = typeck_results.adjustments_mut(); 90 ( 0.00%) if let Some(a) = adjustments.get_mut(lhs.hir_id) { . a.pop(); . } 60 ( 0.00%) if let Some(a) = adjustments.get_mut(rhs.hir_id) { . a.pop(); . } . } . } . hir::ExprKind::AssignOp(..) . if let Some(a) = typeck_results.adjustments_mut().get_mut(lhs.hir_id) => . { . a.pop(); -- line 180 ---------------------------------------- -- 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<'_>) { 8,424 ( 0.00%) if let hir::ExprKind::Index(ref base, ref index) = e.kind { . let mut typeck_results = self.fcx.typeck_results.borrow_mut(); . . // All valid indexing looks like this; might encounter non-valid indexes at this point. . let base_ty = typeck_results . .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 -- line 203 ---------------------------------------- -- 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> { 37,782 ( 0.01%) fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) { 4,198 ( 0.00%) self.fix_scalar_builtin_expr(e); . self.fix_index_builtin_expr(e); . 20,990 ( 0.01%) self.visit_node_id(e.span, e.hir_id); . 16,792 ( 0.01%) match e.kind { 2 ( 0.00%) hir::ExprKind::Closure(_, _, body, _, _) => { 6 ( 0.00%) let body = self.fcx.tcx.hir().body(body); 2 ( 0.00%) for param in body.params { 5 ( 0.00%) self.visit_node_id(e.span, param.hir_id); . } . . self.visit_body(body); . } . hir::ExprKind::Struct(_, fields, _) => { . for field in fields { . self.visit_field_id(field.hir_id); . } -- line 274 ---------------------------------------- -- line 280 ---------------------------------------- . self.visit_node_id(e.span, anon_const.hir_id); . . let body = self.tcx().hir().body(anon_const.body); . self.visit_body(body); . } . _ => {} . } . 12,594 ( 0.00%) intravisit::walk_expr(self, e); 33,584 ( 0.01%) } . 81 ( 0.00%) fn visit_block(&mut self, b: &'tcx hir::Block<'tcx>) { 36 ( 0.00%) self.visit_node_id(b.span, b.hir_id); . intravisit::walk_block(self, b); . } . 90 ( 0.00%) fn visit_pat(&mut self, p: &'tcx hir::Pat<'tcx>) { 34 ( 0.00%) match p.kind { . hir::PatKind::Binding(..) => { 16 ( 0.00%) let typeck_results = self.fcx.typeck_results.borrow(); 24 ( 0.00%) if let Some(bm) = 64 ( 0.00%) typeck_results.extract_binding_mode(self.tcx().sess, p.hir_id, p.span) . { 24 ( 0.00%) self.typeck_results.pat_binding_modes_mut().insert(p.hir_id, bm); . } . } . hir::PatKind::Struct(_, fields, _) => { . for field in fields { . self.visit_field_id(field.hir_id); . } . } . _ => {} . }; . 40 ( 0.00%) self.visit_pat_adjustments(p.span, p.hir_id); . 50 ( 0.00%) self.visit_node_id(p.span, p.hir_id); 30 ( 0.00%) intravisit::walk_pat(self, p); 80 ( 0.00%) } . . fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) { . intravisit::walk_local(self, l); . 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); . } . 7 ( 0.00%) fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty<'tcx>) { 1 ( 0.00%) intravisit::walk_ty(self, hir_ty); 4 ( 0.00%) let ty = self.fcx.node_ty(hir_ty.hir_id); 1 ( 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> { 56 ( 0.00%) fn eval_closure_size(&mut self) { . let mut res: FxHashMap> = Default::default(); 24 ( 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); . } . 80 ( 0.00%) self.typeck_results.closure_size_eval = res; 64 ( 0.00%) } 56 ( 0.00%) fn visit_min_capture_map(&mut self) { . let mut min_captures_wb = ty::MinCaptureInformationMap::with_capacity_and_hasher( 16 ( 0.00%) self.fcx.typeck_results.borrow().closure_min_captures.len(), . Default::default(), . ); . for (closure_def_id, root_min_captures) in 16 ( 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| { 3 ( 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(); 2 ( 0.00%) root_var_map_wb.insert(*var_hir_id, min_list_wb); . } 2 ( 0.00%) min_captures_wb.insert(*closure_def_id, root_var_map_wb); . } . 72 ( 0.00%) self.typeck_results.closure_min_captures = min_captures_wb; 64 ( 0.00%) } . 56 ( 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 16 ( 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)); . } 2 ( 0.00%) resolved_closure_fake_reads.insert(*closure_def_id, resolved_fake_reads); . } 72 ( 0.00%) self.typeck_results.closure_fake_reads = resolved_closure_fake_reads; 64 ( 0.00%) } . 56 ( 0.00%) fn visit_closures(&mut self) { 16 ( 0.00%) let fcx_typeck_results = self.fcx.typeck_results.borrow(); 24 ( 0.00%) assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner); . let common_hir_owner = fcx_typeck_results.hir_owner; . 8 ( 0.00%) for (id, origin) in fcx_typeck_results.closure_kind_origins().iter() { . let hir_id = hir::HirId { owner: common_hir_owner, local_id: *id }; . let place_span = origin.0; . let place = self.resolve(origin.1.clone(), &place_span); . self.typeck_results.closure_kind_origins_mut().insert(hir_id, (place_span, place)); . } 64 ( 0.00%) } . 56 ( 0.00%) fn visit_coercion_casts(&mut self) { 16 ( 0.00%) let fcx_typeck_results = self.fcx.typeck_results.borrow(); 8 ( 0.00%) let fcx_coercion_casts = fcx_typeck_results.coercion_casts(); 16 ( 0.00%) assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner); . . for local_id in fcx_coercion_casts { . self.typeck_results.set_coercion_cast(*local_id); . } 64 ( 0.00%) } . 64 ( 0.00%) fn visit_user_provided_tys(&mut self) { 16 ( 0.00%) let fcx_typeck_results = self.fcx.typeck_results.borrow(); 32 ( 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(); 8 ( 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 . ); -- line 447 ---------------------------------------- -- line 459 ---------------------------------------- . .tcx() . .sess . .struct_span_err(span, &format!("user substs: {:?}", user_substs)); . err.buffer(&mut errors_buffer); . } . } . } . 8 ( 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); . } . } 64 ( 0.00%) } . 56 ( 0.00%) fn visit_user_provided_sigs(&mut self) { 16 ( 0.00%) let fcx_typeck_results = self.fcx.typeck_results.borrow(); 16 ( 0.00%) assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner); . 2 ( 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 . ); . }; . 6 ( 0.00%) self.typeck_results.user_provided_sigs.insert(def_id, *c_sig); . } 64 ( 0.00%) } . 40 ( 0.00%) fn visit_generator_interior_types(&mut self) { 16 ( 0.00%) let fcx_typeck_results = self.fcx.typeck_results.borrow(); 16 ( 0.00%) assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner); 48 ( 0.00%) self.typeck_results.generator_interior_types = 16 ( 0.00%) fcx_typeck_results.generator_interior_types.clone(); 48 ( 0.00%) } . 128 ( 0.00%) #[instrument(skip(self, span), level = "debug")] . fn visit_opaque_types(&mut self, span: Span) { 8 ( 0.00%) let opaque_types = self.fcx.infcx.inner.borrow().opaque_types.clone(); 32 ( 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 559 ---------------------------------------- . . fn visit_field_id(&mut self, hir_id: hir::HirId) { . if let Some(index) = self.fcx.typeck_results.borrow_mut().field_indices_mut().remove(hir_id) . { . self.typeck_results.field_indices_mut().insert(hir_id, index); . } . } . 76,086 ( 0.03%) #[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. 16,908 ( 0.01%) if let Some(def) = 12,681 ( 0.00%) self.fcx.typeck_results.borrow_mut().type_dependent_defs_mut().remove(hir_id) . { 4 ( 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` 16,908 ( 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 25,362 ( 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()); 4 ( 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) { 12,681 ( 0.00%) let adjustment = self.fcx.typeck_results.borrow_mut().adjustments_mut().remove(hir_id); 21,135 ( 0.01%) match adjustment { . None => { . debug!("no adjustments for node"); . } . . Some(adjustment) => { 72 ( 0.00%) let resolved_adjustment = self.resolve(adjustment, &span); . debug!(?resolved_adjustment); 216 ( 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) { 30 ( 0.00%) let adjustment = self.fcx.typeck_results.borrow_mut().pat_adjustments_mut().remove(hir_id); 20 ( 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); . } . } . } . 64 ( 0.00%) fn visit_liberated_fn_sigs(&mut self) { 16 ( 0.00%) let fcx_typeck_results = self.fcx.typeck_results.borrow(); 32 ( 0.00%) assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner); . let common_hir_owner = fcx_typeck_results.hir_owner; . 32 ( 0.00%) for (&local_id, &fn_sig) in fcx_typeck_results.liberated_fn_sigs().iter() { 18 ( 0.00%) let hir_id = hir::HirId { owner: common_hir_owner, local_id }; . let fn_sig = self.resolve(fn_sig, &hir_id); 18 ( 0.00%) self.typeck_results.liberated_fn_sigs_mut().insert(hir_id, fn_sig); . } 64 ( 0.00%) } . 64 ( 0.00%) fn visit_fru_field_types(&mut self) { 16 ( 0.00%) let fcx_typeck_results = self.fcx.typeck_results.borrow(); 32 ( 0.00%) assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner); . let common_hir_owner = fcx_typeck_results.hir_owner; . 8 ( 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); . } 64 ( 0.00%) } . . fn resolve(&mut self, x: T, span: &dyn Locatable) -> T . where . T: TypeFoldable<'tcx>, . { 8,510 ( 0.00%) let mut resolver = Resolver::new(self.fcx, span, self.body); 23 ( 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. 8,583 ( 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> { 42,683 ( 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> { 8 ( 0.00%) self.tcx . } . fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> { 4,267 ( 0.00%) if ty.has_type_flags(ty::TypeFlags::HAS_FREE_REGIONS) { 16 ( 0.00%) ty.super_fold_with(self) . } else { . ty . } . } . fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> { 32 ( 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> { 4 ( 0.00%) self.tcx . } . 38,331 ( 0.01%) fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { 12,777 ( 0.00%) 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. 8,518 ( 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() . } . } 34,072 ( 0.01%) } . . fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> { . debug_assert!(!r.is_late_bound(), "Should not be resolving bound region."); 29 ( 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 ---------------------------------------- 55,651 ( 0.02%) -------------------------------------------------------------------------------- -- 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 { 5,464 ( 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 { 12 ( 0.00%) pub fn new() -> Self { . let linewidth = 78; 427 ( 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, . } 15 ( 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) { 18 ( 0.00%) if !self.scan_stack.is_empty() { 6 ( 0.00%) self.check_stack(0); 6 ( 0.00%) self.advance_left(); . } . } . . fn scan_begin(&mut self, token: BeginToken) { 5,477 ( 0.00%) if self.scan_stack.is_empty() { 6 ( 0.00%) self.left_total = 1; . self.right_total = 1; . self.buf.clear(); . } 21,908 ( 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) { 5,477 ( 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) { 2,732 ( 0.00%) if self.scan_stack.is_empty() { . self.left_total = 1; . self.right_total = 1; . self.buf.clear(); . } else { 5,464 ( 0.00%) self.check_stack(0); . } 10,928 ( 0.00%) let right = self.buf.push(BufEntry { token: Token::Break(token), size: -self.right_total }); . self.scan_stack.push_back(right); 8,196 ( 0.00%) self.right_total += token.blank_space; . } . 73,998 ( 0.03%) fn scan_string(&mut self, string: Cow<'static, str>) { 8,222 ( 0.00%) if self.scan_stack.is_empty() { . self.print_string(&string); . } else { . let len = string.len() as isize; 8,207 ( 0.00%) self.buf.push(BufEntry { token: Token::String(string), size: len }); 24,621 ( 0.01%) self.right_total += len; . self.check_stream(); . } 65,656 ( 0.02%) } . . fn check_stream(&mut self) { 39,058 ( 0.01%) while self.right_total - self.left_total > self.space { 3,738 ( 0.00%) if *self.scan_stack.front().unwrap() == self.buf.index_of_first() { . self.scan_stack.pop_front().unwrap(); 628 ( 0.00%) self.buf.first_mut().unwrap().size = SIZE_INFINITY; . } 2,492 ( 0.00%) self.advance_left(); 1,246 ( 0.00%) if self.buf.is_empty() { . break; . } . } . } . 43,126 ( 0.02%) fn advance_left(&mut self) { 46,278 ( 0.02%) while self.buf.first().unwrap().size >= 0 { 65,679 ( 0.02%) let left = self.buf.pop_first().unwrap(); . . match &left.token { . Token::String(string) => { 24,621 ( 0.01%) self.left_total += string.len() as isize; . self.print_string(string); . } . Token::Break(token) => { 8,196 ( 0.00%) self.left_total += token.blank_space; . self.print_break(*token, left.size); . } 24 ( 0.00%) Token::Begin(token) => self.print_begin(*token, left.size), . Token::End => self.print_end(), . } . 175,144 ( 0.06%) self.last_printed = Some(left.token); . 21,893 ( 0.01%) if self.buf.is_empty() { . break; . } . } 9,992 ( 0.00%) } . 24,615 ( 0.01%) fn check_stack(&mut self, mut depth: usize) { 29,476 ( 0.01%) while let Some(&index) = self.scan_stack.back() { . let mut entry = &mut self.buf[index]; 58,459 ( 0.02%) match entry.token { . Token::Begin(_) => { 13,676 ( 0.01%) if depth == 0 { . break; . } . self.scan_stack.pop_back().unwrap(); 16,407 ( 0.01%) entry.size += self.right_total; 5,469 ( 0.00%) depth -= 1; . } . Token::End => { . // paper says + not =, but that makes no sense. . self.scan_stack.pop_back().unwrap(); 5,477 ( 0.00%) entry.size = 1; 10,954 ( 0.00%) depth += 1; . } . _ => { . self.scan_stack.pop_back().unwrap(); 6,336 ( 0.00%) entry.size += self.right_total; 4,968 ( 0.00%) if depth == 0 { . break; . } . } . } . } 21,880 ( 0.01%) } . . fn get_top(&self) -> PrintFrame { 8,196 ( 0.00%) *self . .print_stack . .last() . .unwrap_or(&PrintFrame::Broken { offset: 0, breaks: Breaks::Inconsistent }) . } . . fn print_begin(&mut self, token: BeginToken, size: isize) { 16,431 ( 0.01%) if size > self.space { 40 ( 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 = 10,920 ( 0.00%) 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'); 1,860 ( 0.00%) self.pending_indentation = offset + token.offset; 2,480 ( 0.00%) self.space = self.margin - (offset + token.offset); . } else { 6,336 ( 0.00%) self.pending_indentation += token.blank_space; 8,448 ( 0.00%) 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. 8,222 ( 0.00%) self.out.reserve(self.pending_indentation as usize); 3 ( 0.00%) self.out.extend(iter::repeat(' ').take(self.pending_indentation as usize)); 8,222 ( 0.00%) self.pending_indentation = 0; . . self.out.push_str(string); 41,095 ( 0.02%) self.space -= string.len() as isize; . } . . // Convenience functions to talk to the printer. . . /// "raw box" 10,952 ( 0.00%) pub fn rbox(&mut self, indent: usize, breaks: Breaks) { . self.scan_begin(BeginToken { offset: indent as isize, breaks }) 8,214 ( 0.00%) } . . /// Inconsistent breaking box 24,648 ( 0.01%) pub fn ibox(&mut self, indent: usize) { . self.rbox(indent, Breaks::Inconsistent) 20,540 ( 0.01%) } . . /// Consistent breaking box . pub fn cbox(&mut self, indent: usize) { . self.rbox(indent, Breaks::Consistent) . } . 21,856 ( 0.01%) pub fn break_offset(&mut self, n: usize, off: isize) { . self.scan_break(BreakToken { offset: off, blank_space: n as isize }) 16,392 ( 0.01%) } . 21,908 ( 0.01%) pub fn end(&mut self) { . self.scan_end() 21,908 ( 0.01%) } . 90 ( 0.00%) pub fn eof(mut self) -> String { . self.scan_eof(); 72 ( 0.00%) self.out 90 ( 0.00%) } . . pub fn word>>(&mut self, wrd: S) { . let string = wrd.into(); 54,836 ( 0.02%) self.scan_string(string) . } . . fn spaces(&mut self, n: usize) { 10,928 ( 0.00%) 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 { 5,464 ( 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 ---------------------------------------- 142,887 ( 0.05%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_metadata/src/rmeta/decoder.rs -------------------------------------------------------------------------------- Ir -- line 176 ---------------------------------------- . } . fn sess(self) -> Option<&'tcx Session> { . None . } . fn tcx(self) -> Option> { . None . } . 402 ( 0.00%) fn decoder(self, pos: usize) -> DecodeContext<'a, 'tcx> { 134 ( 0.00%) let tcx = self.tcx(); 44,833 ( 0.02%) DecodeContext { 4,488 ( 0.00%) opaque: opaque::Decoder::new(self.blob(), pos), 134 ( 0.00%) cdata: self.cdata(), . blob: self.blob(), 844 ( 0.00%) sess: self.sess().or(tcx.map(|tcx| tcx.sess)), . tcx, . last_source_file_index: 0, . lazy_state: LazyState::NoNode, . alloc_decoding_session: self . .cdata() 3,859 ( 0.00%) .map(|cdata| cdata.cdata.alloc_decoding_state.new_decoding_session()), . } 402 ( 0.00%) } . } . . impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a MetadataBlob { . #[inline] . fn blob(self) -> &'a MetadataBlob { . self . } . } -- line 206 ---------------------------------------- -- line 255 ---------------------------------------- . } . #[inline] . fn tcx(self) -> Option> { . Some(self.1) . } . } . . impl<'a, 'tcx, T: Decodable>> Lazy { 3,337 ( 0.00%) fn decode>(self, metadata: M) -> T { 1,795 ( 0.00%) let mut dcx = metadata.decoder(self.position.get()); 13,061 ( 0.00%) dcx.lazy_state = LazyState::NodeStart(self.position); 5,538 ( 0.00%) T::decode(&mut dcx) 4,259 ( 0.00%) } . } . . impl<'a: 'x, 'tcx: 'x, 'x, T: Decodable>> Lazy<[T]> { . fn decode>( . self, . metadata: M, . ) -> impl ExactSizeIterator + Captures<'a> + Captures<'tcx> + 'x { 28 ( 0.00%) let mut dcx = metadata.decoder(self.position.get()); 8 ( 0.00%) dcx.lazy_state = LazyState::NodeStart(self.position); 6,072 ( 0.00%) (0..self.meta).map(move |_| T::decode(&mut dcx)) . } . } . . impl<'a, 'tcx> DecodeContext<'a, 'tcx> { . #[inline] . fn tcx(&self) -> TyCtxt<'tcx> { . debug_assert!(self.tcx.is_some(), "missing TyCtxt in DecodeContext"); . self.tcx.unwrap() -- line 285 ---------------------------------------- -- line 292 ---------------------------------------- . . #[inline] . pub fn cdata(&self) -> CrateMetadataRef<'a> { . debug_assert!(self.cdata.is_some(), "missing CrateMetadata in DecodeContext"); . self.cdata.unwrap() . } . . fn map_encoded_cnum_to_current(&self, cnum: CrateNum) -> CrateNum { 12,430 ( 0.00%) if cnum == LOCAL_CRATE { self.cdata().cnum } else { self.cdata().cnum_map[cnum] } . } . 6,437 ( 0.00%) fn read_lazy_with_meta(&mut self, meta: T::Meta) -> Lazy { . let distance = self.read_usize(); 5,755 ( 0.00%) let position = match self.lazy_state { . LazyState::NoNode => bug!("read_lazy_with_meta: outside of a metadata node"), 1,015 ( 0.00%) LazyState::NodeStart(start) => { . let start = start.get(); 2,030 ( 0.00%) assert!(distance <= start); . start - distance . } 1,626 ( 0.00%) LazyState::Previous(last_pos) => last_pos.get() + distance, . }; 3,114 ( 0.00%) self.lazy_state = LazyState::Previous(NonZeroUsize::new(position).unwrap()); . Lazy::from_position_and_meta(NonZeroUsize::new(position).unwrap(), meta) 6,437 ( 0.00%) } . . #[inline] . pub fn read_raw_bytes(&mut self, len: usize) -> &'a [u8] { . self.opaque.read_raw_bytes(len) . } . } . . impl<'a, 'tcx> TyDecoder<'tcx> for DecodeContext<'a, 'tcx> { -- line 324 ---------------------------------------- -- line 326 ---------------------------------------- . . #[inline] . fn tcx(&self) -> TyCtxt<'tcx> { . self.tcx.expect("missing TyCtxt in DecodeContext") . } . . #[inline] . fn peek_byte(&self) -> u8 { 9,950 ( 0.00%) self.opaque.data[self.opaque.position()] . } . . #[inline] . fn position(&self) -> usize { . self.opaque.position() . } . 9,828 ( 0.00%) fn cached_ty_for_shorthand(&mut self, shorthand: usize, or_insert_with: F) -> Ty<'tcx> . where . F: FnOnce(&mut Self) -> Ty<'tcx>, . { 1,404 ( 0.00%) let tcx = self.tcx(); . 1,404 ( 0.00%) let key = ty::CReaderCacheKey { cnum: Some(self.cdata().cnum), pos: shorthand }; . 4,252 ( 0.00%) if let Some(&ty) = tcx.ty_rcache.borrow().get(&key) { . return ty; . } . 341 ( 0.00%) let ty = or_insert_with(self); . tcx.ty_rcache.borrow_mut().insert(key, ty); . ty 12,636 ( 0.00%) } . . fn with_position(&mut self, pos: usize, f: F) -> R . where . F: FnOnce(&mut Self) -> R, . { . let new_opaque = opaque::Decoder::new(self.opaque.data, pos); . let old_opaque = mem::replace(&mut self.opaque, new_opaque); . let old_state = mem::replace(&mut self.lazy_state, LazyState::NoNode); . let r = f(self); 1,830 ( 0.00%) self.opaque = old_opaque; 366 ( 0.00%) self.lazy_state = old_state; . r . } . . fn decode_alloc_id(&mut self) -> rustc_middle::mir::interpret::AllocId { . if let Some(alloc_decoding_session) = self.alloc_decoding_session { . alloc_decoding_session.decode_alloc_id(self) . } else { . bug!("Attempting to decode interpret::AllocId without CrateMetadata") . } . } . } . . impl<'a, 'tcx> Decodable> for CrateNum { . fn decode(d: &mut DecodeContext<'a, 'tcx>) -> CrateNum { 6,079 ( 0.00%) let cnum = CrateNum::from_u32(d.read_u32()); . d.map_encoded_cnum_to_current(cnum) . } . } . . impl<'a, 'tcx> Decodable> for DefIndex { 3 ( 0.00%) fn decode(d: &mut DecodeContext<'a, 'tcx>) -> DefIndex { 11,776 ( 0.00%) DefIndex::from_u32(d.read_u32()) 6 ( 0.00%) } . } . . impl<'a, 'tcx> Decodable> for ExpnIndex { . fn decode(d: &mut DecodeContext<'a, 'tcx>) -> ExpnIndex { . ExpnIndex::from_u32(d.read_u32()) . } . } . . impl<'a, 'tcx> Decodable> for SyntaxContext { 9,240 ( 0.00%) fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> SyntaxContext { 2,310 ( 0.00%) let cdata = decoder.cdata(); 2,310 ( 0.00%) let sess = decoder.sess.unwrap(); 4,620 ( 0.00%) let cname = cdata.root.name; . rustc_span::hygiene::decode_syntax_context(decoder, &cdata.hygiene_context, |_, id| { . debug!("SpecializedDecoder: decoding {}", id); 36 ( 0.00%) cdata . .root . .syntax_contexts . .get(cdata, id) . .unwrap_or_else(|| panic!("Missing SyntaxContext {:?} for crate {:?}", id, cname)) . .decode((cdata, sess)) . }) 11,550 ( 0.00%) } . } . . impl<'a, 'tcx> Decodable> for ExpnId { 1,134 ( 0.00%) fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> ExpnId { 162 ( 0.00%) let local_cdata = decoder.cdata(); 162 ( 0.00%) let sess = decoder.sess.unwrap(); . . let cnum = CrateNum::decode(decoder); . let index = u32::decode(decoder); . . let expn_id = rustc_span::hygiene::decode_expn_id(cnum, index, |expn_id| { . let ExpnId { krate: cnum, local_id: index } = expn_id; . // Lookup local `ExpnData`s in our own crate data. Foreign `ExpnData`s . // are stored in the owning crate, to avoid duplication. . debug_assert_ne!(cnum, LOCAL_CRATE); 13 ( 0.00%) let crate_data = if cnum == local_cdata.cnum { . local_cdata . } else { . local_cdata.cstore.get_crate_data(cnum) . }; 65 ( 0.00%) let expn_data = crate_data . .root . .expn_data . .get(crate_data, index) . .unwrap() . .decode((crate_data, sess)); 65 ( 0.00%) let expn_hash = crate_data . .root . .expn_hashes . .get(crate_data, index) . .unwrap() . .decode((crate_data, sess)); 130 ( 0.00%) (expn_data, expn_hash) . }); . expn_id 1,296 ( 0.00%) } . } . . impl<'a, 'tcx> Decodable> for Span { 18,264 ( 0.01%) fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Span { 2,283 ( 0.00%) let ctxt = SyntaxContext::decode(decoder); . let tag = u8::decode(decoder); . 4,566 ( 0.00%) if tag == TAG_PARTIAL_SPAN { . return DUMMY_SP.with_ctxt(ctxt); . } . . debug_assert!(tag == TAG_VALID_SPAN_LOCAL || tag == TAG_VALID_SPAN_FOREIGN); . . let lo = BytePos::decode(decoder); . let len = BytePos::decode(decoder); . let hi = lo + len; . 6,822 ( 0.00%) let Some(sess) = decoder.sess else { . bug!("Cannot decode Span without Session.") . }; . . // There are two possibilities here: . // 1. This is a 'local span', which is located inside a `SourceFile` . // that came from this crate. In this case, we use the source map data . // encoded in this crate. This branch should be taken nearly all of the time. . // 2. This is a 'foreign span', which is located inside a `SourceFile` -- line 476 ---------------------------------------- -- line 492 ---------------------------------------- . // a transitive dependency. . // . // When we encode a foreign span, we adjust its 'lo' and 'high' values . // to be based on the *foreign* crate (e.g. crate C), not the crate . // we are writing metadata for (e.g. crate B). This allows us to . // treat the 'local' and 'foreign' cases almost identically during deserialization: . // we can call `imported_source_files` for the proper crate, and binary search . // through the returned slice using our span. 5,379 ( 0.00%) let imported_source_files = if tag == TAG_VALID_SPAN_LOCAL { . decoder.cdata().imported_source_files(sess) . } else { . // When we encode a proc-macro crate, all `Span`s should be encoded . // with `TAG_VALID_SPAN_LOCAL` . if decoder.cdata().root.is_proc_macro_crate() { . // Decode `CrateNum` as u32 - using `CrateNum::decode` will ICE . // since we don't have `cnum_map` populated. . let cnum = u32::decode(decoder); -- line 508 ---------------------------------------- -- line 527 ---------------------------------------- . . let foreign_data = decoder.cdata().cstore.get_crate_data(cnum); . foreign_data.imported_source_files(sess) . }; . . let source_file = { . // Optimize for the case that most spans within a translated item . // originate from the same source_file. 6,822 ( 0.00%) let last_source_file = &imported_source_files[decoder.last_source_file_index]; . 9,017 ( 0.00%) if lo >= last_source_file.original_start_pos && lo <= last_source_file.original_end_pos . { . last_source_file . } else { . let index = imported_source_files . .binary_search_by_key(&lo, |source_file| source_file.original_start_pos) 1,662 ( 0.00%) .unwrap_or_else(|index| index - 1); . . // Don't try to cache the index for foreign spans, . // as this would require a map from CrateNums to indices 831 ( 0.00%) if tag == TAG_VALID_SPAN_LOCAL { 831 ( 0.00%) decoder.last_source_file_index = index; . } 1,662 ( 0.00%) &imported_source_files[index] . } . }; . . // Make sure our binary search above is correct. . debug_assert!( . lo >= source_file.original_start_pos && lo <= source_file.original_end_pos, . "Bad binary search: lo={:?} source_file.original_start_pos={:?} source_file.original_end_pos={:?}", . lo, -- line 558 ---------------------------------------- -- line 565 ---------------------------------------- . hi >= source_file.original_start_pos && hi <= source_file.original_end_pos, . "Bad binary search: hi={:?} source_file.original_start_pos={:?} source_file.original_end_pos={:?}", . hi, . source_file.original_start_pos, . source_file.original_end_pos . ); . . let lo = 9,096 ( 0.00%) (lo + source_file.translated_source_file.start_pos) - source_file.original_start_pos; . let hi = . (hi + source_file.translated_source_file.start_pos) - source_file.original_start_pos; . . // Do not try to decode parent for foreign spans. . Span::new(lo, hi, ctxt, None) 20,547 ( 0.01%) } . } . . impl<'a, 'tcx> Decodable> for &'tcx [thir::abstract_const::Node<'tcx>] { . fn decode(d: &mut DecodeContext<'a, 'tcx>) -> Self { . ty::codec::RefDecodable::decode(d) . } . } . -- line 587 ---------------------------------------- -- line 590 ---------------------------------------- . ty::codec::RefDecodable::decode(d) . } . } . . impl<'a, 'tcx, T: Decodable>> Decodable> . for Lazy . { . fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Self { 1,363 ( 0.00%) decoder.read_lazy_with_meta(()) . } . } . . impl<'a, 'tcx, T: Decodable>> Decodable> . for Lazy<[T]> . { . fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Self { . let len = decoder.read_usize(); 4,247 ( 0.00%) if len == 0 { Lazy::empty() } else { decoder.read_lazy_with_meta(len) } . } . } . . impl<'a, 'tcx, I: Idx, T: Decodable>> Decodable> . for Lazy> . where . Option: FixedSizeEncoding, . { . fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Self { . let len = decoder.read_usize(); 1,521 ( 0.00%) decoder.read_lazy_with_meta(len) . } . } . . implement_ty_decoder!(DecodeContext<'a, 'tcx>); . . impl<'tcx> MetadataBlob { . crate fn new(metadata_ref: MetadataRef) -> MetadataBlob { . MetadataBlob(Lrc::new(metadata_ref)) -- line 626 ---------------------------------------- -- line 630 ---------------------------------------- . self.blob().starts_with(METADATA_HEADER) . } . . crate fn get_rustc_version(&self) -> String { . Lazy::::from_position(NonZeroUsize::new(METADATA_HEADER.len() + 4).unwrap()) . .decode(self) . } . 27 ( 0.00%) crate fn get_root(&self) -> CrateRoot<'tcx> { 9 ( 0.00%) let slice = &self.blob()[..]; . let offset = METADATA_HEADER.len(); 45 ( 0.00%) let pos = (((slice[offset + 0] as u32) << 24) 18 ( 0.00%) | ((slice[offset + 1] as u32) << 16) 36 ( 0.00%) | ((slice[offset + 2] as u32) << 8) 27 ( 0.00%) | ((slice[offset + 3] as u32) << 0)) as usize; . Lazy::>::from_position(NonZeroUsize::new(pos).unwrap()).decode(self) 45 ( 0.00%) } . . crate fn list_crate_metadata(&self, out: &mut dyn io::Write) -> io::Result<()> { . let root = self.get_root(); . writeln!(out, "Crate info:")?; . writeln!(out, "name {}{}", root.name, root.extra_filename)?; . writeln!(out, "hash {} stable_crate_id {:?}", root.hash, root.stable_crate_id)?; . writeln!(out, "proc_macro {:?}", root.proc_macro_data.is_some())?; . writeln!(out, "=External Dependencies=")?; -- line 654 ---------------------------------------- -- line 666 ---------------------------------------- . } . write!(out, "\n")?; . Ok(()) . } . } . . impl CrateRoot<'_> { . crate fn is_proc_macro_crate(&self) -> bool { 6 ( 0.00%) self.proc_macro_data.is_some() . } . . crate fn name(&self) -> Symbol { 4 ( 0.00%) self.name . } . . crate fn hash(&self) -> Svh { 3 ( 0.00%) self.hash . } . . crate fn stable_crate_id(&self) -> StableCrateId { 6 ( 0.00%) self.stable_crate_id . } . . crate fn triple(&self) -> &TargetTriple { . &self.triple . } . . crate fn decode_crate_deps<'a>( . &self, . metadata: &'a MetadataBlob, . ) -> impl ExactSizeIterator + Captures<'a> { 6 ( 0.00%) self.crate_deps.decode(metadata) . } . } . . impl<'a, 'tcx> CrateMetadataRef<'a> { . fn raw_proc_macro(self, id: DefIndex) -> &'a ProcMacro { . // DefIndex's in root.proc_macro_data have a one-to-one correspondence . // with items in 'raw_proc_macros'. . let pos = self -- line 705 ---------------------------------------- -- line 709 ---------------------------------------- . .unwrap() . .macros . .decode(self) . .position(|i| i == id) . .unwrap(); . &self.raw_proc_macros.unwrap()[pos] . } . 4,917 ( 0.00%) fn opt_item_ident(self, item_index: DefIndex, sess: &Session) -> Option { 3,636 ( 0.00%) let name = self.def_key(item_index).disambiguated_data.data.get_opt_name()?; 2,996 ( 0.00%) let span = match self.root.tables.ident_span.get(self, item_index) { . Some(lazy_span) => lazy_span.decode((self, sess)), . None => { . // FIXME: this weird case of a name with no span is specific to `extern crate` . // items, which are supposed to be treated like `use` items and only be encoded . // to metadata as `Export`s, return `None` because that's what all the callers . // expect in this case. 18 ( 0.00%) assert_eq!(self.def_kind(item_index), DefKind::ExternCrate); . return None; . } . }; . Some(Ident::new(name, span)) 6,282 ( 0.00%) } . 2 ( 0.00%) fn item_ident(self, item_index: DefIndex, sess: &Session) -> Ident { 1,096 ( 0.00%) self.opt_item_ident(item_index, sess).expect("no encoded ident for item") 4 ( 0.00%) } . . fn maybe_kind(self, item_id: DefIndex) -> Option { 1,584 ( 0.00%) self.root.tables.kind.get(self, item_id).map(|k| k.decode(self)) . } . 6,336 ( 0.00%) fn kind(self, item_id: DefIndex) -> EntryKind { . self.maybe_kind(item_id).unwrap_or_else(|| { . bug!( . "CrateMetadata::kind({:?}): id not found, in crate {:?} with number {}", . item_id, . self.root.name, . self.cnum, . ) . }) 4,752 ( 0.00%) } . 2,576 ( 0.00%) fn def_kind(self, item_id: DefIndex) -> DefKind { 1,797 ( 0.00%) self.root.tables.def_kind.get(self, item_id).map(|k| k.decode(self)).unwrap_or_else(|| { . bug!( . "CrateMetadata::def_kind({:?}): id not found, in crate {:?} with number {}", . item_id, . self.root.name, . self.cnum, . ) . }) 1,472 ( 0.00%) } . 18 ( 0.00%) fn get_span(self, index: DefIndex, sess: &Session) -> Span { 1,114 ( 0.00%) self.root . .tables . .span . .get(self, index) . .unwrap_or_else(|| panic!("Missing span for {:?}", index)) . .decode((self, sess)) 10 ( 0.00%) } . . fn load_proc_macro(self, id: DefIndex, sess: &Session) -> SyntaxExtension { . let (name, kind, helper_attrs) = match *self.raw_proc_macro(id) { . ProcMacro::CustomDerive { trait_name, attributes, client } => { . let helper_attrs = . attributes.iter().cloned().map(Symbol::intern).collect::>(); . ( . trait_name, -- line 778 ---------------------------------------- -- line 795 ---------------------------------------- . self.get_span(id, sess), . helper_attrs, . self.root.edition, . Symbol::intern(name), . &attrs, . ) . } . 91 ( 0.00%) fn get_trait_def(self, item_id: DefIndex, sess: &Session) -> ty::TraitDef { 28 ( 0.00%) match self.kind(item_id) { 7 ( 0.00%) EntryKind::Trait(data) => { 42 ( 0.00%) let data = data.decode((self, sess)); 112 ( 0.00%) ty::TraitDef::new( . self.local_def_id(item_id), 14 ( 0.00%) data.unsafety, 14 ( 0.00%) data.paren_sugar, 14 ( 0.00%) data.has_auto_impl, 14 ( 0.00%) data.is_marker, 7 ( 0.00%) data.skip_array_during_method_dispatch, 7 ( 0.00%) data.specialization_kind, 28 ( 0.00%) self.def_path_hash(item_id), 7 ( 0.00%) data.must_implement_one_of, . ) . } . EntryKind::TraitAlias => ty::TraitDef::new( . self.local_def_id(item_id), . hir::Unsafety::Normal, . false, . false, . false, . false, . ty::trait_def::TraitSpecializationKind::None, . self.def_path_hash(item_id), . None, . ), . _ => bug!("def-index does not refer to trait or trait alias"), . } 63 ( 0.00%) } . 63 ( 0.00%) fn get_variant( . self, . kind: &EntryKind, . index: DefIndex, . parent_did: DefId, . sess: &Session, . ) -> ty::VariantDef { 28 ( 0.00%) let data = match kind { . EntryKind::Variant(data) | EntryKind::Struct(data, _) | EntryKind::Union(data, _) => { 35 ( 0.00%) data.decode(self) . } . _ => bug!(), . }; . 18 ( 0.00%) let adt_kind = match kind { . EntryKind::Variant(_) => ty::AdtKind::Enum, . EntryKind::Struct(..) => ty::AdtKind::Struct, . EntryKind::Union(..) => ty::AdtKind::Union, . _ => bug!(), . }; . . let variant_did = . if adt_kind == ty::AdtKind::Enum { Some(self.local_def_id(index)) } else { None }; 14 ( 0.00%) let ctor_did = data.ctor.map(|index| self.local_def_id(index)); . 154 ( 0.00%) ty::VariantDef::new( . self.item_ident(index, sess).name, . variant_did, . ctor_did, 28 ( 0.00%) data.discr, 42 ( 0.00%) self.root . .tables . .children . .get(self, index) . .unwrap_or_else(Lazy::empty) . .decode(self) . .map(|index| ty::FieldDef { 7 ( 0.00%) did: self.local_def_id(index), 14 ( 0.00%) name: self.item_ident(index, sess).name, 14 ( 0.00%) vis: self.get_visibility(index), . }) . .collect(), . data.ctor_kind, . adt_kind, . parent_did, . false, 7 ( 0.00%) data.is_non_exhaustive, . ) 63 ( 0.00%) } . 60 ( 0.00%) fn get_adt_def(self, item_id: DefIndex, tcx: TyCtxt<'tcx>) -> &'tcx ty::AdtDef { 16 ( 0.00%) let kind = self.kind(item_id); 8 ( 0.00%) let did = self.local_def_id(item_id); . 16 ( 0.00%) let (adt_kind, repr) = match kind { . EntryKind::Enum(repr) => (ty::AdtKind::Enum, repr), . EntryKind::Struct(_, repr) => (ty::AdtKind::Struct, repr), . EntryKind::Union(_, repr) => (ty::AdtKind::Union, repr), . _ => bug!("get_adt_def called on a non-ADT {:?}", did), . }; . . let variants = if let ty::AdtKind::Enum = adt_kind { 10 ( 0.00%) self.root . .tables . .children . .get(self, item_id) . .unwrap_or_else(Lazy::empty) . .decode(self) 85 ( 0.00%) .map(|index| self.get_variant(&self.kind(index), index, did, tcx.sess)) . .collect() . } else { 16 ( 0.00%) std::iter::once(self.get_variant(&kind, item_id, did, tcx.sess)).collect() . }; . 66 ( 0.00%) tcx.alloc_adt_def(did, adt_kind, variants, repr) 28 ( 0.00%) } . . fn get_explicit_predicates( . self, . item_id: DefIndex, . tcx: TyCtxt<'tcx>, . ) -> ty::GenericPredicates<'tcx> { 230 ( 0.00%) self.root.tables.explicit_predicates.get(self, item_id).unwrap().decode((self, tcx)) . } . . fn get_inferred_outlives( . self, . item_id: DefIndex, . tcx: TyCtxt<'tcx>, . ) -> &'tcx [(ty::Predicate<'tcx>, Span)] { 230 ( 0.00%) self.root . .tables . .inferred_outlives . .get(self, item_id) . .map(|predicates| tcx.arena.alloc_from_iter(predicates.decode((self, tcx)))) . .unwrap_or_default() . } . . fn get_super_predicates( . self, . item_id: DefIndex, . tcx: TyCtxt<'tcx>, . ) -> ty::GenericPredicates<'tcx> { 75 ( 0.00%) self.root.tables.super_predicates.get(self, item_id).unwrap().decode((self, tcx)) . } . . fn get_explicit_item_bounds( . self, . item_id: DefIndex, . tcx: TyCtxt<'tcx>, . ) -> &'tcx [(ty::Predicate<'tcx>, Span)] { 5 ( 0.00%) self.root . .tables . .explicit_item_bounds . .get(self, item_id) 4 ( 0.00%) .map(|bounds| tcx.arena.alloc_from_iter(bounds.decode((self, tcx)))) . .unwrap_or_default() . } . . fn get_generics(self, item_id: DefIndex, sess: &Session) -> ty::Generics { 230 ( 0.00%) self.root.tables.generics.get(self, item_id).unwrap().decode((self, sess)) . } . . fn get_type(self, id: DefIndex, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { 185 ( 0.00%) self.root . .tables . .ty . .get(self, id) . .unwrap_or_else(|| panic!("Not a type: {:?}", id)) . .decode((self, tcx)) . } . . fn get_stability(self, id: DefIndex) -> Option { 45 ( 0.00%) self.root.tables.stability.get(self, id).map(|stab| stab.decode(self)) . } . . fn get_const_stability(self, id: DefIndex) -> Option { . self.root.tables.const_stability.get(self, id).map(|stab| stab.decode(self)) . } . . fn get_deprecation(self, id: DefIndex) -> Option { 40 ( 0.00%) self.root.tables.deprecation.get(self, id).map(|depr| depr.decode(self)) . } . 6 ( 0.00%) fn get_visibility(self, id: DefIndex) -> ty::Visibility { 1,418 ( 0.00%) self.root.tables.visibility.get(self, id).unwrap().decode(self) 4 ( 0.00%) } . . fn get_impl_data(self, id: DefIndex) -> ImplData { 1,752 ( 0.00%) match self.kind(id) { 1,460 ( 0.00%) EntryKind::Impl(data) => data.decode(self), . _ => bug!(), . } . } . . fn get_parent_impl(self, id: DefIndex) -> Option { 837 ( 0.00%) self.get_impl_data(id).parent_impl . } . . fn get_impl_polarity(self, id: DefIndex) -> ty::ImplPolarity { 11 ( 0.00%) self.get_impl_data(id).polarity . } . . fn get_impl_defaultness(self, id: DefIndex) -> hir::Defaultness { 2 ( 0.00%) self.get_impl_data(id).defaultness . } . . fn get_impl_constness(self, id: DefIndex) -> hir::Constness { . self.get_impl_data(id).constness . } . . fn get_trait_item_def_id(self, id: DefIndex) -> Option { 905 ( 0.00%) self.root.tables.trait_item_def_id.get(self, id).map(|d| d.decode(self)) . } . . fn get_coerce_unsized_info(self, id: DefIndex) -> Option { . self.get_impl_data(id).coerce_unsized_info . } . . fn get_impl_trait(self, id: DefIndex, tcx: TyCtxt<'tcx>) -> Option> { 3,476 ( 0.00%) self.root.tables.impl_trait_ref.get(self, id).map(|tr| tr.decode((self, tcx))) . } . . fn get_expn_that_defined(self, id: DefIndex, sess: &Session) -> ExpnId { 700 ( 0.00%) self.root.tables.expn_that_defined.get(self, id).unwrap().decode((self, sess)) . } . . fn get_const_param_default( . self, . tcx: TyCtxt<'tcx>, . id: DefIndex, . ) -> rustc_middle::ty::Const<'tcx> { . self.root.tables.const_defaults.get(self, id).unwrap().decode((self, tcx)) -- line 1026 ---------------------------------------- -- line 1028 ---------------------------------------- . . /// Iterates over all the stability attributes in the given crate. . fn get_lib_features(self, tcx: TyCtxt<'tcx>) -> &'tcx [(Symbol, Option)] { . tcx.arena.alloc_from_iter(self.root.lib_features.decode(self)) . } . . /// Iterates over the language items in the given crate. . fn get_lang_items(self, tcx: TyCtxt<'tcx>) -> &'tcx [(DefId, usize)] { 9 ( 0.00%) tcx.arena.alloc_from_iter( 6 ( 0.00%) self.root . .lang_items . .decode(self) 508 ( 0.00%) .map(|(def_index, index)| (self.local_def_id(def_index), index)), . ) . } . . /// Iterates over the diagnostic items in the given crate. . fn get_diagnostic_items(self) -> DiagnosticItems { . let mut id_to_name = FxHashMap::default(); 2 ( 0.00%) let name_to_id = self . .root . .diagnostic_items . .decode(self) . .map(|(name, def_index)| { 91 ( 0.00%) let id = self.local_def_id(def_index); 91 ( 0.00%) id_to_name.insert(id, name); . (name, id) . }) . .collect(); 9 ( 0.00%) DiagnosticItems { id_to_name, name_to_id } . } . . /// Iterates over all named children of the given module, . /// including both proper items and reexports. . /// Module here is understood in name resolution sense - it can be a `mod` item, . /// or a crate root, or an enum, or a trait. . fn for_each_module_child( . self, . id: DefIndex, . mut callback: impl FnMut(ModChild), . sess: &Session, . ) { 120 ( 0.00%) if let Some(data) = &self.root.proc_macro_data { . // If we are loading as a proc macro, we want to return . // the view of this crate as a proc macro crate. . if id == CRATE_DEF_INDEX { . for def_index in data.macros.decode(self) { . let raw_macro = self.raw_proc_macro(def_index); . let res = Res::Def( . DefKind::Macro(macro_kind(raw_macro)), . self.local_def_id(def_index), -- line 1078 ---------------------------------------- -- line 1085 ---------------------------------------- . span: ident.span, . }); . } . } . return; . } . . // Iterate over all children. 240 ( 0.00%) if let Some(children) = self.root.tables.children.get(self, id) { 480 ( 0.00%) for child_index in children.decode((self, sess)) { 1,542 ( 0.00%) if let Some(ident) = self.opt_item_ident(child_index, sess) { 690 ( 0.00%) let kind = self.def_kind(child_index); 460 ( 0.00%) if matches!(kind, DefKind::Macro(..)) { . // FIXME: Macros are currently encoded twice, once as items and once as . // reexports. We ignore the items here and only use the reexports. . continue; . } . let def_id = self.local_def_id(child_index); . let res = Res::Def(kind, def_id); . let vis = self.get_visibility(child_index); . let span = self.get_span(child_index, sess); . . callback(ModChild { ident, res, vis, span }); . . // For non-re-export structs and variants add their constructors to children. . // Re-export lists automatically contain constructors when necessary. 898 ( 0.00%) match kind { . DefKind::Struct => { 2 ( 0.00%) if let Some((ctor_def_id, ctor_kind)) = . self.get_ctor_def_id_and_kind(child_index) . { . let ctor_res = . Res::Def(DefKind::Ctor(CtorOf::Struct, ctor_kind), ctor_def_id); . let vis = self.get_visibility(ctor_def_id.index); . callback(ModChild { ident, res: ctor_res, vis, span }); . } . } . DefKind::Variant => { . // Braced variants, unlike structs, generate unusable names in . // value namespace, they are reserved for possible future use. . // It's ok to use the variant's id as a ctor id since an . // error will be reported on any use of such resolution anyway. 9 ( 0.00%) let (ctor_def_id, ctor_kind) = self . .get_ctor_def_id_and_kind(child_index) . .unwrap_or((def_id, CtorKind::Fictive)); . let ctor_res = . Res::Def(DefKind::Ctor(CtorOf::Variant, ctor_kind), ctor_def_id); . let mut vis = self.get_visibility(ctor_def_id.index); 3 ( 0.00%) if ctor_def_id == def_id && vis.is_public() { . // For non-exhaustive variants lower the constructor visibility to . // within the crate. We only need this for fictive constructors, . // for other constructors correct visibilities . // were already encoded in metadata. . let mut attrs = self.get_item_attrs(def_id.index, sess); . if attrs.any(|item| item.has_name(sym::non_exhaustive)) { . let crate_def_id = self.local_def_id(CRATE_DEF_INDEX); . vis = ty::Visibility::Restricted(crate_def_id); -- line 1141 ---------------------------------------- -- line 1144 ---------------------------------------- . callback(ModChild { ident, res: ctor_res, vis, span }); . } . _ => {} . } . } . } . } . 316 ( 0.00%) match self.kind(id) { 10 ( 0.00%) EntryKind::Mod(exports) => { 308 ( 0.00%) for exp in exports.decode((self, sess)) { . callback(exp); . } . } . EntryKind::Enum(..) | EntryKind::Trait(..) => {} . _ => bug!("`for_each_module_child` is called on a non-module: {:?}", self.def_kind(id)), . } . } . . fn is_ctfe_mir_available(self, id: DefIndex) -> bool { 12 ( 0.00%) self.root.tables.mir_for_ctfe.get(self, id).is_some() . } . . fn is_item_mir_available(self, id: DefIndex) -> bool { 36 ( 0.00%) self.root.tables.mir.get(self, id).is_some() . } . . fn module_expansion(self, id: DefIndex, sess: &Session) -> ExpnId { 952 ( 0.00%) match self.kind(id) { . EntryKind::Mod(_) | EntryKind::Enum(_) | EntryKind::Trait(_) => { . self.get_expn_that_defined(id, sess) . } . _ => panic!("Expected module, found {:?}", self.local_def_id(id)), . } . } . . fn get_optimized_mir(self, tcx: TyCtxt<'tcx>, id: DefIndex) -> Body<'tcx> { 45 ( 0.00%) self.root . .tables . .mir . .get(self, id) . .unwrap_or_else(|| { . bug!("get_optimized_mir: missing MIR for `{:?}`", self.local_def_id(id)) . }) . .decode((self, tcx)) . } . . fn get_mir_for_ctfe(self, tcx: TyCtxt<'tcx>, id: DefIndex) -> Body<'tcx> { 15 ( 0.00%) self.root . .tables . .mir_for_ctfe . .get(self, id) . .unwrap_or_else(|| { . bug!("get_mir_for_ctfe: missing MIR for `{:?}`", self.local_def_id(id)) . }) . .decode((self, tcx)) . } -- line 1200 ---------------------------------------- -- line 1216 ---------------------------------------- . .tables . .unused_generic_params . .get(self, id) . .map(|params| params.decode(self)) . .unwrap_or_default() . } . . fn get_promoted_mir(self, tcx: TyCtxt<'tcx>, id: DefIndex) -> IndexVec> { 5 ( 0.00%) self.root . .tables . .promoted_mir . .get(self, id) . .unwrap_or_else(|| { . bug!("get_promoted_mir: missing MIR for `{:?}`", self.local_def_id(id)) . }) . .decode((self, tcx)) . } -- line 1232 ---------------------------------------- -- line 1242 ---------------------------------------- . qualif, . _, . ) => qualif, . _ => bug!("mir_const_qualif: unexpected kind"), . } . } . . fn get_fn_has_self_parameter(self, id: DefIndex) -> bool { 535 ( 0.00%) match self.kind(id) { 428 ( 0.00%) EntryKind::AssocFn(data) => data.decode(self).has_self, . _ => false, . } . } . . fn get_associated_item_def_ids(self, tcx: TyCtxt<'tcx>, id: DefIndex) -> &'tcx [DefId] { 84 ( 0.00%) if let Some(children) = self.root.tables.children.get(self, id) { 36 ( 0.00%) tcx.arena.alloc_from_iter( 12 ( 0.00%) children.decode((self, tcx.sess)).map(|child_index| self.local_def_id(child_index)), . ) . } else { . &[] . } . } . 2,076 ( 0.00%) fn get_associated_item(self, id: DefIndex, sess: &Session) -> ty::AssocItem { 1,211 ( 0.00%) let def_key = self.def_key(id); . let parent = self.local_def_id(def_key.parent.unwrap()); . let ident = self.item_ident(id, sess); . 1,219 ( 0.00%) let (kind, container, has_self) = match self.kind(id) { . EntryKind::AssocConst(container, _, _) => (ty::AssocKind::Const, container, false), 169 ( 0.00%) EntryKind::AssocFn(data) => { . let data = data.decode(self); 1,183 ( 0.00%) (ty::AssocKind::Fn, data.container, data.has_self) . } 8 ( 0.00%) EntryKind::AssocType(container) => (ty::AssocKind::Type, container, false), . _ => bug!("cannot get associated-item of `{:?}`", def_key), . }; . 3,114 ( 0.00%) ty::AssocItem { . name: ident.name, . kind, . vis: self.get_visibility(id), . defaultness: container.defaultness(), . def_id: self.local_def_id(id), . trait_item_def_id: self.get_trait_item_def_id(id), . container: container.with_def_id(parent), . fn_has_self_parameter: has_self, . } 1,557 ( 0.00%) } . . fn get_item_variances(self, id: DefIndex) -> impl Iterator + 'a { 10 ( 0.00%) self.root.tables.variances.get(self, id).unwrap_or_else(Lazy::empty).decode(self) . } . . fn get_ctor_def_id_and_kind(self, node_id: DefIndex) -> Option<(DefId, CtorKind)> { 62 ( 0.00%) match self.kind(node_id) { . EntryKind::Struct(data, _) | EntryKind::Variant(data) => { 26 ( 0.00%) let vdata = data.decode(self); 27 ( 0.00%) vdata.ctor.map(|index| (self.local_def_id(index), vdata.ctor_kind)) . } . _ => None, . } 28 ( 0.00%) } . 12 ( 0.00%) fn get_item_attrs( . self, . id: DefIndex, . sess: &'a Session, . ) -> impl Iterator + 'a { 111 ( 0.00%) self.root . .tables . .attributes . .get(self, id) . .unwrap_or_else(|| { . // Structure and variant constructors don't have any attributes encoded for them, . // but we assume that someone passing a constructor ID actually wants to look at . // the attributes on the corresponding struct or variant. . let def_key = self.def_key(id); -- line 1320 ---------------------------------------- -- line 1322 ---------------------------------------- . let parent_id = def_key.parent.expect("no parent for a constructor"); . self.root . .tables . .attributes . .get(self, parent_id) . .expect("no encoded attributes for a structure or variant") . }) . .decode((self, sess)) 9 ( 0.00%) } . . fn get_struct_field_names( . self, . id: DefIndex, . sess: &'a Session, . ) -> impl Iterator> + 'a { 10 ( 0.00%) self.root . .tables . .children . .get(self, id) . .unwrap_or_else(Lazy::empty) . .decode(self) 20 ( 0.00%) .map(move |index| respan(self.get_span(index, sess), self.item_ident(index, sess).name)) . } . . fn get_struct_field_visibilities(self, id: DefIndex) -> impl Iterator + 'a { 5 ( 0.00%) self.root . .tables . .children . .get(self, id) . .unwrap_or_else(Lazy::empty) . .decode(self) 2 ( 0.00%) .map(move |field_index| self.get_visibility(field_index)) . } . . fn get_inherent_implementations_for_type( . self, . tcx: TyCtxt<'tcx>, . id: DefIndex, . ) -> &'tcx [DefId] { 4 ( 0.00%) tcx.arena.alloc_from_iter( 5 ( 0.00%) self.root . .tables . .inherent_impls . .get(self, id) . .unwrap_or_else(Lazy::empty) . .decode(self) 172 ( 0.00%) .map(|index| self.local_def_id(index)), . ) . } . . fn get_traits(self) -> impl Iterator + 'a { . self.root.traits.decode(self).map(move |index| self.local_def_id(index)) . } . . fn get_trait_impls(self) -> impl Iterator)> + 'a { -- line 1376 ---------------------------------------- -- line 1380 ---------------------------------------- . index: *trait_index, . }; . impls.decode(self).map(move |(impl_index, simplified_self_ty)| { . (trait_def_id, self.local_def_id(impl_index), simplified_self_ty) . }) . }) . } . 243 ( 0.00%) fn get_implementations_of_trait( . self, . tcx: TyCtxt<'tcx>, . trait_def_id: DefId, . ) -> &'tcx [(DefId, Option)] { 27 ( 0.00%) if self.trait_impls.is_empty() { . return &[]; . } . . // Do a reverse lookup beforehand to avoid touching the crate_num . // hash map in the loop below. 36 ( 0.00%) let key = match self.reverse_translate_def_id(trait_def_id) { . Some(def_id) => (def_id.krate.as_u32(), def_id.index), . None => return &[], . }; . . if let Some(impls) = self.trait_impls.get(&key) { 40 ( 0.00%) tcx.arena.alloc_from_iter( 20 ( 0.00%) impls . .decode(self) 645 ( 0.00%) .map(|(idx, simplified_self_ty)| (self.local_def_id(idx), simplified_self_ty)), . ) . } else { . &[] . } 216 ( 0.00%) } . . fn get_trait_of_item(self, id: DefIndex) -> Option { 60 ( 0.00%) let def_key = self.def_key(id); 75 ( 0.00%) match def_key.disambiguated_data.data { . DefPathData::TypeNs(..) | DefPathData::ValueNs(..) => (), . // Not an associated item . _ => return None, . } 135 ( 0.00%) def_key.parent.and_then(|parent_index| match self.kind(parent_index) { . EntryKind::Trait(_) | EntryKind::TraitAlias => Some(self.local_def_id(parent_index)), . _ => None, . }) . } . . fn get_native_libraries(self, sess: &'a Session) -> impl Iterator + 'a { 6 ( 0.00%) self.root.native_libraries.decode((self, sess)) . } . . fn get_proc_macro_quoted_span(self, index: usize, sess: &Session) -> Span { . self.root . .tables . .proc_macro_quoted_spans . .get(self, index) . .unwrap_or_else(|| panic!("Missing proc macro quoted span: {:?}", index)) -- line 1437 ---------------------------------------- -- line 1450 ---------------------------------------- . self.root.dylib_dependency_formats.decode(self).enumerate().flat_map(|(i, link)| { . let cnum = CrateNum::new(i + 1); . link.map(|link| (self.cnum_map[cnum], link)) . }), . ) . } . . fn get_missing_lang_items(self, tcx: TyCtxt<'tcx>) -> &'tcx [lang_items::LangItem] { 15 ( 0.00%) tcx.arena.alloc_from_iter(self.root.lang_items_missing.decode(self)) . } . . fn get_fn_param_names(self, tcx: TyCtxt<'tcx>, id: DefIndex) -> &'tcx [Ident] { . let param_names = match self.kind(id) { . EntryKind::Fn(data) | EntryKind::ForeignFn(data) => data.decode(self).param_names, . EntryKind::AssocFn(data) => data.decode(self).fn_data.param_names, . _ => Lazy::empty(), . }; . tcx.arena.alloc_from_iter(param_names.decode((self, tcx))) . } . . fn exported_symbols( . self, . tcx: TyCtxt<'tcx>, . ) -> &'tcx [(ExportedSymbol<'tcx>, SymbolExportLevel)] { 18 ( 0.00%) tcx.arena.alloc_from_iter(self.root.exported_symbols.decode((self, tcx))) . } . . fn get_rendered_const(self, id: DefIndex) -> String { . match self.kind(id) { . EntryKind::AnonConst(_, data) . | EntryKind::Const(_, data) . | EntryKind::AssocConst(_, _, data) => data.decode(self).0, . _ => bug!(), . } . } . . fn get_macro(self, id: DefIndex, sess: &Session) -> MacroDef { 6 ( 0.00%) match self.kind(id) { 1 ( 0.00%) EntryKind::MacroDef(macro_def) => macro_def.decode((self, sess)), . _ => bug!(), . } . } . . // This replicates some of the logic of the crate-local `is_const_fn_raw` query, because we . // don't serialize constness for tuple variant and tuple struct constructors. . fn is_const_fn_raw(self, id: DefIndex) -> bool { 9 ( 0.00%) let constness = match self.kind(id) { 2 ( 0.00%) EntryKind::AssocFn(data) => data.decode(self).fn_data.constness, . EntryKind::Fn(data) => data.decode(self).constness, . EntryKind::ForeignFn(data) => data.decode(self).constness, . EntryKind::Variant(..) | EntryKind::Struct(..) => hir::Constness::Const, . _ => hir::Constness::NotConst, . }; . constness == hir::Constness::Const . } . -- line 1505 ---------------------------------------- -- line 1508 ---------------------------------------- . EntryKind::Fn(data) => data.decode(self).asyncness, . EntryKind::AssocFn(data) => data.decode(self).fn_data.asyncness, . EntryKind::ForeignFn(data) => data.decode(self).asyncness, . _ => bug!("asyncness: expected function kind"), . } . } . . fn is_foreign_item(self, id: DefIndex) -> bool { 110 ( 0.00%) match self.kind(id) { . EntryKind::ForeignImmStatic | EntryKind::ForeignMutStatic | EntryKind::ForeignFn(_) => { . true . } . _ => false, . } . } . . fn static_mutability(self, id: DefIndex) -> Option { 44 ( 0.00%) match self.kind(id) { . EntryKind::ImmStatic | EntryKind::ForeignImmStatic => Some(hir::Mutability::Not), . EntryKind::MutStatic | EntryKind::ForeignMutStatic => Some(hir::Mutability::Mut), . _ => None, . } . } . . fn generator_kind(self, id: DefIndex) -> Option { . match self.kind(id) { . EntryKind::Generator(data) => Some(data), . _ => None, . } . } . . fn fn_sig(self, id: DefIndex, tcx: TyCtxt<'tcx>) -> ty::PolyFnSig<'tcx> { 95 ( 0.00%) self.root.tables.fn_sig.get(self, id).unwrap().decode((self, tcx)) . } . . #[inline] 7,133 ( 0.00%) fn def_key(self, index: DefIndex) -> DefKey { 2,062 ( 0.00%) *self . .def_key_cache . .lock() . .entry(index) 2,430 ( 0.00%) .or_insert_with(|| self.root.tables.def_keys.get(self, index).unwrap().decode(self)) 8,152 ( 0.00%) } . . // Returns the path leading to the thing with this `id`. . fn def_path(self, id: DefIndex) -> DefPath { . debug!("def_path(cnum={:?}, id={:?})", self.cnum, id); 20 ( 0.00%) DefPath::make(self.cnum, id, |parent| self.def_key(parent)) . } . . fn def_path_hash_unlocked( . self, . index: DefIndex, . def_path_hashes: &mut FxHashMap, . ) -> DefPathHash { 168 ( 0.00%) *def_path_hashes.entry(index).or_insert_with(|| { 210 ( 0.00%) self.root.tables.def_path_hashes.get(self, index).unwrap().decode(self) . }) . } . . #[inline] 588 ( 0.00%) fn def_path_hash(self, index: DefIndex) -> DefPathHash { . let mut def_path_hashes = self.def_path_hash_cache.lock(); . self.def_path_hash_unlocked(index, &mut def_path_hashes) 672 ( 0.00%) } . . #[inline] . fn def_path_hash_to_def_index(self, hash: DefPathHash) -> DefIndex { . self.def_path_hash_map.def_path_hash_to_def_index(&hash) . } . . fn expn_hash_to_expn_id(self, sess: &Session, index_guess: u32, hash: ExpnHash) -> ExpnId { . debug_assert_eq!(ExpnId::from_hash(hash), None); -- line 1580 ---------------------------------------- -- line 1635 ---------------------------------------- . /// Proc macro crates don't currently export spans, so this function does not have . /// to work for them. . fn imported_source_files(self, sess: &Session) -> &'a [ImportedSourceFile] { . // Translate the virtual `/rustc/$hash` prefix back to a real directory . // that should hold actual sources, where possible. . // . // NOTE: if you update this, you might need to also update bootstrap's code for generating . // the `rust-src` component in `Src::run` in `src/bootstrap/dist.rs`. 4,548 ( 0.00%) let virtual_rust_source_base_dir = option_env!("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR") . .map(Path::new) . .filter(|_| { . // Only spend time on further checks if we have what to translate *to*. . sess.opts.real_rust_source_base_dir.is_some() . }) . .filter(|virtual_dir| { . // Don't translate away `/rustc/$hash` if we're still remapping to it, . // since that means we're still building `std`/`rustc` that need it, . // and we don't want the real path to leak into codegen/debuginfo. . !sess.opts.remap_path_prefix.iter().any(|(_from, to)| to == virtual_dir) . }); 4,548 ( 0.00%) let try_to_translate_virtual_to_real = |name: &mut rustc_span::FileName| { . debug!( . "try_to_translate_virtual_to_real(name={:?}): \ . virtual_rust_source_base_dir={:?}, real_rust_source_base_dir={:?}", . name, virtual_rust_source_base_dir, sess.opts.real_rust_source_base_dir, . ); . 1,565 ( 0.00%) if let Some(virtual_dir) = virtual_rust_source_base_dir { . if let Some(real_dir) = &sess.opts.real_rust_source_base_dir { . if let rustc_span::FileName::Real(old_name) = name { . if let rustc_span::RealFileName::Remapped { local_path: _, virtual_name } = . old_name . { . if let Ok(rest) = virtual_name.strip_prefix(virtual_dir) { . let virtual_name = virtual_name.clone(); . -- line 1670 ---------------------------------------- -- line 1709 ---------------------------------------- . *old_name = new_name; . } . } . } . } . } . }; . 4,548 ( 0.00%) self.cdata.source_map_import_info.get_or_init(|| { 9 ( 0.00%) let external_source_map = self.root.source_map.decode(self); . . external_source_map . .map(|source_file_to_import| { . // We can't reuse an existing SourceFile, so allocate a new one . // containing the information we need. . let rustc_span::SourceFile { 6,573 ( 0.00%) mut name, 1,878 ( 0.00%) src_hash, 313 ( 0.00%) start_pos, 626 ( 0.00%) end_pos, 1,565 ( 0.00%) mut lines, 1,565 ( 0.00%) mut multibyte_chars, 1,878 ( 0.00%) mut non_narrow_chars, 1,565 ( 0.00%) mut normalized_pos, 1,878 ( 0.00%) name_hash, . .. . } = source_file_to_import; . . // If this file is under $sysroot/lib/rustlib/src/ but has not been remapped . // during rust bootstrapping by `remap-debuginfo = true`, and the user . // wish to simulate that behaviour by -Z simulate-remapped-rust-src-base, . // then we change `name` to a similar state as if the rust was bootstrapped . // with `remap-debuginfo = true`. . // This is useful for testing so that tests about the effects of . // `try_to_translate_virtual_to_real` don't have to worry about how the . // compiler is bootstrapped. 626 ( 0.00%) if let Some(virtual_dir) = . &sess.opts.debugging_opts.simulate_remapped_rust_src_base . { . if let Some(real_dir) = &sess.opts.real_rust_source_base_dir { . if let rustc_span::FileName::Real(ref mut old_name) = name { . if let rustc_span::RealFileName::LocalPath(local) = old_name { . if let Ok(rest) = local.strip_prefix(real_dir) { . *old_name = rustc_span::RealFileName::Remapped { . local_path: None, -- line 1753 ---------------------------------------- -- line 1767 ---------------------------------------- . let source_length = (end_pos - start_pos).to_usize(); . . // Translate line-start positions and multibyte character . // position into frame of reference local to file. . // `SourceMap::new_imported_source_file()` will then translate those . // coordinates to their new global frame of reference when the . // offset of the SourceFile is known. . for pos in &mut lines { 476,936 ( 0.17%) *pos = *pos - start_pos; . } . for mbc in &mut multibyte_chars { 1,136 ( 0.00%) mbc.pos = mbc.pos - start_pos; . } . for swc in &mut non_narrow_chars { 804 ( 0.00%) *swc = *swc - start_pos; . } . for np in &mut normalized_pos { . np.pos = np.pos - start_pos; . } . 5,634 ( 0.00%) let local_version = sess.source_map().new_imported_source_file( 4,069 ( 0.00%) name, 2,191 ( 0.00%) src_hash, . name_hash, . source_length, 626 ( 0.00%) self.cnum, 1,565 ( 0.00%) lines, 1,878 ( 0.00%) multibyte_chars, 1,565 ( 0.00%) non_narrow_chars, 1,252 ( 0.00%) normalized_pos, . start_pos, . end_pos, . ); . debug!( . "CrateMetaData::imported_source_files alloc \ . source_file {:?} original (start_pos {:?} end_pos {:?}) \ . translated (start_pos {:?} end_pos {:?})", . local_version.name, -- line 1804 ---------------------------------------- -- line 1808 ---------------------------------------- . local_version.end_pos . ); . . ImportedSourceFile { . original_start_pos: start_pos, . original_end_pos: end_pos, . translated_source_file: local_version, . } 939 ( 0.00%) }) . .collect() . }) . } . } . . impl CrateMetadata { 36 ( 0.00%) crate fn new( . sess: &Session, . blob: MetadataBlob, . root: CrateRoot<'static>, . raw_proc_macros: Option<&'static [ProcMacro]>, . cnum: CrateNum, . cnum_map: CrateNumMap, . dep_kind: CrateDepKind, . source: CrateSource, . private_dep: bool, . host_hash: Option, . ) -> CrateMetadata { 9 ( 0.00%) let trait_impls = root . .impls . .decode((&blob, sess)) . .map(|trait_impls| (trait_impls.trait_id, trait_impls.impls)) . .collect(); . let alloc_decoding_state = 9 ( 0.00%) AllocDecodingState::new(root.interpret_alloc_index.decode(&blob).collect()); . let dependencies = Lock::new(cnum_map.iter().cloned().collect()); . . // Pre-decode the DefPathHash->DefIndex table. This is a cheap operation . // that does not copy any data. It just does some data verification. 3 ( 0.00%) let def_path_hash_map = root.def_path_hash_map.decode(&blob); . 69 ( 0.00%) CrateMetadata { 3 ( 0.00%) blob, 9 ( 0.00%) root, 12 ( 0.00%) trait_impls, . raw_proc_macros, . source_map_import_info: OnceCell::new(), 12 ( 0.00%) def_path_hash_map, . expn_hash_map: Default::default(), 21 ( 0.00%) alloc_decoding_state, . cnum, 12 ( 0.00%) cnum_map, 15 ( 0.00%) dependencies, . dep_kind: Lock::new(dep_kind), 36 ( 0.00%) source, . private_dep, . host_hash, . extern_crate: Lock::new(None), . hygiene_context: Default::default(), . def_key_cache: Default::default(), . def_path_hash_cache: Default::default(), . } 27 ( 0.00%) } . . crate fn dependencies(&self) -> LockGuard<'_, Vec> { . self.dependencies.borrow() . } . . crate fn add_dependency(&self, cnum: CrateNum) { . self.dependencies.borrow_mut().push(cnum); . } . . crate fn update_extern_crate(&self, new_extern_crate: ExternCrate) -> bool { . let mut extern_crate = self.extern_crate.borrow_mut(); . let update = Some(new_extern_crate.rank()) > extern_crate.as_ref().map(ExternCrate::rank); . if update { 15 ( 0.00%) *extern_crate = Some(new_extern_crate); . } . update . } . . crate fn source(&self) -> &CrateSource { . &self.source . } . . crate fn dep_kind(&self) -> CrateDepKind { . *self.dep_kind.lock() . } . . crate fn update_dep_kind(&self, f: impl FnOnce(CrateDepKind) -> CrateDepKind) { 2 ( 0.00%) self.dep_kind.with_lock(|dep_kind| *dep_kind = f(*dep_kind)) . } . . crate fn panic_strategy(&self) -> PanicStrategy { . self.root.panic_strategy . } . . crate fn needs_panic_runtime(&self) -> bool { . self.root.needs_panic_runtime -- line 1905 ---------------------------------------- -- line 1909 ---------------------------------------- . self.root.panic_runtime . } . . crate fn is_profiler_runtime(&self) -> bool { . self.root.profiler_runtime . } . . crate fn needs_allocator(&self) -> bool { 3 ( 0.00%) self.root.needs_allocator . } . . crate fn has_global_allocator(&self) -> bool { . self.root.has_global_allocator . } . . crate fn has_default_lib_allocator(&self) -> bool { . self.root.has_default_lib_allocator . } . . crate fn is_proc_macro_crate(&self) -> bool { . self.root.is_proc_macro_crate() . } . . crate fn name(&self) -> Symbol { 1 ( 0.00%) self.root.name . } . . crate fn stable_crate_id(&self) -> StableCrateId { . self.root.stable_crate_id . } . . crate fn hash(&self) -> Svh { . self.root.hash . } . . fn num_def_ids(&self) -> usize { . self.root.tables.def_keys.size() . } . . fn local_def_id(&self, index: DefIndex) -> DefId { 2,753 ( 0.00%) DefId { krate: self.cnum, index } . } . . // Translate a DefId from the current compilation environment to a DefId . // for an external crate. . fn reverse_translate_def_id(&self, did: DefId) -> Option { . for (local, &global) in self.cnum_map.iter_enumerated() { 45 ( 0.00%) if global == did.krate { . return Some(DefId { krate: local, index: did.index }); . } . } . . None . } . } . -- line 1964 ---------------------------------------- 55,130 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/rustc-hash-1.1.0/src/lib.rs -------------------------------------------------------------------------------- Ir -- line 71 ---------------------------------------- . fn default() -> FxHasher { . FxHasher { hash: 0 } . } . } . . impl FxHasher { . #[inline] . fn add_to_hash(&mut self, i: usize) { 100,797 ( 0.04%) self.hash = self.hash.rotate_left(5).bitxor(i).wrapping_mul(K); . } . } . . impl Hasher for FxHasher { . #[inline] 5,298 ( 0.00%) fn write(&mut self, mut bytes: &[u8]) { . #[cfg(target_pointer_width = "32")] . let read_usize = |bytes: &[u8]| u32::from_ne_bytes(bytes[..4].try_into().unwrap()); . #[cfg(target_pointer_width = "64")] . let read_usize = |bytes: &[u8]| u64::from_ne_bytes(bytes[..8].try_into().unwrap()); . 24,621 ( 0.01%) let mut hash = FxHasher { hash: self.hash }; . assert!(size_of::() <= 8); 372,807 ( 0.14%) while bytes.len() >= size_of::() { . hash.add_to_hash(read_usize(bytes) as usize); . bytes = &bytes[size_of::()..]; . } 49,764 ( 0.02%) if (size_of::() > 4) && (bytes.len() >= 4) { . hash.add_to_hash(u32::from_ne_bytes(bytes[..4].try_into().unwrap()) as usize); . bytes = &bytes[4..]; . } 49,764 ( 0.02%) if (size_of::() > 2) && bytes.len() >= 2 { . hash.add_to_hash(u16::from_ne_bytes(bytes[..2].try_into().unwrap()) as usize); . bytes = &bytes[2..]; . } 52,458 ( 0.02%) if (size_of::() > 1) && bytes.len() >= 1 { 11,833 ( 0.00%) hash.add_to_hash(bytes[0] as usize); . } 5,422 ( 0.00%) self.hash = hash.hash; 5,298 ( 0.00%) } . . #[inline] . fn write_u8(&mut self, i: u8) { 2,774 ( 0.00%) self.add_to_hash(i as usize); . } . . #[inline] . fn write_u16(&mut self, i: u16) { 1 ( 0.00%) self.add_to_hash(i as usize); . } . . #[inline] . fn write_u32(&mut self, i: u32) { 289,599 ( 0.11%) self.add_to_hash(i as usize); . } . . #[cfg(target_pointer_width = "32")] . #[inline] . fn write_u64(&mut self, i: u64) { . self.add_to_hash(i as usize); . self.add_to_hash((i >> 32) as usize); . } -- line 131 ---------------------------------------- 276 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/mod.rs -------------------------------------------------------------------------------- Ir -- line 141 ---------------------------------------- . /// ``` . /// let a = [1, 2, 3]; . /// assert!(!a.is_empty()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_slice_is_empty", since = "1.39.0")] . #[inline] . pub const fn is_empty(&self) -> bool { 76,061 ( 0.03%) self.len() == 0 . } . . /// Returns the first element of the slice, or `None` if it is empty. . /// . /// # Examples . /// . /// ``` . /// let v = [10, 40, 30]; -- line 157 ---------------------------------------- -- line 159 ---------------------------------------- . /// . /// let w: &[i32] = &[]; . /// assert_eq!(None, w.first()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")] . #[inline] . pub const fn first(&self) -> Option<&T> { 11 ( 0.00%) if let [first, ..] = self { Some(first) } else { None } . } . . /// Returns a mutable pointer to the first element of the slice, or `None` if it is empty. . /// . /// # Examples . /// . /// ``` . /// let x = &mut [0, 1, 2]; -- line 175 ---------------------------------------- -- line 237 ---------------------------------------- . /// assert_eq!(last, &2); . /// assert_eq!(elements, &[0, 1]); . /// } . /// ``` . #[stable(feature = "slice_splits", since = "1.5.0")] . #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")] . #[inline] . pub const fn split_last(&self) -> Option<(&T, &[T])> { 116 ( 0.00%) if let [init @ .., last] = self { Some((last, init)) } else { None } . } . . /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty. . /// . /// # Examples . /// . /// ``` . /// let x = &mut [0, 1, 2]; -- line 253 ---------------------------------------- -- line 276 ---------------------------------------- . /// . /// let w: &[i32] = &[]; . /// assert_eq!(None, w.last()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")] . #[inline] . pub const fn last(&self) -> Option<&T> { 86,048 ( 0.03%) if let [.., last] = self { Some(last) } else { None } . } . . /// Returns a mutable pointer to the last item in the slice. . /// . /// # Examples . /// . /// ``` . /// let x = &mut [0, 1, 2]; -- line 292 ---------------------------------------- -- line 295 ---------------------------------------- . /// *last = 10; . /// } . /// assert_eq!(x, &[0, 1, 10]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")] . #[inline] . pub const fn last_mut(&mut self) -> Option<&mut T> { 6,680 ( 0.00%) if let [.., last] = self { Some(last) } else { None } . } . . /// Returns a reference to an element or subslice depending on the type of . /// index. . /// . /// - If given a position, returns a reference to the element at that . /// position or `None` if out of bounds. . /// - If given a range, returns the subslice corresponding to that range, -- line 311 ---------------------------------------- -- line 448 ---------------------------------------- . /// } . /// ``` . /// . /// [`as_mut_ptr`]: slice::as_mut_ptr . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_slice_as_ptr", since = "1.32.0")] . #[inline] . pub const fn as_ptr(&self) -> *const T { 44,251 ( 0.02%) self as *const [T] as *const T . } . . /// Returns an unsafe mutable pointer to the slice's buffer. . /// . /// The caller must ensure that the slice outlives the pointer this . /// function returns, or else it will end up pointing to garbage. . /// . /// Modifying the container referenced by this slice may cause its buffer -- line 464 ---------------------------------------- -- line 476 ---------------------------------------- . /// } . /// } . /// assert_eq!(x, &[3, 4, 6]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")] . #[inline] . pub const fn as_mut_ptr(&mut self) -> *mut T { 2 ( 0.00%) self as *mut [T] as *mut T . } . . /// Returns the two raw pointers spanning the slice. . /// . /// The returned range is half-open, which means that the end pointer . /// points *one past* the last element of the slice. This way, an empty . /// slice is represented by two equal pointers, and the difference between . /// the two pointers represents the size of the slice. -- line 492 ---------------------------------------- -- line 582 ---------------------------------------- . /// v.swap(2, 4); . /// assert!(v == ["a", "b", "e", "d", "c"]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_swap", issue = "83163")] . #[inline] . #[track_caller] . pub const fn swap(&mut self, a: usize, b: usize) { 2,768 ( 0.00%) let _ = &self[a]; 2,899 ( 0.00%) let _ = &self[b]; . . // SAFETY: we just checked that both `a` and `b` are in bounds . unsafe { self.swap_unchecked(a, b) } . } . . /// Swaps two elements in the slice, without doing bounds checking. . /// . /// For a safe alternative see [`swap`]. -- line 599 ---------------------------------------- -- line 677 ---------------------------------------- . . // Because this function is first compiled in isolation, . // this check tells LLVM that the indexing below is . // in-bounds. Then after inlining -- once the actual . // lengths of the slices are known -- it's removed. . let (a, b) = (&mut a[..n], &mut b[..n]); . . for i in 0..n { 286 ( 0.00%) mem::swap(&mut a[i], &mut b[n - 1 - i]); . } . } . } . . /// Returns an iterator over the slice. . /// . /// # Examples . /// -- line 693 ---------------------------------------- -- line 1499 ---------------------------------------- . /// assert_eq!(left, [1, 2, 3, 4, 5, 6]); . /// assert_eq!(right, []); . /// } . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . #[track_caller] . pub fn split_at(&self, mid: usize) -> (&[T], &[T]) { 162 ( 0.00%) assert!(mid <= self.len()); . // SAFETY: `[ptr; mid]` and `[mid; len]` are inside `self`, which . // fulfills the requirements of `from_raw_parts_mut`. . unsafe { self.split_at_unchecked(mid) } . } . . /// Divides one mutable slice into two at an index. . /// . /// The first will contain all indices from `[0, mid)` (excluding -- line 1515 ---------------------------------------- -- line 1530 ---------------------------------------- . /// left[1] = 2; . /// right[1] = 4; . /// assert_eq!(v, [1, 2, 3, 4, 5, 6]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . #[track_caller] . pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) { 360 ( 0.00%) assert!(mid <= self.len()); . // SAFETY: `[ptr; mid]` and `[mid; len]` are inside `self`, which . // fulfills the requirements of `from_raw_parts_mut`. . unsafe { self.split_at_mut_unchecked(mid) } . } . . /// Divides one slice into two at an index, without doing bounds checking. . /// . /// The first will contain all indices from `[0, mid)` (excluding -- line 1546 ---------------------------------------- -- line 1628 ---------------------------------------- . pub unsafe fn split_at_mut_unchecked(&mut self, mid: usize) -> (&mut [T], &mut [T]) { . let len = self.len(); . let ptr = self.as_mut_ptr(); . . // SAFETY: Caller has to check that `0 <= mid <= self.len()`. . // . // `[ptr; mid]` and `[mid; len]` are not overlapping, so returning a mutable reference . // is fine. 90 ( 0.00%) unsafe { (from_raw_parts_mut(ptr, mid), from_raw_parts_mut(ptr.add(mid), len - mid)) } . } . . /// Divides one slice into an array and a remainder slice at an index. . /// . /// The array will contain all indices from `[0, N)` (excluding . /// the index `N` itself) and the slice will contain all . /// indices from `[N, len)` (excluding the index `len` itself). . /// -- line 1644 ---------------------------------------- -- line 2113 ---------------------------------------- . /// assert!(!v.iter().any(|e| e == "hi")); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . pub fn contains(&self, x: &T) -> bool . where . T: PartialEq, . { 12 ( 0.00%) cmp::SliceContains::slice_contains(x, self) . } . . /// Returns `true` if `needle` is a prefix of the slice. . /// . /// # Examples . /// . /// ``` . /// let v = [10, 40, 30]; -- line 2129 ---------------------------------------- -- line 2142 ---------------------------------------- . /// assert!(v.starts_with(&[])); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn starts_with(&self, needle: &[T]) -> bool . where . T: PartialEq, . { . let n = needle.len(); 707 ( 0.00%) self.len() >= n && needle == &self[..n] . } . . /// Returns `true` if `needle` is a suffix of the slice. . /// . /// # Examples . /// . /// ``` . /// let v = [10, 40, 30]; -- line 2158 ---------------------------------------- -- line 2171 ---------------------------------------- . /// assert!(v.ends_with(&[])); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn ends_with(&self, needle: &[T]) -> bool . where . T: PartialEq, . { . let (m, n) = (self.len(), needle.len()); 550 ( 0.00%) m >= n && needle == &self[m - n..] . } . . /// Returns a subslice with the prefix removed. . /// . /// If the slice starts with `prefix`, returns the subslice after the prefix, wrapped in `Some`. . /// If `prefix` is empty, simply returns the original slice. . /// . /// If the slice does not start with `prefix`, returns `None`. -- line 2187 ---------------------------------------- -- line 2293 ---------------------------------------- . /// s.insert(idx, num); . /// assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn binary_search(&self, x: &T) -> Result . where . T: Ord, . { 3 ( 0.00%) self.binary_search_by(|p| p.cmp(x)) . } . . /// Binary searches this sorted slice with a comparator function. . /// . /// The comparator function should implement an order consistent . /// with the sort order of the underlying slice, returning an . /// order code that indicates whether its argument is `Less`, . /// `Equal` or `Greater` the desired target. -- line 2309 ---------------------------------------- -- line 2345 ---------------------------------------- . #[inline] . pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result . where . F: FnMut(&'a T) -> Ordering, . { . let mut size = self.len(); . let mut left = 0; . let mut right = size; 255,081 ( 0.09%) while left < right { 226,781 ( 0.08%) let mid = left + size / 2; . . // SAFETY: the call is made safe by the following invariants: . // - `mid >= 0` . // - `mid < size`: `mid` is limited by `[left; right)` bound. 40,332 ( 0.01%) let cmp = f(unsafe { self.get_unchecked(mid) }); . . // The reason why we use if/else control flow rather than match . // is because match reorders comparison operations, which is perf sensitive. . // This is x86 asm for u8: https://rust.godbolt.org/z/8Y8Pra. 58,822 ( 0.02%) if cmp == Less { 85,160 ( 0.03%) left = mid + 1; 39,318 ( 0.01%) } else if cmp == Greater { . right = mid; . } else { . // SAFETY: same as the `get_unchecked` above . unsafe { crate::intrinsics::assume(mid < self.len()) }; . return Ok(mid); . } . 174,555 ( 0.06%) size = right - left; . } . Err(left) . } . . /// Binary searches this sorted slice with a key extraction function. . /// . /// Assumes that the slice is sorted by the key, for instance with . /// [`sort_by_key`] using the same key extraction function. -- line 2382 ---------------------------------------- -- line 3203 ---------------------------------------- . #[track_caller] . fn len_mismatch_fail(dst_len: usize, src_len: usize) -> ! { . panic!( . "source slice length ({}) does not match destination slice length ({})", . src_len, dst_len, . ); . } . 1,630 ( 0.00%) if self.len() != src.len() { . len_mismatch_fail(self.len(), src.len()); . } . . // SAFETY: `self` is valid for `self.len()` elements by definition, and `src` was . // checked to have the same length. The slices cannot overlap because . // mutable references are exclusive. . unsafe { . ptr::copy_nonoverlapping(src.as_ptr(), self.as_mut_ptr(), self.len()); -- line 3219 ---------------------------------------- -- line 3382 ---------------------------------------- . } . let gcd: usize = gcd(mem::size_of::(), mem::size_of::()); . let ts: usize = mem::size_of::() / gcd; . let us: usize = mem::size_of::() / gcd; . . // Armed with this knowledge, we can find how many `U`s we can fit! . let us_len = self.len() / ts * us; . // And how many `T`s will be in the trailing slice! 470 ( 0.00%) let ts_len = self.len() % ts; . (us_len, ts_len) . } . . /// Transmute the slice to a slice of another type, ensuring alignment of the types is . /// maintained. . /// . /// This method splits the slice into three distinct slices: prefix, correctly aligned middle . /// slice of a new type, and the suffix slice. The method may make the middle slice the greatest -- line 3398 ---------------------------------------- -- line 3429 ---------------------------------------- . return (self, &[], &[]); . } . . // First, find at what point do we split between the first and 2nd slice. Easy with . // ptr.align_offset. . let ptr = self.as_ptr(); . // SAFETY: See the `align_to_mut` method for the detailed safety comment. . let offset = unsafe { crate::ptr::align_offset(ptr, mem::align_of::()) }; 470 ( 0.00%) if offset > self.len() { . (self, &[], &[]) . } else { . let (left, rest) = self.split_at(offset); . let (us_len, ts_len) = rest.align_to_offsets::(); . // SAFETY: now `rest` is definitely aligned, so `from_raw_parts` below is okay, . // since the caller guarantees that we can transmute `T` to `U` safely. . unsafe { . ( . left, . from_raw_parts(rest.as_ptr() as *const U, us_len), 470 ( 0.00%) from_raw_parts(rest.as_ptr().add(rest.len() - ts_len), ts_len), . ) . } . } . } . . /// Transmute the slice to a slice of another type, ensuring alignment of the types is . /// maintained. . /// -- line 3456 ---------------------------------------- 164,795 ( 0.06%) -------------------------------------------------------------------------------- -- 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) { 62 ( 0.00%) let old = self.replace(val); 44 ( 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. 8,433 ( 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 { 46,635 ( 0.02%) 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,568 ( 0.00%) RefCell { 2,158 ( 0.00%) 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. 52 ( 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] 72 ( 0.00%) pub fn borrow(&self) -> Ref<'_, T> { . self.try_borrow().expect("already mutably borrowed") 216 ( 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] 5,654 ( 0.00%) pub fn borrow_mut(&self) -> RefMut<'_, T> { . self.try_borrow_mut().expect("already borrowed") 16,962 ( 0.01%) } . . /// 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. 44 ( 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> { 74,812 ( 0.03%) let b = borrow.get().wrapping_add(1); 42,164 ( 0.02%) 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) { 38,085 ( 0.01%) let borrow = self.borrow.get(); . debug_assert!(is_reading(borrow)); 76,507 ( 0.03%) 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) { 278,315 ( 0.10%) let borrow = self.borrow.get(); . debug_assert!(is_writing(borrow)); 523,114 ( 0.19%) 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. 563,980 ( 0.21%) 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 { 9 ( 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! 221,708 ( 0.08%) 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 ---------------------------------------- 429,300 ( 0.16%) -------------------------------------------------------------------------------- -- 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")] 6 ( 0.00%) pub fn from_str_radix(src: &str, radix: u32) -> Result { 3 ( 0.00%) from_str_radix(src, radix) 9 ( 0.00%) } . . /// Returns the number of ones in the binary representation of `self`. . /// . /// # Examples . /// . /// Basic usage: . /// . /// ``` -- line 75 ---------------------------------------- -- line 80 ---------------------------------------- . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_math", since = "1.32.0")] . #[doc(alias = "popcount")] . #[doc(alias = "popcnt")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn count_ones(self) -> u32 { 4,125 ( 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 { 24,024 ( 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 { 82,133 ( 0.03%) 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 { 857,696 ( 0.31%) 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 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`. 90,097 ( 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`. 505 ( 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 136 ( 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 { 44,856 ( 0.02%) 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 { 60,409 ( 0.02%) 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 { 597,246 ( 0.22%) 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 { 342,622 ( 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 { 640,845 ( 0.23%) 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 1492 ---------------------------------------- . #[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)] . pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) { 305,830 ( 0.11%) let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT); . (a as Self, b) . } . . /// 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. -- line 1508 ---------------------------------------- -- line 1588 ---------------------------------------- . #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));")] . /// ``` . #[stable(feature = "wrapping", since = "1.7.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) { 27,743 ( 0.01%) let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT); . (a as Self, b) . } . . /// Calculates `self - rhs - borrow` without the ability to overflow. . /// . /// Performs "ternary subtraction" which takes in an extra bit to subtract, and may return . /// an additional bit of overflow. This allows for chaining together multiple subtractions . /// to create "big integers" which represent larger values. -- line 1604 ---------------------------------------- -- line 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) { 88,479 ( 0.03%) 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 { 36 ( 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 { 212 ( 0.00%) if self <= 1 { return 0; } . 780 ( 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. 2,339 ( 0.00%) let z = unsafe { intrinsics::ctlz_nonzero(p) }; 781 ( 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 { 1,348 ( 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 ---------------------------------------- 2,746 ( 0.00%) -------------------------------------------------------------------------------- -- 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 { 301 ( 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 344 ( 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 { 43,851 ( 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 { 48,476 ( 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 { 1,528 ( 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 { 108,255 ( 0.04%) 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 ] . 48 ( 0.00%) if self.tail <= self.head { . // A . // Nop . } else if self.head < old_capacity - self.tail { . // B . unsafe { . self.copy_nonoverlapping(old_capacity, 0, self.head); . } . self.head += old_capacity; -- line 468 ---------------------------------------- -- 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 { 90 ( 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 { 50 ( 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")] 280 ( 0.00%) pub fn with_capacity_in(capacity: usize, alloc: A) -> VecDeque { 206 ( 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(); . 426 ( 0.00%) VecDeque { tail: 0, head: 0, buf: RawVec::with_capacity_in(cap, alloc) } 420 ( 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> { 165,791 ( 0.06%) 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> { 89,074 ( 0.03%) 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 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")] 24 ( 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 { 6 ( 0.00%) if len > self.len() { . return; . } . let num_dropped = self.len() - len; . let (front, back) = self.as_mut_slices(); 6 ( 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 _; 3 ( 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); . } . } 24 ( 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 { 164 ( 0.00%) let head = self.head; 164 ( 0.00%) let tail = self.tail; 181 ( 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 { 74,897 ( 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 { 148,317 ( 0.05%) 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) { 6 ( 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> { 2,735 ( 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 { 23,765 ( 0.01%) if self.is_empty() { . None . } else { . let tail = self.tail; 45,485 ( 0.02%) self.tail = self.wrap_add(self.tail, 1); 529 ( 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 { 13,058 ( 0.00%) if self.is_empty() { . None . } else { 20,639 ( 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")] 87,572 ( 0.03%) pub fn push_back(&mut self, value: T) { 108,253 ( 0.04%) if self.is_full() { 22 ( 0.00%) self.grow(); . } . 12 ( 0.00%) let head = self.head; 36,096 ( 0.01%) self.head = self.wrap_add(self.head, 1); 14,191 ( 0.01%) unsafe { self.buffer_write(head, value) } 87,572 ( 0.03%) } . . #[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)] 72 ( 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(); 36 ( 0.00%) self.buf.reserve_exact(old_cap, old_cap); 60 ( 0.00%) assert!(self.cap() == old_cap * 2); . unsafe { . self.handle_capacity_increase(old_cap); . } . debug_assert!(!self.is_full()); 72 ( 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()); 189,349 ( 0.07%) 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 312,680 ( 0.11%) (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 { 168 ( 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() { 89 ( 0.00%) if self.len() == self.capacity() { . let (lower, _) = iter.size_hint(); . self.reserve(lower.saturating_add(1)); . } . . let head = self.head; 18 ( 0.00%) self.head = self.wrap_add(self.head, 1); . unsafe { 16 ( 0.00%) self.buffer_write(head, element); . } . } 192 ( 0.00%) } . . #[inline] . fn extend_one(&mut self, elem: T) { . self.push_back(elem); . } . . #[inline] . fn extend_reserve(&mut self, additional: usize) { -- line 2937 ---------------------------------------- 46,655 ( 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> { 2 ( 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`. 2 ( 0.00%) if ty.is_never() { . assert!( . !self.typeck_results.borrow().adjustments().contains_key(expr.hir_id), . "expression with never type wound up being adjusted" . ); . let adj_ty = self.next_ty_var(TypeVariableOrigin { . kind: TypeVariableOriginKind::AdjustmentType, . span: expr.span, . }); . self.apply_adjustments( . expr, . vec![Adjustment { kind: Adjust::NeverToAny, target: adj_ty }], . ); . ty = adj_ty; . } . 18 ( 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 . } . 25,011 ( 0.01%) 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) 19,453 ( 0.01%) } . . pub(super) fn check_expr_with_hint( . &self, . expr: &'tcx hir::Expr<'tcx>, . expected: Ty<'tcx>, . ) -> Ty<'tcx> { 6 ( 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. 2 ( 0.00%) if let Needs::MutPlace = needs { . 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 140 ---------------------------------------- -- 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> { 23,687 ( 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`. 54,574 ( 0.02%) 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> { 16,792 ( 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. 8,396 ( 0.00%) let is_try_block_generated_unit_expr = match expr.kind { 20 ( 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 { 29,386 ( 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); . 8,458 ( 0.00%) let ty = ensure_sufficient_stack(|| match &expr.kind { . hir::ExprKind::Path( . qpath @ hir::QPath::Resolved(..) | qpath @ hir::QPath::TypeRelative(..), 186 ( 0.00%) ) => self.check_expr_path(qpath, expr, args), 20,835 ( 0.01%) _ => self.check_expr_kind(expr, expected), . }); . . // Warn for non-block expressions with diverging children. 16,792 ( 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. 20 ( 0.00%) ExprKind::Call(..) if expr.span.is_desugaring(DesugaringKind::TryBlock) => {} 20 ( 0.00%) ExprKind::Call(callee, _) => self.warn_if_unreachable(expr.hir_id, callee.span, "call"), 2 ( 0.00%) ExprKind::MethodCall(segment, ..) => { 6 ( 0.00%) self.warn_if_unreachable(expr.hir_id, segment.ident.span, "call") . } 25,086 ( 0.01%) _ => self.warn_if_unreachable(expr.hir_id, expr.span, "expression"), . } . . // Any expression that produces a value of type `!` must have diverged 4,198 ( 0.00%) if ty.is_never() { . 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. 20,990 ( 0.01%) self.write_ty(expr.hir_id, ty); . . // Combine the diverging and has_error flags. . self.diverges.set(self.diverges.get() | old_diverges); 4,198 ( 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 37,782 ( 0.01%) } . 82,935 ( 0.03%) #[instrument(skip(self, expr), level = "debug")] . fn check_expr_kind( . &self, . expr: &'tcx hir::Expr<'tcx>, . expected: Expectation<'tcx>, . ) -> Ty<'tcx> { . trace!("expr={:#?}", expr); . 4,167 ( 0.00%) let tcx = self.tcx; 25,002 ( 0.01%) match expr.kind { . ExprKind::Box(subexpr) => self.check_expr_box(subexpr, expected), . ExprKind::Lit(ref lit) => self.check_lit(&lit, expected), 392 ( 0.00%) ExprKind::Binary(op, lhs, rhs) => self.check_binop(expr, op, lhs, rhs), . ExprKind::Assign(lhs, rhs, ref span) => { . self.check_expr_assign(expr, expected, lhs, rhs, span) . } . ExprKind::AssignOp(op, lhs, rhs) => self.check_binop_assign(expr, op, lhs, rhs), . ExprKind::Unary(unop, oprnd) => self.check_expr_unary(unop, oprnd, expected, expr), 18 ( 0.00%) ExprKind::AddrOf(kind, mutbl, oprnd) => { . self.check_expr_addr_of(kind, mutbl, oprnd, expected, expr) . } . 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) => { -- line 285 ---------------------------------------- -- line 296 ---------------------------------------- . ExprKind::Ret(ref expr_opt) => self.check_expr_return(expr_opt.as_deref(), expr), . ExprKind::Let(let_expr) => self.check_expr_let(let_expr), . ExprKind::Loop(body, _, source, _) => { . self.check_expr_loop(body, source, expected, expr) . } . ExprKind::Match(discrim, arms, match_src) => { . self.check_match(expr, &discrim, arms, expected, match_src) . } 3 ( 0.00%) ExprKind::Closure(capture, decl, body_id, _, gen) => { 12 ( 0.00%) self.check_expr_closure(expr, capture, &decl, body_id, gen, expected) . } 99 ( 0.00%) ExprKind::Block(body, _) => self.check_block_with_expected(&body, expected), 32 ( 0.00%) ExprKind::Call(callee, args) => self.check_call(expr, &callee, args, expected), 2 ( 0.00%) ExprKind::MethodCall(segment, args, _) => { . self.check_method_call(expr, segment, args, expected) . } . 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 . } 10 ( 0.00%) ExprKind::If(cond, then_expr, opt_else_expr) => { 2 ( 0.00%) self.check_then_else(cond, then_expr, opt_else_expr, expr.span, expected) . } 2 ( 0.00%) ExprKind::DropTemps(e) => self.check_expr_with_expectation(e, expected), 4 ( 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) . } 4,101 ( 0.00%) ExprKind::Tup(elts) => self.check_expr_tuple(elts, expected, expr), . ExprKind::Struct(qpath, fields, ref base_expr) => { . self.check_expr_struct(expr, expected, qpath, fields, base_expr) . } . ExprKind::Field(base, field) => self.check_field(expr, &base, field), . 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(), . } -- line 337 ---------------------------------------- -- 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| { 10 ( 0.00%) match ty.kind() { . ty::Ref(_, ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) => { 8 ( 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 { 12 ( 0.00%) Expectation::rvalue_hint(self, ty) . } . } . _ => NoExpectation, . } 6 ( 0.00%) }); . let ty = . self.check_expr_with_expectation_and_needs(&oprnd, hint, Needs::maybe_mut_place(mutbl)); . . let tm = ty::TypeAndMut { ty, mutbl }; 2 ( 0.00%) match kind { 2 ( 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. 10 ( 0.00%) let region = self.next_region_var(infer::AddrOfRegion(expr.span)); 2 ( 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 492 ---------------------------------------- . &self, . lang_item: hir::LangItem, . expr: &'tcx hir::Expr<'tcx>, . hir_id: Option, . ) -> Ty<'tcx> { . self.resolve_lang_item_path(lang_item, expr.span, expr.hir_id, hir_id).1 . } . 341 ( 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> { 31 ( 0.00%) let tcx = self.tcx; 341 ( 0.00%) let (res, opt_ty, segs) = 310 ( 0.00%) self.resolve_ty_and_res_fully_qualified_call(qpath, expr.hir_id, expr.span); 142 ( 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() . } 558 ( 0.00%) _ => self.instantiate_value_path(segs, opt_ty, res, expr.span, expr.hir_id).0, . }; . 93 ( 0.00%) if let ty::FnDef(..) = ty.kind() { 12 ( 0.00%) let fn_sig = ty.fn_sig(tcx); 16 ( 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. 6 ( 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; 24 ( 0.00%) self.require_type_is_sized_deferred( . input, . span, 18 ( 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; 24 ( 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. 124 ( 0.00%) let substs = self.typeck_results.borrow().node_substs(expr.hir_id); . self.add_wf_bounds(substs, expr); . . ty 248 ( 0.00%) } . . fn check_expr_break( . &self, . destination: hir::Destination, . expr_opt: Option<&'tcx hir::Expr<'tcx>>, . expr: &'tcx hir::Expr<'tcx>, . ) -> Ty<'tcx> { . let tcx = self.tcx; -- line 582 ---------------------------------------- -- line 791 ---------------------------------------- . coercion.coerce_forced_unit(self, &cause, &mut |_| (), true); . } . } . 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. 48 ( 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); 6 ( 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 12 ( 0.00%) if !explicit_return { 18 ( 0.00%) if let ExprKind::Block(body, _) = return_expr.kind { 18 ( 0.00%) if let Some(last_expr) = body.expr { 6 ( 0.00%) span = last_expr.span; . } . } . } . ret_coercion.borrow_mut().coerce( . self, 12 ( 0.00%) &self.cause(span, ObligationCauseCode::ReturnValue(return_expr.hir_id)), . return_expr, . return_expr_ty, . ); 48 ( 0.00%) } . . pub(crate) fn check_lhs_assignable( . &self, . lhs: &'tcx hir::Expr<'tcx>, . err_code: &'static str, . op_span: Span, . ) { . if lhs.is_syntactic_place_expr() { -- line 834 ---------------------------------------- -- line 894 ---------------------------------------- . 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, |_| {}); . 10 ( 0.00%) self.warn_if_unreachable( 4 ( 0.00%) cond_expr.hir_id, 2 ( 0.00%) then_expr.span, . "block in `if` or `while` expression", . ); . 4 ( 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); . 4 ( 0.00%) if let Some(else_expr) = opt_else_expr { 4 ( 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 = 16 ( 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). 34 ( 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); . } . 26 ( 0.00%) let result_ty = coerce.complete(self); 2 ( 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>, -- line 975 ---------------------------------------- -- line 1095 ---------------------------------------- . /// 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> { 4 ( 0.00%) let rcvr = &args[0]; . let rcvr_t = self.check_expr(&rcvr); . // no need to check for bot/err -- callee does that 8 ( 0.00%) let rcvr_t = self.structurally_resolved_type(args[0].span, rcvr_t); 2 ( 0.00%) let span = segment.ident.span; . 32 ( 0.00%) let method = match self.lookup_method(rcvr_t, segment, span, expr, rcvr, args) { 4 ( 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. . 22 ( 0.00%) self.write_method_call(expr.hir_id, method); 10 ( 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. 28 ( 0.00%) self.check_method_argument_types( . span, . expr, 12 ( 0.00%) method, . &args[1..], . DontTupleArguments, . expected, . ) . } . . fn check_expr_cast( . &self, -- line 1146 ---------------------------------------- -- line 1176 ---------------------------------------- . } . . fn check_expr_array( . &self, . args: &'tcx [hir::Expr<'tcx>], . expected: Expectation<'tcx>, . expr: &'tcx hir::Expr<'tcx>, . ) -> Ty<'tcx> { 2 ( 0.00%) let element_ty = if !args.is_empty() { 6 ( 0.00%) let coerce_to = expected . .to_option(self) 6 ( 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); 2 ( 0.00%) assert_eq!(self.diverges.get(), Diverges::Maybe); . for e in args { . let e_ty = self.check_expr_with_hint(e, coerce_to); 1,366 ( 0.00%) let cause = self.misc(e.span); 8,196 ( 0.00%) coerce.coerce(self, &cause, e, e_ty); . } 24 ( 0.00%) coerce.complete(self) . } else { . self.next_ty_var(TypeVariableOrigin { . kind: TypeVariableOriginKind::TypeInference, . span: expr.span, . }) . }; 12 ( 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> { 2,734 ( 0.00%) let flds = expected.only_has_type(self).and_then(|ty| { 1,367 ( 0.00%) let ty = self.resolve_vars_with_obligations(ty); 2,734 ( 0.00%) match ty.kind() { 1,367 ( 0.00%) ty::Tuple(flds) => Some(&flds[..]), . _ => None, . } . }); . 9,571 ( 0.00%) let elt_ts_iter = elts.iter().enumerate().map(|(i, e)| match flds { 5,470 ( 0.00%) Some(fs) if i < fs.len() => { 9,568 ( 0.00%) let ety = fs[i].expect_ty(); 17,773 ( 0.01%) self.check_expr_coercable_to_type(&e, ety, None); . ety . } . _ => self.check_expr_with_expectation(&e, NoExpectation), . }); 2,734 ( 0.00%) let tuple = self.tcx.mk_tup(elt_ts_iter); 1,367 ( 0.00%) if tuple.references_error() { . self.tcx.ty_error() . } else { 9,569 ( 0.00%) self.require_type_is_sized(tuple, expr.span, traits::TupleInitializerSized); . tuple . } . } . . fn check_expr_struct( . &self, . expr: &hir::Expr<'_>, . expected: Expectation<'tcx>, -- line 1306 ---------------------------------------- 40,479 ( 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);)*) => { 545 ( 0.00%) $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> { . self.opaque.$name(value) 654 ( 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 { 68 ( 0.00%) e.emit_lazy_distance(*self) . } . } . . impl<'a, 'tcx, T: Encodable>> Encodable> . for Lazy<[T]> . { 15 ( 0.00%) fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { . e.emit_usize(self.meta)?; 48 ( 0.00%) if self.meta == 0 { . return Ok(()); . } 85 ( 0.00%) e.emit_lazy_distance(*self) 12 ( 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 { 266 ( 0.00%) fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { 260 ( 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()) 228 ( 0.00%) } . } . . impl<'a, 'tcx> Encodable> for DefIndex { 170 ( 0.00%) fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { . s.emit_u32(self.as_u32()) 204 ( 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 { 43,390 ( 0.02%) fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { 26,034 ( 0.01%) rustc_span::hygiene::raw_encode_syntax_context(*self, &s.hygiene_ctxt, s) 52,068 ( 0.02%) } . } . . impl<'a, 'tcx> Encodable> for ExpnId { . fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { 33 ( 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. 116 ( 0.00%) s.hygiene_ctxt.schedule_expn_data_for_encoding(*self); . } 80 ( 0.00%) self.krate.encode(s)?; . self.local_id.encode(s) . } . } . . impl<'a, 'tcx> Encodable> for Span { 69,328 ( 0.03%) fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { 51,996 ( 0.02%) 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. 17,332 ( 0.01%) if s.is_proc_macro { . SyntaxContext::root().encode(s)?; . } else { 8,666 ( 0.00%) span.ctxt.encode(s)?; . } . 8,666 ( 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); . 43,209 ( 0.02%) if !s.source_file_cache.0.contains(span.lo) { 14 ( 0.00%) let source_map = s.tcx.sess.source_map(); 28 ( 0.00%) let source_file_index = source_map.lookup_source_file_idx(span.lo); 14 ( 0.00%) s.source_file_cache = 28 ( 0.00%) (source_map.files()[source_file_index].clone(), source_file_index); . } . 25,957 ( 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` 8,643 ( 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. 51,858 ( 0.02%) 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' -- line 290 ---------------------------------------- -- line 296 ---------------------------------------- . src => panic!("Unexpected external source {:?}", src), . } . }; . let lo = (span.lo - s.source_file_cache.0.start_pos) + external_start_pos; . let hi = (span.hi - s.source_file_cache.0.start_pos) + external_start_pos; . . (TAG_VALID_SPAN_FOREIGN, lo, hi) . } else { 25,929 ( 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)?; . 17,286 ( 0.01%) 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)` . let cnum = s.source_file_cache.0.cnum; . cnum.encode(s)?; . } . . Ok(()) 69,328 ( 0.03%) } . } . . 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 { 209 ( 0.00%) fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) { 126 ( 0.00%) self.encode(ecx).unwrap() 6 ( 0.00%) } . } . . impl<'a, 'tcx, T: Encodable>> EncodeContentsForLazy<'a, 'tcx, T> for T { 549 ( 0.00%) fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) { 249 ( 0.00%) self.encode(ecx).unwrap() 349 ( 0.00%) } . } . . impl<'a, 'tcx, I, T: Encodable>> EncodeContentsForLazy<'a, 'tcx, [T]> for I . where . I: IntoIterator, . I::Item: EncodeContentsForLazy<'a, 'tcx, T>, . { 21 ( 0.00%) fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> usize { 262 ( 0.00%) self.into_iter().map(|value| value.encode_contents_for_lazy(ecx)).count() 27 ( 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> { 310 ( 0.00%) fn emit_lazy_distance( . &mut self, . lazy: Lazy, . ) -> Result<(), ::Error> { . let pos = lazy.position.get(); 266 ( 0.00%) let distance = match self.lazy_state { . LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"), 22 ( 0.00%) LazyState::NodeStart(start) => { . let start = start.get(); 44 ( 0.00%) assert!(pos <= start); . start - pos . } 40 ( 0.00%) LazyState::Previous(last_pos) => { 40 ( 0.00%) assert!( . last_pos <= lazy.position, . "make sure that the calls to `lazy*` \ . are in the same order as the metadata fields", . ); 120 ( 0.00%) lazy.position.get() - last_pos.get() . } . }; 124 ( 0.00%) self.lazy_state = LazyState::Previous(NonZeroUsize::new(pos).unwrap()); . self.emit_usize(distance) 310 ( 0.00%) } . 244 ( 0.00%) fn lazy( . &mut self, . value: impl EncodeContentsForLazy<'a, 'tcx, T>, . ) -> Lazy { . let pos = NonZeroUsize::new(self.position()).unwrap(); . 331 ( 0.00%) assert_eq!(self.lazy_state, LazyState::NoNode); 951 ( 0.00%) self.lazy_state = LazyState::NodeStart(pos); 594 ( 0.00%) let meta = value.encode_contents_for_lazy(self); 394 ( 0.00%) self.lazy_state = LazyState::NoNode; . 691 ( 0.00%) assert!(pos.get() <= self.position()); . . Lazy::from_position_and_meta(pos, meta) 359 ( 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); 140 ( 0.00%) self.tables.def_keys.set(def_index, def_key); 140 ( 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` 629 ( 0.00%) required_source_files.contains(*idx) && . // Don't serialize imported `SourceFile`s, unless . // we're in a proc-macro crate. 9 ( 0.00%) (!source_file.is_imported() || self.is_proc_macro) . }) . .map(|(_, source_file)| { 6 ( 0.00%) let mut adapted = match source_file.name { . FileName::Real(ref realname) => { 4 ( 0.00%) let mut adapted = (**source_file).clone(); 32 ( 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. 4 ( 0.00%) let working_dir = &self.tcx.sess.opts.working_dir; 4 ( 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); 14 ( 0.00%) let (joined, remapped) = 22 ( 0.00%) source_map.path_mapping().map_prefix(joined); 4 ( 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(), . } . } . }); 4 ( 0.00%) adapted.name_hash = { . let mut hasher: StableHasher = StableHasher::new(); 2 ( 0.00%) adapted.name.hash(&mut hasher); . hasher.finish::() . }; 2 ( 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. 4 ( 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. 81 ( 0.00%) fn should_encode_mir(tcx: TyCtxt<'_>, def_id: LocalDefId) -> (bool, bool) { 45 ( 0.00%) match tcx.def_kind(def_id) { . // Constructors . DefKind::Ctor(_, _) => { . 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); 30 ( 0.00%) let needs_inline = (generics.requires_monomorphization(tcx) 10 ( 0.00%) || tcx.codegen_fn_attrs(def_id).requests_inline()) 6 ( 0.00%) && tcx.sess.opts.output_types.should_codegen(); . // The function has a `const` modifier or is annotated with `default_method_body_is_const`. 5 ( 0.00%) let is_const_fn = tcx.is_const_fn_raw(def_id.to_def_id()) 25 ( 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; 10 ( 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); 4 ( 0.00%) let needs_inline = (generics.requires_monomorphization(tcx) . || tcx.codegen_fn_attrs(def_id).requests_inline()) 2 ( 0.00%) && tcx.sess.opts.output_types.should_codegen(); . let always_encode_mir = tcx.sess.opts.debugging_opts.always_encode_mir; 2 ( 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), . } 81 ( 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); 210 ( 0.00%) let def_kind = if let Some(def_kind) = def_kind { def_kind } else { continue }; 448 ( 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, . }); 84 ( 0.00%) record!(self.tables.span[def_id] <- tcx.def_span(def_id)); 336 ( 0.00%) record!(self.tables.attributes[def_id] <- tcx.get_attrs(def_id)); 224 ( 0.00%) record!(self.tables.expn_that_defined[def_id] <- self.tcx.expn_that_defined(def_id)); . if should_encode_visibility(def_kind) { 150 ( 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); 90 ( 0.00%) self.encode_deprecation(def_id); . } . if should_encode_variances(def_kind) { 14 ( 0.00%) let v = self.tcx.variances_of(def_id); 49 ( 0.00%) record!(self.tables.variances[def_id] <- v); . } . if should_encode_generics(def_kind) { . let g = tcx.generics_of(def_id); 52 ( 0.00%) record!(self.tables.generics[def_id] <- g); 156 ( 0.00%) record!(self.tables.explicit_predicates[def_id] <- self.tcx.explicit_predicates_of(def_id)); 13 ( 0.00%) let inferred_outlives = self.tcx.inferred_outlives_of(def_id); 13 ( 0.00%) if !inferred_outlives.is_empty() { . record!(self.tables.inferred_outlives[def_id] <- inferred_outlives); . } . } 196 ( 0.00%) if let DefKind::Trait | DefKind::TraitAlias = def_kind { 14 ( 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() { . if implementations.is_empty() { . continue; . } . record!(self.tables.inherent_impls[def_id.to_def_id()] <- implementations.iter().map(|&def_id| { . assert!(def_id.is_local()); . def_id.index . })); . } . } . 84 ( 0.00%) fn encode_item_type(&mut self, def_id: DefId) { . debug!("EncodeContext::encode_item_type({:?})", def_id); 72 ( 0.00%) record!(self.tables.ty[def_id] <- self.tcx.type_of(def_id)); 96 ( 0.00%) } . . fn encode_enum_variant_info(&mut self, def: &ty::AdtDef, index: VariantIdx) { . let tcx = self.tcx; . let variant = &def.variants[index]; . let def_id = variant.def_id; . debug!("EncodeContext::encode_enum_variant_info({:?})", def_id); . . let data = VariantData { -- line 1043 ---------------------------------------- -- line 1078 ---------------------------------------- . . record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data))); . self.encode_item_type(def_id); . if variant.ctor_kind == CtorKind::Fn { . record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); . } . } . 30 ( 0.00%) fn encode_info_for_mod(&mut self, local_def_id: LocalDefId, md: &hir::Mod<'_>) { 6 ( 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. 9 ( 0.00%) let reexports = if !self.is_proc_macro { 6 ( 0.00%) match tcx.module_reexports(local_def_id) { . Some(exports) => self.lazy(exports), . _ => Lazy::empty(), . } . } else { . Lazy::empty() . }; . 12 ( 0.00%) record!(self.tables.kind[def_id] <- EntryKind::Mod(reexports)); 6 ( 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. 6 ( 0.00%) let tcx = self.tcx; . let foreign_item_children = md . .item_ids . .iter() 75 ( 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(); . 21 ( 0.00%) record!(self.tables.children[def_id] <- direct_children.chain(foreign_item_children)); . } 24 ( 0.00%) } . . fn encode_field( . &mut self, . adt_def: &ty::AdtDef, . variant_index: VariantIdx, . field_index: usize, . ) { . let variant = &adt_def.variants[variant_index]; -- line 1134 ---------------------------------------- -- 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); 2 ( 0.00%) let tcx = self.tcx; . 14 ( 0.00%) let ast_item = tcx.hir().expect_trait_item(def_id.expect_local()); . let trait_item = tcx.associated_item(def_id); . 10 ( 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"), . }; . 12 ( 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 => { 4 ( 0.00%) let fn_data = if let hir::TraitItemKind::Fn(m_sig, m) = &ast_item.kind { 4 ( 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); 6 ( 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); . } . } . } 2 ( 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); 4 ( 0.00%) let tcx = self.tcx; . 12 ( 0.00%) let ast_item = self.tcx.hir().expect_impl_item(def_id.expect_local()); 2 ( 0.00%) let impl_item = self.tcx.associated_item(def_id); . 8 ( 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)") . } . }; . 12 ( 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 => { 4 ( 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 2 ( 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)); . } . } 6 ( 0.00%) self.encode_ident_span(def_id, impl_item.ident(self.tcx)); 10 ( 0.00%) self.encode_item_type(def_id); 8 ( 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); . } 2 ( 0.00%) if impl_item.kind == ty::AssocKind::Fn { . record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); . } . } . 24 ( 0.00%) fn encode_fn_param_names_for_body(&mut self, body_id: hir::BodyId) -> Lazy<[Ident]> { 29 ( 0.00%) self.lazy(self.tcx.hir().body_param_names(body_id)) 24 ( 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| { 45 ( 0.00%) let (encode_const, encode_opt) = should_encode_mir(self.tcx, def_id); 45 ( 0.00%) if encode_const || encode_opt { 12 ( 0.00%) Some((def_id, encode_const, encode_opt)) . } else { . None . } 18 ( 0.00%) }) . .collect::>(); 35 ( 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); 6 ( 0.00%) if encode_opt { 12 ( 0.00%) record!(self.tables.mir[def_id.to_def_id()] <- self.tcx.optimized_mir(def_id)); . } 6 ( 0.00%) if encode_const { 12 ( 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` 3 ( 0.00%) let abstract_const = self.tcx.thir_abstract_const(def_id); 12 ( 0.00%) if let Ok(Some(abstract_const)) = abstract_const { . record!(self.tables.thir_abstract_consts[def_id.to_def_id()] <- abstract_const); . } . } 24 ( 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())); 6 ( 0.00%) let unused = self.tcx.unused_generic_params(instance); 6 ( 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. 120 ( 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. 105 ( 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) . } . } . } . 90 ( 0.00%) fn encode_deprecation(&mut self, def_id: DefId) { . debug!("EncodeContext::encode_deprecation({:?})", def_id); 75 ( 0.00%) if let Some(depr) = self.tcx.lookup_deprecation(def_id) { . record!(self.tables.deprecation[def_id] <- depr); . } 75 ( 0.00%) } . 18 ( 0.00%) fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> Lazy { 9 ( 0.00%) let hir = self.tcx.hir(); 6 ( 0.00%) let body = hir.body(body_id); 24 ( 0.00%) let rendered = rustc_hir_pretty::to_string(&(&hir as &dyn intravisit::Map<'_>), |s| { 9 ( 0.00%) s.print_expr(&body.value) . }); 6 ( 0.00%) let rendered_const = &RenderedConst(rendered); . self.lazy(rendered_const) 21 ( 0.00%) } . 90 ( 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); . 60 ( 0.00%) let entry_kind = match item.kind { . hir::ItemKind::Static(_, hir::Mutability::Mut, _) => EntryKind::MutStatic, . hir::ItemKind::Static(_, hir::Mutability::Not, _) => EntryKind::ImmStatic, 9 ( 0.00%) hir::ItemKind::Const(_, body_id) => { 9 ( 0.00%) let qualifs = self.tcx.at(item.span).mir_const_qualif(def_id); 21 ( 0.00%) EntryKind::Const(qualifs, self.encode_rendered_const_for_body(body_id)) . } 6 ( 0.00%) hir::ItemKind::Fn(ref sig, .., body) => { . let data = FnData { 3 ( 0.00%) asyncness: sig.header.asyncness, 3 ( 0.00%) constness: sig.header.constness, 6 ( 0.00%) param_names: self.encode_fn_param_names_for_body(body), . }; . . EntryKind::Fn(self.lazy(data)) . } . hir::ItemKind::Macro(ref macro_def) => { . EntryKind::MacroDef(self.lazy(macro_def.clone())) . } . hir::ItemKind::Mod(ref m) => { 24 ( 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 . } -- line 1433 ---------------------------------------- -- line 1462 ---------------------------------------- . ctor_kind: variant.ctor_kind, . discr: variant.discr, . ctor: None, . is_non_exhaustive: variant.is_field_list_non_exhaustive(), . }), . adt_def.repr, . ) . } 4 ( 0.00%) hir::ItemKind::Impl(hir::Impl { defaultness, constness, .. }) => { 4 ( 0.00%) let trait_ref = self.tcx.impl_trait_ref(def_id); 2 ( 0.00%) let polarity = self.tcx.impl_polarity(def_id); 2 ( 0.00%) let parent = if let Some(trait_ref) = trait_ref { 1 ( 0.00%) let trait_def = self.tcx.trait_def(trait_ref.def_id); 6 ( 0.00%) trait_def.ancestors(self.tcx, def_id).ok().and_then(|mut an| { 6 ( 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| { 6 ( 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(..) => { 2 ( 0.00%) let trait_def = self.tcx.trait_def(def_id); . let data = TraitData { 1 ( 0.00%) unsafety: trait_def.unsafety, 2 ( 0.00%) paren_sugar: trait_def.paren_sugar, 5 ( 0.00%) has_auto_impl: self.tcx.trait_is_auto(def_id), 1 ( 0.00%) is_marker: trait_def.is_marker, 1 ( 0.00%) skip_array_during_method_dispatch: trait_def.skip_array_during_method_dispatch, 1 ( 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. 40 ( 0.00%) match item.kind { . hir::ItemKind::Enum(..) => record!(self.tables.children[def_id] <- . self.tcx.adt_def(def_id).variants.iter().map(|v| { . assert!(v.def_id.is_local()); . v.def_id.index . }) . ), . hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => { . record!(self.tables.children[def_id] <- . self.tcx.adt_def(def_id).non_enum_variant().fields.iter().map(|f| { . assert!(f.did.is_local()); . f.did.index . }) . ) . } . hir::ItemKind::Impl { .. } | hir::ItemKind::Trait(..) => { 4 ( 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| { 4 ( 0.00%) assert!(def_id.is_local()); . def_id.index . }) . ); . } . _ => {} . } 18 ( 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(..) 28 ( 0.00%) | hir::ItemKind::Impl { .. } => self.encode_item_type(def_id), . _ => {} . } 23 ( 0.00%) if let hir::ItemKind::Fn(..) = item.kind { 12 ( 0.00%) record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); . } 19 ( 0.00%) if let hir::ItemKind::Impl { .. } = item.kind { 5 ( 0.00%) if let Some(trait_ref) = self.tcx.impl_trait_ref(def_id) { 5 ( 0.00%) record!(self.tables.impl_trait_ref[def_id] <- trait_ref); . } . } 64 ( 0.00%) } . . fn encode_info_for_generic_param(&mut self, def_id: DefId, kind: EntryKind, encode_type: bool) { . record!(self.tables.kind[def_id] <- kind); . if encode_type { . self.encode_item_type(def_id); . } . } . . fn encode_info_for_closure(&mut self, hir_id: hir::HirId) { 6 ( 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. 3 ( 0.00%) let ty = self.tcx.typeck(def_id).node_type(hir_id); . 3 ( 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"), . } 4 ( 0.00%) self.encode_item_type(def_id.to_def_id()); 4 ( 0.00%) if let ty::Closure(def_id, substs) = *ty.kind() { 9 ( 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() { 8 ( 0.00%) expn_data_table.set(index.as_raw(), this.lazy(expn_data)); 8 ( 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 { 3 ( 0.00%) name: self.tcx.crate_name(cnum), 3 ( 0.00%) hash: self.tcx.crate_hash(cnum), 3 ( 0.00%) host_hash: self.tcx.crate_host_hash(cnum), 3 ( 0.00%) kind: self.tcx.dep_kind(cnum), 3 ( 0.00%) extra_filename: self.tcx.extra_filename(cnum), . }; 15 ( 0.00%) (cnum, dep) . }) . .collect::>(); . . { . // Sanity-check the crate numbers . let mut expected_cnum = 1; 6 ( 0.00%) for &(n, _) in &deps { 8 ( 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 . all_impls.sort_by_cached_key(|&(trait_def_id, _)| tcx.def_path_hash(trait_def_id)); . . let all_impls: Vec<_> = all_impls . .into_iter() 15 ( 0.00%) .map(|(trait_def_id, mut impls)| { . // Bring everything into deterministic order for hashing . impls.sort_by_cached_key(|&(index, _)| { . tcx.hir().def_path_hash(LocalDefId { local_def_index: index }) . }); . 4 ( 0.00%) TraitImpls { . trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index), 3 ( 0.00%) impls: self.lazy(&impls), . } 8 ( 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() 16 ( 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 { 9 ( 0.00%) self.tcx.hir() . } 37,782 ( 0.01%) fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) { 4,198 ( 0.00%) intravisit::walk_expr(self, ex); . self.encode_info_for_expr(ex); 33,584 ( 0.01%) } . 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>) { 66 ( 0.00%) intravisit::walk_item(self, item); 44 ( 0.00%) match item.kind { . hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {} // ignore these 40 ( 0.00%) _ => self.encode_info_for_item(item.def_id.to_def_id(), item), . } 88 ( 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); . } 81 ( 0.00%) fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) { . intravisit::walk_generics(self, generics); . self.encode_info_for_generics(generics); 72 ( 0.00%) } . } . . impl<'a, 'tcx> EncodeContext<'a, 'tcx> { . 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); . } -- line 1955 ---------------------------------------- -- 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<'_>) { 8,396 ( 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. 198 ( 0.00%) fn encode_addl_info_for_item(&mut self, item: &hir::Item<'_>) { 110 ( 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(..) -- line 2005 ---------------------------------------- -- line 2031 ---------------------------------------- . 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 { .. } => { 8 ( 0.00%) for &trait_item_def_id in 1 ( 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(..) => { 7 ( 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); . } . } . } 176 ( 0.00%) } . } . . struct ImplsVisitor<'tcx> { . tcx: TyCtxt<'tcx>, . impls: FxHashMap)>>, . } . . impl<'tcx, 'v> ItemLikeVisitor<'v> for ImplsVisitor<'tcx> { 154 ( 0.00%) fn visit_item(&mut self, item: &hir::Item<'_>) { 44 ( 0.00%) match item.kind { . hir::ItemKind::Impl(..) => { 4 ( 0.00%) if let Some(trait_ref) = self.tcx.impl_trait_ref(item.def_id.to_def_id()) { 6 ( 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)); . } . } . _ => {} . } 176 ( 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<'_>) { 88 ( 0.00%) if let hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) = item.kind { 1 ( 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. . visitor.traits.sort_by_cached_key(|&def_id| tcx.def_path_hash(def_id)); . tcx.arena.alloc_slice(&visitor.traits) . }, . . ..*providers . }; . } -- line 2257 ---------------------------------------- 18,733 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/char/mod.rs -------------------------------------------------------------------------------- Ir -- line 139 ---------------------------------------- . Type, . Backslash, . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Iterator for EscapeUnicode { . type Item = char; . 189 ( 0.00%) fn next(&mut self) -> Option { 125,294 ( 0.05%) match self.state { . EscapeUnicodeState::Backslash => { 5,494 ( 0.00%) self.state = EscapeUnicodeState::Type; . Some('\\') . } . EscapeUnicodeState::Type => { 5,494 ( 0.00%) self.state = EscapeUnicodeState::LeftBrace; . Some('u') . } . EscapeUnicodeState::LeftBrace => { 5,494 ( 0.00%) self.state = EscapeUnicodeState::Value; . Some('{') . } . EscapeUnicodeState::Value => { 124,146 ( 0.05%) let hex_digit = ((self.c as u32) >> (self.hex_digit_idx * 4)) & 0xf; . let c = from_digit(hex_digit, 16).unwrap(); 22,572 ( 0.01%) if self.hex_digit_idx == 0 { 2,747 ( 0.00%) self.state = EscapeUnicodeState::RightBrace; . } else { 17,078 ( 0.01%) self.hex_digit_idx -= 1; . } . Some(c) . } . EscapeUnicodeState::RightBrace => { 5,494 ( 0.00%) self.state = EscapeUnicodeState::Done; . Some('}') . } . EscapeUnicodeState::Done => None, . } 378 ( 0.00%) } . . #[inline] . fn size_hint(&self) -> (usize, Option) { . let n = self.len(); . (n, Some(n)) . } . . #[inline] -- line 185 ---------------------------------------- -- line 200 ---------------------------------------- . } . } . . #[stable(feature = "exact_size_escape", since = "1.11.0")] . impl ExactSizeIterator for EscapeUnicode { . #[inline] . fn len(&self) -> usize { . // The match is a single memory access with no branching 5,440 ( 0.00%) self.hex_digit_idx . + match self.state { . EscapeUnicodeState::Done => 0, . EscapeUnicodeState::RightBrace => 1, . EscapeUnicodeState::Value => 2, . EscapeUnicodeState::LeftBrace => 3, . EscapeUnicodeState::Type => 4, . EscapeUnicodeState::Backslash => 5, . } -- line 216 ---------------------------------------- -- line 249 ---------------------------------------- . Backslash(char), . Unicode(EscapeUnicode), . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Iterator for EscapeDefault { . type Item = char; . 24,856 ( 0.01%) fn next(&mut self) -> Option { 149,136 ( 0.05%) match self.state { . EscapeDefaultState::Backslash(c) => { . self.state = EscapeDefaultState::Char(c); . Some('\\') . } 12 ( 0.00%) EscapeDefaultState::Char(c) => { 12 ( 0.00%) self.state = EscapeDefaultState::Done; . Some(c) . } . EscapeDefaultState::Done => None, . EscapeDefaultState::Unicode(ref mut iter) => iter.next(), . } 49,712 ( 0.02%) } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 2,732 ( 0.00%) let n = self.len(); . (n, Some(n)) . } . . #[inline] . fn count(self) -> usize { . self.len() . } . -- line 282 ---------------------------------------- -- line 310 ---------------------------------------- . EscapeDefaultState::Done => None, . EscapeDefaultState::Backslash(c) | EscapeDefaultState::Char(c) => Some(c), . } . } . } . . #[stable(feature = "exact_size_escape", since = "1.11.0")] . impl ExactSizeIterator for EscapeDefault { 2,732 ( 0.00%) fn len(&self) -> usize { 8,196 ( 0.00%) match self.state { . EscapeDefaultState::Done => 0, . EscapeDefaultState::Char(_) => 1, . EscapeDefaultState::Backslash(_) => 2, 2,720 ( 0.00%) EscapeDefaultState::Unicode(ref iter) => iter.len(), . } 5,464 ( 0.00%) } . } . . #[stable(feature = "fused", since = "1.26.0")] . impl FusedIterator for EscapeDefault {} . . #[stable(feature = "char_struct_display", since = "1.16.0")] . impl fmt::Display for EscapeDefault { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { -- line 333 ---------------------------------------- -- line 382 ---------------------------------------- . #[derive(Debug, Clone)] . pub struct ToLowercase(CaseMappingIter); . . #[stable(feature = "rust1", since = "1.0.0")] . impl Iterator for ToLowercase { . type Item = char; . fn next(&mut self) -> Option { . self.0.next() 36 ( 0.00%) } . fn size_hint(&self) -> (usize, Option) { . self.0.size_hint() . } . } . . #[stable(feature = "case_mapping_double_ended", since = "1.59.0")] . impl DoubleEndedIterator for ToLowercase { . fn next_back(&mut self) -> Option { -- line 398 ---------------------------------------- -- line 444 ---------------------------------------- . enum CaseMappingIter { . Three(char, char, char), . Two(char, char), . One(char), . Zero, . } . . impl CaseMappingIter { 252 ( 0.00%) fn new(chars: [char; 3]) -> CaseMappingIter { 36 ( 0.00%) if chars[2] == '\0' { . if chars[1] == '\0' { . CaseMappingIter::One(chars[0]) // Including if chars[0] == '\0' . } else { . CaseMappingIter::Two(chars[0], chars[1]) . } . } else { . CaseMappingIter::Three(chars[0], chars[1], chars[2]) . } 360 ( 0.00%) } . } . . impl Iterator for CaseMappingIter { . type Item = char; . fn next(&mut self) -> Option { 216 ( 0.00%) match *self { . CaseMappingIter::Three(a, b, c) => { . *self = CaseMappingIter::Two(b, c); . Some(a) . } . CaseMappingIter::Two(b, c) => { . *self = CaseMappingIter::One(c); . Some(b) . } 36 ( 0.00%) CaseMappingIter::One(c) => { 36 ( 0.00%) *self = CaseMappingIter::Zero; . Some(c) . } . CaseMappingIter::Zero => None, . } . } . . fn size_hint(&self) -> (usize, Option) { . let size = match self { -- line 486 ---------------------------------------- -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/undo_log.rs -------------------------------------------------------------------------------- Ir -- line 28 ---------------------------------------- . PushRegionObligation, . } . . macro_rules! impl_from { . ($($ctor: ident ($ty: ty),)*) => { . $( . impl<'tcx> From<$ty> for UndoLog<'tcx> { . fn from(x: $ty) -> Self { 12 ( 0.00%) UndoLog::$ctor(x.into()) . } . } . )* . } . } . . // Upcast from a single kind of "undoable action" to the general enum . impl_from! { -- line 44 ---------------------------------------- -- line 57 ---------------------------------------- . ConstUnificationTable(sv::UndoLog>>), . . RegionUnificationTable(sv::UndoLog>>), . ProjectionCache(traits::UndoLog<'tcx>), . } . . /// The Rollback trait defines how to rollback a particular action. . impl<'tcx> Rollback> for InferCtxtInner<'tcx> { 42,702 ( 0.02%) fn reverse(&mut self, undo: UndoLog<'tcx>) { 71,170 ( 0.03%) match undo { 141,340 ( 0.05%) UndoLog::TypeVariables(undo) => self.type_variable_storage.reverse(undo), . UndoLog::ConstUnificationTable(undo) => self.const_unification_storage.reverse(undo), . UndoLog::IntUnificationTable(undo) => self.int_unification_storage.reverse(undo), . UndoLog::FloatUnificationTable(undo) => self.float_unification_storage.reverse(undo), . UndoLog::RegionConstraintCollector(undo) => { 350 ( 0.00%) self.region_constraint_storage.as_mut().unwrap().reverse(undo) . } . UndoLog::RegionUnificationTable(undo) => { 88 ( 0.00%) self.region_constraint_storage.as_mut().unwrap().unification_table.reverse(undo) . } . UndoLog::ProjectionCache(undo) => self.projection_cache.reverse(undo), . UndoLog::PushRegionObligation => { . self.region_obligations.pop(); . } . } 56,936 ( 0.02%) } . } . . /// The combined undo log for all the various unification tables. For each change to the storage . /// for any kind of inference variable, we record an UndoLog entry in the vector here. . pub(crate) struct InferCtxtUndoLogs<'tcx> { . logs: Vec>, . num_open_snapshots: usize, . } . . impl Default for InferCtxtUndoLogs<'_> { . fn default() -> Self { 460 ( 0.00%) Self { logs: Default::default(), num_open_snapshots: Default::default() } . } . } . . /// The UndoLogs trait defines how we undo a particular kind of action (of type T). We can undo any . /// action that is convertable into an UndoLog (per the From impls above). . impl<'tcx, T> UndoLogs for InferCtxtUndoLogs<'tcx> . where . UndoLog<'tcx>: From, -- line 102 ---------------------------------------- -- line 103 ---------------------------------------- . { . #[inline] . fn num_open_snapshots(&self) -> usize { . self.num_open_snapshots . } . . #[inline] . fn push(&mut self, undo: T) { 3,243 ( 0.00%) if self.in_snapshot() { 96 ( 0.00%) self.logs.push(undo.into()) . } . } . . fn clear(&mut self) { . self.logs.clear(); . self.num_open_snapshots = 0; . } . -- line 120 ---------------------------------------- -- line 125 ---------------------------------------- . { . if self.in_snapshot() { . self.logs.extend(undos.into_iter().map(UndoLog::from)) . } . } . } . . impl<'tcx> InferCtxtInner<'tcx> { 17,724 ( 0.01%) pub fn rollback_to(&mut self, snapshot: Snapshot<'tcx>) { . debug!("rollback_to({})", snapshot.undo_len); . self.undo_log.assert_open_snapshot(&snapshot); . 48,610 ( 0.02%) while self.undo_log.logs.len() > snapshot.undo_len { . let undo = self.undo_log.logs.pop().unwrap(); 170,808 ( 0.06%) self.reverse(undo); . } . 8,732 ( 0.00%) if self.undo_log.num_open_snapshots == 1 { . // The root snapshot. It's safe to clear the undo log because . // there's no snapshot further out that we might need to roll back . // to. 108 ( 0.00%) assert!(snapshot.undo_len == 0); . self.undo_log.logs.clear(); . } . 8,916 ( 0.00%) self.undo_log.num_open_snapshots -= 1; 20,678 ( 0.01%) } . . pub fn commit(&mut self, snapshot: Snapshot<'tcx>) { . debug!("commit({})", snapshot.undo_len); . 43,056 ( 0.02%) if self.undo_log.num_open_snapshots == 1 { . // The root snapshot. It's safe to clear the undo log because . // there's no snapshot further out that we might need to roll back . // to. 5,958 ( 0.00%) assert!(snapshot.undo_len == 0); . self.undo_log.logs.clear(); . } . 46,035 ( 0.02%) self.undo_log.num_open_snapshots -= 1; . } . } . . impl<'tcx> InferCtxtUndoLogs<'tcx> { . pub fn start_snapshot(&mut self) -> Snapshot<'tcx> { 69,224 ( 0.03%) self.num_open_snapshots += 1; . Snapshot { undo_len: self.logs.len(), _marker: PhantomData } . } . . pub(crate) fn region_constraints_in_snapshot( . &self, . s: &Snapshot<'tcx>, . ) -> impl Iterator> + Clone { 120 ( 0.00%) self.logs[s.undo_len..].iter().filter_map(|log| match log { . UndoLog::RegionConstraintCollector(log) => Some(log), . _ => None, . }) . } . . pub(crate) fn region_constraints( . &self, . ) -> impl Iterator> + Clone { -- line 186 ---------------------------------------- -- line 187 ---------------------------------------- . self.logs.iter().filter_map(|log| match log { . UndoLog::RegionConstraintCollector(log) => Some(log), . _ => None, . }) . } . . fn assert_open_snapshot(&self, snapshot: &Snapshot<'tcx>) { . // Failures here may indicate a failure to follow a stack discipline. 8,862 ( 0.00%) assert!(self.logs.len() >= snapshot.undo_len); 8,862 ( 0.00%) assert!(self.num_open_snapshots > 0); . } . } . . impl<'tcx> std::ops::Index for InferCtxtUndoLogs<'tcx> { . type Output = UndoLog<'tcx>; . . fn index(&self, key: usize) -> &Self::Output { . &self.logs[key] -- line 204 ---------------------------------------- 17,292 ( 0.01%) -------------------------------------------------------------------------------- -- 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) { 57 ( 0.00%) let mut tt_reader = TokenTreesReader { . string_reader: self, 3 ( 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(), . }; 3 ( 0.00%) let res = tt_reader.parse_all_token_trees(); 18 ( 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`. 24 ( 0.00%) fn parse_all_token_trees(&mut self) -> PResult<'a, TokenStream> { . let mut buf = TokenStreamBuilder::default(); . . self.bump(); 218 ( 0.00%) while self.token != token::Eof { 848 ( 0.00%) buf.push(self.parse_token_tree()?); . } . . Ok(buf.into_token_stream()) 27 ( 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 { 17,176 ( 0.01%) if let token::CloseDelim(..) = self.token.kind { . return buf.into_token_stream(); . } . 35,785 ( 0.01%) match self.parse_token_tree() { 64,413 ( 0.02%) Ok(tree) => buf.push(tree), . Err(mut e) => { . e.emit(); . return buf.into_token_stream(); . } . } . } . } . 65,367 ( 0.02%) fn parse_token_tree(&mut self) -> PResult<'a, TreeAndSpacing> { 14,526 ( 0.01%) let sm = self.string_reader.sess.source_map(); . 59,643 ( 0.02%) 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) . } 1,431 ( 0.00%) token::OpenDelim(delim) => { . // The span for beginning of the delimited section 1,431 ( 0.00%) let pre_span = self.token.span; . . // Parse the open delimiter. 10,017 ( 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. 1,431 ( 0.00%) let tts = self.parse_token_trees_until_close_delim(); . . // Expand to cover the entire delimited token tree 7,155 ( 0.00%) let delim_span = DelimSpan::from_pair(pre_span, self.token.span); . 2,862 ( 0.00%) match self.token.kind { . // Correct delimiter. 2,862 ( 0.00%) token::CloseDelim(d) if d == delim => { . let (open_brace, open_brace_span) = self.open_braces.pop().unwrap(); 2,862 ( 0.00%) let close_brace_span = self.token.span; . 4,293 ( 0.00%) if tts.is_empty() { 3 ( 0.00%) let empty_block_span = open_brace_span.to(close_brace_span); 4 ( 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 5,724 ( 0.00%) if let (DelimToken::Brace, DelimToken::Brace) = (open_brace, delim) { . self.matching_block_spans.push((open_brace_span, close_brace_span)); . } . 1,431 ( 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. . } . _ => {} . } . 10,017 ( 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) . } . _ => { 29,160 ( 0.01%) let tt = TokenTree::Token(self.token.take()); . let mut spacing = self.bump(); 11,664 ( 0.00%) if !self.token.is_op() { . spacing = Alone; . } 34,992 ( 0.01%) Ok((tt, spacing)) . } . } 58,104 ( 0.02%) } . . fn bump(&mut self) -> Spacing { 71,109 ( 0.03%) let (spacing, token) = self.string_reader.next_token(); 36,342 ( 0.01%) self.token = token; . spacing . } . } . 1,431 ( 0.00%) #[derive(Default)] . struct TokenStreamBuilder { . buf: Vec, . } . . impl TokenStreamBuilder { 94,419 ( 0.03%) fn push(&mut self, (tree, joint): TreeAndSpacing) { 39,431 ( 0.01%) if let Some((TokenTree::Token(prev_token), Joint)) = self.buf.last() { 2,914 ( 0.00%) if let TokenTree::Token(token) = &tree { 4,531 ( 0.00%) if let Some(glued) = prev_token.glue(token) { . self.buf.pop(); 480 ( 0.00%) self.buf.push((TokenTree::Token(glued), joint)); . return; . } . } . } 36,115 ( 0.01%) self.buf.push((tree, joint)) 58,104 ( 0.02%) } . . fn into_token_stream(self) -> TokenStream { 14,337 ( 0.01%) TokenStream::new(self.buf) . } . } 31,609 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs -------------------------------------------------------------------------------- Ir -- line 70 ---------------------------------------- . . impl<'a, T> $name<'a, T> { . // Helper function for creating a slice from the iterator. . #[inline(always)] . fn make_slice(&self) -> &'a [T] { . // SAFETY: the iterator was created from a slice with pointer . // `self.ptr` and length `len!(self)`. This guarantees that all . // the prerequisites for `from_raw_parts` are fulfilled. 17,674 ( 0.01%) unsafe { from_raw_parts(self.ptr.as_ptr(), len!(self)) } . } . . // Helper function for moving the start of the iterator forwards by `offset` elements, . // returning the old start. . // Unsafe because the offset must not exceed `self.len()`. . #[inline(always)] . unsafe fn post_inc_start(&mut self, offset: isize) -> * $raw_mut T { . if mem::size_of::() == 0 { . zst_shrink!(self, offset); . self.ptr.as_ptr() . } else { . let old = self.ptr.as_ptr(); . // SAFETY: the caller guarantees that `offset` doesn't exceed `self.len()`, . // so this new pointer is inside `self` and thus guaranteed to be non-null. 116,406 ( 0.04%) self.ptr = unsafe { NonNull::new_unchecked(self.ptr.as_ptr().offset(offset)) }; . old . } . } . . // Helper function for moving the end of the iterator backwards by `offset` elements, . // returning the new end. . // Unsafe because the offset must not exceed `self.len()`. . #[inline(always)] -- line 101 ---------------------------------------- -- line 102 ---------------------------------------- . unsafe fn pre_dec_end(&mut self, offset: isize) -> * $raw_mut T { . if mem::size_of::() == 0 { . zst_shrink!(self, offset); . self.ptr.as_ptr() . } else { . // SAFETY: the caller guarantees that `offset` doesn't exceed `self.len()`, . // which is guaranteed to not overflow an `isize`. Also, the resulting pointer . // is in bounds of `slice`, which fulfills the other requirements for `offset`. 33 ( 0.00%) self.end = unsafe { self.end.offset(-offset) }; . self.end . } . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl ExactSizeIterator for $name<'_, T> { . #[inline(always)] . fn len(&self) -> usize { 6,067 ( 0.00%) len!(self) . } . . #[inline(always)] . fn is_empty(&self) -> bool { . is_empty!(self) . } . } . -- line 128 ---------------------------------------- -- line 134 ---------------------------------------- . fn next(&mut self) -> Option<$elem> { . // could be implemented with slices, but this avoids bounds checks . . // SAFETY: `assume` calls are safe since a slice's start pointer . // must be non-null, and slices over non-ZSTs must also have a . // non-null end pointer. The call to `next_unchecked!` is safe . // since we check if the iterator is empty first. . unsafe { 32,040 ( 0.01%) assume(!self.ptr.as_ptr().is_null()); . if mem::size_of::() != 0 { 11,938 ( 0.00%) assume(!self.end.is_null()); . } 4,330,645 ( 1.59%) if is_empty!(self) { . None . } else { . Some(next_unchecked!(self)) . } . } . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 88,251 ( 0.03%) let exact = len!(self); . (exact, Some(exact)) . } . . #[inline] . fn count(self) -> usize { . len!(self) . } . . #[inline] . fn nth(&mut self, n: usize) -> Option<$elem> { 87 ( 0.00%) if n >= len!(self) { . // This iterator is now empty. . if mem::size_of::() == 0 { . // We have to do it this way as `ptr` may never be 0, but `end` . // could be (due to wrapping). . self.end = self.ptr.as_ptr(); . } else { . // SAFETY: end can't be 0 if T isn't ZST because ptr isn't 0 and end >= ptr . unsafe { -- line 175 ---------------------------------------- -- line 203 ---------------------------------------- . // faster to compile. . #[inline] . fn for_each(mut self, mut f: F) . where . Self: Sized, . F: FnMut(Self::Item), . { . while let Some(x) = self.next() { 35 ( 0.00%) f(x); . } . } . . // We override the default implementation, which uses `try_fold`, . // because this simple implementation generates less LLVM IR and is . // faster to compile. . #[inline] . fn all(&mut self, mut f: F) -> bool . where . Self: Sized, . F: FnMut(Self::Item) -> bool, . { 6 ( 0.00%) while let Some(x) = self.next() { 697 ( 0.00%) if !f(x) { . return false; . } . } . true . } . . // We override the default implementation, which uses `try_fold`, . // because this simple implementation generates less LLVM IR and is . // faster to compile. . #[inline] . fn any(&mut self, mut f: F) -> bool . where . Self: Sized, . F: FnMut(Self::Item) -> bool, . { 83,972 ( 0.03%) while let Some(x) = self.next() { 146,813 ( 0.05%) if f(x) { . return true; . } . } . false . } . . // We override the default implementation, which uses `try_fold`, . // because this simple implementation generates less LLVM IR and is . // faster to compile. . #[inline] . fn find

(&mut self, mut predicate: P) -> Option . where . Self: Sized, . P: FnMut(&Self::Item) -> bool, . { 1,151 ( 0.00%) while let Some(x) = self.next() { 1,965 ( 0.00%) if predicate(&x) { . return Some(x); . } . } . None 48 ( 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, . { 378 ( 0.00%) while let Some(x) = self.next() { 9,755 ( 0.00%) if let Some(y) = f(x) { 49 ( 0.00%) return Some(y); . } . } . None 130 ( 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() { 25,457 ( 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; 1,289 ( 0.00%) while let Some(x) = self.next_back() { 24,150 ( 0.01%) i -= 1; 20,828 ( 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` 406 ( 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 { 14 ( 0.00%) assume(!self.ptr.as_ptr().is_null()); . if mem::size_of::() != 0 { 18 ( 0.00%) assume(!self.end.is_null()); . } 87,446 ( 0.03%) if is_empty!(self) { . None . } else { . Some(next_back_unchecked!(self)) . } . } . } . . #[inline] -- line 369 ---------------------------------------- 551,633 ( 0.20%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/interpret/allocation.rs -------------------------------------------------------------------------------- Ir -- line 18 ---------------------------------------- . }; . use crate::ty; . . /// This type represents an Allocation in the Miri/CTFE core engine. . /// . /// Its public API is rather low-level, working directly with allocation offsets and a custom error . /// type to account for the lack of an AllocId on this level. The Miri/CTFE core engine `memory` . /// module provides higher-level access. 460 ( 0.00%) #[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] . #[derive(HashStable)] . pub struct Allocation { . /// The actual bytes of the allocation. . /// Note that the bytes of a pointer represent the offset of the pointer. 54 ( 0.00%) bytes: Box<[u8]>, . /// Maps from byte addresses to extra data for each pointer. . /// Only the first byte of a pointer is inserted into the map; i.e., . /// every entry in this map applies to `pointer_size` consecutive bytes starting . /// at the given offset. 4 ( 0.00%) relocations: Relocations, . /// Denotes which part of this allocation is initialized. . init_mask: InitMask, . /// The alignment of the allocation to detect unaligned reads. . /// (`Align` guarantees that this is a power of two.) 12 ( 0.00%) pub align: Align, . /// `true` if the allocation is mutable. . /// Also used by codegen to determine if a static should be put into mutable memory, . /// which happens for `static mut` and `static` with interior mutability. 4 ( 0.00%) pub mutability: Mutability, . /// Extra state for the machine. . pub extra: Extra, . } . . /// We have our own error type that does not know about the `AllocId`; that information . /// is added when converting to `InterpError`. . #[derive(Debug)] . pub enum AllocError { -- line 53 ---------------------------------------- -- line 91 ---------------------------------------- . impl AllocRange { . #[inline(always)] . pub fn end(self) -> Size { . self.start + self.size // This does overflow checking. . } . . /// Returns the `subrange` within this range; panics if it is not a subrange. . #[inline] 13,738 ( 0.01%) pub fn subrange(self, subrange: AllocRange) -> AllocRange { . let sub_start = self.start + subrange.start; . let range = alloc_range(sub_start, subrange.size); 13,738 ( 0.01%) assert!(range.end() <= self.end(), "access outside the bounds for given AllocRange"); . range 41,214 ( 0.02%) } . } . . // The constructors are all without extra; the extra gets added by a machine hook later. . impl Allocation { . /// Creates an allocation initialized by the given bytes . pub fn from_bytes<'a>( . slice: impl Into>, . align: Align, . mutability: Mutability, . ) -> Self { . let bytes = Box::<[u8]>::from(slice.into()); . let size = Size::from_bytes(bytes.len()); 24 ( 0.00%) Self { . bytes, . relocations: Relocations::new(), 9 ( 0.00%) init_mask: InitMask::new(size, true), . align, . mutability, . extra: (), . } . } . . pub fn from_bytes_byte_aligned_immutable<'a>(slice: impl Into>) -> Self { . Allocation::from_bytes(slice, Align::ONE, Mutability::Not) . } . . /// Try to create an Allocation of `size` bytes, failing if there is not enough memory . /// available to the compiler to do so. 15,334 ( 0.01%) pub fn uninit(size: Size, align: Align, panic_on_fail: bool) -> InterpResult<'static, Self> { . let bytes = Box::<[u8]>::try_new_zeroed_slice(size.bytes_usize()).map_err(|_| { . // This results in an error that can happen non-deterministically, since the memory . // available to the compiler can change between runs. Normally queries are always . // deterministic. However, we can be non-determinstic here because all uses of const . // evaluation (including ConstProp!) will make compilation fail (via hard error . // or ICE) upon encountering a `MemoryExhausted` error. . if panic_on_fail { . panic!("Allocation::uninit called with panic_on_fail had allocation failure") -- line 141 ---------------------------------------- -- line 142 ---------------------------------------- . } . ty::tls::with(|tcx| { . tcx.sess.delay_span_bug(DUMMY_SP, "exhausted memory during interpreation") . }); . InterpError::ResourceExhaustion(ResourceExhaustionInfo::MemoryExhausted) . })?; . // SAFETY: the box was zero-allocated, which is a valid initial value for Box<[u8]> . let bytes = unsafe { bytes.assume_init() }; 19,516 ( 0.01%) Ok(Allocation { . bytes, . relocations: Relocations::new(), 4,182 ( 0.00%) init_mask: InitMask::new(size, false), . align, . mutability: Mutability::Mut, . extra: (), . }) 12,546 ( 0.00%) } . } . . impl Allocation { . /// Convert Tag and add Extra fields . pub fn convert_tag_add_extra( . self, . cx: &impl HasDataLayout, . extra: Extra, -- line 166 ---------------------------------------- -- line 190 ---------------------------------------- . extra, . } . } . } . . /// Raw accessors. Provide access to otherwise private bytes. . impl Allocation { . pub fn len(&self) -> usize { 19 ( 0.00%) self.bytes.len() . } . . pub fn size(&self) -> Size { 11,005 ( 0.00%) Size::from_bytes(self.len()) . } . . /// Looks at a slice which may describe uninitialized bytes or describe a relocation. This differs . /// from `get_bytes_with_uninit_and_ptr` in that it does no relocation checks (even on the . /// edges) at all. . /// This must not be used for reads affecting the interpreter execution. . pub fn inspect_with_uninit_and_ptr_outside_interpreter(&self, range: Range) -> &[u8] { 5 ( 0.00%) &self.bytes[range] . } . . /// Returns the mask indicating which bytes are initialized. . pub fn init_mask(&self) -> &InitMask { . &self.init_mask . } . . /// Returns the relocation list. -- line 218 ---------------------------------------- -- line 227 ---------------------------------------- . /// or pointer bytes. You should never call this, call `get_bytes` or . /// `get_bytes_with_uninit_and_ptr` instead, . /// . /// This function also guarantees that the resulting pointer will remain stable . /// even when new allocations are pushed to the `HashMap`. `copy_repeatedly` relies . /// on that. . /// . /// It is the caller's responsibility to check bounds and alignment beforehand. 98,928 ( 0.04%) fn get_bytes_internal( . &self, . cx: &impl HasDataLayout, . range: AllocRange, . check_init_and_ptr: bool, . ) -> AllocResult<&[u8]> { 16,488 ( 0.01%) if check_init_and_ptr { . self.check_init(range)?; . self.check_relocations(cx, range)?; . } else { . // We still don't want relocations on the *edges*. . self.check_relocation_edges(cx, range)?; . } . 32,976 ( 0.01%) Ok(&self.bytes[range.start.bytes_usize()..range.end().bytes_usize()]) 74,196 ( 0.03%) } . . /// Checks that these bytes are initialized and not pointer bytes, and then return them . /// as a slice. . /// . /// It is the caller's responsibility to check bounds and alignment beforehand. . /// Most likely, you want to use the `PlaceTy` and `OperandTy`-based methods . /// on `InterpCx` instead. . #[inline] -- line 258 ---------------------------------------- -- line 265 ---------------------------------------- . /// . /// It is the caller's responsibility to check bounds and alignment beforehand. . #[inline] . pub fn get_bytes_with_uninit_and_ptr( . &self, . cx: &impl HasDataLayout, . range: AllocRange, . ) -> AllocResult<&[u8]> { 16,493 ( 0.01%) self.get_bytes_internal(cx, range, false) . } . . /// Just calling this already marks everything as defined and removes relocations, . /// so be sure to actually put data there! . /// . /// It is the caller's responsibility to check bounds and alignment beforehand. . /// Most likely, you want to use the `PlaceTy` and `OperandTy`-based methods . /// on `InterpCx` instead. 60,412 ( 0.02%) pub fn get_bytes_mut( . &mut self, . cx: &impl HasDataLayout, . range: AllocRange, . ) -> AllocResult<&mut [u8]> { . self.mark_init(range, true); 27,475 ( 0.01%) self.clear_relocations(cx, range)?; . 21,971 ( 0.01%) Ok(&mut self.bytes[range.start.bytes_usize()..range.end().bytes_usize()]) 43,936 ( 0.02%) } . . /// A raw pointer variant of `get_bytes_mut` that avoids invalidating existing aliases into this memory. 11 ( 0.00%) pub fn get_bytes_mut_ptr( . &mut self, . cx: &impl HasDataLayout, . range: AllocRange, . ) -> AllocResult<*mut [u8]> { . self.mark_init(range, true); 5 ( 0.00%) self.clear_relocations(cx, range)?; . 2 ( 0.00%) assert!(range.end().bytes_usize() <= self.bytes.len()); // need to do our own bounds-check . let begin_ptr = self.bytes.as_mut_ptr().wrapping_add(range.start.bytes_usize()); 2 ( 0.00%) let len = range.end().bytes_usize() - range.start.bytes_usize(); 4 ( 0.00%) Ok(ptr::slice_from_raw_parts_mut(begin_ptr, len)) 8 ( 0.00%) } . } . . /// Reading and writing. . impl Allocation { . /// Validates that `ptr.offset` and `ptr.offset + size` do not point to the middle of a . /// relocation. If `allow_uninit_and_ptr` is `false`, also enforces that the memory in the . /// given range contains neither relocations nor uninitialized bytes. . pub fn check_bytes( -- line 314 ---------------------------------------- -- line 329 ---------------------------------------- . . /// Reads a *non-ZST* scalar. . /// . /// ZSTs can't be read because in order to obtain a `Pointer`, we need to check . /// for ZSTness anyway due to integer pointers being valid for ZSTs. . /// . /// It is the caller's responsibility to check bounds and alignment beforehand. . /// Most likely, you want to call `InterpCx::read_scalar` instead of this method. 107,159 ( 0.04%) pub fn read_scalar( . &self, . cx: &impl HasDataLayout, . range: AllocRange, . ) -> AllocResult> { . // `get_bytes_with_uninit_and_ptr` tests relocation edges. . // We deliberately error when loading data that partially has provenance, or partially . // initialized data (that's the check below), into a scalar. The LLVM semantics of this are . // unclear so we are conservative. See for -- line 345 ---------------------------------------- -- line 348 ---------------------------------------- . // Uninit check happens *after* we established that the alignment is correct. . // We must not return `Ok()` for unaligned pointers! . if self.is_init(range).is_err() { . // This inflates uninitialized bytes to the entire scalar, even if only a few . // bytes are uninitialized. . return Ok(ScalarMaybeUninit::Uninit); . } . // Now we do the actual reading. 8,243 ( 0.00%) let bits = read_target_uint(cx.data_layout().endian, bytes).unwrap(); . // See if we got a pointer. 8,243 ( 0.00%) if range.size != cx.data_layout().pointer_size { . // Not a pointer. . // *Now*, we better make sure that the inside is free of relocations too. . self.check_relocations(cx, range)?; . } else { . // Maybe a pointer. . if let Some(&prov) = self.relocations.get(&range.start) { . let ptr = Pointer::new(prov, Size::from_bytes(bits)); 105 ( 0.00%) return Ok(ScalarMaybeUninit::from_pointer(ptr, cx)); . } . } . // We don't. Just return the bits. 49,332 ( 0.02%) Ok(ScalarMaybeUninit::Scalar(Scalar::from_uint(bits, range.size))) 74,187 ( 0.03%) } . . /// Writes a *non-ZST* scalar. . /// . /// ZSTs can't be read because in order to obtain a `Pointer`, we need to check . /// for ZSTness anyway due to integer pointers being valid for ZSTs. . /// . /// It is the caller's responsibility to check bounds and alignment beforehand. . /// Most likely, you want to call `InterpCx::write_scalar` instead of this method. 38,465 ( 0.01%) pub fn write_scalar( . &mut self, . cx: &impl HasDataLayout, . range: AllocRange, . val: ScalarMaybeUninit, . ) -> AllocResult { 5,495 ( 0.00%) assert!(self.mutability == Mutability::Mut); . 16,485 ( 0.01%) let val = match val { . ScalarMaybeUninit::Scalar(scalar) => scalar, . ScalarMaybeUninit::Uninit => { . self.mark_init(range, false); . return Ok(()); . } . }; . . // `to_bits_or_ptr_internal` is the right method because we just want to store this data . // as-is into memory. 21,980 ( 0.01%) let (bytes, provenance) = match val.to_bits_or_ptr_internal(range.size) { . Err(val) => { . let (provenance, offset) = val.into_parts(); . (u128::from(offset.bytes()), Some(provenance)) . } . Ok(data) => (data, None), . }; . 16,479 ( 0.01%) let endian = cx.data_layout().endian; 16,476 ( 0.01%) let dst = self.get_bytes_mut(cx, range)?; . write_target_uint(endian, dst, bytes).unwrap(); . . // See if we have to also write a relocation. 16,476 ( 0.01%) if let Some(provenance) = provenance { 36 ( 0.00%) self.relocations.0.insert(range.start, provenance); . } . . Ok(()) 49,455 ( 0.02%) } . } . . /// Relocations. . impl Allocation { . /// Returns all relocations overlapping with the given pointer-offset pair. 90,582 ( 0.03%) pub fn get_relocations(&self, cx: &impl HasDataLayout, range: AllocRange) -> &[(Size, Tag)] { . // We have to go back `pointer_size - 1` bytes, as that one would still overlap with . // the beginning of this range. 90,585 ( 0.03%) let start = range.start.bytes().saturating_sub(cx.data_layout().pointer_size.bytes() - 1); . self.relocations.range(Size::from_bytes(start)..range.end()) 120,776 ( 0.04%) } . . /// Checks that there are no relocations overlapping with the given range. . #[inline(always)] . fn check_relocations(&self, cx: &impl HasDataLayout, range: AllocRange) -> AllocResult { 148,188 ( 0.05%) if self.get_relocations(cx, range).is_empty() { . Ok(()) . } else { . Err(AllocError::ReadPointerAsBytes) . } . } . . /// Removes all relocations inside the given range. . /// If there are relocations overlapping with the edges, they . /// are removed as well *and* the bytes they cover are marked as . /// uninitialized. This is a somewhat odd "spooky action at a distance", . /// but it allows strictly more code to run than if we would just error . /// immediately in that case. 60,456 ( 0.02%) fn clear_relocations(&mut self, cx: &impl HasDataLayout, range: AllocRange) -> AllocResult . where . Tag: Provenance, . { . // Find the start and end of the given range and its outermost relocations. . let (first, last) = { . // Find all relocations overlapping the given range. 27,480 ( 0.01%) let relocations = self.get_relocations(cx, range); 5,496 ( 0.00%) if relocations.is_empty() { . return Ok(()); . } . . ( . relocations.first().unwrap().0, . relocations.last().unwrap().0 + cx.data_layout().pointer_size, . ) . }; -- line 461 ---------------------------------------- -- line 478 ---------------------------------------- . } . self.init_mask.set_range(end, last, false); . } . . // Forget all the relocations. . self.relocations.0.remove_range(first..last); . . Ok(()) 38,472 ( 0.01%) } . . /// Errors if there are relocations overlapping with the edges of the . /// given memory range. . #[inline] . fn check_relocation_edges(&self, cx: &impl HasDataLayout, range: AllocRange) -> AllocResult { . self.check_relocations(cx, alloc_range(range.start, Size::ZERO))?; . self.check_relocations(cx, alloc_range(range.end(), Size::ZERO))?; . Ok(()) -- line 494 ---------------------------------------- -- line 496 ---------------------------------------- . } . . /// "Relocations" stores the provenance information of pointers stored in memory. . #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] . pub struct Relocations(SortedMap); . . impl Relocations { . pub fn new() -> Self { 2,794 ( 0.00%) Relocations(SortedMap::new()) . } . . // The caller must guarantee that the given relocations are already sorted . // by address and contain no duplicates. . pub fn from_presorted(r: Vec<(Size, Tag)>) -> Self { . Relocations(SortedMap::from_presorted_elements(r)) . } . } -- line 512 ---------------------------------------- -- line 520 ---------------------------------------- . } . . /// A partial, owned list of relocations to transfer into another allocation. . pub struct AllocationRelocations { . relative_relocations: Vec<(Size, Tag)>, . } . . impl Allocation { 10 ( 0.00%) pub fn prepare_relocation_copy( . &self, . cx: &impl HasDataLayout, . src: AllocRange, . dest: Size, . count: u64, . ) -> AllocationRelocations { . let relocations = self.get_relocations(cx, src); 1 ( 0.00%) if relocations.is_empty() { 2 ( 0.00%) return AllocationRelocations { relative_relocations: Vec::new() }; . } . . let size = src.size; . let mut new_relocations = Vec::with_capacity(relocations.len() * (count as usize)); . . for i in 0..count { . new_relocations.extend(relocations.iter().map(|&(offset, reloc)| { . // compute offset for current repetition -- line 545 ---------------------------------------- -- line 548 ---------------------------------------- . // shift offsets from source allocation to destination allocation . (offset + dest_offset) - src.start, // `Size` operations . reloc, . ) . })); . } . . AllocationRelocations { relative_relocations: new_relocations } 9 ( 0.00%) } . . /// Applies a relocation copy. . /// The affected range, as defined in the parameters to `prepare_relocation_copy` is expected . /// to be clear of relocations. 7 ( 0.00%) pub fn mark_relocation_range(&mut self, relocations: AllocationRelocations) { 4 ( 0.00%) self.relocations.0.insert_presorted(relocations.relative_relocations); 8 ( 0.00%) } . } . . //////////////////////////////////////////////////////////////////////////////// . // Uninitialized byte tracking . //////////////////////////////////////////////////////////////////////////////// . . type Block = u64; . -- line 571 ---------------------------------------- -- line 582 ---------------------------------------- . pub const BLOCK_SIZE: u64 = 64; . . #[inline] . fn bit_index(bits: Size) -> (usize, usize) { . // BLOCK_SIZE is the number of bits that can fit in a `Block`. . // Each bit in a `Block` represents the initialization state of one byte of an allocation, . // so we use `.bytes()` here. . let bits = bits.bytes(); 44,114 ( 0.02%) let a = bits / InitMask::BLOCK_SIZE; 13,788 ( 0.01%) let b = bits % InitMask::BLOCK_SIZE; . (usize::try_from(a).unwrap(), usize::try_from(b).unwrap()) . } . . #[inline] . fn size_from_bit_index(block: impl TryInto, bit: impl TryInto) -> Size { . let block = block.try_into().ok().unwrap(); . let bit = bit.try_into().ok().unwrap(); 2,821 ( 0.00%) Size::from_bytes(block * InitMask::BLOCK_SIZE + bit) . } . 5,588 ( 0.00%) pub fn new(size: Size, state: bool) -> Self { 2,794 ( 0.00%) let mut m = InitMask { blocks: vec![], len: Size::ZERO }; 1,397 ( 0.00%) m.grow(size, state); . m 6,985 ( 0.00%) } . 43,968 ( 0.02%) pub fn set_range(&mut self, start: Size, end: Size, new_state: bool) { 10,992 ( 0.00%) let len = self.len; 5,496 ( 0.00%) if end > len { . self.grow(end - len, new_state); . } 54,960 ( 0.02%) self.set_range_inbounds(start, end, new_state); . } . 27,576 ( 0.01%) pub fn set_range_inbounds(&mut self, start: Size, end: Size, new_state: bool) { . let (blocka, bita) = Self::bit_index(start); . let (blockb, bitb) = Self::bit_index(end); 13,788 ( 0.01%) if blocka == blockb { . // First set all bits except the first `bita`, . // then unset the last `64 - bitb` bits. 13,438 ( 0.00%) let range = if bitb == 0 { . u64::MAX << bita . } else { 47,033 ( 0.02%) (u64::MAX << bita) & (u64::MAX >> (64 - bitb)) . }; 13,438 ( 0.00%) if new_state { 5,327 ( 0.00%) self.blocks[blocka] |= range; . } else { 2,784 ( 0.00%) self.blocks[blocka] &= !range; . } . return; . } . // across block boundaries 350 ( 0.00%) if new_state { . // Set `bita..64` to `1`. 519 ( 0.00%) self.blocks[blocka] |= u64::MAX << bita; . // Set `0..bitb` to `1`. 346 ( 0.00%) if bitb != 0 { 15 ( 0.00%) self.blocks[blockb] |= u64::MAX >> (64 - bitb); . } . // Fill in all the other blocks (much faster than one bit at a time). . for block in (blocka + 1)..blockb { . self.blocks[block] = u64::MAX; . } . } else { . // Set `bita..64` to `0`. 8 ( 0.00%) self.blocks[blocka] &= !(u64::MAX << bita); . // Set `0..bitb` to `0`. 4 ( 0.00%) if bitb != 0 { 12 ( 0.00%) self.blocks[blockb] &= !(u64::MAX >> (64 - bitb)); . } . // Fill in all the other blocks (much faster than one bit at a time). . for block in (blocka + 1)..blockb { 168 ( 0.00%) self.blocks[block] = 0; . } . } 13,788 ( 0.01%) } . . #[inline] . pub fn get(&self, i: Size) -> bool { . let (block, bit) = Self::bit_index(i); 43 ( 0.00%) (self.blocks[block] & (1 << bit)) != 0 . } . . #[inline] . pub fn set(&mut self, i: Size, new_state: bool) { . let (block, bit) = Self::bit_index(i); . self.set_bit(block, bit, new_state); . } . -- line 671 ---------------------------------------- -- line 673 ---------------------------------------- . fn set_bit(&mut self, block: usize, bit: usize, new_state: bool) { . if new_state { . self.blocks[block] |= 1 << bit; . } else { . self.blocks[block] &= !(1 << bit); . } . } . 8,382 ( 0.00%) pub fn grow(&mut self, amount: Size, new_state: bool) { 2,794 ( 0.00%) if amount.bytes() == 0 { . return; . } . let unused_trailing_bits = 11,176 ( 0.00%) u64::try_from(self.blocks.len()).unwrap() * Self::BLOCK_SIZE - self.len.bytes(); 2,794 ( 0.00%) if amount.bytes() > unused_trailing_bits { 4,191 ( 0.00%) let additional_blocks = amount.bytes() / Self::BLOCK_SIZE + 1; . self.blocks.extend( . // FIXME(oli-obk): optimize this by repeating `new_state as Block`. . iter::repeat(0).take(usize::try_from(additional_blocks).unwrap()), . ); . } 1,397 ( 0.00%) let start = self.len; . self.len += amount; 12,573 ( 0.00%) self.set_range_inbounds(start, start + amount, new_state); // `Size` operation . } . . /// Returns the index of the first bit in `start..end` (end-exclusive) that is equal to is_init. 16,512 ( 0.01%) fn find_bit(&self, start: Size, end: Size, is_init: bool) -> Option { . /// A fast implementation of `find_bit`, . /// which skips over an entire block at a time if it's all 0s (resp. 1s), . /// and finds the first 1 (resp. 0) bit inside a block using `trailing_zeros` instead of a loop. . /// . /// Note that all examples below are written with 8 (instead of 64) bit blocks for simplicity, . /// and with the least significant bit (and lowest block) first: . /// . /// 00000000|00000000 -- line 708 ---------------------------------------- -- line 728 ---------------------------------------- . // start_bit = 3 . // is_init = false . // Note that, for the examples in this function, the most significant bit is written first, . // which is backwards compared to the comments in `find_bit`/`find_bit_fast`. . . // Invert bits so we're always looking for the first set bit. . // ! 0b00111011 . // bits = 0b11000100 33,024 ( 0.01%) let bits = if is_init { bits } else { !bits }; . // Mask off unused start bits. . // 0b11000100 . // & 0b11111000 . // bits = 0b11000000 24,768 ( 0.01%) let bits = bits & (!0 << start_bit); . // Find set bit, if any. . // bit = trailing_zeros(0b11000000) . // bit = 6 16,883 ( 0.01%) if bits == 0 { . None . } else { . let bit = bits.trailing_zeros(); . Some(InitMask::size_from_bit_index(block, bit)) . } . } . 8,256 ( 0.00%) if start >= end { . return None; . } . . // Convert `start` and `end` to block indexes and bit indexes within each block. . // We must convert `end` to an inclusive bound to handle block boundaries correctly. . // . // For example: . // -- line 761 ---------------------------------------- -- line 819 ---------------------------------------- . // The block marked (3) in this example is the first block that will be handled by this loop, . // and it will be skipped for that reason: . // . // (3) . // -------- . // (e) 01000000|00000000|00000001 . // ^~~~~~~~~~~~~~~~~~^ . // start end 10,890 ( 0.00%) if start_block < end_block_inclusive { . // This loop is written in a specific way for performance. . // Notably: `..end_block_inclusive + 1` is used for an inclusive range instead of `..=end_block_inclusive`, . // and `.zip(start_block + 1..)` is used to track the index instead of `.enumerate().skip().take()`, . // because both alternatives result in significantly worse codegen. . // `end_block_inclusive + 1` is guaranteed not to wrap, because `end_block_inclusive <= end / BLOCK_SIZE`, . // and `BLOCK_SIZE` (the number of bits per block) will always be at least 8 (1 byte). 5 ( 0.00%) for (&bits, block) in init_mask.blocks[start_block + 1..end_block_inclusive + 1] . .iter() . .zip(start_block + 1..) . { . if let Some(i) = search_block(bits, block, 0, is_init) { . // If this is the last block, we may find a matching bit after `end`. . // . // For example, we shouldn't successfully find bit (4), because it's after `end`: . // -- line 842 ---------------------------------------- -- line 879 ---------------------------------------- . "optimized implementation of find_bit is wrong for start={:?} end={:?} is_init={} init_mask={:#?}", . start, . end, . is_init, . self . ); . . result 16,512 ( 0.01%) } . } . . /// A contiguous chunk of initialized or uninitialized memory. . pub enum InitChunk { . Init(Range), . Uninit(Range), . } . -- line 895 ---------------------------------------- -- line 913 ---------------------------------------- . . impl InitMask { . /// Checks whether the range `start..end` (end-exclusive) is entirely initialized. . /// . /// Returns `Ok(())` if it's initialized. Otherwise returns a range of byte . /// indexes for the first contiguous span of the uninitialized access. . #[inline] . pub fn is_range_initialized(&self, start: Size, end: Size) -> Result<(), Range> { 8,243 ( 0.00%) if end > self.len { . return Err(self.len..end); . } . 41,215 ( 0.02%) let uninit_start = self.find_bit(start, end, false); . 16,486 ( 0.01%) match uninit_start { . Some(uninit_start) => { . let uninit_end = self.find_bit(uninit_start, end, true).unwrap_or(end); . Err(uninit_start..uninit_end) . } . None => Ok(()), . } . } . -- line 935 ---------------------------------------- -- line 938 ---------------------------------------- . /// . /// The iterator guarantees the following: . /// - Chunks are nonempty. . /// - Chunks are adjacent (each range's start is equal to the previous range's end). . /// - Chunks span exactly `start..end` (the first starts at `start`, the last ends at `end`). . /// - Chunks alternate between [`InitChunk::Init`] and [`InitChunk::Uninit`]. . #[inline] . pub fn range_as_init_chunks(&self, start: Size, end: Size) -> InitChunkIter<'_> { 13 ( 0.00%) assert!(end <= self.len); . 13 ( 0.00%) let is_init = if start < end { . self.get(start) . } else { . // `start..end` is empty: there are no chunks, so use some arbitrary value . false . }; . . InitChunkIter { init_mask: self, is_init, start, end } . } -- line 956 ---------------------------------------- -- line 968 ---------------------------------------- . end: Size, . } . . impl<'a> Iterator for InitChunkIter<'a> { . type Item = InitChunk; . . #[inline] . fn next(&mut self) -> Option { 25 ( 0.00%) if self.start >= self.end { . return None; . } . . let end_of_chunk = 113 ( 0.00%) self.init_mask.find_bit(self.start, self.end, !self.is_init).unwrap_or(self.end); . let range = self.start..end_of_chunk; . . let ret = 28 ( 0.00%) Some(if self.is_init { InitChunk::Init(range) } else { InitChunk::Uninit(range) }); . . self.is_init = !self.is_init; . self.start = end_of_chunk; . . ret . } . } . -- line 993 ---------------------------------------- -- line 1010 ---------------------------------------- . access_size: range.size, . uninit_offset: idx_range.start, . uninit_size: idx_range.end - idx_range.start, // `Size` subtraction . })) . }) . } . . pub fn mark_init(&mut self, range: AllocRange, is_init: bool) { 10,986 ( 0.00%) if range.size.bytes() == 0 { . return; . } 5,493 ( 0.00%) assert!(self.mutability == Mutability::Mut); 21,990 ( 0.01%) self.init_mask.set_range(range.start, range.end(), is_init); . } . } . . /// Run-length encoding of the uninit mask. . /// Used to copy parts of a mask multiple times to another allocation. . pub struct InitMaskCompressed { . /// Whether the first range is initialized. . initial: bool, -- line 1030 ---------------------------------------- -- line 1032 ---------------------------------------- . /// The initialization state of the ranges alternate starting with `initial`. . ranges: smallvec::SmallVec<[u64; 1]>, . } . . impl InitMaskCompressed { . pub fn no_bytes_init(&self) -> bool { . // The `ranges` are run-length encoded and of alternating initialization state. . // So if `ranges.len() > 1` then the second block is an initialized range. 2 ( 0.00%) !self.initial && self.ranges.len() == 1 1 ( 0.00%) } . } . . /// Transferring the initialization mask to other allocations. . impl Allocation { . /// Creates a run-length encoding of the initialization mask; panics if range is empty. . /// . /// This is essentially a more space-efficient version of . /// `InitMask::range_as_init_chunks(...).collect::>()`. 7 ( 0.00%) pub fn compress_uninit_range(&self, range: AllocRange) -> InitMaskCompressed { . // Since we are copying `size` bytes from `src` to `dest + i * size` (`for i in 0..repeat`), . // a naive initialization mask copying algorithm would repeatedly have to read the initialization mask from . // the source and write it to the destination. Even if we optimized the memory accesses, . // we'd be doing all of this `repeat` times. . // Therefore we precompute a compressed version of the initialization mask of the source value and . // then write it back `repeat` times without computing any more information from the source. . . // A precomputed cache for ranges of initialized / uninitialized bits -- line 1058 ---------------------------------------- -- line 1063 ---------------------------------------- . let mut ranges = smallvec::SmallVec::<[u64; 1]>::new(); . . let mut chunks = self.init_mask.range_as_init_chunks(range.start, range.end()).peekable(); . . let initial = chunks.peek().expect("range should be nonempty").is_init(); . . // Here we rely on `range_as_init_chunks` to yield alternating init/uninit chunks. . for chunk in chunks { 2 ( 0.00%) let len = chunk.range().end.bytes() - chunk.range().start.bytes(); . ranges.push(len); . } . 7 ( 0.00%) InitMaskCompressed { ranges, initial } 8 ( 0.00%) } . . /// Applies multiple instances of the run-length encoding to the initialization mask. 11 ( 0.00%) pub fn mark_compressed_init_range( . &mut self, . defined: &InitMaskCompressed, . range: AllocRange, . repeat: u64, . ) { . // An optimization where we can just overwrite an entire range of initialization . // bits if they are going to be uniformly `1` or `0`. 2 ( 0.00%) if defined.ranges.len() <= 1 { 10 ( 0.00%) self.init_mask.set_range_inbounds( . range.start, . range.start + range.size * repeat, // `Size` operations 1 ( 0.00%) defined.initial, . ); . return; . } . . for mut j in 0..repeat { . j *= range.size.bytes(); . j += range.start.bytes(); . let mut cur = defined.initial; -- line 1099 ---------------------------------------- 162,943 ( 0.06%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/operand.rs -------------------------------------------------------------------------------- Ir -- line 55 ---------------------------------------- . 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)) . } . . pub fn new_slice(val: Scalar, len: u64, cx: &impl HasDataLayout) -> Self { 4 ( 0.00%) Immediate::ScalarPair(val.into(), Scalar::from_machine_usize(len, cx).into()) . } . . 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 { 10,960 ( 0.00%) match self { 21,896 ( 0.01%) Immediate::Scalar(val) => val, . Immediate::ScalarPair(..) => bug!("Got a scalar pair where a scalar was expected"), . } . } . . #[inline] . pub fn to_scalar(self) -> InterpResult<'tcx, Scalar> { . self.to_scalar_or_uninit().check_init() . } -- line 85 ---------------------------------------- -- 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. 12 ( 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 { 143 ( 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 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>> { 6,871 ( 0.00%) if mplace.layout.is_unsized() { . // Don't touch unsized . return Ok(None); . } . 20,607 ( 0.01%) let alloc = match self.get_alloc(mplace)? { 34,345 ( 0.01%) Some(ptr) => ptr, . None => { . return Ok(Some(ImmTy { . // zero-sized type . imm: Scalar::ZST.into(), . layout: mplace.layout, . })); . } . }; . 52,202 ( 0.02%) match mplace.layout.abi { . Abi::Scalar(..) => { 5,493 ( 0.00%) let scalar = alloc.read_scalar(alloc_range(Size::ZERO, mplace.layout.size))?; . Ok(Some(ImmTy { imm: scalar.into(), layout: mplace.layout })) . } 4,125 ( 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); 2,750 ( 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))?; 4,125 ( 0.00%) let b_val = alloc.read_scalar(alloc_range(b_offset, b_size))?; 6,875 ( 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. 87,066 ( 0.03%) pub fn try_read_immediate( . &self, . src: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, Result, MPlaceTy<'tcx, M::PointerTag>>> { 174,132 ( 0.06%) Ok(match src.try_as_mplace() { . Ok(ref mplace) => { 13,738 ( 0.01%) if let Some(val) = self.try_read_immediate_from_mplace(mplace)? { . Ok(val) . } else { . Err(*mplace) . } . } 28,050 ( 0.01%) Err(val) => Ok(val), . }) 87,066 ( 0.03%) } . . /// 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>> { 16,639 ( 0.01%) if let Ok(imm) = self.try_read_immediate(op)? { 44,148 ( 0.02%) Ok(imm) . } else { . span_bug!(self.cur_span(), "primitive read failed for type: {:?}", op.layout.ty); . } . } . . /// Read a scalar from a place 60,214 ( 0.02%) pub fn read_scalar( . &self, . op: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, ScalarMaybeUninit> { 5,474 ( 0.00%) Ok(self.read_immediate(op)?.to_scalar_or_uninit()) 49,266 ( 0.02%) } . . /// 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 54,730 ( 0.02%) 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)?; 60,203 ( 0.02%) return Ok(field.into()); . } . Err(value) => value, . }; . . 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 }); -- line 370 ---------------------------------------- -- line 381 ---------------------------------------- . Immediate::Scalar(val) => span_bug!( . self.cur_span(), . "field access on non aggregate {:#?}, {:#?}", . val, . op.layout . ), . }; . Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout }) 49,257 ( 0.02%) } . . 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()) . } . } . 22 ( 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 34 ( 0.00%) Ok(match op.try_as_mplace() { 20 ( 0.00%) Ok(ref mplace) => self.mplace_downcast(mplace, variant)?.into(), . Err(..) => { . let layout = op.layout.for_variant(self, variant); . OpTy { layout, ..*op } . } . }) 18 ( 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::*; . Ok(match proj_elem { -- line 427 ---------------------------------------- -- 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 13,686 ( 0.01%) 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)?; 1 ( 0.00%) let op = if layout.is_zst() { . // Do not read from ZST, they might not be initialized . Operand::Immediate(Scalar::ZST.into()) . } else { 312 ( 0.00%) M::access_local(&self, frame, local)? . }; 18,213 ( 0.01%) Ok(OpTy { op, layout }) 11,992 ( 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>> { 8 ( 0.00%) let op = match **place { . Place::Ptr(mplace) => Operand::Indirect(mplace), . Place::Local { frame, local } => { 36 ( 0.00%) *self.access_local(&self.stack()[frame], local, None)? . } . }; 28 ( 0.00%) Ok(OpTy { op, layout: place.layout }) . } . . // Evaluate a place with the goal of reading from it. This lets us sometimes . // avoid allocations. 11,776 ( 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. 1,472 ( 0.00%) let layout = if place.projection.is_empty() { layout } else { None }; . 4,416 ( 0.00%) let base_op = self.access_local(self.frame(), place.local, layout)?; . . let op = place . .projection . .iter() . .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. -- line 509 ---------------------------------------- -- line 510 ---------------------------------------- . 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, . )); 4,161 ( 0.00%) Ok(op) 13,248 ( 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] 37,022 ( 0.01%) pub fn eval_operand( . &self, . mir_op: &mir::Operand<'tcx>, . layout: Option>, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { . use rustc_middle::mir::Operand::*; 8,471 ( 0.00%) let op = match *mir_op { . // FIXME: do some more logic on `move` to invalidate the old location 7,176 ( 0.00%) Copy(place) | Move(place) => self.eval_place_to_op(place, layout)?, . . Constant(ref constant) => { . let val = 41,666 ( 0.02%) 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. . 119 ( 0.00%) self.mir_const_to_op(&val, layout)? . } . }; . trace!("{:?}: {:?}", mir_op, *op); 53,754 ( 0.02%) Ok(op) 24,683 ( 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). 32,880 ( 0.01%) pub fn const_to_op( . &self, . val: &ty::Const<'tcx>, . layout: Option>, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { 14,035 ( 0.01%) match val.val { . ty::ConstKind::Param(_) | ty::ConstKind::Bound(..) => throw_inval!(TooGeneric), . ty::ConstKind::Error(_) => throw_inval!(AlreadyReported(ErrorReported)), 8 ( 0.00%) ty::ConstKind::Unevaluated(uv) => { . let instance = self.resolve(uv.def, uv.substs)?; 22 ( 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) . } 27,790 ( 0.01%) ty::ConstKind::Value(val_val) => self.const_val_to_op(val_val, val.ty, layout), . } 24,660 ( 0.01%) } . 737 ( 0.00%) pub fn mir_const_to_op( . &self, . val: &mir::ConstantKind<'tcx>, . layout: Option>, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { 5,614 ( 0.00%) match val { 11,094 ( 0.00%) mir::ConstantKind::Ty(ct) => self.const_to_op(ct, layout), . mir::ConstantKind::Val(val, ty) => self.const_val_to_op(*val, ty, layout), . } 603 ( 0.00%) } . 28,050 ( 0.01%) 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, _> { 16,818 ( 0.01%) Ok(match scalar { . Scalar::Ptr(ptr, size) => Scalar::Ptr(self.global_base_pointer(ptr)?, size), 8,403 ( 0.00%) Scalar::Int(int) => Scalar::Int(int), . }) . }; 150 ( 0.00%) let layout = from_known_layout(self.tcx, self.param_env, layout, || self.layout_of(ty))?; 8,419 ( 0.00%) let op = match val_val { 4 ( 0.00%) ConstValue::ByRef { alloc, offset } => { 4 ( 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))?; 8 ( 0.00%) Operand::Indirect(MemPlace::from_ptr(ptr.into(), layout.align.abi)) . } 25,290 ( 0.01%) ConstValue::Scalar(x) => Operand::Immediate(tag_scalar(x)?.into()), . 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( . self.tcx.create_memory_alloc(data), . Size::from_bytes(start), // offset: `start` . ); . 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, . )) . } . }; 58,905 ( 0.02%) Ok(OpTy { op, layout }) 22,440 ( 0.01%) } . . /// 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 => { 80 ( 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. 32 ( 0.00%) let discr_val = self.cast_from_scalar(tag_bits, tag_layout, discr_layout.ty); 8 ( 0.00%) let discr_bits = discr_val.assert_bits(discr_layout.size); . // Convert discriminant to variant index, and catch invalid discriminants. 20 ( 0.00%) let index = match *op.layout.ty.kind() { 4 ( 0.00%) ty::Adt(adt, _) => { 56 ( 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. 16 ( 0.00%) (discr_val, index.0) . } . 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(); . let variants_end = niche_variants.end().as_u32(); . let variant = match tag_val.try_to_int() { . Err(dbg_val) => { -- line 721 ---------------------------------------- -- line 766 ---------------------------------------- . } . }; . // 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. . (Scalar::from_uint(variant.as_u32(), discr_layout.size), variant) . } . }) 36 ( 0.00%) } . } 209,151 ( 0.08%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/expr.rs -------------------------------------------------------------------------------- Ir -- line 72 ---------------------------------------- . } . . impl From> for LhsExpr { . /// Converts `Some(attrs)` into `LhsExpr::AttributesParsed(attrs)` . /// and `None` into `LhsExpr::NotYetParsed`. . /// . /// This conversion does not allocate. . fn from(o: Option) -> Self { 9,645 ( 0.00%) if let Some(attrs) = o { LhsExpr::AttributesParsed(attrs) } else { LhsExpr::NotYetParsed } . } . } . . impl From> for LhsExpr { . /// Converts the `expr: P` into `LhsExpr::AlreadyParsed(expr)`. . /// . /// This conversion does not allocate. . fn from(expr: P) -> Self { -- line 88 ---------------------------------------- -- line 103 ---------------------------------------- . pub fn parse_expr_force_collect(&mut self) -> PResult<'a, P> { . 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 }) . } . 21,992 ( 0.01%) fn parse_expr_catch_underscore(&mut self) -> PResult<'a, P> { 5,498 ( 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), . }, . } 27,490 ( 0.01%) } . . /// Parses a sequence of expressions delimited by parentheses. . fn parse_paren_expr_seq(&mut self) -> PResult<'a, Vec>> { 38 ( 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> { 13,736 ( 0.01%) self.parse_assoc_expr_with(0, already_parsed_attrs.into()) . } . . /// Parses an associative expression with operators of at least `min_prec` precedence. 37,422 ( 0.01%) pub(super) fn parse_assoc_expr_with( . &mut self, . min_prec: usize, . lhs: LhsExpr, . ) -> PResult<'a, P> { 20,793 ( 0.01%) let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs { 24 ( 0.00%) expr . } else { 8,304 ( 0.00%) let attrs = match lhs { 8,319 ( 0.00%) LhsExpr::AttributesParsed(attrs) => Some(attrs), . _ => None, . }; 4,152 ( 0.00%) if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind) { . return self.parse_prefix_range_expr(attrs); . } else { 49,824 ( 0.02%) self.parse_prefix_expr(attrs)? . } . }; 8,316 ( 0.00%) let last_type_ascription_set = self.last_type_ascription.is_some(); . . if !self.should_continue_as_assoc_expr(&lhs) { 3 ( 0.00%) self.last_type_ascription = None; . return Ok(lhs); . } . . self.expected_tokens.push(TokenType::Operator); 160 ( 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. 240 ( 0.00%) let lhs_span = match self.prev_token.kind { . TokenKind::Interpolated(..) => self.prev_token.span, . _ => lhs.span, . }; . 80 ( 0.00%) let cur_op_span = self.token.span; 320 ( 0.00%) let restrictions = if op.node.is_assign_like() { . self.restrictions & Restrictions::NO_STRUCT_LITERAL . } else { . self.restrictions . }; 120 ( 0.00%) let prec = op.node.precedence(); 80 ( 0.00%) if prec < min_prec { . break; . } . // Check for deprecated `...` syntax 112 ( 0.00%) if self.token == token::DotDotDot && op.node == AssocOp::DotDotEq { . self.err_dotdotdot_syntax(self.token.span); . } . 112 ( 0.00%) if self.token == token::LArrow { . self.err_larrow_operator(self.token.span); . } . 28 ( 0.00%) self.bump(); 112 ( 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 30 ( 0.00%) if (op.node == AssocOp::Equal || op.node == AssocOp::NotEqual) 2 ( 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 3 ( 0.00%) if op.node == AssocOp::Less 2 ( 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 20 ( 0.00%) if op.node == AssocOp::LessEqual 20 ( 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(); . } . 56 ( 0.00%) let op = op.node; . // Special cases: . if op == AssocOp::As { . 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. . lhs = self.parse_range_expr(prec, lhs, op, cur_op_span)?; . break; . } . 28 ( 0.00%) let fixity = op.fixity(); 84 ( 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, . }; 56 ( 0.00%) let rhs = self.with_res(restrictions - Restrictions::STMT_EXPR, |this| { 140 ( 0.00%) this.parse_assoc_expr_with(prec + prec_adjustment, LhsExpr::NotYetParsed) . })?; . . let span = self.mk_expr_sp(&lhs, lhs_span, rhs.span); 252 ( 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 => { 56 ( 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") . } . }; . 56 ( 0.00%) if let Fixity::None = fixity { . break; . } . } 4,157 ( 0.00%) if last_type_ascription_set { . self.last_type_ascription = None; . } 8,314 ( 0.00%) Ok(lhs) 70,682 ( 0.03%) } . . fn should_continue_as_assoc_expr(&mut self, lhs: &Expr) -> bool { 29,108 ( 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> { 46,075 ( 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), . ), . _, 3 ( 0.00%) ) if self.restrictions.contains(Restrictions::CONST_EXPR) => { . return None; . } 80 ( 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 { 8,320 ( 0.00%) self.restrictions.contains(Restrictions::STMT_EXPR) 49 ( 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, -- line 460 ---------------------------------------- -- line 520 ---------------------------------------- . (lo, None) . }; . let range = this.mk_range(None, opt_end, limits); . Ok(this.mk_expr(span, range, attrs.into())) . }) . } . . /// Parses a prefix-unary-operator expr. 29,078 ( 0.01%) fn parse_prefix_expr(&mut self, attrs: Option) -> PResult<'a, P> { 33,232 ( 0.01%) let attrs = self.parse_or_use_outer_attributes(attrs)?; 20,770 ( 0.01%) let lo = self.token.span; . . macro_rules! make_it { . ($this:ident, $attrs:expr, |this, _| $body:expr) => { 18 ( 0.00%) $this.collect_tokens_for_expr($attrs, |$this, attrs| { 34 ( 0.00%) let (hi, ex) = $body?; 32 ( 0.00%) Ok($this.mk_expr(lo.to(hi), ex, attrs.into())) 20 ( 0.00%) }) . }; . } . . let this = self; . . // Note: when adding new unary operators, don't forget to adjust TokenKind::can_begin_expr() 24,936 ( 0.01%) match this.token.uninterpolate().kind { . 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) => { . make_it!(this, attrs, |this, _| this.parse_unary_expr(lo, UnOp::Deref)) . } // `*expr` . token::BinOp(token::And) | token::AndAnd => { 4 ( 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` 104 ( 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)), . } 41,540 ( 0.02%) } . . fn parse_prefix_expr_common(&mut self, lo: Span) -> PResult<'a, (Span, P)> { . self.bump(); . let expr = self.parse_prefix_expr(None); . let (span, expr) = self.interpolated_or_expr_span(expr)?; . Ok((lo.to(span), expr)) . } . -- line 592 ---------------------------------------- -- 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(), . }; 104 ( 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| { . ( 16,618 ( 0.01%) match self.prev_token.kind { . TokenKind::Interpolated(..) => self.prev_token.span, . _ => e.span, . }, . e, . ) . }) . } . -- line 667 ---------------------------------------- -- 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()?; 10 ( 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); 8 ( 0.00%) let expr = self.parse_prefix_expr(None); 4 ( 0.00%) let (hi, expr) = self.interpolated_or_expr_span(expr)?; 2 ( 0.00%) let span = lo.to(hi); 4 ( 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) { 4 ( 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)?; 16,608 ( 0.01%) this.parse_dot_or_call_expr_with(base, span, attrs) . }) . } . . 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 29,106 ( 0.01%) self.parse_dot_or_call_expr_with_(e0, lo).map(|expr| { 29,106 ( 0.01%) expr.map(|mut expr| { 4,158 ( 0.00%) attrs.extend::>(expr.attrs.into()); 8,316 ( 0.00%) expr.attrs = attrs.into(); 58,212 ( 0.02%) expr . }) . }) . } . 128,898 ( 0.05%) fn parse_dot_or_call_expr_with_(&mut self, mut e: P, lo: Span) -> PResult<'a, P> { . loop { . if self.eat(&token::Question) { . // `expr?` . e = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Try(e), AttrVec::new()); . continue; . } . if self.eat(&token::Dot) { . // expr.f 8 ( 0.00%) e = self.parse_dot_suffix_expr(lo, e)?; . continue; . } 22 ( 0.00%) if self.expr_is_complete(&e) { . return Ok(e); . } 8,360 ( 0.00%) e = match self.token.kind { 12 ( 0.00%) token::OpenDelim(token::Paren) => self.parse_fn_call_expr(lo, e), . token::OpenDelim(token::Bracket) => self.parse_index_expr(lo, e)?, 4,157 ( 0.00%) _ => return Ok(e), . } . } 37,422 ( 0.01%) } . . fn look_ahead_type_ascription_as_field(&mut self) -> bool { 26 ( 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> { 22 ( 0.00%) match self.token.uninterpolate().kind { . token::Ident(..) => self.parse_dot_suffix(base, lo), . token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) => { . 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)) . } . _ => { -- line 957 ---------------------------------------- -- line 1091 ---------------------------------------- . let span = self.prev_token.span; . let field = ExprKind::Field(base, Ident::new(field, span)); . self.expect_no_suffix(span, "a tuple index", suffix); . self.mk_expr(lo.to(span), field, AttrVec::new()) . } . . /// Parse a function call expression, `expr(...)`. . fn parse_fn_call_expr(&mut self, lo: Span, fun: P) -> P { 20 ( 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 { 12 ( 0.00%) None . }; 4 ( 0.00%) let open_paren = self.token.span; . 8 ( 0.00%) let mut seq = self.parse_paren_expr_seq().map(|args| { 12 ( 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; . } 20 ( 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> { 40 ( 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(), . } . } . _ => {} 12 ( 0.00%) } . None . } . . /// Parse an indexing expression `expr[...]`. . fn parse_index_expr(&mut self, lo: Span, base: P) -> PResult<'a, P> { . self.bump(); // `[` . let index = self.parse_expr()?; . self.expect(&token::CloseDelim(token::Bracket))?; . 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> { 4 ( 0.00%) if self.token.uninterpolated_span().rust_2018() && self.eat_keyword(kw::Await) { . return Ok(self.mk_await_expr(self_arg, lo)); . } . 2 ( 0.00%) let fn_span_lo = self.token.span; 12 ( 0.00%) let mut segment = self.parse_path_segment(PathStyle::Expr, None)?; 10 ( 0.00%) self.check_trailing_angle_brackets(&segment, &[&token::OpenDelim(token::Paren)]); . self.check_turbofish_missing_angle_brackets(&mut segment); . 10 ( 0.00%) if self.check(&token::OpenDelim(token::Paren)) { . // Method call `expr.f()` 2 ( 0.00%) let mut args = self.parse_paren_expr_seq()?; 8 ( 0.00%) args.insert(0, self_arg); . 6 ( 0.00%) let fn_span = fn_span_lo.to(self.prev_token.span); 6 ( 0.00%) let span = lo.to(self.prev_token.span); 10 ( 0.00%) Ok(self.mk_expr(span, ExprKind::MethodCall(segment, args, fn_span), AttrVec::new())) . } else { . // Field access `expr.f` . if let Some(args) = segment.args { . self.struct_span_err( . args.span(), . "field expressions cannot have generic arguments", . ) . .emit(); -- line 1211 ---------------------------------------- -- line 1217 ---------------------------------------- . } . . /// 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> { 9,688 ( 0.00%) maybe_recover_from_interpolated_ty_qpath!(self, true); 12,456 ( 0.00%) 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. 4,152 ( 0.00%) let attrs = AttrVec::new(); . . // Note: when adding new syntax here, don't forget to adjust `TokenKind::can_begin_expr()`. 1,404 ( 0.00%) let lo = self.token.span; 12,456 ( 0.00%) 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. 10,992 ( 0.00%) self.parse_lit_expr(attrs) 7,020 ( 0.00%) } else if self.check(&token::OpenDelim(token::Paren)) { 4,122 ( 0.00%) self.parse_tuple_parens_expr(attrs) 150 ( 0.00%) } else if self.check(&token::OpenDelim(token::Brace)) { 8 ( 0.00%) self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs) 285 ( 0.00%) } else if self.check(&token::BinOp(token::Or)) || self.check(&token::OrOr) { 4 ( 0.00%) self.parse_closure_expr(attrs) 140 ( 0.00%) } else if self.check(&token::OpenDelim(token::Bracket)) { 10 ( 0.00%) self.parse_array_or_repeat_expr(attrs, token::Bracket) 104 ( 0.00%) } else if self.check_path() { 100 ( 0.00%) self.parse_path_start_expr(attrs) 10 ( 0.00%) } else if self.check_keyword(kw::Move) || self.check_keyword(kw::Static) { . self.parse_closure_expr(attrs) 5 ( 0.00%) } else if self.eat_keyword(kw::If) { 4 ( 0.00%) self.parse_if_expr(attrs) . } else if self.check_keyword(kw::For) { . 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 { -- line 1263 ---------------------------------------- -- line 1325 ---------------------------------------- . } else { . self.parse_lit_expr(attrs) . } . } else { . self.parse_lit_expr(attrs) . } . } . 27,480 ( 0.01%) fn parse_lit_expr(&mut self, attrs: AttrVec) -> PResult<'a, P> { 5,496 ( 0.00%) let lo = self.token.span; 10,992 ( 0.00%) match self.parse_opt_lit() { 16,488 ( 0.01%) Some(literal) => { 24,732 ( 0.01%) let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Lit(literal), attrs); 27,480 ( 0.01%) 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> { 2,748 ( 0.00%) let lo = self.token.span; 4,122 ( 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), 5,484 ( 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))), . }; 6,870 ( 0.00%) let kind = if es.len() == 1 && !trailing_comma { . // `(e)` is parenthesized `e`. 21 ( 0.00%) ExprKind::Paren(es.into_iter().next().unwrap()) . } else { . // `(e,)` is a tuple with only one field, `e`. 6,835 ( 0.00%) ExprKind::Tup(es) . }; 4,122 ( 0.00%) let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs); 4,122 ( 0.00%) self.maybe_recover_from_bad_qpath(expr, true) . } . 22 ( 0.00%) fn parse_array_or_repeat_expr( . &mut self, . attrs: AttrVec, . close_delim: token::DelimToken, . ) -> PResult<'a, P> { 6 ( 0.00%) let lo = self.token.span; 2 ( 0.00%) self.bump(); // `[` or other open delim . 6 ( 0.00%) let close = &token::CloseDelim(close_delim); . let kind = if self.eat(close) { . // Empty vector . ExprKind::Array(Vec::new()) . } else { . // Non-empty vector 4 ( 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())?; 2 ( 0.00%) let mut exprs = vec![first_expr]; . exprs.extend(remaining_exprs); 10 ( 0.00%) ExprKind::Array(exprs) . } else { . // Vector with one element . self.expect(close)?; . ExprKind::Array(vec![first_expr]) . } . }; 6 ( 0.00%) let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs); 6 ( 0.00%) self.maybe_recover_from_bad_qpath(expr, true) 20 ( 0.00%) } . 250 ( 0.00%) fn parse_path_start_expr(&mut self, attrs: AttrVec) -> PResult<'a, P> { 200 ( 0.00%) let (qself, path) = if self.eat_lt() { . let (qself, path) = self.parse_qpath(PathStyle::Expr)?; . (Some(qself), path) . } else { 50 ( 0.00%) (None, self.parse_path(PathStyle::Expr)?) . }; 25 ( 0.00%) let lo = path.span; . . // `!`, as an operator, is prefix, so we know this isn't that. 375 ( 0.00%) let (hi, kind) = if self.eat(&token::Not) { . // MACRO INVOCATION expression . if qself.is_some() { . self.struct_span_err(path.span, "macros cannot use qualified paths").emit(); . } . let mac = MacCall { . path, . args: self.parse_mac_args()?, . prior_type_ascription: self.last_type_ascription, . }; . (self.prev_token.span, ExprKind::MacCall(mac)) 125 ( 0.00%) } else if self.check(&token::OpenDelim(token::Brace)) { . if let Some(expr) = self.maybe_parse_struct_expr(qself.as_ref(), &path, &attrs) { . 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)) . }; . 50 ( 0.00%) let expr = self.mk_expr(lo.to(hi), kind, attrs); 75 ( 0.00%) self.maybe_recover_from_bad_qpath(expr, true) 300 ( 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 1607 ---------------------------------------- . symbol_unescaped, . }), . _ => Err(Some(lit)), . }, . None => Err(None), . } . } . 144 ( 0.00%) pub(super) fn parse_lit(&mut self) -> PResult<'a, Lit> { 16 ( 0.00%) self.parse_opt_lit().ok_or_else(|| { 20 ( 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(); . } . } . } 110 ( 0.00%) let msg = format!("unexpected token: {}", super::token_descr(&self.token)); 10 ( 0.00%) self.struct_span_err(self.token.span, &msg) . }) 112 ( 0.00%) } . . /// Matches `lit = true | false | token_lit`. . /// Returns `None` if the next token is not a literal. 24,876 ( 0.01%) pub(super) fn parse_opt_lit(&mut self) -> Option { 2,764 ( 0.00%) let mut recovered = None; 16,584 ( 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); 8,322 ( 0.00%) match Lit::from_token(token) { 16,524 ( 0.01%) Ok(lit) => { 5,508 ( 0.00%) self.bump(); 16,524 ( 0.01%) Some(lit) . } 10 ( 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!())) . } . } 22,112 ( 0.01%) } . . 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 1815 ---------------------------------------- . AttrVec::new(), . )) . } else { . Ok(expr) . } . } . . fn is_array_like_block(&mut self) -> bool { 3 ( 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. 14 ( 0.00%) pub(super) fn parse_block_expr( . &mut self, . opt_label: Option

(self, predicate: P) -> Self . where . T: ~const Drop, . P: ~const FnOnce(&T) -> bool, . P: ~const Drop, . { 69 ( 0.00%) if let Some(x) = self { 6 ( 0.00%) if predicate(&x) { . return Some(x); . } . } . None . } . . /// Returns the option if it contains a value, otherwise returns `optb`. . /// -- line 1274 ---------------------------------------- -- 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, . { 164 ( 0.00%) match self { . Some(x) => Some(x), . None => optb, . } . } . . /// Returns the option if it contains a value, otherwise calls `f` and . /// returns the result. . /// -- line 1315 ---------------------------------------- -- 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, . { 30,344 ( 0.01%) match self { 43 ( 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, . { 270 ( 0.00%) if let None = *self { 630 ( 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, . { 15,574 ( 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. . 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 1515 ---------------------------------------- -- 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 { 28 ( 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 507 ( 0.00%) match self { 37,741 ( 0.01%) Some(&v) => Some(v), 14 ( 0.00%) None => None, . } . } . . /// Maps an `Option<&T>` to an `Option` by cloning the contents of the . /// option. . /// . /// # Examples . /// -- line 1730 ---------------------------------------- -- 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")] 168 ( 0.00%) pub const fn cloned(self) -> Option . where . T: ~const Clone, . { 7,113 ( 0.00%) match self { 63,101 ( 0.02%) Some(t) => Some(t.clone()), 110 ( 0.00%) None => None, . } 268 ( 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 { 106,629 ( 0.04%) match self { 540 ( 0.00%) Some(x) => Some(x.clone()), 13 ( 0.00%) None => None, . } 17,242 ( 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) { 20,715 ( 0.01%) 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) { 1 ( 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) 35 ( 0.00%) } . . #[inline] . fn branch(self) -> ControlFlow { 79,347 ( 0.03%) match self { 10,566 ( 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 { 9,111 ( 0.00%) None => None, . } . } . } . . #[unstable(feature = "try_trait_v2_residual", issue = "91285")] . impl ops::Residual for Option { . type TryType = Option; . } -- line 2274 ---------------------------------------- 399,579 ( 0.15%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/md-5-0.9.1/src/utils.rs -------------------------------------------------------------------------------- Ir . #![allow(clippy::many_single_char_names)] . use crate::consts::RC; . use core::convert::TryInto; . . #[inline(always)] . fn op_f(w: u32, x: u32, y: u32, z: u32, m: u32, c: u32, s: u32) -> u32 { 86,349 ( 0.03%) ((x & y) | (!x & z)) . .wrapping_add(w) . .wrapping_add(m) . .wrapping_add(c) . .rotate_left(s) . .wrapping_add(x) . } . #[inline(always)] . fn op_g(w: u32, x: u32, y: u32, z: u32, m: u32, c: u32, s: u32) -> u32 { 82,314 ( 0.03%) ((x & z) | (y & !z)) . .wrapping_add(w) . .wrapping_add(m) . .wrapping_add(c) . .rotate_left(s) . .wrapping_add(x) . } . . #[inline(always)] . fn op_h(w: u32, x: u32, y: u32, z: u32, m: u32, c: u32, s: u32) -> u32 { 40,350 ( 0.01%) (x ^ y ^ z) . .wrapping_add(w) . .wrapping_add(m) . .wrapping_add(c) . .rotate_left(s) . .wrapping_add(x) . } . . #[inline(always)] . fn op_i(w: u32, x: u32, y: u32, z: u32, m: u32, c: u32, s: u32) -> u32 { 51,648 ( 0.02%) (y ^ (x | !z)) . .wrapping_add(w) . .wrapping_add(m) . .wrapping_add(c) . .rotate_left(s) . .wrapping_add(x) . } . . #[inline] 7,263 ( 0.00%) pub fn compress(state: &mut [u32; 4], input: &[u8; 64]) { 1,614 ( 0.00%) let mut a = state[0]; 807 ( 0.00%) let mut b = state[1]; 807 ( 0.00%) let mut c = state[2]; 807 ( 0.00%) let mut d = state[3]; . . let mut data = [0u32; 16]; . for (o, chunk) in data.iter_mut().zip(input.chunks_exact(4)) { 20,175 ( 0.01%) *o = u32::from_le_bytes(chunk.try_into().unwrap()); . } . . // round 1 . a = op_f(a, b, c, d, data[0], RC[0], 7); . d = op_f(d, a, b, c, data[1], RC[1], 12); . c = op_f(c, d, a, b, data[2], RC[2], 17); . b = op_f(b, c, d, a, data[3], RC[3], 22); . -- line 61 ---------------------------------------- -- line 132 ---------------------------------------- . c = op_i(c, d, a, b, data[6], RC[58], 15); . b = op_i(b, c, d, a, data[13], RC[59], 21); . . a = op_i(a, b, c, d, data[4], RC[60], 6); . d = op_i(d, a, b, c, data[11], RC[61], 10); . c = op_i(c, d, a, b, data[2], RC[62], 15); . b = op_i(b, c, d, a, data[9], RC[63], 21); . 1,614 ( 0.00%) state[0] = state[0].wrapping_add(a); 807 ( 0.00%) state[1] = state[1].wrapping_add(b); 807 ( 0.00%) state[2] = state[2].wrapping_add(c); 807 ( 0.00%) state[3] = state[3].wrapping_add(d); 6,456 ( 0.00%) } -------------------------------------------------------------------------------- -- 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 { 2 ( 0.00%) qualifs.has_mut_interior . } . . fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool { 49,206 ( 0.02%) !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. -- line 102 ---------------------------------------- -- line 115 ---------------------------------------- . 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 { . qualifs.needs_drop . } . 21,880 ( 0.01%) fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool { 5,470 ( 0.00%) ty.needs_drop(cx.tcx, cx.param_env) 24,615 ( 0.01%) } . . fn in_adt_inherently<'tcx>( . cx: &ConstCx<'_, 'tcx>, . adt: &'tcx AdtDef, . _: SubstsRef<'tcx>, . ) -> bool { . adt.has_dtor(cx.tcx) . } -- line 133 ---------------------------------------- -- 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 . } . 27 ( 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. 12 ( 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() . }) 27 ( 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 223 ---------------------------------------- . } . . 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`). 9 ( 0.00%) traits::search_for_structural_match_violation(cx.body.span, cx.tcx, ty).is_some() . } . . fn in_adt_inherently<'tcx>( . cx: &ConstCx<'_, 'tcx>, . adt: &'tcx AdtDef, . substs: SubstsRef<'tcx>, . ) -> bool { . let ty = cx.tcx.mk_ty(ty::Adt(adt, substs)); . !ty.is_structural_eq_shallow(cx.tcx) . } . } . . // FIXME: Use `mir::visit::Visitor` for the `in_*` functions if/when it supports early return. . . /// Returns `true` if this `Rvalue` contains qualif `Q`. 54,760 ( 0.02%) 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, . { 27,380 ( 0.01%) 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, _) 10 ( 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) . } . 4 ( 0.00%) Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => { . // Special-case reborrows to be more like a copy of the reference. . if let Some((place_base, ProjectionElem::Deref)) = place.as_ref().last_projection() { . let base_ty = place_base.ty(cx.body, cx.tcx).ty; . if let ty::Ref(..) = base_ty.kind() { . return in_place::(cx, in_local, place_base); . } . } . 12 ( 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. 16,416 ( 0.01%) if let AggregateKind::Adt(adt_did, _, substs, ..) = **kind { . let def = cx.tcx.adt_def(adt_did); . if Q::in_adt_inherently(cx, def, substs) { . return true; . } . if def.is_union() && Q::in_any_value_of_ty(cx, rvalue.ty(cx.body, cx.tcx)) { . return true; . } . } . . // Otherwise, proceed structurally... 73,764 ( 0.03%) operands.iter().any(|o| in_operand::(cx, in_local, o)) . } . } 45,160 ( 0.02%) } . . /// Returns `true` if this `Place` contains qualif `Q`. 68,340 ( 0.03%) 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, . { 18 ( 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()); 10 ( 0.00%) in_local(place.local) . } . . /// Returns `true` if this `Operand` contains qualif `Q`. 143,448 ( 0.05%) 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, . { 32,788 ( 0.01%) let constant = match operand { . Operand::Copy(place) | Operand::Move(place) => { 40,980 ( 0.02%) return in_place::(cx, in_local, place.as_ref()); . } . . Operand::Constant(c) => c, . }; . . // Check the qualifs of the value of `const` items. 54,650 ( 0.02%) if let Some(ct) = constant.literal.const_for_ty() { 21,860 ( 0.01%) 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. 2 ( 0.00%) assert!(promoted.is_none() || Q::ALLOW_PROMOTED); . // Don't peek inside trait associated constants. 2 ( 0.00%) if promoted.is_none() && cx.tcx.trait_of_item(def.did).is_none() { 20 ( 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) . }; . 2 ( 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. 30,052 ( 0.01%) Q::in_any_value_of_ty(cx, constant.literal.ty()) 116,126 ( 0.04%) } 4,148 ( 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}; . 774 ( 0.00%) #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub enum CommentKind { . Line, . Block, . } . 23 ( 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. 5,731 ( 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, . } . 122 ( 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. 6,020 ( 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 { 13,675 ( 0.01%) fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 24,615 ( 0.01%) let Lit { kind, symbol, suffix } = *self; . match kind { . Byte => write!(f, "b'{}'", symbol)?, 8,196 ( 0.00%) Char => write!(f, "'{}'", symbol)?, . 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 . )?, 9 ( 0.00%) Integer | Float | Bool | Err => write!(f, "{}", symbol)?, . } . 5,470 ( 0.00%) if let Some(suffix) = suffix { . write!(f, "{}", suffix)?; . } . . Ok(()) 13,675 ( 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 } 19,145 ( 0.01%) } . } . . pub fn ident_can_begin_expr(name: Symbol, span: Span, is_raw: bool) -> bool { . let ident_token = Token::new(Ident(name, is_raw), span); . . !ident_token.is_reserved_ident() . || ident_token.is_path_segment_keyword() . || [ -- line 146 ---------------------------------------- -- line 172 ---------------------------------------- . let ident_token = Token::new(Ident(name, is_raw), span); . . !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) . } . 785,233 ( 0.29%) #[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, 336 ( 0.00%) BinOp(BinOpToken), . BinOpEq(BinOpToken), . . /* Structural symbols */ . At, . Dot, . DotDot, . DotDotDot, . DotDotEq, -- line 202 ---------------------------------------- -- 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., `{`). 702 ( 0.00%) OpenDelim(DelimToken), . /// A closing delimiter (e.g., `}`). 24,867 ( 0.01%) CloseDelim(DelimToken), . . /* Literals */ 8,656 ( 0.00%) Literal(Lit), . . /// Identifier token. . /// Do not forget about `NtIdent` when you want to match on identifiers. . /// It's recommended to use `Token::(ident,uninterpolate,uninterpolated_span)` to . /// treat regular and interpolated identifiers in the same way. 391 ( 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. . Lifetime(Symbol), . . Interpolated(Lrc), . . /// A doc comment token. . /// `Symbol` is the doc comment's data excluding its "quotes" (`///`, `/**`, etc) . /// similarly to symbols in string literal tokens. 102 ( 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); . 28,183 ( 0.01%) #[derive(Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub struct Token { 422 ( 0.00%) pub kind: TokenKind, . 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`. 54 ( 0.00%) pub fn break_two_token_op(&self) -> Option<(TokenKind, TokenKind)> { 216 ( 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), 54 ( 0.00%) _ => return None, . }) 54 ( 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]), -- line 298 ---------------------------------------- -- line 301 ---------------------------------------- . } . . pub fn should_end_const_arg(&self) -> bool { . matches!(self, Gt | Ge | BinOp(Shr) | BinOpEq(Shr)) . } . } . . impl Token { 10,133 ( 0.00%) pub fn new(kind: TokenKind, span: Span) -> Self { 30,567 ( 0.01%) Token { kind, span } 10,133 ( 0.00%) } . . /// Some token that will be thrown away later. 56 ( 0.00%) pub fn dummy() -> Self { . Token::new(TokenKind::Question, DUMMY_SP) 56 ( 0.00%) } . . /// Recovers a `Token` from an `Ident`. This creates a raw identifier if necessary. . pub fn from_ast_ident(ident: Ident) -> Self { . Token::new(Ident(ident.name, ident.is_raw_guess()), ident.span) . } . . /// Return this token by value and leave a dummy token in its place. 5,832 ( 0.00%) pub fn take(&mut self) -> Self { . mem::replace(self, Token::dummy()) 5,832 ( 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 { 12 ( 0.00%) match &self.kind { . Interpolated(nt) => nt.span(), 6 ( 0.00%) _ => self.span, . } 6 ( 0.00%) } . . pub fn is_op(&self) -> bool { 17,496 ( 0.01%) !matches!( 5,832 ( 0.00%) self.kind, . OpenDelim(..) . | CloseDelim(..) . | Literal(..) . | DocComment(..) . | Ident(..) . | Lifetime(..) . | Interpolated(..) . | Eof . ) 5,832 ( 0.00%) } . . pub fn is_like_plus(&self) -> bool { 245 ( 0.00%) matches!(self.kind, BinOp(Plus) | BinOpEq(Plus)) 49 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of an expression. . pub fn can_begin_expr(&self) -> bool { . match self.uninterpolate().kind { . Ident(name, is_raw) => . ident_can_begin_expr(name, self.span, is_raw), // value name or keyword . OpenDelim(..) | // tuple, array or block . Literal(..) | // literal -- line 365 ---------------------------------------- -- line 427 ---------------------------------------- . } . . /// Returns `true` if the token is any literal, a minus (which can prefix a literal, . /// for example a '-42', or one of the boolean idents). . /// . /// In other words, would this token be a valid start of `parse_literal_maybe_minus`? . /// . /// Keep this in sync with and `Lit::from_token`, excluding unary negation. 2 ( 0.00%) pub fn can_begin_literal_maybe_minus(&self) -> bool { 20 ( 0.00%) match self.uninterpolate().kind { . Literal(..) | BinOp(Minus) => true, 8 ( 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, . } 4 ( 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. 4,170 ( 0.00%) pub fn uninterpolate(&self) -> Cow<'_, Token> { 42,784 ( 0.02%) match &self.kind { . Interpolated(nt) => match **nt { . NtIdent(ident, is_raw) => { . 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), . } 4,170 ( 0.00%) } . . /// Returns an identifier if this token is an identifier. 12,677 ( 0.00%) pub fn ident(&self) -> Option<(Ident, /* is_raw */ bool)> { . let token = self.uninterpolate(); 27,490 ( 0.01%) match token.kind { 12,116 ( 0.00%) Ident(name, is_raw) => Some((Ident::new(name, token.span), is_raw)), . _ => None, . } 76,707 ( 0.03%) } . . /// Returns a lifetime identifier if this token is a lifetime. 8 ( 0.00%) pub fn lifetime(&self) -> Option { . let token = self.uninterpolate(); 32 ( 0.00%) match token.kind { . Lifetime(name) => Some(Ident::new(name, token.span)), . _ => None, . } 56 ( 0.00%) } . . /// Returns `true` if the token is an identifier. . pub fn is_ident(&self) -> bool { . self.ident().is_some() 22 ( 0.00%) } . . /// Returns `true` if the token is a lifetime. 8 ( 0.00%) pub fn is_lifetime(&self) -> bool { . self.lifetime().is_some() 16 ( 0.00%) } . . /// Returns `true` if the token is an identifier whose name is the given . /// string slice. 26 ( 0.00%) pub fn is_ident_named(&self, name: Symbol) -> bool { . self.ident().map_or(false, |(ident, _)| ident.name == name) 52 ( 0.00%) } . . /// Returns `true` if the token is an interpolated path. . fn is_path(&self) -> bool { 240 ( 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 { 2 ( 0.00%) if let Interpolated(ref nt) = self.kind { . if let NtBlock(..) = **nt { . return true; . } . } . false 1 ( 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) . } . 12 ( 0.00%) pub fn is_qpath_start(&self) -> bool { 132 ( 0.00%) self == &Lt || self == &BinOp(Shl) . } . 240 ( 0.00%) pub fn is_path_start(&self) -> bool { 350 ( 0.00%) self == &ModSep . || self.is_qpath_start() . || self.is_path() . || self.is_path_segment_keyword() 43 ( 0.00%) || self.is_ident() && !self.is_reserved_ident() 300 ( 0.00%) } . . /// Returns `true` if the token is a given keyword, `kw`. 856 ( 0.00%) pub fn is_keyword(&self, kw: Symbol) -> bool { . self.is_non_raw_ident_where(|id| id.name == kw) 1,712 ( 0.00%) } . 6 ( 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. 10 ( 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. 10 ( 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. 10 ( 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`. 6 ( 0.00%) pub fn is_bool_lit(&self) -> bool { 12 ( 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. 8 ( 0.00%) pub fn is_non_raw_ident_where(&self, pred: impl FnOnce(Ident) -> bool) -> bool { 63,352 ( 0.02%) match self.ident() { 44 ( 0.00%) Some((id, false)) => pred(id), . _ => false, . } 10 ( 0.00%) } . 14,570 ( 0.01%) pub fn glue(&self, joint: &Token) -> Option { 7,285 ( 0.00%) let kind = match self.kind { 3 ( 0.00%) Eq => match joint.kind { . Eq => EqEq, . Gt => FatArrow, . _ => return None, . }, 30 ( 0.00%) Lt => match joint.kind { . Eq => Le, . Lt => BinOp(Shl), . Le => BinOpEq(Shl), . BinOp(Minus) => LArrow, . _ => return None, . }, . Gt => match joint.kind { . Eq => Ge, -- line 620 ---------------------------------------- -- line 621 ---------------------------------------- . Gt => BinOp(Shr), . Ge => BinOpEq(Shr), . _ => return None, . }, . Not => match joint.kind { . Eq => Ne, . _ => return None, . }, 212 ( 0.00%) BinOp(op) => match joint.kind { . Eq => BinOpEq(op), 8 ( 0.00%) BinOp(And) if op == And => AndAnd, 6 ( 0.00%) BinOp(Or) if op == Or => OrOr, 7 ( 0.00%) Gt if op == Minus => RArrow, . _ => return None, . }, . Dot => match joint.kind { . Dot => DotDot, . DotDot => DotDotDot, . _ => return None, . }, . DotDot => match joint.kind { . Dot => DotDotDot, . Eq => DotDotEq, . _ => return None, . }, 18 ( 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, . }; . 520 ( 0.00%) Some(Token::new(kind, self.span.to(joint.span))) 13,113 ( 0.00%) } . } . . impl PartialEq for Token { . fn eq(&self, rhs: &TokenKind) -> bool { 38,095 ( 0.01%) self.kind == *rhs . } . } . . #[derive(Clone, Encodable, Decodable)] . /// For interpolation during macro expansion. . pub enum Nonterminal { . NtItem(P), . NtBlock(P), -- line 675 ---------------------------------------- -- line 711 ---------------------------------------- . Path, . Vis, . TT, . } . . impl NonterminalKind { . /// The `edition` closure is used to get the edition for the given symbol. Doing . /// `span.edition()` is expensive, so we do it lazily. 4 ( 0.00%) pub fn from_symbol( . symbol: Symbol, . edition: impl FnOnce() -> Edition, . ) -> Option { 10 ( 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, . }) 4 ( 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 ---------------------------------------- 296,575 ( 0.11%) -------------------------------------------------------------------------------- -- 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, . ) { 1,512 ( 0.00%) if let Some((file, file_idx)) = new_file_and_idx { 51 ( 0.00%) self.file = file; 69 ( 0.00%) self.file_index = file_idx; . } . 1,431 ( 0.00%) let line_index = self.file.lookup_line(pos).unwrap(); . let line_bounds = self.file.line_bounds(line_index); 2,942 ( 0.00%) self.line_number = line_index + 1; 4,398 ( 0.00%) self.line = line_bounds; . self.touch(time_stamp); . } . . #[inline] . fn touch(&mut self, time_stamp: usize) { 13,612 ( 0.00%) 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> { 60 ( 0.00%) pub fn new(source_map: &'sm SourceMap) -> CachingSourceMapView<'sm> { . let files = source_map.files(); 30 ( 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, . }; . 150 ( 0.00%) CachingSourceMapView { . source_map, 210 ( 0.00%) line_cache: [entry.clone(), entry.clone(), entry], . time_stamp: 0, . } 120 ( 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)) . } . 52,752 ( 0.02%) pub fn span_data_to_lines_and_cols( . &mut self, . span_data: &SpanData, . ) -> Option<(Lrc, usize, BytePos, usize, BytePos)> { 30,144 ( 0.01%) self.time_stamp += 1; . . // Check if lo and hi are in the cached lines. 7,536 ( 0.00%) let lo_cache_idx = self.cache_entry_index(span_data.lo); 7,536 ( 0.00%) let hi_cache_idx = self.cache_entry_index(span_data.hi); . 12,154 ( 0.00%) 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 = { 12,152 ( 0.00%) let lo = &self.line_cache[lo_cache_idx as usize]; . let hi = &self.line_cache[hi_cache_idx as usize]; . 36,456 ( 0.01%) if lo.file_index != hi.file_index { . return None; . } . . ( 12,152 ( 0.00%) lo.file.clone(), . lo.line_number, . span_data.lo - lo.line.start, 6,076 ( 0.00%) hi.line_number, . span_data.hi - hi.line.start, . ) . }; . 6,076 ( 0.00%) self.line_cache[lo_cache_idx as usize].touch(self.time_stamp); 6,076 ( 0.00%) self.line_cache[hi_cache_idx as usize].touch(self.time_stamp); . 24,304 ( 0.01%) return Some(result); . } . . // No cache hit or cache hit for only one of span lo and hi. 2,918 ( 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. 11,680 ( 0.00%) let new_file_and_idx = if !file_contains(&self.line_cache[oldest].file, span_data.lo) { 145 ( 0.00%) let new_file_and_idx = self.file_for_position(span_data.lo)?; 174 ( 0.00%) if !file_contains(&new_file_and_idx.0, span_data.hi) { . return None; . } . 116 ( 0.00%) Some(new_file_and_idx) . } else { . let file = &self.line_cache[oldest].file; 4,293 ( 0.00%) if !file_contains(&file, span_data.hi) { . return None; . } . 4,293 ( 0.00%) None . }; . . // Update the cache entries. 7,300 ( 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); . 4,299 ( 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); 2 ( 0.00%) let hi = &mut self.line_cache[hi_cache_idx as usize]; 3 ( 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]; 26 ( 0.00%) hi.update(new_file_and_idx, span_data.hi, self.time_stamp); 52 ( 0.00%) let lo = &mut self.line_cache[lo_cache_idx as usize]; 104 ( 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. 2,920 ( 0.00%) assert!(span_data.lo >= lo.line.start); 1,460 ( 0.00%) assert!(span_data.lo <= lo.line.end); 2,920 ( 0.00%) assert!(span_data.hi >= hi.line.start); 1,460 ( 0.00%) assert!(span_data.hi <= hi.line.end); 7,300 ( 0.00%) assert!(lo.file.contains(span_data.lo)); 4,380 ( 0.00%) assert!(lo.file.contains(span_data.hi)); 4,380 ( 0.00%) assert_eq!(lo.file_index, hi.file_index); . 4,380 ( 0.00%) Some(( 1,460 ( 0.00%) lo.file.clone(), . lo.line_number, . span_data.lo - lo.line.start, 1,460 ( 0.00%) hi.line_number, . span_data.hi - hi.line.start, . )) 67,824 ( 0.02%) } . . fn cache_entry_index(&self, pos: BytePos) -> isize { . for (idx, cache_entry) in self.line_cache.iter().enumerate() { 96,651 ( 0.04%) 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() { 8,598 ( 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() { 232 ( 0.00%) if idx != avoid_idx 118 ( 0.00%) && self.line_cache[idx].time_stamp < self.line_cache[oldest].time_stamp . { . oldest = idx; . } . } . . oldest . } . 145 ( 0.00%) fn file_for_position(&self, pos: BytePos) -> Option<(Lrc, usize)> { 29 ( 0.00%) if !self.source_map.files().is_empty() { 58 ( 0.00%) let file_idx = self.source_map.lookup_source_file_idx(pos); . let file = &self.source_map.files()[file_idx]; . 232 ( 0.00%) if file_contains(file, pos) { . return Some((file.clone(), file_idx)); . } . } . . None 145 ( 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 ---------------------------------------- 104,283 ( 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>> { 65 ( 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>> { 24 ( 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 { 1,480 ( 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), . .. . }) 238 ( 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>); . 42 ( 0.00%) fn next(&mut self) -> Option { 6 ( 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); . 18 ( 0.00%) if parent_id == self.current_id { . self.current_id = CRATE_HIR_ID; . return None; . } . 12 ( 0.00%) self.current_id = parent_id; 48 ( 0.00%) if let Some(node) = self.map.find(parent_id) { 24 ( 0.00%) return Some((parent_id, node)); . } . // If this `HirId` doesn't have an entry, skip it and look for its `parent_id`. . } 54 ( 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>); . 738 ( 0.00%) fn next(&mut self) -> Option { 246 ( 0.00%) if self.current_id.local_id.index() != 0 { 35 ( 0.00%) self.current_id.local_id = ItemLocalId::new(0); 140 ( 0.00%) if let Some(node) = self.map.tcx.hir_owner(self.current_id.owner) { . return Some((self.current_id.owner, node.node)); . } . } 47 ( 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 . }); 90 ( 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`. 90 ( 0.00%) if let Some(node) = self.map.tcx.hir_owner(self.current_id.owner) { . return Some((self.current_id.owner, node.node)); . } . } 656 ( 0.00%) } . } . . impl<'hir> Map<'hir> { 217 ( 0.00%) pub fn krate(&self) -> &'hir Crate<'hir> { 31 ( 0.00%) self.tcx.hir_crate(()) 248 ( 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] 1,044 ( 0.00%) pub fn local_def_id(&self, hir_id: HirId) -> LocalDefId { 426 ( 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) . ) . }) 783 ( 0.00%) } . . #[inline] 1,136 ( 0.00%) pub fn opt_local_def_id(&self, hir_id: HirId) -> Option { 246 ( 0.00%) if hir_id.local_id == ItemLocalId::new(0) { . Some(hir_id.owner) . } else { 46 ( 0.00%) self.tcx . .hir_owner_nodes(hir_id.owner)? . .local_id_to_def_id . .get(&hir_id.local_id) . .copied() . } 1,278 ( 0.00%) } . . #[inline] . pub fn local_def_id_to_hir_id(&self, def_id: LocalDefId) -> HirId { . // FIXME(#85914) is this access safe for incr. comp.? 101 ( 0.00%) self.tcx.untracked_resolutions.definitions.local_def_id_to_hir_id(def_id) . } . 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%) } . 245 ( 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); 455 ( 0.00%) let def_kind = match self.find(hir_id)? { 88 ( 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, . }, 4 ( 0.00%) Node::TraitItem(item) => match item.kind { . TraitItemKind::Const(..) => DefKind::AssocConst, . TraitItemKind::Fn(..) => DefKind::AssocFn, . TraitItemKind::Type(..) => DefKind::AssocTy, . }, 2 ( 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`? . assert_ne!(variant_data.ctor_hir_id(), None); -- line 268 ---------------------------------------- -- line 279 ---------------------------------------- . 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, 5 ( 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)), . }, . Node::GenericParam(param) => match param.kind { . GenericParamKind::Lifetime { .. } => DefKind::LifetimeParam, . GenericParamKind::Type { .. } => DefKind::TyParam, . GenericParamKind::Const { .. } => DefKind::ConstParam, -- line 295 ---------------------------------------- -- line 304 ---------------------------------------- . | Node::Binding(_) . | Node::Local(_) . | Node::Param(_) . | Node::Arm(_) . | Node::Lifetime(_) . | Node::Visibility(_) . | Node::Block(_) => return None, . }; 112 ( 0.00%) Some(def_kind) 350 ( 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)) . } . 126,744 ( 0.05%) pub fn find_parent_node(&self, id: HirId) -> Option { 15,843 ( 0.01%) if id.local_id == ItemLocalId::from_u32(0) { . Some(self.tcx.hir_owner_parent(id.owner)) . } else { 31,560 ( 0.01%) let owner = self.tcx.hir_owner_nodes(id.owner)?; 15,780 ( 0.01%) let node = owner.nodes[id.local_id].as_ref()?; 47,340 ( 0.02%) let hir_id = HirId { owner: id.owner, local_id: node.parent }; . Some(hir_id) . } 126,744 ( 0.05%) } . 22 ( 0.00%) pub fn get_parent_node(&self, hir_id: HirId) -> HirId { 93,909 ( 0.03%) self.find_parent_node(hir_id).unwrap() 44 ( 0.00%) } . . /// Retrieves the `Node` corresponding to `id`, returning `None` if cannot be found. 18,664 ( 0.01%) pub fn find(&self, id: HirId) -> Option> { 2,333 ( 0.00%) if id.local_id == ItemLocalId::from_u32(0) { . let owner = self.tcx.hir_owner(id.owner)?; 793 ( 0.00%) Some(owner.node.into()) . } else { 3,058 ( 0.00%) let owner = self.tcx.hir_owner_nodes(id.owner)?; 1,529 ( 0.00%) let node = owner.nodes[id.local_id].as_ref()?; 4,587 ( 0.00%) Some(node.node) . } 18,664 ( 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> { 207 ( 0.00%) self.find(self.local_def_id_to_hir_id(id)) . } . . /// Retrieves the `Node` corresponding to `id`, panicking if it cannot be found. 645 ( 0.00%) pub fn get(&self, id: HirId) -> Node<'hir> { 324 ( 0.00%) self.find(id).unwrap_or_else(|| bug!("couldn't find hir id {} in the HIR map", id)) 430 ( 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)) . } . 20 ( 0.00%) pub fn get_if_local(&self, id: DefId) -> Option> { 10 ( 0.00%) id.as_local().and_then(|id| self.find(self.local_def_id_to_hir_id(id))) 20 ( 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, . } . } . 4,004 ( 0.00%) pub fn item(&self, id: ItemId) -> &'hir Item<'hir> { 1,144 ( 0.00%) self.tcx.hir_owner(id.def_id).unwrap().node.expect_item() 4,576 ( 0.00%) } . 378 ( 0.00%) pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> { 108 ( 0.00%) self.tcx.hir_owner(id.def_id).unwrap().node.expect_trait_item() 432 ( 0.00%) } . 406 ( 0.00%) pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> { 116 ( 0.00%) self.tcx.hir_owner(id.def_id).unwrap().node.expect_impl_item() 464 ( 0.00%) } . . pub fn foreign_item(&self, id: ForeignItemId) -> &'hir ForeignItem<'hir> { . self.tcx.hir_owner(id.def_id).unwrap().node.expect_foreign_item() . } . 2,051 ( 0.00%) pub fn body(&self, id: BodyId) -> &'hir Body<'hir> { 586 ( 0.00%) self.tcx.hir_owner_nodes(id.hir_id.owner).unwrap().bodies[&id.hir_id.local_id] 2,344 ( 0.00%) } . 39 ( 0.00%) pub fn fn_decl_by_hir_id(&self, hir_id: HirId) -> Option<&'hir FnDecl<'hir>> { 39 ( 0.00%) if let Some(node) = self.find(hir_id) { . fn_decl(node) . } else { . bug!("no node for hir_id `{}`", hir_id) . } 26 ( 0.00%) } . 9 ( 0.00%) pub fn fn_sig_by_hir_id(&self, hir_id: HirId) -> Option<&'hir FnSig<'hir>> { 9 ( 0.00%) if let Some(node) = self.find(hir_id) { . fn_sig(node) . } else { . bug!("no node for hir_id `{}`", hir_id) . } 9 ( 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`. 1,400 ( 0.00%) pub fn body_owner(&self, BodyId { hir_id }: BodyId) -> HirId { . let parent = self.get_parent_node(hir_id); 1,050 ( 0.00%) assert!(self.find(parent).map_or(false, |n| is_body_owner(n, hir_id))); . parent 1,400 ( 0.00%) } . 450 ( 0.00%) pub fn body_owner_def_id(&self, id: BodyId) -> LocalDefId { 710 ( 0.00%) self.local_def_id(self.body_owner(id)) 450 ( 0.00%) } . . /// Given a `HirId`, returns the `BodyId` associated with it, . /// if the node is a body owner, otherwise returns `None`. 71 ( 0.00%) pub fn maybe_body_owned_by(&self, hir_id: HirId) -> Option { 231 ( 0.00%) self.find(hir_id).map(associated_body).flatten() 213 ( 0.00%) } . . /// Given a body owner's id, returns the `BodyId` associated with it. 162 ( 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) . ); . }) 126 ( 0.00%) } . 5 ( 0.00%) pub fn body_param_names(&self, id: BodyId) -> impl Iterator + 'hir { 39 ( 0.00%) self.body(id).params.iter().map(|arg| match arg.pat.kind { 12 ( 0.00%) PatKind::Binding(_, _, ident, _) => ident, . _ => Ident::empty(), . }) 15 ( 0.00%) } . . /// Returns the `BodyOwnerKind` of this `LocalDefId`. . /// . /// Panics if `LocalDefId` does not have an associated body. 321 ( 0.00%) pub fn body_owner_kind(&self, id: HirId) -> BodyOwnerKind { 895 ( 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), . } 321 ( 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. 432 ( 0.00%) pub fn body_const_context(&self, did: LocalDefId) -> Option { . let hir_id = self.local_def_id_to_hir_id(did); 648 ( 0.00%) let ccx = match self.body_owner_kind(hir_id) { . BodyOwnerKind::Const => ConstContext::Const, . BodyOwnerKind::Static(mt) => ConstContext::Static(mt), . 30 ( 0.00%) BodyOwnerKind::Fn if self.tcx.is_constructor(did.to_def_id()) => return None, 30 ( 0.00%) BodyOwnerKind::Fn if self.tcx.is_const_fn_raw(did.to_def_id()) => ConstContext::ConstFn, . BodyOwnerKind::Fn 60 ( 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) 486 ( 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)| { 105 ( 0.00%) let bodies = &owner_info.as_ref()?.nodes.bodies; . Some(bodies.iter().map(move |&(local_id, _)| { 1 ( 0.00%) let hir_id = HirId { owner, local_id }; . let body_id = BodyId { hir_id }; 87 ( 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); 210 ( 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 }; 81 ( 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)), . } . } . 117 ( 0.00%) pub fn trait_impls(&self, trait_did: DefId) -> &'hir [LocalDefId] { 13 ( 0.00%) self.tcx.all_local_trait_impls(()).get(&trait_did).map_or(&[], |xs| &xs[..]) 117 ( 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] { 47 ( 0.00%) self.attrs(CRATE_HIR_ID) . } . 119 ( 0.00%) pub fn get_module(&self, module: LocalDefId) -> (&'hir Mod<'hir>, Span, HirId) { . let hir_id = HirId::make_owner(module); 85 ( 0.00%) match self.tcx.hir_owner(module).map(|o| o.node) { 12 ( 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), . } 153 ( 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() { 140 ( 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 { 220 ( 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. 144 ( 0.00%) pub fn visit_all_item_likes(&self, visitor: &mut V) . where . V: itemlikevisit::ItemLikeVisitor<'hir>, . { 21 ( 0.00%) let krate = self.krate(); 81 ( 0.00%) for owner in krate.owners.iter().filter_map(Option::as_ref) { 810 ( 0.00%) match owner.node() { 1,034 ( 0.00%) OwnerNode::Item(item) => visitor.visit_item(item), . OwnerNode::ForeignItem(item) => visitor.visit_foreign_item(item), 6 ( 0.00%) OwnerNode::ImplItem(item) => visitor.visit_impl_item(item), . OwnerNode::TraitItem(item) => visitor.visit_trait_item(item), . OwnerNode::Crate(_) => {} . } . } 144 ( 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) { 22 ( 0.00%) Some(OwnerNode::Item(item)) => visitor.visit_item(item), . Some(OwnerNode::ForeignItem(item)) => visitor.visit_foreign_item(item), 2 ( 0.00%) Some(OwnerNode::ImplItem(item)) => visitor.visit_impl_item(item), 2 ( 0.00%) Some(OwnerNode::TraitItem(item)) => visitor.visit_trait_item(item), . Some(OwnerNode::Crate(_)) | None => {} . }) . } . 258 ( 0.00%) pub fn visit_item_likes_in_module(&self, module: LocalDefId, visitor: &mut V) . where . V: ItemLikeVisitor<'hir>, . { 33 ( 0.00%) let module = self.tcx.hir_module_items(module); . 36 ( 0.00%) for id in module.items.iter() { 990 ( 0.00%) visitor.visit_item(self.item(*id)); . } . 36 ( 0.00%) for id in module.trait_items.iter() { 80 ( 0.00%) visitor.visit_trait_item(self.trait_item(*id)); . } . 36 ( 0.00%) for id in module.impl_items.iter() { 78 ( 0.00%) visitor.visit_impl_item(self.impl_item(*id)); . } . 36 ( 0.00%) for id in module.foreign_items.iter() { . visitor.visit_foreign_item(self.foreign_item(*id)); . } 264 ( 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); . 24 ( 0.00%) while let Some(id) = queue.pop_front() { . f(id); 9 ( 0.00%) let items = self.tcx.hir_module_items(id); 96 ( 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`. 6 ( 0.00%) pub fn parent_iter(self, current_id: HirId) -> ParentHirIterator<'hir> { . ParentHirIterator { current_id, map: self } 24 ( 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 } 227 ( 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 792 ---------------------------------------- . } . None . } . . /// 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. 61 ( 0.00%) pub fn get_parent_item(&self, hir_id: HirId) -> LocalDefId { 549 ( 0.00%) if let Some((def_id, _node)) = self.parent_owner_iter(hir_id).next() { . def_id . } else { . CRATE_DEF_ID . } 122 ( 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 { 148 ( 0.00%) for (def_id, node) in self.parent_owner_iter(hir_id) { 72 ( 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)) . ) . } . 392 ( 0.00%) pub fn expect_item(&self, id: LocalDefId) -> &'hir Item<'hir> { 168 ( 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))), . } 448 ( 0.00%) } . 28 ( 0.00%) pub fn expect_impl_item(&self, id: LocalDefId) -> &'hir ImplItem<'hir> { 12 ( 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))), . } 32 ( 0.00%) } . 28 ( 0.00%) pub fn expect_trait_item(&self, id: LocalDefId) -> &'hir TraitItem<'hir> { 12 ( 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))), . } 32 ( 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)), . } . } . 18 ( 0.00%) pub fn opt_name(&self, id: HirId) -> Option { 10 ( 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, . Node::GenericParam(param) => param.name.ident().name, 4 ( 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, . }) 10 ( 0.00%) } . 8 ( 0.00%) pub fn name(&self, id: HirId) -> Symbol { 8 ( 0.00%) match self.opt_name(id) { . Some(name) => name, . None => bug!("no name for {}", self.node_to_string(id)), . } 6 ( 0.00%) } . . /// Given a node ID, gets a list of attributes associated with the AST . /// corresponding to the node-ID. 231,133 ( 0.08%) pub fn attrs(&self, id: HirId) -> &'hir [ast::Attribute] { 33,019 ( 0.01%) self.tcx.hir_attrs(id.owner).get(id.local_id) 264,152 ( 0.10%) } . . /// Gets the span of the definition of the specified HIR node. . /// This is used by `tcx.get_span` 150 ( 0.00%) pub fn span(&self, hir_id: HirId) -> Span { 5,770 ( 0.00%) self.opt_span(hir_id) . .unwrap_or_else(|| bug!("hir::map::Map::span: id not in map: {:?}", hir_id)) 150 ( 0.00%) } . 10,577 ( 0.00%) pub fn opt_span(&self, hir_id: HirId) -> Option { 10,577 ( 0.00%) let span = match self.find(hir_id)? { . Node::Param(param) => param.span, 80 ( 0.00%) Node::Item(item) => match &item.kind { . ItemKind::Fn(sig, _, _) => sig.span, 56 ( 0.00%) _ => item.span, . }, . Node::ForeignItem(foreign_item) => foreign_item.span, 8 ( 0.00%) Node::TraitItem(trait_item) => match &trait_item.kind { 8 ( 0.00%) TraitItemKind::Fn(sig, _) => sig.span, . _ => trait_item.span, . }, 16 ( 0.00%) Node::ImplItem(impl_item) => match &impl_item.kind { 16 ( 0.00%) ImplItemKind::Fn(sig, _) => sig.span, . _ => impl_item.span, . }, . Node::Variant(variant) => variant.span, . 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, -- line 994 ---------------------------------------- -- line 1007 ---------------------------------------- . 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) 15,110 ( 0.01%) } . . /// 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), . } . } . 4 ( 0.00%) pub fn span_if_local(&self, id: DefId) -> Option { 58 ( 0.00%) id.as_local().and_then(|id| self.opt_span(self.local_def_id_to_hir_id(id))) 6 ( 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> { 174 ( 0.00%) self.body(id) . } . . fn item(&self, id: ItemId) -> &'hir Item<'hir> { 272 ( 0.00%) self.item(id) . } . . fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> { 30 ( 0.00%) self.trait_item(id) . } . . fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> { 28 ( 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) 5 ( 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| { 15 ( 0.00%) let stable_crate_id = tcx.resolutions(()).cstore.stable_crate_id(cnum); 3 ( 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), . } . } . 27 ( 0.00%) pub(super) fn hir_module_items(tcx: TyCtxt<'_>, module_id: LocalDefId) -> ModuleItems { 18 ( 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(), . }; . 15 ( 0.00%) let (hir_mod, span, hir_id) = tcx.hir().get_module(module_id); . collector.visit_mod(hir_mod, span, hir_id); . 48 ( 0.00%) let ModuleCollector { submodules, items, trait_items, impl_items, foreign_items, .. } = . collector; 33 ( 0.00%) return ModuleItems { 12 ( 0.00%) submodules: submodules.into_boxed_slice(), 12 ( 0.00%) items: items.into_boxed_slice(), 12 ( 0.00%) trait_items: trait_items.into_boxed_slice(), 12 ( 0.00%) impl_items: impl_items.into_boxed_slice(), 12 ( 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 { 32 ( 0.00%) self.tcx.hir() . } . 110 ( 0.00%) fn visit_item(&mut self, item: &'hir Item<'hir>) { 66 ( 0.00%) self.items.push(item.item_id()); 44 ( 0.00%) if let ItemKind::Mod(..) = item.kind { . // If this declares another module, do not recurse inside it. 2 ( 0.00%) self.submodules.push(item.def_id); . } else { 120 ( 0.00%) intravisit::walk_item(self, item) . } 8 ( 0.00%) } . . fn visit_trait_item(&mut self, item: &'hir TraitItem<'hir>) { 6 ( 0.00%) self.trait_items.push(item.trait_item_id()); 6 ( 0.00%) intravisit::walk_trait_item(self, item) . } . . fn visit_impl_item(&mut self, item: &'hir ImplItem<'hir>) { 6 ( 0.00%) self.impl_items.push(item.impl_item_id()); 6 ( 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) . } . } 24 ( 0.00%) } 43,228 ( 0.02%) -------------------------------------------------------------------------------- The following files chosen for auto-annotation could not be found: -------------------------------------------------------------------------------- ./elf/../sysdeps/x86_64/dl-machine.h ./elf/dl-lookup.c ./elf/do-rel.h ./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/strlen-avx2.S ./string/../sysdeps/x86_64/strcmp.S -------------------------------------------------------------------------------- Ir -------------------------------------------------------------------------------- 78,788,410 (28.88%) events annotated