-------------------------------------------------------------------------------- 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 lsp_types --edition=2018 src/lib.rs --error-format=json --json=diagnostic-rendered-ansi,artifacts,future-incompat --crate-type lib --emit=dep-info,metadata -C embed-bitcode=no -C debuginfo=2 --cfg feature="default" -C metadata=2951920b29c9b06e -C extra-filename=-2951920b29c9b06e --out-dir /usr/home/liquid/tmp/.tmpWT9wYn/target/debug/deps -L dependency=/usr/home/liquid/tmp/.tmpWT9wYn/target/debug/deps --extern bitflags=/usr/home/liquid/tmp/.tmpWT9wYn/target/debug/deps/libbitflags-96ce9d0595c920f6.rmeta --extern serde=/usr/home/liquid/tmp/.tmpWT9wYn/target/debug/deps/libserde-8e040b031b5b6e4f.rmeta --extern serde_json=/usr/home/liquid/tmp/.tmpWT9wYn/target/debug/deps/libserde_json-64b7bbd847e9e8c8.rmeta --extern serde_repr=/usr/home/liquid/tmp/.tmpWT9wYn/target/debug/deps/libserde_repr-64ab1725c7eb960e.so --extern url=/usr/home/liquid/tmp/.tmpWT9wYn/target/debug/deps/liburl-d22e594ce34821a0.rmeta -Adeprecated -Aunknown-lints -Zincremental-verify-ich Data file: results/cgout-w-profiling-lsp-types-0.91.1-Check-Full Events recorded: Ir Events shown: Ir Event sort order: Ir Thresholds: 0.1 Include dirs: User annotated: Auto-annotation: on -------------------------------------------------------------------------------- Ir -------------------------------------------------------------------------------- 34,737,348,990 (100.0%) PROGRAM TOTALS -------------------------------------------------------------------------------- Ir file:function -------------------------------------------------------------------------------- 1,114,621,479 ( 3.21%) ./malloc/malloc.c:_int_free 817,666,097 ( 2.35%) ./malloc/malloc.c:_int_malloc 730,321,869 ( 2.10%) ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:__memcpy_avx_unaligned_erms 650,157,275 ( 1.87%) ./malloc/malloc.c:malloc 331,730,334 ( 0.95%) ./malloc/malloc.c:free 300,886,452 ( 0.87%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/hash/sip.rs:::write 260,555,046 ( 0.75%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/server.rs:> as proc_macro::bridge::server::DispatcherTrait>::dispatch 249,597,216 ( 0.72%) ./elf/../elf/dl-tls.c:_dl_update_slotinfo 193,117,729 ( 0.56%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs:::short_write_process_buffer:: 183,263,366 ( 0.53%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, (), core::hash::BuildHasherDefault>>::from_hash::>::{closure#0}> 171,636,501 ( 0.49%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/client.rs:proc_macro::bridge::scoped_cell::ScopedCell::replace 134,485,560 ( 0.39%) ./malloc/malloc.c:malloc_consolidate 134,348,192 ( 0.39%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/string.rs:alloc::string::String::push 129,544,812 ( 0.37%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs:::short_write_process_buffer:: 122,254,912 ( 0.35%) ./malloc/malloc.c:realloc 112,409,791 ( 0.32%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/rpc.rs:>::decode 109,921,248 ( 0.32%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:alloc::string::String::push 105,889,728 ( 0.30%) ./elf/../elf/dl-tls.c:update_get_addr 104,169,116 ( 0.30%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:core::ptr::drop_in_place::replace::PutBackOnDrop> 100,562,609 ( 0.29%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/mod.rs:::shallow_resolve_ty 98,846,433 ( 0.28%) /usr/home/liquid/rust/worktree-benchmarking/library/std/src/sys/unix/alloc.rs:__rdl_alloc 95,172,777 ( 0.27%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/sty.rs:::eq 94,267,234 ( 0.27%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::from_key_hashed_nocheck:: 91,873,264 ( 0.26%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/mem/mod.rs:proc_macro::bridge::scoped_cell::ScopedCell::replace 91,549,011 ( 0.26%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/scoped_cell.rs:proc_macro::bridge::scoped_cell::ScopedCell::replace 86,052,729 ( 0.25%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/rpc.rs:>::encode 85,158,872 ( 0.25%) ./malloc/malloc.c:_int_realloc 83,847,691 ( 0.24%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs:>, (), core::hash::BuildHasherDefault>>::from_hash::>>::{closure#0}> 83,596,765 ( 0.24%) ./malloc/malloc.c:unlink_chunk.constprop.0 83,241,246 ( 0.24%) ./elf/../sysdeps/x86_64/tls_get_addr.S:__tls_get_addr 83,027,589 ( 0.24%) /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}> 82,902,099 ( 0.24%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs:, (), core::hash::BuildHasherDefault>>::from_hash::>::{closure#0}> 81,523,638 ( 0.23%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:proc_macro::bridge::scoped_cell::ScopedCell::replace 80,408,526 ( 0.23%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/buffer.rs:proc_macro::bridge::scoped_cell::ScopedCell::replace 80,265,801 ( 0.23%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/caching_source_map_view.rs:::span_data_to_lines_and_cols 79,548,648 ( 0.23%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/rpc.rs: as proc_macro::bridge::rpc::DecodeMut>::decode 78,963,551 ( 0.23%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/context.rs:::intern_ty 76,608,361 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/context.rs:::_intern_substs 73,327,071 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:::_intern_substs 72,647,391 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/hash/sip.rs:::write 72,465,456 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/closure.rs:proc_macro::bridge::scoped_cell::ScopedCell::replace 69,690,738 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:>::hash_stable 68,664,679 ( 0.20%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>, (), core::hash::BuildHasherDefault>>::from_hash::>>::{closure#0}> 68,432,456 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/sty.rs:::hash:: 67,319,954 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/buffer.rs:>::encode 66,563,246 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/search.rs:, proc_macro::bridge::client::SourceFile>, alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree:: 64,318,908 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs: as core::iter::traits::iterator::Iterator>::next 63,639,969 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/obligation_forest/mod.rs:>::process_obligations::> 63,407,288 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/mem/mod.rs:core::ptr::drop_in_place::replace::PutBackOnDrop> 61,426,118 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/buffer.rs:>::encode 60,232,794 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/mem/mod.rs:core::mem::replace 59,498,170 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/node.rs:, alloc::collections::btree::node::marker::Leaf>, alloc::collections::btree::node::marker::Edge>>::insert_recursing 58,910,364 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/type_variable.rs:::probe 58,042,991 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::check 56,402,996 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/search.rs:, alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree:: 55,544,458 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/search.rs:>>::insert 53,225,591 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:core::ptr::read 52,478,383 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs:>::hash_stable 51,955,244 ( 0.15%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/proc-macro2-1.0.36/src/wrapper.rs:>::extend 50,847,614 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::next 50,609,486 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_resolve/src/imports.rs:::resolve_ident_in_module_unadjusted_ext 50,308,674 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_borrowck/src/lib.rs:::access_place 48,808,676 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mut_ptr.rs:core::ptr::mut_ptr::::guaranteed_eq 48,149,072 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cmp.rs:, proc_macro::bridge::client::SourceFile>, alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree:: 48,006,801 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::bump 47,293,950 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/sty.rs:, (), core::hash::BuildHasherDefault>>::from_hash::>::{closure#0}> 46,232,239 ( 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 45,322,342 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mut_ptr.rs:core::ptr::mut_ptr::::is_null 45,127,548 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cmp.rs:>>::insert 44,707,265 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_trait_selection/src/traits/fulfill.rs:>::process_obligations::> 42,834,763 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/sty.rs:::eq 42,535,014 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/rpc.rs:>::encode 41,903,843 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/sty.rs:::hash:: 41,791,288 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/hir/map/mod.rs:::find_parent_node 41,777,277 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/remove.rs:, alloc::collections::btree::node::marker::Leaf>, alloc::collections::btree::node::marker::KV>>::remove_leaf_kv::<>>::remove_kv::{closure#0}> 41,432,034 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/search.rs:>::search_tree:: 41,278,841 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/tokenstream.rs:::next_with_spacing 41,068,702 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/map/entry.rs:>>::remove_entry 40,761,819 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/server.rs: as core::convert::From<&mut _>>::from::call::, proc_macro::bridge::buffer::Buffer, ::run_bridge_and_client proc_macro::TokenStream, proc_macro::bridge::server::Dispatcher>>::{closure#0}> 40,666,203 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/traversal.rs:::traverse_successor 40,445,209 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:alloc::vec::Vec::push 40,349,568 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/hir/map/mod.rs:::attrs 40,187,221 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast_pretty/src/pp.rs:::advance_left 39,460,218 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/mod.rs:::lookup_source_file_idx 39,385,359 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::is_keyword 39,075,174 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::clone 37,817,760 ( 0.11%) ./elf/../sysdeps/x86_64/dl-tls.c:__tls_get_addr_slow 37,537,767 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/context.rs:::intern_predicate 37,371,517 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_privacy/src/lib.rs: as rustc_middle::ty::fold::TypeVisitor>::visit_ty 37,325,836 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cmp.rs:, alloc::collections::btree::node::marker::LeafOrInternal>>::search_tree:: 36,640,416 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/string.rs:::advance_left 36,486,821 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_resolve/src/lib.rs:::resolve_path_with_ribs 36,249,418 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/non_null.rs:core::ptr::non_null::NonNull::as_ptr 36,237,090 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/node.rs:, alloc::collections::btree::node::marker::Leaf>, alloc::collections::btree::node::marker::Edge>>::insert_fit 36,191,583 ( 0.10%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs:, (), core::hash::BuildHasherDefault>>::from_hash::, rustc_middle::ty::context::Interned>::{closure#0}> 36,099,693 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/iter/traits/iterator.rs:core::iter::traits::iterator::Iterator::fold 35,752,561 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/subst.rs:<&rustc_middle::ty::list::List as rustc_middle::ty::fold::TypeFoldable>::try_fold_with:: 35,681,863 ( 0.10%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs:, (), core::hash::BuildHasherDefault>>::from_hash::>::{closure#0}> 35,128,599 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::eq 34,900,078 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/library/std/src/thread/local.rs:rustc_span::SESSION_GLOBALS::FOO::__getit -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/mod.rs -------------------------------------------------------------------------------- Ir -- line 118 ---------------------------------------- . /// let a = [1, 2, 3]; . /// assert_eq!(a.len(), 3); . /// ``` . #[lang = "slice_len_fn"] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_slice_len", since = "1.39.0")] . #[inline] . // SAFETY: const sound because we transmute out the length field as a usize (which it must be) 515,793 ( 0.00%) pub const fn len(&self) -> usize { . // FIXME: Replace with `crate::ptr::metadata(self)` when that is const-stable. . // As of this writing this causes a "Const-stable functions can only call other . // const-stable functions" error. . . // SAFETY: Accessing the value from the `PtrRepr` union is safe since *const T . // and PtrComponents have the same memory layouts. Only std can make this . // guarantee. 515,793 ( 0.00%) unsafe { crate::ptr::PtrRepr { const_ptr: self }.components.metadata } 343,862 ( 0.00%) } . . /// Returns `true` if the slice has a length of 0. . /// . /// # Examples . /// . /// ``` . /// let a = [1, 2, 3]; . /// assert!(!a.is_empty()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_slice_is_empty", since = "1.39.0")] . #[inline] 12 ( 0.00%) pub const fn is_empty(&self) -> bool { 8,793,344 ( 0.03%) self.len() == 0 16 ( 0.00%) } . . /// Returns the first element of the slice, or `None` if it is empty. . /// . /// # Examples . /// . /// ``` . /// let v = [10, 40, 30]; . /// assert_eq!(Some(&10), v.first()); -- line 158 ---------------------------------------- -- 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> { 200,246 ( 0.00%) if let [first, ..] = self { Some(first) } else { None } . } . . /// Returns a mutable pointer to the first element of the slice, or `None` if it is empty. . /// . /// # Examples . /// . /// ``` . /// let x = &mut [0, 1, 2]; -- line 175 ---------------------------------------- -- line 178 ---------------------------------------- . /// *first = 5; . /// } . /// assert_eq!(x, &[5, 1, 2]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")] . #[inline] . pub const fn first_mut(&mut self) -> Option<&mut T> { 91,988 ( 0.00%) if let [first, ..] = self { Some(first) } else { None } . } . . /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty. . /// . /// # Examples . /// . /// ``` . /// let x = &[0, 1, 2]; -- line 194 ---------------------------------------- -- line 197 ---------------------------------------- . /// assert_eq!(first, &0); . /// assert_eq!(elements, &[1, 2]); . /// } . /// ``` . #[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_first(&self) -> Option<(&T, &[T])> { 30,517 ( 0.00%) if let [first, tail @ ..] = self { Some((first, tail)) } else { None } . } . . /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty. . /// . /// # Examples . /// . /// ``` . /// let x = &mut [0, 1, 2]; -- line 213 ---------------------------------------- -- 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])> { 333,963 ( 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 275 ---------------------------------------- . /// assert_eq!(Some(&30), v.last()); . /// . /// 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] 1,370 ( 0.00%) pub const fn last(&self) -> Option<&T> { 5,213,480 ( 0.02%) if let [.., last] = self { Some(last) } else { None } 822 ( 0.00%) } . . /// Returns a mutable pointer to the last item in the slice. . /// . /// # Examples . /// . /// ``` . /// let x = &mut [0, 1, 2]; . /// -- line 293 ---------------------------------------- -- 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> { 10,293,914 ( 0.03%) if let [.., last] = self { Some(last) } else { None } . } . . /// Returns a reference to an element or subslice depending on the type of . /// index. . /// . /// - If given a position, returns a reference to the element at that . /// position or `None` if out of bounds. . /// - If given a range, returns the subslice corresponding to that range, -- line 311 ---------------------------------------- -- line 317 ---------------------------------------- . /// let v = [10, 40, 30]; . /// assert_eq!(Some(&40), v.get(1)); . /// assert_eq!(Some(&[10, 40][..]), v.get(0..2)); . /// assert_eq!(None, v.get(3)); . /// assert_eq!(None, v.get(0..4)); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] 462,464 ( 0.00%) pub fn get(&self, index: I) -> Option<&I::Output> . where . I: SliceIndex, . { 115,616 ( 0.00%) index.get(self) 115,616 ( 0.00%) } . . /// Returns a mutable reference to an element or subslice depending on the . /// type of index (see [`get`]) or `None` if the index is out of bounds. . /// . /// [`get`]: slice::get . /// . /// # Examples . /// -- line 338 ---------------------------------------- -- line 372 ---------------------------------------- . /// let x = &[1, 2, 4]; . /// . /// unsafe { . /// assert_eq!(x.get_unchecked(1), &2); . /// } . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] 1,072 ( 0.00%) pub unsafe fn get_unchecked(&self, index: I) -> &I::Output . where . I: SliceIndex, . { . // SAFETY: the caller must uphold most of the safety requirements for `get_unchecked`; . // the slice is dereferenceable because `self` is a safe reference. . // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is. 344 ( 0.00%) unsafe { &*index.get_unchecked(self) } 268 ( 0.00%) } . . /// Returns a mutable reference to an element or subslice, without doing . /// bounds checking. . /// . /// For a safe alternative see [`get_mut`]. . /// . /// # Safety . /// -- line 396 ---------------------------------------- -- line 408 ---------------------------------------- . /// unsafe { . /// let elem = x.get_unchecked_mut(1); . /// *elem = 13; . /// } . /// assert_eq!(x, &[1, 13, 4]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] 1,520 ( 0.00%) pub unsafe fn get_unchecked_mut(&mut self, index: I) -> &mut I::Output . where . I: SliceIndex, . { . // SAFETY: the caller must uphold the safety requirements for `get_unchecked_mut`; . // the slice is dereferenceable because `self` is a safe reference. . // The returned pointer is safe because impls of `SliceIndex` have to guarantee that it is. 456 ( 0.00%) unsafe { &mut *index.get_unchecked_mut(self) } 380 ( 0.00%) } . . /// Returns a raw pointer to the slice's buffer. . /// . /// The caller must ensure that the slice outlives the pointer this . /// function returns, or else it will end up pointing to garbage. . /// . /// The caller must also ensure that the memory the pointer (non-transitively) points to . /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer -- line 432 ---------------------------------------- -- line 447 ---------------------------------------- . /// } . /// } . /// ``` . /// . /// [`as_mut_ptr`]: slice::as_mut_ptr . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_slice_as_ptr", since = "1.32.0")] . #[inline] 4,977,156 ( 0.01%) pub const fn as_ptr(&self) -> *const T { 8,774,073 ( 0.03%) self as *const [T] as *const T 2,488,578 ( 0.01%) } . . /// Returns an unsafe mutable pointer to the slice's buffer. . /// . /// The caller must ensure that the slice outlives the pointer this . /// function returns, or else it will end up pointing to garbage. . /// . /// Modifying the container referenced by this slice may cause its buffer . /// to be reallocated, which would also make any pointers to it invalid. -- line 465 ---------------------------------------- -- line 475 ---------------------------------------- . /// *x_ptr.add(i) += 2; . /// } . /// } . /// assert_eq!(x, &[3, 4, 6]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")] . #[inline] 38,896 ( 0.00%) pub const fn as_mut_ptr(&mut self) -> *mut T { 29 ( 0.00%) self as *mut [T] as *mut T 19,448 ( 0.00%) } . . /// Returns the two raw pointers spanning the slice. . /// . /// The returned range is half-open, which means that the end pointer . /// points *one past* the last element of the slice. This way, an empty . /// slice is represented by two equal pointers, and the difference between . /// the two pointers represents the size of the slice. . /// -- line 493 ---------------------------------------- -- line 582 ---------------------------------------- . /// v.swap(2, 4); . /// assert!(v == ["a", "b", "e", "d", "c"]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_swap", issue = "83163")] . #[inline] . #[track_caller] . pub const fn swap(&mut self, a: usize, b: usize) { 150,480 ( 0.00%) let _ = &self[a]; 664,187 ( 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 { 14,701 ( 0.00%) mem::swap(&mut a[i], &mut b[n - 1 - i]); . } . } . } . . /// Returns an iterator over the slice. . /// . /// # Examples . /// -- line 693 ---------------------------------------- -- line 697 ---------------------------------------- . /// . /// assert_eq!(iterator.next(), Some(&1)); . /// assert_eq!(iterator.next(), Some(&2)); . /// assert_eq!(iterator.next(), Some(&4)); . /// assert_eq!(iterator.next(), None); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] 1,449,231 ( 0.00%) pub fn iter(&self) -> Iter<'_, T> { 1,449,231 ( 0.00%) Iter::new(self) 966,154 ( 0.00%) } . . /// Returns an iterator that allows modifying each value. . /// . /// # Examples . /// . /// ``` . /// let x = &mut [1, 2, 4]; . /// for elem in x.iter_mut() { . /// *elem += 2; . /// } . /// assert_eq!(x, &[3, 4, 6]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] 26,964 ( 0.00%) pub fn iter_mut(&mut self) -> IterMut<'_, T> { 26,964 ( 0.00%) IterMut::new(self) 17,976 ( 0.00%) } . . /// Returns an iterator over all contiguous windows of length . /// `size`. The windows overlap. If the slice is shorter than . /// `size`, the iterator returns no values. . /// . /// # Panics . /// . /// Panics if `size` is 0. -- line 732 ---------------------------------------- -- 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]) { 30 ( 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]) { 738,702 ( 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. 94,625 ( 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 2109 ---------------------------------------- . /// . /// ``` . /// let v = [String::from("hello"), String::from("world")]; // slice of `String` . /// assert!(v.iter().any(|e| e == "hello")); // search with `&str` . /// assert!(!v.iter().any(|e| e == "hi")); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] 5,592 ( 0.00%) pub fn contains(&self, x: &T) -> bool . where . T: PartialEq, . { 8,316 ( 0.00%) cmp::SliceContains::slice_contains(x, self) 2,796 ( 0.00%) } . . /// Returns `true` if `needle` is a prefix of the slice. . /// . /// # Examples . /// . /// ``` . /// let v = [10, 40, 30]; . /// assert!(v.starts_with(&[10])); -- line 2130 ---------------------------------------- -- line 2137 ---------------------------------------- . /// . /// ``` . /// let v = &[10, 40, 30]; . /// assert!(v.starts_with(&[])); . /// let v: &[u8] = &[]; . /// assert!(v.starts_with(&[])); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 1,537,956 ( 0.00%) pub fn starts_with(&self, needle: &[T]) -> bool . where . T: PartialEq, . { 659,124 ( 0.00%) let n = needle.len(); 4,339,872 ( 0.01%) self.len() >= n && needle == &self[..n] 1,098,540 ( 0.00%) } . . /// Returns `true` if `needle` is a suffix of the slice. . /// . /// # Examples . /// . /// ``` . /// let v = [10, 40, 30]; . /// assert!(v.ends_with(&[30])); -- line 2159 ---------------------------------------- -- line 2166 ---------------------------------------- . /// . /// ``` . /// let v = &[10, 40, 30]; . /// assert!(v.ends_with(&[])); . /// let v: &[u8] = &[]; . /// assert!(v.ends_with(&[])); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 199,087 ( 0.00%) pub fn ends_with(&self, needle: &[T]) -> bool . where . T: PartialEq, . { 255,969 ( 0.00%) let (m, n) = (self.len(), needle.len()); 634,814 ( 0.00%) m >= n && needle == &self[m - n..] 142,205 ( 0.00%) } . . /// 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 2188 ---------------------------------------- -- 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; 23,668,193 ( 0.07%) while left < right { 27,338,912 ( 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. 4,251,556 ( 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. 7,953,444 ( 0.02%) if cmp == Less { 8,938,920 ( 0.03%) left = mid + 1; 4,397,934 ( 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); . } . 21,973,604 ( 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 3187 ---------------------------------------- . /// assert_eq!(slice, [4, 5, 3, 4, 5]); . /// ``` . /// . /// [`clone_from_slice`]: slice::clone_from_slice . /// [`split_at_mut`]: slice::split_at_mut . #[doc(alias = "memcpy")] . #[stable(feature = "copy_from_slice", since = "1.9.0")] . #[track_caller] 6,600 ( 0.00%) pub fn copy_from_slice(&mut self, src: &[T]) . where . T: Copy, . { . // The panic code path was put into a cold function to not bloat the . // call site. . #[inline(never)] . #[cold] . #[track_caller] . fn len_mismatch_fail(dst_len: usize, src_len: usize) -> ! { . panic!( . "source slice length ({}) does not match destination slice length ({})", . src_len, dst_len, . ); . } . 1,980,098 ( 0.01%) 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 { 3,960 ( 0.00%) ptr::copy_nonoverlapping(src.as_ptr(), self.as_mut_ptr(), self.len()); . } 1,320 ( 0.00%) } . . /// Copies elements from one part of the slice to another part of itself, . /// using a memmove. . /// . /// `src` is the range within `self` to copy from. `dest` is the starting . /// index of the range within `self` to copy to, which will have the same . /// length as `src`. The two ranges may overlap. The ends of the two ranges . /// must be less than or equal to `self.len()`. -- line 3229 ---------------------------------------- -- line 3380 ---------------------------------------- . } . a << k . } . let gcd: usize = gcd(mem::size_of::(), mem::size_of::()); . let ts: usize = mem::size_of::() / gcd; . let us: usize = mem::size_of::() / gcd; . . // Armed with this knowledge, we can find how many `U`s we can fit! 4 ( 0.00%) let us_len = self.len() / ts * us; . // And how many `T`s will be in the trailing slice! 93,494 ( 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::()) }; 93,494 ( 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), 93,498 ( 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 ---------------------------------------- -- line 3731 ---------------------------------------- . /// let v = [1, 2, 3, 3, 5, 6, 7]; . /// let i = v.partition_point(|&x| x < 5); . /// . /// assert_eq!(i, 4); . /// assert!(v[..i].iter().all(|&x| x < 5)); . /// assert!(v[i..].iter().all(|&x| !(x < 5))); . /// ``` . #[stable(feature = "partition_point", since = "1.52.0")] 1,788 ( 0.00%) pub fn partition_point

(&self, mut pred: P) -> usize . where . P: FnMut(&T) -> bool, . { . self.binary_search_by(|x| if pred(x) { Less } else { Greater }).unwrap_or_else(|i| i) 3,576 ( 0.00%) } . . /// Removes the subslice corresponding to the given range . /// and returns a reference to it. . /// . /// Returns `None` and does not modify the slice if the given . /// range is out of bounds. . /// . /// Note that this method only accepts one-sided ranges such as -- line 3752 ---------------------------------------- 26,083,042 ( 0.08%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/node.rs -------------------------------------------------------------------------------- Ir -- line 62 ---------------------------------------- . /// The arrays storing the actual data of the node. Only the first `len` elements of each . /// array are initialized and valid. . keys: [MaybeUninit; CAPACITY], . vals: [MaybeUninit; CAPACITY], . } . . impl LeafNode { . /// Initializes a new `LeafNode` in-place. 114 ( 0.00%) unsafe fn init(this: *mut Self) { . // As a general policy, we leave fields uninitialized if they can be, as this should . // be both slightly faster and easier to track in Valgrind. . unsafe { . // parent_idx, keys, and vals are all MaybeUninit 152 ( 0.00%) ptr::addr_of_mut!((*this).parent).write(None); 114 ( 0.00%) ptr::addr_of_mut!((*this).len).write(0); . } 76 ( 0.00%) } . . /// Creates a new boxed `LeafNode`. 38 ( 0.00%) fn new() -> Box { . unsafe { 152 ( 0.00%) let mut leaf = Box::new_uninit(); 190 ( 0.00%) LeafNode::init(leaf.as_mut_ptr()); 190 ( 0.00%) leaf.assume_init() 38 ( 0.00%) } 76 ( 0.00%) } . } . . /// The underlying representation of internal nodes. As with `LeafNode`s, these should be hidden . /// behind `BoxedNode`s to prevent dropping uninitialized keys and values. Any pointer to an . /// `InternalNode` can be directly cast to a pointer to the underlying `LeafNode` portion of the . /// node, allowing code to act on leaf and internal nodes generically without having to even check . /// which of the two a pointer is pointing at. This property is enabled by the use of `repr(C)`. . #[repr(C)] -- line 95 ---------------------------------------- -- line 208 ---------------------------------------- . . unsafe impl<'a, K: Sync + 'a, V: Sync + 'a, Type> Send for NodeRef, K, V, Type> {} . unsafe impl<'a, K: Send + 'a, V: Send + 'a, Type> Send for NodeRef, K, V, Type> {} . unsafe impl<'a, K: Send + 'a, V: Send + 'a, Type> Send for NodeRef, K, V, Type> {} . unsafe impl Send for NodeRef {} . unsafe impl Send for NodeRef {} . . impl NodeRef { 38 ( 0.00%) fn new_leaf() -> Self { 190 ( 0.00%) Self::from_new_leaf(LeafNode::new()) 76 ( 0.00%) } . 76 ( 0.00%) fn from_new_leaf(leaf: Box>) -> Self { 228 ( 0.00%) NodeRef { height: 0, node: NonNull::from(Box::leak(leaf)), _marker: PhantomData } 152 ( 0.00%) } . } . . impl NodeRef { . fn new_internal(child: Root) -> Self { . let mut new_node = unsafe { InternalNode::new() }; . new_node.edges[0].write(child.node); 136,702 ( 0.00%) unsafe { NodeRef::from_new_internal(new_node, child.height + 1) } . } . . /// # Safety . /// `height` must not be zero. . unsafe fn from_new_internal(internal: Box>, height: usize) -> Self { . debug_assert!(height > 0); . let node = NonNull::from(Box::leak(internal)).cast(); . let mut this = NodeRef { height, node, _marker: PhantomData }; -- line 237 ---------------------------------------- -- line 266 ---------------------------------------- . } . } . . impl NodeRef { . /// Finds the length of the node. This is the number of keys or values. . /// The number of edges is `len() + 1`. . /// Note that, despite being safe, calling this function can have the side effect . /// of invalidating mutable references that unsafe code has created. 228 ( 0.00%) pub fn len(&self) -> usize { . // Crucially, we only access the `len` field here. If BorrowType is marker::ValMut, . // there might be outstanding mutable references to values that we must not invalidate. 2,324,267 ( 0.01%) unsafe { usize::from((*Self::as_leaf_ptr(self)).len) } 228 ( 0.00%) } . . /// Returns the number of levels that the node and leaves are apart. Zero . /// height means the node is a leaf itself. If you picture trees with the . /// root on top, the number says at which elevation the node appears. . /// If you picture trees with leaves on top, the number says how high . /// the tree extends above the node. . pub fn height(&self) -> usize { . self.height . } . . /// Temporarily takes out another, immutable reference to the same node. 76 ( 0.00%) pub fn reborrow(&self) -> NodeRef, K, V, Type> { 5,932,884 ( 0.02%) NodeRef { height: self.height, node: self.node, _marker: PhantomData } 152 ( 0.00%) } . . /// Exposes the leaf portion of any leaf or internal node. . /// . /// Returns a raw ptr to avoid invalidating other references to this node. 760 ( 0.00%) fn as_leaf_ptr(this: &Self) -> *mut LeafNode { . // The node must be valid for at least the LeafNode portion. . // This is not a reference in the NodeRef type because we don't know if . // it should be unique or shared. 1,140 ( 0.00%) this.node.as_ptr() 760 ( 0.00%) } . } . . impl NodeRef { . /// Finds the parent of the current node. Returns `Ok(handle)` if the current . /// node actually has a parent, where `handle` points to the edge of the parent . /// that points to the current node. Returns `Err(self)` if the current node has . /// no parent, giving back the original `NodeRef`. . /// . /// The method name assumes you picture trees with the root node on top. . /// . /// `edge.descend().ascend().unwrap()` and `node.ascend().unwrap().descend()` should . /// both, upon success, do nothing. 190 ( 0.00%) pub fn ascend( . self, . ) -> Result, marker::Edge>, Self> { 114 ( 0.00%) assert!(BorrowType::PERMITS_TRAVERSAL); . // We need to use raw pointers to nodes because, if BorrowType is marker::ValMut, . // there might be outstanding mutable references to values that we must not invalidate. 190 ( 0.00%) let leaf_ptr: *const _ = Self::as_leaf_ptr(&self); 1,537,060 ( 0.00%) unsafe { (*leaf_ptr).parent } . .as_ref() 152 ( 0.00%) .map(|parent| Handle { 1,805,037 ( 0.01%) node: NodeRef::from_internal(*parent, self.height + 1), 587,079 ( 0.00%) idx: unsafe { usize::from((*leaf_ptr).parent_idx.assume_init()) }, . _marker: PhantomData, . }) 76 ( 0.00%) .ok_or(self) 76 ( 0.00%) } . 190 ( 0.00%) pub fn first_edge(self) -> Handle { 114 ( 0.00%) unsafe { Handle::new_edge(self, 0) } 76 ( 0.00%) } . . pub fn last_edge(self) -> Handle { . let len = self.len(); . unsafe { Handle::new_edge(self, len) } . } . . /// Note that `self` must be nonempty. . pub fn first_kv(self) -> Handle { -- line 342 ---------------------------------------- -- line 363 ---------------------------------------- . } else { . false . } . } . } . . impl<'a, K: 'a, V: 'a, Type> NodeRef, K, V, Type> { . /// Exposes the leaf portion of any leaf or internal node in an immutable tree. 114 ( 0.00%) fn into_leaf(self) -> &'a LeafNode { 152 ( 0.00%) let ptr = Self::as_leaf_ptr(&self); . // SAFETY: there can be no mutable references into this tree borrowed as `Immut`. . unsafe { &*ptr } 76 ( 0.00%) } . . /// Borrows a view into the keys stored in the node. 114 ( 0.00%) pub fn keys(&self) -> &[K] { 190 ( 0.00%) let leaf = self.into_leaf(); . unsafe { 12,345,398 ( 0.04%) MaybeUninit::slice_assume_init_ref(leaf.keys.get_unchecked(..usize::from(leaf.len))) . } 76 ( 0.00%) } . } . . impl NodeRef { . /// Similar to `ascend`, gets a reference to a node's parent node, but also . /// deallocates the current node in the process. This is unsafe because the . /// current node will still be accessible despite being deallocated. 266 ( 0.00%) pub unsafe fn deallocate_and_ascend( . self, . ) -> Option, marker::Edge>> { 38 ( 0.00%) let height = self.height; 38 ( 0.00%) let node = self.node; 152 ( 0.00%) let ret = self.ascend().ok(); . unsafe { 152 ( 0.00%) Global.deallocate( 76 ( 0.00%) node.cast(), 353,050 ( 0.00%) if height > 0 { . Layout::new::>() . } else { 152 ( 0.00%) Layout::new::>() . }, . ); . } . ret 76 ( 0.00%) } . } . . impl<'a, K, V, Type> NodeRef, K, V, Type> { . /// Temporarily takes out another mutable reference to the same node. Beware, as . /// this method is very dangerous, doubly so since it might not immediately appear . /// dangerous. . /// . /// Because mutable pointers can roam anywhere around the tree, the returned -- line 415 ---------------------------------------- -- line 418 ---------------------------------------- . // FIXME(@gereeter) consider adding yet another type parameter to `NodeRef` . // that restricts the use of navigation methods on reborrowed pointers, . // preventing this unsafety. . unsafe fn reborrow_mut(&mut self) -> NodeRef, K, V, Type> { . NodeRef { height: self.height, node: self.node, _marker: PhantomData } . } . . /// Borrows exclusive access to the leaf portion of a leaf or internal node. 304 ( 0.00%) fn as_leaf_mut(&mut self) -> &mut LeafNode { 456 ( 0.00%) let ptr = Self::as_leaf_ptr(self); . // SAFETY: we have exclusive access to the entire node. . unsafe { &mut *ptr } 304 ( 0.00%) } . . /// Offers exclusive access to the leaf portion of a leaf or internal node. . fn into_leaf_mut(mut self) -> &'a mut LeafNode { . let ptr = Self::as_leaf_ptr(&mut self); . // SAFETY: we have exclusive access to the entire node. . unsafe { &mut *ptr } . } . } . . impl NodeRef { . /// Borrows exclusive access to the leaf portion of a dying leaf or internal node. 76 ( 0.00%) fn as_leaf_dying(&mut self) -> &mut LeafNode { 119 ( 0.00%) let ptr = Self::as_leaf_ptr(self); . // SAFETY: we have exclusive access to the entire node. . unsafe { &mut *ptr } 76 ( 0.00%) } . } . . impl<'a, K: 'a, V: 'a, Type> NodeRef, K, V, Type> { . /// Borrows exclusive access to an element of the key storage area. . /// . /// # Safety . /// `index` is in bounds of 0..CAPACITY 152 ( 0.00%) unsafe fn key_area_mut(&mut self, index: I) -> &mut Output . where . I: SliceIndex<[MaybeUninit], Output = Output>, . { . // SAFETY: the caller will not be able to call further methods on self . // until the key slice reference is dropped, as we have unique access . // for the lifetime of the borrow. 570 ( 0.00%) unsafe { self.as_leaf_mut().keys.as_mut_slice().get_unchecked_mut(index) } 76 ( 0.00%) } . . /// Borrows exclusive access to an element or slice of the node's value storage area. . /// . /// # Safety . /// `index` is in bounds of 0..CAPACITY 304 ( 0.00%) unsafe fn val_area_mut(&mut self, index: I) -> &mut Output . where . I: SliceIndex<[MaybeUninit], Output = Output>, . { . // SAFETY: the caller will not be able to call further methods on self . // until the value slice reference is dropped, as we have unique access . // for the lifetime of the borrow. 2,050,294 ( 0.01%) unsafe { self.as_leaf_mut().vals.as_mut_slice().get_unchecked_mut(index) } 152 ( 0.00%) } . } . . impl<'a, K: 'a, V: 'a> NodeRef, K, V, marker::Internal> { . /// Borrows exclusive access to an element or slice of the node's storage area for edge contents. . /// . /// # Safety . /// `index` is in bounds of 0..CAPACITY + 1 . unsafe fn edge_area_mut(&mut self, index: I) -> &mut Output -- line 484 ---------------------------------------- -- line 508 ---------------------------------------- . let key = unsafe { (&*keys.get_unchecked(idx)).assume_init_ref() }; . let val = unsafe { (&mut *vals.get_unchecked_mut(idx)).assume_init_mut() }; . (key, val) . } . } . . impl<'a, K: 'a, V: 'a, Type> NodeRef, K, V, Type> { . /// Borrows exclusive access to the length of the node. 76 ( 0.00%) pub fn len_mut(&mut self) -> &mut u16 { 114 ( 0.00%) &mut self.as_leaf_mut().len 76 ( 0.00%) } . } . . impl<'a, K, V> NodeRef, K, V, marker::Internal> { . /// # Safety . /// Every item returned by `range` is a valid edge index for the node. . unsafe fn correct_childrens_parent_links>(&mut self, range: R) { . for i in range { . debug_assert!(i <= self.len()); -- line 526 ---------------------------------------- -- line 534 ---------------------------------------- . } . } . . impl<'a, K: 'a, V: 'a> NodeRef, K, V, marker::LeafOrInternal> { . /// Sets the node's link to its parent edge, . /// without invalidating other references to the node. . fn set_parent_link(&mut self, parent: NonNull>, parent_idx: usize) { . let leaf = Self::as_leaf_ptr(self); 314,973 ( 0.00%) unsafe { (*leaf).parent = Some(parent) }; . unsafe { (*leaf).parent_idx.write(parent_idx as u16) }; . } . } . . impl NodeRef { . /// Clears the root's link to its parent edge. . fn clear_parent_link(&mut self) { . let mut root_node = self.borrow_mut(); . let leaf = root_node.as_leaf_mut(); 63,587 ( 0.00%) leaf.parent = None; . } . } . . impl NodeRef { . /// Returns a new owned tree, with its own root node that is initially empty. 38 ( 0.00%) pub fn new() -> Self { 228 ( 0.00%) NodeRef::new_leaf().forget_type() 76 ( 0.00%) } . . /// Adds a new internal node with a single edge pointing to the previous root node, . /// make that new node the root node, and return it. This increases the height by 1 . /// and is the opposite of `pop_internal_level`. 410,106 ( 0.00%) pub fn push_internal_level(&mut self) -> NodeRef, K, V, marker::Internal> { . super::mem::take_mut(self, |old_root| NodeRef::new_internal(old_root).forget_type()); . . // `self.borrow_mut()`, except that we just forgot we're internal now: . NodeRef { height: self.height, node: self.node, _marker: PhantomData } 546,808 ( 0.00%) } . . /// Removes the internal root node, using its first child as the new root node. . /// As it is intended only to be called when the root node has only one child, . /// no cleanup is done on any of the keys, values and other children. . /// This decreases the height by 1 and is the opposite of `push_internal_level`. . /// . /// Requires exclusive access to the `NodeRef` object but not to the root node; . /// it will not invalidate other handles or references to the root node. . /// . /// Panics if there is no internal level, i.e., if the root node is a leaf. . pub fn pop_internal_level(&mut self) { 187,993 ( 0.00%) assert!(self.height > 0); . . let top = self.node; . . // SAFETY: we asserted to be internal. . let internal_self = unsafe { self.borrow_mut().cast_to_internal_unchecked() }; . // SAFETY: we borrowed `self` exclusively and its borrow type is exclusive. . let internal_node = unsafe { &mut *NodeRef::as_internal_ptr(&internal_self) }; . // SAFETY: the first edge is always initialized. 63,587 ( 0.00%) self.node = unsafe { internal_node.edges[0].assume_init_read() }; 127,174 ( 0.00%) self.height -= 1; . self.clear_parent_link(); . . unsafe { . Global.deallocate(top.cast(), Layout::new::>()); . } . } . } . . impl NodeRef { . /// Mutably borrows the owned root node. Unlike `reborrow_mut`, this is safe . /// because the return value cannot be used to destroy the root, and there . /// cannot be other references to the tree. 76 ( 0.00%) pub fn borrow_mut(&mut self) -> NodeRef, K, V, Type> { 11,438,396 ( 0.03%) NodeRef { height: self.height, node: self.node, _marker: PhantomData } 152 ( 0.00%) } . . /// Slightly mutably borrows the owned root node. . pub fn borrow_valmut(&mut self) -> NodeRef, K, V, Type> { . NodeRef { height: self.height, node: self.node, _marker: PhantomData } . } . . /// Irreversibly transitions to a reference that permits traversal and offers . /// destructive methods and little else. 114 ( 0.00%) pub fn into_dying(self) -> NodeRef { 76 ( 0.00%) NodeRef { height: self.height, node: self.node, _marker: PhantomData } 152 ( 0.00%) } . } . . impl<'a, K: 'a, V: 'a> NodeRef, K, V, marker::Leaf> { . /// Adds a key-value pair to the end of the node. . pub fn push(&mut self, key: K, val: V) { . let len = self.len_mut(); 32 ( 0.00%) let idx = usize::from(*len); 16 ( 0.00%) assert!(idx < CAPACITY); 44 ( 0.00%) *len += 1; . unsafe { . self.key_area_mut(idx).write(key); . self.val_area_mut(idx).write(val); . } . } . } . . impl<'a, K: 'a, V: 'a> NodeRef, K, V, marker::Internal> { . /// Adds a key-value pair, and an edge to go to the right of that pair, . /// to the end of the node. . pub fn push(&mut self, key: K, val: V, edge: Root) { 273,404 ( 0.00%) assert!(edge.height == self.height - 1); . . let len = self.len_mut(); 136,702 ( 0.00%) let idx = usize::from(*len); 68,351 ( 0.00%) assert!(idx < CAPACITY); 136,702 ( 0.00%) *len += 1; . unsafe { . self.key_area_mut(idx).write(key); . self.val_area_mut(idx).write(val); 68,351 ( 0.00%) self.edge_area_mut(idx + 1).write(edge.node); . Handle::new_edge(self.reborrow_mut(), idx + 1).correct_parent_link(); . } . } . } . . impl NodeRef { . /// Removes any static information asserting that this node is a `Leaf` node. 456 ( 0.00%) pub fn forget_type(self) -> NodeRef { 304 ( 0.00%) NodeRef { height: self.height, node: self.node, _marker: PhantomData } 608 ( 0.00%) } . } . . impl NodeRef { . /// Removes any static information asserting that this node is an `Internal` node. . pub fn forget_type(self) -> NodeRef { . NodeRef { height: self.height, node: self.node, _marker: PhantomData } . } . } . . impl NodeRef { . /// Checks whether a node is an `Internal` node or a `Leaf` node. 798 ( 0.00%) pub fn force( . self, . ) -> ForceResult< . NodeRef, . NodeRef, . > { 11,114,774 ( 0.03%) if self.height == 0 { 798 ( 0.00%) ForceResult::Leaf(NodeRef { . height: self.height, . node: self.node, . _marker: PhantomData, . }) . } else { . ForceResult::Internal(NodeRef { . height: self.height, . node: self.node, . _marker: PhantomData, . }) . } 228 ( 0.00%) } . } . . impl<'a, K, V> NodeRef, K, V, marker::LeafOrInternal> { . /// Unsafely asserts to the compiler the static information that this node is a `Leaf`. . unsafe fn cast_to_leaf_unchecked(self) -> NodeRef, K, V, marker::Leaf> { . debug_assert!(self.height == 0); . NodeRef { height: self.height, node: self.node, _marker: PhantomData } . } -- line 697 ---------------------------------------- -- line 724 ---------------------------------------- . fn clone(&self) -> Self { . *self . } . } . . impl Handle { . /// Retrieves the node that contains the edge or key-value pair this handle points to. . pub fn into_node(self) -> Node { 76 ( 0.00%) self.node 38 ( 0.00%) } . . /// Returns the position of this handle in the node. . pub fn idx(&self) -> usize { . self.idx . } . } . . impl Handle, marker::KV> { . /// Creates a new handle to a key-value pair in `node`. . /// Unsafe because the caller must ensure that `idx < node.len()`. 570 ( 0.00%) pub unsafe fn new_kv(node: NodeRef, idx: usize) -> Self { . debug_assert!(idx < node.len()); . 342 ( 0.00%) Handle { node, idx, _marker: PhantomData } 228 ( 0.00%) } . . pub fn left_edge(self) -> Handle, marker::Edge> { . unsafe { Handle::new_edge(self.node, self.idx) } . } . 114 ( 0.00%) pub fn right_edge(self) -> Handle, marker::Edge> { 1,304,077 ( 0.00%) unsafe { Handle::new_edge(self.node, self.idx + 1) } 76 ( 0.00%) } . } . . impl PartialEq . for Handle, HandleType> . { . fn eq(&self, other: &Self) -> bool { . let Self { node, idx, _marker } = self; . node.eq(&other.node) && *idx == other.idx -- line 764 ---------------------------------------- -- line 787 ---------------------------------------- . // We can't use Handle::new_kv or Handle::new_edge because we don't know our type . Handle { node: unsafe { self.node.reborrow_mut() }, idx: self.idx, _marker: PhantomData } . } . } . . impl Handle, marker::Edge> { . /// Creates a new handle to an edge in `node`. . /// Unsafe because the caller must ensure that `idx <= node.len()`. 950 ( 0.00%) pub unsafe fn new_edge(node: NodeRef, idx: usize) -> Self { . debug_assert!(idx <= node.len()); . 2,394,305 ( 0.01%) Handle { node, idx, _marker: PhantomData } 380 ( 0.00%) } . . pub fn left_kv(self) -> Result, marker::KV>, Self> { 179,418 ( 0.00%) if self.idx > 0 { 169,291 ( 0.00%) Ok(unsafe { Handle::new_kv(self.node, self.idx - 1) }) . } else { . Err(self) . } . } . 228 ( 0.00%) pub fn right_kv(self) -> Result, marker::KV>, Self> { 1,894,838 ( 0.01%) if self.idx < self.node.len() { 456 ( 0.00%) Ok(unsafe { Handle::new_kv(self.node, self.idx) }) . } else { . Err(self) . } 76 ( 0.00%) } . } . . pub enum LeftOrRight { . Left(T), . Right(T), . } . . /// Given an edge index where we want to insert into a node filled to capacity, . /// computes a sensible KV index of a split point and where to perform the insertion. . /// The goal of the split point is for its key and value to end up in a parent node; . /// the keys, values and edges to the left of the split point become the left child; . /// the keys, values and edges to the right of the split point become the right child. 196,009 ( 0.00%) fn splitpoint(edge_idx: usize) -> (usize, LeftOrRight) { . debug_assert!(edge_idx <= CAPACITY); . // Rust issue #74834 tries to explain these symmetric rules. 773,800 ( 0.00%) match edge_idx { 392,018 ( 0.00%) 0..EDGE_IDX_LEFT_OF_CENTER => (KV_IDX_CENTER - 1, LeftOrRight::Left(edge_idx)), . EDGE_IDX_LEFT_OF_CENTER => (KV_IDX_CENTER, LeftOrRight::Left(edge_idx)), . EDGE_IDX_RIGHT_OF_CENTER => (KV_IDX_CENTER, LeftOrRight::Right(0)), 573,171 ( 0.00%) _ => (KV_IDX_CENTER + 1, LeftOrRight::Right(edge_idx - (KV_IDX_CENTER + 1 + 1))), . } 196,009 ( 0.00%) } . . impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Leaf>, marker::Edge> { . /// Inserts a new key-value pair between the key-value pairs to the right and left of . /// this edge. This method assumes that there is enough space in the node for the new . /// pair to fit. . /// . /// The returned pointer points to the inserted value. 15,740,004 ( 0.05%) fn insert_fit(&mut self, key: K, val: V) -> *mut V { 152 ( 0.00%) debug_assert!(self.node.len() < CAPACITY); 342 ( 0.00%) let new_len = self.node.len() + 1; . . unsafe { 1,997,058 ( 0.01%) slice_insert(self.node.key_area_mut(..new_len), self.idx, key); 2,262,774 ( 0.01%) slice_insert(self.node.val_area_mut(..new_len), self.idx, val); 1,996,622 ( 0.01%) *self.node.len_mut() = new_len as u16; . 152 ( 0.00%) self.node.val_area_mut(self.idx).assume_init_mut() . } 15,971,836 ( 0.05%) } . } . . impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Leaf>, marker::Edge> { . /// Inserts a new key-value pair between the key-value pairs to the right and left of . /// this edge. This method splits the node if there isn't enough room. . /// . /// The returned pointer points to the inserted value. 266 ( 0.00%) fn insert(mut self, key: K, val: V) -> (InsertResult<'a, K, V, marker::Leaf>, *mut V) { 5,989,714 ( 0.02%) if self.node.len() < CAPACITY { 9,851,340 ( 0.03%) let val_ptr = self.insert_fit(key, val); 3,607,870 ( 0.01%) let kv = unsafe { Handle::new_kv(self.node, self.idx) }; 722 ( 0.00%) (InsertResult::Fit(kv), val_ptr) . } else { 1,541,192 ( 0.00%) let (middle_kv_idx, insertion) = splitpoint(self.idx); 381,759 ( 0.00%) let middle = unsafe { Handle::new_kv(self.node, middle_kv_idx) }; . let mut result = middle.split(); 942,172 ( 0.00%) let mut insertion_edge = match insertion { . LeftOrRight::Left(insert_idx) => unsafe { . Handle::new_edge(result.left.reborrow_mut(), insert_idx) . }, . LeftOrRight::Right(insert_idx) => unsafe { . Handle::new_edge(result.right.borrow_mut(), insert_idx) . }, . }; 609,277 ( 0.00%) let val_ptr = insertion_edge.insert_fit(key, val); 463,621 ( 0.00%) (InsertResult::Split(result), val_ptr) . } 76 ( 0.00%) } . } . . impl<'a, K, V> Handle, K, V, marker::Internal>, marker::Edge> { . /// Fixes the parent pointer and index in the child node that this edge . /// links to. This is useful when the ordering of edges has been changed, . fn correct_parent_link(self) { . // Create backpointer without invalidating other references to the node. . let ptr = unsafe { NonNull::new_unchecked(NodeRef::as_internal_ptr(&self.node)) }; -- line 892 ---------------------------------------- -- line 895 ---------------------------------------- . child.set_parent_link(ptr, idx); . } . } . . impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Internal>, marker::Edge> { . /// Inserts a new key-value pair and an edge that will go to the right of that new pair . /// between this edge and the key-value pair to the right of this edge. This method assumes . /// that there is enough space in the node for the new pair to fit. 1,017,953 ( 0.00%) fn insert_fit(&mut self, key: K, val: V, edge: Root) { . debug_assert!(self.node.len() < CAPACITY); . debug_assert!(edge.height == self.node.height - 1); . let new_len = self.node.len() + 1; . . unsafe { 127,658 ( 0.00%) slice_insert(self.node.key_area_mut(..new_len), self.idx, key); 65,532 ( 0.00%) slice_insert(self.node.val_area_mut(..new_len), self.idx, val); . slice_insert(self.node.edge_area_mut(..new_len + 1), self.idx + 1, edge.node); 127,658 ( 0.00%) *self.node.len_mut() = new_len as u16; . . self.node.correct_childrens_parent_links(self.idx + 1..new_len + 1); . } 1,021,264 ( 0.00%) } . . /// Inserts a new key-value pair and an edge that will go to the right of that new pair . /// between this edge and the key-value pair to the right of this edge. This method splits . /// the node if there isn't enough room. . fn insert( . mut self, . key: K, . val: V, . edge: Root, . ) -> InsertResult<'a, K, V, marker::Internal> { 382,974 ( 0.00%) assert!(edge.height == self.node.height - 1); . 255,316 ( 0.00%) if self.node.len() < CAPACITY { 552,038 ( 0.00%) self.insert_fit(key, val, edge); . let kv = unsafe { Handle::new_kv(self.node, self.idx) }; . InsertResult::Fit(kv) . } else { 24,359 ( 0.00%) let (middle_kv_idx, insertion) = splitpoint(self.idx); . let middle = unsafe { Handle::new_kv(self.node, middle_kv_idx) }; . let mut result = middle.split(); 4,193 ( 0.00%) let mut insertion_edge = match insertion { . LeftOrRight::Left(insert_idx) => unsafe { . Handle::new_edge(result.left.reborrow_mut(), insert_idx) . }, . LeftOrRight::Right(insert_idx) => unsafe { . Handle::new_edge(result.right.borrow_mut(), insert_idx) . }, . }; 29,024 ( 0.00%) insertion_edge.insert_fit(key, val, edge); 8,343 ( 0.00%) InsertResult::Split(result) . } . } . } . . impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Leaf>, marker::Edge> { . /// Inserts a new key-value pair between the key-value pairs to the right and left of . /// this edge. This method splits the node if there isn't enough room, and tries to . /// insert the split off portion into the parent node recursively, until the root is reached. . /// . /// If the returned result is a `Fit`, its handle's node can be this edge's node or an ancestor. . /// If the returned result is a `Split`, the `left` field will be the root node. . /// The returned pointer points to the inserted value. 19,806,736 ( 0.06%) pub fn insert_recursing( . self, . key: K, . value: V, . ) -> (InsertResult<'a, K, V, marker::LeafOrInternal>, *mut V) { 11,560,759 ( 0.03%) let (mut split, val_ptr) = match self.insert(key, value) { 342 ( 0.00%) (InsertResult::Fit(handle), ptr) => { 9,019,979 ( 0.03%) return (InsertResult::Fit(handle.forget_node_type()), ptr); . } . (InsertResult::Split(split), val_ptr) => (split.forget_node_type(), val_ptr), . }; . . loop { 953,123 ( 0.00%) split = match split.left.ascend() { 558,468 ( 0.00%) Ok(parent) => match parent.insert(split.kv.0, split.kv.1, split.right) { . InsertResult::Fit(handle) => { 648,861 ( 0.00%) return (InsertResult::Fit(handle.forget_node_type()), val_ptr); . } . InsertResult::Split(split) => split.forget_node_type(), . }, . Err(root) => { 607,007 ( 0.00%) return (InsertResult::Split(SplitResult { left: root, ..split }), val_ptr); . } . }; . } 17,968,306 ( 0.05%) } . } . . impl . Handle, marker::Edge> . { . /// Finds the node pointed to by this edge. . /// . /// The method name assumes you picture trees with the root node on top. -- line 992 ---------------------------------------- -- line 999 ---------------------------------------- . // marker::ValMut, there might be outstanding mutable references to . // values that we must not invalidate. There's no worry accessing the . // height field because that value is copied. Beware that, once the . // node pointer is dereferenced, we access the edges array with a . // reference (Rust issue #73987) and invalidate any other references . // to or inside the array, should any be around. . let parent_ptr = NodeRef::as_internal_ptr(&self.node); . let node = unsafe { (*parent_ptr).edges.get_unchecked(self.idx).assume_init_read() }; 485,057 ( 0.00%) NodeRef { node, height: self.node.height - 1, _marker: PhantomData } . } . } . . impl<'a, K: 'a, V: 'a, NodeType> Handle, K, V, NodeType>, marker::KV> { . pub fn into_kv(self) -> (&'a K, &'a V) { . debug_assert!(self.idx < self.node.len()); . let leaf = self.node.into_leaf(); . let k = unsafe { leaf.keys.get_unchecked(self.idx).assume_init_ref() }; . let v = unsafe { leaf.vals.get_unchecked(self.idx).assume_init_ref() }; 2,680,920 ( 0.01%) (k, v) . } . } . . impl<'a, K: 'a, V: 'a, NodeType> Handle, K, V, NodeType>, marker::KV> { . pub fn key_mut(&mut self) -> &mut K { . unsafe { self.node.key_area_mut(self.idx).assume_init_mut() } . } . -- line 1025 ---------------------------------------- -- line 1037 ---------------------------------------- . } . . impl<'a, K: 'a, V: 'a, NodeType> Handle, K, V, NodeType>, marker::KV> { . pub fn kv_mut(&mut self) -> (&mut K, &mut V) { . debug_assert!(self.idx < self.node.len()); . // We cannot call separate key and value methods, because calling the second one . // invalidates the reference returned by the first. . unsafe { 7,427 ( 0.00%) let leaf = self.node.as_leaf_mut(); 7,427 ( 0.00%) let key = leaf.keys.get_unchecked_mut(self.idx).assume_init_mut(); . let val = leaf.vals.get_unchecked_mut(self.idx).assume_init_mut(); 6,760 ( 0.00%) (key, val) . } . } . . /// Replaces the key and value that the KV handle refers to. . pub fn replace_kv(&mut self, k: K, v: V) -> (K, V) { . let (key, val) = self.kv_mut(); . (mem::replace(key, k), mem::replace(val, v)) . } . } . . impl Handle, marker::KV> { . /// Extracts the key and value that the KV handle refers to. . /// # Safety . /// The node that the handle refers to must not yet have been deallocated. 228 ( 0.00%) pub unsafe fn into_key_val(mut self) -> (K, V) { . debug_assert!(self.idx < self.node.len()); 76 ( 0.00%) let leaf = self.node.as_leaf_dying(); . unsafe { 190 ( 0.00%) let key = leaf.keys.get_unchecked_mut(self.idx).assume_init_read(); 190 ( 0.00%) let val = leaf.vals.get_unchecked_mut(self.idx).assume_init_read(); 456 ( 0.00%) (key, val) . } 76 ( 0.00%) } . . /// Drops the key and value that the KV handle refers to. . /// # Safety . /// The node that the handle refers to must not yet have been deallocated. . #[inline] 30 ( 0.00%) pub unsafe fn drop_key_val(mut self) { . debug_assert!(self.idx < self.node.len()); . let leaf = self.node.as_leaf_dying(); . unsafe { 5 ( 0.00%) leaf.keys.get_unchecked_mut(self.idx).assume_init_drop(); 138,858 ( 0.00%) leaf.vals.get_unchecked_mut(self.idx).assume_init_drop(); . } 35 ( 0.00%) } . } . . impl<'a, K: 'a, V: 'a, NodeType> Handle, K, V, NodeType>, marker::KV> { . /// Helps implementations of `split` for a particular `NodeType`, . /// by taking care of leaf data. . fn split_leaf_data(&mut self, new_node: &mut LeafNode) -> (K, V) { . debug_assert!(self.idx < self.node.len()); . let old_len = self.node.len(); 997,618 ( 0.00%) let new_len = old_len - self.idx - 1; 196,669 ( 0.00%) new_node.len = new_len as u16; . unsafe { 163,190 ( 0.00%) let k = self.node.key_area_mut(self.idx).assume_init_read(); 151,657 ( 0.00%) let v = self.node.val_area_mut(self.idx).assume_init_read(); . . move_to_slice( 588,027 ( 0.00%) self.node.key_area_mut(self.idx + 1..old_len), 196,009 ( 0.00%) &mut new_node.keys[..new_len], . ); . move_to_slice( . self.node.val_area_mut(self.idx + 1..old_len), 197,877 ( 0.00%) &mut new_node.vals[..new_len], . ); . 347,670 ( 0.00%) *self.node.len_mut() = self.idx as u16; 185,567 ( 0.00%) (k, v) . } . } . } . . impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Leaf>, marker::KV> { . /// Splits the underlying node into three parts: . /// . /// - The node is truncated to only contain the key-value pairs to the left of -- line 1117 ---------------------------------------- -- line 1120 ---------------------------------------- . /// - All the key-value pairs to the right of this handle are put into a newly . /// allocated node. . pub fn split(mut self) -> SplitResult<'a, K, V, marker::Leaf> { . let mut new_node = LeafNode::new(); . . let kv = self.split_leaf_data(&mut new_node); . . let right = NodeRef::from_new_leaf(new_node); 1,720,895 ( 0.00%) SplitResult { left: self.node, kv, right } . } . . /// Removes the key-value pair pointed to by this handle and returns it, along with the edge . /// that the key-value pair collapsed into. . pub fn remove( . mut self, . ) -> ((K, V), Handle, K, V, marker::Leaf>, marker::Edge>) { . let old_len = self.node.len(); . unsafe { . let k = slice_remove(self.node.key_area_mut(..old_len), self.idx); 1,207,903 ( 0.00%) let v = slice_remove(self.node.val_area_mut(..old_len), self.idx); 6,074,332 ( 0.02%) *self.node.len_mut() = (old_len - 1) as u16; 5,264,777 ( 0.02%) ((k, v), self.left_edge()) . } . } . } . . impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Internal>, marker::KV> { . /// Splits the underlying node into three parts: . /// . /// - The node is truncated to only contain the edges and key-value pairs to the -- line 1149 ---------------------------------------- -- line 1150 ---------------------------------------- . /// left of this handle. . /// - The key and value pointed to by this handle are extracted. . /// - All the edges and key-value pairs to the right of this handle are put into . /// a newly allocated node. . pub fn split(mut self) -> SplitResult<'a, K, V, marker::Internal> { . let old_len = self.node.len(); . unsafe { . let mut new_node = InternalNode::new(); 5,604 ( 0.00%) let kv = self.split_leaf_data(&mut new_node.data); . let new_len = usize::from(new_node.data.len); . move_to_slice( 3,360 ( 0.00%) self.node.edge_area_mut(self.idx + 1..old_len + 1), 6,720 ( 0.00%) &mut new_node.edges[..new_len + 1], . ); . . let height = self.node.height; . let right = NodeRef::from_new_internal(new_node, height); . 22,290 ( 0.00%) SplitResult { left: self.node, kv, right } . } . } . } . . /// Represents a session for evaluating and performing a balancing operation . /// around an internal key-value pair. . pub struct BalancingContext<'a, K, V> { . parent: Handle, K, V, marker::Internal>, marker::KV>, -- line 1176 ---------------------------------------- -- line 1242 ---------------------------------------- . . pub fn into_right_child(self) -> NodeRef, K, V, marker::LeafOrInternal> { . self.right_child . } . . /// Returns whether merging is possible, i.e., whether there is enough room . /// in a node to combine the central KV with both adjacent child nodes. . pub fn can_merge(&self) -> bool { 526,048 ( 0.00%) self.left_child.len() + 1 + self.right_child.len() <= CAPACITY . } . } . . impl<'a, K: 'a, V: 'a> BalancingContext<'a, K, V> { . /// Performs a merge and lets a closure decide what to return. . fn do_merge< . F: FnOnce( . NodeRef, K, V, marker::Internal>, -- line 1258 ---------------------------------------- -- line 1264 ---------------------------------------- . result: F, . ) -> R { . let Handle { node: mut parent_node, idx: parent_idx, _marker } = self.parent; . let old_parent_len = parent_node.len(); . let mut left_node = self.left_child; . let old_left_len = left_node.len(); . let mut right_node = self.right_child; . let right_len = right_node.len(); 335,164 ( 0.00%) let new_left_len = old_left_len + 1 + right_len; . 335,164 ( 0.00%) assert!(new_left_len <= CAPACITY); . . unsafe { 167,582 ( 0.00%) *left_node.len_mut() = new_left_len as u16; . . let parent_key = slice_remove(parent_node.key_area_mut(..old_parent_len), parent_idx); . left_node.key_area_mut(old_left_len).write(parent_key); . move_to_slice( . right_node.key_area_mut(..right_len), . left_node.key_area_mut(old_left_len + 1..new_left_len), . ); . . let parent_val = slice_remove(parent_node.val_area_mut(..old_parent_len), parent_idx); . left_node.val_area_mut(old_left_len).write(parent_val); . move_to_slice( . right_node.val_area_mut(..right_len), . left_node.val_area_mut(old_left_len + 1..new_left_len), . ); . 167,582 ( 0.00%) slice_remove(&mut parent_node.edge_area_mut(..old_parent_len + 1), parent_idx + 1); . parent_node.correct_childrens_parent_links(parent_idx + 1..old_parent_len); 1,005,687 ( 0.00%) *parent_node.len_mut() -= 1; . 335,164 ( 0.00%) if parent_node.height > 1 { . // SAFETY: the height of the nodes being merged is one below the height . // of the node of this edge, thus above zero, so they are internal. . let mut left_node = left_node.reborrow_mut().cast_to_internal_unchecked(); . let mut right_node = right_node.cast_to_internal_unchecked(); . move_to_slice( . right_node.edge_area_mut(..right_len + 1), 2,069 ( 0.00%) left_node.edge_area_mut(old_left_len + 1..new_left_len + 1), . ); . . left_node.correct_childrens_parent_links(old_left_len + 1..new_left_len + 1); . . Global.deallocate(right_node.node.cast(), Layout::new::>()); . } else { . Global.deallocate(right_node.node.cast(), Layout::new::>()); . } -- line 1312 ---------------------------------------- -- line 1313 ---------------------------------------- . } . result(parent_node, left_node) . } . . /// Merges the parent's key-value pair and both adjacent child nodes into . /// the left child node and returns the shrunk parent node. . /// . /// Panics unless we `.can_merge()`. 14,483 ( 0.00%) pub fn merge_tracking_parent(self) -> NodeRef, K, V, marker::Internal> { 4,138 ( 0.00%) self.do_merge(|parent, _child| parent) 20,684 ( 0.00%) } . . /// Merges the parent's key-value pair and both adjacent child nodes into . /// the left child node and returns that child node. . /// . /// Panics unless we `.can_merge()`. . pub fn merge_tracking_child(self) -> NodeRef, K, V, marker::LeafOrInternal> { . self.do_merge(|_parent, child| child) . } . . /// Merges the parent's key-value pair and both adjacent child nodes into . /// the left child node and returns the edge handle in that child node . /// where the tracked child edge ended up, . /// . /// Panics unless we `.can_merge()`. 1,158,591 ( 0.00%) pub fn merge_tracking_child_edge( . self, . track_edge_idx: LeftOrRight, . ) -> Handle, K, V, marker::LeafOrInternal>, marker::Edge> { 165,513 ( 0.00%) let old_left_len = self.left_child.len(); 165,513 ( 0.00%) let right_len = self.right_child.len(); 496,539 ( 0.00%) assert!(match track_edge_idx { . LeftOrRight::Left(idx) => idx <= old_left_len, . LeftOrRight::Right(idx) => idx <= right_len, . }); . let child = self.merge_tracking_child(); 165,513 ( 0.00%) let new_idx = match track_edge_idx { . LeftOrRight::Left(idx) => idx, 487,587 ( 0.00%) LeftOrRight::Right(idx) => old_left_len + 1 + idx, . }; . unsafe { Handle::new_edge(child, new_idx) } 1,324,104 ( 0.00%) } . . /// Removes a key-value pair from the left child and places it in the key-value storage . /// of the parent, while pushing the old parent key-value pair into the right child. . /// Returns a handle to the edge in the right child corresponding to where the original . /// edge specified by `track_right_edge_idx` ended up. . pub fn steal_left( . mut self, . track_right_edge_idx: usize, . ) -> Handle, K, V, marker::LeafOrInternal>, marker::Edge> { 9,390 ( 0.00%) self.bulk_steal_left(1); . unsafe { Handle::new_edge(self.right_child, 1 + track_right_edge_idx) } . } . . /// Removes a key-value pair from the right child and places it in the key-value storage . /// of the parent, while pushing the old parent key-value pair onto the left child. . /// Returns a handle to the edge in the left child specified by `track_left_edge_idx`, . /// which didn't move. . pub fn steal_right( . mut self, . track_left_edge_idx: usize, . ) -> Handle, K, V, marker::LeafOrInternal>, marker::Edge> { 5,464 ( 0.00%) self.bulk_steal_right(1); . unsafe { Handle::new_edge(self.left_child, track_left_edge_idx) } . } . . /// This does stealing similar to `steal_left` but steals multiple elements at once. 32,865 ( 0.00%) pub fn bulk_steal_left(&mut self, count: usize) { 9,390 ( 0.00%) assert!(count > 0); . unsafe { . let left_node = &mut self.left_child; . let old_left_len = left_node.len(); . let right_node = &mut self.right_child; 4,695 ( 0.00%) let old_right_len = right_node.len(); . . // Make sure that we may steal safely. 23,475 ( 0.00%) assert!(old_right_len + count <= CAPACITY); 13,856 ( 0.00%) assert!(old_left_len >= count); . . let new_left_len = old_left_len - count; . let new_right_len = old_right_len + count; 4,695 ( 0.00%) *left_node.len_mut() = new_left_len as u16; 8,320 ( 0.00%) *right_node.len_mut() = new_right_len as u16; . . // Move leaf data. . { . // Make room for stolen elements in the right child. . slice_shr(right_node.key_area_mut(..new_right_len), count); . slice_shr(right_node.val_area_mut(..new_right_len), count); . . // Move elements from the left child to the right one. . move_to_slice( 9,390 ( 0.00%) left_node.key_area_mut(new_left_len + 1..old_left_len), 4,695 ( 0.00%) right_node.key_area_mut(..count - 1), . ); . move_to_slice( . left_node.val_area_mut(new_left_len + 1..old_left_len), . right_node.val_area_mut(..count - 1), . ); . . // Move the left-most stolen pair to the parent. 4,466 ( 0.00%) let k = left_node.key_area_mut(new_left_len).assume_init_read(); . let v = left_node.val_area_mut(new_left_len).assume_init_read(); 6,381 ( 0.00%) let (k, v) = self.parent.replace_kv(k, v); . . // Move parent's key-value pair to the right child. . right_node.key_area_mut(count - 1).write(k); . right_node.val_area_mut(count - 1).write(v); . } . 23,475 ( 0.00%) match (left_node.reborrow_mut().force(), right_node.reborrow_mut().force()) { . (ForceResult::Internal(mut left), ForceResult::Internal(mut right)) => { . // Make room for stolen edges. . slice_shr(right.edge_area_mut(..new_right_len + 1), count); . . // Steal edges. . move_to_slice( . left.edge_area_mut(new_left_len + 1..old_left_len + 1), . right.edge_area_mut(..count), -- line 1432 ---------------------------------------- -- line 1433 ---------------------------------------- . ); . . right.correct_childrens_parent_links(0..new_right_len + 1); . } . (ForceResult::Leaf(_), ForceResult::Leaf(_)) => {} . _ => unreachable!(), . } . } 37,560 ( 0.00%) } . . /// The symmetric clone of `bulk_steal_left`. 19,124 ( 0.00%) pub fn bulk_steal_right(&mut self, count: usize) { 5,464 ( 0.00%) assert!(count > 0); . unsafe { . let left_node = &mut self.left_child; 2,732 ( 0.00%) let old_left_len = left_node.len(); . let right_node = &mut self.right_child; . let old_right_len = right_node.len(); . . // Make sure that we may steal safely. 13,660 ( 0.00%) assert!(old_left_len + count <= CAPACITY); 5,606 ( 0.00%) assert!(old_right_len >= count); . . let new_left_len = old_left_len + count; . let new_right_len = old_right_len - count; 2,732 ( 0.00%) *left_node.len_mut() = new_left_len as u16; 2,732 ( 0.00%) *right_node.len_mut() = new_right_len as u16; . . // Move leaf data. . { . // Move the right-most stolen pair to the parent. 3,155 ( 0.00%) let k = right_node.key_area_mut(count - 1).assume_init_read(); . let v = right_node.val_area_mut(count - 1).assume_init_read(); 1,692 ( 0.00%) let (k, v) = self.parent.replace_kv(k, v); . . // Move parent's key-value pair to the left child. . left_node.key_area_mut(old_left_len).write(k); . left_node.val_area_mut(old_left_len).write(v); . . // Move elements from the right child to the left one. . move_to_slice( . right_node.key_area_mut(..count - 1), 2,732 ( 0.00%) left_node.key_area_mut(old_left_len + 1..new_left_len), . ); . move_to_slice( . right_node.val_area_mut(..count - 1), . left_node.val_area_mut(old_left_len + 1..new_left_len), . ); . . // Fill gap where stolen elements used to be. . slice_shl(right_node.key_area_mut(..old_right_len), count); . slice_shl(right_node.val_area_mut(..old_right_len), count); . } . 13,660 ( 0.00%) match (left_node.reborrow_mut().force(), right_node.reborrow_mut().force()) { . (ForceResult::Internal(mut left), ForceResult::Internal(mut right)) => { . // Steal edges. . move_to_slice( . right.edge_area_mut(..count), . left.edge_area_mut(old_left_len + 1..new_left_len + 1), . ); . . // Fill gap where stolen edges used to be. -- line 1495 ---------------------------------------- -- line 1497 ---------------------------------------- . . left.correct_childrens_parent_links(old_left_len + 1..new_left_len + 1); . right.correct_childrens_parent_links(0..new_right_len + 1); . } . (ForceResult::Leaf(_), ForceResult::Leaf(_)) => {} . _ => unreachable!(), . } . } 21,856 ( 0.00%) } . } . . impl Handle, marker::Edge> { 304 ( 0.00%) pub fn forget_node_type( . self, . ) -> Handle, marker::Edge> { 532 ( 0.00%) unsafe { Handle::new_edge(self.node.forget_type(), self.idx) } 152 ( 0.00%) } . } . . impl Handle, marker::Edge> { . pub fn forget_node_type( . self, . ) -> Handle, marker::Edge> { . unsafe { Handle::new_edge(self.node.forget_type(), self.idx) } . } . } . . impl Handle, marker::KV> { 152 ( 0.00%) pub fn forget_node_type( . self, . ) -> Handle, marker::KV> { 266 ( 0.00%) unsafe { Handle::new_kv(self.node.forget_type(), self.idx) } 76 ( 0.00%) } . } . . impl Handle, marker::KV> { . pub fn forget_node_type( . self, . ) -> Handle, marker::KV> { . unsafe { Handle::new_kv(self.node.forget_type(), self.idx) } . } . } . . impl Handle, Type> { . /// Checks whether the underlying node is an `Internal` node or a `Leaf` node. 380 ( 0.00%) pub fn force( . self, . ) -> ForceResult< . Handle, Type>, . Handle, Type>, . > { 532 ( 0.00%) match self.node.force() { 304 ( 0.00%) ForceResult::Leaf(node) => { 836 ( 0.00%) ForceResult::Leaf(Handle { node, idx: self.idx, _marker: PhantomData }) 76 ( 0.00%) } . ForceResult::Internal(node) => { . ForceResult::Internal(Handle { node, idx: self.idx, _marker: PhantomData }) . } . } 152 ( 0.00%) } . } . . impl<'a, K, V, Type> Handle, K, V, marker::LeafOrInternal>, Type> { . /// Unsafely asserts to the compiler the static information that the handle's node is a `Leaf`. . pub unsafe fn cast_to_leaf_unchecked( . self, . ) -> Handle, K, V, marker::Leaf>, Type> { . let node = unsafe { self.node.cast_to_leaf_unchecked() }; -- line 1564 ---------------------------------------- -- line 1676 ---------------------------------------- . pub enum KV {} . pub enum Edge {} . } . . /// Inserts a value into a slice of initialized elements followed by one uninitialized element. . /// . /// # Safety . /// The slice has more than `idx` elements. 570 ( 0.00%) unsafe fn slice_insert(slice: &mut [MaybeUninit], idx: usize, val: T) { . unsafe { 418 ( 0.00%) let len = slice.len(); . debug_assert!(len > idx); 304 ( 0.00%) let slice_ptr = slice.as_mut_ptr(); 15,206,425 ( 0.04%) if len > idx + 1 { 1,735,870 ( 0.00%) ptr::copy(slice_ptr.add(idx), slice_ptr.add(idx + 1), len - idx - 1); . } 456 ( 0.00%) (*slice_ptr.add(idx)).write(val); . } 152 ( 0.00%) } . . /// Removes and returns a value from a slice of all initialized elements, leaving behind one . /// trailing uninitialized element. . /// . /// # Safety . /// The slice has more than `idx` elements. . unsafe fn slice_remove(slice: &mut [MaybeUninit], idx: usize) -> T { . unsafe { . let len = slice.len(); . debug_assert!(idx < len); . let slice_ptr = slice.as_mut_ptr(); . let ret = (*slice_ptr.add(idx)).assume_init_read(); 15,658,456 ( 0.05%) ptr::copy(slice_ptr.add(idx + 1), slice_ptr.add(idx), len - idx - 1); . ret . } . } . . /// Shifts the elements in a slice `distance` positions to the left. . /// . /// # Safety . /// The slice has at least `distance` elements. -- line 1715 ---------------------------------------- -- line 1722 ---------------------------------------- . . /// Shifts the elements in a slice `distance` positions to the right. . /// . /// # Safety . /// The slice has at least `distance` elements. . unsafe fn slice_shr(slice: &mut [MaybeUninit], distance: usize) { . unsafe { . let slice_ptr = slice.as_mut_ptr(); 10,460 ( 0.00%) ptr::copy(slice_ptr, slice_ptr.add(distance), slice.len() - distance); . } . } . . /// Moves all values from a slice of initialized elements to a slice . /// of uninitialized elements, leaving behind `src` as all uninitialized. . /// Works like `dst.copy_from_slice(src)` but does not require `T` to be `Copy`. . fn move_to_slice(src: &mut [MaybeUninit], dst: &mut [MaybeUninit]) { 755,916 ( 0.00%) assert!(src.len() == dst.len()); . unsafe { . ptr::copy_nonoverlapping(src.as_ptr(), dst.as_mut_ptr(), src.len()); . } . } . . #[cfg(test)] . mod tests; 44,658,008 ( 0.13%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/context.rs -------------------------------------------------------------------------------- Ir -- line 118 ---------------------------------------- . stability: InternedSet<'tcx, attr::Stability>, . . /// `#[rustc_const_stable]` and `#[rustc_const_unstable]` attributes . const_stability: InternedSet<'tcx, attr::ConstStability>, . } . . impl<'tcx> CtxtInterners<'tcx> { . fn new(arena: &'tcx WorkerLocal>) -> CtxtInterners<'tcx> { 17 ( 0.00%) CtxtInterners { . arena, . type_: Default::default(), . type_list: Default::default(), . substs: Default::default(), . region: Default::default(), . poly_existential_predicates: Default::default(), . canonical_var_infos: Default::default(), . predicate: Default::default(), -- line 134 ---------------------------------------- -- line 143 ---------------------------------------- . stability: Default::default(), . const_stability: Default::default(), . } . } . . /// Interns a type. . #[allow(rustc::usage_of_ty_tykind)] . #[inline(never)] 28,186,720 ( 0.08%) fn intern_ty(&self, kind: TyKind<'tcx>) -> Ty<'tcx> { . self.type_ 17,616,700 ( 0.05%) .intern(kind, |kind| { 414,306 ( 0.00%) let flags = super::flags::FlagComputation::for_kind(&kind); . . let ty_struct = TyS { 828,612 ( 0.00%) kind, . flags: flags.flags, . outer_exclusive_binder: flags.outer_exclusive_binder, . }; . . Interned(self.arena.alloc(ty_struct)) . }) . .0 31,710,060 ( 0.09%) } . . #[inline(never)] 12,119,952 ( 0.03%) fn intern_predicate( . &self, . kind: Binder<'tcx, PredicateKind<'tcx>>, . ) -> &'tcx PredicateInner<'tcx> { . self.predicate 10,604,958 ( 0.03%) .intern(kind, |kind| { 1,009,638 ( 0.00%) let flags = super::flags::FlagComputation::for_predicate(kind); . . let predicate_struct = PredicateInner { . kind, . flags: flags.flags, . outer_exclusive_binder: flags.outer_exclusive_binder, . }; . . Interned(self.arena.alloc(predicate_struct)) . }) . .0 13,634,946 ( 0.04%) } . } . . pub struct CommonTypes<'tcx> { . pub unit: Ty<'tcx>, . pub bool: Ty<'tcx>, . pub char: Ty<'tcx>, . pub isize: Ty<'tcx>, . pub i8: Ty<'tcx>, -- line 193 ---------------------------------------- -- line 237 ---------------------------------------- . /// safely used as a key in the maps of a TypeckResults. For that to be . /// the case, the HirId must have the same `owner` as all the other IDs in . /// this table (signified by `hir_owner`). Otherwise the HirId . /// would be in a different frame of reference and using its `local_id` . /// would result in lookup errors, or worse, in silently wrong data being . /// stored/returned. . #[inline] . fn validate_hir_id_for_typeck_results(hir_owner: LocalDefId, hir_id: hir::HirId) { 4,204,484 ( 0.01%) if hir_id.owner != hir_owner { . invalid_hir_id_for_typeck_results(hir_owner, hir_id); . } . } . . #[cold] . #[inline(never)] . fn invalid_hir_id_for_typeck_results(hir_owner: LocalDefId, hir_id: hir::HirId) { . ty::tls::with(|tcx| { -- line 253 ---------------------------------------- -- line 261 ---------------------------------------- . } . . impl<'a, V> LocalTableInContext<'a, V> { . pub fn contains_key(&self, id: hir::HirId) -> bool { . validate_hir_id_for_typeck_results(self.hir_owner, id); . self.data.contains_key(&id.local_id) . } . 3,435,418 ( 0.01%) pub fn get(&self, id: hir::HirId) -> Option<&V> { 685,522 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, id); 685,522 ( 0.00%) self.data.get(&id.local_id) 2,755,624 ( 0.01%) } . . pub fn iter(&self) -> hash_map::Iter<'_, hir::ItemLocalId, V> { . self.data.iter() . } . } . . impl<'a, V> ::std::ops::Index for LocalTableInContext<'a, V> { . type Output = V; . 34,368 ( 0.00%) fn index(&self, key: hir::HirId) -> &V { 3 ( 0.00%) self.get(key).expect("LocalTableInContext: key not found") 22,912 ( 0.00%) } . } . . pub struct LocalTableInContextMut<'a, V> { . hir_owner: LocalDefId, . data: &'a mut ItemLocalMap, . } . . impl<'a, V> LocalTableInContextMut<'a, V> { -- line 292 ---------------------------------------- -- line 507 ---------------------------------------- . pub treat_byte_string_as_slice: ItemLocalSet, . . /// Contains the data for evaluating the effect of feature `capture_disjoint_fields` . /// on closure size. . pub closure_size_eval: FxHashMap>, . } . . impl<'tcx> TypeckResults<'tcx> { 156,228 ( 0.00%) pub fn new(hir_owner: LocalDefId) -> TypeckResults<'tcx> { 1,848,698 ( 0.01%) TypeckResults { . hir_owner, . type_dependent_defs: Default::default(), . field_indices: Default::default(), . user_provided_types: Default::default(), . user_provided_sigs: Default::default(), . node_types: Default::default(), . node_substs: Default::default(), . adjustments: Default::default(), -- line 524 ---------------------------------------- -- line 532 ---------------------------------------- . tainted_by_errors: None, . concrete_opaque_types: Default::default(), . closure_min_captures: Default::default(), . closure_fake_reads: Default::default(), . generator_interior_types: ty::Binder::dummy(Default::default()), . treat_byte_string_as_slice: Default::default(), . closure_size_eval: Default::default(), . } 156,228 ( 0.00%) } . . /// Returns the final resolution of a `QPath` in an `Expr` or `Pat` node. 710,769 ( 0.00%) pub fn qpath_res(&self, qpath: &hir::QPath<'_>, id: hir::HirId) -> Res { 473,846 ( 0.00%) match *qpath { 1,330,428 ( 0.00%) hir::QPath::Resolved(_, ref path) => path.res, . hir::QPath::TypeRelative(..) | hir::QPath::LangItem(..) => self . .type_dependent_def(id) 91,110 ( 0.00%) .map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)), . } 1,184,615 ( 0.00%) } . 4,103 ( 0.00%) pub fn type_dependent_defs( . &self, . ) -> LocalTableInContext<'_, Result<(DefKind, DefId), ErrorReported>> { 51,224 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.type_dependent_defs } 4,103 ( 0.00%) } . 23,346 ( 0.00%) pub fn type_dependent_def(&self, id: HirId) -> Option<(DefKind, DefId)> { 39,279 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, id); . self.type_dependent_defs.get(&id.local_id).cloned().and_then(|r| r.ok()) 46,692 ( 0.00%) } . 2,992 ( 0.00%) pub fn type_dependent_def_id(&self, id: HirId) -> Option { . self.type_dependent_def(id).map(|(_, def_id)| def_id) 2,992 ( 0.00%) } . 243,679 ( 0.00%) pub fn type_dependent_defs_mut( . &mut self, . ) -> LocalTableInContextMut<'_, Result<(DefKind, DefId), ErrorReported>> { 243,679 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.type_dependent_defs } 243,679 ( 0.00%) } . . pub fn field_indices(&self) -> LocalTableInContext<'_, usize> { 39,725 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.field_indices } 7,340 ( 0.00%) } . . pub fn field_indices_mut(&mut self) -> LocalTableInContextMut<'_, usize> { 52,986 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.field_indices } 26,493 ( 0.00%) } . . pub fn user_provided_types(&self) -> LocalTableInContext<'_, CanonicalUserType<'tcx>> { 137,174 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.user_provided_types } 68,587 ( 0.00%) } . . pub fn user_provided_types_mut( . &mut self, . ) -> LocalTableInContextMut<'_, CanonicalUserType<'tcx>> { 30,448 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.user_provided_types } 15,224 ( 0.00%) } . . pub fn node_types(&self) -> LocalTableInContext<'_, Ty<'tcx>> { 623,374 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.node_types } 311,687 ( 0.00%) } . . pub fn node_types_mut(&mut self) -> LocalTableInContextMut<'_, Ty<'tcx>> { 1,043,644 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.node_types } 521,822 ( 0.00%) } . 4,573,122 ( 0.01%) pub fn node_type(&self, id: hir::HirId) -> Ty<'tcx> { 762,187 ( 0.00%) self.node_type_opt(id).unwrap_or_else(|| { . bug!("node_type: no type for node `{}`", tls::with(|tcx| tcx.hir().node_to_string(id))) . }) 3,810,935 ( 0.01%) } . 970,476 ( 0.00%) pub fn node_type_opt(&self, id: hir::HirId) -> Option> { 970,476 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, id); . self.node_types.get(&id.local_id).cloned() 1,940,952 ( 0.01%) } . . pub fn node_substs_mut(&mut self) -> LocalTableInContextMut<'_, SubstsRef<'tcx>> { 160,028 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.node_substs } 80,014 ( 0.00%) } . 337,008 ( 0.00%) pub fn node_substs(&self, id: hir::HirId) -> SubstsRef<'tcx> { 337,008 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, id); . self.node_substs.get(&id.local_id).cloned().unwrap_or_else(|| InternalSubsts::empty()) 674,016 ( 0.00%) } . 228,223 ( 0.00%) pub fn node_substs_opt(&self, id: hir::HirId) -> Option> { 228,223 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, id); . self.node_substs.get(&id.local_id).cloned() 456,446 ( 0.00%) } . . // Returns the type of a pattern as a monotype. Like @expr_ty, this function . // doesn't provide type parameter substitutions. . pub fn pat_ty(&self, pat: &hir::Pat<'_>) -> Ty<'tcx> { 96,712 ( 0.00%) self.node_type(pat.hir_id) . } . . // Returns the type of an expression as a monotype. . // . // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression. That is, in . // some cases, we insert `Adjustment` annotations such as auto-deref or . // auto-ref. The type returned by this function does not consider such . // adjustments. See `expr_ty_adjusted()` instead. . // . // NB (2): This type doesn't provide type parameter substitutions; e.g., if you . // ask for the type of "id" in "id(3)", it will return "fn(&isize) -> isize" . // instead of "fn(ty) -> T with T = isize". . pub fn expr_ty(&self, expr: &hir::Expr<'_>) -> Ty<'tcx> { 809,358 ( 0.00%) self.node_type(expr.hir_id) . } . . pub fn expr_ty_opt(&self, expr: &hir::Expr<'_>) -> Option> { 756,463 ( 0.00%) self.node_type_opt(expr.hir_id) . } . . pub fn adjustments(&self) -> LocalTableInContext<'_, Vec>> { 450,968 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.adjustments } 225,484 ( 0.00%) } . . pub fn adjustments_mut( . &mut self, . ) -> LocalTableInContextMut<'_, Vec>> { 578,660 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.adjustments } 289,330 ( 0.00%) } . 336,938 ( 0.00%) pub fn expr_adjustments(&self, expr: &hir::Expr<'_>) -> &[ty::adjustment::Adjustment<'tcx>] { 673,876 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, expr.hir_id); . self.adjustments.get(&expr.hir_id.local_id).map_or(&[], |a| &a[..]) 673,876 ( 0.00%) } . . /// Returns the type of `expr`, considering any `Adjustment` . /// entry recorded for that expression. 48,180 ( 0.00%) pub fn expr_ty_adjusted(&self, expr: &hir::Expr<'_>) -> Ty<'tcx> { 9,636 ( 0.00%) self.expr_adjustments(expr).last().map_or_else(|| self.expr_ty(expr), |adj| adj.target) 5,752 ( 0.00%) } . 125 ( 0.00%) pub fn expr_ty_adjusted_opt(&self, expr: &hir::Expr<'_>) -> Option> { 25 ( 0.00%) self.expr_adjustments(expr).last().map(|adj| adj.target).or_else(|| self.expr_ty_opt(expr)) 80 ( 0.00%) } . 47,121 ( 0.00%) pub fn is_method_call(&self, expr: &hir::Expr<'_>) -> bool { . // Only paths and method calls/overloaded operators have . // entries in type_dependent_defs, ignore the former here. 94,242 ( 0.00%) if let hir::ExprKind::Path(_) = expr.kind { . return false; . } . 100,658 ( 0.00%) matches!(self.type_dependent_defs().get(expr.hir_id), Some(Ok((DefKind::AssocFn, _)))) 94,242 ( 0.00%) } . 246,429 ( 0.00%) pub fn extract_binding_mode(&self, s: &Session, id: HirId, sp: Span) -> Option { . self.pat_binding_modes().get(id).copied().or_else(|| { . s.delay_span_bug(sp, "missing binding mode"); . None . }) 328,572 ( 0.00%) } . . pub fn pat_binding_modes(&self) -> LocalTableInContext<'_, BindingMode> { 220,341 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.pat_binding_modes } 69,099 ( 0.00%) } . . pub fn pat_binding_modes_mut(&mut self) -> LocalTableInContextMut<'_, BindingMode> { 109,956 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.pat_binding_modes } 54,978 ( 0.00%) } . . pub fn pat_adjustments(&self) -> LocalTableInContext<'_, Vec>> { 312,602 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.pat_adjustments } 156,301 ( 0.00%) } . . pub fn pat_adjustments_mut(&mut self) -> LocalTableInContextMut<'_, Vec>> { 95,092 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.pat_adjustments } 47,546 ( 0.00%) } . . /// For a given closure, returns the iterator of `ty::CapturedPlace`s that are captured . /// by the closure. 27,720 ( 0.00%) pub fn closure_min_captures_flattened( . &self, . closure_def_id: DefId, . ) -> impl Iterator> { . self.closure_min_captures . .get(&closure_def_id) . .map(|closure_min_captures| closure_min_captures.values().flat_map(|v| v.iter())) . .into_iter() . .flatten() 34,650 ( 0.00%) } . . pub fn closure_kind_origins(&self) -> LocalTableInContext<'_, (Span, HirPlace<'tcx>)> { 13,566 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.closure_kind_origins } 6,783 ( 0.00%) } . . pub fn closure_kind_origins_mut( . &mut self, . ) -> LocalTableInContextMut<'_, (Span, HirPlace<'tcx>)> { . LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.closure_kind_origins } . } . . pub fn liberated_fn_sigs(&self) -> LocalTableInContext<'_, ty::FnSig<'tcx>> { 36,478 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.liberated_fn_sigs } 18,239 ( 0.00%) } . . pub fn liberated_fn_sigs_mut(&mut self) -> LocalTableInContextMut<'_, ty::FnSig<'tcx>> { 22,912 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.liberated_fn_sigs } 11,456 ( 0.00%) } . . pub fn fru_field_types(&self) -> LocalTableInContext<'_, Vec>> { 13,572 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.fru_field_types } 6,786 ( 0.00%) } . . pub fn fru_field_types_mut(&mut self) -> LocalTableInContextMut<'_, Vec>> { 12 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.fru_field_types } 6 ( 0.00%) } . 561 ( 0.00%) pub fn is_coercion_cast(&self, hir_id: hir::HirId) -> bool { 187 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, hir_id); . self.coercion_casts.contains(&hir_id.local_id) 374 ( 0.00%) } . . pub fn set_coercion_cast(&mut self, id: ItemLocalId) { . self.coercion_casts.insert(id); . } . . pub fn coercion_casts(&self) -> &ItemLocalSet { 6,783 ( 0.00%) &self.coercion_casts 6,783 ( 0.00%) } . } . . impl<'a, 'tcx> HashStable> for TypeckResults<'tcx> { . fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) { . let ty::TypeckResults { . hir_owner, . ref type_dependent_defs, . ref field_indices, -- line 764 ---------------------------------------- -- line 819 ---------------------------------------- . const START_INDEX = 0, . } . } . . /// Mapping of type annotation indices to canonical user type annotations. . pub type CanonicalUserTypeAnnotations<'tcx> = . IndexVec>; . 6,938 ( 0.00%) #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)] . pub struct CanonicalUserTypeAnnotation<'tcx> { . pub user_ty: CanonicalUserType<'tcx>, . pub span: Span, 8,938 ( 0.00%) pub inferred_ty: Ty<'tcx>, . } . . /// Canonicalized user type annotation. . pub type CanonicalUserType<'tcx> = Canonical<'tcx, UserType<'tcx>>; . . impl<'tcx> CanonicalUserType<'tcx> { . /// Returns `true` if this represents a substitution of the form `[?0, ?1, ?2]`, . /// i.e., each thing is mapped to a canonical variable with the same index. 36,619 ( 0.00%) pub fn is_identity(&self) -> bool { 73,238 ( 0.00%) match self.value { . UserType::Ty(_) => false, . UserType::TypeOf(_, user_substs) => { 36,619 ( 0.00%) if user_substs.user_self_ty.is_some() { . return false; . } . . iter::zip(user_substs.substs, BoundVar::new(0)..).all(|(kind, cvar)| { . match kind.unpack() { 101,658 ( 0.00%) GenericArgKind::Type(ty) => match ty.kind() { . ty::Bound(debruijn, b) => { . // We only allow a `ty::INNERMOST` index in substitutions. 48,456 ( 0.00%) assert_eq!(*debruijn, ty::INNERMOST); . cvar == b.var . } . _ => false, . }, . 13,028 ( 0.00%) GenericArgKind::Lifetime(r) => match r { . ty::ReLateBound(debruijn, br) => { . // We only allow a `ty::INNERMOST` index in substitutions. . assert_eq!(*debruijn, ty::INNERMOST); . cvar == br.var . } . _ => false, . }, . -- line 867 ---------------------------------------- -- line 872 ---------------------------------------- . cvar == b . } . _ => false, . }, . } . }) . } . } 73,238 ( 0.00%) } . } . . /// A user-given type annotation attached to a constant. These arise . /// from constants that are named via paths, like `Foo::::new` and . /// so forth. 53,628 ( 0.00%) #[derive(Copy, Clone, Debug, PartialEq, TyEncodable, TyDecodable)] 398,827 ( 0.00%) #[derive(HashStable, TypeFoldable, Lift)] . pub enum UserType<'tcx> { . Ty(Ty<'tcx>), . . /// The canonical type is the result of `type_of(def_id)` with the . /// given substitutions applied. . TypeOf(DefId, UserSubsts<'tcx>), . } . . impl<'tcx> CommonTypes<'tcx> { . fn new(interners: &CtxtInterners<'tcx>) -> CommonTypes<'tcx> { 111 ( 0.00%) let mk = |ty| interners.intern_ty(ty); . . CommonTypes { . unit: mk(Tuple(List::empty())), . bool: mk(Bool), . char: mk(Char), . never: mk(Never), . isize: mk(Int(ty::IntTy::Isize)), . i8: mk(Int(ty::IntTy::I8)), -- line 906 ---------------------------------------- -- line 921 ---------------------------------------- . . trait_object_dummy_self: mk(Infer(ty::FreshTy(0))), . } . } . } . . impl<'tcx> CommonLifetimes<'tcx> { . fn new(interners: &CtxtInterners<'tcx>) -> CommonLifetimes<'tcx> { 67 ( 0.00%) let mk = |r| interners.region.intern(r, |r| Interned(interners.arena.alloc(r))).0; . . CommonLifetimes { 5 ( 0.00%) re_root_empty: mk(RegionKind::ReEmpty(ty::UniverseIndex::ROOT)), 5 ( 0.00%) re_static: mk(RegionKind::ReStatic), 5 ( 0.00%) re_erased: mk(RegionKind::ReErased), . } . } . } . . impl<'tcx> CommonConsts<'tcx> { . fn new(interners: &CtxtInterners<'tcx>, types: &CommonTypes<'tcx>) -> CommonConsts<'tcx> { 6 ( 0.00%) let mk_const = |c| interners.const_.intern(c, |c| Interned(interners.arena.alloc(c))).0; . . CommonConsts { . unit: mk_const(ty::Const { . val: ty::ConstKind::Value(ConstValue::Scalar(Scalar::ZST)), . ty: types.unit, . }), . } . } -- line 949 ---------------------------------------- -- line 1045 ---------------------------------------- . . /// Stores memory for globals (statics/consts). . pub(crate) alloc_map: Lock>, . . output_filenames: Arc, . } . . impl<'tcx> TyCtxt<'tcx> { 295,900 ( 0.00%) pub fn typeck_opt_const_arg( . self, . def: ty::WithOptConstParam, . ) -> &'tcx TypeckResults<'tcx> { 118,360 ( 0.00%) if let Some(param_did) = def.const_param_did { . self.typeck_const_arg((def.did, param_did)) . } else { . self.typeck(def.did) . } 236,720 ( 0.00%) } . 20,436 ( 0.00%) pub fn alloc_steal_thir(self, thir: Thir<'tcx>) -> &'tcx Steal> { 6,812 ( 0.00%) self.arena.alloc(Steal::new(thir)) 27,248 ( 0.00%) } . 107,695 ( 0.00%) pub fn alloc_steal_mir(self, mir: Body<'tcx>) -> &'tcx Steal> { 21,539 ( 0.00%) self.arena.alloc(Steal::new(mir)) 150,773 ( 0.00%) } . 27,248 ( 0.00%) pub fn alloc_steal_promoted( . self, . promoted: IndexVec>, . ) -> &'tcx Steal>> { 6,812 ( 0.00%) self.arena.alloc(Steal::new(promoted)) 34,060 ( 0.00%) } . 12,051 ( 0.00%) pub fn alloc_adt_def( . self, . did: DefId, . kind: AdtKind, . variants: IndexVec, . repr: ReprOptions, . ) -> &'tcx ty::AdtDef { 21,424 ( 0.00%) self.intern_adt_def(ty::AdtDef::new(self, did, kind, variants, repr)) 5,356 ( 0.00%) } . . /// Allocates a read-only byte or string literal for `mir::interpret`. 1,970 ( 0.00%) pub fn allocate_bytes(self, bytes: &[u8]) -> interpret::AllocId { . // Create an allocation that just contains these bytes. 394 ( 0.00%) let alloc = interpret::Allocation::from_bytes_byte_aligned_immutable(bytes); 5,122 ( 0.00%) let alloc = self.intern_const_alloc(alloc); . self.create_memory_alloc(alloc) 1,970 ( 0.00%) } . . /// Returns a range of the start/end indices specified with the . /// `rustc_layout_scalar_valid_range` attribute. . // FIXME(eddyb) this is an awkward spot for this method, maybe move it? 204,776 ( 0.00%) pub fn layout_scalar_valid_range(self, def_id: DefId) -> (Bound, Bound) { 102,388 ( 0.00%) let attrs = self.get_attrs(def_id); 435,149 ( 0.00%) let get = |name| { 102,388 ( 0.00%) let attr = match attrs.iter().find(|a| a.has_name(name)) { . Some(attr) => attr, . None => return Bound::Unbounded, . }; . debug!("layout_scalar_valid_range: attr={:?}", attr); 216 ( 0.00%) if let Some( . &[ . ast::NestedMetaItem::Literal(ast::Lit { 108 ( 0.00%) kind: ast::LitKind::Int(a, _), .. . }), . ], 54 ( 0.00%) ) = attr.meta_item_list().as_deref() . { . Bound::Included(a) . } else { . self.sess . .delay_span_bug(attr.span, "invalid rustc_layout_scalar_valid_range attribute"); . Bound::Unbounded . } 511,940 ( 0.00%) }; 153,582 ( 0.00%) ( 153,582 ( 0.00%) get(sym::rustc_layout_scalar_valid_range_start), 76,791 ( 0.00%) get(sym::rustc_layout_scalar_valid_range_end), . ) 204,776 ( 0.00%) } . . pub fn lift>(self, value: T) -> Option { . value.lift_to_tcx(self) . } . . /// Creates a type context and call the closure with a `TyCtxt` reference . /// to the context. The closure enforces that the type context and any interned . /// value (types, substs, etc.) can only be used while `ty::tls` has a valid . /// reference to the context, to allow formatting values that need it. 23 ( 0.00%) pub fn create_global_ctxt( . s: &'tcx Session, . lint_store: Lrc, . arena: &'tcx WorkerLocal>, . resolutions: ty::ResolverOutputs, . krate: &'tcx hir::Crate<'tcx>, . dep_graph: DepGraph, . on_disk_cache: Option<&'tcx dyn OnDiskCache<'tcx>>, . queries: &'tcx dyn query::QueryEngine<'tcx>, . query_kinds: &'tcx [DepKindStruct], . crate_name: &str, . output_filenames: OutputFilenames, . ) -> GlobalCtxt<'tcx> { 1 ( 0.00%) let data_layout = TargetDataLayout::parse(&s.target).unwrap_or_else(|err| { . s.fatal(&err); . }); . let interners = CtxtInterners::new(arena); . let common_types = CommonTypes::new(&interners); . let common_lifetimes = CommonLifetimes::new(&interners); . let common_consts = CommonConsts::new(&interners, &common_types); . 127 ( 0.00%) GlobalCtxt { . sess: s, 6 ( 0.00%) lint_store, . arena, 2 ( 0.00%) interners, 5 ( 0.00%) dep_graph, 4 ( 0.00%) untracked_resolutions: resolutions, 2 ( 0.00%) prof: s.prof.clone(), . types: common_types, . lifetimes: common_lifetimes, . consts: common_consts, . untracked_crate: krate, . on_disk_cache, . queries, . query_caches: query::QueryCaches::default(), . query_kinds, . ty_rcache: Default::default(), . pred_rcache: Default::default(), . selection_cache: Default::default(), . evaluation_cache: Default::default(), 1 ( 0.00%) crate_name: Symbol::intern(crate_name), . data_layout, . alloc_map: Lock::new(interpret::AllocMap::new()), . output_filenames: Arc::new(output_filenames), . } 9 ( 0.00%) } . . crate fn query_kind(self, k: DepKind) -> &'tcx DepKindStruct { . &self.query_kinds[k as usize] . } . . /// Constructs a `TyKind::Error` type and registers a `delay_span_bug` to ensure it gets used. . #[track_caller] . pub fn ty_error(self) -> Ty<'tcx> { -- line 1191 ---------------------------------------- -- line 1217 ---------------------------------------- . ty: Ty<'tcx>, . span: S, . msg: &str, . ) -> &'tcx Const<'tcx> { . self.sess.delay_span_bug(span, msg); . self.mk_const(ty::Const { val: ty::ConstKind::Error(DelaySpanBugEmitted(())), ty }) . } . 10,066 ( 0.00%) pub fn consider_optimizing String>(self, msg: T) -> bool { 1,438 ( 0.00%) let cname = self.crate_name(LOCAL_CRATE); 11,334 ( 0.00%) self.sess.consider_optimizing(cname.as_str(), msg) 11,504 ( 0.00%) } . . /// Obtain all lang items of this crate and all dependencies (recursively) 10,217,529 ( 0.03%) pub fn lang_items(self) -> &'tcx rustc_hir::lang_items::LanguageItems { . self.get_lang_items(()) 13,136,823 ( 0.04%) } . . /// Obtain the given diagnostic item's `DefId`. Use `is_diagnostic_item` if you just want to . /// compare against another `DefId`, since `is_diagnostic_item` is cheaper. 2,814 ( 0.00%) pub fn get_diagnostic_item(self, name: Symbol) -> Option { . self.all_diagnostic_items(()).name_to_id.get(&name).copied() 3,216 ( 0.00%) } . . /// Obtain the diagnostic item's name 524,181 ( 0.00%) pub fn get_diagnostic_name(self, id: DefId) -> Option { . self.diagnostic_items(id.krate).id_to_name.get(&id).copied() 599,064 ( 0.00%) } . . /// Check whether the diagnostic item with the given `name` has the given `DefId`. 105,056 ( 0.00%) pub fn is_diagnostic_item(self, name: Symbol, did: DefId) -> bool { . self.diagnostic_items(did.krate).name_to_id.get(&name) == Some(&did) 120,064 ( 0.00%) } . 145,159 ( 0.00%) pub fn stability(self) -> &'tcx stability::Index<'tcx> { . self.stability_index(()) 186,633 ( 0.00%) } . 4,562,943 ( 0.01%) pub fn features(self) -> &'tcx rustc_feature::Features { . self.features_query(()) 5,214,792 ( 0.02%) } . . pub fn def_key(self, id: DefId) -> rustc_hir::definitions::DefKey { . // Accessing the DefKey is ok, since it is part of DefPathHash. 871,809 ( 0.00%) if let Some(id) = id.as_local() { . self.untracked_resolutions.definitions.def_key(id) . } else { 431,685 ( 0.00%) self.untracked_resolutions.cstore.def_key(id) . } . } . . /// Converts a `DefId` into its fully expanded `DefPath` (every . /// `DefId` is really just an interned `DefPath`). . /// . /// Note that if `id` is not local to this crate, the result will . /// be a non-local `DefPath`. -- line 1272 ---------------------------------------- -- line 1277 ---------------------------------------- . } else { . self.untracked_resolutions.cstore.def_path(id) . } . } . . #[inline] . pub fn def_path_hash(self, def_id: DefId) -> rustc_hir::definitions::DefPathHash { . // Accessing the DefPathHash is ok, it is incr. comp. stable. 67,479 ( 0.00%) if let Some(def_id) = def_id.as_local() { . self.untracked_resolutions.definitions.def_path_hash(def_id) . } else { 380 ( 0.00%) self.untracked_resolutions.cstore.def_path_hash(def_id) . } . } . . #[inline] . pub fn stable_crate_id(self, crate_num: CrateNum) -> StableCrateId { . if crate_num == LOCAL_CRATE { . self.sess.local_stable_crate_id() . } else { -- line 1296 ---------------------------------------- -- line 1353 ---------------------------------------- . &(format!("{:08x}", stable_crate_id.to_u64()))[..4], . self.def_path(def_id).to_string_no_crate_verbose() . ) . } . . /// Note that this is *untracked* and should only be used within the query . /// system if the result is otherwise tracked through queries . pub fn cstore_untracked(self) -> &'tcx ty::CrateStoreDyn { 61,074 ( 0.00%) &*self.untracked_resolutions.cstore 30,537 ( 0.00%) } . . /// Note that this is *untracked* and should only be used within the query . /// system if the result is otherwise tracked through queries . pub fn definitions_untracked(self) -> &'tcx hir::definitions::Definitions { . &self.untracked_resolutions.definitions . } . . #[inline(always)] . pub fn create_stable_hashing_context(self) -> StableHashingContext<'tcx> { 1,018 ( 0.00%) let resolutions = &self.gcx.untracked_resolutions; 5,089 ( 0.00%) StableHashingContext::new(self.sess, &resolutions.definitions, &*resolutions.cstore) . } . . #[inline(always)] . pub fn create_no_span_stable_hashing_context(self) -> StableHashingContext<'tcx> { . let resolutions = &self.gcx.untracked_resolutions; . StableHashingContext::ignore_spans( . self.sess, . &resolutions.definitions, -- line 1381 ---------------------------------------- -- line 1390 ---------------------------------------- . /// If `true`, we should use the MIR-based borrowck, but also . /// fall back on the AST borrowck if the MIR-based one errors. . pub fn migrate_borrowck(self) -> bool { . self.borrowck_mode().migrate() . } . . /// What mode(s) of borrowck should we run? AST? MIR? both? . /// (Also considers the `#![feature(nll)]` setting.) 13,566 ( 0.00%) pub fn borrowck_mode(self) -> BorrowckMode { . // Here are the main constraints we need to deal with: . // . // 1. An opts.borrowck_mode of `BorrowckMode::Migrate` is . // synonymous with no `-Z borrowck=...` flag at all. . // . // 2. We want to allow developers on the Nightly channel . // to opt back into the "hard error" mode for NLL, . // (which they can do via specifying `#![feature(nll)]` -- line 1406 ---------------------------------------- -- line 1413 ---------------------------------------- . // errors. (To simplify the code here, it now even overrides . // a user's attempt to specify `-Z borrowck=compare`, which . // we arguably do not need anymore and should remove.) . // . // * Otherwise, if no `-Z borrowck=...` then use migrate mode . // . // * Otherwise, use the behavior requested via `-Z borrowck=...` . 20,349 ( 0.00%) if self.features().nll { . return BorrowckMode::Mir; . } . 6,783 ( 0.00%) self.sess.opts.borrowck_mode 27,132 ( 0.00%) } . . /// If `true`, we should use lazy normalization for constants, otherwise . /// we still evaluate them eagerly. . #[inline] . pub fn lazy_normalization(self) -> bool { 47 ( 0.00%) let features = self.features(); . // Note: We only use lazy normalization for generic const expressions. 9 ( 0.00%) features.generic_const_exprs . } . . #[inline] . pub fn local_crate_exports_generics(self) -> bool { . debug_assert!(self.sess.opts.share_generics()); . . self.sess.crate_types().iter().any(|crate_type| { . match crate_type { -- line 1442 ---------------------------------------- -- line 1554 ---------------------------------------- . self.mk_imm_ref( . self.lifetimes.re_static, . self.type_of(self.require_lang_item(LangItem::PanicLocation, None)) . .subst(self, self.mk_substs([self.lifetimes.re_static.into()].iter())), . ) . } . . /// Returns a displayable description and article for the given `def_id` (e.g. `("a", "struct")`). 33,517 ( 0.00%) pub fn article_and_description(self, def_id: DefId) -> (&'static str, &'static str) { 24,376 ( 0.00%) match self.def_kind(def_id) { . DefKind::Generator => match self.generator_kind(def_id).unwrap() { . rustc_hir::GeneratorKind::Async(..) => ("an", "async closure"), . rustc_hir::GeneratorKind::Gen => ("a", "generator"), . }, 54,846 ( 0.00%) def_kind => (def_kind.article(), def_kind.descr(def_id)), . } 27,423 ( 0.00%) } . . pub fn type_length_limit(self) -> Limit { . self.limits(()).type_length_limit . } . 3,369,961 ( 0.01%) pub fn recursion_limit(self) -> Limit { . self.limits(()).recursion_limit 3,851,384 ( 0.01%) } . . pub fn move_size_limit(self) -> Limit { . self.limits(()).move_size_limit . } . 22,554 ( 0.00%) pub fn const_eval_limit(self) -> Limit { . self.limits(()).const_eval_limit 25,776 ( 0.00%) } . . pub fn all_traits(self) -> impl Iterator + 'tcx { . iter::once(LOCAL_CRATE) . .chain(self.crates(()).iter().copied()) . .flat_map(move |cnum| self.traits_in_crate(cnum).iter().copied()) . } . } . -- line 1594 ---------------------------------------- -- line 1684 ---------------------------------------- . /// This is the implicit state of rustc. It contains the current . /// `TyCtxt` and query. It is updated when creating a local interner or . /// executing a new query. Whenever there's a `TyCtxt` value available . /// you should also have access to an `ImplicitCtxt` through the functions . /// in this module. . #[derive(Clone)] . pub struct ImplicitCtxt<'a, 'tcx> { . /// The current `TyCtxt`. 1 ( 0.00%) pub tcx: TyCtxt<'tcx>, . . /// The current query job, if any. This is updated by `JobOwner::start` in . /// `ty::query::plumbing` when executing a query. . pub query: Option>, . . /// Where to store diagnostics for the current query job, if any. . /// This is updated by `JobOwner::start` in `ty::query::plumbing` when executing a query. . pub diagnostics: Option<&'a Lock>>, -- line 1700 ---------------------------------------- -- line 1703 ---------------------------------------- . pub layout_depth: usize, . . /// The current dep graph task. This is used to add dependencies to queries . /// when executing them. . pub task_deps: TaskDepsRef<'a>, . } . . impl<'a, 'tcx> ImplicitCtxt<'a, 'tcx> { 5 ( 0.00%) pub fn new(gcx: &'tcx GlobalCtxt<'tcx>) -> Self { . let tcx = TyCtxt { gcx }; 25 ( 0.00%) ImplicitCtxt { . tcx, . query: None, . diagnostics: None, . layout_depth: 0, . task_deps: TaskDepsRef::Ignore, . } 5 ( 0.00%) } . } . . /// Sets Rayon's thread-local variable, which is preserved for Rayon jobs . /// to `value` during the call to `f`. It is restored to its previous value after. . /// This is used to set the pointer to the new `ImplicitCtxt`. . #[cfg(parallel_compiler)] . #[inline] . fn set_tlv R, R>(value: usize, f: F) -> R { -- line 1728 ---------------------------------------- -- line 1745 ---------------------------------------- . . /// Sets TLV to `value` during the call to `f`. . /// It is restored to its previous value after. . /// This is used to set the pointer to the new `ImplicitCtxt`. . #[cfg(not(parallel_compiler))] . #[inline] . fn set_tlv R, R>(value: usize, f: F) -> R { . let old = get_tlv(); 726,244 ( 0.00%) let _reset = rustc_data_structures::OnDrop(move || TLV.with(|tlv| tlv.set(old))); . TLV.with(|tlv| tlv.set(value)); . f() . } . . /// Gets the pointer to the current `ImplicitCtxt`. . #[cfg(not(parallel_compiler))] . #[inline] . fn get_tlv() -> usize { -- line 1761 ---------------------------------------- -- line 1763 ---------------------------------------- . } . . /// Sets `context` as the new current `ImplicitCtxt` for the duration of the function `f`. . #[inline] . pub fn enter_context<'a, 'tcx, F, R>(context: &ImplicitCtxt<'a, 'tcx>, f: F) -> R . where . F: FnOnce(&ImplicitCtxt<'a, 'tcx>) -> R, . { 1 ( 0.00%) set_tlv(context as *const _ as usize, || f(&context)) . } . . /// Allows access to the current `ImplicitCtxt` in a closure if one is available. . #[inline] . pub fn with_context_opt(f: F) -> R . where . F: for<'a, 'tcx> FnOnce(Option<&ImplicitCtxt<'a, 'tcx>>) -> R, . { . let context = get_tlv(); 2,863,118 ( 0.01%) if context == 0 { . f(None) . } else { . // We could get an `ImplicitCtxt` pointer from another thread. . // Ensure that `ImplicitCtxt` is `Sync`. . sync::assert_sync::>(); . . unsafe { f(Some(&*(context as *const ImplicitCtxt<'_, '_>))) } . } -- line 1789 ---------------------------------------- -- line 1805 ---------------------------------------- . /// This will panic if you pass it a `TyCtxt` which is different from the current . /// `ImplicitCtxt`'s `tcx` field. . #[inline] . pub fn with_related_context<'tcx, F, R>(tcx: TyCtxt<'tcx>, f: F) -> R . where . F: FnOnce(&ImplicitCtxt<'_, 'tcx>) -> R, . { . with_context(|context| unsafe { 1,407,466 ( 0.00%) assert!(ptr_eq(context.tcx.gcx, tcx.gcx)); . let context: &ImplicitCtxt<'_, '_> = mem::transmute(context); 1,406,610 ( 0.00%) f(context) . }) . } . . /// Allows access to the `TyCtxt` in the current `ImplicitCtxt`. . /// Panics if there is no `ImplicitCtxt` available. . #[inline] . pub fn with(f: F) -> R . where -- line 1823 ---------------------------------------- -- line 1981 ---------------------------------------- . fn into_pointer(&self) -> *const () { . self.0 as *const _ as *const () . } . } . . #[allow(rustc::usage_of_ty_tykind)] . impl<'tcx> Borrow> for Interned<'tcx, TyS<'tcx>> { . fn borrow<'a>(&'a self) -> &'a TyKind<'tcx> { 3,361,684 ( 0.01%) &self.0.kind() . } . } . . impl<'tcx> PartialEq for Interned<'tcx, TyS<'tcx>> { . fn eq(&self, other: &Interned<'tcx, TyS<'tcx>>) -> bool { . // The `Borrow` trait requires that `x.borrow() == y.borrow()` equals . // `x == y`. . self.0.kind() == other.0.kind() -- line 1997 ---------------------------------------- -- line 1998 ---------------------------------------- . } . } . . impl<'tcx> Eq for Interned<'tcx, TyS<'tcx>> {} . . impl<'tcx> Hash for Interned<'tcx, TyS<'tcx>> { . fn hash(&self, s: &mut H) { . // The `Borrow` trait requires that `x.borrow().hash(s) == x.hash(s)`. 688,116 ( 0.00%) self.0.kind().hash(s) . } . } . . impl<'tcx> Borrow>> for Interned<'tcx, PredicateInner<'tcx>> { . fn borrow<'a>(&'a self) -> &'a Binder<'tcx, PredicateKind<'tcx>> { 1,370,840 ( 0.00%) &self.0.kind . } . } . . impl<'tcx> PartialEq for Interned<'tcx, PredicateInner<'tcx>> { . fn eq(&self, other: &Interned<'tcx, PredicateInner<'tcx>>) -> bool { . // The `Borrow` trait requires that `x.borrow() == y.borrow()` equals . // `x == y`. . self.0.kind == other.0.kind -- line 2020 ---------------------------------------- -- line 2021 ---------------------------------------- . } . } . . impl<'tcx> Eq for Interned<'tcx, PredicateInner<'tcx>> {} . . impl<'tcx> Hash for Interned<'tcx, PredicateInner<'tcx>> { . fn hash(&self, s: &mut H) { . // The `Borrow` trait requires that `x.borrow().hash(s) == x.hash(s)`. 229,372 ( 0.00%) self.0.kind.hash(s) . } . } . . impl<'tcx, T> Borrow<[T]> for Interned<'tcx, List> { . fn borrow<'a>(&'a self) -> &'a [T] { 4,705,439 ( 0.01%) &self.0[..] . } . } . . impl<'tcx, T: PartialEq> PartialEq for Interned<'tcx, List> { . fn eq(&self, other: &Interned<'tcx, List>) -> bool { . // The `Borrow` trait requires that `x.borrow() == y.borrow()` equals . // `x == y`. . self.0[..] == other.0[..] -- line 2043 ---------------------------------------- -- line 2044 ---------------------------------------- . } . } . . impl<'tcx, T: Eq> Eq for Interned<'tcx, List> {} . . impl<'tcx, T: Hash> Hash for Interned<'tcx, List> { . fn hash(&self, s: &mut H) { . // The `Borrow` trait requires that `x.borrow().hash(s) == x.hash(s)`. 358,456 ( 0.00%) self.0[..].hash(s) . } . } . . macro_rules! direct_interners { . ($($name:ident: $method:ident($ty:ty),)+) => { . $(impl<'tcx> Borrow<$ty> for Interned<'tcx, $ty> { . fn borrow<'a>(&'a self) -> &'a $ty { 1,581,952 ( 0.00%) &self.0 . } . } . . impl<'tcx> PartialEq for Interned<'tcx, $ty> { . fn eq(&self, other: &Self) -> bool { . // The `Borrow` trait requires that `x.borrow() == y.borrow()` . // equals `x == y`. . self.0 == other.0 -- line 2068 ---------------------------------------- -- line 2070 ---------------------------------------- . } . . impl<'tcx> Eq for Interned<'tcx, $ty> {} . . impl<'tcx> Hash for Interned<'tcx, $ty> { . fn hash(&self, s: &mut H) { . // The `Borrow` trait requires that `x.borrow().hash(s) == . // x.hash(s)`. 143,986 ( 0.00%) self.0.hash(s) . } . } . . impl<'tcx> TyCtxt<'tcx> { 10,770,922 ( 0.03%) pub fn $method(self, v: $ty) -> &'tcx $ty { 5,505,834 ( 0.02%) self.interners.$name.intern(v, |v| { 32,462 ( 0.00%) Interned(self.interners.arena.alloc(v)) . }).0 12,117,303 ( 0.03%) } . })+ . } . } . . direct_interners! { . region: mk_region(RegionKind), . const_: mk_const(Const<'tcx>), . const_allocation: intern_const_alloc(Allocation), -- line 2095 ---------------------------------------- -- line 2097 ---------------------------------------- . adt_def: intern_adt_def(AdtDef), . stability: intern_stability(attr::Stability), . const_stability: intern_const_stability(attr::ConstStability), . } . . macro_rules! slice_interners { . ($($field:ident: $method:ident($ty:ty)),+ $(,)?) => ( . impl<'tcx> TyCtxt<'tcx> { 49,641,555 ( 0.14%) $(pub fn $method(self, v: &[$ty]) -> &'tcx List<$ty> { . self.interners.$field.intern_ref(v, || { . Interned(List::from_arena(&*self.arena, v)) . }).0 44,297,964 ( 0.13%) })+ . } . ); . } . . slice_interners!( . type_list: _intern_type_list(Ty<'tcx>), . substs: _intern_substs(GenericArg<'tcx>), . canonical_var_infos: _intern_canonical_var_infos(CanonicalVarInfo<'tcx>), -- line 2117 ---------------------------------------- -- line 2129 ---------------------------------------- . /// unsafe. . pub fn safe_to_unsafe_fn_ty(self, sig: PolyFnSig<'tcx>) -> Ty<'tcx> { . assert_eq!(sig.unsafety(), hir::Unsafety::Normal); . self.mk_fn_ptr(sig.map_bound(|sig| ty::FnSig { unsafety: hir::Unsafety::Unsafe, ..sig })) . } . . /// Given the def_id of a Trait `trait_def_id` and the name of an associated item `assoc_name` . /// returns true if the `trait_def_id` defines an associated item of name `assoc_name`. 21,444 ( 0.00%) pub fn trait_may_define_assoc_type(self, trait_def_id: DefId, assoc_name: Ident) -> bool { . self.super_traits_of(trait_def_id).any(|trait_did| { . self.associated_items(trait_did) . .find_by_name_and_kind(self, assoc_name, ty::AssocKind::Type, trait_did) . .is_some() . }) 16,083 ( 0.00%) } . . /// Computes the def-ids of the transitive supertraits of `trait_def_id`. This (intentionally) . /// does not compute the full elaborated super-predicates but just the set of def-ids. It is used . /// to identify which traits may define a given associated type to help avoid cycle errors. . /// Returns a `DefId` iterator. . fn super_traits_of(self, trait_def_id: DefId) -> impl Iterator + 'tcx { . let mut set = FxHashSet::default(); 3,574 ( 0.00%) let mut stack = vec![trait_def_id]; . . set.insert(trait_def_id); . 16,083 ( 0.00%) iter::from_fn(move || -> Option { 3,576 ( 0.00%) let trait_did = stack.pop()?; 1,788 ( 0.00%) let generic_predicates = self.super_predicates_of(trait_did); . . for (predicate, _) in generic_predicates.predicates { 3,996 ( 0.00%) if let ty::PredicateKind::Trait(data) = predicate.kind().skip_binder() { 2,664 ( 0.00%) if set.insert(data.def_id()) { . stack.push(data.def_id()); . } . } . } . . Some(trait_did) . }) . } -- line 2169 ---------------------------------------- -- line 2188 ---------------------------------------- . self.mk_fn_sig(params_iter, s.output(), s.c_variadic, unsafety, abi::Abi::Rust) . }) . } . . /// Same a `self.mk_region(kind)`, but avoids accessing the interners if . /// `*r == kind`. . #[inline] . pub fn reuse_or_mk_region(self, r: Region<'tcx>, kind: RegionKind) -> Region<'tcx> { 1,643,536 ( 0.00%) if *r == kind { r } else { self.mk_region(kind) } . } . . #[allow(rustc::usage_of_ty_tykind)] . #[inline] . pub fn mk_ty(self, st: TyKind<'tcx>) -> Ty<'tcx> { 24,822,851 ( 0.07%) self.interners.intern_ty(st) . } . . #[inline] . pub fn mk_predicate(self, binder: Binder<'tcx, PredicateKind<'tcx>>) -> Predicate<'tcx> { 16,375,801 ( 0.05%) let inner = self.interners.intern_predicate(binder); . Predicate { inner } . } . . #[inline] 19,925,968 ( 0.06%) pub fn reuse_or_mk_predicate( . self, . pred: Predicate<'tcx>, . binder: Binder<'tcx, PredicateKind<'tcx>>, . ) -> Predicate<'tcx> { 1,571,648 ( 0.00%) if pred.kind() != binder { self.mk_predicate(binder) } else { pred } 19,925,968 ( 0.06%) } . . pub fn mk_mach_int(self, tm: IntTy) -> Ty<'tcx> { 752 ( 0.00%) match tm { . IntTy::Isize => self.types.isize, . IntTy::I8 => self.types.i8, . IntTy::I16 => self.types.i16, . IntTy::I32 => self.types.i32, . IntTy::I64 => self.types.i64, . IntTy::I128 => self.types.i128, . } 752 ( 0.00%) } . . pub fn mk_mach_uint(self, tm: UintTy) -> Ty<'tcx> { 4,559 ( 0.00%) match tm { . UintTy::Usize => self.types.usize, . UintTy::U8 => self.types.u8, . UintTy::U16 => self.types.u16, . UintTy::U32 => self.types.u32, . UintTy::U64 => self.types.u64, . UintTy::U128 => self.types.u128, . } 4,559 ( 0.00%) } . . pub fn mk_mach_float(self, tm: FloatTy) -> Ty<'tcx> { 308 ( 0.00%) match tm { . FloatTy::F32 => self.types.f32, . FloatTy::F64 => self.types.f64, . } 308 ( 0.00%) } . . #[inline] . pub fn mk_static_str(self) -> Ty<'tcx> { 13,436 ( 0.00%) self.mk_imm_ref(self.lifetimes.re_static, self.types.str_) . } . . #[inline] . pub fn mk_adt(self, def: &'tcx AdtDef, substs: SubstsRef<'tcx>) -> Ty<'tcx> { . // Take a copy of substs so that we own the vectors inside. . self.mk_ty(Adt(def, substs)) . } . -- line 2259 ---------------------------------------- -- line 2329 ---------------------------------------- . } . . #[inline] . pub fn mk_imm_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> { . self.mk_ptr(TypeAndMut { ty, mutbl: hir::Mutability::Not }) . } . . #[inline] 10,892 ( 0.00%) pub fn mk_array(self, ty: Ty<'tcx>, n: u64) -> Ty<'tcx> { . self.mk_ty(Array(ty, ty::Const::from_usize(self, n))) 11,888 ( 0.00%) } . . #[inline] . pub fn mk_slice(self, ty: Ty<'tcx>) -> Ty<'tcx> { . self.mk_ty(Slice(ty)) . } . . #[inline] . pub fn intern_tup(self, ts: &[Ty<'tcx>]) -> Ty<'tcx> { 4,392 ( 0.00%) let kinds: Vec<_> = ts.iter().map(|&t| GenericArg::from(t)).collect(); 9,054 ( 0.00%) self.mk_ty(Tuple(self.intern_substs(&kinds))) . } . . pub fn mk_tup], Ty<'tcx>>>(self, iter: I) -> I::Output { 28,890 ( 0.00%) iter.intern_with(|ts| { 15,186 ( 0.00%) let kinds: Vec<_> = ts.iter().map(|&t| GenericArg::from(t)).collect(); 107,266 ( 0.00%) self.mk_ty(Tuple(self.intern_substs(&kinds))) 26,001 ( 0.00%) }) . } . . #[inline] . pub fn mk_unit(self) -> Ty<'tcx> { 4,294 ( 0.00%) self.types.unit . } . . #[inline] . pub fn mk_diverging_default(self) -> Ty<'tcx> { . if self.features().never_type_fallback { self.types.never } else { self.types.unit } . } . . #[inline] . pub fn mk_fn_def(self, def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> { . self.mk_ty(FnDef(def_id, substs)) . } . . #[inline] . pub fn mk_fn_ptr(self, fty: PolyFnSig<'tcx>) -> Ty<'tcx> { 7,164 ( 0.00%) self.mk_ty(FnPtr(fty)) . } . . #[inline] . pub fn mk_dynamic( . self, . obj: &'tcx List>>, . reg: ty::Region<'tcx>, . ) -> Ty<'tcx> { -- line 2384 ---------------------------------------- -- line 2412 ---------------------------------------- . . #[inline] . pub fn mk_ty_var(self, v: TyVid) -> Ty<'tcx> { . self.mk_ty_infer(TyVar(v)) . } . . #[inline] . pub fn mk_const_var(self, v: ConstVid<'tcx>, ty: Ty<'tcx>) -> &'tcx Const<'tcx> { 1,194 ( 0.00%) self.mk_const(ty::Const { val: ty::ConstKind::Infer(InferConst::Var(v)), ty }) . } . . #[inline] . pub fn mk_int_var(self, v: IntVid) -> Ty<'tcx> { . self.mk_ty_infer(IntVar(v)) . } . . #[inline] -- line 2428 ---------------------------------------- -- line 2445 ---------------------------------------- . self.mk_ty(Param(ParamTy { index, name })) . } . . #[inline] . pub fn mk_const_param(self, index: u32, name: Symbol, ty: Ty<'tcx>) -> &'tcx Const<'tcx> { . self.mk_const(ty::Const { val: ty::ConstKind::Param(ParamConst { index, name }), ty }) . } . 224,483 ( 0.00%) pub fn mk_param_from_def(self, param: &ty::GenericParamDef) -> GenericArg<'tcx> { 124,413 ( 0.00%) match param.kind { . GenericParamDefKind::Lifetime => { 107,796 ( 0.00%) self.mk_region(ty::ReEarlyBound(param.to_early_bound_region_data())).into() . } 28,206 ( 0.00%) GenericParamDefKind::Type { .. } => self.mk_ty_param(param.index, param.name).into(), . GenericParamDefKind::Const { .. } => { . self.mk_const_param(param.index, param.name, self.type_of(param.def_id)).into() . } . } 224,483 ( 0.00%) } . . #[inline] . pub fn mk_opaque(self, def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> { . self.mk_ty(Opaque(def_id, substs)) . } . 1,416 ( 0.00%) pub fn mk_place_field(self, place: Place<'tcx>, f: Field, ty: Ty<'tcx>) -> Place<'tcx> { 1,416 ( 0.00%) self.mk_place_elem(place, PlaceElem::Field(f, ty)) 2,832 ( 0.00%) } . . pub fn mk_place_deref(self, place: Place<'tcx>) -> Place<'tcx> { . self.mk_place_elem(place, PlaceElem::Deref) . } . 196 ( 0.00%) pub fn mk_place_downcast( . self, . place: Place<'tcx>, . adt_def: &'tcx AdtDef, . variant_index: VariantIdx, . ) -> Place<'tcx> { 196 ( 0.00%) self.mk_place_elem( . place, 392 ( 0.00%) PlaceElem::Downcast(Some(adt_def.variants[variant_index].name), variant_index), . ) 392 ( 0.00%) } . . pub fn mk_place_downcast_unnamed( . self, . place: Place<'tcx>, . variant_index: VariantIdx, . ) -> Place<'tcx> { . self.mk_place_elem(place, PlaceElem::Downcast(None, variant_index)) . } -- line 2496 ---------------------------------------- -- line 2497 ---------------------------------------- . . pub fn mk_place_index(self, place: Place<'tcx>, index: Local) -> Place<'tcx> { . self.mk_place_elem(place, PlaceElem::Index(index)) . } . . /// This method copies `Place`'s projection, add an element and reintern it. Should not be used . /// to build a full `Place` it's just a convenient way to grab a projection and modify it in . /// flight. 14,508 ( 0.00%) pub fn mk_place_elem(self, place: Place<'tcx>, elem: PlaceElem<'tcx>) -> Place<'tcx> { . let mut projection = place.projection.to_vec(); . projection.push(elem); . . Place { local: place.local, projection: self.intern_place_elems(&projection) } 16,120 ( 0.00%) } . 54,124 ( 0.00%) pub fn intern_poly_existential_predicates( . self, . eps: &[ty::Binder<'tcx, ExistentialPredicate<'tcx>>], . ) -> &'tcx List>> { 7,732 ( 0.00%) assert!(!eps.is_empty()); . assert!( . eps.array_windows() 70 ( 0.00%) .all(|[a, b]| a.skip_binder().stable_cmp(self, &b.skip_binder()) . != Ordering::Greater) . ); 30,928 ( 0.00%) self._intern_poly_existential_predicates(eps) 61,856 ( 0.00%) } . . pub fn intern_predicates(self, preds: &[Predicate<'tcx>]) -> &'tcx List> { . // FIXME consider asking the input slice to be sorted to avoid . // re-interning permutations, in which case that would be asserted . // here. 317,651 ( 0.00%) if preds.is_empty() { . // The macro-generated method below asserts we don't intern an empty slice. . List::empty() . } else { 264,872 ( 0.00%) self._intern_predicates(preds) . } 107,984 ( 0.00%) } . . pub fn intern_type_list(self, ts: &[Ty<'tcx>]) -> &'tcx List> { 403,691 ( 0.00%) if ts.is_empty() { List::empty() } else { self._intern_type_list(ts) } 3,030 ( 0.00%) } . . pub fn intern_substs(self, ts: &[GenericArg<'tcx>]) -> &'tcx List> { 7,616,011 ( 0.02%) if ts.is_empty() { List::empty() } else { self._intern_substs(ts) } 373,080 ( 0.00%) } . . pub fn intern_projs(self, ps: &[ProjectionKind]) -> &'tcx List { . if ps.is_empty() { List::empty() } else { self._intern_projs(ps) } . } . . pub fn intern_place_elems(self, ts: &[PlaceElem<'tcx>]) -> &'tcx List> { 188,118 ( 0.00%) if ts.is_empty() { List::empty() } else { self._intern_place_elems(ts) } 95,404 ( 0.00%) } . . pub fn intern_canonical_var_infos( . self, . ts: &[CanonicalVarInfo<'tcx>], . ) -> CanonicalVarInfos<'tcx> { 690,305 ( 0.00%) if ts.is_empty() { List::empty() } else { self._intern_canonical_var_infos(ts) } 5,990 ( 0.00%) } . . pub fn intern_bound_variable_kinds( . self, . ts: &[ty::BoundVariableKind], . ) -> &'tcx List { 111,671 ( 0.00%) if ts.is_empty() { List::empty() } else { self._intern_bound_variable_kinds(ts) } 169,076 ( 0.00%) } . . pub fn mk_fn_sig( . self, . inputs: I, . output: I::Item, . c_variadic: bool, . unsafety: hir::Unsafety, . abi: abi::Abi, . ) -> , ty::FnSig<'tcx>>>::Output . where . I: Iterator, ty::FnSig<'tcx>>>, . { . inputs.chain(iter::once(output)).intern_with(|xs| ty::FnSig { 31,293 ( 0.00%) inputs_and_output: self.intern_type_list(xs), 10,109 ( 0.00%) c_variadic, 11,683 ( 0.00%) unsafety, 17,070 ( 0.00%) abi, 290 ( 0.00%) }) . } . . pub fn mk_poly_existential_predicates< . I: InternAs< . [ty::Binder<'tcx, ExistentialPredicate<'tcx>>], . &'tcx List>>, . >, . >( . self, . iter: I, . ) -> I::Output { 30,906 ( 0.00%) iter.intern_with(|xs| self.intern_poly_existential_predicates(xs)) . } . . pub fn mk_predicates], &'tcx List>>>( . self, . iter: I, . ) -> I::Output { 32 ( 0.00%) iter.intern_with(|xs| self.intern_predicates(xs)) . } . . pub fn mk_type_list], &'tcx List>>>(self, iter: I) -> I::Output { 25,620 ( 0.00%) iter.intern_with(|xs| self.intern_type_list(xs)) . } . . pub fn mk_substs], &'tcx List>>>( . self, . iter: I, . ) -> I::Output { 3,364,783 ( 0.01%) iter.intern_with(|xs| self.intern_substs(xs)) . } . . pub fn mk_place_elems], &'tcx List>>>( . self, . iter: I, . ) -> I::Output { 54 ( 0.00%) iter.intern_with(|xs| self.intern_place_elems(xs)) . } . 302,282 ( 0.00%) pub fn mk_substs_trait(self, self_ty: Ty<'tcx>, rest: &[GenericArg<'tcx>]) -> SubstsRef<'tcx> { . self.mk_substs(iter::once(self_ty.into()).chain(rest.iter().cloned())) 604,564 ( 0.00%) } . . pub fn mk_bound_variable_kinds< . I: InternAs<[ty::BoundVariableKind], &'tcx List>, . >( . self, . iter: I, . ) -> I::Output { 511,051 ( 0.00%) iter.intern_with(|xs| self.intern_bound_variable_kinds(xs)) . } . . /// Walks upwards from `id` to find a node which might change lint levels with attributes. . /// It stops at `bound` and just returns it if reached. 2,370,620 ( 0.01%) pub fn maybe_lint_level_root_bounded(self, mut id: HirId, bound: HirId) -> HirId { 2,370,620 ( 0.01%) let hir = self.hir(); . loop { 5,268,762 ( 0.02%) if id == bound { . return bound; . } . 7,089,634 ( 0.02%) if hir.attrs(id).iter().any(|attr| Level::from_symbol(attr.name_or_empty()).is_some()) { . return id; . } . let next = hir.get_parent_node(id); 4,252,782 ( 0.01%) if next == id { . bug!("lint traversal reached the root of the crate"); . } . id = next; . } 3,386,600 ( 0.01%) } . 81,232 ( 0.00%) pub fn lint_level_at_node( . self, . lint: &'static Lint, . mut id: hir::HirId, . ) -> (Level, LintLevelSource) { . let sets = self.lint_levels(()); . loop { 514,324 ( 0.00%) if let Some(pair) = sets.level_and_source(lint, id, self.sess) { . return pair; . } 41,352 ( 0.00%) let next = self.hir().get_parent_node(id); 124,056 ( 0.00%) if next == id { . bug!("lint traversal reached the root of the crate"); . } . id = next; . } 81,232 ( 0.00%) } . 16,702 ( 0.00%) pub fn struct_span_lint_hir( . self, . lint: &'static Lint, . hir_id: HirId, . span: impl Into, . decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>), . ) { 19,084 ( 0.00%) let (level, src) = self.lint_level_at_node(lint, hir_id); 10,385 ( 0.00%) struct_lint_level(self.sess, lint, level, src, Some(span.into()), decorate); 9,544 ( 0.00%) } . . pub fn struct_lint_node( . self, . lint: &'static Lint, . id: HirId, . decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>), . ) { . let (level, src) = self.lint_level_at_node(lint, id); . struct_lint_level(self.sess, lint, level, src, None, decorate); . } . 30,128 ( 0.00%) pub fn in_scope_traits(self, id: HirId) -> Option<&'tcx [TraitCandidate]> { 8,608 ( 0.00%) let map = self.in_scope_traits_map(id.owner)?; . let candidates = map.get(&id.local_id)?; 8,608 ( 0.00%) Some(&*candidates) 34,432 ( 0.00%) } . 205,016 ( 0.00%) pub fn named_region(self, id: HirId) -> Option { . debug!(?id, "named_region"); . self.named_region_map(id.owner).and_then(|map| map.get(&id.local_id).cloned()) 263,592 ( 0.00%) } . 28,386 ( 0.00%) pub fn is_late_bound(self, id: HirId) -> bool { . self.is_late_bound_map(id.owner) 1,575 ( 0.00%) .map_or(false, |(owner, set)| owner == id.owner && set.contains(&id.local_id)) 25,232 ( 0.00%) } . 157,850 ( 0.00%) pub fn object_lifetime_defaults(self, id: HirId) -> Option> { . self.object_lifetime_defaults_map(id.owner) 202,950 ( 0.00%) } . 206,676 ( 0.00%) pub fn late_bound_vars(self, id: HirId) -> &'tcx List { . self.mk_bound_variable_kinds( . self.late_bound_vars_map(id.owner) . .and_then(|map| map.get(&id.local_id).cloned()) . .unwrap_or_else(|| { . bug!("No bound vars found for {:?} ({:?})", self.hir().node_to_string(id), id) . }) . .iter(), . ) 206,676 ( 0.00%) } . . pub fn lifetime_scope(self, id: HirId) -> Option { . self.lifetime_scope_map(id.owner).and_then(|mut map| map.remove(&id.local_id)) . } . . /// Whether the `def_id` counts as const fn in the current crate, considering all active . /// feature gates 3,770 ( 0.00%) pub fn is_const_fn(self, def_id: DefId) -> bool { 377 ( 0.00%) if self.is_const_fn_raw(def_id) { 962 ( 0.00%) match self.lookup_const_stability(def_id) { 4 ( 0.00%) Some(stability) if stability.level.is_unstable() => { . // has a `rustc_const_unstable` attribute, check whether the user enabled the . // corresponding feature gate. 2 ( 0.00%) self.features() . .declared_lib_features . .iter() . .any(|&(sym, _)| sym == stability.feature) . } . // functions without const stability are either stable user written . // const fn or the user is using feature gates and we thus don't . // care what they do . _ => true, . } . } else { . false . } 3,393 ( 0.00%) } . } . . impl<'tcx> TyCtxtAt<'tcx> { . /// Constructs a `TyKind::Error` type and registers a `delay_span_bug` to ensure it gets used. . #[track_caller] . pub fn ty_error(self) -> Ty<'tcx> { . self.tcx.ty_error_with_message(self.span, "TyKind::Error constructed but no error reported") . } -- line 2759 ---------------------------------------- -- line 2774 ---------------------------------------- . } . . impl InternAs<[T], R> for I . where . E: InternIteratorElement, . I: Iterator, . { . type Output = E::Output; 110,560 ( 0.00%) fn intern_with(self, f: F) -> Self::Output . where . F: FnOnce(&[T]) -> R, . { 16,118,140 ( 0.05%) E::intern_with(self, f) 115,065 ( 0.00%) } . } . . pub trait InternIteratorElement: Sized { . type Output; . fn intern_with, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output; . } . . impl InternIteratorElement for T { . type Output = R; 2,257,397 ( 0.01%) fn intern_with, F: FnOnce(&[T]) -> R>( . mut iter: I, . f: F, . ) -> Self::Output { . // This code is hot enough that it's worth specializing for the most . // common length lists, to avoid the overhead of `SmallVec` creation. . // Lengths 0, 1, and 2 typically account for ~95% of cases. If . // `size_hint` is incorrect a panic will occur via an `unwrap` or an . // `assert`. 2,551,384 ( 0.01%) match iter.size_hint() { . (0, Some(0)) => { 3 ( 0.00%) assert!(iter.next().is_none()); . f(&[]) . } . (1, Some(1)) => { . let t0 = iter.next().unwrap(); 111 ( 0.00%) assert!(iter.next().is_none()); 303,054 ( 0.00%) f(&[t0]) . } . (2, Some(2)) => { . let t0 = iter.next().unwrap(); . let t1 = iter.next().unwrap(); 1,604 ( 0.00%) assert!(iter.next().is_none()); 339,834 ( 0.00%) f(&[t0, t1]) . } 34,024 ( 0.00%) _ => f(&iter.collect::>()), . } 2,393,378 ( 0.01%) } . } . . impl<'a, T, R> InternIteratorElement for &'a T . where . T: Clone + 'a, . { . type Output = R; 115,962 ( 0.00%) fn intern_with, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output { . // This code isn't hot. 116 ( 0.00%) f(&iter.cloned().collect::>()) 92,874 ( 0.00%) } . } . . impl InternIteratorElement for Result { . type Output = Result; 5,592,091 ( 0.02%) fn intern_with, F: FnOnce(&[T]) -> R>( . mut iter: I, . f: F, . ) -> Self::Output { . // This code is hot enough that it's worth specializing for the most . // common length lists, to avoid the overhead of `SmallVec` creation. . // Lengths 0, 1, and 2 typically account for ~95% of cases. If . // `size_hint` is incorrect a panic will occur via an `unwrap` or an . // `assert`, unless a failure happens first, in which case the result . // will be an error anyway. 4,437,722 ( 0.01%) Ok(match iter.size_hint() { . (0, Some(0)) => { . assert!(iter.next().is_none()); . f(&[]) . } . (1, Some(1)) => { 23,136 ( 0.00%) let t0 = iter.next().unwrap()?; . assert!(iter.next().is_none()); 302,342 ( 0.00%) f(&[t0]) . } . (2, Some(2)) => { 1,396 ( 0.00%) let t0 = iter.next().unwrap()?; 1,396 ( 0.00%) let t1 = iter.next().unwrap()?; 2,094 ( 0.00%) assert!(iter.next().is_none()); 538,002 ( 0.00%) f(&[t0, t1]) . } 44,380 ( 0.00%) _ => f(&iter.collect::, _>>()?), . }) 6,286,192 ( 0.02%) } . } . . // We are comparing types with different invariant lifetimes, so `ptr::eq` . // won't work for us. . fn ptr_eq(t: *const T, u: *const U) -> bool { 1,407,466 ( 0.00%) t as *const () == u as *const () . } . . pub fn provide(providers: &mut ty::query::Providers) { 2 ( 0.00%) providers.in_scope_traits_map = . |tcx, id| tcx.hir_crate(()).owners[id].as_ref().map(|owner_info| &owner_info.trait_map); 3 ( 0.00%) providers.resolutions = |tcx, ()| &tcx.untracked_resolutions; 2 ( 0.00%) providers.module_reexports = . |tcx, id| tcx.resolutions(()).reexport_map.get(&id).map(|v| &v[..]); 2 ( 0.00%) providers.crate_name = |tcx, id| { 1 ( 0.00%) assert_eq!(id, LOCAL_CRATE); 1 ( 0.00%) tcx.crate_name . }; 2 ( 0.00%) providers.maybe_unused_trait_import = . |tcx, id| tcx.resolutions(()).maybe_unused_trait_imports.contains(&id); 2 ( 0.00%) providers.maybe_unused_extern_crates = . |tcx, ()| &tcx.resolutions(()).maybe_unused_extern_crates[..]; 2 ( 0.00%) providers.names_imported_by_glob_use = |tcx, id| { . tcx.arena.alloc(tcx.resolutions(()).glob_map.get(&id).cloned().unwrap_or_default()) . }; . 92 ( 0.00%) providers.lookup_stability = |tcx, id| tcx.stability().local_stability(id.expect_local()); 2 ( 0.00%) providers.lookup_const_stability = 1,143 ( 0.00%) |tcx, id| tcx.stability().local_const_stability(id.expect_local()); 2 ( 0.00%) providers.lookup_deprecation_entry = 164,792 ( 0.00%) |tcx, id| tcx.stability().local_deprecation_entry(id.expect_local()); 2 ( 0.00%) providers.extern_mod_stmt_cnum = . |tcx, id| tcx.resolutions(()).extern_crate_map.get(&id).cloned(); 3 ( 0.00%) providers.output_filenames = |tcx, ()| tcx.output_filenames.clone(); 3 ( 0.00%) providers.features_query = |tcx, ()| tcx.sess.features_untracked(); 2 ( 0.00%) providers.is_panic_runtime = |tcx, cnum| { . assert_eq!(cnum, LOCAL_CRATE); . tcx.sess.contains_name(tcx.hir().krate_attrs(), sym::panic_runtime) . }; 2 ( 0.00%) providers.is_compiler_builtins = |tcx, cnum| { . assert_eq!(cnum, LOCAL_CRATE); . tcx.sess.contains_name(tcx.hir().krate_attrs(), sym::compiler_builtins) . }; 2 ( 0.00%) providers.has_panic_handler = |tcx, cnum| { 1 ( 0.00%) assert_eq!(cnum, LOCAL_CRATE); . // We want to check if the panic handler was defined in this crate 3 ( 0.00%) tcx.lang_items().panic_impl().map_or(false, |did| did.is_local()) . }; . } 12,937,947 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/iter/traits/iterator.rs -------------------------------------------------------------------------------- Ir -- line 152 ---------------------------------------- . /// // an infinite iterator has no upper bound . /// // and the maximum possible lower bound . /// let iter = 0..; . /// . /// assert_eq!((usize::MAX, None), iter.size_hint()); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 2,970 ( 0.00%) fn size_hint(&self) -> (usize, Option) { 5,940 ( 0.00%) (0, None) 1,980 ( 0.00%) } . . /// Consumes the iterator, counting the number of iterations and returning it. . /// . /// This method will call [`next`] repeatedly until [`None`] is encountered, . /// returning the number of times it saw [`Some`]. Note that [`next`] has to be . /// called at least once even if the iterator does not have any elements. . /// . /// [`next`]: Iterator::next -- line 170 ---------------------------------------- -- line 193 ---------------------------------------- . /// assert_eq!(a.iter().count(), 5); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . fn count(self) -> usize . where . Self: Sized, . { 57,143 ( 0.00%) self.fold( . 0, . #[rustc_inherit_overflow_checks] 193,198 ( 0.00%) |count, _| count + 1, . ) . } . . /// Consumes the iterator, returning the last element. . /// . /// This method will evaluate the iterator until it returns [`None`]. While . /// doing so, it keeps track of the current element. After [`None`] is . /// returned, `last()` will then return the last element it saw. -- line 212 ---------------------------------------- -- line 267 ---------------------------------------- . /// assert_eq!(iter.next(), Some(&3)); . /// assert_eq!(iter.advance_by(0), Ok(())); . /// assert_eq!(iter.advance_by(100), Err(1)); // only `&4` was skipped . /// ``` . #[inline] . #[unstable(feature = "iter_advance_by", reason = "recently added", issue = "77404")] . fn advance_by(&mut self, n: usize) -> Result<(), usize> { . for i in 0..n { 11,272 ( 0.00%) self.next().ok_or(i)?; . } . Ok(()) . } . . /// Returns the `n`th element of the iterator. . /// . /// Like most indexing operations, the count starts from zero, so `nth(0)` . /// returns the first value, `nth(1)` the second, and so on. -- line 283 ---------------------------------------- -- line 313 ---------------------------------------- . /// Returning `None` if there are less than `n + 1` elements: . /// . /// ``` . /// let a = [1, 2, 3]; . /// assert_eq!(a.iter().nth(10), None); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 8 ( 0.00%) fn nth(&mut self, n: usize) -> Option { . self.advance_by(n).ok()?; 24,090 ( 0.00%) self.next() . } . . /// Creates an iterator starting at the same point, but stepping by . /// the given amount at each iteration. . /// . /// Note 1: The first element of the iterator will always be returned, . /// regardless of the step given. . /// -- line 331 ---------------------------------------- -- line 436 ---------------------------------------- . /// s.encode_wide().chain(std::iter::once(0)).collect() . /// } . /// ``` . /// . /// [`once`]: crate::iter::once . /// [`OsStr`]: ../../std/ffi/struct.OsStr.html . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 750,976 ( 0.00%) fn chain(self, other: U) -> Chain . where . Self: Sized, . U: IntoIterator, . { 2,884,595 ( 0.01%) Chain::new(self, other.into_iter()) 253,284 ( 0.00%) } . . /// 'Zips up' two iterators into a single iterator of pairs. . /// . /// `zip()` returns a new iterator that will iterate over two other . /// iterators, returning a tuple where the first element comes from the . /// first iterator, and the second element comes from the second iterator. . /// . /// In other words, it zips two iterators together, into a single one. -- line 458 ---------------------------------------- -- line 550 ---------------------------------------- . /// # assert_eq!(zipped.next(), None); . /// ``` . /// . /// [`enumerate`]: Iterator::enumerate . /// [`next`]: Iterator::next . /// [`zip`]: crate::iter::zip . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 290,112 ( 0.00%) fn zip(self, other: U) -> Zip . where . Self: Sized, . U: IntoIterator, . { 233,302 ( 0.00%) Zip::new(self, other.into_iter()) 38,824 ( 0.00%) } . . /// Creates a new iterator which places a copy of `separator` between adjacent . /// items of the original iterator. . /// . /// In case `separator` does not implement [`Clone`] or needs to be . /// computed every time, use [`intersperse_with`]. . /// . /// # Examples -- line 572 ---------------------------------------- -- line 709 ---------------------------------------- . /// . /// // Instead, use for: . /// for x in 0..5 { . /// println!("{}", x); . /// } . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 592,440 ( 0.00%) fn map(self, f: F) -> Map . where . Self: Sized, . F: FnMut(Self::Item) -> B, . { 2,650,597 ( 0.01%) Map::new(self, f) 381,484 ( 0.00%) } . . /// Calls a closure on each element of an iterator. . /// . /// This is equivalent to using a [`for`] loop on the iterator, although . /// `break` and `continue` are not possible from a closure. It's generally . /// more idiomatic to use a `for` loop, but `for_each` may be more legible . /// when processing items at the end of longer iterator chains. In some . /// cases `for_each` may also be faster than a loop, because it will use -- line 731 ---------------------------------------- -- line 754 ---------------------------------------- . /// ``` . /// (0..5).flat_map(|x| x * 100 .. x * 110) . /// .enumerate() . /// .filter(|&(i, x)| (i + x) % 3 == 0) . /// .for_each(|(i, x)| println!("{}:{}", i, x)); . /// ``` . #[inline] . #[stable(feature = "iterator_for_each", since = "1.21.0")] 672,163 ( 0.00%) fn for_each(self, f: F) . where . Self: Sized, . F: FnMut(Self::Item), . { . #[inline] 270,025 ( 0.00%) fn call(mut f: impl FnMut(T)) -> impl FnMut((), T) { 11,210,684 ( 0.03%) move |(), item| f(item) 401,044 ( 0.00%) } . 21,987,690 ( 0.06%) self.fold((), call(f)); 278,012 ( 0.00%) } . . /// Creates an iterator which uses a closure to determine if an element . /// should be yielded. . /// . /// Given an element the closure must return `true` or `false`. The returned . /// iterator will yield only the elements for which the closure returns . /// true. . /// -- line 781 ---------------------------------------- -- line 829 ---------------------------------------- . /// assert_eq!(iter.next(), None); . /// ``` . /// . /// of these layers. . /// . /// Note that `iter.filter(f).next()` is equivalent to `iter.find(f)`. . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 26,598 ( 0.00%) fn filter

(self, predicate: P) -> Filter . where . Self: Sized, . P: FnMut(&Self::Item) -> bool, . { 385,771 ( 0.00%) Filter::new(self, predicate) 10,880 ( 0.00%) } . . /// Creates an iterator that both filters and maps. . /// . /// The returned iterator yields only the `value`s for which the supplied . /// closure returns `Some(value)`. . /// . /// `filter_map` can be used to make chains of [`filter`] and [`map`] more . /// concise. The example below shows how a `map().filter().map()` can be -- line 851 ---------------------------------------- -- line 874 ---------------------------------------- . /// let a = ["1", "two", "NaN", "four", "5"]; . /// let mut iter = a.iter().map(|s| s.parse()).filter(|s| s.is_ok()).map(|s| s.unwrap()); . /// assert_eq!(iter.next(), Some(1)); . /// assert_eq!(iter.next(), Some(5)); . /// assert_eq!(iter.next(), None); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 13,650 ( 0.00%) fn filter_map(self, f: F) -> FilterMap . where . Self: Sized, . F: FnMut(Self::Item) -> Option, . { 33,585 ( 0.00%) FilterMap::new(self, f) 7,556 ( 0.00%) } . . /// Creates an iterator which gives the current iteration count as well as . /// the next value. . /// . /// The iterator returned yields pairs `(i, val)`, where `i` is the . /// current index of iteration and `val` is the value returned by the . /// iterator. . /// -- line 896 ---------------------------------------- -- line 920 ---------------------------------------- . /// . /// assert_eq!(iter.next(), Some((0, &'a'))); . /// assert_eq!(iter.next(), Some((1, &'b'))); . /// assert_eq!(iter.next(), Some((2, &'c'))); . /// assert_eq!(iter.next(), None); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 629,915 ( 0.00%) fn enumerate(self) -> Enumerate . where . Self: Sized, . { 125,983 ( 0.00%) Enumerate::new(self) 251,966 ( 0.00%) } . . /// Creates an iterator which can use the [`peek`] and [`peek_mut`] methods . /// to look at the next element of the iterator without consuming it. See . /// their documentation for more information. . /// . /// Note that the underlying iterator is still advanced when [`peek`] or . /// [`peek_mut`] are called for the first time: In order to retrieve the . /// next element, [`next`] is called on the underlying iterator, hence any -- line 941 ---------------------------------------- -- line 991 ---------------------------------------- . /// // The value reappears as the iterator continues . /// assert_eq!(iter.collect::>(), vec![&1000, &3]); . /// ``` . /// [`peek`]: Peekable::peek . /// [`peek_mut`]: Peekable::peek_mut . /// [`next`]: Iterator::next . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 1,315 ( 0.00%) fn peekable(self) -> Peekable . where . Self: Sized, . { 280 ( 0.00%) Peekable::new(self) 526 ( 0.00%) } . . /// Creates an iterator that [`skip`]s elements based on a predicate. . /// . /// [`skip`]: Iterator::skip . /// . /// `skip_while()` takes a closure as an argument. It will call this . /// closure on each element of the iterator, and ignore elements . /// until it returns `false`. -- line 1012 ---------------------------------------- -- line 1309 ---------------------------------------- . /// let v = [1, 2]; . /// let mut iter = v.into_iter().take(5); . /// assert_eq!(iter.next(), Some(1)); . /// assert_eq!(iter.next(), Some(2)); . /// assert_eq!(iter.next(), None); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 169,684 ( 0.00%) fn take(self, n: usize) -> Take . where . Self: Sized, . { 339,424 ( 0.00%) Take::new(self, n) 84,842 ( 0.00%) } . . /// An iterator adapter similar to [`fold`] that holds internal state and . /// produces a new iterator. . /// . /// [`fold`]: Iterator::fold . /// . /// `scan()` takes two arguments: an initial value which seeds the internal . /// state, and a closure with two arguments, the first being a mutable -- line 1330 ---------------------------------------- -- line 1393 ---------------------------------------- . /// // chars() returns an iterator . /// let merged: String = words.iter() . /// .flat_map(|s| s.chars()) . /// .collect(); . /// assert_eq!(merged, "alphabetagamma"); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 20,488 ( 0.00%) fn flat_map(self, f: F) -> FlatMap . where . Self: Sized, . U: IntoIterator, . F: FnMut(Self::Item) -> U, . { 9,270 ( 0.00%) FlatMap::new(self, f) 7,732 ( 0.00%) } . . /// Creates an iterator that flattens nested structure. . /// . /// This is useful when you have an iterator of iterators or an iterator of . /// things that can be turned into iterators and you want to remove one . /// level of indirection. . /// . /// # Examples -- line 1416 ---------------------------------------- -- line 1465 ---------------------------------------- . /// Instead, only one level of nesting is removed. That is, if you . /// `flatten()` a three-dimensional array, the result will be . /// two-dimensional and not one-dimensional. To get a one-dimensional . /// structure, you have to `flatten()` again. . /// . /// [`flat_map()`]: Iterator::flat_map . #[inline] . #[stable(feature = "iterator_flatten", since = "1.29.0")] 8,106 ( 0.00%) fn flatten(self) -> Flatten . where . Self: Sized, . Self::Item: IntoIterator, . { 13,510 ( 0.00%) Flatten::new(self) 5,404 ( 0.00%) } . . /// Creates an iterator which ends after the first [`None`]. . /// . /// After an iterator returns [`None`], future calls may or may not yield . /// [`Some(T)`] again. `fuse()` adapts an iterator, ensuring that after a . /// [`None`] is given, it will always return [`None`] forever. . /// . /// Note that the [`Fuse`] wrapper is a no-op on iterators that implement -- line 1487 ---------------------------------------- -- line 1533 ---------------------------------------- . /// . /// // it will always return `None` after the first time. . /// assert_eq!(iter.next(), None); . /// assert_eq!(iter.next(), None); . /// assert_eq!(iter.next(), None); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 19,704 ( 0.00%) fn fuse(self) -> Fuse . where . Self: Sized, . { 93,275 ( 0.00%) Fuse::new(self) 13,136 ( 0.00%) } . . /// Does something with each element of an iterator, passing the value on. . /// . /// When using iterators, you'll often chain several of them together. . /// While working on such code, you might want to check out what's . /// happening at various parts in the pipeline. To do that, insert . /// a call to `inspect()`. . /// -- line 1554 ---------------------------------------- -- line 1765 ---------------------------------------- . /// ``` . /// . /// [`iter`]: Iterator::next . /// [`String`]: ../../std/string/struct.String.html . /// [`char`]: type@char . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[must_use = "if you really need to exhaust the iterator, consider `.for_each(drop)` instead"] 334,196 ( 0.00%) fn collect>(self) -> B . where . Self: Sized, . { 1,676,533 ( 0.00%) FromIterator::from_iter(self) 449,265 ( 0.00%) } . . /// Consumes an iterator, creating two collections from it. . /// . /// The predicate passed to `partition()` can return `true`, or `false`. . /// `partition()` returns a pair, all of the elements for which it returned . /// `true`, and all of the elements for which it returned `false`. . /// . /// See also [`is_partitioned()`] and [`partition_in_place()`]. -- line 1786 ---------------------------------------- -- line 1798 ---------------------------------------- . /// let (even, odd): (Vec, Vec) = a . /// .iter() . /// .partition(|&n| n % 2 == 0); . /// . /// assert_eq!(even, vec![2]); . /// assert_eq!(odd, vec![1, 3]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 504 ( 0.00%) fn partition(self, f: F) -> (B, B) . where . Self: Sized, . B: Default + Extend, . F: FnMut(&Self::Item) -> bool, . { . #[inline] . fn extend<'a, T, B: Extend>( . mut f: impl FnMut(&T) -> bool + 'a, . left: &'a mut B, . right: &'a mut B, . ) -> impl FnMut((), T) + 'a { . move |(), x| { 57 ( 0.00%) if f(&x) { . left.extend_one(x); . } else { . right.extend_one(x); . } . } . } . . let mut left: B = Default::default(); . let mut right: B = Default::default(); . 4 ( 0.00%) self.fold((), extend(f, &mut left, &mut right)); . 752 ( 0.00%) (left, right) 567 ( 0.00%) } . . /// Reorders the elements of this iterator *in-place* according to the given predicate, . /// such that all those that return `true` precede all those that return `false`. . /// Returns the number of `true` elements found. . /// . /// The relative order of partitioned items is not maintained. . /// . /// # Current implementation -- line 1841 ---------------------------------------- -- line 2011 ---------------------------------------- . /// } else { . /// ControlFlow::Break(prev) . /// } . /// }); . /// assert_eq!(triangular, ControlFlow::Continue(435)); . /// ``` . #[inline] . #[stable(feature = "iterator_try_fold", since = "1.27.0")] 334,187 ( 0.00%) fn try_fold(&mut self, init: B, mut f: F) -> R . where . Self: Sized, . F: FnMut(B, Self::Item) -> R, . R: Try, . { 108,888 ( 0.00%) let mut accum = init; 24,104,232 ( 0.07%) while let Some(x) = self.next() { 53,467,699 ( 0.15%) accum = f(accum, x)?; . } 115,205 ( 0.00%) try { accum } 338,925 ( 0.00%) } . . /// An iterator method that applies a fallible function to each item in the . /// iterator, stopping at the first error and returning that error. . /// . /// This can also be thought of as the fallible form of [`for_each()`] . /// or as the stateless version of [`try_fold()`]. . /// . /// [`for_each()`]: Iterator::for_each -- line 2038 ---------------------------------------- -- line 2077 ---------------------------------------- . fn try_for_each(&mut self, f: F) -> R . where . Self: Sized, . F: FnMut(Self::Item) -> R, . R: Try, . { . #[inline] . fn call(mut f: impl FnMut(T) -> R) -> impl FnMut((), T) -> R { 41,592 ( 0.00%) move |(), x| f(x) . } . 5,231 ( 0.00%) self.try_fold((), call(f)) . } . . /// Folds every element into an accumulator by applying an operation, . /// returning the final result. . /// . /// `fold()` takes two arguments: an initial value, and a closure with two . /// arguments: an 'accumulator', and an element. The closure returns the value that . /// the accumulator should have for the next iteration. -- line 2096 ---------------------------------------- -- line 2188 ---------------------------------------- . /// // they're the same . /// assert_eq!(result, result2); . /// ``` . /// . /// [`reduce()`]: Iterator::reduce . #[doc(alias = "inject", alias = "foldl")] . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 1,182,082 ( 0.00%) fn fold(mut self, init: B, mut f: F) -> B . where . Self: Sized, . F: FnMut(B, Self::Item) -> B, . { 630,326 ( 0.00%) let mut accum = init; 28,057,317 ( 0.08%) while let Some(x) = self.next() { 13,195,116 ( 0.04%) accum = f(accum, x); . } 265,171 ( 0.00%) accum 1,350,966 ( 0.00%) } . . /// Reduces the elements to a single one, by repeatedly applying a reducing . /// operation. . /// . /// If the iterator is empty, returns [`None`]; otherwise, returns the . /// result of the reduction. . /// . /// The reducing function is a closure with two arguments: an 'accumulator', and an element. -- line 2214 ---------------------------------------- -- line 2240 ---------------------------------------- . #[inline] . #[stable(feature = "iterator_fold_self", since = "1.51.0")] . fn reduce(mut self, f: F) -> Option . where . Self: Sized, . F: FnMut(Self::Item, Self::Item) -> Self::Item, . { . let first = self.next()?; 59,631 ( 0.00%) Some(self.fold(first, f)) . } . . /// Reduces the elements to a single one by repeatedly applying a reducing operation. If the . /// closure returns a failure, the failure is propagated back to the caller immediately. . /// . /// The return type of this method depends on the return type of the closure. If the closure . /// returns `Result`, then this function will return `Result, . /// E>`. If the closure returns `Option`, then this function will return -- line 2256 ---------------------------------------- -- line 2370 ---------------------------------------- . fn all(&mut self, f: F) -> bool . where . Self: Sized, . F: FnMut(Self::Item) -> bool, . { . #[inline] . fn check(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> ControlFlow<()> { . move |(), x| { 158,876 ( 0.00%) if f(x) { ControlFlow::CONTINUE } else { ControlFlow::BREAK } . } . } 157,281 ( 0.00%) self.try_fold((), check(f)) == ControlFlow::CONTINUE . } . . /// Tests if any element of the iterator matches a predicate. . /// . /// `any()` takes a closure that returns `true` or `false`. It applies . /// this closure to each element of the iterator, and if any of them return . /// `true`, then so does `any()`. If they all return `false`, it . /// returns `false`. -- line 2389 ---------------------------------------- -- line 2415 ---------------------------------------- . /// . /// assert!(iter.any(|&x| x != 2)); . /// . /// // we can still use `iter`, as there are more elements. . /// assert_eq!(iter.next(), Some(&2)); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 4,950 ( 0.00%) fn any(&mut self, f: F) -> bool . where . Self: Sized, . F: FnMut(Self::Item) -> bool, . { . #[inline] . fn check(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> ControlFlow<()> { 7,677 ( 0.00%) move |(), x| { 23,055 ( 0.00%) if f(x) { ControlFlow::BREAK } else { ControlFlow::CONTINUE } 12,795 ( 0.00%) } 1,650 ( 0.00%) } . 13,200 ( 0.00%) self.try_fold((), check(f)) == ControlFlow::BREAK 6,600 ( 0.00%) } . . /// Searches for an element of an iterator that satisfies a predicate. . /// . /// `find()` takes a closure that returns `true` or `false`. It applies . /// this closure to each element of the iterator, and if any of them return . /// `true`, then `find()` returns [`Some(element)`]. If they all return . /// `false`, it returns [`None`]. . /// -- line 2444 ---------------------------------------- -- line 2475 ---------------------------------------- . /// . /// // we can still use `iter`, as there are more elements. . /// assert_eq!(iter.next(), Some(&3)); . /// ``` . /// . /// Note that `iter.find(f)` is equivalent to `iter.filter(f).next()`. . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 16,419 ( 0.00%) fn find

(&mut self, predicate: P) -> Option . where . Self: Sized, . P: FnMut(&Self::Item) -> bool, . { . #[inline] 4,122 ( 0.00%) fn check(mut predicate: impl FnMut(&T) -> bool) -> impl FnMut((), T) -> ControlFlow { 5,637 ( 0.00%) move |(), x| { 1,088,435 ( 0.00%) if predicate(&x) { ControlFlow::Break(x) } else { ControlFlow::CONTINUE } 5,408 ( 0.00%) } 6,183 ( 0.00%) } . 1,200,075 ( 0.00%) self.try_fold((), check(predicate)).break_value() 4,122 ( 0.00%) } . . /// Applies function to the elements of iterator and returns . /// the first non-none result. . /// . /// `iter.find_map(f)` is equivalent to `iter.filter_map(f).next()`. . /// . /// # Examples . /// -- line 2504 ---------------------------------------- -- line 2506 ---------------------------------------- . /// let a = ["lol", "NaN", "2", "5"]; . /// . /// let first_number = a.iter().find_map(|s| s.parse().ok()); . /// . /// assert_eq!(first_number, Some(2)); . /// ``` . #[inline] . #[stable(feature = "iterator_find_map", since = "1.30.0")] 25,662 ( 0.00%) fn find_map(&mut self, f: F) -> Option . where . Self: Sized, . F: FnMut(Self::Item) -> Option, . { . #[inline] 7,332 ( 0.00%) fn check(mut f: impl FnMut(T) -> Option) -> impl FnMut((), T) -> ControlFlow { 692,193 ( 0.00%) move |(), x| match f(x) { 353,329 ( 0.00%) Some(x) => ControlFlow::Break(x), 8,530 ( 0.00%) None => ControlFlow::CONTINUE, 15,842 ( 0.00%) } 10,998 ( 0.00%) } . 41,119 ( 0.00%) self.try_fold((), check(f)).break_value() 10,338 ( 0.00%) } . . /// Applies function to the elements of iterator and returns . /// the first true result or the first error. . /// . /// The return type of this method depends on the return type of the closure. . /// If you return `Result` from the closure, you'll get a `Result; E>`. . /// If you return `Option` from the closure, you'll get an `Option>`. . /// -- line 2536 ---------------------------------------- -- line 2644 ---------------------------------------- . /// assert_eq!(iter.next(), Some(&3)); . /// . /// // The returned index depends on iterator state . /// assert_eq!(iter.position(|&x| x == 4), Some(0)); . /// . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 54 ( 0.00%) fn position

(&mut self, predicate: P) -> Option . where . Self: Sized, . P: FnMut(Self::Item) -> bool, . { . #[inline] . fn check( . mut predicate: impl FnMut(T) -> bool, . ) -> impl FnMut(usize, T) -> ControlFlow { . #[rustc_inherit_overflow_checks] 486 ( 0.00%) move |i, x| { 1,461 ( 0.00%) if predicate(x) { ControlFlow::Break(i) } else { ControlFlow::Continue(i + 1) } 324 ( 0.00%) } 18 ( 0.00%) } . 162 ( 0.00%) self.try_fold(0, check(predicate)).break_value() 36 ( 0.00%) } . . /// Searches for an element in an iterator from the right, returning its . /// index. . /// . /// `rposition()` takes a closure that returns `true` or `false`. It applies . /// this closure to each element of the iterator, starting from the end, . /// and if one of them returns `true`, then `rposition()` returns . /// [`Some(index)`]. If all of them return `false`, it returns [`None`]. -- line 2676 ---------------------------------------- -- line 2812 ---------------------------------------- . /// # Examples . /// . /// ``` . /// let a = [-3_i32, 0, 1, 5, -10]; . /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10); . /// ``` . #[inline] . #[stable(feature = "iter_cmp_by_key", since = "1.6.0")] 518 ( 0.00%) fn max_by_key(self, f: F) -> Option . where . Self: Sized, . F: FnMut(&Self::Item) -> B, . { . #[inline] . fn key(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) { 188 ( 0.00%) move |x| (f(&x), x) . } . . #[inline] . fn compare((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering { . x_p.cmp(y_p) . } . 856 ( 0.00%) let (_, x) = self.map(key(f)).max_by(compare)?; . Some(x) 592 ( 0.00%) } . . /// Returns the element that gives the maximum value with respect to the . /// specified comparison function. . /// . /// If several elements are equally maximum, the last element is . /// returned. If the iterator is empty, [`None`] is returned. . /// . /// # Examples -- line 2845 ---------------------------------------- -- line 2852 ---------------------------------------- . #[stable(feature = "iter_max_by", since = "1.15.0")] . fn max_by(self, compare: F) -> Option . where . Self: Sized, . F: FnMut(&Self::Item, &Self::Item) -> Ordering, . { . #[inline] . fn fold(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T { 84 ( 0.00%) move |x, y| cmp::max_by(x, y, &mut compare) . } . 94,998 ( 0.00%) self.reduce(fold(compare)) . } . . /// Returns the element that gives the minimum value from the . /// specified function. . /// . /// If several elements are equally minimum, the first element is . /// returned. If the iterator is empty, [`None`] is returned. . /// -- line 2871 ---------------------------------------- -- line 2942 ---------------------------------------- . /// assert_eq!(iter.next(), Some(&2)); . /// assert_eq!(iter.next(), Some(&1)); . /// . /// assert_eq!(iter.next(), None); . /// ``` . #[inline] . #[doc(alias = "reverse")] . #[stable(feature = "rust1", since = "1.0.0")] 18 ( 0.00%) fn rev(self) -> Rev . where . Self: Sized + DoubleEndedIterator, . { 31 ( 0.00%) Rev::new(self) 12 ( 0.00%) } . . /// Converts an iterator of pairs into a pair of containers. . /// . /// `unzip()` consumes an entire iterator of pairs, producing two . /// collections: one from the left elements of the pairs, and one . /// from the right elements. . /// . /// This function is, in some sense, the opposite of [`zip`]. -- line 2963 ---------------------------------------- -- line 2987 ---------------------------------------- . #[stable(feature = "rust1", since = "1.0.0")] . fn unzip(self) -> (FromA, FromB) . where . FromA: Default + Extend, . FromB: Default + Extend, . Self: Sized + Iterator, . { . let mut unzipped: (FromA, FromB) = Default::default(); 105,851 ( 0.00%) unzipped.extend(self); . unzipped . } . . /// Creates an iterator which copies all of its elements. . /// . /// This is useful when you have an iterator over `&T`, but you need an . /// iterator over `T`. . /// -- line 3003 ---------------------------------------- -- line 3017 ---------------------------------------- . /// assert_eq!(v_map, vec![1, 2, 3]); . /// ``` . #[stable(feature = "iter_copied", since = "1.36.0")] . fn copied<'a, T: 'a>(self) -> Copied . where . Self: Sized + Iterator, . T: Copy, . { 169,770 ( 0.00%) Copied::new(self) . } . . /// Creates an iterator which [`clone`]s all of its elements. . /// . /// This is useful when you have an iterator over `&T`, but you need an . /// iterator over `T`. . /// . /// [`clone`]: Clone::clone -- line 3033 ---------------------------------------- -- line 3043 ---------------------------------------- . /// . /// // cloned is the same as .map(|&x| x), for integers . /// let v_map: Vec<_> = a.iter().map(|&x| x).collect(); . /// . /// assert_eq!(v_cloned, vec![1, 2, 3]); . /// assert_eq!(v_map, vec![1, 2, 3]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 11,829 ( 0.00%) fn cloned<'a, T: 'a>(self) -> Cloned . where . Self: Sized + Iterator, . T: Clone, . { 1,071,432 ( 0.00%) Cloned::new(self) 7,886 ( 0.00%) } . . /// Repeats an iterator endlessly. . /// . /// Instead of stopping at [`None`], the iterator will instead start again, . /// from the beginning. After iterating again, it will start at the . /// beginning again. And again. And again. Forever. Note that in case the . /// original iterator is empty, the resulting iterator will also be empty. . /// -- line 3065 ---------------------------------------- -- line 3107 ---------------------------------------- . /// . /// ``` . /// let a = [1, 2, 3]; . /// let sum: i32 = a.iter().sum(); . /// . /// assert_eq!(sum, 6); . /// ``` . #[stable(feature = "iter_arith", since = "1.11.0")] 801 ( 0.00%) fn sum(self) -> S . where . Self: Sized, . S: Sum, . { 534 ( 0.00%) Sum::sum(self) 534 ( 0.00%) } . . /// Iterates over the entire iterator, multiplying all the elements . /// . /// An empty iterator returns the one value of the type. . /// . /// # Panics . /// . /// When calling `product()` and a primitive integer type is being returned, -- line 3129 ---------------------------------------- -- line 3313 ---------------------------------------- . /// . /// # Examples . /// . /// ``` . /// assert_eq!([1].iter().eq([1].iter()), true); . /// assert_eq!([1].iter().eq([1, 2].iter()), false); . /// ``` . #[stable(feature = "iter_order", since = "1.5.0")] 196 ( 0.00%) fn eq(self, other: I) -> bool . where . I: IntoIterator, . Self::Item: PartialEq, . Self: Sized, . { 224 ( 0.00%) self.eq_by(other, |x, y| x == y) 224 ( 0.00%) } . . /// Determines if the elements of this [`Iterator`] are equal to those of . /// another with respect to the specified equality function. . /// . /// # Examples . /// . /// Basic usage: . /// -- line 3336 ---------------------------------------- -- line 3344 ---------------------------------------- . /// ``` . #[unstable(feature = "iter_order_by", issue = "64295")] . fn eq_by(mut self, other: I, mut eq: F) -> bool . where . Self: Sized, . I: IntoIterator, . F: FnMut(Self::Item, I::Item) -> bool, . { 280 ( 0.00%) let mut other = other.into_iter(); . . loop { 84 ( 0.00%) let x = match self.next() { . None => return other.next().is_none(), 308 ( 0.00%) Some(val) => val, . }; . 84 ( 0.00%) let y = match other.next() { . None => return false, . Some(val) => val, . }; . . if !eq(x, y) { . return false; . } . } -- line 3368 ---------------------------------------- -- line 3589 ---------------------------------------- . unreachable!("Always specialized"); . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Iterator for &mut I { . type Item = I::Item; . #[inline] 188 ( 0.00%) fn next(&mut self) -> Option { 892,042 ( 0.00%) (**self).next() 282 ( 0.00%) } . fn size_hint(&self) -> (usize, Option) { . (**self).size_hint() . } . fn advance_by(&mut self, n: usize) -> Result<(), usize> { . (**self).advance_by(n) . } . fn nth(&mut self, n: usize) -> Option { . (**self).nth(n) -- line 3607 ---------------------------------------- 12,509,050 ( 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>> { 78,055 ( 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>> { 7,935 ( 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,090,419 ( 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), . .. . }) 188,366 ( 0.00%) | Node::Expr(Expr { kind: ExprKind::Closure(.., body, _, _), .. }) => Some(*body), . 210 ( 0.00%) Node::AnonConst(constant) => Some(constant.body), . . _ => None, . } . } . . fn is_body_owner<'hir>(node: Node<'hir>, hir_id: HirId) -> bool { . match associated_body(node) { . Some(b) => b.hir_id == hir_id, -- line 71 ---------------------------------------- -- line 83 ---------------------------------------- . pub struct ParentHirIterator<'hir> { . current_id: HirId, . map: Map<'hir>, . } . . impl<'hir> Iterator for ParentHirIterator<'hir> { . type Item = (HirId, Node<'hir>); . 112,966 ( 0.00%) fn next(&mut self) -> Option { 16,138 ( 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); . 48,414 ( 0.00%) if parent_id == self.current_id { . self.current_id = CRATE_HIR_ID; . return None; . } . 32,276 ( 0.00%) self.current_id = parent_id; 129,104 ( 0.00%) if let Some(node) = self.map.find(parent_id) { 64,552 ( 0.00%) return Some((parent_id, node)); . } . // If this `HirId` doesn't have an entry, skip it and look for its `parent_id`. . } 145,242 ( 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>); . 1,213,335 ( 0.00%) fn next(&mut self) -> Option { 404,445 ( 0.00%) if self.current_id.local_id.index() != 0 { 64,473 ( 0.00%) self.current_id.local_id = ItemLocalId::new(0); 257,892 ( 0.00%) if let Some(node) = self.map.tcx.hir_owner(self.current_id.owner) { . return Some((self.current_id.owner, node.node)); . } . } 70,342 ( 0.00%) if self.current_id == CRATE_HIR_ID { 5,068 ( 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 . }); 135,616 ( 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`. 135,616 ( 0.00%) if let Some(node) = self.map.tcx.hir_owner(self.current_id.owner) { . return Some((self.current_id.owner, node.node)); . } . } 1,078,520 ( 0.00%) } . } . . impl<'hir> Map<'hir> { 210 ( 0.00%) pub fn krate(&self) -> &'hir Crate<'hir> { 30 ( 0.00%) self.tcx.hir_crate(()) 240 ( 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,960,032 ( 0.01%) pub fn local_def_id(&self, hir_id: HirId) -> LocalDefId { 314,466 ( 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) . ) . }) 1,470,024 ( 0.00%) } . . #[inline] 838,576 ( 0.00%) pub fn opt_local_def_id(&self, hir_id: HirId) -> Option { 293,745 ( 0.00%) if hir_id.local_id == ItemLocalId::new(0) { . Some(hir_id.owner) . } else { 120,302 ( 0.00%) self.tcx . .hir_owner_nodes(hir_id.owner)? . .local_id_to_def_id . .get(&hir_id.local_id) . .copied() . } 943,398 ( 0.00%) } . . #[inline] 1,428 ( 0.00%) pub fn local_def_id_to_hir_id(&self, def_id: LocalDefId) -> HirId { . // FIXME(#85914) is this access safe for incr. comp.? 65,128 ( 0.00%) self.tcx.untracked_resolutions.definitions.local_def_id_to_hir_id(def_id) 2,856 ( 0.00%) } . 7 ( 0.00%) pub fn iter_local_def_id(&self) -> impl Iterator + '_ { . // Create a dependency to the crate to be sure we reexcute this when the amount of . // definitions change. 1 ( 0.00%) self.tcx.ensure().hir_crate(()); . self.tcx.untracked_resolutions.definitions.iter_local_def_id() 9 ( 0.00%) } . 164,934 ( 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); 306,306 ( 0.00%) let def_kind = match self.find(hir_id)? { 30,336 ( 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, . }, 22 ( 0.00%) Node::TraitItem(item) => match item.kind { . TraitItemKind::Const(..) => DefKind::AssocConst, . TraitItemKind::Fn(..) => DefKind::AssocFn, . TraitItemKind::Type(..) => DefKind::AssocTy, . }, 6,595 ( 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`? 7,045 ( 0.00%) assert_ne!(variant_data.ctor_hir_id(), None); . 9,257 ( 0.00%) let ctor_of = match self.find(self.get_parent_node(hir_id)) { . Some(Node::Item(..)) => def::CtorOf::Struct, . Some(Node::Variant(..)) => def::CtorOf::Variant, . _ => unreachable!(), . }; 2,818 ( 0.00%) DefKind::Ctor(ctor_of, def::CtorKind::from_hir(variant_data)) 5,636 ( 0.00%) } . Node::AnonConst(_) => { 18 ( 0.00%) let inline = match self.find(self.get_parent_node(hir_id)) { . Some(Node::Expr(&Expr { . kind: ExprKind::ConstBlock(ref anon_const), .. . })) if anon_const.hir_id == hir_id => true, . _ => false, . }; . if inline { DefKind::InlineConst } else { DefKind::AnonConst } . } . Node::Field(_) => DefKind::Field, 145 ( 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)), . }, 14,745 ( 0.00%) Node::GenericParam(param) => match param.kind { . GenericParamKind::Lifetime { .. } => DefKind::LifetimeParam, . GenericParamKind::Type { .. } => DefKind::TyParam, . GenericParamKind::Const { .. } => DefKind::ConstParam, . }, . Node::Crate(_) => DefKind::Mod, . Node::Stmt(_) . | Node::PathSegment(_) . | Node::Ty(_) -- line 300 ---------------------------------------- -- line 304 ---------------------------------------- . | Node::Binding(_) . | Node::Local(_) . | Node::Param(_) . | Node::Arm(_) . | Node::Lifetime(_) . | Node::Visibility(_) . | Node::Block(_) => return None, . }; 92,836 ( 0.00%) Some(def_kind) 235,620 ( 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)) . } . 13,469,792 ( 0.04%) pub fn find_parent_node(&self, id: HirId) -> Option { 1,683,724 ( 0.00%) if id.local_id == ItemLocalId::from_u32(0) { . Some(self.tcx.hir_owner_parent(id.owner)) . } else { 3,281,216 ( 0.01%) let owner = self.tcx.hir_owner_nodes(id.owner)?; 1,640,608 ( 0.00%) let node = owner.nodes[id.local_id].as_ref()?; 4,921,824 ( 0.01%) let hir_id = HirId { owner: id.owner, local_id: node.parent }; . Some(hir_id) . } 13,469,792 ( 0.04%) } . 70,516 ( 0.00%) pub fn get_parent_node(&self, hir_id: HirId) -> HirId { 8,953,257 ( 0.03%) self.find_parent_node(hir_id).unwrap() 141,032 ( 0.00%) } . . /// Retrieves the `Node` corresponding to `id`, returning `None` if cannot be found. 7,367,960 ( 0.02%) pub fn find(&self, id: HirId) -> Option> { 920,995 ( 0.00%) if id.local_id == ItemLocalId::from_u32(0) { . let owner = self.tcx.hir_owner(id.owner)?; 621,215 ( 0.00%) Some(owner.node.into()) . } else { 598,850 ( 0.00%) let owner = self.tcx.hir_owner_nodes(id.owner)?; 299,425 ( 0.00%) let node = owner.nodes[id.local_id].as_ref()?; 898,275 ( 0.00%) Some(node.node) . } 7,367,960 ( 0.02%) } . . /// Retrieves the `Node` corresponding to `id`, returning `None` if cannot be found. . #[inline] . pub fn find_by_def_id(&self, id: LocalDefId) -> Option> { 154,118 ( 0.00%) self.find(self.local_def_id_to_hir_id(id)) . } . . /// Retrieves the `Node` corresponding to `id`, panicking if it cannot be found. 685,167 ( 0.00%) pub fn get(&self, id: HirId) -> Node<'hir> { 370,610 ( 0.00%) self.find(id).unwrap_or_else(|| bug!("couldn't find hir id {} in the HIR map", id)) 456,778 ( 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,694 ( 0.00%) pub fn get_if_local(&self, id: DefId) -> Option> { 10,347 ( 0.00%) id.as_local().and_then(|id| self.find(self.local_def_id_to_hir_id(id))) 20,694 ( 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, . } . } . 1,406,468 ( 0.00%) pub fn item(&self, id: ItemId) -> &'hir Item<'hir> { 401,848 ( 0.00%) self.tcx.hir_owner(id.def_id).unwrap().node.expect_item() 1,607,392 ( 0.00%) } . 2,037 ( 0.00%) pub fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> { 582 ( 0.00%) self.tcx.hir_owner(id.def_id).unwrap().node.expect_trait_item() 2,328 ( 0.00%) } . 1,306,781 ( 0.00%) pub fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> { 373,366 ( 0.00%) self.tcx.hir_owner(id.def_id).unwrap().node.expect_impl_item() 1,493,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() . } . 1,594,397 ( 0.00%) pub fn body(&self, id: BodyId) -> &'hir Body<'hir> { 455,542 ( 0.00%) self.tcx.hir_owner_nodes(id.hir_id.owner).unwrap().bodies[&id.hir_id.local_id] 1,822,168 ( 0.01%) } . 46,833 ( 0.00%) pub fn fn_decl_by_hir_id(&self, hir_id: HirId) -> Option<&'hir FnDecl<'hir>> { 46,833 ( 0.00%) if let Some(node) = self.find(hir_id) { . fn_decl(node) . } else { . bug!("no node for hir_id `{}`", hir_id) . } 31,222 ( 0.00%) } . 3,309 ( 0.00%) pub fn fn_sig_by_hir_id(&self, hir_id: HirId) -> Option<&'hir FnSig<'hir>> { 3,309 ( 0.00%) if let Some(node) = self.find(hir_id) { . fn_sig(node) . } else { . bug!("no node for hir_id `{}`", hir_id) . } 3,309 ( 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,080,744 ( 0.00%) pub fn body_owner(&self, BodyId { hir_id }: BodyId) -> HirId { . let parent = self.get_parent_node(hir_id); 810,558 ( 0.00%) assert!(self.find(parent).map_or(false, |n| is_body_owner(n, hir_id))); . parent 1,080,744 ( 0.00%) } . 339,625 ( 0.00%) pub fn body_owner_def_id(&self, id: BodyId) -> LocalDefId { 524,110 ( 0.00%) self.local_def_id(self.body_owner(id)) 339,625 ( 0.00%) } . . /// Given a `HirId`, returns the `BodyId` associated with it, . /// if the node is a body owner, otherwise returns `None`. 59,417 ( 0.00%) pub fn maybe_body_owned_by(&self, hir_id: HirId) -> Option { 191,878 ( 0.00%) self.find(hir_id).map(associated_body).flatten() 178,251 ( 0.00%) } . . /// Given a body owner's id, returns the `BodyId` associated with it. 122,643 ( 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) . ); . }) 95,389 ( 0.00%) } . 5,699 ( 0.00%) pub fn body_param_names(&self, id: BodyId) -> impl Iterator + 'hir { 56,517 ( 0.00%) self.body(id).params.iter().map(|arg| match arg.pat.kind { 19,704 ( 0.00%) PatKind::Binding(_, _, ident, _) => ident, . _ => Ident::empty(), . }) 17,097 ( 0.00%) } . . /// Returns the `BodyOwnerKind` of this `LocalDefId`. . /// . /// Panics if `LocalDefId` does not have an associated body. 210,891 ( 0.00%) pub fn body_owner_kind(&self, id: HirId) -> BodyOwnerKind { 556,481 ( 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), . } 210,891 ( 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. 235,632 ( 0.00%) pub fn body_const_context(&self, did: LocalDefId) -> Option { . let hir_id = self.local_def_id_to_hir_id(did); 353,448 ( 0.00%) let ccx = match self.body_owner_kind(hir_id) { . BodyOwnerKind::Const => ConstContext::Const, . BodyOwnerKind::Static(mt) => ConstContext::Static(mt), . 22,834 ( 0.00%) BodyOwnerKind::Fn if self.tcx.is_constructor(did.to_def_id()) => return None, 22,834 ( 0.00%) BodyOwnerKind::Fn if self.tcx.is_const_fn_raw(did.to_def_id()) => ConstContext::ConstFn, . BodyOwnerKind::Fn 45,440 ( 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) 265,086 ( 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)| { 70,686 ( 0.00%) let bodies = &owner_info.as_ref()?.nodes.bodies; . Some(bodies.iter().map(move |&(local_id, _)| { 31 ( 0.00%) let hir_id = HirId { owner, local_id }; . let body_id = BodyId { hir_id }; 68,027 ( 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); 141,372 ( 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 }; 61,308 ( 0.00%) f(self.body_owner_def_id(body_id)) . }) . } . }); 8 ( 0.00%) } . 25,260 ( 0.00%) pub fn ty_param_owner(&self, id: HirId) -> LocalDefId { 5,052 ( 0.00%) 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)), . } 17,682 ( 0.00%) } . 78,840 ( 0.00%) pub fn ty_param_name(&self, id: HirId) -> Symbol { 15,768 ( 0.00%) match self.get(id) { . Node::Item(&Item { kind: ItemKind::Trait(..) | ItemKind::TraitAlias(..), .. }) => { . kw::SelfUpper . } 15,768 ( 0.00%) Node::GenericParam(param) => param.name.ident().name, . _ => bug!("ty_param_name: {} not a type parameter", self.node_to_string(id)), . } 47,304 ( 0.00%) } . 999 ( 0.00%) pub fn trait_impls(&self, trait_did: DefId) -> &'hir [LocalDefId] { 111 ( 0.00%) self.tcx.all_local_trait_impls(()).get(&trait_did).map_or(&[], |xs| &xs[..]) 999 ( 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] { 20 ( 0.00%) self.attrs(CRATE_HIR_ID) . } . 665 ( 0.00%) pub fn get_module(&self, module: LocalDefId) -> (&'hir Mod<'hir>, Span, HirId) { . let hir_id = HirId::make_owner(module); 475 ( 0.00%) match self.tcx.hir_owner(module).map(|o| o.node) { 168 ( 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), . } 855 ( 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() { 94,248 ( 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 { 58,150 ( 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>, . { 20 ( 0.00%) let krate = self.krate(); 70 ( 0.00%) for owner in krate.owners.iter().filter_map(Option::as_ref) { 468,303 ( 0.00%) match owner.node() { 326,112 ( 0.00%) OwnerNode::Item(item) => visitor.visit_item(item), . OwnerNode::ForeignItem(item) => visitor.visit_foreign_item(item), 19,785 ( 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) { 7,584 ( 0.00%) Some(OwnerNode::Item(item)) => visitor.visit_item(item), . Some(OwnerNode::ForeignItem(item)) => visitor.visit_foreign_item(item), 6,595 ( 0.00%) Some(OwnerNode::ImplItem(item)) => visitor.visit_impl_item(item), 11 ( 0.00%) Some(OwnerNode::TraitItem(item)) => visitor.visit_trait_item(item), . Some(OwnerNode::Crate(_)) | None => {} . }) . } . 2,494 ( 0.00%) pub fn visit_item_likes_in_module(&self, module: LocalDefId, visitor: &mut V) . where . V: ItemLikeVisitor<'hir>, . { 319 ( 0.00%) let module = self.tcx.hir_module_items(module); . 348 ( 0.00%) for id in module.items.iter() { 341,280 ( 0.00%) visitor.visit_item(self.item(*id)); . } . 348 ( 0.00%) for id in module.trait_items.iter() { 440 ( 0.00%) visitor.visit_trait_item(self.trait_item(*id)); . } . 348 ( 0.00%) for id in module.impl_items.iter() { 257,205 ( 0.00%) visitor.visit_impl_item(self.impl_item(*id)); . } . 348 ( 0.00%) for id in module.foreign_items.iter() { . visitor.visit_foreign_item(self.foreign_item(*id)); . } 2,552 ( 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); . 232 ( 0.00%) while let Some(id) = queue.pop_front() { . f(id); 87 ( 0.00%) let items = self.tcx.hir_module_items(id); 928 ( 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`. 16,117 ( 0.00%) pub fn parent_iter(self, current_id: HirId) -> ParentHirIterator<'hir> { . ParentHirIterator { current_id, map: self } 64,468 ( 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 } 352,852 ( 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. 105,206 ( 0.00%) pub fn get_parent_item(&self, hir_id: HirId) -> LocalDefId { 969,876 ( 0.00%) if let Some((def_id, _node)) = self.parent_owner_iter(hir_id).next() { . def_id . } else { . CRATE_DEF_ID . } 210,412 ( 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 { 177,056 ( 0.00%) for (def_id, node) in self.parent_owner_iter(hir_id) { 85,988 ( 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)) . ) . } . 397,880 ( 0.00%) pub fn expect_item(&self, id: LocalDefId) -> &'hir Item<'hir> { 170,520 ( 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))), . } 454,720 ( 0.00%) } . 92,330 ( 0.00%) pub fn expect_impl_item(&self, id: LocalDefId) -> &'hir ImplItem<'hir> { 39,570 ( 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))), . } 105,520 ( 0.00%) } . 154 ( 0.00%) pub fn expect_trait_item(&self, id: LocalDefId) -> &'hir TraitItem<'hir> { 66 ( 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))), . } 176 ( 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)), . } . } . 279,954 ( 0.00%) pub fn opt_name(&self, id: HirId) -> Option { 93,322 ( 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, 93,312 ( 0.00%) 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, . }) 155,530 ( 0.00%) } . 248,840 ( 0.00%) pub fn name(&self, id: HirId) -> Symbol { 93,320 ( 0.00%) match self.opt_name(id) { . Some(name) => name, . None => bug!("no name for {}", self.node_to_string(id)), . } 186,630 ( 0.00%) } . . /// Given a node ID, gets a list of attributes associated with the AST . /// corresponding to the node-ID. 17,652,936 ( 0.05%) pub fn attrs(&self, id: HirId) -> &'hir [ast::Attribute] { 2,521,848 ( 0.01%) self.tcx.hir_attrs(id.owner).get(id.local_id) 20,174,784 ( 0.06%) } . . /// Gets the span of the definition of the specified HIR node. . /// This is used by `tcx.get_span` 61,686 ( 0.00%) pub fn span(&self, hir_id: HirId) -> Span { 465,030 ( 0.00%) self.opt_span(hir_id) . .unwrap_or_else(|| bug!("hir::map::Map::span: id not in map: {:?}", hir_id)) 61,686 ( 0.00%) } . 1,086,582 ( 0.00%) pub fn opt_span(&self, hir_id: HirId) -> Option { 1,086,582 ( 0.00%) let span = match self.find(hir_id)? { . Node::Param(param) => param.span, 20,474 ( 0.00%) Node::Item(item) => match &item.kind { . ItemKind::Fn(sig, _, _) => sig.span, 20,450 ( 0.00%) _ => item.span, . }, . Node::ForeignItem(foreign_item) => foreign_item.span, 312 ( 0.00%) Node::TraitItem(trait_item) => match &trait_item.kind { 30 ( 0.00%) TraitItemKind::Fn(sig, _) => sig.span, 282 ( 0.00%) _ => trait_item.span, . }, 48,578 ( 0.00%) Node::ImplItem(impl_item) => match &impl_item.kind { 45,544 ( 0.00%) ImplItemKind::Fn(sig, _) => sig.span, 3,034 ( 0.00%) _ => impl_item.span, . }, 2,232 ( 0.00%) Node::Variant(variant) => variant.span, 3,092 ( 0.00%) Node::Field(field) => field.span, 105 ( 0.00%) Node::AnonConst(constant) => self.body(constant.body).value.span, . Node::Expr(expr) => expr.span, . Node::Stmt(stmt) => stmt.span, . Node::PathSegment(seg) => seg.ident.span, . Node::Ty(ty) => ty.span, . Node::TraitRef(tr) => tr.path.span, . Node::Binding(pat) => pat.span, . Node::Pat(pat) => pat.span, . Node::Arm(arm) => arm.span, . Node::Block(block) => block.span, 10,687 ( 0.00%) Node::Ctor(..) => match self.find(self.get_parent_node(hir_id))? { . Node::Item(item) => item.span, . Node::Variant(variant) => variant.span, . _ => unreachable!(), . }, . Node::Lifetime(lifetime) => lifetime.span, . Node::GenericParam(param) => param.span, . Node::Visibility(&Spanned { . node: VisibilityKind::Restricted { ref path, .. }, . .. . }) => path.span, . Node::Infer(i) => i.span, . Node::Visibility(v) => bug!("unexpected Visibility {:?}", v), . Node::Local(local) => local.span, 4 ( 0.00%) Node::Crate(item) => item.inner, . }; . Some(span) 1,552,260 ( 0.00%) } . . /// Like `hir.span()`, but includes the body of function items . /// (instead of just the function header) . pub fn span_with_body(&self, hir_id: HirId) -> Span { . match self.find(hir_id) { . Some(Node::TraitItem(item)) => item.span, . Some(Node::ImplItem(impl_item)) => impl_item.span, . Some(Node::Item(item)) => item.span, . Some(_) => self.span(hir_id), . _ => bug!("hir::map::Map::span_with_body: id not in map: {:?}", hir_id), . } . } . 13,098 ( 0.00%) pub fn span_if_local(&self, id: DefId) -> Option { 46,755 ( 0.00%) id.as_local().and_then(|id| self.opt_span(self.local_def_id_to_hir_id(id))) 19,647 ( 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> { 141,854 ( 0.00%) self.body(id) . } . . fn item(&self, id: ItemId) -> &'hir Item<'hir> { 90,732 ( 0.00%) self.item(id) . } . . fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> { 159 ( 0.00%) self.trait_item(id) . } . . fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> { 92,330 ( 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) 119 ( 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| { 170 ( 0.00%) let stable_crate_id = tcx.resolutions(()).cstore.stable_crate_id(cnum); 34 ( 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), . } . } . 261 ( 0.00%) pub(super) fn hir_module_items(tcx: TyCtxt<'_>, module_id: LocalDefId) -> ModuleItems { 174 ( 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(), . }; . 145 ( 0.00%) let (hir_mod, span, hir_id) = tcx.hir().get_module(module_id); . collector.visit_mod(hir_mod, span, hir_id); . 464 ( 0.00%) let ModuleCollector { submodules, items, trait_items, impl_items, foreign_items, .. } = . collector; 319 ( 0.00%) return ModuleItems { 116 ( 0.00%) submodules: submodules.into_boxed_slice(), 116 ( 0.00%) items: items.into_boxed_slice(), 116 ( 0.00%) trait_items: trait_items.into_boxed_slice(), 116 ( 0.00%) impl_items: impl_items.into_boxed_slice(), 116 ( 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 { 20,973 ( 0.00%) self.tcx.hir() . } . 37,920 ( 0.00%) fn visit_item(&mut self, item: &'hir Item<'hir>) { 22,752 ( 0.00%) self.items.push(item.item_id()); 15,168 ( 0.00%) if let ItemKind::Mod(..) = item.kind { . // If this declares another module, do not recurse inside it. 28 ( 0.00%) self.submodules.push(item.def_id); . } else { 45,336 ( 0.00%) intravisit::walk_item(self, item) . } 112 ( 0.00%) } . . fn visit_trait_item(&mut self, item: &'hir TraitItem<'hir>) { 33 ( 0.00%) self.trait_items.push(item.trait_item_id()); 33 ( 0.00%) intravisit::walk_trait_item(self, item) . } . . fn visit_impl_item(&mut self, item: &'hir ImplItem<'hir>) { 19,785 ( 0.00%) self.impl_items.push(item.impl_item_id()); 19,785 ( 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) . } . } 232 ( 0.00%) } 8,204,884 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cmp.rs -------------------------------------------------------------------------------- Ir -- line 222 ---------------------------------------- . #[stable(feature = "rust1", since = "1.0.0")] . fn eq(&self, other: &Rhs) -> bool; . . /// This method tests for `!=`. . #[inline] . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[default_method_body_is_const] 160,902 ( 0.00%) fn ne(&self, other: &Rhs) -> bool { 631,476 ( 0.00%) !self.eq(other) 214,536 ( 0.00%) } . } . . /// Derive macro generating an impl of the trait `PartialEq`. . #[rustc_builtin_macro] . #[stable(feature = "builtin_macro_prelude", since = "1.38.0")] . #[allow_internal_unstable(core_intrinsics, structural_match)] . pub macro PartialEq($item:item) { . /* compiler built-in */ -- line 240 ---------------------------------------- -- line 328 ---------------------------------------- . /// assert_eq!(Ordering::Less, result); . /// . /// let result = 1.cmp(&1); . /// assert_eq!(Ordering::Equal, result); . /// . /// let result = 2.cmp(&1); . /// assert_eq!(Ordering::Greater, result); . /// ``` 76,676 ( 0.00%) #[derive(Clone, Copy, PartialEq, Debug, Hash)] . #[stable(feature = "rust1", since = "1.0.0")] . #[repr(i8)] . pub enum Ordering { . /// An ordering where a compared value is less than another. . #[stable(feature = "rust1", since = "1.0.0")] . Less = -1, . /// An ordering where a compared value is equal to another. . #[stable(feature = "rust1", since = "1.0.0")] -- line 344 ---------------------------------------- -- line 569 ---------------------------------------- . /// let result = x.0.cmp(&y.0).then_with(|| x.1.cmp(&y.1)).then_with(|| x.2.cmp(&y.2)); . /// . /// assert_eq!(result, Ordering::Less); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "ordering_chaining", since = "1.17.0")] . pub fn then_with Ordering>(self, f: F) -> Ordering { 81,345 ( 0.00%) match self { . Equal => f(), . _ => self, . } . } . } . . /// A helper struct for reverse ordering. . /// -- line 585 ---------------------------------------- -- line 788 ---------------------------------------- . /// . /// ``` . /// assert_eq!(2, 1.max(2)); . /// assert_eq!(2, 2.max(2)); . /// ``` . #[stable(feature = "ord_max_min", since = "1.21.0")] . #[inline] . #[must_use] 1,437,255 ( 0.00%) fn max(self, other: Self) -> Self . where . Self: Sized, . { 2,775,348 ( 0.01%) max_by(self, other, Ord::cmp) 958,170 ( 0.00%) } . . /// Compares and returns the minimum of two values. . /// . /// Returns the first argument if the comparison determines them to be equal. . /// . /// # Examples . /// . /// ``` . /// assert_eq!(1, 1.min(2)); . /// assert_eq!(2, 2.min(2)); . /// ``` . #[stable(feature = "ord_max_min", since = "1.21.0")] . #[inline] . #[must_use] 1,020 ( 0.00%) fn min(self, other: Self) -> Self . where . Self: Sized, . { 239,524 ( 0.00%) min_by(self, other, Ord::cmp) 680 ( 0.00%) } . . /// Restrict a value to a certain interval. . /// . /// Returns `max` if `self` is greater than `max`, and `min` if `self` is . /// less than `min`. Otherwise this returns `self`. . /// . /// # Panics . /// -- line 829 ---------------------------------------- -- line 1097 ---------------------------------------- . /// let result = 2.0 < 1.0; . /// assert_eq!(result, false); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[default_method_body_is_const] . fn lt(&self, other: &Rhs) -> bool { 657,026 ( 0.00%) matches!(self.partial_cmp(other), Some(Less)) . } . . /// This method tests less than or equal to (for `self` and `other`) and is used by the `<=` . /// operator. . /// . /// # Examples . /// . /// ``` -- line 1113 ---------------------------------------- -- line 1121 ---------------------------------------- . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[default_method_body_is_const] . fn le(&self, other: &Rhs) -> bool { . // Pattern `Some(Less | Eq)` optimizes worse than negating `None | Some(Greater)`. . // FIXME: The root cause was fixed upstream in LLVM with: . // https://github.com/llvm/llvm-project/commit/9bad7de9a3fb844f1ca2965f35d0c2a3d1e11775 . // Revert this workaround once support for LLVM 12 gets dropped. 7,734,309 ( 0.02%) !matches!(self.partial_cmp(other), None | Some(Greater)) . } . . /// This method tests greater than (for `self` and `other`) and is used by the `>` operator. . /// . /// # Examples . /// . /// ``` . /// let result = 1.0 > 2.0; -- line 1137 ---------------------------------------- -- line 1140 ---------------------------------------- . /// let result = 2.0 > 2.0; . /// assert_eq!(result, false); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[default_method_body_is_const] . fn gt(&self, other: &Rhs) -> bool { 12,971,158 ( 0.04%) matches!(self.partial_cmp(other), Some(Greater)) . } . . /// This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` . /// operator. . /// . /// # Examples . /// . /// ``` -- line 1156 ---------------------------------------- -- line 1159 ---------------------------------------- . /// . /// let result = 2.0 >= 2.0; . /// assert_eq!(result, true); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[default_method_body_is_const] 6 ( 0.00%) fn ge(&self, other: &Rhs) -> bool { 5,845 ( 0.00%) matches!(self.partial_cmp(other), Some(Greater | Equal)) 10 ( 0.00%) } . } . . /// Derive macro generating an impl of the trait `PartialOrd`. . #[rustc_builtin_macro] . #[stable(feature = "builtin_macro_prelude", since = "1.38.0")] . #[allow_internal_unstable(core_intrinsics)] . pub macro PartialOrd($item:item) { . /* compiler built-in */ -- line 1177 ---------------------------------------- -- line 1190 ---------------------------------------- . /// . /// assert_eq!(1, cmp::min(1, 2)); . /// assert_eq!(2, cmp::min(2, 2)); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[cfg_attr(not(test), rustc_diagnostic_item = "cmp_min")] 888 ( 0.00%) pub fn min(v1: T, v2: T) -> T { 592 ( 0.00%) v1.min(v2) 592 ( 0.00%) } . . /// Returns the minimum of two values with respect to the specified comparison function. . /// . /// Returns the first argument if the comparison determines them to be equal. . /// . /// # Examples . /// . /// ``` -- line 1208 ---------------------------------------- -- line 1209 ---------------------------------------- . /// use std::cmp; . /// . /// assert_eq!(cmp::min_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 1); . /// assert_eq!(cmp::min_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "cmp_min_max_by", since = "1.53.0")] 1,020 ( 0.00%) pub fn min_by Ordering>(v1: T, v2: T, compare: F) -> T { 8,569,939 ( 0.02%) match compare(&v1, &v2) { 1,360 ( 0.00%) Ordering::Less | Ordering::Equal => v1, . Ordering::Greater => v2, . } 3,198 ( 0.00%) } . . /// Returns the element that gives the minimum value from the specified function. . /// . /// Returns the first argument if the comparison determines them to be equal. . /// . /// # Examples . /// . /// ``` -- line 1230 ---------------------------------------- -- line 1231 ---------------------------------------- . /// use std::cmp; . /// . /// assert_eq!(cmp::min_by_key(-2, 1, |x: &i32| x.abs()), 1); . /// assert_eq!(cmp::min_by_key(-2, 2, |x: &i32| x.abs()), -2); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "cmp_min_max_by", since = "1.53.0")] 828 ( 0.00%) pub fn min_by_key K, K: Ord>(v1: T, v2: T, mut f: F) -> T { 552 ( 0.00%) min_by(v1, v2, |v1, v2| f(v1).cmp(&f(v2))) 552 ( 0.00%) } . . /// Compares and returns the maximum of two values. . /// . /// Returns the second argument if the comparison determines them to be equal. . /// . /// Internally uses an alias to [`Ord::max`]. . /// . /// # Examples -- line 1249 ---------------------------------------- -- line 1253 ---------------------------------------- . /// . /// assert_eq!(2, cmp::max(1, 2)); . /// assert_eq!(2, cmp::max(2, 2)); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[cfg_attr(not(test), rustc_diagnostic_item = "cmp_max")] 1,437,165 ( 0.00%) pub fn max(v1: T, v2: T) -> T { 958,110 ( 0.00%) v1.max(v2) 958,110 ( 0.00%) } . . /// Returns the maximum of two values with respect to the specified comparison function. . /// . /// Returns the second argument if the comparison determines them to be equal. . /// . /// # Examples . /// . /// ``` -- line 1271 ---------------------------------------- -- line 1272 ---------------------------------------- . /// use std::cmp; . /// . /// assert_eq!(cmp::max_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2); . /// assert_eq!(cmp::max_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 2); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "cmp_min_max_by", since = "1.53.0")] 1,437,255 ( 0.00%) pub fn max_by Ordering>(v1: T, v2: T, compare: F) -> T { 16,935,572 ( 0.05%) match compare(&v1, &v2) { 1,135,156 ( 0.00%) Ordering::Less | Ordering::Equal => v2, 672,618 ( 0.00%) Ordering::Greater => v1, . } 4,056,886 ( 0.01%) } . . /// Returns the element that gives the maximum value from the specified function. . /// . /// Returns the second argument if the comparison determines them to be equal. . /// . /// # Examples . /// . /// ``` -- line 1293 ---------------------------------------- -- line 1308 ---------------------------------------- . use crate::cmp::Ordering::{self, Equal, Greater, Less}; . use crate::hint::unreachable_unchecked; . . macro_rules! partial_eq_impl { . ($($t:ty)*) => ($( . #[stable(feature = "rust1", since = "1.0.0")] . impl PartialEq for $t { . #[inline] 505,862 ( 0.00%) fn eq(&self, other: &$t) -> bool { (*self) == (*other) } . #[inline] 105,641 ( 0.00%) fn ne(&self, other: &$t) -> bool { (*self) != (*other) } . } . )*) . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl PartialEq for () { . #[inline] . fn eq(&self, _other: &()) -> bool { -- line 1326 ---------------------------------------- -- line 1392 ---------------------------------------- . ($($t:ty)*) => ($( . #[stable(feature = "rust1", since = "1.0.0")] . impl PartialOrd for $t { . #[inline] . fn partial_cmp(&self, other: &$t) -> Option { . Some(self.cmp(other)) . } . #[inline] 48,823,489 ( 0.14%) fn lt(&self, other: &$t) -> bool { (*self) < (*other) } . #[inline] 1,066,754 ( 0.00%) fn le(&self, other: &$t) -> bool { (*self) <= (*other) } . #[inline] . fn ge(&self, other: &$t) -> bool { (*self) >= (*other) } . #[inline] . fn gt(&self, other: &$t) -> bool { (*self) > (*other) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Ord for $t { . #[inline] 2,397,135 ( 0.01%) fn cmp(&self, other: &$t) -> Ordering { . // The order here is important to generate more optimal assembly. . // See for more info. 185,081,754 ( 0.53%) if *self < *other { Less } 1,134,588 ( 0.00%) else if *self == *other { Equal } 224,208 ( 0.00%) else { Greater } 1,438,281 ( 0.00%) } . } . )*) . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Ord for () { . #[inline] . fn cmp(&self, _other: &()) -> Ordering { -- line 1426 ---------------------------------------- -- line 1430 ---------------------------------------- . . #[stable(feature = "rust1", since = "1.0.0")] . impl Ord for bool { . #[inline] . fn cmp(&self, other: &bool) -> Ordering { . // Casting to i8's and converting the difference to an Ordering generates . // more optimal assembly. . // See for more info. 159,155 ( 0.00%) match (*self as i8) - (*other as i8) { . -1 => Less, . 0 => Equal, . 1 => Greater, . // SAFETY: bool as i8 returns 0 or 1, so the difference can't be anything else . _ => unsafe { unreachable_unchecked() }, . } . } . } -- line 1446 ---------------------------------------- -- line 1474 ---------------------------------------- . // & pointers . . #[stable(feature = "rust1", since = "1.0.0")] . impl PartialEq<&B> for &A . where . A: PartialEq, . { . #[inline] 6,149,754 ( 0.02%) fn eq(&self, other: &&B) -> bool { 17,257,452 ( 0.05%) PartialEq::eq(*self, *other) 6,034,071 ( 0.02%) } . #[inline] 3,455 ( 0.00%) fn ne(&self, other: &&B) -> bool { 102 ( 0.00%) PartialEq::ne(*self, *other) 613,753 ( 0.00%) } . } . #[stable(feature = "rust1", since = "1.0.0")] . impl PartialOrd<&B> for &A . where . A: PartialOrd, . { . #[inline] . fn partial_cmp(&self, other: &&B) -> Option { -- line 1496 ---------------------------------------- -- line 1516 ---------------------------------------- . #[stable(feature = "rust1", since = "1.0.0")] . impl Ord for &A . where . A: Ord, . { . #[inline] . fn cmp(&self, other: &Self) -> Ordering { . Ord::cmp(*self, *other) 87,576 ( 0.00%) } . } . #[stable(feature = "rust1", since = "1.0.0")] . impl Eq for &A where A: Eq {} . . // &mut pointers . . #[stable(feature = "rust1", since = "1.0.0")] . impl PartialEq<&mut B> for &mut A -- line 1532 ---------------------------------------- 43,248,376 ( 0.12%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_dataflow/src/drop_flag_effects.rs -------------------------------------------------------------------------------- Ir -- line 48 ---------------------------------------- . // . // FIXME: we have to do something for moving slice patterns. . fn place_contents_drop_state_cannot_differ<'tcx>( . tcx: TyCtxt<'tcx>, . body: &Body<'tcx>, . place: mir::Place<'tcx>, . ) -> bool { . let ty = place.ty(body, tcx).ty; 7,762,622 ( 0.02%) match ty.kind() { . ty::Array(..) => { . debug!( . "place_contents_drop_state_cannot_differ place: {:?} ty: {:?} => false", . place, ty . ); . false . } . ty::Slice(..) | ty::Ref(..) | ty::RawPtr(..) => { . debug!( . "place_contents_drop_state_cannot_differ place: {:?} ty: {:?} refd => true", . place, ty . ); . true . } 5,616,621 ( 0.02%) ty::Adt(def, _) if (def.has_dtor(tcx) && !def.is_box()) || def.is_union() => { . debug!( . "place_contents_drop_state_cannot_differ place: {:?} ty: {:?} Drop => true", . place, ty . ); . true . } . _ => false, . } -- line 79 ---------------------------------------- -- line 83 ---------------------------------------- . tcx: TyCtxt<'tcx>, . body: &Body<'tcx>, . move_data: &MoveData<'tcx>, . lookup_result: LookupResult, . each_child: F, . ) where . F: FnMut(MovePathIndex), . { 103,892 ( 0.00%) match lookup_result { . LookupResult::Parent(..) => { . // access to untracked value - do not touch children . } . LookupResult::Exact(e) => on_all_children_bits(tcx, body, move_data, e, each_child), . } . } . . pub fn on_all_children_bits<'tcx, F>( -- line 99 ---------------------------------------- -- line 100 ---------------------------------------- . tcx: TyCtxt<'tcx>, . body: &Body<'tcx>, . move_data: &MoveData<'tcx>, . move_path_index: MovePathIndex, . mut each_child: F, . ) where . F: FnMut(MovePathIndex), . { 11,155,872 ( 0.03%) fn is_terminal_path<'tcx>( . tcx: TyCtxt<'tcx>, . body: &Body<'tcx>, . move_data: &MoveData<'tcx>, . path: MovePathIndex, . ) -> bool { 2,788,968 ( 0.01%) place_contents_drop_state_cannot_differ(tcx, body, move_data.move_paths[path].place) 11,155,872 ( 0.03%) } . 13,304,463 ( 0.04%) fn on_all_children_bits<'tcx, F>( . tcx: TyCtxt<'tcx>, . body: &Body<'tcx>, . move_data: &MoveData<'tcx>, . move_path_index: MovePathIndex, . each_child: &mut F, . ) where . F: FnMut(MovePathIndex), . { 327,514 ( 0.00%) each_child(move_path_index); . 9,761,392 ( 0.03%) if is_terminal_path(tcx, body, move_data, move_path_index) { . return; . } . 1,077,900 ( 0.00%) let mut next_child_index = move_data.move_paths[move_path_index].first_child; 3,410,724 ( 0.01%) while let Some(child_index) = next_child_index { 1,796,718 ( 0.01%) on_all_children_bits(tcx, body, move_data, child_index, each_child); 299,453 ( 0.00%) next_child_index = move_data.move_paths[child_index].next_sibling; . } 11,149,918 ( 0.03%) } 6,759,344 ( 0.02%) on_all_children_bits(tcx, body, move_data, move_path_index, &mut each_child); . } . . pub fn on_all_drop_children_bits<'tcx, F>( . tcx: TyCtxt<'tcx>, . body: &Body<'tcx>, . ctxt: &MoveDataParamEnv<'tcx>, . path: MovePathIndex, . mut each_child: F, . ) where . F: FnMut(MovePathIndex), . { 68 ( 0.00%) on_all_children_bits(tcx, body, &ctxt.move_data, path, |child| { 32 ( 0.00%) let place = &ctxt.move_data.move_paths[path].place; 8 ( 0.00%) let ty = place.ty(body, tcx).ty; . debug!("on_all_drop_children_bits({:?}, {:?} : {:?})", path, place, ty); . . let erased_ty = tcx.erase_regions(ty); 48 ( 0.00%) if erased_ty.needs_drop(tcx, ctxt.param_env) { 8 ( 0.00%) each_child(child); . } else { . debug!("on_all_drop_children_bits - skipping") . } . }) . } . 208,904 ( 0.00%) pub fn drop_flag_effects_for_function_entry<'tcx, F>( . tcx: TyCtxt<'tcx>, . body: &Body<'tcx>, . ctxt: &MoveDataParamEnv<'tcx>, . mut callback: F, . ) where . F: FnMut(MovePathIndex, DropFlagState), . { . let move_data = &ctxt.move_data; 18,872 ( 0.00%) for arg in body.args_iter() { 39,832 ( 0.00%) let place = mir::Place::from(arg); 59,748 ( 0.00%) let lookup_result = move_data.rev_lookup.find(place.as_ref()); . on_lookup_result_bits(tcx, body, move_data, lookup_result, |mpi| { 19,934 ( 0.00%) callback(mpi, DropFlagState::Present) . }); . } 150,976 ( 0.00%) } . 16,034,520 ( 0.05%) pub fn drop_flag_effects_for_location<'tcx, F>( . tcx: TyCtxt<'tcx>, . body: &Body<'tcx>, . ctxt: &MoveDataParamEnv<'tcx>, . loc: Location, . mut callback: F, . ) where . F: FnMut(MovePathIndex, DropFlagState), . { . let move_data = &ctxt.move_data; . debug!("drop_flag_effects_for_location({:?})", loc); . . // first, move out of the RHS 1,322,707 ( 0.00%) for mi in &move_data.loc_map[loc] { 2,858,661 ( 0.01%) let path = mi.move_path_index(move_data); . debug!("moving out of path {:?}", move_data.move_paths[path]); . 960,103 ( 0.00%) on_all_children_bits(tcx, body, move_data, path, |mpi| callback(mpi, DropFlagState::Absent)) . } . . debug!("drop_flag_effects: assignment for location({:?})", loc); . 327,514 ( 0.00%) for_location_inits(tcx, body, move_data, loc, |mpi| callback(mpi, DropFlagState::Present)); 10,725,688 ( 0.03%) } . . pub fn for_location_inits<'tcx, F>( . tcx: TyCtxt<'tcx>, . body: &Body<'tcx>, . move_data: &MoveData<'tcx>, . loc: Location, . mut callback: F, . ) where . F: FnMut(MovePathIndex), . { 1,322,707 ( 0.00%) for ii in &move_data.init_loc_map[loc] { 1,440,000 ( 0.00%) let init = move_data.inits[*ii]; 814,072 ( 0.00%) match init.kind { . InitKind::Deep => { . let path = init.path; . . on_all_children_bits(tcx, body, move_data, path, &mut callback) . } . InitKind::Shallow => { . let mpi = init.path; . callback(mpi); -- line 226 ---------------------------------------- -- line 230 ---------------------------------------- . } . } . . /// Calls `handle_inactive_variant` for each descendant move path of `enum_place` that contains a . /// `Downcast` to a variant besides the `active_variant`. . /// . /// NOTE: If there are no move paths corresponding to an inactive variant, . /// `handle_inactive_variant` will not be called for that variant. 213,552 ( 0.00%) pub(crate) fn on_all_inactive_variants<'tcx>( . tcx: TyCtxt<'tcx>, . body: &mir::Body<'tcx>, . move_data: &MoveData<'tcx>, . enum_place: mir::Place<'tcx>, . active_variant: VariantIdx, . mut handle_inactive_variant: impl FnMut(MovePathIndex), . ) { 88,980 ( 0.00%) let enum_mpi = match move_data.rev_lookup.find(enum_place.as_ref()) { . LookupResult::Exact(mpi) => mpi, . LookupResult::Parent(_) => return, . }; . . let enum_path = &move_data.move_paths[enum_mpi]; 108,182 ( 0.00%) for (variant_mpi, variant_path) in enum_path.children(&move_data.move_paths) { . // Because of the way we build the `MoveData` tree, each child should have exactly one more . // projection than `enum_place`. This additional projection must be a downcast since the . // base is an enum. 20,771 ( 0.00%) let (downcast, base_proj) = variant_path.place.projection.split_last().unwrap(); 83,084 ( 0.00%) assert_eq!(enum_place.projection.len(), base_proj.len()); . 62,313 ( 0.00%) let variant_idx = match *downcast { . mir::ProjectionElem::Downcast(_, idx) => idx, . _ => unreachable!(), . }; . 20,771 ( 0.00%) if variant_idx != active_variant { . on_all_children_bits(tcx, body, move_data, variant_mpi, |mpi| { 20,202 ( 0.00%) handle_inactive_variant(mpi) . }); . } . } 142,368 ( 0.00%) } 9,862,413 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs -------------------------------------------------------------------------------- Ir -- line 91 ---------------------------------------- . // maximum of number bytes needed to fill an 8-byte-sized element on which . // SipHash operates. Note that for variable-sized copies which are known to be . // less than 8 bytes, this function will perform more work than necessary unless . // the compiler is able to optimize the extra work away. . #[inline] . unsafe fn copy_nonoverlapping_small(src: *const u8, dst: *mut u8, count: usize) { . debug_assert!(count <= 8); . 750,676 ( 0.00%) if count == 8 { . ptr::copy_nonoverlapping(src, dst, 8); . return; . } . . let mut i = 0; 808,852 ( 0.00%) if i + 3 < count { . ptr::copy_nonoverlapping(src.add(i), dst.add(i), 4); . i += 4; . } . 1,724,040 ( 0.00%) if i + 1 < count { . ptr::copy_nonoverlapping(src.add(i), dst.add(i), 2); 261,364 ( 0.00%) i += 2 . } . 808,852 ( 0.00%) if i < count { 550,266 ( 0.00%) *dst.add(i) = *src.add(i); . i += 1; . } . . debug_assert_eq!(i, count); . } . . // # Implementation . // -- line 124 ---------------------------------------- -- line 201 ---------------------------------------- . . hasher . } . . // A specialized write function for values with size <= 8. . #[inline] . fn short_write(&mut self, x: T) { . let size = mem::size_of::(); 12,131,353 ( 0.03%) let nbuf = self.nbuf; . debug_assert!(size <= 8); . debug_assert!(nbuf < BUFFER_SIZE); . debug_assert!(nbuf + size < BUFFER_WITH_SPILL_SIZE); . 83,522,005 ( 0.24%) if nbuf + size < BUFFER_SIZE { . unsafe { . // The memcpy call is optimized away because the size is known. . let dst = (self.buf.as_mut_ptr() as *mut u8).add(nbuf); . ptr::copy_nonoverlapping(&x as *const _ as *const u8, dst, size); . } . 26,502,710 ( 0.08%) self.nbuf = nbuf + size; . . return; . } . 4,571,810 ( 0.01%) unsafe { self.short_write_process_buffer(x) } . } . . // A specialized write function for values with size <= 8 that should only . // be called when the write would cause the buffer to fill. . // . // SAFETY: the write of `x` into `self.buf` starting at byte offset . // `self.nbuf` must cause `self.buf` to become fully initialized (and not . // overflow) if it wasn't already. . #[inline(never)] 1,357,437 ( 0.00%) unsafe fn short_write_process_buffer(&mut self, x: T) { . let size = mem::size_of::(); 1,357,437 ( 0.00%) let nbuf = self.nbuf; . debug_assert!(size <= 8); . debug_assert!(nbuf < BUFFER_SIZE); . debug_assert!(nbuf + size >= BUFFER_SIZE); . debug_assert!(nbuf + size < BUFFER_WITH_SPILL_SIZE); . . // Copy first part of input into end of buffer, possibly into spill . // element. The memcpy call is optimized away because the size is known. . let dst = (self.buf.as_mut_ptr() as *mut u8).add(nbuf); . ptr::copy_nonoverlapping(&x as *const _ as *const u8, dst, size); . . // Process buffer. . for i in 0..BUFFER_CAPACITY { 13,574,370 ( 0.04%) let elem = self.buf.get_unchecked(i).assume_init().to_le(); 10,859,496 ( 0.03%) self.state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut self.state); 12,216,933 ( 0.04%) self.state.v0 ^= elem; . } . . // Copy remaining input into start of buffer by copying size - 1 . // elements from spill (at most size - 1 bytes could have overflowed . // into the spill). The memcpy call is optimized away because the size . // is known. And the whole copy is optimized away for size == 1. . let src = self.buf.get_unchecked(BUFFER_SPILL_INDEX) as *const _ as *const u8; . ptr::copy_nonoverlapping(src, self.buf.as_mut_ptr() as *mut u8, size - 1); . . // This function should only be called when the write fills the buffer. . // Therefore, when size == 1, the new `self.nbuf` must be zero. The size . // is statically known, so the branch is optimized away. 6,468,237 ( 0.02%) self.nbuf = if size == 1 { 0 } else { nbuf + size - BUFFER_SIZE }; 5,429,748 ( 0.02%) self.processed += BUFFER_SIZE; 2,714,874 ( 0.01%) } . . // A write function for byte slices. . #[inline] . fn slice_write(&mut self, msg: &[u8]) { . let length = msg.len(); 69,960 ( 0.00%) let nbuf = self.nbuf; . debug_assert!(nbuf < BUFFER_SIZE); . 2,537,829 ( 0.01%) if nbuf + length < BUFFER_SIZE { . unsafe { . let dst = (self.buf.as_mut_ptr() as *mut u8).add(nbuf); . 918,950 ( 0.00%) if length <= 8 { . copy_nonoverlapping_small(msg.as_ptr(), dst, length); . } else { . // This memcpy is *not* optimized away. . ptr::copy_nonoverlapping(msg.as_ptr(), dst, length); . } . } . 462,919 ( 0.00%) self.nbuf = nbuf + length; . . return; . } . 397,475 ( 0.00%) unsafe { self.slice_write_process_buffer(msg) } . } . . // A write function for byte slices that should only be called when the . // write would cause the buffer to fill. . // . // SAFETY: `self.buf` must be initialized up to the byte offset `self.nbuf`, . // and `msg` must contain enough bytes to initialize the rest of the element . // containing the byte offset `self.nbuf`. . #[inline(never)] 226,015 ( 0.00%) unsafe fn slice_write_process_buffer(&mut self, msg: &[u8]) { . let length = msg.len(); 45,203 ( 0.00%) let nbuf = self.nbuf; . debug_assert!(nbuf < BUFFER_SIZE); . debug_assert!(nbuf + length >= BUFFER_SIZE); . . // Always copy first part of input into current element of buffer. . // This function should only be called when the write fills the buffer, . // so we know that there is enough input to fill the current element. 135,609 ( 0.00%) let valid_in_elem = nbuf % ELEM_SIZE; 45,203 ( 0.00%) let needed_in_elem = ELEM_SIZE - valid_in_elem; . . let src = msg.as_ptr(); . let dst = (self.buf.as_mut_ptr() as *mut u8).add(nbuf); . copy_nonoverlapping_small(src, dst, needed_in_elem); . . // Process buffer. . . // Using `nbuf / ELEM_SIZE + 1` rather than `(nbuf + needed_in_elem) / . // ELEM_SIZE` to show the compiler that this loop's upper bound is > 0. . // We know that is true, because last step ensured we have a full . // element in the buffer. 90,406 ( 0.00%) let last = nbuf / ELEM_SIZE + 1; . . for i in 0..last { 346,641 ( 0.00%) let elem = self.buf.get_unchecked(i).assume_init().to_le(); 391,844 ( 0.00%) self.state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut self.state); 693,282 ( 0.00%) self.state.v0 ^= elem; . } . . // Process the remaining element-sized chunks of input. . let mut processed = needed_in_elem; 90,406 ( 0.00%) let input_left = length - processed; 48,231 ( 0.00%) let elems_left = input_left / ELEM_SIZE; . let extra_bytes_left = input_left % ELEM_SIZE; . . for _ in 0..elems_left { 25,931 ( 0.00%) let elem = (msg.as_ptr().add(processed) as *const u64).read_unaligned().to_le(); 25,931 ( 0.00%) self.state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut self.state); 25,931 ( 0.00%) self.state.v0 ^= elem; 51,862 ( 0.00%) processed += ELEM_SIZE; . } . . // Copy remaining input into start of buffer. . let src = msg.as_ptr().add(processed); . let dst = self.buf.as_mut_ptr() as *mut u8; . copy_nonoverlapping_small(src, dst, extra_bytes_left); . 45,203 ( 0.00%) self.nbuf = extra_bytes_left; 226,015 ( 0.00%) self.processed += nbuf + processed; 271,218 ( 0.00%) } . . #[inline] . pub fn finish128(mut self) -> (u64, u64) { . debug_assert!(self.nbuf < BUFFER_SIZE); . . // Process full elements in buffer. 303,870 ( 0.00%) let last = self.nbuf / ELEM_SIZE; . . // Since we're consuming self, avoid updating members for a potential . // performance gain. 405,160 ( 0.00%) let mut state = self.state; . . for i in 0..last { 336,419 ( 0.00%) let elem = unsafe { self.buf.get_unchecked(i).assume_init().to_le() }; 336,419 ( 0.00%) state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut state); 336,419 ( 0.00%) state.v0 ^= elem; . } . . // Get remaining partial element. 202,580 ( 0.00%) let elem = if self.nbuf % ELEM_SIZE != 0 { . unsafe { . // Ensure element is initialized by writing zero bytes. At most . // `ELEM_SIZE - 1` are required given the above check. It's safe . // to write this many because we have the spill and we maintain . // `self.nbuf` such that this write will start before the spill. . let dst = (self.buf.as_mut_ptr() as *mut u8).add(self.nbuf); . ptr::write_bytes(dst, 0, ELEM_SIZE - 1); 76,965 ( 0.00%) self.buf.get_unchecked(last).assume_init().to_le() . } . } else { . 0 . }; . . // Finalize the hash. 279,545 ( 0.00%) let length = self.processed + self.nbuf; 202,578 ( 0.00%) let b: u64 = ((length as u64 & 0xff) << 56) | elem; . 101,289 ( 0.00%) state.v3 ^= b; . Sip24Rounds::c_rounds(&mut state); 101,289 ( 0.00%) state.v0 ^= b; . 101,289 ( 0.00%) state.v2 ^= 0xee; . Sip24Rounds::d_rounds(&mut state); 327,224 ( 0.00%) let _0 = state.v0 ^ state.v1 ^ state.v2 ^ state.v3; . 124,644 ( 0.00%) state.v1 ^= 0xdd; . Sip24Rounds::d_rounds(&mut state); 124,644 ( 0.00%) let _1 = state.v0 ^ state.v1 ^ state.v2 ^ state.v3; . . (_0, _1) . } . } . . impl Hasher for SipHasher128 { . #[inline] . fn write_u8(&mut self, i: u8) { -- line 414 ---------------------------------------- -- line 471 ---------------------------------------- . } . . #[derive(Debug, Clone, Default)] . struct Sip24Rounds; . . impl Sip24Rounds { . #[inline] . fn c_rounds(state: &mut State) { 48,172,150 ( 0.14%) compress!(state); 51,791,338 ( 0.15%) compress!(state); . } . . #[inline] . fn d_rounds(state: &mut State) { 654,444 ( 0.00%) compress!(state); 654,444 ( 0.00%) compress!(state); 654,444 ( 0.00%) compress!(state); 553,156 ( 0.00%) compress!(state); . } . } 9,471,487 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/search.rs -------------------------------------------------------------------------------- Ir -- line 40 ---------------------------------------- . . impl NodeRef { . /// Looks up a given key in a (sub)tree headed by the node, recursively. . /// Returns a `Found` with the handle of the matching KV, if any. Otherwise, . /// returns a `GoDown` with the handle of the leaf edge where the key belongs. . /// . /// The result is meaningful only if the tree is ordered by key, like the tree . /// in a `BTreeMap` is. 21,033,074 ( 0.06%) pub fn search_tree( . mut self, . key: &Q, . ) -> SearchResult . where . Q: Ord, . K: Borrow, . { . loop { 342 ( 0.00%) self = match self.search_node(key) { . Found(handle) => return Found(handle), 4,519,021 ( 0.01%) GoDown(handle) => match handle.force() { 722 ( 0.00%) Leaf(leaf) => return GoDown(leaf), . Internal(internal) => internal.descend(), . }, . } . } 8,622,149 ( 0.02%) } . . /// Descends to the nearest node where the edge matching the lower bound . /// of the range is different from the edge matching the upper bound, i.e., . /// the nearest node that has at least one key contained in the range. . /// . /// If found, returns an `Ok` with that node, the strictly ascending pair of . /// edge indices in the node delimiting the range, and the corresponding . /// pair of bounds for continuing the search in the child nodes, in case -- line 73 ---------------------------------------- -- line 175 ---------------------------------------- . impl NodeRef { . /// Looks up a given key in the node, without recursion. . /// Returns a `Found` with the handle of the matching KV, if any. Otherwise, . /// returns a `GoDown` with the handle of the edge where the key might be found . /// (if the node is internal) or where the key can be inserted. . /// . /// The result is meaningful only if the tree is ordered by key, like the tree . /// in a `BTreeMap` is. 456 ( 0.00%) pub fn search_node(self, key: &Q) -> SearchResult . where . Q: Ord, . K: Borrow, . { 304 ( 0.00%) match unsafe { self.find_key_index(key, 0) } { . IndexResult::KV(idx) => Found(unsafe { Handle::new_kv(self, idx) }), 494 ( 0.00%) IndexResult::Edge(idx) => GoDown(unsafe { Handle::new_edge(self, idx) }), . } 76 ( 0.00%) } . . /// Returns either the KV index in the node at which the key (or an equivalent) . /// exists, or the edge index where the key belongs, starting from a particular index. . /// . /// The result is meaningful only if the tree is ordered by key, like the tree . /// in a `BTreeMap` is. . /// . /// # Safety . /// `start_index` must be a valid edge index for the node. 228 ( 0.00%) unsafe fn find_key_index(&self, key: &Q, start_index: usize) -> IndexResult . where . Q: Ord, . K: Borrow, . { 114 ( 0.00%) let node = self.reborrow(); 228 ( 0.00%) let keys = node.keys(); . debug_assert!(start_index <= keys.len()); 45,390,322 ( 0.13%) for (offset, k) in unsafe { keys.get_unchecked(start_index..) }.iter().enumerate() { 186,763,649 ( 0.54%) match key.cmp(k.borrow()) { . Ordering::Greater => {} . Ordering::Equal => return IndexResult::KV(start_index + offset), . Ordering::Less => return IndexResult::Edge(start_index + offset), . } . } 76 ( 0.00%) IndexResult::Edge(keys.len()) 190 ( 0.00%) } . . /// Finds an edge index in the node delimiting the lower bound of a range. . /// Also returns the lower bound to be used for continuing the search in . /// the matching child node, if `self` is an internal node. . /// . /// The result is meaningful only if the tree is ordered by key. . fn find_lower_bound_index<'r, Q>( . &self, -- line 226 ---------------------------------------- 8,702,752 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/std/src/thread/local.rs -------------------------------------------------------------------------------- Ir -- line 173 ---------------------------------------- . #[unstable(feature = "thread_local_internals", reason = "should not be necessary", issue = "none")] . #[macro_export] . #[allow_internal_unstable(thread_local_internals, cfg_target_thread_local, thread_local)] . #[allow_internal_unsafe] . macro_rules! __thread_local_inner { . // used to generate the `LocalKey` value for const-initialized thread locals . (@key $t:ty, const $init:expr) => {{ . #[cfg_attr(not(windows), inline)] // see comments below 4 ( 0.00%) unsafe fn __getit() -> $crate::option::Option<&'static $t> { . const INIT_EXPR: $t = $init; . . // wasm without atomics maps directly to `static mut`, and dtors . // aren't implemented because thread dtors aren't really a thing . // on wasm right now . // . // FIXME(#84224) this should come after the `target_thread_local` . // block. -- line 189 ---------------------------------------- -- line 211 ---------------------------------------- . } . . // 0 == dtor not registered . // 1 == dtor registered, dtor not run . // 2 == dtor registered and is running or has run . #[thread_local] . static mut STATE: u8 = 0; . 8 ( 0.00%) unsafe extern "C" fn destroy(ptr: *mut u8) { . let ptr = ptr as *mut $t; . . unsafe { . debug_assert_eq!(STATE, 1); 12 ( 0.00%) STATE = 2; . $crate::ptr::drop_in_place(ptr); . } 8 ( 0.00%) } . . unsafe { 42,120 ( 0.00%) match STATE { . // 0 == we haven't registered a destructor, so do . // so now. . 0 => { . $crate::thread::__FastLocalKeyInner::<$t>::register_dtor( . $crate::ptr::addr_of_mut!(VAL) as *mut u8, . destroy, . ); 8 ( 0.00%) STATE = 1; . Some(&VAL) . } . // 1 == the destructor is registered and the value . // is valid, so return the pointer. . 1 => Some(&VAL), . // otherwise the destructor has already run, so we . // can't give access. . _ => None, -- line 246 ---------------------------------------- -- line 257 ---------------------------------------- . { . #[inline] . const fn __init() -> $t { INIT_EXPR } . static __KEY: $crate::thread::__OsLocalKeyInner<$t> = . $crate::thread::__OsLocalKeyInner::new(); . #[allow(unused_unsafe)] . unsafe { __KEY.get(__init) } . } 2,109,926 ( 0.01%) } . . unsafe { . $crate::thread::LocalKey::new(__getit) . } . }}; . . // used to generate the `LocalKey` value for `thread_local!` . (@key $t:ty, $init:expr) => { . { . #[inline] 5 ( 0.00%) fn __init() -> $t { $init } . . // When reading this function you might ask "why is this inlined . // everywhere other than Windows?", and that's a very reasonable . // question to ask. The short story is that it segfaults rustc if . // this function is inlined. The longer story is that Windows looks . // to not support `extern` references to thread locals across DLL . // boundaries. This appears to at least not be supported in the ABI . // that LLVM implements. -- line 284 ---------------------------------------- -- line 293 ---------------------------------------- . // across a DLL boundary. Unfortunately rustc doesn't currently . // have this sort of logic available in an attribute, and it's not . // clear that rustc is even equipped to answer this (it's more of a . // Cargo question kinda). This means that, unfortunately, Windows . // gets the pessimistic path for now where it's never inlined. . // . // The issue of "should enable on Windows sometimes" is #84933 . #[cfg_attr(not(windows), inline)] 3,027,444 ( 0.01%) unsafe fn __getit() -> $crate::option::Option<&'static $t> { . #[cfg(all(target_family = "wasm", not(target_feature = "atomics")))] . static __KEY: $crate::thread::__StaticLocalKeyInner<$t> = . $crate::thread::__StaticLocalKeyInner::new(); . . #[thread_local] . #[cfg(all( . target_thread_local, . not(all(target_family = "wasm", not(target_feature = "atomics"))), -- line 309 ---------------------------------------- -- line 317 ---------------------------------------- . ))] . static __KEY: $crate::thread::__OsLocalKeyInner<$t> = . $crate::thread::__OsLocalKeyInner::new(); . . // FIXME: remove the #[allow(...)] marker when macros don't . // raise warning for missing/extraneous unsafe blocks anymore. . // See https://github.com/rust-lang/rust/issues/74838. . #[allow(unused_unsafe)] 19,800 ( 0.00%) unsafe { __KEY.get(__init) } 43,075,186 ( 0.12%) } . . unsafe { . $crate::thread::LocalKey::new(__getit) . } . } . }; . ($(#[$attr:meta])* $vis:vis $name:ident, $t:ty, $($init:tt)*) => { . $(#[$attr])* $vis const $name: $crate::thread::LocalKey<$t> = -- line 334 ---------------------------------------- -- line 377 ---------------------------------------- . /// this key yet. . /// . /// # Panics . /// . /// This function will `panic!()` if the key currently has its . /// destructor running, and it **may** panic if the destructor has . /// previously been run for this thread. . #[stable(feature = "rust1", since = "1.0.0")] 5,042,384 ( 0.01%) pub fn with(&'static self, f: F) -> R . where . F: FnOnce(&T) -> R, . { 35,657 ( 0.00%) self.try_with(f).expect( . "cannot access a Thread Local Storage value \ . during or after destruction", . ) 4,057,040 ( 0.01%) } . . /// Acquires a reference to the value in this TLS key. . /// . /// This will lazily initialize the value if this thread has not referenced . /// this key yet. If the key has been destroyed (which may happen if this is called . /// in a destructor), this function will return an [`AccessError`]. . /// . /// # Panics . /// . /// This function will still `panic!()` if the key is uninitialized and the . /// key's initializer panics. . #[stable(feature = "thread_local_try_with", since = "1.26.0")] . #[inline] 15,180 ( 0.00%) pub fn try_with(&'static self, f: F) -> Result . where . F: FnOnce(&T) -> R, . { . unsafe { 30,826,118 ( 0.09%) let thread_local = (self.inner)().ok_or(AccessError)?; 11,962,268 ( 0.03%) Ok(f(thread_local)) . } 15,840 ( 0.00%) } . } . . mod lazy { . use crate::cell::UnsafeCell; . use crate::hint; . use crate::mem; . . pub struct LazyKeyInner { -- line 423 ---------------------------------------- -- line 424 ---------------------------------------- . inner: UnsafeCell>, . } . . impl LazyKeyInner { . pub const fn new() -> LazyKeyInner { . LazyKeyInner { inner: UnsafeCell::new(None) } . } . 19,800 ( 0.00%) pub unsafe fn get(&self) -> Option<&'static T> { . // SAFETY: The caller must ensure no reference is ever handed out to . // the inner cell nor mutable reference to the Option inside said . // cell. This make it safe to hand a reference, though the lifetime . // of 'static is itself unsafe, making the get method unsafe. 7,920 ( 0.00%) unsafe { (*self.inner.get()).as_ref() } 7,920 ( 0.00%) } . . /// The caller must ensure that no reference is active: this method . /// needs unique access. 12 ( 0.00%) pub unsafe fn initialize T>(&self, init: F) -> &'static T { . // Execute the initialization up front, *then* move it into our slot, . // just in case initialization fails. 6 ( 0.00%) let value = init(); 1 ( 0.00%) let ptr = self.inner.get(); . . // SAFETY: . // . // note that this can in theory just be `*ptr = Some(value)`, but due to . // the compiler will currently codegen that pattern with something like: . // . // ptr::drop_in_place(ptr) . // ptr::write(ptr, Some(value)) -- line 454 ---------------------------------------- -- line 458 ---------------------------------------- . // TLS, in which case there will be a `&` and `&mut` pointer to the same . // value (an aliasing violation). To avoid setting the "I'm running a . // destructor" flag we just use `mem::replace` which should sequence the . // operations a little differently and make this safe to call. . // . // The precondition also ensures that we are the only one accessing . // `self` at the moment so replacing is fine. . unsafe { 24 ( 0.00%) let _ = mem::replace(&mut *ptr, Some(value)); . } . . // SAFETY: With the call to `mem::replace` it is guaranteed there is . // a `Some` behind `ptr`, not a `None` so `unreachable_unchecked` . // will never be reached. . unsafe { . // After storing `Some` we want to get a reference to the contents of . // what we just stored. While we could use `unwrap` here and it should . // always work it empirically doesn't seem to always get optimized away, . // which means that using something like `try_with` can pull in . // panicking code and cause a large size bloat. 5 ( 0.00%) match *ptr { 2 ( 0.00%) Some(ref x) => x, . None => hint::unreachable_unchecked(), . } . } 13 ( 0.00%) } . . /// The other methods hand out references while taking &self. . /// As such, callers of this method must ensure no `&` and `&mut` are . /// available and used at the same time. . #[allow(unused)] 8 ( 0.00%) pub unsafe fn take(&mut self) -> Option { . // SAFETY: See doc comment for this method. 1 ( 0.00%) unsafe { (*self.inner.get()).take() } 2 ( 0.00%) } . } . } . . /// On some targets like wasm there's no threads, so no need to generate . /// thread locals and we can instead just use plain statics! . #[doc(hidden)] . #[cfg(all(target_family = "wasm", not(target_feature = "atomics")))] . pub mod statik { -- line 500 ---------------------------------------- -- line 587 ---------------------------------------- . // const-initialized form of thread locals, basically a way to call the . // free `register_dtor` function defined elsewhere in libstd. . pub unsafe fn register_dtor(a: *mut u8, dtor: unsafe extern "C" fn(*mut u8)) { . unsafe { . register_dtor(a, dtor); . } . } . 11,880 ( 0.00%) pub unsafe fn get T>(&self, init: F) -> Option<&'static T> { . // SAFETY: See the definitions of `LazyKeyInner::get` and . // `try_initialize` for more information. . // . // The caller must ensure no mutable references are ever active to . // the inner cell or the inner T when this is called. . // The `try_initialize` is dependant on the passed `init` function . // for this. . unsafe { 14,015,451 ( 0.04%) match self.inner.get() { 11,877 ( 0.00%) Some(val) => Some(val), 27 ( 0.00%) None => self.try_initialize(init), . } . } 23,760 ( 0.00%) } . . // `try_initialize` is only called once per fast thread local variable, . // except in corner cases where thread_local dtors reference other . // thread_local's, or it is being recursively initialized. . // . // Macos: Inlining this function can cause two `tlv_get_addr` calls to . // be performed for every call to `Key::get`. . // LLVM issue: https://bugs.llvm.org/show_bug.cgi?id=41722 . #[inline(never)] 13 ( 0.00%) unsafe fn try_initialize T>(&self, init: F) -> Option<&'static T> { . // SAFETY: See comment above (this function doc). 18 ( 0.00%) if !mem::needs_drop::() || unsafe { self.try_register_dtor() } { . // SAFETY: See comment above (his function doc). 11 ( 0.00%) Some(unsafe { self.inner.initialize(init) }) . } else { . None . } 16 ( 0.00%) } . . // `try_register_dtor` is only called once per fast thread local . // variable, except in corner cases where thread_local dtors reference . // other thread_local's, or it is being recursively initialized. 3 ( 0.00%) unsafe fn try_register_dtor(&self) -> bool { 13 ( 0.00%) match self.dtor_state.get() { . DtorState::Unregistered => { . // SAFETY: dtor registration happens before initialization. . // Passing `self` as a pointer while using `destroy_value` . // is safe because the function will build a pointer to a . // Key, which is the type of self and so find the correct . // size. 9 ( 0.00%) unsafe { register_dtor(self as *const _ as *mut u8, destroy_value::) }; 4 ( 0.00%) self.dtor_state.set(DtorState::Registered); 2 ( 0.00%) true . } . DtorState::Registered => { . // recursively initialized . true . } . DtorState::RunningOrHasRun => false, . } 5 ( 0.00%) } . } . 7 ( 0.00%) unsafe extern "C" fn destroy_value(ptr: *mut u8) { 4 ( 0.00%) let ptr = ptr as *mut Key; . . // SAFETY: . // . // The pointer `ptr` has been built just above and comes from . // `try_register_dtor` where it is originally a Key coming from `self`, . // making it non-NUL and of the correct type. . // . // Right before we run the user destructor be sure to set the . // `Option` to `None`, and `dtor_state` to `RunningOrHasRun`. This . // causes future calls to `get` to run `try_initialize_drop` again, . // which will now fail, and return `None`. . unsafe { 2 ( 0.00%) let value = (*ptr).inner.take(); 5 ( 0.00%) (*ptr).dtor_state.set(DtorState::RunningOrHasRun); 13 ( 0.00%) drop(value); . } 2 ( 0.00%) } . } . . #[doc(hidden)] . pub mod os { . use super::lazy::LazyKeyInner; . use crate::cell::Cell; . use crate::fmt; . use crate::marker; -- line 679 ---------------------------------------- 3,062,792 ( 0.01%) -------------------------------------------------------------------------------- -- 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, . { 16,489,063 ( 0.05%) 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. 13,877 ( 0.00%) #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd)] 1,156 ( 0.00%) #[derive(Decodable)] . pub enum RealFileName { 2,762 ( 0.00%) 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 . local_path: Option, . /// `virtual_name` is the stable path rustc will store internally within -- line 175 ---------------------------------------- -- line 179 ---------------------------------------- . } . . impl Hash for RealFileName { . fn hash(&self, state: &mut H) { . // To prevent #70924 from happening again we should only hash the . // remapped (virtualized) path if that exists. This is because . // virtualized paths to sysroot crates (/rust/$hash or /rust/$version) . // remain stable even if the corresponding local_path changes 3,428 ( 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> { 56 ( 0.00%) encoder.emit_enum(|encoder| match *self { . RealFileName::LocalPath(ref local_path) => { 224 ( 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 213 ---------------------------------------- . } . } . . impl RealFileName { . /// 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. . pub fn local_path(&self) -> Option<&Path> { 2 ( 0.00%) match self { . RealFileName::LocalPath(p) => Some(p), . RealFileName::Remapped { local_path: p, virtual_name: _ } => { . p.as_ref().map(PathBuf::as_path) . } . } . } . . /// Returns the path suitable for reading from the file system on the local host, . /// if this information exists. . /// Avoid embedding this in build artifacts; see `remapped_path_if_available()` for that. 2 ( 0.00%) pub fn into_local_path(self) -> Option { 2 ( 0.00%) match self { . RealFileName::LocalPath(p) => Some(p), . RealFileName::Remapped { local_path: p, virtual_name: _ } => p, . } 3 ( 0.00%) } . . /// Returns the path suitable for embedding into build artifacts. This would still . /// be a local path if it has not been remapped. A remapped path will not correspond . /// to a valid file system path: see `local_path_if_available()` for something that . /// is more likely to return paths into the local host file system. . pub fn remapped_path_if_available(&self) -> &Path { 2,652 ( 0.00%) match self { . RealFileName::LocalPath(p) . | RealFileName::Remapped { local_path: _, virtual_name: p } => &p, . } 29 ( 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 { 28 ( 0.00%) match self { . RealFileName::LocalPath(path) . | RealFileName::Remapped { local_path: None, virtual_name: path } . | RealFileName::Remapped { local_path: Some(path), virtual_name: _ } => path, . } . } . . pub fn to_string_lossy(&self, display_pref: FileNameDisplayPreference) -> Cow<'_, str> { 28 ( 0.00%) match display_pref { . FileNameDisplayPreference::Local => self.local_path_if_available().to_string_lossy(), . FileNameDisplayPreference::Remapped => { . self.remapped_path_if_available().to_string_lossy() . } . } . } . } . . /// Differentiates between real files and common virtual files. 77,980 ( 0.00%) #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash)] 7,335 ( 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), 1,599 ( 0.00%) ProcMacroSourceCode(u64), . /// Strings provided as `--cfg [cfgspec]` stored in a `crate_cfg`. . CfgSpec(u64), . /// Strings provided as crate attributes in the CLI. . CliCrateAttr(u64), . /// 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 { 196 ( 0.00%) fn from(p: PathBuf) -> Self { 56 ( 0.00%) assert!(!p.to_string_lossy().ends_with('>')); 168 ( 0.00%) FileName::Real(RealFileName::LocalPath(p)) 196 ( 0.00%) } . } . 2 ( 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<'_> { 112 ( 0.00%) fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { . use FileName::*; 168 ( 0.00%) match *self.inner { . Real(ref name) => { 168 ( 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, ""), . } 140 ( 0.00%) } . } . . impl FileNameDisplay<'_> { . pub fn to_string_lossy(&self) -> Cow<'_, str> { . match self.inner { . FileName::Real(ref inner) => inner.to_string_lossy(self.display_pref), . _ => Cow::from(format!("{}", self)), . } . } . } . . impl FileName { . pub fn is_real(&self) -> bool { . use FileName::*; 1,226 ( 0.00%) match *self { . Real(_) => true, . Anon(_) . | MacroExpansion(_) . | ProcMacroSourceCode(_) . | CfgSpec(_) . | CliCrateAttr(_) . | Custom(_) . | QuoteExpansion(_) -- line 353 ---------------------------------------- -- line 357 ---------------------------------------- . } . . pub fn prefer_remapped(&self) -> FileNameDisplay<'_> { . FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Remapped } . } . . // This may include transient local filesystem information. . // Must not be embedded in build outputs. 28 ( 0.00%) pub fn prefer_local(&self) -> FileNameDisplay<'_> { . FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Local } 56 ( 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 377 ---------------------------------------- . } . . pub fn anon_source_code(src: &str) -> FileName { . let mut hasher = StableHasher::new(); . src.hash(&mut hasher); . FileName::Anon(hasher.finish()) . } . 7,995 ( 0.00%) pub fn proc_macro_source_code(src: &str) -> FileName { . let mut hasher = StableHasher::new(); . src.hash(&mut hasher); 3,198 ( 0.00%) FileName::ProcMacroSourceCode(hasher.finish()) 7,995 ( 0.00%) } . 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 { 13 ( 0.00%) pub lo: BytePos, 13 ( 0.00%) pub hi: BytePos, . /// Information about where the macro came from, if this piece of . /// code was created by a macro expansion. 39 ( 0.00%) pub ctxt: SyntaxContext, 13 ( 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 { 3,636,922 ( 0.01%) self.lo.0 == 0 && self.hi.0 == 0 . } . /// Returns `true` if `self` fully encloses `other`. . pub fn contains(self, other: Self) -> bool { 26,481 ( 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 { 200,480 ( 0.00%) fn partial_cmp(&self, rhs: &Self) -> Option { 150,360 ( 0.00%) PartialOrd::partial_cmp(&self.data(), &rhs.data()) 200,480 ( 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] 1,058,454 ( 0.00%) pub fn with_lo(self, lo: BytePos) -> Span { . self.data().with_lo(lo) 705,636 ( 0.00%) } . #[inline] 115,764 ( 0.00%) pub fn hi(self) -> BytePos { . self.data().hi 115,764 ( 0.00%) } . #[inline] 542,799 ( 0.00%) pub fn with_hi(self, hi: BytePos) -> Span { . self.data().with_hi(hi) 361,866 ( 0.00%) } . #[inline] . pub fn ctxt(self) -> SyntaxContext { . self.data_untracked().ctxt . } . #[inline] 142,965 ( 0.00%) pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span { . self.data_untracked().with_ctxt(ctxt) 85,779 ( 0.00%) } . #[inline] . pub fn parent(self) -> Option { . self.data().parent . } . #[inline] . pub fn with_parent(self, ctxt: Option) -> Span { . self.data().with_parent(ctxt) . } -- line 566 ---------------------------------------- -- line 568 ---------------------------------------- . /// Returns `true` if this is a dummy span with any hygienic context. . #[inline] . pub fn is_dummy(self) -> bool { . self.data_untracked().is_dummy() . } . . /// Returns `true` if this span comes from a macro or desugaring. . #[inline] 18 ( 0.00%) pub fn from_expansion(self) -> bool { . self.ctxt() != SyntaxContext::root() 12 ( 0.00%) } . . /// Returns `true` if `span` originates in a derive-macro's expansion. . pub fn in_derive_expansion(self) -> bool { . matches!(self.ctxt().outer_expn_data().kind, ExpnKind::Macro(MacroKind::Derive, _)) . } . . /// Gate suggestions that would not be appropriate in a context the user didn't write. . pub fn can_be_used_for_suggestions(self) -> bool { -- line 586 ---------------------------------------- -- line 600 ---------------------------------------- . /// Returns a new span representing an empty span at the beginning of this span. . #[inline] . pub fn shrink_to_lo(self) -> Span { . let span = self.data_untracked(); . span.with_hi(span.lo) . } . /// Returns a new span representing an empty span at the end of this span. . #[inline] 2,163 ( 0.00%) pub fn shrink_to_hi(self) -> Span { . let span = self.data_untracked(); . span.with_lo(span.hi) 1,442 ( 0.00%) } . . #[inline] . /// Returns `true` if `hi == lo`. . pub fn is_empty(self) -> bool { . let span = self.data_untracked(); . span.hi == span.lo . } . . /// Returns `self` if `self` is not the dummy span, and `other` otherwise. . pub fn substitute_dummy(self, other: Span) -> Span { . if self.is_dummy() { other } else { self } . } . . /// Returns `true` if `self` fully encloses `other`. 79,443 ( 0.00%) pub fn contains(self, other: Span) -> bool { . let span = self.data(); . let other = other.data(); . span.contains(other) 52,962 ( 0.00%) } . . /// Returns `true` if `self` touches `other`. . pub fn overlaps(self, other: Span) -> bool { . let span = self.data(); . let other = other.data(); . span.lo < other.hi && other.lo < span.hi . } . -- line 638 ---------------------------------------- -- line 663 ---------------------------------------- . /// The `Span` for the tokens in the previous macro expansion from which `self` was generated, . /// if any. . pub fn parent_callsite(self) -> Option { . let expn_data = self.ctxt().outer_expn_data(); . if !expn_data.is_root() { Some(expn_data.call_site) } else { None } . } . . /// Walk down the expansion ancestors to find a span that's contained within `outer`. 37,660 ( 0.00%) pub fn find_ancestor_inside(mut self, outer: Span) -> Option { 18,830 ( 0.00%) while !outer.contains(self) { . self = self.parent_callsite()?; . } . Some(self) 41,426 ( 0.00%) } . . /// Edition of the crate from which this span came. 263,493 ( 0.00%) pub fn edition(self) -> edition::Edition { . self.ctxt().edition() 175,662 ( 0.00%) } . . #[inline] . pub fn rust_2015(self) -> bool { 77,699 ( 0.00%) self.edition() == edition::Edition::Edition2015 . } . . #[inline] . pub fn rust_2018(self) -> bool { 3,968 ( 0.00%) self.edition() >= edition::Edition::Edition2018 . } . . #[inline] . pub fn rust_2021(self) -> bool { 8,861 ( 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]`). 11,640 ( 0.00%) pub fn allows_unstable(self, feature: Symbol) -> bool { 2,328 ( 0.00%) self.ctxt() . .outer_expn_data() . .allow_internal_unstable . .map_or(false, |features| features.iter().any(|&f| f == feature)) 9,312 ( 0.00%) } . . /// Checks if this span arises from a compiler desugaring of kind `kind`. 351,239 ( 0.00%) pub fn is_desugaring(self, kind: DesugaringKind) -> bool { 301,062 ( 0.00%) match self.ctxt().outer_expn_data().kind { . ExpnKind::Desugaring(k) => k == kind, . _ => false, . } 250,885 ( 0.00%) } . . /// Returns the compiler desugaring that created this span, or `None` . /// if this span is not from a desugaring. 5,060 ( 0.00%) pub fn desugaring_kind(self) -> Option { 6,072 ( 0.00%) match self.ctxt().outer_expn_data().kind { . ExpnKind::Desugaring(k) => Some(k), . _ => None, . } 4,048 ( 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]`). 4 ( 0.00%) pub fn allows_unsafe(self) -> bool { 1 ( 0.00%) self.ctxt().outer_expn_data().allow_internal_unsafe 4 ( 0.00%) } . . pub fn macro_backtrace(mut self) -> impl Iterator { . let mut prev_span = DUMMY_SP; . std::iter::from_fn(move || { . loop { . let expn_data = self.ctxt().outer_expn_data(); . if expn_data.is_root() { . return None; -- line 752 ---------------------------------------- -- line 767 ---------------------------------------- . . /// Returns a `Span` that would enclose both `self` and `end`. . /// . /// ```text . /// ____ ___ . /// self lorem ipsum end . /// ^^^^^^^^^^^^^^^^^^^^ . /// ``` 7,806,271 ( 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. 1,394,859 ( 0.00%) if span_data.ctxt != end_data.ctxt { 24,463 ( 0.00%) if span_data.ctxt == SyntaxContext::root() { . return end; 17,923 ( 0.00%) } else if end_data.ctxt == SyntaxContext::root() { . return self; . } . // Both spans fall within a macro. . // FIXME(estebank): check if it is the *same* macro. . } . Span::new( . cmp::min(span_data.lo, end_data.lo), . cmp::max(span_data.hi, end_data.hi), . if span_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt }, 4,826,871 ( 0.01%) if span_data.parent == end_data.parent { span_data.parent } else { None }, . ) 6,386,949 ( 0.02%) } . . /// Returns a `Span` between the end of `self` to the beginning of `end`. . /// . /// ```text . /// ____ ___ . /// self lorem ipsum end . /// ^^^^^^^^^^^^^ . /// ``` 18,997 ( 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 }, 12,089 ( 0.00%) if span.parent == end.parent { span.parent } else { None }, . ) 13,816 ( 0.00%) } . . /// Returns a `Span` from the beginning of `self` until the beginning of `end`. . /// . /// ```text . /// ____ ___ . /// self lorem ipsum end . /// ^^^^^^^^^^^^^^^^^ . /// ``` 43,384 ( 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. 7,888 ( 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 }, 27,608 ( 0.00%) if span_data.parent == end_data.parent { span_data.parent } else { None }, . ) 35,496 ( 0.00%) } . 374 ( 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, . ) 238 ( 0.00%) } . . /// Equivalent of `Span::def_site` from the proc macro API, . /// except that the location is taken from the `self` span. . pub fn with_def_site_ctxt(self, expn_id: ExpnId) -> Span { 19,966 ( 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 { 1,322 ( 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 { 1,320 ( 0.00%) 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). 135,648 ( 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)) 79,128 ( 0.00%) } . . #[inline] . pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span { . let span = self.data(); 1,281,681 ( 0.00%) span.with_ctxt(span.ctxt.apply_mark(expn_id, transparency)) . } . . #[inline] . pub fn remove_mark(&mut self) -> ExpnId { 37,900 ( 0.00%) let mut span = self.data(); 37,900 ( 0.00%) let mark = span.ctxt.remove_mark(); 151,600 ( 0.00%) *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark . } . . #[inline] . 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] 1,449,675 ( 0.00%) pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option { 966,450 ( 0.00%) let mut span = self.data(); 792,547 ( 0.00%) let mark = span.ctxt.normalize_to_macros_2_0_and_adjust(expn_id); 1,449,675 ( 0.00%) *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark 1,597,922 ( 0.00%) } . . #[inline] . pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option> { 11,688 ( 0.00%) let mut span = self.data(); 17,532 ( 0.00%) let mark = span.ctxt.glob_adjust(expn_id, glob_span); 46,752 ( 0.00%) *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark . } . . #[inline] 21,186 ( 0.00%) pub fn reverse_glob_adjust( . &mut self, . expn_id: ExpnId, . glob_span: Span, . ) -> Option> { 14,688 ( 0.00%) let mut span = self.data(); 12,898 ( 0.00%) let mark = span.ctxt.reverse_glob_adjust(expn_id, glob_span); 23,442 ( 0.00%) *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark 23,540 ( 0.00%) } . . #[inline] 1,576,696 ( 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()) 1,379,609 ( 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 { 188,075 ( 0.00%) MultiSpan { primary_spans: vec![primary_span], span_labels: vec![] } . } . . pub fn from_spans(mut vec: Vec) -> MultiSpan { . vec.sort(); 5,965 ( 0.00%) MultiSpan { primary_spans: vec, span_labels: vec![] } . } . . pub fn push_span_label(&mut self, span: Span, label: String) { . self.span_labels.push((span, label)); . } . . /// Selects the first primary span (if any). . pub fn primary_span(&self) -> Option { . self.primary_spans.first().cloned() 9,337 ( 0.00%) } . . /// Returns all primary spans. . pub fn primary_spans(&self) -> &[Span] { . &self.primary_spans 1 ( 0.00%) } . . /// Returns `true` if any of the primary spans are displayable. . pub fn has_primary_spans(&self) -> bool { . self.primary_spans.iter().any(|sp| !sp.is_dummy()) . } . . /// Returns `true` if this contains only a dummy primary span with any hygienic context. . pub fn is_dummy(&self) -> bool { -- line 1084 ---------------------------------------- -- 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 { 188,075 ( 0.00%) fn from(span: Span) -> MultiSpan { . MultiSpan::from_span(span) 188,075 ( 0.00%) } . } . . impl From> for MultiSpan { 5,965 ( 0.00%) fn from(spans: Vec) -> MultiSpan { 4,772 ( 0.00%) MultiSpan::from_spans(spans) 5,965 ( 0.00%) } . } . . /// Identifies an offset of a multi-byte character in a `SourceFile`. 88 ( 0.00%) #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)] . pub struct MultiByteChar { . /// The absolute offset of the character in the `SourceMap`. . pub pos: BytePos, . /// The number of bytes, `>= 2`. . pub bytes: u8, . } . . /// Identifies an offset of a non-narrow character in a `SourceFile`. 325 ( 0.00%) #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)] . pub enum NonNarrowChar { . /// Represents a zero-width character. . ZeroWidth(BytePos), . /// Represents a wide (full-width) character. . Wide(BytePos), . /// Represents a tab character, represented visually with a width of 4 characters. . Tab(BytePos), . } . . impl NonNarrowChar { . fn new(pos: BytePos, width: usize) -> Self { 2 ( 0.00%) match width { . 0 => NonNarrowChar::ZeroWidth(pos), . 2 => NonNarrowChar::Wide(pos), . 4 => NonNarrowChar::Tab(pos), . _ => panic!("width {} given for non-narrow character", width), . } . } . . /// Returns the absolute offset of the character in the `SourceMap`. -- line 1188 ---------------------------------------- -- line 1201 ---------------------------------------- . } . } . } . . impl Add for NonNarrowChar { . type Output = Self; . . fn add(self, rhs: BytePos) -> Self { 544 ( 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; . 158 ( 0.00%) fn sub(self, rhs: BytePos) -> Self { 544 ( 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), . } 474 ( 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, . } . 84 ( 0.00%) #[derive(PartialEq, Eq, Clone, Debug)] . pub enum ExternalSource { . /// No external source has to be loaded, since the `SourceFile` represents a local crate. . Unneeded, . Foreign { . kind: ExternalSourceKind, . /// This SourceFile's byte-offset within the source_map of its original crate. . original_start_pos: BytePos, . /// The end of this SourceFile within the source_map of its original crate. -- line 1246 ---------------------------------------- -- line 1257 ---------------------------------------- . AbsentOk, . /// A failed attempt has been made to load the external source. . AbsentErr, . Unneeded, . } . . impl ExternalSource { . pub fn get_source(&self) -> Option<&Lrc> { 796 ( 0.00%) match self { . ExternalSource::Foreign { kind: ExternalSourceKind::Present(ref src), .. } => Some(src), . _ => None, . } . } . } . . #[derive(Debug)] . pub struct OffsetOverflowError; . 1,170 ( 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. 168 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, Debug)] 2,340 ( 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 { 1 ( 0.00%) 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 => { 126 ( 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)); . } . } . hash . } . . /// Check if the stored hash matches the hash of the string. . pub fn matches(&self, src: &str) -> bool { 1 ( 0.00%) Self::new(self.kind, src) == *self . } . . /// The bytes of the hash. . pub fn hash_bytes(&self) -> &[u8] { . let len = self.hash_len(); . &self.value[..len] . } . . fn hash_len(&self) -> usize { 125 ( 0.00%) match self.kind { . SourceFileHashAlgorithm::Md5 => 16, . SourceFileHashAlgorithm::Sha1 => 20, . SourceFileHashAlgorithm::Sha256 => 32, . } . } . } . . /// A single source in the [`SourceMap`]. 1,624 ( 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. 28 ( 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. 28 ( 0.00%) pub name_hash: u128, . /// Indicates which crate this `SourceFile` was imported from. 28 ( 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)?; . 112 ( 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 { 56 ( 0.00%) 0..=0xFF => 1, 4 ( 0.00%) 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); . 58 ( 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))?; 84 ( 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))?; 308 ( 0.00%) s.emit_struct_field("cnum", false, |s| self.cnum.encode(s)) . }) . } . } . . impl Decodable for SourceFile { 5,265 ( 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); 585 ( 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 { 964,512 ( 0.00%) let diff = match bytes_per_diff { . 1 => d.read_u8() as u32, . 2 => d.read_u16() as u32, . 4 => d.read_u32(), . _ => unreachable!(), . }; . . line_start = line_start + BytePos(diff); . -- line 1480 ---------------------------------------- -- line 1483 ---------------------------------------- . } . . lines . }); . let multibyte_chars: Vec = . d.read_struct_field("multibyte_chars", |d| Decodable::decode(d)); . let non_narrow_chars: Vec = . d.read_struct_field("non_narrow_chars", |d| Decodable::decode(d)); 1,170 ( 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)); 6,435 ( 0.00%) SourceFile { 4,680 ( 0.00%) name, . start_pos, . end_pos, . src: None, 2,340 ( 0.00%) src_hash, . // Unused - the metadata decoder will construct . // a new SourceFile, filling in `external_src` properly . external_src: Lock::new(ExternalSource::Unneeded), 2,340 ( 0.00%) lines, 2,340 ( 0.00%) multibyte_chars, 2,340 ( 0.00%) non_narrow_chars, 2,340 ( 0.00%) normalized_pos, . name_hash, . cnum, . } . }) 5,265 ( 0.00%) } . } . . impl fmt::Debug for SourceFile { . fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { . write!(fmt, "SourceFile({:?})", self.name) . } . } . . impl SourceFile { 451 ( 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); 123 ( 0.00%) let normalized_pos = normalize_src(&mut src, start_pos); . . let name_hash = { . let mut hasher: StableHasher = StableHasher::new(); 82 ( 0.00%) name.hash(&mut hasher); . hasher.finish::() . }; 82 ( 0.00%) let end_pos = start_pos.to_usize() + src.len(); 123 ( 0.00%) assert!(end_pos <= u32::MAX as usize); . 492 ( 0.00%) let (lines, multibyte_chars, non_narrow_chars) = 82 ( 0.00%) analyze_source_file::analyze_source_file(&src, start_pos); . 697 ( 0.00%) SourceFile { . name, . src: Some(Lrc::new(src)), 451 ( 0.00%) src_hash, . external_src: Lock::new(ExternalSource::Unneeded), . start_pos, . end_pos: Pos::from_usize(end_pos), 164 ( 0.00%) lines, 164 ( 0.00%) multibyte_chars, 164 ( 0.00%) non_narrow_chars, 164 ( 0.00%) normalized_pos, . name_hash, . cnum: LOCAL_CRATE, . } 369 ( 0.00%) } . . /// Returns the `BytePos` of the beginning of the current line. . pub fn line_begin_pos(&self, pos: BytePos) -> BytePos { . let line_index = self.lookup_line(pos).unwrap(); . self.lines[line_index] . } . . /// Add externally loaded source. . /// If the hash of the input doesn't match or no input is supplied via None, . /// it is interpreted as an error and the corresponding enum variant is set. . /// The return value signifies whether some kind of source is present. 101,892 ( 0.00%) pub fn add_external_src(&self, get_src: F) -> bool . where . F: FnOnce() -> Option, . { 14,672 ( 0.00%) if matches!( 29,112 ( 0.00%) *self.external_src.borrow(), . ExternalSource::Foreign { kind: ExternalSourceKind::AbsentOk, .. } . ) { 1 ( 0.00%) 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 3 ( 0.00%) if let ExternalSource::Foreign { . kind: src_kind @ ExternalSourceKind::AbsentOk, .. . } = &mut *external_src . { 5 ( 0.00%) if let Some(mut src) = src { . // The src_hash needs to be computed on the pre-normalized src. 1 ( 0.00%) if self.src_hash.matches(&src) { 3 ( 0.00%) normalize_src(&mut src, BytePos::from_usize(0)); 8 ( 0.00%) *src_kind = ExternalSourceKind::Present(Lrc::new(src)); . return true; . } . } else { . *src_kind = ExternalSourceKind::AbsentErr; . } . . false . } else { . self.src.is_some() || external_src.get_source().is_some() . } . } else { 14,555 ( 0.00%) self.src.is_some() || self.external_src.borrow().get_source().is_some() . } 131,004 ( 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() 613 ( 0.00%) } . . pub fn is_imported(&self) -> bool { . self.src.is_none() 165,826 ( 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 { 72,753 ( 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 { 188,457 ( 0.00%) if self.is_empty() { . return self.start_pos..self.end_pos; . } . 124,582 ( 0.00%) assert!(line_index < self.lines.len()); 184,443 ( 0.00%) if line_index == (self.lines.len() - 1) { 162 ( 0.00%) self.lines[line_index]..self.end_pos . } else { 122,830 ( 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`. 11,050 ( 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; . 33,150 ( 0.00%) for mbc in self.multibyte_chars.iter() { . debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos); 1,168 ( 0.00%) if mbc.pos < bpos { . // Every character is at least one byte, so we only . // count the actual extra bytes. 1,824 ( 0.00%) total_extra_bytes += mbc.bytes as u32 - 1; . // We should never see a byte position in the middle of a . // character. 1,520 ( 0.00%) assert!(bpos.to_u32() >= mbc.pos.to_u32() + mbc.bytes as u32); . } else { . break; . } . } . 66,300 ( 0.00%) assert!(self.start_pos.to_u32() + total_extra_bytes <= bpos.to_u32()); 55,250 ( 0.00%) CharPos(bpos.to_usize() - self.start_pos.to_usize() - total_extra_bytes as usize) 22,100 ( 0.00%) } . . /// Looks up the file's (1-based) line number and (0-based `CharPos`) column offset, for a . /// given `BytePos`. 38,675 ( 0.00%) pub fn lookup_file_pos(&self, pos: BytePos) -> (usize, CharPos) { 11,050 ( 0.00%) let chpos = self.bytepos_to_file_charpos(pos); 5,524 ( 0.00%) match self.lookup_line(pos) { . Some(a) => { . let line = a + 1; // Line numbers start at 1 5,525 ( 0.00%) let linebpos = self.lines[a]; 11,050 ( 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); 5,525 ( 0.00%) assert!(chpos >= linechpos); . (line, col) . } . None => (0, chpos), . } 44,200 ( 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`. 44,200 ( 0.00%) pub fn lookup_file_pos_with_col_display(&self, pos: BytePos) -> (usize, CharPos, usize) { 16,575 ( 0.00%) let (line, col_or_chpos) = self.lookup_file_pos(pos); 11,050 ( 0.00%) if line > 0 { . let col = col_or_chpos; 5,525 ( 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); 648 ( 0.00%) let special_chars = end_width_idx - start_width_idx; . let non_narrow: usize = self.non_narrow_chars[start_width_idx..end_width_idx] . .iter() . .map(|x| x.width()) . .sum(); 27,625 ( 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) . } 38,675 ( 0.00%) } . } . . /// Normalizes the source code and records the normalizations. 420 ( 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 378 ( 0.00%) } . . /// Removes UTF-8 BOM, if any. . fn remove_bom(src: &mut String, normalized_pos: &mut Vec) { 40 ( 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) { 42 ( 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])* 561,183 ( 0.00%) $vis struct $ident($inner_vis $inner_ty); . . impl Pos for $ident { . #[inline(always)] . fn from_usize(n: usize) -> $ident { 6,002 ( 0.00%) $ident(n as $inner_ty) . } . . #[inline(always)] . fn to_usize(&self) -> usize { 135,359 ( 0.00%) 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 { 2,052,537 ( 0.01%) $ident(self.0 + rhs.0) . } . } . . impl Sub for $ident { . type Output = $ident; . . #[inline(always)] . fn sub(self, rhs: $ident) -> $ident { 10,041,641 ( 0.03%) $ident(self.0 - rhs.0) . } . } . )* . }; . } . . impl_pos! { . /// A byte offset. -- line 1931 ---------------------------------------- -- line 1939 ---------------------------------------- . /// Because of multibyte UTF-8 characters, a byte offset . /// is not equivalent to a character offset. The [`SourceMap`] will convert [`BytePos`] . /// values to `CharPos` values as necessary. . #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] . pub struct CharPos(pub usize); . } . . impl Encodable for BytePos { 5 ( 0.00%) fn encode(&self, s: &mut S) -> Result<(), S::Error> { . s.emit_u32(self.0) 6 ( 0.00%) } . } . . impl Decodable for BytePos { . fn decode(d: &mut D) -> BytePos { 225,340 ( 0.00%) BytePos(d.read_u32()) . } . } . . // _____________________________________________________________________________ . // Loc, SourceFileAndLine, SourceFileAndBytePos . // . . /// A source code location used for error reporting. -- line 1962 ---------------------------------------- -- line 2042 ---------------------------------------- . /// Range inside of a `Span` used for diagnostics when we only have access to relative positions. . #[derive(Copy, Clone, PartialEq, Eq, Debug)] . pub struct InnerSpan { . pub start: usize, . pub end: usize, . } . . impl InnerSpan { 172 ( 0.00%) pub fn new(start: usize, end: usize) -> InnerSpan { . InnerSpan { start, end } 86 ( 0.00%) } . } . . /// Requirements for a `StableHashingContext` to be used in this crate. . /// . /// This is a hack to allow using the [`HashStable_Generic`] derive macro . /// instead of implementing everything in rustc_middle. . pub trait HashStableContext { . fn def_path_hash(&self, def_id: DefId) -> DefPathHash; -- line 2060 ---------------------------------------- -- line 2079 ---------------------------------------- . /// offsets into the `SourceMap`). Instead, we hash the (file name, line, column) . /// triple, which stays the same even if the containing `SourceFile` has moved . /// within the `SourceMap`. . /// . /// Also note that we are hashing byte offsets for the column, not unicode . /// codepoint offsets. For the purpose of the hash that's sufficient. . /// Also, hashing filenames is expensive so we avoid doing it twice when the . /// span starts and ends in the same file, which is almost always the case. 8,939,392 ( 0.03%) fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) { . const TAG_VALID_SPAN: u8 = 0; . const TAG_INVALID_SPAN: u8 = 1; . const TAG_RELATIVE_SPAN: u8 = 2; . 1,642,895 ( 0.00%) if !ctx.hash_spans() { . return; . } . 7,296,497 ( 0.02%) let span = self.data_untracked(); 2,733,659 ( 0.01%) span.ctxt.hash_stable(ctx, hasher); 3,831,168 ( 0.01%) span.parent.hash_stable(ctx, hasher); . 2,569,368 ( 0.01%) if span.is_dummy() { . Hash::hash(&TAG_INVALID_SPAN, hasher); . return; . } . 2,523,600 ( 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. 5,047,200 ( 0.01%) let (file, line_lo, col_lo, line_hi, col_hi) = match ctx.span_data_to_lines_and_cols(&span) . { 2,523,600 ( 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. . 1,261,800 ( 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; 1,261,800 ( 0.00%) let len = (span.hi - span.lo).0; . Hash::hash(&col_line, hasher); . Hash::hash(&len, hasher); 10,216,448 ( 0.03%) } . } 18,704,600 ( 0.05%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/string.rs -------------------------------------------------------------------------------- Ir -- line 374 ---------------------------------------- . /// . /// ``` . /// let s = String::new(); . /// ``` . #[inline] . #[rustc_const_stable(feature = "const_string_new", since = "1.39.0")] . #[stable(feature = "rust1", since = "1.0.0")] . #[must_use] 96,480 ( 0.00%) pub const fn new() -> String { 672,607 ( 0.00%) String { vec: Vec::new() } 64,320 ( 0.00%) } . . /// Creates a new empty `String` with a particular capacity. . /// . /// `String`s have an internal buffer to hold their data. The capacity is . /// the length of that buffer, and can be queried with the [`capacity`] . /// method. This method creates an empty `String`, but one with an initial . /// buffer that can hold `capacity` bytes. This is useful when you may be . /// appending a bunch of data to the `String`, reducing the number of -- line 392 ---------------------------------------- -- line 419 ---------------------------------------- . /// . /// // ...but this may make the string reallocate . /// s.push('a'); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[must_use] 16 ( 0.00%) pub fn with_capacity(capacity: usize) -> String { 493,130 ( 0.00%) String { vec: Vec::with_capacity(capacity) } 8 ( 0.00%) } . . // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is . // required for this method definition, is not available. Since we don't . // require this method for testing purposes, I'll just stub it . // NB see the slice::hack module in slice.rs for more information . #[inline] . #[cfg(test)] . pub fn from_str(_: &str) -> String { -- line 437 ---------------------------------------- -- line 492 ---------------------------------------- . /// . /// [`from_utf8_unchecked`]: String::from_utf8_unchecked . /// [`Vec`]: crate::vec::Vec "Vec" . /// [`&str`]: prim@str "&str" . /// [`into_bytes`]: String::into_bytes . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn from_utf8(vec: Vec) -> Result { 195 ( 0.00%) match str::from_utf8(&vec) { . Ok(..) => Ok(String { vec }), . Err(e) => Err(FromUtf8Error { bytes: vec, error: e }), . } . } . . /// Converts a slice of bytes to a string, including invalid characters. . /// . /// Strings are made of bytes ([`u8`]), and a slice of bytes -- line 508 ---------------------------------------- -- line 550 ---------------------------------------- . /// let input = b"Hello \xF0\x90\x80World"; . /// let output = String::from_utf8_lossy(input); . /// . /// assert_eq!("Hello �World", output); . /// ``` . #[must_use] . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] 513 ( 0.00%) pub fn from_utf8_lossy(v: &[u8]) -> Cow<'_, str> { 570 ( 0.00%) let mut iter = lossy::Utf8Lossy::from_bytes(v).chunks(); . 285 ( 0.00%) let first_valid = if let Some(chunk) = iter.next() { . let lossy::Utf8LossyChunk { valid, broken } = chunk; 57 ( 0.00%) if broken.is_empty() { . debug_assert_eq!(valid.len(), v.len()); 57 ( 0.00%) return Cow::Borrowed(valid); . } . valid . } else { . return Cow::Borrowed(""); . }; . . const REPLACEMENT: &str = "\u{FFFD}"; . -- line 573 ---------------------------------------- -- line 578 ---------------------------------------- . for lossy::Utf8LossyChunk { valid, broken } in iter { . res.push_str(valid); . if !broken.is_empty() { . res.push_str(REPLACEMENT); . } . } . . Cow::Owned(res) 456 ( 0.00%) } . . /// Decode a UTF-16–encoded vector `v` into a `String`, returning [`Err`] . /// if `v` contains any invalid data. . /// . /// # Examples . /// . /// Basic usage: . /// -- line 594 ---------------------------------------- -- line 761 ---------------------------------------- . /// String::from_utf8_unchecked(sparkle_heart) . /// }; . /// . /// assert_eq!("💖", sparkle_heart); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] 17,932 ( 0.00%) pub unsafe fn from_utf8_unchecked(bytes: Vec) -> String { 179,839 ( 0.00%) String { vec: bytes } 17,932 ( 0.00%) } . . /// Converts a `String` into a byte vector. . /// . /// This consumes the `String`, so we do not need to copy its contents. . /// . /// # Examples . /// . /// Basic usage: -- line 779 ---------------------------------------- -- line 800 ---------------------------------------- . /// ``` . /// let s = String::from("foo"); . /// . /// assert_eq!("foo", s.as_str()); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "string_as_str", since = "1.7.0")] 44,210 ( 0.00%) pub fn as_str(&self) -> &str { 66,315 ( 0.00%) self 44,210 ( 0.00%) } . . /// Converts a `String` into a mutable string slice. . /// . /// # Examples . /// . /// Basic usage: . /// . /// ``` -- line 818 ---------------------------------------- -- line 841 ---------------------------------------- . /// . /// s.push_str("bar"); . /// . /// assert_eq!("foobar", s); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 209,272 ( 0.00%) pub fn push_str(&mut self, string: &str) { 29,896 ( 0.00%) self.vec.extend_from_slice(string.as_bytes()) 59,792 ( 0.00%) } . . /// Copies elements from `src` range to the end of the string. . /// . /// ## Panics . /// . /// Panics if the starting point or end point do not lie on a [`char`] . /// boundary, or if they're out of bounds. . /// -- line 859 ---------------------------------------- -- line 1138 ---------------------------------------- . /// s.push('2'); . /// s.push('3'); . /// . /// assert_eq!("abc123", s); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 75,079,822 ( 0.22%) pub fn push(&mut self, ch: char) { 253,232 ( 0.00%) match ch.len_utf8() { 253,232 ( 0.00%) 1 => self.vec.push(ch as u8), 2 ( 0.00%) _ => self.vec.extend_from_slice(ch.encode_utf8(&mut [0; 4]).as_bytes()), . } 62,271,081 ( 0.18%) } . . /// Returns a byte slice of this `String`'s contents. . /// . /// The inverse of this method is [`from_utf8`]. . /// . /// [`from_utf8`]: String::from_utf8 . /// . /// # Examples -- line 1159 ---------------------------------------- -- line 1163 ---------------------------------------- . /// ``` . /// let s = String::from("hello"); . /// . /// assert_eq!(&[104, 101, 108, 108, 111], s.as_bytes()); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] 3,830 ( 0.00%) pub fn as_bytes(&self) -> &[u8] { 5,745 ( 0.00%) &self.vec 3,830 ( 0.00%) } . . /// Shortens this `String` to the specified length. . /// . /// If `new_len` is greater than the string's current length, this has no . /// effect. . /// . /// Note that this method has no effect on the allocated capacity . /// of the string -- line 1181 ---------------------------------------- -- line 1542 ---------------------------------------- . /// . /// let fancy_f = String::from("ƒoo"); . /// assert_eq!(fancy_f.len(), 4); . /// assert_eq!(fancy_f.chars().count(), 3); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] 8 ( 0.00%) pub fn len(&self) -> usize { 121 ( 0.00%) self.vec.len() 8 ( 0.00%) } . . /// Returns `true` if this `String` has a length of zero, and `false` otherwise. . /// . /// # Examples . /// . /// Basic usage: . /// . /// ``` -- line 1560 ---------------------------------------- -- line 1562 ---------------------------------------- . /// assert!(v.is_empty()); . /// . /// v.push('a'); . /// assert!(!v.is_empty()); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] 8 ( 0.00%) pub fn is_empty(&self) -> bool { 34 ( 0.00%) self.len() == 0 16 ( 0.00%) } . . /// Splits the string into two at the given byte index. . /// . /// Returns a newly allocated `String`. `self` contains bytes `[0, at)`, and . /// the returned `String` contains bytes `[at, len)`. `at` must be on the . /// boundary of a UTF-8 code point. . /// . /// Note that the capacity of `self` does not change. -- line 1580 ---------------------------------------- -- line 1747 ---------------------------------------- . /// let s = String::from("hello"); . /// . /// let b = s.into_boxed_str(); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "box_str", since = "1.4.0")] . #[must_use = "`self` will be dropped if the result is not used"] . #[inline] 5,064 ( 0.00%) pub fn into_boxed_str(self) -> Box { 60,768 ( 0.00%) let slice = self.vec.into_boxed_slice(); 15,192 ( 0.00%) unsafe { from_boxed_utf8_unchecked(slice) } 10,128 ( 0.00%) } . } . . impl FromUtf8Error { . /// Returns a slice of [`u8`]s bytes that were attempted to convert to a `String`. . /// . /// # Examples . /// . /// Basic usage: -- line 1766 ---------------------------------------- -- line 1845 ---------------------------------------- . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . fmt::Display::fmt("invalid utf-16: lone surrogate found", f) . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl Clone for String { 41,700 ( 0.00%) fn clone(&self) -> Self { 20,850 ( 0.00%) String { vec: self.vec.clone() } 48,650 ( 0.00%) } . . fn clone_from(&mut self, source: &Self) { . self.vec.clone_from(&source.vec); . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl FromIterator for String { 10,156 ( 0.00%) fn from_iter>(iter: I) -> String { . let mut buf = String::new(); . buf.extend(iter); . buf 11,626 ( 0.00%) } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "string_from_iter_by_ref", since = "1.17.0")] . impl<'a> FromIterator<&'a char> for String { . fn from_iter>(iter: I) -> String { . let mut buf = String::new(); . buf.extend(iter); -- line 1877 ---------------------------------------- -- line 1937 ---------------------------------------- . } . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl Extend for String { . fn extend>(&mut self, iter: I) { 866,386 ( 0.00%) let iterator = iter.into_iter(); 860,472 ( 0.00%) let (lower_bound, _) = iterator.size_hint(); . self.reserve(lower_bound); 37,291,387 ( 0.11%) iterator.for_each(move |c| self.push(c)); . } . . #[inline] . fn extend_one(&mut self, c: char) { . self.push(c); . } . . #[inline] -- line 1956 ---------------------------------------- -- line 2067 ---------------------------------------- . fn strip_suffix_of(self, haystack: &'a str) -> Option<&'a str> { . self[..].strip_suffix_of(haystack) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl PartialEq for String { . #[inline] 124 ( 0.00%) fn eq(&self, other: &String) -> bool { 310 ( 0.00%) PartialEq::eq(&self[..], &other[..]) 124 ( 0.00%) } . #[inline] . fn ne(&self, other: &String) -> bool { . PartialEq::ne(&self[..], &other[..]) . } . } . . macro_rules! impl_eq { . ($lhs:ty, $rhs: ty) => { . #[stable(feature = "rust1", since = "1.0.0")] . #[allow(unused_lifetimes)] . impl<'a, 'b> PartialEq<$rhs> for $lhs { . #[inline] 306,036 ( 0.00%) fn eq(&self, other: &$rhs) -> bool { 918,108 ( 0.00%) PartialEq::eq(&self[..], &other[..]) 306,036 ( 0.00%) } . #[inline] . fn ne(&self, other: &$rhs) -> bool { . PartialEq::ne(&self[..], &other[..]) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . #[allow(unused_lifetimes)] -- line 2100 ---------------------------------------- -- line 2128 ---------------------------------------- . fn default() -> String { . String::new() . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl fmt::Display for String { . #[inline] 10,787 ( 0.00%) fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 20,962 ( 0.00%) fmt::Display::fmt(&**self, f) 1,292 ( 0.00%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl fmt::Debug for String { . #[inline] . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . fmt::Debug::fmt(&**self, f) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl hash::Hash for String { . #[inline] 116 ( 0.00%) fn hash(&self, hasher: &mut H) { 28,653 ( 0.00%) (**self).hash(hasher) 58 ( 0.00%) } . } . . /// Implements the `+` operator for concatenating two strings. . /// . /// This consumes the `String` on the left-hand side and re-uses its buffer (growing it if . /// necessary). This is done to avoid allocating a new `String` and copying the entire contents on . /// every operation, which would lead to *O*(*n*^2) running time when building an *n*-byte string by . /// repeated concatenation. -- line 2162 ---------------------------------------- -- line 2192 ---------------------------------------- . /// let c = a.to_string() + b; . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl Add<&str> for String { . type Output = String; . . #[inline] 38,024 ( 0.00%) fn add(mut self, other: &str) -> String { 5,432 ( 0.00%) self.push_str(other); 16,298 ( 0.00%) self 5,432 ( 0.00%) } . } . . /// Implements the `+=` operator for appending to a `String`. . /// . /// This has the same behavior as the [`push_str`][String::push_str] method. . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "stringaddassign", since = "1.12.0")] . impl AddAssign<&str> for String { -- line 2211 ---------------------------------------- -- line 2224 ---------------------------------------- . &self[..][index] . } . } . #[stable(feature = "rust1", since = "1.0.0")] . impl ops::Index> for String { . type Output = str; . . #[inline] 19,616 ( 0.00%) fn index(&self, index: ops::RangeTo) -> &str { 14,712 ( 0.00%) &self[..][index] 4,904 ( 0.00%) } . } . #[stable(feature = "rust1", since = "1.0.0")] . impl ops::Index> for String { . type Output = str; . . #[inline] 20,540 ( 0.00%) fn index(&self, index: ops::RangeFrom) -> &str { 14,712 ( 0.00%) &self[..][index] 5,828 ( 0.00%) } . } . #[stable(feature = "rust1", since = "1.0.0")] . impl ops::Index for String { . type Output = str; . . #[inline] 162,950 ( 0.00%) fn index(&self, _index: ops::RangeFull) -> &str { 488,850 ( 0.00%) unsafe { str::from_utf8_unchecked(&self.vec) } 162,950 ( 0.00%) } . } . #[stable(feature = "inclusive_range", since = "1.26.0")] . impl ops::Index> for String { . type Output = str; . . #[inline] . fn index(&self, index: ops::RangeInclusive) -> &str { . Index::index(&**self, index) -- line 2260 ---------------------------------------- -- line 2313 ---------------------------------------- . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl ops::Deref for String { . type Target = str; . . #[inline] 130,504 ( 0.00%) fn deref(&self) -> &str { 391,512 ( 0.00%) unsafe { str::from_utf8_unchecked(&self.vec) } 130,504 ( 0.00%) } . } . . #[stable(feature = "derefmut_for_string", since = "1.3.0")] . impl ops::DerefMut for String { . #[inline] . fn deref_mut(&mut self) -> &mut str { . unsafe { str::from_utf8_unchecked_mut(&mut *self.vec) } . } -- line 2331 ---------------------------------------- -- line 2386 ---------------------------------------- . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl ToString for T { . // A common guideline is to not inline generic functions. However, . // removing `#[inline]` from this method causes non-negligible regressions. . // See , the last attempt . // to try to remove it. . #[inline] 163,080 ( 0.00%) default fn to_string(&self) -> String { 27,180 ( 0.00%) let mut buf = String::new(); 1,810,692 ( 0.01%) let mut formatter = core::fmt::Formatter::new(&mut buf); . // Bypass format_args!() to avoid write_str with zero-length strs 757,782 ( 0.00%) fmt::Display::fmt(self, &mut formatter) . .expect("a Display implementation returned an error unexpectedly"); . buf 54,360 ( 0.00%) } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "char_to_string_specialization", since = "1.46.0")] . impl ToString for char { . #[inline] . fn to_string(&self) -> String { . String::from(self.encode_utf8(&mut [0; 4])) -- line 2409 ---------------------------------------- -- line 2470 ---------------------------------------- . self[..].to_owned() . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "string_to_string_specialization", since = "1.17.0")] . impl ToString for String { . #[inline] 8 ( 0.00%) fn to_string(&self) -> String { 2 ( 0.00%) self.to_owned() 4 ( 0.00%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl AsRef for String { . #[inline] . fn as_ref(&self) -> &str { . self . } -- line 2488 ---------------------------------------- -- line 2494 ---------------------------------------- . fn as_mut(&mut self) -> &mut str { . self . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl AsRef<[u8]> for String { . #[inline] 2,460 ( 0.00%) fn as_ref(&self) -> &[u8] { 3,690 ( 0.00%) self.as_bytes() 2,460 ( 0.00%) } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl From<&str> for String { . /// Converts a `&str` into a [`String`]. . /// . /// The result is allocated on the heap. -- line 2512 ---------------------------------------- -- line 2553 ---------------------------------------- . /// . /// ``` . /// let s1: String = String::from("hello world"); . /// let s2: Box = s1.into_boxed_str(); . /// let s3: String = String::from(s2); . /// . /// assert_eq!("hello world", s3) . /// ``` 1,302 ( 0.00%) fn from(s: Box) -> String { . s.into_string() 1,302 ( 0.00%) } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "box_from_str", since = "1.20.0")] . impl From for Box { . /// Converts the given [`String`] to a boxed `str` slice that is owned. . /// . /// # Examples -- line 2571 ---------------------------------------- -- line 2620 ---------------------------------------- . /// ``` . /// # use std::borrow::Cow; . /// assert_eq!(Cow::from("eggplant"), Cow::Borrowed("eggplant")); . /// ``` . /// . /// [`Borrowed`]: crate::borrow::Cow::Borrowed "borrow::Cow::Borrowed" . #[inline] . fn from(s: &'a str) -> Cow<'a, str> { 95,278 ( 0.00%) Cow::Borrowed(s) . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl<'a> From for Cow<'a, str> { . /// Converts a [`String`] into an [`Owned`] variant. . /// No heap allocation is performed, and the string -- line 2636 ---------------------------------------- -- line 2643 ---------------------------------------- . /// let s = "eggplant".to_string(); . /// let s2 = "eggplant".to_string(); . /// assert_eq!(Cow::from(s), Cow::<'static, str>::Owned(s2)); . /// ``` . /// . /// [`Owned`]: crate::borrow::Cow::Owned "borrow::Cow::Owned" . #[inline] . fn from(s: String) -> Cow<'a, str> { 39,480 ( 0.00%) Cow::Owned(s) . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "cow_from_string_ref", since = "1.28.0")] . impl<'a> From<&'a String> for Cow<'a, str> { . /// Converts a [`String`] reference into a [`Borrowed`] variant. . /// No heap allocation is performed, and the string -- line 2659 ---------------------------------------- -- line 2709 ---------------------------------------- . /// ``` . /// let s1 = String::from("hello world"); . /// let v1 = Vec::from(s1); . /// . /// for b in v1 { . /// println!("{}", b); . /// } . /// ``` 3 ( 0.00%) fn from(string: String) -> Vec { 12 ( 0.00%) string.into_bytes() 3 ( 0.00%) } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl fmt::Write for String { . #[inline] 3,344,592 ( 0.01%) fn write_str(&mut self, s: &str) -> fmt::Result { 27,180 ( 0.00%) self.push_str(s); 27,180 ( 0.00%) Ok(()) 2,967,288 ( 0.01%) } . . #[inline] 666,654 ( 0.00%) fn write_char(&mut self, c: char) -> fmt::Result { 29 ( 0.00%) self.push(c); . Ok(()) 666,654 ( 0.00%) } . } . . /// A draining iterator for `String`. . /// . /// This struct is created by the [`drain`] method on [`String`]. See its . /// documentation for more. . /// . /// [`drain`]: String::drain -- line 2743 ---------------------------------------- 2,305,417 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_resolve/src/lib.rs -------------------------------------------------------------------------------- Ir -- line 91 ---------------------------------------- . mod late; . mod macros; . . enum Weak { . Yes, . No, . } . 137,532 ( 0.00%) #[derive(Copy, Clone, PartialEq, Debug)] . pub enum Determinacy { . Determined, . Undetermined, . } . . impl Determinacy { . fn determined(determined: bool) -> Determinacy { . if determined { Determinacy::Determined } else { Determinacy::Undetermined } 91,688 ( 0.00%) } . } . . /// A specific scope in which a name can be looked up. . /// This enum is currently used only for early resolution (imports and macros), . /// but not for late resolution yet. . #[derive(Clone, Copy)] . enum Scope<'a> { . DeriveHelpers(LocalExpnId), -- line 116 ---------------------------------------- -- line 157 ---------------------------------------- . macro_rules: MacroRulesScopeRef<'a>, . derives: &'a [ast::Path], . } . . impl<'a> ParentScope<'a> { . /// Creates a parent scope with the passed argument used as the module scope component, . /// and other scope components set to default empty values. . pub fn module(module: Module<'a>, resolver: &Resolver<'a>) -> ParentScope<'a> { 8 ( 0.00%) ParentScope { . module, . expansion: LocalExpnId::ROOT, 2,049 ( 0.00%) macro_rules: resolver.arenas.alloc_macro_rules_scope(MacroRulesScope::Empty), . derives: &[], . } . } . } . . #[derive(Copy, Debug, Clone)] . enum ImplTraitContext { . Existential, -- line 176 ---------------------------------------- -- line 278 ---------------------------------------- . FailedToResolve(Span, String, Option), . ExpectedFound(Span, String, Res), . Indeterminate(Span), . ModuleOnly(Span), . } . . /// A minimal representation of a path segment. We use this in resolve because we synthesize 'path . /// segments' which don't have the rest of an AST or HIR `PathSegment`. 890 ( 0.00%) #[derive(Clone, Copy, Debug)] . pub struct Segment { . ident: Ident, . id: Option, . /// Signals whether this `PathSegment` has generic arguments. Used to avoid providing . /// nonsensical suggestions. . has_generic_args: bool, . } . -- line 294 ---------------------------------------- -- line 303 ---------------------------------------- . . fn names_to_string(segments: &[Segment]) -> String { . names_to_string(&segments.iter().map(|seg| seg.ident.name).collect::>()) . } . } . . impl<'a> From<&'a ast::PathSegment> for Segment { . fn from(seg: &'a ast::PathSegment) -> Segment { 520 ( 0.00%) Segment { ident: seg.ident, id: Some(seg.id), has_generic_args: seg.args.is_some() } . } . } . . struct UsePlacementFinder { . target_module: NodeId, . span: Option, . found_use: bool, . } -- line 319 ---------------------------------------- -- line 391 ---------------------------------------- . #[derive(Debug)] . enum LexicalScopeBinding<'a> { . Item(&'a NameBinding<'a>), . Res(Res), . } . . impl<'a> LexicalScopeBinding<'a> { . fn res(self) -> Res { 19,504 ( 0.00%) match self { . LexicalScopeBinding::Item(binding) => binding.res(), 29,256 ( 0.00%) LexicalScopeBinding::Res(res) => res, . } . } . } . . #[derive(Copy, Clone, Debug)] . enum ModuleOrUniformRoot<'a> { . /// Regular module. . Module(Module<'a>), -- line 409 ---------------------------------------- -- line 418 ---------------------------------------- . /// Virtual module that denotes resolution in current scope. . /// Used only for resolving single-segment imports. The reason it exists is that import paths . /// are always split into two parts, the first of which should be some kind of module. . CurrentScope, . } . . impl ModuleOrUniformRoot<'_> { . fn same_def(lhs: Self, rhs: Self) -> bool { 932 ( 0.00%) match (lhs, rhs) { . (ModuleOrUniformRoot::Module(lhs), ModuleOrUniformRoot::Module(rhs)) => { . ptr::eq(lhs, rhs) . } . ( . ModuleOrUniformRoot::CrateRootAndExternPrelude, . ModuleOrUniformRoot::CrateRootAndExternPrelude, . ) . | (ModuleOrUniformRoot::ExternPrelude, ModuleOrUniformRoot::ExternPrelude) -- line 434 ---------------------------------------- -- line 491 ---------------------------------------- . /// A key that identifies a binding in a given `Module`. . /// . /// Multiple bindings in the same module can have the same key (in a valid . /// program) if all but one of them come from glob imports. . #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] . struct BindingKey { . /// The identifier for the binding, aways the `normalize_to_macros_2_0` version of the . /// identifier. 6,881,160 ( 0.02%) ident: Ident, 2,282,764 ( 0.01%) ns: Namespace, . /// 0 if ident is not `_`, otherwise a value that's unique to the specific . /// `_` in the expanded AST that introduced this binding. 1,703,856 ( 0.00%) disambiguator: u32, . } . . type Resolutions<'a> = RefCell>>>; . . /// One node in the tree of modules. . /// . /// Note that a "module" in resolve is broader than a `mod` that you declare in Rust code. It may be one of these: . /// -- line 511 ---------------------------------------- -- line 551 ---------------------------------------- . impl<'a> ModuleData<'a> { . fn new( . parent: Option>, . kind: ModuleKind, . expansion: ExpnId, . span: Span, . no_implicit_prelude: bool, . ) -> Self { 19,670 ( 0.00%) let is_foreign = match kind { . ModuleKind::Def(_, def_id, _) => !def_id.is_local(), . ModuleKind::Block(_) => false, . }; 64,630 ( 0.00%) ModuleData { . parent, . kind, . lazy_resolutions: Default::default(), . populate_on_access: Cell::new(is_foreign), . unexpanded_invocations: Default::default(), . no_implicit_prelude, . glob_importers: RefCell::new(Vec::new()), . globs: RefCell::new(Vec::new()), . traits: RefCell::new(None), . span, . expansion, . } . } . 23,352 ( 0.00%) fn for_each_child(&'a self, resolver: &mut R, mut f: F) . where . R: AsMut>, . F: FnMut(&mut R, Ident, Namespace, &'a NameBinding<'a>), . { 11,462 ( 0.00%) for (key, name_resolution) in resolver.as_mut().resolutions(self).borrow().iter() { 145,020 ( 0.00%) if let Some(binding) = name_resolution.borrow().binding { 23,058 ( 0.00%) f(resolver, key.ident, key.ns, binding); . } . } 18,680 ( 0.00%) } . . /// This modifies `self` in place. The traits will be stored in `self.traits`. . fn ensure_traits(&'a self, resolver: &mut R) . where . R: AsMut>, . { . let mut traits = self.traits.borrow_mut(); 18,735 ( 0.00%) if traits.is_none() { . let mut collected_traits = Vec::new(); . self.for_each_child(resolver, |_, name, ns, binding| { 4,164 ( 0.00%) if ns != TypeNS { . return; . } 13,452 ( 0.00%) if let Res::Def(DefKind::Trait | DefKind::TraitAlias, _) = binding.res() { . collected_traits.push((name, binding)) . } . }); 8,922 ( 0.00%) *traits = Some(collected_traits.into_boxed_slice()); . } . } . . fn res(&self) -> Option { 350,931 ( 0.00%) match self.kind { 577,740 ( 0.00%) ModuleKind::Def(kind, def_id, _) => Some(Res::Def(kind, def_id)), 4 ( 0.00%) _ => None, . } . } . . // Public for rustdoc. . pub fn def_id(&self) -> DefId { . self.opt_def_id().expect("`ModuleData::def_id` is called on a block module") . } . . fn opt_def_id(&self) -> Option { 28,586 ( 0.00%) match self.kind { . ModuleKind::Def(_, def_id, _) => Some(def_id), . _ => None, . } . } . . // `self` resolves to the first module ancestor that `is_normal`. . fn is_normal(&self) -> bool { 92,214 ( 0.00%) matches!(self.kind, ModuleKind::Def(DefKind::Mod, _, _)) . } . . fn is_trait(&self) -> bool { 27 ( 0.00%) matches!(self.kind, ModuleKind::Def(DefKind::Trait, _, _)) . } . . fn nearest_item_scope(&'a self) -> Module<'a> { 261,520 ( 0.00%) match self.kind { . ModuleKind::Def(DefKind::Enum | DefKind::Trait, ..) => { 324 ( 0.00%) self.parent.expect("enum or trait module without a parent") . } . _ => self, . } . } . . /// The [`DefId`] of the nearest `mod` item ancestor (which may be this module). . /// This may be the crate root. 625,433 ( 0.00%) fn nearest_parent_mod(&self) -> DefId { 1,759,478 ( 0.01%) match self.kind { 508,612 ( 0.00%) ModuleKind::Def(DefKind::Mod, def_id, _) => def_id, 742,254 ( 0.00%) _ => self.parent.expect("non-root module without parent").nearest_parent_mod(), . } 1,250,866 ( 0.00%) } . . fn is_ancestor_of(&self, mut other: &Self) -> bool { . while !ptr::eq(self, other) { . if let Some(parent) = other.parent { . other = parent; . } else { . return false; . } -- line 662 ---------------------------------------- -- line 773 ---------------------------------------- . b1: &'a NameBinding<'a>, . b2: &'a NameBinding<'a>, . misc1: AmbiguityErrorMisc, . misc2: AmbiguityErrorMisc, . } . . impl<'a> NameBinding<'a> { . fn module(&self) -> Option> { 2,200,110 ( 0.01%) match self.kind { 305,762 ( 0.00%) NameBindingKind::Module(module) => Some(module), 64,142 ( 0.00%) NameBindingKind::Import { binding, .. } => binding.module(), . _ => None, . } . } . . fn res(&self) -> Res { 2,158,563 ( 0.01%) match self.kind { 973,685 ( 0.00%) NameBindingKind::Res(res, _) => res, 153,119 ( 0.00%) NameBindingKind::Module(module) => module.res().unwrap(), 77,849 ( 0.00%) NameBindingKind::Import { binding, .. } => binding.res(), . } . } . . fn is_ambiguity(&self) -> bool { 6,516 ( 0.00%) self.ambiguity.is_some() 7,156 ( 0.00%) || match self.kind { 3,576 ( 0.00%) NameBindingKind::Import { binding, .. } => binding.is_ambiguity(), . _ => false, . } . } . . fn is_possibly_imported_variant(&self) -> bool { . match self.kind { . NameBindingKind::Import { binding, .. } => binding.is_possibly_imported_variant(), . NameBindingKind::Res( -- line 807 ---------------------------------------- -- line 822 ---------------------------------------- . kind: ModuleKind::Def(DefKind::Mod, def_id, _), . .. . }) => def_id.index == CRATE_DEF_INDEX, . _ => false, . } . } . . fn is_import(&self) -> bool { 16,147 ( 0.00%) matches!(self.kind, NameBindingKind::Import { .. }) . } . . fn is_glob_import(&self) -> bool { 120,792 ( 0.00%) match self.kind { 7,873 ( 0.00%) NameBindingKind::Import { import, .. } => import.is_glob(), . _ => false, . } . } . . fn is_importable(&self) -> bool { 904 ( 0.00%) !matches!( . self.res(), . Res::Def(DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy, _) . ) . } . . fn is_macro_def(&self) -> bool { 4,749 ( 0.00%) matches!(self.kind, NameBindingKind::Res(Res::Def(DefKind::Macro(..), _), _)) . } . . fn macro_kind(&self) -> Option { . self.res().macro_kind() . } . . // Suppose that we resolved macro invocation with `invoc_parent_expansion` to binding `binding` . // at some expansion round `max(invoc, binding)` when they both emerged from macros. -- line 856 ---------------------------------------- -- line 1065 ---------------------------------------- . /// they are declared in the static array generated by proc_macro_harness. . proc_macros: Vec, . confused_type_with_std_module: FxHashMap, . . access_levels: AccessLevels, . } . . /// Nothing really interesting here; it just provides memory for the rest of the crate. 7 ( 0.00%) #[derive(Default)] . pub struct ResolverArenas<'a> { . modules: TypedArena>, . local_modules: RefCell>>, . imports: TypedArena>, . name_resolutions: TypedArena>>, . ast_paths: TypedArena, . dropless: DroplessArena, . } . . impl<'a> ResolverArenas<'a> { 36,530 ( 0.00%) fn new_module( . &'a self, . parent: Option>, . kind: ModuleKind, . expn_id: ExpnId, . span: Span, . no_implicit_prelude: bool, . module_map: &mut FxHashMap>, . ) -> Module<'a> { . let module = . self.modules.alloc(ModuleData::new(parent, kind, expn_id, span, no_implicit_prelude)); . let def_id = module.opt_def_id(); 8,430 ( 0.00%) if def_id.map_or(true, |def_id| def_id.is_local()) { . self.local_modules.borrow_mut().push(module); . } 2,810 ( 0.00%) if let Some(def_id) = def_id { . module_map.insert(def_id, module); . } . module 25,290 ( 0.00%) } . fn local_modules(&'a self) -> std::cell::Ref<'a, Vec>> { . self.local_modules.borrow() . } . fn alloc_name_binding(&'a self, name_binding: NameBinding<'a>) -> &'a NameBinding<'a> { . self.dropless.alloc(name_binding) . } 4,648 ( 0.00%) fn alloc_import(&'a self, import: Import<'a>) -> &'a Import<'_> { 8,714 ( 0.00%) self.imports.alloc(import) 4,648 ( 0.00%) } . fn alloc_name_resolution(&'a self) -> &'a RefCell> { 73,436 ( 0.00%) self.name_resolutions.alloc(Default::default()) . } . fn alloc_macro_rules_scope(&'a self, scope: MacroRulesScope<'a>) -> MacroRulesScopeRef<'a> { . PtrKey(self.dropless.alloc(Cell::new(scope))) . } . fn alloc_macro_rules_binding( . &'a self, . binding: MacroRulesBinding<'a>, . ) -> &'a MacroRulesBinding<'a> { -- line 1122 ---------------------------------------- -- line 1133 ---------------------------------------- . impl<'a> AsMut> for Resolver<'a> { . fn as_mut(&mut self) -> &mut Resolver<'a> { . self . } . } . . impl<'a, 'b> DefIdTree for &'a Resolver<'b> { . fn parent(self, id: DefId) -> Option { 66,071 ( 0.00%) match id.as_local() { . Some(id) => self.definitions.def_key(id).parent, . None => self.cstore().def_key(id).parent, . } . .map(|index| DefId { index, ..id }) . } . } . . /// This interface is used through the AST→HIR step, to embed full paths into the HIR. After that . /// the resolver is no longer needed as all the relevant information is inline. . impl ResolverAstLowering for Resolver<'_> { 390 ( 0.00%) fn def_key(&mut self, id: DefId) -> DefKey { 234 ( 0.00%) if let Some(id) = id.as_local() { . self.definitions().def_key(id) . } else { 178,910 ( 0.00%) self.cstore().def_key(id) . } 312 ( 0.00%) } . . #[inline] . fn def_span(&self, id: LocalDefId) -> Span { . self.definitions.def_span(id) . } . 196,776 ( 0.00%) fn item_generics_num_lifetimes(&self, def_id: DefId) -> usize { 55,742 ( 0.00%) if let Some(def_id) = def_id.as_local() { 11,473 ( 0.00%) self.item_generics_num_lifetimes[&def_id] . } else { 170,584 ( 0.00%) self.cstore().item_generics_num_lifetimes(def_id, self.session) . } 45,892 ( 0.00%) } . 49,784 ( 0.00%) fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option> { 24,892 ( 0.00%) self.legacy_const_generic_args(expr) 74,676 ( 0.00%) } . 407,742 ( 0.00%) fn get_partial_res(&self, id: NodeId) -> Option { . self.partial_res_map.get(&id).cloned() 1,223,226 ( 0.00%) } . 1,844 ( 0.00%) fn get_import_res(&mut self, id: NodeId) -> PerNS> { 461 ( 0.00%) self.import_res_map.get(&id).cloned().unwrap_or_default() 2,305 ( 0.00%) } . . fn get_label_res(&mut self, id: NodeId) -> Option { . self.label_res_map.get(&id).cloned() . } . . fn definitions(&mut self) -> &mut Definitions { 14,194 ( 0.00%) &mut self.definitions 14,194 ( 0.00%) } . 120,384 ( 0.00%) fn create_stable_hashing_context(&self) -> StableHashingContext<'_> { 223,781 ( 0.00%) StableHashingContext::new(self.session, &self.definitions, self.crate_loader.cstore()) 150,480 ( 0.00%) } . . fn lint_buffer(&mut self) -> &mut LintBuffer { . &mut self.lint_buffer . } . . fn next_node_id(&mut self) -> NodeId { . self.next_node_id() . } . 2,449,564 ( 0.01%) fn take_trait_map(&mut self, node: NodeId) -> Option> { . self.trait_map.remove(&node) 2,449,564 ( 0.01%) } . 2,515,690 ( 0.01%) fn opt_local_def_id(&self, node: NodeId) -> Option { 138,579 ( 0.00%) self.node_id_to_def_id.get(&node).copied() 2,515,690 ( 0.01%) } . 71,744 ( 0.00%) fn local_def_id(&self, node: NodeId) -> LocalDefId { . self.opt_local_def_id(node).unwrap_or_else(|| panic!("no entry for node id: `{:?}`", node)) 71,744 ( 0.00%) } . . fn def_path_hash(&self, def_id: DefId) -> DefPathHash { . match def_id.as_local() { . Some(def_id) => self.definitions.def_path_hash(def_id), . None => self.cstore().def_path_hash(def_id), . } . } . . /// Adds a definition with a parent definition. 353,415 ( 0.00%) fn create_def( . &mut self, . parent: LocalDefId, . node_id: ast::NodeId, . data: DefPathData, . expn_id: ExpnId, . span: Span, . ) -> LocalDefId { 47,122 ( 0.00%) assert!( 47,122 ( 0.00%) !self.node_id_to_def_id.contains_key(&node_id), . "adding a def'n for node-id {:?} and data {:?} but a previous def'n exists: {:?}", . node_id, . data, . self.definitions.def_key(self.node_id_to_def_id[&node_id]), . ); . . // Find the next free disambiguator for this key. 23,561 ( 0.00%) let next_disambiguator = &mut self.next_disambiguator; . let next_disambiguator = |parent, data| { 117,805 ( 0.00%) let next_disamb = next_disambiguator.entry((parent, data)).or_insert(0); 23,561 ( 0.00%) let disambiguator = *next_disamb; 23,561 ( 0.00%) *next_disamb = next_disamb.checked_add(1).expect("disambiguator overflow"); . disambiguator . }; . 235,610 ( 0.00%) let def_id = self.definitions.create_def(parent, data, expn_id, next_disambiguator, span); . . // Some things for which we allocate `LocalDefId`s don't correspond to . // anything in the AST, so they don't have a `NodeId`. For these cases . // we don't need a mapping from `NodeId` to `LocalDefId`. 70,683 ( 0.00%) if node_id != ast::DUMMY_NODE_ID { . debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id); . self.node_id_to_def_id.insert(node_id, def_id); . } 70,683 ( 0.00%) assert_eq!(self.def_id_to_node_id.push(node_id), def_id); . . def_id 212,049 ( 0.00%) } . } . . impl<'a> Resolver<'a> { 16 ( 0.00%) pub fn new( . session: &'a Session, . krate: &Crate, . crate_name: &str, . metadata_loader: Box, . arenas: &'a ResolverArenas<'a>, . ) -> Resolver<'a> { . let root_def_id = CRATE_DEF_ID.to_def_id(); . let mut module_map = FxHashMap::default(); 14 ( 0.00%) let graph_root = arenas.new_module( . None, . ModuleKind::Def(DefKind::Mod, root_def_id, kw::Empty), 1 ( 0.00%) ExpnId::root(), 1 ( 0.00%) krate.span, 2 ( 0.00%) session.contains_name(&krate.attrs, sym::no_implicit_prelude), . &mut module_map, . ); 12 ( 0.00%) let empty_module = arenas.new_module( . None, . ModuleKind::Def(DefKind::Mod, root_def_id, kw::Empty), 1 ( 0.00%) ExpnId::root(), . DUMMY_SP, . true, . &mut FxHashMap::default(), . ); . 4 ( 0.00%) let definitions = Definitions::new(session.local_stable_crate_id(), krate.span); 2 ( 0.00%) let root = definitions.get_root_def(); . . let mut visibilities = FxHashMap::default(); . visibilities.insert(CRATE_DEF_ID, ty::Visibility::Public); . . let mut def_id_to_node_id = IndexVec::default(); 2 ( 0.00%) assert_eq!(def_id_to_node_id.push(CRATE_NODE_ID), root); . let mut node_id_to_def_id = FxHashMap::default(); . node_id_to_def_id.insert(CRATE_NODE_ID, root); . . let mut invocation_parents = FxHashMap::default(); . invocation_parents.insert(LocalExpnId::ROOT, (root, ImplTraitContext::Existential)); . 3 ( 0.00%) let mut extern_prelude: FxHashMap> = session . .opts . .externs . .iter() 5 ( 0.00%) .filter(|(_, entry)| entry.add_prelude) 5 ( 0.00%) .map(|(name, _)| (Ident::from_str(name), Default::default())) . .collect(); . 9 ( 0.00%) if !session.contains_name(&krate.attrs, sym::no_core) { . extern_prelude.insert(Ident::with_dummy_span(sym::core), Default::default()); 7 ( 0.00%) if !session.contains_name(&krate.attrs, sym::no_std) { . extern_prelude.insert(Ident::with_dummy_span(sym::std), Default::default()); . } . } . 8 ( 0.00%) let (registered_attrs, registered_tools) = 4 ( 0.00%) macros::registered_attrs_and_tools(session, &krate.attrs); . . let features = session.features_untracked(); . 237 ( 0.00%) let mut resolver = Resolver { . session, . 2 ( 0.00%) definitions, . . // The outermost module has def ID 0; this is not reflected in the . // AST. . graph_root, . prelude: None, 4 ( 0.00%) extern_prelude, . . has_self: FxHashSet::default(), . field_names: FxHashMap::default(), . . determined_imports: Vec::new(), . indeterminate_imports: Vec::new(), . . last_import_segment: false, -- line 1343 ---------------------------------------- -- line 1347 ---------------------------------------- . partial_res_map: Default::default(), . import_res_map: Default::default(), . label_res_map: Default::default(), . extern_crate_map: Default::default(), . reexport_map: FxHashMap::default(), . trait_map: NodeMap::default(), . underscore_disambiguator: 0, . empty_module, 4 ( 0.00%) module_map, . block_map: Default::default(), . binding_parent_modules: FxHashMap::default(), . ast_transform_scopes: FxHashMap::default(), . . glob_map: Default::default(), 4 ( 0.00%) visibilities, . used_imports: FxHashSet::default(), . maybe_unused_trait_imports: Default::default(), . maybe_unused_extern_crates: Vec::new(), . . privacy_errors: Vec::new(), . ambiguity_errors: Vec::new(), . use_injections: Vec::new(), . macro_expanded_macro_export_errors: BTreeSet::new(), -- line 1369 ---------------------------------------- -- line 1372 ---------------------------------------- . dummy_binding: arenas.alloc_name_binding(NameBinding { . kind: NameBindingKind::Res(Res::Err, false), . ambiguity: None, . expansion: LocalExpnId::ROOT, . span: DUMMY_SP, . vis: ty::Visibility::Public, . }), . 6 ( 0.00%) crate_loader: CrateLoader::new(session, metadata_loader, crate_name), . macro_names: FxHashSet::default(), . builtin_macros: Default::default(), 4 ( 0.00%) registered_attrs, 4 ( 0.00%) registered_tools, . macro_use_prelude: FxHashMap::default(), . all_macros: FxHashMap::default(), . macro_map: FxHashMap::default(), 7 ( 0.00%) dummy_ext_bang: Lrc::new(SyntaxExtension::dummy_bang(session.edition())), 6 ( 0.00%) dummy_ext_derive: Lrc::new(SyntaxExtension::dummy_derive(session.edition())), 5 ( 0.00%) non_macro_attr: Lrc::new(SyntaxExtension::non_macro_attr(session.edition())), . invocation_parent_scopes: Default::default(), . output_macro_rules_scopes: Default::default(), . helper_attrs: Default::default(), . derive_data: Default::default(), . local_macro_def_scopes: FxHashMap::default(), . name_already_seen: FxHashMap::default(), . potentially_unused_imports: Vec::new(), . struct_constructors: Default::default(), -- line 1398 ---------------------------------------- -- line 1405 ---------------------------------------- . active_features: features . .declared_lib_features . .iter() . .map(|(feat, ..)| *feat) . .chain(features.declared_lang_features.iter().map(|(feat, ..)| *feat)) . .collect(), . lint_buffer: LintBuffer::default(), . next_node_id: CRATE_NODE_ID, 4 ( 0.00%) node_id_to_def_id, 4 ( 0.00%) def_id_to_node_id, . placeholder_field_indices: Default::default(), 4 ( 0.00%) invocation_parents, . next_disambiguator: Default::default(), . trait_impl_items: Default::default(), . legacy_const_generic_args: Default::default(), . item_generics_num_lifetimes: Default::default(), . main_def: Default::default(), . trait_impls: Default::default(), . proc_macros: Default::default(), . confused_type_with_std_module: Default::default(), . access_levels: Default::default(), . }; . . let root_parent_scope = ParentScope::module(graph_root, &resolver); . resolver.invocation_parent_scopes.insert(LocalExpnId::ROOT, root_parent_scope); . . resolver 9 ( 0.00%) } . . fn new_module( . &mut self, . parent: Option>, . kind: ModuleKind, . expn_id: ExpnId, . span: Span, . no_implicit_prelude: bool, . ) -> Module<'a> { 1,918 ( 0.00%) let module_map = &mut self.module_map; 27,758 ( 0.00%) self.arenas.new_module(parent, kind, expn_id, span, no_implicit_prelude, module_map) . } . . pub fn next_node_id(&mut self) -> NodeId { . let next = 659,645 ( 0.00%) self.next_node_id.as_u32().checked_add(1).expect("input too large; ran out of NodeIds"); . mem::replace(&mut self.next_node_id, ast::NodeId::from_u32(next)) . } . . pub fn lint_buffer(&mut self) -> &mut LintBuffer { 4 ( 0.00%) &mut self.lint_buffer 4 ( 0.00%) } . 1 ( 0.00%) pub fn arenas() -> ResolverArenas<'a> { . Default::default() 1 ( 0.00%) } . 9 ( 0.00%) pub fn into_outputs(self) -> ResolverOutputs { . let proc_macros = self.proc_macros.iter().map(|id| self.local_def_id(*id)).collect(); 1 ( 0.00%) let definitions = self.definitions; 4 ( 0.00%) let visibilities = self.visibilities; 4 ( 0.00%) let extern_crate_map = self.extern_crate_map; 4 ( 0.00%) let reexport_map = self.reexport_map; 4 ( 0.00%) let maybe_unused_trait_imports = self.maybe_unused_trait_imports; 4 ( 0.00%) let maybe_unused_extern_crates = self.maybe_unused_extern_crates; 4 ( 0.00%) let glob_map = self.glob_map; 6 ( 0.00%) let main_def = self.main_def; 4 ( 0.00%) let confused_type_with_std_module = self.confused_type_with_std_module; 6 ( 0.00%) let access_levels = self.access_levels; 37 ( 0.00%) ResolverOutputs { 2 ( 0.00%) definitions, 11 ( 0.00%) cstore: Box::new(self.crate_loader.into_cstore()), 4 ( 0.00%) visibilities, 4 ( 0.00%) access_levels, 4 ( 0.00%) extern_crate_map, 4 ( 0.00%) reexport_map, 4 ( 0.00%) glob_map, 4 ( 0.00%) maybe_unused_trait_imports, 4 ( 0.00%) maybe_unused_extern_crates, . extern_prelude: self . .extern_prelude . .iter() 8 ( 0.00%) .map(|(ident, entry)| (ident.name, entry.introduced_by_item)) . .collect(), 6 ( 0.00%) main_def, 4 ( 0.00%) trait_impls: self.trait_impls, 4 ( 0.00%) proc_macros, 4 ( 0.00%) confused_type_with_std_module, 5 ( 0.00%) registered_tools: self.registered_tools, . } 19 ( 0.00%) } . . pub fn clone_outputs(&self) -> ResolverOutputs { . let proc_macros = self.proc_macros.iter().map(|id| self.local_def_id(*id)).collect(); . ResolverOutputs { . definitions: self.definitions.clone(), . access_levels: self.access_levels.clone(), . cstore: Box::new(self.cstore().clone()), . visibilities: self.visibilities.clone(), -- line 1501 ---------------------------------------- -- line 1513 ---------------------------------------- . trait_impls: self.trait_impls.clone(), . proc_macros, . confused_type_with_std_module: self.confused_type_with_std_module.clone(), . registered_tools: self.registered_tools.clone(), . } . } . . pub fn cstore(&self) -> &CStore { 234,598 ( 0.00%) self.crate_loader.cstore() . } . . fn dummy_ext(&self, macro_kind: MacroKind) -> Lrc { . match macro_kind { . MacroKind::Bang => self.dummy_ext_bang.clone(), . MacroKind::Derive => self.dummy_ext_derive.clone(), . MacroKind::Attr => self.non_macro_attr.clone(), . } . } . . /// Runs the function on each namespace. 2,611 ( 0.00%) fn per_ns(&mut self, mut f: F) { 4,494 ( 0.00%) f(self, TypeNS); 3,912 ( 0.00%) f(self, ValueNS); 3,915 ( 0.00%) f(self, MacroNS); 2,400 ( 0.00%) } . . fn is_builtin_macro(&mut self, res: Res) -> bool { . self.get_macro(res).map_or(false, |ext| ext.builtin_name.is_some()) . } . 478,971 ( 0.00%) fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId { . loop { 159,657 ( 0.00%) match ctxt.outer_expn_data().macro_def_id { 53,219 ( 0.00%) Some(def_id) => return def_id, . None => ctxt.remove_mark(), . }; . } 532,190 ( 0.00%) } . . /// Entry point to crate resolution. 2 ( 0.00%) pub fn resolve_crate(&mut self, krate: &Crate) { 4 ( 0.00%) self.session.time("resolve_crate", || { 3 ( 0.00%) self.session.time("finalize_imports", || ImportResolver { r: self }.finalize_imports()); . self.session.time("resolve_access_levels", || { 3 ( 0.00%) AccessLevelsVisitor::compute_access_levels(self, krate) . }); 2 ( 0.00%) self.session.time("finalize_macro_resolutions", || self.finalize_macro_resolutions()); 3 ( 0.00%) self.session.time("late_resolve_crate", || self.late_resolve_crate(krate)); 2 ( 0.00%) self.session.time("resolve_main", || self.resolve_main()); 3 ( 0.00%) self.session.time("resolve_check_unused", || self.check_unused(krate)); 3 ( 0.00%) self.session.time("resolve_report_errors", || self.report_errors(krate)); 4 ( 0.00%) self.session.time("resolve_postprocess", || self.crate_loader.postprocess(krate)); . }); . } . 70,560 ( 0.00%) pub fn traits_in_scope( . &mut self, . current_trait: Option>, . parent_scope: &ParentScope<'a>, . ctxt: SyntaxContext, . assoc_item: Option<(Symbol, Namespace)>, . ) -> Vec { . let mut found_traits = Vec::new(); . 11,760 ( 0.00%) if let Some(module) = current_trait { . if self.trait_may_have_item(Some(module), assoc_item) { . let def_id = module.def_id(); 51 ( 0.00%) found_traits.push(TraitCandidate { def_id, import_ids: smallvec![] }); . } . } . . self.visit_scopes(ScopeSet::All(TypeNS, false), parent_scope, ctxt, |this, scope, _, _| { . match scope { . Scope::Module(module, _) => { . this.traits_in_module(module, assoc_item, &mut found_traits); . } . Scope::StdLibPrelude => { 17,640 ( 0.00%) if let Some(module) = this.prelude { . this.traits_in_module(module, assoc_item, &mut found_traits); . } . } . Scope::ExternPrelude | Scope::ToolPrelude | Scope::BuiltinTypes => {} . _ => unreachable!(), . } . None::<()> . }); . . found_traits 47,040 ( 0.00%) } . . fn traits_in_module( . &mut self, . module: Module<'a>, . assoc_item: Option<(Symbol, Namespace)>, . found_traits: &mut Vec, . ) { . module.ensure_traits(self); . let traits = module.traits.borrow(); 358,751 ( 0.00%) for (trait_name, trait_binding) in traits.as_ref().unwrap().iter() { . if self.trait_may_have_item(trait_binding.module(), assoc_item) { . let def_id = trait_binding.res().def_id(); 603 ( 0.00%) let import_ids = self.find_transitive_imports(&trait_binding.kind, *trait_name); 1,809 ( 0.00%) found_traits.push(TraitCandidate { def_id, import_ids }); . } . } . } . . // List of traits in scope is pruned on best effort basis. We reject traits not having an . // associated item with the given name and namespace (if specified). This is a conservative . // optimization, proper hygienic type-based resolution of associated items is done in typeck. . // We don't reject trait aliases (`trait_module == None`) because we don't have access to their . // associated items. . fn trait_may_have_item( . &mut self, . trait_module: Option>, . assoc_item: Option<(Symbol, Namespace)>, . ) -> bool { 181,498 ( 0.00%) match (trait_module, assoc_item) { . (Some(trait_module), Some((name, ns))) => { 357,251 ( 0.00%) self.resolutions(trait_module).borrow().iter().any(|resolution| { . let (&BindingKey { ident: assoc_ident, ns: assoc_ns, .. }, _) = resolution; 1,339,563 ( 0.00%) assoc_ns == ns && assoc_ident.name == name . }) . } . _ => true, . } . } . . fn find_transitive_imports( . &mut self, . mut kind: &NameBindingKind<'_>, . trait_name: Ident, . ) -> SmallVec<[LocalDefId; 1]> { . let mut import_ids = smallvec![]; 477 ( 0.00%) while let NameBindingKind::Import { import, binding, .. } = kind { 45 ( 0.00%) let id = self.local_def_id(import.id); . self.maybe_unused_trait_imports.insert(id); 15 ( 0.00%) self.add_to_glob_map(&import, trait_name); . import_ids.push(id); 15 ( 0.00%) kind = &binding.kind; . } . import_ids . } . . fn new_key(&mut self, ident: Ident, ns: Namespace) -> BindingKey { 1,940,808 ( 0.01%) let ident = ident.normalize_to_macros_2_0(); 639,174 ( 0.00%) let disambiguator = if ident.name == kw::Underscore { 2,640 ( 0.00%) self.underscore_disambiguator += 1; . self.underscore_disambiguator . } else { . 0 . }; . BindingKey { ident, ns, disambiguator } . } . 6,567,904 ( 0.02%) fn resolutions(&mut self, module: Module<'a>) -> &'a Resolutions<'a> { 820,988 ( 0.00%) if module.populate_on_access.get() { . module.populate_on_access.set(false); . self.build_reduced_graph_external(module); . } 820,988 ( 0.00%) &module.lazy_resolutions 7,388,892 ( 0.02%) } . 5,772,483 ( 0.02%) fn resolution( . &mut self, . module: Module<'a>, . key: BindingKey, . ) -> &'a RefCell> { 1,924,161 ( 0.01%) *self . .resolutions(module) . .borrow_mut() 3,848,322 ( 0.01%) .entry(key) 1,282,774 ( 0.00%) .or_insert_with(|| self.arenas.alloc_name_resolution()) 5,131,096 ( 0.01%) } . 2,632,718 ( 0.01%) fn record_use( . &mut self, . ident: Ident, . used_binding: &'a NameBinding<'a>, . is_lexical_scope: bool, . ) { 718,014 ( 0.00%) if let Some((b2, kind)) = used_binding.ambiguity { . self.ambiguity_errors.push(AmbiguityError { . kind, . ident, . b1: used_binding, . b2, . misc1: AmbiguityErrorMisc::None, . misc2: AmbiguityErrorMisc::None, . }); . } 575,890 ( 0.00%) if let NameBindingKind::Import { import, binding, ref used } = used_binding.kind { . // Avoid marking `extern crate` items that refer to a name from extern prelude, . // but not introduce it, as used if they are accessed from lexical scope. 97,214 ( 0.00%) if is_lexical_scope { 18,579 ( 0.00%) if let Some(entry) = self.extern_prelude.get(&ident.normalize_to_macros_2_0()) { 5 ( 0.00%) if let Some(crate_item) = entry.extern_crate_item { 2 ( 0.00%) if ptr::eq(used_binding, crate_item) && !entry.introduced_by_item { . return; . } . } . } . } . used.set(true); . import.used.set(true); 48,607 ( 0.00%) self.used_imports.insert(import.id); 243,035 ( 0.00%) self.add_to_glob_map(&import, ident); 291,642 ( 0.00%) self.record_use(ident, binding, false); . } 1,914,704 ( 0.01%) } . . #[inline] 145,821 ( 0.00%) fn add_to_glob_map(&mut self, import: &Import<'_>, ident: Ident) { 48,622 ( 0.00%) if import.is_glob() { 1,506 ( 0.00%) let def_id = self.local_def_id(import.id); . self.glob_map.entry(def_id).or_default().insert(ident.name); . } 191,416 ( 0.00%) } . . /// A generic scope visitor. . /// Visits scopes in order to resolve some identifier in them or perform other actions. . /// If the callback returns `Some` result, we stop visiting scopes and return it. . fn visit_scopes( . &mut self, . scope_set: ScopeSet<'a>, . parent_scope: &ParentScope<'a>, -- line 1738 ---------------------------------------- -- line 1780 ---------------------------------------- . // ambiguities with `macro_rules`. . // 4. `macro_use` prelude (open, the open part is from macro expansions, not controlled). . // 4a. User-defined prelude from macro-use . // (open, the open part is from macro expansions, not controlled). . // 4b. "Standard library prelude" part implemented through `macro-use` (closed, controlled). . // 4c. Standard library prelude (de-facto closed, controlled). . // 6. Language prelude: builtin attributes (closed, controlled). . 1,135,305 ( 0.00%) let rust_2015 = ctxt.edition() == Edition::Edition2015; . let (ns, macro_kind, is_absolute_path) = match scope_set { . ScopeSet::All(ns, _) => (ns, None, false), . ScopeSet::AbsolutePath(ns) => (ns, None, true), . ScopeSet::Macro(macro_kind) => (MacroNS, Some(macro_kind), false), . ScopeSet::Late(ns, ..) => (ns, None, false), . }; 3,477,180 ( 0.01%) let module = match scope_set { . // Start with the specified module. . ScopeSet::Late(_, module, _) => module, . // Jump out of trait or enum modules, they do not act as scopes. 33,622 ( 0.00%) _ => parent_scope.module.nearest_item_scope(), . }; 248,370 ( 0.00%) let mut scope = match ns { 620,925 ( 0.00%) _ if is_absolute_path => Scope::CrateRoot, . TypeNS | ValueNS => Scope::Module(module, None), 82,611 ( 0.00%) MacroNS => Scope::DeriveHelpers(parent_scope.expansion), . }; 260,130 ( 0.00%) let mut ctxt = ctxt.normalize_to_macros_2_0(); 567,300 ( 0.00%) let mut use_prelude = !module.no_implicit_prelude; . . loop { 4,060,898 ( 0.01%) let visit = match scope { . // Derive helpers are not in scope when resolving derives in the same container. . Scope::DeriveHelpers(expn_id) => { 88,477 ( 0.00%) !(expn_id == parent_scope.expansion && macro_kind == Some(MacroKind::Derive)) . } . Scope::DeriveHelpersCompat => true, . Scope::MacroRules(macro_rules_scope) => { . // Use "path compression" on `macro_rules` scope chains. This is an optimization . // used to avoid long scope chains, see the comments on `MacroRulesScopeRef`. . // As another consequence of this optimization visitors never observe invocation . // scopes for macros that were already expanded. 123,914 ( 0.00%) while let MacroRulesScope::Invocation(invoc_id) = macro_rules_scope.get() { . if let Some(next_scope) = self.output_macro_rules_scopes.get(&invoc_id) { . macro_rules_scope.set(next_scope.get()); . } else { . break; . } . } . true . } . Scope::CrateRoot => true, . Scope::Module(..) => true, 21,268 ( 0.00%) Scope::RegisteredAttrs => use_prelude, . Scope::MacroUsePrelude => use_prelude || rust_2015, . Scope::BuiltinAttrs => true, 68,220 ( 0.00%) Scope::ExternPrelude => use_prelude || is_absolute_path, 22,464 ( 0.00%) Scope::ToolPrelude => use_prelude, 621,408 ( 0.00%) Scope::StdLibPrelude => use_prelude || ns == MacroNS, . Scope::BuiltinTypes => true, . }; . 109,012 ( 0.00%) if visit { 473,984 ( 0.00%) if let break_result @ Some(..) = visitor(self, scope, use_prelude, ctxt) { . return break_result; . } . } . 1,291,376 ( 0.00%) scope = match scope { . Scope::DeriveHelpers(LocalExpnId::ROOT) => Scope::DeriveHelpersCompat, . Scope::DeriveHelpers(expn_id) => { . // Derive helpers are not visible to code generated by bang or derive macros. . let expn_data = expn_id.expn_data(); 204,948 ( 0.00%) match expn_data.kind { . ExpnKind::Root . | ExpnKind::Macro(MacroKind::Bang | MacroKind::Derive, _) => { . Scope::DeriveHelpersCompat . } 5,866 ( 0.00%) _ => Scope::DeriveHelpers(expn_data.parent.expect_local()), . } . } 80,286 ( 0.00%) Scope::DeriveHelpersCompat => Scope::MacroRules(parent_scope.macro_rules), 168,120 ( 0.00%) Scope::MacroRules(macro_rules_scope) => match macro_rules_scope.get() { . MacroRulesScope::Binding(binding) => { 86,649 ( 0.00%) Scope::MacroRules(binding.parent_macro_rules_scope) . } . MacroRulesScope::Invocation(invoc_id) => { 5,007 ( 0.00%) Scope::MacroRules(self.invocation_parent_scopes[&invoc_id].macro_rules) . } . MacroRulesScope::Empty => Scope::Module(module, None), . }, . Scope::CrateRoot => match ns { . TypeNS => { . ctxt.adjust(ExpnId::root()); . Scope::ExternPrelude . } . ValueNS | MacroNS => break, . }, . Scope::Module(module, prev_lint_id) => { 529,438 ( 0.00%) use_prelude = !module.no_implicit_prelude; . let derive_fallback_lint_id = match scope_set { . ScopeSet::Late(.., lint_id) => lint_id, . _ => None, . }; 845,577 ( 0.00%) match self.hygienic_lexical_parent(module, &mut ctxt, derive_fallback_lint_id) { . Some((parent_module, lint_id)) => { . Scope::Module(parent_module, lint_id.or(prev_lint_id)) . } . None => { 545,310 ( 0.00%) ctxt.adjust(ExpnId::root()); 362,544 ( 0.00%) match ns { . TypeNS => Scope::ExternPrelude, . ValueNS => Scope::StdLibPrelude, . MacroNS => Scope::RegisteredAttrs, . } . } . } . } . Scope::RegisteredAttrs => Scope::MacroUsePrelude, . Scope::MacroUsePrelude => Scope::StdLibPrelude, . Scope::BuiltinAttrs => break, // nowhere else to search 44,928 ( 0.00%) Scope::ExternPrelude if is_absolute_path => break, . Scope::ExternPrelude => Scope::ToolPrelude, . Scope::ToolPrelude => Scope::StdLibPrelude, 247,816 ( 0.00%) Scope::StdLibPrelude => match ns { . TypeNS => Scope::BuiltinTypes, . ValueNS => break, // nowhere else to search . MacroNS => Scope::BuiltinAttrs, . }, . Scope::BuiltinTypes => break, // nowhere else to search . }; . } . -- line 1911 ---------------------------------------- -- line 1924 ---------------------------------------- . /// let g = || {}; . /// fn g() {} . /// g(); // This resolves to the local variable `g` since it shadows the item. . /// } . /// ``` . /// . /// Invariant: This must only be called during main resolution, not during . /// import resolution. 2,050,370 ( 0.01%) fn resolve_ident_in_lexical_scope( . &mut self, . mut ident: Ident, . ns: Namespace, . parent_scope: &ParentScope<'a>, . record_used_id: Option, . path_span: Span, . ribs: &[Rib<'a>], . ) -> Option> { 410,074 ( 0.00%) assert!(ns == TypeNS || ns == ValueNS); . let orig_ident = ident; 1,435,259 ( 0.00%) if ident.name == kw::Empty { . return Some(LexicalScopeBinding::Res(Res::Err)); . } . let (general_span, normalized_span) = if ident.name == kw::SelfUpper { . // FIXME(jseyfried) improve `Self` hygiene . let empty_span = ident.span.with_ctxt(SyntaxContext::root()); . (empty_span, empty_span) 196,320 ( 0.00%) } else if ns == TypeNS { 497,565 ( 0.00%) let normalized_span = ident.span.normalize_to_macros_2_0(); . (normalized_span, normalized_span) . } else { 484,035 ( 0.00%) (ident.span.normalize_to_macro_rules(), ident.span.normalize_to_macros_2_0()) . }; . ident.span = general_span; . let normalized_ident = Ident { span: normalized_span, ..ident }; . . // Walk backwards up the ribs in scope. . let record_used = record_used_id.is_some(); 615,111 ( 0.00%) let mut module = self.graph_root; . for i in (0..ribs.len()).rev() { . debug!("walk rib\n{:?}", ribs[i].bindings); . // Use the rib kind to determine whether we are resolving parameters . // (macro 2.0 hygiene) or local variables (`macro_rules` hygiene). 1,768,017 ( 0.01%) let rib_ident = if ribs[i].kind.contains_params() { normalized_ident } else { ident }; . if let Some((original_rib_ident_def, res)) = ribs[i].bindings.get_key_value(&rib_ident) . { . // The ident resolves to a type parameter or local variable. 635,784 ( 0.00%) return Some(LexicalScopeBinding::Res(self.validate_res_from_ribs( . i, 105,964 ( 0.00%) rib_ident, 264,910 ( 0.00%) *res, . record_used, . path_span, . *original_rib_ident_def, . ribs, . ))); . } . 10,592,125 ( 0.03%) module = match ribs[i].kind { 353,280 ( 0.00%) ModuleRibKind(module) => module, 144,338 ( 0.00%) MacroDefinition(def) if def == self.macro_def(ident.span.ctxt()) => { . // If an invocation of this macro created `ident`, give up on `ident` . // and switch to `ident`'s source from the macro definition. . ident.span.remove_mark(); . continue; . } . _ => continue, . }; . 1,059,840 ( 0.00%) match module.kind { . ModuleKind::Block(..) => {} // We can see through blocks . _ => break, . } . . let item = self.resolve_ident_in_module_unadjusted( . ModuleOrUniformRoot::Module(module), . ident, . ns, . parent_scope, . record_used, . path_span, . ); . if let Ok(binding) = item { . // The ident resolves to an item. 152,238 ( 0.00%) return Some(LexicalScopeBinding::Item(binding)); . } . } 1,722,253 ( 0.00%) self.early_resolve_ident_in_lexical_scope( . orig_ident, . ScopeSet::Late(ns, module, record_used_id), . parent_scope, . record_used, . record_used, . path_span, . ) . .ok() . .map(LexicalScopeBinding::Item) 1,845,333 ( 0.01%) } . 1,526,657 ( 0.00%) fn hygienic_lexical_parent( . &mut self, . module: Module<'a>, . ctxt: &mut SyntaxContext, . derive_fallback_lint_id: Option, . ) -> Option<(Module<'a>, Option)> { 971,509 ( 0.00%) if !module.expansion.outer_expn_is_descendant_of(*ctxt) { 71,928 ( 0.00%) return Some((self.expn_def_scope(ctxt.remove_mark()), None)); . } . 253,598 ( 0.00%) if let ModuleKind::Block(..) = module.kind { 18,913 ( 0.00%) return Some((module.parent.unwrap().nearest_item_scope(), None)); . } . . // We need to support the next case under a deprecation warning . // ``` . // struct MyStruct; . // ---- begin: this comes from a proc macro derive . // mod implementation_details { . // // Note that `MyStruct` is not in scope here. . // impl SomeTrait for MyStruct { ... } . // } . // ---- end . // ``` . // So we have to fall back to the module's parent during lexical resolution in this case. 107,886 ( 0.00%) if derive_fallback_lint_id.is_some() { 22,143 ( 0.00%) if let Some(parent) = module.parent { . // Inner module is inside the macro, parent module is outside of the macro. 24,300 ( 0.00%) if module.expansion != parent.expansion . && module.expansion.is_descendant_of(parent.expansion) . { . // The macro is a proc macro derive . if let Some(def_id) = module.expansion.expn_data().macro_def_id { . let ext = self.get_macro_by_def_id(def_id); . if ext.builtin_name.is_none() . && ext.macro_kind() == MacroKind::Derive . && parent.expansion.outer_expn_is_descendant_of(*ctxt) -- line 2058 ---------------------------------------- -- line 2060 ---------------------------------------- . return Some((parent, derive_fallback_lint_id)); . } . } . } . } . } . . None 1,387,870 ( 0.00%) } . . fn resolve_ident_in_module( . &mut self, . module: ModuleOrUniformRoot<'a>, . ident: Ident, . ns: Namespace, . parent_scope: &ParentScope<'a>, . record_used: bool, . path_span: Span, . ) -> Result<&'a NameBinding<'a>, Determinacy> { 1,089,426 ( 0.00%) self.resolve_ident_in_module_ext(module, ident, ns, parent_scope, record_used, path_span) . .map_err(|(determinacy, _)| determinacy) . } . 2,422,320 ( 0.01%) fn resolve_ident_in_module_ext( . &mut self, . module: ModuleOrUniformRoot<'a>, . mut ident: Ident, . ns: Namespace, . parent_scope: &ParentScope<'a>, . record_used: bool, . path_span: Span, . ) -> Result<&'a NameBinding<'a>, (Determinacy, Weak)> { . let tmp_parent_scope; . let mut adjusted_parent_scope = parent_scope; . match module { . ModuleOrUniformRoot::Module(m) => { 726,702 ( 0.00%) if let Some(def) = ident.span.normalize_to_macros_2_0_and_adjust(m.expansion) { 47,700 ( 0.00%) tmp_parent_scope = 57,240 ( 0.00%) ParentScope { module: self.expn_def_scope(def), ..*parent_scope }; . adjusted_parent_scope = &tmp_parent_scope; . } . } . ModuleOrUniformRoot::ExternPrelude => { . ident.span.normalize_to_macros_2_0_and_adjust(ExpnId::root()); . } . ModuleOrUniformRoot::CrateRootAndExternPrelude | ModuleOrUniformRoot::CurrentScope => { . // No adjustments . } . } 1,332,286 ( 0.00%) self.resolve_ident_in_module_unadjusted_ext( . module, 242,234 ( 0.00%) ident, . ns, . adjusted_parent_scope, . false, . record_used, . path_span, . ) 847,812 ( 0.00%) } . 202,720 ( 0.00%) fn resolve_crate_root(&mut self, ident: Ident) -> Module<'a> { . debug!("resolve_crate_root({:?})", ident); 20,272 ( 0.00%) let mut ctxt = ident.span.ctxt(); 20,272 ( 0.00%) let mark = if ident.name == kw::DollarCrate { . // When resolving `$crate` from a `macro_rules!` invoked in a `macro`, . // we don't want to pretend that the `macro_rules!` definition is in the `macro` . // as described in `SyntaxContext::apply_mark`, so we ignore prepended opaque marks. . // FIXME: This is only a guess and it doesn't work correctly for `macro_rules!` . // definitions actually produced by `macro` and `macro` definitions produced by . // `macro_rules!`, but at least such configurations are not stable yet. 39,806 ( 0.00%) ctxt = ctxt.normalize_to_macro_rules(); . debug!( . "resolve_crate_root: marks={:?}", . ctxt.marks().into_iter().map(|(i, t)| (i.expn_data(), t)).collect::>() . ); 39,806 ( 0.00%) let mut iter = ctxt.marks().into_iter().rev().peekable(); . let mut result = None; . // Find the last opaque mark from the end if it exists. 92,133 ( 0.00%) while let Some(&(mark, transparency)) = iter.peek() { . if transparency == Transparency::Opaque { . result = Some(mark); . iter.next(); . } else { . break; . } . } . debug!( . "resolve_crate_root: found opaque mark {:?} {:?}", . result, . result.map(|r| r.expn_data()) . ); . // Then find the last semi-transparent mark from the end if it exists. 59,709 ( 0.00%) for (mark, transparency) in iter { . if transparency == Transparency::SemiTransparent { . result = Some(mark); . } else { . break; . } . } . debug!( . "resolve_crate_root: found semi-transparent mark {:?} {:?}", . result, . result.map(|r| r.expn_data()) . ); . result . } else { . debug!("resolve_crate_root: not DollarCrate"); 369 ( 0.00%) ctxt = ctxt.normalize_to_macros_2_0(); 2,583 ( 0.00%) ctxt.adjust(ExpnId::root()) . }; 40,544 ( 0.00%) let module = match mark { 96,205 ( 0.00%) Some(def) => self.expn_def_scope(def), . None => { . debug!( . "resolve_crate_root({:?}): found no mark (ident.span = {:?})", . ident, ident.span . ); 2,062 ( 0.00%) return self.graph_root; . } . }; . let module = self.expect_module( . module.opt_def_id().map_or(LOCAL_CRATE, |def_id| def_id.krate).as_def_id(), . ); . debug!( . "resolve_crate_root({:?}): got module {:?} ({:?}) (ident.span = {:?})", . ident, . module, . module.kind.name(), . ident.span . ); . module 141,904 ( 0.00%) } . 108 ( 0.00%) fn resolve_self(&mut self, ctxt: &mut SyntaxContext, module: Module<'a>) -> Module<'a> { 24 ( 0.00%) let mut module = self.expect_module(module.nearest_parent_mod()); 48 ( 0.00%) while module.span.ctxt().normalize_to_macros_2_0() != *ctxt { . let parent = module.parent.unwrap_or_else(|| self.expn_def_scope(ctxt.remove_mark())); . module = self.expect_module(parent.nearest_parent_mod()); . } . module 108 ( 0.00%) } . . fn resolve_path( . &mut self, . path: &[Segment], . opt_ns: Option, // `None` indicates a module path in import . parent_scope: &ParentScope<'a>, . record_used: bool, . path_span: Span, . crate_lint: CrateLint, . ) -> PathResult<'a> { 5,892 ( 0.00%) self.resolve_path_with_ribs( . path, . opt_ns, . parent_scope, . record_used, . path_span, . crate_lint, . None, . ) . } . 2,633,640 ( 0.01%) fn resolve_path_with_ribs( . &mut self, . path: &[Segment], . opt_ns: Option, // `None` indicates a module path in import . parent_scope: &ParentScope<'a>, . record_used: bool, . path_span: Span, . crate_lint: CrateLint, . ribs: Option<&PerNS>>>, . ) -> PathResult<'a> { 175,576 ( 0.00%) let mut module = None; . let mut allow_super = true; . let mut second_binding = None; . . debug!( . "resolve_path(path={:?}, opt_ns={:?}, record_used={:?}, \ . path_span={:?}, crate_lint={:?})", . path, opt_ns, record_used, path_span, crate_lint, . ); . 1,768,152 ( 0.01%) for (i, &Segment { ident, id, has_generic_args: _ }) in path.iter().enumerate() { . debug!("resolve_path ident {} {:?} {:?}", i, ident, id); 2,011,960 ( 0.01%) let record_segment_res = |this: &mut Self, res| { 538,500 ( 0.00%) if record_used { 860,512 ( 0.00%) if let Some(id) = id { 344,200 ( 0.00%) if !this.partial_res_map.contains_key(&id) { 328,484 ( 0.00%) assert!(id != ast::DUMMY_NODE_ID, "Trying to resolve dummy id"); 656,968 ( 0.00%) this.record_partial_res(id, PartialRes::new(res)); . } . } . } 718,000 ( 0.00%) }; . 748,544 ( 0.00%) let is_last = i == path.len() - 1; 1,473,460 ( 0.00%) let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS }; 294,692 ( 0.00%) let name = ident.name; . 481,504 ( 0.00%) allow_super &= ns == TypeNS && (name == kw::SelfLower || name == kw::Super); . . if ns == TypeNS { 373,624 ( 0.00%) if allow_super && name == kw::Super { 24 ( 0.00%) let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0(); 12 ( 0.00%) let self_module = match i { 24 ( 0.00%) 0 => Some(self.resolve_self(&mut ctxt, parent_scope.module)), . _ => match module { . Some(ModuleOrUniformRoot::Module(module)) => Some(module), . _ => None, . }, . }; . if let Some(self_module) = self_module { 18 ( 0.00%) if let Some(parent) = self_module.parent { 30 ( 0.00%) module = Some(ModuleOrUniformRoot::Module( 12 ( 0.00%) self.resolve_self(&mut ctxt, parent), . )); . continue; . } . } . let msg = "there are too many leading `super` keywords".to_string(); . return PathResult::Failed { . span: ident.span, . label: msg, . suggestion: None, . is_error_from_last_segment: false, . }; . } 373,612 ( 0.00%) if i == 0 { 318,591 ( 0.00%) if name == kw::SelfLower { . let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0(); . module = Some(ModuleOrUniformRoot::Module( . self.resolve_self(&mut ctxt, parent_scope.module), . )); . continue; . } . if name == kw::PathRoot && ident.span.rust_2018() { . module = Some(ModuleOrUniformRoot::ExternPrelude); -- line 2296 ---------------------------------------- -- line 2298 ---------------------------------------- . } . if name == kw::PathRoot && ident.span.rust_2015() && self.session.rust_2018() { . // `::a::b` from 2015 macro on 2018 global edition . module = Some(ModuleOrUniformRoot::CrateRootAndExternPrelude); . continue; . } . if name == kw::PathRoot || name == kw::Crate || name == kw::DollarCrate { . // `::a::b`, `crate::a::b` or `$crate::a::b` 36,440 ( 0.00%) module = Some(ModuleOrUniformRoot::Module(self.resolve_crate_root(ident))); . continue; . } . } . } . . // Report special messages for path segment keywords in wrong positions. 1,440,128 ( 0.00%) if ident.is_path_segment_keyword() && i != 0 { . let name_str = if name == kw::PathRoot { . "crate root".to_string() . } else { . format!("`{}`", name) . }; . let label = if i == 1 && path[0].ident.name == kw::PathRoot { . format!("global paths cannot start with {}", name_str) . } else { -- line 2321 ---------------------------------------- -- line 2328 ---------------------------------------- . is_error_from_last_segment: false, . }; . } . . enum FindBindingResult<'a> { . Binding(Result<&'a NameBinding<'a>, Determinacy>), . PathResult(PathResult<'a>), . } 9,138,452 ( 0.03%) let find_binding_in_ns = |this: &mut Self, ns| { 1,261,430 ( 0.00%) let binding = if let Some(module) = module { . this.resolve_ident_in_module( . module, 357,354 ( 0.00%) ident, . ns, . parent_scope, 238,236 ( 0.00%) record_used, 119,118 ( 0.00%) path_span, . ) 997,944 ( 0.00%) } else if ribs.is_none() || opt_ns.is_none() || opt_ns == Some(MacroNS) { . let scopes = ScopeSet::All(ns, opt_ns.is_none()); 3,468 ( 0.00%) this.early_resolve_ident_in_lexical_scope( 612 ( 0.00%) ident, . scopes, 204 ( 0.00%) parent_scope, 408 ( 0.00%) record_used, . record_used, 204 ( 0.00%) path_span, . ) . } else { 665,024 ( 0.00%) let record_used_id = if record_used { 112,394 ( 0.00%) crate_lint.node_id().or(Some(CRATE_NODE_ID)) . } else { . None . }; 2,406,348 ( 0.01%) match this.resolve_ident_in_lexical_scope( 498,768 ( 0.00%) ident, . ns, 166,256 ( 0.00%) parent_scope, . record_used_id, 332,512 ( 0.00%) path_span, . &ribs.unwrap()[ns], . ) { . // we found a locally-imported or available item/module 292,284 ( 0.00%) Some(LexicalScopeBinding::Item(binding)) => Ok(binding), . // we found a local variable or type param . Some(LexicalScopeBinding::Res(res)) 87,492 ( 0.00%) if opt_ns == Some(TypeNS) || opt_ns == Some(ValueNS) => . { 393,714 ( 0.00%) record_segment_res(this, res); 349,968 ( 0.00%) return FindBindingResult::PathResult(PathResult::NonModule( 306,222 ( 0.00%) PartialRes::with_unresolved_segments(res, path.len() - 1), . )); . } 75,246 ( 0.00%) _ => Err(Determinacy::determined(record_used)), . } . }; 1,692,824 ( 0.00%) FindBindingResult::Binding(binding) 2,284,624 ( 0.01%) }; 1,999,032 ( 0.01%) let binding = match find_binding_in_ns(self, ns) { 612,444 ( 0.00%) FindBindingResult::PathResult(x) => return x, . FindBindingResult::Binding(binding) => binding, . }; 563,151 ( 0.00%) match binding { . Ok(binding) => { 1,076,665 ( 0.00%) if i == 1 { . second_binding = Some(binding); . } . let res = binding.res(); 2,152,610 ( 0.01%) let maybe_assoc = opt_ns != Some(MacroNS) && PathSource::Type.is_expected(res); . if let Some(next_module) = binding.module() { 271,508 ( 0.00%) module = Some(ModuleOrUniformRoot::Module(next_module)); 1,221,786 ( 0.00%) record_segment_res(self, res); 557,053 ( 0.00%) } else if res == Res::ToolMod && i + 1 != path.len() { . if binding.is_import() { . self.session . .struct_span_err( . ident.span, . "cannot use a tool module through an import", . ) . .span_note(binding.span, "the tool module imported here") . .emit(); . } . let res = Res::NonMacroAttr(NonMacroAttrKind::Tool); . return PathResult::NonModule(PartialRes::new(res)); 397,895 ( 0.00%) } else if res == Res::Err { . return PathResult::NonModule(PartialRes::new(Res::Err)); 238,737 ( 0.00%) } else if opt_ns.is_some() && (is_last || maybe_assoc) { 557,053 ( 0.00%) self.lint_if_path_starts_with_module( 159,158 ( 0.00%) crate_lint, . path, 79,579 ( 0.00%) path_span, . second_binding, . ); 238,737 ( 0.00%) return PathResult::NonModule(PartialRes::with_unresolved_segments( 318,316 ( 0.00%) res, 318,316 ( 0.00%) path.len() - i - 1, . )); . } else { . let label = format!( . "`{}` is {} {}, not a module", . ident, . res.article(), . res.descr(), . ); -- line 2431 ---------------------------------------- -- line 2433 ---------------------------------------- . return PathResult::Failed { . span: ident.span, . label, . suggestion: None, . is_error_from_last_segment: is_last, . }; . } . } 50,164 ( 0.00%) Err(Undetermined) => return PathResult::Indeterminate, . Err(Determined) => { 5,660 ( 0.00%) if let Some(ModuleOrUniformRoot::Module(module)) = module { 5,660 ( 0.00%) if opt_ns.is_some() && !module.is_normal() { 4,239 ( 0.00%) return PathResult::NonModule(PartialRes::with_unresolved_segments( . module.res().unwrap(), 2,826 ( 0.00%) path.len() - i, . )); . } . } . let module_res = match module { . Some(ModuleOrUniformRoot::Module(module)) => module.res(), . _ => None, . }; 32 ( 0.00%) let (label, suggestion) = if module_res == self.graph_root.res() { . let is_mod = |res| matches!(res, Res::Def(DefKind::Mod, _)); . // Don't look up import candidates if this is a speculative resolve . let mut candidates = if record_used { . self.lookup_import_candidates(ident, TypeNS, parent_scope, is_mod) . } else { . Vec::new() . }; . candidates.sort_by_cached_key(|c| { -- line 2463 ---------------------------------------- -- line 2472 ---------------------------------------- . Applicability::MaybeIncorrect, . )), . ) . } else if self.session.edition() == Edition::Edition2015 { . (format!("maybe a missing crate `{}`?", ident), None) . } else { . (format!("could not find `{}` in the crate root", ident), None) . } 4 ( 0.00%) } else if i == 0 { . if ident . .name . .as_str() . .chars() . .next() . .map_or(false, |c| c.is_ascii_uppercase()) . { . // Check whether the name refers to an item in the value namespace. -- line 2488 ---------------------------------------- -- line 2562 ---------------------------------------- . ), . Applicability::MaybeIncorrect, . ) . }) . }, . ) . } . } else { 16 ( 0.00%) let parent = path[i - 1].ident.name; 8 ( 0.00%) let parent = match parent { . // ::foo is mounted at the crate root for 2015, and is the extern . // prelude for 2018+ . kw::PathRoot if self.session.edition() > Edition::Edition2015 => { . "the list of imported crates".to_owned() . } . kw::PathRoot | kw::Crate => "the crate root".to_owned(), . _ => { 18 ( 0.00%) format!("`{}`", parent) . } . }; . 26 ( 0.00%) let mut msg = format!("could not find `{}` in {}", ident, parent); 4 ( 0.00%) if ns == TypeNS || ns == ValueNS { . let ns_to_try = if ns == TypeNS { ValueNS } else { TypeNS }; 8 ( 0.00%) if let FindBindingResult::Binding(Ok(binding)) = 12 ( 0.00%) find_binding_in_ns(self, ns_to_try) . { . let mut found = |what| { . msg = format!( . "expected {}, found {} `{}` in {}", . ns.descr(), . what, . ident, . parent -- line 2595 ---------------------------------------- -- line 2598 ---------------------------------------- . if binding.module().is_some() { . found("module") . } else { . match binding.res() { . def::Res::::Def(kind, id) => found(kind.descr(id)), . _ => found(ns_to_try.descr()), . } . } 2 ( 0.00%) }; . } 6 ( 0.00%) (msg, None) . }; 10 ( 0.00%) return PathResult::Failed { 2 ( 0.00%) span: ident.span, . label, . suggestion, . is_error_from_last_segment: is_last, . }; . } . } . } . 283,294 ( 0.00%) self.lint_if_path_starts_with_module(crate_lint, path, path_span, second_binding); . 154,524 ( 0.00%) PathResult::Module(match module { 51,508 ( 0.00%) Some(module) => module, . None if path.is_empty() => ModuleOrUniformRoot::CurrentScope, . _ => span_bug!(path_span, "resolve_path: non-empty path `{:?}` has no module", path), . }) 1,580,184 ( 0.00%) } . 1,267,320 ( 0.00%) fn lint_if_path_starts_with_module( . &mut self, . crate_lint: CrateLint, . path: &[Segment], . path_span: Span, . second_binding: Option<&NameBinding<'_>>, . ) { 528,050 ( 0.00%) let (diag_id, diag_span) = match crate_lint { . CrateLint::No => return, . CrateLint::SimplePath(id) => (id, path_span), . CrateLint::UsePath { root_id, root_span } => (root_id, root_span), . CrateLint::QPathTrait { qpath_id, qpath_span } => (qpath_id, qpath_span), . }; . 77,366 ( 0.00%) let first_name = match path.get(0) { . // In the 2018 edition this lint is a hard error, so nothing to do 304,200 ( 0.00%) Some(seg) if seg.ident.span.rust_2015() && self.session.rust_2015() => seg.ident.name, . _ => return, . }; . . // We're only interested in `use` paths which should start with . // `{{root}}` currently. . if first_name != kw::PathRoot { . return; . } -- line 2653 ---------------------------------------- -- line 2679 ---------------------------------------- . self.lint_buffer.buffer_lint_with_diagnostic( . lint::builtin::ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE, . diag_id, . diag_span, . "absolute paths must start with `self`, `super`, \ . `crate`, or an external crate name in the 2018 edition", . diag, . ); 844,880 ( 0.00%) } . . // Validate a local resolution (from ribs). . fn validate_res_from_ribs( . &mut self, . rib_index: usize, . rib_ident: Ident, . mut res: Res, . record_used: bool, . span: Span, . original_rib_ident_def: Ident, . all_ribs: &[Rib<'a>], . ) -> Res { . const CG_BUG_STR: &str = "min_const_generics resolve check didn't stop compilation"; . debug!("validate_res_from_ribs({:?})", res); 105,964 ( 0.00%) let ribs = &all_ribs[rib_index + 1..]; . . // An invalid forward use of a generic parameter from a previous default. 211,928 ( 0.00%) if let ForwardGenericParamBanRibKind = all_ribs[rib_index].kind { . if record_used { . let res_error = if rib_ident.name == kw::SelfUpper { . ResolutionError::SelfInGenericParamDefault . } else { . ResolutionError::ForwardDeclaredGenericParam . }; . self.report_error(span, res_error); . } . assert_eq!(res, Res::Err); . return Res::Err; . } . 364,540 ( 0.00%) match res { . Res::Local(_) => { . use ResolutionError::*; 33,165 ( 0.00%) let mut res_err = None; . . for rib in ribs { 221,403 ( 0.00%) match rib.kind { . NormalRibKind . | ClosureOrAsyncRibKind . | ModuleRibKind(..) . | MacroDefinition(..) . | ForwardGenericParamBanRibKind => { . // Nothing to do. Continue. . } . ItemRibKind(_) | FnItemRibKind | AssocItemRibKind => { . // This was an attempt to access an upvar inside a . // named function item. This is not allowed, so we . // report an error. 20,551 ( 0.00%) if record_used { . // We don't immediately trigger a resolve error, because . // we want certain other resolution errors (namely those . // emitted for `ConstantItemRibKind` below) to take . // precedence. . res_err = Some(CannotCaptureDynamicEnvironmentInFnItem); . } . } . ConstantItemRibKind(_, item) => { -- line 2744 ---------------------------------------- -- line 2773 ---------------------------------------- . ConstParamTyRibKind => { . if record_used { . self.report_error(span, ParamInTyOfConstParam(rib_ident.name)); . } . return Res::Err; . } . } . } 37,436 ( 0.00%) if let Some(res_err) = res_err { . self.report_error(span, res_err); . return Res::Err; . } . } . Res::Def(DefKind::TyParam, _) | Res::SelfTy(..) => { . for rib in ribs { 62,818 ( 0.00%) let has_generic_params: HasGenericParams = match rib.kind { . NormalRibKind . | ClosureOrAsyncRibKind . | AssocItemRibKind . | ModuleRibKind(..) . | MacroDefinition(..) . | ForwardGenericParamBanRibKind => { . // Nothing to do. Continue. . continue; . } . 9 ( 0.00%) ConstantItemRibKind(trivial, _) => { . let features = self.session.features_untracked(); . // HACK(min_const_generics): We currently only allow `N` or `{ N }`. 18 ( 0.00%) if !(trivial || features.generic_const_exprs) { . // HACK(min_const_generics): If we encounter `Self` in an anonymous constant . // we can't easily tell if it's generic at this stage, so we instead remember . // this and then enforce the self type to be concrete later on. . if let Res::SelfTy(trait_def, Some((impl_def, _))) = res { 8,878 ( 0.00%) res = Res::SelfTy(trait_def, Some((impl_def, true))); . } else { . if record_used { . self.report_error( . span, . ResolutionError::ParamInNonTrivialAnonConst { . name: rib_ident.name, . is_type: true, . }, -- line 2815 ---------------------------------------- -- line 2912 ---------------------------------------- . ), . ); . } . return Res::Err; . } . } . _ => {} . } 211,928 ( 0.00%) res . } . . fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) { . debug!("(recording res) recording {:?} for {}", resolution, node_id); 702,522 ( 0.00%) if let Some(prev_res) = self.partial_res_map.insert(node_id, resolution) { . panic!("path resolved multiple times ({:?} before, {:?} now)", prev_res, resolution); . } . } . . fn record_pat_span(&mut self, node: NodeId, span: Span) { . debug!("(recording pat) recording {:?} for {:?}", node, span); . self.pat_span_map.insert(node, span); . } . 2,790 ( 0.00%) fn is_accessible_from(&self, vis: ty::Visibility, module: Module<'a>) -> bool { 1,359,474 ( 0.00%) vis.is_accessible_from(module.nearest_parent_mod(), self) 2,511 ( 0.00%) } . . fn set_binding_parent_module(&mut self, binding: &'a NameBinding<'a>, module: Module<'a>) { 41,600 ( 0.00%) if let Some(old_module) = self.binding_parent_modules.insert(PtrKey(binding), module) { . if !ptr::eq(module, old_module) { . span_bug!(binding.span, "parent module is reset for binding"); . } . } . } . . fn disambiguate_macro_rules_vs_modularized( . &self, -- line 2948 ---------------------------------------- -- line 2959 ---------------------------------------- . (Some(macro_rules), Some(modularized)) => { . macro_rules.nearest_parent_mod() == modularized.nearest_parent_mod() . && modularized.is_ancestor_of(macro_rules) . } . _ => false, . } . } . 7 ( 0.00%) fn report_errors(&mut self, krate: &Crate) { . self.report_with_use_injections(krate); . 6 ( 0.00%) for &(span_use, span_def) in &self.macro_expanded_macro_export_errors { . let msg = "macro-expanded `macro_export` macros from the current crate \ . cannot be referred to by absolute paths"; . self.lint_buffer.buffer_lint_with_diagnostic( . lint::builtin::MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS, . CRATE_NODE_ID, . span_use, . msg, . BuiltinLintDiagnostics::MacroExpandedMacroExportsAccessedByAbsolutePaths(span_def), -- line 2978 ---------------------------------------- -- line 2984 ---------------------------------------- . } . . let mut reported_spans = FxHashSet::default(); . for error in &self.privacy_errors { . if reported_spans.insert(error.dedup_span) { . self.report_privacy_error(error); . } . } 8 ( 0.00%) } . . fn report_with_use_injections(&mut self, krate: &Crate) { . for UseError { mut err, candidates, def_id, instead, suggestion } in 10 ( 0.00%) self.use_injections.drain(..) . { . let (span, found_use) = if let Some(def_id) = def_id.as_local() { . UsePlacementFinder::check(krate, self.def_id_to_node_id[def_id]) . } else { . (None, false) . }; . if !candidates.is_empty() { . diagnostics::show_candidates( -- line 3004 ---------------------------------------- -- line 3284 ---------------------------------------- . } . . return; . } . . err.span_suggestion(span, message, String::new(), Applicability::MachineApplicable); . } . 227,380 ( 0.00%) fn extern_prelude_get( . &mut self, . ident: Ident, . speculative: bool, . ) -> Option<&'a NameBinding<'a>> { 113,690 ( 0.00%) if ident.is_path_segment_keyword() { . // Make sure `self`, `super` etc produce an error when passed to here. . return None; . } 204,642 ( 0.00%) self.extern_prelude.get(&ident.normalize_to_macros_2_0()).cloned().and_then(|entry| { 708 ( 0.00%) if let Some(binding) = entry.extern_crate_item { . if !speculative && entry.introduced_by_item { . self.record_use(ident, binding, false); . } . Some(binding) . } else { 708 ( 0.00%) let crate_id = if !speculative { 344 ( 0.00%) let Some(crate_id) = 516 ( 0.00%) self.crate_loader.process_path_extern(ident.name, ident.span) else { return Some(self.dummy_binding); }; . crate_id . } else { 728 ( 0.00%) self.crate_loader.maybe_process_path_extern(ident.name)? . }; . let crate_root = self.expect_module(crate_id.as_def_id()); . Some( . (crate_root, ty::Visibility::Public, DUMMY_SP, LocalExpnId::ROOT) 354 ( 0.00%) .to_name_binding(self.arenas), . ) . } . }) 181,904 ( 0.00%) } . . /// Rustdoc uses this to resolve things in a recoverable way. `ResolutionError<'a>` . /// isn't something that can be returned because it can't be made to live that long, . /// and also it's a private type. Fortunately rustdoc doesn't need to know the error, . /// just that an error occurred. . // FIXME(Manishearth): intra-doc links won't get warned of epoch changes. . pub fn resolve_str_path_error( . &mut self, -- line 3330 ---------------------------------------- -- line 3422 ---------------------------------------- . #[inline] . pub fn opt_span(&self, def_id: DefId) -> Option { . def_id.as_local().map(|def_id| self.definitions.def_span(def_id)) . } . . /// Checks if an expression refers to a function marked with . /// `#[rustc_legacy_const_generics]` and returns the argument index list . /// from the attribute. 398,272 ( 0.00%) pub fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option> { 199,136 ( 0.00%) if let ExprKind::Path(None, path) = &expr.kind { . // Don't perform legacy const generics rewriting if the path already . // has generic arguments. 48,246 ( 0.00%) if path.segments.last().unwrap().args.is_some() { . return None; . } . . let partial_res = self.partial_res_map.get(&expr.id)?; 90,112 ( 0.00%) if partial_res.unresolved_segments() != 0 { . return None; . } . 148,184 ( 0.00%) if let Res::Def(def::DefKind::Fn, def_id) = partial_res.base_res() { . // We only support cross-crate argument rewriting. Uses . // within the same crate should be updated to use the new . // const generics style. 2,138 ( 0.00%) if def_id.is_local() { . return None; . } . . if let Some(v) = self.legacy_const_generic_args.get(&def_id) { . return v.clone(); . } . 11,760 ( 0.00%) let attr = self . .cstore() 3,920 ( 0.00%) .item_attrs_untracked(def_id, self.session) . .find(|a| a.has_name(sym::rustc_legacy_const_generics))?; . let mut ret = Vec::new(); . for meta in attr.meta_item_list()? { . match meta.literal()?.kind { . LitKind::Int(a, _) => ret.push(a as usize), . _ => panic!("invalid arg index"), . } . } . // Cache the lookup to avoid parsing attributes for an iterm multiple times. . self.legacy_const_generic_args.insert(def_id, Some(ret.clone())); . return Some(ret); . } . } . None 448,056 ( 0.00%) } . 7 ( 0.00%) fn resolve_main(&mut self) { 2 ( 0.00%) let module = self.graph_root; . let ident = Ident::with_dummy_span(sym::main); . let parent_scope = &ParentScope::module(module, self); . . let name_binding = match self.resolve_ident_in_module( . ModuleOrUniformRoot::Module(module), . ident, . ValueNS, . parent_scope, -- line 3483 ---------------------------------------- -- line 3490 ---------------------------------------- . . let res = name_binding.res(); . let is_import = name_binding.is_import(); . let span = name_binding.span; . if let Res::Def(DefKind::Fn, _) = res { . self.record_use(ident, name_binding, false); . } . self.main_def = Some(MainDefinition { res, is_import, span }); 8 ( 0.00%) } . } . . fn names_to_string(names: &[Symbol]) -> String { . let mut result = String::new(); . for (i, name) in names.iter().filter(|name| **name != kw::PathRoot).enumerate() { . if i > 0 { . result.push_str("::"); . } -- line 3506 ---------------------------------------- -- line 3558 ---------------------------------------- . /// This is the "trait item" from a fully qualified path. For example, . /// we might be resolving `X::Y::Z` from a path like `::Z`. . /// The `path_span` is the span of the to the trait itself (`X::Y`). . QPathTrait { qpath_id: NodeId, qpath_span: Span }, . } . . impl CrateLint { . fn node_id(&self) -> Option { 337,182 ( 0.00%) match *self { . CrateLint::No => None, . CrateLint::SimplePath(id) . | CrateLint::UsePath { root_id: id, .. } . | CrateLint::QPathTrait { qpath_id: id, .. } => Some(id), . } . } . } . . pub fn provide(providers: &mut Providers) { . late::lifetimes::provide(providers); 1 ( 0.00%) } 13,716,718 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/mem/mod.rs -------------------------------------------------------------------------------- Ir -- line 136 ---------------------------------------- . /// [`Box::leak`]: ../../std/boxed/struct.Box.html#method.leak . /// [`Box::into_raw`]: ../../std/boxed/struct.Box.html#method.into_raw . /// [`mem::drop`]: drop . /// [ub]: ../../reference/behavior-considered-undefined.html . #[inline] . #[rustc_const_stable(feature = "const_forget", since = "1.46.0")] . #[stable(feature = "rust1", since = "1.0.0")] . #[cfg_attr(not(test), rustc_diagnostic_item = "mem_forget")] 229,488 ( 0.00%) pub const fn forget(t: T) { 43,560 ( 0.00%) let _ = ManuallyDrop::new(t); 104,000 ( 0.00%) } . . /// Like [`forget`], but also accepts unsized values. . /// . /// This function is just a shim intended to be removed when the `unsized_locals` feature gets . /// stabilized. . #[inline] . #[unstable(feature = "forget_unsized", issue = "none")] . pub fn forget_unsized(t: T) { -- line 154 ---------------------------------------- -- line 324 ---------------------------------------- . /// let y: &[u8] = &x; . /// assert_eq!(13, mem::size_of_val(y)); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_size_of_val", issue = "46571")] . #[cfg_attr(not(test), rustc_diagnostic_item = "mem_size_of_val")] 1,138,996 ( 0.00%) pub const fn size_of_val(val: &T) -> usize { . // SAFETY: `val` is a reference, so it's a valid raw pointer 1,841,743 ( 0.01%) unsafe { intrinsics::size_of_val(val) } 767,640 ( 0.00%) } . . /// Returns the size of the pointed-to value in bytes. . /// . /// This is usually the same as `size_of::()`. However, when `T` *has* no . /// statically-known size, e.g., a slice [`[T]`][slice] or a [trait object], . /// then `size_of_val_raw` can be used to get the dynamically-known size. . /// . /// # Safety -- line 343 ---------------------------------------- -- line 375 ---------------------------------------- . /// assert_eq!(13, unsafe { mem::size_of_val_raw(y) }); . /// ``` . #[inline] . #[must_use] . #[unstable(feature = "layout_for_ptr", issue = "69835")] . #[rustc_const_unstable(feature = "const_size_of_val_raw", issue = "46571")] . pub const unsafe fn size_of_val_raw(val: *const T) -> usize { . // SAFETY: the caller must provide a valid raw pointer 14 ( 0.00%) unsafe { intrinsics::size_of_val(val) } . } . . /// Returns the [ABI]-required minimum alignment of a type. . /// . /// Every reference to a value of the type `T` must be a multiple of this number. . /// . /// This is the alignment used for struct fields. It may be smaller than the preferred alignment. . /// -- line 391 ---------------------------------------- -- line 467 ---------------------------------------- . /// . /// assert_eq!(4, mem::align_of_val(&5i32)); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_align_of_val", issue = "46571")] . #[allow(deprecated)] 24,928 ( 0.00%) pub const fn align_of_val(val: &T) -> usize { . // SAFETY: val is a reference, so it's a valid raw pointer 37,392 ( 0.00%) unsafe { intrinsics::min_align_of_val(val) } 24,928 ( 0.00%) } . . /// Returns the [ABI]-required minimum alignment of the type of the value that `val` points to. . /// . /// Every reference to a value of the type `T` must be a multiple of this number. . /// . /// [ABI]: https://en.wikipedia.org/wiki/Application_binary_interface . /// . /// # Safety -- line 486 ---------------------------------------- -- line 578 ---------------------------------------- . /// } . /// } . /// ``` . #[inline] . #[must_use] . #[stable(feature = "needs_drop", since = "1.21.0")] . #[rustc_const_stable(feature = "const_needs_drop", since = "1.36.0")] . #[rustc_diagnostic_item = "needs_drop"] 21 ( 0.00%) pub const fn needs_drop() -> bool { 63 ( 0.00%) intrinsics::needs_drop::() 84 ( 0.00%) } . . /// Returns the value of type `T` represented by the all-zero byte-pattern. . /// . /// This means that, for example, the padding byte in `(u8, u16)` is not . /// necessarily zeroed. . /// . /// There is no guarantee that an all-zero byte-pattern represents a valid value . /// of some type `T`. For example, the all-zero byte-pattern is not a valid value -- line 596 ---------------------------------------- -- line 694 ---------------------------------------- . /// mem::swap(&mut x, &mut y); . /// . /// assert_eq!(42, x); . /// assert_eq!(5, y); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_swap", issue = "83163")] 30 ( 0.00%) pub const fn swap(x: &mut T, y: &mut T) { . // SAFETY: the raw pointers have been created from safe mutable references satisfying all the . // constraints on `ptr::swap_nonoverlapping_one` . unsafe { 10 ( 0.00%) ptr::swap_nonoverlapping_one(x, y); . } 20 ( 0.00%) } . . /// Replaces `dest` with the default value of `T`, returning the previous `dest` value. . /// . /// * If you want to replace the values of two variables, see [`swap`]. . /// * If you want to replace with a passed value instead of the default value, see [`replace`]. . /// . /// # Examples . /// -- line 716 ---------------------------------------- -- line 759 ---------------------------------------- . /// let mut buffer = Buffer { buf: vec![0, 1] }; . /// assert_eq!(buffer.buf.len(), 2); . /// . /// assert_eq!(buffer.get_and_reset(), vec![0, 1]); . /// assert_eq!(buffer.buf.len(), 0); . /// ``` . #[inline] . #[stable(feature = "mem_take", since = "1.40.0")] 19,800 ( 0.00%) pub fn take(dest: &mut T) -> T { 15,840 ( 0.00%) replace(dest, T::default()) 7,920 ( 0.00%) } . . /// Moves `src` into the referenced `dest`, returning the previous `dest` value. . /// . /// Neither value is dropped. . /// . /// * If you want to replace the values of two variables, see [`swap`]. . /// * If you want to replace with a default value, see [`take`]. . /// -- line 777 ---------------------------------------- -- line 826 ---------------------------------------- . /// assert_eq!(buffer.replace_index(0, 2), 0); . /// assert_eq!(buffer.buf[0], 2); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[must_use = "if you don't need the old value, you can just assign the new value directly"] . #[rustc_const_unstable(feature = "const_replace", issue = "83164")] . #[cfg_attr(not(test), rustc_diagnostic_item = "mem_replace")] 14,429,401 ( 0.04%) pub const fn replace(dest: &mut T, src: T) -> T { . // SAFETY: We read from `dest` but directly write `src` into it afterwards, . // such that the old value is not duplicated. Nothing is dropped and . // nothing here can panic. . unsafe { 17,027,784 ( 0.05%) let result = ptr::read(dest); 190,250,233 ( 0.55%) ptr::write(dest, src); . result . } 4,850,355 ( 0.01%) } . . /// Disposes of a value. . /// . /// This does so by calling the argument's implementation of [`Drop`][drop]. . /// . /// This effectively does nothing for types which implement `Copy`, e.g. . /// integers. Such values are copied and _then_ moved into the function, so the . /// value persists after this function call. -- line 851 ---------------------------------------- -- line 901 ---------------------------------------- . /// . /// println!("x: {}, y: {}", x, y.0); // still available . /// ``` . /// . /// [`RefCell`]: crate::cell::RefCell . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[cfg_attr(not(test), rustc_diagnostic_item = "mem_drop")] 965,744 ( 0.00%) pub fn drop(_x: T) {} . . /// Interprets `src` as having type `&U`, and then reads `src` without moving . /// the contained value. . /// . /// This function will unsafely assume the pointer `src` is valid for [`size_of::`][size_of] . /// bytes by transmuting `&T` to `&U` and then reading the `&U` (except that this is done in a way . /// that is correct even when `&U` makes stricter alignment requirements than `&T`). It will also . /// unsafely create a copy of the contained value instead of moving out of `src`. -- line 917 ---------------------------------------- -- line 947 ---------------------------------------- . /// . /// // The contents of 'foo_array' should not have changed . /// assert_eq!(foo_array, [10]); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_transmute_copy", issue = "83165")] 9,900 ( 0.00%) pub const unsafe fn transmute_copy(src: &T) -> U { . // If U has a higher alignment requirement, src might not be suitably aligned. 3,960 ( 0.00%) if align_of::() > align_of::() { . // SAFETY: `src` is a reference which is guaranteed to be valid for reads. . // The caller must guarantee that the actual transmutation is safe. . unsafe { ptr::read_unaligned(src as *const T as *const U) } . } else { . // SAFETY: `src` is a reference which is guaranteed to be valid for reads. . // We just checked that `src as *const U` was properly aligned. . // The caller must guarantee that the actual transmutation is safe. 3,960 ( 0.00%) unsafe { ptr::read(src as *const T as *const U) } . } 3,960 ( 0.00%) } . . /// Opaque type representing the discriminant of an enum. . /// . /// See the [`discriminant`] function in this module for more information. . #[stable(feature = "discriminant_value", since = "1.21.0")] . pub struct Discriminant(::Discriminant); . . // N.B. These trait implementations cannot be derived because we don't want any bounds on T. -- line 975 ---------------------------------------- -- line 991 ---------------------------------------- . } . } . . #[stable(feature = "discriminant_value", since = "1.21.0")] . impl cmp::Eq for Discriminant {} . . #[stable(feature = "discriminant_value", since = "1.21.0")] . impl hash::Hash for Discriminant { 69,668 ( 0.00%) fn hash(&self, state: &mut H) { . self.0.hash(state); 121,580 ( 0.00%) } . } . . #[stable(feature = "discriminant_value", since = "1.21.0")] . impl fmt::Debug for Discriminant { . fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { . fmt.debug_tuple("Discriminant").field(&self.0).finish() . } . } -- line 1009 ---------------------------------------- -- line 1031 ---------------------------------------- . /// assert_eq!(mem::discriminant(&Foo::A("bar")), mem::discriminant(&Foo::A("baz"))); . /// assert_eq!(mem::discriminant(&Foo::B(1)), mem::discriminant(&Foo::B(2))); . /// assert_ne!(mem::discriminant(&Foo::B(3)), mem::discriminant(&Foo::C(3))); . /// ``` . #[stable(feature = "discriminant_value", since = "1.21.0")] . #[rustc_const_unstable(feature = "const_discriminant", issue = "69821")] . #[cfg_attr(not(test), rustc_diagnostic_item = "mem_discriminant")] . pub const fn discriminant(v: &T) -> Discriminant { 362,625 ( 0.00%) Discriminant(intrinsics::discriminant_value(v)) . } . . /// Returns the number of variants in the enum type `T`. . /// . /// If `T` is not an enum, calling this function will not result in undefined behavior, but the . /// return value is unspecified. Equally, if `T` is an enum with more variants than `usize::MAX` . /// the return value is unspecified. Uninhabited variants will be counted. . /// -- line 1047 ---------------------------------------- 7,528,202 ( 0.02%) -------------------------------------------------------------------------------- -- 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}; . 69,982 ( 0.00%) #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub enum CommentKind { . Line, . Block, . } . 4,232 ( 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. 581,744 ( 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, . } . 11,319 ( 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. 136,384 ( 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 { 58,305 ( 0.00%) fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 104,949 ( 0.00%) let Lit { kind, symbol, suffix } = *self; . match kind { . Byte => write!(f, "b'{}'", symbol)?, . Char => write!(f, "'{}'", symbol)?, 25,665 ( 0.00%) Str => write!(f, "\"{}\"", symbol)?, . StrRaw(n) => write!( . f, . "r{delim}\"{string}\"{delim}", . delim = "#".repeat(n as usize), . string = symbol . )?, 2,253 ( 0.00%) ByteStr => write!(f, "b\"{}\"", symbol)?, . ByteStrRaw(n) => write!( . f, . "br{delim}\"{string}\"{delim}", . delim = "#".repeat(n as usize), . string = symbol . )?, 7,065 ( 0.00%) Integer | Float | Bool | Err => write!(f, "{}", symbol)?, . } . 25,680 ( 0.00%) if let Some(suffix) = suffix { 8,253 ( 0.00%) write!(f, "{}", suffix)?; . } . . Ok(()) 58,305 ( 0.00%) } . } . . impl LitKind { . /// An English article for the literal token kind. . pub fn article(self) -> &'static str { . match self { . Integer | Err => "an", . _ => "a", -- line 113 ---------------------------------------- -- line 123 ---------------------------------------- . Float => "float", . Str | StrRaw(..) => "string", . ByteStr | ByteStrRaw(..) => "byte string", . Err => "error", . } . } . . crate fn may_have_suffix(self) -> bool { 2,358 ( 0.00%) matches!(self, Integer | Float | Err) . } . } . . impl Lit { . pub fn new(kind: LitKind, symbol: Symbol, suffix: Option) -> Lit { . Lit { kind, symbol, suffix } 152,994 ( 0.00%) } . } . 35,480 ( 0.00%) pub fn ident_can_begin_expr(name: Symbol, span: Span, is_raw: bool) -> bool { 62,090 ( 0.00%) let ident_token = Token::new(Ident(name, is_raw), span); . 17,742 ( 0.00%) !ident_token.is_reserved_ident() . || ident_token.is_path_segment_keyword() . || [ . kw::Async, . kw::Do, . kw::Box, . kw::Break, . kw::Const, . kw::Continue, -- line 152 ---------------------------------------- -- line 161 ---------------------------------------- . kw::True, . kw::Try, . kw::Unsafe, . kw::While, . kw::Yield, . kw::Static, . ] . .contains(&name) 44,350 ( 0.00%) } . . fn ident_can_begin_type(name: Symbol, span: Span, is_raw: bool) -> bool { 90,678 ( 0.00%) let ident_token = Token::new(Ident(name, is_raw), span); . 36,190 ( 0.00%) !ident_token.is_reserved_ident() . || ident_token.is_path_segment_keyword() . || [kw::Underscore, kw::For, kw::Impl, kw::Fn, kw::Unsafe, kw::Extern, kw::Typeof, kw::Dyn] . .contains(&name) . } . 97,380,603 ( 0.28%) #[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, 751,584 ( 0.00%) BinOp(BinOpToken), 84 ( 0.00%) BinOpEq(BinOpToken), . . /* Structural symbols */ . At, . Dot, . DotDot, . DotDotDot, . DotDotEq, . Comma, -- line 203 ---------------------------------------- -- line 208 ---------------------------------------- . LArrow, . FatArrow, . Pound, . Dollar, . Question, . /// Used by proc macros for representing lifetimes, not generated by lexer right now. . SingleQuote, . /// An opening delimiter (e.g., `{`). 1,398,798 ( 0.00%) OpenDelim(DelimToken), . /// A closing delimiter (e.g., `}`). 352,254 ( 0.00%) CloseDelim(DelimToken), . . /* Literals */ 125,709 ( 0.00%) Literal(Lit), . . /// Identifier token. . /// Do not forget about `NtIdent` when you want to match on identifiers. . /// It's recommended to use `Token::(ident,uninterpolate,uninterpolated_span)` to . /// treat regular and interpolated identifiers in the same way. 1,242,280 ( 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. 51,879 ( 0.00%) Lifetime(Symbol), . 13,816 ( 0.00%) Interpolated(Lrc), . . /// A doc comment token. . /// `Symbol` is the doc comment's data excluding its "quotes" (`///`, `/**`, etc) . /// similarly to symbols in string literal tokens. 32,109 ( 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); . 5,816,149 ( 0.02%) #[derive(Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub struct Token { 110,778 ( 0.00%) pub kind: TokenKind, 38 ( 0.00%) pub span: Span, . } . . impl TokenKind { . pub fn lit(kind: LitKind, symbol: Symbol, suffix: Option) -> TokenKind { . Literal(Lit::new(kind, symbol, suffix)) 13,930 ( 0.00%) } . . // An approximation to proc-macro-style single-character operators used by rustc parser. . // If the operator token can be broken into two tokens, the first of which is single-character, . // then this function performs that operation, otherwise it returns `None`. 94,577 ( 0.00%) pub fn break_two_token_op(&self) -> Option<(TokenKind, TokenKind)> { 379,775 ( 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), 94,414 ( 0.00%) _ => return None, . }) 94,577 ( 0.00%) } . . /// Returns tokens that are likely to be typed accidentally instead of the current token. . /// Enables better error recovery when the wrong token is found. . pub fn similar_tokens(&self) -> Option> { . match *self { . Comma => Some(vec![Dot, Lt, Semi]), . Semi => Some(vec![Colon, Comma]), . FatArrow => Some(vec![Eq, RArrow]), . _ => None, . } . } . . pub fn should_end_const_arg(&self) -> bool { 47,226 ( 0.00%) matches!(self, Gt | Ge | BinOp(Shr) | BinOpEq(Shr)) 11,562 ( 0.00%) } . } . . impl Token { 115,426 ( 0.00%) pub fn new(kind: TokenKind, span: Span) -> Self { 657,280 ( 0.00%) Token { kind, span } 115,426 ( 0.00%) } . . /// Some token that will be thrown away later. 71,690 ( 0.00%) pub fn dummy() -> Self { . Token::new(TokenKind::Question, DUMMY_SP) 71,690 ( 0.00%) } . . /// Recovers a `Token` from an `Ident`. This creates a raw identifier if necessary. . pub fn from_ast_ident(ident: Ident) -> Self { 30,040 ( 0.00%) Token::new(Ident(ident.name, ident.is_raw_guess()), ident.span) . } . . /// Return this token by value and leave a dummy token in its place. 30,510 ( 0.00%) pub fn take(&mut self) -> Self { . mem::replace(self, Token::dummy()) 30,510 ( 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 { 6,176 ( 0.00%) match &self.kind { . Interpolated(nt) => nt.span(), 3,088 ( 0.00%) _ => self.span, . } 3,088 ( 0.00%) } . . pub fn is_op(&self) -> bool { 91,530 ( 0.00%) !matches!( 30,510 ( 0.00%) self.kind, . OpenDelim(..) . | CloseDelim(..) . | Literal(..) . | DocComment(..) . | Ident(..) . | Lifetime(..) . | Interpolated(..) . | Eof . ) 30,510 ( 0.00%) } . . pub fn is_like_plus(&self) -> bool { 323,873 ( 0.00%) matches!(self.kind, BinOp(Plus) | BinOpEq(Plus)) 64,673 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of an expression. 8,921 ( 0.00%) pub fn can_begin_expr(&self) -> bool { 44,605 ( 0.00%) match self.uninterpolate().kind { 79,830 ( 0.00%) Ident(name, is_raw) => 26,610 ( 0.00%) ident_can_begin_expr(name, self.span, is_raw), // value name or keyword . OpenDelim(..) | // tuple, array or block . Literal(..) | // literal . Not | // operator not . BinOp(Minus) | // unary minus . BinOp(Star) | // dereference . BinOp(Or) | OrOr | // closure . BinOp(And) | // reference . AndAnd | // double reference . // DotDotDot is no longer supported, but we need some way to display the error . DotDot | DotDotDot | DotDotEq | // range notation . Lt | BinOp(Shl) | // associated path . ModSep | // global path . Lifetime(..) | // labeled loop . Pound => true, // expression attributes 48 ( 0.00%) Interpolated(ref nt) => matches!(**nt, NtLiteral(..) | . NtExpr(..) | . NtBlock(..) | . NtPath(..)), . _ => false, . } 17,842 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of a type. 75,332 ( 0.00%) pub fn can_begin_type(&self) -> bool { 110,528 ( 0.00%) match self.uninterpolate().kind { 136,017 ( 0.00%) Ident(name, is_raw) => 15,113 ( 0.00%) ident_can_begin_type(name, self.span, is_raw), // type name or keyword . OpenDelim(Paren) | // tuple . OpenDelim(Bracket) | // array . Not | // never . BinOp(Star) | // raw pointer . BinOp(And) | // reference . AndAnd | // double reference . Question | // maybe bound in trait object . Lifetime(..) | // lifetime bound in trait object . Lt | BinOp(Shl) | // associated path . ModSep => true, // global path 22 ( 0.00%) Interpolated(ref nt) => matches!(**nt, NtTy(..) | NtPath(..)), . _ => false, . } 112,998 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of a const param. . pub fn can_begin_const_arg(&self) -> bool { 60,330 ( 0.00%) match self.kind { . OpenDelim(Brace) => true, 16 ( 0.00%) Interpolated(ref nt) => matches!(**nt, NtExpr(..) | NtBlock(..) | NtLiteral(..)), 12,064 ( 0.00%) _ => self.can_begin_literal_maybe_minus(), . } 2 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of a generic bound. . pub fn can_begin_bound(&self) -> bool { . self.is_path_start() . || self.is_lifetime() . || self.is_keyword(kw::For) . || self == &Question . || self == &OpenDelim(Paren) -- line 421 ---------------------------------------- -- line 427 ---------------------------------------- . } . . /// Returns `true` if the token is any literal, a minus (which can prefix a literal, . /// for example a '-42', or one of the boolean idents). . /// . /// In other words, would this token be a valid start of `parse_literal_maybe_minus`? . /// . /// Keep this in sync with and `Lit::from_token`, excluding unary negation. 12,725 ( 0.00%) pub fn can_begin_literal_maybe_minus(&self) -> bool { 126,581 ( 0.00%) match self.uninterpolate().kind { . Literal(..) | BinOp(Minus) => true, 49,408 ( 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, . } 25,450 ( 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. 123,847 ( 0.00%) pub fn uninterpolate(&self) -> Cow<'_, Token> { 7,615,975 ( 0.02%) match &self.kind { 31,440 ( 0.00%) Interpolated(nt) => match **nt { 2,386 ( 0.00%) NtIdent(ident, is_raw) => { 5,965 ( 0.00%) Cow::Owned(Token::new(Ident(ident.name, is_raw), ident.span)) . } . NtLifetime(ident) => Cow::Owned(Token::new(Lifetime(ident.name), ident.span)), . _ => Cow::Borrowed(self), . }, . _ => Cow::Borrowed(self), . } 123,847 ( 0.00%) } . . /// Returns an identifier if this token is an identifier. 716,409 ( 0.00%) pub fn ident(&self) -> Option<(Ident, /* is_raw */ bool)> { . let token = self.uninterpolate(); 5,255,461 ( 0.02%) match token.kind { 25,256,168 ( 0.07%) Ident(name, is_raw) => Some((Ident::new(name, token.span), is_raw)), . _ => None, . } 5,922,099 ( 0.02%) } . . /// Returns a lifetime identifier if this token is a lifetime. 24,349 ( 0.00%) pub fn lifetime(&self) -> Option { . let token = self.uninterpolate(); 130,794 ( 0.00%) match token.kind { 80,512 ( 0.00%) Lifetime(name) => Some(Ident::new(name, token.span)), . _ => None, . } 170,443 ( 0.00%) } . . /// Returns `true` if the token is an identifier. . pub fn is_ident(&self) -> bool { . self.ident().is_some() 74,026 ( 0.00%) } . . /// Returns `true` if the token is a lifetime. 41,048 ( 0.00%) pub fn is_lifetime(&self) -> bool { . self.lifetime().is_some() 82,096 ( 0.00%) } . . /// Returns `true` if the token is an identifier whose name is the given . /// string slice. 60,016 ( 0.00%) pub fn is_ident_named(&self, name: Symbol) -> bool { . self.ident().map_or(false, |(ident, _)| ident.name == name) 120,032 ( 0.00%) } . . /// Returns `true` if the token is an interpolated path. . fn is_path(&self) -> bool { 509,376 ( 0.00%) if let Interpolated(ref nt) = self.kind { 44 ( 0.00%) if let NtPath(..) = **nt { . return true; . } . } . false . } . . /// Would `maybe_whole_expr` in `parser.rs` return `Ok(..)`? . /// That is, is this a pre-parsed expression dropped into the token stream -- line 516 ---------------------------------------- -- line 522 ---------------------------------------- . } . } . . false . } . . // Is the token an interpolated block (`$b:block`)? . pub fn is_whole_block(&self) -> bool { 13,312 ( 0.00%) if let Interpolated(ref nt) = self.kind { . if let NtBlock(..) = **nt { . return true; . } . } . false 6,656 ( 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,686 ( 0.00%) pub fn is_qpath_start(&self) -> bool { 268,918 ( 0.00%) self == &Lt || self == &BinOp(Shl) . } . 512,464 ( 0.00%) pub fn is_path_start(&self) -> bool { 758,622 ( 0.00%) self == &ModSep . || self.is_qpath_start() . || self.is_path() . || self.is_path_segment_keyword() 122,409 ( 0.00%) || self.is_ident() && !self.is_reserved_ident() 640,580 ( 0.00%) } . . /// Returns `true` if the token is a given keyword, `kw`. 1,383,081 ( 0.00%) pub fn is_keyword(&self, kw: Symbol) -> bool { . self.is_non_raw_ident_where(|id| id.name == kw) 2,766,162 ( 0.01%) } . 26,988 ( 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. 9,336 ( 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. 9,336 ( 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. 9,336 ( 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`. 26,992 ( 0.00%) pub fn is_bool_lit(&self) -> bool { 53,984 ( 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. 4,308 ( 0.00%) pub fn is_non_raw_ident_where(&self, pred: impl FnOnce(Ident) -> bool) -> bool { 10,081,743 ( 0.03%) match self.ident() { 122,158 ( 0.00%) Some((id, false)) => pred(id), . _ => false, . } 5,385 ( 0.00%) } . 1,183,340 ( 0.00%) pub fn glue(&self, joint: &Token) -> Option { 591,670 ( 0.00%) let kind = match self.kind { 44,375 ( 0.00%) Eq => match joint.kind { . Eq => EqEq, . Gt => FatArrow, . _ => return None, . }, 20 ( 0.00%) Lt => match joint.kind { . Eq => Le, . Lt => BinOp(Shl), . Le => BinOpEq(Shl), . BinOp(Minus) => LArrow, . _ => return None, . }, 3,976 ( 0.00%) Gt => match joint.kind { . Eq => Ge, . Gt => BinOp(Shr), . Ge => BinOpEq(Shr), . _ => return None, . }, . Not => match joint.kind { . Eq => Ne, . _ => return None, . }, 24,517 ( 0.00%) BinOp(op) => match joint.kind { . Eq => BinOpEq(op), . BinOp(And) if op == And => AndAnd, 1 ( 0.00%) BinOp(Or) if op == Or => OrOr, 3,947 ( 0.00%) Gt if op == Minus => RArrow, . _ => return None, . }, 21 ( 0.00%) Dot => match joint.kind { . Dot => DotDot, . DotDot => DotDotDot, . _ => return None, . }, . DotDot => match joint.kind { . Dot => DotDotDot, . Eq => DotDotEq, . _ => return None, . }, 184,982 ( 0.00%) Colon => match joint.kind { . Colon => ModSep, . _ => return None, . }, 22,484 ( 0.00%) SingleQuote => match joint.kind { 50,589 ( 0.00%) 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, . }; . 1,444,183 ( 0.00%) Some(Token::new(kind, self.span.to(joint.span))) 1,065,006 ( 0.00%) } . } . . impl PartialEq for Token { . fn eq(&self, rhs: &TokenKind) -> bool { 4,624,864 ( 0.01%) self.kind == *rhs . } . } . 315 ( 0.00%) #[derive(Clone, Encodable, Decodable)] . /// For interpolation during macro expansion. . pub enum Nonterminal { . NtItem(P), . NtBlock(P), . NtStmt(ast::Stmt), . NtPat(P), 90 ( 0.00%) NtExpr(P), . NtTy(P), . NtIdent(Ident, /* is_raw */ bool), . NtLifetime(Ident), . NtLiteral(P), . /// Stuff inside brackets for attributes . NtMeta(P), . NtPath(ast::Path), . NtVis(ast::Visibility), -- line 686 ---------------------------------------- -- line 711 ---------------------------------------- . Path, . Vis, . TT, . } . . impl NonterminalKind { . /// The `edition` closure is used to get the edition for the given symbol. Doing . /// `span.edition()` is expensive, so we do it lazily. 2,940 ( 0.00%) pub fn from_symbol( . symbol: Symbol, . edition: impl FnOnce() -> Edition, . ) -> Option { 5,976 ( 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, . }) 2,940 ( 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 ---------------------------------------- 28,963,170 ( 0.08%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/traversal.rs -------------------------------------------------------------------------------- Ir -- line 23 ---------------------------------------- . pub struct Preorder<'a, 'tcx> { . body: &'a Body<'tcx>, . visited: BitSet, . worklist: Vec, . root_is_start_block: bool, . } . . impl<'a, 'tcx> Preorder<'a, 'tcx> { 404,110 ( 0.00%) pub fn new(body: &'a Body<'tcx>, root: BasicBlock) -> Preorder<'a, 'tcx> { 40,411 ( 0.00%) let worklist = vec![root]; . 121,233 ( 0.00%) Preorder { . body, . visited: BitSet::new_empty(body.basic_blocks().len()), 161,644 ( 0.00%) worklist, . root_is_start_block: root == START_BLOCK, . } 363,699 ( 0.00%) } . } . 46,120 ( 0.00%) pub fn preorder<'a, 'tcx>(body: &'a Body<'tcx>) -> Preorder<'a, 'tcx> { 150,226 ( 0.00%) Preorder::new(body, START_BLOCK) 69,180 ( 0.00%) } . . impl<'a, 'tcx> Iterator for Preorder<'a, 'tcx> { . type Item = (BasicBlock, &'a BasicBlockData<'tcx>); . 7,471,662 ( 0.02%) fn next(&mut self) -> Option<(BasicBlock, &'a BasicBlockData<'tcx>)> { 987,466 ( 0.00%) while let Some(idx) = self.worklist.pop() { 987,466 ( 0.00%) if !self.visited.insert(idx) { . continue; . } . 638,831 ( 0.00%) let data = &self.body[idx]; . 3,194,155 ( 0.01%) if let Some(ref term) = data.terminator { . self.worklist.extend(term.successors()); . } . . return Some((idx, data)); . } . . None 6,113,178 ( 0.02%) } . . fn size_hint(&self) -> (usize, Option) { . // All the blocks, minus the number of blocks we've visited. . let upper = self.body.basic_blocks().len() - self.visited.count(); . . let lower = if self.root_is_start_block { . // We will visit all remaining blocks exactly once. . upper -- line 74 ---------------------------------------- -- line 101 ---------------------------------------- . pub struct Postorder<'a, 'tcx> { . body: &'a Body<'tcx>, . visited: BitSet, . visit_stack: Vec<(BasicBlock, Successors<'a>)>, . root_is_start_block: bool, . } . . impl<'a, 'tcx> Postorder<'a, 'tcx> { 379,029 ( 0.00%) pub fn new(body: &'a Body<'tcx>, root: BasicBlock) -> Postorder<'a, 'tcx> { . let mut po = Postorder { . body, . visited: BitSet::new_empty(body.basic_blocks().len()), . visit_stack: Vec::new(), . root_is_start_block: root == START_BLOCK, . }; . . let data = &po.body[root]; . 379,029 ( 0.00%) if let Some(ref term) = data.terminator { . po.visited.insert(root); 216,588 ( 0.00%) po.visit_stack.push((root, term.successors())); 108,294 ( 0.00%) po.traverse_successor(); . } . . po 487,323 ( 0.00%) } . 6,469,358 ( 0.02%) fn traverse_successor(&mut self) { . // This is quite a complex loop due to 1. the borrow checker not liking it much . // and 2. what exactly is going on is not clear . // . // It does the actual traversal of the graph, while the `next` method on the iterator . // just pops off of the stack. `visit_stack` is a stack containing pairs of nodes and . // iterators over the successors of those nodes. Each iteration attempts to get the next . // node from the top of the stack, then pushes that node and an iterator over the . // successors to the top of the stack. This loop only grows `visit_stack`, stopping when -- line 136 ---------------------------------------- -- line 169 ---------------------------------------- . // . // Now that the top of the stack has no successors we can traverse, each item will . // be popped off during iteration until we get back to `A`. This yields [E, D, B]. . // . // When we yield `B` and call `traverse_successor`, we push `C` to the stack, but . // since we've already visited `E`, that child isn't added to the stack. The last . // two iterations yield `C` and finally `A` for a final traversal of [E, D, B, C, A] . loop { 6,576,255 ( 0.02%) let bb = if let Some(&mut (_, ref mut iter)) = self.visit_stack.last_mut() { 3,911,967 ( 0.01%) if let Some(&bb) = iter.next() { . bb . } else { . break; . } . } else { . break; . }; . 1,303,989 ( 0.00%) if self.visited.insert(bb) { 5,711,300 ( 0.02%) if let Some(term) = &self.body[bb].terminator { 3,263,600 ( 0.01%) self.visit_stack.push((bb, term.successors())); . } . } . } 7,393,552 ( 0.02%) } . } . 2,624 ( 0.00%) pub fn postorder<'a, 'tcx>(body: &'a Body<'tcx>) -> Postorder<'a, 'tcx> { 2,624 ( 0.00%) Postorder::new(body, START_BLOCK) 3,936 ( 0.00%) } . . impl<'a, 'tcx> Iterator for Postorder<'a, 'tcx> { . type Item = (BasicBlock, &'a BasicBlockData<'tcx>); . 8,196 ( 0.00%) fn next(&mut self) -> Option<(BasicBlock, &'a BasicBlockData<'tcx>)> { . let next = self.visit_stack.pop(); 870,047 ( 0.00%) if next.is_some() { 1,687,259 ( 0.00%) self.traverse_successor(); . } . 870,047 ( 0.00%) next.map(|(bb, _)| (bb, &self.body[bb])) 13,660 ( 0.00%) } . 6,570 ( 0.00%) fn size_hint(&self) -> (usize, Option) { . // All the blocks, minus the number of blocks we've visited. 176,314 ( 0.00%) let upper = self.body.basic_blocks().len() - self.visited.count(); . 176,314 ( 0.00%) let lower = if self.root_is_start_block { . // We will visit all remaining blocks exactly once. . upper . } else { . self.visit_stack.len() . }; . 3,942 ( 0.00%) (lower, Some(upper)) 9,198 ( 0.00%) } . } . . /// Reverse postorder traversal of a graph . /// . /// Reverse postorder is the reverse order of a postorder traversal. . /// This is different to a preorder traversal and represents a natural . /// linearization of control-flow. . /// -- line 232 ---------------------------------------- -- line 253 ---------------------------------------- . pub struct ReversePostorder<'a, 'tcx> { . body: &'a Body<'tcx>, . blocks: Vec, . idx: usize, . } . . impl<'a, 'tcx> ReversePostorder<'a, 'tcx> { . pub fn new(body: &'a Body<'tcx>, root: BasicBlock) -> ReversePostorder<'a, 'tcx> { 105,670 ( 0.00%) let blocks: Vec<_> = Postorder::new(body, root).map(|(bb, _)| bb).collect(); . 52,835 ( 0.00%) let len = blocks.len(); . 264,175 ( 0.00%) ReversePostorder { body, blocks, idx: len } . } . } . 317,010 ( 0.00%) pub fn reverse_postorder<'a, 'tcx>(body: &'a Body<'tcx>) -> ReversePostorder<'a, 'tcx> { . ReversePostorder::new(body, START_BLOCK) 264,175 ( 0.00%) } . . impl<'a, 'tcx> Iterator for ReversePostorder<'a, 'tcx> { . type Item = (BasicBlock, &'a BasicBlockData<'tcx>); . 921,462 ( 0.00%) fn next(&mut self) -> Option<(BasicBlock, &'a BasicBlockData<'tcx>)> { 3,685,848 ( 0.01%) if self.idx == 0 { . return None; . } 1,737,254 ( 0.01%) self.idx -= 1; . . self.blocks.get(self.idx).map(|&bb| (bb, &self.body[bb])) 1,842,924 ( 0.01%) } . . fn size_hint(&self) -> (usize, Option) { . (self.idx, Some(self.idx)) . } . } . . impl<'a, 'tcx> ExactSizeIterator for ReversePostorder<'a, 'tcx> {} . -- line 291 ---------------------------------------- -- line 295 ---------------------------------------- . /// This is clearer than writing `preorder` in cases where the order doesn't matter. . pub fn reachable<'a, 'tcx>( . body: &'a Body<'tcx>, . ) -> impl 'a + Iterator)> { . preorder(body) . } . . /// Returns a `BitSet` containing all basic blocks reachable from the `START_BLOCK`. 104,106 ( 0.00%) pub fn reachable_as_bitset<'tcx>(body: &Body<'tcx>) -> BitSet { . let mut iter = preorder(body); . (&mut iter).for_each(drop); 69,404 ( 0.00%) iter.visited 104,106 ( 0.00%) } 8,911,594 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/scoped_cell.rs -------------------------------------------------------------------------------- Ir -- line 22 ---------------------------------------- . impl<'a, 'b, T: LambdaL> Deref for RefMutL<'a, 'b, T> { . type Target = >::Out; . fn deref(&self) -> &Self::Target { . self.0 . } . } . . impl<'a, 'b, T: LambdaL> DerefMut for RefMutL<'a, 'b, T> { 2,640 ( 0.00%) fn deref_mut(&mut self) -> &mut Self::Target { 1,320 ( 0.00%) self.0 2,640 ( 0.00%) } . } . . pub struct ScopedCell(Cell<>::Out>); . . impl ScopedCell { . #[rustc_allow_const_fn_unstable(const_fn)] 3 ( 0.00%) pub const fn new(value: >::Out) -> Self { 10 ( 0.00%) ScopedCell(Cell::new(value)) 2 ( 0.00%) } . . /// Sets the value in `self` to `replacement` while . /// running `f`, which gets the old value, mutably. . /// The old value will be restored after `f` exits, even . /// by panic, including modifications made to it by `f`. 33,237,748 ( 0.10%) pub fn replace<'a, R>( . &self, . replacement: >::Out, . f: impl for<'b, 'c> FnOnce(RefMutL<'b, 'c, T>) -> R, . ) -> R { . /// Wrapper that ensures that the cell always gets filled . /// (with the original state, optionally changed by `f`), . /// even if `f` had panicked. . struct PutBackOnDrop<'a, T: LambdaL> { . cell: &'a ScopedCell, . value: Option<>::Out>, . } . . impl<'a, T: LambdaL> Drop for PutBackOnDrop<'a, T> { 5,940 ( 0.00%) fn drop(&mut self) { 4,550,872 ( 0.01%) self.cell.0.set(self.value.take().unwrap()); 3,960 ( 0.00%) } . } . 9,091,843 ( 0.03%) let mut put_back_on_drop = PutBackOnDrop { . cell: self, 19,800 ( 0.00%) value: Some(self.0.replace(unsafe { 3,960 ( 0.00%) let erased = mem::transmute_copy(&replacement); 23,760 ( 0.00%) mem::forget(replacement); 19,800 ( 0.00%) erased . })), . }; . 2,624,916 ( 0.01%) f(RefMutL(put_back_on_drop.value.as_mut().unwrap())) 44,105,906 ( 0.13%) } . . /// Sets the value in `self` to `value` while running `f`. 4,620 ( 0.00%) pub fn set(&self, value: >::Out, f: impl FnOnce() -> R) -> R { 10,560 ( 0.00%) self.replace(value, |_| f()) 1,320 ( 0.00%) } . } 2,425,241 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/non_null.rs -------------------------------------------------------------------------------- Ir -- line 186 ---------------------------------------- . /// use std::ptr::NonNull; . /// . /// // NEVER DO THAT!!! This is undefined behavior. ⚠️ . /// let ptr = unsafe { NonNull::::new_unchecked(std::ptr::null_mut()) }; . /// ``` . #[stable(feature = "nonnull", since = "1.25.0")] . #[rustc_const_stable(feature = "const_nonnull_new_unchecked", since = "1.25.0")] . #[inline] 6,826,669 ( 0.02%) pub const unsafe fn new_unchecked(ptr: *mut T) -> Self { . // SAFETY: the caller must guarantee that `ptr` is non-null. 30,332,613 ( 0.09%) unsafe { NonNull { pointer: ptr as _ } } 10,055,354 ( 0.03%) } . . /// Creates a new `NonNull` if `ptr` is non-null. . /// . /// # Examples . /// . /// ``` . /// use std::ptr::NonNull; . /// -- line 205 ---------------------------------------- -- line 207 ---------------------------------------- . /// let ptr = NonNull::::new(&mut x as *mut _).expect("ptr is null!"); . /// . /// if let Some(ptr) = NonNull::::new(std::ptr::null_mut()) { . /// unreachable!(); . /// } . /// ``` . #[stable(feature = "nonnull", since = "1.25.0")] . #[inline] 1,045,833 ( 0.00%) pub fn new(ptr: *mut T) -> Option { 1,743,055 ( 0.01%) if !ptr.is_null() { . // SAFETY: The pointer is already checked and is not null 1,045,833 ( 0.00%) Some(unsafe { Self::new_unchecked(ptr) }) . } else { . None . } 1,045,833 ( 0.00%) } . . /// Performs the same functionality as [`std::ptr::from_raw_parts`], except that a . /// `NonNull` pointer is returned, as opposed to a raw `*const` pointer. . /// . /// See the documentation of [`std::ptr::from_raw_parts`] for more details. . /// . /// [`std::ptr::from_raw_parts`]: crate::ptr::from_raw_parts . #[unstable(feature = "ptr_metadata", issue = "81513")] -- line 230 ---------------------------------------- -- line 268 ---------------------------------------- . /// unsafe { *ptr.as_ptr() += 2; } . /// let x_value = unsafe { *ptr.as_ptr() }; . /// assert_eq!(x_value, 2); . /// ``` . #[stable(feature = "nonnull", since = "1.25.0")] . #[rustc_const_stable(feature = "const_nonnull_as_ptr", since = "1.32.0")] . #[must_use] . #[inline] 22,045,090 ( 0.06%) pub const fn as_ptr(self) -> *mut T { . self.pointer as *mut T 14,204,328 ( 0.04%) } . . /// Returns a shared reference to the value. If the value may be uninitialized, [`as_uninit_ref`] . /// must be used instead. . /// . /// For the mutable counterpart see [`as_mut`]. . /// . /// [`as_uninit_ref`]: NonNull::as_uninit_ref . /// [`as_mut`]: NonNull::as_mut -- line 286 ---------------------------------------- -- line 316 ---------------------------------------- . /// println!("{}", ref_x); . /// ``` . /// . /// [the module documentation]: crate::ptr#safety . #[stable(feature = "nonnull", since = "1.25.0")] . #[rustc_const_unstable(feature = "const_ptr_as_ref", issue = "91822")] . #[must_use] . #[inline] 291,336 ( 0.00%) pub const unsafe fn as_ref<'a>(&self) -> &'a T { . // SAFETY: the caller must guarantee that `self` meets all the . // requirements for a reference. 437,004 ( 0.00%) unsafe { &*self.as_ptr() } 291,336 ( 0.00%) } . . /// Returns a unique reference to the value. If the value may be uninitialized, [`as_uninit_mut`] . /// must be used instead. . /// . /// For the shared counterpart see [`as_ref`]. . /// . /// [`as_uninit_mut`]: NonNull::as_uninit_mut . /// [`as_ref`]: NonNull::as_ref -- line 336 ---------------------------------------- -- line 391 ---------------------------------------- . /// let casted_ptr = ptr.cast::(); . /// let raw_ptr: *mut i8 = casted_ptr.as_ptr(); . /// ``` . #[stable(feature = "nonnull_cast", since = "1.27.0")] . #[rustc_const_stable(feature = "const_nonnull_cast", since = "1.36.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline] 946,147 ( 0.00%) pub const fn cast(self) -> NonNull { . // SAFETY: `self` is a `NonNull` pointer which is necessarily non-null 1,279,784 ( 0.00%) unsafe { NonNull::new_unchecked(self.as_ptr() as *mut U) } 639,106 ( 0.00%) } . } . . impl NonNull<[T]> { . /// Creates a non-null raw slice from a thin pointer and a length. . /// . /// The `len` argument is the number of **elements**, not the number of bytes. . /// . /// This function is safe, but dereferencing the return value is unsafe. -- line 410 ---------------------------------------- -- line 425 ---------------------------------------- . /// ``` . /// . /// (Note that this example artificially demonstrates a use of this method, . /// but `let slice = NonNull::from(&x[..]);` would be a better way to write code like this.) . #[unstable(feature = "nonnull_slice_from_raw_parts", issue = "71941")] . #[rustc_const_unstable(feature = "const_nonnull_slice_from_raw_parts", issue = "71941")] . #[must_use] . #[inline] 1,477,196 ( 0.00%) pub const fn slice_from_raw_parts(data: NonNull, len: usize) -> Self { . // SAFETY: `data` is a `NonNull` pointer which is necessarily non-null 2,954,392 ( 0.01%) unsafe { Self::new_unchecked(super::slice_from_raw_parts_mut(data.as_ptr(), len)) } 738,598 ( 0.00%) } . . /// Returns the length of a non-null raw slice. . /// . /// The returned value is the number of **elements**, not the number of bytes. . /// . /// This function is safe, even when the non-null raw slice cannot be dereferenced to a slice . /// because the pointer does not have a valid address. . /// -- line 444 ---------------------------------------- -- line 469 ---------------------------------------- . /// . /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3); . /// assert_eq!(slice.as_non_null_ptr(), NonNull::new(1 as *mut i8).unwrap()); . /// ``` . #[inline] . #[must_use] . #[unstable(feature = "slice_ptr_get", issue = "74265")] . #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")] 186,774 ( 0.00%) pub const fn as_non_null_ptr(self) -> NonNull { . // SAFETY: We know `self` is non-null. 311,290 ( 0.00%) unsafe { NonNull::new_unchecked(self.as_ptr().as_mut_ptr()) } 124,516 ( 0.00%) } . . /// Returns a raw pointer to the slice's buffer. . /// . /// # Examples . /// . /// ```rust . /// #![feature(slice_ptr_get, nonnull_slice_from_raw_parts)] . /// use std::ptr::NonNull; -- line 488 ---------------------------------------- -- line 489 ---------------------------------------- . /// . /// let slice: NonNull<[i8]> = NonNull::slice_from_raw_parts(NonNull::dangling(), 3); . /// assert_eq!(slice.as_mut_ptr(), 1 as *mut i8); . /// ``` . #[inline] . #[must_use] . #[unstable(feature = "slice_ptr_get", issue = "74265")] . #[rustc_const_unstable(feature = "slice_ptr_get", issue = "74265")] 186,744 ( 0.00%) pub const fn as_mut_ptr(self) -> *mut T { 248,992 ( 0.00%) self.as_non_null_ptr().as_ptr() 124,496 ( 0.00%) } . . /// Returns a shared reference to a slice of possibly uninitialized values. In contrast to . /// [`as_ref`], this does not require that the value has to be initialized. . /// . /// For the mutable counterpart see [`as_uninit_slice_mut`]. . /// . /// [`as_ref`]: NonNull::as_ref . /// [`as_uninit_slice_mut`]: NonNull::as_uninit_slice_mut -- line 507 ---------------------------------------- -- line 705 ---------------------------------------- . self.as_ptr().hash(state) . } . } . . #[unstable(feature = "ptr_internals", issue = "none")] . #[rustc_const_unstable(feature = "const_convert", issue = "88674")] . impl const From> for NonNull { . #[inline] 908,756 ( 0.00%) fn from(unique: Unique) -> Self { . // SAFETY: A Unique pointer cannot be null, so the conditions for . // new_unchecked() are respected. 1,817,512 ( 0.01%) unsafe { NonNull::new_unchecked(unique.as_ptr()) } 908,756 ( 0.00%) } . } . . #[stable(feature = "nonnull", since = "1.25.0")] . #[rustc_const_unstable(feature = "const_convert", issue = "88674")] . impl const From<&mut T> for NonNull { . #[inline] 202,838 ( 0.00%) fn from(reference: &mut T) -> Self { . // SAFETY: A mutable reference cannot be null. 435,242 ( 0.00%) unsafe { NonNull { pointer: reference as *mut T } } 304,257 ( 0.00%) } . } . . #[stable(feature = "nonnull", since = "1.25.0")] . #[rustc_const_unstable(feature = "const_convert", issue = "88674")] . impl const From<&T> for NonNull { . #[inline] . fn from(reference: &T) -> Self { . // SAFETY: A reference cannot be null, so the conditions for -- line 735 ---------------------------------------- 5,945,942 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/buffer.rs -------------------------------------------------------------------------------- Ir -- line 13 ---------------------------------------- . reserve: extern "C" fn(Buffer, usize) -> Buffer, . drop: extern "C" fn(Buffer), . } . . unsafe impl Sync for Buffer {} . unsafe impl Send for Buffer {} . . impl Default for Buffer { 11,880 ( 0.00%) fn default() -> Self { 15,840 ( 0.00%) Self::from(vec![]) 7,920 ( 0.00%) } . } . . impl Deref for Buffer { . type Target = [T]; 1,980 ( 0.00%) fn deref(&self) -> &[T] { 10,255,067 ( 0.03%) unsafe { slice::from_raw_parts(self.data as *const T, self.len) } 1,320 ( 0.00%) } . } . . impl DerefMut for Buffer { . fn deref_mut(&mut self) -> &mut [T] { . unsafe { slice::from_raw_parts_mut(self.data, self.len) } . } . } . . impl Buffer { . pub(super) fn new() -> Self { . Self::default() . } . 1,320 ( 0.00%) pub(super) fn clear(&mut self) { 21,546,481 ( 0.06%) self.len = 0; 1,320 ( 0.00%) } . 15,840 ( 0.00%) pub(super) fn take(&mut self) -> Self { 3,960 ( 0.00%) mem::take(self) 7,920 ( 0.00%) } . . // We have the array method separate from extending from a slice. This is . // because in the case of small arrays, codegen can be more efficient . // (avoiding a memmove call). With extend_from_slice, LLVM at least . // currently is not able to make that optimization. 3,300 ( 0.00%) pub(super) fn extend_from_array(&mut self, xs: &[T; N]) { 47,756,167 ( 0.14%) if xs.len() > (self.capacity - self.len) { . let b = self.take(); 27,720 ( 0.00%) *self = (b.reserve)(b, xs.len()); . } . unsafe { 8,232,536 ( 0.02%) xs.as_ptr().copy_to_nonoverlapping(self.data.add(self.len), xs.len()); 24,911,700 ( 0.07%) self.len += xs.len(); . } 1,320 ( 0.00%) } . 1,423,152 ( 0.00%) pub(super) fn extend_from_slice(&mut self, xs: &[T]) { 2,193,192 ( 0.01%) if xs.len() > (self.capacity - self.len) { . let b = self.take(); 28,161 ( 0.00%) *self = (b.reserve)(b, xs.len()); . } . unsafe { 1,341 ( 0.00%) xs.as_ptr().copy_to_nonoverlapping(self.data.add(self.len), xs.len()); 1,096,596 ( 0.00%) self.len += xs.len(); . } 1,660,344 ( 0.00%) } . 3,960 ( 0.00%) pub(super) fn push(&mut self, v: T) { . // The code here is taken from Vec::push, and we know that reserve() . // will panic if we're exceeding isize::MAX bytes and so there's no need . // to check for overflow. 53,685,777 ( 0.15%) if self.len == self.capacity { . let b = self.take(); . *self = (b.reserve)(b, 1); . } . unsafe { 34,758,909 ( 0.10%) *self.data.add(self.len) = v; 31,161,991 ( 0.09%) self.len += 1; . } 1,320 ( 0.00%) } . } . . impl Write for Buffer { . fn write(&mut self, xs: &[u8]) -> io::Result { . self.extend_from_slice(xs); . Ok(xs.len()) . } . 770,040 ( 0.00%) fn write_all(&mut self, xs: &[u8]) -> io::Result<()> { 711,576 ( 0.00%) self.extend_from_slice(xs); . Ok(()) 1,155,060 ( 0.00%) } . . fn flush(&mut self) -> io::Result<()> { . Ok(()) . } . } . . impl Drop for Buffer { 5,940 ( 0.00%) fn drop(&mut self) { 3,960 ( 0.00%) let b = self.take(); 54,386,712 ( 0.16%) (b.drop)(b); 3,960 ( 0.00%) } . } . . impl From> for Buffer { 23,760 ( 0.00%) fn from(mut v: Vec) -> Self { 102,960 ( 0.00%) let (data, len, capacity) = (v.as_mut_ptr(), v.len(), v.capacity()); 31,680 ( 0.00%) mem::forget(v); . . // This utility function is nested in here because it can *only* . // be safely called on `Buffer`s created by *this* `proc_macro`. 5,940 ( 0.00%) fn to_vec(b: Buffer) -> Vec { . unsafe { 17,820 ( 0.00%) let Buffer { data, len, capacity, .. } = b; 9,900 ( 0.00%) mem::forget(b); 1,980 ( 0.00%) Vec::from_raw_parts(data, len, capacity) . } 3,960 ( 0.00%) } . 10,644 ( 0.00%) extern "C" fn reserve(b: Buffer, additional: usize) -> Buffer { 7,983 ( 0.00%) let mut v = to_vec(b); . v.reserve(additional); 7,983 ( 0.00%) Buffer::from(v) 10,644 ( 0.00%) } . 3,960 ( 0.00%) extern "C" fn drop(b: Buffer) { 4,546,251 ( 0.01%) mem::drop(to_vec(b)); 4,533,051 ( 0.01%) } . 51,627 ( 0.00%) Buffer { data, len, capacity, reserve, drop } 7,920 ( 0.00%) } . } 21,267,329 ( 0.06%) -------------------------------------------------------------------------------- -- 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. 977,650 ( 0.00%) unsafe { from_raw_parts(self.ptr.as_ptr(), len!(self)) } . } . . // Helper function for moving the start of the iterator forwards by `offset` elements, . // returning the old start. . // Unsafe because the offset must not exceed `self.len()`. . #[inline(always)] . unsafe fn post_inc_start(&mut self, offset: isize) -> * $raw_mut T { . if mem::size_of::() == 0 { . zst_shrink!(self, offset); . self.ptr.as_ptr() . } else { 6,766,968 ( 0.02%) 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. 14,335,255 ( 0.04%) self.ptr = unsafe { NonNull::new_unchecked(self.ptr.as_ptr().offset(offset)) }; 1,127,828 ( 0.00%) old . } 2,255,656 ( 0.01%) } . . // 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)] . 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`. 268,120 ( 0.00%) self.end = unsafe { self.end.offset(-offset) }; 76,596 ( 0.00%) self.end . } 76,596 ( 0.00%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl ExactSizeIterator for $name<'_, T> { . #[inline(always)] . fn len(&self) -> usize { 3,448,178 ( 0.01%) len!(self) 181,398 ( 0.00%) } . . #[inline(always)] . fn is_empty(&self) -> bool { . is_empty!(self) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl<'a, T> Iterator for $name<'a, T> { . type Item = $elem; . . #[inline] 4,068,945 ( 0.01%) 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 { 8,747,891 ( 0.03%) assume(!self.ptr.as_ptr().is_null()); 6,781,575 ( 0.02%) if mem::size_of::() != 0 { 3,119,447 ( 0.01%) assume(!self.end.is_null()); . } 547,581,211 ( 1.58%) if is_empty!(self) { 228,487 ( 0.00%) None . } else { 2,255,656 ( 0.01%) Some(next_unchecked!(self)) . } . } 4,068,945 ( 0.01%) } . . #[inline] 24,930 ( 0.00%) fn size_hint(&self) -> (usize, Option) { 16,071,879 ( 0.05%) let exact = len!(self); 44,874 ( 0.00%) (exact, Some(exact)) 9,972 ( 0.00%) } . . #[inline] . fn count(self) -> usize { . len!(self) . } . . #[inline] . fn nth(&mut self, n: usize) -> Option<$elem> { 259,233 ( 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() { 63,343 ( 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] 2,168 ( 0.00%) fn all(&mut self, mut f: F) -> bool . where . Self: Sized, . F: FnMut(Self::Item) -> bool, . { 70,693 ( 0.00%) while let Some(x) = self.next() { 132,903 ( 0.00%) if !f(x) { 536 ( 0.00%) return false; . } . } 6 ( 0.00%) true 3,246 ( 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] 3,561 ( 0.00%) fn any(&mut self, mut f: F) -> bool . where . Self: Sized, . F: FnMut(Self::Item) -> bool, . { 6,815,192 ( 0.02%) while let Some(x) = self.next() { 6,702,225 ( 0.02%) if f(x) { 20 ( 0.00%) return true; . } . } 689 ( 0.00%) false 3,581 ( 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] 43,476 ( 0.00%) fn find

(&mut self, mut predicate: P) -> Option . where . Self: Sized, . P: FnMut(&Self::Item) -> bool, . { 634,952 ( 0.00%) while let Some(x) = self.next() { 1,184,974 ( 0.00%) if predicate(&x) { 9,440 ( 0.00%) return Some(x); . } . } 3,624 ( 0.00%) None 35,314 ( 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] 896 ( 0.00%) fn find_map(&mut self, mut f: F) -> Option . where . Self: Sized, . F: FnMut(Self::Item) -> Option, . { 377,463 ( 0.00%) while let Some(x) = self.next() { 2,391,402 ( 0.01%) if let Some(y) = f(x) { 390,904 ( 0.00%) return Some(y); . } 336 ( 0.00%) } 112 ( 0.00%) None 82,984 ( 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() { 3,100,579 ( 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; 141,296 ( 0.00%) while let Some(x) = self.next_back() { 2,084,416 ( 0.01%) i -= 1; 1,412,609 ( 0.00%) if predicate(x) { . // SAFETY: `i` must be lower than `n` since it starts at `n` . // and is only decreasing. . unsafe { assume(i < n) }; . return Some(i); . } . } . None . } . . #[doc(hidden)] 2,872 ( 0.00%) unsafe fn __iterator_get_unchecked(&mut self, idx: usize) -> Self::Item { . // SAFETY: the caller must guarantee that `i` is in bounds of . // the underlying slice, so `i` cannot overflow an `isize`, and . // 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` 1,043,191 ( 0.00%) unsafe { & $( $mut_ )? * self.ptr.as_ptr().add(idx) } 1,436 ( 0.00%) } . . $($extra)* . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl<'a, T> DoubleEndedIterator for $name<'a, T> { . #[inline] 114,906 ( 0.00%) 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 { 153,372 ( 0.00%) assume(!self.ptr.as_ptr().is_null()); 191,510 ( 0.00%) if mem::size_of::() != 0 { 76,802 ( 0.00%) assume(!self.end.is_null()); . } 11,994,809 ( 0.03%) if is_empty!(self) { 4 ( 0.00%) None . } else { 76,596 ( 0.00%) Some(next_back_unchecked!(self)) . } . } 114,906 ( 0.00%) } . . #[inline] . fn nth_back(&mut self, n: usize) -> Option<$elem> { . if n >= len!(self) { . // This iterator is now empty. . self.end = self.ptr.as_ptr(); . return None; . } -- line 375 ---------------------------------------- 111,637,966 ( 0.32%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs -------------------------------------------------------------------------------- Ir -- line 416 ---------------------------------------- . /// ``` . /// # #![allow(unused_mut)] . /// let mut vec: Vec = Vec::new(); . /// ``` . #[inline] . #[rustc_const_stable(feature = "const_vec_new", since = "1.39.0")] . #[stable(feature = "rust1", since = "1.0.0")] . #[must_use] 261,653 ( 0.00%) pub const fn new() -> Self { 55,237,543 ( 0.16%) Vec { buf: RawVec::NEW, len: 0 } 268,424 ( 0.00%) } . . /// Constructs a new, empty `Vec` with the specified capacity. . /// . /// The vector will be able to hold exactly `capacity` elements without . /// reallocating. If `capacity` is 0, the vector will not allocate. . /// . /// It is important to note that although the returned vector has the . /// *capacity* specified, the vector will have a zero *length*. For an -- line 434 ---------------------------------------- -- line 461 ---------------------------------------- . /// vec.push(11); . /// assert_eq!(vec.len(), 11); . /// assert!(vec.capacity() >= 11); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[must_use] 30,080 ( 0.00%) pub fn with_capacity(capacity: usize) -> Self { 7,520 ( 0.00%) Self::with_capacity_in(capacity, Global) 15,040 ( 0.00%) } . . /// Creates a `Vec` directly from the raw components of another vector. . /// . /// # Safety . /// . /// This is highly unsafe, due to the number of invariants that aren't . /// checked: . /// -- line 479 ---------------------------------------- -- line 529 ---------------------------------------- . /// . /// // Put everything back together into a Vec . /// let rebuilt = Vec::from_raw_parts(p, len, cap); . /// assert_eq!(rebuilt, [4, 5, 6]); . /// } . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 11,880 ( 0.00%) pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Self { 1,980 ( 0.00%) unsafe { Self::from_raw_parts_in(ptr, length, capacity, Global) } 3,960 ( 0.00%) } . } . . impl Vec { . /// Constructs a new, empty `Vec`. . /// . /// The vector will not allocate until elements are pushed onto it. . /// . /// # Examples -- line 547 ---------------------------------------- -- line 600 ---------------------------------------- . /// // ...but this may make the vector reallocate . /// vec.push(11); . /// assert_eq!(vec.len(), 11); . /// assert!(vec.capacity() >= 11); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[inline] . #[unstable(feature = "allocator_api", issue = "32838")] 412,349 ( 0.00%) pub fn with_capacity_in(capacity: usize, alloc: A) -> Self { 14,774,900 ( 0.04%) Vec { buf: RawVec::with_capacity_in(capacity, alloc), len: 0 } 117,814 ( 0.00%) } . . /// Creates a `Vec` directly from the raw components of another vector. . /// . /// # Safety . /// . /// This is highly unsafe, due to the number of invariants that aren't . /// checked: . /// -- line 618 ---------------------------------------- -- line 676 ---------------------------------------- . /// . /// // Put everything back together into a Vec . /// let rebuilt = Vec::from_raw_parts_in(p, len, cap, alloc.clone()); . /// assert_eq!(rebuilt, [4, 5, 6]); . /// } . /// ``` . #[inline] . #[unstable(feature = "allocator_api", issue = "32838")] 71,396 ( 0.00%) pub unsafe fn from_raw_parts_in(ptr: *mut T, length: usize, capacity: usize, alloc: A) -> Self { 2,548,983 ( 0.01%) unsafe { Vec { buf: RawVec::from_raw_parts_in(ptr, capacity, alloc), len: length } } 10,984 ( 0.00%) } . . /// Decomposes a `Vec` into its raw components. . /// . /// Returns the raw pointer to the underlying data, the length of . /// the vector (in elements), and the allocated capacity of the . /// data (in elements). These are the same arguments in the same . /// order as the arguments to [`from_raw_parts`]. . /// -- line 694 ---------------------------------------- -- line 777 ---------------------------------------- . /// # Examples . /// . /// ``` . /// let vec: Vec = Vec::with_capacity(10); . /// assert_eq!(vec.capacity(), 10); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 100,936 ( 0.00%) pub fn capacity(&self) -> usize { 2,184,545 ( 0.01%) self.buf.capacity() 50,468 ( 0.00%) } . . /// Reserves capacity for at least `additional` more elements to be inserted . /// in the given `Vec`. The collection may reserve more space to avoid . /// frequent reallocations. After calling `reserve`, capacity will be . /// greater than or equal to `self.len() + additional`. Does nothing if . /// capacity is already sufficient. . /// . /// # Panics -- line 795 ---------------------------------------- -- line 800 ---------------------------------------- . /// . /// ``` . /// let mut vec = vec![1]; . /// vec.reserve(10); . /// assert!(vec.capacity() >= 11); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] 189,820 ( 0.00%) pub fn reserve(&mut self, additional: usize) { 7,187,782 ( 0.02%) self.buf.reserve(self.len, additional); 75,928 ( 0.00%) } . . /// Reserves the minimum capacity for exactly `additional` more elements to . /// be inserted in the given `Vec`. After calling `reserve_exact`, . /// capacity will be greater than or equal to `self.len() + additional`. . /// Does nothing if the capacity is already sufficient. . /// . /// Note that the allocator may give the collection more space than it . /// requests. Therefore, capacity can not be relied upon to be precisely -- line 818 ---------------------------------------- -- line 829 ---------------------------------------- . /// ``` . /// let mut vec = vec![1]; . /// vec.reserve_exact(10); . /// assert!(vec.capacity() >= 11); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn reserve_exact(&mut self, additional: usize) { 201,286 ( 0.00%) self.buf.reserve_exact(self.len, additional); . } . . /// Tries to reserve capacity for at least `additional` more elements to be inserted . /// in the given `Vec`. The collection may reserve more space to avoid . /// frequent reallocations. After calling `try_reserve`, capacity will be . /// greater than or equal to `self.len() + additional`. Does nothing if . /// capacity is already sufficient. . /// -- line 845 ---------------------------------------- -- line 926 ---------------------------------------- . /// let mut vec = Vec::with_capacity(10); . /// vec.extend([1, 2, 3]); . /// assert_eq!(vec.capacity(), 10); . /// vec.shrink_to_fit(); . /// assert!(vec.capacity() >= 3); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] 57,660 ( 0.00%) pub fn shrink_to_fit(&mut self) { . // The capacity is never less than the length, and there's nothing to do when . // they are equal, so we can avoid the panic case in `RawVec::shrink_to_fit` . // by only calling it with a greater capacity. 339,444 ( 0.00%) if self.capacity() > self.len { 126,940 ( 0.00%) self.buf.shrink_to_fit(self.len); . } 38,440 ( 0.00%) } . . /// Shrinks the capacity of the vector with a lower bound. . /// . /// The capacity will remain at least as large as both the length . /// and the supplied value. . /// . /// If the current capacity is less than the lower limit, this is a no-op. . /// -- line 949 ---------------------------------------- -- line 987 ---------------------------------------- . /// vec.extend([1, 2, 3]); . /// . /// assert_eq!(vec.capacity(), 10); . /// let slice = vec.into_boxed_slice(); . /// assert_eq!(slice.into_vec().capacity(), 3); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] 38,440 ( 0.00%) pub fn into_boxed_slice(mut self) -> Box<[T], A> { . unsafe { 115,320 ( 0.00%) self.shrink_to_fit(); 241,025 ( 0.00%) let me = ManuallyDrop::new(self); 192,200 ( 0.00%) let buf = ptr::read(&me.buf); 96,100 ( 0.00%) let len = me.len(); 249,860 ( 0.00%) buf.into_box(len).assume_init() 19,220 ( 0.00%) } 38,440 ( 0.00%) } . . /// Shortens the vector, keeping the first `len` elements and dropping . /// the rest. . /// . /// If `len` is greater than the vector's current length, this has no . /// effect. . /// . /// The [`drain`] method can emulate `truncate`, but causes the excess -- line 1011 ---------------------------------------- -- line 1040 ---------------------------------------- . /// let mut vec = vec![1, 2, 3]; . /// vec.truncate(0); . /// assert_eq!(vec, []); . /// ``` . /// . /// [`clear`]: Vec::clear . /// [`drain`]: Vec::drain . #[stable(feature = "rust1", since = "1.0.0")] 4,445,137 ( 0.01%) pub fn truncate(&mut self, len: usize) { . // This is safe because: . // . // * the slice passed to `drop_in_place` is valid; the `len > self.len` . // case avoids creating an invalid slice, and . // * the `len` of the vector is shrunk before calling `drop_in_place`, . // such that no value will be dropped twice in case `drop_in_place` . // were to panic once (if it panics twice, the program aborts). . unsafe { . // Note: It's intentional that this is `>` and not `>=`. . // Changing it to `>=` has negative performance . // implications in some cases. See #78884 for more. 3,510,546 ( 0.01%) if len > self.len { . return; . } 32 ( 0.00%) let remaining_len = self.len - len; 24 ( 0.00%) let s = ptr::slice_from_raw_parts_mut(self.as_mut_ptr().add(len), remaining_len); 3,296,148 ( 0.01%) self.len = len; 93,054 ( 0.00%) ptr::drop_in_place(s); . } 5,334,152 ( 0.02%) } . . /// Extracts a slice containing the entire vector. . /// . /// Equivalent to `&s[..]`. . /// . /// # Examples . /// . /// ``` -- line 1076 ---------------------------------------- -- line 1123 ---------------------------------------- . /// assert_eq!(*x_ptr.add(i), 1 << i); . /// } . /// } . /// ``` . /// . /// [`as_mut_ptr`]: Vec::as_mut_ptr . #[stable(feature = "vec_as_ptr", since = "1.37.0")] . #[inline] 528,954 ( 0.00%) pub fn as_ptr(&self) -> *const T { . // We shadow the slice method of the same name to avoid going through . // `deref`, which creates an intermediate reference. 66,336,389 ( 0.19%) let ptr = self.buf.ptr(); . unsafe { 264,477 ( 0.00%) assume(!ptr.is_null()); . } . ptr 528,954 ( 0.00%) } . . /// Returns an unsafe mutable pointer to the vector's buffer. . /// . /// The caller must ensure that the vector outlives the pointer this . /// function returns, or else it will end up pointing to garbage. . /// Modifying the vector may cause its buffer to be reallocated, . /// which would also make any pointers to it invalid. . /// -- line 1147 ---------------------------------------- -- line 1159 ---------------------------------------- . /// *x_ptr.add(i) = i as i32; . /// } . /// x.set_len(size); . /// } . /// assert_eq!(&*x, &[0, 1, 2, 3]); . /// ``` . #[stable(feature = "vec_as_ptr", since = "1.37.0")] . #[inline] 2,899,502 ( 0.01%) pub fn as_mut_ptr(&mut self) -> *mut T { . // We shadow the slice method of the same name to avoid going through . // `deref_mut`, which creates an intermediate reference. 61,954,244 ( 0.18%) let ptr = self.buf.ptr(); . unsafe { 1,449,751 ( 0.00%) assume(!ptr.is_null()); . } . ptr 2,899,502 ( 0.01%) } . . /// Returns a reference to the underlying allocator. . #[unstable(feature = "allocator_api", issue = "32838")] . #[inline] 148,626 ( 0.00%) pub fn allocator(&self) -> &A { 148,626 ( 0.00%) self.buf.allocator() 148,626 ( 0.00%) } . . /// Forces the length of the vector to `new_len`. . /// . /// This is a low-level operation that maintains none of the normal . /// invariants of the type. Normally changing the length of a vector . /// is done using one of the safe operations instead, such as . /// [`truncate`], [`resize`], [`extend`], or [`clear`]. . /// -- line 1190 ---------------------------------------- -- line 1256 ---------------------------------------- . /// vec.set_len(0); . /// } . /// ``` . /// . /// Normally, here, one would use [`clear`] instead to correctly drop . /// the contents and thus not leak memory. . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 435,969 ( 0.00%) pub unsafe fn set_len(&mut self, new_len: usize) { . debug_assert!(new_len <= self.capacity()); . 7,468,546 ( 0.02%) self.len = new_len; 326,852 ( 0.00%) } . . /// Removes an element from the vector and returns it. . /// . /// The removed element is replaced by the last element of the vector. . /// . /// This does not preserve ordering, but is *O*(1). . /// If you need to preserve the element order, use [`remove`] instead. . /// -- line 1276 ---------------------------------------- -- line 1305 ---------------------------------------- . assert_failed(index, len); . } . unsafe { . // We replace self[index] with the last element. Note that if the . // bounds check above succeeds there must be a last element (which . // can be self[index] itself). . let value = ptr::read(self.as_ptr().add(index)); . let base_ptr = self.as_mut_ptr(); 4 ( 0.00%) ptr::copy(base_ptr.add(len - 1), base_ptr.add(index), 1); . self.set_len(len - 1); . value . } . } . . /// Inserts an element at position `index` within the vector, shifting all . /// elements after it to the right. . /// -- line 1321 ---------------------------------------- -- line 1329 ---------------------------------------- . /// let mut vec = vec![1, 2, 3]; . /// vec.insert(1, 4); . /// assert_eq!(vec, [1, 4, 2, 3]); . /// vec.insert(4, 5); . /// assert_eq!(vec, [1, 4, 2, 3, 5]); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] 12,635 ( 0.00%) pub fn insert(&mut self, index: usize, element: T) { . #[cold] . #[inline(never)] . fn assert_failed(index: usize, len: usize) -> ! { . panic!("insertion index (is {}) should be <= len (is {})", index, len); . } . 4,569 ( 0.00%) let len = self.len(); 11,362 ( 0.00%) if index > len { . assert_failed(index, len); . } . . // space for the new element 31,940 ( 0.00%) if len == self.buf.capacity() { . self.reserve(1); . } . . unsafe { . // infallible . // The spot to put the new value . { . let p = self.as_mut_ptr().add(index); . // Shift everything over to make space. (Duplicating the . // `index`th element into two consecutive places.) 39,573 ( 0.00%) ptr::copy(p, p.offset(1), len - index); . // Write it in, overwriting the first copy of the `index`th . // element. . ptr::write(p, element); . } 31,910 ( 0.00%) self.set_len(len + 1); . } 10,830 ( 0.00%) } . . /// Removes and returns the element at position `index` within the vector, . /// shifting all elements after it to the left. . /// . /// Note: Because this shifts over the remaining elements, it has a . /// worst-case performance of *O*(*n*). If you don't need the order of elements . /// to be preserved, use [`swap_remove`] instead. If you'd like to remove . /// elements from the beginning of the `Vec`, consider using -- line 1376 ---------------------------------------- -- line 1387 ---------------------------------------- . /// . /// ``` . /// let mut v = vec![1, 2, 3]; . /// assert_eq!(v.remove(1), 2); . /// assert_eq!(v, [1, 3]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[track_caller] 328,728 ( 0.00%) pub fn remove(&mut self, index: usize) -> T { . #[cold] . #[inline(never)] . #[track_caller] . fn assert_failed(index: usize, len: usize) -> ! { . panic!("removal index (is {}) should be < len (is {})", index, len); . } . 114,266 ( 0.00%) let len = self.len(); 346,304 ( 0.00%) if index >= len { . assert_failed(index, len); . } . unsafe { . // infallible . let ret; . { . // the place we are taking from. . let ptr = self.as_mut_ptr().add(index); . // copy it out, unsafely having a copy of the value on . // the stack and in the vector at the same time. 676,400 ( 0.00%) ret = ptr::read(ptr); . . // Shift everything down to fill in that spot. 228,684 ( 0.00%) ptr::copy(ptr.offset(1), ptr, len - index - 1); . } 116,956 ( 0.00%) self.set_len(len - 1); . ret . } 547,880 ( 0.00%) } . . /// Retains only the elements specified by the predicate. . /// . /// In other words, remove all elements `e` such that `f(&e)` returns `false`. . /// This method operates in place, visiting each element exactly once in the . /// original order, and preserves the order of the retained elements. . /// . /// # Examples -- line 1431 ---------------------------------------- -- line 1442 ---------------------------------------- . /// ``` . /// let mut vec = vec![1, 2, 3, 4, 5]; . /// let keep = [false, true, true, false, true]; . /// let mut iter = keep.iter(); . /// vec.retain(|_| *iter.next().unwrap()); . /// assert_eq!(vec, [2, 3, 5]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 3,890,922 ( 0.01%) pub fn retain(&mut self, mut f: F) . where . F: FnMut(&T) -> bool, . { 68,881 ( 0.00%) self.retain_mut(|elem| f(elem)); 3,855,912 ( 0.01%) } . . /// Retains only the elements specified by the predicate, passing a mutable reference to it. . /// . /// In other words, remove all elements `e` such that `f(&mut e)` returns `false`. . /// This method operates in place, visiting each element exactly once in the . /// original order, and preserves the order of the retained elements. . /// . /// # Examples -- line 1463 ---------------------------------------- -- line 1474 ---------------------------------------- . /// }); . /// assert_eq!(vec, [2, 3, 4]); . /// ``` . #[unstable(feature = "vec_retain_mut", issue = "90829")] . pub fn retain_mut(&mut self, mut f: F) . where . F: FnMut(&mut T) -> bool, . { 511,269 ( 0.00%) let original_len = self.len(); . // Avoid double drop if the drop guard is not executed, . // since we may make some holes during the process. . unsafe { self.set_len(0) }; . . // Vec: [Kept, Kept, Hole, Hole, Hole, Hole, Unchecked, Unchecked] . // |<- processed len ->| ^- next to check . // |<- deleted cnt ->| . // |<- original_len ->| -- line 1490 ---------------------------------------- -- line 1499 ---------------------------------------- . v: &'a mut Vec, . processed_len: usize, . deleted_cnt: usize, . original_len: usize, . } . . impl Drop for BackshiftOnDrop<'_, T, A> { . fn drop(&mut self) { 435,676 ( 0.00%) if self.deleted_cnt > 0 { . // SAFETY: Trailing unchecked items must be valid since we never touch them. . unsafe { . ptr::copy( . self.v.as_ptr().add(self.processed_len), 366,278 ( 0.00%) self.v.as_mut_ptr().add(self.processed_len - self.deleted_cnt), . self.original_len - self.processed_len, . ); . } . } . // SAFETY: After filling holes, all items are in contiguous memory. . unsafe { 2 ( 0.00%) self.v.set_len(self.original_len - self.deleted_cnt); . } . } . } . . let mut g = BackshiftOnDrop { v: self, processed_len: 0, deleted_cnt: 0, original_len }; . . fn process_loop( . original_len: usize, . f: &mut F, . g: &mut BackshiftOnDrop<'_, T, A>, . ) where . F: FnMut(&mut T) -> bool, . { 4,916,265 ( 0.01%) while g.processed_len != original_len { . // SAFETY: Unchecked element must be valid. . let cur = unsafe { &mut *g.v.as_mut_ptr().add(g.processed_len) }; 1,103,774 ( 0.00%) if !f(cur) { . // Advance early to avoid double drop if `drop_in_place` panicked. 11,138 ( 0.00%) g.processed_len += 1; 5,106 ( 0.00%) g.deleted_cnt += 1; . // SAFETY: We never touch this element again after dropped. 2,973 ( 0.00%) unsafe { ptr::drop_in_place(cur) }; . // We already advanced the counter. . if DELETED { . continue; . } else { . break; . } . } . if DELETED { . // SAFETY: `deleted_cnt` > 0, so the hole slot must not overlap with current element. . // We use copy for move, and never touch this element again. . unsafe { 16,179 ( 0.00%) let hole_slot = g.v.as_mut_ptr().add(g.processed_len - g.deleted_cnt); . ptr::copy_nonoverlapping(cur, hole_slot, 1); . } . } 10,786 ( 0.00%) g.processed_len += 1; . } . } . . // Stage 1: Nothing was deleted. . process_loop::(original_len, &mut f, &mut g); . . // Stage 2: Some elements were deleted. . process_loop::(original_len, &mut f, &mut g); -- line 1565 ---------------------------------------- -- line 1606 ---------------------------------------- . /// ``` . /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"]; . /// . /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b)); . /// . /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]); . /// ``` . #[stable(feature = "dedup_by", since = "1.16.0")] 107,975 ( 0.00%) pub fn dedup_by(&mut self, mut same_bucket: F) . where . F: FnMut(&mut T, &mut T) -> bool, . { 15,466 ( 0.00%) let len = self.len(); 61,700 ( 0.00%) if len <= 1 { . return; . } . . /* INVARIANT: vec.len() > read >= write > write-1 >= 0 */ . struct FillGapOnDrop<'a, T, A: core::alloc::Allocator> { . /* Offset of the element we want to check if it is duplicate */ . read: usize, . -- line 1627 ---------------------------------------- -- line 1670 ---------------------------------------- . let ptr = gap.vec.as_mut_ptr(); . . /* Drop items while going through Vec, it should be more efficient than . * doing slice partition_dedup + truncate */ . . /* SAFETY: Because of the invariant, read_ptr, prev_ptr and write_ptr . * are always in-bounds and read_ptr never aliases prev_ptr */ . unsafe { 19,794 ( 0.00%) while gap.read < len { . let read_ptr = ptr.add(gap.read); . let prev_ptr = ptr.add(gap.write.wrapping_sub(1)); . 11,884 ( 0.00%) if same_bucket(&mut *read_ptr, &mut *prev_ptr) { . // Increase `gap.read` now since the drop may panic. . gap.read += 1; . /* We have found duplicate, drop it in-place */ . ptr::drop_in_place(read_ptr); . } else { . let write_ptr = ptr.add(gap.write); . . /* Because `read_ptr` can be equal to `write_ptr`, we either . * have to use `copy` or conditional `copy_nonoverlapping`. . * Looks like the first option is faster. */ . ptr::copy(read_ptr, write_ptr, 1); . . /* We have filled that place, so go further */ 6,598 ( 0.00%) gap.write += 1; . gap.read += 1; . } . } . . /* Technically we could let `gap` clean up with its Drop, but . * when `same_bucket` is guaranteed to not panic, this bloats a little . * the codegen, so we just do it manually */ . gap.vec.set_len(gap.write); . mem::forget(gap); . } 123,400 ( 0.00%) } . . /// Appends an element to the back of a collection. . /// . /// # Panics . /// . /// Panics if the new capacity exceeds `isize::MAX` bytes. . /// . /// # Examples -- line 1715 ---------------------------------------- -- line 1717 ---------------------------------------- . /// ``` . /// let mut vec = vec![1, 2]; . /// vec.push(3); . /// assert_eq!(vec, [1, 2, 3]); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 4,856,699 ( 0.01%) pub fn push(&mut self, value: T) { . // This will panic or abort if we would allocate > isize::MAX bytes . // or if the length increment would overflow for zero-sized types. 96,155,780 ( 0.28%) if self.len == self.buf.capacity() { 6,297,473 ( 0.02%) self.buf.reserve_for_push(self.len); . } . unsafe { 10,918,141 ( 0.03%) let end = self.as_mut_ptr().add(self.len); 6,244,129 ( 0.02%) ptr::write(end, value); 145,132,493 ( 0.42%) self.len += 1; . } 1,694,826 ( 0.00%) } . . /// Removes the last element from a vector and returns it, or [`None`] if it . /// is empty. . /// . /// If you'd like to pop the first element, consider using . /// [`VecDeque::pop_front`] instead. . /// . /// [`VecDeque::pop_front`]: crate::collections::VecDeque::pop_front -- line 1744 ---------------------------------------- -- line 1748 ---------------------------------------- . /// ``` . /// let mut vec = vec![1, 2, 3]; . /// assert_eq!(vec.pop(), Some(3)); . /// assert_eq!(vec, [1, 2]); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn pop(&mut self) -> Option { 18,874,189 ( 0.05%) if self.len == 0 { 38 ( 0.00%) None . } else { . unsafe { 13,612,724 ( 0.04%) self.len -= 1; 2,820,498 ( 0.01%) Some(ptr::read(self.as_ptr().add(self.len()))) . } . } . } . . /// Moves all the elements of `other` into `Self`, leaving `other` empty. . /// . /// # Panics . /// -- line 1769 ---------------------------------------- -- line 1776 ---------------------------------------- . /// let mut vec2 = vec![4, 5, 6]; . /// vec.append(&mut vec2); . /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]); . /// assert_eq!(vec2, []); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[inline] . #[stable(feature = "append", since = "1.4.0")] 12,145 ( 0.00%) pub fn append(&mut self, other: &mut Self) { . unsafe { . self.append_elements(other.as_slice() as _); . other.set_len(0); . } 10,410 ( 0.00%) } . . /// Appends elements to `Self` from other buffer. . #[cfg(not(no_global_oom_handling))] . #[inline] 298,960 ( 0.00%) unsafe fn append_elements(&mut self, other: *const [T]) { 29,896 ( 0.00%) let count = unsafe { (*other).len() }; 29,896 ( 0.00%) self.reserve(count); 1,446,342 ( 0.00%) let len = self.len(); 89,688 ( 0.00%) unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) }; 8,771,648 ( 0.03%) self.len += count; 59,792 ( 0.00%) } . . /// Creates a draining iterator that removes the specified range in the vector . /// and yields the removed items. . /// . /// When the iterator **is** dropped, all elements in the range are removed . /// from the vector, even if the iterator was not fully consumed. If the . /// iterator **is not** dropped (with [`mem::forget`] for example), it is . /// unspecified how many elements are removed. -- line 1808 ---------------------------------------- -- line 1820 ---------------------------------------- . /// assert_eq!(v, &[1]); . /// assert_eq!(u, &[2, 3]); . /// . /// // A full range clears the vector . /// v.drain(..); . /// assert_eq!(v, &[]); . /// ``` . #[stable(feature = "drain", since = "1.6.0")] 622,153 ( 0.00%) pub fn drain(&mut self, range: R) -> Drain<'_, T, A> . where . R: RangeBounds, . { . // Memory safety . // . // When the Drain is first created, it shortens the length of . // the source vector to make sure no uninitialized or moved-from elements . // are accessible at all if the Drain's destructor never gets to run. . // . // Drain will ptr::read out the values to remove. . // When finished, remaining tail of the vec is copied back to cover . // the hole, and the vector length is restored to the new length. . // 983,100 ( 0.00%) let len = self.len(); 1,333,185 ( 0.00%) let Range { start, end } = slice::range(range, ..len); . . unsafe { . // set self.vec length's to start, to be safe in case Drain is leaked 266,637 ( 0.00%) self.set_len(start); . // Use the borrow in the IterMut to indicate borrowing behavior of the . // whole Drain iterator (like &mut T). 1,422,110 ( 0.00%) let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start), end - start); 455,262 ( 0.00%) Drain { . tail_start: end, 444,429 ( 0.00%) tail_len: len - end, 444,395 ( 0.00%) iter: range_slice.iter(), 355,516 ( 0.00%) vec: NonNull::from(self), . } . } 177,758 ( 0.00%) } . . /// Clears the vector, removing all values. . /// . /// Note that this method has no effect on the allocated capacity . /// of the vector. . /// . /// # Examples . /// -- line 1866 ---------------------------------------- -- line 1869 ---------------------------------------- . /// . /// v.clear(); . /// . /// assert!(v.is_empty()); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn clear(&mut self) { 7,946,799 ( 0.02%) self.truncate(0) . } . . /// Returns the number of elements in the vector, also referred to . /// as its 'length'. . /// . /// # Examples . /// . /// ``` . /// let a = vec![1, 2, 3]; . /// assert_eq!(a.len(), 3); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 812,614 ( 0.00%) pub fn len(&self) -> usize { 406,307 ( 0.00%) self.len 812,614 ( 0.00%) } . . /// Returns `true` if the vector contains no elements. . /// . /// # Examples . /// . /// ``` . /// let mut v = Vec::new(); . /// assert!(v.is_empty()); . /// . /// v.push(1); . /// assert!(!v.is_empty()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 297,266 ( 0.00%) pub fn is_empty(&self) -> bool { 7,721,502 ( 0.02%) self.len() == 0 594,532 ( 0.00%) } . . /// Splits the collection into two at the given index. . /// . /// Returns a newly allocated vector containing the elements in the range . /// `[at, len)`. After the call, the original vector will be left containing . /// the elements `[0, at)` with its previous capacity unchanged. . /// . /// # Panics -- line 1917 ---------------------------------------- -- line 1935 ---------------------------------------- . A: Clone, . { . #[cold] . #[inline(never)] . fn assert_failed(at: usize, len: usize) -> ! { . panic!("`at` split index (is {}) should be <= len (is {})", at, len); . } . 31,969 ( 0.00%) if at > self.len() { . assert_failed(at, self.len()); . } . 24,533 ( 0.00%) if at == 0 { . // the new vector can take over the original buffer and avoid the copy . return mem::replace( . self, . Vec::with_capacity_in(self.capacity(), self.allocator().clone()), . ); . } . . let other_len = self.len - at; -- line 1955 ---------------------------------------- -- line 1988 ---------------------------------------- . /// . /// let mut vec = vec![]; . /// let mut p = 1; . /// vec.resize_with(4, || { p *= 2; p }); . /// assert_eq!(vec, [2, 4, 8, 16]); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "vec_resize_with", since = "1.33.0")] 573,979 ( 0.00%) pub fn resize_with(&mut self, new_len: usize, f: F) . where . F: FnMut() -> T, . { 75,665 ( 0.00%) let len = self.len(); 151,330 ( 0.00%) if new_len > len { 511,759 ( 0.00%) self.extend_with(new_len - len, ExtendFunc(f)); . } else { . self.truncate(new_len); . } 498,314 ( 0.00%) } . . /// Consumes and leaks the `Vec`, returning a mutable reference to the contents, . /// `&'a mut [T]`. Note that the type `T` must outlive the chosen lifetime . /// `'a`. If the type has only static references, or none at all, then this . /// may be chosen to be `'static`. . /// . /// As of Rust 1.57, this method does not reallocate or shrink the `Vec`, . /// so the leaked allocation may include unused capacity that is not part -- line 2014 ---------------------------------------- -- line 2064 ---------------------------------------- . /// unsafe { . /// v.set_len(3); . /// } . /// . /// assert_eq!(&v, &[0, 1, 2]); . /// ``` . #[stable(feature = "vec_spare_capacity", since = "1.60.0")] . #[inline] 127,263 ( 0.00%) pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit] { . // Note: . // This method is not implemented in terms of `split_at_spare_mut`, . // to prevent invalidation of pointers to the buffer. . unsafe { 169,684 ( 0.00%) slice::from_raw_parts_mut( 296,951 ( 0.00%) self.as_mut_ptr().add(self.len) as *mut MaybeUninit, 212,239 ( 0.00%) self.buf.capacity() - self.len, . ) . } 84,842 ( 0.00%) } . . /// Returns vector content as a slice of `T`, along with the remaining spare . /// capacity of the vector as a slice of `MaybeUninit`. . /// . /// The returned spare capacity slice can be used to fill the vector with data . /// (e.g. by reading from a file) before marking the data as initialized using . /// the [`set_len`] method. . /// -- line 2090 ---------------------------------------- -- line 2189 ---------------------------------------- . /// assert_eq!(vec, ["hello", "world", "world"]); . /// . /// let mut vec = vec![1, 2, 3, 4]; . /// vec.resize(2, 0); . /// assert_eq!(vec, [1, 2]); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "vec_resize", since = "1.5.0")] 13,714 ( 0.00%) pub fn resize(&mut self, new_len: usize, value: T) { 1,421 ( 0.00%) let len = self.len(); . 4,123 ( 0.00%) if new_len > len { 68,525 ( 0.00%) self.extend_with(new_len - len, ExtendElement(value)) . } else { 12 ( 0.00%) self.truncate(new_len); . } 1,445 ( 0.00%) } . . /// Clones and appends all elements in a slice to the `Vec`. . /// . /// Iterates over the slice `other`, clones each element, and then appends . /// it to this `Vec`. The `other` slice is traversed in-order. . /// . /// Note that this function is same as [`extend`] except that it is . /// specialized to work with slices instead. If and when Rust gets -- line 2213 ---------------------------------------- -- line 2220 ---------------------------------------- . /// let mut vec = vec![1]; . /// vec.extend_from_slice(&[2, 3, 4]); . /// assert_eq!(vec, [1, 2, 3, 4]); . /// ``` . /// . /// [`extend`]: Vec::extend . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "vec_extend_from_slice", since = "1.6.0")] 328,856 ( 0.00%) pub fn extend_from_slice(&mut self, other: &[T]) { 119,584 ( 0.00%) self.spec_extend(other.iter()) 59,792 ( 0.00%) } . . /// Copies elements from `src` range to the end of the vector. . /// . /// # Panics . /// . /// Panics if the starting point is greater than the end point or if . /// the end point is greater than the length of the vector. . /// -- line 2238 ---------------------------------------- -- line 2270 ---------------------------------------- . // This code generalizes `extend_with_{element,default}`. . trait ExtendWith { . fn next(&mut self) -> T; . fn last(self) -> T; . } . . struct ExtendElement(T); . impl ExtendWith for ExtendElement { 8 ( 0.00%) fn next(&mut self) -> T { 1,449 ( 0.00%) self.0.clone() 8 ( 0.00%) } 12 ( 0.00%) fn last(self) -> T { . self.0 8 ( 0.00%) } . } . . struct ExtendFunc(F); . impl T> ExtendWith for ExtendFunc { . fn next(&mut self) -> T { . (self.0)() . } . fn last(mut self) -> T { . (self.0)() . } . } . . impl Vec { . #[cfg(not(no_global_oom_handling))] . /// Extend the vector by `n` values, using the given generator. 3,163,283 ( 0.01%) fn extend_with>(&mut self, n: usize, mut value: E) { 20 ( 0.00%) self.reserve(n); . . unsafe { 121,265 ( 0.00%) let mut ptr = self.as_mut_ptr().add(self.len()); . // Use SetLenOnDrop to work around bug where compiler . // might not realize the store through `ptr` through self.set_len() . // don't alias. 28 ( 0.00%) let mut local_len = SetLenOnDrop::new(&mut self.len); . . // Write all elements except the last one 148 ( 0.00%) for _ in 1..n { 44 ( 0.00%) ptr::write(ptr, value.next()); 24 ( 0.00%) ptr = ptr.offset(1); . // Increment the length in every step in case next() panics 8 ( 0.00%) local_len.increment_len(1); . } . 4,059,428 ( 0.01%) if n > 0 { . // We can write the last element directly without cloning needlessly 48 ( 0.00%) ptr::write(ptr, value.last()); 8 ( 0.00%) local_len.increment_len(1); . } . . // len set by scope guard 16 ( 0.00%) } 2,514,233 ( 0.01%) } . } . . impl Vec { . /// Removes consecutive repeated elements in the vector according to the . /// [`PartialEq`] trait implementation. . /// . /// If the vector is sorted, this removes all duplicates. . /// -- line 2333 ---------------------------------------- -- line 2338 ---------------------------------------- . /// . /// vec.dedup(); . /// . /// assert_eq!(vec, [1, 2, 3, 2]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . pub fn dedup(&mut self) { 15,426 ( 0.00%) self.dedup_by(|a, b| a == b) . } . } . . //////////////////////////////////////////////////////////////////////////////// . // Internal methods and functions . //////////////////////////////////////////////////////////////////////////////// . . #[doc(hidden)] . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] 580,377 ( 0.00%) pub fn from_elem(elem: T, n: usize) -> Vec { 4,250,230 ( 0.01%) ::from_elem(elem, n, Global) 741,442 ( 0.00%) } . . #[doc(hidden)] . #[cfg(not(no_global_oom_handling))] . #[unstable(feature = "allocator_api", issue = "32838")] . pub fn from_elem_in(elem: T, n: usize, alloc: A) -> Vec { . ::from_elem(elem, n, alloc) . } . -- line 2367 ---------------------------------------- -- line 2423 ---------------------------------------- . //////////////////////////////////////////////////////////////////////////////// . // Common trait implementations for Vec . //////////////////////////////////////////////////////////////////////////////// . . #[stable(feature = "rust1", since = "1.0.0")] . impl ops::Deref for Vec { . type Target = [T]; . 793,431 ( 0.00%) fn deref(&self) -> &[T] { 99,991,562 ( 0.29%) unsafe { slice::from_raw_parts(self.as_ptr(), self.len) } 528,991 ( 0.00%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl ops::DerefMut for Vec { 26,976 ( 0.00%) fn deref_mut(&mut self) -> &mut [T] { 28,090,171 ( 0.08%) unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) } 17,984 ( 0.00%) } . } . . #[cfg(not(no_global_oom_handling))] . trait SpecCloneFrom { . fn clone_from(this: &mut Self, other: &Self); . } . . #[cfg(not(no_global_oom_handling))] -- line 2448 ---------------------------------------- -- line 2468 ---------------------------------------- . this.extend_from_slice(other); . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl Clone for Vec { . #[cfg(not(test))] 4,457,584 ( 0.01%) fn clone(&self) -> Self { 212,105 ( 0.00%) let alloc = self.allocator().clone(); 380,393 ( 0.00%) <[T]>::to_vec_in(&**self, alloc) 5,356,691 ( 0.02%) } . . // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is . // required for this method definition, is not available. Instead use the . // `slice::to_vec` function which is only available with cfg(test) . // NB see the slice::hack module in slice.rs for more information . #[cfg(test)] . fn clone(&self) -> Self { . let alloc = self.allocator().clone(); -- line 2487 ---------------------------------------- -- line 2517 ---------------------------------------- . #[rustc_on_unimplemented( . message = "vector indices are of type `usize` or ranges of `usize`", . label = "vector indices are of type `usize` or ranges of `usize`" . )] . impl, A: Allocator> Index for Vec { . type Output = I::Output; . . #[inline] 2,500 ( 0.00%) fn index(&self, index: I) -> &Self::Output { 3,973,169 ( 0.01%) Index::index(&**self, index) 1,000 ( 0.00%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_on_unimplemented( . message = "vector indices are of type `usize` or ranges of `usize`", . label = "vector indices are of type `usize` or ranges of `usize`" . )] . impl, A: Allocator> IndexMut for Vec { . #[inline] 20 ( 0.00%) fn index_mut(&mut self, index: I) -> &mut Self::Output { 9,392 ( 0.00%) IndexMut::index_mut(&mut **self, index) 8 ( 0.00%) } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl FromIterator for Vec { . #[inline] 27,060 ( 0.00%) fn from_iter>(iter: I) -> Vec { 24,441,247 ( 0.07%) >::from_iter(iter.into_iter()) 13,544 ( 0.00%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl IntoIterator for Vec { . type Item = T; . type IntoIter = IntoIter; . . /// Creates a consuming iterator, that is, one that moves each value out of -- line 2556 ---------------------------------------- -- line 2562 ---------------------------------------- . /// ``` . /// let v = vec!["a".to_string(), "b".to_string()]; . /// for s in v.into_iter() { . /// // s has type String, not &String . /// println!("{}", s); . /// } . /// ``` . #[inline] 95,676 ( 0.00%) fn into_iter(self) -> IntoIter { . unsafe { 10,218,934 ( 0.03%) let mut me = ManuallyDrop::new(self); 63,784 ( 0.00%) let alloc = ptr::read(me.allocator()); 155,171 ( 0.00%) let begin = me.as_mut_ptr(); 95,676 ( 0.00%) let end = if mem::size_of::() == 0 { . arith_offset(begin as *const i8, me.len() as isize) as *const T . } else { 147,883 ( 0.00%) begin.add(me.len()) as *const T . }; 31,892 ( 0.00%) let cap = me.buf.capacity(); 3,783,716 ( 0.01%) IntoIter { 123,279 ( 0.00%) buf: NonNull::new_unchecked(begin), . phantom: PhantomData, . cap, . alloc, . ptr: begin, 31,892 ( 0.00%) end, . } . } 63,784 ( 0.00%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl<'a, T, A: Allocator> IntoIterator for &'a Vec { . type Item = &'a T; . type IntoIter = slice::Iter<'a, T>; . 9,372 ( 0.00%) fn into_iter(self) -> slice::Iter<'a, T> { 28,254 ( 0.00%) self.iter() 9,372 ( 0.00%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl<'a, T, A: Allocator> IntoIterator for &'a mut Vec { . type Item = &'a mut T; . type IntoIter = slice::IterMut<'a, T>; . 2,068 ( 0.00%) fn into_iter(self) -> slice::IterMut<'a, T> { 7,374 ( 0.00%) self.iter_mut() 2,068 ( 0.00%) } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl Extend for Vec { . #[inline] 121,109 ( 0.00%) fn extend>(&mut self, iter: I) { 13,219,684 ( 0.04%) >::spec_extend(self, iter.into_iter()) 114,846 ( 0.00%) } . . #[inline] . fn extend_one(&mut self, item: T) { . self.push(item); . } . . #[inline] . fn extend_reserve(&mut self, additional: usize) { -- line 2627 ---------------------------------------- -- line 2628 ---------------------------------------- . self.reserve(additional); . } . } . . impl Vec { . // leaf method to which various SpecFrom/SpecExtend implementations delegate when . // they have no further optimizations to apply . #[cfg(not(no_global_oom_handling))] 12,012 ( 0.00%) fn extend_desugared>(&mut self, mut iterator: I) { . // This is the case for a general iterator. . // . // This function should be the moral equivalent of: . // . // for item in iterator { . // self.push(item); . // } 1,946,143 ( 0.01%) while let Some(element) = iterator.next() { 460,585 ( 0.00%) let len = self.len(); 5,046,406 ( 0.01%) if len == self.capacity() { 8,580 ( 0.00%) let (lower, _) = iterator.size_hint(); 154 ( 0.00%) self.reserve(lower.saturating_add(1)); . } . unsafe { 30,770 ( 0.00%) ptr::write(self.as_mut_ptr().add(len), element); . // Since next() executes user code which can panic we have to bump the length . // after each step. . // NB can't overflow since we would have had to alloc the address space 3,408,503 ( 0.01%) self.set_len(len + 1); . } 2,054 ( 0.00%) } 83,228 ( 0.00%) } . . /// Creates a splicing iterator that replaces the specified range in the vector . /// with the given `replace_with` iterator and yields the removed items. . /// `replace_with` does not need to be the same length as `range`. . /// . /// `range` is removed even if the iterator is not consumed until the end. . /// . /// It is unspecified how many elements are removed from the vector -- line 2666 ---------------------------------------- -- line 2693 ---------------------------------------- . #[cfg(not(no_global_oom_handling))] . #[inline] . #[stable(feature = "vec_splice", since = "1.21.0")] . pub fn splice(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter, A> . where . R: RangeBounds, . I: IntoIterator, . { 167 ( 0.00%) Splice { drain: self.drain(range), replace_with: replace_with.into_iter() } . } . . /// Creates an iterator which uses a closure to determine if an element should be removed. . /// . /// If the closure returns true, then the element is removed and yielded. . /// If the closure returns false, the element will remain in the vector and will not be yielded . /// by the iterator. . /// -- line 2709 ---------------------------------------- -- line 2745 ---------------------------------------- . /// assert_eq!(evens, vec![2, 4, 6, 8, 14]); . /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]); . /// ``` . #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")] . pub fn drain_filter(&mut self, filter: F) -> DrainFilter<'_, T, F, A> . where . F: FnMut(&mut T) -> bool, . { 32,489 ( 0.00%) let old_len = self.len(); . . // Guard against us getting leaked (leak amplification) . unsafe { . self.set_len(0); . } . 97,792 ( 0.00%) DrainFilter { vec: self, idx: 0, del: 0, old_len, pred: filter, panic_flag: false } . } . } . . /// Extend implementation that copies elements out of references before pushing them onto the Vec. . /// . /// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to . /// append the entire slice at once. . /// -- line 2768 ---------------------------------------- -- line 2803 ---------------------------------------- . #[inline] . fn cmp(&self, other: &Self) -> Ordering { . Ord::cmp(&**self, &**other) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . unsafe impl<#[may_dangle] T, A: Allocator> Drop for Vec { 13,342,296 ( 0.04%) fn drop(&mut self) { . unsafe { . // use drop for [T] . // use a raw slice to refer to the elements of the vector as weakest necessary type; . // could avoid questions of validity in certain cases 8,790,979 ( 0.03%) ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len)) . } . // RawVec handles deallocation 15,139,030 ( 0.04%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")] . impl const Default for Vec { . /// Creates an empty `Vec`. . fn default() -> Vec { . Vec::new() -- line 2827 ---------------------------------------- -- line 2976 ---------------------------------------- . /// newly-allocated buffer with exactly the right capacity. . /// . /// # Examples . /// . /// ``` . /// assert_eq!(Box::from(vec![1, 2, 3]), vec![1, 2, 3].into_boxed_slice()); . /// ``` . fn from(v: Vec) -> Self { 4 ( 0.00%) v.into_boxed_slice() . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl From<&str> for Vec { . /// Allocate a `Vec` and fill it with a UTF-8 string. . /// -- line 2992 ---------------------------------------- 44,038,907 ( 0.13%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs -------------------------------------------------------------------------------- Ir -- line 180 ---------------------------------------- . /// assert_eq!(v, &[0.into()]); . /// . /// // Ensure that the last item was dropped. . /// assert!(weak.upgrade().is_none()); . /// ``` . #[stable(feature = "drop_in_place", since = "1.8.0")] . #[lang = "drop_in_place"] . #[allow(unconditional_recursion)] 443,314,295 ( 1.28%) pub unsafe fn drop_in_place(to_drop: *mut T) { . // Code here does not matter - this is replaced by the . // real drop glue by the compiler. . . // SAFETY: see comment above . unsafe { drop_in_place(to_drop) } . } . . /// Creates a null raw pointer. -- line 196 ---------------------------------------- -- line 206 ---------------------------------------- . #[inline(always)] . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_promotable] . #[rustc_const_stable(feature = "const_ptr_null", since = "1.24.0")] . #[rustc_diagnostic_item = "ptr_null"] . pub const fn null() -> *const T { . 0 as *const T 8,212 ( 0.00%) } . . /// Creates a null mutable raw pointer. . /// . /// # Examples . /// . /// ``` . /// use std::ptr; . /// -- line 222 ---------------------------------------- -- line 251 ---------------------------------------- . /// let x = [5, 6, 7]; . /// let raw_pointer = x.as_ptr(); . /// let slice = ptr::slice_from_raw_parts(raw_pointer, 3); . /// assert_eq!(unsafe { &*slice }[2], 7); . /// ``` . #[inline] . #[stable(feature = "slice_from_raw_parts", since = "1.42.0")] . #[rustc_const_unstable(feature = "const_slice_from_raw_parts", issue = "67456")] 2,387,436 ( 0.01%) pub const fn slice_from_raw_parts(data: *const T, len: usize) -> *const [T] { 2,984,295 ( 0.01%) from_raw_parts(data.cast(), len) 1,193,718 ( 0.00%) } . . /// Performs the same functionality as [`slice_from_raw_parts`], except that a . /// raw mutable slice is returned, as opposed to a raw immutable slice. . /// . /// See the documentation of [`slice_from_raw_parts`] for more details. . /// . /// This function is safe, but actually using the return value is unsafe. . /// See the documentation of [`slice::from_raw_parts_mut`] for slice safety requirements. -- line 269 ---------------------------------------- -- line 283 ---------------------------------------- . /// (*slice)[2] = 99; // assign a value at an index in the slice . /// }; . /// . /// assert_eq!(unsafe { &*slice }[2], 99); . /// ``` . #[inline] . #[stable(feature = "slice_from_raw_parts", since = "1.42.0")] . #[rustc_const_unstable(feature = "const_slice_from_raw_parts", issue = "67456")] 7,743,520 ( 0.02%) pub const fn slice_from_raw_parts_mut(data: *mut T, len: usize) -> *mut [T] { 2,903,820 ( 0.01%) from_raw_parts_mut(data.cast(), len) 1,935,880 ( 0.01%) } . . /// Swaps the values at two mutable locations of the same type, without . /// deinitializing either. . /// . /// But for the following two exceptions, this function is semantically . /// equivalent to [`mem::swap`]: . /// . /// * It operates on raw pointers instead of references. When references are -- line 301 ---------------------------------------- -- line 366 ---------------------------------------- . let mut tmp = MaybeUninit::::uninit(); . . // Perform the swap . // SAFETY: the caller must guarantee that `x` and `y` are . // valid for writes and properly aligned. `tmp` cannot be . // overlapping either `x` or `y` because `tmp` was just allocated . // on the stack as a separate allocated object. . unsafe { 6 ( 0.00%) copy_nonoverlapping(x, tmp.as_mut_ptr(), 1); 6 ( 0.00%) copy(y, x, 1); // `x` and `y` may overlap . copy_nonoverlapping(tmp.as_ptr(), y, 1); . } . } . . /// Swaps `count * size_of::()` bytes between the two regions of memory . /// beginning at `x` and `y`. The two regions must *not* overlap. . /// . /// # Safety -- line 383 ---------------------------------------- -- line 413 ---------------------------------------- . /// } . /// . /// assert_eq!(x, [7, 8, 3, 4]); . /// assert_eq!(y, [1, 2, 9]); . /// ``` . #[inline] . #[stable(feature = "swap_nonoverlapping", since = "1.27.0")] . #[rustc_const_unstable(feature = "const_swap", issue = "83163")] 60 ( 0.00%) pub const unsafe fn swap_nonoverlapping(x: *mut T, y: *mut T, count: usize) { 20 ( 0.00%) let x = x as *mut u8; 10 ( 0.00%) let y = y as *mut u8; 70 ( 0.00%) let len = mem::size_of::() * count; . // SAFETY: the caller must guarantee that `x` and `y` are . // valid for writes and properly aligned. 20 ( 0.00%) unsafe { swap_nonoverlapping_bytes(x, y, len) } 20 ( 0.00%) } . . #[inline] . #[rustc_const_unstable(feature = "const_swap", issue = "83163")] 50 ( 0.00%) pub(crate) const unsafe fn swap_nonoverlapping_one(x: *mut T, y: *mut T) { . // NOTE(eddyb) SPIR-V's Logical addressing model doesn't allow for arbitrary . // reinterpretation of values as (chunkable) byte arrays, and the loop in the . // block optimization in `swap_nonoverlapping_bytes` is hard to rewrite back . // into the (unoptimized) direct swapping implementation, so we disable it. . // FIXME(eddyb) the block optimization also prevents MIR optimizations from . // understanding `mem::replace`, `Option::take`, etc. - a better overall . // solution might be to make `swap_nonoverlapping` into an intrinsic, which . // a backend can choose to implement using the block optimization, or not. . #[cfg(not(target_arch = "spirv"))] 10 ( 0.00%) { . // Only apply the block optimization in `swap_nonoverlapping_bytes` for types . // at least as large as the block size, to avoid pessimizing codegen. 10 ( 0.00%) if mem::size_of::() >= 32 { . // SAFETY: the caller must uphold the safety contract for `swap_nonoverlapping`. 20 ( 0.00%) unsafe { swap_nonoverlapping(x, y, 1) }; . return; . } . } . . // Direct swapping, for the cases not going through the block optimization. . // SAFETY: the caller must guarantee that `x` and `y` are valid . // for writes, properly aligned, and non-overlapping. . unsafe { 26 ( 0.00%) let z = read(x); . copy_nonoverlapping(y, x, 1); . write(y, z); . } 30 ( 0.00%) } . . #[inline] . #[rustc_const_unstable(feature = "const_swap", issue = "83163")] 100 ( 0.00%) const unsafe fn swap_nonoverlapping_bytes(x: *mut u8, y: *mut u8, len: usize) { . // The approach here is to utilize simd to swap x & y efficiently. Testing reveals . // that swapping either 32 bytes or 64 bytes at a time is most efficient for Intel . // Haswell E processors. LLVM is more able to optimize if we give a struct a . // #[repr(simd)], even if we don't actually use this struct directly. . // . // FIXME repr(simd) broken on emscripten and redox . #[cfg_attr(not(any(target_os = "emscripten", target_os = "redox")), repr(simd))] . struct Block(u64, u64, u64, u64); . struct UnalignedBlock(u64, u64, u64, u64); . 10 ( 0.00%) let block_size = mem::size_of::(); . . // Loop through x & y, copying them `Block` at a time . // The optimizer should unroll the loop fully for most types . // N.B. We can't use a for loop as the `range` impl calls `mem::swap` recursively 10 ( 0.00%) let mut i = 0; 180 ( 0.00%) while i + block_size <= len { . // Create some uninitialized memory as scratch space . // Declaring `t` here avoids aligning the stack when this loop is unused . let mut t = mem::MaybeUninit::::uninit(); 30 ( 0.00%) let t = t.as_mut_ptr() as *mut u8; . . // SAFETY: As `i < len`, and as the caller must guarantee that `x` and `y` are valid . // for `len` bytes, `x + i` and `y + i` must be valid addresses, which fulfills the . // safety contract for `add`. . // . // Also, the caller must guarantee that `x` and `y` are valid for writes, properly aligned, . // and non-overlapping, which fulfills the safety contract for `copy_nonoverlapping`. . unsafe { 60 ( 0.00%) let x = x.add(i); 60 ( 0.00%) let y = y.add(i); . . // Swap a block of bytes of x & y, using t as a temporary buffer . // This should be optimized into efficient SIMD operations where available 20 ( 0.00%) copy_nonoverlapping(x, t, block_size); 20 ( 0.00%) copy_nonoverlapping(y, x, block_size); 20 ( 0.00%) copy_nonoverlapping(t, y, block_size); . } 70 ( 0.00%) i += block_size; . } . 30 ( 0.00%) if i < len { . // Swap any remaining bytes . let mut t = mem::MaybeUninit::::uninit(); . let rem = len - i; . . let t = t.as_mut_ptr() as *mut u8; . . // SAFETY: see previous safety comment. . unsafe { -- line 514 ---------------------------------------- -- line 515 ---------------------------------------- . let x = x.add(i); . let y = y.add(i); . . copy_nonoverlapping(x, t, rem); . copy_nonoverlapping(y, x, rem); . copy_nonoverlapping(t, y, rem); . } . } 30 ( 0.00%) } . . /// Moves `src` into the pointed `dst`, returning the previous `dst` value. . /// . /// Neither value is dropped. . /// . /// This function is semantically equivalent to [`mem::replace`] except that it . /// operates on raw pointers instead of references. When references are . /// available, [`mem::replace`] should be preferred. -- line 531 ---------------------------------------- -- line 677 ---------------------------------------- . /// . /// assert_eq!(s, "bar"); . /// ``` . /// . /// [valid]: self#safety . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_ptr_read", issue = "80377")] 14,955,715 ( 0.04%) pub const unsafe fn read(src: *const T) -> T { . // We are calling the intrinsics directly to avoid function calls in the generated code . // as `intrinsics::copy_nonoverlapping` is a wrapper function. . extern "rust-intrinsic" { . #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")] . fn copy_nonoverlapping(src: *const T, dst: *mut T, count: usize); . } . 3,851,106 ( 0.01%) let mut tmp = MaybeUninit::::uninit(); . // SAFETY: the caller must guarantee that `src` is valid for reads. . // `src` cannot overlap `tmp` because `tmp` was just allocated on . // the stack as a separate allocated object. . // . // Also, since we just wrote a valid value into `tmp`, it is guaranteed . // to be properly initialized. . unsafe { 25,713,229 ( 0.07%) copy_nonoverlapping(src, tmp.as_mut_ptr(), 1); 173,380,628 ( 0.50%) tmp.assume_init() . } 7,151,670 ( 0.02%) } . . /// Reads the value from `src` without moving it. This leaves the . /// memory in `src` unchanged. . /// . /// Unlike [`read`], `read_unaligned` works with unaligned pointers. . /// . /// # Safety . /// -- line 712 ---------------------------------------- -- line 872 ---------------------------------------- . /// swap(&mut foo, &mut bar); . /// . /// assert_eq!(foo, "bar"); . /// assert_eq!(bar, "foo"); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")] 10,014,901 ( 0.03%) pub const unsafe fn write(dst: *mut T, src: T) { . // We are calling the intrinsics directly to avoid function calls in the generated code . // as `intrinsics::copy_nonoverlapping` is a wrapper function. . extern "rust-intrinsic" { . #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")] . fn copy_nonoverlapping(src: *const T, dst: *mut T, count: usize); . } . . // SAFETY: the caller must guarantee that `dst` is valid for writes. . // `dst` cannot overlap `src` because the caller has mutable access . // to `dst` while `src` is owned by this function. . unsafe { 398,147,292 ( 1.15%) copy_nonoverlapping(&src as *const T, dst, 1); . intrinsics::forget(src); . } 6,068,416 ( 0.02%) } . . /// Overwrites a memory location with the given value without reading or . /// dropping the old value. . /// . /// Unlike [`write()`], the pointer may be unaligned. . /// . /// `write_unaligned` does not drop the contents of `dst`. This is safe, but it . /// could leak allocations or resources, so care should be taken not to overwrite -- line 903 ---------------------------------------- -- line 1206 ---------------------------------------- . if stride == 1 { . // `stride == 1` case can be computed more simply through `-p (mod a)`, but doing so . // inhibits LLVM's ability to select instructions like `lea`. Instead we compute . // . // round_up_to_next_alignment(p, a) - p . // . // which distributes operations around the load-bearing, but pessimizing `and` sufficiently . // for LLVM to be able to utilize the various optimizations it knows about. 46,747 ( 0.00%) return wrapping_sub( 109,088 ( 0.00%) wrapping_add(p as usize, a_minus_one) & wrapping_sub(0, a), . p as usize, . ); . } . . let pmoda = p as usize & a_minus_one; . if pmoda == 0 { . // Already aligned. Yay! . return 0; -- line 1223 ---------------------------------------- -- line 1347 ---------------------------------------- . /// // Converting the reference to a `*const u8` compares by address. . /// assert!(std::ptr::eq( . /// &wrapper as &dyn Trait as *const dyn Trait as *const u8, . /// &wrapper.member as &dyn Trait as *const dyn Trait as *const u8, . /// )); . /// ``` . #[stable(feature = "ptr_eq", since = "1.17.0")] . #[inline] 51 ( 0.00%) pub fn eq(a: *const T, b: *const T) -> bool { 19,159,854 ( 0.06%) a == b 68 ( 0.00%) } . . /// Hash a raw pointer. . /// . /// This can be used to hash a `&T` reference (which coerces to `*const T` implicitly) . /// by its address rather than the value it points to . /// (which is what the `Hash for &T` implementation does). . /// . /// # Examples -- line 1365 ---------------------------------------- 78,632,773 ( 0.23%) -------------------------------------------------------------------------------- -- 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")] 4,436 ( 0.00%) pub fn from_str_radix(src: &str, radix: u32) -> Result { 2,218 ( 0.00%) from_str_radix(src, radix) 6,654 ( 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 { 1,775,205 ( 0.01%) 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 { 4,742,440 ( 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 { 3,847,979 ( 0.01%) intrinsics::cttz(self) as u32 . } . . /// Returns the number of leading ones in the binary representation of `self`. . /// . /// # Examples . /// . /// Basic usage: . /// -- line 155 ---------------------------------------- -- line 204 ---------------------------------------- . #[doc = concat!("assert_eq!(n.rotate_left(", $rot, "), m);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn rotate_left(self, n: u32) -> Self { 247,745,180 ( 0.71%) 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 429 ---------------------------------------- . )] . #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline] 1,188,455 ( 0.00%) pub const fn checked_add(self, rhs: Self) -> Option { 957,908 ( 0.00%) let (a, b) = self.overflowing_add(rhs); 2,376,910 ( 0.01%) if unlikely!(b) {None} else {Some(a)} 950,764 ( 0.00%) } . . /// Unchecked integer addition. Computes `self + rhs`, assuming overflow . /// cannot occur. . /// . /// # Safety . /// . /// This results in undefined behavior when . #[doc = concat!("`self + rhs > ", stringify!($SelfT), "::MAX` or `self + rhs < ", stringify!($SelfT), "::MIN`,")] -- line 448 ---------------------------------------- -- 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`. 10,991,968 ( 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`. 3,640,937 ( 0.01%) unsafe { intrinsics::unchecked_sub(self, rhs) } . } . . /// Checked integer multiplication. Computes `self * rhs`, returning . /// `None` if overflow occurred. . /// . /// # Examples . /// . /// Basic usage: -- line 541 ---------------------------------------- -- line 544 ---------------------------------------- . #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));")] . #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_mul(2), None);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline] 1,774,440 ( 0.01%) pub const fn checked_mul(self, rhs: Self) -> Option { 1,182,960 ( 0.00%) let (a, b) = self.overflowing_mul(rhs); 2,957,400 ( 0.01%) if unlikely!(b) {None} else {Some(a)} 1,182,960 ( 0.00%) } . . /// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow . /// cannot occur. . /// . /// # Safety . /// . /// This results in undefined behavior when . #[doc = concat!("`self * rhs > ", stringify!($SelfT), "::MAX` or `self * rhs < ", stringify!($SelfT), "::MIN`,")] -- line 563 ---------------------------------------- -- 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 { 2,670,589 ( 0.01%) intrinsics::saturating_add(self, rhs) 3,003 ( 0.00%) } . . /// Saturating addition with a signed integer. Computes `self + rhs`, . /// saturating at the numeric bounds instead of overflowing. . /// . /// # Examples . /// . /// Basic usage: . /// -- line 1052 ---------------------------------------- -- 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 { 116,272 ( 0.00%) intrinsics::saturating_sub(self, rhs) . } . . /// Saturating integer multiplication. Computes `self * rhs`, . /// saturating at the numeric bounds instead of overflowing. . /// . /// # Examples . /// . /// Basic usage: -- line 1100 ---------------------------------------- -- line 1175 ---------------------------------------- . #[doc = concat!("assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::MAX), 199);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn wrapping_add(self, rhs: Self) -> Self { 136,496,704 ( 0.39%) 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 { 34,653,600 ( 0.10%) 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 { 94,902,330 ( 0.27%) intrinsics::wrapping_mul(self, rhs) . } . . /// Wrapping (modular) division. Computes `self / rhs`. . /// Wrapped division on unsigned types is just normal division. . /// There's no way wrapping could ever happen. . /// This function exists, so that all operations . /// are accounted for in the wrapping operations. . /// -- line 1256 ---------------------------------------- -- line 1397 ---------------------------------------- . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn wrapping_shl(self, rhs: u32) -> Self { . // SAFETY: the masking by the bitsize of the type ensures that we do not shift . // out of bounds . unsafe { 8 ( 0.00%) intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT) . } . } . . /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`, . /// where `mask` removes any high-order bits of `rhs` that . /// would cause the shift to exceed the bitwidth of the type. . /// . /// Note that this is *not* the same as a rotate-right; the -- line 1413 ---------------------------------------- -- line 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) { 13,784,160 ( 0.04%) let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT); 475,382 ( 0.00%) (a as Self, b) 950,764 ( 0.00%) } . . /// Calculates `self + rhs + carry` without the ability to overflow. . /// . /// Performs "ternary addition" which takes in an extra bit to add, and may return an . /// additional bit of overflow. This allows for chaining together multiple additions . /// to create "big integers" which represent larger values. . /// . #[doc = concat!("This can be thought of as a ", stringify!($BITS), "-bit \"full adder\", in the electronics sense.")] -- line 1510 ---------------------------------------- -- line 1588 ---------------------------------------- . #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));")] . /// ``` . #[stable(feature = "wrapping", since = "1.7.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) { 3,120,061 ( 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) { 26,607,776 ( 0.08%) let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT); 591,480 ( 0.00%) (a as Self, b) 1,182,960 ( 0.00%) } . . /// Calculates the divisor when `self` is divided by `rhs`. . /// . /// Returns a tuple of the divisor along with a boolean indicating . /// whether an arithmetic overflow would occur. Note that for unsigned . /// integers overflow never occurs, so the second value is always . /// `false`. . /// -- line 1692 ---------------------------------------- -- line 2132 ---------------------------------------- . #[doc = concat!("assert!(16", stringify!($SelfT), ".is_power_of_two());")] . #[doc = concat!("assert!(!10", stringify!($SelfT), ".is_power_of_two());")] . /// ``` . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")] . #[inline(always)] . pub const fn is_power_of_two(self) -> bool { 276 ( 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 { 572,630 ( 0.00%) if self <= 1 { return 0; } . 591,668 ( 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. 1,774,481 ( 0.01%) let z = unsafe { intrinsics::ctlz_nonzero(p) }; 591,823 ( 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 { 610,522 ( 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 ---------------------------------------- -- line 2264 ---------------------------------------- . #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();")] . #[doc = concat!("assert_eq!(bytes, ", $le_bytes, ");")] . /// ``` . #[stable(feature = "int_to_from_bytes", since = "1.32.0")] . #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline] 3,300 ( 0.00%) pub const fn to_le_bytes(self) -> [u8; mem::size_of::()] { 2,640 ( 0.00%) self.to_le().to_ne_bytes() 1,980 ( 0.00%) } . . /// Return the memory representation of this integer as a byte array in . /// native byte order. . /// . /// As the target platform's native endianness is used, portable code . /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, . /// instead. . /// -- line 2282 ---------------------------------------- -- line 2300 ---------------------------------------- . /// ``` . #[stable(feature = "int_to_from_bytes", since = "1.32.0")] . #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . // SAFETY: const sound because integers are plain old datatypes so we can always . // transmute them to arrays of bytes . #[inline] 1,320 ( 0.00%) pub const fn to_ne_bytes(self) -> [u8; mem::size_of::()] { . // SAFETY: integers are plain old datatypes so we can always transmute them to . // arrays of bytes 660 ( 0.00%) unsafe { mem::transmute(self) } 1,980 ( 0.00%) } . . /// Create a native endian integer value from its representation . /// as a byte array in big endian. . /// . #[doc = $from_xe_bytes_doc] . /// . /// # Examples . /// -- line 2320 ---------------------------------------- -- line 2360 ---------------------------------------- . /// *input = rest; . #[doc = concat!(" ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())")] . /// } . /// ``` . #[stable(feature = "int_to_from_bytes", since = "1.32.0")] . #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")] . #[must_use] . #[inline] 2,640 ( 0.00%) pub const fn from_le_bytes(bytes: [u8; mem::size_of::()]) -> Self { 3,300 ( 0.00%) Self::from_le(Self::from_ne_bytes(bytes)) 1,320 ( 0.00%) } . . /// Create a native endian integer value from its memory representation . /// as a byte array in native endianness. . /// . /// As the target platform's native endianness is used, portable code . /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as . /// appropriate instead. . /// -- line 2378 ---------------------------------------- -- line 2402 ---------------------------------------- . /// } . /// ``` . #[stable(feature = "int_to_from_bytes", since = "1.32.0")] . #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")] . #[must_use] . // SAFETY: const sound because integers are plain old datatypes so we can always . // transmute to them . #[inline] 2,640 ( 0.00%) pub const fn from_ne_bytes(bytes: [u8; mem::size_of::()]) -> Self { . // SAFETY: integers are plain old datatypes so we can always transmute to them 3,960 ( 0.00%) unsafe { mem::transmute(bytes) } 1,320 ( 0.00%) } . . /// New code should prefer to use . #[doc = concat!("[`", stringify!($SelfT), "::MIN", "`] instead.")] . /// . /// Returns the smallest value that can be represented by this integer type. . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_promotable] . #[inline(always)] -- line 2421 ---------------------------------------- 3,932,970 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/type_variable.rs -------------------------------------------------------------------------------- Ir -- line 44 ---------------------------------------- . /// Convert from a specific kind of undo to the more general UndoLog . impl<'tcx> From for UndoLog<'tcx> { . fn from(l: Instantiate) -> Self { . UndoLog::Values(sv::UndoLog::Other(l)) . } . } . . impl<'tcx> Rollback> for TypeVariableStorage<'tcx> { 715,206 ( 0.00%) fn reverse(&mut self, undo: UndoLog<'tcx>) { 3,007,768 ( 0.01%) match undo { 568,262 ( 0.00%) UndoLog::EqRelation(undo) => self.eq_relations.reverse(undo), 313,544 ( 0.00%) UndoLog::SubRelation(undo) => self.sub_relations.reverse(undo), 548,606 ( 0.00%) UndoLog::Values(undo) => self.values.reverse(undo), . } 1,430,412 ( 0.00%) } . } . . pub struct TypeVariableStorage<'tcx> { . values: sv::SnapshotVecStorage, . . /// Two variables are unified in `eq_relations` when we have a . /// constraint `?X == ?Y`. This table also stores, for each key, . /// the known value. -- line 66 ---------------------------------------- -- line 136 ---------------------------------------- . DynReturnFn, . LatticeVariable, . } . . pub(crate) struct TypeVariableData { . origin: TypeVariableOrigin, . } . 7,128,244 ( 0.02%) #[derive(Copy, Clone, Debug)] . pub enum TypeVariableValue<'tcx> { . Known { value: Ty<'tcx> }, . Unknown { universe: ty::UniverseIndex }, . } . . impl<'tcx> TypeVariableValue<'tcx> { . /// If this value is known, returns the type it is known to be. . /// Otherwise, `None`. . pub fn known(&self) -> Option> { 4,646,538 ( 0.01%) match *self { . TypeVariableValue::Unknown { .. } => None, . TypeVariableValue::Known { value } => Some(value), . } . } . . pub fn is_unknown(&self) -> bool { . match *self { . TypeVariableValue::Unknown { .. } => true, -- line 162 ---------------------------------------- -- line 166 ---------------------------------------- . } . . pub(crate) struct Instantiate; . . pub(crate) struct Delegate; . . impl<'tcx> TypeVariableStorage<'tcx> { . pub fn new() -> TypeVariableStorage<'tcx> { 452,874 ( 0.00%) TypeVariableStorage { . values: sv::SnapshotVecStorage::new(), . eq_relations: ut::UnificationTableStorage::new(), . sub_relations: ut::UnificationTableStorage::new(), . } . } . . #[inline] . pub(crate) fn with_log<'a>( -- line 182 ---------------------------------------- -- line 188 ---------------------------------------- . } . . impl<'tcx> TypeVariableTable<'_, 'tcx> { . /// Returns the origin that was given when `vid` was created. . /// . /// Note that this function does not return care whether . /// `vid` has been unified with something else or not. . pub fn var_origin(&self, vid: ty::TyVid) -> &TypeVariableOrigin { 14,021 ( 0.00%) &self.storage.values.get(vid.as_usize()).origin . } . . /// Records that `a == b`, depending on `dir`. . /// . /// Precondition: neither `a` nor `b` are known. . pub fn equate(&mut self, a: ty::TyVid, b: ty::TyVid) { . debug_assert!(self.probe(a).is_unknown()); . debug_assert!(self.probe(b).is_unknown()); 79,212 ( 0.00%) self.eq_relations().union(a, b); 67,896 ( 0.00%) self.sub_relations().union(a, b); . } . . /// Records that `a <: b`, depending on `dir`. . /// . /// Precondition: neither `a` nor `b` are known. . pub fn sub(&mut self, a: ty::TyVid, b: ty::TyVid) { . debug_assert!(self.probe(a).is_unknown()); . debug_assert!(self.probe(b).is_unknown()); 81,466 ( 0.00%) self.sub_relations().union(a, b); . } . . /// Instantiates `vid` with the type `ty`. . /// . /// Precondition: `vid` must not have been previously instantiated. 1,370,970 ( 0.00%) pub fn instantiate(&mut self, vid: ty::TyVid, ty: Ty<'tcx>) { . let vid = self.root_var(vid); . debug_assert!(self.probe(vid).is_unknown()); . debug_assert!( . self.eq_relations().probe_value(vid).is_unknown(), . "instantiating type variable `{:?}` twice: new-value = {:?}, old-value={:?}", . vid, . ty, . self.eq_relations().probe_value(vid) . ); 1,919,358 ( 0.01%) self.eq_relations().union_value(vid, TypeVariableValue::Known { value: ty }); . . // Hack: we only need this so that `types_escaping_snapshot` . // can see what has been unified; see the Delegate impl for . // more details. . self.undo_log.push(Instantiate); 1,370,970 ( 0.00%) } . . /// Creates a new type variable. . /// . /// - `diverging`: indicates if this is a "diverging" type . /// variable, e.g., one created as the type of a `return` . /// expression. The code in this module doesn't care if a . /// variable is diverging, but the main Rust type-checker will . /// sometimes "unify" such variables with the `!` or `()` types. . /// - `origin`: indicates *why* the type variable was created. . /// The code in this module doesn't care, but it can be useful . /// for improving error messages. 1,623,336 ( 0.00%) pub fn new_var( . &mut self, . universe: ty::UniverseIndex, . origin: TypeVariableOrigin, . ) -> ty::TyVid { 2,435,004 ( 0.01%) let eq_key = self.eq_relations().new_key(TypeVariableValue::Unknown { universe }); . 1,352,780 ( 0.00%) let sub_key = self.sub_relations().new_key(()); 270,556 ( 0.00%) assert_eq!(eq_key.vid, sub_key); . 2,435,004 ( 0.01%) let index = self.values().push(TypeVariableData { origin }); 1,082,224 ( 0.00%) assert_eq!(eq_key.vid.as_u32(), index as u32); . . debug!("new_var(index={:?}, universe={:?}, origin={:?}", eq_key.vid, universe, origin,); . . eq_key.vid 1,893,892 ( 0.01%) } . . /// Returns the number of type variables created thus far. . pub fn num_vars(&self) -> usize { 25,657 ( 0.00%) self.storage.values.len() . } . . /// Returns the "root" variable of `vid` in the `eq_relations` . /// equivalence table. All type variables that have been equated . /// will yield the same root variable (per the union-find . /// algorithm), so `root_var(a) == root_var(b)` implies that `a == . /// b` (transitively). . pub fn root_var(&mut self, vid: ty::TyVid) -> ty::TyVid { 1,162,770 ( 0.00%) self.eq_relations().find(vid).vid . } . . /// Returns the "root" variable of `vid` in the `sub_relations` . /// equivalence table. All type variables that have been are . /// related via equality or subtyping will yield the same root . /// variable (per the union-find algorithm), so `sub_root_var(a) . /// == sub_root_var(b)` implies that: . /// . /// exists X. (a <: X || X <: a) && (b <: X || X <: b) 5,502 ( 0.00%) pub fn sub_root_var(&mut self, vid: ty::TyVid) -> ty::TyVid { 882,264 ( 0.00%) self.sub_relations().find(vid) 11,004 ( 0.00%) } . . /// Returns `true` if `a` and `b` have same "sub-root" (i.e., exists some . /// type X such that `forall i in {a, b}. (i <: X || X <: i)`. . pub fn sub_unified(&mut self, a: ty::TyVid, b: ty::TyVid) -> bool { . self.sub_root_var(a) == self.sub_root_var(b) . } . . /// Retrieves the type to which `vid` has been instantiated, if . /// any. 16,363,990 ( 0.05%) pub fn probe(&mut self, vid: ty::TyVid) -> TypeVariableValue<'tcx> { . self.inlined_probe(vid) 16,363,990 ( 0.05%) } . . /// An always-inlined variant of `probe`, for very hot call sites. . #[inline(always)] . pub fn inlined_probe(&mut self, vid: ty::TyVid) -> TypeVariableValue<'tcx> { 12,418,736 ( 0.04%) self.eq_relations().inlined_probe_value(vid) . } . . /// If `t` is a type-inference variable, and it has been . /// instantiated, then return the with which it was . /// instantiated. Otherwise, returns `t`. . pub fn replace_if_possible(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { 2,869,248 ( 0.01%) match *t.kind() { 2,381,516 ( 0.01%) ty::Infer(ty::TyVar(v)) => match self.probe(v) { . TypeVariableValue::Unknown { .. } => t, . TypeVariableValue::Known { value } => value, . }, . _ => t, . } . } . . #[inline] -- line 323 ---------------------------------------- -- line 324 ---------------------------------------- . fn values( . &mut self, . ) -> sv::SnapshotVec, &mut InferCtxtUndoLogs<'tcx>> { . self.storage.values.with_log(self.undo_log) . } . . #[inline] . fn eq_relations(&mut self) -> super::UnificationTable<'_, 'tcx, TyVidEqKey<'tcx>> { 14,513,926 ( 0.04%) self.storage.eq_relations.with_log(self.undo_log) . } . . #[inline] . fn sub_relations(&mut self) -> super::UnificationTable<'_, 'tcx, ty::TyVid> { 624,603 ( 0.00%) self.storage.sub_relations.with_log(self.undo_log) . } . . /// Returns a range of the type variables created during the snapshot. 128,285 ( 0.00%) pub fn vars_since_snapshot( . &mut self, . value_count: usize, . ) -> (Range, Vec) { . let range = TyVid::from_usize(value_count)..TyVid::from_usize(self.num_vars()); 153,942 ( 0.00%) ( . range.start..range.end, . (range.start.as_usize()..range.end.as_usize()) . .map(|index| self.storage.values.get(index).origin) . .collect(), . ) 153,942 ( 0.00%) } . . /// Returns indices of all variables that are not yet . /// instantiated. . pub fn unsolved_variables(&mut self) -> Vec { . (0..self.storage.values.len()) . .filter_map(|i| { . let vid = ty::TyVid::from_usize(i); 868,456 ( 0.00%) match self.probe(vid) { . TypeVariableValue::Unknown { .. } => Some(vid), . TypeVariableValue::Known { .. } => None, . } . }) . .collect() . } . } . -- line 368 ---------------------------------------- -- line 391 ---------------------------------------- . /// These structs (a newtyped TyVid) are used as the unification key . /// for the `eq_relations`; they carry a `TypeVariableValue` along . /// with them. . #[derive(Copy, Clone, Debug, PartialEq, Eq)] . pub(crate) struct TyVidEqKey<'tcx> { . vid: ty::TyVid, . . // in the table, we map each ty-vid to one of these: 13,285,383 ( 0.04%) phantom: PhantomData>, . } . . impl<'tcx> From for TyVidEqKey<'tcx> { . #[inline] // make this function eligible for inlining - it is quite hot. . fn from(vid: ty::TyVid) -> Self { . TyVidEqKey { vid, phantom: PhantomData } . } . } -- line 407 ---------------------------------------- -- line 419 ---------------------------------------- . "TyVidEqKey" . } . } . . impl<'tcx> ut::UnifyValue for TypeVariableValue<'tcx> { . type Error = ut::NoError; . . fn unify_values(value1: &Self, value2: &Self) -> Result { 1,153,356 ( 0.00%) match (value1, value2) { . // We never equate two type variables, both of which . // have known types. Instead, we recursively equate . // those types. . (&TypeVariableValue::Known { .. }, &TypeVariableValue::Known { .. }) => { . bug!("equating two type variables, both of which have known types") . } . . // If one side is known, prefer that one. . (&TypeVariableValue::Known { .. }, &TypeVariableValue::Unknown { .. }) => Ok(*value1), . (&TypeVariableValue::Unknown { .. }, &TypeVariableValue::Known { .. }) => Ok(*value2), . . // If both sides are *unknown*, it hardly matters, does it? . ( 11,316 ( 0.00%) &TypeVariableValue::Unknown { universe: universe1 }, 11,316 ( 0.00%) &TypeVariableValue::Unknown { universe: universe2 }, . ) => { . // If we unify two unbound variables, ?T and ?U, then whatever . // value they wind up taking (which must be the same value) must . // be nameable by both universes. Therefore, the resulting . // universe is the minimum of the two universes, because that is . // the one which contains the fewest names in scope. . let universe = cmp::min(universe1, universe2); 45,264 ( 0.00%) Ok(TypeVariableValue::Unknown { universe }) . } . } . } . } 832,665 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/mod.rs -------------------------------------------------------------------------------- Ir -- line 108 ---------------------------------------- . suppress_errors: bool, . }, . } . . impl RegionckMode { . /// Indicates that the MIR borrowck will repeat these region . /// checks, so we should ignore errors if NLL is (unconditionally) . /// enabled. 6,783 ( 0.00%) pub fn for_item_body(tcx: TyCtxt<'_>) -> Self { . // FIXME(Centril): Once we actually remove `::Migrate` also make . // this always `true` and then proceed to eliminate the dead code. 6,783 ( 0.00%) match tcx.borrowck_mode() { . // If we're on Migrate mode, report AST region errors . BorrowckMode::Migrate => RegionckMode::Erase { suppress_errors: false }, . . // If we're on MIR, don't report AST region errors as they should be reported by NLL . BorrowckMode::Mir => RegionckMode::Erase { suppress_errors: true }, . } 13,566 ( 0.00%) } . } . . /// This type contains all the things within `InferCtxt` that sit within a . /// `RefCell` and are involved with taking/rolling back snapshots. Snapshot . /// operations are hot enough that we want only one call to `borrow_mut` per . /// call to `start_snapshot` and `rollback_to`. . pub struct InferCtxtInner<'tcx> { . /// Cache for projections. This cache is snapshotted along with the infcx. -- line 134 ---------------------------------------- -- line 202 ---------------------------------------- . /// type instantiations (`ty::Infer`) to the actual opaque . /// type (`ty::Opaque`). Used during fallback to map unconstrained . /// opaque type inference variables to their corresponding . /// opaque type. . pub opaque_types_vars: FxHashMap, Ty<'tcx>>, . } . . impl<'tcx> InferCtxtInner<'tcx> { 754,790 ( 0.00%) fn new() -> InferCtxtInner<'tcx> { 5,132,572 ( 0.01%) InferCtxtInner { . projection_cache: Default::default(), . type_variable_storage: type_variable::TypeVariableStorage::new(), . undo_log: InferCtxtUndoLogs::default(), . const_unification_storage: ut::UnificationTableStorage::new(), . int_unification_storage: ut::UnificationTableStorage::new(), . float_unification_storage: ut::UnificationTableStorage::new(), 452,874 ( 0.00%) region_constraint_storage: Some(RegionConstraintStorage::new()), . region_obligations: vec![], . opaque_types: Default::default(), . opaque_types_vars: Default::default(), . } 905,748 ( 0.00%) } . . #[inline] . pub fn region_obligations(&self) -> &[(hir::HirId, RegionObligation<'tcx>)] { . &self.region_obligations . } . . #[inline] . pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> { 174,131 ( 0.00%) self.projection_cache.with_log(&mut self.undo_log) . } . . #[inline] . fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> { 6,952,167 ( 0.02%) self.type_variable_storage.with_log(&mut self.undo_log) . } . . #[inline] . fn int_unification_table( . &mut self, . ) -> ut::UnificationTable< . ut::InPlace< . ty::IntVid, . &mut ut::UnificationStorage, . &mut InferCtxtUndoLogs<'tcx>, . >, . > { 35,627 ( 0.00%) self.int_unification_storage.with_log(&mut self.undo_log) . } . . #[inline] . fn float_unification_table( . &mut self, . ) -> ut::UnificationTable< . ut::InPlace< . ty::FloatVid, -- line 258 ---------------------------------------- -- line 268 ---------------------------------------- . &mut self, . ) -> ut::UnificationTable< . ut::InPlace< . ty::ConstVid<'tcx>, . &mut ut::UnificationStorage>, . &mut InferCtxtUndoLogs<'tcx>, . >, . > { 26,951 ( 0.00%) self.const_unification_storage.with_log(&mut self.undo_log) . } . . #[inline] . pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> { 991,557 ( 0.00%) self.region_constraint_storage . .as_mut() . .expect("region constraints already solved") 1,305,350 ( 0.00%) .with_log(&mut self.undo_log) . } . } . . pub struct InferCtxt<'a, 'tcx> { . pub tcx: TyCtxt<'tcx>, . . /// The `DefId` of the item in whose context we are performing inference or typeck. . /// It is used to check whether an opaque type use is a defining use. -- line 292 ---------------------------------------- -- line 361 ---------------------------------------- . /// item we are type-checking, and just consider those names as . /// part of the root universe. So this would only get incremented . /// when we enter into a higher-ranked (`for<..>`) type or trait . /// bound. . universe: Cell, . } . . /// See the `error_reporting` module for more details. 2,334,280 ( 0.01%) #[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable)] . pub enum ValuePairs<'tcx> { . Types(ExpectedFound>), . Regions(ExpectedFound>), . Consts(ExpectedFound<&'tcx ty::Const<'tcx>>), . TraitRefs(ExpectedFound>), . PolyTraitRefs(ExpectedFound>), . } . -- line 377 ---------------------------------------- -- line 383 ---------------------------------------- . pub struct TypeTrace<'tcx> { . cause: ObligationCause<'tcx>, . values: ValuePairs<'tcx>, . } . . /// The origin of a `r1 <= r2` constraint. . /// . /// See `error_reporting` module for more details 1,929,037 ( 0.01%) #[derive(Clone, Debug)] . pub enum SubregionOrigin<'tcx> { . /// Arose from a subtyping relation 112,553 ( 0.00%) Subtype(Box>), . . /// When casting `&'a T` to an `&'b Trait` object, . /// relating `'a` to `'b` . RelateObjectBound(Span), . . /// Some type parameter was instantiated with the given type, . /// and that type must outlive some region. 14,437 ( 0.00%) RelateParamBound(Span, Ty<'tcx>, Option), . . /// The given region parameter was instantiated with a region . /// that must outlive some other region. . RelateRegionParamBound(Span), . . /// Creating a pointer `b` to contents of another reference . Reborrow(Span), . . /// Creating a pointer `b` to contents of an upvar . ReborrowUpvar(Span, ty::UpvarId), . . /// Data with type `Ty<'tcx>` was borrowed 14,298 ( 0.00%) DataBorrowed(Ty<'tcx>, Span), . . /// (&'a &'b T) where a >= b 9,883 ( 0.00%) ReferenceOutlivesReferent(Ty<'tcx>, Span), . . /// Comparing the signature and requirements of an impl method against . /// the containing trait. . CompareImplMethodObligation { span: Span, impl_item_def_id: DefId, trait_item_def_id: DefId }, . . /// Comparing the signature and requirements of an impl associated type . /// against the containing trait . CompareImplTypeObligation { span: Span, impl_item_def_id: DefId, trait_item_def_id: DefId }, -- line 426 ---------------------------------------- -- line 554 ---------------------------------------- . defining_use_anchor: Option, . } . . pub trait TyCtxtInferExt<'tcx> { . fn infer_ctxt(self) -> InferCtxtBuilder<'tcx>; . } . . impl<'tcx> TyCtxtInferExt<'tcx> for TyCtxt<'tcx> { 150,958 ( 0.00%) fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> { 452,874 ( 0.00%) InferCtxtBuilder { tcx: self, defining_use_anchor: None, fresh_typeck_results: None } 150,958 ( 0.00%) } . } . . impl<'tcx> InferCtxtBuilder<'tcx> { . /// Used only by `rustc_typeck` during body type-checking/inference, . /// will initialize `in_progress_typeck_results` with fresh `TypeckResults`. . /// Will also change the scope for opaque type defining use checks to the given owner. 173,295 ( 0.00%) pub fn with_fresh_in_progress_typeck_results(mut self, table_owner: LocalDefId) -> Self { 211,805 ( 0.00%) self.fresh_typeck_results = Some(RefCell::new(ty::TypeckResults::new(table_owner))); 96,275 ( 0.00%) self.with_opaque_type_inference(table_owner) 134,785 ( 0.00%) } . . /// Whenever the `InferCtxt` should be able to handle defining uses of opaque types, . /// you need to call this function. Otherwise the opaque type will be treated opaquely. . /// . /// It is only meant to be called in two places, for typeck . /// (via `with_fresh_in_progress_typeck_results`) and for the inference context used . /// in mir borrowck. 13,624 ( 0.00%) pub fn with_opaque_type_inference(mut self, defining_use_anchor: LocalDefId) -> Self { 6,812 ( 0.00%) self.defining_use_anchor = Some(defining_use_anchor); 52,134 ( 0.00%) self 20,436 ( 0.00%) } . . /// Given a canonical value `C` as a starting point, create an . /// inference context that contains each of the bound values . /// within instantiated as a fresh variable. The `f` closure is . /// invoked with the new infcx, along with the instantiated value . /// `V` and a substitution `S`. This substitution `S` maps from . /// the bound values in `C` to their instantiated values in `V` . /// (in other words, `S(C) = V`). 211,068 ( 0.00%) pub fn enter_with_canonical( . &mut self, . span: Span, . canonical: &Canonical<'tcx, T>, . f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>, T, CanonicalVarValues<'tcx>) -> R, . ) -> R . where . T: TypeFoldable<'tcx>, . { . self.enter(|infcx| { 326,552 ( 0.00%) let (value, subst) = 28,666 ( 0.00%) infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical); 449,805 ( 0.00%) f(infcx, value, subst) . }) 228,101 ( 0.00%) } . 865,799 ( 0.00%) pub fn enter(&mut self, f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>) -> R) -> R { 428,526 ( 0.00%) let InferCtxtBuilder { tcx, defining_use_anchor, ref fresh_typeck_results } = *self; . let in_progress_typeck_results = fresh_typeck_results.as_ref(); 6,482,604 ( 0.02%) f(InferCtxt { . tcx, . defining_use_anchor, . in_progress_typeck_results, 150,958 ( 0.00%) inner: RefCell::new(InferCtxtInner::new()), . lexical_region_resolutions: RefCell::new(None), . selection_cache: Default::default(), . evaluation_cache: Default::default(), . reported_trait_errors: Default::default(), . reported_closure_mismatch: Default::default(), . tainted_by_errors_flag: Cell::new(false), 150,958 ( 0.00%) err_count_on_creation: tcx.sess.err_count(), . in_snapshot: Cell::new(false), . skip_leak_check: Cell::new(false), . universe: Cell::new(ty::UniverseIndex::ROOT), . }) 932,652 ( 0.00%) } . } . . impl<'tcx, T> InferOk<'tcx, T> { . pub fn unit(self) -> InferOk<'tcx, ()> { . InferOk { value: (), obligations: self.obligations } . } . . /// Extracts `value`, registering any obligations into `fulfill_cx`. . pub fn into_value_registering_obligations( . self, . infcx: &InferCtxt<'_, 'tcx>, . fulfill_cx: &mut dyn TraitEngine<'tcx>, . ) -> T { 10,961 ( 0.00%) let InferOk { value, obligations } = self; 38,638 ( 0.00%) for obligation in obligations { . fulfill_cx.register_predicate_obligation(infcx, obligation); . } . value . } . } . . impl<'tcx> InferOk<'tcx, ()> { 250,757 ( 0.00%) pub fn into_obligations(self) -> PredicateObligations<'tcx> { 1,003,028 ( 0.00%) self.obligations 250,757 ( 0.00%) } . } . . #[must_use = "once you start a snapshot, you should always consume it"] . pub struct CombinedSnapshot<'a, 'tcx> { . undo_snapshot: Snapshot<'tcx>, . region_constraints_snapshot: RegionSnapshot, . universe: ty::UniverseIndex, . was_in_snapshot: bool, -- line 662 ---------------------------------------- -- line 674 ---------------------------------------- . let canonical = self.canonicalize_query((a, b), &mut OriginalQueryValues::default()); . debug!("canonical consts: {:?}", &canonical.value); . . self.tcx.try_unify_abstract_consts(canonical.value) . } . . pub fn is_in_snapshot(&self) -> bool { . self.in_snapshot.get() 359,677 ( 0.00%) } . 2,493,504 ( 0.01%) pub fn freshen>(&self, t: T) -> T { 2,805,192 ( 0.01%) t.fold_with(&mut self.freshener()) 2,805,192 ( 0.01%) } . . /// Returns the origin of the type variable identified by `vid`, or `None` . /// if this is not a type variable. . /// . /// No attempt is made to resolve `ty`. 8,302 ( 0.00%) pub fn type_var_origin(&'a self, ty: Ty<'tcx>) -> Option { 16,604 ( 0.00%) match *ty.kind() { 4,151 ( 0.00%) ty::Infer(ty::TyVar(vid)) => { 16,604 ( 0.00%) Some(*self.inner.borrow_mut().type_variables().var_origin(vid)) . } . _ => None, . } 16,604 ( 0.00%) } . 311,688 ( 0.00%) pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> { . freshen::TypeFreshener::new(self, false) 311,688 ( 0.00%) } . . /// Like `freshener`, but does not replace `'static` regions. 1,116,975 ( 0.00%) pub fn freshener_keep_static<'b>(&'b self) -> TypeFreshener<'b, 'tcx> { . freshen::TypeFreshener::new(self, true) 1,116,975 ( 0.00%) } . 30,276 ( 0.00%) pub fn unsolved_variables(&self) -> Vec> { 15,138 ( 0.00%) let mut inner = self.inner.borrow_mut(); 15,138 ( 0.00%) let mut vars: Vec> = inner . .type_variables() . .unsolved_variables() . .into_iter() 8,302 ( 0.00%) .map(|t| self.tcx.mk_ty_var(t)) . .collect(); . vars.extend( . (0..inner.int_unification_table().len()) . .map(|i| ty::IntVid { index: i as u32 }) 3,560 ( 0.00%) .filter(|&vid| inner.int_unification_table().probe_value(vid).is_none()) . .map(|v| self.tcx.mk_int_var(v)), . ); . vars.extend( . (0..inner.float_unification_table().len()) . .map(|i| ty::FloatVid { index: i as u32 }) . .filter(|&vid| inner.float_unification_table().probe_value(vid).is_none()) . .map(|v| self.tcx.mk_float_var(v)), . ); . vars 52,983 ( 0.00%) } . 596,290 ( 0.00%) fn combine_fields( . &'a self, . trace: TypeTrace<'tcx>, . param_env: ty::ParamEnv<'tcx>, . ) -> CombineFields<'a, 'tcx> { 2,394,860 ( 0.01%) CombineFields { . infcx: self, 5,987,150 ( 0.02%) trace, . cause: None, . param_env, . obligations: PredicateObligations::new(), . } 596,290 ( 0.00%) } . . /// Clear the "currently in a snapshot" flag, invoke the closure, . /// then restore the flag to its original value. This flag is a . /// debugging measure designed to detect cases where we start a . /// snapshot, create type variables, and register obligations . /// which may involve those type variables in the fulfillment cx, . /// potentially leaving "dangling type variables" behind. . /// In such cases, an assertion will fail when attempting to -- line 753 ---------------------------------------- -- line 755 ---------------------------------------- . /// better than grovelling through megabytes of `RUSTC_LOG` output. . /// . /// HOWEVER, in some cases the flag is unhelpful. In particular, we . /// sometimes create a "mini-fulfilment-cx" in which we enroll . /// obligations. As long as this fulfillment cx is fully drained . /// before we return, this is not a problem, as there won't be any . /// escaping obligations in the main cx. In those cases, you can . /// use this function. 8 ( 0.00%) pub fn save_and_restore_in_snapshot_flag(&self, func: F) -> R . where . F: FnOnce(&Self) -> R, . { . let flag = self.in_snapshot.replace(false); 153,945 ( 0.00%) let result = func(self); . self.in_snapshot.set(flag); . result 9 ( 0.00%) } . 3,091,690 ( 0.01%) fn start_snapshot(&self) -> CombinedSnapshot<'a, 'tcx> { . debug!("start_snapshot()"); . . let in_snapshot = self.in_snapshot.replace(true); . . let mut inner = self.inner.borrow_mut(); . 9,275,070 ( 0.03%) CombinedSnapshot { . undo_snapshot: inner.undo_log.start_snapshot(), . region_constraints_snapshot: inner.unwrap_region_constraints().start_snapshot(), . universe: self.universe(), . was_in_snapshot: in_snapshot, . // Borrow typeck results "in progress" (i.e., during typeck) . // to ban writes from within a snapshot to them. 1,545,845 ( 0.00%) _in_progress_typeck_results: self . .in_progress_typeck_results . .map(|typeck_results| typeck_results.borrow()), . } 6,183,380 ( 0.02%) } . 3,957,745 ( 0.01%) #[instrument(skip(self, snapshot), level = "debug")] . fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) { . let CombinedSnapshot { 359,795 ( 0.00%) undo_snapshot, 359,795 ( 0.00%) region_constraints_snapshot, 359,795 ( 0.00%) universe, 359,795 ( 0.00%) was_in_snapshot, 719,590 ( 0.00%) _in_progress_typeck_results, . } = snapshot; . . self.in_snapshot.set(was_in_snapshot); . self.universe.set(universe); . . let mut inner = self.inner.borrow_mut(); 359,795 ( 0.00%) inner.rollback_to(undo_snapshot); . inner.unwrap_region_constraints().rollback_to(region_constraints_snapshot); . } . 17,790,750 ( 0.05%) #[instrument(skip(self, snapshot), level = "debug")] . fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) { . let CombinedSnapshot { 1,186,050 ( 0.00%) undo_snapshot, . region_constraints_snapshot: _, . universe: _, 1,186,050 ( 0.00%) was_in_snapshot, 2,372,100 ( 0.01%) _in_progress_typeck_results, . } = snapshot; . . self.in_snapshot.set(was_in_snapshot); . . self.inner.borrow_mut().commit(undo_snapshot); . } . . /// Executes `f` and commit the bindings. 722,162 ( 0.00%) #[instrument(skip(self, f), level = "debug")] 924,015 ( 0.00%) pub fn commit_unconditionally(&self, f: F) -> R . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R, . { 84,105 ( 0.00%) let snapshot = self.start_snapshot(); 322,886 ( 0.00%) let r = f(&snapshot); 587,975 ( 0.00%) self.commit_from(snapshot); 732,931 ( 0.00%) r . } . . /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`. 7,274,944 ( 0.02%) #[instrument(skip(self, f), level = "debug")] 8,959,512 ( 0.03%) pub fn commit_if_ok(&self, f: F) -> Result . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result, . { 1,416,090 ( 0.00%) let snapshot = self.start_snapshot(); 4,136,467 ( 0.01%) let r = f(&snapshot); . debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok()); 1,238,403 ( 0.00%) match r { . Ok(_) => { 8,031,008 ( 0.02%) self.commit_from(snapshot); . } . Err(_) => { 1,402,709 ( 0.00%) self.rollback_to("commit_if_ok -- error", snapshot); . } . } 7,323,476 ( 0.02%) r . } . . /// Execute `f` then unroll any bindings it creates. 1,319,546 ( 0.00%) #[instrument(skip(self, f), level = "debug")] 1,522,200 ( 0.00%) pub fn probe(&self, f: F) -> R . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R, . { 426,565 ( 0.00%) let snapshot = self.start_snapshot(); 593,195 ( 0.00%) let r = f(&snapshot); 1,995,523 ( 0.01%) self.rollback_to("probe", snapshot); 501,799 ( 0.00%) r . } . . /// If `should_skip` is true, then execute `f` then unroll any bindings it creates. 468 ( 0.00%) #[instrument(skip(self, f), level = "debug")] 624 ( 0.00%) pub fn probe_maybe_skip_leak_check(&self, should_skip: bool, f: F) -> R . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R, . { 104 ( 0.00%) let snapshot = self.start_snapshot(); 52 ( 0.00%) let was_skip_leak_check = self.skip_leak_check.get(); 104 ( 0.00%) if should_skip { . self.skip_leak_check.set(true); . } 208 ( 0.00%) let r = f(&snapshot); 468 ( 0.00%) self.rollback_to("probe", snapshot); . self.skip_leak_check.set(was_skip_leak_check); 624 ( 0.00%) r . } . . /// Scan the constraints produced since `snapshot` began and returns: . /// . /// - `None` -- if none of them involve "region outlives" constraints . /// - `Some(true)` -- if there are `'a: 'b` constraints where `'a` or `'b` is a placeholder . /// - `Some(false)` -- if there are `'a: 'b` constraints but none involve placeholders 128,748 ( 0.00%) pub fn region_constraints_added_in_snapshot( . &self, . snapshot: &CombinedSnapshot<'a, 'tcx>, . ) -> Option { 257,496 ( 0.00%) self.inner . .borrow_mut() . .unwrap_region_constraints() . .region_constraints_added_in_snapshot(&snapshot.undo_snapshot) 193,122 ( 0.00%) } . . pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) { . self.inner.borrow_mut().unwrap_region_constraints().add_given(sub, sup); . } . 71,940 ( 0.00%) pub fn can_sub(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx> . where . T: at::ToTrace<'tcx>, . { . let origin = &ObligationCause::dummy(); . self.probe(|_| { . self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| { . // Ignore obligations, since we are unrolling . // everything anyway. . }) . }) 53,955 ( 0.00%) } . 88,932 ( 0.00%) pub fn can_eq(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx> . where . T: at::ToTrace<'tcx>, . { . let origin = &ObligationCause::dummy(); . self.probe(|_| { . self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| { . // Ignore obligations, since we are unrolling . // everything anyway. . }) . }) 66,699 ( 0.00%) } . 543,360 ( 0.00%) #[instrument(skip(self), level = "debug")] . pub fn sub_regions( . &self, . origin: SubregionOrigin<'tcx>, . a: ty::Region<'tcx>, . b: ty::Region<'tcx>, . ) { 489,024 ( 0.00%) self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b); . } . . /// Require that the region `r` be equal to one of the regions in . /// the set `regions`. . #[instrument(skip(self), level = "debug")] . pub fn member_constraint( . &self, . opaque_type_def_id: DefId, -- line 947 ---------------------------------------- -- line 969 ---------------------------------------- . /// to `subtype_predicate` -- that is, "coercing" `a` to `b` winds up . /// actually requiring `a <: b`. This is of course a valid coercion, . /// but it's not as flexible as `FnCtxt::coerce` would be. . /// . /// (We may refactor this in the future, but there are a number of . /// practical obstacles. Among other things, `FnCtxt::coerce` presently . /// records adjustments that are required on the HIR in order to perform . /// the coercion, and we don't currently have a way to manage that.) 3,612 ( 0.00%) pub fn coerce_predicate( . &self, . cause: &ObligationCause<'tcx>, . param_env: ty::ParamEnv<'tcx>, . predicate: ty::PolyCoercePredicate<'tcx>, . ) -> Option> { 2,408 ( 0.00%) let subtype_predicate = predicate.map_bound(|p| ty::SubtypePredicate { . a_is_expected: false, // when coercing from `a` to `b`, `b` is expected . a: p.a, . b: p.b, . }); 6,020 ( 0.00%) self.subtype_predicate(cause, param_env, subtype_predicate) 4,816 ( 0.00%) } . 124,824 ( 0.00%) pub fn subtype_predicate( . &self, . cause: &ObligationCause<'tcx>, . param_env: ty::ParamEnv<'tcx>, . predicate: ty::PolySubtypePredicate<'tcx>, . ) -> Option> { . // Check for two unresolved inference variables, in which case we can . // make no progress. This is partly a micro-optimization, but it's . // also an opportunity to "sub-unify" the variables. This isn't -- line 999 ---------------------------------------- -- line 1002 ---------------------------------------- . // earlier that they are sub-unified). . // . // Note that we can just skip the binders here because . // type variables can't (at present, at . // least) capture any of the things bound by this binder. . // . // Note that this sub here is not just for diagnostics - it has semantic . // effects as well. 10,402 ( 0.00%) let r_a = self.shallow_resolve(predicate.skip_binder().a); 10,402 ( 0.00%) let r_b = self.shallow_resolve(predicate.skip_binder().b); 73,720 ( 0.00%) match (r_a.kind(), r_b.kind()) { 16,058 ( 0.00%) (&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => { . self.inner.borrow_mut().type_variables().sub(a_vid, b_vid); 16,058 ( 0.00%) return None; . } . _ => {} . } . . Some(self.commit_if_ok(|_snapshot| { 2,373 ( 0.00%) let ty::SubtypePredicate { a_is_expected, a, b } = . self.replace_bound_vars_with_placeholders(predicate); . 4,746 ( 0.00%) let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?; . . Ok(ok.unit()) . })) 93,618 ( 0.00%) } . 149,820 ( 0.00%) pub fn region_outlives_predicate( . &self, . cause: &traits::ObligationCause<'tcx>, . predicate: ty::PolyRegionOutlivesPredicate<'tcx>, . ) -> UnitResult<'tcx> { . self.commit_if_ok(|_snapshot| { . let ty::OutlivesPredicate(r_a, r_b) = . self.replace_bound_vars_with_placeholders(predicate); . let origin = SubregionOrigin::from_obligation_cause(cause, || { . RelateRegionParamBound(cause.span) . }); 124,850 ( 0.00%) self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b` . Ok(()) . }) 99,880 ( 0.00%) } . . /// Number of type variables created so far. 786 ( 0.00%) pub fn num_ty_vars(&self) -> usize { . self.inner.borrow_mut().type_variables().num_vars() 1,572 ( 0.00%) } . 269,908 ( 0.00%) pub fn next_ty_var_id(&self, origin: TypeVariableOrigin) -> TyVid { 1,349,540 ( 0.00%) self.inner.borrow_mut().type_variables().new_var(self.universe(), origin) 404,862 ( 0.00%) } . 231,416 ( 0.00%) pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> { 925,432 ( 0.00%) self.tcx.mk_ty_var(self.next_ty_var_id(origin)) 347,124 ( 0.00%) } . 19,582 ( 0.00%) pub fn next_ty_var_in_universe( . &self, . origin: TypeVariableOrigin, . universe: ty::UniverseIndex, . ) -> Ty<'tcx> { 107,701 ( 0.00%) let vid = self.inner.borrow_mut().type_variables().new_var(universe, origin); 9,791 ( 0.00%) self.tcx.mk_ty_var(vid) 29,373 ( 0.00%) } . . pub fn next_const_var( . &self, . ty: Ty<'tcx>, . origin: ConstVariableOrigin, . ) -> &'tcx ty::Const<'tcx> { . self.tcx.mk_const_var(self.next_const_var_id(origin), ty) . } -- line 1074 ---------------------------------------- -- line 1090 ---------------------------------------- . pub fn next_const_var_id(&self, origin: ConstVariableOrigin) -> ConstVid<'tcx> { . self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue { . origin, . val: ConstVariableValue::Unknown { universe: self.universe() }, . }) . } . . fn next_int_var_id(&self) -> IntVid { 4,475 ( 0.00%) self.inner.borrow_mut().int_unification_table().new_key(None) . } . 2,685 ( 0.00%) pub fn next_int_var(&self) -> Ty<'tcx> { . self.tcx.mk_int_var(self.next_int_var_id()) 3,580 ( 0.00%) } . . fn next_float_var_id(&self) -> FloatVid { . self.inner.borrow_mut().float_unification_table().new_key(None) . } . . pub fn next_float_var(&self) -> Ty<'tcx> { . self.tcx.mk_float_var(self.next_float_var_id()) . } . . /// Creates a fresh region variable with the next available index. . /// The variable will be created in the maximum universe created . /// thus far, allowing it to name any region created thus far. 95,079 ( 0.00%) pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> { 2,143,156 ( 0.01%) self.next_region_var_in_universe(origin, self.universe()) 190,158 ( 0.00%) } . . /// Creates a fresh region variable with the next available index . /// in the given universe; typically, you can use . /// `next_region_var` and just use the maximal universe. 907,314 ( 0.00%) pub fn next_region_var_in_universe( . &self, . origin: RegionVariableOrigin, . universe: ty::UniverseIndex, . ) -> ty::Region<'tcx> { . let region_var = 5,897,541 ( 0.02%) self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin); 2,268,285 ( 0.01%) self.tcx.mk_region(ty::ReVar(region_var)) 1,360,971 ( 0.00%) } . . /// Return the universe that the region `r` was created in. For . /// most regions (e.g., `'static`, named regions from the user, . /// etc) this is the root universe U0. For inference variables or . /// placeholders, however, it will return the universe which which . /// they are associated. 147,824 ( 0.00%) pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex { . self.inner.borrow_mut().unwrap_region_constraints().universe(r) 221,736 ( 0.00%) } . . /// Number of region variables created so far. 54,554 ( 0.00%) pub fn num_region_vars(&self) -> usize { . self.inner.borrow_mut().unwrap_region_constraints().num_region_vars() 81,831 ( 0.00%) } . . /// Just a convenient wrapper of `next_region_var` for using during NLL. 186,883 ( 0.00%) pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin) -> ty::Region<'tcx> { . self.next_region_var(RegionVariableOrigin::Nll(origin)) 373,766 ( 0.00%) } . . /// Just a convenient wrapper of `next_region_var` for using during NLL. 203 ( 0.00%) pub fn next_nll_region_var_in_universe( . &self, . origin: NllRegionVariableOrigin, . universe: ty::UniverseIndex, . ) -> ty::Region<'tcx> { 5,145 ( 0.00%) self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe) 406 ( 0.00%) } . 1,470,984 ( 0.00%) pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> { 783,899 ( 0.00%) match param.kind { . GenericParamDefKind::Lifetime => { . // Create a region inference variable for the given . // region parameter definition. 67,733 ( 0.00%) self.next_region_var(EarlyBoundRegion(span, param.name)).into() . } . GenericParamDefKind::Type { .. } => { . // Create a type inference variable for the given . // type parameter definition. The substitutions are . // for actual parameters that may be referred to by . // the default of this type parameter, if it exists. . // e.g., `struct Foo(...);` when . // used in a path such as `Foo::::new()` will . // use an inference variable for `C` with `[T, U]` . // as the substitutions for the default, `(T, U)`. 463,764 ( 0.00%) let ty_var_id = self.inner.borrow_mut().type_variables().new_var( . self.universe(), 579,705 ( 0.00%) TypeVariableOrigin { . kind: TypeVariableOriginKind::TypeParameterDefinition( 115,941 ( 0.00%) param.name, 115,941 ( 0.00%) Some(param.def_id), . ), . span, . }, . ); . 115,941 ( 0.00%) self.tcx.mk_ty_var(ty_var_id).into() . } . GenericParamDefKind::Const { .. } => { . let origin = ConstVariableOrigin { . kind: ConstVariableOriginKind::ConstParameterDefinition( . param.name, . param.def_id, . ), . span, . }; . let const_var_id = 2,189 ( 0.00%) self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue { . origin, . val: ConstVariableValue::Unknown { universe: self.universe() }, . }); 199 ( 0.00%) self.tcx.mk_const_var(const_var_id, self.tcx.type_of(param.def_id)).into() . } . } 1,592 ( 0.00%) } . . /// Given a set of generics defined on a type or impl, returns a substitution mapping each . /// type/region parameter to a fresh inference variable. 223,647 ( 0.00%) pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> { 1,105,514 ( 0.00%) InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param)) 149,098 ( 0.00%) } . . /// Returns `true` if errors have been reported since this infcx was . /// created. This is sometimes used as a heuristic to skip . /// reporting errors that often occur as a result of earlier . /// errors, but where it's hard to be 100% sure (e.g., unresolved . /// inference variables, regionck errors). 21,868 ( 0.00%) pub fn is_tainted_by_errors(&self) -> bool { . debug!( . "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \ . tainted_by_errors_flag={})", . self.tcx.sess.err_count(), . self.err_count_on_creation, . self.tainted_by_errors_flag.get() . ); . 473,732 ( 0.00%) if self.tcx.sess.err_count() > self.err_count_on_creation { . return true; // errors reported since this infcx was made . } . self.tainted_by_errors_flag.get() 32,802 ( 0.00%) } . . /// Set the "tainted by errors" flag to true. We call this when we . /// observe an error from a prior pass. . pub fn set_tainted_by_errors(&self) { . debug!("set_tainted_by_errors()"); . self.tainted_by_errors_flag.set(true) . } . . /// Process the region constraints and return any any errors that . /// result. After this, no more unification operations should be . /// done -- or the compiler will panic -- but it is legal to use . /// `resolve_vars_if_possible` as well as `fully_resolve`. 463,393 ( 0.00%) pub fn resolve_regions( . &self, . region_context: DefId, . outlives_env: &OutlivesEnvironment<'tcx>, . mode: RegionckMode, . ) -> Vec> { 1,257,781 ( 0.00%) let (var_infos, data) = { . let mut inner = self.inner.borrow_mut(); . let inner = &mut *inner; 66,199 ( 0.00%) assert!( 198,597 ( 0.00%) self.is_tainted_by_errors() || inner.region_obligations.is_empty(), . "region_obligations not empty: {:#?}", . inner.region_obligations . ); . inner . .region_constraint_storage . .take() . .expect("regions already resolved") . .with_log(&mut inner.undo_log) . .into_infos_and_data() 66,199 ( 0.00%) }; . . let region_rels = 66,199 ( 0.00%) &RegionRelations::new(self.tcx, region_context, outlives_env.free_region_map()); . 595,791 ( 0.00%) let (lexical_region_resolutions, errors) = 1,588,776 ( 0.00%) lexical_region_resolve::resolve(region_rels, var_infos, data, mode); . 264,796 ( 0.00%) let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions)); 66,199 ( 0.00%) assert!(old_value.is_none()); . . errors 595,791 ( 0.00%) } . . /// Process the region constraints and report any errors that . /// result. After this, no more unification operations should be . /// done -- or the compiler will panic -- but it is legal to use . /// `resolve_vars_if_possible` as well as `fully_resolve`. 661,990 ( 0.00%) pub fn resolve_regions_and_report_errors( . &self, . region_context: DefId, . outlives_env: &OutlivesEnvironment<'tcx>, . mode: RegionckMode, . ) { 132,398 ( 0.00%) let errors = self.resolve_regions(region_context, outlives_env, mode); . 198,597 ( 0.00%) if !self.is_tainted_by_errors() { . // As a heuristic, just skip reporting region errors . // altogether if other errors have been reported while . // this infcx was in use. This is totally hokey but . // otherwise we have a hard time separating legit region . // errors from silly ones. 132,398 ( 0.00%) self.report_region_errors(&errors); . } 330,995 ( 0.00%) } . . /// Obtains (and clears) the current set of region . /// constraints. The inference context is still usable: further . /// unifications will simply add new constraints. . /// . /// This method is not meant to be used with normal lexical region . /// resolution. Rather, it is used in the NLL mode as a kind of . /// interim hack: basically we run normal type-check and generate -- line 1307 ---------------------------------------- -- line 1319 ---------------------------------------- . } . . /// Gives temporary access to the region constraint data. . pub fn with_region_constraints( . &self, . op: impl FnOnce(&RegionConstraintData<'tcx>) -> R, . ) -> R { . let mut inner = self.inner.borrow_mut(); 113,988 ( 0.00%) op(inner.unwrap_region_constraints().data()) . } . . pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin { . let mut inner = self.inner.borrow_mut(); . let inner = &mut *inner; . inner . .region_constraint_storage . .as_mut() -- line 1335 ---------------------------------------- -- line 1338 ---------------------------------------- . .var_origin(vid) . } . . /// Takes ownership of the list of variable regions. This implies . /// that all the region constraints have already been taken, and . /// hence that `resolve_regions_and_report_errors` can never be . /// called. This is used only during NLL processing to "hand off" ownership . /// of the set of region variables into the NLL region context. 34,060 ( 0.00%) pub fn take_region_var_origins(&self) -> VarInfos { . let mut inner = self.inner.borrow_mut(); 129,428 ( 0.00%) let (var_infos, data) = inner . .region_constraint_storage . .take() . .expect("regions already resolved") . .with_log(&mut inner.undo_log) 6,812 ( 0.00%) .into_infos_and_data(); 6,812 ( 0.00%) assert!(data.is_empty()); . var_infos 54,496 ( 0.00%) } . . pub fn ty_to_string(&self, t: Ty<'tcx>) -> String { . self.resolve_vars_if_possible(t).to_string() . } . . /// If `TyVar(vid)` resolves to a type, return that type. Else, return the . /// universe index of `TyVar(vid)`. 155,504 ( 0.00%) pub fn probe_ty_var(&self, vid: TyVid) -> Result, ty::UniverseIndex> { . use self::type_variable::TypeVariableValue; . 466,512 ( 0.00%) match self.inner.borrow_mut().type_variables().probe(vid) { . TypeVariableValue::Known { value } => Ok(value), . TypeVariableValue::Unknown { universe } => Err(universe), . } 544,264 ( 0.00%) } . . /// Resolve any type variables found in `value` -- but only one . /// level. So, if the variable `?X` is bound to some type . /// `Foo`, then this would return `Foo` (but `?Y` may . /// itself be bound to a type). . /// . /// Useful when you only need to inspect the outermost level of . /// the type and don't care about nested types (or perhaps you . /// will be resolving them as well, e.g. in a loop). . pub fn shallow_resolve(&self, value: T) -> T . where . T: TypeFoldable<'tcx>, . { 2,542,236 ( 0.01%) value.fold_with(&mut ShallowResolver { infcx: self }) . } . 187,004 ( 0.00%) pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid { . self.inner.borrow_mut().type_variables().root_var(var) 280,506 ( 0.00%) } . . /// Where possible, replaces type/const variables in . /// `value` with their final value. Note that region variables . /// are unaffected. If a type/const variable has not been unified, it . /// is left as is. This is an idempotent operation that does . /// not affect inference state in any way and so you can do it . /// at will. 1,768 ( 0.00%) pub fn resolve_vars_if_possible(&self, value: T) -> T . where . T: TypeFoldable<'tcx>, . { 2,378,698 ( 0.01%) if !value.needs_infer() { 1,752,715 ( 0.01%) return value; // Avoid duplicated subst-folding. . } 2,540,129 ( 0.01%) let mut r = resolve::OpportunisticVarResolver::new(self); 3,127,361 ( 0.01%) value.fold_with(&mut r) 1,846 ( 0.00%) } . . /// Returns the first unresolved variable contained in `T`. In the . /// process of visiting `T`, this will resolve (where possible) . /// type variables in `T`, but it never constructs the final, . /// resolved type, so it's more efficient than . /// `resolve_vars_if_possible()`. . pub fn unresolved_type_vars(&self, value: &T) -> Option<(Ty<'tcx>, Option)> . where -- line 1415 ---------------------------------------- -- line 1490 ---------------------------------------- . expected: &'tcx ty::Const<'tcx>, . actual: &'tcx ty::Const<'tcx>, . err: TypeError<'tcx>, . ) -> DiagnosticBuilder<'tcx> { . let trace = TypeTrace::consts(cause, true, expected, actual); . self.report_and_explain_type_error(trace, &err) . } . 249,750 ( 0.00%) pub fn replace_bound_vars_with_fresh_vars( . &self, . span: Span, . lbrct: LateBoundRegionConversionTime, . value: ty::Binder<'tcx, T>, . ) -> (T, BTreeMap>) . where . T: TypeFoldable<'tcx>, . { . let fld_r = 861,426 ( 0.00%) |br: ty::BoundRegion| self.next_region_var(LateBoundRegion(span, br.kind, lbrct)); . let fld_t = |_| { . self.next_ty_var(TypeVariableOrigin { . kind: TypeVariableOriginKind::MiscVariable, . span, . }) . }; . let fld_c = |_, ty| { . self.next_const_var( . ty, . ConstVariableOrigin { kind: ConstVariableOriginKind::MiscVariable, span }, . ) . }; 2,787,188 ( 0.01%) self.tcx.replace_bound_vars(value, fld_r, fld_t, fld_c) 166,500 ( 0.00%) } . . /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method. 71,016 ( 0.00%) pub fn verify_generic_bound( . &self, . origin: SubregionOrigin<'tcx>, . kind: GenericKind<'tcx>, . a: ty::Region<'tcx>, . bound: VerifyBound<'tcx>, . ) { . debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound); . 26,631 ( 0.00%) self.inner . .borrow_mut() . .unwrap_region_constraints() 150,909 ( 0.00%) .verify_generic_bound(origin, kind, a, bound); 62,139 ( 0.00%) } . . /// Obtains the latest type of the given closure; this may be a . /// closure in the current function, in which case its . /// `ClosureKind` may not yet be known. 334 ( 0.00%) pub fn closure_kind(&self, closure_substs: SubstsRef<'tcx>) -> Option { 668 ( 0.00%) let closure_kind_ty = closure_substs.as_closure().kind_ty(); . let closure_kind_ty = self.shallow_resolve(closure_kind_ty); 501 ( 0.00%) closure_kind_ty.to_opt_closure_kind() . } . . /// Clears the selection, evaluation, and projection caches. This is useful when . /// repeatedly attempting to select an `Obligation` while changing only . /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing. . pub fn clear_caches(&self) { . self.selection_cache.clear(); . self.evaluation_cache.clear(); . self.inner.borrow_mut().projection_cache().clear(); . } . . pub fn universe(&self) -> ty::UniverseIndex { 3,968,922 ( 0.01%) self.universe.get() 1,385,003 ( 0.00%) } . . /// Creates and return a fresh universe that extends all previous . /// universes. Updates `self.universe` to that new universe. 1,400 ( 0.00%) pub fn create_next_universe(&self) -> ty::UniverseIndex { 1,568 ( 0.00%) let u = self.universe.get().next_universe(); . self.universe.set(u); . u 1,400 ( 0.00%) } . . /// Resolves and evaluates a constant. . /// . /// The constant can be located on a trait like `::C`, in which case the given . /// substitutions and environment are used to resolve the constant. Alternatively if the . /// constant has generic parameters in scope the substitutions are used to evaluate the value of . /// the constant. For example in `fn foo() { let _ = [0; bar::()]; }` the repeat count . /// constant `bar::()` requires a substitution for `T`, if the substitution for `T` is still -- line 1576 ---------------------------------------- -- line 1606 ---------------------------------------- . // variables, thus we don't need to substitute back the original values. . self.tcx.const_eval_resolve(param_env_erased, unevaluated, span) . } . . /// If `typ` is a type variable of some kind, resolve it one level . /// (but do not resolve types found in the result). If `typ` is . /// not a type variable, just return it unmodified. . // FIXME(eddyb) inline into `ShallowResolver::visit_ty`. 27,986,888 ( 0.08%) fn shallow_resolve_ty(&self, typ: Ty<'tcx>) -> Ty<'tcx> { 15,154,934 ( 0.04%) match *typ.kind() { . ty::Infer(ty::TyVar(v)) => { . // Not entirely obvious: if `typ` is a type variable, . // it can be resolved to an int/float variable, which . // can then be recursively resolved, hence the . // recursion. Note though that we prevent type . // variables from unifying to other type variables . // directly (though they may be embedded . // structurally), and we prevent cycles in any case, . // so this recursion should always be of very limited . // depth. . // . // Note: if these two lines are combined into one we get . // dynamic borrow errors on `self.inner`. 8,092,780 ( 0.02%) let known = self.inner.borrow_mut().type_variables().probe(v).known(); . known.map_or(typ, |t| self.shallow_resolve_ty(t)) . } . 75,420 ( 0.00%) ty::Infer(ty::IntVar(v)) => self . .inner . .borrow_mut() . .int_unification_table() . .probe_value(v) 21,756 ( 0.00%) .map(|v| v.to_type(self.tcx)) . .unwrap_or(typ), . . ty::Infer(ty::FloatVar(v)) => self . .inner . .borrow_mut() . .float_unification_table() . .probe_value(v) . .map(|v| v.to_type(self.tcx)) . .unwrap_or(typ), . . _ => typ, . } 31,485,249 ( 0.09%) } . . /// `ty_or_const_infer_var_changed` is equivalent to one of these two: . /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`) . /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`) . /// . /// However, `ty_or_const_infer_var_changed` is more efficient. It's always . /// inlined, despite being large, because it has only two call sites that . /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on` -- line 1659 ---------------------------------------- -- line 1662 ---------------------------------------- . #[inline(always)] . pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar<'tcx>) -> bool { . match infer_var { . TyOrConstInferVar::Ty(v) => { . use self::type_variable::TypeVariableValue; . . // If `inlined_probe` returns a `Known` value, it never equals . // `ty::Infer(ty::TyVar(v))`. 14,786,368 ( 0.04%) match self.inner.borrow_mut().type_variables().inlined_probe(v) { . TypeVariableValue::Unknown { .. } => false, . TypeVariableValue::Known { .. } => true, . } . } . . TyOrConstInferVar::TyInt(v) => { . // If `inlined_probe_value` returns a value it's always a . // `ty::Int(_)` or `ty::UInt(_)`, which never matches a . // `ty::Infer(_)`. 1,192 ( 0.00%) self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_some() . } . . TyOrConstInferVar::TyFloat(v) => { . // If `probe_value` returns a value it's always a . // `ty::Float(_)`, which never matches a `ty::Infer(_)`. . // . // Not `inlined_probe_value(v)` because this call site is colder. . self.inner.borrow_mut().float_unification_table().probe_value(v).is_some() -- line 1688 ---------------------------------------- -- line 1716 ---------------------------------------- . /// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`. . Const(ConstVid<'tcx>), . } . . impl<'tcx> TyOrConstInferVar<'tcx> { . /// Tries to extract an inference variable from a type or a constant, returns `None` . /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and . /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`). 101,904 ( 0.00%) pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option { . match arg.unpack() { . GenericArgKind::Type(ty) => Self::maybe_from_ty(ty), . GenericArgKind::Const(ct) => Self::maybe_from_const(ct), . GenericArgKind::Lifetime(_) => None, . } 101,904 ( 0.00%) } . . /// Tries to extract an inference variable from a type, returns `None` . /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`). 16,042 ( 0.00%) pub fn maybe_from_ty(ty: Ty<'tcx>) -> Option { 1,059,290 ( 0.00%) match *ty.kind() { 235,128 ( 0.00%) ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)), 180 ( 0.00%) ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)), . ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)), . _ => None, . } 16,042 ( 0.00%) } . . /// Tries to extract an inference variable from a constant, returns `None` . /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`). . pub fn maybe_from_const(ct: &'tcx ty::Const<'tcx>) -> Option { . match ct.val { . ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)), . _ => None, . } -- line 1749 ---------------------------------------- -- line 1755 ---------------------------------------- . } . . impl<'a, 'tcx> TypeFolder<'tcx> for ShallowResolver<'a, 'tcx> { . fn tcx<'b>(&'b self) -> TyCtxt<'tcx> { . self.infcx.tcx . } . . fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> { 5,297,926 ( 0.02%) self.infcx.shallow_resolve_ty(ty) . } . 6,596 ( 0.00%) fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> { 3,764 ( 0.00%) if let ty::Const { val: ty::ConstKind::Infer(InferConst::Var(vid)), .. } = ct { 1,165 ( 0.00%) self.infcx . .inner . .borrow_mut() . .const_unification_table() 699 ( 0.00%) .probe_value(*vid) . .val . .known() . .unwrap_or(ct) . } else { . ct . } 8,245 ( 0.00%) } . } . . impl<'tcx> TypeTrace<'tcx> { . pub fn span(&self) -> Span { 336 ( 0.00%) self.cause.span . } . . pub fn types( . cause: &ObligationCause<'tcx>, . a_is_expected: bool, . a: Ty<'tcx>, . b: Ty<'tcx>, . ) -> TypeTrace<'tcx> { -- line 1792 ---------------------------------------- -- line 1800 ---------------------------------------- . b: &'tcx ty::Const<'tcx>, . ) -> TypeTrace<'tcx> { . TypeTrace { cause: cause.clone(), values: Consts(ExpectedFound::new(a_is_expected, a, b)) } . } . } . . impl<'tcx> SubregionOrigin<'tcx> { . pub fn span(&self) -> Span { 840 ( 0.00%) match *self { 168 ( 0.00%) Subtype(ref a) => a.span(), . RelateObjectBound(a) => a, . RelateParamBound(a, ..) => a, . RelateRegionParamBound(a) => a, . Reborrow(a) => a, . ReborrowUpvar(a, _) => a, . DataBorrowed(_, a) => a, . ReferenceOutlivesReferent(_, a) => a, . CompareImplMethodObligation { span, .. } => span, -- line 1817 ---------------------------------------- -- line 1818 ---------------------------------------- . CompareImplTypeObligation { span, .. } => span, . } . } . . pub fn from_obligation_cause(cause: &traits::ObligationCause<'tcx>, default: F) -> Self . where . F: FnOnce() -> Self, . { 178,076 ( 0.00%) match *cause.code() { 24,347 ( 0.00%) traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => { 121,735 ( 0.00%) SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span) . } . . traits::ObligationCauseCode::CompareImplMethodObligation { . impl_item_def_id, . trait_item_def_id, . } => SubregionOrigin::CompareImplMethodObligation { . span: cause.span, . impl_item_def_id, -- line 1836 ---------------------------------------- 29,880,847 ( 0.09%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/obligation_forest/mod.rs -------------------------------------------------------------------------------- Ir -- line 121 ---------------------------------------- . #[derive(Debug)] . pub enum ProcessResult { . Unchanged, . Changed(Vec), . Error(E), . } . . #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] 568,550 ( 0.00%) struct ObligationTreeId(usize); . . type ObligationTreeIdGenerator = . std::iter::Map, fn(usize) -> ObligationTreeId>; . . pub struct ObligationForest { . /// The list of obligations. In between calls to `process_obligations`, . /// this list only contains nodes in the `Pending` or `Waiting` state. . /// -- line 137 ---------------------------------------- -- line 181 ---------------------------------------- . has_parent: bool, . . /// Identifier of the obligation tree to which this node belongs. . obligation_tree_id: ObligationTreeId, . } . . impl Node { . fn new(parent: Option, obligation: O, obligation_tree_id: ObligationTreeId) -> Node { 5,819,472 ( 0.02%) Node { . obligation, . state: Cell::new(NodeState::Pending), 602,313 ( 0.00%) dependents: if let Some(parent_index) = parent { vec![parent_index] } else { vec![] }, . has_parent: parent.is_some(), . obligation_tree_id, . } . } . } . . /// The state of one node in some tree within the forest. This represents the . /// current state of processing for the obligation (of type `O`) associated -- line 200 ---------------------------------------- -- line 223 ---------------------------------------- . /// | compress() . /// v . /// (Removed) . /// ``` . /// The `Error` state can be introduced in several places, via `error_at()`. . /// . /// Outside of `ObligationForest` methods, nodes should be either `Pending` or . /// `Waiting`. 7,876,896 ( 0.02%) #[derive(Debug, Copy, Clone, PartialEq, Eq)] . enum NodeState { . /// This obligation has not yet been selected successfully. Cannot have . /// subobligations. . Pending, . . /// This obligation was selected successfully, but may or may not have . /// subobligations. . Success, -- line 239 ---------------------------------------- -- line 279 ---------------------------------------- . pub stalled: bool, . } . . impl OutcomeTrait for Outcome { . type Error = Error; . type Obligation = O; . . fn new() -> Self { 1,025,382 ( 0.00%) Self { stalled: true, errors: vec![] } . } . . fn mark_not_stalled(&mut self) { 358,067 ( 0.00%) self.stalled = false; . } . . fn is_stalled(&self) -> bool { 227,343 ( 0.00%) self.stalled . } . . fn record_completed(&mut self, _outcome: &Self::Obligation) { . // do nothing . } . . fn record_error(&mut self, error: Self::Error) { 1,536 ( 0.00%) self.errors.push(error) . } . } . . #[derive(Debug, PartialEq, Eq)] . pub struct Error { . pub error: E, . pub backtrace: Vec, . } . . impl ObligationForest { 122,318 ( 0.00%) pub fn new() -> ObligationForest { 1,467,816 ( 0.00%) ObligationForest { . nodes: vec![], . done_cache: Default::default(), . active_cache: Default::default(), . reused_node_vec: vec![], . obligation_tree_id_generator: (0..).map(ObligationTreeId), . error_cache: Default::default(), . } 122,318 ( 0.00%) } . . /// Returns the total number of nodes in the forest that have not . /// yet been fully resolved. . pub fn len(&self) -> usize { . self.nodes.len() . } . . /// Registers an obligation. . pub fn register_obligation(&mut self, obligation: O) { . // Ignore errors here - there is no guarantee of success. 4,675,801 ( 0.01%) let _ = self.register_obligation_at(obligation, None); . } . . // Returns Err(()) if we already know this obligation failed. 6,186,092 ( 0.02%) fn register_obligation_at(&mut self, obligation: O, parent: Option) -> Result<(), ()> { 1,124,744 ( 0.00%) let cache_key = obligation.as_cache_key(); 1,124,744 ( 0.00%) if self.done_cache.contains(&cache_key) { . debug!("register_obligation_at: ignoring already done obligation: {:?}", obligation); . return Ok(()); . } . 2,666,784 ( 0.01%) match self.active_cache.entry(cache_key) { . Entry::Occupied(o) => { 161,494 ( 0.00%) let node = &mut self.nodes[*o.get()]; 161,494 ( 0.00%) if let Some(parent_index) = parent { . // If the node is already in `active_cache`, it has already . // had its chance to be marked with a parent. So if it's . // not already present, just dump `parent` into the . // dependents as a non-parent. 150,393 ( 0.00%) if !node.dependents.contains(&parent_index) { . node.dependents.push(parent_index); . } . } 242,241 ( 0.00%) if let NodeState::Error = node.state.get() { Err(()) } else { Ok(()) } . } 1,091,151 ( 0.00%) Entry::Vacant(v) => { 2,182,302 ( 0.01%) let obligation_tree_id = match parent { 159,064 ( 0.00%) Some(parent_index) => self.nodes[parent_index].obligation_tree_id, . None => self.obligation_tree_id_generator.next().unwrap(), . }; . . let already_failed = parent.is_some() . && self . .error_cache . .get(&obligation_tree_id) . .map_or(false, |errors| errors.contains(v.key())); . . if already_failed { . Err(()) . } else { 363,717 ( 0.00%) let new_index = self.nodes.len(); . v.insert(new_index); . self.nodes.push(Node::new(parent, obligation, obligation_tree_id)); . Ok(()) . } . } . } 5,061,348 ( 0.01%) } . . /// Converts all remaining obligations to the given error. 1,487,241 ( 0.00%) pub fn to_errors(&mut self, error: E) -> Vec> { . let errors = self . .nodes . .iter() . .enumerate() . .filter(|(_index, node)| node.state.get() == NodeState::Pending) . .map(|(index, _node)| Error { error: error.clone(), backtrace: self.error_at(index) }) . .collect(); . 424,926 ( 0.00%) self.compress(|_| assert!(false)); . errors 1,274,778 ( 0.00%) } . . /// Returns the set of obligations that are in a pending state. . pub fn map_pending_obligations(&self, f: F) -> Vec

. where . F: Fn(&O) -> P, . { 30 ( 0.00%) self.nodes . .iter() . .filter(|node| node.state.get() == NodeState::Pending) . .map(|node| f(&node.obligation)) . .collect() . } . 1,932 ( 0.00%) fn insert_into_error_cache(&mut self, index: usize) { . let node = &self.nodes[index]; 276 ( 0.00%) self.error_cache 828 ( 0.00%) .entry(node.obligation_tree_id) . .or_default() . .insert(node.obligation.as_cache_key()); 2,208 ( 0.00%) } . . /// Performs a pass through the obligation list. This must . /// be called in a loop until `outcome.stalled` is false. . /// . /// This _cannot_ be unrolled (presently, at least). . #[inline(never)] 4,614,219 ( 0.01%) pub fn process_obligations(&mut self, processor: &mut P) -> OUT . where . P: ObligationProcessor, . OUT: OutcomeTrait>, . { . let mut outcome = OUT::new(); . . // Note that the loop body can append new nodes, and those new nodes . // will then be processed by subsequent iterations of the loop. . // . // We can't use an iterator for the loop because `self.nodes` is . // appended to and the borrow checker would complain. We also can't use . // `for index in 0..self.nodes.len() { ... }` because the range would . // be computed with the initial length, and we would miss the appended . // nodes. Therefore we use a `while` loop. . let mut index = 0; 3,860,184 ( 0.01%) while let Some(node) = self.nodes.get_mut(index) { . // `processor.process_obligation` can modify the predicate within . // `node.obligation`, and that predicate is the key used for . // `self.active_cache`. This means that `self.active_cache` can get . // out of sync with `nodes`. It's not very common, but it does . // happen, and code in `compress` has to allow for it. 6,694,986 ( 0.02%) if node.state.get() != NodeState::Pending { 80,896 ( 0.00%) index += 1; . continue; . } . 2,117,929 ( 0.01%) match processor.process_obligation(&mut node.obligation) { . ProcessResult::Unchanged => { . // No change in state. . } 1,431,884 ( 0.00%) ProcessResult::Changed(children) => { . // We are not (yet) stalled. . outcome.mark_not_stalled(); . node.state.set(NodeState::Success); . 1,837,274 ( 0.01%) for child in children { 3,445,815 ( 0.01%) let st = self.register_obligation_at(child, Some(index)); 405,390 ( 0.00%) if let Err(()) = st { . // Error already reported - propagate it . // to our node. . self.error_at(index); . } . } . } . ProcessResult::Error(err) => { . outcome.mark_not_stalled(); 3,168 ( 0.00%) outcome.record_error(Error { error: err, backtrace: self.error_at(index) }); . } . } 6,533,194 ( 0.02%) index += 1; . } . . // There's no need to perform marking, cycle processing and compression when nothing . // changed. 227,343 ( 0.00%) if !outcome.is_stalled() { . self.mark_successes(); . self.process_cycles(processor); 209,682 ( 0.00%) self.compress(|obl| outcome.record_completed(obl)); . } . . outcome 4,614,219 ( 0.01%) } . . /// Returns a vector of obligations for `p` and all of its . /// ancestors, putting them into the error state in the process. 672 ( 0.00%) fn error_at(&self, mut index: usize) -> Vec { . let mut error_stack: Vec = vec![]; . let mut trace = vec![]; . . loop { . let node = &self.nodes[index]; 276 ( 0.00%) node.state.set(NodeState::Error); . trace.push(node.obligation.clone()); 552 ( 0.00%) if node.has_parent { . // The first dependent is the parent, which is treated . // specially. . error_stack.extend(node.dependents.iter().skip(1)); 180 ( 0.00%) index = node.dependents[0]; . } else { . // No parent; treat all dependents non-specially. . error_stack.extend(node.dependents.iter()); . break; . } . } . . while let Some(index) = error_stack.pop() { -- line 508 ---------------------------------------- -- line 509 ---------------------------------------- . let node = &self.nodes[index]; . if node.state.get() != NodeState::Error { . node.state.set(NodeState::Error); . error_stack.extend(node.dependents.iter()); . } . } . . trace 768 ( 0.00%) } . . /// Mark all `Waiting` nodes as `Success`, except those that depend on a . /// pending node. . fn mark_successes(&self) { . // Convert all `Waiting` nodes to `Success`. . for node in &self.nodes { 2,630,354 ( 0.01%) if node.state.get() == NodeState::Waiting { . node.state.set(NodeState::Success); . } . } . . // Convert `Success` nodes that depend on a pending node back to . // `Waiting`. . for node in &self.nodes { 1,335,419 ( 0.00%) if node.state.get() == NodeState::Pending { . // This call site is hot. . self.inlined_mark_dependents_as_waiting(node); . } . } . } . . // This always-inlined function is for the hot call site. . #[inline(always)] . fn inlined_mark_dependents_as_waiting(&self, node: &Node) { 60,518 ( 0.00%) for &index in node.dependents.iter() { . let node = &self.nodes[index]; 60,518 ( 0.00%) let state = node.state.get(); 60,518 ( 0.00%) if state == NodeState::Success { . // This call site is cold. 91,968 ( 0.00%) self.uninlined_mark_dependents_as_waiting(node); . } else { . debug_assert!(state == NodeState::Waiting || state == NodeState::Error) . } . } . } . . // This never-inlined function is for the cold call site. . #[inline(never)] 214,592 ( 0.00%) fn uninlined_mark_dependents_as_waiting(&self, node: &Node) { . // Mark node Waiting in the cold uninlined code instead of the hot inlined . node.state.set(NodeState::Waiting); . self.inlined_mark_dependents_as_waiting(node) 245,248 ( 0.00%) } . . /// Report cycles between all `Success` nodes, and convert all `Success` . /// nodes to `Done`. This must be called after `mark_successes`. . fn process_cycles

(&mut self, processor: &mut P) . where . P: ObligationProcessor, . { 104,841 ( 0.00%) let mut stack = std::mem::take(&mut self.reused_node_vec); . for (index, node) in self.nodes.iter().enumerate() { . // For some benchmarks this state test is extremely hot. It's a win . // to handle the no-op cases immediately to avoid the cost of the . // function call. 1,335,419 ( 0.00%) if node.state.get() == NodeState::Success { 1,685,360 ( 0.00%) self.find_cycles_from_node(&mut stack, processor, index); . } . } . . debug_assert!(stack.is_empty()); 838,728 ( 0.00%) self.reused_node_vec = stack; . } . 4,155,480 ( 0.01%) fn find_cycles_from_node

(&self, stack: &mut Vec, processor: &mut P, index: usize) . where . P: ObligationProcessor, . { . let node = &self.nodes[index]; 923,440 ( 0.00%) if node.state.get() == NodeState::Success { 41,438 ( 0.00%) match stack.iter().rposition(|&n| n == index) { . None => { . stack.push(index); 124,648 ( 0.00%) for &dep_index in node.dependents.iter() { 498,592 ( 0.00%) self.find_cycles_from_node(stack, processor, dep_index); . } . stack.pop(); . node.state.set(NodeState::Done); . } . Some(rpos) => { . // Cycle detected. . processor.process_backedge( . stack[rpos..].iter().map(|&i| &self.nodes[i].obligation), . PhantomData, . ); . } . } . } 3,693,760 ( 0.01%) } . . /// Compresses the vector, removing all popped nodes. This adjusts the . /// indices and hence invalidates any outstanding indices. `process_cycles` . /// must be run beforehand to remove any cycles on `Success` nodes. . #[inline(never)] 2,325,969 ( 0.01%) fn compress(&mut self, mut outcome_cb: impl FnMut(&O)) { 317,304 ( 0.00%) let orig_nodes_len = self.nodes.len(); . let mut node_rewrites: Vec<_> = std::mem::take(&mut self.reused_node_vec); . debug_assert!(node_rewrites.is_empty()); . node_rewrites.extend(0..orig_nodes_len); . let mut dead_nodes = 0; . . // Move removable nodes to the end, preserving the order of the . // remaining nodes. . // . // LOOP INVARIANT: . // self.nodes[0..index - dead_nodes] are the first remaining nodes . // self.nodes[index - dead_nodes..index] are all dead . // self.nodes[index..] are unchanged . for index in 0..orig_nodes_len { . let node = &self.nodes[index]; 7,096,459 ( 0.02%) match node.state.get() { . NodeState::Pending | NodeState::Waiting => { 1,954,704 ( 0.01%) if dead_nodes > 0 { 744,885 ( 0.00%) self.nodes.swap(index, index - dead_nodes); 1,241,475 ( 0.00%) node_rewrites[index] -= dead_nodes; . } . } . NodeState::Done => { . // This lookup can fail because the contents of . // `self.active_cache` are not guaranteed to match those of . // `self.nodes`. See the comment in `process_obligation` . // for more details. 1,296,002 ( 0.00%) if let Some((predicate, _)) = 1,073,373 ( 0.00%) self.active_cache.remove_entry(&node.obligation.as_cache_key()) . { . self.done_cache.insert(predicate); . } else { . self.done_cache.insert(node.obligation.as_cache_key().clone()); . } . // Extract the success stories. . outcome_cb(&node.obligation); 715,582 ( 0.00%) node_rewrites[index] = orig_nodes_len; 715,582 ( 0.00%) dead_nodes += 1; . } . NodeState::Error => { . // We *intentionally* remove the node from the cache at this point. Otherwise . // tests must come up with a different type on every type error they . // check against. 828 ( 0.00%) self.active_cache.remove(&node.obligation.as_cache_key()); 552 ( 0.00%) self.insert_into_error_cache(index); 552 ( 0.00%) node_rewrites[index] = orig_nodes_len; 552 ( 0.00%) dead_nodes += 1; . } . NodeState::Success => unreachable!(), . } . } . . if dead_nodes > 0 { . // Remove the dead nodes and rewrite indices. 186,108 ( 0.00%) self.nodes.truncate(orig_nodes_len - dead_nodes); 93,054 ( 0.00%) self.apply_rewrites(&node_rewrites); . } . . node_rewrites.truncate(0); 1,269,216 ( 0.00%) self.reused_node_vec = node_rewrites; 2,538,432 ( 0.01%) } . . #[inline(never)] 837,486 ( 0.00%) fn apply_rewrites(&mut self, node_rewrites: &[usize]) { . let orig_nodes_len = node_rewrites.len(); . . for node in &mut self.nodes { . let mut i = 0; 816,573 ( 0.00%) while let Some(dependent) = node.dependents.get_mut(i) { 129,884 ( 0.00%) let new_index = node_rewrites[*dependent]; 64,942 ( 0.00%) if new_index >= orig_nodes_len { . node.dependents.swap_remove(i); . if i == 0 && node.has_parent { . // We just removed the parent. . node.has_parent = false; . } . } else { 32,471 ( 0.00%) *dependent = new_index; 64,942 ( 0.00%) i += 1; . } . } . } . . // This updating of `self.active_cache` is necessary because the . // removal of nodes within `compress` can fail. See above. . self.active_cache.retain(|_predicate, index| { 3,677,056 ( 0.01%) let new_index = node_rewrites[*index]; 1,838,528 ( 0.01%) if new_index >= orig_nodes_len { . false . } else { 784,102 ( 0.00%) *index = new_index; . true . } . }); 744,432 ( 0.00%) } . } 14,029,166 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/hash/sip.rs -------------------------------------------------------------------------------- Ir -- line 120 ---------------------------------------- . } . . /// Loads a u64 using up to 7 bytes of a byte slice. It looks clumsy but the . /// `copy_nonoverlapping` calls that occur (via `load_int_le!`) all have fixed . /// sizes and avoid calling `memcpy`, which is good for speed. . /// . /// Unsafe because: unchecked indexing at start..start+len . #[inline] 522 ( 0.00%) unsafe fn u8to64_le(buf: &[u8], start: usize, len: usize) -> u64 { . debug_assert!(len < 8); 58 ( 0.00%) let mut i = 0; // current byte index (from LSB) in the output u64 58 ( 0.00%) let mut out = 0; 18,194,558 ( 0.05%) if i + 3 < len { . // SAFETY: `i` cannot be greater than `len`, and the caller must guarantee . // that the index start..start+len is in bounds. . out = unsafe { load_int_le!(buf, start + i, u32) } as u64; . i += 4; . } 37,859,575 ( 0.11%) if i + 1 < len { . // SAFETY: same as above. 18,929,537 ( 0.05%) out |= (unsafe { load_int_le!(buf, start + i, u16) } as u64) << (i * 8); 9,464,536 ( 0.03%) i += 2 . } 21,082,122 ( 0.06%) if i < len { . // SAFETY: same as above. 30,972,315 ( 0.09%) out |= (unsafe { *buf.get_unchecked(start + i) } as u64) << (i * 8); 464 ( 0.00%) i += 1; . } . debug_assert_eq!(i, len); . out 174 ( 0.00%) } . . impl SipHasher { . /// Creates a new `SipHasher` with the two initial keys set to 0. . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_deprecated( . since = "1.13.0", . reason = "use `std::collections::hash_map::DefaultHasher` instead" -- line 158 ---------------------------------------- -- line 189 ---------------------------------------- . . /// Creates a `SipHasher13` that is keyed off the provided keys. . #[inline] . #[unstable(feature = "hashmap_internals", issue = "none")] . #[rustc_deprecated( . since = "1.13.0", . reason = "use `std::collections::hash_map::DefaultHasher` instead" . )] 145 ( 0.00%) pub fn new_with_keys(key0: u64, key1: u64) -> SipHasher13 { 3,626,197 ( 0.01%) SipHasher13 { hasher: Hasher::new_with_keys(key0, key1) } 58 ( 0.00%) } . } . . impl Hasher { . #[inline] 174 ( 0.00%) fn new_with_keys(key0: u64, key1: u64) -> Hasher { 386 ( 0.00%) let mut state = Hasher { . k0: key0, . k1: key1, . length: 0, 116 ( 0.00%) state: State { v0: 0, v1: 0, v2: 0, v3: 0 }, . tail: 0, . ntail: 0, . _marker: PhantomData, . }; 29 ( 0.00%) state.reset(); . state 58 ( 0.00%) } . . #[inline] 58 ( 0.00%) fn reset(&mut self) { 29 ( 0.00%) self.length = 0; 5,439,117 ( 0.02%) self.state.v0 = self.k0 ^ 0x736f6d6570736575; 5,806,845 ( 0.02%) self.state.v1 = self.k1 ^ 0x646f72616e646f6d; 87 ( 0.00%) self.state.v2 = self.k0 ^ 0x6c7967656e657261; 87 ( 0.00%) self.state.v3 = self.k1 ^ 0x7465646279746573; 29 ( 0.00%) self.ntail = 0; 58 ( 0.00%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl super::Hasher for SipHasher { . #[inline] . fn write(&mut self, msg: &[u8]) { . self.0.hasher.write(msg) . } -- line 234 ---------------------------------------- -- line 237 ---------------------------------------- . fn finish(&self) -> u64 { . self.0.hasher.finish() . } . } . . #[unstable(feature = "hashmap_internals", issue = "none")] . impl super::Hasher for SipHasher13 { . #[inline] 232 ( 0.00%) fn write(&mut self, msg: &[u8]) { 58 ( 0.00%) self.hasher.write(msg) 116 ( 0.00%) } . . #[inline] 58 ( 0.00%) fn finish(&self) -> u64 { 58 ( 0.00%) self.hasher.finish() 58 ( 0.00%) } . } . . impl super::Hasher for Hasher { . // Note: no integer hashing methods (`write_u*`, `write_i*`) are defined . // for this type. We could add them, copy the `short_write` implementation . // in librustc_data_structures/sip128.rs, and add `write_u*`/`write_i*` . // methods to `SipHasher`, `SipHasher13`, and `DefaultHasher`. This would . // greatly speed up integer hashing by those hashers, at the cost of . // slightly slowing down compile speeds on some benchmarks. See #69152 for . // details. . #[inline] 406 ( 0.00%) fn write(&mut self, msg: &[u8]) { 58 ( 0.00%) let length = msg.len(); 23,322,323 ( 0.07%) self.length += length; . 58 ( 0.00%) let mut needed = 0; . 22,954,410 ( 0.07%) if self.ntail != 0 { 11,676,863 ( 0.03%) needed = 8 - self.ntail; . // SAFETY: `cmp::min(length, needed)` is guaranteed to not be over `length` 58,384,043 ( 0.17%) self.tail |= unsafe { u8to64_le(msg, 0, cmp::min(length, needed)) } << (8 * self.ntail); 11,676,710 ( 0.03%) if length < needed { 8,050,190 ( 0.02%) self.ntail += length; . return; . } else { 1,813,318 ( 0.01%) self.state.v3 ^= self.tail; . S::c_rounds(&mut self.state); 3,626,636 ( 0.01%) self.state.v0 ^= self.tail; 1,813,318 ( 0.01%) self.ntail = 0; . } . } . . // Buffered tail is now flushed, process new input. 6,517,515 ( 0.02%) let len = length - needed; 6,517,439 ( 0.02%) let left = len & 0x7; // len % 8 . 58 ( 0.00%) let mut i = needed; 9,776,677 ( 0.03%) while i < len - left { . // SAFETY: because `len - left` is the biggest multiple of 8 under . // `len`, and because `i` starts at `needed` where `len` is `length - needed`, . // `i + 8` is guaranteed to be less than or equal to `length`. . let mi = unsafe { load_int_le!(msg, i, u64) }; . 165 ( 0.00%) self.state.v3 ^= mi; . S::c_rounds(&mut self.state); 165 ( 0.00%) self.state.v0 ^= mi; . 330 ( 0.00%) i += 8; . } . . // SAFETY: `i` is now `needed + len.div_euclid(8) * 8`, . // so `i + left` = `needed + len` = `length`, which is by . // definition equal to `msg.len()`. 6,885,214 ( 0.02%) self.tail = unsafe { u8to64_le(msg, i, left) }; 29 ( 0.00%) self.ntail = left; 174 ( 0.00%) } . . #[inline] 87 ( 0.00%) fn finish(&self) -> u64 { 1,813,245 ( 0.01%) let mut state = self.state; . 9,065,268 ( 0.03%) let b: u64 = ((self.length as u64 & 0xff) << 56) | self.tail; . 1,813,071 ( 0.01%) state.v3 ^= b; 58 ( 0.00%) S::c_rounds(&mut state); 1,813,071 ( 0.01%) state.v0 ^= b; . 1,813,100 ( 0.01%) state.v2 ^= 0xff; 58 ( 0.00%) S::d_rounds(&mut state); . 3,626,142 ( 0.01%) state.v0 ^ state.v1 ^ state.v2 ^ state.v3 58 ( 0.00%) } . } . . impl Clone for Hasher { . #[inline] . fn clone(&self) -> Hasher { . Hasher { . k0: self.k0, . k1: self.k1, -- line 332 ---------------------------------------- -- line 353 ---------------------------------------- . fn d_rounds(_: &mut State); . } . . #[derive(Debug, Clone, Default)] . struct Sip13Rounds; . . impl Sip for Sip13Rounds { . #[inline] 87 ( 0.00%) fn c_rounds(state: &mut State) { 23,574,436 ( 0.07%) compress!(state); 58 ( 0.00%) } . . #[inline] 87 ( 0.00%) fn d_rounds(state: &mut State) { 7,253,676 ( 0.02%) compress!(state); 7,253,676 ( 0.02%) compress!(state); 5,440,663 ( 0.02%) compress!(state); 58 ( 0.00%) } . } . . #[derive(Debug, Clone, Default)] . struct Sip24Rounds; . . impl Sip for Sip24Rounds { . #[inline] . fn c_rounds(state: &mut State) { -- line 378 ---------------------------------------- 54,361,081 ( 0.16%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs -------------------------------------------------------------------------------- Ir -- line 110 ---------------------------------------- . /// Control byte value for an empty bucket. . const EMPTY: u8 = 0b1111_1111; . . /// Control byte value for a deleted bucket. . const DELETED: u8 = 0b1000_0000; . . /// Checks whether a control byte represents a full bucket (top bit is clear). . #[inline] 105 ( 0.00%) fn is_full(ctrl: u8) -> bool { 21,734,536 ( 0.06%) ctrl & 0x80 == 0 140 ( 0.00%) } . . /// Checks whether a control byte represents a special value (top bit is set). . #[inline] . fn is_special(ctrl: u8) -> bool { . ctrl & 0x80 != 0 . } . . /// Checks whether a special control value is EMPTY (just check 1 bit). . #[inline] 75 ( 0.00%) fn special_is_empty(ctrl: u8) -> bool { . debug_assert!(is_special(ctrl)); 1,621,089 ( 0.00%) ctrl & 0x01 != 0 100 ( 0.00%) } . . /// Primary hash function, used to select the initial bucket to probe from. . #[inline] . #[allow(clippy::cast_possible_truncation)] 162 ( 0.00%) fn h1(hash: u64) -> usize { . // On 32-bit platforms we simply ignore the higher hash bits. . hash as usize 108 ( 0.00%) } . . /// Secondary hash function, saved in the low 7 bits of the control byte. . #[inline] . #[allow(clippy::cast_possible_truncation)] 132 ( 0.00%) fn h2(hash: u64) -> u8 { . // Grab the top 7 bits of the hash. While the hash is normally a full 64-bit . // value, some hash functions (such as FxHash) produce a usize result . // instead, which means that the top 32 bits are 0 on 32-bit platforms. 264 ( 0.00%) let hash_len = usize::min(mem::size_of::(), mem::size_of::()); 519,694,935 ( 1.50%) let top7 = hash >> (hash_len * 8 - 7); 44 ( 0.00%) (top7 & 0x7f) as u8 // truncation 88 ( 0.00%) } . . /// Probe sequence based on triangular numbers, which is guaranteed (since our . /// table size is a power of two) to visit every group of elements exactly once. . /// . /// A triangular probe has us jump by 1 more group every time. So first we . /// jump by 1 group (meaning we just continue our linear scan), then 2 groups . /// (skipping over 1 group), then 3 groups (skipping over 2 groups), and so on. . /// -- line 161 ---------------------------------------- -- line 170 ---------------------------------------- . #[inline] . fn move_next(&mut self, bucket_mask: usize) { . // We should have found an empty bucket by now and ended the probe. . debug_assert!( . self.stride <= bucket_mask, . "Went past end of probe sequence" . ); . 3,262,714 ( 0.01%) self.stride += Group::WIDTH; 3,262,714 ( 0.01%) self.pos += self.stride; 2,919,752 ( 0.01%) self.pos &= bucket_mask; . } . } . . /// Returns the number of buckets needed to hold the given number of items, . /// taking the maximum load factor into account. . /// . /// Returns `None` if an overflow occurs. . // Workaround for emscripten bug emscripten-core/emscripten-fastcomp#258 . #[cfg_attr(target_os = "emscripten", inline(never))] . #[cfg_attr(not(target_os = "emscripten"), inline)] 30 ( 0.00%) fn capacity_to_buckets(cap: usize) -> Option { . debug_assert_ne!(cap, 0); . . // For small tables we require at least 1 empty bucket so that lookups are . // guaranteed to terminate if an element doesn't exist in the table. 2,141,242 ( 0.01%) if cap < 8 { . // We don't bother with a table size of 2 buckets since that can only . // hold a single element. Instead we skip directly to a 4 bucket table . // which can hold 3 elements. 4,617,035 ( 0.01%) return Some(if cap < 4 { 4 } else { 8 }); . } . . // Otherwise require 1/8 buckets to be empty (87.5% load) . // . // Be careful when modifying this, calculate_layout relies on the . // overflow check here. 883,296 ( 0.00%) let adjusted_cap = cap.checked_mul(8)? / 7; . . // Any overflows will have been caught by the checked_mul. Also, any . // rounding errors from the division above will be cleaned up by . // next_power_of_two (which can't overflow because of the previous division). . Some(adjusted_cap.next_power_of_two()) 40 ( 0.00%) } . . /// Returns the maximum effective capacity for the given bucket mask, taking . /// the maximum load factor into account. . #[inline] 60 ( 0.00%) fn bucket_mask_to_capacity(bucket_mask: usize) -> usize { 5,570,830 ( 0.02%) if bucket_mask < 8 { . // For tables with 1/2/4/8 buckets, we always reserve one empty slot. . // Keep in mind that the bucket mask is one less than the bucket count. 20 ( 0.00%) bucket_mask . } else { . // For larger tables we reserve 12.5% of the slots as empty. 1,076,520 ( 0.00%) ((bucket_mask + 1) / 8) * 7 . } 60 ( 0.00%) } . . /// Helper which allows the max calculation for ctrl_align to be statically computed for each T . /// while keeping the rest of `calculate_layout_for` independent of `T` . #[derive(Copy, Clone)] . struct TableLayout { . size: usize, . ctrl_align: usize, . } . . impl TableLayout { . #[inline] 20 ( 0.00%) fn new() -> Self { 60 ( 0.00%) let layout = Layout::new::(); 40 ( 0.00%) Self { 60 ( 0.00%) size: layout.size(), 120 ( 0.00%) ctrl_align: usize::max(layout.align(), Group::WIDTH), . } 80 ( 0.00%) } . . #[inline] 260 ( 0.00%) fn calculate_layout_for(self, buckets: usize) -> Option<(Layout, usize)> { . debug_assert!(buckets.is_power_of_two()); . 40 ( 0.00%) let TableLayout { size, ctrl_align } = self; . // Manual layout calculation since Layout methods are not yet stable. . let ctrl_offset = 4,370,555 ( 0.01%) size.checked_mul(buckets)?.checked_add(ctrl_align - 1)? & !(ctrl_align - 1); 5,844,733 ( 0.02%) let len = ctrl_offset.checked_add(buckets + Group::WIDTH)?; . 180 ( 0.00%) Some(( 80 ( 0.00%) unsafe { Layout::from_size_align_unchecked(len, ctrl_align) }, . ctrl_offset, . )) 60 ( 0.00%) } . } . . /// Returns a Layout which describes the allocation required for a hash table, . /// and the offset of the control bytes in the allocation. . /// (the offset is also one past last element of buckets) . /// . /// Returns `None` if an overflow occurs. . #[cfg_attr(feature = "inline-more", inline)] -- line 269 ---------------------------------------- -- line 292 ---------------------------------------- . #[inline] . fn clone(&self) -> Self { . Self { ptr: self.ptr } . } . } . . impl Bucket { . #[inline] 245 ( 0.00%) unsafe fn from_base_index(base: NonNull, index: usize) -> Self { 196 ( 0.00%) let ptr = if mem::size_of::() == 0 { . // won't overflow because index must be less than length . (index + 1) as *mut T . } else { 196 ( 0.00%) base.as_ptr().sub(index) . }; 49 ( 0.00%) Self { 196 ( 0.00%) ptr: NonNull::new_unchecked(ptr), . } 147 ( 0.00%) } . #[inline] . unsafe fn to_base_index(&self, base: NonNull) -> usize { . if mem::size_of::() == 0 { . self.ptr.as_ptr() as usize - 1 . } else { . offset_from(base.as_ptr(), self.ptr.as_ptr()) . } . } . #[inline] 162 ( 0.00%) pub fn as_ptr(&self) -> *mut T { 216 ( 0.00%) if mem::size_of::() == 0 { . // Just return an arbitrary ZST pointer which is properly aligned . mem::align_of::() as *mut T . } else { 324 ( 0.00%) unsafe { self.ptr.as_ptr().sub(1) } . } 162 ( 0.00%) } . #[inline] 75 ( 0.00%) unsafe fn next_n(&self, offset: usize) -> Self { 60 ( 0.00%) let ptr = if mem::size_of::() == 0 { . (self.ptr.as_ptr() as usize + offset) as *mut T . } else { 75 ( 0.00%) self.ptr.as_ptr().sub(offset) . }; 15 ( 0.00%) Self { 60 ( 0.00%) ptr: NonNull::new_unchecked(ptr), . } 45 ( 0.00%) } . #[cfg_attr(feature = "inline-more", inline)] 30 ( 0.00%) pub unsafe fn drop(&self) { 30 ( 0.00%) self.as_ptr().drop_in_place(); 30 ( 0.00%) } . #[inline] . pub unsafe fn read(&self) -> T { 17,662 ( 0.00%) self.as_ptr().read() . } . #[inline] 45 ( 0.00%) pub unsafe fn write(&self, val: T) { 180 ( 0.00%) self.as_ptr().write(val); 30 ( 0.00%) } . #[inline] 48 ( 0.00%) pub unsafe fn as_ref<'a>(&self) -> &'a T { 48 ( 0.00%) &*self.as_ptr() 48 ( 0.00%) } . #[inline] . pub unsafe fn as_mut<'a>(&self) -> &'a mut T { . &mut *self.as_ptr() . } . #[cfg(feature = "raw")] . #[inline] . pub unsafe fn copy_from_nonoverlapping(&self, other: &Self) { . self.as_ptr().copy_from_nonoverlapping(other.as_ptr(), 1); -- line 362 ---------------------------------------- -- line 392 ---------------------------------------- . . impl RawTable { . /// Creates a new empty hash table without allocating any memory. . /// . /// In effect this returns a table with exactly 1 bucket. However we can . /// leave the data pointer dangling since that bucket is never written to . /// due to our load factor forcing us to always have at least 1 free bucket. . #[inline] 2,970 ( 0.00%) pub const fn new() -> Self { 7,920 ( 0.00%) Self { 1,980 ( 0.00%) table: RawTableInner::new_in(Global), . marker: PhantomData, . } 1,980 ( 0.00%) } . . /// Attempts to allocate a new hash table with at least enough capacity . /// for inserting the given number of elements without reallocating. . #[cfg(feature = "raw")] . pub fn try_with_capacity(capacity: usize) -> Result { . Self::try_with_capacity_in(capacity, Global) . } . -- line 413 ---------------------------------------- -- line 421 ---------------------------------------- . impl RawTable { . /// Creates a new empty hash table without allocating any memory, using the . /// given allocator. . /// . /// In effect this returns a table with exactly 1 bucket. However we can . /// leave the data pointer dangling since that bucket is never written to . /// due to our load factor forcing us to always have at least 1 free bucket. . #[inline] 2,970 ( 0.00%) pub fn new_in(alloc: A) -> Self { 42,135 ( 0.00%) Self { 1,980 ( 0.00%) table: RawTableInner::new_in(alloc), . marker: PhantomData, . } 1,980 ( 0.00%) } . . /// Allocates a new hash table with the given number of buckets. . /// . /// The control bytes are left uninitialized. . #[cfg_attr(feature = "inline-more", inline)] . unsafe fn new_uninitialized( . alloc: A, . buckets: usize, . fallibility: Fallibility, . ) -> Result { . debug_assert!(buckets.is_power_of_two()); . . Ok(Self { 3,940 ( 0.00%) table: RawTableInner::new_uninitialized( . alloc, . TableLayout::new::(), . buckets, . fallibility, . )?, . marker: PhantomData, . }) . } -- line 456 ---------------------------------------- -- line 458 ---------------------------------------- . /// Attempts to allocate a new hash table with at least enough capacity . /// for inserting the given number of elements without reallocating. . fn fallible_with_capacity( . alloc: A, . capacity: usize, . fallibility: Fallibility, . ) -> Result { . Ok(Self { 109,849 ( 0.00%) table: RawTableInner::fallible_with_capacity( . alloc, . TableLayout::new::(), . capacity, . fallibility, . )?, . marker: PhantomData, . }) . } -- line 474 ---------------------------------------- -- line 493 ---------------------------------------- . /// Returns a reference to the underlying allocator. . #[inline] . pub fn allocator(&self) -> &A { . &self.table.alloc . } . . /// Deallocates the table without dropping any entries. . #[cfg_attr(feature = "inline-more", inline)] 30 ( 0.00%) unsafe fn free_buckets(&mut self) { 40 ( 0.00%) self.table.free_buckets(TableLayout::new::()); 20 ( 0.00%) } . . /// Returns pointer to one past last element of data table. . #[inline] 98 ( 0.00%) pub unsafe fn data_end(&self) -> NonNull { 245 ( 0.00%) NonNull::new_unchecked(self.table.ctrl.as_ptr().cast()) 98 ( 0.00%) } . . /// Returns pointer to start of data table. . #[inline] . #[cfg(feature = "nightly")] . pub unsafe fn data_start(&self) -> *mut T { . self.data_end().as_ptr().wrapping_sub(self.buckets()) . } . -- line 517 ---------------------------------------- -- line 518 ---------------------------------------- . /// Returns the index of a bucket from a `Bucket`. . #[inline] . pub unsafe fn bucket_index(&self, bucket: &Bucket) -> usize { . bucket.to_base_index(self.data_end()) . } . . /// Returns a pointer to an element in the table. . #[inline] 156 ( 0.00%) pub unsafe fn bucket(&self, index: usize) -> Bucket { . debug_assert_ne!(self.table.bucket_mask, 0); . debug_assert!(index < self.buckets()); 156 ( 0.00%) Bucket::from_base_index(self.data_end(), index) 78 ( 0.00%) } . . /// Erases an element from the table without dropping it. . #[cfg_attr(feature = "inline-more", inline)] . #[deprecated(since = "0.8.1", note = "use erase or remove instead")] 358,067 ( 0.00%) pub unsafe fn erase_no_drop(&mut self, item: &Bucket) { 358,067 ( 0.00%) let index = self.bucket_index(item); . self.table.erase(index); 716,134 ( 0.00%) } . . /// Erases an element from the table, dropping it in place. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::needless_pass_by_value)] . #[allow(deprecated)] . pub unsafe fn erase(&mut self, item: Bucket) { . // Erase the element from the table first since drop might panic. 270,324 ( 0.00%) self.erase_no_drop(&item); . item.drop(); . } . . /// Finds and erases an element from the table, dropping it in place. . /// Returns true if an element was found. . #[cfg(feature = "raw")] . #[cfg_attr(feature = "inline-more", inline)] . pub fn erase_entry(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> bool { -- line 554 ---------------------------------------- -- line 563 ---------------------------------------- . } . } . . /// Removes an element from the table, returning it. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::needless_pass_by_value)] . #[allow(deprecated)] . pub unsafe fn remove(&mut self, item: Bucket) -> T { 445,810 ( 0.00%) self.erase_no_drop(&item); 3,876 ( 0.00%) item.read() . } . . /// Finds and removes an element from the table, returning it. . #[cfg_attr(feature = "inline-more", inline)] 8,836,184 ( 0.03%) pub fn remove_entry(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option { . // Avoid `Option::map` because it bloats LLVM IR. 15,174 ( 0.00%) match self.find(hash, eq) { 86,312 ( 0.00%) Some(bucket) => Some(unsafe { self.remove(bucket) }), 2,449,658 ( 0.01%) None => None, . } 12,158,686 ( 0.04%) } . . /// Marks all table buckets as empty without dropping their contents. . #[cfg_attr(feature = "inline-more", inline)] . pub fn clear_no_drop(&mut self) { . self.table.clear_no_drop(); . } . . /// Removes all elements from the table without freeing the backing memory. . #[cfg_attr(feature = "inline-more", inline)] . pub fn clear(&mut self) { . // Ensure that the table is reset even if one of the drops panic . let mut self_ = guard(self, |self_| self_.clear_no_drop()); . unsafe { 1 ( 0.00%) self_.drop_elements(); . } . } . 37 ( 0.00%) unsafe fn drop_elements(&mut self) { 240,788 ( 0.00%) if mem::needs_drop::() && !self.is_empty() { 365 ( 0.00%) for item in self.iter() { 30 ( 0.00%) item.drop(); . } . } 28 ( 0.00%) } . . /// Shrinks the table to fit `max(self.len(), min_size)` elements. . #[cfg_attr(feature = "inline-more", inline)] . pub fn shrink_to(&mut self, min_size: usize, hasher: impl Fn(&T) -> u64) { . // Calculate the minimal number of elements that we need to reserve . // space for. . let min_size = usize::max(self.table.items, min_size); . if min_size == 0 { -- line 615 ---------------------------------------- -- line 641 ---------------------------------------- . } . } . } . } . . /// Ensures that at least `additional` items can be inserted into the table . /// without reallocation. . #[cfg_attr(feature = "inline-more", inline)] 7,000 ( 0.00%) pub fn reserve(&mut self, additional: usize, hasher: impl Fn(&T) -> u64) { 4,848,704 ( 0.01%) if additional > self.table.growth_left { . // Avoid `Result::unwrap_or_else` because it bloats LLVM IR. 3,724,604 ( 0.01%) if self 20 ( 0.00%) .reserve_rehash(additional, hasher, Fallibility::Infallible) . .is_err() . { . unsafe { hint::unreachable_unchecked() } . } . } 5,000 ( 0.00%) } . . /// Tries to ensure that at least `additional` items can be inserted into . /// the table without reallocation. . #[cfg_attr(feature = "inline-more", inline)] . pub fn try_reserve( . &mut self, . additional: usize, . hasher: impl Fn(&T) -> u64, -- line 667 ---------------------------------------- -- line 671 ---------------------------------------- . } else { . Ok(()) . } . } . . /// Out-of-line slow path for `reserve` and `try_reserve`. . #[cold] . #[inline(never)] 8,570,552 ( 0.02%) fn reserve_rehash( . &mut self, . additional: usize, . hasher: impl Fn(&T) -> u64, . fallibility: Fallibility, . ) -> Result<(), TryReserveError> { . unsafe { 120 ( 0.00%) self.table.reserve_rehash_inner( . additional, 30 ( 0.00%) &|table, index| hasher(table.bucket::(index).as_ref()), . fallibility, 40 ( 0.00%) TableLayout::new::(), 50 ( 0.00%) if mem::needs_drop::() { 50 ( 0.00%) Some(mem::transmute(ptr::drop_in_place:: as unsafe fn(*mut T))) . } else { . None . }, . ) . } 6,153,414 ( 0.02%) } . . /// Allocates a new table of a different size and moves the contents of the . /// current table into it. . fn resize( . &mut self, . capacity: usize, . hasher: impl Fn(&T) -> u64, . fallibility: Fallibility, -- line 706 ---------------------------------------- -- line 714 ---------------------------------------- . ) . } . } . . /// Inserts a new element into the table, and returns its raw bucket. . /// . /// This does not check if the given element already exists in the table. . #[cfg_attr(feature = "inline-more", inline)] 30,601,202 ( 0.09%) pub fn insert(&mut self, hash: u64, value: T, hasher: impl Fn(&T) -> u64) -> Bucket { . unsafe { 105 ( 0.00%) let mut index = self.table.find_insert_slot(hash); . . // We can avoid growing the table once we have reached our load . // factor if we are replacing a tombstone. This works since the . // number of EMPTY slots does not change in this case. 74,600 ( 0.00%) let old_ctrl = *self.table.ctrl(index); 20,907,156 ( 0.06%) if unlikely(self.table.growth_left == 0 && special_is_empty(old_ctrl)) { 40 ( 0.00%) self.reserve(1, hasher); 40 ( 0.00%) index = self.table.find_insert_slot(hash); . } . 60 ( 0.00%) self.table.record_item_insert_at(index, old_ctrl, hash); . 75 ( 0.00%) let bucket = self.bucket(index); 167 ( 0.00%) bucket.write(value); 30 ( 0.00%) bucket . } 22,599,370 ( 0.07%) } . . /// Attempts to insert a new element without growing the table and return its raw bucket. . /// . /// Returns an `Err` containing the given element if inserting it would require growing the . /// table. . /// . /// This does not check if the given element already exists in the table. . #[cfg(feature = "raw")] -- line 749 ---------------------------------------- -- line 760 ---------------------------------------- . } . } . } . . /// Inserts a new element into the table, and returns a mutable reference to it. . /// . /// This does not check if the given element already exists in the table. . #[cfg_attr(feature = "inline-more", inline)] 5,463,072 ( 0.02%) pub fn insert_entry(&mut self, hash: u64, value: T, hasher: impl Fn(&T) -> u64) -> &mut T { 4,173 ( 0.00%) unsafe { self.insert(hash, value, hasher).as_mut() } 4,097,304 ( 0.01%) } . . /// Inserts a new element into the table, without growing the table. . /// . /// There must be enough space in the table to insert the new element. . /// . /// This does not check if the given element already exists in the table. . #[cfg_attr(feature = "inline-more", inline)] . #[cfg(any(feature = "raw", feature = "rustc-internal-api"))] 194,254 ( 0.00%) pub unsafe fn insert_no_grow(&mut self, hash: u64, value: T) -> Bucket { 4,159,910 ( 0.01%) let (index, old_ctrl) = self.table.prepare_insert_slot(hash); 184,665 ( 0.00%) let bucket = self.table.bucket(index); . . // If we are replacing a DELETED entry then we don't need to update . // the load counter. 9,099,912 ( 0.03%) self.table.growth_left -= special_is_empty(old_ctrl) as usize; . . bucket.write(value); 7,323,720 ( 0.02%) self.table.items += 1; . bucket 283,683 ( 0.00%) } . . /// Temporary removes a bucket, applying the given function to the removed . /// element and optionally put back the returned value in the same bucket. . /// . /// Returns `true` if the bucket still contains an element . /// . /// This does not check if the given bucket is actually occupied. . #[cfg_attr(feature = "inline-more", inline)] -- line 798 ---------------------------------------- -- line 813 ---------------------------------------- . true . } else { . false . } . } . . /// Searches for an element in the table. . #[inline] 55,782 ( 0.00%) pub fn find(&self, hash: u64, mut eq: impl FnMut(&T) -> bool) -> Option> { 105,603 ( 0.00%) let result = self.table.find_inner(hash, &mut |index| unsafe { 617,646 ( 0.00%) eq(self.bucket(index).as_ref()) 46,216 ( 0.00%) }); . . // Avoid `Option::map` because it bloats LLVM IR. 111 ( 0.00%) match result { 14,595 ( 0.00%) Some(index) => Some(unsafe { self.bucket(index) }), 34 ( 0.00%) None => None, . } 55,724 ( 0.00%) } . . /// Gets a reference to an element in the table. . #[inline] 56 ( 0.00%) pub fn get(&self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option<&T> { . // Avoid `Option::map` because it bloats LLVM IR. 340,026 ( 0.00%) match self.find(hash, eq) { 72 ( 0.00%) Some(bucket) => Some(unsafe { bucket.as_ref() }), 4 ( 0.00%) None => None, . } 42 ( 0.00%) } . . /// Gets a mutable reference to an element in the table. . #[inline] 60 ( 0.00%) pub fn get_mut(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option<&mut T> { . // Avoid `Option::map` because it bloats LLVM IR. 48,175 ( 0.00%) match self.find(hash, eq) { . Some(bucket) => Some(unsafe { bucket.as_mut() }), 30 ( 0.00%) None => None, . } 45 ( 0.00%) } . . /// Attempts to get mutable references to `N` entries in the table at once. . /// . /// Returns an array of length `N` with the results of each query. . /// . /// At most one mutable reference will be returned to any entry. `None` will be returned if any . /// of the hashes are duplicates. `None` will be returned if the hash is not found. . /// -- line 859 ---------------------------------------- -- line 913 ---------------------------------------- . /// more, but is guaranteed to be able to hold at least this many. . #[inline] . pub fn capacity(&self) -> usize { . self.table.items + self.table.growth_left . } . . /// Returns the number of elements in the table. . #[inline] 7,294 ( 0.00%) pub fn len(&self) -> usize { 3,647 ( 0.00%) self.table.items 7,294 ( 0.00%) } . . /// Returns `true` if the table contains no elements. . #[inline] 5,314 ( 0.00%) pub fn is_empty(&self) -> bool { 14,748,456 ( 0.04%) self.len() == 0 10,628 ( 0.00%) } . . /// Returns the number of buckets in the table. . #[inline] . pub fn buckets(&self) -> usize { . self.table.bucket_mask + 1 . } . . /// Returns an iterator over every element in the table. It is up to . /// the caller to ensure that the `RawTable` outlives the `RawIter`. . /// Because we cannot make the `next` method unsafe on the `RawIter` . /// struct, we have to make the `iter` method unsafe. . #[inline] 70 ( 0.00%) pub unsafe fn iter(&self) -> RawIter { 70 ( 0.00%) let data = Bucket::from_base_index(self.data_end(), 0); 90 ( 0.00%) RawIter { 70 ( 0.00%) iter: RawIterRange::new(self.table.ctrl.as_ptr(), data, self.table.buckets()), 1,850,861 ( 0.01%) items: self.table.items, . } 20 ( 0.00%) } . . /// Returns an iterator over occupied buckets that could match a given hash. . /// . /// `RawTable` only stores 7 bits of the hash value, so this iterator may . /// return items that have a hash value different than the one provided. You . /// should always validate the returned values before using them. . /// . /// It is up to the caller to ensure that the `RawTable` outlives the -- line 956 ---------------------------------------- -- line 995 ---------------------------------------- . /// Iteration starts at the provided iterator's current location. . /// . /// It is up to the caller to ensure that the iterator is valid for this . /// `RawTable` and covers all items that remain in the table. . pub unsafe fn into_iter_from(self, iter: RawIter) -> RawIntoIter { . debug_assert_eq!(iter.len(), self.len()); . . let alloc = self.table.alloc.clone(); 114,848 ( 0.00%) let allocation = self.into_allocation(); 86,136 ( 0.00%) RawIntoIter { 143,560 ( 0.00%) iter, . allocation, . marker: PhantomData, . alloc, . } . } . . /// Converts the table into a raw allocation. The contents of the table . /// should be dropped using a `RawIter` before freeing the allocation. . #[cfg_attr(feature = "inline-more", inline)] . pub(crate) fn into_allocation(self) -> Option<(NonNull, Layout)> { 59,025 ( 0.00%) let alloc = if self.table.is_empty_singleton() { . None . } else { . // Avoid `Option::unwrap_or_else` because it bloats LLVM IR. . let (layout, ctrl_offset) = match calculate_layout::(self.table.buckets()) { . Some(lco) => lco, . None => unsafe { hint::unreachable_unchecked() }, . }; . Some(( 7,716 ( 0.00%) unsafe { NonNull::new_unchecked(self.table.ctrl.as_ptr().sub(ctrl_offset)) }, . layout, . )) . }; . mem::forget(self); . alloc . } . } . -- line 1033 ---------------------------------------- -- line 1041 ---------------------------------------- . where . T: Sync, . A: Sync, . { . } . . impl RawTableInner { . #[inline] 5,940 ( 0.00%) const fn new_in(alloc: A) -> Self { 11,795,256 ( 0.03%) Self { . // Be careful to cast the entire slice to a raw pointer. 13,860 ( 0.00%) ctrl: unsafe { NonNull::new_unchecked(Group::static_empty() as *const _ as *mut u8) }, . bucket_mask: 0, . items: 0, . growth_left: 0, . alloc, . } 3,960 ( 0.00%) } . } . . impl RawTableInner { . #[cfg_attr(feature = "inline-more", inline)] 8,018,595 ( 0.02%) unsafe fn new_uninitialized( . alloc: A, . table_layout: TableLayout, . buckets: usize, . fallibility: Fallibility, . ) -> Result { . debug_assert!(buckets.is_power_of_two()); . . // Avoid `Option::ok_or_else` because it bloats LLVM IR. 160 ( 0.00%) let (layout, ctrl_offset) = match table_layout.calculate_layout_for(buckets) { 120 ( 0.00%) Some(lco) => lco, . None => return Err(fallibility.capacity_overflow()), . }; . . // We need an additional check to ensure that the allocation doesn't . // exceed `isize::MAX`. We can skip this check on 64-bit systems since . // such allocations will never succeed anyways. . // . // This mirrors what Vec does in the standard library. 40 ( 0.00%) if mem::size_of::() < 8 && layout.size() > isize::MAX as usize { . return Err(fallibility.capacity_overflow()); . } . 1,830,180 ( 0.01%) let ptr: NonNull = match do_alloc(&alloc, layout) { 60 ( 0.00%) Ok(block) => block.cast(), . Err(_) => return Err(fallibility.alloc_err(layout)), . }; . 90 ( 0.00%) let ctrl = NonNull::new_unchecked(ptr.as_ptr().add(ctrl_offset)); 4,420,966 ( 0.01%) Ok(Self { . ctrl, 1,808,255 ( 0.01%) bucket_mask: buckets - 1, . items: 0, 90 ( 0.00%) growth_left: bucket_mask_to_capacity(buckets - 1), . alloc, . }) 5,836,874 ( 0.02%) } . . #[inline] 290,043 ( 0.00%) fn fallible_with_capacity( . alloc: A, . table_layout: TableLayout, . capacity: usize, . fallibility: Fallibility, . ) -> Result { 77,608 ( 0.00%) if capacity == 0 { 38,743 ( 0.00%) Ok(Self::new_in(alloc)) . } else { . unsafe { . let buckets = 170 ( 0.00%) capacity_to_buckets(capacity).ok_or_else(|| fallibility.capacity_overflow())?; . 3,628,888 ( 0.01%) let result = Self::new_uninitialized(alloc, table_layout, buckets, fallibility)?; 60 ( 0.00%) result.ctrl(0).write_bytes(EMPTY, result.num_ctrl_bytes()); . 178,243 ( 0.00%) Ok(result) . } . } 289,953 ( 0.00%) } . . /// Searches for an empty or deleted bucket which is suitable for inserting . /// a new element and sets the hash for that slot. . /// . /// There must be at least 1 empty bucket in the table. . #[inline] 1,505,380 ( 0.00%) unsafe fn prepare_insert_slot(&self, hash: u64) -> (usize, u8) { . let index = self.find_insert_slot(hash); 1,505,380 ( 0.00%) let old_ctrl = *self.ctrl(index); . self.set_ctrl_h2(index, hash); . (index, old_ctrl) 3,010,760 ( 0.01%) } . . /// Searches for an empty or deleted bucket which is suitable for inserting . /// a new element. . /// . /// There must be at least 1 empty bucket in the table. . #[inline] 100 ( 0.00%) fn find_insert_slot(&self, hash: u64) -> usize { 75 ( 0.00%) let mut probe_seq = self.probe_seq(hash); 25 ( 0.00%) loop { . unsafe { 200 ( 0.00%) let group = Group::load(self.ctrl(probe_seq.pos)); 14,038,233 ( 0.04%) if let Some(bit) = group.match_empty_or_deleted().lowest_set_bit() { 41,286,675 ( 0.12%) let result = (probe_seq.pos + bit) & self.bucket_mask; . . // In tables smaller than the group width, trailing control . // bytes outside the range of the table are filled with . // EMPTY entries. These will unfortunately trigger a . // match, but once masked may point to a full bucket that . // is already occupied. We detect this situation here and . // perform a second scan starting at the beginning of the . // table. This second scan is guaranteed to find an empty . // slot (due to the load factor) before hitting the trailing . // control bytes (containing EMPTY). 18,984,163 ( 0.05%) if unlikely(is_full(*self.ctrl(result))) { . debug_assert!(self.bucket_mask < Group::WIDTH); . debug_assert_ne!(probe_seq.pos, 0); . return Group::load_aligned(self.ctrl(0)) . .match_empty_or_deleted() . .lowest_set_bit_nonzero(); . } . 50 ( 0.00%) return result; . } . } . probe_seq.move_next(self.bucket_mask); . } 75 ( 0.00%) } . . /// Searches for an element in the table. This uses dynamic dispatch to reduce the amount of . /// code generated, but it is eliminated by LLVM optimizations. . #[inline] 348 ( 0.00%) fn find_inner(&self, hash: u64, eq: &mut dyn FnMut(usize) -> bool) -> Option { 87 ( 0.00%) let h2_hash = h2(hash); 87 ( 0.00%) let mut probe_seq = self.probe_seq(hash); . 1,859,017 ( 0.01%) loop { 232 ( 0.00%) let group = unsafe { Group::load(self.ctrl(probe_seq.pos)) }; . 56,413,321 ( 0.16%) for bit in group.match_byte(h2_hash) { 112,188,039 ( 0.32%) let index = (probe_seq.pos + bit) & self.bucket_mask; . 68,461,396 ( 0.20%) if likely(eq(index)) { 24 ( 0.00%) return Some(index); . } . } . 16,286,103 ( 0.05%) if likely(group.match_empty().any_bit_set()) { 17 ( 0.00%) return None; . } . . probe_seq.move_next(self.bucket_mask); . } 116 ( 0.00%) } . . #[allow(clippy::mut_mut)] . #[inline] . unsafe fn prepare_rehash_in_place(&mut self) { . // Bulk convert all full control bytes to DELETED, and all DELETED . // control bytes to EMPTY. This effectively frees up all buckets . // containing a DELETED entry. 41 ( 0.00%) for i in (0..self.buckets()).step_by(Group::WIDTH) { . let group = Group::load_aligned(self.ctrl(i)); . let group = group.convert_special_to_empty_and_full_to_deleted(); . group.store_aligned(self.ctrl(i)); . } . . // Fix up the trailing control bytes. See the comments in set_ctrl . // for the handling of tables smaller than the group width. 39 ( 0.00%) if self.buckets() < Group::WIDTH { . self.ctrl(0) . .copy_to(self.ctrl(Group::WIDTH), self.buckets()); . } else { . self.ctrl(0) . .copy_to(self.ctrl(self.buckets()), Group::WIDTH); . } . } . -- line 1220 ---------------------------------------- -- line 1225 ---------------------------------------- . Bucket::from_base_index(self.data_end(), index) . } . . #[inline] . unsafe fn bucket_ptr(&self, index: usize, size_of: usize) -> *mut u8 { . debug_assert_ne!(self.bucket_mask, 0); . debug_assert!(index < self.buckets()); . let base: *mut u8 = self.data_end().as_ptr(); 49,893,168 ( 0.14%) base.sub((index + 1) * size_of) . } . . #[inline] . unsafe fn data_end(&self) -> NonNull { . NonNull::new_unchecked(self.ctrl.as_ptr().cast()) . } . . /// Returns an iterator-like object for a probe sequence on the table. . /// . /// This iterator never terminates, but is guaranteed to visit each bucket . /// group exactly once. The loop using `probe_seq` must terminate upon . /// reaching a group containing an empty bucket. . #[inline] 378 ( 0.00%) fn probe_seq(&self, hash: u64) -> ProbeSeq { 108 ( 0.00%) ProbeSeq { 293,944,766 ( 0.85%) pos: h1(hash) & self.bucket_mask, . stride: 0, . } 216 ( 0.00%) } . . /// Returns the index of a bucket for which a value must be inserted if there is enough rooom . /// in the table, otherwise returns error . #[cfg(feature = "raw")] . #[inline] . unsafe fn prepare_insert_no_grow(&mut self, hash: u64) -> Result { . let index = self.find_insert_slot(hash); . let old_ctrl = *self.ctrl(index); -- line 1260 ---------------------------------------- -- line 1262 ---------------------------------------- . Err(()) . } else { . self.record_item_insert_at(index, old_ctrl, hash); . Ok(index) . } . } . . #[inline] 135 ( 0.00%) unsafe fn record_item_insert_at(&mut self, index: usize, old_ctrl: u8, hash: u64) { 26,119,105 ( 0.08%) self.growth_left -= special_is_empty(old_ctrl) as usize; 30 ( 0.00%) self.set_ctrl_h2(index, hash); 20,895,245 ( 0.06%) self.items += 1; 30 ( 0.00%) } . . #[inline] . fn is_in_same_group(&self, i: usize, new_i: usize, hash: u64) -> bool { . let probe_seq_pos = self.probe_seq(hash).pos; . let probe_index = . |pos: usize| (pos.wrapping_sub(probe_seq_pos) & self.bucket_mask) / Group::WIDTH; 429 ( 0.00%) probe_index(i) == probe_index(new_i) . } . . /// Sets a control byte to the hash, and possibly also the replicated control byte at . /// the end of the array. . #[inline] 135 ( 0.00%) unsafe fn set_ctrl_h2(&self, index: usize, hash: u64) { 60 ( 0.00%) self.set_ctrl(index, h2(hash)); 30 ( 0.00%) } . . #[inline] . unsafe fn replace_ctrl_h2(&self, index: usize, hash: u64) -> u8 { . let prev_ctrl = *self.ctrl(index); . self.set_ctrl_h2(index, hash); . prev_ctrl . } . . /// Sets a control byte, and possibly also the replicated control byte at . /// the end of the array. . #[inline] 150 ( 0.00%) unsafe fn set_ctrl(&self, index: usize, ctrl: u8) { . // Replicate the first Group::WIDTH control bytes at the end of . // the array without using a branch: . // - If index >= Group::WIDTH then index == index2. . // - Otherwise index2 == self.bucket_mask + 1 + index. . // . // The very last replicated control byte is never actually read because . // we mask the initial index for unaligned loads, but we write it . // anyways because it makes the set_ctrl implementation simpler. -- line 1309 ---------------------------------------- -- line 1312 ---------------------------------------- . // replicate the buckets at the end of the trailing group. For example . // with 2 buckets and a group size of 4, the control bytes will look . // like this: . // . // Real | Replicated . // --------------------------------------------- . // | [A] | [B] | [EMPTY] | [EMPTY] | [A] | [B] | . // --------------------------------------------- 39,244,440 ( 0.11%) let index2 = ((index.wrapping_sub(Group::WIDTH)) & self.bucket_mask) + Group::WIDTH; . 13,081,505 ( 0.04%) *self.ctrl(index) = ctrl; 13,093,090 ( 0.04%) *self.ctrl(index2) = ctrl; 30 ( 0.00%) } . . /// Returns a pointer to a control byte. . #[inline] 576 ( 0.00%) unsafe fn ctrl(&self, index: usize) -> *mut u8 { . debug_assert!(index < self.num_ctrl_bytes()); 432 ( 0.00%) self.ctrl.as_ptr().add(index) 288 ( 0.00%) } . . #[inline] 60 ( 0.00%) fn buckets(&self) -> usize { 5,686,133 ( 0.02%) self.bucket_mask + 1 60 ( 0.00%) } . . #[inline] 20 ( 0.00%) fn num_ctrl_bytes(&self) -> usize { 4,546,289 ( 0.01%) self.bucket_mask + 1 + Group::WIDTH 20 ( 0.00%) } . . #[inline] 3,980 ( 0.00%) fn is_empty_singleton(&self) -> bool { 21,121,872 ( 0.06%) self.bucket_mask == 0 7,960 ( 0.00%) } . . #[allow(clippy::mut_mut)] . #[inline] 170 ( 0.00%) unsafe fn prepare_resize( . &self, . table_layout: TableLayout, . capacity: usize, . fallibility: Fallibility, . ) -> Result, TryReserveError> { 10 ( 0.00%) debug_assert!(self.items <= capacity); . . // Allocate and initialize the new table. 29,148 ( 0.00%) let mut new_table = RawTableInner::fallible_with_capacity( 10 ( 0.00%) self.alloc.clone(), . table_layout, . capacity, . fallibility, . )?; 2,362,746 ( 0.01%) new_table.growth_left -= self.items; 20 ( 0.00%) new_table.items = self.items; . . // The hash function may panic, in which case we simply free the new . // table without dropping any elements that may have been copied into . // it. . // . // This guard is also used to free the old table on success, see . // the comment at the bottom of this function. 270 ( 0.00%) Ok(guard(new_table, move |self_| { 1,050,608 ( 0.00%) if !self_.is_empty_singleton() { . self_.free_buckets(table_layout); . } 20 ( 0.00%) })) 40 ( 0.00%) } . . /// Reserves or rehashes to make room for `additional` more elements. . /// . /// This uses dynamic dispatch to reduce the amount of . /// code generated, but it is eliminated by LLVM optimizations when inlined. . #[allow(clippy::inline_always)] . #[inline(always)] . unsafe fn reserve_rehash_inner( -- line 1387 ---------------------------------------- -- line 1388 ---------------------------------------- . &mut self, . additional: usize, . hasher: &dyn Fn(&mut Self, usize) -> u64, . fallibility: Fallibility, . layout: TableLayout, . drop: Option, . ) -> Result<(), TryReserveError> { . // Avoid `Option::ok_or_else` because it bloats LLVM IR. 2,101,276 ( 0.01%) let new_items = match self.items.checked_add(additional) { 40 ( 0.00%) Some(new_items) => new_items, . None => return Err(fallibility.capacity_overflow()), . }; 2,101,192 ( 0.01%) let full_capacity = bucket_mask_to_capacity(self.bucket_mask); 4,449,539 ( 0.01%) if new_items <= full_capacity / 2 { . // Rehash in-place without re-allocating if we have plenty of spare . // capacity that is locked up due to DELETED entries. . self.rehash_in_place(hasher, layout.size, drop); 26 ( 0.00%) Ok(()) . } else { . // Otherwise, conservatively resize to at least the next size up . // to avoid churning deletes into frequent rehashes. . self.resize_inner( 1,050,658 ( 0.00%) usize::max(new_items, full_capacity + 1), . hasher, . fallibility, . layout, . ) . } 20 ( 0.00%) } . . /// Allocates a new table of a different size and moves the contents of the . /// current table into it. . /// . /// This uses dynamic dispatch to reduce the amount of . /// code generated, but it is eliminated by LLVM optimizations when inlined. . #[allow(clippy::inline_always)] . #[inline(always)] . unsafe fn resize_inner( . &mut self, . capacity: usize, . hasher: &dyn Fn(&mut Self, usize) -> u64, . fallibility: Fallibility, . layout: TableLayout, . ) -> Result<(), TryReserveError> { 67,970 ( 0.00%) let mut new_table = self.prepare_resize(layout, capacity, fallibility)?; . . // Copy all elements to the new table. 410 ( 0.00%) for i in 0..self.buckets() { 7,974,478 ( 0.02%) if !is_full(*self.ctrl(i)) { . continue; . } . . // This may panic. . let hash = hasher(self, i); . . // We can use a simpler version of insert() here since: . // - there are no DELETED entries. -- line 1444 ---------------------------------------- -- line 1452 ---------------------------------------- . layout.size, . ); . } . . // We successfully copied all elements without panicking. Now replace . // self with the new table. The old table will have its memory freed but . // the items will not be dropped (since they have been moved into the . // new table). 50 ( 0.00%) mem::swap(self, &mut new_table); . 1,050,578 ( 0.00%) Ok(()) 40 ( 0.00%) } . . /// Rehashes the contents of the table in place (i.e. without changing the . /// allocation). . /// . /// If `hasher` panics then some the table's contents may be lost. . /// . /// This uses dynamic dispatch to reduce the amount of . /// code generated, but it is eliminated by LLVM optimizations when inlined. -- line 1471 ---------------------------------------- -- line 1496 ---------------------------------------- . } . self_.growth_left = bucket_mask_to_capacity(self_.bucket_mask) - self_.items; . }); . . // At this point, DELETED elements are elements that we haven't . // rehashed yet. Find them and re-insert them at their ideal . // position. . 'outer: for i in 0..guard.buckets() { 896 ( 0.00%) if *guard.ctrl(i) != DELETED { . continue; . } . . let i_p = guard.bucket_ptr(i, size_of); . . 'inner: loop { . // Hash the current item . let hash = hasher(*guard, i); -- line 1512 ---------------------------------------- -- line 1515 ---------------------------------------- . let new_i = guard.find_insert_slot(hash); . let new_i_p = guard.bucket_ptr(new_i, size_of); . . // Probing works by scanning through all of the control . // bytes in groups, which may not be aligned to the group . // size. If both the new and old position fall within the . // same unaligned group, then there is no benefit in moving . // it and we can just continue to the next item. 143 ( 0.00%) if likely(guard.is_in_same_group(i, new_i, hash)) { . guard.set_ctrl_h2(i, hash); . continue 'outer; . } . . // We are moving the current item to a new position. Write . // our H2 to the control byte of the new position. . let prev_ctrl = guard.replace_ctrl_h2(new_i, hash); . if prev_ctrl == EMPTY { -- line 1531 ---------------------------------------- -- line 1541 ---------------------------------------- . // swapped into the old slot. . debug_assert_eq!(prev_ctrl, DELETED); . ptr::swap_nonoverlapping(i_p, new_i_p, size_of); . continue 'inner; . } . } . } . 39 ( 0.00%) guard.growth_left = bucket_mask_to_capacity(guard.bucket_mask) - guard.items; . . mem::forget(guard); . } . . #[inline] 70 ( 0.00%) unsafe fn free_buckets(&mut self, table_layout: TableLayout) { . // Avoid `Option::unwrap_or_else` because it bloats LLVM IR. 200 ( 0.00%) let (layout, ctrl_offset) = match table_layout.calculate_layout_for(self.buckets()) { 120 ( 0.00%) Some(lco) => lco, . None => hint::unreachable_unchecked(), . }; 30 ( 0.00%) self.alloc.deallocate( 713,652 ( 0.00%) NonNull::new_unchecked(self.ctrl.as_ptr().sub(ctrl_offset)), . layout, . ); 20 ( 0.00%) } . . /// Marks all table buckets as empty without dropping their contents. . #[inline] . fn clear_no_drop(&mut self) { 145,946 ( 0.00%) if !self.is_empty_singleton() { . unsafe { . self.ctrl(0).write_bytes(EMPTY, self.num_ctrl_bytes()); . } . } 175,149 ( 0.00%) self.items = 0; 145,946 ( 0.00%) self.growth_left = bucket_mask_to_capacity(self.bucket_mask); . } . . #[inline] . unsafe fn erase(&mut self, index: usize) { . debug_assert!(is_full(*self.ctrl(index))); 1,178,599 ( 0.00%) let index_before = index.wrapping_sub(Group::WIDTH) & self.bucket_mask; . let empty_before = Group::load(self.ctrl(index_before)).match_empty(); . let empty_after = Group::load(self.ctrl(index)).match_empty(); . . // If we are inside a continuous block of Group::WIDTH full or deleted . // cells then a probe window may have seen a full block when trying to . // insert. We therefore need to keep that block non-empty so that . // lookups will continue searching to the next probe window. . // . // Note that in this context `leading_zeros` refers to the bytes at the . // end of a group, while `trailing_zeros` refers to the bytes at the . // beginning of a group. 4,714,396 ( 0.01%) let ctrl = if empty_before.leading_zeros() + empty_after.trailing_zeros() >= Group::WIDTH { . DELETED . } else { 5,742,105 ( 0.02%) self.growth_left += 1; . EMPTY . }; . self.set_ctrl(index, ctrl); 4,714,396 ( 0.01%) self.items -= 1; . } . } . . impl Clone for RawTable { 91,256 ( 0.00%) fn clone(&self) -> Self { 12,193 ( 0.00%) if self.table.is_empty_singleton() { . Self::new_in(self.table.alloc.clone()) . } else { . unsafe { . let mut new_table = ManuallyDrop::new( . // Avoid `Result::ok_or_else` because it bloats LLVM IR. . match Self::new_uninitialized( . self.table.alloc.clone(), . self.table.buckets(), -- line 1615 ---------------------------------------- -- line 1624 ---------------------------------------- . // We need to free the memory allocated for the new table. . new_table.free_buckets(); . }); . . // Return the newly created table. . ManuallyDrop::into_inner(new_table) . } . } 102,663 ( 0.00%) } . . fn clone_from(&mut self, source: &Self) { . if source.table.is_empty_singleton() { . *self = Self::new_in(self.table.alloc.clone()); . } else { . unsafe { . // First, drop all our elements without clearing the control bytes. . self.drop_elements(); -- line 1640 ---------------------------------------- -- line 1687 ---------------------------------------- . .table . .ctrl(0) . .copy_to_nonoverlapping(self.table.ctrl(0), self.table.num_ctrl_bytes()); . source . .data_start() . .copy_to_nonoverlapping(self.data_start(), self.table.buckets()); . . self.table.items = source.table.items; 1,576 ( 0.00%) self.table.growth_left = source.table.growth_left; . } . } . . impl RawTable { . /// Common code for clone and clone_from. Assumes `self.buckets() == source.buckets()`. . #[cfg_attr(feature = "inline-more", inline)] . unsafe fn clone_from_impl(&mut self, source: &Self, mut on_panic: impl FnMut(&mut Self)) { . // Copy the control bytes unchanged. We do this in a single pass -- line 1703 ---------------------------------------- -- line 1790 ---------------------------------------- . fn default() -> Self { . Self::new_in(Default::default()) . } . } . . #[cfg(feature = "nightly")] . unsafe impl<#[may_dangle] T, A: Allocator + Clone> Drop for RawTable { . #[cfg_attr(feature = "inline-more", inline)] 9,666,740 ( 0.03%) fn drop(&mut self) { 9,096,784 ( 0.03%) if !self.table.is_empty_singleton() { . unsafe { 10 ( 0.00%) self.drop_elements(); 10 ( 0.00%) self.free_buckets(); . } . } 10,243,266 ( 0.03%) } . } . #[cfg(not(feature = "nightly"))] . impl Drop for RawTable { . #[cfg_attr(feature = "inline-more", inline)] . fn drop(&mut self) { . if !self.table.is_empty_singleton() { . unsafe { . self.drop_elements(); -- line 1813 ---------------------------------------- -- line 1817 ---------------------------------------- . } . } . . impl IntoIterator for RawTable { . type Item = T; . type IntoIter = RawIntoIter; . . #[cfg_attr(feature = "inline-more", inline)] 114,848 ( 0.00%) fn into_iter(self) -> RawIntoIter { . unsafe { . let iter = self.iter(); . self.into_iter_from(iter) . } 143,560 ( 0.00%) } . } . . /// Iterator over a sub-range of a table. Unlike `RawIter` this iterator does . /// not track an item count. . pub(crate) struct RawIterRange { . // Mask of full buckets in the current group. Bits are cleared from this . // mask as each element is processed. . current_group: BitMask, -- line 1838 ---------------------------------------- -- line 1848 ---------------------------------------- . end: *const u8, . } . . impl RawIterRange { . /// Returns a `RawIterRange` covering a subset of a table. . /// . /// The control byte address must be aligned to the group size. . #[cfg_attr(feature = "inline-more", inline)] 120 ( 0.00%) unsafe fn new(ctrl: *const u8, data: Bucket, len: usize) -> Self { . debug_assert_ne!(len, 0); . debug_assert_eq!(ctrl as usize % Group::WIDTH, 0); 10 ( 0.00%) let end = ctrl.add(len); . . // Load the first group and advance ctrl to point to the next group 60 ( 0.00%) let current_group = Group::load_aligned(ctrl).match_full(); 10 ( 0.00%) let next_ctrl = ctrl.add(Group::WIDTH); . 40 ( 0.00%) Self { . current_group, . data, . next_ctrl, . end, . } 20 ( 0.00%) } . . /// Splits a `RawIterRange` into two halves. . /// . /// Returns `None` if the remaining range is smaller than or equal to the . /// group width. . #[cfg_attr(feature = "inline-more", inline)] . #[cfg(feature = "rayon")] . pub(crate) fn split(mut self) -> (Self, Option>) { -- line 1879 ---------------------------------------- -- line 1931 ---------------------------------------- . } . } . } . . impl Iterator for RawIterRange { . type Item = Bucket; . . #[cfg_attr(feature = "inline-more", inline)] 100 ( 0.00%) fn next(&mut self) -> Option> { . unsafe { . loop { 4,594,392 ( 0.01%) if let Some(index) = self.current_group.lowest_set_bit() { 686,072 ( 0.00%) self.current_group = self.current_group.remove_lowest_bit(); 1,143,842 ( 0.00%) return Some(self.data.next_n(index)); . } . 4,512,223 ( 0.01%) if self.next_ctrl >= self.end { 10 ( 0.00%) return None; . } . . // We might read past self.end up to the next group boundary, . // but this is fine because it only occurs on tables smaller . // than the group size where the trailing control bytes are all . // EMPTY. On larger tables self.end is guaranteed to be aligned . // to the group size (since tables are power-of-two sized). 85,959 ( 0.00%) self.current_group = Group::load_aligned(self.next_ctrl).match_full(); 106,452 ( 0.00%) self.data = self.data.next_n(Group::WIDTH); 133,475 ( 0.00%) self.next_ctrl = self.next_ctrl.add(Group::WIDTH); . } . } 75 ( 0.00%) } . . #[inline] . fn size_hint(&self) -> (usize, Option) { . // We don't have an item count, so just guess based on the range size. . ( . 0, . Some(unsafe { offset_from(self.end, self.next_ctrl) + Group::WIDTH }), . ) -- line 1969 ---------------------------------------- -- line 2102 ---------------------------------------- . } . } else { . // We must have already iterated past the removed item. . } . } . } . . unsafe fn drop_elements(&mut self) { 26,892 ( 0.00%) if mem::needs_drop::() && self.len() != 0 { . for item in self { . item.drop(); . } . } . } . } . . impl Clone for RawIter { -- line 2118 ---------------------------------------- -- line 2124 ---------------------------------------- . } . } . } . . impl Iterator for RawIter { . type Item = Bucket; . . #[cfg_attr(feature = "inline-more", inline)] 993,548 ( 0.00%) fn next(&mut self) -> Option> { 2,481,264 ( 0.01%) if let Some(b) = self.iter.next() { 6,943,798 ( 0.02%) self.items -= 1; 15 ( 0.00%) Some(b) . } else { . // We don't check against items == 0 here to allow the . // compiler to optimize away the item count entirely if the . // iterator length is never queried. . debug_assert_eq!(self.items, 0); 10 ( 0.00%) None . } 1,987,021 ( 0.01%) } . . #[inline] . fn size_hint(&self) -> (usize, Option) { . (self.items, Some(self.items)) . } . } . . impl ExactSizeIterator for RawIter {} -- line 2151 ---------------------------------------- -- line 2177 ---------------------------------------- . T: Sync, . A: Sync, . { . } . . #[cfg(feature = "nightly")] . unsafe impl<#[may_dangle] T, A: Allocator + Clone> Drop for RawIntoIter { . #[cfg_attr(feature = "inline-more", inline)] 40,680 ( 0.00%) fn drop(&mut self) { . unsafe { . // Drop all remaining elements . self.iter.drop_elements(); . . // Free the table 278,341 ( 0.00%) if let Some((ptr, layout)) = self.allocation { . self.alloc.deallocate(ptr, layout); . } . } 7,376 ( 0.00%) } . } . #[cfg(not(feature = "nightly"))] . impl Drop for RawIntoIter { . #[cfg_attr(feature = "inline-more", inline)] . fn drop(&mut self) { . unsafe { . // Drop all remaining elements . self.iter.drop_elements(); -- line 2203 ---------------------------------------- -- line 2209 ---------------------------------------- . } . } . } . . impl Iterator for RawIntoIter { . type Item = T; . . #[cfg_attr(feature = "inline-more", inline)] 10,569 ( 0.00%) fn next(&mut self) -> Option { 6,312 ( 0.00%) unsafe { Some(self.iter.next()?.read()) } 21,138 ( 0.00%) } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 5 ( 0.00%) self.iter.size_hint() . } . } . . impl ExactSizeIterator for RawIntoIter {} . impl FusedIterator for RawIntoIter {} . . /// Iterator which consumes elements without freeing the table storage. . pub struct RawDrain<'a, T, A: Allocator + Clone = Global> { -- line 2231 ---------------------------------------- -- line 2259 ---------------------------------------- . where . T: Sync, . A: Sync, . { . } . . impl Drop for RawDrain<'_, T, A> { . #[cfg_attr(feature = "inline-more", inline)] 30,744 ( 0.00%) fn drop(&mut self) { . unsafe { . // Drop all remaining elements. Note that this may panic. . self.iter.drop_elements(); . . // Reset the contents of the table now that all elements have been . // dropped. . self.table.clear_no_drop(); . . // Move the now empty table back to its original location. 3,843 ( 0.00%) self.orig_table . .as_ptr() . .copy_from_nonoverlapping(&*self.table, 1); . } 30,744 ( 0.00%) } . } . . impl Iterator for RawDrain<'_, T, A> { . type Item = T; . . #[cfg_attr(feature = "inline-more", inline)] . fn next(&mut self) -> Option { . unsafe { -- line 2289 ---------------------------------------- 163,141,916 ( 0.47%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_privacy/src/lib.rs -------------------------------------------------------------------------------- Ir -- line 59 ---------------------------------------- . &mut self, . def_id: DefId, . kind: &str, . descr: &dyn fmt::Display, . ) -> ControlFlow; . . /// Not overridden, but used to actually visit types and traits. . fn skeleton(&mut self) -> DefIdVisitorSkeleton<'_, 'tcx, Self> { 3,068,965 ( 0.01%) DefIdVisitorSkeleton { . def_id_visitor: self, . visited_opaque_tys: Default::default(), . dummy: Default::default(), . } . } 33,462 ( 0.00%) fn visit(&mut self, ty_fragment: impl TypeFoldable<'tcx>) -> ControlFlow { . ty_fragment.visit_with(&mut self.skeleton()) 55,770 ( 0.00%) } 22,074 ( 0.00%) fn visit_trait(&mut self, trait_ref: TraitRef<'tcx>) -> ControlFlow { . self.skeleton().visit_trait(trait_ref) 22,074 ( 0.00%) } . fn visit_projection_ty( . &mut self, . projection: ty::ProjectionTy<'tcx>, . ) -> ControlFlow { 8 ( 0.00%) self.skeleton().visit_projection_ty(projection) . } . fn visit_predicates( . &mut self, . predicates: ty::GenericPredicates<'tcx>, . ) -> ControlFlow { 20,990 ( 0.00%) self.skeleton().visit_predicates(predicates) . } . } . . struct DefIdVisitorSkeleton<'v, 'tcx, V: ?Sized> { . def_id_visitor: &'v mut V, . visited_opaque_tys: FxHashSet, . dummy: PhantomData>, . } . . impl<'tcx, V> DefIdVisitorSkeleton<'_, 'tcx, V> . where . V: DefIdVisitor<'tcx> + ?Sized, . { . fn visit_trait(&mut self, trait_ref: TraitRef<'tcx>) -> ControlFlow { 3,679 ( 0.00%) let TraitRef { def_id, substs } = trait_ref; 1,878,151 ( 0.01%) self.def_id_visitor.visit_def_id(def_id, "trait", &trait_ref.print_only_trait_path())?; 3,679 ( 0.00%) if self.def_id_visitor.shallow() { ControlFlow::CONTINUE } else { substs.visit_with(self) } . } . 939,600 ( 0.00%) fn visit_projection_ty( . &mut self, . projection: ty::ProjectionTy<'tcx>, . ) -> ControlFlow { 751,680 ( 0.00%) let (trait_ref, assoc_substs) = 187,920 ( 0.00%) projection.trait_ref_and_own_substs(self.def_id_visitor.tcx()); . self.visit_trait(trait_ref)?; . if self.def_id_visitor.shallow() { . ControlFlow::CONTINUE . } else { . assoc_substs.iter().try_for_each(|subst| subst.visit_with(self)) . } 845,640 ( 0.00%) } . . fn visit_predicate(&mut self, predicate: ty::Predicate<'tcx>) -> ControlFlow { 9,404 ( 0.00%) match predicate.kind().skip_binder() { . ty::PredicateKind::Trait(ty::TraitPredicate { . trait_ref, . constness: _, . polarity: _, . }) => self.visit_trait(trait_ref), . ty::PredicateKind::Projection(ty::ProjectionPredicate { projection_ty, term }) => { 12 ( 0.00%) term.visit_with(self)?; 30 ( 0.00%) self.visit_projection_ty(projection_ty) . } . ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty, _region)) => { . ty.visit_with(self) . } . ty::PredicateKind::RegionOutlives(..) => ControlFlow::CONTINUE, . ty::PredicateKind::ConstEvaluatable(uv) . if self.def_id_visitor.tcx().features().generic_const_exprs => . { -- line 140 ---------------------------------------- -- line 157 ---------------------------------------- . ACNode::Leaf(leaf) => self.visit_const(leaf), . ACNode::Cast(_, _, ty) => self.visit_ty(ty), . ACNode::Binop(..) | ACNode::UnaryOp(..) | ACNode::FunctionCall(_, _) => { . ControlFlow::CONTINUE . } . }) . } . 146,930 ( 0.00%) fn visit_predicates( . &mut self, . predicates: ty::GenericPredicates<'tcx>, . ) -> ControlFlow { . let ty::GenericPredicates { parent: _, predicates } = predicates; . predicates.iter().try_for_each(|&(predicate, _span)| self.visit_predicate(predicate)) 167,920 ( 0.00%) } . } . . impl<'tcx, V> TypeVisitor<'tcx> for DefIdVisitorSkeleton<'_, 'tcx, V> . where . V: DefIdVisitor<'tcx> + ?Sized, . { . type BreakTy = V::BreakTy; . 9,212,234 ( 0.03%) fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow { 1,031,890 ( 0.00%) let tcx = self.def_id_visitor.tcx(); . // InternalSubsts are not visited here because they are visited below in `super_visit_with`. 5,098,238 ( 0.01%) match *ty.kind() { 1,341,179 ( 0.00%) ty::Adt(&ty::AdtDef { did: def_id, .. }, ..) . | ty::Foreign(def_id) . | ty::FnDef(def_id, ..) . | ty::Closure(def_id, ..) . | ty::Generator(def_id, ..) => { 6,098,954 ( 0.02%) self.def_id_visitor.visit_def_id(def_id, "type", &ty)?; . if self.def_id_visitor.shallow() { . return ControlFlow::CONTINUE; . } . // Default type visitor doesn't visit signatures of fn types. . // Something like `fn() -> Priv {my_func}` is considered a private type even if . // `my_func` is public, so we need to visit signatures. 1,368,788 ( 0.00%) if let ty::FnDef(..) = ty.kind() { . tcx.fn_sig(def_id).visit_with(self)?; . } . // Inherent static methods don't have self type in substs. . // Something like `fn() {my_method}` type of the method . // `impl Pub { pub fn my_method() {} }` is considered a private type, . // so we need to visit the self type additionally. 2,030,994 ( 0.01%) if let Some(assoc_item) = tcx.opt_associated_item(def_id) { 73,062 ( 0.00%) if let ty::ImplContainer(impl_def_id) = assoc_item.container { 8,344 ( 0.00%) tcx.type_of(impl_def_id).visit_with(self)?; . } . } . } 187,904 ( 0.00%) ty::Projection(proj) => { . if self.def_id_visitor.skip_assoc_tys() { . // Visitors searching for minimal visibility/reachability want to . // conservatively approximate associated types like `::Alias` . // as visible/reachable even if both `Type` and `Trait` are private. . // Ideally, associated types should be substituted in the same way as . // free type aliases, but this isn't done yet. . return ControlFlow::CONTINUE; . } . // This will also visit substs if necessary, so we don't need to recurse. 937,546 ( 0.00%) return self.visit_projection_ty(proj); . } 2,770 ( 0.00%) ty::Dynamic(predicates, ..) => { . // All traits in the list are considered the "primary" part of the type . // and are visited by shallow visitors. 22,160 ( 0.00%) for predicate in predicates { 16,620 ( 0.00%) let trait_ref = match predicate.skip_binder() { 16,620 ( 0.00%) ty::ExistentialPredicate::Trait(trait_ref) => trait_ref, . ty::ExistentialPredicate::Projection(proj) => proj.trait_ref(tcx), . ty::ExistentialPredicate::AutoTrait(def_id) => { . ty::ExistentialTraitRef { def_id, substs: InternalSubsts::empty() } . } . }; 5,540 ( 0.00%) let ty::ExistentialTraitRef { def_id, substs: _ } = trait_ref; 33,240 ( 0.00%) self.def_id_visitor.visit_def_id(def_id, "trait", &trait_ref)?; . } . } . ty::Opaque(def_id, ..) => { . // Skip repeated `Opaque`s to avoid infinite recursion. . if self.visited_opaque_tys.insert(def_id) { . // The intent is to treat `impl Trait1 + Trait2` identically to . // `dyn Trait1 + Trait2`. Therefore we ignore def-id of the opaque type itself . // (it either has no visibility, or its visibility is insignificant, like -- line 241 ---------------------------------------- -- line 270 ---------------------------------------- . ty::Bound(..) | ty::Placeholder(..) | ty::Infer(..) => { . bug!("unexpected type: {:?}", ty) . } . } . . if self.def_id_visitor.shallow() { . ControlFlow::CONTINUE . } else { 2,628,147 ( 0.01%) ty.super_visit_with(self) . } 8,178,829 ( 0.02%) } . . fn visit_const(&mut self, c: &'tcx Const<'tcx>) -> ControlFlow { 10,746 ( 0.00%) self.visit_ty(c.ty)?; 1,791 ( 0.00%) let tcx = self.def_id_visitor.tcx(); 12,537 ( 0.00%) if let Ok(Some(ct)) = AbstractConst::from_const(tcx, c) { . self.visit_abstract_const_expr(tcx, ct)?; . } . ControlFlow::CONTINUE . } . } . . fn min(vis1: ty::Visibility, vis2: ty::Visibility, tcx: TyCtxt<'_>) -> ty::Visibility { 10,610 ( 0.00%) if vis1.is_at_least(vis2, tcx) { vis2 } else { vis1 } . } . . //////////////////////////////////////////////////////////////////////////////// . /// Visitor used to determine if pub(restricted) is used anywhere in the crate. . /// . /// This is done so that `private_in_public` warnings can be turned into hard errors . /// in crates that have been updated to use pub(restricted). . //////////////////////////////////////////////////////////////////////////////// -- line 301 ---------------------------------------- -- line 303 ---------------------------------------- . tcx: TyCtxt<'tcx>, . has_pub_restricted: bool, . } . . impl<'tcx> Visitor<'tcx> for PubRestrictedVisitor<'tcx> { . type NestedFilter = nested_filter::All; . . fn nested_visit_map(&mut self) -> Self::Map { 21,002 ( 0.00%) self.tcx.hir() . } . fn visit_vis(&mut self, vis: &'tcx hir::Visibility<'tcx>) { 80,171 ( 0.00%) self.has_pub_restricted = self.has_pub_restricted || vis.node.is_pub_restricted(); . } . } . . //////////////////////////////////////////////////////////////////////////////// . /// Visitor used to determine impl visibility and reachability. . //////////////////////////////////////////////////////////////////////////////// . . struct FindMin<'a, 'tcx, VL: VisibilityLike> { -- line 322 ---------------------------------------- -- line 336 ---------------------------------------- . true . } . fn visit_def_id( . &mut self, . def_id: DefId, . _kind: &str, . _descr: &dyn fmt::Display, . ) -> ControlFlow { 116,977 ( 0.00%) self.min = VL::new_min(self, def_id); . ControlFlow::CONTINUE . } . } . . trait VisibilityLike: Sized { . const MAX: Self; . const SHALLOW: bool = false; . fn new_min(find: &FindMin<'_, '_, Self>, def_id: DefId) -> Self; . . // Returns an over-approximation (`skip_assoc_tys` = true) of visibility due to . // associated types for which we can't determine visibility precisely. 78,078 ( 0.00%) fn of_impl(def_id: LocalDefId, tcx: TyCtxt<'_>, access_levels: &AccessLevels) -> Self { 37,180 ( 0.00%) let mut find = FindMin { tcx, access_levels, min: Self::MAX }; 11,154 ( 0.00%) find.visit(tcx.type_of(def_id)); 33,462 ( 0.00%) if let Some(trait_ref) = tcx.impl_trait_ref(def_id) { 3,679 ( 0.00%) find.visit_trait(trait_ref); . } 7,592 ( 0.00%) find.min 89,232 ( 0.00%) } . } . impl VisibilityLike for ty::Visibility { . const MAX: Self = ty::Visibility::Public; 80,311 ( 0.00%) fn new_min(find: &FindMin<'_, '_, Self>, def_id: DefId) -> Self { 34,419 ( 0.00%) min(find.tcx.visibility(def_id), find.min, find.tcx) 114,730 ( 0.00%) } . } . impl VisibilityLike for Option { . const MAX: Self = Some(AccessLevel::Public); . // Type inference is very smart sometimes. . // It can make an impl reachable even some components of its type or trait are unreachable. . // E.g. methods of `impl ReachableTrait for ReachableTy { ... }` . // can be usable from other crates (#57264). So we skip substs when calculating reachability . // and consider an impl reachable if its "shallow" type and trait are reachable. . // . // The assumption we make here is that type-inference won't let you use an impl without knowing . // both "shallow" version of its self type and "shallow" version of its trait if it exists . // (which require reaching the `DefId`s in them). . const SHALLOW: bool = true; 44,382 ( 0.00%) fn new_min(find: &FindMin<'_, '_, Self>, def_id: DefId) -> Self { . cmp::min( 44,382 ( 0.00%) if let Some(def_id) = def_id.as_local() { 15,168 ( 0.00%) find.access_levels.map.get(&def_id).copied() . } else { . Self::MAX . }, 33,270 ( 0.00%) find.min, . ) 59,176 ( 0.00%) } . } . . //////////////////////////////////////////////////////////////////////////////// . /// The embargo visitor, used to determine the exports of the AST. . //////////////////////////////////////////////////////////////////////////////// . . struct EmbargoVisitor<'tcx> { . tcx: TyCtxt<'tcx>, -- line 400 ---------------------------------------- -- line 422 ---------------------------------------- . . struct ReachEverythingInTheInterfaceVisitor<'a, 'tcx> { . access_level: Option, . item_def_id: LocalDefId, . ev: &'a mut EmbargoVisitor<'tcx>, . } . . impl<'tcx> EmbargoVisitor<'tcx> { 150,384 ( 0.00%) fn get(&self, def_id: LocalDefId) -> Option { . self.access_levels.map.get(&def_id).copied() 150,384 ( 0.00%) } . . fn update_with_hir_id( . &mut self, . hir_id: hir::HirId, . level: Option, . ) -> Option { 36,634 ( 0.00%) let def_id = self.tcx.hir().local_def_id(hir_id); . self.update(def_id, level) . } . . /// Updates node level and returns the updated level. . fn update(&mut self, def_id: LocalDefId, level: Option) -> Option { 170,550 ( 0.00%) let old_level = self.get(def_id); . // Accessibility levels can only grow. . if level > old_level { . self.access_levels.map.insert(def_id, level.unwrap()); 5,648 ( 0.00%) self.changed = true; . level . } else { . old_level . } . } . . fn reach( . &mut self, -- line 457 ---------------------------------------- -- line 458 ---------------------------------------- . def_id: LocalDefId, . access_level: Option, . ) -> ReachEverythingInTheInterfaceVisitor<'_, 'tcx> { . ReachEverythingInTheInterfaceVisitor { . access_level: cmp::min(access_level, Some(AccessLevel::Reachable)), . item_def_id: def_id, . ev: self, . } 51,262 ( 0.00%) } . . // We have to make sure that the items that macros might reference . // are reachable, since they might be exported transitively. . fn update_reachability_from_macro(&mut self, local_def_id: LocalDefId, md: &MacroDef) { . // Non-opaque macros cannot make other items more accessible than they already are. . 1,326 ( 0.00%) let hir_id = self.tcx.hir().local_def_id_to_hir_id(local_def_id); 3,978 ( 0.00%) let attrs = self.tcx.hir().attrs(hir_id); 9,282 ( 0.00%) if attr::find_transparency(attrs, md.macro_rules).0 != Transparency::Opaque { . return; . } . . let item_def_id = local_def_id.to_def_id(); . let macro_module_def_id = . ty::DefIdTree::parent(self.tcx, item_def_id).unwrap().expect_local(); . if self.tcx.hir().opt_def_kind(macro_module_def_id) != Some(DefKind::Mod) { . // The macro's parent doesn't correspond to a `mod`, return early (#63164, #65252). -- line 483 ---------------------------------------- -- line 630 ---------------------------------------- . } . . impl<'tcx> Visitor<'tcx> for EmbargoVisitor<'tcx> { . type NestedFilter = nested_filter::All; . . /// We want to visit items in the context of their containing . /// module and so forth, so supply a crate for doing a deep walk. . fn nested_visit_map(&mut self) -> Self::Map { 42,004 ( 0.00%) self.tcx.hir() . } . 136,512 ( 0.00%) fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { 30,336 ( 0.00%) let item_level = match item.kind { . hir::ItemKind::Impl { .. } => { . let impl_level = 44,616 ( 0.00%) Option::::of_impl(item.def_id, self.tcx, &self.access_levels); 7,436 ( 0.00%) self.update(item.def_id, impl_level) . } 30,928 ( 0.00%) _ => self.get(item.def_id), . }; . . // Update levels of nested things. 78,676 ( 0.00%) match item.kind { . hir::ItemKind::Enum(ref def, _) => { 818 ( 0.00%) for variant in def.variants { 6,696 ( 0.00%) let variant_level = self.update_with_hir_id(variant.id, item_level); 8,928 ( 0.00%) if let Some(ctor_hir_id) = variant.data.ctor_hir_id() { . self.update_with_hir_id(ctor_hir_id, item_level); . } 4,464 ( 0.00%) for field in variant.data.fields() { 1,068 ( 0.00%) self.update_with_hir_id(field.hir_id, variant_level); . } . } . } . hir::ItemKind::Impl(ref impl_) => { 22,308 ( 0.00%) for impl_item_ref in impl_.items { 45,014 ( 0.00%) if impl_.of_trait.is_some() 724 ( 0.00%) || self.tcx.visibility(impl_item_ref.id.def_id) == ty::Visibility::Public . { 26,360 ( 0.00%) self.update(impl_item_ref.id.def_id, item_level); . } . } . } 24 ( 0.00%) hir::ItemKind::Trait(.., trait_item_refs) => { . for trait_item_ref in trait_item_refs { 44 ( 0.00%) self.update(trait_item_ref.id.def_id, item_level); . } . } . hir::ItemKind::Struct(ref def, _) | hir::ItemKind::Union(ref def, _) => { 6,872 ( 0.00%) if let Some(ctor_hir_id) = def.ctor_hir_id() { . self.update_with_hir_id(ctor_hir_id, item_level); . } 3,436 ( 0.00%) for field in def.fields() { 10,752 ( 0.00%) if field.vis.node.is_pub() { 5,560 ( 0.00%) self.update_with_hir_id(field.hir_id, item_level); . } . } . } . hir::ItemKind::Macro(ref macro_def) => { 2,652 ( 0.00%) self.update_reachability_from_macro(item.def_id, macro_def); . } . hir::ItemKind::ForeignMod { items, .. } => { . for foreign_item in items { . if self.tcx.visibility(foreign_item.id.def_id) == ty::Visibility::Public { . self.update(foreign_item.id.def_id, item_level); . } . } . } -- line 697 ---------------------------------------- -- line 704 ---------------------------------------- . | hir::ItemKind::TyAlias(..) . | hir::ItemKind::Mod(..) . | hir::ItemKind::TraitAlias(..) . | hir::ItemKind::Fn(..) . | hir::ItemKind::ExternCrate(..) => {} . } . . // Mark all items in interfaces of reachable items as reachable. 75,840 ( 0.00%) match item.kind { . // The interface is empty. . hir::ItemKind::Macro(..) | hir::ItemKind::ExternCrate(..) => {} . // All nested items are checked by `visit_item`. . hir::ItemKind::Mod(..) => {} . // Handled in the access level of in rustc_resolve . hir::ItemKind::Use(..) => {} . // The interface is empty. . hir::ItemKind::GlobalAsm(..) => {} -- line 720 ---------------------------------------- -- line 732 ---------------------------------------- . self.reach(item.def_id, exist_level).generics().predicates().ty(); . } . } . // Visit everything. . hir::ItemKind::Const(..) . | hir::ItemKind::Static(..) . | hir::ItemKind::Fn(..) . | hir::ItemKind::TyAlias(..) => { 1,800 ( 0.00%) if item_level.is_some() { 112 ( 0.00%) self.reach(item.def_id, item_level).generics().predicates().ty(); . } . } 8 ( 0.00%) hir::ItemKind::Trait(.., trait_item_refs) => { 8 ( 0.00%) if item_level.is_some() { 32 ( 0.00%) self.reach(item.def_id, item_level).generics().predicates(); . . for trait_item_ref in trait_item_refs { 20 ( 0.00%) let mut reach = self.reach(trait_item_ref.id.def_id, item_level); 40 ( 0.00%) reach.generics().predicates(); . 28 ( 0.00%) if trait_item_ref.kind == AssocItemKind::Type 12 ( 0.00%) && !trait_item_ref.defaultness.has_value() . { . // No type to visit. . } else { 8 ( 0.00%) reach.ty(); . } . } . } . } . hir::ItemKind::TraitAlias(..) => { . if item_level.is_some() { . self.reach(item.def_id, item_level).generics().predicates(); . } . } . // Visit everything except for private impl items. . hir::ItemKind::Impl(ref impl_) => { 7,436 ( 0.00%) if item_level.is_some() { 56,720 ( 0.00%) self.reach(item.def_id, item_level).generics().predicates().ty().trait_ref(); . 5,672 ( 0.00%) for impl_item_ref in impl_.items { 16,902 ( 0.00%) let impl_item_level = self.get(impl_item_ref.id.def_id); 32,406 ( 0.00%) if impl_item_level.is_some() { 56,240 ( 0.00%) self.reach(impl_item_ref.id.def_id, impl_item_level) . .generics() . .predicates() . .ty(); . } . } . } . } . . // Visit everything, but enum variants have their own levels. . hir::ItemKind::Enum(ref def, _) => { 818 ( 0.00%) if item_level.is_some() { 2,048 ( 0.00%) self.reach(item.def_id, item_level).generics().predicates(); . } 818 ( 0.00%) for variant in def.variants { 20,088 ( 0.00%) let variant_level = self.get(self.tcx.hir().local_def_id(variant.id)); 2,232 ( 0.00%) if variant_level.is_some() { 672 ( 0.00%) for field in variant.data.fields() { 2,340 ( 0.00%) self.reach(self.tcx.hir().local_def_id(field.hir_id), variant_level) . .ty(); . } . // Corner case: if the variant is reachable, but its . // enum is not, make the enum reachable as well. 672 ( 0.00%) self.update(item.def_id, variant_level); . } . } . } . // Visit everything, but foreign items have their own levels. . hir::ItemKind::ForeignMod { items, .. } => { . for foreign_item in items { . let foreign_item_level = self.get(foreign_item.id.def_id); . if foreign_item_level.is_some() { -- line 806 ---------------------------------------- -- line 808 ---------------------------------------- . .generics() . .predicates() . .ty(); . } . } . } . // Visit everything except for private fields. . hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => { 1,718 ( 0.00%) if item_level.is_some() { 4,384 ( 0.00%) self.reach(item.def_id, item_level).generics().predicates(); 1,096 ( 0.00%) for field in struct_def.fields() { 10,178 ( 0.00%) let def_id = self.tcx.hir().local_def_id(field.hir_id); 4,362 ( 0.00%) let field_level = self.get(def_id); 1,454 ( 0.00%) if field_level.is_some() { 6,940 ( 0.00%) self.reach(def_id, field_level).ty(); . } . } . } . } . } . . let orig_level = mem::replace(&mut self.prev_level, item_level); 45,504 ( 0.00%) intravisit::walk_item(self, item); 15,168 ( 0.00%) self.prev_level = orig_level; 121,344 ( 0.00%) } . . fn visit_block(&mut self, b: &'tcx hir::Block<'tcx>) { . // Blocks can have public items, for example impls, but they always . // start as completely private regardless of publicity of a function, . // constant, type, field, etc., in which this block resides. . let orig_level = mem::replace(&mut self.prev_level, None); . intravisit::walk_block(self, b); . self.prev_level = orig_level; . } . } . . impl ReachEverythingInTheInterfaceVisitor<'_, '_> { 85,190 ( 0.00%) fn generics(&mut self) -> &mut Self { 48,680 ( 0.00%) for param in &self.ev.tcx.generics_of(self.item_def_id).params { 19,094 ( 0.00%) match param.kind { . GenericParamDefKind::Lifetime => {} 1,394 ( 0.00%) GenericParamDefKind::Type { has_default, .. } => { 1,394 ( 0.00%) if has_default { . self.visit(self.ev.tcx.type_of(param.def_id)); . } . } . GenericParamDefKind::Const { has_default, .. } => { . self.visit(self.ev.tcx.type_of(param.def_id)); . if has_default { . self.visit(self.ev.tcx.const_param_default(param.def_id)); . } . } . } . } . self 109,530 ( 0.00%) } . 60,850 ( 0.00%) fn predicates(&mut self) -> &mut Self { 36,510 ( 0.00%) self.visit_predicates(self.ev.tcx.predicates_of(self.item_def_id)); . self 73,020 ( 0.00%) } . 63,720 ( 0.00%) fn ty(&mut self) -> &mut Self { 38,492 ( 0.00%) self.visit(self.ev.tcx.type_of(self.item_def_id)); . self 76,464 ( 0.00%) } . . fn trait_ref(&mut self) -> &mut Self { 34,032 ( 0.00%) if let Some(trait_ref) = self.ev.tcx.impl_trait_ref(self.item_def_id) { . self.visit_trait(trait_ref); . } . self . } . } . . impl<'tcx> DefIdVisitor<'tcx> for ReachEverythingInTheInterfaceVisitor<'_, 'tcx> { . fn tcx(&self) -> TyCtxt<'tcx> { 179,538 ( 0.00%) self.ev.tcx . } 231,760 ( 0.00%) fn visit_def_id( . &mut self, . def_id: DefId, . _kind: &str, . _descr: &dyn fmt::Display, . ) -> ControlFlow { 139,056 ( 0.00%) if let Some(def_id) = def_id.as_local() { 122,502 ( 0.00%) if let (ty::Visibility::Public, _) | (_, Some(AccessLevel::ReachableFromImplTrait)) = 30,726 ( 0.00%) (self.tcx().visibility(def_id.to_def_id()), self.access_level) . { . self.ev.update(def_id, self.access_level); . } . } . ControlFlow::CONTINUE 324,464 ( 0.00%) } . } . . ////////////////////////////////////////////////////////////////////////////////////// . /// Name privacy visitor, checks privacy and reports violations. . /// Most of name privacy checks are performed during the main resolution phase, . /// or later in type checking when field accesses and associated items are resolved. . /// This pass performs remaining checks for fields in struct expressions and patterns. . ////////////////////////////////////////////////////////////////////////////////////// -- line 909 ---------------------------------------- -- line 920 ---------------------------------------- . /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies). . #[track_caller] . fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> { . self.maybe_typeck_results . .expect("`NamePrivacyVisitor::typeck_results` called outside of body") . } . . // Checks that a field in a struct constructor (expression or pattern) is accessible. 72,960 ( 0.00%) fn check_field( . &mut self, . use_ctxt: Span, // syntax context of the field name at the use site . span: Span, // span of the field pattern, e.g., `x: 0` . def: &'tcx ty::AdtDef, // definition of the struct or enum . field: &'tcx ty::FieldDef, . in_update_syntax: bool, . ) { 14,592 ( 0.00%) if def.is_enum() { . return; . } . . // definition of the field . let ident = Ident::new(kw::Empty, use_ctxt); 14,290 ( 0.00%) let hir_id = self.tcx.hir().local_def_id_to_hir_id(self.current_item); 50,015 ( 0.00%) let def_id = self.tcx.adjust_ident_and_get_scope(ident, def.did, hir_id).1; 7,145 ( 0.00%) if !field.vis.is_accessible_from(def_id, self.tcx) { . let label = if in_update_syntax { . format!("field `{}` is private", field.name) . } else { . "private field".to_string() . }; . . struct_span_err!( . self.tcx.sess, -- line 952 ---------------------------------------- -- line 955 ---------------------------------------- . "field `{}` of {} `{}` is private", . field.name, . def.variant_descr(), . self.tcx.def_path_str(def.did) . ) . .span_label(span, label) . .emit(); . } 58,368 ( 0.00%) } . } . . impl<'tcx> Visitor<'tcx> for NamePrivacyVisitor<'tcx> { . type NestedFilter = nested_filter::All; . . /// We want to visit items in the context of their containing . /// module and so forth, so supply a crate for doing a deep walk. . fn nested_visit_map(&mut self) -> Self::Map { 14,161 ( 0.00%) self.tcx.hir() . } . . fn visit_mod(&mut self, _m: &'tcx hir::Mod<'tcx>, _s: Span, _n: hir::HirId) { . // Don't visit nested modules, since we run a separate visitor walk . // for each module in `privacy_access_levels` . } . . fn visit_nested_body(&mut self, body: hir::BodyId) { . let old_maybe_typeck_results = 34,121 ( 0.00%) self.maybe_typeck_results.replace(self.tcx.typeck_body(body)); 40,872 ( 0.00%) let body = self.tcx.hir().body(body); . self.visit_body(body); 1,781 ( 0.00%) self.maybe_typeck_results = old_maybe_typeck_results; . } . . fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { 7,584 ( 0.00%) let orig_current_item = mem::replace(&mut self.current_item, item.def_id); 22,723 ( 0.00%) intravisit::walk_item(self, item); 7,584 ( 0.00%) self.current_item = orig_current_item; . } . 1,380,492 ( 0.00%) fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) { 306,776 ( 0.00%) if let hir::ExprKind::Struct(qpath, fields, ref base) = expr.kind { 6,864 ( 0.00%) let res = self.typeck_results().qpath_res(qpath, expr.hir_id); 3,432 ( 0.00%) let adt = self.typeck_results().expr_ty(expr).ty_adt_def().unwrap(); 10,296 ( 0.00%) let variant = adt.variant_of_res(res); 4,576 ( 0.00%) if let Some(base) = *base { . // If the expression uses FRU we need to make sure all the unmentioned fields . // are checked for privacy (RFC 736). Rather than computing the set of . // unmentioned fields, just check them all. . for (vf_index, variant_field) in variant.fields.iter().enumerate() { . let field = fields.iter().find(|f| { 320 ( 0.00%) self.tcx.field_index(f.hir_id, self.typeck_results()) == vf_index . }); . let (use_ctxt, span) = match field { 33 ( 0.00%) Some(field) => (field.ident.span, field.span), 36 ( 0.00%) None => (base.span, base.span), . }; 290 ( 0.00%) self.check_field(use_ctxt, span, adt, variant_field, true); . } . } else { . for field in fields { 2,923 ( 0.00%) let use_ctxt = field.ident.span; 20,280 ( 0.00%) let index = self.tcx.field_index(field.hir_id, self.typeck_results()); 32,153 ( 0.00%) self.check_field(use_ctxt, field.span, adt, &variant.fields[index], false); . } . } . } . 1,533,880 ( 0.00%) intravisit::walk_expr(self, expr); . } . 380,368 ( 0.00%) fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) { 96,733 ( 0.00%) if let PatKind::Struct(ref qpath, fields, _) = pat.kind { 11,487 ( 0.00%) let res = self.typeck_results().qpath_res(qpath, pat.hir_id); 6,564 ( 0.00%) let adt = self.typeck_results().pat_ty(pat).ty_adt_def().unwrap(); 13,128 ( 0.00%) let variant = adt.variant_of_res(res); . for field in fields { 4,344 ( 0.00%) let use_ctxt = field.ident.span; 26,595 ( 0.00%) let index = self.tcx.field_index(field.hir_id, self.typeck_results()); 43,440 ( 0.00%) self.check_field(use_ctxt, field.span, adt, &variant.fields[index], false); . } . } . 427,914 ( 0.00%) intravisit::walk_pat(self, pat); . } . } . . //////////////////////////////////////////////////////////////////////////////////////////// . /// Type privacy visitor, checks types for privacy and reports violations. . /// Both explicitly written types and inferred types of expressions and patterns are checked. . /// Checks are performed on "semantic" types regardless of names and their hygiene. . //////////////////////////////////////////////////////////////////////////////////////////// -- line 1045 ---------------------------------------- -- line 1061 ---------------------------------------- . .expect("`TypePrivacyVisitor::typeck_results` called outside of body") . } . . fn item_is_accessible(&self, did: DefId) -> bool { . self.tcx.visibility(did).is_accessible_from(self.current_item.to_def_id(), self.tcx) . } . . // Take node-id of an expression or pattern and check its type for privacy. 1,496,593 ( 0.00%) fn check_expr_pat_type(&mut self, id: hir::HirId, span: Span) -> bool { 213,799 ( 0.00%) self.span = span; 213,799 ( 0.00%) let typeck_results = self.typeck_results(); . let result: ControlFlow<()> = try { 855,196 ( 0.00%) self.visit(typeck_results.node_type(id))?; 1,710,392 ( 0.00%) self.visit(typeck_results.node_substs(id))?; 1,924,191 ( 0.01%) if let Some(adjustments) = typeck_results.adjustments().get(id) { . adjustments.iter().try_for_each(|adjustment| self.visit(adjustment.target))?; . } . }; . result.is_break() 1,710,392 ( 0.00%) } . . fn check_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool { 989,482 ( 0.00%) let is_error = !self.item_is_accessible(def_id); . if is_error { . self.tcx . .sess . .struct_span_err(self.span, &format!("{} `{}` is private", kind, descr)) . .span_label(self.span, &format!("private {}", kind)) . .emit(); . } . is_error -- line 1091 ---------------------------------------- -- line 1093 ---------------------------------------- . } . . impl<'tcx> Visitor<'tcx> for TypePrivacyVisitor<'tcx> { . type NestedFilter = nested_filter::All; . . /// We want to visit items in the context of their containing . /// module and so forth, so supply a crate for doing a deep walk. . fn nested_visit_map(&mut self) -> Self::Map { 14,161 ( 0.00%) self.tcx.hir() . } . . fn visit_mod(&mut self, _m: &'tcx hir::Mod<'tcx>, _s: Span, _n: hir::HirId) { . // Don't visit nested modules, since we run a separate visitor walk . // for each module in `privacy_access_levels` . } . 68,120 ( 0.00%) fn visit_nested_body(&mut self, body: hir::BodyId) { . let old_maybe_typeck_results = 20,436 ( 0.00%) self.maybe_typeck_results.replace(self.tcx.typeck_body(body)); 40,872 ( 0.00%) let body = self.tcx.hir().body(body); . self.visit_body(body); 6,812 ( 0.00%) self.maybe_typeck_results = old_maybe_typeck_results; 54,496 ( 0.00%) } . . fn visit_generic_arg(&mut self, generic_arg: &'tcx hir::GenericArg<'tcx>) { 100,447 ( 0.00%) match generic_arg { 51,820 ( 0.00%) hir::GenericArg::Type(t) => self.visit_ty(t), . hir::GenericArg::Infer(inf) => self.visit_infer(inf), . hir::GenericArg::Lifetime(_) | hir::GenericArg::Const(_) => {} . } . } . 395,794 ( 0.00%) fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty<'tcx>) { 113,084 ( 0.00%) self.span = hir_ty.span; 169,626 ( 0.00%) if let Some(typeck_results) = self.maybe_typeck_results { . // Types in bodies. 37,014 ( 0.00%) if self.visit(typeck_results.node_type(hir_ty.hir_id)).is_break() { . return; . } . } else { . // Types in signatures. . // FIXME: This is very ineffective. Ideally each HIR type should be converted . // into a semantic type only once and the result should be cached somehow. 132,612 ( 0.00%) if self.visit(rustc_typeck::hir_ty_to_ty(self.tcx, hir_ty)).is_break() { . return; . } . } . 169,626 ( 0.00%) intravisit::walk_ty(self, hir_ty); 339,252 ( 0.00%) } . . fn visit_infer(&mut self, inf: &'tcx hir::InferArg) { . self.span = inf.span; . if let Some(typeck_results) = self.maybe_typeck_results { . if let Some(ty) = typeck_results.node_type_opt(inf.hir_id) { . if self.visit(ty).is_break() { . return; . } -- line 1150 ---------------------------------------- -- line 1152 ---------------------------------------- . // We don't do anything for const infers here. . } . } else { . bug!("visit_infer without typeck_results"); . } . intravisit::walk_inf(self, inf); . } . 56,128 ( 0.00%) fn visit_trait_ref(&mut self, trait_ref: &'tcx hir::TraitRef<'tcx>) { 21,048 ( 0.00%) self.span = trait_ref.path.span; 7,016 ( 0.00%) if self.maybe_typeck_results.is_none() { . // Avoid calling `hir_trait_to_predicates` in bodies, it will ICE. . // The traits' privacy in bodies is already checked as a part of trait object types. 7,016 ( 0.00%) let bounds = rustc_typeck::hir_trait_to_predicates( 7,016 ( 0.00%) self.tcx, . trait_ref, . // NOTE: This isn't really right, but the actual type doesn't matter here. It's . // just required by `ty::TraitRef`. 21,048 ( 0.00%) self.tcx.types.never, . ); . 63,144 ( 0.00%) for (trait_predicate, _, _) in bounds.trait_bounds { 49,112 ( 0.00%) if self.visit_trait(trait_predicate.skip_binder()).is_break() { . return; . } . } . 42,110 ( 0.00%) for (poly_predicate, _) in bounds.projection_bounds { 12 ( 0.00%) let pred = poly_predicate.skip_binder(); . let poly_pred_term = self.visit(pred.term); 8 ( 0.00%) if poly_pred_term.is_break() . || self.visit_projection_ty(pred.projection_ty).is_break() . { . return; . } . } . } . . intravisit::walk_trait_ref(self, trait_ref); 56,128 ( 0.00%) } . . // Check types of expressions 1,380,492 ( 0.00%) fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) { 1,380,492 ( 0.00%) if self.check_expr_pat_type(expr.hir_id, expr.span) { . // Do not check nested expressions if the error already happened. . return; . } 1,056,654 ( 0.00%) match expr.kind { 9,299 ( 0.00%) hir::ExprKind::Assign(_, rhs, _) | hir::ExprKind::Match(rhs, ..) => { . // Do not report duplicate errors for `x = y` and `match x { ... }`. 60,837 ( 0.00%) if self.check_expr_pat_type(rhs.hir_id, rhs.span) { . return; . } . } 224 ( 0.00%) hir::ExprKind::MethodCall(segment, ..) => { . // Method calls have to be checked specially. 448 ( 0.00%) self.span = segment.ident.span; 1,344 ( 0.00%) if let Some(def_id) = self.typeck_results().type_dependent_def_id(expr.hir_id) { 672 ( 0.00%) if self.visit(self.tcx.type_of(def_id)).is_break() { . return; . } . } else { . self.tcx . .sess . .delay_span_bug(expr.span, "no type-dependent def for method call"); . } . } . _ => {} . } . 460,164 ( 0.00%) intravisit::walk_expr(self, expr); 1,227,104 ( 0.00%) } . . // Prohibit access to associated items with insufficient nominal visibility. . // . // Additionally, until better reachability analysis for macros 2.0 is available, . // we prohibit access to private statics from other crates, this allows to give . // more code internal visibility at link time. (Access to private functions . // is already prohibited by type privacy for function types.) 1,244,980 ( 0.00%) fn visit_qpath(&mut self, qpath: &'tcx hir::QPath<'tcx>, id: hir::HirId, span: Span) { 248,996 ( 0.00%) let def = match qpath { 346,242 ( 0.00%) hir::QPath::Resolved(_, path) => match path.res { 436,608 ( 0.00%) Res::Def(kind, def_id) => Some((kind, def_id)), . _ => None, . }, 9,084 ( 0.00%) hir::QPath::TypeRelative(..) | hir::QPath::LangItem(..) => self . .maybe_typeck_results 44,703 ( 0.00%) .and_then(|typeck_results| typeck_results.type_dependent_def(id)), . }; . let def = def.filter(|(kind, _)| { 153,990 ( 0.00%) matches!( . kind, . DefKind::AssocFn | DefKind::AssocConst | DefKind::AssocTy | DefKind::Static . ) . }); . if let Some((kind, def_id)) = def { . let is_local_static = 43,684 ( 0.00%) if let DefKind::Static = kind { def_id.is_local() } else { false }; 21,942 ( 0.00%) if !self.item_is_accessible(def_id) && !is_local_static { . let sess = self.tcx.sess; . let sm = sess.source_map(); . let name = match qpath { . hir::QPath::Resolved(..) | hir::QPath::LangItem(..) => { . sm.span_to_snippet(qpath.span()).ok() . } . hir::QPath::TypeRelative(_, segment) => Some(segment.ident.to_string()), . }; -- line 1258 ---------------------------------------- -- line 1263 ---------------------------------------- . }; . sess.struct_span_err(span, &msg) . .span_label(span, &format!("private {}", kind)) . .emit(); . return; . } . } . 1,369,478 ( 0.00%) intravisit::walk_qpath(self, qpath, id, span); . } . . // Check types of patterns. . fn visit_pat(&mut self, pattern: &'tcx hir::Pat<'tcx>) { 310,908 ( 0.00%) if self.check_expr_pat_type(pattern.hir_id, pattern.span) { . // Do not check nested patterns if the error already happened. . return; . } . 165,465 ( 0.00%) intravisit::walk_pat(self, pattern); . } . 23,910 ( 0.00%) fn visit_local(&mut self, local: &'tcx hir::Local<'tcx>) { 14,346 ( 0.00%) if let Some(init) = local.init { 29,218 ( 0.00%) if self.check_expr_pat_type(init.hir_id, init.span) { . // Do not report duplicate errors for `let x = y`. . return; . } . } . . intravisit::walk_local(self, local); 13,824 ( 0.00%) } . . // Check types in item interfaces. . fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { 7,584 ( 0.00%) let orig_current_item = mem::replace(&mut self.current_item, item.def_id); . let old_maybe_typeck_results = self.maybe_typeck_results.take(); 22,723 ( 0.00%) intravisit::walk_item(self, item); 7,584 ( 0.00%) self.maybe_typeck_results = old_maybe_typeck_results; 15,444 ( 0.00%) self.current_item = orig_current_item; . } . } . . impl<'tcx> DefIdVisitor<'tcx> for TypePrivacyVisitor<'tcx> { . fn tcx(&self) -> TyCtxt<'tcx> { 2,038,340 ( 0.01%) self.tcx . } 7,421,115 ( 0.02%) fn visit_def_id( . &mut self, . def_id: DefId, . kind: &str, . descr: &dyn fmt::Display, . ) -> ControlFlow { . if self.check_def_id(def_id, kind, descr) { . ControlFlow::BREAK . } else { . ControlFlow::CONTINUE . } 4,452,669 ( 0.01%) } . } . . /////////////////////////////////////////////////////////////////////////////// . /// Obsolete visitors for checking for private items in public interfaces. . /// These visitors are supposed to be kept in frozen state and produce an . /// "old error node set". For backward compatibility the new visitor reports . /// warnings instead of hard errors when the erroneous node is not in this old set. . /////////////////////////////////////////////////////////////////////////////// -- line 1328 ---------------------------------------- -- line 1342 ---------------------------------------- . /// Whether we've recurred at all (i.e., if we're pointing at the . /// first type on which `visit_ty` was called). . at_outer_type: bool, . /// Whether that first type is a public path. . outer_type_is_public_path: bool, . } . . impl<'a, 'tcx> ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { 4,026 ( 0.00%) fn path_is_private_type(&self, path: &hir::Path<'_>) -> bool { 12,084 ( 0.00%) let did = match path.res { . Res::PrimTy(..) | Res::SelfTy(..) | Res::Err => return false, 22,626 ( 0.00%) res => res.def_id(), . }; . . // A path can only be private if: . // it's in this crate... 3,771 ( 0.00%) if let Some(did) = did.as_local() { . // .. and it corresponds to a private type in the AST (this returns . // `None` for type parameters). 15,260 ( 0.00%) match self.tcx.hir().find(self.tcx.hir().local_def_id_to_hir_id(did)) { 12,096 ( 0.00%) Some(Node::Item(item)) => !item.vis.node.is_pub(), . Some(_) | None => false, . } . } else { . false . } 8,052 ( 0.00%) } . . fn trait_is_public(&self, trait_id: LocalDefId) -> bool { . // FIXME: this would preferably be using `exported_items`, but all . // traits are exported currently (see `EmbargoVisitor.exported_trait`). . self.access_levels.is_public(trait_id) . } . . fn check_generic_bound(&mut self, bound: &hir::GenericBound<'_>) { 12 ( 0.00%) if let hir::GenericBound::Trait(ref trait_ref, _) = *bound { 2 ( 0.00%) if self.path_is_private_type(trait_ref.trait_ref.path) { . self.old_error_set.insert(trait_ref.trait_ref.hir_ref_id); . } . } . } . . fn item_is_public(&self, def_id: LocalDefId, vis: &hir::Visibility<'_>) -> bool { 2,394 ( 0.00%) self.access_levels.is_reachable(def_id) || vis.node.is_pub() . } . } . . impl<'a, 'b, 'tcx, 'v> Visitor<'v> for ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> { . fn visit_generic_arg(&mut self, generic_arg: &'v hir::GenericArg<'v>) { 108 ( 0.00%) match generic_arg { . hir::GenericArg::Type(t) => self.visit_ty(t), . hir::GenericArg::Infer(inf) => self.visit_ty(&inf.to_ty()), . hir::GenericArg::Lifetime(_) | hir::GenericArg::Const(_) => {} . } . } . . fn visit_ty(&mut self, ty: &hir::Ty<'_>) { 11,035 ( 0.00%) if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = ty.kind { 8,828 ( 0.00%) if self.inner.path_is_private_type(path) { . self.contains_private = true; . // Found what we're looking for, so let's stop working. . return; . } . } . if let hir::TyKind::Path(_) = ty.kind { 40 ( 0.00%) if self.at_outer_type { 2,187 ( 0.00%) self.outer_type_is_public_path = true; . } . } 4,394 ( 0.00%) self.at_outer_type = false; 4,414 ( 0.00%) intravisit::walk_ty(self, ty) 8,748 ( 0.00%) } . . // Don't want to recurse into `[, .. expr]`. . fn visit_expr(&mut self, _: &hir::Expr<'_>) {} . } . . impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { . type NestedFilter = nested_filter::All; . . /// We want to visit items in the context of their containing . /// module and so forth, so supply a crate for doing a deep walk. . fn nested_visit_map(&mut self) -> Self::Map { 3,842 ( 0.00%) self.tcx.hir() . } . 32,886 ( 0.00%) fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { 14,616 ( 0.00%) match item.kind { . // Contents of a private mod can be re-exported, so we need . // to check internals. . hir::ItemKind::Mod(_) => {} . . // An `extern {}` doesn't introduce a new privacy . // namespace (the contents have their own privacies). . hir::ItemKind::ForeignMod { .. } => {} . 4 ( 0.00%) hir::ItemKind::Trait(.., bounds, _) => { 10 ( 0.00%) if !self.trait_is_public(item.def_id) { . return; . } . . for bound in bounds.iter() { . self.check_generic_bound(bound) . } . } . -- line 1447 ---------------------------------------- -- line 1454 ---------------------------------------- . // `impl [... for] Private` is never visible. . let self_contains_private; . // `impl [... for] Public<...>`, but not `impl [... for] . // Vec` or `(Public,)`, etc. . let self_is_public_path; . . // Check the properties of the `Self` type: . { 8,748 ( 0.00%) let mut visitor = ObsoleteCheckTypeForPrivatenessVisitor { . inner: self, . contains_private: false, . at_outer_type: true, . outer_type_is_public_path: false, . }; 2,187 ( 0.00%) visitor.visit_ty(impl_.self_ty); . self_contains_private = visitor.contains_private; . self_is_public_path = visitor.outer_type_is_public_path; . } . . // Miscellaneous info about the impl: . . // `true` iff this is `impl Private for ...`. . let not_private_trait = impl_.of_trait.as_ref().map_or( . true, // no trait counts as public trait . |tr| { 6,444 ( 0.00%) if let Some(def_id) = tr.path.res.def_id().as_local() { 216 ( 0.00%) self.trait_is_public(def_id) . } else { . true // external traits must be public . } . }, . ); . . // `true` iff this is a trait impl or at least one method is public. . // . // `impl Public { $( fn ...() {} )* }` is not visible. . // . // This is required over just using the methods' privacy . // directly because we might have `impl> ...`, . // and we shouldn't warn about the generics if all the methods . // are private (because `T` won't be visible externally). . let trait_or_some_public_method = impl_.of_trait.is_some() 39 ( 0.00%) || impl_.items.iter().any(|impl_item_ref| { 168 ( 0.00%) let impl_item = self.tcx.hir().impl_item(impl_item_ref.id); 279 ( 0.00%) match impl_item.kind { . hir::ImplItemKind::Const(..) | hir::ImplItemKind::Fn(..) => { . self.access_levels.is_reachable(impl_item_ref.id.def_id) . } . hir::ImplItemKind::TyAlias(_) => false, . } . }); . 4,370 ( 0.00%) if !self_contains_private && not_private_trait && trait_or_some_public_method { . intravisit::walk_generics(self, &impl_.generics); . 4,370 ( 0.00%) match impl_.of_trait { . None => { 37 ( 0.00%) for impl_item_ref in impl_.items { . // This is where we choose whether to walk down . // further into the impl to check its items. We . // should only walk into public items so that we . // don't erroneously report errors for private . // types in private items. 1,056 ( 0.00%) let impl_item = self.tcx.hir().impl_item(impl_item_ref.id); 1,065 ( 0.00%) match impl_item.kind { . hir::ImplItemKind::Const(..) | hir::ImplItemKind::Fn(..) 352 ( 0.00%) if self 176 ( 0.00%) .item_is_public(impl_item.def_id, &impl_item.vis) => . { . intravisit::walk_impl_item(self, impl_item) . } . hir::ImplItemKind::TyAlias(..) => { . intravisit::walk_impl_item(self, impl_item) . } . _ => {} . } -- line 1529 ---------------------------------------- -- line 1538 ---------------------------------------- . // . // Those in 1. can only occur if the trait is in . // this crate and will've been warned about on the . // trait definition (there's no need to warn twice . // so we don't check the methods). . // . // Those in 2. are warned via walk_generics and this . // call here. 6,444 ( 0.00%) intravisit::walk_path(self, tr.path); . . // Those in 3. are warned with this call. 2,148 ( 0.00%) for impl_item_ref in impl_.items { 9,930 ( 0.00%) let impl_item = self.tcx.hir().impl_item(impl_item_ref.id); 14,888 ( 0.00%) if let hir::ImplItemKind::TyAlias(ty) = impl_item.kind { . self.visit_ty(ty); . } . } . } . } 6 ( 0.00%) } else if impl_.of_trait.is_none() && self_is_public_path { . // `impl Public { ... }`. Any public static . // methods will be visible as `Public::foo`. . let mut found_pub_static = false; 2 ( 0.00%) for impl_item_ref in impl_.items { 20 ( 0.00%) if self.access_levels.is_reachable(impl_item_ref.id.def_id) 10 ( 0.00%) || self.tcx.visibility(impl_item_ref.id.def_id) . == ty::Visibility::Public . { . let impl_item = self.tcx.hir().impl_item(impl_item_ref.id); . match impl_item_ref.kind { . AssocItemKind::Const => { . found_pub_static = true; . intravisit::walk_impl_item(self, impl_item); . } -- line 1571 ---------------------------------------- -- line 1572 ---------------------------------------- . AssocItemKind::Fn { has_self: false } => { . found_pub_static = true; . intravisit::walk_impl_item(self, impl_item); . } . _ => {} . } . } . } 4 ( 0.00%) if found_pub_static { . intravisit::walk_generics(self, &impl_.generics) . } . } . return; . } . . // `type ... = ...;` can contain private types, because . // we're introducing a new name. . hir::ItemKind::TyAlias(..) => return, . . // Not at all public, so we don't care. 8,592 ( 0.00%) _ if !self.item_is_public(item.def_id, &item.vis) => { . return; . } . . _ => {} . } . . // We've carefully constructed it so that if we're here, then . // any `visit_ty`'s will be called on things that are in . // public signatures, i.e., things that we're interested in for . // this visitor. 4,650 ( 0.00%) intravisit::walk_item(self, item); 25,512 ( 0.00%) } . 4,704 ( 0.00%) fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) { . for param in generics.params { 6 ( 0.00%) for bound in param.bounds { . self.check_generic_bound(bound); . } . } 588 ( 0.00%) for predicate in generics.where_clause.predicates { 6 ( 0.00%) match predicate { . hir::WherePredicate::BoundPredicate(bound_pred) => { 2 ( 0.00%) for bound in bound_pred.bounds.iter() { . self.check_generic_bound(bound) . } . } . hir::WherePredicate::RegionPredicate(_) => {} . hir::WherePredicate::EqPredicate(eq_pred) => { . self.visit_ty(eq_pred.rhs_ty); . } . } . } 4,704 ( 0.00%) } . . fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem<'tcx>) { . if self.access_levels.is_reachable(item.def_id) { . intravisit::walk_foreign_item(self, item) . } . } . . fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx>) { 9,047 ( 0.00%) if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = t.kind { 7,164 ( 0.00%) if self.path_is_private_type(path) { . self.old_error_set.insert(t.hir_id); . } . } 11,471 ( 0.00%) intravisit::walk_ty(self, t) . } . 1,344 ( 0.00%) fn visit_variant( . &mut self, . v: &'tcx hir::Variant<'tcx>, . g: &'tcx hir::Generics<'tcx>, . item_id: hir::HirId, . ) { 1,680 ( 0.00%) if self.access_levels.is_reachable(self.tcx.hir().local_def_id(v.id)) { 168 ( 0.00%) self.in_variant = true; . intravisit::walk_variant(self, v, g, item_id); 168 ( 0.00%) self.in_variant = false; . } 1,176 ( 0.00%) } . 4,290 ( 0.00%) fn visit_field_def(&mut self, s: &'tcx hir::FieldDef<'tcx>) { 3,758 ( 0.00%) if s.vis.node.is_pub() || self.in_variant { . intravisit::walk_field_def(self, s); . } 132 ( 0.00%) } . . // We don't need to introspect into these at all: an . // expression/block context can't possibly contain exported things. . // (Making them no-ops stops us from traversing the whole AST without . // having to be super careful about our `walk_...` calls above.) . fn visit_block(&mut self, _: &'tcx hir::Block<'tcx>) {} . fn visit_expr(&mut self, _: &'tcx hir::Expr<'tcx>) {} . } -- line 1667 ---------------------------------------- -- line 1679 ---------------------------------------- . /// The visitor checks that each component type is at least this visible. . required_visibility: ty::Visibility, . has_pub_restricted: bool, . has_old_errors: bool, . in_assoc_ty: bool, . } . . impl SearchInterfaceForPrivateItemsVisitor<'_> { 61,719 ( 0.00%) fn generics(&mut self) -> &mut Self { 26,451 ( 0.00%) for param in &self.tcx.generics_of(self.item_def_id).params { 28,776 ( 0.00%) match param.kind { . GenericParamDefKind::Lifetime => {} 3,318 ( 0.00%) GenericParamDefKind::Type { has_default, .. } => { 3,318 ( 0.00%) if has_default { . self.visit(self.tcx.type_of(param.def_id)); . } . } . // FIXME(generic_const_exprs): May want to look inside const here . GenericParamDefKind::Const { .. } => { . self.visit(self.tcx.type_of(param.def_id)); . } . } . } . self 70,536 ( 0.00%) } . 44,085 ( 0.00%) fn predicates(&mut self) -> &mut Self { . // N.B., we use `explicit_predicates_of` and not `predicates_of` . // because we don't want to report privacy errors due to where . // clauses that the compiler inferred. We only want to . // consider the ones that the user wrote. This is important . // for the inferred outlives rules; see . // `src/test/ui/rfc-2093-infer-outlives/privacy.rs`. 17,634 ( 0.00%) self.visit_predicates(self.tcx.explicit_predicates_of(self.item_def_id)); . self 52,902 ( 0.00%) } . 15 ( 0.00%) fn bounds(&mut self) -> &mut Self { . self.visit_predicates(ty::GenericPredicates { . parent: None, 6 ( 0.00%) predicates: self.tcx.explicit_item_bounds(self.item_def_id), . }); . self 15 ( 0.00%) } . 45,245 ( 0.00%) fn ty(&mut self) -> &mut Self { 18,098 ( 0.00%) self.visit(self.tcx.type_of(self.item_def_id)); . self 45,245 ( 0.00%) } . . fn check_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool { 177,255 ( 0.00%) if self.leaks_private_dep(def_id) { . self.tcx.struct_span_lint_hir( . lint::builtin::EXPORTED_PRIVATE_DEPENDENCIES, . self.tcx.hir().local_def_id_to_hir_id(self.item_def_id), . self.tcx.def_span(self.item_def_id.to_def_id()), . |lint| { . lint.build(&format!( . "{} `{}` from private dependency '{}' in public \ . interface", -- line 1738 ---------------------------------------- -- line 1740 ---------------------------------------- . descr, . self.tcx.crate_name(def_id.krate) . )) . .emit() . }, . ); . } . 85,041 ( 0.00%) let hir_id = match def_id.as_local() { 22,162 ( 0.00%) Some(def_id) => self.tcx.hir().local_def_id_to_hir_id(def_id), . None => return false, . }; . . let vis = self.tcx.visibility(def_id); 31,476 ( 0.00%) if !vis.is_at_least(self.required_visibility, self.tcx) { . let vis_descr = match vis { . ty::Visibility::Public => "public", . ty::Visibility::Invisible => "private", . ty::Visibility::Restricted(vis_def_id) => { . if vis_def_id == self.tcx.parent_module(hir_id).to_def_id() { . "private" . } else if vis_def_id.is_top_level_module() { . "crate-private" -- line 1762 ---------------------------------------- -- line 1792 ---------------------------------------- . false . } . . /// An item is 'leaked' from a private dependency if all . /// of the following are true: . /// 1. It's contained within a public type . /// 2. It comes from a private crate . fn leaks_private_dep(&self, item_id: DefId) -> bool { 122,151 ( 0.00%) let ret = self.required_visibility.is_public() && self.tcx.is_private_dep(item_id.krate); . . tracing::debug!("leaks_private_dep(item_id={:?})={}", item_id, ret); . ret . } . } . . impl<'tcx> DefIdVisitor<'tcx> for SearchInterfaceForPrivateItemsVisitor<'tcx> { . fn tcx(&self) -> TyCtxt<'tcx> { 72,985 ( 0.00%) self.tcx . } 651,472 ( 0.00%) fn visit_def_id( . &mut self, . def_id: DefId, . kind: &str, . descr: &dyn fmt::Display, . ) -> ControlFlow { . if self.check_def_id(def_id, kind, descr) { . ControlFlow::BREAK . } else { . ControlFlow::CONTINUE . } 366,453 ( 0.00%) } . } . . struct PrivateItemsInPublicInterfacesVisitor<'tcx> { . tcx: TyCtxt<'tcx>, . has_pub_restricted: bool, . old_error_set_ancestry: LocalDefIdSet, . } . . impl<'tcx> PrivateItemsInPublicInterfacesVisitor<'tcx> { . fn check( . &self, . def_id: LocalDefId, . required_visibility: ty::Visibility, . ) -> SearchInterfaceForPrivateItemsVisitor<'tcx> { 79,150 ( 0.00%) SearchInterfaceForPrivateItemsVisitor { 8,155 ( 0.00%) tcx: self.tcx, . item_def_id: def_id, . required_visibility, 11,915 ( 0.00%) has_pub_restricted: self.has_pub_restricted, . has_old_errors: self.old_error_set_ancestry.contains(&def_id), . in_assoc_ty: false, . } . } . 85,878 ( 0.00%) fn check_assoc_item( . &self, . def_id: LocalDefId, . assoc_item_kind: AssocItemKind, . defaultness: hir::Defaultness, . vis: ty::Visibility, . ) { . let mut check = self.check(def_id, vis); . 13,212 ( 0.00%) let (check_ty, is_assoc_ty) = match assoc_item_kind { . AssocItemKind::Const | AssocItemKind::Fn { .. } => (true, false), 1,400 ( 0.00%) AssocItemKind::Type => (defaultness.has_value(), true), . }; 13,212 ( 0.00%) check.in_assoc_ty = is_assoc_ty; 26,424 ( 0.00%) check.generics().predicates(); 1,403 ( 0.00%) if check_ty { 6,603 ( 0.00%) check.ty(); . } 52,848 ( 0.00%) } . } . . impl<'tcx> Visitor<'tcx> for PrivateItemsInPublicInterfacesVisitor<'tcx> { . type NestedFilter = nested_filter::OnlyBodies; . . fn nested_visit_map(&mut self) -> Self::Map { 5,935 ( 0.00%) self.tcx.hir() . } . 68,256 ( 0.00%) fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { 7,584 ( 0.00%) let tcx = self.tcx; 7,584 ( 0.00%) let item_visibility = tcx.visibility(item.def_id); . 37,920 ( 0.00%) match item.kind { . // Crates are always public. . hir::ItemKind::ExternCrate(..) => {} . // All nested items are checked by `visit_item`. . hir::ItemKind::Mod(..) => {} . // Checked in resolve. . hir::ItemKind::Use(..) => {} . // No subitems. . hir::ItemKind::Macro(..) | hir::ItemKind::GlobalAsm(..) => {} . // Subitems of these items have inherited publicity. . hir::ItemKind::Const(..) . | hir::ItemKind::Static(..) . | hir::ItemKind::Fn(..) . | hir::ItemKind::TyAlias(..) => { 5,400 ( 0.00%) self.check(item.def_id, item_visibility).generics().predicates().ty(); . } . hir::ItemKind::OpaqueTy(..) => { . // `ty()` for opaque types is the underlying type, . // it's not a part of interface, so we skip it. . self.check(item.def_id, item_visibility).generics().bounds(); . } 16 ( 0.00%) hir::ItemKind::Trait(.., trait_item_refs) => { 16 ( 0.00%) self.check(item.def_id, item_visibility).generics().predicates(); . . for trait_item_ref in trait_item_refs { 66 ( 0.00%) self.check_assoc_item( 11 ( 0.00%) trait_item_ref.id.def_id, . trait_item_ref.kind, . trait_item_ref.defaultness, . item_visibility, . ); . 42 ( 0.00%) if let AssocItemKind::Type = trait_item_ref.kind { 18 ( 0.00%) self.check(trait_item_ref.id.def_id, item_visibility).bounds(); . } . } . } . hir::ItemKind::TraitAlias(..) => { . self.check(item.def_id, item_visibility).generics().predicates(); . } . hir::ItemKind::Enum(ref def, _) => { 1,636 ( 0.00%) self.check(item.def_id, item_visibility).generics().predicates(); . 409 ( 0.00%) for variant in def.variants { 1,116 ( 0.00%) for field in variant.data.fields() { 2,424 ( 0.00%) self.check(self.tcx.hir().local_def_id(field.hir_id), item_visibility).ty(); . } . } . } . // Subitems of foreign modules have their own publicity. . hir::ItemKind::ForeignMod { items, .. } => { . for foreign_item in items { . let vis = tcx.visibility(foreign_item.id.def_id); . self.check(foreign_item.id.def_id, vis).generics().predicates().ty(); . } . } . // Subitems of structs and unions have their own publicity. . hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => { 3,436 ( 0.00%) self.check(item.def_id, item_visibility).generics().predicates(); . 2,577 ( 0.00%) for field in struct_def.fields() { 8,064 ( 0.00%) let def_id = tcx.hir().local_def_id(field.hir_id); . let field_visibility = tcx.visibility(def_id); 4,032 ( 0.00%) self.check(def_id, min(item_visibility, field_visibility, tcx)).ty(); . } . } . // An inherent impl is public when its type is public . // Subitems of inherent impls have their own publicity. . // A trait impl is public when both its type and its trait are public . // Subitems of trait impls have inherited publicity. . hir::ItemKind::Impl(ref impl_) => { 14,872 ( 0.00%) let impl_vis = ty::Visibility::of_impl(item.def_id, tcx, &Default::default()); . // check that private components do not appear in the generics or predicates of inherent impls . // this check is intentionally NOT performed for impls of traits, per #90586 7,436 ( 0.00%) if impl_.of_trait.is_none() { 195 ( 0.00%) self.check(item.def_id, impl_vis).generics().predicates(); . } 3,718 ( 0.00%) for impl_item_ref in impl_.items { 6,183 ( 0.00%) let impl_item_vis = if impl_.of_trait.is_none() { 181 ( 0.00%) min(tcx.visibility(impl_item_ref.id.def_id), impl_vis, tcx) . } else { . impl_vis . }; 39,389 ( 0.00%) self.check_assoc_item( 6,595 ( 0.00%) impl_item_ref.id.def_id, . impl_item_ref.kind, . impl_item_ref.defaultness, . impl_item_vis, . ); . } . } . } 60,672 ( 0.00%) } . } . . pub fn provide(providers: &mut Providers) { 8 ( 0.00%) *providers = Providers { . visibility, . privacy_access_levels, . check_private_in_public, . check_mod_privacy, . ..*providers . }; 1 ( 0.00%) } . 164,619 ( 0.00%) fn visibility(tcx: TyCtxt<'_>, def_id: DefId) -> ty::Visibility { 18,291 ( 0.00%) let def_id = def_id.expect_local(); . match tcx.resolutions(()).visibilities.get(&def_id) { 23,222 ( 0.00%) Some(vis) => *vis, . None => { . let hir_id = tcx.hir().local_def_id_to_hir_id(def_id); 67,627 ( 0.00%) match tcx.hir().get(hir_id) { . // Unique types created for closures participate in type privacy checking. . // They have visibilities inherited from the module they are defined in. . Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => { 174 ( 0.00%) ty::Visibility::Restricted(tcx.parent_module(hir_id).to_def_id()) . } . // - AST lowering may clone `use` items and the clones don't . // get their entries in the resolver's visibility table. . // - AST lowering also creates opaque type items with inherited visibilies. . // Visibility on them should have no effect, but to avoid the visibility . // query failing on some items, we provide it for opaque types as well. . Node::Item(hir::Item { 237 ( 0.00%) vis, . kind: hir::ItemKind::Use(..) | hir::ItemKind::OpaqueTy(..), . .. 1,422 ( 0.00%) }) => ty::Visibility::from_hir(vis, hir_id, tcx), . // Visibilities of trait impl items are inherited from their traits . // and are not filled in resolve. . Node::ImplItem(impl_item) => { 83,382 ( 0.00%) match tcx.hir().get_by_def_id(tcx.hir().get_parent_item(hir_id)) { . Node::Item(hir::Item { . kind: hir::ItemKind::Impl(hir::Impl { of_trait: Some(tr), .. }), . .. 6,414 ( 0.00%) }) => tr.path.res.opt_def_id().map_or_else( . || { . tcx.sess.delay_span_bug(tr.path.span, "trait without a def-id"); . ty::Visibility::Public . }, . |def_id| tcx.visibility(def_id), . ), . _ => span_bug!(impl_item.span, "the parent is not a trait impl"), . } -- line 2021 ---------------------------------------- -- line 2023 ---------------------------------------- . _ => span_bug!( . tcx.def_span(def_id), . "visibility table unexpectedly missing a def-id: {:?}", . def_id, . ), . } . } . } 146,328 ( 0.00%) } . 232 ( 0.00%) fn check_mod_privacy(tcx: TyCtxt<'_>, module_def_id: LocalDefId) { . // Check privacy of names not checked in previous compilation stages. . let mut visitor = 116 ( 0.00%) NamePrivacyVisitor { tcx, maybe_typeck_results: None, current_item: module_def_id }; 261 ( 0.00%) let (module, span, hir_id) = tcx.hir().get_module(module_def_id); . . intravisit::walk_mod(&mut visitor, module, hir_id); . . // Check privacy of explicitly written types and traits as well as . // inferred types of expressions and patterns. . let mut visitor = 174 ( 0.00%) TypePrivacyVisitor { tcx, maybe_typeck_results: None, current_item: module_def_id, span }; . intravisit::walk_mod(&mut visitor, module, hir_id); 232 ( 0.00%) } . 7 ( 0.00%) fn privacy_access_levels(tcx: TyCtxt<'_>, (): ()) -> &AccessLevels { . // Build up a set of all exported items in the AST. This is a set of all . // items which are reachable from external crates based on visibility. 9 ( 0.00%) let mut visitor = EmbargoVisitor { . tcx, . access_levels: tcx.resolutions(()).access_levels.clone(), . macro_reachable: Default::default(), . prev_level: Some(AccessLevel::Public), . changed: false, . }; . . loop { . tcx.hir().walk_toplevel_module(&mut visitor); 4 ( 0.00%) if visitor.changed { 3 ( 0.00%) visitor.changed = false; . } else { . break; . } . } . 1 ( 0.00%) tcx.arena.alloc(visitor.access_levels) 9 ( 0.00%) } . 8 ( 0.00%) fn check_private_in_public(tcx: TyCtxt<'_>, (): ()) { . let access_levels = tcx.privacy_access_levels(()); . 9 ( 0.00%) let mut visitor = ObsoleteVisiblePrivateTypesVisitor { . tcx, . access_levels, . in_variant: false, . old_error_set: Default::default(), . }; . tcx.hir().walk_toplevel_module(&mut visitor); . . let has_pub_restricted = { 5 ( 0.00%) let mut pub_restricted_visitor = PubRestrictedVisitor { tcx, has_pub_restricted: false }; . tcx.hir().walk_toplevel_module(&mut pub_restricted_visitor); 1 ( 0.00%) pub_restricted_visitor.has_pub_restricted . }; . . let mut old_error_set_ancestry = HirIdSet::default(); 9 ( 0.00%) for mut id in visitor.old_error_set.iter().copied() { . loop { . if !old_error_set_ancestry.insert(id) { . break; . } . let parent = tcx.hir().get_parent_node(id); . if parent == id { . break; . } . id = parent; . } . } . . // Check for private types and traits in public interfaces. 8 ( 0.00%) let mut visitor = PrivateItemsInPublicInterfacesVisitor { . tcx, . has_pub_restricted, . // Only definition IDs are ever searched in `old_error_set_ancestry`, . // so we can filter away all non-definition IDs at this point. . old_error_set_ancestry: old_error_set_ancestry . .into_iter() . .filter_map(|hir_id| tcx.hir().opt_local_def_id(hir_id)) . .collect(), . }; 6 ( 0.00%) tcx.hir().visit_all_item_likes(&mut DeepVisitor::new(&mut visitor)); 8 ( 0.00%) } 4,997,016 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/tokenstream.rs -------------------------------------------------------------------------------- Ir -- line 32 ---------------------------------------- . /// . /// If the syntax extension is an MBE macro, it will attempt to match its . /// LHS token tree against the provided token tree, and if it finds a . /// match, will transcribe the RHS token tree, splicing in any captured . /// `macro_parser::matched_nonterminals` into the `SubstNt`s it finds. . /// . /// The RHS of an MBE macro is the only place `SubstNt`s are substituted. . /// Nothing special happens to misnamed or misplaced `SubstNt`s. 19,679,732 ( 0.06%) #[derive(Debug, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)] . pub enum TokenTree { . /// A single token. 4,780,298 ( 0.01%) Token(Token), . /// A delimited sequence of token trees. 502,304 ( 0.00%) Delimited(DelimSpan, DelimToken, TokenStream), . } . . #[derive(Copy, Clone)] . pub enum CanSynthesizeMissingTokens { . Yes, . No, . } . -- line 53 ---------------------------------------- -- line 71 ---------------------------------------- . delim == delim2 && tts.eq_unspanned(&tts2) . } . _ => false, . } . } . . /// Retrieves the `TokenTree`'s span. . pub fn span(&self) -> Span { 23,718 ( 0.00%) match self { 16,315 ( 0.00%) TokenTree::Token(token) => token.span, 15,484 ( 0.00%) TokenTree::Delimited(sp, ..) => sp.entire(), . } 7,989 ( 0.00%) } . . /// Modify the `TokenTree`'s span in-place. . pub fn set_span(&mut self, span: Span) { 23,718 ( 0.00%) match self { 7,989 ( 0.00%) TokenTree::Token(token) => token.span = span, 7,740 ( 0.00%) TokenTree::Delimited(dspan, ..) => *dspan = DelimSpan::from_single(span), . } 11,859 ( 0.00%) } . 724,899 ( 0.00%) pub fn token(kind: TokenKind, span: Span) -> TokenTree { 3,672,944 ( 0.01%) TokenTree::Token(Token::new(kind, span)) 724,899 ( 0.00%) } . . /// Returns the opening delimiter as a token tree. 98,721 ( 0.00%) pub fn open_tt(span: DelimSpan, delim: DelimToken) -> TokenTree { 296,163 ( 0.00%) TokenTree::token(token::OpenDelim(delim), span.open) 98,721 ( 0.00%) } . . /// Returns the closing delimiter as a token tree. 94,616 ( 0.00%) pub fn close_tt(span: DelimSpan, delim: DelimToken) -> TokenTree { 283,848 ( 0.00%) TokenTree::token(token::CloseDelim(delim), span.close) 94,616 ( 0.00%) } . 86,823 ( 0.00%) pub fn uninterpolate(self) -> TokenTree { 57,882 ( 0.00%) match self { 260,469 ( 0.00%) TokenTree::Token(token) => TokenTree::Token(token.uninterpolate().into_owned()), . tt => tt, . } 115,764 ( 0.00%) } . } . . impl HashStable for TokenStream . where . CTX: crate::HashStableContext, . { 147,123 ( 0.00%) fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) { 800,904 ( 0.00%) for sub_tt in self.trees() { . sub_tt.hash_stable(hcx, hasher); . } 130,776 ( 0.00%) } . } . . pub trait CreateTokenStream: sync::Send + sync::Sync { . fn create_token_stream(&self) -> AttrAnnotatedTokenStream; . } . . impl CreateTokenStream for AttrAnnotatedTokenStream { . fn create_token_stream(&self) -> AttrAnnotatedTokenStream { 14 ( 0.00%) self.clone() 14 ( 0.00%) } . } . . /// A lazy version of [`TokenStream`], which defers creation . /// of an actual `TokenStream` until it is needed. . /// `Box` is here only to reduce the structure size. . #[derive(Clone)] . pub struct LazyTokenStream(Lrc>); . . impl LazyTokenStream { 412 ( 0.00%) pub fn new(inner: impl CreateTokenStream + 'static) -> LazyTokenStream { . LazyTokenStream(Lrc::new(Box::new(inner))) 412 ( 0.00%) } . . pub fn create_token_stream(&self) -> AttrAnnotatedTokenStream { 8,135 ( 0.00%) self.0.create_token_stream() . } . } . . impl fmt::Debug for LazyTokenStream { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . write!(f, "LazyTokenStream({:?})", self.create_token_stream()) . } . } -- line 156 ---------------------------------------- -- line 177 ---------------------------------------- . /// A `AttrAnnotatedTokenStream` is similar to a `TokenStream`, but with extra . /// information about the tokens for attribute targets. This is used . /// during expansion to perform early cfg-expansion, and to process attributes . /// during proc-macro invocations. . #[derive(Clone, Debug, Default, Encodable, Decodable)] . pub struct AttrAnnotatedTokenStream(pub Lrc>); . . /// Like `TokenTree`, but for `AttrAnnotatedTokenStream` 3,243 ( 0.00%) #[derive(Clone, Debug, Encodable, Decodable)] . pub enum AttrAnnotatedTokenTree { 1,620 ( 0.00%) Token(Token), 96 ( 0.00%) Delimited(DelimSpan, DelimToken, AttrAnnotatedTokenStream), . /// Stores the attributes for an attribute target, . /// along with the tokens for that attribute target. . /// See `AttributesData` for more information . Attributes(AttributesData), . } . . impl AttrAnnotatedTokenStream { 749,036 ( 0.00%) pub fn new(tokens: Vec<(AttrAnnotatedTokenTree, Spacing)>) -> AttrAnnotatedTokenStream { . AttrAnnotatedTokenStream(Lrc::new(tokens)) 749,036 ( 0.00%) } . . /// Converts this `AttrAnnotatedTokenStream` to a plain `TokenStream . /// During conversion, `AttrAnnotatedTokenTree::Attributes` get 'flattened' . /// back to a `TokenStream` of the form `outer_attr attr_target`. . /// If there are inner attributes, they are inserted into the proper . /// place in the attribute target tokens. 715 ( 0.00%) pub fn to_tokenstream(&self) -> TokenStream { 4,868 ( 0.00%) let trees: Vec<_> = self . .0 . .iter() 94,747 ( 0.00%) .flat_map(|tree| match &tree.0 { 47,298 ( 0.00%) AttrAnnotatedTokenTree::Token(inner) => { 118,245 ( 0.00%) smallvec![(TokenTree::Token(inner.clone()), tree.1)].into_iter() . } 83,060 ( 0.00%) AttrAnnotatedTokenTree::Delimited(span, delim, stream) => smallvec![( 12,459 ( 0.00%) TokenTree::Delimited(*span, *delim, stream.to_tokenstream()), 4,153 ( 0.00%) tree.1, . )] . .into_iter(), . AttrAnnotatedTokenTree::Attributes(data) => { . let mut outer_attrs = Vec::new(); . let mut inner_attrs = Vec::new(); . for attr in &data.attrs { 2,210 ( 0.00%) match attr.style { . crate::AttrStyle::Outer => { . outer_attrs.push(attr); . } . crate::AttrStyle::Inner => { . inner_attrs.push(attr); . } . } . } . 1,214 ( 0.00%) let mut target_tokens: Vec<_> = data . .tokens . .create_token_stream() . .to_tokenstream() . .0 . .iter() . .cloned() . .collect(); 607 ( 0.00%) if !inner_attrs.is_empty() { . let mut found = false; . // Check the last two trees (to account for a trailing semi) . for (tree, _) in target_tokens.iter_mut().rev().take(2) { . if let TokenTree::Delimited(span, delim, delim_tokens) = tree { . // Inner attributes are only supported on extern blocks, functions, impls, . // and modules. All of these have their inner attributes placed at . // the beginning of the rightmost outermost braced group: . // e.g. fn foo() { #![my_attr} } -- line 248 ---------------------------------------- -- line 269 ---------------------------------------- . . assert!( . found, . "Failed to find trailing delimited group in: {:?}", . target_tokens . ); . } . let mut flat: SmallVec<[_; 1]> = SmallVec::new(); 10,101 ( 0.00%) for attr in outer_attrs { . // FIXME: Make this more efficient 6,630 ( 0.00%) flat.extend(attr.tokens().to_tokenstream().0.clone().iter().cloned()); . } 4,856 ( 0.00%) flat.extend(target_tokens); 6,070 ( 0.00%) flat.into_iter() 607 ( 0.00%) } . }) . .collect(); . TokenStream::new(trees) 1,430 ( 0.00%) } . } . . /// Stores the tokens for an attribute target, along . /// with its attributes. . /// . /// This is constructed during parsing when we need to capture . /// tokens. . /// -- line 295 ---------------------------------------- -- line 298 ---------------------------------------- . /// and a `tokens` field storing the (unparesd) tokens `struct Foo {}` . #[derive(Clone, Debug, Encodable, Decodable)] . pub struct AttributesData { . /// Attributes, both outer and inner. . /// These are stored in the original order that they were parsed in. . pub attrs: AttrVec, . /// The underlying tokens for the attribute target that `attrs` . /// are applied to 28 ( 0.00%) pub tokens: LazyTokenStream, . } . . /// A `TokenStream` is an abstract sequence of tokens, organized into [`TokenTree`]s. . /// . /// The goal is for procedural macros to work with `TokenStream`s and `TokenTree`s . /// instead of a representation of the abstract syntax tree. . /// Today's `TokenTree`s can still contain AST via `token::Interpolated` for . /// backwards compatibility. -- line 314 ---------------------------------------- -- line 316 ---------------------------------------- . pub struct TokenStream(pub(crate) Lrc>); . . pub type TreeAndSpacing = (TokenTree, Spacing); . . // `TokenStream` is used a lot. Make sure it doesn't unintentionally get bigger. . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . rustc_data_structures::static_assert_size!(TokenStream, 8); . 2,054,597 ( 0.01%) #[derive(Clone, Copy, Debug, PartialEq, Encodable, Decodable)] . pub enum Spacing { . Alone, . Joint, . } . . impl TokenStream { . /// Given a `TokenStream` with a `Stream` of only two arguments, return a new `TokenStream` . /// separating the two arguments with a comma for diagnostic suggestions. -- line 332 ---------------------------------------- -- line 365 ---------------------------------------- . return Some((TokenStream::new(new_stream), sp)); . } . None . } . } . . impl From<(AttrAnnotatedTokenTree, Spacing)> for AttrAnnotatedTokenStream { . fn from((tree, spacing): (AttrAnnotatedTokenTree, Spacing)) -> AttrAnnotatedTokenStream { 2,610 ( 0.00%) AttrAnnotatedTokenStream::new(vec![(tree, spacing)]) . } . } . . impl From for TokenStream { . fn from(tree: TokenTree) -> TokenStream { 2,207,605 ( 0.01%) TokenStream::new(vec![(tree, Spacing::Alone)]) . } . } . . impl From for TreeAndSpacing { . fn from(tree: TokenTree) -> TreeAndSpacing { 338,425 ( 0.00%) (tree, Spacing::Alone) . } . } . . impl iter::FromIterator for TokenStream { 5,288 ( 0.00%) fn from_iter>(iter: I) -> Self { 5,572 ( 0.00%) TokenStream::new(iter.into_iter().map(Into::into).collect::>()) 7,932 ( 0.00%) } . } . . impl Eq for TokenStream {} . . impl PartialEq for TokenStream { . fn eq(&self, other: &TokenStream) -> bool { . self.trees().eq(other.trees()) . } -- line 400 ---------------------------------------- -- line 401 ---------------------------------------- . } . . impl TokenStream { . pub fn new(streams: Vec) -> TokenStream { . TokenStream(Lrc::new(streams)) . } . . pub fn is_empty(&self) -> bool { 119,298 ( 0.00%) self.0.is_empty() 119,298 ( 0.00%) } . . pub fn len(&self) -> usize { 2,224,478 ( 0.01%) self.0.len() 3,938 ( 0.00%) } . 1,026,584 ( 0.00%) pub fn from_streams(mut streams: SmallVec<[TokenStream; 2]>) -> TokenStream { 513,292 ( 0.00%) match streams.len() { . 0 => TokenStream::default(), . 1 => streams.pop().unwrap(), . _ => { . // We are going to extend the first stream in `streams` with . // the elements from the subsequent streams. This requires . // using `make_mut()` on the first stream, and in practice this . // doesn't cause cloning 99.9% of the time. . // -- line 425 ---------------------------------------- -- line 430 ---------------------------------------- . . // Determine how much the first stream will be extended. . // Needed to avoid quadratic blow up from on-the-fly . // reallocations (#57735). . let num_appends = streams.iter().skip(1).map(|ts| ts.len()).sum(); . . // Get the first stream. If it's `None`, create an empty . // stream. 253,534 ( 0.00%) let mut iter = streams.drain(..); 253,534 ( 0.00%) let mut first_stream_lrc = iter.next().unwrap().0; . . // Append the elements to the first stream, after reserving . // space for them. 126,767 ( 0.00%) let first_vec_mut = Lrc::make_mut(&mut first_stream_lrc); . first_vec_mut.reserve(num_appends); 2,553,033 ( 0.01%) for stream in iter { . first_vec_mut.extend(stream.0.iter().cloned()); . } . . // Create the final `TokenStream`. 253,534 ( 0.00%) TokenStream(first_stream_lrc) . } . } 1,154,907 ( 0.00%) } . . pub fn trees(&self) -> Cursor { 154,776 ( 0.00%) self.clone().into_trees() 309,552 ( 0.00%) } . 112,370 ( 0.00%) pub fn into_trees(self) -> Cursor { . Cursor::new(self) 224,740 ( 0.00%) } . . /// Compares two `TokenStream`s, checking equality without regarding span information. . pub fn eq_unspanned(&self, other: &TokenStream) -> bool { . let mut t1 = self.trees(); . let mut t2 = other.trees(); . for (t1, t2) in iter::zip(&mut t1, &mut t2) { . if !t1.eq_unspanned(&t2) { . return false; . } . } . t1.next().is_none() && t2.next().is_none() . } . . pub fn map_enumerated TokenTree>(self, mut f: F) -> TokenStream { 3,835 ( 0.00%) TokenStream(Lrc::new( . self.0 . .iter() . .enumerate() 71,154 ( 0.00%) .map(|(i, (tree, is_joint))| (f(i, tree), *is_joint)) . .collect(), . )) . } . } . . // 99.5%+ of the time we have 1 or 2 elements in this vector. . #[derive(Clone)] . pub struct TokenStreamBuilder(SmallVec<[TokenStream; 2]>); . . impl TokenStreamBuilder { 128,323 ( 0.00%) pub fn new() -> TokenStreamBuilder { 128,323 ( 0.00%) TokenStreamBuilder(SmallVec::new()) 128,323 ( 0.00%) } . 7,518,384 ( 0.02%) pub fn push>(&mut self, stream: T) { 835,376 ( 0.00%) let mut stream = stream.into(); . . // If `self` is not empty and the last tree within the last stream is a . // token tree marked with `Joint`... 2,506,128 ( 0.01%) if let Some(TokenStream(ref mut last_stream_lrc)) = self.0.last_mut() { 4,405,111 ( 0.01%) if let Some((TokenTree::Token(last_token), Spacing::Joint)) = last_stream_lrc.last() { . // ...and `stream` is not empty and the first tree within it is . // a token tree... . let TokenStream(ref mut stream_lrc) = stream; 767,032 ( 0.00%) if let Some((TokenTree::Token(token), spacing)) = stream_lrc.first() { . // ...and the two tokens can be glued together... 767,032 ( 0.00%) if let Some(glued_tok) = last_token.glue(&token) { . // ...then do so, by overwriting the last token . // tree in `self` and removing the first token tree . // from `stream`. This requires using `make_mut()` . // on the last stream in `self` and on `stream`, . // and in practice this doesn't cause cloning 99.9% . // of the time. . . // Overwrite the last token tree with the merged . // token. 109,576 ( 0.00%) let last_vec_mut = Lrc::make_mut(last_stream_lrc); 2,520,248 ( 0.01%) *last_vec_mut.last_mut().unwrap() = (TokenTree::Token(glued_tok), *spacing); . . // Remove the first token tree from `stream`. (This . // is almost always the only tree in `stream`.) 109,576 ( 0.00%) let stream_vec_mut = Lrc::make_mut(stream_lrc); 657,456 ( 0.00%) stream_vec_mut.remove(0); . . // Don't push `stream` if it's empty -- that could . // block subsequent token gluing, by getting . // between two token trees that should be glued . // together. 328,728 ( 0.00%) if !stream.is_empty() { . self.0.push(stream); . } . return; . } . } . } . } . self.0.push(stream); 6,683,008 ( 0.02%) } . 128,323 ( 0.00%) pub fn build(self) -> TokenStream { 769,938 ( 0.00%) TokenStream::from_streams(self.0) 256,646 ( 0.00%) } . } . . /// By-reference iterator over a [`TokenStream`]. . #[derive(Clone)] . pub struct CursorRef<'t> { . stream: &'t TokenStream, . index: usize, . } -- line 550 ---------------------------------------- -- line 572 ---------------------------------------- . pub struct Cursor { . pub stream: TokenStream, . index: usize, . } . . impl Iterator for Cursor { . type Item = TokenTree; . 1,189,905 ( 0.00%) fn next(&mut self) -> Option { 1,914,925 ( 0.01%) self.next_with_spacing().map(|(tree, _)| tree) 1,586,540 ( 0.00%) } . } . . impl Cursor { . fn new(stream: TokenStream) -> Self { . Cursor { stream, index: 0 } . } . 6,112,450 ( 0.02%) pub fn next_with_spacing(&mut self) -> Option { 4,857,375 ( 0.01%) if self.index < self.stream.len() { 2,451,950 ( 0.01%) self.index += 1; 6,766,655 ( 0.02%) Some(self.stream.0[self.index - 1].clone()) . } else { 511,650 ( 0.00%) None . } 7,334,940 ( 0.02%) } . . pub fn index(&self) -> usize { . self.index . } . . pub fn append(&mut self, new_stream: TokenStream) { . if new_stream.is_empty() { . return; . } . let index = self.index; . let stream = mem::take(&mut self.stream); . *self = TokenStream::from_streams(smallvec![stream, new_stream]).into_trees(); . self.index = index; . } . 973,313 ( 0.00%) pub fn look_ahead(&self, n: usize) -> Option<&TokenTree> { 1,946,626 ( 0.01%) self.stream.0[self.index..].get(n).map(|(tree, _)| tree) 1,946,626 ( 0.01%) } . } . 906,563 ( 0.00%) #[derive(Debug, Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)] . pub struct DelimSpan { . pub open: Span, . pub close: Span, . } . . impl DelimSpan { 70,973 ( 0.00%) pub fn from_single(sp: Span) -> Self { . DelimSpan { open: sp, close: sp } 141,946 ( 0.00%) } . 16,506 ( 0.00%) pub fn from_pair(open: Span, close: Span) -> Self { . DelimSpan { open, close } 8,253 ( 0.00%) } . . pub fn dummy() -> Self { . Self::from_single(DUMMY_SP) 54,999 ( 0.00%) } . 281,624 ( 0.00%) pub fn entire(self) -> Span { . self.open.with_hi(self.close.hi()) 211,218 ( 0.00%) } . } 4,833,743 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/std/src/sys/unix/alloc.rs -------------------------------------------------------------------------------- Ir -- line 5 ---------------------------------------- . #[stable(feature = "alloc_system_type", since = "1.28.0")] . unsafe impl GlobalAlloc for System { . #[inline] . unsafe fn alloc(&self, layout: Layout) -> *mut u8 { . // jemalloc provides alignment less than MIN_ALIGN for small allocations. . // So only rely on MIN_ALIGN if size >= align. . // Also see and . // . 56,483,676 ( 0.16%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 42,362,757 ( 0.12%) libc::malloc(layout.size()) as *mut u8 . } else { . #[cfg(target_os = "macos")] . { . if layout.align() > (1 << 31) { . return ptr::null_mut(); . } . } . aligned_malloc(&layout) . } . } . . #[inline] . unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { . // See the comment above in `alloc` for why this check looks the way it does. 1,199,840 ( 0.00%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 1,799,760 ( 0.01%) libc::calloc(layout.size(), 1) as *mut u8 . } else { . let ptr = self.alloc(layout); . if !ptr.is_null() { . ptr::write_bytes(ptr, 0, layout.size()); . } . ptr . } . } . . #[inline] . unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) { 14,420,867 ( 0.04%) libc::free(ptr as *mut libc::c_void) . } . . #[inline] . unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { 5,202,428 ( 0.01%) if layout.align() <= MIN_ALIGN && layout.align() <= new_size { 10,404,856 ( 0.03%) libc::realloc(ptr as *mut libc::c_void, new_size) as *mut u8 . } else { . realloc_fallback(self, ptr, layout, new_size) . } . } . } . . cfg_if::cfg_if! { . if #[cfg(any( -- line 56 ---------------------------------------- -------------------------------------------------------------------------------- -- 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, . ) { 60,707 ( 0.00%) if let Some((file, file_idx)) = new_file_and_idx { 36,092 ( 0.00%) self.file = file; 60,142 ( 0.00%) self.file_index = file_idx; . } . 29,403 ( 0.00%) let line_index = self.file.lookup_line(pos).unwrap(); . let line_bounds = self.file.line_bounds(line_index); 122,962 ( 0.00%) self.line_number = line_index + 1; 186,837 ( 0.00%) self.line = line_bounds; . self.touch(time_stamp); . } . . #[inline] . fn touch(&mut self, time_stamp: usize) { 2,466,133 ( 0.01%) self.time_stamp = time_stamp; . } . } . . #[derive(Clone)] . pub struct CachingSourceMapView<'sm> { . source_map: &'sm SourceMap, . line_cache: [CacheEntry; 3], . time_stamp: usize, . } . . impl<'sm> CachingSourceMapView<'sm> { 59,780 ( 0.00%) pub fn new(source_map: &'sm SourceMap) -> CachingSourceMapView<'sm> { . let files = source_map.files(); 29,890 ( 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, . }; . 149,450 ( 0.00%) CachingSourceMapView { . source_map, 209,230 ( 0.00%) line_cache: [entry.clone(), entry.clone(), entry], . time_stamp: 0, . } 119,560 ( 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)) . } . 8,832,600 ( 0.03%) pub fn span_data_to_lines_and_cols( . &mut self, . span_data: &SpanData, . ) -> Option<(Lrc, usize, BytePos, usize, BytePos)> { 5,047,200 ( 0.01%) self.time_stamp += 1; . . // Check if lo and hi are in the cached lines. 1,261,800 ( 0.00%) let lo_cache_idx = self.cache_entry_index(span_data.lo); 1,261,800 ( 0.00%) let hi_cache_idx = self.cache_entry_index(span_data.hi); . 2,410,152 ( 0.01%) if lo_cache_idx != -1 && hi_cache_idx != -1 { . // Cache hit for span lo and hi. Check if they belong to the same file. . let result = { 2,408,666 ( 0.01%) let lo = &self.line_cache[lo_cache_idx as usize]; . let hi = &self.line_cache[hi_cache_idx as usize]; . 7,225,998 ( 0.02%) if lo.file_index != hi.file_index { . return None; . } . . ( 2,408,666 ( 0.01%) lo.file.clone(), . lo.line_number, . span_data.lo - lo.line.start, 1,204,333 ( 0.00%) hi.line_number, . span_data.hi - hi.line.start, . ) . }; . 1,204,333 ( 0.00%) self.line_cache[lo_cache_idx as usize].touch(self.time_stamp); 1,204,333 ( 0.00%) self.line_cache[hi_cache_idx as usize].touch(self.time_stamp); . 4,817,332 ( 0.01%) return Some(result); . } . . // No cache hit or cache hit for only one of span lo and hi. 113,448 ( 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. 459,288 ( 0.00%) let new_file_and_idx = if !file_contains(&self.line_cache[oldest].file, span_data.lo) { 140,320 ( 0.00%) let new_file_and_idx = self.file_for_position(span_data.lo)?; 168,384 ( 0.00%) if !file_contains(&new_file_and_idx.0, span_data.hi) { . return None; . } . 112,256 ( 0.00%) Some(new_file_and_idx) . } else { . let file = &self.line_cache[oldest].file; 88,209 ( 0.00%) if !file_contains(&file, span_data.hi) { . return None; . } . 88,209 ( 0.00%) None . }; . . // Update the cache entries. 287,335 ( 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); . 165,312 ( 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); 1,486 ( 0.00%) let hi = &mut self.line_cache[hi_cache_idx as usize]; 2,229 ( 0.00%) hi.touch(self.time_stamp); . (oldest, hi_cache_idx as usize) . } . // Oldest cache entry is for span_data.hi line. . (_, -1) => { . let hi = &mut self.line_cache[oldest]; 1,620 ( 0.00%) hi.update(new_file_and_idx, span_data.hi, self.time_stamp); 3,240 ( 0.00%) let lo = &mut self.line_cache[lo_cache_idx as usize]; 6,480 ( 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. 114,934 ( 0.00%) assert!(span_data.lo >= lo.line.start); 57,467 ( 0.00%) assert!(span_data.lo <= lo.line.end); 114,934 ( 0.00%) assert!(span_data.hi >= hi.line.start); 57,467 ( 0.00%) assert!(span_data.hi <= hi.line.end); 287,335 ( 0.00%) assert!(lo.file.contains(span_data.lo)); 172,401 ( 0.00%) assert!(lo.file.contains(span_data.hi)); 172,401 ( 0.00%) assert_eq!(lo.file_index, hi.file_index); . 172,401 ( 0.00%) Some(( 57,467 ( 0.00%) lo.file.clone(), . lo.line_number, . span_data.lo - lo.line.start, 57,467 ( 0.00%) hi.line_number, . span_data.hi - hi.line.start, . )) 11,356,200 ( 0.03%) } . . fn cache_entry_index(&self, pos: BytePos) -> isize { . for (idx, cache_entry) in self.line_cache.iter().enumerate() { 9,459,636 ( 0.03%) 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() { 330,624 ( 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() { 34,931 ( 0.00%) if idx != avoid_idx 20,828 ( 0.00%) && self.line_cache[idx].time_stamp < self.line_cache[oldest].time_stamp . { . oldest = idx; . } . } . . oldest . } . 140,320 ( 0.00%) fn file_for_position(&self, pos: BytePos) -> Option<(Lrc, usize)> { 28,064 ( 0.00%) if !self.source_map.files().is_empty() { 56,128 ( 0.00%) let file_idx = self.source_map.lookup_source_file_idx(pos); . let file = &self.source_map.files()[file_idx]; . 224,512 ( 0.00%) if file_contains(file, pos) { . return Some((file.clone(), file_idx)); . } . } . . None 140,320 ( 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 ---------------------------------------- 13,968,131 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_borrowck/src/lib.rs -------------------------------------------------------------------------------- Ir -- line 97 ---------------------------------------- . . /// If true, the capture is behind a reference. . by_ref: bool, . } . . const DEREF_PROJECTION: &[PlaceElem<'_>; 1] = &[ProjectionElem::Deref]; . . pub fn provide(providers: &mut Providers) { 4 ( 0.00%) *providers = Providers { . mir_borrowck: |tcx, did| { 6,812 ( 0.00%) if let Some(def) = ty::WithOptConstParam::try_lookup(did, tcx) { . tcx.mir_borrowck_const_arg(def) . } else { 27,248 ( 0.00%) mir_borrowck(tcx, ty::WithOptConstParam::unknown(did)) . } . }, . mir_borrowck_const_arg: |tcx, (did, param_did)| { . mir_borrowck(tcx, ty::WithOptConstParam { did, const_param_did: Some(param_did) }) . }, . ..*providers . }; 1 ( 0.00%) } . 68,120 ( 0.00%) fn mir_borrowck<'tcx>( . tcx: TyCtxt<'tcx>, . def: ty::WithOptConstParam, . ) -> &'tcx BorrowCheckResult<'tcx> { . let (input_body, promoted) = tcx.mir_promoted(def); . debug!("run query mir_borrowck: {}", tcx.def_path_str(def.did.to_def_id())); . 88,556 ( 0.00%) let opt_closure_req = tcx.infer_ctxt().with_opaque_type_inference(def.did).enter(|infcx| { . let input_body: &Body<'_> = &input_body.borrow(); . let promoted: &IndexVec<_, _> = &promoted.borrow(); 95,368 ( 0.00%) do_mir_borrowck(&infcx, input_body, promoted, false).0 27,248 ( 0.00%) }); . debug!("mir_borrowck done"); . 6,812 ( 0.00%) tcx.arena.alloc(opt_closure_req) 54,496 ( 0.00%) } . . /// Perform the actual borrow checking. . /// . /// If `return_body_with_facts` is true, then return the body with non-erased . /// region ids on which the borrow checking was performed together with Polonius . /// facts. 149,864 ( 0.00%) #[instrument(skip(infcx, input_body, input_promoted), level = "debug")] . fn do_mir_borrowck<'a, 'tcx>( . infcx: &InferCtxt<'a, 'tcx>, . input_body: &Body<'tcx>, . input_promoted: &IndexVec>, . return_body_with_facts: bool, . ) -> (BorrowCheckResult<'tcx>, Option>>) { 68,120 ( 0.00%) let def = input_body.source.with_opt_param().as_local().unwrap(); . . debug!(?def); . 13,624 ( 0.00%) let tcx = infcx.tcx; . let param_env = tcx.param_env(def.did); 6,812 ( 0.00%) let id = tcx.hir().local_def_id_to_hir_id(def.did); . 13,624 ( 0.00%) let mut local_names = IndexVec::from_elem(None, &input_body.local_decls); . for var_debug_info in &input_body.var_debug_info { 99,324 ( 0.00%) if let VarDebugInfoContents::Place(place) = var_debug_info.value { 54,979 ( 0.00%) if let Some(local) = place.as_local() { 82,467 ( 0.00%) if let Some(prev_name) = local_names[local] { . if var_debug_info.name != prev_name { . span_bug!( . var_debug_info.source_info.span, . "local {:?} has many names (`{}` vs `{}`)", . local, . prev_name, . var_debug_info.name . ); . } . } 82,467 ( 0.00%) local_names[local] = Some(var_debug_info.name); . } . } . } . . // Gather the upvars of a closure, if any. 27,248 ( 0.00%) let tables = tcx.typeck_opt_const_arg(def); 13,624 ( 0.00%) if let Some(ErrorReported) = tables.tainted_by_errors { . infcx.set_tainted_by_errors(); . } 27,248 ( 0.00%) let upvars: Vec<_> = tables . .closure_min_captures_flattened(def.did.to_def_id()) . .map(|captured_place| { . let capture = captured_place.info.capture_kind; 1 ( 0.00%) let by_ref = match capture { . ty::UpvarCapture::ByValue => false, . ty::UpvarCapture::ByRef(..) => true, . }; . Upvar { place: captured_place.clone(), by_ref } . }) . .collect(); . . // Replace all regions with fresh inference variables. This . // requires first making our own copy of the MIR. This copy will . // be modified (in place) to contain non-lexical lifetimes. It . // will have a lifetime tied to the inference context. 13,624 ( 0.00%) let mut body_owned = input_body.clone(); . let mut promoted = input_promoted.clone(); . let free_regions = 20,436 ( 0.00%) nll::replace_regions_in_mir(infcx, param_env, &mut body_owned, &mut promoted); . let body = &body_owned; // no further changes . 6,812 ( 0.00%) let location_table_owned = LocationTable::new(body); . let location_table = &location_table_owned; . . let mut errors_buffer = Vec::new(); 20,436 ( 0.00%) let (move_data, move_errors): (MoveData<'tcx>, Vec<(Place<'tcx>, MoveError<'tcx>)>) = 47,684 ( 0.00%) match MoveData::gather_moves(&body, tcx, param_env) { 40,872 ( 0.00%) Ok(move_data) => (move_data, Vec::new()), . Err((move_data, move_errors)) => (move_data, move_errors), . }; . let promoted_errors = promoted . .iter_enumerated() 7,870 ( 0.00%) .map(|(idx, body)| (idx, MoveData::gather_moves(&body, tcx, param_env))); . 40,872 ( 0.00%) let mdpe = MoveDataParamEnv { move_data, param_env }; . 54,496 ( 0.00%) let mut flow_inits = MaybeInitializedPlaces::new(tcx, &body, &mdpe) 6,812 ( 0.00%) .into_engine(tcx, &body) . .pass_name("borrowck") . .iterate_to_fixpoint() . .into_results_cursor(&body); . 81,744 ( 0.00%) let locals_are_invalidated_at_exit = tcx.hir().body_owner_kind(id).is_fn_or_closure(); . let borrow_set = 68,120 ( 0.00%) Rc::new(BorrowSet::build(tcx, body, locals_are_invalidated_at_exit, &mdpe.move_data)); . 34,060 ( 0.00%) let use_polonius = return_body_with_facts || infcx.tcx.sess.opts.debugging_opts.polonius; . . // Compute non-lexical lifetimes. . let nll::NllOutput { 20,436 ( 0.00%) regioncx, 27,248 ( 0.00%) opaque_type_values, 13,624 ( 0.00%) polonius_input, 20,436 ( 0.00%) polonius_output, 27,248 ( 0.00%) opt_closure_req, 68,120 ( 0.00%) nll_errors, 122,616 ( 0.00%) } = nll::compute_regions( . infcx, 108,992 ( 0.00%) free_regions, . body, . &promoted, . location_table, . param_env, . &mut flow_inits, . &mdpe.move_data, . &borrow_set, . &upvars, . use_polonius, . ); . . // Dump MIR results into a file, if that is enabled. This let us . // write unit-tests, as well as helping with debugging. 20,436 ( 0.00%) nll::dump_mir_results(infcx, &body, ®ioncx, &opt_closure_req); . . // We also have a `#[rustc_regions]` annotation that causes us to dump . // information. 13,624 ( 0.00%) nll::dump_annotation( . infcx, . &body, . ®ioncx, . &opt_closure_req, . &opaque_type_values, . &mut errors_buffer, . ); . . // The various `flow_*` structures can be large. We drop `flow_inits` here . // so it doesn't overlap with the others below. This reduces peak memory . // usage significantly on some benchmarks. 108,992 ( 0.00%) drop(flow_inits); . 6,812 ( 0.00%) let regioncx = Rc::new(regioncx); . 40,872 ( 0.00%) let flow_borrows = Borrows::new(tcx, body, ®ioncx, &borrow_set) 6,812 ( 0.00%) .into_engine(tcx, body) . .pass_name("borrowck") . .iterate_to_fixpoint(); 40,872 ( 0.00%) let flow_uninits = MaybeUninitializedPlaces::new(tcx, body, &mdpe) 6,812 ( 0.00%) .into_engine(tcx, body) . .pass_name("borrowck") . .iterate_to_fixpoint(); 40,872 ( 0.00%) let flow_ever_inits = EverInitializedPlaces::new(tcx, body, &mdpe) 6,812 ( 0.00%) .into_engine(tcx, body) . .pass_name("borrowck") . .iterate_to_fixpoint(); . 13,740 ( 0.00%) let movable_generator = !matches!( 40,988 ( 0.00%) tcx.hir().get(id), . Node::Expr(&hir::Expr { . kind: hir::ExprKind::Closure(.., Some(hir::Movability::Static)), . .. . }) . ); . 5,509 ( 0.00%) for (idx, move_data_results) in promoted_errors { . let promoted_body = &promoted[idx]; . 1,574 ( 0.00%) if let Err((move_data, move_errors)) = move_data_results { . let mut promoted_mbcx = MirBorrowckCtxt { . infcx, . param_env, . body: promoted_body, . move_data: &move_data, . location_table, // no need to create a real one for the promoted, it is not used . movable_generator, . fn_self_span_reported: Default::default(), -- line 307 ---------------------------------------- -- line 325 ---------------------------------------- . }; . promoted_mbcx.report_move_errors(move_errors); . errors_buffer = promoted_mbcx.errors_buffer; . }; . } . . let dominators = body.dominators(); . 306,540 ( 0.00%) let mut mbcx = MirBorrowckCtxt { . infcx, . param_env, . body, . move_data: &mdpe.move_data, . location_table, . movable_generator, . locals_are_invalidated_at_exit, . fn_self_span_reported: Default::default(), . access_place_error_reported: Default::default(), . reservation_error_reported: Default::default(), . reservation_warnings: Default::default(), . move_error_reported: BTreeMap::new(), . uninitialized_error_reported: Default::default(), 27,248 ( 0.00%) errors_buffer, 6,812 ( 0.00%) regioncx: Rc::clone(®ioncx), . used_mut: Default::default(), . used_mut_upvars: SmallVec::new(), 6,812 ( 0.00%) borrow_set: Rc::clone(&borrow_set), 40,872 ( 0.00%) dominators, 27,248 ( 0.00%) upvars, 27,248 ( 0.00%) local_names, . region_names: RefCell::default(), . next_region_name: RefCell::new(1), . polonius_output, . }; . . // Compute and report region errors, if any. 20,436 ( 0.00%) mbcx.report_region_errors(nll_errors); . . let results = BorrowckResults { 40,872 ( 0.00%) ever_inits: flow_ever_inits, 54,496 ( 0.00%) uninits: flow_uninits, 74,932 ( 0.00%) borrows: flow_borrows, . }; . 40,872 ( 0.00%) mbcx.report_move_errors(move_errors); . 6,812 ( 0.00%) rustc_mir_dataflow::visit_results( . body, 6,812 ( 0.00%) traversal::reverse_postorder(body).map(|(bb, _)| bb), . &results, . &mut mbcx, . ); . . // Convert any reservation warnings into lints. . let reservation_warnings = mem::take(&mut mbcx.reservation_warnings); . for (_, (place, span, location, bk, borrow)) in reservation_warnings { . let mut initial_diag = mbcx.report_conflicting_borrow(location, (place, span), bk, &borrow); -- line 381 ---------------------------------------- -- line 406 ---------------------------------------- . // For each non-user used mutable variable, check if it's been assigned from . // a user-declared local. If so, then put that local into the used_mut set. . // Note that this set is expected to be small - only upvars from closures . // would have a chance of erroneously adding non-user-defined mutable vars . // to the set. . let temporary_used_locals: FxHashSet = mbcx . .used_mut . .iter() 6,812 ( 0.00%) .filter(|&local| !mbcx.body.local_decls[*local].is_user_variable()) . .cloned() . .collect(); . // For the remaining unused locals that are marked as mutable, we avoid linting any that . // were never initialized. These locals may have been removed as unreachable code; or will be . // linted as unused variables. . let unused_mut_locals = 6,812 ( 0.00%) mbcx.body.mut_vars_iter().filter(|local| !mbcx.used_mut.contains(local)).collect(); 27,248 ( 0.00%) mbcx.gather_used_muts(temporary_used_locals, unused_mut_locals); . . debug!("mbcx.used_mut: {:?}", mbcx.used_mut); 27,248 ( 0.00%) let used_mut = mbcx.used_mut; 6,812 ( 0.00%) for local in mbcx.body.mut_vars_and_args_iter().filter(|local| !used_mut.contains(local)) { 32 ( 0.00%) let local_decl = &mbcx.body.local_decls[local]; 192 ( 0.00%) let lint_root = match &mbcx.body.source_scopes[local_decl.source_info.scope].local_data { . ClearCrossCrate::Set(data) => data.lint_root, . _ => continue, . }; . . // Skip over locals that begin with an underscore or have no name 96 ( 0.00%) match mbcx.local_names[local] { . Some(name) => { . if name.as_str().starts_with('_') { . continue; . } . } . None => continue, . } . -- line 442 ---------------------------------------- -- line 455 ---------------------------------------- . String::new(), . Applicability::MachineApplicable, . ) . .emit(); . }) . } . . // Buffer any move errors that we collected and de-duplicated. 61,308 ( 0.00%) for (_, (_, diag)) in mbcx.move_error_reported { . diag.buffer(&mut mbcx.errors_buffer); . } . 6,812 ( 0.00%) if !mbcx.errors_buffer.is_empty() { . mbcx.errors_buffer.sort_by_key(|diag| diag.sort_span); . . for diag in mbcx.errors_buffer.drain(..) { . mbcx.infcx.tcx.sess.diagnostic().emit_diagnostic(&diag); . } . } . . let result = BorrowCheckResult { 27,248 ( 0.00%) concrete_opaque_types: opaque_type_values, 34,060 ( 0.00%) closure_requirements: opt_closure_req, 40,872 ( 0.00%) used_mut_upvars: mbcx.used_mut_upvars, . }; . 13,624 ( 0.00%) let body_with_facts = if return_body_with_facts { . let output_facts = mbcx.polonius_output.expect("Polonius output was not computed"); . Some(Box::new(BodyWithBorrowckFacts { . body: body_owned, . input_facts: *polonius_input.expect("Polonius input facts were not generated"), . output_facts, . location_table: location_table_owned, . })) . } else { . None . }; . . debug!("do_mir_borrowck: result = {:#?}", result); . 95,368 ( 0.00%) (result, body_with_facts) 81,744 ( 0.00%) } . . /// A `Body` with information computed by the borrow checker. This struct is . /// intended to be consumed by compiler consumers. . /// . /// We need to include the MIR body here because the region identifiers must . /// match the ones in the Polonius facts. . pub struct BodyWithBorrowckFacts<'tcx> { . /// A mir body that contains region identifiers. -- line 504 ---------------------------------------- -- line 608 ---------------------------------------- . // Check that: . // 1. assignments are always made to mutable locations (FIXME: does that still really go here?) . // 2. loans made in overlapping scopes do not conflict . // 3. assignments do not affect things loaned out as immutable . // 4. moves do not affect things loaned out in any way . impl<'cx, 'tcx> rustc_mir_dataflow::ResultsVisitor<'cx, 'tcx> for MirBorrowckCtxt<'cx, 'tcx> { . type FlowState = Flows<'cx, 'tcx>; . 2,526,714 ( 0.01%) fn visit_statement_before_primary_effect( . &mut self, . flow_state: &Flows<'cx, 'tcx>, . stmt: &'cx Statement<'tcx>, . location: Location, . ) { . debug!("MirBorrowckCtxt::process_statement({:?}, {:?}): {:?}", location, stmt, flow_state); . let span = stmt.source_info.span; . . self.check_activations(location, span, flow_state); . 1,403,730 ( 0.00%) match &stmt.kind { 185,490 ( 0.00%) StatementKind::Assign(box (lhs, ref rhs)) => { . self.consume_rvalue(location, (rhs, span), flow_state); . 370,980 ( 0.00%) self.mutate_place(location, (*lhs, span), Shallow(None), flow_state); . } 11,576 ( 0.00%) StatementKind::FakeRead(box (_, ref place)) => { . // Read for match doesn't access any memory and is used to . // assert that a place is safe and live. So we don't have to . // do any checks here. . // . // FIXME: Remove check that the place is initialized. This is . // needed for now because matches don't have never patterns yet. . // So this is the only place we prevent . // let x: !; . // match x {}; . // from compiling. 46,304 ( 0.00%) self.check_if_path_or_subpath_is_moved( . location, . InitializationRequiringAction::Use, 104,184 ( 0.00%) (place.as_ref(), span), . flow_state, . ); . } . StatementKind::SetDiscriminant { place, variant_index: _ } => { . self.mutate_place(location, (**place, span), Shallow(None), flow_state); . } . StatementKind::CopyNonOverlapping(box rustc_middle::mir::CopyNonOverlapping { . .. -- line 655 ---------------------------------------- -- line 663 ---------------------------------------- . | StatementKind::Coverage(..) . | StatementKind::AscribeUserType(..) . | StatementKind::Retag { .. } . | StatementKind::StorageLive(..) => { . // `Nop`, `AscribeUserType`, `Retag`, and `StorageLive` are irrelevant . // to borrow check. . } . StatementKind::StorageDead(local) => { 578,532 ( 0.00%) self.access_place( . location, 1,060,642 ( 0.00%) (Place::from(*local), span), . (Shallow(None), Write(WriteKind::StorageDeadOrDrop)), . LocalMutationIsAllowed::Yes, . flow_state, . ); . } . } 2,245,968 ( 0.01%) } . 986,288 ( 0.00%) fn visit_terminator_before_primary_effect( . &mut self, . flow_state: &Flows<'cx, 'tcx>, . term: &'cx Terminator<'tcx>, . loc: Location, . ) { . debug!("MirBorrowckCtxt::process_terminator({:?}, {:?}): {:?}", loc, term, flow_state); . let span = term.source_info.span; . . self.check_activations(loc, span, flow_state); . 616,430 ( 0.00%) match term.kind { 70,224 ( 0.00%) TerminatorKind::SwitchInt { ref discr, switch_ty: _, targets: _ } => { 70,224 ( 0.00%) self.consume_operand(loc, (discr, span), flow_state); . } 96,684 ( 0.00%) TerminatorKind::Drop { place, target: _, unwind: _ } => { . debug!( . "visit_terminator_drop \ . loc: {:?} term: {:?} place: {:?} span: {:?}", . loc, term, place, span . ); . 290,052 ( 0.00%) self.access_place( . loc, 435,078 ( 0.00%) (place, span), . (AccessDepth::Drop, Write(WriteKind::StorageDeadOrDrop)), . LocalMutationIsAllowed::Yes, . flow_state, . ); . } . TerminatorKind::DropAndReplace { 714 ( 0.00%) place: drop_place, 357 ( 0.00%) value: ref new_value, . target: _, . unwind: _, . } => { 5,712 ( 0.00%) self.mutate_place(loc, (drop_place, span), Deep, flow_state); . self.consume_operand(loc, (new_value, span), flow_state); . } . TerminatorKind::Call { 43,401 ( 0.00%) ref func, . ref args, . ref destination, . cleanup: _, . from_hir_call: _, . fn_span: _, . } => { 115,736 ( 0.00%) self.consume_operand(loc, (func, span), flow_state); . for arg in args { 139,872 ( 0.00%) self.consume_operand(loc, (arg, span), flow_state); . } 57,726 ( 0.00%) if let Some((dest, _ /*bb*/)) = *destination { 171,900 ( 0.00%) self.mutate_place(loc, (dest, span), Deep, flow_state); . } . } 3,324 ( 0.00%) TerminatorKind::Assert { ref cond, expected: _, ref msg, target: _, cleanup: _ } => { 554 ( 0.00%) self.consume_operand(loc, (cond, span), flow_state); . use rustc_middle::mir::AssertKind; 1,123 ( 0.00%) if let AssertKind::BoundsCheck { ref len, ref index } = *msg { 50 ( 0.00%) self.consume_operand(loc, (len, span), flow_state); . self.consume_operand(loc, (index, span), flow_state); . } . } . . TerminatorKind::Yield { ref value, resume: _, resume_arg, drop: _ } => { . self.consume_operand(loc, (value, span), flow_state); . self.mutate_place(loc, (resume_arg, span), Deep, flow_state); . } -- line 749 ---------------------------------------- -- line 790 ---------------------------------------- . | TerminatorKind::Resume . | TerminatorKind::Return . | TerminatorKind::GeneratorDrop . | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ } . | TerminatorKind::FalseUnwind { real_target: _, unwind: _ } => { . // no data used, thus irrelevant to borrowck . } . } 842,944 ( 0.00%) } . 863,002 ( 0.00%) fn visit_terminator_after_primary_effect( . &mut self, . flow_state: &Flows<'cx, 'tcx>, . term: &'cx Terminator<'tcx>, . loc: Location, . ) { 123,286 ( 0.00%) let span = term.source_info.span; . 493,144 ( 0.00%) match term.kind { . TerminatorKind::Yield { value: _, resume: _, resume_arg: _, drop: _ } => { . if self.movable_generator { . // Look for any active borrows to locals . let borrow_set = self.borrow_set.clone(); . for i in flow_state.borrows.iter() { . let borrow = &borrow_set[i]; . self.check_for_local_borrow(borrow, span); . } -- line 816 ---------------------------------------- -- line 817 ---------------------------------------- . } . } . . TerminatorKind::Resume | TerminatorKind::Return | TerminatorKind::GeneratorDrop => { . // Returning from the function implicitly kills storage for all locals and statics. . // Often, the storage will already have been killed by an explicit . // StorageDead, but we don't always emit those (notably on unwind paths), . // so this "extra check" serves as a kind of backup. 23,520 ( 0.00%) let borrow_set = self.borrow_set.clone(); . for i in flow_state.borrows.iter() { . let borrow = &borrow_set[i]; . self.check_for_invalidation_at_exit(loc, borrow, span); . } . } . . TerminatorKind::Abort . | TerminatorKind::Assert { .. } -- line 833 ---------------------------------------- -- line 836 ---------------------------------------- . | TerminatorKind::DropAndReplace { .. } . | TerminatorKind::FalseEdge { real_target: _, imaginary_target: _ } . | TerminatorKind::FalseUnwind { real_target: _, unwind: _ } . | TerminatorKind::Goto { .. } . | TerminatorKind::SwitchInt { .. } . | TerminatorKind::Unreachable . | TerminatorKind::InlineAsm { .. } => {} . } 986,288 ( 0.00%) } . } . . use self::AccessDepth::{Deep, Shallow}; . use self::ReadOrWrite::{Activation, Read, Reservation, Write}; . . #[derive(Copy, Clone, PartialEq, Eq, Debug)] . enum ArtificialField { . ArrayLength, -- line 852 ---------------------------------------- -- line 913 ---------------------------------------- . /// When checking permissions for a place access, this flag is used to indicate that an immutable . /// local place can be mutated. . // . // FIXME: @nikomatsakis suggested that this flag could be removed with the following modifications: . // - Merge `check_access_permissions()` and `check_if_reassignment_to_immutable_state()`. . // - Split `is_mutable()` into `is_assignable()` (can be directly assigned) and . // `is_declared_mutable()`. . // - Take flow state into consideration in `is_assignable()` for local variables. 88,122 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, Debug)] . enum LocalMutationIsAllowed { . Yes, . /// We want use of immutable upvars to cause a "write to immutable upvar" . /// error, not an "reassignment" error. . ExceptUpvars, . No, . } . -- line 929 ---------------------------------------- -- line 970 ---------------------------------------- . } . . /// Checks an access to the given place to see if it is allowed. Examines the set of borrows . /// that are in scope, as well as which paths have been initialized, to ensure that (a) the . /// place is initialized and (b) it is not borrowed in some way that would prevent this . /// access. . /// . /// Returns `true` if an error is reported. 5,591,536 ( 0.02%) fn access_place( . &mut self, . location: Location, . place_span: (Place<'tcx>, Span), . kind: (AccessDepth, ReadOrWrite), . is_local_mutation_allowed: LocalMutationIsAllowed, . flow_state: &Flows<'cx, 'tcx>, . ) { . let (sd, rw) = kind; . 1,397,884 ( 0.00%) if let Activation(_, borrow_index) = rw { 10,514 ( 0.00%) if self.reservation_error_reported.contains(&place_span.0) { . debug!( . "skipping access_place for activation of invalid reservation \ . place: {:?} borrow_index: {:?}", . place_span.0, borrow_index . ); . return; . } . } . . // Check is_empty() first because it's the common case, and doing that . // way we avoid the clone() call. 349,471 ( 0.00%) if !self.access_place_error_reported.is_empty() . && self.access_place_error_reported.contains(&(place_span.0, place_span.1)) . { . debug!( . "access_place: suppressing error place_span=`{:?}` kind=`{:?}`", . place_span, kind . ); . return; . } . 2,096,826 ( 0.01%) let mutability_error = self.check_access_permissions( 1,397,884 ( 0.00%) place_span, . rw, . is_local_mutation_allowed, . flow_state, . location, . ); . let conflict_error = 3,844,181 ( 0.01%) self.check_access_for_conflict(location, place_span, sd, rw, flow_state); . 1,048,413 ( 0.00%) if let (Activation(_, borrow_idx), true) = (kind.1, conflict_error) { . // Suppress this warning when there's an error being emitted for the . // same borrow: fixing the error is likely to fix the warning. . self.reservation_warnings.remove(&borrow_idx); . } . 1,048,413 ( 0.00%) if conflict_error || mutability_error { . debug!("access_place: logging error place_span=`{:?}` kind=`{:?}`", place_span, kind); . . self.access_place_error_reported.insert((place_span.0, place_span.1)); . } 2,795,768 ( 0.01%) } . . fn check_access_for_conflict( . &mut self, . location: Location, . place_span: (Place<'tcx>, Span), . sd: AccessDepth, . rw: ReadOrWrite, . flow_state: &Flows<'cx, 'tcx>, . ) -> bool { . debug!( . "check_access_for_conflict(location={:?}, place_span={:?}, sd={:?}, rw={:?})", . location, place_span, sd, rw, . ); . 349,471 ( 0.00%) let mut error_reported = false; 1,048,413 ( 0.00%) let tcx = self.infcx.tcx; . let body = self.body; 698,942 ( 0.00%) let borrow_set = self.borrow_set.clone(); . . // Use polonius output if it has been enabled. 698,942 ( 0.00%) let polonius_output = self.polonius_output.clone(); . let borrows_in_scope = if let Some(polonius) = &polonius_output { . let location = self.location_table.start_index(location); . Either::Left(polonius.errors_at(location).iter().copied()) . } else { . Either::Right(flow_state.borrows.iter()) . }; . 4,543,123 ( 0.01%) each_borrow_involving_path( . self, . tcx, . body, . location, 2,096,826 ( 0.01%) (sd, place_span.0), . &borrow_set, 2,096,826 ( 0.01%) borrows_in_scope, 3,912,522 ( 0.01%) |this, borrow_index, borrow| match (rw, borrow.kind) { . // Obviously an activation is compatible with its own . // reservation (or even prior activating uses of same . // borrow); so don't check if they interfere. . // . // NOTE: *reservations* do conflict with themselves; . // thus aren't injecting unsoundenss w/ this check.) 5,257 ( 0.00%) (Activation(_, activating), _) if activating == borrow_index => { . debug!( . "check_access_for_conflict place_span: {:?} sd: {:?} rw: {:?} \ . skipping {:?} b/c activation of same borrow_index", . place_span, . sd, . rw, . (borrow_index, borrow), . ); -- line 1084 ---------------------------------------- -- line 1179 ---------------------------------------- . } . } . Control::Break . } . }, . ); . . error_reported 1,048,413 ( 0.00%) } . 1,074,270 ( 0.00%) fn mutate_place( . &mut self, . location: Location, . place_span: (Place<'tcx>, Span), . kind: AccessDepth, . flow_state: &Flows<'cx, 'tcx>, . ) { . // Write of P[i] or *P requires P init'd. 966,843 ( 0.00%) self.check_if_assigned_path_is_moved(location, place_span, flow_state); . . // Special case: you can assign an immutable local variable . // (e.g., `x = ...`) so long as it has never been initialized . // before (at this point in the flow). 107,427 ( 0.00%) if let Some(local) = place_span.0.as_local() { 429,680 ( 0.00%) if let Mutability::Not = self.body.local_decls[local].mutability { . // check for reassignments to immutable local variables . self.check_if_reassignment_to_immutable_state( . location, local, place_span, flow_state, . ); . return; . } . } . . // Otherwise, use the normal access permission rules. 955,788 ( 0.00%) self.access_place( . location, 318,596 ( 0.00%) place_span, . (kind, Write(WriteKind::Mutate)), . LocalMutationIsAllowed::No, . flow_state, . ); 859,416 ( 0.00%) } . . fn consume_rvalue( . &mut self, . location: Location, . (rvalue, span): (&'cx Rvalue<'tcx>, Span), . flow_state: &Flows<'cx, 'tcx>, . ) { 556,470 ( 0.00%) match *rvalue { 90,012 ( 0.00%) Rvalue::Ref(_ /*rgn*/, bk, place) => { 343,102 ( 0.00%) let access_kind = match bk { . BorrowKind::Shallow => { . (Shallow(Some(ArtificialField::ShallowBorrow)), Read(ReadKind::Borrow(bk))) . } . BorrowKind::Shared => (Deep, Read(ReadKind::Borrow(bk))), . BorrowKind::Unique | BorrowKind::Mut { .. } => { . let wk = WriteKind::MutableBorrow(bk); 16,946 ( 0.00%) if allow_two_phase_borrow(bk) { . (Deep, Reservation(wk)) . } else { . (Deep, Write(wk)) . } . } . }; . 630,084 ( 0.00%) self.access_place( . location, 120,016 ( 0.00%) (place, span), . access_kind, . LocalMutationIsAllowed::No, . flow_state, . ); . . let action = if bk == BorrowKind::Shallow { . InitializationRequiringAction::MatchOn . } else { . InitializationRequiringAction::Borrow . }; . 210,028 ( 0.00%) self.check_if_path_or_subpath_is_moved( . location, . action, 210,028 ( 0.00%) (place.as_ref(), span), . flow_state, . ); . } . . Rvalue::AddressOf(mutability, place) => { . let access_kind = match mutability { . Mutability::Mut => ( . Deep, -- line 1270 ---------------------------------------- -- line 1302 ---------------------------------------- . } . . Rvalue::Len(place) | Rvalue::Discriminant(place) => { . let af = match *rvalue { . Rvalue::Len(..) => Some(ArtificialField::ArrayLength), . Rvalue::Discriminant(..) => None, . _ => unreachable!(), . }; 107,792 ( 0.00%) self.access_place( . location, 26,948 ( 0.00%) (place, span), . (Shallow(af), Read(ReadKind::Copy)), . LocalMutationIsAllowed::No, . flow_state, . ); 47,159 ( 0.00%) self.check_if_path_or_subpath_is_moved( . location, . InitializationRequiringAction::Use, 47,159 ( 0.00%) (place.as_ref(), span), . flow_state, . ); . } . . Rvalue::BinaryOp(_bin_op, box (ref operand1, ref operand2)) . | Rvalue::CheckedBinaryOp(_bin_op, box (ref operand1, ref operand2)) => { 14,620 ( 0.00%) self.consume_operand(location, (operand1, span), flow_state); 10,234 ( 0.00%) self.consume_operand(location, (operand2, span), flow_state); . } . . Rvalue::NullaryOp(_op, _ty) => { . // nullary ops take no dynamic input; no borrowck effect. . } . . Rvalue::Aggregate(ref aggregate_kind, ref operands) => { . // We need to report back the list of mutable upvars that were . // moved into the closure and subsequently used by the closure, . // in order to populate our used_mut set. 57,129 ( 0.00%) match **aggregate_kind { . AggregateKind::Closure(def_id, _) | AggregateKind::Generator(def_id, _, _) => { . let BorrowCheckResult { used_mut_upvars, .. } = 116 ( 0.00%) self.infcx.tcx.mir_borrowck(def_id.expect_local()); . debug!("{:?} used_mut_upvars={:?}", def_id, used_mut_upvars); . for field in used_mut_upvars { . self.propagate_closure_used_mut_upvar(&operands[field.index()]); . } . } . AggregateKind::Adt(..) . | AggregateKind::Array(..) . | AggregateKind::Tuple { .. } => (), -- line 1350 ---------------------------------------- -- line 1448 ---------------------------------------- . } . _ => propagate_closure_used_mut_place(self, place), . } . } . Operand::Constant(..) => {} . } . } . 1,136,148 ( 0.00%) fn consume_operand( . &mut self, . location: Location, . (operand, span): (&'cx Operand<'tcx>, Span), . flow_state: &Flows<'cx, 'tcx>, . ) { 611,909 ( 0.00%) match *operand { 47,433 ( 0.00%) Operand::Copy(place) => { . // copy of place: check if this is "copy of frozen path" . // (FIXME: see check_loans.rs) 94,901 ( 0.00%) self.access_place( . location, 79,055 ( 0.00%) (place, span), . (Deep, Read(ReadKind::Copy)), . LocalMutationIsAllowed::No, . flow_state, . ); . . // Finally, check if path was already moved. 35 ( 0.00%) self.check_if_path_or_subpath_is_moved( . location, . InitializationRequiringAction::Use, 30 ( 0.00%) (place.as_ref(), span), . flow_state, . ); . } 201,747 ( 0.00%) Operand::Move(place) => { . // move of place: check if this is move of already borrowed path 569,893 ( 0.00%) self.access_place( . location, 336,245 ( 0.00%) (place, span), . (Deep, Write(WriteKind::Move)), . LocalMutationIsAllowed::Yes, . flow_state, . ); . . // Finally, check if path was already moved. 132,200 ( 0.00%) self.check_if_path_or_subpath_is_moved( . location, . InitializationRequiringAction::Use, 99,150 ( 0.00%) (place.as_ref(), span), . flow_state, . ); . } . Operand::Constant(_) => {} . } 757,432 ( 0.00%) } . . /// Checks whether a borrow of this place is invalidated when the function . /// exits . fn check_for_invalidation_at_exit( . &mut self, . location: Location, . borrow: &BorrowData<'tcx>, . span: Span, -- line 1510 ---------------------------------------- -- line 1573 ---------------------------------------- . err.buffer(&mut self.errors_buffer); . } . } . . fn check_activations(&mut self, location: Location, span: Span, flow_state: &Flows<'cx, 'tcx>) { . // Two-phase borrow support: For each activation that is newly . // generated at this statement, check if it interferes with . // another borrow. 808,064 ( 0.00%) let borrow_set = self.borrow_set.clone(); 1,498,099 ( 0.00%) for &borrow_index in borrow_set.activations_at_location(location) { . let borrow = &borrow_set[borrow_index]; . . // only mutable borrows should be 2-phase 26,285 ( 0.00%) assert!(match borrow.kind { . BorrowKind::Shared | BorrowKind::Shallow => false, . BorrowKind::Unique | BorrowKind::Mut { .. } => true, . }); . 63,084 ( 0.00%) self.access_place( . location, 31,542 ( 0.00%) (borrow.borrowed_place, span), 47,313 ( 0.00%) (Deep, Activation(WriteKind::MutableBorrow(borrow.kind), borrow_index)), . LocalMutationIsAllowed::No, . flow_state, . ); . // We do not need to call `check_if_path_or_subpath_is_moved` . // again, as we already called it when we made the . // initial reservation. . } . } -- line 1602 ---------------------------------------- -- line 1606 ---------------------------------------- . location: Location, . local: Local, . place_span: (Place<'tcx>, Span), . flow_state: &Flows<'cx, 'tcx>, . ) { . debug!("check_if_reassignment_to_immutable_state({:?})", local); . . // Check if any of the initializiations of `local` have happened yet: 166,668 ( 0.00%) if let Some(init_index) = self.is_local_ever_initialized(local, flow_state) { . // And, if so, report an error. . let init = &self.move_data.inits[init_index]; . let span = init.span(&self.body); . self.report_illegal_reassignment(location, place_span, span, place_span.0); . } . } . 1,707,992 ( 0.00%) fn check_if_full_path_is_moved( . &mut self, . location: Location, . desired_action: InitializationRequiringAction, . place_span: (PlaceRef<'tcx>, Span), . flow_state: &Flows<'cx, 'tcx>, . ) { . let maybe_uninits = &flow_state.uninits; . -- line 1630 ---------------------------------------- -- line 1660 ---------------------------------------- . // Therefore, if we seek out the *closest* prefix for which we . // have a MovePath, that should capture the initialization . // state for the place scenario. . // . // This code covers scenarios 1, 2, and 3. . . debug!("check_if_full_path_is_moved place: {:?}", place_span.0); . let (prefix, mpi) = self.move_path_closest_to(place_span.0); 131,384 ( 0.00%) if maybe_uninits.contains(mpi) { . self.report_use_of_moved_or_uninitialized( . location, . desired_action, . (prefix, place_span.0, place_span.1), . mpi, . ); . } // Only query longest prefix with a MovePath, not further . // ancestors; dataflow recurs on children when parents . // move (to support partial (re)inits). . // . // (I.e., querying parents breaks scenario 7; but may want . // to do such a query based on partial-init feature-gate.) 1,051,072 ( 0.00%) } . . /// Subslices correspond to multiple move paths, so we iterate through the . /// elements of the base array. For each element we check . /// . /// * Does this element overlap with our slice. . /// * Is any part of it uninitialized. . fn check_if_subslice_element_is_moved( . &mut self, -- line 1689 ---------------------------------------- -- line 1719 ---------------------------------------- . return; // don't bother finding other problems. . } . } . } . } . } . } . 1,445,147 ( 0.00%) fn check_if_path_or_subpath_is_moved( . &mut self, . location: Location, . desired_action: InitializationRequiringAction, . place_span: (PlaceRef<'tcx>, Span), . flow_state: &Flows<'cx, 'tcx>, . ) { 262,754 ( 0.00%) let maybe_uninits = &flow_state.uninits; . . // Bad scenarios: . // . // 1. Move of `a.b.c`, use of `a` or `a.b` . // partial initialization support, one might have `a.x` . // initialized but not `a.b`. . // 2. All bad scenarios from `check_if_full_path_is_moved` . // -- line 1742 ---------------------------------------- -- line 1743 ---------------------------------------- . // OK scenarios: . // . // 3. Move of `a.b.c`, use of `a.b.d` . // 4. Uninitialized `a.x`, initialized `a.b`, use of `a.b` . // 5. Copied `(a.b: &_)`, use of `*(a.b).c`; note that `a.b` . // must have been initialized for the use to be sound. . // 6. Move of `a.b.c` then reinit of `a.b.c.d`, use of `a.b.c.d` . 919,639 ( 0.00%) self.check_if_full_path_is_moved(location, desired_action, place_span, flow_state); . 184,516 ( 0.00%) if let Some((place_base, ProjectionElem::Subslice { from, to, from_end: false })) = 131,377 ( 0.00%) place_span.0.last_projection() . { . let place_ty = place_base.ty(self.body(), self.infcx.tcx); . if let ty::Array(..) = place_ty.ty.kind() { . self.check_if_subslice_element_is_moved( . location, . desired_action, . (place_base, place_span.1), . maybe_uninits, -- line 1762 ---------------------------------------- -- line 1772 ---------------------------------------- . // . // (Distinct from handling of scenarios 1+2+4 above because . // `place` does not interfere with suffixes of its prefixes, . // e.g., `a.b.c` does not interfere with `a.b.d`) . // . // This code covers scenario 1. . . debug!("check_if_path_or_subpath_is_moved place: {:?}", place_span.0); 525,508 ( 0.00%) if let Some(mpi) = self.move_path_for_place(place_span.0) { 373,576 ( 0.00%) let uninit_mpi = self . .move_data . .find_in_move_path_or_its_descendants(mpi, |mpi| maybe_uninits.contains(mpi)); . 186,788 ( 0.00%) if let Some(uninit_mpi) = uninit_mpi { . self.report_use_of_moved_or_uninitialized( . location, . desired_action, . (place_span.0, place_span.0, place_span.1), . uninit_mpi, . ); . return; // don't bother finding other problems. . } . } 1,051,016 ( 0.00%) } . . /// Currently MoveData does not store entries for all places in . /// the input MIR. For example it will currently filter out . /// places that are Copy; thus we do not track places of shared . /// reference type. This routine will walk up a place along its . /// prefixes, searching for a foundational place that *is* . /// tracked in the MoveData. . /// . /// An Err result includes a tag indicated why the search failed. . /// Currently this can only occur if the place is built off of a . /// static variable, as we do not track those in the MoveData. . fn move_path_closest_to(&mut self, place: PlaceRef<'tcx>) -> (PlaceRef<'tcx>, MovePathIndex) { 1,707,992 ( 0.00%) match self.move_data.rev_lookup.find(place) { . LookupResult::Parent(Some(mpi)) | LookupResult::Exact(mpi) => { . (self.move_data.move_paths[mpi].place.as_ref(), mpi) . } . LookupResult::Parent(None) => panic!("should have move path for every Local"), . } . } . . fn move_path_for_place(&mut self, place: PlaceRef<'tcx>) -> Option { . // If returns None, then there is no move path corresponding . // to a direct owner of `place` (which means there is nothing . // that borrowck tracks for its analysis). . 1,182,449 ( 0.00%) match self.move_data.rev_lookup.find(place) { . LookupResult::Parent(_) => None, . LookupResult::Exact(mpi) => Some(mpi), . } . } . . fn check_if_assigned_path_is_moved( . &mut self, . location: Location, . (place, span): (Place<'tcx>, Span), . flow_state: &Flows<'cx, 'tcx>, . ) { . debug!("check_if_assigned_path_is_moved place: {:?}", place); . . // None case => assigning to `x` does not require `x` be initialized. 7 ( 0.00%) for (place_base, elem) in place.iter_projections().rev() { 56 ( 0.00%) match elem { . ProjectionElem::Index(_/*operand*/) | . ProjectionElem::ConstantIndex { .. } | . // assigning to P[i] requires P to be valid. . ProjectionElem::Downcast(_/*adt_def*/, _/*variant_idx*/) => . // assigning to (P->variant) is okay if assigning to `P` is okay . // . // FIXME: is this true even if P is an adt with a dtor? . { } . . // assigning to (*P) requires P to be initialized . ProjectionElem::Deref => { 49 ( 0.00%) self.check_if_full_path_is_moved( . location, InitializationRequiringAction::Use, 42 ( 0.00%) (place_base, span), flow_state); . // (base initialized; no need to . // recur further) . break; . } . . ProjectionElem::Subslice { .. } => { . panic!("we don't allow assignments to subslices, location: {:?}", . location); . } . . ProjectionElem::Field(..) => { . // if type of `P` has a dtor, then . // assigning to `P.f` requires `P` itself . // be already initialized . let tcx = self.infcx.tcx; 7 ( 0.00%) let base_ty = place_base.ty(self.body(), tcx).ty; 21 ( 0.00%) match base_ty.kind() { 42 ( 0.00%) ty::Adt(def, _) if def.has_dtor(tcx) => { . self.check_if_path_or_subpath_is_moved( . location, InitializationRequiringAction::Assignment, . (place_base, span), flow_state); . . // (base initialized; no need to . // recur further) . break; . } -- line 1877 ---------------------------------------- -- line 1931 ---------------------------------------- . . // Shallow so that we'll stop at any dereference; we'll . // report errors about issues with such bases elsewhere. . let maybe_uninits = &flow_state.uninits; . . // Find the shortest uninitialized prefix you can reach . // without going over a Deref. . let mut shortest_uninit_seen = None; 154 ( 0.00%) for prefix in this.prefixes(base, PrefixSet::Shallow) { 7 ( 0.00%) let mpi = match this.move_path_for_place(prefix) { . Some(mpi) => mpi, . None => continue, . }; . . if maybe_uninits.contains(mpi) { . debug!( . "check_parent_of_field updating shortest_uninit_seen from {:?} to {:?}", . shortest_uninit_seen, -- line 1948 ---------------------------------------- -- line 1949 ---------------------------------------- . Some((prefix, mpi)) . ); . shortest_uninit_seen = Some((prefix, mpi)); . } else { . debug!("check_parent_of_field {:?} is definitely initialized", (prefix, mpi)); . } . } . 21 ( 0.00%) if let Some((prefix, mpi)) = shortest_uninit_seen { . // Check for a reassignment into an uninitialized field of a union (for example, . // after a move out). In this case, do not report an error here. There is an . // exception, if this is the first assignment into the union (that is, there is . // no move out from an earlier location) then this is an attempt at initialization . // of the union - we should error in that case. . let tcx = this.infcx.tcx; . if base.ty(this.body(), tcx).ty.is_union() { . if this.move_data.path_map[mpi].iter().any(|moi| { -- line 1965 ---------------------------------------- -- line 1979 ---------------------------------------- . } . } . . /// Checks the permissions for the given place and read or write kind . /// . /// Returns `true` if an error is reported. . fn check_access_permissions( . &mut self, 698,942 ( 0.00%) (place, span): (Place<'tcx>, Span), . kind: ReadOrWrite, . is_local_mutation_allowed: LocalMutationIsAllowed, . flow_state: &Flows<'cx, 'tcx>, . location: Location, . ) -> bool { . debug!( . "check_access_permissions({:?}, {:?}, is_local_mutation_allowed: {:?})", . place, kind, is_local_mutation_allowed . ); . . let error_access; . let the_place_err; . 5,481,539 ( 0.02%) match kind { . Reservation(WriteKind::MutableBorrow( . borrow_kind @ (BorrowKind::Unique | BorrowKind::Mut { .. }), . )) . | Write(WriteKind::MutableBorrow( . borrow_kind @ (BorrowKind::Unique | BorrowKind::Mut { .. }), . )) => { 84,730 ( 0.00%) let is_local_mutation_allowed = match borrow_kind { . BorrowKind::Unique => LocalMutationIsAllowed::Yes, . BorrowKind::Mut { .. } => is_local_mutation_allowed, . BorrowKind::Shared | BorrowKind::Shallow => unreachable!(), . }; 59,311 ( 0.00%) match self.is_mutable(place.as_ref(), is_local_mutation_allowed) { . Ok(root_place) => { . self.add_used_mut(root_place, flow_state); . return false; . } . Err(place_err) => { . error_access = AccessKind::MutableBorrow; . the_place_err = place_err; . } . } . } . Reservation(WriteKind::Mutate) | Write(WriteKind::Mutate) => { 557,543 ( 0.00%) match self.is_mutable(place.as_ref(), is_local_mutation_allowed) { . Ok(root_place) => { . self.add_used_mut(root_place, flow_state); . return false; . } . Err(place_err) => { . error_access = AccessKind::Mutate; . the_place_err = place_err; . } -- line 2033 ---------------------------------------- -- line 2041 ---------------------------------------- . | WriteKind::MutableBorrow(BorrowKind::Shallow), . ) . | Write( . WriteKind::Move . | WriteKind::StorageDeadOrDrop . | WriteKind::MutableBorrow(BorrowKind::Shared) . | WriteKind::MutableBorrow(BorrowKind::Shallow), . ) => { 424,026 ( 0.00%) if let (Err(_), true) = ( 1,484,091 ( 0.00%) self.is_mutable(place.as_ref(), is_local_mutation_allowed), . self.errors_buffer.is_empty(), . ) { . // rust-lang/rust#46908: In pure NLL mode this code path should be . // unreachable, but we use `delay_span_bug` because we can hit this when . // dereferencing a non-Copy raw pointer *and* have `-Ztreat-err-as-bug` . // enabled. We don't want to ICE for that case, as other errors will have . // been emitted (#52262). . self.infcx.tcx.sess.delay_span_bug( -- line 2058 ---------------------------------------- -- line 2094 ---------------------------------------- . if previously_initialized { . self.report_mutability_error(place, span, the_place_err, error_access, location); . true . } else { . false . } . } . 553,590 ( 0.00%) fn is_local_ever_initialized( . &self, . local: Local, . flow_state: &Flows<'cx, 'tcx>, . ) -> Option { 332,154 ( 0.00%) let mpi = self.move_data.rev_lookup.find_local(local); 110,718 ( 0.00%) let ii = &self.move_data.init_path_map[mpi]; 549,516 ( 0.00%) for &index in ii { 434,724 ( 0.00%) if flow_state.ever_inits.contains(index) { . return Some(index); . } . } . None 442,872 ( 0.00%) } . . /// Adds the place into the used mutable variables set 352,488 ( 0.00%) fn add_used_mut(&mut self, root_place: RootPlace<'tcx>, flow_state: &Flows<'cx, 'tcx>) { . match root_place { 264,366 ( 0.00%) RootPlace { place_local: local, place_projection: [], is_local_mutation_allowed } => { . // If the local may have been initialized, and it is now currently being . // mutated, then it is justified to be annotated with the `mut` . // keyword, since the mutation may be a possible reassignment. 171,062 ( 0.00%) if is_local_mutation_allowed != LocalMutationIsAllowed::Yes 248,820 ( 0.00%) && self.is_local_ever_initialized(local, flow_state).is_some() . { . self.used_mut.insert(local); . } . } . RootPlace { . place_local: _, . place_projection: _, . is_local_mutation_allowed: LocalMutationIsAllowed::Yes, -- line 2133 ---------------------------------------- -- line 2140 ---------------------------------------- . if let Some(field) = self.is_upvar_field_projection(PlaceRef { . local: place_local, . projection: place_projection, . }) { . self.used_mut_upvars.push(field); . } . } . } 326,808 ( 0.00%) } . . /// Whether this value can be written or borrowed mutably. . /// Returns the root place if the place passed in is a projection. 3,524,213 ( 0.01%) fn is_mutable( . &self, . place: PlaceRef<'tcx>, . is_local_mutation_allowed: LocalMutationIsAllowed, . ) -> Result, PlaceRef<'tcx>> { . debug!("is_mutable: place={:?}, is_local...={:?}", place, is_local_mutation_allowed); 1,001,645 ( 0.00%) match place.last_projection() { . None => { 300,135 ( 0.00%) let local = &self.body.local_decls[place.local]; 900,405 ( 0.00%) match local.mutability { 119,096 ( 0.00%) Mutability::Not => match is_local_mutation_allowed { 357,288 ( 0.00%) LocalMutationIsAllowed::Yes => Ok(RootPlace { . place_local: place.local, . place_projection: place.projection, . is_local_mutation_allowed: LocalMutationIsAllowed::Yes, . }), . LocalMutationIsAllowed::ExceptUpvars => Ok(RootPlace { . place_local: place.local, . place_projection: place.projection, . is_local_mutation_allowed: LocalMutationIsAllowed::ExceptUpvars, . }), . LocalMutationIsAllowed::No => Err(place), . }, 481,174 ( 0.00%) Mutability::Mut => Ok(RootPlace { . place_local: place.local, . place_projection: place.projection, . is_local_mutation_allowed, . }), . } . } . Some((place_base, elem)) => { 60,744 ( 0.00%) match elem { . ProjectionElem::Deref => { 10,364 ( 0.00%) let base_ty = place_base.ty(self.body(), self.infcx.tcx).ty; . . // Check the kind of deref to decide 31,092 ( 0.00%) match base_ty.kind() { . ty::Ref(_, _, mutbl) => { 10,364 ( 0.00%) match mutbl { . // Shared borrowed data is never mutable . hir::Mutability::Not => Err(place), . // Mutably borrowed data is mutable, but only if we have a . // unique path to the `&mut` . hir::Mutability::Mut => { 10,364 ( 0.00%) let mode = match self.is_upvar_field_projection(place) { . Some(field) if self.upvars[field.index()].by_ref => { . is_local_mutation_allowed . } . _ => LocalMutationIsAllowed::Yes, . }; . 31,092 ( 0.00%) self.is_mutable(place_base, mode) . } . } . } . ty::RawPtr(tnm) => { . match tnm.mutbl { . // `*const` raw pointers are not mutable . hir::Mutability::Not => Err(place), . // `*mut` raw pointers are always mutable, regardless of -- line 2211 ---------------------------------------- -- line 2228 ---------------------------------------- . // All other projections are owned by their base path, so mutable if . // base path is mutable . ProjectionElem::Field(..) . | ProjectionElem::Index(..) . | ProjectionElem::ConstantIndex { .. } . | ProjectionElem::Subslice { .. } . | ProjectionElem::Downcast(..) => { . let upvar_field_projection = self.is_upvar_field_projection(place); 30,132 ( 0.00%) if let Some(field) = upvar_field_projection { . let upvar = &self.upvars[field.index()]; . debug!( . "is_mutable: upvar.mutability={:?} local_mutation_is_allowed={:?} \ . place={:?}, place_base={:?}", . upvar, is_local_mutation_allowed, place, place_base . ); . match (upvar.place.mutability, is_local_mutation_allowed) { . ( -- line 2244 ---------------------------------------- -- line 2285 ---------------------------------------- . } . } else { . self.is_mutable(place_base, is_local_mutation_allowed) . } . } . } . } . } 2,563,064 ( 0.01%) } . . /// If `place` is a field projection, and the field is being projected from a closure type, . /// then returns the index of the field being projected. Note that this closure will always . /// be `self` in the current MIR, because that is the only time we directly access the fields . /// of a closure type. . fn is_upvar_field_projection(&self, place_ref: PlaceRef<'tcx>) -> Option { 182,232 ( 0.00%) path_utils::is_upvar_field_projection(self.infcx.tcx, &self.upvars, place_ref, self.body()) . } . } . . /// The degree of overlap between 2 places for borrow-checking. . enum Overlap { . /// The places might partially overlap - in this case, we give . /// up and say that they might conflict. This occurs when . /// different fields of a union are borrowed. For example, -- line 2308 ---------------------------------------- 10,885,156 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs -------------------------------------------------------------------------------- Ir -- line 186 ---------------------------------------- . /// // use the values stored in map . /// ``` . pub struct HashMap { . pub(crate) hash_builder: S, . pub(crate) table: RawTable<(K, V), A>, . } . . impl Clone for HashMap { 6,288 ( 0.00%) fn clone(&self) -> Self { 55,545 ( 0.00%) HashMap { . hash_builder: self.hash_builder.clone(), 11,406 ( 0.00%) table: self.table.clone(), . } 7,074 ( 0.00%) } . . fn clone_from(&mut self, source: &Self) { . self.table.clone_from(&source.table); . . // Update hash_builder only if we successfully cloned all elements. . self.hash_builder.clone_from(&source.hash_builder); . } . } . . /// Ensures that a single closure type across uses of this which, in turn prevents multiple . /// instances of any functions like RawTable::reserve from being generated . #[cfg_attr(feature = "inline-more", inline)] 2,010 ( 0.00%) pub(crate) fn make_hasher(hash_builder: &S) -> impl Fn(&(Q, V)) -> u64 + '_ . where . K: Borrow, . Q: Hash, . S: BuildHasher, . { 2,393,672 ( 0.01%) move |val| make_hash::(hash_builder, &val.0) 3,015 ( 0.00%) } . . /// Ensures that a single closure type across uses of this which, in turn prevents multiple . /// instances of any functions like RawTable::reserve from being generated . #[cfg_attr(feature = "inline-more", inline)] 58 ( 0.00%) fn equivalent_key(k: &Q) -> impl Fn(&(K, V)) -> bool + '_ . where . K: Borrow, . Q: ?Sized + Eq, . { 5,575,506 ( 0.02%) move |x| k.eq(x.0.borrow()) 87 ( 0.00%) } . . /// Ensures that a single closure type across uses of this which, in turn prevents multiple . /// instances of any functions like RawTable::reserve from being generated . #[cfg_attr(feature = "inline-more", inline)] . fn equivalent(k: &Q) -> impl Fn(&K) -> bool + '_ . where . K: Borrow, . Q: ?Sized + Eq, . { 7,341,293 ( 0.02%) move |x| k.eq(x.borrow()) . } . . #[cfg(not(feature = "nightly"))] . #[cfg_attr(feature = "inline-more", inline)] . pub(crate) fn make_hash(hash_builder: &S, val: &Q) -> u64 . where . K: Borrow, . Q: Hash + ?Sized, -- line 248 ---------------------------------------- -- line 251 ---------------------------------------- . use core::hash::Hasher; . let mut state = hash_builder.build_hasher(); . val.hash(&mut state); . state.finish() . } . . #[cfg(feature = "nightly")] . #[cfg_attr(feature = "inline-more", inline)] 46 ( 0.00%) pub(crate) fn make_hash(hash_builder: &S, val: &Q) -> u64 . where . K: Borrow, . Q: Hash + ?Sized, . S: BuildHasher, . { 185,728 ( 0.00%) hash_builder.hash_one(val) 36 ( 0.00%) } . . #[cfg(not(feature = "nightly"))] . #[cfg_attr(feature = "inline-more", inline)] . pub(crate) fn make_insert_hash(hash_builder: &S, val: &K) -> u64 . where . K: Hash, . S: BuildHasher, . { -- line 274 ---------------------------------------- -- line 275 ---------------------------------------- . use core::hash::Hasher; . let mut state = hash_builder.build_hasher(); . val.hash(&mut state); . state.finish() . } . . #[cfg(feature = "nightly")] . #[cfg_attr(feature = "inline-more", inline)] 45 ( 0.00%) pub(crate) fn make_insert_hash(hash_builder: &S, val: &K) -> u64 . where . K: Hash, . S: BuildHasher, . { 4,881,960 ( 0.01%) hash_builder.hash_one(val) 30 ( 0.00%) } . . #[cfg(feature = "ahash")] . impl HashMap { . /// Creates an empty `HashMap`. . /// . /// The hash map is initially created with a capacity of 0, so it will not allocate until it . /// is first inserted into. . /// -- line 297 ---------------------------------------- -- line 366 ---------------------------------------- . /// . /// let s = DefaultHashBuilder::default(); . /// let mut map = HashMap::with_hasher(s); . /// map.insert(1, 2); . /// ``` . /// . /// [`BuildHasher`]: ../../std/hash/trait.BuildHasher.html . #[cfg_attr(feature = "inline-more", inline)] 7,920 ( 0.00%) pub const fn with_hasher(hash_builder: S) -> Self { 3,269,494 ( 0.01%) Self { . hash_builder, 1,980 ( 0.00%) table: RawTable::new(), . } 1,980 ( 0.00%) } . . /// Creates an empty `HashMap` with the specified capacity, using `hash_builder` . /// to hash the keys. . /// . /// The hash map will be able to hold at least `capacity` elements without . /// reallocating. If `capacity` is 0, the hash map will not allocate. . /// . /// Warning: `hash_builder` is normally randomly generated, and -- line 387 ---------------------------------------- -- line 436 ---------------------------------------- . /// use hashbrown::HashMap; . /// use hashbrown::hash_map::DefaultHashBuilder; . /// . /// let s = DefaultHashBuilder::default(); . /// let mut map = HashMap::with_hasher(s); . /// map.insert(1, 2); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 7,920 ( 0.00%) pub fn with_hasher_in(hash_builder: S, alloc: A) -> Self { 9,997 ( 0.00%) Self { . hash_builder, 1,980 ( 0.00%) table: RawTable::new_in(alloc), . } 1,980 ( 0.00%) } . . /// Creates an empty `HashMap` with the specified capacity, using `hash_builder` . /// to hash the keys. It will be allocated with the given allocator. . /// . /// The hash map will be able to hold at least `capacity` elements without . /// reallocating. If `capacity` is 0, the hash map will not allocate. . /// . /// Warning: `hash_builder` is normally randomly generated, and -- line 457 ---------------------------------------- -- line 662 ---------------------------------------- . /// use hashbrown::HashMap; . /// . /// let mut a = HashMap::new(); . /// assert_eq!(a.len(), 0); . /// a.insert(1, "a"); . /// assert_eq!(a.len(), 1); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 1,980 ( 0.00%) pub fn len(&self) -> usize { 663,805 ( 0.00%) self.table.len() 1,980 ( 0.00%) } . . /// Returns `true` if the map contains no elements. . /// . /// # Examples . /// . /// ``` . /// use hashbrown::HashMap; . /// . /// let mut a = HashMap::new(); . /// assert!(a.is_empty()); . /// a.insert(1, "a"); . /// assert!(!a.is_empty()); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 1,980 ( 0.00%) pub fn is_empty(&self) -> bool { 1,413,336 ( 0.00%) self.len() == 0 3,960 ( 0.00%) } . . /// Clears the map, returning all key-value pairs as an iterator. Keeps the . /// allocated memory for reuse. . /// . /// # Examples . /// . /// ``` . /// use hashbrown::HashMap; -- line 697 ---------------------------------------- -- line 790 ---------------------------------------- . /// use hashbrown::HashMap; . /// . /// let mut a = HashMap::new(); . /// a.insert(1, "a"); . /// a.clear(); . /// assert!(a.is_empty()); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 6 ( 0.00%) pub fn clear(&mut self) { . self.table.clear(); 6 ( 0.00%) } . . /// Creates a consuming iterator visiting all the keys in arbitrary order. . /// The map cannot be used after calling this. . /// The iterator element type is `K`. . /// . /// # Examples . /// . /// ``` -- line 808 ---------------------------------------- -- line 865 ---------------------------------------- . /// # Examples . /// . /// ``` . /// use hashbrown::HashMap; . /// let mut map: HashMap<&str, i32> = HashMap::new(); . /// map.reserve(10); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 3,960 ( 0.00%) pub fn reserve(&mut self, additional: usize) { 3,960 ( 0.00%) self.table 1,980 ( 0.00%) .reserve(additional, make_hasher::(&self.hash_builder)); 1,980 ( 0.00%) } . . /// Tries to reserve capacity for at least `additional` more elements to be inserted . /// in the given `HashMap`. The collection may reserve more space to avoid . /// frequent reallocations. . /// . /// # Errors . /// . /// If the capacity overflows, or the allocator reports a failure, then an error -- line 884 ---------------------------------------- -- line 963 ---------------------------------------- . /// } . /// . /// assert_eq!(letters[&'s'], 2); . /// assert_eq!(letters[&'t'], 3); . /// assert_eq!(letters[&'u'], 1); . /// assert_eq!(letters.get(&'y'), None); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 10,772 ( 0.00%) pub fn entry(&mut self, key: K) -> Entry<'_, K, V, S, A> { . let hash = make_insert_hash::(&self.hash_builder, &key); . if let Some(elem) = self.table.find(hash, equivalent_key(&key)) { 2,055 ( 0.00%) Entry::Occupied(OccupiedEntry { . hash, . key: Some(key), . elem, . table: self, . }) . } else { 11,410 ( 0.00%) Entry::Vacant(VacantEntry { . hash, . key, . table: self, . }) . } 13,465 ( 0.00%) } . . /// Gets the given key's corresponding entry by reference in the map for in-place manipulation. . /// . /// # Examples . /// . /// ``` . /// use hashbrown::HashMap; . /// -- line 995 ---------------------------------------- -- line 1047 ---------------------------------------- . /// ``` . #[inline] . pub fn get(&self, k: &Q) -> Option<&V> . where . K: Borrow, . Q: Hash + Eq, . { . // Avoid `Option::map` because it bloats LLVM IR. 11,335,237 ( 0.03%) match self.get_inner(k) { . Some(&(_, ref v)) => Some(v), . None => None, . } . } . . /// Returns the key-value pair corresponding to the supplied key. . /// . /// The supplied key may be any borrowed form of the map's key type, but -- line 1063 ---------------------------------------- -- line 1086 ---------------------------------------- . // Avoid `Option::map` because it bloats LLVM IR. . match self.get_inner(k) { . Some(&(ref key, ref value)) => Some((key, value)), . None => None, . } . } . . #[inline] 13,235 ( 0.00%) fn get_inner(&self, k: &Q) -> Option<&(K, V)> . where . K: Borrow, . Q: Hash + Eq, . { 14,657,990 ( 0.04%) if self.table.is_empty() { 2,633 ( 0.00%) None . } else { 58 ( 0.00%) let hash = make_hash::(&self.hash_builder, k); 84 ( 0.00%) self.table.get(hash, equivalent_key(k)) . } 7,941 ( 0.00%) } . . /// Returns the key-value pair corresponding to the supplied key, with a mutable reference to value. . /// . /// The supplied key may be any borrowed form of the map's key type, but . /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for . /// the key type. . /// . /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html -- line 1113 ---------------------------------------- -- line 1155 ---------------------------------------- . /// use hashbrown::HashMap; . /// . /// let mut map = HashMap::new(); . /// map.insert(1, "a"); . /// assert_eq!(map.contains_key(&1), true); . /// assert_eq!(map.contains_key(&2), false); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 5,241,126 ( 0.02%) pub fn contains_key(&self, k: &Q) -> bool . where . K: Borrow, . Q: Hash + Eq, . { 13,235 ( 0.00%) self.get_inner(k).is_some() 6,735,290 ( 0.02%) } . . /// Returns a mutable reference to the value corresponding to the key. . /// . /// The key may be any borrowed form of the map's key type, but . /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for . /// the key type. . /// . /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html -- line 1177 ---------------------------------------- -- line 1185 ---------------------------------------- . /// let mut map = HashMap::new(); . /// map.insert(1, "a"); . /// if let Some(x) = map.get_mut(&1) { . /// *x = "b"; . /// } . /// assert_eq!(map[&1], "b"); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 1,383 ( 0.00%) pub fn get_mut(&mut self, k: &Q) -> Option<&mut V> . where . K: Borrow, . Q: Hash + Eq, . { . // Avoid `Option::map` because it bloats LLVM IR. 4,149 ( 0.00%) match self.get_inner_mut(k) { . Some(&mut (_, ref mut v)) => Some(v), . None => None, . } 2,766 ( 0.00%) } . . #[inline] . fn get_inner_mut(&mut self, k: &Q) -> Option<&mut (K, V)> . where . K: Borrow, . Q: Hash + Eq, . { 1,383 ( 0.00%) if self.table.is_empty() { . None . } else { . let hash = make_hash::(&self.hash_builder, k); . self.table.get_mut(hash, equivalent_key(k)) . } . } . . /// Attempts to get mutable references to `N` values in the map at once. -- line 1219 ---------------------------------------- -- line 1495 ---------------------------------------- . /// assert_eq!(map.insert(37, "a"), None); . /// assert_eq!(map.is_empty(), false); . /// . /// map.insert(37, "b"); . /// assert_eq!(map.insert(37, "c"), Some("b")); . /// assert_eq!(map[&37], "c"); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 34,845,116 ( 0.10%) pub fn insert(&mut self, k: K, v: V) -> Option { 120 ( 0.00%) let hash = make_insert_hash::(&self.hash_builder, &k); 7,187 ( 0.00%) if let Some((_, item)) = self.table.get_mut(hash, equivalent_key(&k)) { . Some(mem::replace(item, v)) . } else { 14,199,696 ( 0.04%) self.table 12,758,554 ( 0.04%) .insert(hash, (k, v), make_hasher::(&self.hash_builder)); 1,769,271 ( 0.01%) None . } 33,115,048 ( 0.10%) } . . /// Insert a key-value pair into the map without checking . /// if the key already exists in the map. . /// . /// Returns a reference to the key and value just inserted. . /// . /// This operation is safe if a key does not exist in the map. . /// -- line 1520 ---------------------------------------- -- line 1592 ---------------------------------------- . /// use hashbrown::HashMap; . /// . /// let mut map = HashMap::new(); . /// map.insert(1, "a"); . /// assert_eq!(map.remove(&1), Some("a")); . /// assert_eq!(map.remove(&1), None); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 1,225,779 ( 0.00%) pub fn remove(&mut self, k: &Q) -> Option . where . K: Borrow, . Q: Hash + Eq, . { . // Avoid `Option::map` because it bloats LLVM IR. 6,573,277 ( 0.02%) match self.remove_entry(k) { 379,335 ( 0.00%) Some((_, v)) => Some(v), 1,119,267 ( 0.00%) None => None, . } 2,738,618 ( 0.01%) } . . /// Removes a key from the map, returning the stored key and value if the . /// key was previously in the map. . /// . /// The key may be any borrowed form of the map's key type, but . /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for . /// the key type. . /// -- line 1618 ---------------------------------------- -- line 1631 ---------------------------------------- . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn remove_entry(&mut self, k: &Q) -> Option<(K, V)> . where . K: Borrow, . Q: Hash + Eq, . { . let hash = make_hash::(&self.hash_builder, k); 2,829,858 ( 0.01%) self.table.remove_entry(hash, equivalent_key(k)) . } . } . . impl HashMap { . /// Creates a raw entry builder for the HashMap. . /// . /// Raw entries provide the lowest level of control for searching and . /// manipulating a map. They must be manually initialized with a hash and -- line 1647 ---------------------------------------- -- line 1737 ---------------------------------------- . . impl Default for HashMap . where . S: Default, . A: Default + Allocator + Clone, . { . /// Creates an empty `HashMap`, with the `Default` value for the hasher and allocator. . #[cfg_attr(feature = "inline-more", inline)] 2,970 ( 0.00%) fn default() -> Self { 10,890 ( 0.00%) Self::with_hasher_in(Default::default(), Default::default()) 1,980 ( 0.00%) } . } . . impl Index<&Q> for HashMap . where . K: Eq + Hash + Borrow, . Q: Eq + Hash, . S: BuildHasher, . A: Allocator + Clone, -- line 1755 ---------------------------------------- -- line 2209 ---------------------------------------- . /// Creates a `RawEntryMut` from the given key and its hash. . #[inline] . #[allow(clippy::wrong_self_convention)] . pub fn from_key_hashed_nocheck(self, hash: u64, k: &Q) -> RawEntryMut<'a, K, V, S, A> . where . K: Borrow, . Q: Eq, . { 32,457,394 ( 0.09%) self.from_hash(hash, equivalent(k)) . } . } . . impl<'a, K, V, S, A: Allocator + Clone> RawEntryBuilderMut<'a, K, V, S, A> { . /// Creates a `RawEntryMut` from the given hash. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::wrong_self_convention)] 80,070,735 ( 0.23%) pub fn from_hash(self, hash: u64, is_match: F) -> RawEntryMut<'a, K, V, S, A> . where . for<'b> F: FnMut(&'b K) -> bool, . { . self.search(hash, is_match) 86,882,319 ( 0.25%) } . . #[cfg_attr(feature = "inline-more", inline)] . fn search(self, hash: u64, mut is_match: F) -> RawEntryMut<'a, K, V, S, A> . where . for<'b> F: FnMut(&'b K) -> bool, . { 10,121,132 ( 0.03%) match self.map.table.find(hash, |(k, _)| is_match(k)) { 54,472,589 ( 0.16%) Some(elem) => RawEntryMut::Occupied(RawOccupiedEntryMut { . elem, . table: &mut self.map.table, . hash_builder: &self.map.hash_builder, . }), 2,289,041 ( 0.01%) None => RawEntryMut::Vacant(RawVacantEntryMut { . table: &mut self.map.table, . hash_builder: &self.map.hash_builder, . }), . } . } . } . . impl<'a, K, V, S, A: Allocator + Clone> RawEntryBuilder<'a, K, V, S, A> { -- line 2251 ---------------------------------------- -- line 2260 ---------------------------------------- . { . let hash = make_hash::(&self.map.hash_builder, k); . self.from_key_hashed_nocheck(hash, k) . } . . /// Access an entry by a key and its hash. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::wrong_self_convention)] 16,629,512 ( 0.05%) pub fn from_key_hashed_nocheck(self, hash: u64, k: &Q) -> Option<(&'a K, &'a V)> . where . K: Borrow, . Q: Eq, . { 20,308,004 ( 0.06%) self.from_hash(hash, equivalent(k)) 30,493,327 ( 0.09%) } . . #[cfg_attr(feature = "inline-more", inline)] . fn search(self, hash: u64, mut is_match: F) -> Option<(&'a K, &'a V)> . where . F: FnMut(&K) -> bool, . { 31,133,389 ( 0.09%) match self.map.table.get(hash, |(k, _)| is_match(k)) { . Some(&(ref key, ref value)) => Some((key, value)), . None => None, . } . } . . /// Access an entry by hash. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::wrong_self_convention)] -- line 2289 ---------------------------------------- -- line 2624 ---------------------------------------- . /// and returns a mutable reference to it. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::shadow_unrelated)] . pub fn insert_hashed_nocheck(self, hash: u64, key: K, value: V) -> (&'a mut K, &'a mut V) . where . K: Hash, . S: BuildHasher, . { 3,811,665 ( 0.01%) let &mut (ref mut k, ref mut v) = self.table.insert_entry( . hash, . (key, value), . make_hasher::(self.hash_builder), . ); . (k, v) . } . . /// Set the value of an entry with a custom hasher function. -- line 2640 ---------------------------------------- -- line 2974 ---------------------------------------- . /// map.insert("a", 1); . /// map.insert("b", 2); . /// map.insert("c", 3); . /// . /// // Not possible with .iter() . /// let vec: Vec<(&str, i32)> = map.into_iter().collect(); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 30,313 ( 0.00%) fn into_iter(self) -> IntoIter { 534,004 ( 0.00%) IntoIter { 255,067 ( 0.00%) inner: self.table.into_iter(), . } 90,939 ( 0.00%) } . } . . impl<'a, K, V> Iterator for Iter<'a, K, V> { . type Item = (&'a K, &'a V); . . #[cfg_attr(feature = "inline-more", inline)] . fn next(&mut self) -> Option<(&'a K, &'a V)> { . // Avoid `Option::map` because it bloats LLVM IR. 3,200,658 ( 0.01%) match self.inner.next() { . Some(x) => unsafe { . let r = x.as_ref(); 17,850 ( 0.00%) Some((&r.0, &r.1)) . }, . None => None, . } . } . #[cfg_attr(feature = "inline-more", inline)] . fn size_hint(&self) -> (usize, Option) { 418 ( 0.00%) self.inner.size_hint() . } . } . impl ExactSizeIterator for Iter<'_, K, V> { . #[cfg_attr(feature = "inline-more", inline)] . fn len(&self) -> usize { . self.inner.len() . } . } -- line 3013 ---------------------------------------- -- line 3051 ---------------------------------------- . } . } . . impl Iterator for IntoIter { . type Item = (K, V); . . #[cfg_attr(feature = "inline-more", inline)] . fn next(&mut self) -> Option<(K, V)> { 21,132 ( 0.00%) self.inner.next() . } . #[cfg_attr(feature = "inline-more", inline)] . fn size_hint(&self) -> (usize, Option) { . self.inner.size_hint() . } . } . impl ExactSizeIterator for IntoIter { . #[cfg_attr(feature = "inline-more", inline)] -- line 3067 ---------------------------------------- -- line 3076 ---------------------------------------- . f.debug_list().entries(self.iter()).finish() . } . } . . impl<'a, K, V> Iterator for Keys<'a, K, V> { . type Item = &'a K; . . #[cfg_attr(feature = "inline-more", inline)] 1,651 ( 0.00%) fn next(&mut self) -> Option<&'a K> { . // Avoid `Option::map` because it bloats LLVM IR. . match self.inner.next() { . Some((k, _)) => Some(k), . None => None, . } 3,302 ( 0.00%) } . #[cfg_attr(feature = "inline-more", inline)] . fn size_hint(&self) -> (usize, Option) { . self.inner.size_hint() . } . } . impl ExactSizeIterator for Keys<'_, K, V> { . #[cfg_attr(feature = "inline-more", inline)] . fn len(&self) -> usize { -- line 3098 ---------------------------------------- -- line 3819 ---------------------------------------- . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn insert(self, value: V) -> &'a mut V . where . K: Hash, . S: BuildHasher, . { . let table = &mut self.table.table; 538 ( 0.00%) let entry = table.insert_entry( . self.hash, . (self.key, value), . make_hasher::(&self.table.hash_builder), . ); . &mut entry.1 . } . . #[cfg_attr(feature = "inline-more", inline)] -- line 3835 ---------------------------------------- -- line 4557 ---------------------------------------- . /// keys with new values returned from the iterator. . impl Extend<(K, V)> for HashMap . where . K: Eq + Hash, . S: BuildHasher, . A: Allocator + Clone, . { . #[cfg_attr(feature = "inline-more", inline)] 454,545 ( 0.00%) fn extend>(&mut self, iter: T) { . // Keys may be already present or show multiple times in the iterator. . // Reserve the entire hint lower bound if the map is empty. . // Otherwise reserve half the hint (rounded up), so the map . // will only resize twice in the worst case. 369,294 ( 0.00%) let iter = iter.into_iter(); 351,531 ( 0.00%) let reserve = if self.is_empty() { 3,960 ( 0.00%) iter.size_hint().0 . } else { 26,619 ( 0.00%) (iter.size_hint().0 + 1) / 2 . }; 2,970 ( 0.00%) self.reserve(reserve); 6,984 ( 0.00%) iter.for_each(move |(k, v)| { 1,017,503 ( 0.00%) self.insert(k, v); 18 ( 0.00%) }); 278,015 ( 0.00%) } . . #[inline] . #[cfg(feature = "nightly")] . fn extend_one(&mut self, (k, v): (K, V)) { . self.insert(k, v); . } . . #[inline] -- line 4588 ---------------------------------------- 33,559,386 ( 0.10%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/server.rs -------------------------------------------------------------------------------- Ir -- line 28 ---------------------------------------- . (type SourceFile: 'static + Clone;); . (type MultiSpan) => . (type MultiSpan: 'static;); . (type Diagnostic) => . (type Diagnostic: 'static;); . (type Span) => . (type Span: 'static + Copy + Eq + Hash;); . (fn drop(&mut self, $arg:ident: $arg_ty:ty)) => 403,380 ( 0.00%) (fn drop(&mut self, $arg: $arg_ty) { mem::drop($arg) }); . (fn clone(&mut self, $arg:ident: $arg_ty:ty) -> $ret_ty:ty) => 34,481 ( 0.00%) (fn clone(&mut self, $arg: $arg_ty) -> $ret_ty { $arg.clone() }); . ($($item:tt)*) => ($($item)*;) . } . . macro_rules! declare_server_traits { . ($($name:ident { . $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)?;)* . }),* $(,)?) => { . pub trait Types { -- line 46 ---------------------------------------- -- line 63 ---------------------------------------- . ($($name:ident { . $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)?;)* . }),* $(,)?) => { . impl Types for MarkedTypes { . $(type $name = Marked;)* . } . . $(impl $name for MarkedTypes { 9,594 ( 0.00%) $(fn $method(&mut self, $($arg: $arg_ty),*) $(-> $ret_ty)? { 18,646,408 ( 0.05%) <_>::mark($name::$method(&mut self.0, $($arg.unmark()),*)) 9,594 ( 0.00%) })* . })* . } . } . with_api!(Self, self_, define_mark_types_impls); . . struct Dispatcher { . handle_store: HandleStore, . server: S, -- line 81 ---------------------------------------- -- line 89 ---------------------------------------- . pub trait DispatcherTrait { . // HACK(eddyb) these are here to allow `Self::$name` to work below. . $(type $name;)* . fn dispatch(&mut self, b: Buffer) -> Buffer; . } . . impl DispatcherTrait for Dispatcher> { . $(type $name = as Types>::$name;)* 45,290,910 ( 0.13%) fn dispatch(&mut self, mut b: Buffer) -> Buffer { . let Dispatcher { handle_store, server } = self; . 13,587,273 ( 0.04%) let mut reader = &b[..]; 31,703,637 ( 0.09%) match api_tags::Method::decode(&mut reader, &mut ()) { 21,782,226 ( 0.06%) $(api_tags::Method::$name(m) => match m { . $(api_tags::$name::$method => { . let mut call_method = || { 14,518,296 ( 0.04%) reverse_decode!(reader, handle_store; $($arg: $arg_ty),*); 4,797 ( 0.00%) $name::$method(server, $($arg),*) . }; . // HACK(eddyb) don't use `panic::catch_unwind` in a panic. . // If client and server happen to use the same `libstd`, . // `catch_unwind` asserts that the panic counter was 0, . // even when the closure passed to it didn't panic. . let r = if thread::panicking() { . Ok(call_method()) . } else { 20,278,007 ( 0.06%) panic::catch_unwind(panic::AssertUnwindSafe(call_method)) . .map_err(PanicMessage::from) . }; . . b.clear(); 49,969,631 ( 0.14%) r.encode(&mut b, handle_store); . })* . }),* . } 27,174,546 ( 0.08%) b 40,761,819 ( 0.12%) } . } . } . } . with_api!(Self, self_, define_dispatcher_impl); . . pub trait ExecutionStrategy { . fn run_bridge_and_client( . &self, -- line 133 ---------------------------------------- -- line 145 ---------------------------------------- . fn run_bridge_and_client( . &self, . dispatcher: &mut impl DispatcherTrait, . input: Buffer, . run_client: extern "C" fn(Bridge<'_>, D) -> Buffer, . client_data: D, . force_show_panics: bool, . ) -> Buffer { 40,762,479 ( 0.12%) let mut dispatch = |b| dispatcher.dispatch(b); . 6,600 ( 0.00%) run_client( 7,260 ( 0.00%) Bridge { cached_buffer: input, dispatch: (&mut dispatch).into(), force_show_panics }, . client_data, . ) . } . } . . // NOTE(eddyb) Two implementations are provided, the second one is a bit . // faster but neither is anywhere near as fast as same-thread execution. . -- line 164 ---------------------------------------- -- line 263 ---------------------------------------- . *state.lock().unwrap() = State::Res(b); . join_handle.thread().unpark(); . } . . join_handle.join().unwrap() . } . } . 8,580 ( 0.00%) fn run_server< . S: Server, . I: Encode>>, . O: for<'a, 's> DecodeMut<'a, 's, HandleStore>>, . D: Copy + Send + 'static, . >( . strategy: &impl ExecutionStrategy, . handle_counters: &'static client::HandleCounters, . server: S, . input: I, . run_client: extern "C" fn(Bridge<'_>, D) -> Buffer, . client_data: D, . force_show_panics: bool, . ) -> Result { . let mut dispatcher = 11,220 ( 0.00%) Dispatcher { handle_store: HandleStore::new(handle_counters), server: MarkedTypes(server) }; . . let mut b = Buffer::new(); 1,980 ( 0.00%) input.encode(&mut b, &mut dispatcher.handle_store); . 3,960 ( 0.00%) b = strategy.run_bridge_and_client( . &mut dispatcher, . b, . run_client, . client_data, . force_show_panics, . ); . 3,300 ( 0.00%) Result::decode(&mut &b[..], &mut dispatcher.handle_store) 6,600 ( 0.00%) } . . impl client::Client crate::TokenStream> { . pub fn run( . &self, . strategy: &impl ExecutionStrategy, . server: S, . input: S::TokenStream, . force_show_panics: bool, . ) -> Result { 1,320 ( 0.00%) let client::Client { get_handle_counters, run, f } = *self; 7,260 ( 0.00%) run_server( . strategy, 660 ( 0.00%) get_handle_counters(), 6,600 ( 0.00%) server, . as Types>::TokenStream::mark(input), . run, . f, . force_show_panics, . ) . .map( as Types>::TokenStream::unmark) . } . } -- line 322 ---------------------------------------- 10,253,290 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/rpc.rs -------------------------------------------------------------------------------- Ir -- line 21 ---------------------------------------- . . pub(super) trait DecodeMut<'a, 's, S>: Sized { . fn decode(r: &mut Reader<'a>, s: &'s mut S) -> Self; . } . . macro_rules! rpc_encode_decode { . (le $ty:ty) => { . impl Encode for $ty { 25,070,880 ( 0.07%) fn encode(self, w: &mut Writer, _: &mut S) { 3,960 ( 0.00%) w.extend_from_array(&self.to_le_bytes()); 31,335,795 ( 0.09%) } . } . . impl DecodeMut<'_, '_, S> for $ty { 2,640 ( 0.00%) fn decode(r: &mut Reader<'_>, _: &mut S) -> Self { . const N: usize = ::std::mem::size_of::<$ty>(); . 3,300 ( 0.00%) let mut bytes = [0; N]; 3,992,073 ( 0.01%) bytes.copy_from_slice(&r[..N]); 16,595,228 ( 0.05%) *r = &r[N..]; . 3,300 ( 0.00%) Self::from_le_bytes(bytes) 1,320 ( 0.00%) } . } . }; . (struct $name:ident { $($field:ident),* $(,)? }) => { . impl Encode for $name { . fn encode(self, w: &mut Writer, s: &mut S) { . $(self.$field.encode(w, s);)* . } . } -- line 51 ---------------------------------------- -- line 55 ---------------------------------------- . $name { . $($field: DecodeMut::decode(r, s)),* . } . } . } . }; . (enum $name:ident $(<$($T:ident),+>)? { $($variant:ident $(($field:ident))*),* $(,)? }) => { . impl),+)?> Encode for $name $(<$($T),+>)? { 69,792,319 ( 0.20%) fn encode(self, w: &mut Writer, s: &mut S) { . // HACK(eddyb): `Tag` enum duplicated between the . // two impls as there's no other place to stash it. . #[allow(non_upper_case_globals)] . mod tag { . #[repr(u8)] enum Tag { $($variant),* } . . $(pub const $variant: u8 = Tag::$variant as u8;)* . } . 38,213,455 ( 0.11%) match self { 7,725,182 ( 0.02%) $($name::$variant $(($field))* => { 581,681 ( 0.00%) tag::$variant.encode(w, s); 8,778,790 ( 0.03%) $($field.encode(w, s);)* 1,320 ( 0.00%) })* . } 54,851,528 ( 0.16%) } . } . . impl<'a, S, $($($T: for<'s> DecodeMut<'a, 's, S>),+)?> DecodeMut<'a, '_, S> . for $name $(<$($T),+>)? . { 17,988,200 ( 0.05%) fn decode(r: &mut Reader<'a>, s: &mut S) -> Self { . // HACK(eddyb): `Tag` enum duplicated between the . // two impls as there's no other place to stash it. . #[allow(non_upper_case_globals)] . mod tag { . #[repr(u8)] enum Tag { $($variant),* } . . $(pub const $variant: u8 = Tag::$variant as u8;)* . } . 17,255,344 ( 0.05%) match u8::decode(r, s) { . $(tag::$variant => { 352,584 ( 0.00%) $(let $field = DecodeMut::decode(r, s);)* 12,443,670 ( 0.04%) $name::$variant $(($field))* 175,302 ( 0.00%) })* . _ => unreachable!(), . } 31,199,554 ( 0.09%) } . } . } . } . . impl Encode for () { . fn encode(self, _: &mut Writer, _: &mut S) {} . } . . impl DecodeMut<'_, '_, S> for () { . fn decode(_: &mut Reader<'_>, _: &mut S) -> Self {} . } . . impl Encode for u8 { 3,727,164 ( 0.01%) fn encode(self, w: &mut Writer, _: &mut S) { 1,320 ( 0.00%) w.push(self); 3,103,440 ( 0.01%) } . } . . impl DecodeMut<'_, '_, S> for u8 { . fn decode(r: &mut Reader<'_>, _: &mut S) -> Self { 69,808,853 ( 0.20%) let x = r[0]; 38,720,398 ( 0.11%) *r = &r[1..]; . x . } . } . . rpc_encode_decode!(le u32); . rpc_encode_decode!(le usize); . . impl Encode for bool { . fn encode(self, w: &mut Writer, s: &mut S) { 680,025 ( 0.00%) (self as u8).encode(w, s); . } . } . . impl DecodeMut<'_, '_, S> for bool { . fn decode(r: &mut Reader<'_>, s: &mut S) -> Self { 454,362 ( 0.00%) match u8::decode(r, s) { . 0 => false, . 1 => true, . _ => unreachable!(), . } . } . } . . impl Encode for char { . fn encode(self, w: &mut Writer, s: &mut S) { 663,090 ( 0.00%) (self as u32).encode(w, s); . } . } . . impl DecodeMut<'_, '_, S> for char { . fn decode(r: &mut Reader<'_>, s: &mut S) -> Self { . char::from_u32(u32::decode(r, s)).unwrap() . } . } . . impl Encode for NonZeroU32 { 3,960 ( 0.00%) fn encode(self, w: &mut Writer, s: &mut S) { 17,593,961 ( 0.05%) self.get().encode(w, s); 1,320 ( 0.00%) } . } . . impl DecodeMut<'_, '_, S> for NonZeroU32 { 1,980 ( 0.00%) fn decode(r: &mut Reader<'_>, s: &mut S) -> Self { 4,620 ( 0.00%) Self::new(u32::decode(r, s)).unwrap() 1,320 ( 0.00%) } . } . . impl, B: Encode> Encode for (A, B) { . fn encode(self, w: &mut Writer, s: &mut S) { . self.0.encode(w, s); . self.1.encode(w, s); . } . } -- line 177 ---------------------------------------- -- line 204 ---------------------------------------- . Ok(x), . Err(e), . } . ); . . impl Encode for &[u8] { . fn encode(self, w: &mut Writer, s: &mut S) { . self.len().encode(w, s); 513,360 ( 0.00%) w.write_all(self).unwrap(); . } . } . . impl<'a, S> DecodeMut<'a, '_, S> for &'a [u8] { . fn decode(r: &mut Reader<'a>, s: &mut S) -> Self { . let len = usize::decode(r, s); . let xs = &r[..len]; 1,095,911 ( 0.00%) *r = &r[len..]; . xs . } . } . . impl Encode for &str { 513,360 ( 0.00%) fn encode(self, w: &mut Writer, s: &mut S) { . self.as_bytes().encode(w, s); 641,700 ( 0.00%) } . } . . impl<'a, S> DecodeMut<'a, '_, S> for &'a str { 364,847 ( 0.00%) fn decode(r: &mut Reader<'a>, s: &mut S) -> Self { 729,694 ( 0.00%) str::from_utf8(<&[u8]>::decode(r, s)).unwrap() 729,694 ( 0.00%) } . } . . impl Encode for String { . fn encode(self, w: &mut Writer, s: &mut S) { 513,360 ( 0.00%) self[..].encode(w, s); . } . } . . impl DecodeMut<'_, '_, S> for String { . fn decode(r: &mut Reader<'_>, s: &mut S) -> Self { 641,700 ( 0.00%) <&str>::decode(r, s).to_string() . } . } . . /// Simplified version of panic payloads, ignoring . /// types other than `&'static str` and `String`. . pub enum PanicMessage { . StaticStr(&'static str), . String(String), -- line 253 ---------------------------------------- 65,378,686 ( 0.19%) -------------------------------------------------------------------------------- -- 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 { 125,089 ( 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 { 26,676 ( 0.00%) pub fn new() -> Self { . let linewidth = 78; 2,492,861 ( 0.01%) 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, . } 33,345 ( 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) { 117,824 ( 0.00%) if !self.scan_stack.is_empty() { 1,826 ( 0.00%) self.check_stack(0); 1,826 ( 0.00%) self.advance_left(); . } . } . . fn scan_begin(&mut self, token: BeginToken) { 300,675 ( 0.00%) if self.scan_stack.is_empty() { 113,692 ( 0.00%) self.left_total = 1; . self.right_total = 1; . self.buf.clear(); . } 1,202,700 ( 0.00%) 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) { 297,435 ( 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) { 175,459 ( 0.00%) if self.scan_stack.is_empty() { 214,222 ( 0.00%) self.left_total = 1; . self.right_total = 1; . self.buf.clear(); . } else { 136,696 ( 0.00%) self.check_stack(0); . } 701,836 ( 0.00%) let right = self.buf.push(BufEntry { token: Token::Break(token), size: -self.right_total }); . self.scan_stack.push_back(right); 526,377 ( 0.00%) self.right_total += token.blank_space; . } . 7,251,831 ( 0.02%) fn scan_string(&mut self, string: Cow<'static, str>) { 805,759 ( 0.00%) if self.scan_stack.is_empty() { . self.print_string(&string); . } else { . let len = string.len() as isize; 408,739 ( 0.00%) self.buf.push(BufEntry { token: Token::String(string), size: len }); 1,226,217 ( 0.00%) self.right_total += len; . self.check_stream(); . } 4,928,552 ( 0.01%) } . . fn check_stream(&mut self) { 2,978,321 ( 0.01%) while self.right_total - self.left_total > self.space { 1,295,151 ( 0.00%) if *self.scan_stack.front().unwrap() == self.buf.index_of_first() { . self.scan_stack.pop_front().unwrap(); 418,886 ( 0.00%) self.buf.first_mut().unwrap().size = SIZE_INFINITY; . } 863,434 ( 0.00%) self.advance_left(); 431,717 ( 0.00%) if self.buf.is_empty() { . break; . } . } . } . 8,332,471 ( 0.02%) fn advance_left(&mut self) { 2,492,868 ( 0.01%) while self.buf.first().unwrap().size >= 0 { 2,933,283 ( 0.01%) let left = self.buf.pop_first().unwrap(); . . match &left.token { . Token::String(string) => { 1,226,217 ( 0.00%) self.left_total += string.len() as isize; . self.print_string(string); . } . Token::Break(token) => { 526,377 ( 0.00%) self.left_total += token.blank_space; . self.print_break(*token, left.size); . } 772,383 ( 0.00%) Token::Begin(token) => self.print_begin(*token, left.size), . Token::End => self.print_end(), . } . 7,822,088 ( 0.02%) self.last_printed = Some(left.token); . 977,761 ( 0.00%) if self.buf.is_empty() { . break; . } . } 3,461,040 ( 0.01%) } . 623,349 ( 0.00%) fn check_stack(&mut self, mut depth: usize) { 379,463 ( 0.00%) while let Some(&index) = self.scan_stack.back() { . let mut entry = &mut self.buf[index]; 758,469 ( 0.00%) match entry.token { . Token::Begin(_) => { 150,146 ( 0.00%) if depth == 0 { . break; . } . self.scan_stack.pop_back().unwrap(); 130,458 ( 0.00%) entry.size += self.right_total; 43,486 ( 0.00%) depth -= 1; . } . Token::End => { . // paper says + not =, but that makes no sense. . self.scan_stack.pop_back().unwrap(); 65,796 ( 0.00%) entry.size = 1; 131,592 ( 0.00%) depth += 1; . } . _ => { . self.scan_stack.pop_back().unwrap(); 122,562 ( 0.00%) entry.size += self.right_total; 103,365 ( 0.00%) if depth == 0 { . break; . } . } . } . } 554,088 ( 0.00%) } . . fn get_top(&self) -> PrintFrame { 526,377 ( 0.00%) *self . .print_stack . .last() . .unwrap_or(&PrintFrame::Broken { offset: 0, breaks: Breaks::Inconsistent }) . } . . fn print_begin(&mut self, token: BeginToken, size: isize) { 902,025 ( 0.00%) if size > self.space { 1,287,305 ( 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 = 846,172 ( 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'); 428,523 ( 0.00%) self.pending_indentation = offset + token.offset; 571,364 ( 0.00%) self.space = self.margin - (offset + token.offset); . } else { 97,854 ( 0.00%) self.pending_indentation += token.blank_space; 130,472 ( 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. 805,759 ( 0.00%) self.out.reserve(self.pending_indentation as usize); 3,828 ( 0.00%) self.out.extend(iter::repeat(' ').take(self.pending_indentation as usize)); 805,759 ( 0.00%) self.pending_indentation = 0; . . self.out.push_str(string); 3,631,775 ( 0.01%) self.space -= string.len() as isize; . } . . // Convenience functions to talk to the printer. . . /// "raw box" 394,512 ( 0.00%) pub fn rbox(&mut self, indent: usize, breaks: Breaks) { . self.scan_begin(BeginToken { offset: indent as isize, breaks }) 295,884 ( 0.00%) } . . /// Inconsistent breaking box 1,268,946 ( 0.00%) pub fn ibox(&mut self, indent: usize) { . self.rbox(indent, Breaks::Inconsistent) 1,057,455 ( 0.00%) } . . /// Consistent breaking box 239,220 ( 0.00%) pub fn cbox(&mut self, indent: usize) { . self.rbox(indent, Breaks::Consistent) 199,350 ( 0.00%) } . 1,403,672 ( 0.00%) pub fn break_offset(&mut self, n: usize, off: isize) { . self.scan_break(BreakToken { offset: off, blank_space: n as isize }) 1,052,754 ( 0.00%) } . 1,189,740 ( 0.00%) pub fn end(&mut self) { . self.scan_end() 1,189,740 ( 0.00%) } . 589,120 ( 0.00%) pub fn eof(mut self) -> String { . self.scan_eof(); 471,296 ( 0.00%) self.out 589,120 ( 0.00%) } . . pub fn word>>(&mut self, wrd: S) { . let string = wrd.into(); 5,706,844 ( 0.02%) self.scan_string(string) . } . . fn spaces(&mut self, n: usize) { 491,250 ( 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) . } . 24,231 ( 0.00%) pub fn is_beginning_of_line(&self) -> bool { 124,202 ( 0.00%) match self.last_token() { . Some(last_token) => last_token.is_hardbreak_tok(), . None => true, . } 48,462 ( 0.00%) } . . pub fn hardbreak_tok_offset(off: isize) -> Token { . Token::Break(BreakToken { offset: off, blank_space: SIZE_INFINITY }) . } . } 9,096,811 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/remove.rs -------------------------------------------------------------------------------- Ir . use super::map::MIN_LEN; . use super::node::{marker, ForceResult::*, Handle, LeftOrRight::*, NodeRef}; . . impl<'a, K: 'a, V: 'a> Handle, K, V, marker::LeafOrInternal>, marker::KV> { . /// Removes a key-value pair from the tree, and returns that pair, as well as . /// the leaf edge corresponding to that former pair. It's possible this empties . /// a root node that is internal, which the caller should pop from the map . /// holding the tree. The caller should also decrement the map's length. 8,151,161 ( 0.02%) pub fn remove_kv_tracking( . self, . handle_emptied_internal_root: F, . ) -> ((K, V), Handle, K, V, marker::Leaf>, marker::Edge>) { 6,488,572 ( 0.02%) match self.force() { 11,324,138 ( 0.03%) Leaf(node) => node.remove_leaf_kv(handle_emptied_internal_root), . Internal(node) => node.remove_internal_kv(handle_emptied_internal_root), . } 9,773,304 ( 0.03%) } . } . . impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Leaf>, marker::KV> { 11,355,001 ( 0.03%) fn remove_leaf_kv( . self, . handle_emptied_internal_root: F, . ) -> ((K, V), Handle, K, V, marker::Leaf>, marker::Edge>) { 7,480,818 ( 0.02%) let (old_kv, mut pos) = self.remove(); . let len = pos.reborrow().into_node().len(); 3,244,286 ( 0.01%) if len < MIN_LEN { . let idx = pos.idx(); . // We have to temporarily forget the child type, because there is no . // distinct node type for the immediate parents of a leaf. . let new_pos = match pos.into_node().forget_type().choose_parent_kv() { . Ok(Left(left_parent_kv)) => { . debug_assert!(left_parent_kv.right_child_len() == MIN_LEN - 1); 167,224 ( 0.00%) if left_parent_kv.can_merge() { 2,268,389 ( 0.01%) left_parent_kv.merge_tracking_child_edge(Right(idx)) . } else { . debug_assert!(left_parent_kv.left_child_len() > MIN_LEN); 41,528 ( 0.00%) left_parent_kv.steal_left(idx) . } . } . Ok(Right(right_parent_kv)) => { . debug_assert!(right_parent_kv.left_child_len() == MIN_LEN - 1); 5,716 ( 0.00%) if right_parent_kv.can_merge() { 39,777 ( 0.00%) right_parent_kv.merge_tracking_child_edge(Left(idx)) . } else { . debug_assert!(right_parent_kv.right_child_len() > MIN_LEN); 24,307 ( 0.00%) right_parent_kv.steal_right(idx) . } . } . Err(pos) => unsafe { Handle::new_edge(pos, idx) }, . }; . // SAFETY: `new_pos` is the leaf we started from or a sibling. 2,019,672 ( 0.01%) pos = unsafe { new_pos.cast_to_leaf_unchecked() }; . . // Only if we merged, the parent (if any) has shrunk, but skipping . // the following step otherwise does not pay off in benchmarks. . // . // SAFETY: We won't destroy or rearrange the leaf where `pos` is at . // by handling its parent recursively; at worst we will destroy or . // rearrange the parent through the grandparent, thus change the . // link to the parent inside the leaf. . if let Ok(parent) = unsafe { pos.reborrow_mut() }.into_node().ascend() { 151,359 ( 0.00%) if !parent.into_node().forget_type().fix_node_and_affected_ancestors() { . handle_emptied_internal_root(); . } . } . } 12,978,664 ( 0.04%) (old_kv, pos) 12,977,144 ( 0.04%) } . } . . impl<'a, K: 'a, V: 'a> Handle, K, V, marker::Internal>, marker::KV> { . fn remove_internal_kv( . self, . handle_emptied_internal_root: F, . ) -> ((K, V), Handle, K, V, marker::Leaf>, marker::Edge>) { . // Remove an adjacent KV from its leaf and then put it back in place of . // the element we were asked to remove. Prefer the left adjacent KV, . // for the reasons listed in `choose_parent_kv`. . let left_leaf_kv = self.left_edge().descend().last_leaf_edge().left_kv(); . let left_leaf_kv = unsafe { left_leaf_kv.ok().unwrap_unchecked() }; 64,893 ( 0.00%) let (left_kv, left_hole) = left_leaf_kv.remove_leaf_kv(handle_emptied_internal_root); . . // The internal node may have been stolen from or merged. Go back right . // to find where the original KV ended up. . let mut internal = unsafe { left_hole.next_kv().ok().unwrap_unchecked() }; 593 ( 0.00%) let old_kv = internal.replace_kv(left_kv.0, left_kv.1); . let pos = internal.next_leaf_edge(); 32,759 ( 0.00%) (old_kv, pos) . } . } 8,727,363 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs -------------------------------------------------------------------------------- Ir -- line 36 ---------------------------------------- . use rustc_session::parse::ParseSess; . use rustc_span::source_map::{MultiSpan, Span, DUMMY_SP}; . use rustc_span::symbol::{kw, sym, Ident, Symbol}; . use tracing::debug; . . use std::ops::Range; . use std::{cmp, mem, slice}; . 273,849 ( 0.00%) bitflags::bitflags! { . struct Restrictions: u8 { . const STMT_EXPR = 1 << 0; . const NO_STRUCT_LITERAL = 1 << 1; . const CONST_EXPR = 1 << 2; . } . } . . #[derive(Clone, Copy, PartialEq, Debug)] -- line 52 ---------------------------------------- -- line 104 ---------------------------------------- . $self.bump(); . return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_token.span, ty); . } . } . } . }; . } . 693,607 ( 0.00%) #[derive(Clone)] . pub struct Parser<'a> { 23,647 ( 0.00%) pub sess: &'a ParseSess, . /// The current token. 16,800 ( 0.00%) pub token: Token, . /// The spacing for the current token 11,405 ( 0.00%) pub token_spacing: Spacing, . /// The previous token. 25,200 ( 0.00%) pub prev_token: Token, 14,410 ( 0.00%) pub capture_cfg: bool, 31,825 ( 0.00%) restrictions: Restrictions, 22,810 ( 0.00%) expected_tokens: Vec, . // Important: This must only be advanced from `next_tok` . // to ensure that `token_cursor.num_next_calls` is updated properly . token_cursor: TokenCursor, 22,810 ( 0.00%) desugar_doc_comments: bool, . /// This field is used to keep track of how many left angle brackets we have seen. This is . /// required in order to detect extra leading left angle brackets (`<` characters) and error . /// appropriately. . /// . /// See the comments in the `parse_path_segment` function for more details. 22,810 ( 0.00%) unmatched_angle_bracket_count: u32, 34,215 ( 0.00%) max_angle_bracket_count: u32, . /// A list of all unclosed delimiters found by the lexer. If an entry is used for error recovery . /// it gets removed from here. Every entry left at the end gets emitted as an independent . /// error. 11,405 ( 0.00%) pub(super) unclosed_delims: Vec, . last_unexpected_token_span: Option, . /// Span pointing at the `:` for the last type ascription the parser has seen, and whether it . /// looked like it could have been a mistyped path or literal `Option:Some(42)`). . pub last_type_ascription: Option<(Span, bool /* likely path typo */)>, . /// If present, this `Parser` is not parsing Rust code but rather a macro call. . subparser_name: Option<&'static str>, . capture_state: CaptureState, . /// This allows us to recover when the user forget to add braces around -- line 146 ---------------------------------------- -- line 173 ---------------------------------------- . /// the first macro inner attribute to invoke a proc-macro). . /// When create a `TokenStream`, the inner attributes get inserted . /// into the proper place in the token stream. . pub type ReplaceRange = (Range, Vec<(FlatToken, Spacing)>); . . /// Controls how we capture tokens. Capturing can be expensive, . /// so we try to avoid performing capturing in cases where . /// we will never need an `AttrAnnotatedTokenStream` 11,405 ( 0.00%) #[derive(Copy, Clone)] . pub enum Capturing { . /// We aren't performing any capturing - this is the default mode. . No, . /// We are capturing tokens . Yes, . } . 49,462 ( 0.00%) #[derive(Clone)] . struct CaptureState { 45,620 ( 0.00%) capturing: Capturing, 11,405 ( 0.00%) replace_ranges: Vec, . inner_attr_ranges: FxHashMap, . } . . impl<'a> Drop for Parser<'a> { . fn drop(&mut self) { 80,653 ( 0.00%) emit_unclosed_delims(&mut self.unclosed_delims, &self.sess); . } . } . 1,319,168 ( 0.00%) #[derive(Clone)] . struct TokenCursor { . frame: TokenCursorFrame, 295,736 ( 0.00%) stack: Vec, . desugar_doc_comments: bool, . // Counts the number of calls to `next` or `next_desugared`, . // depending on whether `desugar_doc_comments` is set. 96,288 ( 0.00%) num_next_calls: usize, . // During parsing, we may sometimes need to 'unglue' a . // glued token into two component tokens . // (e.g. '>>' into '>' and '>), so that the parser . // can consume them one at a time. This process . // bypasses the normal capturing mechanism . // (e.g. `num_next_calls` will not be incremented), . // since the 'unglued' tokens due not exist in . // the original `TokenStream`. -- line 217 ---------------------------------------- -- line 226 ---------------------------------------- . // in `Option>` requires us to unglue . // the trailing `>>` token. The `break_last_token` . // field is used to track this token - it gets . // appended to the captured stream when . // we evaluate a `LazyTokenStream` . break_last_token: bool, . } . 595,022 ( 0.00%) #[derive(Clone)] . struct TokenCursorFrame { 212,054 ( 0.00%) delim: token::DelimToken, . span: DelimSpan, . open_delim: bool, 424,108 ( 0.00%) tree_cursor: tokenstream::Cursor, . close_delim: bool, . } . . impl TokenCursorFrame { . fn new(span: DelimSpan, delim: DelimToken, tts: TokenStream) -> Self { 65,640 ( 0.00%) TokenCursorFrame { . delim, . span, . open_delim: false, 125,119 ( 0.00%) tree_cursor: tts.into_trees(), . close_delim: false, . } . } . } . . impl TokenCursor { 11,451,288 ( 0.03%) fn next(&mut self) -> (Token, Spacing) { . loop { 5,451,091 ( 0.02%) let (tree, spacing) = if !self.frame.open_delim { 98,721 ( 0.00%) self.frame.open_delim = true; 493,605 ( 0.00%) TokenTree::open_tt(self.frame.span, self.frame.delim).into() 11,157,191 ( 0.03%) } else if let Some(tree) = self.frame.tree_cursor.next_with_spacing() { . tree 403,814 ( 0.00%) } else if !self.frame.close_delim { 94,616 ( 0.00%) self.frame.close_delim = true; 473,080 ( 0.00%) TokenTree::close_tt(self.frame.span, self.frame.delim).into() 186,826 ( 0.00%) } else if let Some(frame) = self.stack.pop() { 1,214,369 ( 0.00%) self.frame = frame; . continue; . } else { 249,804 ( 0.00%) (TokenTree::Token(Token::new(token::Eof, DUMMY_SP)), Spacing::Alone) . }; . 2,105,706 ( 0.01%) match tree { . TokenTree::Token(token) => { 7,634,192 ( 0.02%) return (token, spacing); . } . TokenTree::Delimited(sp, delim, tts) => { . let frame = TokenCursorFrame::new(sp, delim, tts); . self.stack.push(mem::replace(&mut self.frame, frame)); . } . } . } 7,634,192 ( 0.02%) } . 1,116,820 ( 0.00%) fn next_desugared(&mut self) -> (Token, Spacing) { 335,330 ( 0.00%) let (data, attr_style, sp) = match self.next() { 426 ( 0.00%) (Token { kind: token::DocComment(_, attr_style, data), span }, _) => { . (data, attr_style, span) . } 557,700 ( 0.00%) tok => return tok, . }; . . // Searches for the occurrences of `"#*` and returns the minimum number of `#`s . // required to wrap the text. . let mut num_of_hashes = 0; . let mut count = 0; 34,268 ( 0.00%) for ch in data.as_str().chars() { . count = match ch { . '"' => 1, 2 ( 0.00%) '#' if count > 0 => count + 1, . _ => 0, . }; . num_of_hashes = cmp::max(num_of_hashes, count); . } . 568 ( 0.00%) let delim_span = DelimSpan::from_single(sp); 710 ( 0.00%) let body = TokenTree::Delimited( . delim_span, . token::Bracket, 1,704 ( 0.00%) [ 994 ( 0.00%) TokenTree::token(token::Ident(sym::doc, false), sp), 568 ( 0.00%) TokenTree::token(token::Eq, sp), 1,136 ( 0.00%) TokenTree::token(TokenKind::lit(token::StrRaw(num_of_hashes), data, None), sp), . ] . .iter() . .cloned() . .collect::(), 142 ( 0.00%) ); . . self.stack.push(mem::replace( . &mut self.frame, . TokenCursorFrame::new( . delim_span, . token::NoDelim, 142 ( 0.00%) if attr_style == AttrStyle::Inner { . [TokenTree::token(token::Pound, sp), TokenTree::token(token::Not, sp), body] . .iter() . .cloned() . .collect::() . } else { 1,704 ( 0.00%) [TokenTree::token(token::Pound, sp), body] . .iter() . .cloned() . .collect::() . }, . ), . )); . 426 ( 0.00%) self.next() 1,005,138 ( 0.00%) } . } . 622,500 ( 0.00%) #[derive(Debug, Clone, PartialEq)] . enum TokenType { 498,000 ( 0.00%) Token(TokenKind), . Keyword(Symbol), . Operator, . Lifetime, . Ident, . Path, . Type, . Const, . } -- line 353 ---------------------------------------- -- line 378 ---------------------------------------- . /// The separator token. . sep: Option, . /// `true` if a trailing separator is allowed. . trailing_sep_allowed: bool, . } . . impl SeqSep { . fn trailing_allowed(t: TokenKind) -> SeqSep { 84 ( 0.00%) SeqSep { sep: Some(t), trailing_sep_allowed: true } . } . . fn none() -> SeqSep { . SeqSep { sep: None, trailing_sep_allowed: false } . } . } . . pub enum FollowedByType { . Yes, . No, . } . . fn token_descr_opt(token: &Token) -> Option<&'static str> { 18,672 ( 0.00%) Some(match token.kind { 37,344 ( 0.00%) _ if token.is_special_ident() => "reserved identifier", 37,344 ( 0.00%) _ if token.is_used_keyword() => "keyword", 37,344 ( 0.00%) _ if token.is_unused_keyword() => "reserved keyword", . token::DocComment(..) => "doc comment", . _ => return None, . }) . } . 65,352 ( 0.00%) pub(super) fn token_descr(token: &Token) -> String { 18,672 ( 0.00%) let token_str = pprust::token_to_string(token); . match token_descr_opt(token) { . Some(prefix) => format!("{} `{}`", prefix, token_str), 65,352 ( 0.00%) _ => format!("`{}`", token_str), . } 46,680 ( 0.00%) } . . impl<'a> Parser<'a> { 183,792 ( 0.00%) pub fn new( . sess: &'a ParseSess, . tokens: TokenStream, . desugar_doc_comments: bool, . subparser_name: Option<&'static str>, . ) -> Self { 13,128 ( 0.00%) let mut start_frame = TokenCursorFrame::new(DelimSpan::dummy(), token::NoDelim, tokens); 26,256 ( 0.00%) start_frame.open_delim = true; . start_frame.close_delim = true; . 406,968 ( 0.00%) let mut parser = Parser { . sess, 13,128 ( 0.00%) token: Token::dummy(), . token_spacing: Spacing::Alone, 13,128 ( 0.00%) prev_token: Token::dummy(), . capture_cfg: false, . restrictions: Restrictions::empty(), . expected_tokens: Vec::new(), . token_cursor: TokenCursor { 78,768 ( 0.00%) frame: start_frame, . stack: Vec::new(), . num_next_calls: 0, . desugar_doc_comments, . break_last_token: false, . }, . desugar_doc_comments, . unmatched_angle_bracket_count: 0, . max_angle_bracket_count: 0, -- line 445 ---------------------------------------- -- line 451 ---------------------------------------- . capturing: Capturing::No, . replace_ranges: Vec::new(), . inner_attr_ranges: Default::default(), . }, . current_closure: None, . }; . . // Make parser point to the first token. 26,256 ( 0.00%) parser.bump(); . . parser 118,152 ( 0.00%) } . . fn next_tok(&mut self, fallback_span: Span) -> (Token, Spacing) { . loop { 5,285,142 ( 0.02%) let (mut next, spacing) = if self.desugar_doc_comments { 446,728 ( 0.00%) self.token_cursor.next_desugared() . } else { 2,307,525 ( 0.01%) self.token_cursor.next() . }; 3,523,428 ( 0.01%) self.token_cursor.num_next_calls += 1; . // We've retrieved an token from the underlying . // cursor, so we no longer need to worry about . // an unglued token. See `break_and_eat` for more details 880,857 ( 0.00%) self.token_cursor.break_last_token = false; 3,523,428 ( 0.01%) if next.span.is_dummy() { . // Tweak the location for better diagnostics, but keep syntactic context intact. 52,624 ( 0.00%) next.span = fallback_span.with_ctxt(next.span.ctxt()); . } 2,914,152 ( 0.01%) if matches!( 1,761,714 ( 0.01%) next.kind, . token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) . ) { . continue; . } 3,522,292 ( 0.01%) return (next, spacing); . } . } . . pub fn unexpected(&mut self) -> PResult<'a, T> { . match self.expect_one_of(&[], &[]) { . Err(e) => Err(e), . // We can get `Ok(true)` from `recover_closing_delimiter` . // which is called in `expected_one_of_not_found`. . Ok(_) => FatalError.raise(), . } . } . . /// Expects and consumes the token `t`. Signals an error if the next token is not `t`. 783,045 ( 0.00%) pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> { 87,005 ( 0.00%) if self.expected_tokens.is_empty() { 68,448 ( 0.00%) if self.token == *t { 57,040 ( 0.00%) self.bump(); . Ok(false) . } else { . self.unexpected_try_recover(t) . } . } else { 907,164 ( 0.00%) self.expect_one_of(slice::from_ref(t), &[]) . } 1,305,075 ( 0.00%) } . . /// Expect next token to be edible or inedible token. If edible, . /// then consume it; if inedible, then return without consuming . /// anything. Signal a fatal error if next token is unexpected. 1,151,388 ( 0.00%) pub fn expect_one_of( . &mut self, . edible: &[TokenKind], . inedible: &[TokenKind], . ) -> PResult<'a, bool /* recovered */> { 191,898 ( 0.00%) if edible.contains(&self.token.kind) { 255,801 ( 0.00%) self.bump(); . Ok(false) . } else if inedible.contains(&self.token.kind) { . // leave it in the input . Ok(false) . } else if self.last_unexpected_token_span == Some(self.token.span) { . FatalError.raise(); . } else { . self.expected_one_of_not_found(edible, inedible) . } 1,439,235 ( 0.00%) } . . // Public for rustfmt usage. . pub fn parse_ident(&mut self) -> PResult<'a, Ident> { 979,227 ( 0.00%) self.parse_ident_common(true) . } . . fn ident_or_err(&mut self) -> PResult<'a, (Ident, /* is_raw */ bool)> { 741,075 ( 0.00%) self.token.ident().ok_or_else(|| match self.prev_token.kind { . TokenKind::DocComment(..) => { . self.span_err(self.prev_token.span, Error::UselessDocComment) . } . _ => self.expected_ident_found(), . }) . } . 1,711,577 ( 0.00%) fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> { 244,511 ( 0.00%) let (ident, is_raw) = self.ident_or_err()?; 1,467,051 ( 0.00%) if !is_raw && ident.is_reserved() { . let mut err = self.expected_ident_found(); . if recover { . err.emit(); . } else { . return Err(err); . } . } 978,044 ( 0.00%) self.bump(); . Ok(ident) 2,445,110 ( 0.01%) } . . /// Checks if the next token is `tok`, and returns `true` if so. . /// . /// This method will automatically add `tok` to `expected_tokens` if `tok` is not . /// encountered. 17,624,698 ( 0.05%) fn check(&mut self, tok: &TokenKind) -> bool { 7,749,802 ( 0.02%) let is_present = self.token == *tok; 5,241,428 ( 0.02%) if !is_present { 10,459,483 ( 0.03%) self.expected_tokens.push(TokenType::Token(tok.clone())); . } . is_present 17,624,698 ( 0.05%) } . . /// Consumes a token 'tok' if it exists. Returns whether the given token was present. 136 ( 0.00%) pub fn eat(&mut self, tok: &TokenKind) -> bool { 3,567,150 ( 0.01%) let is_present = self.check(tok); 2,283,047 ( 0.01%) if is_present { 489,518 ( 0.00%) self.bump() . } . is_present 170 ( 0.00%) } . . /// If the next token is the given keyword, returns `true` without eating it. . /// An expectation is also added for diagnostics purposes. 686,630 ( 0.00%) fn check_keyword(&mut self, kw: Symbol) -> bool { 112,162 ( 0.00%) self.expected_tokens.push(TokenType::Keyword(kw)); 4,199,035 ( 0.01%) self.token.is_keyword(kw) . } . . /// If the next token is the given keyword, eats it and returns `true`. . /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes. . // Public for rustfmt usage. 1,519,120 ( 0.00%) pub fn eat_keyword(&mut self, kw: Symbol) -> bool { 916,440 ( 0.00%) if self.check_keyword(kw) { 88,491 ( 0.00%) self.bump(); . true . } else { . false . } 1,519,120 ( 0.00%) } . . fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool { 152,980 ( 0.00%) if self.token.is_keyword(kw) { 30,901 ( 0.00%) self.bump(); . true . } else { . false . } . } . . /// If the given word is not a keyword, signals an error. . /// If the next token is not the given word, signals an error. . /// Otherwise, eats it. 12,155 ( 0.00%) fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> { . if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) } 9,724 ( 0.00%) } . . /// Is the given keyword `kw` followed by a non-reserved identifier? 592,312 ( 0.00%) fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool { 296,156 ( 0.00%) self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()) 666,351 ( 0.00%) } . 1,210,770 ( 0.00%) fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool { 441,532 ( 0.00%) if ok { . true . } else { 252,920 ( 0.00%) self.expected_tokens.push(typ); . false . } 1,210,770 ( 0.00%) } . . fn check_ident(&mut self) -> bool { 285,232 ( 0.00%) self.check_or_expected(self.token.is_ident(), TokenType::Ident) . } . 369,784 ( 0.00%) fn check_path(&mut self) -> bool { 922,199 ( 0.00%) self.check_or_expected(self.token.is_path_start(), TokenType::Path) 462,230 ( 0.00%) } . . fn check_type(&mut self) -> bool { 136,260 ( 0.00%) self.check_or_expected(self.token.can_begin_type(), TokenType::Type) . } . . fn check_const_arg(&mut self) -> bool { 96,528 ( 0.00%) self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const) . } . 312,129 ( 0.00%) fn check_inline_const(&self, dist: usize) -> bool { 173,405 ( 0.00%) self.is_keyword_ahead(dist, &[kw::Const]) . && self.look_ahead(dist + 1, |t| match t.kind { . token::Interpolated(ref nt) => matches!(**nt, token::NtBlock(..)), . token::OpenDelim(DelimToken::Brace) => true, . _ => false, . }) 312,129 ( 0.00%) } . . /// Checks to see if the next token is either `+` or `+=`. . /// Otherwise returns `false`. . fn check_plus(&mut self) -> bool { 117,864 ( 0.00%) self.check_or_expected( 58,932 ( 0.00%) self.token.is_like_plus(), 58,932 ( 0.00%) TokenType::Token(token::BinOp(token::Plus)), . ) . } . . /// Eats the expected token if it's present possibly breaking . /// compound tokens like multi-character operators in process. . /// Returns `true` if the token was eaten. 1,632,672 ( 0.00%) fn break_and_eat(&mut self, expected: TokenKind) -> bool { 952,392 ( 0.00%) if self.token.kind == expected { 82,958 ( 0.00%) self.bump(); . return true; . } 472,885 ( 0.00%) match self.token.kind.break_two_token_op() { 1,141 ( 0.00%) Some((first, second)) if first == expected => { 652 ( 0.00%) let first_span = self.sess.source_map().start_point(self.token.span); 815 ( 0.00%) let second_span = self.token.span.with_lo(first_span.hi()); 1,467 ( 0.00%) self.token = Token::new(first, first_span); . // Keep track of this token - if we end token capturing now, . // we'll want to append this token to the captured stream. . // . // If we consume any additional tokens, then this token . // is not needed (we'll capture the entire 'glued' token), . // and `next_tok` will set this field to `None` 163 ( 0.00%) self.token_cursor.break_last_token = true; . // Use the spacing of the glued token as the spacing . // of the unglued second token. 2,282 ( 0.00%) self.bump_with((Token::new(second, second_span), self.token_spacing)); . true . } . _ => { 283,242 ( 0.00%) self.expected_tokens.push(TokenType::Token(expected)); . false . } . } 1,602,160 ( 0.00%) } . . /// Eats `+` possibly breaking tokens like `+=` in process. . fn eat_plus(&mut self) -> bool { 13,320 ( 0.00%) self.break_and_eat(token::BinOp(token::Plus)) . } . . /// Eats `&` possibly breaking tokens like `&&` in process. . /// Signals an error if `&` is not eaten. . fn expect_and(&mut self) -> PResult<'a, ()> { 47,640 ( 0.00%) if self.break_and_eat(token::BinOp(token::And)) { Ok(()) } else { self.unexpected() } . } . . /// Eats `|` possibly breaking tokens like `||` in process. . /// Signals an error if `|` was not eaten. . fn expect_or(&mut self) -> PResult<'a, ()> { 168 ( 0.00%) if self.break_and_eat(token::BinOp(token::Or)) { Ok(()) } else { self.unexpected() } . } . . /// Eats `<` possibly breaking tokens like `<<` in process. 84,292 ( 0.00%) fn eat_lt(&mut self) -> bool { 343,730 ( 0.00%) let ate = self.break_and_eat(token::Lt); 228,184 ( 0.00%) if ate { . // See doc comment for `unmatched_angle_bracket_count`. 68,876 ( 0.00%) self.unmatched_angle_bracket_count += 1; 74,533 ( 0.00%) self.max_angle_bracket_count += 1; . debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count); . } . ate 84,292 ( 0.00%) } . . /// Eats `<` possibly breaking tokens like `<<` in process. . /// Signals an error if `<` was not eaten. . fn expect_lt(&mut self) -> PResult<'a, ()> { . if self.eat_lt() { Ok(()) } else { self.unexpected() } . } . . /// Eats `>` possibly breaking tokens like `>>` in process. . /// Signals an error if `>` was not eaten. . fn expect_gt(&mut self) -> PResult<'a, ()> { 98,682 ( 0.00%) if self.break_and_eat(token::Gt) { . // See doc comment for `unmatched_angle_bracket_count`. 49,341 ( 0.00%) if self.unmatched_angle_bracket_count > 0 { 32,894 ( 0.00%) self.unmatched_angle_bracket_count -= 1; . debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count); . } . Ok(()) . } else { . self.unexpected() . } . } . . fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool { . kets.iter().any(|k| match expect { 240,510 ( 0.00%) TokenExpectType::Expect => self.check(k), 420 ( 0.00%) TokenExpectType::NoExpect => self.token == **k, . }) . } . . fn parse_seq_to_before_tokens( . &mut self, . kets: &[&TokenKind], . sep: SeqSep, . expect: TokenExpectType, -- line 759 ---------------------------------------- -- line 761 ---------------------------------------- . ) -> PResult<'a, (Vec, bool /* trailing */, bool /* recovered */)> { . let mut first = true; . let mut recovered = false; . let mut trailing = false; . let mut v = vec![]; . let unclosed_delims = !self.unclosed_delims.is_empty(); . . while !self.expect_any_with_type(kets, expect) { 258,123 ( 0.00%) if let token::CloseDelim(..) | token::Eof = self.token.kind { . break; . } 208,338 ( 0.00%) if let Some(ref t) = sep.sep { 223,917 ( 0.00%) if first { . first = false; . } else { 71,260 ( 0.00%) match self.expect(t) { . Ok(false) => { . self.current_closure.take(); . } . Ok(true) => { . self.current_closure.take(); . recovered = true; . break; . } -- line 784 ---------------------------------------- -- line 857 ---------------------------------------- . e.cancel(); . break; . } . } . } . } . } . } 92,204 ( 0.00%) if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) { . trailing = true; . break; . } . 74,947 ( 0.00%) let t = f(self)?; 33,227 ( 0.00%) v.push(t); . } . 149,024 ( 0.00%) Ok((v, trailing, recovered)) . } . . fn recover_missing_braces_around_closure_body( . &mut self, . closure_spans: ClosureSpans, . mut expect_err: DiagnosticBuilder<'_>, . ) -> PResult<'a, ()> { . let initial_semicolon = self.token.span; -- line 882 ---------------------------------------- -- line 937 ---------------------------------------- . /// `f` must consume tokens until reaching the next separator or . /// closing bracket. . fn parse_seq_to_before_end( . &mut self, . ket: &TokenKind, . sep: SeqSep, . f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, . ) -> PResult<'a, (Vec, bool, bool)> { 149,719 ( 0.00%) self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f) . } . . /// Parses a sequence, including the closing delimiter. The function . /// `f` must consume tokens until reaching the next separator or . /// closing bracket. 219,390 ( 0.00%) fn parse_seq_to_end( . &mut self, . ket: &TokenKind, . sep: SeqSep, . f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, . ) -> PResult<'a, (Vec, bool /* trailing */)> { 96,656 ( 0.00%) let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?; 52,256 ( 0.00%) if !recovered { . self.eat(ket); . } 247,373 ( 0.00%) Ok((val, trailing)) 175,512 ( 0.00%) } . . /// Parses a sequence, including the closing delimiter. The function . /// `f` must consume tokens until reaching the next separator or . /// closing bracket. . fn parse_unspanned_seq( . &mut self, . bra: &TokenKind, . ket: &TokenKind, . sep: SeqSep, . f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, . ) -> PResult<'a, (Vec, bool)> { 91,911 ( 0.00%) self.expect(bra)?; 175,512 ( 0.00%) self.parse_seq_to_end(ket, sep, f) . } . . fn parse_delim_comma_seq( . &mut self, . delim: DelimToken, . f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, . ) -> PResult<'a, (Vec, bool)> { . self.parse_unspanned_seq( 36,998 ( 0.00%) &token::OpenDelim(delim), 52,466 ( 0.00%) &token::CloseDelim(delim), . SeqSep::trailing_allowed(token::Comma), . f, . ) . } . . fn parse_paren_comma_seq( . &mut self, . f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, . ) -> PResult<'a, (Vec, bool)> { . self.parse_delim_comma_seq(token::Paren, f) . } . . /// Advance the parser by one token using provided token as the next one. 11,449,568 ( 0.03%) fn bump_with(&mut self, (next_token, next_spacing): (Token, Spacing)) { . // Bumping after EOF is a bad sign, usually an infinite loop. 5,284,416 ( 0.02%) if self.prev_token.kind == TokenKind::Eof { . let msg = "attempted to bump the parser past EOF (may be stuck in a loop)"; . self.span_bug(self.token.span, msg); . } . . // Update the current and previous tokens. 3,522,944 ( 0.01%) self.prev_token = mem::replace(&mut self.token, next_token); 880,736 ( 0.00%) self.token_spacing = next_spacing; . . // Diagnostics. 880,736 ( 0.00%) self.expected_tokens.clear(); . } . . /// Advance the parser by one token. 7,044,584 ( 0.02%) pub fn bump(&mut self) { 3,522,292 ( 0.01%) let next_token = self.next_tok(self.token.span); 5,283,438 ( 0.02%) self.bump_with(next_token); 7,044,584 ( 0.02%) } . . /// Look-ahead `dist` tokens of `self.token` and get access to that token there. . /// When `dist == 0` then the current token is looked at. 272 ( 0.00%) pub fn look_ahead(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R { 99,112 ( 0.00%) if dist == 0 { 46,004 ( 0.00%) return looker(&self.token); . } . 467,945 ( 0.00%) let frame = &self.token_cursor.frame; 517,389 ( 0.00%) if frame.delim != DelimToken::NoDelim { . let all_normal = (0..dist).all(|i| { 1,455,738 ( 0.00%) let token = frame.tree_cursor.look_ahead(i); 1,901,432 ( 0.01%) !matches!(token, Some(TokenTree::Delimited(_, DelimToken::NoDelim, _))) . }); . if all_normal { 2,358,530 ( 0.01%) return match frame.tree_cursor.look_ahead(dist - 1) { 844,593 ( 0.00%) Some(tree) => match tree { 420,421 ( 0.00%) TokenTree::Token(token) => looker(token), . TokenTree::Delimited(dspan, delim, _) => { 44,867 ( 0.00%) looker(&Token::new(token::OpenDelim(*delim), dspan.open)) . } . }, 395,805 ( 0.00%) None => looker(&Token::new(token::CloseDelim(frame.delim), frame.span.close)), . }; . } . } . . let mut cursor = self.token_cursor.clone(); . let mut i = 0; 43,815 ( 0.00%) let mut token = Token::dummy(); 484 ( 0.00%) while i < dist { 306,863 ( 0.00%) token = cursor.next().0; 139,670 ( 0.00%) if matches!( 87,622 ( 0.00%) token.kind, . token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) . ) { . continue; . } 210 ( 0.00%) i += 1; . } 13,050 ( 0.00%) return looker(&token); 306 ( 0.00%) } . . /// Returns whether any of the given keywords are `dist` tokens ahead of the current one. 381,420 ( 0.00%) fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool { 96,592 ( 0.00%) self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw))) 381,420 ( 0.00%) } . . /// Parses asyncness: `async` or nothing. . fn parse_asyncness(&mut self) -> Async { . if self.eat_keyword(kw::Async) { . let span = self.prev_token.uninterpolated_span(); . Async::Yes { span, closure_id: DUMMY_NODE_ID, return_impl_trait_id: DUMMY_NODE_ID } . } else { . Async::No . } . } . . /// Parses unsafety: `unsafe` or nothing. 11,580 ( 0.00%) fn parse_unsafety(&mut self) -> Unsafe { . if self.eat_keyword(kw::Unsafe) { 5 ( 0.00%) Unsafe::Yes(self.prev_token.uninterpolated_span()) . } else { . Unsafe::No . } 46,320 ( 0.00%) } . . /// Parses constness: `const` or nothing. 171,088 ( 0.00%) fn parse_constness(&mut self) -> Const { . // Avoid const blocks to be parsed as const items 46,110 ( 0.00%) if self.look_ahead(1, |t| t != &token::OpenDelim(DelimToken::Brace)) . && self.eat_keyword(kw::Const) . { 5,515 ( 0.00%) Const::Yes(self.prev_token.uninterpolated_span()) . } else { . Const::No . } 299,404 ( 0.00%) } . . /// Parses inline const expressions. . fn parse_const_block(&mut self, span: Span, pat: bool) -> PResult<'a, P> { . if pat { . self.sess.gated_spans.gate(sym::inline_const_pat, span); . } else { . self.sess.gated_spans.gate(sym::inline_const, span); . } -- line 1104 ---------------------------------------- -- line 1108 ---------------------------------------- . id: DUMMY_NODE_ID, . value: self.mk_expr(blk.span, ExprKind::Block(blk, None), AttrVec::new()), . }; . let blk_span = anon_const.value.span; . Ok(self.mk_expr(span.to(blk_span), ExprKind::ConstBlock(anon_const), AttrVec::new())) . } . . /// Parses mutability (`mut` or nothing). 476 ( 0.00%) fn parse_mutability(&mut self) -> Mutability { . if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not } 16,594 ( 0.00%) } . . /// Possibly parses mutability (`const` or `mut`). . fn parse_const_or_mut(&mut self) -> Option { . if self.eat_keyword(kw::Mut) { . Some(Mutability::Mut) . } else if self.eat_keyword(kw::Const) { . Some(Mutability::Not) . } else { . None . } . } . . fn parse_field_name(&mut self) -> PResult<'a, Ident> { 3,998 ( 0.00%) if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind . { 80 ( 0.00%) self.expect_no_suffix(self.token.span, "a tuple index", suffix); 32 ( 0.00%) self.bump(); . Ok(Ident::new(symbol, self.prev_token.span)) . } else { 5,853 ( 0.00%) self.parse_ident_common(true) . } 48 ( 0.00%) } . . fn parse_mac_args(&mut self) -> PResult<'a, P> { 13,001 ( 0.00%) self.parse_mac_args_common(true).map(P) . } . . fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> { 17,199 ( 0.00%) self.parse_mac_args_common(false) . } . 94,104 ( 0.00%) fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> { 83,648 ( 0.00%) Ok( 61,170 ( 0.00%) if self.check(&token::OpenDelim(DelimToken::Paren)) 6,693 ( 0.00%) || self.check(&token::OpenDelim(DelimToken::Bracket)) 6,642 ( 0.00%) || self.check(&token::OpenDelim(DelimToken::Brace)) . { 35,756 ( 0.00%) match self.parse_token_tree() { 44,695 ( 0.00%) TokenTree::Delimited(dspan, delim, tokens) => . // We've confirmed above that there is a delimiter so unwrapping is OK. . { 17,878 ( 0.00%) MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens) . } . _ => unreachable!(), . } 3,034 ( 0.00%) } else if !delimited_only { . if self.eat(&token::Eq) { 48 ( 0.00%) let eq_span = self.prev_token.span; . . // Collect tokens because they are used during lowering to HIR. 48 ( 0.00%) let expr = self.parse_expr_force_collect()?; 48 ( 0.00%) let span = expr.span; . 240 ( 0.00%) let token_kind = token::Interpolated(Lrc::new(token::NtExpr(expr))); 432 ( 0.00%) MacArgs::Eq(eq_span, Token::new(token_kind, span)) . } else { . MacArgs::Empty . } . } else { . return self.unexpected(); . }, . ) 73,192 ( 0.00%) } . . fn parse_or_use_outer_attributes( . &mut self, . already_parsed_attrs: Option, . ) -> PResult<'a, AttrWrapper> { 280,884 ( 0.00%) if let Some(attrs) = already_parsed_attrs { . Ok(attrs) . } else { 149,816 ( 0.00%) self.parse_outer_attributes() . } . } . . /// Parses a single token tree from the input. 85,952 ( 0.00%) pub(crate) fn parse_token_tree(&mut self) -> TokenTree { 33,232 ( 0.00%) match self.token.kind { . token::OpenDelim(..) => { . let depth = self.token_cursor.stack.len(); . . // We keep advancing the token cursor until we hit . // the matching `CloseDelim` token. 476,156 ( 0.00%) while !(depth == self.token_cursor.stack.len() . && matches!(self.token.kind, token::CloseDelim(_))) . { . // Advance one token at a time, so `TokenCursor::next()` . // can capture these tokens if necessary. 319,634 ( 0.00%) self.bump(); . } . // We are still inside the frame corresponding . // to the delimited stream we captured, so grab . // the tokens from this frame. . let frame = &self.token_cursor.frame; 20,988 ( 0.00%) let stream = frame.tree_cursor.stream.clone(); 20,988 ( 0.00%) let span = frame.span; 10,494 ( 0.00%) let delim = frame.delim; . // Consume close delimiter 20,988 ( 0.00%) self.bump(); 52,470 ( 0.00%) TokenTree::Delimited(span, delim, stream) . } . token::CloseDelim(_) | token::Eof => unreachable!(), . _ => { 500 ( 0.00%) self.bump(); 1,250 ( 0.00%) TokenTree::Token(self.prev_token.clone()) . } . } 75,208 ( 0.00%) } . . /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF. . pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec> { . let mut tts = Vec::new(); . while self.token != token::Eof { . tts.push(self.parse_token_tree()); . } . Ok(tts) -- line 1234 ---------------------------------------- -- line 1244 ---------------------------------------- . } . TokenStream::new(result) . } . . /// Evaluates the closure with restrictions in place. . /// . /// Afters the closure is evaluated, restrictions are reset. . fn with_res(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T { 86,650 ( 0.00%) let old = self.restrictions; 102,112 ( 0.00%) self.restrictions = res; . let res = f(self); 115,110 ( 0.00%) self.restrictions = old; . res . } . 236,016 ( 0.00%) fn is_crate_vis(&self) -> bool { 147,510 ( 0.00%) self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep) 265,518 ( 0.00%) } . . /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`, . /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`. . /// If the following element can't be a tuple (i.e., it's a function definition), then . /// it's not a tuple struct field), and the contents within the parentheses aren't valid, . /// so emit a proper diagnostic. . // Public for rustfmt usage. 231,600 ( 0.00%) pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> { 46,330 ( 0.00%) maybe_whole!(self, NtVis, |x| x); . 23,159 ( 0.00%) self.expected_tokens.push(TokenType::Keyword(kw::Crate)); 92,636 ( 0.00%) if self.is_crate_vis() { . self.bump(); // `crate` . self.sess.gated_spans.gate(sym::crate_visibility_modifier, self.prev_token.span); . return Ok(Visibility { . span: self.prev_token.span, . kind: VisibilityKind::Crate(CrateSugar::JustCrate), . tokens: None, . }); . } . . if !self.eat_keyword(kw::Pub) { . // We need a span for our `Spanned`, but there's inherently no . // keyword to grab a span from for inherited visibility; an empty span at the . // beginning of the current token would seem to be the "Schelling span". 21,749 ( 0.00%) return Ok(Visibility { 65,247 ( 0.00%) span: self.token.span.shrink_to_lo(), . kind: VisibilityKind::Inherited, . tokens: None, . }); . } 1,410 ( 0.00%) let lo = self.prev_token.span; . 7,050 ( 0.00%) if self.check(&token::OpenDelim(token::Paren)) { . // We don't `self.bump()` the `(` yet because this might be a struct definition where . // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`. . // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so . // by the following tokens. 18 ( 0.00%) if self.is_keyword_ahead(1, &[kw::Crate]) && self.look_ahead(2, |t| t != &token::ModSep) . // account for `pub(crate::foo)` . { . // Parse `pub(crate)`. 6 ( 0.00%) self.bump(); // `(` 4 ( 0.00%) self.bump(); // `crate` 6 ( 0.00%) self.expect(&token::CloseDelim(token::Paren))?; // `)` 2 ( 0.00%) let vis = VisibilityKind::Crate(CrateSugar::PubCrate); . return Ok(Visibility { 6 ( 0.00%) span: lo.to(self.prev_token.span), . kind: vis, . tokens: None, . }); . } else if self.is_keyword_ahead(1, &[kw::In]) { . // Parse `pub(in path)`. . self.bump(); // `(` . self.bump(); // `in` . let path = self.parse_path(PathStyle::Mod)?; // `path` -- line 1317 ---------------------------------------- -- line 1338 ---------------------------------------- . } else if let FollowedByType::No = fbt { . // Provide this diagnostic if a type cannot follow; . // in particular, if this is not a tuple struct. . self.recover_incorrect_vis_restriction()?; . // Emit diagnostic, but continue with public visibility. . } . } . 4,224 ( 0.00%) Ok(Visibility { span: lo, kind: VisibilityKind::Public, tokens: None }) 208,440 ( 0.00%) } . . /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }` . fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> { . self.bump(); // `(` . let path = self.parse_path(PathStyle::Mod)?; . self.expect(&token::CloseDelim(token::Paren))?; // `)` . . let msg = "incorrect visibility restriction"; -- line 1355 ---------------------------------------- -- line 1370 ---------------------------------------- . ) . .emit(); . . Ok(()) . } . . /// Parses `extern string_literal?`. . fn parse_extern(&mut self) -> Extern { 4,024 ( 0.00%) if self.eat_keyword(kw::Extern) { Extern::from_abi(self.parse_abi()) } else { Extern::None } . } . . /// Parses a string literal as an ABI spec. . fn parse_abi(&mut self) -> Option { . match self.parse_str_lit() { . Ok(str_lit) => Some(str_lit), . Err(Some(lit)) => match lit.kind { . ast::LitKind::Err(_) => None, -- line 1386 ---------------------------------------- -- line 1395 ---------------------------------------- . .emit(); . None . } . }, . Err(None) => None, . } . } . 39,520 ( 0.00%) pub fn collect_tokens_no_attrs( . &mut self, . f: impl FnOnce(&mut Self) -> PResult<'a, R>, . ) -> PResult<'a, R> { . // The only reason to call `collect_tokens_no_attrs` is if you want tokens, so use . // `ForceCollect::Yes` . self.collect_tokens_trailing_token( . AttrWrapper::empty(), . ForceCollect::Yes, 4,057 ( 0.00%) |this, _attrs| Ok((f(this)?, TrailingToken::None)), . ) 39,520 ( 0.00%) } . . /// `::{` or `::*` 1,746,912 ( 0.01%) fn is_import_coupler(&mut self) -> bool { 873,456 ( 0.00%) self.check(&token::ModSep) . && self.look_ahead(1, |t| { 1,557,239 ( 0.00%) *t == token::OpenDelim(token::Brace) || *t == token::BinOp(token::Star) . }) 1,144,296 ( 0.00%) } . . pub fn clear_expected_tokens(&mut self) { . self.expected_tokens.clear(); . } . } . . crate fn make_unclosed_delims_error( . unmatched: UnmatchedBrace, -- line 1430 ---------------------------------------- -- line 1450 ---------------------------------------- . err.span_label(sp, "closing delimiter possibly meant for this"); . } . if let Some(sp) = unmatched.unclosed_span { . err.span_label(sp, "unclosed delimiter"); . } . Some(err) . } . 209,056 ( 0.00%) pub fn emit_unclosed_delims(unclosed_delims: &mut Vec, sess: &ParseSess) { 104,528 ( 0.00%) *sess.reached_eof.borrow_mut() |= . unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none()); 104,528 ( 0.00%) for unmatched in unclosed_delims.drain(..) { . if let Some(mut e) = make_unclosed_delims_error(unmatched, sess) { . e.emit(); . } . } 209,056 ( 0.00%) } . . /// A helper struct used when building an `AttrAnnotatedTokenStream` from . /// a `LazyTokenStream`. Both delimiter and non-delimited tokens . /// are stored as `FlatToken::Token`. A vector of `FlatToken`s . /// is then 'parsed' to build up an `AttrAnnotatedTokenStream` with nested . /// `AttrAnnotatedTokenTree::Delimited` tokens 909 ( 0.00%) #[derive(Debug, Clone)] . pub enum FlatToken { . /// A token - this holds both delimiter (e.g. '{' and '}') . /// and non-delimiter tokens . Token(Token), . /// Holds the `AttributesData` for an AST node. The . /// `AttributesData` is inserted directly into the . /// constructed `AttrAnnotatedTokenStream` as . /// an `AttrAnnotatedTokenTree::Attributes` -- line 1481 ---------------------------------------- 5,723,454 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/sty.rs -------------------------------------------------------------------------------- Ir -- line 23 ---------------------------------------- . 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)] . #[derive(HashStable, TypeFoldable, Lift)] . pub struct TypeAndMut<'tcx> { 2,373 ( 0.00%) pub ty: Ty<'tcx>, 11,865 ( 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 { 248,396 ( 0.00%) pub scope: DefId, 520,703 ( 0.00%) pub bound_region: BoundRegionKind, . } . 3,328,962 ( 0.01%) #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, TyEncodable, TyDecodable, Copy)] . #[derive(HashStable)] . pub enum BoundRegionKind { . /// An anonymous region parameter for a given fn (&T) 35,593 ( 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. 23,281 ( 0.00%) BrNamed(DefId, Symbol), . . /// Anonymous region for the implicit env pointer parameter . /// to a closure . BrEnv, . } . 7,800 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, Debug, PartialOrd, Ord)] . #[derive(HashStable)] . pub struct BoundRegion { 846,890 ( 0.00%) pub var: BoundVar, 757,346 ( 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. 106,345,105 ( 0.31%) #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable, Debug)] . #[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`. -- line 89 ---------------------------------------- -- 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. 16,352,188 ( 0.05%) 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]`. 45,183 ( 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`. 8,430,281 ( 0.02%) 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 143 ---------------------------------------- . /// . /// ```rust . /// fn foo() -> i32 { 1 } . /// let bar: fn() -> i32 = foo; . /// ``` . FnPtr(PolyFnSig<'tcx>), . . /// A trait object. Written as `dyn for<'b> Trait<'b, Assoc = u32> + Send + 'a`. 313,802 ( 0.00%) Dynamic(&'tcx List>>, ty::Region<'tcx>), . . /// The anonymous type of a closure. Used to represent the type of . /// `|a| a`. . Closure(DefId, SubstsRef<'tcx>), . . /// The anonymous type of a generator. Used to represent the type of . /// `|a| yield a`. . Generator(DefId, SubstsRef<'tcx>, hir::Movability), -- line 159 ---------------------------------------- -- 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. 69,862 ( 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. 29 ( 0.00%) pub fn new( . tcx: TyCtxt<'tcx>, . parts: ClosureSubstsParts<'tcx, Ty<'tcx>>, . ) -> ClosureSubsts<'tcx> { . ClosureSubsts { . substs: tcx.mk_substs( 58 ( 0.00%) parts.parent_substs.iter().copied().chain( 116 ( 0.00%) [parts.closure_kind_ty, parts.closure_sig_as_fn_ptr_ty, parts.tupled_upvars_ty] . .iter() . .map(|&ty| ty.into()), . ), . ), . } 58 ( 0.00%) } . . /// Divides the closure substs into their respective components. . /// The ordering assumed here must match that used by `ClosureSubsts::new` above. 330 ( 0.00%) fn split(self) -> ClosureSubstsParts<'tcx, GenericArg<'tcx>> { . match self.substs[..] { 4,468 ( 0.00%) [ 1,286 ( 0.00%) ref parent_substs @ .., 1,034 ( 0.00%) closure_kind_ty, 722 ( 0.00%) closure_sig_as_fn_ptr_ty, 808 ( 0.00%) tupled_upvars_ty, 1,320 ( 0.00%) ] => ClosureSubstsParts { . parent_substs, . closure_kind_ty, . closure_sig_as_fn_ptr_ty, . tupled_upvars_ty, . }, . _ => bug!("closure substs missing synthetics"), . } 990 ( 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] 6 ( 0.00%) pub fn upvar_tys(self) -> impl Iterator> + 'tcx { 93 ( 0.00%) match self.tupled_upvars_ty().kind() { . TyKind::Error(_) => None, 62 ( 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() 4 ( 0.00%) } . . /// Returns the tuple type representing the upvars for this closure. . #[inline] . pub fn tupled_upvars_ty(self) -> Ty<'tcx> { 1,497 ( 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)`. 167 ( 0.00%) pub fn kind_ty(self) -> Ty<'tcx> { . self.split().closure_kind_ty.expect_ty() 334 ( 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 { 1 ( 0.00%) self.kind_ty().to_opt_closure_kind().unwrap() 2 ( 0.00%) } . . /// Extracts the signature from the closure. 244 ( 0.00%) pub fn sig(self) -> ty::PolyFnSig<'tcx> { . let ty = self.sig_as_fn_ptr_ty(); 488 ( 0.00%) match ty.kind() { 976 ( 0.00%) ty::FnPtr(sig) => *sig, . _ => bug!("closure_sig_as_fn_ptr_ty is not a fn-ptr: {:?}", ty.kind()), . } 732 ( 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 { 60 ( 0.00%) let tupled_tys = match self { 89 ( 0.00%) UpvarSubsts::Closure(substs) => substs.as_closure().tupled_upvars_ty(), . UpvarSubsts::Generator(substs) => substs.as_generator().tupled_upvars_ty(), . }; . 148 ( 0.00%) match tupled_tys.kind() { . TyKind::Error(_) => None, 119 ( 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> { 118 ( 0.00%) match self { 119 ( 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 760 ---------------------------------------- . } . . /// Returns the type of this inline const. . pub fn ty(self) -> Ty<'tcx> { . self.split().ty.expect_ty() . } . } . 221,641 ( 0.00%) #[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Ord, Eq, Hash, TyEncodable, TyDecodable)] 255,343 ( 0.00%) #[derive(HashStable, TypeFoldable)] . pub enum ExistentialPredicate<'tcx> { . /// E.g., `Iterator`. . Trait(ExistentialTraitRef<'tcx>), . /// E.g., `Iterator::Item = T`. . Projection(ExistentialProjection<'tcx>), . /// E.g., `Send`. 18 ( 0.00%) AutoTrait(DefId), . } . . impl<'tcx> ExistentialPredicate<'tcx> { . /// Compares via an ordering that will not change if modules are reordered or other changes are . /// made to the tree. In particular, this ordering is preserved across incremental compilations. 70 ( 0.00%) pub fn stable_cmp(&self, tcx: TyCtxt<'tcx>, other: &Self) -> Ordering { . use self::ExistentialPredicate::*; 80 ( 0.00%) match (*self, *other) { . (Trait(_), Trait(_)) => Ordering::Equal, . (Projection(ref a), Projection(ref b)) => { . tcx.def_path_hash(a.item_def_id).cmp(&tcx.def_path_hash(b.item_def_id)) . } . (AutoTrait(ref a), AutoTrait(ref b)) => { . tcx.def_path_hash(*a).cmp(&tcx.def_path_hash(*b)) . } . (Trait(_), _) => Ordering::Less, . (Projection(_), Trait(_)) => Ordering::Greater, . (Projection(_), _) => Ordering::Less, . (AutoTrait(_), _) => Ordering::Greater, . } 84 ( 0.00%) } . } . . impl<'tcx> Binder<'tcx, ExistentialPredicate<'tcx>> { 27,675 ( 0.00%) pub fn with_self_ty(&self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ty::Predicate<'tcx> { . use crate::ty::ToPredicate; 15,375 ( 0.00%) match self.skip_binder() { . ExistentialPredicate::Trait(tr) => { . self.rebind(tr).with_self_ty(tcx, self_ty).without_const().to_predicate(tcx) . } . ExistentialPredicate::Projection(p) => { . self.rebind(p.with_self_ty(tcx, self_ty)).to_predicate(tcx) . } . ExistentialPredicate::AutoTrait(did) => { . let trait_ref = self.rebind(ty::TraitRef { . def_id: did, . substs: tcx.mk_substs_trait(self_ty, &[]), . }); . trait_ref.without_const().to_predicate(tcx) . } . } 24,600 ( 0.00%) } . } . . impl<'tcx> List>> { . /// Returns the "principal `DefId`" of this set of existential predicates. . /// . /// A Rust trait object type consists (in addition to a lifetime bound) . /// of a set of trait bounds, which are separated into any number . /// of auto-trait bounds, and at most one non-auto-trait bound. The -- line 826 ---------------------------------------- -- line 840 ---------------------------------------- . /// . /// It is also possible to have a "trivial" trait object that . /// consists only of auto traits, with no principal - for example, . /// `dyn Send + Sync`. In that case, the set of auto-trait bounds . /// is `{Send, Sync}`, while there is no principal. These trait objects . /// have a "trivial" vtable consisting of just the size, alignment, . /// and destructor. . pub fn principal(&self) -> Option>> { 9,231 ( 0.00%) self[0] 9,231 ( 0.00%) .map_bound(|this| match this { . ExistentialPredicate::Trait(tr) => Some(tr), . _ => None, . }) . .transpose() . } . 3,075 ( 0.00%) pub fn principal_def_id(&self) -> Option { . self.principal().map(|trait_ref| trait_ref.skip_binder().def_id) 6,150 ( 0.00%) } . . #[inline] . pub fn projection_bounds<'a>( . &'a self, . ) -> impl Iterator>> + 'a { . self.iter().filter_map(|predicate| { . predicate . .map_bound(|pred| match pred { -- line 866 ---------------------------------------- -- 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. 43,237 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] 18,293,186 ( 0.05%) #[derive(HashStable, TypeFoldable)] . pub struct TraitRef<'tcx> { 5,648 ( 0.00%) pub def_id: DefId, 11,170,444 ( 0.03%) pub substs: SubstsRef<'tcx>, . } . . impl<'tcx> TraitRef<'tcx> { 20,501 ( 0.00%) pub fn new(def_id: DefId, substs: SubstsRef<'tcx>) -> TraitRef<'tcx> { . TraitRef { def_id, substs } 82,004 ( 0.00%) } . . /// Returns a `TraitRef` of the form `P0: Foo` where `Pi` . /// are the parameters defined on trait. 621 ( 0.00%) pub fn identity(tcx: TyCtxt<'tcx>, def_id: DefId) -> Binder<'tcx, TraitRef<'tcx>> { 276 ( 0.00%) ty::Binder::dummy(TraitRef { . def_id, 414 ( 0.00%) substs: InternalSubsts::identity_for_item(tcx, def_id), . }) 552 ( 0.00%) } . . #[inline] . pub fn self_ty(&self) -> Ty<'tcx> { . self.substs.type_at(0) . } . 13,120 ( 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); . 1,640 ( 0.00%) ty::TraitRef { def_id: trait_id, substs: tcx.intern_substs(&substs[..defs.params.len()]) } 18,040 ( 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 { 216,009 ( 0.00%) self.skip_binder().def_id 72,003 ( 0.00%) } . 32,853 ( 0.00%) pub fn to_poly_trait_predicate(&self) -> ty::PolyTraitPredicate<'tcx> { 65,706 ( 0.00%) self.map_bound(|trait_ref| ty::TraitPredicate { . trait_ref, . constness: ty::BoundConstness::NotConst, . polarity: ty::ImplPolarity::Positive, . }) 32,853 ( 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 . /// type and lifetime parameters (`[X, Y]` and `['a, 'b]` above). 72 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] 125,963 ( 0.00%) #[derive(HashStable, TypeFoldable)] . pub struct ExistentialTraitRef<'tcx> { 15,448 ( 0.00%) pub def_id: DefId, 139,904 ( 0.00%) pub substs: SubstsRef<'tcx>, . } . . impl<'tcx> ExistentialTraitRef<'tcx> { 8 ( 0.00%) pub fn erase_self_ty( . tcx: TyCtxt<'tcx>, . trait_ref: ty::TraitRef<'tcx>, . ) -> ty::ExistentialTraitRef<'tcx> { . // Assert there is a Self. . trait_ref.substs.type_at(0); . . ty::ExistentialTraitRef { . def_id: trait_ref.def_id, . substs: tcx.intern_substs(&trait_ref.substs[1..]), . } 8 ( 0.00%) } . . /// Object types don't have a self type specified. Therefore, when . /// 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::TraitRef<'tcx> { . // otherwise the escaping vars would be captured by the binder . // debug_assert!(!self_ty.has_escaping_bound_vars()); -- line 985 ---------------------------------------- -- 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)) . } . } . 191,527 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] . #[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 -- line 1015 ---------------------------------------- -- line 1016 ---------------------------------------- . /// 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. 326,904 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] 4,008,500 ( 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. 249,620 ( 0.00%) pub fn dummy(value: T) -> Binder<'tcx, T> { 1,442,252 ( 0.00%) assert!(!value.has_escaping_bound_vars()); 3,291,427 ( 0.01%) Binder(value, ty::List::empty()) 247,937 ( 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); . } 217,993 ( 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 { 12,915,358 ( 0.04%) self.0 . } . . pub fn bound_vars(&self) -> &'tcx List { 38,792 ( 0.00%) self.1 . } . . pub fn as_ref(&self) -> Binder<'tcx, &T> { 76,837 ( 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) . } . 232 ( 0.00%) pub fn map_bound>(self, f: F) -> Binder<'tcx, U> . where . F: FnOnce(T) -> U, . { 205,644 ( 0.00%) let value = f(self.0); . if cfg!(debug_assertions) { . let mut validator = ValidateBoundVars::new(self.1); . value.visit_with(&mut validator); . } 2,968,933 ( 0.01%) Binder(value, self.1) 232 ( 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); . } 90,290 ( 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); . } 208,204 ( 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>, . { 2,244,425 ( 0.01%) if self.0.has_escaping_bound_vars() { None } else { Some(self.skip_binder()) } 495 ( 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`. 20,129 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] 1,656,280 ( 0.00%) #[derive(HashStable, TypeFoldable)] . pub struct ProjectionTy<'tcx> { . /// The parameters of the associated item. 1,158,032 ( 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`. 1,869,214 ( 0.01%) pub item_def_id: DefId, . } . . impl<'tcx> ProjectionTy<'tcx> { 225,925 ( 0.00%) pub fn trait_def_id(&self, tcx: TyCtxt<'tcx>) -> DefId { 64,550 ( 0.00%) tcx.associated_item(self.item_def_id).container.id() 258,200 ( 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 657,720 ( 0.00%) pub fn trait_ref_and_own_substs( . &self, . tcx: TyCtxt<'tcx>, . ) -> (ty::TraitRef<'tcx>, &'tcx [ty::GenericArg<'tcx>]) { 281,880 ( 0.00%) let def_id = tcx.associated_item(self.item_def_id).container.id(); . let trait_generics = tcx.generics_of(def_id); 469,800 ( 0.00%) ( . ty::TraitRef { def_id, substs: self.substs.truncate_to(tcx, trait_generics) }, . &self.substs[trait_generics.count()..], . ) 845,640 ( 0.00%) } . . /// 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. 290,214 ( 0.00%) pub fn trait_ref(&self, tcx: TyCtxt<'tcx>) -> ty::TraitRef<'tcx> { 32,246 ( 0.00%) let def_id = self.trait_def_id(tcx); 32,246 ( 0.00%) ty::TraitRef { def_id, substs: self.substs.truncate_to(tcx, tcx.generics_of(def_id)) } 354,706 ( 0.00%) } . 64,980 ( 0.00%) pub fn self_ty(&self) -> Ty<'tcx> { 194,940 ( 0.00%) self.substs.type_at(0) 129,960 ( 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. 413,389 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] 222,752 ( 0.00%) #[derive(HashStable, TypeFoldable)] . pub struct FnSig<'tcx> { 10,708 ( 0.00%) pub inputs_and_output: &'tcx List>, 159,685 ( 0.00%) pub c_variadic: bool, 29,156 ( 0.00%) pub unsafety: hir::Unsafety, 174,791 ( 0.00%) pub abi: abi::Abi, . } . . impl<'tcx> FnSig<'tcx> { 240,396 ( 0.00%) pub fn inputs(&self) -> &'tcx [Ty<'tcx>] { 992,838 ( 0.00%) &self.inputs_and_output[..self.inputs_and_output.len() - 1] 480,792 ( 0.00%) } . 158,028 ( 0.00%) pub fn output(&self) -> Ty<'tcx> { 1,136,082 ( 0.00%) self.inputs_and_output[self.inputs_and_output.len() - 1] 316,056 ( 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>]> { 78,447 ( 0.00%) self.map_bound_ref_unchecked(|fn_sig| fn_sig.inputs()) . } . #[inline] . pub fn input(&self, index: usize) -> ty::Binder<'tcx, Ty<'tcx>> { 220,984 ( 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) 5,728 ( 0.00%) } . #[inline] . pub fn output(&self) -> ty::Binder<'tcx, Ty<'tcx>> { 166,917 ( 0.00%) self.map_bound_ref(|fn_sig| fn_sig.output()) . } . pub fn c_variadic(&self) -> bool { 11,456 ( 0.00%) self.skip_binder().c_variadic 5,728 ( 0.00%) } . pub fn unsafety(&self) -> hir::Unsafety { 29,138 ( 0.00%) self.skip_binder().unsafety 14,569 ( 0.00%) } . pub fn abi(&self) -> abi::Abi { 34,208 ( 0.00%) self.skip_binder().abi 8,552 ( 0.00%) } . } . . pub type CanonicalPolyFnSig<'tcx> = Canonical<'tcx, Binder<'tcx, FnSig<'tcx>>>; . 88 ( 0.00%) #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] . #[derive(HashStable)] . pub struct ParamTy { 32 ( 0.00%) pub index: u32, . pub name: Symbol, . } . . impl<'tcx> ParamTy { 6,680 ( 0.00%) pub fn new(index: u32, name: Symbol) -> ParamTy { . ParamTy { index, name } 3,340 ( 0.00%) } . . pub fn for_def(def: &ty::GenericParamDef) -> ParamTy { 54 ( 0.00%) ParamTy::new(def.index, def.name) 27 ( 0.00%) } . . #[inline] . 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 { 106 ( 0.00%) pub index: u32, 106 ( 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 37,319,378 ( 0.11%) #[derive(Clone, PartialEq, Eq, Hash, Copy, TyEncodable, TyDecodable, PartialOrd, Ord)] 26 ( 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. 1,513,942 ( 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, . } . 95,462 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, Debug, PartialOrd, Ord)] . pub struct EarlyBoundRegion { 436,850 ( 0.00%) pub def_id: DefId, 242,280 ( 0.00%) pub index: u32, 1,363,498 ( 0.00%) pub name: Symbol, . } . . /// A **`const`** **v**ariable **ID**. . #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] . pub struct ConstVid<'tcx> { 18,952 ( 0.00%) pub index: u32, 597 ( 0.00%) pub phantom: PhantomData<&'tcx ()>, . } . . rustc_index::newtype_index! { . /// A **region** (lifetime) **v**ariable **ID**. . pub struct RegionVid { . DEBUG_FORMAT = custom, . } . } -- line 1505 ---------------------------------------- -- 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, 69,862 ( 0.00%) pub kind: BoundTyKind, . } . 1,187,753 ( 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 { 26,832 ( 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 { 1,820,606 ( 0.01%) match *self { . ty::ReLateBound(debruijn, _) => debruijn >= index, . _ => false, . } . } . . pub fn type_flags(&self) -> TypeFlags { . let mut flags = TypeFlags::empty(); . 1,611,808 ( 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 310,997 ( 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 { 42,622 ( 0.00%) match self.kind() { 8,254 ( 0.00%) Tuple(ref tys) => tys.is_empty(), . _ => false, . } . } . . #[inline] . pub fn is_never(&self) -> bool { 521,105 ( 0.00%) 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 { 711,131 ( 0.00%) matches!(self.kind(), Infer(TyVar(_))) . } . . #[inline] . pub fn ty_vid(&self) -> Option { 608,502 ( 0.00%) match self.kind() { 106,595 ( 0.00%) &Infer(TyVar(vid)) => Some(vid), . _ => None, . } . } . . #[inline] . pub fn is_ty_infer(&self) -> bool { 87 ( 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] . pub fn is_bool(&self) -> bool { 102 ( 0.00%) *self.kind() == Bool . } . . /// Returns `true` if this type is a `str`. . #[inline] . pub fn is_str(&self) -> bool { . *self.kind() == Str . } . . #[inline] . pub fn is_param(&self, index: u32) -> bool { 10,420 ( 0.00%) match self.kind() { . ty::Param(ref data) => data.index == index, . _ => false, . } . } . . #[inline] . pub fn is_slice(&self) -> bool { . match self.kind() { . RawPtr(TypeAndMut { ty, .. }) | Ref(_, ty, _) => matches!(ty.kind(), Slice(_) | Str), . _ => false, . } . } . . #[inline] . pub fn is_array(&self) -> bool { 26 ( 0.00%) matches!(self.kind(), Array(..)) . } . . #[inline] . pub fn is_simd(&self) -> bool { . match self.kind() { . Adt(def, _) => def.repr.simd(), . _ => false, . } . } . 490 ( 0.00%) pub fn sequence_element_type(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { 980 ( 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), . } 490 ( 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 1838 ---------------------------------------- . } . } . _ => bug!("`simd_size_and_type` called on invalid type"), . } . } . . #[inline] . pub fn is_region_ptr(&self) -> bool { 187 ( 0.00%) matches!(self.kind(), Ref(..)) . } . . #[inline] . pub fn is_mutable_ptr(&self) -> bool { . matches!( . self.kind(), . RawPtr(TypeAndMut { mutbl: hir::Mutability::Mut, .. }) . | Ref(_, _, hir::Mutability::Mut) -- line 1854 ---------------------------------------- -- line 1861 ---------------------------------------- . match self.kind() { . Ref(_, _, mutability) => Some(*mutability), . _ => None, . } . } . . #[inline] . pub fn is_unsafe_ptr(&self) -> bool { 35,086 ( 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 { 685,050 ( 0.00%) match self.kind() { 140,034 ( 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 { 8,427 ( 0.00%) matches!( 19,671 ( 0.00%) self.kind(), . Bool | Char . | Int(_) . | Float(_) . | Uint(_) . | FnDef(..) . | FnPtr(_) . | RawPtr(_) . | Infer(IntVar(_) | FloatVar(_)) -- line 1908 ---------------------------------------- -- line 1922 ---------------------------------------- . . #[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 { 121,927 ( 0.00%) matches!(self.kind(), Adt(adt_def, _) if adt_def.is_union()) . } . . #[inline] . pub fn is_closure(&self) -> bool { 29,500 ( 0.00%) matches!(self.kind(), Closure(..)) . } . . #[inline] . pub fn is_generator(&self) -> bool { 44,458 ( 0.00%) matches!(self.kind(), Generator(..)) . } . . #[inline] . pub fn is_integral(&self) -> bool { 208,563 ( 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 { 24,864 ( 0.00%) matches!(self.kind(), Infer(FreshTy(_) | FreshIntTy(_) | FreshFloatTy(_))) . } . . #[inline] . pub fn is_char(&self) -> bool { . matches!(self.kind(), Char) . } . . #[inline] -- line 1963 ---------------------------------------- -- line 1967 ---------------------------------------- . . #[inline] . pub fn is_signed(&self) -> bool { . matches!(self.kind(), Int(_)) . } . . #[inline] . pub fn is_ptr_sized_integral(&self) -> bool { 8,904 ( 0.00%) matches!(self.kind(), Int(ty::IntTy::Isize) | Uint(ty::UintTy::Usize)) . } . . #[inline] . 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. 100,525 ( 0.00%) pub fn builtin_deref(&self, explicit: bool) -> Option> { 627,020 ( 0.00%) match self.kind() { 290 ( 0.00%) Adt(def, _) if def.is_box() => { . Some(TypeAndMut { ty: self.boxed_ty(), mutbl: hir::Mutability::Not }) . } 406,468 ( 0.00%) Ref(_, ty, mutbl) => Some(TypeAndMut { ty, mutbl: *mutbl }), . RawPtr(mt) if explicit => Some(*mt), . _ => None, . } 201,050 ( 0.00%) } . . /// Returns the type of `ty[i]`. . pub fn builtin_index(&self) -> Option> { 74,605 ( 0.00%) match self.kind() { . Array(ty, _) | Slice(ty) => Some(ty), . _ => None, . } 7,462 ( 0.00%) } . 523,744 ( 0.00%) pub fn fn_sig(&self, tcx: TyCtxt<'tcx>) -> PolyFnSig<'tcx> { 261,872 ( 0.00%) match self.kind() { 196,404 ( 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), . } 589,212 ( 0.00%) } . . #[inline] . pub fn is_fn(&self) -> bool { 30,234 ( 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> { 51,828 ( 0.00%) match self.kind() { . Adt(adt, _) => Some(adt), . _ => None, . } . } . . /// Iterates over tuple fields. . /// Panics when called on anything but a tuple. 66 ( 0.00%) pub fn tuple_fields(&self) -> impl DoubleEndedIterator> { 11,438 ( 0.00%) match self.kind() { 5,728 ( 0.00%) Tuple(substs) => substs.iter().map(|field| field.expect_ty()), . _ => bug!("tuple_fields called on non-tuple"), . } 132 ( 0.00%) } . . /// Get the `i`-th element of a tuple. . /// Panics when called on anything but a tuple. 3 ( 0.00%) pub fn tuple_element_ty(&self, i: usize) -> Option> { 6 ( 0.00%) match self.kind() { 6 ( 0.00%) Tuple(substs) => substs.iter().nth(i).map(|field| field.expect_ty()), . _ => bug!("tuple_fields called on non-tuple"), . } 6 ( 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] 860 ( 0.00%) pub fn discriminant_for_variant( . &self, . tcx: TyCtxt<'tcx>, . variant_index: VariantIdx, . ) -> Option> { 430 ( 0.00%) match self.kind() { 172 ( 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 . } 86 ( 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, . } 688 ( 0.00%) } . . /// Returns the type of the discriminant of this type. 124,170 ( 0.00%) pub fn discriminant_ty(&'tcx self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { 62,085 ( 0.00%) match self.kind() { 98,820 ( 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 2127 ---------------------------------------- . | ty::FnDef(..) . | ty::FnPtr(..) . | ty::Dynamic(..) . | ty::Closure(..) . | ty::GeneratorWitness(..) . | ty::Never . | ty::Tuple(_) . | ty::Error(_) 86 ( 0.00%) | 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) . } . } 99,336 ( 0.00%) } . . /// Returns the type of metadata for (potentially fat) pointers to this type. . pub fn ptr_metadata_ty( . &'tcx self, . tcx: TyCtxt<'tcx>, . normalize: impl FnMut(Ty<'tcx>) -> Ty<'tcx>, . ) -> Ty<'tcx> { . let tail = tcx.struct_tail_with_normalize(self, normalize); -- line 2151 ---------------------------------------- -- line 2200 ---------------------------------------- . /// 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. 452 ( 0.00%) pub fn to_opt_closure_kind(&self) -> Option { 904 ( 0.00%) match self.kind() { 904 ( 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), . } 452 ( 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`. 1,989,531 ( 0.01%) pub fn is_trivially_sized(&self, tcx: TyCtxt<'tcx>) -> bool { 1,326,354 ( 0.00%) 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, . 18,238 ( 0.00%) ty::Tuple(tys) => tys.iter().all(|ty| ty.expect_ty().is_trivially_sized(tcx)), . 193,806 ( 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) . } . } 1,989,531 ( 0.01%) } . } . . /// 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. . /// . /// When in doubt, use `VarianceDiagInfo::default()` 18 ( 0.00%) #[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] . pub enum VarianceDiagInfo<'tcx> { . /// No additional information - this is the default. . /// We will not add any additional information to error messages. . #[default] . None, . /// We switched our variance because a generic argument occurs inside . /// the invariant generic argument of another type. . Invariant { -- line 2290 ---------------------------------------- -- 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. 521,726 ( 0.00%) pub fn xform(self, other: VarianceDiagInfo<'tcx>) -> VarianceDiagInfo<'tcx> { . // For now, just use the first `VarianceDiagInfo::Invariant` that we see 782,589 ( 0.00%) match self { . VarianceDiagInfo::None => other, . VarianceDiagInfo::Invariant { .. } => self, . } 260,863 ( 0.00%) } . } 150,269,364 ( 0.43%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/subst.rs -------------------------------------------------------------------------------- Ir -- line 22 ---------------------------------------- . . /// An entity in the Rust type system, which can be one of . /// several kinds (types, lifetimes, and consts). . /// To reduce memory usage, a `GenericArg` is an interned pointer, . /// with the lowest 2 bits being reserved for a tag to . /// indicate the type (`Ty`, `Region`, or `Const`) it points to. . #[derive(Copy, Clone, PartialEq, Eq, Hash)] . pub struct GenericArg<'tcx> { 6,147,406 ( 0.02%) ptr: NonZeroUsize, 14,886,684 ( 0.04%) marker: PhantomData<(Ty<'tcx>, ty::Region<'tcx>, &'tcx ty::Const<'tcx>)>, . } . . const TAG_MASK: usize = 0b11; . const TYPE_TAG: usize = 0b00; . const REGION_TAG: usize = 0b01; . const CONST_TAG: usize = 0b10; . 107,448 ( 0.00%) #[derive(Debug, TyEncodable, TyDecodable, PartialEq, Eq, PartialOrd, Ord, HashStable)] . pub enum GenericArgKind<'tcx> { . Lifetime(ty::Region<'tcx>), . Type(Ty<'tcx>), . Const(&'tcx ty::Const<'tcx>), . } . . impl<'tcx> GenericArgKind<'tcx> { 19,301 ( 0.00%) fn pack(self) -> GenericArg<'tcx> { 19,301 ( 0.00%) let (tag, ptr) = match self { . GenericArgKind::Lifetime(lt) => { . // Ensure we can use the tag bits. . assert_eq!(mem::align_of_val(lt) & TAG_MASK, 0); . (REGION_TAG, lt as *const _ as usize) . } . GenericArgKind::Type(ty) => { . // Ensure we can use the tag bits. . assert_eq!(mem::align_of_val(ty) & TAG_MASK, 0); -- line 56 ---------------------------------------- -- line 58 ---------------------------------------- . } . GenericArgKind::Const(ct) => { . // Ensure we can use the tag bits. . assert_eq!(mem::align_of_val(ct) & TAG_MASK, 0); . (CONST_TAG, ct as *const _ as usize) . } . }; . 3,971,247 ( 0.01%) GenericArg { ptr: unsafe { NonZeroUsize::new_unchecked(ptr | tag) }, marker: PhantomData } 19,301 ( 0.00%) } . } . . impl<'tcx> fmt::Debug for GenericArg<'tcx> { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . match self.unpack() { . GenericArgKind::Lifetime(lt) => lt.fmt(f), . GenericArgKind::Type(ty) => ty.fmt(f), . GenericArgKind::Const(ct) => ct.fmt(f), . } . } . } . . impl<'tcx> Ord for GenericArg<'tcx> { 3 ( 0.00%) fn cmp(&self, other: &GenericArg<'_>) -> Ordering { 2 ( 0.00%) self.unpack().cmp(&other.unpack()) . } . } . . impl<'tcx> PartialOrd for GenericArg<'tcx> { . fn partial_cmp(&self, other: &GenericArg<'_>) -> Option { . Some(self.cmp(&other)) . } . } . . impl<'tcx> From> for GenericArg<'tcx> { 3,146,356 ( 0.01%) fn from(r: ty::Region<'tcx>) -> GenericArg<'tcx> { . GenericArgKind::Lifetime(r).pack() 3,146,356 ( 0.01%) } . } . . impl<'tcx> From> for GenericArg<'tcx> { 6,882,252 ( 0.02%) fn from(ty: Ty<'tcx>) -> GenericArg<'tcx> { . GenericArgKind::Type(ty).pack() 6,882,252 ( 0.02%) } . } . . impl<'tcx> From<&'tcx ty::Const<'tcx>> for GenericArg<'tcx> { 259 ( 0.00%) fn from(c: &'tcx ty::Const<'tcx>) -> GenericArg<'tcx> { . GenericArgKind::Const(c).pack() 259 ( 0.00%) } . } . . impl<'tcx> GenericArg<'tcx> { . #[inline] . pub fn unpack(self) -> GenericArgKind<'tcx> { . let ptr = self.ptr.get(); . unsafe { 96,437,326 ( 0.28%) match ptr & TAG_MASK { 1,689,577 ( 0.00%) REGION_TAG => GenericArgKind::Lifetime(&*((ptr & !TAG_MASK) as *const _)), 21,854,436 ( 0.06%) TYPE_TAG => GenericArgKind::Type(&*((ptr & !TAG_MASK) as *const _)), 15,897 ( 0.00%) CONST_TAG => GenericArgKind::Const(&*((ptr & !TAG_MASK) as *const _)), . _ => intrinsics::unreachable(), . } . } . } . . /// Unpack the `GenericArg` as a type when it is known certainly to be a type. . /// This is true in cases where `Substs` is used in places where the kinds are known . /// to be limited (e.g. in tuples, where the only parameters are type parameters). . pub fn expect_ty(self) -> Ty<'tcx> { . match self.unpack() { . GenericArgKind::Type(ty) => ty, . _ => bug!("expected a type, but found another kind"), . } 92,538 ( 0.00%) } . . /// Unpack the `GenericArg` as a const when it is known certainly to be a const. . pub fn expect_const(self) -> &'tcx ty::Const<'tcx> { . match self.unpack() { . GenericArgKind::Const(c) => c, . _ => bug!("expected a const, but found another kind"), . } . } -- line 140 ---------------------------------------- -- line 170 ---------------------------------------- . GenericArgKind::Type(ty) => ty.visit_with(visitor), . GenericArgKind::Const(ct) => ct.visit_with(visitor), . } . } . } . . impl<'tcx, E: TyEncoder<'tcx>> Encodable for GenericArg<'tcx> { . fn encode(&self, e: &mut E) -> Result<(), E::Error> { 68,379 ( 0.00%) self.unpack().encode(e) . } . } . . impl<'tcx, D: TyDecoder<'tcx>> Decodable for GenericArg<'tcx> { 96,505 ( 0.00%) fn decode(d: &mut D) -> GenericArg<'tcx> { 96,505 ( 0.00%) GenericArgKind::decode(d).pack() . } . } . . /// A substitution mapping generic parameters to new values. . pub type InternalSubsts<'tcx> = List>; . . pub type SubstsRef<'tcx> = &'tcx InternalSubsts<'tcx>; . . impl<'a, 'tcx> InternalSubsts<'tcx> { . /// Interpret these substitutions as the substitutions of a closure type. . /// Closure substitutions have a particular structure controlled by the . /// compiler that encodes information like the signature and closure kind; . /// see `ty::ClosureSubsts` struct for more comments. 711 ( 0.00%) pub fn as_closure(&'a self) -> ClosureSubsts<'a> { . ClosureSubsts { substs: self } 711 ( 0.00%) } . . /// Interpret these substitutions as the substitutions of a generator type. . /// Generator substitutions have a particular structure controlled by the . /// compiler that encodes information like the signature and generator kind; . /// see `ty::GeneratorSubsts` struct for more comments. . pub fn as_generator(&'tcx self) -> GeneratorSubsts<'tcx> { . GeneratorSubsts { substs: self } . } -- line 208 ---------------------------------------- -- line 211 ---------------------------------------- . /// Inline const substitutions have a particular structure controlled by the . /// compiler that encodes information like the inferred type; . /// see `ty::InlineConstSubsts` struct for more comments. . pub fn as_inline_const(&'tcx self) -> InlineConstSubsts<'tcx> { . InlineConstSubsts { substs: self } . } . . /// Creates an `InternalSubsts` that maps each generic parameter to itself. 235,790 ( 0.00%) pub fn identity_for_item(tcx: TyCtxt<'tcx>, def_id: DefId) -> SubstsRef<'tcx> { 89,916 ( 0.00%) Self::for_item(tcx, def_id, |param, _| tcx.mk_param_from_def(param)) 212,211 ( 0.00%) } . . /// Creates an `InternalSubsts` for generic parameter definitions, . /// by calling closures to obtain each kind. . /// The closures get to observe the `InternalSubsts` as they're . /// being built, which can be used to correctly . /// substitute defaults of generic parameters. 833,685 ( 0.00%) pub fn for_item(tcx: TyCtxt<'tcx>, def_id: DefId, mut mk_kind: F) -> SubstsRef<'tcx> . where . F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>, . { . let defs = tcx.generics_of(def_id); . let count = defs.count(); . let mut substs = SmallVec::with_capacity(count); 353,596 ( 0.00%) Self::fill_item(&mut substs, tcx, defs, &mut mk_kind); 186,692 ( 0.00%) tcx.intern_substs(&substs) 840,114 ( 0.00%) } . . pub fn extend_to(&self, tcx: TyCtxt<'tcx>, def_id: DefId, mut mk_kind: F) -> SubstsRef<'tcx> . where . F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>, . { . Self::for_item(tcx, def_id, |param, substs| { . self.get(param.index as usize).cloned().unwrap_or_else(|| mk_kind(param, substs)) . }) . } . 1,453,125 ( 0.00%) pub fn fill_item( . substs: &mut SmallVec<[GenericArg<'tcx>; 8]>, . tcx: TyCtxt<'tcx>, . defs: &ty::Generics, . mk_kind: &mut F, . ) where . F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>, . { 601,996 ( 0.00%) if let Some(def_id) = defs.parent { . let parent_defs = tcx.generics_of(def_id); 130,266 ( 0.00%) Self::fill_item(substs, tcx, parent_defs, mk_kind); . } . Self::fill_single(substs, defs, mk_kind) 1,149,392 ( 0.00%) } . 5,576 ( 0.00%) pub fn fill_single( . substs: &mut SmallVec<[GenericArg<'tcx>; 8]>, . defs: &ty::Generics, . mk_kind: &mut F, . ) where . F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>, . { . substs.reserve(defs.params.len()); . for param in &defs.params { . let kind = mk_kind(param, substs); 886,323 ( 0.00%) assert_eq!(param.index as usize, substs.len()); . substs.push(kind); . } 5,576 ( 0.00%) } . . #[inline] . pub fn types(&'a self) -> impl DoubleEndedIterator> + 'a { . self.iter() . .filter_map(|k| if let GenericArgKind::Type(ty) = k.unpack() { Some(ty) } else { None }) . } . . #[inline] -- line 284 ---------------------------------------- -- line 302 ---------------------------------------- . self.iter().filter_map(|k| match k.unpack() { . GenericArgKind::Lifetime(_) => None, . generic => Some(generic), . }) . } . . #[inline] . pub fn type_at(&self, i: usize) -> Ty<'tcx> { 2,533,827 ( 0.01%) if let GenericArgKind::Type(ty) = self[i].unpack() { . ty . } else { . bug!("expected type for param #{} in {:?}", i, self); . } . } . . #[inline] . pub fn region_at(&self, i: usize) -> ty::Region<'tcx> { -- line 318 ---------------------------------------- -- line 350 ---------------------------------------- . /// impl X for U { fn f() {} } . /// ``` . /// . /// * If `self` is `[Self, S, T]`: the identity substs of `f` in the trait. . /// * If `source_ancestor` is the def_id of the trait. . /// * If `target_substs` is `[U]`, the substs for the impl. . /// * Then we will return `[U, T]`, the subst for `f` in the impl that . /// are needed for it to match the trait. 132,699 ( 0.00%) pub fn rebase_onto( . &self, . tcx: TyCtxt<'tcx>, . source_ancestor: DefId, . target_substs: SubstsRef<'tcx>, . ) -> SubstsRef<'tcx> { . let defs = tcx.generics_of(source_ancestor); 37,914 ( 0.00%) tcx.mk_substs(target_substs.iter().chain(self.iter().skip(defs.params.len()))) 151,656 ( 0.00%) } . . pub fn truncate_to(&self, tcx: TyCtxt<'tcx>, generics: &ty::Generics) -> SubstsRef<'tcx> { . tcx.mk_substs(self.iter().take(generics.count())) . } . } . . impl<'tcx> TypeFoldable<'tcx> for SubstsRef<'tcx> { 1,678,404 ( 0.00%) fn try_super_fold_with>( . self, . folder: &mut F, . ) -> Result { . // This code is hot enough that it's worth specializing for the most . // common length lists, to avoid the overhead of `SmallVec` creation. . // The match arms are in order of frequency. The 1, 2, and 0 cases are . // typically hit in 90--99.99% of cases. When folding doesn't change . // the substs, it's faster to reuse the existing substs rather than . // calling `intern_substs`. 27,418,516 ( 0.08%) match self.len() { . 1 => { 4,093,908 ( 0.01%) let param0 = self[0].try_fold_with(folder)?; 11,333,668 ( 0.03%) if param0 == self[0] { Ok(self) } else { Ok(folder.tcx().intern_substs(&[param0])) } . } . 2 => { 3,837,953 ( 0.01%) let param0 = self[0].try_fold_with(folder)?; 8,496,715 ( 0.02%) let param1 = self[1].try_fold_with(folder)?; 9,408,834 ( 0.03%) if param0 == self[0] && param1 == self[1] { . Ok(self) . } else { 7,800,673 ( 0.02%) Ok(folder.tcx().intern_substs(&[param0, param1])) . } . } . 0 => Ok(self), . _ => { . let params: SmallVec<[_; 8]> = 145,515 ( 0.00%) self.iter().map(|k| k.try_fold_with(folder)).collect::>()?; 17,760 ( 0.00%) if params[..] == self[..] { . Ok(self) . } else { 116,778 ( 0.00%) Ok(folder.tcx().intern_substs(¶ms)) . } . } . } 2,664,138 ( 0.01%) } . . fn super_visit_with>(&self, visitor: &mut V) -> ControlFlow { 3,012,524 ( 0.01%) self.iter().try_for_each(|t| t.visit_with(visitor)) . } . } . . /////////////////////////////////////////////////////////////////////////// . // Public trait `Subst` . // . // Just call `foo.subst(tcx, substs)` to perform a substitution across . // `foo`. Or use `foo.subst_spanned(tcx, substs, Some(span))` when -- line 420 ---------------------------------------- -- line 435 ---------------------------------------- . . impl<'tcx, T: TypeFoldable<'tcx>> Subst<'tcx> for T { . fn subst_spanned( . self, . tcx: TyCtxt<'tcx>, . substs: &[GenericArg<'tcx>], . span: Option, . ) -> T { 6,034,343 ( 0.02%) let mut folder = SubstFolder { tcx, substs, span, binders_passed: 0 }; . self.fold_with(&mut folder) . } . } . . /////////////////////////////////////////////////////////////////////////// . // The actual substitution engine itself is a type folder. . . struct SubstFolder<'a, 'tcx> { -- line 451 ---------------------------------------- -- line 456 ---------------------------------------- . span: Option, . . /// Number of region binders we have passed through while doing the substitution . binders_passed: u32, . } . . impl<'a, 'tcx> TypeFolder<'tcx> for SubstFolder<'a, 'tcx> { . fn tcx<'b>(&'b self) -> TyCtxt<'tcx> { 1,353,163 ( 0.00%) self.tcx . } . . fn fold_binder>( . &mut self, . t: ty::Binder<'tcx, T>, . ) -> ty::Binder<'tcx, T> { 1,728,028 ( 0.00%) self.binders_passed += 1; 386,658 ( 0.00%) let t = t.super_fold_with(self); 1,728,028 ( 0.00%) self.binders_passed -= 1; . t . } . 2,466,354 ( 0.01%) fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> { . // Note: This routine only handles regions that are bound on . // type declarations and other outer declarations, not those . // bound in *fn types*. Region substitution of the bound . // regions that appear in a function signature is done using . // the specialized routine `ty::replace_late_regions()`. 822,118 ( 0.00%) match *r { 711,282 ( 0.00%) ty::ReEarlyBound(data) => { 711,282 ( 0.00%) let rk = self.substs.get(data.index as usize).map(|k| k.unpack()); . match rk { 355,641 ( 0.00%) Some(GenericArgKind::Lifetime(lt)) => self.shift_region_through_binders(lt), . _ => { . let span = self.span.unwrap_or(DUMMY_SP); . let msg = format!( . "Region parameter out of range \ . when substituting in region {} (index={})", . data.name, data.index . ); . span_bug!(span, "{}", msg); . } . } . } . _ => r, . } 2,877,413 ( 0.01%) } . 4,939,365 ( 0.01%) fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { 1,646,455 ( 0.00%) if !t.needs_subst() { . return t; . } . 2,764,780 ( 0.01%) match *t.kind() { 4,629,610 ( 0.01%) ty::Param(p) => self.ty_for_param(p, t), 2,738,808 ( 0.01%) _ => t.super_fold_with(self), . } 5,949,935 ( 0.02%) } . 14,602 ( 0.00%) fn fold_const(&mut self, c: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> { 5,337 ( 0.00%) if let ty::ConstKind::Param(p) = c.val { . self.const_for_param(p, c) . } else { 16,677 ( 0.00%) c.super_fold_with(self) . } 1,864 ( 0.00%) } . . #[inline] . fn fold_mir_const(&mut self, c: mir::ConstantKind<'tcx>) -> mir::ConstantKind<'tcx> { . c.super_fold_with(self) . } . } . . impl<'a, 'tcx> SubstFolder<'a, 'tcx> { . fn ty_for_param(&self, p: ty::ParamTy, source_ty: Ty<'tcx>) -> Ty<'tcx> { . // Look up the type in the substitutions. It really should be in there. 1,851,844 ( 0.01%) let opt_ty = self.substs.get(p.index as usize).map(|k| k.unpack()); . let ty = match opt_ty { . Some(GenericArgKind::Type(ty)) => ty, . Some(kind) => { . let span = self.span.unwrap_or(DUMMY_SP); . span_bug!( . span, . "expected type for `{:?}` ({:?}/{}) but found {:?} \ . when substituting, substs={:?}", -- line 539 ---------------------------------------- -- line 562 ---------------------------------------- . } . . fn const_for_param( . &self, . p: ParamConst, . source_ct: &'tcx ty::Const<'tcx>, . ) -> &'tcx ty::Const<'tcx> { . // Look up the const in the substitutions. It really should be in there. 466 ( 0.00%) let opt_ct = self.substs.get(p.index as usize).map(|k| k.unpack()); . let ct = match opt_ct { . Some(GenericArgKind::Const(ct)) => ct, . Some(kind) => { . let span = self.span.unwrap_or(DUMMY_SP); . span_bug!( . span, . "expected const for `{:?}` ({:?}/{}) but found {:?} \ . when substituting substs={:?}", -- line 578 ---------------------------------------- -- line 645 ---------------------------------------- . fn shift_vars_through_binders>(&self, val: T) -> T { . debug!( . "shift_vars(val={:?}, binders_passed={:?}, has_escaping_bound_vars={:?})", . val, . self.binders_passed, . val.has_escaping_bound_vars() . ); . 3,345,543 ( 0.01%) if self.binders_passed == 0 || !val.has_escaping_bound_vars() { . return val; . } . . let result = ty::fold::shift_vars(self.tcx(), val, self.binders_passed); . debug!("shift_vars: shifted result = {:?}", result); . . result . } . . fn shift_region_through_binders(&self, region: ty::Region<'tcx>) -> ty::Region<'tcx> { 894,857 ( 0.00%) if self.binders_passed == 0 || !region.has_escaping_bound_vars() { . return region; . } . ty::fold::shift_region(self.tcx, region, self.binders_passed) . } . } . . /// Stores the user-given substs to reach some fully qualified path . /// (e.g., `::Item` or `::Item`). . #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyEncodable, TyDecodable)] 145,778 ( 0.00%) #[derive(HashStable, TypeFoldable, Lift)] . pub struct UserSubsts<'tcx> { . /// The substitutions for the item as given by the user. . pub substs: SubstsRef<'tcx>, . . /// The self type, in the case of a `::Item` path (when applied . /// to an inherent impl). See `UserSelfTy` below. 21,613 ( 0.00%) pub user_self_ty: Option>, . } . . /// Specifies the user-given self type. In the case of a path that . /// refers to a member in an inherent impl, this self type is . /// sometimes needed to constrain the type parameters on the impl. For . /// example, in this code: . /// . /// ``` -- line 689 ---------------------------------------- -- line 696 ---------------------------------------- . /// self type `Foo`. Then we can instantiate the parameters of . /// the impl (with the substs from `UserSubsts`) and apply those to . /// the self type, giving `Foo`. Finally, we unify that with . /// the self type here, which contains `?A` to be `&'static u32` . #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, TyEncodable, TyDecodable)] . #[derive(HashStable, TypeFoldable, Lift)] . pub struct UserSelfTy<'tcx> { . pub impl_def_id: DefId, 11,739 ( 0.00%) pub self_ty: Ty<'tcx>, . } 38,081,563 ( 0.11%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/closure.rs -------------------------------------------------------------------------------- Ir -- line 10 ---------------------------------------- . type Env; . } . . impl<'a, A, R> !Sync for Closure<'a, A, R> {} . impl<'a, A, R> !Send for Closure<'a, A, R> {} . . impl<'a, A, R, F: FnMut(A) -> R> From<&'a mut F> for Closure<'a, A, R> { . fn from(f: &'a mut F) -> Self { 13,587,273 ( 0.04%) unsafe extern "C" fn call R>(env: &mut Env, arg: A) -> R { . (*(env as *mut _ as *mut F))(arg) 18,116,364 ( 0.05%) } . Closure { call: call::, env: unsafe { &mut *(f as *mut _ as *mut Env) } } . } . } . . impl<'a, A, R> Closure<'a, A, R> { . pub fn call(&mut self, arg: A) -> R { 72,465,456 ( 0.21%) unsafe { (self.call)(self.env, arg) } . } . } -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_trait_selection/src/traits/fulfill.rs -------------------------------------------------------------------------------- Ir -- line 33 ---------------------------------------- . . impl<'tcx> ForestObligation for PendingPredicateObligation<'tcx> { . /// Note that we include both the `ParamEnv` and the `Predicate`, . /// as the `ParamEnv` can influence whether fulfillment succeeds . /// or fails. . type CacheKey = ty::ParamEnvAnd<'tcx, ty::Predicate<'tcx>>; . . fn as_cache_key(&self) -> Self::CacheKey { 3,167,631 ( 0.01%) self.obligation.param_env.and(self.obligation.predicate) . } . } . . /// The fulfillment context is used to drive trait resolution. It . /// consists of a list of obligations that must be (eventually) . /// satisfied. The job is to track which are satisfied, which yielded . /// errors, and which are still pending. At any point, users can call . /// `select_where_possible`, and the fulfillment context will try to do -- line 49 ---------------------------------------- -- line 79 ---------------------------------------- . // outside of any snapshot, so any use of it inside a snapshot . // will lead to trouble and therefore is checked against, but . // other fulfillment contexts sometimes do live inside of . // a snapshot (they don't *straddle* a snapshot, so there . // is no trouble there). . usable_in_snapshot: bool, . } . 2,760 ( 0.00%) #[derive(Clone, Debug)] . pub struct PendingPredicateObligation<'tcx> { . pub obligation: PredicateObligation<'tcx>, . // This is far more often read than modified, meaning that we . // should mostly optimize for reading speed, while modifying is not as relevant. . // . // For whatever reason using a boxed slice is slower than using a `Vec` here. . pub stalled_on: Vec>, . } . . // `PendingPredicateObligation` is used a lot. Make sure it doesn't unintentionally get bigger. . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . static_assert_size!(PendingPredicateObligation<'_>, 72); . . impl<'a, 'tcx> FulfillmentContext<'tcx> { . /// Creates a new fulfillment context. 77,757 ( 0.00%) pub fn new() -> FulfillmentContext<'tcx> { 942,298 ( 0.00%) FulfillmentContext { 82,611 ( 0.00%) predicates: ObligationForest::new(), . relationships: FxHashMap::default(), . register_region_obligations: true, . usable_in_snapshot: false, . } 77,757 ( 0.00%) } . . pub fn new_in_snapshot() -> FulfillmentContext<'tcx> { 90 ( 0.00%) FulfillmentContext { 30 ( 0.00%) predicates: ObligationForest::new(), . relationships: FxHashMap::default(), . register_region_obligations: true, . usable_in_snapshot: true, . } . } . . pub fn new_ignoring_regions() -> FulfillmentContext<'tcx> { 162,124 ( 0.00%) FulfillmentContext { 40,531 ( 0.00%) predicates: ObligationForest::new(), . relationships: FxHashMap::default(), . register_region_obligations: false, . usable_in_snapshot: false, . } . } . . /// Attempts to select obligations using `selcx`. . fn select(&mut self, selcx: &mut SelectionContext<'a, 'tcx>) -> Vec> { 815,700 ( 0.00%) let span = debug_span!("select", obligation_forest_size = ?self.predicates.len()); . let _enter = span.enter(); . . let mut errors = Vec::new(); . . loop { . debug!("select: starting another iteration"); . . // Process pending obligations. . let outcome: Outcome<_, _> = 3,588,837 ( 0.01%) self.predicates.process_obligations(&mut FulfillProcessor { . selcx, 512,691 ( 0.00%) register_region_obligations: self.register_region_obligations, . }); . debug!("select: outcome={:#?}", outcome); . . // FIXME: if we kept the original cache key, we could mark projection . // obligations as complete for the projection cache here. . . errors.extend(outcome.errors.into_iter().map(to_fulfillment_error)); . . // If nothing new was added, no need to keep looping. 1,025,382 ( 0.00%) if outcome.stalled { . break; . } . } . . debug!( . "select({} predicates remaining, {} errors) done", . self.predicates.len(), . errors.len() -- line 162 ---------------------------------------- -- line 169 ---------------------------------------- . impl<'tcx> TraitEngine<'tcx> for FulfillmentContext<'tcx> { . /// "Normalize" a projection type `::X` by . /// creating a fresh type variable `$0` as well as a projection . /// predicate `::X == $0`. When the . /// inference engine runs, it will attempt to find an impl of . /// `SomeTrait` or a where-clause that lets us unify `$0` with . /// something concrete. If this fails, we'll unify `$0` with . /// `projection_ty` again. 660 ( 0.00%) #[tracing::instrument(level = "debug", skip(self, infcx, param_env, cause))] . fn normalize_projection_type( . &mut self, . infcx: &InferCtxt<'_, 'tcx>, . param_env: ty::ParamEnv<'tcx>, . projection_ty: ty::ProjectionTy<'tcx>, . cause: ObligationCause<'tcx>, . ) -> Ty<'tcx> { . debug_assert!(!projection_ty.has_escaping_bound_vars()); . . // FIXME(#20304) -- cache . . let mut selcx = SelectionContext::new(infcx); . let mut obligations = vec![]; 270 ( 0.00%) let normalized_ty = project::normalize_projection_type( . &mut selcx, . param_env, . projection_ty, 150 ( 0.00%) cause, . 0, . &mut obligations, . ); . self.register_predicate_obligations(infcx, obligations); . . debug!(?normalized_ty); . . normalized_ty . } . 2,158,062 ( 0.01%) fn register_predicate_obligation( . &mut self, . infcx: &InferCtxt<'_, 'tcx>, . obligation: PredicateObligation<'tcx>, . ) { . // this helps to reduce duplicate errors, as well as making . // debug output much nicer to read and so on. 1,079,031 ( 0.00%) let obligation = infcx.resolve_vars_if_possible(obligation); . . debug!(?obligation, "register_predicate_obligation"); . 2,158,062 ( 0.01%) assert!(!infcx.is_in_snapshot() || self.usable_in_snapshot); . 1,079,031 ( 0.00%) super::relationships::update(self, infcx, &obligation); . . self.predicates . .register_obligation(PendingPredicateObligation { obligation, stalled_on: vec![] }); 1,798,385 ( 0.01%) } . 1,700,464 ( 0.00%) fn select_all_or_error(&mut self, infcx: &InferCtxt<'_, 'tcx>) -> Vec> { . { 212,558 ( 0.00%) let errors = self.select_where_possible(infcx); 212,558 ( 0.00%) if !errors.is_empty() { 475 ( 0.00%) return errors; . } . } . 1,062,315 ( 0.00%) self.predicates.to_errors(CodeAmbiguity).into_iter().map(to_fulfillment_error).collect() 1,487,906 ( 0.00%) } . 4,078,500 ( 0.01%) fn select_where_possible( . &mut self, . infcx: &InferCtxt<'_, 'tcx>, . ) -> Vec> { . let mut selcx = SelectionContext::new(infcx); . self.select(&mut selcx) 3,670,650 ( 0.01%) } . 2,532 ( 0.00%) fn pending_obligations(&self) -> Vec> { . self.predicates.map_pending_obligations(|o| o.obligation.clone()) 3,376 ( 0.00%) } . . fn relationships(&mut self) -> &mut FxHashMap { 786 ( 0.00%) &mut self.relationships 786 ( 0.00%) } . } . . struct FulfillProcessor<'a, 'b, 'tcx> { . selcx: &'a mut SelectionContext<'b, 'tcx>, . register_region_obligations: bool, . } . . fn mk_pending(os: Vec>) -> Vec> { -- line 258 ---------------------------------------- -- line 275 ---------------------------------------- . #[inline(always)] . fn process_obligation( . &mut self, . pending_obligation: &mut Self::Obligation, . ) -> ProcessResult { . // If we were stalled on some unresolved variables, first check whether . // any of them have been resolved; if not, don't bother doing more work . // yet. 18,508,431 ( 0.05%) let change = match pending_obligation.stalled_on.len() { . // Match arms are in order of frequency, which matters because this . // code is so hot. 1 and 0 dominate; 2+ is fairly rare. . 1 => { 8,605,515 ( 0.02%) let infer_var = pending_obligation.stalled_on[0]; 2,868,505 ( 0.01%) self.selcx.infcx().ty_or_const_infer_var_changed(infer_var) . } . 0 => { . // In this case we haven't changed, but wish to make a change. . true . } . _ => { . // This `for` loop was once a call to `all()`, but this lower-level . // form was a perf win. See #64545 for details. 103,125 ( 0.00%) (|| { 205,983 ( 0.00%) for &infer_var in &pending_obligation.stalled_on { 596 ( 0.00%) if self.selcx.infcx().ty_or_const_infer_var_changed(infer_var) { . return true; . } . } . false . })() . } . }; . -- line 307 ---------------------------------------- -- line 309 ---------------------------------------- . debug!( . "process_predicate: pending obligation {:?} still stalled on {:?}", . self.selcx.infcx().resolve_vars_if_possible(pending_obligation.obligation.clone()), . pending_obligation.stalled_on . ); . return ProcessResult::Unchanged; . } . 1,401,795 ( 0.00%) self.progress_changed_obligations(pending_obligation) . } . . fn process_backedge<'c, I>( . &mut self, . cycle: I, . _marker: PhantomData<&'c PendingPredicateObligation<'tcx>>, . ) where . I: Clone + Iterator>, -- line 325 ---------------------------------------- -- line 333 ---------------------------------------- . } . } . . impl<'a, 'b, 'tcx> FulfillProcessor<'a, 'b, 'tcx> { . // The code calling this method is extremely hot and only rarely . // actually uses this, so move this part of the code . // out of that loop. . #[inline(never)] 4,672,650 ( 0.01%) fn progress_changed_obligations( . &mut self, . pending_obligation: &mut PendingPredicateObligation<'tcx>, . ) -> ProcessResult, FulfillmentErrorCode<'tcx>> { . pending_obligation.stalled_on.truncate(0); . . let obligation = &mut pending_obligation.obligation; . 1,401,795 ( 0.00%) if obligation.predicate.has_infer_types_or_consts() { 270,134 ( 0.00%) obligation.predicate = 810,402 ( 0.00%) self.selcx.infcx().resolve_vars_if_possible(obligation.predicate); . } . . debug!(?obligation, ?obligation.cause, "process_obligation"); . . let infcx = self.selcx.infcx(); . 394,262 ( 0.00%) let binder = obligation.predicate.kind(); 3,270,855 ( 0.01%) match binder.no_bound_vars() { 2,761 ( 0.00%) None => match binder.skip_binder() { . // Evaluation will discard candidates using the leak check. . // This means we need to pass it the bound version of our . // predicate. . ty::PredicateKind::Trait(trait_ref) => { . let trait_obligation = obligation.with(binder.rebind(trait_ref)); . 1,004 ( 0.00%) self.process_trait_obligation( . obligation, 3,012 ( 0.00%) trait_obligation, . &mut pending_obligation.stalled_on, . ) . } . ty::PredicateKind::Projection(data) => { . let project_obligation = obligation.with(binder.rebind(data)); . . self.process_projection_obligation( . obligation, -- line 377 ---------------------------------------- -- line 397 ---------------------------------------- . ty::PredicateKind::TypeWellFormedFromEnv(..) => { . bug!("TypeWellFormedFromEnv is only used for Chalk") . } . }, . Some(pred) => match pred { . ty::PredicateKind::Trait(data) => { . let trait_obligation = obligation.with(Binder::dummy(data)); . 1,271,700 ( 0.00%) self.process_trait_obligation( . obligation, 5,595,480 ( 0.02%) trait_obligation, . &mut pending_obligation.stalled_on, . ) . } . . ty::PredicateKind::RegionOutlives(data) => { 74,910 ( 0.00%) match infcx.region_outlives_predicate(&obligation.cause, Binder::dummy(data)) { 49,940 ( 0.00%) Ok(()) => ProcessResult::Changed(vec![]), . Err(_) => ProcessResult::Error(CodeSelectionError(Unimplemented)), . } . } . . ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(t_a, r_b)) => { 53,734 ( 0.00%) if self.register_region_obligations { 134,335 ( 0.00%) self.selcx.infcx().register_region_obligation_with_cause( . t_a, . r_b, . &obligation.cause, . ); . } . ProcessResult::Changed(vec![]) . } . . ty::PredicateKind::Projection(ref data) => { . let project_obligation = obligation.with(Binder::dummy(*data)); . 69,495 ( 0.00%) self.process_projection_obligation( . obligation, 208,485 ( 0.00%) project_obligation, . &mut pending_obligation.stalled_on, . ) . } . . ty::PredicateKind::ObjectSafe(trait_def_id) => { 2,052 ( 0.00%) if !self.selcx.tcx().is_object_safe(trait_def_id) { . ProcessResult::Error(CodeSelectionError(Unimplemented)) . } else { . ProcessResult::Changed(vec![]) . } . } . . ty::PredicateKind::ClosureKind(_, closure_substs, kind) => { 201 ( 0.00%) match self.selcx.infcx().closure_kind(closure_substs) { . Some(closure_kind) => { 402 ( 0.00%) if closure_kind.extends(kind) { . ProcessResult::Changed(vec![]) . } else { . ProcessResult::Error(CodeSelectionError(Unimplemented)) . } . } . None => ProcessResult::Unchanged, . } . } . . ty::PredicateKind::WellFormed(arg) => { 1,039,143 ( 0.00%) match wf::obligations( . self.selcx.infcx(), 296,898 ( 0.00%) obligation.param_env, 296,898 ( 0.00%) obligation.cause.body_id, 445,347 ( 0.00%) obligation.recursion_depth + 1, . arg, . obligation.cause.span, . ) { . None => { 143,976 ( 0.00%) pending_obligation.stalled_on = 251,958 ( 0.00%) vec![TyOrConstInferVar::maybe_from_generic_arg(arg).unwrap()]; 71,988 ( 0.00%) ProcessResult::Unchanged . } 337,365 ( 0.00%) Some(os) => ProcessResult::Changed(mk_pending(os)), . } . } . . ty::PredicateKind::Subtype(subtype) => { 73,520 ( 0.00%) match self.selcx.infcx().subtype_predicate( . &obligation.cause, . obligation.param_env, . Binder::dummy(subtype), . ) { . None => { . // None means that both are unresolved. 37,095 ( 0.00%) pending_obligation.stalled_on = vec![ 7,419 ( 0.00%) TyOrConstInferVar::maybe_from_ty(subtype.a).unwrap(), 14,838 ( 0.00%) TyOrConstInferVar::maybe_from_ty(subtype.b).unwrap(), . ]; . ProcessResult::Unchanged . } . Some(Ok(ok)) => ProcessResult::Changed(mk_pending(ok.obligations)), . Some(Err(err)) => { . let expected_found = . ExpectedFound::new(subtype.a_is_expected, subtype.a, subtype.b); . ProcessResult::Error(FulfillmentErrorCode::CodeSubtypeError( -- line 497 ---------------------------------------- -- line 498 ---------------------------------------- . expected_found, . err, . )) . } . } . } . . ty::PredicateKind::Coerce(coerce) => { 9,632 ( 0.00%) match self.selcx.infcx().coerce_predicate( . &obligation.cause, . obligation.param_env, . Binder::dummy(coerce), . ) { . None => { . // None means that both are unresolved. 3,010 ( 0.00%) pending_obligation.stalled_on = vec![ 602 ( 0.00%) TyOrConstInferVar::maybe_from_ty(coerce.a).unwrap(), 1,204 ( 0.00%) TyOrConstInferVar::maybe_from_ty(coerce.b).unwrap(), . ]; . ProcessResult::Unchanged . } . Some(Ok(ok)) => ProcessResult::Changed(mk_pending(ok.obligations)), . Some(Err(err)) => { . let expected_found = ExpectedFound::new(false, coerce.a, coerce.b); . ProcessResult::Error(FulfillmentErrorCode::CodeSubtypeError( . expected_found, -- line 523 ---------------------------------------- -- line 639 ---------------------------------------- . } . } . } . ty::PredicateKind::TypeWellFormedFromEnv(..) => { . bug!("TypeWellFormedFromEnv is only used for Chalk") . } . }, . } 4,205,385 ( 0.01%) } . 4,837,229 ( 0.01%) #[instrument(level = "debug", skip(self, obligation, stalled_on))] . fn process_trait_obligation( . &mut self, . obligation: &PredicateObligation<'tcx>, . trait_obligation: TraitObligation<'tcx>, . stalled_on: &mut Vec>, . ) -> ProcessResult, FulfillmentErrorCode<'tcx>> { 254,591 ( 0.00%) let infcx = self.selcx.infcx(); 763,773 ( 0.00%) if obligation.predicate.is_global() { . // no type variables present, can use evaluation for better caching. . // FIXME: consider caching errors too. 152,828 ( 0.00%) if infcx.predicate_must_hold_considering_regions(obligation) { . debug!( . "selecting trait at depth {} evaluated to holds", . obligation.recursion_depth . ); 151,090 ( 0.00%) return ProcessResult::Changed(vec![]); . } . } . 1,253,130 ( 0.00%) match self.selcx.select(&trait_obligation) { . Ok(Some(impl_source)) => { . debug!("selecting trait at depth {} yielded Ok(Some)", obligation.recursion_depth); 2,172,906 ( 0.01%) ProcessResult::Changed(mk_pending(impl_source.nested_obligations())) . } . Ok(None) => { . debug!("selecting trait at depth {} yielded Ok(None)", obligation.recursion_depth); . . // This is a bit subtle: for the most part, the . // only reason we can fail to make progress on . // trait selection is because we don't have enough . // information about the types in the trait. . stalled_on.clear(); . stalled_on.extend(substs_infer_vars( . self.selcx, 58,233 ( 0.00%) trait_obligation.predicate.map_bound(|pred| pred.trait_ref.substs), . )); . . debug!( . "process_predicate: pending obligation {:?} now stalled on {:?}", . infcx.resolve_vars_if_possible(obligation.clone()), . stalled_on . ); . 58,233 ( 0.00%) ProcessResult::Unchanged . } . Err(selection_err) => { . debug!("selecting trait at depth {} yielded Err", obligation.recursion_depth); . 1,344 ( 0.00%) ProcessResult::Error(CodeSelectionError(selection_err)) . } . } . } . 152,889 ( 0.00%) fn process_projection_obligation( . &mut self, . obligation: &PredicateObligation<'tcx>, . project_obligation: PolyProjectionObligation<'tcx>, . stalled_on: &mut Vec>, . ) -> ProcessResult, FulfillmentErrorCode<'tcx>> { 13,899 ( 0.00%) let tcx = self.selcx.tcx(); . 41,697 ( 0.00%) if obligation.predicate.is_global() { . // no type variables present, can use evaluation for better caching. . // FIXME: consider caching errors too. 302 ( 0.00%) if self.selcx.infcx().predicate_must_hold_considering_regions(obligation) { 906 ( 0.00%) if let Some(key) = ProjectionCacheKey::from_poly_projection_predicate( . &mut self.selcx, 1,057 ( 0.00%) project_obligation.predicate, . ) { . // If `predicate_must_hold_considering_regions` succeeds, then we've . // evaluated all sub-obligations. We can therefore mark the 'root' . // obligation as complete, and skip evaluating sub-obligations. 906 ( 0.00%) self.selcx . .infcx() . .inner . .borrow_mut() . .projection_cache() . .complete(key, EvaluationResult::EvaluatedToOk); . } 302 ( 0.00%) return ProcessResult::Changed(vec![]); . } else { . tracing::debug!("Does NOT hold: {:?}", obligation); . } . } . 96,236 ( 0.00%) match project::poly_project_and_unify_type(self.selcx, &project_obligation) { . Ok(Ok(Some(os))) => ProcessResult::Changed(mk_pending(os)), . Ok(Ok(None)) => { . stalled_on.clear(); . stalled_on.extend(substs_infer_vars( . self.selcx, 6,950 ( 0.00%) project_obligation.predicate.map_bound(|pred| pred.projection_ty.substs), . )); 6,950 ( 0.00%) ProcessResult::Unchanged . } . // Let the caller handle the recursion . Ok(Err(project::InProgress)) => ProcessResult::Changed(mk_pending(vec![ . project_obligation.with(project_obligation.predicate.to_predicate(tcx)), . ])), . Err(e) => ProcessResult::Error(CodeProjectionError(e)), . } 111,192 ( 0.00%) } . } . . /// Returns the set of inference variables contained in `substs`. . fn substs_infer_vars<'a, 'tcx>( . selcx: &mut SelectionContext<'a, 'tcx>, . substs: ty::Binder<'tcx, SubstsRef<'tcx>>, . ) -> impl Iterator> { . selcx . .infcx() . .resolve_vars_if_possible(substs) . .skip_binder() // ok because this check doesn't care about regions . .iter() . .filter(|arg| arg.has_infer_types_or_consts()) . .flat_map(|arg| { 328,090 ( 0.00%) let mut walker = arg.walk(); 592,052 ( 0.00%) while let Some(c) = walker.next() { 65,920 ( 0.00%) if !c.has_infer_types_or_consts() { . walker.visited.remove(&c); 12 ( 0.00%) walker.skip_current_subtree(); . } . } . walker.visited.into_iter() . }) . .filter_map(TyOrConstInferVar::maybe_from_generic_arg) . } . . fn to_fulfillment_error<'tcx>( . error: Error, FulfillmentErrorCode<'tcx>>, . ) -> FulfillmentError<'tcx> { . let mut iter = error.backtrace.into_iter(); 96 ( 0.00%) let obligation = iter.next().unwrap().obligation; . // The root obligation is the last item in the backtrace - if there's only . // one item, then it's the same as the main obligation . let root_obligation = iter.next_back().map_or_else(|| obligation.clone(), |e| e.obligation); 2,880 ( 0.00%) FulfillmentError::new(obligation, error.error, root_obligation) . } 16,724,791 ( 0.05%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/proc_macro/src/bridge/client.rs -------------------------------------------------------------------------------- Ir -- line 18 ---------------------------------------- . // FIXME(eddyb) use a reference to the `static COUNTERS`, instead of . // a wrapper `fn` pointer, once `const fn` can reference `static`s. . extern "C" fn get() -> &'static Self { . static COUNTERS: HandleCounters = HandleCounters { . $($oty: AtomicUsize::new(1),)* . $($ity: AtomicUsize::new(1),)* . }; . &COUNTERS 1,320 ( 0.00%) } . } . . // FIXME(eddyb) generate the definition of `HandleStore` in `server.rs`. . #[repr(C)] . #[allow(non_snake_case)] . pub(super) struct HandleStore { . $($oty: handle::OwnedStore,)* . $($ity: handle::InternedStore,)* . } . . impl HandleStore { 3,960 ( 0.00%) pub(super) fn new(handle_counters: &'static HandleCounters) -> Self { 38,940 ( 0.00%) HandleStore { . $($oty: handle::OwnedStore::new(&handle_counters.$oty),)* . $($ity: handle::InternedStore::new(&handle_counters.$ity),)* . } 5,280 ( 0.00%) } . } . . $( . #[repr(C)] . pub(crate) struct $oty(handle::Handle); . impl !Send for $oty {} . impl !Sync for $oty {} . . // Forward `Drop::drop` to the inherent `drop` method. . impl Drop for $oty { 69,744 ( 0.00%) fn drop(&mut self) { 386,446 ( 0.00%) $oty(self.0).drop(); 104,616 ( 0.00%) } . } . . impl Encode for $oty { 5,280 ( 0.00%) fn encode(self, w: &mut Writer, s: &mut S) { 1,980 ( 0.00%) let handle = self.0; 2,640 ( 0.00%) mem::forget(self); 660 ( 0.00%) handle.encode(w, s); 1,320 ( 0.00%) } . } . . impl DecodeMut<'_, '_, HandleStore>> . for Marked . { 3,623,709 ( 0.01%) fn decode(r: &mut Reader<'_>, s: &mut HandleStore>) -> Self { . s.$oty.take(handle::Handle::decode(r, &mut ())) 4,831,612 ( 0.01%) } . } . . impl Encode for &$oty { . fn encode(self, w: &mut Writer, s: &mut S) { 646,623 ( 0.00%) self.0.encode(w, s); . } . } . . impl<'s, S: server::Types> Decode<'_, 's, HandleStore>> . for &'s Marked . { 215,541 ( 0.00%) fn decode(r: &mut Reader<'_>, s: &'s HandleStore>) -> Self { . &s.$oty[handle::Handle::decode(r, &mut ())] 431,082 ( 0.00%) } . } . . impl Encode for &mut $oty { . fn encode(self, w: &mut Writer, s: &mut S) { 2,840,634 ( 0.01%) self.0.encode(w, s); . } . } . . impl<'s, S: server::Types> DecodeMut<'_, 's, HandleStore>> . for &'s mut Marked . { 946,878 ( 0.00%) fn decode( . r: &mut Reader<'_>, . s: &'s mut HandleStore> . ) -> Self { . &mut s.$oty[handle::Handle::decode(r, &mut ())] 1,893,756 ( 0.01%) } . } . . impl Encode>> . for Marked . { 7,159,686 ( 0.02%) fn encode(self, w: &mut Writer, s: &mut HandleStore>) { 1,157,968 ( 0.00%) s.$oty.alloc(self).encode(w, s); . } . } . . impl DecodeMut<'_, '_, S> for $oty { 1,980 ( 0.00%) fn decode(r: &mut Reader<'_>, s: &mut S) -> Self { 1,980 ( 0.00%) $oty(handle::Handle::decode(r, s)) 1,980 ( 0.00%) } . } . )* . . $( . #[repr(C)] 2,488,724 ( 0.01%) #[derive(Copy, Clone, PartialEq, Eq, Hash)] . pub(crate) struct $ity(handle::Handle); . impl !Send for $ity {} . impl !Sync for $ity {} . . impl Encode for $ity { . fn encode(self, w: &mut Writer, s: &mut S) { . self.0.encode(w, s); . } . } . . impl DecodeMut<'_, '_, HandleStore>> . for Marked . { 1,059,529 ( 0.00%) fn decode(r: &mut Reader<'_>, s: &mut HandleStore>) -> Self { . s.$ity.copy(handle::Handle::decode(r, &mut ())) 2,119,058 ( 0.01%) } . } . . impl Encode>> . for Marked . { . fn encode(self, w: &mut Writer, s: &mut HandleStore>) { 8,987,434 ( 0.03%) s.$ity.alloc(self).encode(w, s); . } . } . . impl DecodeMut<'_, '_, S> for $ity { . fn decode(r: &mut Reader<'_>, s: &mut S) -> Self { . $ity(handle::Handle::decode(r, s)) . } . } -- line 154 ---------------------------------------- -- line 175 ---------------------------------------- . . // FIXME(eddyb) generate these impls by pattern-matching on the . // names of methods - also could use the presence of `fn drop` . // to distinguish between 'owned and 'interned, above. . // Alternatively, special 'modes" could be listed of types in with_api . // instead of pattern matching on methods, here and in server decl. . . impl Clone for TokenStream { 103,443 ( 0.00%) fn clone(&self) -> Self { . self.clone() 103,443 ( 0.00%) } . } . . impl Clone for TokenStreamIter { . fn clone(&self) -> Self { . self.clone() . } . } . . impl Clone for Group { 68,649 ( 0.00%) fn clone(&self) -> Self { . self.clone() 68,649 ( 0.00%) } . } . . impl Clone for Literal { 13,944 ( 0.00%) fn clone(&self) -> Self { . self.clone() 13,944 ( 0.00%) } . } . . impl fmt::Debug for Literal { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . f.debug_struct("Literal") . // format the kind without quotes, as in `kind: Float` . .field("kind", &format_args!("{}", &self.debug_kind())) . .field("symbol", &self.symbol()) -- line 211 ---------------------------------------- -- line 219 ---------------------------------------- . impl Clone for SourceFile { . fn clone(&self) -> Self { . self.clone() . } . } . . impl fmt::Debug for Span { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 142,125 ( 0.00%) f.write_str(&self.debug()) . } . } . . macro_rules! define_client_side { . ($($name:ident { . $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)*;)* . }),* $(,)?) => { . $(impl $name { 5,012,256 ( 0.01%) $(pub(crate) fn $method($($arg: $arg_ty),*) $(-> $ret_ty)* { 2,568,332 ( 0.01%) Bridge::with(|bridge| { . let mut b = bridge.cached_buffer.take(); . . b.clear(); 13,587,273 ( 0.04%) api_tags::Method::$name(api_tags::$name::$method).encode(&mut b, &mut ()); 3,890,230 ( 0.01%) reverse_encode!(b; $($arg),*); . 27,174,546 ( 0.08%) b = bridge.dispatch.call(b); . 19,066,680 ( 0.05%) let r = Result::<_, PanicMessage>::decode(&mut &b[..], &mut ()); . 54,349,092 ( 0.16%) bridge.cached_buffer = b; . 6,786,057 ( 0.02%) r.unwrap_or_else(|e| panic::resume_unwind(e.into())) . }) 4,176,880 ( 0.01%) })* . })* . } . } . with_api!(self, self, define_client_side); . . enum BridgeState<'a> { . /// No server is currently connected to this client. . NotConnected, -- line 260 ---------------------------------------- -- line 270 ---------------------------------------- . enum BridgeStateL {} . . impl<'a> scoped_cell::ApplyL<'a> for BridgeStateL { . type Out = BridgeState<'a>; . } . . thread_local! { . static BRIDGE_STATE: scoped_cell::ScopedCell = 3 ( 0.00%) scoped_cell::ScopedCell::new(BridgeState::NotConnected); . } . . impl BridgeState<'_> { . /// Take exclusive control of the thread-local . /// `BridgeState`, and pass it to `f`, mutably. . /// The state will be restored after `f` exits, even . /// by panic, including modifications made to it by `f`. . /// . /// N.B., while `f` is running, the thread-local state . /// is `BridgeState::InUse`. 2,228,425 ( 0.01%) fn with(f: impl FnOnce(&mut BridgeState<'_>) -> R) -> R { 2,275,354 ( 0.01%) BRIDGE_STATE.with(|state| { 24,757,901 ( 0.07%) state.replace(BridgeState::InUse, |mut state| { . // FIXME(#52812) pass `f` directly to `replace` when `RefMutL` is gone 15,840 ( 0.00%) f(&mut *state) 2,640 ( 0.00%) }) 2,640 ( 0.00%) }) 1,911,063 ( 0.01%) } . } . . impl Bridge<'_> { . pub(crate) fn is_available() -> bool { 3 ( 0.00%) BridgeState::with(|state| match state { . BridgeState::Connected(_) | BridgeState::InUse => true, . BridgeState::NotConnected => false, . }) . } . 3,960 ( 0.00%) fn enter(self, f: impl FnOnce() -> R) -> R { 4,620 ( 0.00%) let force_show_panics = self.force_show_panics; . // Hide the default panic output within `proc_macro` expansions. . // NB. the server can't do this because it may use a different libstd. . static HIDE_PANICS_DURING_EXPANSION: Once = Once::new(); 3,302 ( 0.00%) HIDE_PANICS_DURING_EXPANSION.call_once(|| { 7 ( 0.00%) panic::update_hook(move |prev, info| { . let show = BridgeState::with(|state| match state { . BridgeState::NotConnected => true, . BridgeState::Connected(_) | BridgeState::InUse => force_show_panics, . }); . if show { . prev(info) . } . }); 2 ( 0.00%) }); . 24,420 ( 0.00%) BRIDGE_STATE.with(|state| state.set(BridgeState::Connected(self), f)) 1,320 ( 0.00%) } . 3,300 ( 0.00%) fn with(f: impl FnOnce(&mut Bridge<'_>) -> R) -> R { 32,050,039 ( 0.09%) BridgeState::with(|state| match state { . BridgeState::NotConnected => { . panic!("procedural macro API is used outside of a procedural macro"); . } . BridgeState::InUse => { . panic!("procedural macro API is used while it's already in use"); . } 8,580 ( 0.00%) BridgeState::Connected(bridge) => f(bridge), 2,640 ( 0.00%) }) 2,640 ( 0.00%) } . } . . /// A client-side "global object" (usually a function pointer), . /// which may be using a different `proc_macro` from the one . /// used by the server, but can be interacted with compatibly. . /// . /// N.B., `F` must have FFI-friendly memory layout (e.g., a pointer). . /// The call ABI of function pointers used for `F` doesn't -- line 345 ---------------------------------------- -- line 353 ---------------------------------------- . pub(super) get_handle_counters: extern "C" fn() -> &'static HandleCounters, . pub(super) run: extern "C" fn(Bridge<'_>, F) -> Buffer, . pub(super) f: F, . } . . /// Client-side helper for handling client panics, entering the bridge, . /// deserializing input and serializing output. . // FIXME(eddyb) maybe replace `Bridge::enter` with this? 4,620 ( 0.00%) fn run_client DecodeMut<'a, 's, ()>, R: Encode<()>>( . mut bridge: Bridge<'_>, . f: impl FnOnce(A) -> R, . ) -> Buffer { . // The initial `cached_buffer` contains the input. 3,960 ( 0.00%) let mut b = bridge.cached_buffer.take(); . 23,760 ( 0.00%) panic::catch_unwind(panic::AssertUnwindSafe(|| { 9,900 ( 0.00%) bridge.enter(|| { 12,540 ( 0.00%) let reader = &mut &b[..]; 4,620 ( 0.00%) let input = A::decode(reader, &mut ()); . . // Put the `cached_buffer` back in the `Bridge`, for requests. 13,200 ( 0.00%) Bridge::with(|bridge| bridge.cached_buffer = b.take()); . 10,560 ( 0.00%) let output = f(input); . . // Take the `cached_buffer` back out, for the output value. 12,540 ( 0.00%) b = Bridge::with(|bridge| bridge.cached_buffer.take()); . . // HACK(eddyb) Separate encoding a success value (`Ok(output)`) . // from encoding a panic (`Err(e: PanicMessage)`) to avoid . // having handles outside the `bridge.enter(|| ...)` scope, and . // to catch panics that could happen while encoding the success. . // . // Note that panics should be impossible beyond this point, but . // this is defensively trying to avoid any accidental panicking . // reaching the `extern "C"` (which should `abort` but might not . // at the moment, so this is also potentially preventing UB). 1,980 ( 0.00%) b.clear(); 6,600 ( 0.00%) Ok::<_, ()>(output).encode(&mut b, &mut ()); 2,640 ( 0.00%) }) 1,320 ( 0.00%) })) . .map_err(PanicMessage::from) 660 ( 0.00%) .unwrap_or_else(|e| { . b.clear(); . Err::<(), _>(e).encode(&mut b, &mut ()); . }); . b 1,320 ( 0.00%) } . . impl Client crate::TokenStream> { . #[rustc_allow_const_fn_unstable(const_fn)] 1 ( 0.00%) pub const fn expand1(f: fn(crate::TokenStream) -> crate::TokenStream) -> Self { 4,620 ( 0.00%) extern "C" fn run( . bridge: Bridge<'_>, . f: impl FnOnce(crate::TokenStream) -> crate::TokenStream, . ) -> Buffer { 19,800 ( 0.00%) run_client(bridge, |input| f(crate::TokenStream(input)).0) 1,320 ( 0.00%) } 5 ( 0.00%) Client { get_handle_counters: HandleCounters::get, run, f } 1 ( 0.00%) } . } . . impl Client crate::TokenStream> { . #[rustc_allow_const_fn_unstable(const_fn)] . pub const fn expand2( . f: fn(crate::TokenStream, crate::TokenStream) -> crate::TokenStream, . ) -> Self { . extern "C" fn run( -- line 420 ---------------------------------------- 11,749,878 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/map/entry.rs -------------------------------------------------------------------------------- Ir -- line 117 ---------------------------------------- . /// use std::collections::BTreeMap; . /// . /// let mut map: BTreeMap<&str, usize> = BTreeMap::new(); . /// map.entry("poneyland").or_insert(12); . /// . /// assert_eq!(map["poneyland"], 12); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 14 ( 0.00%) pub fn or_insert(self, default: V) -> &'a mut V { 4 ( 0.00%) match self { . Occupied(entry) => entry.into_mut(), 3 ( 0.00%) Vacant(entry) => entry.insert(default), . } 18 ( 0.00%) } . . /// Ensures a value is in the entry by inserting the result of the default function if empty, . /// and returns a mutable reference to the value in the entry. . /// . /// # Examples . /// . /// ``` . /// use std::collections::BTreeMap; -- line 138 ---------------------------------------- -- line 140 ---------------------------------------- . /// let mut map: BTreeMap<&str, String> = BTreeMap::new(); . /// let s = "hoho".to_string(); . /// . /// map.entry("poneyland").or_insert_with(|| s); . /// . /// assert_eq!(map["poneyland"], "hoho".to_string()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 1,673,460 ( 0.00%) pub fn or_insert_with V>(self, default: F) -> &'a mut V { 753,321 ( 0.00%) match self { . Occupied(entry) => entry.into_mut(), 4,926,267 ( 0.01%) Vacant(entry) => entry.insert(default()), . } 2,009,289 ( 0.01%) } . . /// Ensures a value is in the entry by inserting, if empty, the result of the default function. . /// This method allows for generating key-derived values for insertion by providing the default . /// function a reference to the key that was moved during the `.entry(key)` method call. . /// . /// The reference to the moved key is provided so that cloning or copying the key is . /// unnecessary, unlike with `.or_insert_with(|| ... )`. . /// -- line 161 ---------------------------------------- -- line 245 ---------------------------------------- . /// ``` . /// use std::collections::BTreeMap; . /// . /// let mut map: BTreeMap<&str, Option> = BTreeMap::new(); . /// map.entry("poneyland").or_default(); . /// . /// assert_eq!(map["poneyland"], None); . /// ``` 11,037 ( 0.00%) pub fn or_default(self) -> &'a mut V { 7,358 ( 0.00%) match self { . Occupied(entry) => entry.into_mut(), 115 ( 0.00%) Vacant(entry) => entry.insert(Default::default()), . } 18,395 ( 0.00%) } . } . . impl<'a, K: Ord, V> VacantEntry<'a, K, V> { . /// Gets a reference to the key that would be used when inserting a value . /// through the VacantEntry. . /// . /// # Examples . /// -- line 266 ---------------------------------------- -- line 306 ---------------------------------------- . /// let mut map: BTreeMap<&str, u32> = BTreeMap::new(); . /// . /// if let Entry::Vacant(o) = map.entry("poneyland") { . /// o.insert(37); . /// } . /// assert_eq!(map["poneyland"], 37); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 9,324,871 ( 0.03%) pub fn insert(self, value: V) -> &'a mut V { 24,665,773 ( 0.07%) let out_ptr = match self.handle.insert_recursing(self.key, value) { 1,870,981 ( 0.01%) (Fit(_), val_ptr) => { . // SAFETY: We have consumed self.handle and the handle returned. 1,622,123 ( 0.00%) let map = unsafe { self.dormant_map.awaken() }; 7,177,376 ( 0.02%) map.length += 1; 38 ( 0.00%) val_ptr 38 ( 0.00%) } 507,795 ( 0.00%) (Split(ins), val_ptr) => { . drop(ins.left); . // SAFETY: We have consumed self.handle and the reference returned. 63,254 ( 0.00%) let map = unsafe { self.dormant_map.awaken() }; . let root = map.root.as_mut().unwrap(); 460,893 ( 0.00%) root.push_internal_level().push(ins.kv.0, ins.kv.1, ins.right); 326,103 ( 0.00%) map.length += 1; . val_ptr . } . }; . // Now that we have finished growing the tree using borrowed references, . // dereference the pointer to a part of it, that we picked up along the way. 114 ( 0.00%) unsafe { &mut *out_ptr } 9,483,283 ( 0.03%) } . } . . impl<'a, K: Ord, V> OccupiedEntry<'a, K, V> { . /// Gets a reference to the key in the entry. . /// . /// # Examples . /// . /// ``` -- line 343 ---------------------------------------- -- line 368 ---------------------------------------- . /// // We delete the entry from the map. . /// o.remove_entry(); . /// } . /// . /// // If now try to get the value, it will panic: . /// // println!("{}", map["poneyland"]); . /// ``` . #[stable(feature = "map_entry_recover_keys2", since = "1.12.0")] 7,353,470 ( 0.02%) pub fn remove_entry(self) -> (K, V) { 1,470,581 ( 0.00%) self.remove_kv() 11,239,857 ( 0.03%) } . . /// Gets a reference to the value in the entry. . /// . /// # Examples . /// . /// ``` . /// use std::collections::BTreeMap; . /// use std::collections::btree_map::Entry; -- line 386 ---------------------------------------- -- line 448 ---------------------------------------- . /// if let Entry::Occupied(o) = map.entry("poneyland") { . /// *o.into_mut() += 10; . /// } . /// assert_eq!(map["poneyland"], 22); . /// ``` . #[must_use = "`self` will be dropped if the result is not used"] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn into_mut(self) -> &'a mut V { 45,092 ( 0.00%) self.handle.into_val_mut() . } . . /// Sets the value of the entry with the `OccupiedEntry`'s key, . /// and returns the entry's old value. . /// . /// # Examples . /// . /// ``` -- line 464 ---------------------------------------- -- line 497 ---------------------------------------- . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn remove(self) -> V { . self.remove_kv().1 . } . . // Body of `remove_entry`, probably separate because the name reflects the returned pair. . pub(super) fn remove_kv(self) -> (K, V) { 1,622,143 ( 0.00%) let mut emptied_internal_root = false; 21,577,542 ( 0.06%) let (old_kv, _) = self.handle.remove_kv_tracking(|| emptied_internal_root = true); . // SAFETY: we consumed the intermediate root borrow, `self.handle`. . let map = unsafe { self.dormant_map.awaken() }; 6,488,572 ( 0.02%) map.length -= 1; 3,244,286 ( 0.01%) if emptied_internal_root { . let root = map.root.as_mut().unwrap(); . root.pop_internal_level(); . } . old_kv . } . } 3,596,811 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/proc-macro2-1.0.36/src/wrapper.rs -------------------------------------------------------------------------------- Ir -- line 3 ---------------------------------------- . use std::fmt::{self, Debug, Display}; . use std::iter::FromIterator; . use std::ops::RangeBounds; . use std::panic; . #[cfg(super_unstable)] . use std::path::PathBuf; . use std::str::FromStr; . 724,101 ( 0.00%) #[derive(Clone)] . pub(crate) enum TokenStream { 206,886 ( 0.00%) Compiler(DeferredTokenStream), . Fallback(fallback::TokenStream), . } . . // Work around https://github.com/rust-lang/rust/issues/65080. . // In `impl Extend for TokenStream` which is used heavily by quote, . // we hold on to the appended tokens and do proc_macro::TokenStream::extend as . // late as possible to batch together consecutive uses of the Extend impl. 482,734 ( 0.00%) #[derive(Clone)] . pub(crate) struct DeferredTokenStream { 275,848 ( 0.00%) stream: proc_macro::TokenStream, 172,405 ( 0.00%) extra: Vec, . } . . pub(crate) enum LexError { . Compiler(proc_macro::LexError), . Fallback(fallback::LexError), . } . . impl LexError { -- line 32 ---------------------------------------- -- line 37 ---------------------------------------- . } . } . . fn mismatch() -> ! { . panic!("stable/nightly mismatch") . } . . impl DeferredTokenStream { 910,704 ( 0.00%) fn new(stream: proc_macro::TokenStream) -> Self { 1,214,272 ( 0.00%) DeferredTokenStream { 303,568 ( 0.00%) stream, 607,136 ( 0.00%) extra: Vec::new(), . } 303,568 ( 0.00%) } . 759 ( 0.00%) fn is_empty(&self) -> bool { 2,277 ( 0.00%) self.stream.is_empty() && self.extra.is_empty() 1,265 ( 0.00%) } . 445,140 ( 0.00%) fn evaluate_now(&mut self) { . // If-check provides a fast short circuit for the common case of `extra` . // being empty, which saves a round trip over the proc macro bridge. . // Improves macro expansion time in winrt by 6% in debug mode. 741,900 ( 0.00%) if !self.extra.is_empty() { 711,032 ( 0.00%) self.stream.extend(self.extra.drain(..)); . } 296,760 ( 0.00%) } . 229,120 ( 0.00%) fn into_token_stream(mut self) -> proc_macro::TokenStream { 343,680 ( 0.00%) self.evaluate_now(); 229,120 ( 0.00%) self.stream 572,800 ( 0.00%) } . } . . impl TokenStream { 407,067 ( 0.00%) pub fn new() -> Self { 542,756 ( 0.00%) if inside_proc_macro() { 2,171,024 ( 0.01%) TokenStream::Compiler(DeferredTokenStream::new(proc_macro::TokenStream::new())) . } else { . TokenStream::Fallback(fallback::TokenStream::new()) . } 271,378 ( 0.00%) } . 759 ( 0.00%) pub fn is_empty(&self) -> bool { 759 ( 0.00%) match self { 1,518 ( 0.00%) TokenStream::Compiler(tts) => tts.is_empty(), . TokenStream::Fallback(tts) => tts.is_empty(), . } 1,265 ( 0.00%) } . 67,640 ( 0.00%) fn unwrap_nightly(self) -> proc_macro::TokenStream { 101,460 ( 0.00%) match self { 541,120 ( 0.00%) TokenStream::Compiler(s) => s.into_token_stream(), . TokenStream::Fallback(_) => mismatch(), . } 169,100 ( 0.00%) } . . fn unwrap_stable(self) -> fallback::TokenStream { . match self { . TokenStream::Compiler(_) => mismatch(), . TokenStream::Fallback(s) => s, . } . } . } . . impl FromStr for TokenStream { . type Err = LexError; . 11,193 ( 0.00%) fn from_str(src: &str) -> Result { 7,995 ( 0.00%) if inside_proc_macro() { 30,381 ( 0.00%) Ok(TokenStream::Compiler(DeferredTokenStream::new( 25,584 ( 0.00%) proc_macro_parse(src)?, . ))) . } else { . Ok(TokenStream::Fallback(src.parse()?)) . } 3,198 ( 0.00%) } . } . . // Work around https://github.com/rust-lang/rust/issues/58736. 4,797 ( 0.00%) fn proc_macro_parse(src: &str) -> Result { 35,178 ( 0.00%) let result = panic::catch_unwind(|| src.parse().map_err(LexError::Compiler)); 17,589 ( 0.00%) result.unwrap_or_else(|_| Err(LexError::call_site())) 4,797 ( 0.00%) } . . impl Display for TokenStream { . fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { . match self { . TokenStream::Compiler(tts) => Display::fmt(&tts.clone().into_token_stream(), f), . TokenStream::Fallback(tts) => Display::fmt(tts, f), . } . } . } . . impl From for TokenStream { 3,960 ( 0.00%) fn from(inner: proc_macro::TokenStream) -> TokenStream { 9,240 ( 0.00%) TokenStream::Compiler(DeferredTokenStream::new(inner)) 1,320 ( 0.00%) } . } . . impl From for proc_macro::TokenStream { 1,320 ( 0.00%) fn from(inner: TokenStream) -> proc_macro::TokenStream { 1,980 ( 0.00%) match inner { 14,520 ( 0.00%) TokenStream::Compiler(inner) => inner.into_token_stream(), . TokenStream::Fallback(inner) => inner.to_string().parse().unwrap(), . } 1,980 ( 0.00%) } . } . . impl From for TokenStream { . fn from(inner: fallback::TokenStream) -> TokenStream { . TokenStream::Fallback(inner) . } . } . . // Assumes inside_proc_macro(). 1,342,330 ( 0.00%) fn into_compiler_token(token: TokenTree) -> proc_macro::TokenTree { 1,342,330 ( 0.00%) match token { 1,275,120 ( 0.00%) TokenTree::Group(tt) => tt.inner.unwrap_nightly().into(), 1,326,180 ( 0.00%) TokenTree::Punct(tt) => { 2,867,542 ( 0.01%) let spacing = match tt.spacing() { 107,591 ( 0.00%) Spacing::Joint => proc_macro::Spacing::Joint, 447,908 ( 0.00%) Spacing::Alone => proc_macro::Spacing::Alone, . }; 3,315,450 ( 0.01%) let mut punct = proc_macro::Punct::new(tt.as_char(), spacing); 4,973,175 ( 0.01%) punct.set_span(tt.span().inner.unwrap_nightly()); 2,652,360 ( 0.01%) punct.into() . } 5,311,840 ( 0.02%) TokenTree::Ident(tt) => tt.inner.unwrap_nightly().into(), 267,072 ( 0.00%) TokenTree::Literal(tt) => tt.inner.unwrap_nightly().into(), . } 2,013,495 ( 0.01%) } . . impl From for TokenStream { . fn from(token: TokenTree) -> TokenStream { . if inside_proc_macro() { . TokenStream::Compiler(DeferredTokenStream::new(into_compiler_token(token).into())) . } else { . TokenStream::Fallback(token.into()) . } . } . } . . impl FromIterator for TokenStream { 22,496 ( 0.00%) fn from_iter>(trees: I) -> Self { 39,368 ( 0.00%) if inside_proc_macro() { 78,736 ( 0.00%) TokenStream::Compiler(DeferredTokenStream::new( 126,496 ( 0.00%) trees.into_iter().map(into_compiler_token).collect(), . )) . } else { . TokenStream::Fallback(trees.into_iter().collect()) . } 11,248 ( 0.00%) } . } . . impl FromIterator for TokenStream { . fn from_iter>(streams: I) -> Self { . let mut streams = streams.into_iter(); . match streams.next() { . Some(TokenStream::Compiler(mut first)) => { . first.evaluate_now(); -- line 197 ---------------------------------------- -- line 209 ---------------------------------------- . TokenStream::Fallback(first) . } . None => TokenStream::new(), . } . } . } . . impl Extend for TokenStream { 2,625,920 ( 0.01%) fn extend>(&mut self, stream: I) { 1,969,440 ( 0.01%) match self { 1,969,440 ( 0.01%) TokenStream::Compiler(tts) => { . // Here is the reason for DeferredTokenStream. 28,933,903 ( 0.08%) for token in stream { 11,854,818 ( 0.03%) tts.extra.push(into_compiler_token(token)); . } . } . TokenStream::Fallback(tts) => tts.extend(stream), . } 1,312,960 ( 0.00%) } . } . . impl Extend for TokenStream { 135,280 ( 0.00%) fn extend>(&mut self, streams: I) { 169,100 ( 0.00%) match self { 101,460 ( 0.00%) TokenStream::Compiler(tts) => { 101,460 ( 0.00%) tts.evaluate_now(); 236,740 ( 0.00%) tts.stream 574,940 ( 0.00%) .extend(streams.into_iter().map(TokenStream::unwrap_nightly)); . } . TokenStream::Fallback(tts) => { . tts.extend(streams.into_iter().map(TokenStream::unwrap_stable)); . } . } 67,640 ( 0.00%) } . } . . impl Debug for TokenStream { . fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { . match self { . TokenStream::Compiler(tts) => Debug::fmt(&tts.clone().into_token_stream(), f), . TokenStream::Fallback(tts) => Debug::fmt(tts, f), . } -- line 250 ---------------------------------------- -- line 303 ---------------------------------------- . Compiler(proc_macro::token_stream::IntoIter), . Fallback(fallback::TokenTreeIter), . } . . impl IntoIterator for TokenStream { . type Item = TokenTree; . type IntoIter = TokenTreeIter; . 71,504 ( 0.00%) fn into_iter(self) -> TokenTreeIter { 53,628 ( 0.00%) match self { 143,008 ( 0.00%) TokenStream::Compiler(tts) => { 393,272 ( 0.00%) TokenTreeIter::Compiler(tts.into_token_stream().into_iter()) 17,876 ( 0.00%) } . TokenStream::Fallback(tts) => TokenTreeIter::Fallback(tts.into_iter()), . } 35,752 ( 0.00%) } . } . . impl Iterator for TokenTreeIter { . type Item = TokenTree; . 527,635 ( 0.00%) fn next(&mut self) -> Option { 316,581 ( 0.00%) let token = match self { 2,198,191 ( 0.01%) TokenTreeIter::Compiler(iter) => iter.next()?, . TokenTreeIter::Fallback(iter) => return iter.next(), . }; 438,255 ( 0.00%) Some(match token { 211,215 ( 0.00%) proc_macro::TokenTree::Group(tt) => crate::Group::_new(Group::Compiler(tt)).into(), 69,574 ( 0.00%) proc_macro::TokenTree::Punct(tt) => { 287,828 ( 0.00%) let spacing = match tt.spacing() { 4,766 ( 0.00%) proc_macro::Spacing::Joint => Spacing::Joint, 60,042 ( 0.00%) proc_macro::Spacing::Alone => Spacing::Alone, . }; 452,231 ( 0.00%) let mut o = Punct::new(tt.as_char(), spacing); 521,805 ( 0.00%) o.set_span(crate::Span::_new(Span::Compiler(tt.span()))); 382,657 ( 0.00%) o.into() . } 505,185 ( 0.00%) proc_macro::TokenTree::Ident(s) => crate::Ident::_new(Ident::Compiler(s)).into(), 66,352 ( 0.00%) proc_macro::TokenTree::Literal(l) => crate::Literal::_new(Literal::Compiler(l)).into(), . }) 316,581 ( 0.00%) } . . fn size_hint(&self) -> (usize, Option) { . match self { . TokenTreeIter::Compiler(tts) => tts.size_hint(), . TokenTreeIter::Fallback(tts) => tts.size_hint(), . } . } . } -- line 351 ---------------------------------------- -- line 403 ---------------------------------------- . . #[derive(Copy, Clone)] . pub(crate) enum Span { . Compiler(proc_macro::Span), . Fallback(fallback::Span), . } . . impl Span { 585,224 ( 0.00%) pub fn call_site() -> Self { 2,340,896 ( 0.01%) if inside_proc_macro() { 3,511,344 ( 0.01%) Span::Compiler(proc_macro::Span::call_site()) . } else { . Span::Fallback(fallback::Span::call_site()) . } 1,755,672 ( 0.01%) } . . #[cfg(not(no_hygiene))] . pub fn mixed_site() -> Self { . if inside_proc_macro() { . Span::Compiler(proc_macro::Span::mixed_site()) . } else { . Span::Fallback(fallback::Span::mixed_site()) . } -- line 425 ---------------------------------------- -- line 506 ---------------------------------------- . Span::Compiler(_) => LineColumn { line: 0, column: 0 }, . Span::Fallback(s) => { . let fallback::LineColumn { line, column } = s.end(); . LineColumn { line, column } . } . } . } . 13,810 ( 0.00%) pub fn join(&self, other: Span) -> Option { 49,716 ( 0.00%) let ret = match (self, other) { . #[cfg(proc_macro_span)] 77,336 ( 0.00%) (Span::Compiler(a), Span::Compiler(b)) => Span::Compiler(a.join(b)?), . (Span::Fallback(a), Span::Fallback(b)) => Span::Fallback(a.join(b)?), . _ => return None, . }; 13,810 ( 0.00%) Some(ret) 11,048 ( 0.00%) } . . #[cfg(super_unstable)] . pub fn eq(&self, other: &Span) -> bool { . match (self, other) { . (Span::Compiler(a), Span::Compiler(b)) => a.eq(b), . (Span::Fallback(a), Span::Fallback(b)) => a.eq(b), . _ => false, . } . } . 1,326,180 ( 0.00%) fn unwrap_nightly(self) -> proc_macro::Span { 1,657,725 ( 0.00%) match self { 663,090 ( 0.00%) Span::Compiler(s) => s, . Span::Fallback(_) => mismatch(), . } 994,635 ( 0.00%) } . } . . impl From for crate::Span { . fn from(proc_span: proc_macro::Span) -> crate::Span { . crate::Span::_new(Span::Compiler(proc_span)) . } . } . . impl From for Span { . fn from(inner: fallback::Span) -> Span { . Span::Fallback(inner) . } . } . . impl Debug for Span { 142,125 ( 0.00%) fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 142,125 ( 0.00%) match self { 142,125 ( 0.00%) Span::Compiler(s) => Debug::fmt(s, f), . Span::Fallback(s) => Debug::fmt(s, f), . } 142,125 ( 0.00%) } . } . . pub(crate) fn debug_span_field_if_nontrivial(debug: &mut fmt::DebugStruct, span: Span) { . match span { . Span::Compiler(s) => { . debug.field("span", &s); . } . Span::Fallback(s) => fallback::debug_span_field_if_nontrivial(debug, s), . } . } . 23,280 ( 0.00%) #[derive(Clone)] . pub(crate) enum Group { 12,416 ( 0.00%) Compiler(proc_macro::Group), . Fallback(fallback::Group), . } . . impl Group { 373,224 ( 0.00%) pub fn new(delimiter: Delimiter, stream: TokenStream) -> Self { 186,612 ( 0.00%) match stream { 248,816 ( 0.00%) TokenStream::Compiler(tts) => { 124,408 ( 0.00%) let delimiter = match delimiter { 67,808 ( 0.00%) Delimiter::Parenthesis => proc_macro::Delimiter::Parenthesis, 21,922 ( 0.00%) Delimiter::Bracket => proc_macro::Delimiter::Bracket, 34,678 ( 0.00%) Delimiter::Brace => proc_macro::Delimiter::Brace, . Delimiter::None => proc_macro::Delimiter::None, . }; 1,492,896 ( 0.00%) Group::Compiler(proc_macro::Group::new(delimiter, tts.into_token_stream())) 62,204 ( 0.00%) } . TokenStream::Fallback(stream) => { . Group::Fallback(fallback::Group::new(delimiter, stream)) . } . } 124,408 ( 0.00%) } . 68,676 ( 0.00%) pub fn delimiter(&self) -> Delimiter { 68,676 ( 0.00%) match self { 160,244 ( 0.00%) Group::Compiler(g) => match g.delimiter() { 18,784 ( 0.00%) proc_macro::Delimiter::Parenthesis => Delimiter::Parenthesis, 17,824 ( 0.00%) proc_macro::Delimiter::Bracket => Delimiter::Bracket, 9,176 ( 0.00%) proc_macro::Delimiter::Brace => Delimiter::Brace, . proc_macro::Delimiter::None => Delimiter::None, . }, . Group::Fallback(g) => g.delimiter(), . } 68,676 ( 0.00%) } . 41,060 ( 0.00%) pub fn stream(&self) -> TokenStream { 24,636 ( 0.00%) match self { 164,240 ( 0.00%) Group::Compiler(g) => TokenStream::Compiler(DeferredTokenStream::new(g.stream())), . Group::Fallback(g) => TokenStream::Fallback(g.stream()), . } 16,424 ( 0.00%) } . 44,649 ( 0.00%) pub fn span(&self) -> Span { 44,649 ( 0.00%) match self { 148,830 ( 0.00%) Group::Compiler(g) => Span::Compiler(g.span()), . Group::Fallback(g) => Span::Fallback(g.span()), . } 44,649 ( 0.00%) } . . pub fn span_open(&self) -> Span { . match self { . #[cfg(not(no_group_open_close))] . Group::Compiler(g) => Span::Compiler(g.span_open()), . #[cfg(no_group_open_close)] . Group::Compiler(g) => Span::Compiler(g.span()), . Group::Fallback(g) => Span::Fallback(g.span_open()), . } . } . 19,980 ( 0.00%) pub fn span_close(&self) -> Span { 19,980 ( 0.00%) match self { . #[cfg(not(no_group_open_close))] 66,600 ( 0.00%) Group::Compiler(g) => Span::Compiler(g.span_close()), . #[cfg(no_group_open_close)] . Group::Compiler(g) => Span::Compiler(g.span()), . Group::Fallback(g) => Span::Fallback(g.span_close()), . } 19,980 ( 0.00%) } . 29,675 ( 0.00%) pub fn set_span(&mut self, span: Span) { 94,960 ( 0.00%) match (self, span) { 59,350 ( 0.00%) (Group::Compiler(g), Span::Compiler(s)) => g.set_span(s), . (Group::Fallback(g), Span::Fallback(s)) => g.set_span(s), . _ => mismatch(), . } 11,870 ( 0.00%) } . 127,512 ( 0.00%) fn unwrap_nightly(self) -> proc_macro::Group { 191,268 ( 0.00%) match self { 255,024 ( 0.00%) Group::Compiler(g) => g, . Group::Fallback(_) => mismatch(), . } 382,536 ( 0.00%) } . } . . impl From for Group { . fn from(g: fallback::Group) -> Self { . Group::Fallback(g) . } . } . -- line 662 ---------------------------------------- -- line 673 ---------------------------------------- . fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { . match self { . Group::Compiler(group) => Debug::fmt(group, formatter), . Group::Fallback(group) => Debug::fmt(group, formatter), . } . } . } . 1,976,730 ( 0.01%) #[derive(Clone)] . pub(crate) enum Ident { 1,054,256 ( 0.00%) Compiler(proc_macro::Ident), . Fallback(fallback::Ident), . } . . impl Ident { 2,266,750 ( 0.01%) pub fn new(string: &str, span: Span) -> Self { 1,133,375 ( 0.00%) match span { 3,173,450 ( 0.01%) Span::Compiler(s) => Ident::Compiler(proc_macro::Ident::new(string, s)), . Span::Fallback(s) => Ident::Fallback(fallback::Ident::new(string, s)), . } 453,350 ( 0.00%) } . . pub fn new_raw(string: &str, span: Span) -> Self { . match span { . Span::Compiler(s) => { . let p: proc_macro::TokenStream = string.parse().unwrap(); . let ident = match p.into_iter().next() { . Some(proc_macro::TokenTree::Ident(mut i)) => { . i.set_span(s); -- line 701 ---------------------------------------- -- line 704 ---------------------------------------- . _ => panic!(), . }; . Ident::Compiler(ident) . } . Span::Fallback(s) => Ident::Fallback(fallback::Ident::new_raw(string, s)), . } . } . 67,857 ( 0.00%) pub fn span(&self) -> Span { 67,857 ( 0.00%) match self { 226,190 ( 0.00%) Ident::Compiler(t) => Span::Compiler(t.span()), . Ident::Fallback(t) => Span::Fallback(t.span()), . } 67,857 ( 0.00%) } . 7,150 ( 0.00%) pub fn set_span(&mut self, span: Span) { 22,880 ( 0.00%) match (self, span) { 14,300 ( 0.00%) (Ident::Compiler(t), Span::Compiler(s)) => t.set_span(s), . (Ident::Fallback(t), Span::Fallback(s)) => t.set_span(s), . _ => mismatch(), . } 2,860 ( 0.00%) } . 531,184 ( 0.00%) fn unwrap_nightly(self) -> proc_macro::Ident { 796,776 ( 0.00%) match self { 1,062,368 ( 0.00%) Ident::Compiler(s) => s, . Ident::Fallback(_) => mismatch(), . } 1,593,552 ( 0.00%) } . } . . impl PartialEq for Ident { 36 ( 0.00%) fn eq(&self, other: &Ident) -> bool { 132 ( 0.00%) match (self, other) { 300 ( 0.00%) (Ident::Compiler(t), Ident::Compiler(o)) => t.to_string() == o.to_string(), . (Ident::Fallback(t), Ident::Fallback(o)) => t == o, . _ => mismatch(), . } 60 ( 0.00%) } . } . . impl PartialEq for Ident . where . T: ?Sized + AsRef, . { 535,367 ( 0.00%) fn eq(&self, other: &T) -> bool { 305,924 ( 0.00%) let other = other.as_ref(); 229,443 ( 0.00%) match self { 994,253 ( 0.00%) Ident::Compiler(t) => t.to_string() == other, . Ident::Fallback(t) => t == other, . } 382,405 ( 0.00%) } . } . . impl Display for Ident { 104,390 ( 0.00%) fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 62,634 ( 0.00%) match self { 125,268 ( 0.00%) Ident::Compiler(t) => Display::fmt(t, f), . Ident::Fallback(t) => Display::fmt(t, f), . } 104,390 ( 0.00%) } . } . . impl Debug for Ident { . fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { . match self { . Ident::Compiler(t) => Debug::fmt(t, f), . Ident::Fallback(t) => Debug::fmt(t, f), . } . } . } . 69,420 ( 0.00%) #[derive(Clone)] . pub(crate) enum Literal { 37,024 ( 0.00%) Compiler(proc_macro::Literal), . Fallback(fallback::Literal), . } . . macro_rules! suffixed_numbers { . ($($name:ident => $kind:ident,)*) => ($( 6,795 ( 0.00%) pub fn $name(n: $kind) -> Literal { 5,436 ( 0.00%) if inside_proc_macro() { 9,513 ( 0.00%) Literal::Compiler(proc_macro::Literal::$name(n)) . } else { . Literal::Fallback(fallback::Literal::$name(n)) . } 2,718 ( 0.00%) } . )*) . } . . macro_rules! unsuffixed_integers { . ($($name:ident => $kind:ident,)*) => ($( 200 ( 0.00%) pub fn $name(n: $kind) -> Literal { 160 ( 0.00%) if inside_proc_macro() { 280 ( 0.00%) Literal::Compiler(proc_macro::Literal::$name(n)) . } else { . Literal::Fallback(fallback::Literal::$name(n)) . } 80 ( 0.00%) } . )*) . } . . impl Literal { . pub unsafe fn from_str_unchecked(repr: &str) -> Self { . if inside_proc_macro() { . Literal::Compiler(compiler_literal_from_str(repr).expect("invalid literal")) . } else { -- line 810 ---------------------------------------- -- line 856 ---------------------------------------- . pub fn f64_unsuffixed(f: f64) -> Literal { . if inside_proc_macro() { . Literal::Compiler(proc_macro::Literal::f64_unsuffixed(f)) . } else { . Literal::Fallback(fallback::Literal::f64_unsuffixed(f)) . } . } . 38,325 ( 0.00%) pub fn string(t: &str) -> Literal { 21,900 ( 0.00%) if inside_proc_macro() { 38,325 ( 0.00%) Literal::Compiler(proc_macro::Literal::string(t)) . } else { . Literal::Fallback(fallback::Literal::string(t)) . } 10,950 ( 0.00%) } . . pub fn character(t: char) -> Literal { . if inside_proc_macro() { . Literal::Compiler(proc_macro::Literal::character(t)) . } else { . Literal::Fallback(fallback::Literal::character(t)) . } . } . 4,795 ( 0.00%) pub fn byte_string(bytes: &[u8]) -> Literal { 2,740 ( 0.00%) if inside_proc_macro() { 4,795 ( 0.00%) Literal::Compiler(proc_macro::Literal::byte_string(bytes)) . } else { . Literal::Fallback(fallback::Literal::byte_string(bytes)) . } 1,370 ( 0.00%) } . 2,142 ( 0.00%) pub fn span(&self) -> Span { 2,142 ( 0.00%) match self { 7,140 ( 0.00%) Literal::Compiler(lit) => Span::Compiler(lit.span()), . Literal::Fallback(lit) => Span::Fallback(lit.span()), . } 2,142 ( 0.00%) } . 200 ( 0.00%) pub fn set_span(&mut self, span: Span) { 640 ( 0.00%) match (self, span) { 400 ( 0.00%) (Literal::Compiler(lit), Span::Compiler(s)) => lit.set_span(s), . (Literal::Fallback(lit), Span::Fallback(s)) => lit.set_span(s), . _ => mismatch(), . } 80 ( 0.00%) } . . pub fn subspan>(&self, range: R) -> Option { . match self { . #[cfg(proc_macro_span)] . Literal::Compiler(lit) => lit.subspan(range).map(Span::Compiler), . #[cfg(not(proc_macro_span))] . Literal::Compiler(_lit) => None, . Literal::Fallback(lit) => lit.subspan(range).map(Span::Fallback), . } . } . 20,544 ( 0.00%) fn unwrap_nightly(self) -> proc_macro::Literal { 30,816 ( 0.00%) match self { 41,088 ( 0.00%) Literal::Compiler(s) => s, . Literal::Fallback(_) => mismatch(), . } 61,632 ( 0.00%) } . } . . impl From for Literal { . fn from(s: fallback::Literal) -> Literal { . Literal::Fallback(s) . } . } . -- line 926 ---------------------------------------- -- line 951 ---------------------------------------- . return Ok(literal); . } . } . Err(LexError::call_site()) . } . } . . impl Display for Literal { 12,660 ( 0.00%) fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 7,596 ( 0.00%) match self { 15,192 ( 0.00%) Literal::Compiler(t) => Display::fmt(t, f), . Literal::Fallback(t) => Display::fmt(t, f), . } 12,660 ( 0.00%) } . } . . impl Debug for Literal { . fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { . match self { . Literal::Compiler(t) => Debug::fmt(t, f), . Literal::Fallback(t) => Debug::fmt(t, f), . } -- line 972 ---------------------------------------- 13,387,461 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mut_ptr.rs -------------------------------------------------------------------------------- Ir -- line 28 ---------------------------------------- . /// ``` . /// let mut s = [1, 2, 3]; . /// let ptr: *mut u32 = s.as_mut_ptr(); . /// assert!(!ptr.is_null()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_ptr_is_null", issue = "74939")] . #[inline] 13,945,336 ( 0.04%) pub const fn is_null(self) -> bool { . // Compare via a cast to a thin pointer, so fat pointers are only . // considering their "data" part for null-ness. 13,945,336 ( 0.04%) (self as *mut u8).guaranteed_eq(null_mut()) 13,945,336 ( 0.04%) } . . /// Casts to a pointer of another type. . #[stable(feature = "ptr_cast", since = "1.38.0")] . #[rustc_const_stable(feature = "const_ptr_cast", since = "1.38.0")] . #[inline(always)] . pub const fn cast(self) -> *mut U { . self as _ . } -- line 48 ---------------------------------------- -- line 299 ---------------------------------------- . #[inline(always)] . pub const unsafe fn offset(self, count: isize) -> *mut T . where . T: Sized, . { . // SAFETY: the caller must uphold the safety contract for `offset`. . // The obtained pointer is valid for writes since the caller must . // guarantee that it points to the same allocated object as `self`. 250,597,950 ( 0.72%) unsafe { intrinsics::offset(self, count) as *mut T } . } . . /// Calculates the offset from a pointer using wrapping arithmetic. . /// `count` is in units of T; e.g., a `count` of 3 represents a pointer . /// offset of `3 * size_of::()` bytes. . /// . /// # Safety . /// -- line 315 ---------------------------------------- -- line 360 ---------------------------------------- . #[must_use = "returns a new pointer rather than modifying its argument"] . #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")] . #[inline(always)] . pub const fn wrapping_offset(self, count: isize) -> *mut T . where . T: Sized, . { . // SAFETY: the `arith_offset` intrinsic has no prerequisites to be called. 3,940 ( 0.00%) unsafe { intrinsics::arith_offset(self, count) as *mut T } . } . . /// Returns `None` if the pointer is null, or else returns a unique reference to . /// the value wrapped in `Some`. If the value may be uninitialized, [`as_uninit_mut`] . /// must be used instead. . /// . /// For the shared counterpart see [`as_ref`]. . /// -- line 376 ---------------------------------------- -- line 492 ---------------------------------------- . /// affect the outcome, but just the performance. . /// The consequences of using this method to make runtime and compile-time code behave . /// differently have not been explored. This method should not be used to introduce such . /// differences, and it should also not be stabilized before we have a better understanding . /// of this issue. . #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")] . #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")] . #[inline] 10,459,002 ( 0.03%) pub const fn guaranteed_eq(self, other: *mut T) -> bool . where . T: Sized, . { 20,918,480 ( 0.06%) intrinsics::ptr_guaranteed_eq(self as *const _, other as *const _) 13,945,336 ( 0.04%) } . . /// Returns whether two pointers are guaranteed to be unequal. . /// . /// At runtime this function behaves like `self != other`. . /// However, in some contexts (e.g., compile-time evaluation), . /// it is not always possible to determine the inequality of two pointers, so this function may . /// spuriously return `false` for pointers that later actually turn out to be unequal. . /// But when it returns `true`, the pointers are guaranteed to be unequal. -- line 513 ---------------------------------------- -- line 683 ---------------------------------------- . #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")] . #[inline(always)] . pub const unsafe fn add(self, count: usize) -> Self . where . T: Sized, . { . // SAFETY: the caller must uphold the safety contract for `offset`. . unsafe { self.offset(count as isize) } 76 ( 0.00%) } . . /// Calculates the offset from a pointer (convenience for . /// `.offset((count as isize).wrapping_neg())`). . /// . /// `count` is in units of T; e.g., a `count` of 3 represents a pointer . /// offset of `3 * size_of::()` bytes. . /// . /// # Safety -- line 699 ---------------------------------------- -- line 741 ---------------------------------------- . /// println!("{}", *end.sub(1) as char); . /// println!("{}", *end.sub(2) as char); . /// } . /// ``` . #[stable(feature = "pointer_methods", since = "1.26.0")] . #[must_use = "returns a new pointer rather than modifying its argument"] . #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")] . #[inline] 896 ( 0.00%) pub const unsafe fn sub(self, count: usize) -> Self . where . T: Sized, . { . // SAFETY: the caller must uphold the safety contract for `offset`. . unsafe { self.offset((count as isize).wrapping_neg()) } 256 ( 0.00%) } . . /// Calculates the offset from a pointer using wrapping arithmetic. . /// (convenience for `.wrapping_offset(count as isize)`) . /// . /// `count` is in units of T; e.g., a `count` of 3 represents a pointer . /// offset of `3 * size_of::()` bytes. . /// . /// # Safety -- line 763 ---------------------------------------- -- line 1055 ---------------------------------------- . /// . /// See [`ptr::drop_in_place`] for safety concerns and examples. . /// . /// [`ptr::drop_in_place`]: crate::ptr::drop_in_place() . #[stable(feature = "pointer_methods", since = "1.26.0")] . #[inline(always)] . pub unsafe fn drop_in_place(self) { . // SAFETY: the caller must uphold the safety contract for `drop_in_place`. 2,293 ( 0.00%) unsafe { drop_in_place(self) } . } . . /// Overwrites a memory location with the given value without reading or . /// dropping the old value. . /// . /// See [`ptr::write`] for safety concerns and examples. . /// . /// [`ptr::write`]: crate::ptr::write() -- line 1071 ---------------------------------------- -- line 1072 ---------------------------------------- . #[stable(feature = "pointer_methods", since = "1.26.0")] . #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")] . #[inline(always)] . pub const unsafe fn write(self, val: T) . where . T: Sized, . { . // SAFETY: the caller must uphold the safety contract for `write`. 788 ( 0.00%) unsafe { write(self, val) } 15 ( 0.00%) } . . /// Invokes memset on the specified pointer, setting `count * size_of::()` . /// bytes of memory starting at `self` to `val`. . /// . /// See [`ptr::write_bytes`] for safety concerns and examples. . /// . /// [`ptr::write_bytes`]: crate::ptr::write_bytes() . #[stable(feature = "pointer_methods", since = "1.26.0")] . #[rustc_const_unstable(feature = "const_ptr_write", issue = "86302")] . #[inline(always)] . pub const unsafe fn write_bytes(self, val: u8, count: usize) . where . T: Sized, . { . // SAFETY: the caller must uphold the safety contract for `write_bytes`. 40 ( 0.00%) unsafe { write_bytes(self, val, count) } 10 ( 0.00%) } . . /// Performs a volatile write of a memory location with the given value without . /// reading or dropping the old value. . /// . /// Volatile operations are intended to act on I/O memory, and are guaranteed . /// to not be elided or reordered by the compiler across other volatile . /// operations. . /// -- line 1106 ---------------------------------------- -- line 1416 ---------------------------------------- . } . } . . // Equality for pointers . #[stable(feature = "rust1", since = "1.0.0")] . impl PartialEq for *mut T { . #[inline(always)] . fn eq(&self, other: &*mut T) -> bool { 431,266 ( 0.00%) *self == *other . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Eq for *mut T {} . . #[stable(feature = "rust1", since = "1.0.0")] . impl Ord for *mut T { -- line 1432 ---------------------------------------- 10,145,087 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_resolve/src/imports.rs -------------------------------------------------------------------------------- Ir -- line 109 ---------------------------------------- . /// The resolution of `module_path`. . pub imported_module: Cell>>, . pub vis: Cell, . pub used: Cell, . } . . impl<'a> Import<'a> { . pub fn is_glob(&self) -> bool { 61,068 ( 0.00%) matches!(self.kind, ImportKind::Glob { .. }) . } . . pub fn is_nested(&self) -> bool { . match self.kind { . ImportKind::Single { nested, .. } => nested, . _ => false, . } . } . . crate fn crate_lint(&self) -> CrateLint { 976 ( 0.00%) CrateLint::UsePath { root_id: self.root_id, root_span: self.root_span } 1,996 ( 0.00%) } . } . 220,308 ( 0.00%) #[derive(Clone, Default, Debug)] . /// Records information about the resolution of a name in a namespace of a module. . pub struct NameResolution<'a> { . /// Single imports that may define the name in the namespace. . /// Imports are arena-allocated, so it's ok to use pointers as keys. . single_imports: FxHashSet>>, . /// The least shadowable known binding for this name, or None if there are no known bindings. . pub binding: Option<&'a NameBinding<'a>>, . shadowed_glob: Option<&'a NameBinding<'a>>, . } . . impl<'a> NameResolution<'a> { . // Returns the binding for the name if it is known or None if it not known. . pub(crate) fn binding(&self) -> Option<&'a NameBinding<'a>> { 11,905 ( 0.00%) self.binding.and_then(|binding| { 5,532 ( 0.00%) if !binding.is_glob_import() || self.single_imports.is_empty() { . Some(binding) . } else { . None . } . }) . } . . crate fn add_single_import(&mut self, import: &'a Import<'a>) { -- line 155 ---------------------------------------- -- line 168 ---------------------------------------- . .. . }, . ) => import.vis.get().is_public(), . _ => false, . } . } . . impl<'a> Resolver<'a> { 40,908 ( 0.00%) crate fn resolve_ident_in_module_unadjusted( . &mut self, . module: ModuleOrUniformRoot<'a>, . ident: Ident, . ns: Namespace, . parent_scope: &ParentScope<'a>, . record_used: bool, . path_span: Span, . ) -> Result<&'a NameBinding<'a>, Determinacy> { 3,727,043 ( 0.01%) self.resolve_ident_in_module_unadjusted_ext( . module, . ident, . ns, . parent_scope, . false, . record_used, . path_span, . ) . .map_err(|(determinacy, _)| determinacy) 11,688 ( 0.00%) } . . /// Attempts to resolve `ident` in namespaces `ns` of `module`. . /// Invariant: if `record_used` is `Some`, expansion and import resolution must be complete. 13,105,428 ( 0.04%) crate fn resolve_ident_in_module_unadjusted_ext( . &mut self, . module: ModuleOrUniformRoot<'a>, . ident: Ident, . ns: Namespace, . parent_scope: &ParentScope<'a>, . restricted_shadowing: bool, . record_used: bool, . path_span: Span, -- line 207 ---------------------------------------- -- line 259 ---------------------------------------- . path_span, . ); . return binding.map_err(|determinacy| (determinacy, Weak::No)); . } . }; . . let key = self.new_key(ident, ns); . let resolution = 4,992,544 ( 0.01%) self.resolution(module, key).try_borrow_mut().map_err(|_| (Determined, Weak::No))?; // This happens when there is a cycle of imports. . 2,321,150 ( 0.01%) if let Some(binding) = resolution.binding { 221,048 ( 0.00%) if !restricted_shadowing && binding.expansion != LocalExpnId::ROOT { 170,054 ( 0.00%) if let NameBindingKind::Res(_, true) = binding.kind { . self.macro_expanded_macro_export_errors.insert((path_span, binding.span)); . } . } . } . 2,499,791 ( 0.01%) let check_usable = |this: &mut Self, binding: &'a NameBinding<'a>| { 257,869 ( 0.00%) if let Some(unusable_binding) = this.unusable_binding { . if ptr::eq(binding, unusable_binding) { . return Err((Determined, Weak::No)); . } . } 129,648 ( 0.00%) let usable = this.is_accessible_from(binding.vis, parent_scope.module); 170,240 ( 0.00%) if usable { Ok(binding) } else { Err((Determined, Weak::No)) } 4,301 ( 0.00%) }; . 1,248,136 ( 0.00%) if record_used { 570,186 ( 0.00%) return resolution . .binding . .and_then(|binding| { . // If the primary binding is unusable, search further and return the shadowed glob . // binding if it exists. What we really want here is having two separate scopes in . // a module - one for non-globs and one for globs, but until that's done use this . // hack to avoid inconsistent resolution ICEs during import validation. 907,750 ( 0.00%) if let Some(unusable_binding) = self.unusable_binding { . if ptr::eq(binding, unusable_binding) { . return resolution.shadowed_glob; . } . } . Some(binding) . }) . .ok_or((Determined, Weak::No)) . .and_then(|binding| { 363,524 ( 0.00%) if self.last_import_segment && check_usable(self, binding).is_err() { . Err((Determined, Weak::No)) . } else { 1,088,982 ( 0.00%) self.record_use(ident, binding, restricted_shadowing); . 544,631 ( 0.00%) if let Some(shadowed_glob) = resolution.shadowed_glob { . // Forbid expanded shadowing to avoid time travel. . if restricted_shadowing . && binding.expansion != LocalExpnId::ROOT . && binding.res() != shadowed_glob.res() . { . self.ambiguity_errors.push(AmbiguityError { . kind: AmbiguityKind::GlobVsExpanded, . ident, -- line 317 ---------------------------------------- -- line 318 ---------------------------------------- . b1: binding, . b2: shadowed_glob, . misc1: AmbiguityErrorMisc::None, . misc2: AmbiguityErrorMisc::None, . }); . } . } . 907,485 ( 0.00%) if !self.is_accessible_from(binding.vis, parent_scope.module) { . self.privacy_errors.push(PrivacyError { . ident, . binding, . dedup_span: path_span, . }); . } . . Ok(binding) . } . }); . } . . // Items and single imports are not shadowable, if we have one, then it's determined. 1,016,925 ( 0.00%) if let Some(binding) = resolution.binding { 4,559 ( 0.00%) if !binding.is_glob_import() { . return check_usable(self, binding); . } . } . . // --- From now on we either have a glob resolution or no resolution. --- . . // Check if one of single imports can still define the name, . // if it can then our result is not determined and can be invalidated. 2,965,271 ( 0.01%) for single_import in &resolution.single_imports { 4,113 ( 0.00%) if !self.is_accessible_from(single_import.vis.get(), parent_scope.module) { . continue; . } . let module = match single_import.imported_module.get() { . Some(x) => x, . None => return Err((Undetermined, Weak::No)), . }; . let ident = match single_import.kind { . ImportKind::Single { source, .. } => source, -- line 359 ---------------------------------------- -- line 385 ---------------------------------------- . // Additionally, any macro in any module can plant names in the root module if it creates . // `macro_export` macros, so the root module effectively has unresolved invocations if any . // module has unresolved invocations. . // However, it causes resolution/expansion to stuck too often (#53144), so, to make . // progress, we have to ignore those potential unresolved invocations from other modules . // and prohibit access to macro-expanded `macro_export` macros instead (unless restricted . // shadowing is enabled, see `macro_expanded_macro_export_errors`). . let unexpanded_macros = !module.unexpanded_invocations.borrow().is_empty(); 1,481,950 ( 0.00%) if let Some(binding) = resolution.binding { 782 ( 0.00%) if !unexpanded_macros || ns == MacroNS || restricted_shadowing { 3,910 ( 0.00%) return check_usable(self, binding); . } else { . return Err((Undetermined, Weak::No)); . } . } . . // --- From now on we have no resolution. --- . . // Now we are in situation when new item/import can appear only from a glob or a macro . // expansion. With restricted shadowing names from globs and macro expansions cannot . // shadow names from outer scopes, so we can freely fallback from module search to search . // in outer scopes. For `early_resolve_ident_in_lexical_scope` to continue search in outer . // scopes we return `Undetermined` with `Weak::Yes`. . . // Check if one of unexpanded macros can still define the name, . // if it can then our "no resolution" result is not determined and can be invalidated. 295,999 ( 0.00%) if unexpanded_macros { . return Err((Undetermined, Weak::Yes)); . } . . // Check if one of glob imports can still define the name, . // if it can then our "no resolution" result is not determined and can be invalidated. 1,168,792 ( 0.00%) for glob_import in module.globs.borrow().iter() { 23,376 ( 0.00%) if !self.is_accessible_from(glob_import.vis.get(), parent_scope.module) { . continue; . } 23,376 ( 0.00%) let module = match glob_import.imported_module.get() { . Some(ModuleOrUniformRoot::Module(module)) => module, . Some(_) => continue, . None => return Err((Undetermined, Weak::Yes)), . }; . let tmp_parent_scope; 11,688 ( 0.00%) let (mut adjusted_parent_scope, mut ident) = 11,688 ( 0.00%) (parent_scope, ident.normalize_to_macros_2_0()); 46,752 ( 0.00%) match ident.span.glob_adjust(module.expansion, glob_import.span) { . Some(Some(def)) => { . tmp_parent_scope = . ParentScope { module: self.expn_def_scope(def), ..*parent_scope }; . adjusted_parent_scope = &tmp_parent_scope; . } . Some(None) => {} . None => continue, . }; 40,908 ( 0.00%) let result = self.resolve_ident_in_module_unadjusted( . ModuleOrUniformRoot::Module(module), . ident, 29,220 ( 0.00%) ns, . adjusted_parent_scope, . false, . path_span, . ); . 23,376 ( 0.00%) match result { . Err(Determined) => continue, . Ok(binding) . if !self.is_accessible_from(binding.vis, glob_import.parent_scope.module) => . { . continue; . } . Ok(_) | Err(Undetermined) => return Err((Undetermined, Weak::Yes)), . } . } . . // No resolution and no one else can define the name - determinate error. . Err((Determined, Weak::No)) 11,233,224 ( 0.03%) } . . // Given a binding and an import that resolves to it, . // return the corresponding binding defined by the import. 29,970 ( 0.00%) crate fn import( . &self, . binding: &'a NameBinding<'a>, . import: &'a Import<'a>, . ) -> &'a NameBinding<'a> { 29,970 ( 0.00%) let vis = if binding.vis.is_at_least(import.vis.get(), self) . || pub_use_of_private_extern_crate_hack(import, binding) . { . import.vis.get() . } else { . binding.vis . }; . 8,991 ( 0.00%) if let ImportKind::Glob { ref max_vis, .. } = import.kind { 7,479 ( 0.00%) if vis == import.vis.get() || vis.is_at_least(max_vis.get(), self) { . max_vis.set(vis) . } . } . 2,997 ( 0.00%) self.arenas.alloc_name_binding(NameBinding { . kind: NameBindingKind::Import { binding, import, used: Cell::new(false) }, . ambiguity: None, 2,997 ( 0.00%) span: import.span, . vis, 2,997 ( 0.00%) expansion: import.parent_scope.expansion, . }) 23,976 ( 0.00%) } . . // Define the name or return the existing binding if there is a collision. 116,844 ( 0.00%) crate fn try_define( . &mut self, . module: Module<'a>, . key: BindingKey, . binding: &'a NameBinding<'a>, . ) -> Result<(), &'a NameBinding<'a>> { . let res = binding.res(); 175,266 ( 0.00%) self.check_reserved_macro_name(key.ident, res); . self.set_binding_parent_module(binding, module); 58,422 ( 0.00%) self.update_resolution(module, key, |this, resolution| { . if let Some(old_binding) = resolution.binding { 25 ( 0.00%) if res == Res::Err { . // Do not override real bindings with `Res::Err`s from error recovery. . return Ok(()); . } 9 ( 0.00%) match (old_binding.is_glob_import(), binding.is_glob_import()) { . (true, true) => { . if res != old_binding.res() { . resolution.binding = Some(this.ambiguity( . AmbiguityKind::GlobVsGlob, . old_binding, . binding, . )); . } else if !old_binding.vis.is_at_least(binding.vis, &*this) { . // We are glob-importing the same item but with greater visibility. . resolution.binding = Some(binding); . } . } . (old_glob @ true, false) | (old_glob @ false, true) => { . let (glob_binding, nonglob_binding) = . if old_glob { (old_binding, binding) } else { (binding, old_binding) }; 16 ( 0.00%) if glob_binding.res() != nonglob_binding.res() . && key.ns == MacroNS . && nonglob_binding.expansion != LocalExpnId::ROOT . { . resolution.binding = Some(this.ambiguity( . AmbiguityKind::GlobVsExpanded, . nonglob_binding, . glob_binding, . )); . } else { . resolution.binding = Some(nonglob_binding); . } 10 ( 0.00%) resolution.shadowed_glob = Some(glob_binding); . } . (false, false) => { . return Err(old_binding); . } . } . } else { 29,196 ( 0.00%) resolution.binding = Some(binding); . } . . Ok(()) . }) 87,633 ( 0.00%) } . . fn ambiguity( . &self, . kind: AmbiguityKind, . primary_binding: &'a NameBinding<'a>, . secondary_binding: &'a NameBinding<'a>, . ) -> &'a NameBinding<'a> { . self.arenas.alloc_name_binding(NameBinding { -- line 556 ---------------------------------------- -- line 563 ---------------------------------------- . // If the resolution becomes a success, define it in the module's glob importers. . fn update_resolution(&mut self, module: Module<'a>, key: BindingKey, f: F) -> T . where . F: FnOnce(&mut Resolver<'a>, &mut NameResolution<'a>) -> T, . { . // Ensure that `resolution` isn't borrowed when defining in the module's glob importers, . // during which the resolution might end up getting re-defined via a glob cycle. . let (binding, t) = { 158,616 ( 0.00%) let resolution = &mut *self.resolution(module, key).borrow_mut(); . let old_binding = resolution.binding(); . . let t = f(self, resolution); . . match resolution.binding() { . _ if old_binding.is_some() => return t, . None => return t, . Some(binding) => match old_binding { -- line 579 ---------------------------------------- -- line 580 ---------------------------------------- . Some(old_binding) if ptr::eq(old_binding, binding) => return t, . _ => (binding, t), . }, . } . }; . . // Define `binding` in `module`s glob importers. . for import in module.glob_importers.borrow_mut().iter() { 9,416 ( 0.00%) let mut ident = key.ident; 21,186 ( 0.00%) let scope = match ident.span.reverse_glob_adjust(module.expansion, import.span) { . Some(Some(def)) => self.expn_def_scope(def), 4,708 ( 0.00%) Some(None) => import.parent_scope.module, . None => continue, . }; 4,708 ( 0.00%) if self.is_accessible_from(binding.vis, scope) { 7,392 ( 0.00%) let imported_binding = self.import(binding, import); . let key = BindingKey { ident, ..key }; 27,720 ( 0.00%) let _ = self.try_define(import.parent_scope.module, key, imported_binding); . } . } . . t . } . . // Define a "dummy" resolution containing a Res::Err as a placeholder for a . // failed resolution -- line 605 ---------------------------------------- -- line 643 ---------------------------------------- . // This is a fixed-point algorithm. We resolve imports until our efforts . // are stymied by an unresolved import; then we bail out of the current . // module and continue. We terminate successfully once no more imports . // remain or unsuccessfully when no forward progress in resolving imports . // is made. . . /// Resolves all imports for the crate. This method performs the fixed- . /// point iteration. 16 ( 0.00%) pub fn resolve_imports(&mut self) { 10 ( 0.00%) let mut prev_num_indeterminates = self.r.indeterminate_imports.len() + 1; 29 ( 0.00%) while self.r.indeterminate_imports.len() < prev_num_indeterminates { . prev_num_indeterminates = self.r.indeterminate_imports.len(); 978 ( 0.00%) for import in mem::take(&mut self.r.indeterminate_imports) { . match self.resolve_import(&import) { 260 ( 0.00%) true => self.r.determined_imports.push(import), 256 ( 0.00%) false => self.r.indeterminate_imports.push(import), . } . } . } 16 ( 0.00%) } . 7 ( 0.00%) pub fn finalize_imports(&mut self) { 2 ( 0.00%) for module in self.r.arenas.local_modules().iter() { 2,333 ( 0.00%) self.finalize_resolutions_in(module); . } . . let mut seen_spans = FxHashSet::default(); . let mut errors = vec![]; . let mut prev_root_id: NodeId = NodeId::from_u32(0); 1 ( 0.00%) let determined_imports = mem::take(&mut self.r.determined_imports); 1 ( 0.00%) let indeterminate_imports = mem::take(&mut self.r.indeterminate_imports); . 12 ( 0.00%) for (is_indeterminate, import) in determined_imports . .into_iter() . .map(|i| (false, i)) . .chain(indeterminate_imports.into_iter().map(|i| (true, i))) . { 1,398 ( 0.00%) if let Some(err) = self.finalize_import(import) { . if let ImportKind::Single { source, ref source_bindings, .. } = import.kind { . if source.name == kw::SelfLower { . // Silence `unresolved import` error if E0429 is already emitted . if let Err(Determined) = source_bindings.value_ns.get() { . continue; . } . } . } -- line 688 ---------------------------------------- -- line 703 ---------------------------------------- . let path = import_path_to_string( . &import.module_path.iter().map(|seg| seg.ident).collect::>(), . &import.kind, . err.span, . ); . errors.push((path, err)); . prev_root_id = import.root_id; . } 466 ( 0.00%) } else if is_indeterminate { . // Consider erroneous imports used to avoid duplicate diagnostics. . self.r.used_imports.insert(import.id); . let path = import_path_to_string( . &import.module_path.iter().map(|seg| seg.ident).collect::>(), . &import.kind, . import.span, . ); . let err = UnresolvedImportError { -- line 719 ---------------------------------------- -- line 721 ---------------------------------------- . label: None, . note: Vec::new(), . suggestion: None, . }; . errors.push((path, err)); . } . } . 1 ( 0.00%) if !errors.is_empty() { . self.throw_unresolved_import_error(errors, None); . } 8 ( 0.00%) } . . fn throw_unresolved_import_error( . &self, . errors: Vec<(String, UnresolvedImportError)>, . span: Option, . ) { . /// Upper limit on the number of `span_label` messages. . const MAX_LABEL_COUNT: usize = 10; -- line 740 ---------------------------------------- -- line 776 ---------------------------------------- . /// If successful, the resolved bindings are written into the module. . fn resolve_import(&mut self, import: &'b Import<'b>) -> bool { . debug!( . "(resolving import for module) resolving import `{}::...` in `{}`", . Segment::names_to_string(&import.module_path), . module_to_string(import.parent_scope.module).unwrap_or_else(|| "???".to_string()), . ); . 1,723 ( 0.00%) let module = if let Some(module) = import.imported_module.get() { 512 ( 0.00%) module . } else { . // For better failure detection, pretend that the import will . // not define any names while resolving its module path. . let orig_vis = import.vis.replace(ty::Visibility::Invisible); . let path_res = self.r.resolve_path( . &import.module_path, . None, 233 ( 0.00%) &import.parent_scope, . false, . import.span, . import.crate_lint(), . ); . import.vis.set(orig_vis); . 1,631 ( 0.00%) match path_res { 1,165 ( 0.00%) PathResult::Module(module) => module, . PathResult::Indeterminate => return false, . PathResult::NonModule(..) | PathResult::Failed { .. } => return true, . } . }; . . import.imported_module.set(Some(module)); 5,679 ( 0.00%) let (source, target, source_bindings, target_bindings, type_ns_only) = match import.kind { . ImportKind::Single { . source, . target, 462 ( 0.00%) ref source_bindings, 462 ( 0.00%) ref target_bindings, 462 ( 0.00%) type_ns_only, . .. . } => (source, target, source_bindings, target_bindings, type_ns_only), . ImportKind::Glob { .. } => { . self.resolve_glob_import(import); . return true; . } . _ => unreachable!(), . }; . 462 ( 0.00%) let mut indeterminate = false; 19,866 ( 0.00%) self.r.per_ns(|this, ns| { 4,158 ( 0.00%) if !type_ns_only || ns == TypeNS { 5,550 ( 0.00%) if let Err(Undetermined) = source_bindings[ns].get() { . // For better failure detection, pretend that the import will . // not define any names while resolving its module path. 1,380 ( 0.00%) let orig_vis = import.vis.replace(ty::Visibility::Invisible); . let binding = this.resolve_ident_in_module( 4,140 ( 0.00%) module, 4,140 ( 0.00%) source, . ns, 1,380 ( 0.00%) &import.parent_scope, . false, 1,380 ( 0.00%) import.span, . ); . import.vis.set(orig_vis); . source_bindings[ns].set(binding); . } else { . return; . }; . 1,380 ( 0.00%) let parent = import.parent_scope.module; 3,610 ( 0.00%) match source_bindings[ns].get() { 2,286 ( 0.00%) Err(Undetermined) => indeterminate = true, . // Don't update the resolution, because it was never added. 706 ( 0.00%) Err(Determined) if target.name == kw::Underscore => {} . Err(Determined) => { 706 ( 0.00%) let key = this.new_key(target, ns); . this.update_resolution(parent, key, |_, resolution| { 706 ( 0.00%) resolution.single_imports.remove(&PtrKey(import)); . }); . } . Ok(binding) if !binding.is_importable() => { . let msg = format!("`{}` is not directly importable", target); . struct_span_err!(this.session, import.span, E0253, "{}", &msg) . .span_label(import.span, "cannot be imported directly") . .emit(); . // Do not import this illegal binding. Import a dummy binding and pretend . // everything is fine . this.import_dummy_binding(import); . } . Ok(binding) => { 1,060 ( 0.00%) let imported_binding = this.import(binding, import); 265 ( 0.00%) target_bindings[ns].set(Some(imported_binding)); 795 ( 0.00%) this.define(parent, target, ns, imported_binding); . } . } . } 11,088 ( 0.00%) }); . 1,130 ( 0.00%) !indeterminate . } . . /// Performs final import resolution, consistency checks and error reporting. . /// . /// Optionally returns an unresolved import error. This error is buffered and used to . /// consolidate multiple unresolved import errors into a single diagnostic. 2,330 ( 0.00%) fn finalize_import(&mut self, import: &'b Import<'b>) -> Option { . let orig_vis = import.vis.replace(ty::Visibility::Invisible); 932 ( 0.00%) let orig_unusable_binding = match &import.kind { . ImportKind::Single { target_bindings, .. } => { 412 ( 0.00%) Some(mem::replace(&mut self.r.unusable_binding, target_bindings[TypeNS].get())) . } . _ => None, . }; 466 ( 0.00%) let prev_ambiguity_errors_len = self.r.ambiguity_errors.len(); . let path_res = self.r.resolve_path( . &import.module_path, . None, 233 ( 0.00%) &import.parent_scope, . true, 233 ( 0.00%) import.span, . import.crate_lint(), . ); 233 ( 0.00%) let no_ambiguity = self.r.ambiguity_errors.len() == prev_ambiguity_errors_len; 233 ( 0.00%) if let Some(orig_unusable_binding) = orig_unusable_binding { 206 ( 0.00%) self.r.unusable_binding = orig_unusable_binding; . } . import.vis.set(orig_vis); 1,165 ( 0.00%) if let PathResult::Failed { .. } | PathResult::NonModule(..) = path_res { . // Consider erroneous imports used to avoid duplicate diagnostics. . self.r.used_imports.insert(import.id); . } . let module = match path_res { 699 ( 0.00%) PathResult::Module(module) => { . // Consistency checks, analogous to `finalize_macro_resolutions`. 699 ( 0.00%) if let Some(initial_module) = import.imported_module.get() { 699 ( 0.00%) if !ModuleOrUniformRoot::same_def(module, initial_module) && no_ambiguity { . span_bug!(import.span, "inconsistent resolution for an import"); . } . } else if self.r.privacy_errors.is_empty() { . let msg = "cannot determine resolution for the import"; . let msg_note = "import resolution is stuck, try simplifying other imports"; . self.r.session.struct_span_err(import.span, msg).note(msg_note).emit(); . } . 699 ( 0.00%) module . } . PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => { . if no_ambiguity { . assert!(import.imported_module.get().is_none()); . self.r . .report_error(span, ResolutionError::FailedToResolve { label, suggestion }); . } . return None; -- line 928 ---------------------------------------- -- line 961 ---------------------------------------- . assert!(import.imported_module.get().is_none()); . } . // The error was already reported earlier. . return None; . } . PathResult::Indeterminate => unreachable!(), . }; . 2,607 ( 0.00%) let (ident, target, source_bindings, target_bindings, type_ns_only) = match import.kind { . ImportKind::Single { . source, . target, 206 ( 0.00%) ref source_bindings, 206 ( 0.00%) ref target_bindings, 206 ( 0.00%) type_ns_only, . .. . } => (source, target, source_bindings, target_bindings, type_ns_only), 54 ( 0.00%) ImportKind::Glob { is_prelude, ref max_vis } => { 81 ( 0.00%) if import.module_path.len() <= 1 { . // HACK(eddyb) `lint_if_path_starts_with_module` needs at least . // 2 segments, so the `resolve_path` above won't trigger it. . let mut full_path = import.module_path.clone(); . full_path.push(Segment::from_ident(Ident::empty())); 104 ( 0.00%) self.r.lint_if_path_starts_with_module( . import.crate_lint(), . &full_path, 26 ( 0.00%) import.span, . None, . ); . } . 134 ( 0.00%) if let ModuleOrUniformRoot::Module(module) = module { 27 ( 0.00%) if ptr::eq(module, import.parent_scope.module) { . // Importing a module into itself is not allowed. . return Some(UnresolvedImportError { . span: import.span, . label: Some(String::from("cannot glob-import a module into itself")), . note: Vec::new(), . suggestion: None, . }); . } . } 85 ( 0.00%) if !is_prelude && 26 ( 0.00%) max_vis.get() != ty::Visibility::Invisible && // Allow empty globs. 26 ( 0.00%) !max_vis.get().is_at_least(import.vis.get(), &*self) . { . let msg = "glob import doesn't reexport anything because no candidate is public enough"; . self.r.lint_buffer.buffer_lint(UNUSED_IMPORTS, import.id, import.span, msg); . } . return None; . } . _ => unreachable!(), . }; . 412 ( 0.00%) let mut all_ns_err = true; 9,476 ( 0.00%) self.r.per_ns(|this, ns| { 1,854 ( 0.00%) if !type_ns_only || ns == TypeNS { 618 ( 0.00%) let orig_vis = import.vis.replace(ty::Visibility::Invisible); . let orig_unusable_binding = 1,236 ( 0.00%) mem::replace(&mut this.unusable_binding, target_bindings[ns].get()); . let orig_last_import_segment = mem::replace(&mut this.last_import_segment, true); . let binding = this.resolve_ident_in_module( 1,854 ( 0.00%) module, 2,472 ( 0.00%) ident, . ns, 618 ( 0.00%) &import.parent_scope, . true, . import.span, . ); 1,236 ( 0.00%) this.last_import_segment = orig_last_import_segment; 1,236 ( 0.00%) this.unusable_binding = orig_unusable_binding; . import.vis.set(orig_vis); . . match binding { . Ok(binding) => { . // Consistency checks, analogous to `finalize_macro_resolutions`. 795 ( 0.00%) let initial_res = source_bindings[ns].get().map(|initial_binding| { 265 ( 0.00%) all_ns_err = false; 795 ( 0.00%) if let Some(target_binding) = target_bindings[ns].get() { 265 ( 0.00%) if target.name == kw::Underscore . && initial_binding.is_extern_crate() . && !initial_binding.is_import() . { . this.record_use( . ident, . target_binding, . import.module_path.is_empty(), . ); . } . } . initial_binding.res() . }); . let res = binding.res(); 3,710 ( 0.00%) if let Ok(initial_res) = initial_res { 795 ( 0.00%) if res != initial_res && this.ambiguity_errors.is_empty() { . span_bug!(import.span, "inconsistent resolution for an import"); . } . } else if res != Res::Err . && this.ambiguity_errors.is_empty() . && this.privacy_errors.is_empty() . { . let msg = "cannot determine resolution for the import"; . let msg_note = -- line 1063 ---------------------------------------- -- line 1070 ---------------------------------------- . // single import (see test `issue-55884-2.rs`). In theory single imports should . // always block globs, even if they are not yet resolved, so that this kind of . // self-inconsistent resolution never happens. . // Re-enable the assert when the issue is fixed. . // assert!(result[ns].get().is_err()); . } . } . } 4,944 ( 0.00%) }); . 412 ( 0.00%) if all_ns_err { . let mut all_ns_failed = true; . self.r.per_ns(|this, ns| { . if !type_ns_only || ns == TypeNS { . let binding = this.resolve_ident_in_module( . module, . ident, . ns, . &import.parent_scope, -- line 1088 ---------------------------------------- -- line 1175 ---------------------------------------- . }) . } else { . // `resolve_ident_in_module` reported a privacy error. . self.r.import_dummy_binding(import); . None . }; . } . 206 ( 0.00%) let mut reexport_error = None; 206 ( 0.00%) let mut any_successful_reexport = false; 412 ( 0.00%) let mut crate_private_reexport = false; 2,472 ( 0.00%) self.r.per_ns(|this, ns| { 1,442 ( 0.00%) if let Ok(binding) = source_bindings[ns].get() { 795 ( 0.00%) let vis = import.vis.get(); 1,590 ( 0.00%) if !binding.vis.is_at_least(vis, &*this) { . reexport_error = Some((ns, binding)); . if let ty::Visibility::Restricted(binding_def_id) = binding.vis { . if binding_def_id.is_top_level_module() { . crate_private_reexport = true; . } . } . } else { 530 ( 0.00%) any_successful_reexport = true; . } . } . }); . . // All namespaces must be re-exported with extra visibility for an error to occur. 412 ( 0.00%) if !any_successful_reexport { . let (ns, binding) = reexport_error.unwrap(); . if pub_use_of_private_extern_crate_hack(import, binding) { . let msg = format!( . "extern crate `{}` is private, and cannot be \ . re-exported (error E0365), consider declaring with \ . `pub`", . ident . ); -- line 1211 ---------------------------------------- -- line 1241 ---------------------------------------- . format!("consider marking `{}` as `pub` in the imported module", ident); . struct_span_err!(self.r.session, import.span, E0364, "{}", error_msg) . .span_note(import.span, ¬e_msg) . .emit(); . } . } . } . 618 ( 0.00%) if import.module_path.len() <= 1 { . // HACK(eddyb) `lint_if_path_starts_with_module` needs at least . // 2 segments, so the `resolve_path` above won't trigger it. . let mut full_path = import.module_path.clone(); 582 ( 0.00%) full_path.push(Segment::from_ident(ident)); 1,358 ( 0.00%) self.r.per_ns(|this, ns| { 1,169 ( 0.00%) if let Ok(binding) = source_bindings[ns].get() { 753 ( 0.00%) this.lint_if_path_starts_with_module( . import.crate_lint(), . &full_path, 251 ( 0.00%) import.span, . Some(binding), . ); . } . }); . } . . // Record what this import resolves to for later uses in documentation, . // this may resolve to either a value or a type, but for documentation . // purposes it's good enough to just favor one over the other. 5,768 ( 0.00%) self.r.per_ns(|this, ns| { 2,413 ( 0.00%) if let Ok(binding) = source_bindings[ns].get() { 4,240 ( 0.00%) this.import_res_map.entry(import.id).or_default()[ns] = Some(binding.res()); . } 4,944 ( 0.00%) }); . 1,854 ( 0.00%) self.check_for_redundant_imports(ident, import, source_bindings, target_bindings, target); . . debug!("(resolving single import) successfully resolved import"); . None 1,864 ( 0.00%) } . . fn check_for_redundant_imports( . &mut self, . ident: Ident, . import: &'b Import<'b>, . source_bindings: &PerNS, Determinacy>>>, . target_bindings: &PerNS>>>, . target: Ident, . ) { . // Skip if the import was produced by a macro. 206 ( 0.00%) if import.parent_scope.expansion != LocalExpnId::ROOT { . return; . } . . // Skip if we are inside a named module (in contrast to an anonymous . // module defined by a block). 618 ( 0.00%) if let ModuleKind::Def(..) = import.parent_scope.module.kind { . return; . } . 2 ( 0.00%) let mut is_redundant = PerNS { value_ns: None, type_ns: None, macro_ns: None }; . 4 ( 0.00%) let mut redundant_span = PerNS { value_ns: None, type_ns: None, macro_ns: None }; . 44 ( 0.00%) self.r.per_ns(|this, ns| { 11 ( 0.00%) if let Ok(binding) = source_bindings[ns].get() { 5 ( 0.00%) if binding.res() == Res::Err { . return; . } . . let orig_unusable_binding = 2 ( 0.00%) mem::replace(&mut this.unusable_binding, target_bindings[ns].get()); . 12 ( 0.00%) match this.early_resolve_ident_in_lexical_scope( 3 ( 0.00%) target, . ScopeSet::All(ns, false), 2 ( 0.00%) &import.parent_scope, . false, . false, . import.span, . ) { . Ok(other_binding) => { . is_redundant[ns] = Some( . binding.res() == other_binding.res() && !other_binding.is_ambiguity(), . ); . redundant_span[ns] = Some((other_binding.span, other_binding.is_import())); . } 2 ( 0.00%) Err(_) => is_redundant[ns] = Some(false), . } . 2 ( 0.00%) this.unusable_binding = orig_unusable_binding; . } 24 ( 0.00%) }); . 8 ( 0.00%) if !is_redundant.is_empty() && is_redundant.present_items().all(|is_redundant| is_redundant) . { . let mut redundant_spans: Vec<_> = redundant_span.present_items().collect(); . redundant_spans.sort(); . redundant_spans.dedup(); . self.r.lint_buffer.buffer_lint_with_diagnostic( . UNUSED_IMPORTS, . import.id, . import.span, -- line 1342 ---------------------------------------- -- line 1350 ---------------------------------------- . let module = match import.imported_module.get().unwrap() { . ModuleOrUniformRoot::Module(module) => module, . _ => { . self.r.session.span_err(import.span, "cannot glob-import all possible crates"); . return; . } . }; . 81 ( 0.00%) if module.is_trait() { . self.r.session.span_err(import.span, "items in traits are not importable"); . return; 27 ( 0.00%) } else if ptr::eq(module, import.parent_scope.module) { . return; 108 ( 0.00%) } else if let ImportKind::Glob { is_prelude: true, .. } = import.kind { 2 ( 0.00%) self.r.prelude = Some(module); . return; . } . . // Add to module's glob_importers . module.glob_importers.borrow_mut().push(import); . . // Ensure that `resolutions` isn't borrowed during `try_define`, . // since it might get updated via a glob cycle. 78 ( 0.00%) let bindings = self . .r . .resolutions(module) . .borrow() . .iter() . .filter_map(|(key, resolution)| { 1,753 ( 0.00%) resolution.borrow().binding().map(|binding| (*key, binding)) . }) . .collect::>(); 564 ( 0.00%) for (mut key, binding) in bindings { 2,535 ( 0.00%) let scope = match key.ident.span.reverse_glob_adjust(module.expansion, import.span) { . Some(Some(def)) => self.r.expn_def_scope(def), 558 ( 0.00%) Some(None) => import.parent_scope.module, . None => continue, . }; 2,232 ( 0.00%) if self.r.is_accessible_from(binding.vis, scope) { 336 ( 0.00%) let imported_binding = self.r.import(binding, import); 1,848 ( 0.00%) let _ = self.r.try_define(import.parent_scope.module, key, imported_binding); . } . } . . // Record the destination of this import . self.r.record_partial_res(import.id, PartialRes::new(module.res().unwrap())); . } . . // Miscellaneous post-processing, including recording re-exports, . // reporting conflicts, and reporting unresolved imports. . fn finalize_resolutions_in(&mut self, module: Module<'b>) { . // Since import resolution is finished, globs will not define any more names. 9,332 ( 0.00%) *module.globs.borrow_mut() = Vec::new(); . . let mut reexports = Vec::new(); . 11,665 ( 0.00%) module.for_each_child(self.r, |_, ident, _, binding| { . // Filter away ambiguous imports and anything that has def-site hygiene. . // FIXME: Implement actual cross-crate hygiene. . let is_good_import = 10,624 ( 0.00%) binding.is_import() && !binding.is_ambiguity() && !ident.span.from_expansion(); 24,917 ( 0.00%) if is_good_import || binding.is_macro_def() { . let res = binding.res().expect_non_local(); . if res != def::Res::Err { 11,756 ( 0.00%) reexports.push(ModChild { ident, res, vis: binding.vis, span: binding.span }); . } . } . }); . 2,333 ( 0.00%) if !reexports.is_empty() { 745 ( 0.00%) if let Some(def_id) = module.opt_def_id() { . // Call to `expect_local` should be fine because current . // code is only called for local modules. . self.r.reexport_map.insert(def_id.expect_local(), reexports); . } . } . } . } . -- line 1428 ---------------------------------------- 2,819,480 ( 0.01%) -------------------------------------------------------------------------------- The following files chosen for auto-annotation could not be found: -------------------------------------------------------------------------------- ./elf/../elf/dl-tls.c ./elf/../sysdeps/x86_64/dl-tls.c ./elf/../sysdeps/x86_64/tls_get_addr.S ./malloc/malloc.c ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S -------------------------------------------------------------------------------- Ir -------------------------------------------------------------------------------- 13,765,101,652 (39.63%) events annotated