-------------------------------------------------------------------------------- I1 cache: 65536 B, 64 B, 4-way associative D1 cache: 32768 B, 64 B, 8-way associative LL cache: 67108864 B, 64 B, 64-way associative Command: /usr/home/liquid/.rustup/toolchains/w-profiling/bin/rustc --crate-name time_macros --edition=2018 src/lib.rs --error-format=json --json=diagnostic-rendered-ansi,artifacts,future-incompat --crate-type proc-macro --emit=dep-info,metadata -C prefer-dynamic -C embed-bitcode=no -C debuginfo=2 -C metadata=9cd0007715307af7 -C extra-filename=-9cd0007715307af7 --out-dir /usr/home/liquid/tmp/.tmpJduqiu/target/debug/deps -L dependency=/usr/home/liquid/tmp/.tmpJduqiu/target/debug/deps --extern proc_macro -Adeprecated -Aunknown-lints -Zincremental-verify-ich Data file: results/cgout-w-profiling-time-macros-0.2.3-Check-Full Events recorded: Ir Events shown: Ir Event sort order: Ir Thresholds: 0.1 Include dirs: User annotated: Auto-annotation: on -------------------------------------------------------------------------------- Ir -------------------------------------------------------------------------------- 4,028,893,325 (100.0%) PROGRAM TOTALS -------------------------------------------------------------------------------- Ir file:function -------------------------------------------------------------------------------- 225,565,744 ( 5.60%) ./malloc/malloc.c:_int_free 186,446,227 ( 4.63%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe/macro_parser.rs:rustc_expand::mbe::macro_parser::parse_tt 178,530,307 ( 4.43%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::bump 173,132,617 ( 4.30%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::next 148,097,732 ( 3.68%) ./malloc/malloc.c:malloc 146,867,522 ( 3.65%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs:rustc_expand::mbe::macro_parser::parse_tt 131,811,517 ( 3.27%) ./malloc/malloc.c:_int_malloc 121,910,129 ( 3.03%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/tokenstream.rs:::next_with_spacing 80,834,550 ( 2.01%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::bump_with 76,979,808 ( 1.91%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::next_desugared 75,152,572 ( 1.87%) ./malloc/malloc.c:free 54,311,007 ( 1.35%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::clone 51,734,112 ( 1.28%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:>::truncate 46,373,315 ( 1.15%) ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:__memcpy_avx_unaligned_erms 46,307,724 ( 1.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe/macro_parser.rs:::clone 43,719,192 ( 1.09%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe.rs:::get_tt 34,221,904 ( 0.85%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:rustc_expand::mbe::macro_parser::parse_tt 31,734,673 ( 0.79%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs: as core::iter::traits::collect::Extend>::extend::>> 31,279,413 ( 0.78%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:core::ptr::drop_in_place:: 30,704,509 ( 0.76%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::parse_token_tree 29,479,464 ( 0.73%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe.rs:rustc_expand::mbe::macro_parser::parse_tt 29,456,474 ( 0.73%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/nonterminal.rs:::parse_nonterminal 29,339,521 ( 0.73%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::eq 29,100,438 ( 0.72%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:::bump_with 29,046,512 ( 0.72%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs:>>::make_mut 27,482,269 ( 0.68%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::ident 26,759,502 ( 0.66%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs: as core::iter::traits::collect::Extend>::extend::>> 24,371,332 ( 0.60%) ./malloc/malloc.c:malloc_consolidate 24,078,790 ( 0.60%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::lifetime 22,781,108 ( 0.57%) /usr/home/liquid/rust/worktree-benchmarking/library/std/src/sys/unix/alloc.rs:__rdl_alloc 20,738,073 ( 0.51%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs:>::try_reserve 20,473,315 ( 0.51%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs: as core::ops::drop::Drop>::drop 19,442,047 ( 0.48%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:::bump_with 19,400,286 ( 0.48%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/span_encoding.rs:::bump 19,324,432 ( 0.48%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs:>::try_reserve 15,873,850 ( 0.39%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe.rs:::clone 15,288,713 ( 0.38%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs: as core::ops::drop::Drop>::drop 14,642,432 ( 0.36%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs:core::ptr::drop_in_place:: 13,881,705 ( 0.34%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs: as core::ops::drop::Drop>::drop 13,152,511 ( 0.33%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs: as core::ops::drop::Drop>::drop 12,933,528 ( 0.32%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/mem/mod.rs:::bump_with 12,899,018 ( 0.32%) ./malloc/malloc.c:unlink_chunk.constprop.0 12,101,144 ( 0.30%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::clone 11,524,538 ( 0.29%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs: as core::ops::drop::Drop>::drop 11,302,863 ( 0.28%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs:rustc_expand::mbe::macro_parser::parse_tt 11,229,015 ( 0.28%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs: as core::iter::traits::collect::Extend>::extend::>> 10,599,220 ( 0.26%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/nonterminal.rs:::nonterminal_may_begin_with 10,305,124 ( 0.26%) ./elf/dl-lookup.c:_dl_lookup_symbol_x 10,164,388 ( 0.25%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/alloc.rs:rustc_expand::mbe::macro_parser::parse_tt 10,127,891 ( 0.25%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs:> as core::ops::drop::Drop>::drop 9,930,240 ( 0.25%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/boxed.rs:>]> as core::clone::Clone>::clone 9,903,738 ( 0.25%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe/macro_parser.rs:::clone 9,815,629 ( 0.24%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:core::ptr::drop_in_place:: 9,071,873 ( 0.23%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe/transcribe.rs:rustc_expand::mbe::transcribe::transcribe 8,930,482 ( 0.22%) ./malloc/malloc.c:realloc 8,706,897 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs: as core::ops::drop::Drop>::drop 8,694,439 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:>>::make_mut 7,900,748 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs: as core::ops::drop::Drop>::drop 7,766,769 ( 0.19%) ./string/../sysdeps/x86_64/multiarch/memcmp-avx2-movbe.S:__memcmp_avx2_movbe 7,491,867 ( 0.19%) ???:object::read::archive::parse_u64_digits 7,085,248 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:::next 6,757,814 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs:::short_write_process_buffer:: 6,691,226 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs: as core::iter::traits::collect::Extend>::extend::>> 6,671,940 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_serialize/src/leb128.rs:::read_usize 6,620,580 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/option.rs:::clone 6,595,755 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/index.rs:::get_tt 6,567,748 ( 0.16%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, (), core::hash::BuildHasherDefault>>::from_hash::>::{closure#0}> 6,508,888 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/library/std/src/alloc.rs:__rdl_alloc 6,256,178 ( 0.16%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::from_key_hashed_nocheck:: 6,202,022 ( 0.15%) ./malloc/malloc.c:_int_realloc 6,034,211 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/convert/mod.rs:::next 5,994,545 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/alloc.rs:core::ptr::drop_in_place:: 5,959,610 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:>]> as core::clone::Clone>::clone 5,735,476 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/mod.rs:::shallow_resolve_ty 5,631,807 ( 0.14%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::get:: 5,614,679 ( 0.14%) ./stdlib/canonicalize.c:realpath@@GLIBC_2.3 5,534,268 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/borrow.rs:rustc_expand::mbe::macro_parser::parse_tt 5,462,688 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_metadata/src/rmeta/decoder.rs:::read_lazy_with_meta::<[u32]> 5,359,671 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:::next 5,299,060 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs:>]> as core::clone::Clone>::clone 5,298,327 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/iter/adapters/take.rs:>]> as core::clone::Clone>::clone 5,296,128 ( 0.13%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs:::clone 5,283,211 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_serialize/src/leb128.rs:::read_usize 5,229,406 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe.rs:::clone 5,228,776 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe/macro_parser.rs: as core::iter::traits::collect::Extend>::extend::>> 4,937,538 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/convert/mod.rs:<(rustc_ast::tokenstream::TokenTree, rustc_ast::tokenstream::Spacing) as core::convert::From>::from 4,835,679 ( 0.12%) ./elf/dl-lookup.c:do_lookup_x 4,681,633 ( 0.12%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs:>>::make_mut 4,648,100 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/clone.rs:::clone 4,634,112 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/alloc.rs:>]> as core::clone::Clone>::clone 4,634,112 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:>]> as core::clone::Clone>::clone 4,620,510 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/option.rs:rustc_expand::mbe::macro_parser::parse_tt 4,581,804 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/ast_like.rs:::tokens_mut 4,533,192 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs:::short_write_process_buffer:: 4,328,541 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:>::truncate 4,305,768 ( 0.11%) ???:object::read::archive::parse_sysv_extended_name 4,225,964 ( 0.10%) /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}> 4,141,271 ( 0.10%) ./elf/../sysdeps/x86_64/dl-machine.h:_dl_relocate_object -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs -------------------------------------------------------------------------------- Ir -- line 111 ---------------------------------------- . const EMPTY: u8 = 0b1111_1111; . . /// Control byte value for a deleted bucket. . const DELETED: u8 = 0b1000_0000; . . /// Checks whether a control byte represents a full bucket (top bit is clear). . #[inline] . fn is_full(ctrl: u8) -> bool { 1,206,865 ( 0.03%) ctrl & 0x80 == 0 . } . . /// Checks whether a control byte represents a special value (top bit is set). . #[inline] . fn is_special(ctrl: u8) -> bool { . ctrl & 0x80 != 0 . } . . /// Checks whether a special control value is EMPTY (just check 1 bit). . #[inline] . fn special_is_empty(ctrl: u8) -> bool { . debug_assert!(is_special(ctrl)); 76,591 ( 0.00%) ctrl & 0x01 != 0 . } . . /// Primary hash function, used to select the initial bucket to probe from. . #[inline] . #[allow(clippy::cast_possible_truncation)] . fn h1(hash: u64) -> usize { . // On 32-bit platforms we simply ignore the higher hash bits. . hash as usize -- line 140 ---------------------------------------- -- line 143 ---------------------------------------- . /// Secondary hash function, saved in the low 7 bits of the control byte. . #[inline] . #[allow(clippy::cast_possible_truncation)] . fn h2(hash: u64) -> u8 { . // Grab the top 7 bits of the hash. While the hash is normally a full 64-bit . // value, some hash functions (such as FxHash) produce a usize result . // instead, which means that the top 32 bits are 0 on 32-bit platforms. . let hash_len = usize::min(mem::size_of::(), mem::size_of::()); 25,764,672 ( 0.64%) let top7 = hash >> (hash_len * 8 - 7); . (top7 & 0x7f) as u8 // truncation . } . . /// Probe sequence based on triangular numbers, which is guaranteed (since our . /// table size is a power of two) to visit every group of elements exactly once. . /// . /// A triangular probe has us jump by 1 more group every time. So first we . /// jump by 1 group (meaning we just continue our linear scan), then 2 groups -- line 159 ---------------------------------------- -- line 170 ---------------------------------------- . #[inline] . fn move_next(&mut self, bucket_mask: usize) { . // We should have found an empty bucket by now and ended the probe. . debug_assert!( . self.stride <= bucket_mask, . "Went past end of probe sequence" . ); . 185,846 ( 0.00%) self.stride += Group::WIDTH; 185,846 ( 0.00%) self.pos += self.stride; 166,401 ( 0.00%) self.pos &= bucket_mask; . } . } . . /// Returns the number of buckets needed to hold the given number of items, . /// taking the maximum load factor into account. . /// . /// Returns `None` if an overflow occurs. . // Workaround for emscripten bug emscripten-core/emscripten-fastcomp#258 . #[cfg_attr(target_os = "emscripten", inline(never))] . #[cfg_attr(not(target_os = "emscripten"), inline)] . fn capacity_to_buckets(cap: usize) -> Option { . debug_assert_ne!(cap, 0); . . // For small tables we require at least 1 empty bucket so that lookups are . // guaranteed to terminate if an element doesn't exist in the table. 102,136 ( 0.00%) if cap < 8 { . // We don't bother with a table size of 2 buckets since that can only . // hold a single element. Instead we skip directly to a 4 bucket table . // which can hold 3 elements. 229,160 ( 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. 31,416 ( 0.00%) let adjusted_cap = cap.checked_mul(8)? / 7; . . // Any overflows will have been caught by the checked_mul. Also, any . // rounding errors from the division above will be cleaned up by . // next_power_of_two (which can't overflow because of the previous division). . Some(adjusted_cap.next_power_of_two()) . } . . /// Returns the maximum effective capacity for the given bucket mask, taking . /// the maximum load factor into account. . #[inline] . fn bucket_mask_to_capacity(bucket_mask: usize) -> usize { 275,433 ( 0.01%) if bucket_mask < 8 { . // For tables with 1/2/4/8 buckets, we always reserve one empty slot. . // Keep in mind that the bucket mask is one less than the bucket count. . bucket_mask . } else { . // For larger tables we reserve 12.5% of the slots as empty. 42,840 ( 0.00%) ((bucket_mask + 1) / 8) * 7 . } . } . . /// Helper which allows the max calculation for ctrl_align to be statically computed for each T . /// while keeping the rest of `calculate_layout_for` independent of `T` . #[derive(Copy, Clone)] . struct TableLayout { . size: usize, -- line 233 ---------------------------------------- -- line 246 ---------------------------------------- . . #[inline] . fn calculate_layout_for(self, buckets: usize) -> Option<(Layout, usize)> { . debug_assert!(buckets.is_power_of_two()); . . let TableLayout { size, ctrl_align } = self; . // Manual layout calculation since Layout methods are not yet stable. . let ctrl_offset = 233,242 ( 0.01%) size.checked_mul(buckets)?.checked_add(ctrl_align - 1)? & !(ctrl_align - 1); 293,335 ( 0.01%) let len = ctrl_offset.checked_add(buckets + Group::WIDTH)?; . . Some(( . unsafe { Layout::from_size_align_unchecked(len, ctrl_align) }, . ctrl_offset, . )) . } . } . -- line 263 ---------------------------------------- -- line 337 ---------------------------------------- . } . } . #[cfg_attr(feature = "inline-more", inline)] . pub unsafe fn drop(&self) { . self.as_ptr().drop_in_place(); . } . #[inline] . pub unsafe fn read(&self) -> T { 740 ( 0.00%) self.as_ptr().read() . } . #[inline] . pub unsafe fn write(&self, val: T) { . self.as_ptr().write(val); . } . #[inline] . pub unsafe fn as_ref<'a>(&self) -> &'a T { . &*self.as_ptr() -- line 353 ---------------------------------------- -- line 422 ---------------------------------------- . /// Creates a new empty hash table without allocating any memory, using the . /// given allocator. . /// . /// In effect this returns a table with exactly 1 bucket. However we can . /// leave the data pointer dangling since that bucket is never written to . /// due to our load factor forcing us to always have at least 1 free bucket. . #[inline] . pub fn new_in(alloc: A) -> Self { 26,748 ( 0.00%) Self { . table: RawTableInner::new_in(alloc), . marker: PhantomData, . } . } . . /// Allocates a new hash table with the given number of buckets. . /// . /// The control bytes are left uninitialized. -- line 438 ---------------------------------------- -- line 440 ---------------------------------------- . unsafe fn new_uninitialized( . alloc: A, . buckets: usize, . fallibility: Fallibility, . ) -> Result { . debug_assert!(buckets.is_power_of_two()); . . Ok(Self { 95 ( 0.00%) table: RawTableInner::new_uninitialized( . alloc, . TableLayout::new::(), . buckets, . fallibility, . )?, . marker: PhantomData, . }) . } -- line 456 ---------------------------------------- -- line 458 ---------------------------------------- . /// Attempts to allocate a new hash table with at least enough capacity . /// for inserting the given number of elements without reallocating. . fn fallible_with_capacity( . alloc: A, . capacity: usize, . fallibility: Fallibility, . ) -> Result { . Ok(Self { 20,981 ( 0.00%) table: RawTableInner::fallible_with_capacity( . alloc, . TableLayout::new::(), . capacity, . fallibility, . )?, . marker: PhantomData, . }) . } -- line 474 ---------------------------------------- -- line 527 ---------------------------------------- . debug_assert_ne!(self.table.bucket_mask, 0); . debug_assert!(index < self.buckets()); . Bucket::from_base_index(self.data_end(), index) . } . . /// Erases an element from the table without dropping it. . #[cfg_attr(feature = "inline-more", inline)] . #[deprecated(since = "0.8.1", note = "use erase or remove instead")] 15,461 ( 0.00%) pub unsafe fn erase_no_drop(&mut self, item: &Bucket) { 15,461 ( 0.00%) let index = self.bucket_index(item); . self.table.erase(index); 30,922 ( 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. 15,926 ( 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 { 14,996 ( 0.00%) self.erase_no_drop(&item); 175 ( 0.00%) item.read() . } . . /// Finds and removes an element from the table, returning it. . #[cfg_attr(feature = "inline-more", inline)] 429,982 ( 0.01%) pub fn remove_entry(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option { . // Avoid `Option::map` because it bloats LLVM IR. 404 ( 0.00%) match self.find(hash, eq) { 15,055 ( 0.00%) Some(bucket) => Some(unsafe { self.remove(bucket) }), 126,851 ( 0.00%) None => None, . } 603,303 ( 0.01%) } . . /// Marks all table buckets as empty without dropping their contents. . #[cfg_attr(feature = "inline-more", inline)] . pub fn clear_no_drop(&mut self) { . self.table.clear_no_drop(); . } . . /// Removes all elements from the table without freeing the backing memory. . #[cfg_attr(feature = "inline-more", inline)] . pub fn clear(&mut self) { . // Ensure that the table is reset even if one of the drops panic . let mut self_ = guard(self, |self_| self_.clear_no_drop()); . unsafe { 1 ( 0.00%) self_.drop_elements(); . } . } . 7 ( 0.00%) unsafe fn drop_elements(&mut self) { 12,716 ( 0.00%) if mem::needs_drop::() && !self.is_empty() { . for item in self.iter() { . item.drop(); . } . } 8 ( 0.00%) } . . /// Shrinks the table to fit `max(self.len(), min_size)` elements. . #[cfg_attr(feature = "inline-more", inline)] . pub fn shrink_to(&mut self, min_size: usize, hasher: impl Fn(&T) -> u64) { . // Calculate the minimal number of elements that we need to reserve . // space for. . let min_size = usize::max(self.table.items, min_size); . if min_size == 0 { -- line 615 ---------------------------------------- -- line 642 ---------------------------------------- . } . } . } . . /// Ensures that at least `additional` items can be inserted into the table . /// without reallocation. . #[cfg_attr(feature = "inline-more", inline)] . pub fn reserve(&mut self, additional: usize, hasher: impl Fn(&T) -> u64) { 221,467 ( 0.01%) if additional > self.table.growth_left { . // Avoid `Result::unwrap_or_else` because it bloats LLVM IR. 187,389 ( 0.00%) if self . .reserve_rehash(additional, hasher, Fallibility::Infallible) . .is_err() . { . unsafe { hint::unreachable_unchecked() } . } . } . } . -- line 660 ---------------------------------------- -- line 671 ---------------------------------------- . } else { . Ok(()) . } . } . . /// Out-of-line slow path for `reserve` and `try_reserve`. . #[cold] . #[inline(never)] 409,387 ( 0.01%) fn reserve_rehash( . &mut self, . additional: usize, . hasher: impl Fn(&T) -> u64, . fallibility: Fallibility, . ) -> Result<(), TryReserveError> { . unsafe { . self.table.reserve_rehash_inner( . additional, -- line 687 ---------------------------------------- -- line 690 ---------------------------------------- . TableLayout::new::(), . if mem::needs_drop::() { . Some(mem::transmute(ptr::drop_in_place:: as unsafe fn(*mut T))) . } else { . None . }, . ) . } 330,952 ( 0.01%) } . . /// Allocates a new table of a different size and moves the contents of the . /// current table into it. . fn resize( . &mut self, . capacity: usize, . hasher: impl Fn(&T) -> u64, . fallibility: Fallibility, -- line 706 ---------------------------------------- -- line 714 ---------------------------------------- . ) . } . } . . /// Inserts a new element into the table, and returns its raw bucket. . /// . /// This does not check if the given element already exists in the table. . #[cfg_attr(feature = "inline-more", inline)] 1,440,440 ( 0.04%) pub fn insert(&mut self, hash: u64, value: T, hasher: impl Fn(&T) -> u64) -> Bucket { . unsafe { . let mut index = self.table.find_insert_slot(hash); . . // We can avoid growing the table once we have reached our load . // factor if we are replacing a tombstone. This works since the . // number of EMPTY slots does not change in this case. 2,004 ( 0.00%) let old_ctrl = *self.table.ctrl(index); 1,126,872 ( 0.03%) if unlikely(self.table.growth_left == 0 && special_is_empty(old_ctrl)) { . self.reserve(1, hasher); . index = self.table.find_insert_slot(hash); . } . . self.table.record_item_insert_at(index, old_ctrl, hash); . . let bucket = self.bucket(index); 2 ( 0.00%) bucket.write(value); . bucket . } 1,065,467 ( 0.03%) } . . /// 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)] 411,224 ( 0.01%) pub fn insert_entry(&mut self, hash: u64, value: T, hasher: impl Fn(&T) -> u64) -> &mut T { 94 ( 0.00%) unsafe { self.insert(hash, value, hasher).as_mut() } 308,418 ( 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"))] 5,845 ( 0.00%) pub unsafe fn insert_no_grow(&mut self, hash: u64, value: T) -> Bucket { 197,351 ( 0.00%) let (index, old_ctrl) = self.table.prepare_insert_slot(hash); 11,165 ( 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. 429,422 ( 0.01%) self.table.growth_left -= special_is_empty(old_ctrl) as usize; . . bucket.write(value); 351,666 ( 0.01%) self.table.items += 1; . bucket 11,685 ( 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] 384 ( 0.00%) pub fn find(&self, hash: u64, mut eq: impl FnMut(&T) -> bool) -> Option> { 6,819 ( 0.00%) let result = self.table.find_inner(hash, &mut |index| unsafe { 27,222 ( 0.00%) eq(self.bucket(index).as_ref()) 4,674 ( 0.00%) }); . . // Avoid `Option::map` because it bloats LLVM IR. . match result { 1,180 ( 0.00%) Some(index) => Some(unsafe { self.bucket(index) }), . None => None, . } 384 ( 0.00%) } . . /// Gets a reference to an element in the table. . #[inline] . pub fn get(&self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option<&T> { . // Avoid `Option::map` because it bloats LLVM IR. 177,263 ( 0.00%) match self.find(hash, eq) { . Some(bucket) => Some(unsafe { bucket.as_ref() }), . None => None, . } . } . . /// Gets a mutable reference to an element in the table. . #[inline] . pub fn get_mut(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option<&mut T> { . // Avoid `Option::map` because it bloats LLVM IR. 728 ( 0.00%) match self.find(hash, eq) { . Some(bucket) => Some(unsafe { bucket.as_mut() }), . None => None, . } . } . . /// 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. -- line 855 ---------------------------------------- -- line 920 ---------------------------------------- . #[inline] . pub fn len(&self) -> usize { . self.table.items . } . . /// Returns `true` if the table contains no elements. . #[inline] . pub fn is_empty(&self) -> bool { 961,764 ( 0.02%) self.len() == 0 . } . . /// Returns the number of buckets in the table. . #[inline] . pub fn buckets(&self) -> usize { . self.table.bucket_mask + 1 . } . . /// Returns an iterator over every element in the table. It is up to . /// the caller to ensure that the `RawTable` outlives the `RawIter`. . /// Because we cannot make the `next` method unsafe on the `RawIter` . /// struct, we have to make the `iter` method unsafe. . #[inline] . pub unsafe fn iter(&self) -> RawIter { 15 ( 0.00%) let data = Bucket::from_base_index(self.data_end(), 0); . RawIter { . iter: RawIterRange::new(self.table.ctrl.as_ptr(), data, self.table.buckets()), 84,790 ( 0.00%) items: self.table.items, . } . } . . /// Returns an iterator over occupied buckets that could match a given hash. . /// . /// `RawTable` only stores 7 bits of the hash value, so this iterator may . /// return items that have a hash value different than the one provided. You . /// should always validate the returned values before using them. -- line 954 ---------------------------------------- -- line 995 ---------------------------------------- . /// Iteration starts at the provided iterator's current location. . /// . /// It is up to the caller to ensure that the iterator is valid for this . /// `RawTable` and covers all items that remain in the table. . pub unsafe fn into_iter_from(self, iter: RawIter) -> RawIntoIter { . debug_assert_eq!(iter.len(), self.len()); . . let alloc = self.table.alloc.clone(); 54,192 ( 0.00%) let allocation = self.into_allocation(); 40,644 ( 0.00%) RawIntoIter { 67,740 ( 0.00%) iter, . allocation, . marker: PhantomData, . alloc, . } . } . . /// Converts the table into a raw allocation. The contents of the table . /// should be dropped using a `RawIter` before freeing the allocation. . #[cfg_attr(feature = "inline-more", inline)] . pub(crate) fn into_allocation(self) -> Option<(NonNull, Layout)> { 14,019 ( 0.00%) let alloc = if self.table.is_empty_singleton() { . None . } else { . // Avoid `Option::unwrap_or_else` because it bloats LLVM IR. . let (layout, ctrl_offset) = match calculate_layout::(self.table.buckets()) { . Some(lco) => lco, . None => unsafe { hint::unreachable_unchecked() }, . }; . Some(( 9,835 ( 0.00%) unsafe { NonNull::new_unchecked(self.table.ctrl.as_ptr().sub(ctrl_offset)) }, . layout, . )) . }; . mem::forget(self); . alloc . } . } . -- line 1033 ---------------------------------------- -- line 1042 ---------------------------------------- . T: Sync, . A: Sync, . { . } . . impl RawTableInner { . #[inline] . const fn new_in(alloc: A) -> Self { 524,613 ( 0.01%) Self { . // Be careful to cast the entire slice to a raw pointer. . ctrl: unsafe { NonNull::new_unchecked(Group::static_empty() as *const _ as *mut u8) }, . bucket_mask: 0, . items: 0, . growth_left: 0, . alloc, . } . } . } . . impl RawTableInner { . #[cfg_attr(feature = "inline-more", inline)] 323,155 ( 0.01%) unsafe fn new_uninitialized( . alloc: A, . table_layout: TableLayout, . buckets: usize, . fallibility: Fallibility, . ) -> Result { . debug_assert!(buckets.is_power_of_two()); . . // Avoid `Option::ok_or_else` because it bloats LLVM IR. -- line 1071 ---------------------------------------- -- line 1078 ---------------------------------------- . // exceed `isize::MAX`. We can skip this check on 64-bit systems since . // such allocations will never succeed anyways. . // . // This mirrors what Vec does in the standard library. . if mem::size_of::() < 8 && layout.size() > isize::MAX as usize { . return Err(fallibility.capacity_overflow()); . } . 95,204 ( 0.00%) let ptr: NonNull = match do_alloc(&alloc, layout) { . Ok(block) => block.cast(), . Err(_) => return Err(fallibility.alloc_err(layout)), . }; . . let ctrl = NonNull::new_unchecked(ptr.as_ptr().add(ctrl_offset)); 179,868 ( 0.00%) Ok(Self { . ctrl, 81,065 ( 0.00%) bucket_mask: buckets - 1, . items: 0, . growth_left: bucket_mask_to_capacity(buckets - 1), . alloc, . }) 235,422 ( 0.01%) } . . #[inline] 146,667 ( 0.00%) fn fallible_with_capacity( . alloc: A, . table_layout: TableLayout, . capacity: usize, . fallibility: Fallibility, . ) -> Result { 36,744 ( 0.00%) if capacity == 0 { 19,754 ( 0.00%) Ok(Self::new_in(alloc)) . } else { . unsafe { . let buckets = . capacity_to_buckets(capacity).ok_or_else(|| fallibility.capacity_overflow())?; . 147,270 ( 0.00%) let result = Self::new_uninitialized(alloc, table_layout, buckets, fallibility)?; . result.ctrl(0).write_bytes(EMPTY, result.num_ctrl_bytes()); . 86,404 ( 0.00%) Ok(result) . } . } 146,667 ( 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] 70,751 ( 0.00%) unsafe fn prepare_insert_slot(&self, hash: u64) -> (usize, u8) { . let index = self.find_insert_slot(hash); 70,751 ( 0.00%) let old_ctrl = *self.ctrl(index); . self.set_ctrl_h2(index, hash); . (index, old_ctrl) 141,502 ( 0.00%) } . . /// Searches for an empty or deleted bucket which is suitable for inserting . /// a new element. . /// . /// There must be at least 1 empty bucket in the table. . #[inline] . fn find_insert_slot(&self, hash: u64) -> usize { . let mut probe_seq = self.probe_seq(hash); . loop { . unsafe { . let group = Group::load(self.ctrl(probe_seq.pos)); 768,028 ( 0.02%) if let Some(bit) = group.match_empty_or_deleted().lowest_set_bit() { 2,255,501 ( 0.06%) let result = (probe_seq.pos + bit) & self.bucket_mask; . . // In tables smaller than the group width, trailing control . // bytes outside the range of the table are filled with . // EMPTY entries. These will unfortunately trigger a . // match, but once masked may point to a full bucket that . // is already occupied. We detect this situation here and . // perform a second scan starting at the beginning of the . // table. This second scan is guaranteed to find an empty . // slot (due to the load factor) before hitting the trailing . // control bytes (containing EMPTY). 1,031,650 ( 0.03%) if unlikely(is_full(*self.ctrl(result))) { . debug_assert!(self.bucket_mask < Group::WIDTH); . debug_assert_ne!(probe_seq.pos, 0); . return Group::load_aligned(self.ctrl(0)) . .match_empty_or_deleted() . .lowest_set_bit_nonzero(); . } . . return result; -- line 1165 ---------------------------------------- -- line 1171 ---------------------------------------- . . /// Searches for an element in the table. This uses dynamic dispatch to reduce the amount of . /// code generated, but it is eliminated by LLVM optimizations. . #[inline] . fn find_inner(&self, hash: u64, eq: &mut dyn FnMut(usize) -> bool) -> Option { . let h2_hash = h2(hash); . let mut probe_seq = self.probe_seq(hash); . 56,748 ( 0.00%) loop { . let group = unsafe { Group::load(self.ctrl(probe_seq.pos)) }; . 2,977,197 ( 0.07%) for bit in group.match_byte(h2_hash) { 6,080,493 ( 0.15%) let index = (probe_seq.pos + bit) & self.bucket_mask; . 3,750,866 ( 0.09%) if likely(eq(index)) { . return Some(index); . } . } . 845,898 ( 0.02%) if likely(group.match_empty().any_bit_set()) { . return None; . } . . probe_seq.move_next(self.bucket_mask); . } . } . . #[allow(clippy::mut_mut)] . #[inline] . unsafe fn prepare_rehash_in_place(&mut self) { . // Bulk convert all full control bytes to DELETED, and all DELETED . // control bytes to EMPTY. This effectively frees up all buckets . // containing a DELETED entry. 3 ( 0.00%) for i in (0..self.buckets()).step_by(Group::WIDTH) { . let group = Group::load_aligned(self.ctrl(i)); . let group = group.convert_special_to_empty_and_full_to_deleted(); . group.store_aligned(self.ctrl(i)); . } . . // Fix up the trailing control bytes. See the comments in set_ctrl . // for the handling of tables smaller than the group width. 3 ( 0.00%) if self.buckets() < Group::WIDTH { . self.ctrl(0) . .copy_to(self.ctrl(Group::WIDTH), self.buckets()); . } else { . self.ctrl(0) . .copy_to(self.ctrl(self.buckets()), Group::WIDTH); . } . } . -- line 1220 ---------------------------------------- -- line 1225 ---------------------------------------- . Bucket::from_base_index(self.data_end(), index) . } . . #[inline] . unsafe fn bucket_ptr(&self, index: usize, size_of: usize) -> *mut u8 { . debug_assert_ne!(self.bucket_mask, 0); . debug_assert!(index < self.buckets()); . let base: *mut u8 = self.data_end().as_ptr(); 2,894,048 ( 0.07%) base.sub((index + 1) * size_of) . } . . #[inline] . unsafe fn data_end(&self) -> NonNull { . NonNull::new_unchecked(self.ctrl.as_ptr().cast()) . } . . /// Returns an iterator-like object for a probe sequence on the table. . /// . /// This iterator never terminates, but is guaranteed to visit each bucket . /// group exactly once. The loop using `probe_seq` must terminate upon . /// reaching a group containing an empty bucket. . #[inline] . fn probe_seq(&self, hash: u64) -> ProbeSeq { . ProbeSeq { 15,834,473 ( 0.39%) pos: h1(hash) & self.bucket_mask, . stride: 0, . } . } . . /// Returns the index of a bucket for which a value must be inserted if there is enough rooom . /// in the table, otherwise returns error . #[cfg(feature = "raw")] . #[inline] -- line 1257 ---------------------------------------- -- line 1263 ---------------------------------------- . } else { . self.record_item_insert_at(index, old_ctrl, hash); . Ok(index) . } . } . . #[inline] . unsafe fn record_item_insert_at(&mut self, index: usize, old_ctrl: u8, hash: u64) { 1,407,855 ( 0.03%) self.growth_left -= special_is_empty(old_ctrl) as usize; . self.set_ctrl_h2(index, hash); 1,126,284 ( 0.03%) self.items += 1; . } . . #[inline] . fn is_in_same_group(&self, i: usize, new_i: usize, hash: u64) -> bool { . let probe_seq_pos = self.probe_seq(hash).pos; . let probe_index = . |pos: usize| (pos.wrapping_sub(probe_seq_pos) & self.bucket_mask) / Group::WIDTH; . probe_index(i) == probe_index(new_i) -- line 1281 ---------------------------------------- -- line 1312 ---------------------------------------- . // replicate the buckets at the end of the trailing group. For example . // with 2 buckets and a group size of 4, the control bytes will look . // like this: . // . // Real | Replicated . // --------------------------------------------- . // | [A] | [B] | [EMPTY] | [EMPTY] | [A] | [B] | . // --------------------------------------------- 2,159,754 ( 0.05%) let index2 = ((index.wrapping_sub(Group::WIDTH)) & self.bucket_mask) + Group::WIDTH; . 719,918 ( 0.02%) *self.ctrl(index) = ctrl; 720,045 ( 0.02%) *self.ctrl(index2) = ctrl; . } . . /// Returns a pointer to a control byte. . #[inline] . unsafe fn ctrl(&self, index: usize) -> *mut u8 { . debug_assert!(index < self.num_ctrl_bytes()); . self.ctrl.as_ptr().add(index) . } . . #[inline] . fn buckets(&self) -> usize { 267,946 ( 0.01%) self.bucket_mask + 1 . } . . #[inline] . fn num_ctrl_bytes(&self) -> usize { 183,733 ( 0.00%) self.bucket_mask + 1 + Group::WIDTH . } . . #[inline] . fn is_empty_singleton(&self) -> bool { 976,057 ( 0.02%) self.bucket_mask == 0 . } . . #[allow(clippy::mut_mut)] . #[inline] . unsafe fn prepare_resize( . &self, . table_layout: TableLayout, . capacity: usize, . fallibility: Fallibility, . ) -> Result, TryReserveError> { . debug_assert!(self.items <= capacity); . . // Allocate and initialize the new table. 39,303 ( 0.00%) let mut new_table = RawTableInner::fallible_with_capacity( . self.alloc.clone(), . table_layout, . capacity, . fallibility, . )?; 116,314 ( 0.00%) new_table.growth_left -= self.items; . new_table.items = self.items; . . // The hash function may panic, in which case we simply free the new . // table without dropping any elements that may have been copied into . // it. . // . // This guard is also used to free the old table on success, see . // the comment at the bottom of this function. . Ok(guard(new_table, move |self_| { 49,768 ( 0.00%) if !self_.is_empty_singleton() { . self_.free_buckets(table_layout); . } . })) . } . . /// Reserves or rehashes to make room for `additional` more elements. . /// . /// This uses dynamic dispatch to reduce the amount of -- line 1383 ---------------------------------------- -- line 1388 ---------------------------------------- . &mut self, . additional: usize, . hasher: &dyn Fn(&mut Self, usize) -> u64, . fallibility: Fallibility, . layout: TableLayout, . drop: Option, . ) -> Result<(), TryReserveError> { . // Avoid `Option::ok_or_else` because it bloats LLVM IR. 99,538 ( 0.00%) let new_items = match self.items.checked_add(additional) { . Some(new_items) => new_items, . None => return Err(fallibility.capacity_overflow()), . }; 99,538 ( 0.00%) let full_capacity = bucket_mask_to_capacity(self.bucket_mask); 213,123 ( 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); 2 ( 0.00%) Ok(()) . } else { . // Otherwise, conservatively resize to at least the next size up . // to avoid churning deletes into frequent rehashes. . self.resize_inner( 49,768 ( 0.00%) usize::max(new_items, full_capacity + 1), . hasher, . fallibility, . layout, . ) . } . } . . /// Allocates a new table of a different size and moves the contents of the -- line 1418 ---------------------------------------- -- line 1424 ---------------------------------------- . #[inline(always)] . unsafe fn resize_inner( . &mut self, . capacity: usize, . hasher: &dyn Fn(&mut Self, usize) -> u64, . fallibility: Fallibility, . layout: TableLayout, . ) -> Result<(), TryReserveError> { 101,418 ( 0.00%) let mut new_table = self.prepare_resize(layout, capacity, fallibility)?; . . // Copy all elements to the new table. . for i in 0..self.buckets() { 456,786 ( 0.01%) if !is_full(*self.ctrl(i)) { . continue; . } . . // This may panic. . let hash = hasher(self, i); . . // We can use a simpler version of insert() here since: . // - there are no DELETED entries. -- line 1444 ---------------------------------------- -- line 1454 ---------------------------------------- . } . . // We successfully copied all elements without panicking. Now replace . // self with the new table. The old table will have its memory freed but . // the items will not be dropped (since they have been moved into the . // new table). . mem::swap(self, &mut new_table); . 49,768 ( 0.00%) Ok(()) . } . . /// Rehashes the contents of the table in place (i.e. without changing the . /// allocation). . /// . /// If `hasher` panics then some the table's contents may be lost. . /// . /// This uses dynamic dispatch to reduce the amount of -- line 1470 ---------------------------------------- -- line 1496 ---------------------------------------- . } . self_.growth_left = bucket_mask_to_capacity(self_.bucket_mask) - self_.items; . }); . . // At this point, DELETED elements are elements that we haven't . // rehashed yet. Find them and re-insert them at their ideal . // position. . 'outer: for i in 0..guard.buckets() { 64 ( 0.00%) if *guard.ctrl(i) != DELETED { . continue; . } . . let i_p = guard.bucket_ptr(i, size_of); . . 'inner: loop { . // Hash the current item . let hash = hasher(*guard, i); -- line 1512 ---------------------------------------- -- line 1541 ---------------------------------------- . // swapped into the old slot. . debug_assert_eq!(prev_ctrl, DELETED); . ptr::swap_nonoverlapping(i_p, new_i_p, size_of); . continue 'inner; . } . } . } . 3 ( 0.00%) guard.growth_left = bucket_mask_to_capacity(guard.bucket_mask) - guard.items; . . mem::forget(guard); . } . . #[inline] . unsafe fn free_buckets(&mut self, table_layout: TableLayout) { . // Avoid `Option::unwrap_or_else` because it bloats LLVM IR. . let (layout, ctrl_offset) = match table_layout.calculate_layout_for(self.buckets()) { . Some(lco) => lco, . None => hint::unreachable_unchecked(), . }; . self.alloc.deallocate( 31,802 ( 0.00%) NonNull::new_unchecked(self.ctrl.as_ptr().sub(ctrl_offset)), . layout, . ); . } . . /// Marks all table buckets as empty without dropping their contents. . #[inline] . fn clear_no_drop(&mut self) { 5,558 ( 0.00%) if !self.is_empty_singleton() { . unsafe { . self.ctrl(0).write_bytes(EMPTY, self.num_ctrl_bytes()); . } . } 6,834 ( 0.00%) self.items = 0; 5,558 ( 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))); 58,356 ( 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. 233,424 ( 0.01%) let ctrl = if empty_before.leading_zeros() + empty_after.trailing_zeros() >= Group::WIDTH { . DELETED . } else { 275,010 ( 0.01%) self.growth_left += 1; . EMPTY . }; . self.set_ctrl(index, ctrl); 233,424 ( 0.01%) self.items -= 1; . } . } . . impl Clone for RawTable { 71,352 ( 0.00%) fn clone(&self) -> Self { 8,935 ( 0.00%) if self.table.is_empty_singleton() { . Self::new_in(self.table.alloc.clone()) . } else { . unsafe { . let mut new_table = ManuallyDrop::new( . // Avoid `Result::ok_or_else` because it bloats LLVM IR. . match Self::new_uninitialized( . self.table.alloc.clone(), . self.table.buckets(), -- line 1615 ---------------------------------------- -- line 1624 ---------------------------------------- . // We need to free the memory allocated for the new table. . new_table.free_buckets(); . }); . . // Return the newly created table. . ManuallyDrop::into_inner(new_table) . } . } 80,271 ( 0.00%) } . . fn clone_from(&mut self, source: &Self) { . if source.table.is_empty_singleton() { . *self = Self::new_in(self.table.alloc.clone()); . } else { . unsafe { . // First, drop all our elements without clearing the control bytes. . self.drop_elements(); -- line 1640 ---------------------------------------- -- line 1687 ---------------------------------------- . .table . .ctrl(0) . .copy_to_nonoverlapping(self.table.ctrl(0), self.table.num_ctrl_bytes()); . source . .data_start() . .copy_to_nonoverlapping(self.data_start(), self.table.buckets()); . . self.table.items = source.table.items; 38 ( 0.00%) self.table.growth_left = source.table.growth_left; . } . } . . impl RawTable { . /// Common code for clone and clone_from. Assumes `self.buckets() == source.buckets()`. . #[cfg_attr(feature = "inline-more", inline)] . unsafe fn clone_from_impl(&mut self, source: &Self, mut on_panic: impl FnMut(&mut Self)) { . // Copy the control bytes unchanged. We do this in a single pass -- line 1703 ---------------------------------------- -- line 1790 ---------------------------------------- . fn default() -> Self { . Self::new_in(Default::default()) . } . } . . #[cfg(feature = "nightly")] . unsafe impl<#[may_dangle] T, A: Allocator + Clone> Drop for RawTable { . #[cfg_attr(feature = "inline-more", inline)] 487,074 ( 0.01%) fn drop(&mut self) { 393,888 ( 0.01%) if !self.table.is_empty_singleton() { . unsafe { . self.drop_elements(); . self.free_buckets(); . } . } 511,440 ( 0.01%) } . } . #[cfg(not(feature = "nightly"))] . impl Drop for RawTable { . #[cfg_attr(feature = "inline-more", inline)] . fn drop(&mut self) { . if !self.table.is_empty_singleton() { . unsafe { . self.drop_elements(); -- line 1813 ---------------------------------------- -- line 1817 ---------------------------------------- . } . } . . impl IntoIterator for RawTable { . type Item = T; . type IntoIter = RawIntoIter; . . #[cfg_attr(feature = "inline-more", inline)] 54,192 ( 0.00%) fn into_iter(self) -> RawIntoIter { . unsafe { . let iter = self.iter(); . self.into_iter_from(iter) . } 67,740 ( 0.00%) } . } . . /// Iterator over a sub-range of a table. Unlike `RawIter` this iterator does . /// not track an item count. . pub(crate) struct RawIterRange { . // Mask of full buckets in the current group. Bits are cleared from this . // mask as each element is processed. . current_group: BitMask, -- line 1838 ---------------------------------------- -- line 1934 ---------------------------------------- . . impl Iterator for RawIterRange { . type Item = Bucket; . . #[cfg_attr(feature = "inline-more", inline)] . fn next(&mut self) -> Option> { . unsafe { . loop { 235,781 ( 0.01%) if let Some(index) = self.current_group.lowest_set_bit() { 40,288 ( 0.00%) self.current_group = self.current_group.remove_lowest_bit(); 74,565 ( 0.00%) return Some(self.data.next_n(index)); . } . 185,334 ( 0.00%) if self.next_ctrl >= self.end { . return None; . } . . // We might read past self.end up to the next group boundary, . // but this is fine because it only occurs on tables smaller . // than the group size where the trailing control bytes are all . // EMPTY. On larger tables self.end is guaranteed to be aligned . // to the group size (since tables are power-of-two sized). 14,522 ( 0.00%) self.current_group = Group::load_aligned(self.next_ctrl).match_full(); 6,080 ( 0.00%) self.data = self.data.next_n(Group::WIDTH); 22,475 ( 0.00%) self.next_ctrl = self.next_ctrl.add(Group::WIDTH); . } . } . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { . // We don't have an item count, so just guess based on the range size. . ( -- line 1966 ---------------------------------------- -- line 2102 ---------------------------------------- . } . } else { . // We must have already iterated past the removed item. . } . } . } . . unsafe fn drop_elements(&mut self) { 38,651 ( 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)] 37,716 ( 0.00%) fn next(&mut self) -> Option> { 122,126 ( 0.00%) if let Some(b) = self.iter.next() { 352,520 ( 0.01%) self.items -= 1; . Some(b) . } else { . // We don't check against items == 0 here to allow the . // compiler to optimize away the item count entirely if the . // iterator length is never queried. . debug_assert_eq!(self.items, 0); . None . } 75,432 ( 0.00%) } . . #[inline] . fn size_hint(&self) -> (usize, Option) { . (self.items, Some(self.items)) . } . } . . impl ExactSizeIterator for RawIter {} -- line 2151 ---------------------------------------- -- line 2177 ---------------------------------------- . T: Sync, . A: Sync, . { . } . . #[cfg(feature = "nightly")] . unsafe impl<#[may_dangle] T, A: Allocator + Clone> Drop for RawIntoIter { . #[cfg_attr(feature = "inline-more", inline)] 65,522 ( 0.00%) fn drop(&mut self) { . unsafe { . // Drop all remaining elements . self.iter.drop_elements(); . . // Free the table 63,159 ( 0.00%) if let Some((ptr, layout)) = self.allocation { . self.alloc.deallocate(ptr, layout); . } . } 19,528 ( 0.00%) } . } . #[cfg(not(feature = "nightly"))] . impl Drop for RawIntoIter { . #[cfg_attr(feature = "inline-more", inline)] . fn drop(&mut self) { . unsafe { . // Drop all remaining elements . self.iter.drop_elements(); -- line 2203 ---------------------------------------- -- line 2209 ---------------------------------------- . } . } . } . . impl Iterator for RawIntoIter { . type Item = T; . . #[cfg_attr(feature = "inline-more", inline)] 213 ( 0.00%) fn next(&mut self) -> Option { 3 ( 0.00%) unsafe { Some(self.iter.next()?.read()) } 426 ( 0.00%) } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 2 ( 0.00%) self.iter.size_hint() . } . } . . impl ExactSizeIterator for RawIntoIter {} . impl FusedIterator for RawIntoIter {} . . /// Iterator which consumes elements without freeing the table storage. . pub struct RawDrain<'a, T, A: Allocator + Clone = Global> { -- line 2231 ---------------------------------------- -- line 2259 ---------------------------------------- . where . T: Sync, . A: Sync, . { . } . . impl Drop for RawDrain<'_, T, A> { . #[cfg_attr(feature = "inline-more", inline)] 7,432 ( 0.00%) fn drop(&mut self) { . unsafe { . // Drop all remaining elements. Note that this may panic. . self.iter.drop_elements(); . . // Reset the contents of the table now that all elements have been . // dropped. . self.table.clear_no_drop(); . . // Move the now empty table back to its original location. 929 ( 0.00%) self.orig_table . .as_ptr() . .copy_from_nonoverlapping(&*self.table, 1); . } 7,432 ( 0.00%) } . } . . impl Iterator for RawDrain<'_, T, A> { . type Item = T; . . #[cfg_attr(feature = "inline-more", inline)] . fn next(&mut self) -> Option { . unsafe { -- line 2289 ---------------------------------------- 9,309,287 ( 0.23%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/alloc.rs -------------------------------------------------------------------------------- Ir -- line 79 ---------------------------------------- . /// . /// dealloc(ptr, layout); . /// } . /// ``` . #[stable(feature = "global_alloc", since = "1.28.0")] . #[must_use = "losing the pointer will leak memory"] . #[inline] . pub unsafe fn alloc(layout: Layout) -> *mut u8 { 10,288,928 ( 0.26%) unsafe { __rust_alloc(layout.size(), layout.align()) } . } . . /// Deallocate memory with the global allocator. . /// . /// This function forwards calls to the [`GlobalAlloc::dealloc`] method . /// of the allocator registered with the `#[global_allocator]` attribute . /// if there is one, or the `std` crate’s default. . /// -- line 95 ---------------------------------------- -- line 97 ---------------------------------------- . /// of the [`Global`] type when it and the [`Allocator`] trait become stable. . /// . /// # Safety . /// . /// See [`GlobalAlloc::dealloc`]. . #[stable(feature = "global_alloc", since = "1.28.0")] . #[inline] . pub unsafe fn dealloc(ptr: *mut u8, layout: Layout) { 10,272,841 ( 0.25%) unsafe { __rust_dealloc(ptr, layout.size(), layout.align()) } . } . . /// Reallocate memory with the global allocator. . /// . /// This function forwards calls to the [`GlobalAlloc::realloc`] method . /// of the allocator registered with the `#[global_allocator]` attribute . /// if there is one, or the `std` crate’s default. . /// -- line 113 ---------------------------------------- -- line 116 ---------------------------------------- . /// . /// # Safety . /// . /// See [`GlobalAlloc::realloc`]. . #[stable(feature = "global_alloc", since = "1.28.0")] . #[must_use = "losing the pointer will leak memory"] . #[inline] . pub unsafe fn realloc(ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { 371,962 ( 0.01%) unsafe { __rust_realloc(ptr, layout.size(), layout.align(), new_size) } . } . . /// Allocate zero-initialized memory with the global allocator. . /// . /// This function forwards calls to the [`GlobalAlloc::alloc_zeroed`] method . /// of the allocator registered with the `#[global_allocator]` attribute . /// if there is one, or the `std` crate’s default. . /// -- line 132 ---------------------------------------- -- line 150 ---------------------------------------- . /// . /// dealloc(ptr, layout); . /// } . /// ``` . #[stable(feature = "global_alloc", since = "1.28.0")] . #[must_use = "losing the pointer will leak memory"] . #[inline] . pub unsafe fn alloc_zeroed(layout: Layout) -> *mut u8 { 33,948 ( 0.00%) unsafe { __rust_alloc_zeroed(layout.size(), layout.align()) } . } . . #[cfg(not(test))] . impl Global { . #[inline] . fn alloc_impl(&self, layout: Layout, zeroed: bool) -> Result, AllocError> { 1,096,373 ( 0.03%) match layout.size() { . 0 => Ok(NonNull::slice_from_raw_parts(layout.dangling(), 0)), . // SAFETY: `layout` is non-zero in size, . size => unsafe { . let raw_ptr = if zeroed { alloc_zeroed(layout) } else { alloc(layout) }; 6,162,982 ( 0.15%) let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?; . Ok(NonNull::slice_from_raw_parts(ptr, size)) . }, . } . } . . // SAFETY: Same as `Allocator::grow` . #[inline] . unsafe fn grow_impl( -- line 178 ---------------------------------------- -- line 182 ---------------------------------------- . new_layout: Layout, . zeroed: bool, . ) -> Result, AllocError> { . debug_assert!( . new_layout.size() >= old_layout.size(), . "`new_layout.size()` must be greater than or equal to `old_layout.size()`" . ); . 132,250 ( 0.00%) match old_layout.size() { . 0 => self.alloc_impl(new_layout, zeroed), . . // SAFETY: `new_size` is non-zero as `old_size` is greater than or equal to `new_size` . // as required by safety conditions. Other conditions must be upheld by the caller . old_size if old_layout.align() == new_layout.align() => unsafe { . let new_size = new_layout.size(); . . // `realloc` probably checks for `new_size >= old_layout.size()` or something similar. -- line 198 ---------------------------------------- -- line 231 ---------------------------------------- . . #[inline] . fn allocate_zeroed(&self, layout: Layout) -> Result, AllocError> { . self.alloc_impl(layout, true) . } . . #[inline] . unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { 1,496,798 ( 0.04%) if layout.size() != 0 { . // SAFETY: `layout` is non-zero in size, . // other conditions must be upheld by the caller . unsafe { dealloc(ptr.as_ptr(), layout) } . } . } . . #[inline] . unsafe fn grow( -- line 247 ---------------------------------------- -- line 272 ---------------------------------------- . old_layout: Layout, . new_layout: Layout, . ) -> Result, AllocError> { . debug_assert!( . new_layout.size() <= old_layout.size(), . "`new_layout.size()` must be smaller than or equal to `old_layout.size()`" . ); . 4,204 ( 0.00%) match new_layout.size() { . // SAFETY: conditions must be upheld by the caller . 0 => unsafe { . self.deallocate(ptr, old_layout); . Ok(NonNull::slice_from_raw_parts(new_layout.dangling(), 0)) . }, . . // SAFETY: `new_size` is non-zero. Other conditions must be upheld by the caller . new_size if old_layout.align() == new_layout.align() => unsafe { . // `realloc` probably checks for `new_size <= old_layout.size()` or something similar. . intrinsics::assume(new_size <= old_layout.size()); . . let raw_ptr = realloc(ptr.as_ptr(), old_layout, new_size); 4,204 ( 0.00%) let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?; . Ok(NonNull::slice_from_raw_parts(ptr, new_size)) . }, . . // SAFETY: because `new_size` must be smaller than or equal to `old_layout.size()`, . // both the old and new memory allocation are valid for reads and writes for `new_size` . // bytes. Also, because the old allocation wasn't yet deallocated, it cannot overlap . // `new_ptr`. Thus, the call to `copy_nonoverlapping` is safe. The safety contract . // for `dealloc` must be upheld by the caller. -- line 301 ---------------------------------------- -- line 308 ---------------------------------------- . } . } . } . . /// The allocator for unique pointers. . #[cfg(all(not(no_global_oom_handling), not(test)))] . #[lang = "exchange_malloc"] . #[inline] 2,489 ( 0.00%) unsafe fn exchange_malloc(size: usize, align: usize) -> *mut u8 { . let layout = unsafe { Layout::from_size_align_unchecked(size, align) }; 15,304 ( 0.00%) match Global.allocate(layout) { . Ok(ptr) => ptr.as_mut_ptr(), . Err(_) => handle_alloc_error(layout), . } 4,666 ( 0.00%) } . . #[cfg_attr(not(test), lang = "box_free")] . #[inline] . #[rustc_const_unstable(feature = "const_box", issue = "92521")] . // This signature has to be the same as `Box`, otherwise an ICE will happen. . // When an additional parameter to `Box` is added (like `A: Allocator`), this has to be added here as . // well. . // For example if `Box` is changed to `struct Box(Unique, A)`, . // this function has to be changed to `fn box_free(Unique, A)` as well. . pub(crate) const unsafe fn box_free( . ptr: Unique, . alloc: A, . ) { . unsafe { 16,743 ( 0.00%) let size = size_of_val(ptr.as_ref()); 8,517 ( 0.00%) let align = min_align_of_val(ptr.as_ref()); . let layout = Layout::from_size_align_unchecked(size, align); . alloc.deallocate(From::from(ptr.cast()), layout) . } . } . . // # Allocation error handler . . #[cfg(not(no_global_oom_handling))] -- line 346 ---------------------------------------- -- line 417 ---------------------------------------- . /// Specialize clones into pre-allocated, uninitialized memory. . /// Used by `Box::clone` and `Rc`/`Arc::make_mut`. . pub(crate) trait WriteCloneIntoRaw: Sized { . unsafe fn write_clone_into_raw(&self, target: *mut Self); . } . . impl WriteCloneIntoRaw for T { . #[inline] 1,332 ( 0.00%) default unsafe fn write_clone_into_raw(&self, target: *mut Self) { . // Having allocated *first* may allow the optimizer to create . // the cloned value in-place, skipping the local and move. 17,671 ( 0.00%) unsafe { target.write(self.clone()) }; 1,184 ( 0.00%) } . } . . impl WriteCloneIntoRaw for T { . #[inline] . unsafe fn write_clone_into_raw(&self, target: *mut Self) { . // We can always copy in-place, without ever involving a local value. . unsafe { target.copy_from_nonoverlapping(self, 1) }; . } -- line 437 ---------------------------------------- 7,131,724 ( 0.18%) -------------------------------------------------------------------------------- -- 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); . 34,813 ( 0.00%) if count == 8 { . ptr::copy_nonoverlapping(src, dst, 8); . return; . } . . let mut i = 0; 37,522 ( 0.00%) if i + 3 < count { . ptr::copy_nonoverlapping(src.add(i), dst.add(i), 4); . i += 4; . } . 82,966 ( 0.00%) if i + 1 < count { . ptr::copy_nonoverlapping(src.add(i), dst.add(i), 2); 8,755 ( 0.00%) i += 2 . } . 37,522 ( 0.00%) if i < count { 23,602 ( 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::(); 481,576 ( 0.01%) let nbuf = self.nbuf; . debug_assert!(size <= 8); . debug_assert!(nbuf < BUFFER_SIZE); . debug_assert!(nbuf + size < BUFFER_WITH_SPILL_SIZE); . 3,278,655 ( 0.08%) 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); . } . 1,068,588 ( 0.03%) self.nbuf = nbuf + size; . . return; . } . 174,335 ( 0.00%) 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)] 49,956 ( 0.00%) unsafe fn short_write_process_buffer(&mut self, x: T) { . let size = mem::size_of::(); 49,956 ( 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 { 499,560 ( 0.01%) let elem = self.buf.get_unchecked(i).assume_init().to_le(); 399,648 ( 0.01%) self.state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut self.state); 449,604 ( 0.01%) 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. 233,796 ( 0.01%) self.nbuf = if size == 1 { 0 } else { nbuf + size - BUFFER_SIZE }; 199,824 ( 0.00%) self.processed += BUFFER_SIZE; 99,912 ( 0.00%) } . . // A write function for byte slices. . #[inline] . fn slice_write(&mut self, msg: &[u8]) { . let length = msg.len(); 9,242 ( 0.00%) let nbuf = self.nbuf; . debug_assert!(nbuf < BUFFER_SIZE); . 142,704 ( 0.00%) if nbuf + length < BUFFER_SIZE { . unsafe { . let dst = (self.buf.as_mut_ptr() as *mut u8).add(nbuf); . 51,286 ( 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); . } . } . 25,888 ( 0.00%) self.nbuf = nbuf + length; . . return; . } . 21,971 ( 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)] 13,495 ( 0.00%) unsafe fn slice_write_process_buffer(&mut self, msg: &[u8]) { . let length = msg.len(); 2,699 ( 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. 8,097 ( 0.00%) let valid_in_elem = nbuf % ELEM_SIZE; 2,699 ( 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. 5,398 ( 0.00%) let last = nbuf / ELEM_SIZE + 1; . . for i in 0..last { 21,229 ( 0.00%) let elem = self.buf.get_unchecked(i).assume_init().to_le(); 23,928 ( 0.00%) self.state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut self.state); 42,458 ( 0.00%) self.state.v0 ^= elem; . } . . // Process the remaining element-sized chunks of input. . let mut processed = needed_in_elem; 5,398 ( 0.00%) let input_left = length - processed; 2,106 ( 0.00%) let elems_left = input_left / ELEM_SIZE; . let extra_bytes_left = input_left % ELEM_SIZE; . . for _ in 0..elems_left { 798 ( 0.00%) let elem = (msg.as_ptr().add(processed) as *const u64).read_unaligned().to_le(); 798 ( 0.00%) self.state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut self.state); 798 ( 0.00%) self.state.v0 ^= elem; 1,596 ( 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); . 2,699 ( 0.00%) self.nbuf = extra_bytes_left; 13,495 ( 0.00%) self.processed += nbuf + processed; 16,194 ( 0.00%) } . . #[inline] . pub fn finish128(mut self) -> (u64, u64) { . debug_assert!(self.nbuf < BUFFER_SIZE); . . // Process full elements in buffer. 22,185 ( 0.00%) let last = self.nbuf / ELEM_SIZE; . . // Since we're consuming self, avoid updating members for a potential . // performance gain. 29,580 ( 0.00%) let mut state = self.state; . . for i in 0..last { 22,519 ( 0.00%) let elem = unsafe { self.buf.get_unchecked(i).assume_init().to_le() }; 22,519 ( 0.00%) state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut state); 22,519 ( 0.00%) state.v0 ^= elem; . } . . // Get remaining partial element. 14,790 ( 0.00%) let elem = if self.nbuf % ELEM_SIZE != 0 { . unsafe { . // Ensure element is initialized by writing zero bytes. At most . // `ELEM_SIZE - 1` are required given the above check. It's safe . // to write this many because we have the spill and we maintain . // `self.nbuf` such that this write will start before the spill. . let dst = (self.buf.as_mut_ptr() as *mut u8).add(self.nbuf); . ptr::write_bytes(dst, 0, ELEM_SIZE - 1); 6,583 ( 0.00%) self.buf.get_unchecked(last).assume_init().to_le() . } . } else { . 0 . }; . . // Finalize the hash. 21,373 ( 0.00%) let length = self.processed + self.nbuf; 14,788 ( 0.00%) let b: u64 = ((length as u64 & 0xff) << 56) | elem; . 7,394 ( 0.00%) state.v3 ^= b; . Sip24Rounds::c_rounds(&mut state); 7,394 ( 0.00%) state.v0 ^= b; . 7,394 ( 0.00%) state.v2 ^= 0xee; . Sip24Rounds::d_rounds(&mut state); 24,232 ( 0.00%) let _0 = state.v0 ^ state.v1 ^ state.v2 ^ state.v3; . 9,442 ( 0.00%) state.v1 ^= 0xdd; . Sip24Rounds::d_rounds(&mut state); 9,442 ( 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) { 1,864,405 ( 0.05%) compress!(state); 2,019,907 ( 0.05%) compress!(state); . } . . #[inline] . fn d_rounds(state: &mut State) { 48,460 ( 0.00%) compress!(state); 48,460 ( 0.00%) compress!(state); 48,460 ( 0.00%) compress!(state); 41,067 ( 0.00%) compress!(state); . } . } 390,064 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/index.rs -------------------------------------------------------------------------------- Ir -- line 154 ---------------------------------------- . . #[stable(feature = "slice_get_slice_impls", since = "1.15.0")] . unsafe impl SliceIndex<[T]> for usize { . type Output = T; . . #[inline] . fn get(self, slice: &[T]) -> Option<&T> { . // SAFETY: `self` is checked to be in bounds. 952,149 ( 0.02%) if self < slice.len() { unsafe { Some(&*self.get_unchecked(slice)) } } else { None } . } . . #[inline] . fn get_mut(self, slice: &mut [T]) -> Option<&mut T> { . // SAFETY: `self` is checked to be in bounds. 205,983 ( 0.01%) if self < slice.len() { unsafe { Some(&mut *self.get_unchecked_mut(slice)) } } else { None } . } . . #[inline] . unsafe fn get_unchecked(self, slice: *const [T]) -> *const T { . // SAFETY: the caller guarantees that `slice` is not dangling, so it . // cannot be longer than `isize::MAX`. They also guarantee that . // `self` is in bounds of `slice` so `self` cannot overflow an `isize`, . // so the call to `add` is safe. -- line 176 ---------------------------------------- -- line 181 ---------------------------------------- . unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut T { . // SAFETY: see comments for `get_unchecked` above. . unsafe { slice.as_mut_ptr().add(self) } . } . . #[inline] . fn index(self, slice: &[T]) -> &T { . // N.B., use intrinsic indexing 13,951,102 ( 0.35%) &(*slice)[self] . } . . #[inline] . fn index_mut(self, slice: &mut [T]) -> &mut T { . // N.B., use intrinsic indexing 2,647,859 ( 0.07%) &mut (*slice)[self] . } . } . . #[stable(feature = "slice_get_slice_impls", since = "1.15.0")] . unsafe impl SliceIndex<[T]> for ops::Range { . type Output = [T]; . . #[inline] . fn get(self, slice: &[T]) -> Option<&[T]> { 69,855 ( 0.00%) if self.start > self.end || self.end > slice.len() { . None . } else { . // SAFETY: `self` is checked to be valid and in bounds above. . unsafe { Some(&*self.get_unchecked(slice)) } . } . } . . #[inline] -- line 213 ---------------------------------------- -- line 221 ---------------------------------------- . } . . #[inline] . unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T] { . // SAFETY: the caller guarantees that `slice` is not dangling, so it . // cannot be longer than `isize::MAX`. They also guarantee that . // `self` is in bounds of `slice` so `self` cannot overflow an `isize`, . // so the call to `add` is safe. 690,900 ( 0.02%) unsafe { ptr::slice_from_raw_parts(slice.as_ptr().add(self.start), self.end - self.start) } . } . . #[inline] . unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T] { . // SAFETY: see comments for `get_unchecked` above. . unsafe { 10,990 ( 0.00%) ptr::slice_from_raw_parts_mut(slice.as_mut_ptr().add(self.start), self.end - self.start) . } . } . . #[inline] . fn index(self, slice: &[T]) -> &[T] { 22,167 ( 0.00%) if self.start > self.end { . slice_index_order_fail(self.start, self.end); 251,692 ( 0.01%) } else if self.end > slice.len() { . slice_end_index_len_fail(self.end, slice.len()); . } . // SAFETY: `self` is checked to be valid and in bounds above. . unsafe { &*self.get_unchecked(slice) } . } . . #[inline] . fn index_mut(self, slice: &mut [T]) -> &mut [T] { 6,456 ( 0.00%) if self.start > self.end { . slice_index_order_fail(self.start, self.end); 9,224 ( 0.00%) } else if self.end > slice.len() { . slice_end_index_len_fail(self.end, slice.len()); . } . // SAFETY: `self` is checked to be valid and in bounds above. . unsafe { &mut *self.get_unchecked_mut(slice) } . } . } . . #[stable(feature = "slice_get_slice_impls", since = "1.15.0")] -- line 263 ---------------------------------------- -- line 320 ---------------------------------------- . #[inline] . unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T] { . // SAFETY: the caller has to uphold the safety contract for `get_unchecked_mut`. . unsafe { (self.start..slice.len()).get_unchecked_mut(slice) } . } . . #[inline] . fn index(self, slice: &[T]) -> &[T] { 198,546 ( 0.00%) if self.start > slice.len() { . slice_start_index_len_fail(self.start, slice.len()); . } . // SAFETY: `self` is checked to be valid and in bounds above. . unsafe { &*self.get_unchecked(slice) } . } . . #[inline] . fn index_mut(self, slice: &mut [T]) -> &mut [T] { 17,745 ( 0.00%) if self.start > slice.len() { . slice_start_index_len_fail(self.start, slice.len()); . } . // SAFETY: `self` is checked to be valid and in bounds above. . unsafe { &mut *self.get_unchecked_mut(slice) } . } . } . . #[stable(feature = "slice_get_slice_impls", since = "1.15.0")] -- line 345 ---------------------------------------- -- line 539 ---------------------------------------- . let end = match end { . ops::Bound::Included(end) => { . end.checked_add(1).unwrap_or_else(|| slice_end_index_overflow_fail()) . } . ops::Bound::Excluded(&end) => end, . ops::Bound::Unbounded => len, . }; . 9,294 ( 0.00%) if start > end { . slice_index_order_fail(start, end); . } 75 ( 0.00%) if end > len { . slice_end_index_len_fail(end, len); . } . . ops::Range { start, end } . } . . /// Convert pair of `ops::Bound`s into `ops::Range` without performing any bounds checking and (in debug) overflow checking . fn into_range_unchecked( -- line 558 ---------------------------------------- 1,573,492 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/ast_like.rs -------------------------------------------------------------------------------- Ir -- line 24 ---------------------------------------- . fn attrs(&self) -> &[Attribute]; . fn visit_attrs(&mut self, f: impl FnOnce(&mut Vec)); . fn tokens_mut(&mut self) -> Option<&mut Option>; . } . . impl AstLike for P { . const SUPPORTS_CUSTOM_INNER_ATTRS: bool = T::SUPPORTS_CUSTOM_INNER_ATTRS; . fn attrs(&self) -> &[Attribute] { 14,949 ( 0.00%) (**self).attrs() . } . fn visit_attrs(&mut self, f: impl FnOnce(&mut Vec)) { . (**self).visit_attrs(f); . } . fn tokens_mut(&mut self) -> Option<&mut Option> { 330 ( 0.00%) (**self).tokens_mut() . } . } . . impl AstLike for crate::token::Nonterminal { . const SUPPORTS_CUSTOM_INNER_ATTRS: bool = true; . fn attrs(&self) -> &[Attribute] { . match self { . Nonterminal::NtItem(item) => item.attrs(), -- line 46 ---------------------------------------- -- line 69 ---------------------------------------- . | Nonterminal::NtVis(_) . | Nonterminal::NtTT(_) . | Nonterminal::NtBlock(_) . | Nonterminal::NtIdent(..) . | Nonterminal::NtLifetime(_) => {} . } . } . fn tokens_mut(&mut self) -> Option<&mut Option> { 3,926,892 ( 0.10%) match self { . Nonterminal::NtItem(item) => item.tokens_mut(), . Nonterminal::NtStmt(stmt) => stmt.tokens_mut(), . Nonterminal::NtExpr(expr) | Nonterminal::NtLiteral(expr) => expr.tokens_mut(), . Nonterminal::NtPat(pat) => pat.tokens_mut(), . Nonterminal::NtTy(ty) => ty.tokens_mut(), . Nonterminal::NtMeta(attr_item) => attr_item.tokens_mut(), . Nonterminal::NtPath(path) => path.tokens_mut(), . Nonterminal::NtVis(vis) => vis.tokens_mut(), . Nonterminal::NtBlock(block) => block.tokens_mut(), . Nonterminal::NtIdent(..) | Nonterminal::NtLifetime(..) | Nonterminal::NtTT(..) => None, . } 654,536 ( 0.02%) } . } . . fn visit_attrvec(attrs: &mut AttrVec, f: impl FnOnce(&mut Vec)) { 107,271 ( 0.00%) crate::mut_visit::visit_clobber(attrs, |attrs| { . let mut vec = attrs.into(); . f(&mut vec); 35,757 ( 0.00%) vec.into() . }); . } . . impl AstLike for StmtKind { . // This might be an `StmtKind::Item`, which contains . // an item that supports inner attrs . const SUPPORTS_CUSTOM_INNER_ATTRS: bool = true; . . fn attrs(&self) -> &[Attribute] { 9,807 ( 0.00%) match self { . StmtKind::Local(local) => local.attrs(), . StmtKind::Expr(expr) | StmtKind::Semi(expr) => expr.attrs(), . StmtKind::Item(item) => item.attrs(), . StmtKind::Empty => &[], . StmtKind::MacCall(mac) => &mac.attrs, . } 80 ( 0.00%) } . . fn visit_attrs(&mut self, f: impl FnOnce(&mut Vec)) { 1,625 ( 0.00%) match self { . StmtKind::Local(local) => local.visit_attrs(f), . StmtKind::Expr(expr) | StmtKind::Semi(expr) => expr.visit_attrs(f), . StmtKind::Item(item) => item.visit_attrs(f), . StmtKind::Empty => {} 149 ( 0.00%) StmtKind::MacCall(mac) => visit_attrvec(&mut mac.attrs, f), . } . } . fn tokens_mut(&mut self) -> Option<&mut Option> { 2,112 ( 0.00%) Some(match self { 80 ( 0.00%) StmtKind::Local(local) => &mut local.tokens, . StmtKind::Item(item) => &mut item.tokens, 123 ( 0.00%) StmtKind::Expr(expr) | StmtKind::Semi(expr) => &mut expr.tokens, . StmtKind::Empty => return None, 149 ( 0.00%) StmtKind::MacCall(mac) => &mut mac.tokens, . }) . } . } . . impl AstLike for Stmt { . const SUPPORTS_CUSTOM_INNER_ATTRS: bool = StmtKind::SUPPORTS_CUSTOM_INNER_ATTRS; . . fn attrs(&self) -> &[Attribute] { . self.kind.attrs() 1,321 ( 0.00%) } . . fn visit_attrs(&mut self, f: impl FnOnce(&mut Vec)) { . self.kind.visit_attrs(f); . } . fn tokens_mut(&mut self) -> Option<&mut Option> { . self.kind.tokens_mut() 352 ( 0.00%) } . } . . impl AstLike for Attribute { . const SUPPORTS_CUSTOM_INNER_ATTRS: bool = false; . . fn attrs(&self) -> &[Attribute] { . &[] 2,670 ( 0.00%) } . fn visit_attrs(&mut self, _f: impl FnOnce(&mut Vec)) {} 42 ( 0.00%) fn tokens_mut(&mut self) -> Option<&mut Option> { 84 ( 0.00%) Some(match &mut self.kind { 42 ( 0.00%) AttrKind::Normal(_, tokens) => tokens, . kind @ AttrKind::DocComment(..) => { . panic!("Called tokens_mut on doc comment attr {:?}", kind) . } . }) 126 ( 0.00%) } . } . . impl AstLike for Option { . const SUPPORTS_CUSTOM_INNER_ATTRS: bool = T::SUPPORTS_CUSTOM_INNER_ATTRS; . . fn attrs(&self) -> &[Attribute] { 313 ( 0.00%) self.as_ref().map(|inner| inner.attrs()).unwrap_or(&[]) . } . fn visit_attrs(&mut self, f: impl FnOnce(&mut Vec)) { . if let Some(inner) = self.as_mut() { . inner.visit_attrs(f); . } . } . fn tokens_mut(&mut self) -> Option<&mut Option> { 311 ( 0.00%) self.as_mut().and_then(|inner| inner.tokens_mut()) . } . } . . /// Helper trait for the macros below. Abstracts over . /// the two types of attribute fields that AST nodes . /// may have (`Vec` or `AttrVec`) . trait VecOrAttrVec { . fn visit(&mut self, f: impl FnOnce(&mut Vec)); . } . . impl VecOrAttrVec for Vec { 2,632 ( 0.00%) fn visit(&mut self, f: impl FnOnce(&mut Vec)) { 658 ( 0.00%) f(self) 2,632 ( 0.00%) } . } . . impl VecOrAttrVec for AttrVec { . fn visit(&mut self, f: impl FnOnce(&mut Vec)) { . visit_attrvec(self, f) . } . } . -- line 201 ---------------------------------------- -- line 204 ---------------------------------------- . const SUPPORTS_CUSTOM_INNER_ATTRS: bool = $inner_attrs:literal; . $($ty:path),* . ) => { $( . impl AstLike for $ty { . const SUPPORTS_CUSTOM_INNER_ATTRS: bool = $inner_attrs; . . fn attrs(&self) -> &[Attribute] { . &self.attrs 11,878 ( 0.00%) } . . fn visit_attrs(&mut self, f: impl FnOnce(&mut Vec)) { 3,119 ( 0.00%) VecOrAttrVec::visit(&mut self.attrs, f) . } . . fn tokens_mut(&mut self) -> Option<&mut Option> { 533 ( 0.00%) Some(&mut self.tokens) 533 ( 0.00%) } . . } . )* } . } . . macro_rules! derive_has_attrs_no_tokens { . ($($ty:path),*) => { $( . impl AstLike for $ty { . const SUPPORTS_CUSTOM_INNER_ATTRS: bool = false; . . fn attrs(&self) -> &[Attribute] { . &self.attrs 691 ( 0.00%) } . . fn visit_attrs(&mut self, f: impl FnOnce(&mut Vec)) { 10 ( 0.00%) VecOrAttrVec::visit(&mut self.attrs, f) . } . . fn tokens_mut(&mut self) -> Option<&mut Option> { . None . } . } . )* } . } -- line 244 ---------------------------------------- -- line 245 ---------------------------------------- . . macro_rules! derive_has_tokens_no_attrs { . ($($ty:path),*) => { $( . impl AstLike for $ty { . const SUPPORTS_CUSTOM_INNER_ATTRS: bool = false; . . fn attrs(&self) -> &[Attribute] { . &[] 2,922 ( 0.00%) } . . fn visit_attrs(&mut self, _f: impl FnOnce(&mut Vec)) {} . fn tokens_mut(&mut self) -> Option<&mut Option> { 315 ( 0.00%) Some(&mut self.tokens) 210 ( 0.00%) } . } . )* } . } . . // These ast nodes support both active and inert attributes, . // so they have tokens collected to pass to proc macros . derive_has_tokens_and_attrs! { . // Both `Item` and `AssocItem` can have bodies, which -- line 266 ---------------------------------------- 31,409 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs -------------------------------------------------------------------------------- Ir -- line 294 ---------------------------------------- . #[allow(deprecated)] . impl From for CollectionAllocErr { . fn from(_: LayoutErr) -> Self { . CollectionAllocErr::CapacityOverflow . } . } . . fn infallible(result: Result) -> T { 2,972,417 ( 0.07%) match result { . Ok(x) => x, . Err(CollectionAllocErr::CapacityOverflow) => panic!("capacity overflow"), . Err(CollectionAllocErr::AllocErr { layout }) => alloc::alloc::handle_alloc_error(layout), . } . } . . /// FIXME: use `Layout::array` when we require a Rust version where it’s stable . /// https://github.com/rust-lang/rust/issues/55724 -- line 310 ---------------------------------------- -- line 422 ---------------------------------------- . #[cfg(feature = "union")] . impl SmallVecData { . #[inline] . unsafe fn inline(&self) -> *const A::Item { . self.inline.as_ptr() as *const A::Item . } . #[inline] . unsafe fn inline_mut(&mut self) -> *mut A::Item { 27,784 ( 0.00%) self.inline.as_mut_ptr() as *mut A::Item . } . #[inline] . fn from_inline(inline: MaybeUninit) -> SmallVecData { . SmallVecData { . inline: core::mem::ManuallyDrop::new(inline), . } . } . #[inline] . unsafe fn into_inline(self) -> MaybeUninit { . core::mem::ManuallyDrop::into_inner(self.inline) . } . #[inline] . unsafe fn heap(&self) -> (*mut A::Item, usize) { 290,121 ( 0.01%) self.heap . } . #[inline] . unsafe fn heap_mut(&mut self) -> &mut (*mut A::Item, usize) { . &mut self.heap . } . #[inline] . fn from_heap(ptr: *mut A::Item, len: usize) -> SmallVecData { . SmallVecData { heap: (ptr, len) } -- line 452 ---------------------------------------- -- line 557 ---------------------------------------- . #[inline] . pub fn new() -> SmallVec { . // Try to detect invalid custom implementations of `Array`. Hopefully, . // this check should be optimized away entirely for valid ones. . assert!( . mem::size_of::() == A::size() * mem::size_of::() . && mem::align_of::() >= mem::align_of::() . ); 4,320,362 ( 0.11%) SmallVec { . capacity: 0, . data: SmallVecData::from_inline(MaybeUninit::uninit()), . } . } . . /// Construct an empty vector with enough capacity pre-allocated to store at least `n` . /// elements. . /// -- line 573 ---------------------------------------- -- line 579 ---------------------------------------- . /// let v: SmallVec<[u8; 3]> = SmallVec::with_capacity(100); . /// . /// assert!(v.is_empty()); . /// assert!(v.capacity() >= 100); . /// ``` . #[inline] . pub fn with_capacity(n: usize) -> Self { . let mut v = SmallVec::new(); 4 ( 0.00%) v.reserve_exact(n); . v . } . . /// Construct a new `SmallVec` from a `Vec`. . /// . /// Elements will be copied to the inline buffer if vec.capacity() <= Self::inline_capacity(). . /// . /// ```rust -- line 595 ---------------------------------------- -- line 635 ---------------------------------------- . /// let small_vec: SmallVec<_> = SmallVec::from_buf(buf); . /// . /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]); . /// ``` . #[inline] . pub fn from_buf(buf: A) -> SmallVec { . SmallVec { . capacity: A::size(), 22,449 ( 0.00%) data: SmallVecData::from_inline(MaybeUninit::new(buf)), . } . } . . /// Constructs a new `SmallVec` on the stack from an `A` without . /// copying elements. Also sets the length, which must be less or . /// equal to the size of `buf`. . /// . /// ```rust -- line 651 ---------------------------------------- -- line 653 ---------------------------------------- . /// . /// let buf = [1, 2, 3, 4, 5, 0, 0, 0]; . /// let small_vec: SmallVec<_> = SmallVec::from_buf_and_len(buf, 5); . /// . /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]); . /// ``` . #[inline] . pub fn from_buf_and_len(buf: A, len: usize) -> SmallVec { 12 ( 0.00%) assert!(len <= A::size()); 36 ( 0.00%) unsafe { SmallVec::from_buf_and_len_unchecked(MaybeUninit::new(buf), len) } . } . . /// Constructs a new `SmallVec` on the stack from an `A` without . /// copying elements. Also sets the length. The user is responsible . /// for ensuring that `len <= A::size()`. . /// . /// ```rust . /// use smallvec::SmallVec; -- line 670 ---------------------------------------- -- line 674 ---------------------------------------- . /// let small_vec: SmallVec<_> = unsafe { . /// SmallVec::from_buf_and_len_unchecked(MaybeUninit::new(buf), 5) . /// }; . /// . /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]); . /// ``` . #[inline] . pub unsafe fn from_buf_and_len_unchecked(buf: MaybeUninit, len: usize) -> SmallVec { 6 ( 0.00%) SmallVec { . capacity: len, . data: SmallVecData::from_inline(buf), . } . } . . /// Sets the length of a vector. . /// . /// This will explicitly set the size of the vector, without actually . /// modifying its buffers, so it is up to the caller to ensure that the . /// vector is actually the specified size. . pub unsafe fn set_len(&mut self, new_len: usize) { . let (_, len_ptr, _) = self.triple_mut(); 57,421 ( 0.00%) *len_ptr = new_len; . } . . /// The maximum number of elements this vector can hold inline . #[inline] . fn inline_capacity() -> usize { . if mem::size_of::() > 0 { 60 ( 0.00%) A::size() . } else { . // For zero-size items code like `ptr.add(offset)` always returns the same pointer. . // Therefore all items are at the same address, . // and any array size has capacity for infinitely many items. . // The capacity is limited by the bit width of the length field. . // . // `Vec` also does this: . // https://github.com/rust-lang/rust/blob/1.44.0/src/liballoc/raw_vec.rs#L186 -- line 710 ---------------------------------------- -- line 725 ---------------------------------------- . #[inline] . pub fn len(&self) -> usize { . self.triple().1 . } . . /// Returns `true` if the vector is empty . #[inline] . pub fn is_empty(&self) -> bool { 2,084,251 ( 0.05%) self.len() == 0 . } . . /// The number of items the vector can hold without reallocating . #[inline] . pub fn capacity(&self) -> usize { . self.triple().2 . } . . /// Returns a tuple with (data ptr, len, capacity) . /// Useful to get all SmallVec properties with a single check of the current storage variant. . #[inline] . fn triple(&self) -> (*const A::Item, usize, usize) { . unsafe { 7,150,078 ( 0.18%) if self.spilled() { . let (ptr, len) = self.data.heap(); . (ptr, len, self.capacity) . } else { . (self.data.inline(), self.capacity, Self::inline_capacity()) . } . } . } . . /// Returns a tuple with (data ptr, len ptr, capacity) . #[inline] . fn triple_mut(&mut self) -> (*mut A::Item, &mut usize, usize) { . unsafe { 83,249,101 ( 2.07%) if self.spilled() { 17,667 ( 0.00%) let &mut (ptr, ref mut len_ptr) = self.data.heap_mut(); . (ptr, len_ptr, self.capacity) . } else { . ( . self.data.inline_mut(), . &mut self.capacity, . Self::inline_capacity(), . ) . } . } . } . . /// Returns `true` if the data has spilled into a separate heap-allocated buffer. . #[inline] . pub fn spilled(&self) -> bool { 44,027,888 ( 1.09%) self.capacity > Self::inline_capacity() . } . . /// Creates a draining iterator that removes the specified range in the vector . /// and yields the removed items. . /// . /// Note 1: The element range is removed even if the iterator is only . /// partially consumed or not consumed at all. . /// -- line 784 ---------------------------------------- -- line 821 ---------------------------------------- . iter: range_slice.iter(), . vec: NonNull::from(self), . } . } . } . . /// Append an item to the vector. . #[inline] 33,030 ( 0.00%) pub fn push(&mut self, value: A::Item) { . unsafe { . let (mut ptr, mut len, cap) = self.triple_mut(); 13,038,106 ( 0.32%) if *len == cap { 145 ( 0.00%) self.reserve(1); 53,865 ( 0.00%) let &mut (heap_ptr, ref mut heap_len) = self.data.heap_mut(); . ptr = heap_ptr; . len = heap_len; . } 80,736 ( 0.00%) ptr::write(ptr.add(*len), value); 16,069,203 ( 0.40%) *len += 1; . } 26,424 ( 0.00%) } . . /// Remove an item from the end of the vector and return it, or None if empty. . #[inline] . pub fn pop(&mut self) -> Option { . unsafe { . let (ptr, len_ptr, _) = self.triple_mut(); 6,919,640 ( 0.17%) if *len_ptr == 0 { . return None; . } 2,062,916 ( 0.05%) let last_index = *len_ptr - 1; 2,717,400 ( 0.07%) *len_ptr = last_index; 35,606 ( 0.00%) Some(ptr::read(ptr.add(last_index))) . } 15 ( 0.00%) } . . /// Moves all the elements of `other` into `self`, leaving `other` empty. . /// . /// # Example . /// . /// ``` . /// # use smallvec::{SmallVec, smallvec}; . /// let mut v0: SmallVec<[u8; 16]> = smallvec![1, 2, 3]; -- line 863 ---------------------------------------- -- line 879 ---------------------------------------- . /// or if the capacity computation overflows `usize`. . pub fn grow(&mut self, new_cap: usize) { . infallible(self.try_grow(new_cap)) . } . . /// Re-allocate to set the capacity to `max(new_cap, inline_size())`. . /// . /// Panics if `new_cap` is less than the vector's length 4,677 ( 0.00%) pub fn try_grow(&mut self, new_cap: usize) -> Result<(), CollectionAllocErr> { . unsafe { 131 ( 0.00%) let (ptr, &mut len, cap) = self.triple_mut(); . let unspilled = !self.spilled(); 97,928 ( 0.00%) assert!(new_cap >= len); 97,928 ( 0.00%) if new_cap <= self.inline_size() { . if unspilled { . return Ok(()); . } . self.data = SmallVecData::from_inline(MaybeUninit::uninit()); . ptr::copy_nonoverlapping(ptr, self.data.inline_mut(), len); . self.capacity = len; . deallocate(ptr, cap); 97,928 ( 0.00%) } else if new_cap != cap { 97,478 ( 0.00%) let layout = layout_array::(new_cap)?; . debug_assert!(layout.size() > 0); . let new_alloc; 48,964 ( 0.00%) if unspilled { . new_alloc = NonNull::new(alloc::alloc::alloc(layout)) . .ok_or(CollectionAllocErr::AllocErr { layout })? . .cast() . .as_ptr(); . ptr::copy_nonoverlapping(ptr, new_alloc, len); . } else { . // This should never fail since the same succeeded . // when previously allocating `ptr`. 53,700 ( 0.00%) let old_layout = layout_array::(cap)?; . . let new_ptr = alloc::alloc::realloc(ptr as *mut u8, old_layout, layout.size()); . new_alloc = NonNull::new(new_ptr) . .ok_or(CollectionAllocErr::AllocErr { layout })? . .cast() . .as_ptr(); . } 97,928 ( 0.00%) self.data = SmallVecData::from_heap(new_alloc, len); 146,462 ( 0.00%) self.capacity = new_cap; . } . Ok(()) . } 4,808 ( 0.00%) } . . /// Reserve capacity for `additional` more elements to be inserted. . /// . /// May reserve more space to avoid frequent reallocations. . /// . /// Panics if the capacity computation overflows `usize`. . #[inline] 102,946 ( 0.00%) pub fn reserve(&mut self, additional: usize) { 3,074,203 ( 0.08%) infallible(self.try_reserve(additional)) 116,192 ( 0.00%) } . . /// Reserve capacity for `additional` more elements to be inserted. . /// . /// May reserve more space to avoid frequent reallocations. 11,884,753 ( 0.29%) pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> { . // prefer triple_mut() even if triple() would work . // so that the optimizer removes duplicated calls to it . // from callers like insert() 2,484 ( 0.00%) let (_, &mut len, cap) = self.triple_mut(); 7,707,712 ( 0.19%) if cap - len >= additional { . return Ok(()); . } . let new_cap = len . .checked_add(additional) . .and_then(usize::checked_next_power_of_two) . .ok_or(CollectionAllocErr::CapacityOverflow)?; 514 ( 0.00%) self.try_grow(new_cap) 13,373,397 ( 0.33%) } . . /// Reserve the minimum capacity for `additional` more elements to be inserted. . /// . /// Panics if the new capacity overflows `usize`. 4 ( 0.00%) pub fn reserve_exact(&mut self, additional: usize) { . infallible(self.try_reserve_exact(additional)) 4 ( 0.00%) } . . /// Reserve the minimum capacity for `additional` more elements to be inserted. . pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), CollectionAllocErr> { . let (_, &mut len, cap) = self.triple_mut(); 63,957 ( 0.00%) if cap - len >= additional { . return Ok(()); . } . let new_cap = len . .checked_add(additional) . .ok_or(CollectionAllocErr::CapacityOverflow)?; 376 ( 0.00%) self.try_grow(new_cap) 376 ( 0.00%) } . . /// Shrink the capacity of the vector as much as possible. . /// . /// When possible, this will move data from an external heap buffer to the vector's inline . /// storage. . pub fn shrink_to_fit(&mut self) { . if !self.spilled() { . return; -- line 981 ---------------------------------------- -- line 999 ---------------------------------------- . /// If `len` is greater than or equal to the vector's current length, this has no . /// effect. . /// . /// This does not re-allocate. If you want the vector's capacity to shrink, call . /// `shrink_to_fit` after truncating. . pub fn truncate(&mut self, len: usize) { . unsafe { . let (ptr, len_ptr, _) = self.triple_mut(); 18,296 ( 0.00%) while len < *len_ptr { . let last_index = *len_ptr - 1; . *len_ptr = last_index; . ptr::drop_in_place(ptr.add(last_index)); . } . } . } . . /// Extracts a slice containing the entire vector. -- line 1015 ---------------------------------------- -- line 1044 ---------------------------------------- . pub fn clear(&mut self) { . self.truncate(0); . } . . /// Remove and return the element at position `index`, shifting all elements after it to the . /// left. . /// . /// Panics if `index` is out of bounds. 6,256 ( 0.00%) pub fn remove(&mut self, index: usize) -> A::Item { . unsafe { . let (mut ptr, len_ptr, _) = self.triple_mut(); 2,544 ( 0.00%) let len = *len_ptr; 13,383 ( 0.00%) assert!(index < len); 16,213 ( 0.00%) *len_ptr = len - 1; . ptr = ptr.add(index); . let item = ptr::read(ptr); 8,922 ( 0.00%) ptr::copy(ptr.add(1), ptr, len - index - 1); . item . } 7,820 ( 0.00%) } . . /// Insert an element at position `index`, shifting all elements after it to the right. . /// . /// Panics if `index` is out of bounds. 26,167 ( 0.00%) pub fn insert(&mut self, index: usize, element: A::Item) { . self.reserve(1); . . unsafe { . let (mut ptr, len_ptr, _) = self.triple_mut(); 2,379 ( 0.00%) let len = *len_ptr; 4,758 ( 0.00%) assert!(index <= len); 9,516 ( 0.00%) *len_ptr = len + 1; . ptr = ptr.add(index); 4,758 ( 0.00%) ptr::copy(ptr, ptr.add(1), len - index); . ptr::write(ptr, element); . } 16,654 ( 0.00%) } . . /// Insert multiple elements at position `index`, shifting all following elements toward the . /// back. . pub fn insert_many>(&mut self, index: usize, iterable: I) { . let mut iter = iterable.into_iter(); . if index == self.len() { . return self.extend(iter); . } -- line 1088 ---------------------------------------- -- line 1201 ---------------------------------------- . } . } . . /// Retains only the elements specified by the predicate. . /// . /// In other words, remove all elements `e` such that `f(&e)` returns `false`. . /// This method operates in place and preserves the order of the retained . /// elements. 47,250 ( 0.00%) pub fn retain bool>(&mut self, mut f: F) { . let mut del = 0; . let len = self.len(); . for i in 0..len { 8,740 ( 0.00%) if !f(&mut self[i]) { . del += 1; 2,390 ( 0.00%) } else if del > 0 { . self.swap(i - del, i); . } . } 10,500 ( 0.00%) self.truncate(len - del); 42,000 ( 0.00%) } . . /// Removes consecutive duplicate elements. . pub fn dedup(&mut self) . where . A::Item: PartialEq, . { . self.dedup_by(|a, b| a == b); . } -- line 1228 ---------------------------------------- -- line 1418 ---------------------------------------- . capacity: len, . data: SmallVecData::from_inline(unsafe { . let mut data: MaybeUninit = MaybeUninit::uninit(); . ptr::copy_nonoverlapping( . slice.as_ptr(), . data.as_mut_ptr() as *mut A::Item, . len, . ); 375 ( 0.00%) data . }), . } . } else { . let mut b = slice.to_vec(); . let (ptr, cap) = (b.as_mut_ptr(), b.capacity()); . mem::forget(b); . SmallVec { . capacity: cap, -- line 1434 ---------------------------------------- -- line 1436 ---------------------------------------- . } . } . } . . /// Copy elements from a slice into the vector at position `index`, shifting any following . /// elements toward the back. . /// . /// For slices of `Copy` types, this is more efficient than `insert`. 266,285 ( 0.01%) pub fn insert_from_slice(&mut self, index: usize, slice: &[A::Item]) { . self.reserve(slice.len()); . . let len = self.len(); 76,581 ( 0.00%) assert!(index <= len); . . unsafe { . let slice_ptr = slice.as_ptr(); . let ptr = self.as_mut_ptr().add(index); . ptr::copy(ptr, ptr.add(slice.len()), len - index); . ptr::copy_nonoverlapping(slice_ptr, ptr, slice.len()); 51,054 ( 0.00%) self.set_len(len + slice.len()); . } 204,216 ( 0.01%) } . . /// Copy elements from a slice and append them to the vector. . /// . /// For slices of `Copy` types, this is more efficient than `extend`. . #[inline] . pub fn extend_from_slice(&mut self, slice: &[A::Item]) { . let len = self.len(); 58,670 ( 0.00%) self.insert_from_slice(len, slice); . } . } . . impl SmallVec . where . A::Item: Clone, . { . /// Resizes the vector so that its length is equal to `len`. . /// . /// If `len` is less than the current length, the vector simply truncated. . /// . /// If `len` is greater than the current length, `value` is appended to the . /// vector until its length equals `len`. 80 ( 0.00%) pub fn resize(&mut self, len: usize, value: A::Item) { . let old_len = self.len(); . 16 ( 0.00%) if len > old_len { . self.extend(repeat(value).take(len - old_len)); . } else { . self.truncate(len); . } 56 ( 0.00%) } . . /// Creates a `SmallVec` with `n` copies of `elem`. . /// ``` . /// use smallvec::SmallVec; . /// . /// let v = SmallVec::<[char; 128]>::from_elem('d', 2); . /// assert_eq!(v, SmallVec::from_buf(['d', 'd'])); . /// ``` -- line 1495 ---------------------------------------- -- line 1522 ---------------------------------------- . } . } . } . . impl ops::DerefMut for SmallVec { . #[inline] . fn deref_mut(&mut self) -> &mut [A::Item] { . unsafe { 274,019 ( 0.01%) let (ptr, &mut len, _) = self.triple_mut(); . slice::from_raw_parts_mut(ptr, len) . } . } . } . . impl AsRef<[A::Item]> for SmallVec { . #[inline] . fn as_ref(&self) -> &[A::Item] { -- line 1538 ---------------------------------------- -- line 1691 ---------------------------------------- . fn from(array: A) -> SmallVec { . SmallVec::from_buf(array) . } . } . . impl> ops::Index for SmallVec { . type Output = I::Output; . 2 ( 0.00%) fn index(&self, index: I) -> &I::Output { . &(**self)[index] 6 ( 0.00%) } . } . . impl> ops::IndexMut for SmallVec { . fn index_mut(&mut self, index: I) -> &mut I::Output { . &mut (&mut **self)[index] . } . } . -- line 1709 ---------------------------------------- -- line 1716 ---------------------------------------- . SmallVec::extend_from_slice(self, other) . } . } . . impl FromIterator for SmallVec { . #[inline] . fn from_iter>(iterable: I) -> SmallVec { . let mut v = SmallVec::new(); 2,258,887 ( 0.06%) v.extend(iterable); . v . } . } . . impl Extend for SmallVec { 14,537,679 ( 0.36%) fn extend>(&mut self, iterable: I) { 147,005 ( 0.00%) let mut iter = iterable.into_iter(); . let (lower_size_bound, _) = iter.size_hint(); 16,706 ( 0.00%) self.reserve(lower_size_bound); . . unsafe { . let (ptr, len_ptr, cap) = self.triple_mut(); . let mut len = SetLenOnDrop::new(len_ptr); 5,856,750 ( 0.15%) while len.get() < cap { 891,815 ( 0.02%) if let Some(out) = iter.next() { 8 ( 0.00%) ptr::write(ptr.add(len.get()), out); . len.increment_len(1); . } else { . return; . } . } . } . 77,722 ( 0.00%) for elem in iter { 7,782 ( 0.00%) self.push(elem); . } 11,708,943 ( 0.29%) } . } . . impl fmt::Debug for SmallVec . where . A::Item: fmt::Debug, . { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . f.debug_list().entries(self.iter()).finish() -- line 1759 ---------------------------------------- -- line 1764 ---------------------------------------- . #[inline] . fn default() -> SmallVec { . SmallVec::new() . } . } . . #[cfg(feature = "may_dangle")] . unsafe impl<#[may_dangle] A: Array> Drop for SmallVec { 18,767,979 ( 0.47%) fn drop(&mut self) { . unsafe { 6,275,204 ( 0.16%) if self.spilled() { . let (ptr, len) = self.data.heap(); . Vec::from_raw_parts(ptr, len, self.capacity); . } else { . ptr::drop_in_place(&mut self[..]); . } . } 18,807,473 ( 0.47%) } . } . . #[cfg(not(feature = "may_dangle"))] . impl Drop for SmallVec { . fn drop(&mut self) { . unsafe { . if self.spilled() { . let (ptr, len) = self.data.heap(); -- line 1789 ---------------------------------------- -- line 1888 ---------------------------------------- . A::Item: Clone, . { . fn clone(&self) -> IntoIter { . SmallVec::from(self.as_slice()).into_iter() . } . } . . impl Drop for IntoIter { 1,086 ( 0.00%) fn drop(&mut self) { 45,243 ( 0.00%) for _ in self {} 1,184 ( 0.00%) } . } . . impl Iterator for IntoIter { . type Item = A::Item; . . #[inline] . fn next(&mut self) -> Option { 249,937 ( 0.01%) if self.current == self.end { 3 ( 0.00%) None . } else { . unsafe { . let current = self.current; 137,402 ( 0.00%) self.current += 1; 1,480 ( 0.00%) Some(ptr::read(self.data.as_ptr().add(current))) . } . } . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 2,337 ( 0.00%) let size = self.end - self.current; . (size, Some(size)) . } . } . . impl DoubleEndedIterator for IntoIter { . #[inline] . fn next_back(&mut self) -> Option { . if self.current == self.end { -- line 1927 ---------------------------------------- -- line 1955 ---------------------------------------- . impl IntoIterator for SmallVec { . type IntoIter = IntoIter; . type Item = A::Item; . fn into_iter(mut self) -> Self::IntoIter { . unsafe { . // Set SmallVec len to zero as `IntoIter` drop handles dropping of the elements . let len = self.len(); . self.set_len(0); 12,206 ( 0.00%) IntoIter { 130,966 ( 0.00%) data: self, . current: 0, . end: len, . } . } . } . } . . impl<'a, A: Array> IntoIterator for &'a SmallVec { -- line 1972 ---------------------------------------- -- line 2000 ---------------------------------------- . len: &'a mut usize, . local_len: usize, . } . . impl<'a> SetLenOnDrop<'a> { . #[inline] . fn new(len: &'a mut usize) -> Self { . SetLenOnDrop { 1,468,263 ( 0.04%) local_len: *len, . len, . } . } . . #[inline] . fn get(&self) -> usize { . self.local_len . } . . #[inline] . fn increment_len(&mut self, increment: usize) { 739,859 ( 0.02%) self.local_len += increment; . } . } . . impl<'a> Drop for SetLenOnDrop<'a> { . #[inline] . fn drop(&mut self) { 2,148,466 ( 0.05%) *self.len = self.local_len; . } . } . . #[cfg(feature = "const_new")] . impl SmallVec<[T; N]> { . /// Construct an empty vector. . /// . /// This is a `const` version of [`SmallVec::new`] that is enabled by the feature `const_new`, with the limitation that it only works for arrays. -- line 2035 ---------------------------------------- 20,005,170 ( 0.50%) -------------------------------------------------------------------------------- -- 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")] 282 ( 0.00%) pub fn from_str_radix(src: &str, radix: u32) -> Result { 141 ( 0.00%) from_str_radix(src, radix) 423 ( 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 { 63,030 ( 0.00%) intrinsics::ctpop(self as $ActualT) as u32 . } . . /// Returns the number of zeros in the binary representation of `self`. . /// . /// # Examples . /// . /// Basic usage: . /// -- line 96 ---------------------------------------- -- line 118 ---------------------------------------- . /// assert_eq!(n.leading_zeros(), 2); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn leading_zeros(self) -> u32 { 232,048 ( 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 { 353,974 ( 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 { 8,675,283 ( 0.22%) intrinsics::rotate_left(self, n as $SelfT) . } . . /// Shifts the bits to the right by a specified amount, `n`, . /// wrapping the truncated bits to the beginning of the resulting . /// integer. . /// . /// Please note this isn't the same operation as the `>>` shifting operator! . /// -- line 220 ---------------------------------------- -- line 430 ---------------------------------------- . #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline] . pub const fn checked_add(self, rhs: Self) -> Option { 2 ( 0.00%) let (a, b) = self.overflowing_add(rhs); . if unlikely!(b) {None} else {Some(a)} . } . . /// Unchecked integer addition. Computes `self + rhs`, assuming overflow . /// cannot occur. . /// . /// # Safety . /// -- line 446 ---------------------------------------- -- line 456 ---------------------------------------- . )] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")] . #[inline(always)] . pub const unsafe fn unchecked_add(self, rhs: Self) -> Self { . // SAFETY: the caller must uphold the safety contract for . // `unchecked_add`. 611,598 ( 0.02%) unsafe { intrinsics::unchecked_add(self, rhs) } . } . . /// Checked addition with a signed integer. Computes `self + rhs`, . /// returning `None` if overflow occurred. . /// . /// # Examples . /// . /// Basic usage: -- line 472 ---------------------------------------- -- line 525 ---------------------------------------- . )] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")] . #[inline(always)] . pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self { . // SAFETY: the caller must uphold the safety contract for . // `unchecked_sub`. 47,163 ( 0.00%) unsafe { intrinsics::unchecked_sub(self, rhs) } . } . . /// Checked integer multiplication. Computes `self * rhs`, returning . /// `None` if overflow occurred. . /// . /// # Examples . /// . /// Basic usage: -- line 541 ---------------------------------------- -- line 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 { 131,911 ( 0.00%) intrinsics::saturating_add(self, rhs) . } . . /// Saturating addition with a signed integer. Computes `self + rhs`, . /// saturating at the numeric bounds instead of overflowing. . /// . /// # Examples . /// . /// Basic usage: -- line 1051 ---------------------------------------- -- line 1084 ---------------------------------------- . #[doc = concat!("assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")] . #[inline(always)] . pub const fn saturating_sub(self, rhs: Self) -> Self { 5,584 ( 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 1104 ---------------------------------------- . #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),"::MAX);")] . /// ``` . #[stable(feature = "wrapping", since = "1.7.0")] . #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline] . pub const fn saturating_mul(self, rhs: Self) -> Self { 4 ( 0.00%) match self.checked_mul(rhs) { . Some(x) => x, . None => Self::MAX, . } . } . . /// Saturating integer division. Computes `self / rhs`, saturating at the . /// numeric bounds instead of overflowing. . /// -- line 1120 ---------------------------------------- -- 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 { 4,464,568 ( 0.11%) intrinsics::wrapping_add(self, rhs) . } . . /// Wrapping (modular) addition with a signed integer. Computes . /// `self + rhs`, wrapping around at the boundary of the type. . /// . /// # Examples . /// . /// Basic usage: -- line 1191 ---------------------------------------- -- line 1217 ---------------------------------------- . #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::MAX), 101);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn wrapping_sub(self, rhs: Self) -> Self { 1,261,471 ( 0.03%) 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 { 5,462,925 ( 0.14%) intrinsics::wrapping_mul(self, rhs) . } . . /// Wrapping (modular) division. Computes `self / rhs`. . /// Wrapped division on unsigned types is just normal division. . /// There's no way wrapping could ever happen. . /// This function exists, so that all operations . /// are accounted for in the wrapping operations. . /// -- line 1256 ---------------------------------------- -- line 1492 ---------------------------------------- . #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));")] . /// ``` . #[stable(feature = "wrapping", since = "1.7.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) { 816,880 ( 0.02%) let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT); . (a as Self, b) . } . . /// Calculates `self + rhs + carry` without the ability to overflow. . /// . /// Performs "ternary addition" which takes in an extra bit to add, and may return an . /// additional bit of overflow. This allows for chaining together multiple additions . /// to create "big integers" which represent larger values. -- line 1508 ---------------------------------------- -- line 1588 ---------------------------------------- . #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));")] . /// ``` . #[stable(feature = "wrapping", since = "1.7.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) { 163,968 ( 0.00%) let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT); . (a as Self, b) . } . . /// Calculates `self - rhs - borrow` without the ability to overflow. . /// . /// Performs "ternary subtraction" which takes in an extra bit to subtract, and may return . /// an additional bit of overflow. This allows for chaining together multiple subtractions . /// to create "big integers" which represent larger values. -- line 1604 ---------------------------------------- -- line 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) { 2,754,489 ( 0.07%) let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT); . (a as Self, b) . } . . /// Calculates the divisor when `self` is divided by `rhs`. . /// . /// Returns a tuple of the divisor along with a boolean indicating . /// whether an arithmetic overflow would occur. Note that for unsigned . /// integers overflow never occurs, so the second value is always -- line 1690 ---------------------------------------- -- line 2132 ---------------------------------------- . #[doc = concat!("assert!(16", stringify!($SelfT), ".is_power_of_two());")] . #[doc = concat!("assert!(!10", stringify!($SelfT), ".is_power_of_two());")] . /// ``` . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")] . #[inline(always)] . pub const fn is_power_of_two(self) -> bool { 162 ( 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 { 97,218 ( 0.00%) if self <= 1 { return 0; } . 55,139 ( 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. 165,327 ( 0.00%) let z = unsafe { intrinsics::ctlz_nonzero(p) }; 55,205 ( 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 { 13,048 ( 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 ---------------------------------------- 60,047 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/option.rs -------------------------------------------------------------------------------- Ir -- line 504 ---------------------------------------- . use crate::panicking::{panic, panic_str}; . use crate::pin::Pin; . use crate::{ . convert, hint, mem, . ops::{self, ControlFlow, Deref, DerefMut}, . }; . . /// The `Option` type. See [the module level documentation](self) for more. 909,741 ( 0.02%) #[derive(Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)] . #[rustc_diagnostic_item = "Option"] . #[stable(feature = "rust1", since = "1.0.0")] . pub enum Option { . /// No value. . #[lang = "None"] . #[stable(feature = "rust1", since = "1.0.0")] . None, . /// Some value of type `T`. . #[lang = "Some"] . #[stable(feature = "rust1", since = "1.0.0")] 7,120 ( 0.00%) Some(#[stable(feature = "rust1", since = "1.0.0")] T), . } . . ///////////////////////////////////////////////////////////////////////////// . // Type implementation . ///////////////////////////////////////////////////////////////////////////// . . impl Option { . ///////////////////////////////////////////////////////////////////////// -- line 531 ---------------------------------------- -- line 543 ---------------------------------------- . /// let x: Option = None; . /// assert_eq!(x.is_some(), false); . /// ``` . #[must_use = "if you intended to assert that this has a value, consider `.unwrap()` instead"] . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_option", since = "1.48.0")] . pub const fn is_some(&self) -> bool { 2,863,688 ( 0.07%) matches!(*self, Some(_)) . } . . /// Returns `true` if the option is a [`Some`] wrapping a value matching the predicate. . /// . /// # Examples . /// . /// ``` . /// #![feature(is_some_with)] -- line 559 ---------------------------------------- -- line 616 ---------------------------------------- . /// // then consume *that* with `map`, leaving `text` on the stack. . /// let text_length: Option = text.as_ref().map(|s| s.len()); . /// println!("still can print text: {:?}", text); . /// ``` . #[inline] . #[rustc_const_stable(feature = "const_option", since = "1.48.0")] . #[stable(feature = "rust1", since = "1.0.0")] . pub const fn as_ref(&self) -> Option<&T> { 3,216,905 ( 0.08%) match *self { . Some(ref x) => Some(x), . None => None, . } . } . . /// Converts from `&mut Option` to `Option<&mut T>`. . /// . /// # Examples -- line 632 ---------------------------------------- -- line 638 ---------------------------------------- . /// None => {}, . /// } . /// assert_eq!(x, Some(42)); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] . pub const fn as_mut(&mut self) -> Option<&mut T> { 428,170 ( 0.01%) match *self { . Some(ref mut x) => Some(x), . None => None, . } . } . . /// Converts from [Pin]<[&]Option\> to Option<[Pin]<[&]T>>. . /// . /// [&]: reference "shared reference" -- line 654 ---------------------------------------- -- line 705 ---------------------------------------- . /// let x: Option<&str> = None; . /// x.expect("fruits are healthy"); // panics with `fruits are healthy` . /// ``` . #[inline] . #[track_caller] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] . pub const fn expect(self, msg: &str) -> T { 728,350 ( 0.02%) match self { 385,830 ( 0.01%) Some(val) => val, . None => expect_failed(msg), . } . } . . /// Returns the contained [`Some`] value, consuming the `self` value. . /// . /// Because this function may panic, its use is generally discouraged. . /// Instead, prefer to use pattern matching and handle the [`None`] -- line 722 ---------------------------------------- -- line 742 ---------------------------------------- . /// let x: Option<&str> = None; . /// assert_eq!(x.unwrap(), "air"); // fails . /// ``` . #[inline] . #[track_caller] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] . pub const fn unwrap(self) -> T { 4,179,673 ( 0.10%) match self { 424,863 ( 0.01%) Some(val) => val, . None => panic("called `Option::unwrap()` on a `None` value"), . } . } . . /// Returns the contained [`Some`] value or a provided default. . /// . /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing . /// the result of a function call, it is recommended to use [`unwrap_or_else`], -- line 759 ---------------------------------------- -- line 769 ---------------------------------------- . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn unwrap_or(self, default: T) -> T . where . T: ~const Drop, . { 887,182 ( 0.02%) match self { . Some(x) => x, 14,856 ( 0.00%) None => default, . } 317 ( 0.00%) } . . /// Returns the contained [`Some`] value or computes it from a closure. . /// . /// # Examples . /// . /// ``` . /// let k = 10; . /// assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4); . /// assert_eq!(None.unwrap_or_else(|| 2 * k), 20); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] 59 ( 0.00%) pub const fn unwrap_or_else(self, f: F) -> T . where . F: ~const FnOnce() -> T, . F: ~const Drop, . { 503,559 ( 0.01%) match self { 47,485 ( 0.00%) Some(x) => x, 8,690 ( 0.00%) None => f(), . } 121 ( 0.00%) } . . /// Returns the contained [`Some`] value or a default. . /// . /// Consumes the `self` argument then, if [`Some`], returns the contained . /// value, otherwise if [`None`], returns the [default value] for that . /// type. . /// . /// # Examples -- line 812 ---------------------------------------- -- line 831 ---------------------------------------- . /// [`FromStr`]: crate::str::FromStr . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn unwrap_or_default(self) -> T . where . T: ~const Default, . { 6,893 ( 0.00%) match self { 2,456 ( 0.00%) Some(x) => x, . None => Default::default(), . } . } . . /// Returns the contained [`Some`] value, consuming the `self` value, . /// without checking that the value is not [`None`]. . /// . /// # Safety -- line 848 ---------------------------------------- -- line 892 ---------------------------------------- . /// // `Option::map` takes self *by value*, consuming `maybe_some_string` . /// let maybe_some_len = maybe_some_string.map(|s| s.len()); . /// . /// assert_eq!(maybe_some_len, Some(13)); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] 917 ( 0.00%) pub const fn map(self, f: F) -> Option . where . F: ~const FnOnce(T) -> U, . F: ~const Drop, . { 1,422,788 ( 0.04%) match self { 1,193,294 ( 0.03%) Some(x) => Some(f(x)), 37,700 ( 0.00%) None => None, . } 44,528 ( 0.00%) } . . /// Calls the provided closure with a reference to the contained value (if [`Some`]). . /// . /// # Examples . /// . /// ``` . /// #![feature(result_option_inspect)] . /// -- line 917 ---------------------------------------- -- line 960 ---------------------------------------- . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn map_or(self, default: U, f: F) -> U . where . F: ~const FnOnce(T) -> U, . F: ~const Drop, . U: ~const Drop, . { 580,201 ( 0.01%) match self { 24,966 ( 0.00%) Some(t) => f(t), 26,380 ( 0.00%) None => default, . } . } . . /// Computes a default function result (if none), or . /// applies a different function to the contained value (if any). . /// . /// # Examples . /// -- line 978 ---------------------------------------- -- line 990 ---------------------------------------- . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn map_or_else(self, default: D, f: F) -> U . where . D: ~const FnOnce() -> U, . D: ~const Drop, . F: ~const FnOnce(T) -> U, . F: ~const Drop, . { 13,643 ( 0.00%) match self { 6 ( 0.00%) Some(t) => f(t), . None => default(), . } . } . . /// Transforms the `Option` into a [`Result`], mapping [`Some(v)`] to . /// [`Ok(v)`] and [`None`] to [`Err(err)`]. . /// . /// Arguments passed to `ok_or` are eagerly evaluated; if you are passing the -- line 1007 ---------------------------------------- -- line 1024 ---------------------------------------- . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn ok_or(self, err: E) -> Result . where . E: ~const Drop, . { 756,100 ( 0.02%) match self { 1,416 ( 0.00%) Some(v) => Ok(v), 704 ( 0.00%) None => Err(err), . } . } . . /// Transforms the `Option` into a [`Result`], mapping [`Some(v)`] to . /// [`Ok(v)`] and [`None`] to [`Err(err())`]. . /// . /// [`Ok(v)`]: Ok . /// [`Err(err())`]: Err -- line 1042 ---------------------------------------- -- line 1049 ---------------------------------------- . /// assert_eq!(x.ok_or_else(|| 0), Ok("foo")); . /// . /// let x: Option<&str> = None; . /// assert_eq!(x.ok_or_else(|| 0), Err(0)); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] 60 ( 0.00%) pub const fn ok_or_else(self, err: F) -> Result . where . F: ~const FnOnce() -> E, . F: ~const Drop, . { 61,999 ( 0.00%) match self { 51,629 ( 0.00%) Some(v) => Ok(v), 13,429 ( 0.00%) None => Err(err()), . } 75 ( 0.00%) } . . /// Converts from `Option` (or `&Option`) to `Option<&T::Target>`. . /// . /// Leaves the original Option in-place, creating a new one with a reference . /// to the original one, additionally coercing the contents via [`Deref`]. . /// . /// # Examples . /// -- line 1074 ---------------------------------------- -- line 1080 ---------------------------------------- . /// assert_eq!(x.as_deref(), None); . /// ``` . #[stable(feature = "option_deref", since = "1.40.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn as_deref(&self) -> Option<&T::Target> . where . T: ~const Deref, . { 18,701 ( 0.00%) match self.as_ref() { . Some(t) => Some(t.deref()), . None => None, . } . } . . /// Converts from `Option` (or `&mut Option`) to `Option<&mut T::Target>`. . /// . /// Leaves the original `Option` in-place, creating a new one containing a mutable reference to -- line 1096 ---------------------------------------- -- line 1213 ---------------------------------------- . /// assert_eq!(Some(2).and_then(sq).and_then(sq), Some(16)); . /// assert_eq!(Some(2).and_then(sq).and_then(nope), None); . /// assert_eq!(Some(2).and_then(nope).and_then(sq), None); . /// assert_eq!(None.and_then(sq).and_then(sq), None); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] 677 ( 0.00%) pub const fn and_then(self, f: F) -> Option . where . F: ~const FnOnce(T) -> Option, . F: ~const Drop, . { 117,703 ( 0.00%) match self { 29,656 ( 0.00%) Some(x) => f(x), . None => None, . } 93,554 ( 0.00%) } . . /// Returns [`None`] if the option is [`None`], otherwise calls `predicate` . /// with the wrapped value and returns: . /// . /// - [`Some(t)`] if `predicate` returns `true` (where `t` is the wrapped . /// value), and . /// - [`None`] if `predicate` returns `false`. . /// -- line 1238 ---------------------------------------- -- line 1257 ---------------------------------------- . #[stable(feature = "option_filter", since = "1.27.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn filter

(self, predicate: P) -> Self . where . T: ~const Drop, . P: ~const FnOnce(&T) -> bool, . P: ~const Drop, . { 10,348 ( 0.00%) if let Some(x) = self { 21,648 ( 0.00%) if predicate(&x) { . return Some(x); . } . } . None 1,104 ( 0.00%) } . . /// Returns the option if it contains a value, otherwise returns `optb`. . /// . /// Arguments passed to `or` are eagerly evaluated; if you are passing the . /// result of a function call, it is recommended to use [`or_else`], which is . /// lazily evaluated. . /// . /// [`or_else`]: Option::or_else -- line 1279 ---------------------------------------- -- line 1299 ---------------------------------------- . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn or(self, optb: Option) -> Option . where . T: ~const Drop, . { 8,136 ( 0.00%) match self { 1,134 ( 0.00%) Some(x) => Some(x), . None => optb, . } . } . . /// Returns the option if it contains a value, otherwise calls `f` and . /// returns the result. . /// . /// # Examples -- line 1316 ---------------------------------------- -- line 1326 ---------------------------------------- . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn or_else(self, f: F) -> Option . where . F: ~const FnOnce() -> Option, . F: ~const Drop, . { 64,038 ( 0.00%) match self { 63,897 ( 0.00%) Some(x) => Some(x), . None => f(), . } . } . . /// Returns [`Some`] if exactly one of `self`, `optb` is [`Some`], otherwise returns [`None`]. . /// . /// # Examples . /// -- line 1343 ---------------------------------------- -- line 1431 ---------------------------------------- . /// ``` . #[inline] . #[stable(feature = "option_entry", since = "1.20.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn get_or_insert(&mut self, value: T) -> &mut T . where . T: ~const Drop, . { 20,352 ( 0.00%) if let None = *self { 47,488 ( 0.00%) *self = Some(value); . } . . // SAFETY: a `None` variant for `self` would have been replaced by a `Some` . // variant in the code above. . unsafe { self.as_mut().unwrap_unchecked() } . } . . /// Inserts the default value into the option if it is [`None`], then -- line 1448 ---------------------------------------- -- line 1499 ---------------------------------------- . #[inline] . #[stable(feature = "option_entry", since = "1.20.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn get_or_insert_with(&mut self, f: F) -> &mut T . where . F: ~const FnOnce() -> T, . F: ~const Drop, . { 202,212 ( 0.01%) if let None = *self { . // the compiler isn't smart enough to know that we are not dropping a `T` . // here and wants us to ensure `T` can be dropped at compile time. . mem::forget(mem::replace(self, Some(f()))) . } . . // SAFETY: a `None` variant for `self` would have been replaced by a `Some` . // variant in the code above. . unsafe { self.as_mut().unwrap_unchecked() } -- line 1515 ---------------------------------------- -- line 1558 ---------------------------------------- . /// let old = x.replace(3); . /// assert_eq!(x, Some(3)); . /// assert_eq!(old, None); . /// ``` . #[inline] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] . #[stable(feature = "option_replace", since = "1.31.0")] . pub const fn replace(&mut self, value: T) -> Option { 428 ( 0.00%) mem::replace(self, Some(value)) . } . . /// Returns `true` if the option is a [`Some`] value containing the given value. . /// . /// # Examples . /// . /// ``` . /// #![feature(option_result_contains)] -- line 1574 ---------------------------------------- -- line 1712 ---------------------------------------- . #[stable(feature = "copied", since = "1.35.0")] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] . pub const fn copied(self) -> Option . where . T: Copy, . { . // FIXME: this implementation, which sidesteps using `Option::map` since it's not const . // ready yet, should be reverted when possible to avoid code repetition 42,745 ( 0.00%) match self { 302,140 ( 0.01%) Some(&v) => Some(v), 4,563 ( 0.00%) None => None, . } 6 ( 0.00%) } . . /// Maps an `Option<&T>` to an `Option` by cloning the contents of the . /// option. . /// . /// # Examples . /// . /// ``` . /// let x = 12; -- line 1732 ---------------------------------------- -- line 1733 ---------------------------------------- . /// let opt_x = Some(&x); . /// assert_eq!(opt_x, Some(&12)); . /// let cloned = opt_x.cloned(); . /// assert_eq!(cloned, Some(12)); . /// ``` . #[must_use = "`self` will be dropped if the result is not used"] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_cloned", issue = "91582")] 8,789 ( 0.00%) pub const fn cloned(self) -> Option . where . T: ~const Clone, . { 302,874 ( 0.01%) match self { 876,517 ( 0.02%) Some(t) => Some(t.clone()), 103,927 ( 0.00%) None => None, . } 86,473 ( 0.00%) } . } . . impl Option<&mut T> { . /// Maps an `Option<&mut T>` to an `Option` by copying the contents of the . /// option. . /// . /// # Examples . /// -- line 1757 ---------------------------------------- -- line 1843 ---------------------------------------- . ///////////////////////////////////////////////////////////////////////////// . // Trait implementations . ///////////////////////////////////////////////////////////////////////////// . . #[stable(feature = "rust1", since = "1.0.0")] . impl Clone for Option { . #[inline] . fn clone(&self) -> Self { 6,576,558 ( 0.16%) match self { 666,586 ( 0.02%) Some(x) => Some(x.clone()), 677,959 ( 0.02%) None => None, . } 525,274 ( 0.01%) } . . #[inline] . fn clone_from(&mut self, source: &Self) { . match (self, source) { . (Some(to), Some(from)) => to.clone_from(from), . (to, from) => *to = from.clone(), . } . } -- line 1863 ---------------------------------------- -- line 2006 ---------------------------------------- . . #[inline] . fn next(&mut self) -> Option { . self.opt.take() . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 10,897 ( 0.00%) match self.opt { . Some(_) => (1, Some(1)), . None => (0, Some(0)), . } . } . } . . impl DoubleEndedIterator for Item { . #[inline] -- line 2022 ---------------------------------------- -- line 2136 ---------------------------------------- . type Item = A; . . #[inline] . fn next(&mut self) -> Option { . self.inner.next() . } . #[inline] . fn size_hint(&self) -> (usize, Option) { 7 ( 0.00%) self.inner.size_hint() . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl DoubleEndedIterator for IntoIter { . #[inline] . fn next_back(&mut self) -> Option { . self.inner.next_back() -- line 2152 ---------------------------------------- -- line 2241 ---------------------------------------- . #[rustc_const_unstable(feature = "const_convert", issue = "88674")] . impl const ops::Try for Option { . type Output = T; . type Residual = Option; . . #[inline] . fn from_output(output: Self::Output) -> Self { . Some(output) 535 ( 0.00%) } . . #[inline] . fn branch(self) -> ControlFlow { 277,219 ( 0.01%) match self { 17,592 ( 0.00%) Some(v) => ControlFlow::Continue(v), . None => ControlFlow::Break(None), . } . } . } . . #[unstable(feature = "try_trait_v2", issue = "84277")] . #[rustc_const_unstable(feature = "const_convert", issue = "88674")] . impl const ops::FromResidual for Option { . #[inline] . fn from_residual(residual: Option) -> Self { . match residual { 32,529 ( 0.00%) None => None, . } . } . } . . #[unstable(feature = "try_trait_v2_residual", issue = "91285")] . impl ops::Residual for Option { . type TryType = Option; . } -- line 2274 ---------------------------------------- 4,201,135 ( 0.10%) -------------------------------------------------------------------------------- -- 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}; . 7,394 ( 0.00%) #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub enum CommentKind { . Line, . Block, . } . 97 ( 0.00%) #[derive(Clone, PartialEq, Encodable, Decodable, Hash, Debug, Copy)] . #[derive(HashStable_Generic)] . pub enum BinOpToken { . Plus, . Minus, . Star, . Slash, . Percent, . Caret, . And, . Or, . Shl, . Shr, . } . . /// A delimiter token. 700,950 ( 0.02%) #[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, . } . 1,096 ( 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. 108,454 ( 0.00%) #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub struct Lit { . pub kind: LitKind, . pub symbol: Symbol, . pub suffix: Option, . } . . impl fmt::Display for Lit { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { -- line 78 ---------------------------------------- -- line 130 ---------------------------------------- . crate fn may_have_suffix(self) -> bool { . matches!(self, Integer | Float | Err) . } . } . . impl Lit { . pub fn new(kind: LitKind, symbol: Symbol, suffix: Option) -> Lit { . Lit { kind, symbol, suffix } 2,565 ( 0.00%) } . } . 480 ( 0.00%) pub fn ident_can_begin_expr(name: Symbol, span: Span, is_raw: bool) -> bool { 840 ( 0.00%) let ident_token = Token::new(Ident(name, is_raw), span); . 392 ( 0.00%) !ident_token.is_reserved_ident() . || ident_token.is_path_segment_keyword() . || [ . kw::Async, . kw::Do, . kw::Box, . kw::Break, . kw::Const, . kw::Continue, -- line 152 ---------------------------------------- -- line 161 ---------------------------------------- . kw::True, . kw::Try, . kw::Unsafe, . kw::While, . kw::Yield, . kw::Static, . ] . .contains(&name) 600 ( 0.00%) } . . fn ident_can_begin_type(name: Symbol, span: Span, is_raw: bool) -> bool { 798 ( 0.00%) let ident_token = Token::new(Ident(name, is_raw), span); . 270 ( 0.00%) !ident_token.is_reserved_ident() . || ident_token.is_path_segment_keyword() . || [kw::Underscore, kw::For, kw::Impl, kw::Fn, kw::Unsafe, kw::Extern, kw::Typeof, kw::Dyn] . .contains(&name) . } . 75,323,134 ( 1.87%) #[derive(Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub enum TokenKind { . /* Expression-operator symbols. */ . Eq, . Lt, . Le, . EqEq, . Ne, . Ge, . Gt, . AndAnd, . OrOr, . Not, . Tilde, 31,974 ( 0.00%) BinOp(BinOpToken), 42 ( 0.00%) BinOpEq(BinOpToken), . . /* Structural symbols */ . At, . Dot, . DotDot, . DotDotDot, . DotDotEq, . Comma, -- line 203 ---------------------------------------- -- line 208 ---------------------------------------- . LArrow, . FatArrow, . Pound, . Dollar, . Question, . /// Used by proc macros for representing lifetimes, not generated by lexer right now. . SingleQuote, . /// An opening delimiter (e.g., `{`). 98,439 ( 0.00%) OpenDelim(DelimToken), . /// A closing delimiter (e.g., `}`). 31,140 ( 0.00%) CloseDelim(DelimToken), . . /* Literals */ 157,630 ( 0.00%) Literal(Lit), . . /// Identifier token. . /// Do not forget about `NtIdent` when you want to match on identifiers. . /// It's recommended to use `Token::(ident,uninterpolate,uninterpolated_span)` to . /// treat regular and interpolated identifiers in the same way. 1,422,016 ( 0.04%) Ident(Symbol, /* is_raw */ bool), . /// Lifetime identifier token. . /// Do not forget about `NtLifetime` when you want to match on lifetime identifiers. . /// It's recommended to use `Token::(lifetime,uninterpolate,uninterpolated_span)` to . /// treat regular and interpolated lifetime identifiers in the same way. 1,716 ( 0.00%) Lifetime(Symbol), . 45,639 ( 0.00%) Interpolated(Lrc), . . /// A doc comment token. . /// `Symbol` is the doc comment's data excluding its "quotes" (`///`, `/**`, etc) . /// similarly to symbols in string literal tokens. . DocComment(CommentKind, ast::AttrStyle, Symbol), . . Eof, . } . . // `TokenKind` is used a lot. Make sure it doesn't unintentionally get bigger. . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . rustc_data_structures::static_assert_size!(TokenKind, 16); . 10,594,229 ( 0.26%) #[derive(Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub struct Token { 1,156,613 ( 0.03%) pub kind: TokenKind, 37 ( 0.00%) pub span: Span, . } . . impl TokenKind { . pub fn lit(kind: LitKind, symbol: Symbol, suffix: Option) -> TokenKind { . Literal(Lit::new(kind, symbol, suffix)) . } . . // An approximation to proc-macro-style single-character operators used by rustc parser. . // If the operator token can be broken into two tokens, the first of which is single-character, . // then this function performs that operation, otherwise it returns `None`. 5,952 ( 0.00%) pub fn break_two_token_op(&self) -> Option<(TokenKind, TokenKind)> { 36,245 ( 0.00%) Some(match *self { . Le => (Lt, Eq), . EqEq => (Eq, Eq), . Ne => (Not, Eq), . Ge => (Gt, Eq), . AndAnd => (BinOp(And), BinOp(And)), . OrOr => (BinOp(Or), BinOp(Or)), . BinOp(Shl) => (Lt, Lt), . BinOp(Shr) => (Gt, Gt), -- line 271 ---------------------------------------- -- line 280 ---------------------------------------- . BinOpEq(Shl) => (Lt, Le), . BinOpEq(Shr) => (Gt, Ge), . DotDot => (Dot, Dot), . DotDotDot => (Dot, DotDot), . ModSep => (Colon, Colon), . RArrow => (BinOp(Minus), Gt), . LArrow => (Lt, BinOp(Minus)), . FatArrow => (Eq, Gt), 2,844 ( 0.00%) _ => return None, . }) 5,952 ( 0.00%) } . . /// Returns tokens that are likely to be typed accidentally instead of the current token. . /// Enables better error recovery when the wrong token is found. . pub fn similar_tokens(&self) -> Option> { . match *self { . Comma => Some(vec![Dot, Lt, Semi]), . Semi => Some(vec![Colon, Comma]), . FatArrow => Some(vec![Eq, RArrow]), . _ => None, . } . } . . pub fn should_end_const_arg(&self) -> bool { 766 ( 0.00%) matches!(self, Gt | Ge | BinOp(Shr) | BinOpEq(Shr)) 190 ( 0.00%) } . } . . impl Token { 679,965 ( 0.02%) pub fn new(kind: TokenKind, span: Span) -> Self { 2,058,259 ( 0.05%) Token { kind, span } 679,965 ( 0.02%) } . . /// Some token that will be thrown away later. 5,784 ( 0.00%) pub fn dummy() -> Self { . Token::new(TokenKind::Question, DUMMY_SP) 5,784 ( 0.00%) } . . /// Recovers a `Token` from an `Ident`. This creates a raw identifier if necessary. . pub fn from_ast_ident(ident: Ident) -> Self { 184 ( 0.00%) Token::new(Ident(ident.name, ident.is_raw_guess()), ident.span) . } . . /// Return this token by value and leave a dummy token in its place. 9,865 ( 0.00%) pub fn take(&mut self) -> Self { . mem::replace(self, Token::dummy()) 9,865 ( 0.00%) } . . /// For interpolated tokens, returns a span of the fragment to which the interpolated . /// token refers. For all other tokens this is just a regular span. . /// It is particularly important to use this for identifiers and lifetimes . /// for which spans affect name resolution and edition checks. . /// Note that keywords are also identifiers, so they should use this . /// if they keep spans or perform edition checks. . pub fn uninterpolated_span(&self) -> Span { 1,366 ( 0.00%) match &self.kind { 50 ( 0.00%) Interpolated(nt) => nt.span(), 658 ( 0.00%) _ => self.span, . } 658 ( 0.00%) } . . pub fn is_op(&self) -> bool { 29,595 ( 0.00%) !matches!( 9,865 ( 0.00%) self.kind, . OpenDelim(..) . | CloseDelim(..) . | Literal(..) . | DocComment(..) . | Ident(..) . | Lifetime(..) . | Interpolated(..) . | Eof . ) 9,865 ( 0.00%) } . . pub fn is_like_plus(&self) -> bool { 5,862 ( 0.00%) matches!(self.kind, BinOp(Plus) | BinOpEq(Plus)) 1,172 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of an expression. 159 ( 0.00%) pub fn can_begin_expr(&self) -> bool { 795 ( 0.00%) match self.uninterpolate().kind { 1,080 ( 0.00%) Ident(name, is_raw) => 360 ( 0.00%) ident_can_begin_expr(name, self.span, is_raw), // value name or keyword . OpenDelim(..) | // tuple, array or block . Literal(..) | // literal . Not | // operator not . BinOp(Minus) | // unary minus . BinOp(Star) | // dereference . BinOp(Or) | OrOr | // closure . BinOp(And) | // reference . AndAnd | // double reference -- line 371 ---------------------------------------- -- line 376 ---------------------------------------- . Lifetime(..) | // labeled loop . Pound => true, // expression attributes . Interpolated(ref nt) => matches!(**nt, NtLiteral(..) | . NtExpr(..) | . NtBlock(..) | . NtPath(..)), . _ => false, . } 318 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of a type. 1,100 ( 0.00%) pub fn can_begin_type(&self) -> bool { 1,411 ( 0.00%) match self.uninterpolate().kind { 1,197 ( 0.00%) Ident(name, is_raw) => 133 ( 0.00%) ident_can_begin_type(name, self.span, is_raw), // type name or keyword . OpenDelim(Paren) | // tuple . OpenDelim(Bracket) | // array . Not | // never . BinOp(Star) | // raw pointer . BinOp(And) | // reference . AndAnd | // double reference . Question | // maybe bound in trait object . Lifetime(..) | // lifetime bound in trait object . Lt | BinOp(Shl) | // associated path . ModSep => true, // global path . Interpolated(ref nt) => matches!(**nt, NtTy(..) | NtPath(..)), . _ => false, . } 1,650 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of a const param. . pub fn can_begin_const_arg(&self) -> bool { 995 ( 0.00%) match self.kind { . OpenDelim(Brace) => true, . Interpolated(ref nt) => matches!(**nt, NtExpr(..) | NtBlock(..) | NtLiteral(..)), 199 ( 0.00%) _ => self.can_begin_literal_maybe_minus(), . } . } . . /// Returns `true` if the token can appear at the start of a generic bound. . pub fn can_begin_bound(&self) -> bool { . self.is_path_start() . || self.is_lifetime() . || self.is_keyword(kw::For) -- line 419 ---------------------------------------- -- line 427 ---------------------------------------- . } . . /// Returns `true` if the token is any literal, a minus (which can prefix a literal, . /// for example a '-42', or one of the boolean idents). . /// . /// In other words, would this token be a valid start of `parse_literal_maybe_minus`? . /// . /// Keep this in sync with and `Lit::from_token`, excluding unary negation. 210 ( 0.00%) pub fn can_begin_literal_maybe_minus(&self) -> bool { 1,440 ( 0.00%) match self.uninterpolate().kind { . Literal(..) | BinOp(Minus) => true, 312 ( 0.00%) Ident(name, false) if name.is_bool_lit() => true, . Interpolated(ref nt) => match &**nt { . NtLiteral(_) => true, . NtExpr(e) => match &e.kind { . ast::ExprKind::Lit(_) => true, . ast::ExprKind::Unary(ast::UnOp::Neg, e) => { . matches!(&e.kind, ast::ExprKind::Lit(_)) . } . _ => false, . }, . _ => false, . }, . _ => false, . } 420 ( 0.00%) } . . // A convenience function for matching on identifiers during parsing. . // Turns interpolated identifier (`$i: ident`) or lifetime (`$l: lifetime`) token . // into the regular identifier or lifetime token it refers to, . // otherwise returns the original token. 7,797 ( 0.00%) pub fn uninterpolate(&self) -> Cow<'_, Token> { 5,600,211 ( 0.14%) match &self.kind { 19,952 ( 0.00%) Interpolated(nt) => match **nt { 4,919 ( 0.00%) NtIdent(ident, is_raw) => { 12,312 ( 0.00%) Cow::Owned(Token::new(Ident(ident.name, is_raw), ident.span)) . } . NtLifetime(ident) => Cow::Owned(Token::new(Lifetime(ident.name), ident.span)), . _ => Cow::Borrowed(self), . }, . _ => Cow::Borrowed(self), . } 7,797 ( 0.00%) } . . /// Returns an identifier if this token is an identifier. 1,387,094 ( 0.03%) pub fn ident(&self) -> Option<(Ident, /* is_raw */ bool)> { . let token = self.uninterpolate(); 2,865,822 ( 0.07%) match token.kind { 4,499,760 ( 0.11%) Ident(name, is_raw) => Some((Ident::new(name, token.span), is_raw)), . _ => None, . } 8,357,624 ( 0.21%) } . . /// Returns a lifetime identifier if this token is a lifetime. 1,336,722 ( 0.03%) pub fn lifetime(&self) -> Option { . let token = self.uninterpolate(); 2,674,124 ( 0.07%) match token.kind { 4,578 ( 0.00%) Lifetime(name) => Some(Ident::new(name, token.span)), . _ => None, . } 9,357,054 ( 0.23%) } . . /// Returns `true` if the token is an identifier. . pub fn is_ident(&self) -> bool { . self.ident().is_some() 4,150 ( 0.00%) } . . /// Returns `true` if the token is a lifetime. 340 ( 0.00%) pub fn is_lifetime(&self) -> bool { . self.lifetime().is_some() 680 ( 0.00%) } . . /// Returns `true` if the token is an identifier whose name is the given . /// string slice. 2,252 ( 0.00%) pub fn is_ident_named(&self, name: Symbol) -> bool { . self.ident().map_or(false, |(ident, _)| ident.name == name) 4,504 ( 0.00%) } . . /// Returns `true` if the token is an interpolated path. . fn is_path(&self) -> bool { 14,348 ( 0.00%) if let Interpolated(ref nt) = self.kind { 88 ( 0.00%) if let NtPath(..) = **nt { . return true; . } . } . false . } . . /// Would `maybe_whole_expr` in `parser.rs` return `Ok(..)`? . /// That is, is this a pre-parsed expression dropped into the token stream . /// (which happens while parsing the result of macro expansion)? . pub fn is_whole_expr(&self) -> bool { 10 ( 0.00%) if let Interpolated(ref nt) = self.kind { . if let NtExpr(_) | NtLiteral(_) | NtPath(_) | NtIdent(..) | NtBlock(_) = **nt { . return true; . } . } . . false 5 ( 0.00%) } . . // Is the token an interpolated block (`$b:block`)? . pub fn is_whole_block(&self) -> bool { 94 ( 0.00%) if let Interpolated(ref nt) = self.kind { . if let NtBlock(..) = **nt { . return true; . } . } . false 47 ( 0.00%) } . . /// Returns `true` if the token is either the `mut` or `const` keyword. . pub fn is_mutability(&self) -> bool { . self.is_keyword(kw::Mut) || self.is_keyword(kw::Const) . } . 546 ( 0.00%) pub fn is_qpath_start(&self) -> bool { 7,720 ( 0.00%) self == &Lt || self == &BinOp(Shl) . } . 26,776 ( 0.00%) pub fn is_path_start(&self) -> bool { 27,082 ( 0.00%) self == &ModSep . || self.is_qpath_start() . || self.is_path() . || self.is_path_segment_keyword() 3,251 ( 0.00%) || self.is_ident() && !self.is_reserved_ident() 33,470 ( 0.00%) } . . /// Returns `true` if the token is a given keyword, `kw`. 30,118 ( 0.00%) pub fn is_keyword(&self, kw: Symbol) -> bool { . self.is_non_raw_ident_where(|id| id.name == kw) 60,236 ( 0.00%) } . 389 ( 0.00%) pub fn is_path_segment_keyword(&self) -> bool { . self.is_non_raw_ident_where(Ident::is_path_segment_keyword) . } . . // Returns true for reserved identifiers used internally for elided lifetimes, . // unnamed method parameters, crate root module, error recovery etc. 40 ( 0.00%) pub fn is_special_ident(&self) -> bool { . self.is_non_raw_ident_where(Ident::is_special) . } . . /// Returns `true` if the token is a keyword used in the language. 40 ( 0.00%) pub fn is_used_keyword(&self) -> bool { . self.is_non_raw_ident_where(Ident::is_used_keyword) . } . . /// Returns `true` if the token is a keyword reserved for possible future use. 40 ( 0.00%) pub fn is_unused_keyword(&self) -> bool { . self.is_non_raw_ident_where(Ident::is_unused_keyword) . } . . /// Returns `true` if the token is either a special identifier or a keyword. . pub fn is_reserved_ident(&self) -> bool { . self.is_non_raw_ident_where(Ident::is_reserved) . } . . /// Returns `true` if the token is the identifier `true` or `false`. 389 ( 0.00%) pub fn is_bool_lit(&self) -> bool { 778 ( 0.00%) self.is_non_raw_ident_where(|id| id.name.is_bool_lit()) . } . . pub fn is_numeric_lit(&self) -> bool { . matches!( . self.kind, . Literal(Lit { kind: LitKind::Integer, .. }) | Literal(Lit { kind: LitKind::Float, .. }) . ) . } . . /// Returns `true` if the token is a non-raw identifier for which `pred` holds. . pub fn is_non_raw_ident_where(&self, pred: impl FnOnce(Ident) -> bool) -> bool { 282,346 ( 0.01%) match self.ident() { 2,946 ( 0.00%) Some((id, false)) => pred(id), . _ => false, . } . } . 32,470 ( 0.00%) pub fn glue(&self, joint: &Token) -> Option { 16,235 ( 0.00%) let kind = match self.kind { 1,202 ( 0.00%) Eq => match joint.kind { . Eq => EqEq, . Gt => FatArrow, . _ => return None, . }, 3 ( 0.00%) Lt => match joint.kind { . Eq => Le, . Lt => BinOp(Shl), . Le => BinOpEq(Shl), . BinOp(Minus) => LArrow, . _ => return None, . }, 252 ( 0.00%) Gt => match joint.kind { . Eq => Ge, . Gt => BinOp(Shr), . Ge => BinOpEq(Shr), . _ => return None, . }, 4 ( 0.00%) Not => match joint.kind { . Eq => Ne, . _ => return None, . }, 601 ( 0.00%) BinOp(op) => match joint.kind { . Eq => BinOpEq(op), 9 ( 0.00%) BinOp(And) if op == And => AndAnd, 8 ( 0.00%) BinOp(Or) if op == Or => OrOr, 54 ( 0.00%) Gt if op == Minus => RArrow, . _ => return None, . }, 169 ( 0.00%) Dot => match joint.kind { . Dot => DotDot, . DotDot => DotDotDot, . _ => return None, . }, 18 ( 0.00%) DotDot => match joint.kind { . Dot => DotDotDot, . Eq => DotDotEq, . _ => return None, . }, 1,386 ( 0.00%) Colon => match joint.kind { . Colon => ModSep, . _ => return None, . }, . SingleQuote => match joint.kind { . Ident(name, false) => Lifetime(Symbol::intern(&format!("'{}", name))), . _ => return None, . }, . . Le | EqEq | Ne | Ge | AndAnd | OrOr | Tilde | BinOpEq(..) | At | DotDotDot . | DotDotEq | Comma | Semi | ModSep | RArrow | LArrow | FatArrow | Pound | Dollar . | Question | OpenDelim(..) | CloseDelim(..) | Literal(..) | Ident(..) . | Lifetime(..) | Interpolated(..) | DocComment(..) | Eof => return None, . }; . 14,170 ( 0.00%) Some(Token::new(kind, self.span.to(joint.span))) 29,223 ( 0.00%) } . } . . impl PartialEq for Token { . fn eq(&self, rhs: &TokenKind) -> bool { 909,999 ( 0.02%) self.kind == *rhs . } . } . . #[derive(Clone, Encodable, Decodable)] . /// For interpolation during macro expansion. . pub enum Nonterminal { . NtItem(P), . NtBlock(P), -- line 675 ---------------------------------------- -- line 711 ---------------------------------------- . Path, . Vis, . TT, . } . . impl NonterminalKind { . /// The `edition` closure is used to get the edition for the given symbol. Doing . /// `span.edition()` is expensive, so we do it lazily. 312 ( 0.00%) pub fn from_symbol( . symbol: Symbol, . edition: impl FnOnce() -> Edition, . ) -> Option { 742 ( 0.00%) Some(match symbol { . sym::item => NonterminalKind::Item, . sym::block => NonterminalKind::Block, . sym::stmt => NonterminalKind::Stmt, . sym::pat => match edition() { . Edition::Edition2015 | Edition::Edition2018 => { . NonterminalKind::PatParam { inferred: true } . } . Edition::Edition2021 => NonterminalKind::PatWithOr, -- line 731 ---------------------------------------- -- line 737 ---------------------------------------- . sym::lifetime => NonterminalKind::Lifetime, . sym::literal => NonterminalKind::Literal, . sym::meta => NonterminalKind::Meta, . sym::path => NonterminalKind::Path, . sym::vis => NonterminalKind::Vis, . sym::tt => NonterminalKind::TT, . _ => return None, . }) 312 ( 0.00%) } . fn symbol(self) -> Symbol { . match self { . NonterminalKind::Item => sym::item, . NonterminalKind::Block => sym::block, . NonterminalKind::Stmt => sym::stmt, . NonterminalKind::PatParam { inferred: false } => sym::pat_param, . NonterminalKind::PatParam { inferred: true } | NonterminalKind::PatWithOr => sym::pat, . NonterminalKind::Expr => sym::expr, -- line 753 ---------------------------------------- -- line 765 ---------------------------------------- . . impl fmt::Display for NonterminalKind { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . write!(f, "{}", self.symbol()) . } . } . . impl Nonterminal { 25 ( 0.00%) pub fn span(&self) -> Span { 125 ( 0.00%) match self { . NtItem(item) => item.span, . NtBlock(block) => block.span, . NtStmt(stmt) => stmt.span, . NtPat(pat) => pat.span, . NtExpr(expr) | NtLiteral(expr) => expr.span, . NtTy(ty) => ty.span, 25 ( 0.00%) NtIdent(ident, _) | NtLifetime(ident) => ident.span, . NtMeta(attr_item) => attr_item.span(), . NtPath(path) => path.span, . NtVis(vis) => vis.span, . NtTT(tt) => tt.span(), . } 50 ( 0.00%) } . } . . impl PartialEq for Nonterminal { . fn eq(&self, rhs: &Self) -> bool { . match (self, rhs) { . (NtIdent(ident_lhs, is_raw_lhs), NtIdent(ident_rhs, is_raw_rhs)) => { . ident_lhs == ident_rhs && is_raw_lhs == is_raw_rhs . } -- line 795 ---------------------------------------- 25,153,166 ( 0.62%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/boxed.rs -------------------------------------------------------------------------------- Ir -- line 187 ---------------------------------------- . /// ``` . /// let five = Box::new(5); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[inline(always)] . #[stable(feature = "rust1", since = "1.0.0")] . #[must_use] . pub fn new(x: T) -> Self { 805,465 ( 0.02%) box x . } . . /// Constructs a new box with uninitialized contents. . /// . /// # Examples . /// . /// ``` . /// #![feature(new_uninit)] -- line 203 ---------------------------------------- -- line 410 ---------------------------------------- . /// . /// assert_eq!(*five, 5) . /// ``` . #[unstable(feature = "allocator_api", issue = "32838")] . #[rustc_const_unstable(feature = "const_box", issue = "92521")] . #[cfg(not(no_global_oom_handling))] . #[must_use] . // #[unstable(feature = "new_uninit", issue = "63291")] 50 ( 0.00%) pub const fn new_uninit_in(alloc: A) -> Box, A> . where . A: ~const Allocator + ~const Drop, . { . let layout = Layout::new::>(); . // NOTE: Prefer match over unwrap_or_else since closure sometimes not inlineable. . // That would make code size bigger. 50 ( 0.00%) match Box::try_new_uninit_in(alloc) { . Ok(m) => m, . Err(_) => handle_alloc_error(layout), . } 100 ( 0.00%) } . . /// Constructs a new box with uninitialized contents in the provided allocator, . /// returning an error if the allocation fails . /// . /// # Examples . /// . /// ``` . /// #![feature(allocator_api, new_uninit)] -- line 437 ---------------------------------------- -- line 600 ---------------------------------------- . /// }; . /// . /// assert_eq!(*values, [1, 2, 3]) . /// ``` . #[cfg(not(no_global_oom_handling))] . #[unstable(feature = "new_uninit", issue = "63291")] . #[must_use] . pub fn new_uninit_slice(len: usize) -> Box<[mem::MaybeUninit]> { 75 ( 0.00%) unsafe { RawVec::with_capacity(len).into_box(len) } . } . . /// Constructs a new boxed slice with uninitialized contents, with the memory . /// being filled with `0` bytes. . /// . /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage . /// of this method. . /// -- line 616 ---------------------------------------- -- line 688 ---------------------------------------- . #[unstable(feature = "allocator_api", issue = "32838")] . #[inline] . pub fn try_new_zeroed_slice(len: usize) -> Result]>, AllocError> { . unsafe { . let layout = match Layout::array::>(len) { . Ok(l) => l, . Err(_) => return Err(AllocError), . }; 48 ( 0.00%) let ptr = Global.allocate_zeroed(layout)?; . Ok(RawVec::from_raw_parts_in(ptr.as_mut_ptr() as *mut _, len, Global).into_box(len)) . } . } . } . . impl Box<[T], A> { . /// Constructs a new boxed slice with uninitialized contents in the provided allocator. . /// -- line 704 ---------------------------------------- -- line 1215 ---------------------------------------- . /// . /// // The value is the same . /// assert_eq!(x, y); . /// . /// // But they are unique objects . /// assert_ne!(&*x as *const i32, &*y as *const i32); . /// ``` . #[inline] 1,744 ( 0.00%) fn clone(&self) -> Self { . // Pre-allocate memory to allow writing the cloned value directly. 50 ( 0.00%) let mut boxed = Self::new_uninit_in(self.1.clone()); . unsafe { 18,113 ( 0.00%) (**self).write_clone_into_raw(boxed.as_mut_ptr()); . boxed.assume_init() . } 1,962 ( 0.00%) } . . /// Copies `source`'s contents into `self` without creating a new allocation. . /// . /// # Examples . /// . /// ``` . /// let x = Box::new(5); . /// let mut y = Box::new(10); -- line 1238 ---------------------------------------- -- line 1303 ---------------------------------------- . Ord::cmp(&**self, &**other) . } . } . #[stable(feature = "rust1", since = "1.0.0")] . impl Eq for Box {} . . #[stable(feature = "rust1", since = "1.0.0")] . impl Hash for Box { 1,665 ( 0.00%) fn hash(&self, state: &mut H) { 3,818 ( 0.00%) (**self).hash(state); 1,665 ( 0.00%) } . } . . #[stable(feature = "indirect_hasher_impl", since = "1.22.0")] . impl Hasher for Box { . fn finish(&self) -> u64 { . (**self).finish() . } . fn write(&mut self, bytes: &[u8]) { -- line 1321 ---------------------------------------- -- line 1574 ---------------------------------------- . /// . /// let my_string = "Hello World".to_string(); . /// print_if_string(Box::new(my_string)); . /// print_if_string(Box::new(0i8)); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn downcast(self) -> Result, Self> { 1 ( 0.00%) if self.is::() { unsafe { Ok(self.downcast_unchecked::()) } } else { Err(self) } . } . . /// Downcasts the box to a concrete type. . /// . /// For a safe alternative see [`downcast`]. . /// . /// # Examples . /// -- line 1590 ---------------------------------------- -- line 1633 ---------------------------------------- . /// . /// let my_string = "Hello World".to_string(); . /// print_if_string(Box::new(my_string)); . /// print_if_string(Box::new(0i8)); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn downcast(self) -> Result, Self> { 1 ( 0.00%) if self.is::() { unsafe { Ok(self.downcast_unchecked::()) } } else { Err(self) } . } . . /// Downcasts the box to a concrete type. . /// . /// For a safe alternative see [`downcast`]. . /// . /// # Examples . /// -- line 1649 ---------------------------------------- -- line 1769 ---------------------------------------- . &**self . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_box", issue = "92521")] . impl const DerefMut for Box { . fn deref_mut(&mut self) -> &mut T { 1 ( 0.00%) &mut **self . } . } . . #[unstable(feature = "receiver_trait", issue = "none")] . impl Receiver for Box {} . . #[stable(feature = "rust1", since = "1.0.0")] . impl Iterator for Box { . type Item = I::Item; . fn next(&mut self) -> Option { 595 ( 0.00%) (**self).next() . } . fn size_hint(&self) -> (usize, Option) { . (**self).size_hint() . } . fn nth(&mut self, n: usize) -> Option { . (**self).nth(n) . } . fn last(self) -> Option { -- line 1796 ---------------------------------------- -- line 1846 ---------------------------------------- . #[stable(feature = "fused", since = "1.26.0")] . impl FusedIterator for Box {} . . #[stable(feature = "boxed_closure_impls", since = "1.35.0")] . impl + ?Sized, A: Allocator> FnOnce for Box { . type Output = >::Output; . . extern "rust-call" fn call_once(self, args: Args) -> Self::Output { 12 ( 0.00%) >::call_once(*self, args) . } . } . . #[stable(feature = "boxed_closure_impls", since = "1.35.0")] . impl + ?Sized, A: Allocator> FnMut for Box { . extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output { 4 ( 0.00%) >::call_mut(self, args) . } . } . . #[stable(feature = "boxed_closure_impls", since = "1.35.0")] . impl + ?Sized, A: Allocator> Fn for Box { . extern "rust-call" fn call(&self, args: Args) -> Self::Output { 37,449 ( 0.00%) >::call(self, args) . } . } . . #[unstable(feature = "coerce_unsized", issue = "27732")] . impl, U: ?Sized, A: Allocator> CoerceUnsized> for Box {} . . #[unstable(feature = "dispatch_from_dyn", issue = "none")] . impl, U: ?Sized> DispatchFromDyn> for Box {} . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "boxed_slice_from_iter", since = "1.32.0")] . impl FromIterator for Box<[I]> { 1,739 ( 0.00%) fn from_iter>(iter: T) -> Self { . iter.into_iter().collect::>().into_boxed_slice() 2,099 ( 0.00%) } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "box_slice_clone", since = "1.3.0")] . impl Clone for Box<[T], A> { 2,648,064 ( 0.07%) fn clone(&self) -> Self { . let alloc = Box::allocator(self).clone(); 1,324,032 ( 0.03%) self.to_vec_in(alloc).into_boxed_slice() 3,972,096 ( 0.10%) } . . fn clone_from(&mut self, other: &Self) { . if self.len() == other.len() { . self.clone_from_slice(&other); . } else { . *self = other.clone(); . } . } . } . . #[stable(feature = "box_borrow", since = "1.1.0")] . impl borrow::Borrow for Box { . fn borrow(&self) -> &T { 791 ( 0.00%) &**self . } . } . . #[stable(feature = "box_borrow", since = "1.1.0")] . impl borrow::BorrowMut for Box { . fn borrow_mut(&mut self) -> &mut T { 785 ( 0.00%) &mut **self . } . } . . #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")] . impl AsRef for Box { . fn as_ref(&self) -> &T { 2,684 ( 0.00%) &**self . } . } . . #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")] . impl AsMut for Box { . fn as_mut(&mut self) -> &mut T { . &mut **self . } -- line 1928 ---------------------------------------- 5,355,083 ( 0.13%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs -------------------------------------------------------------------------------- Ir -- line 417 ---------------------------------------- . /// # #![allow(unused_mut)] . /// let mut vec: Vec = Vec::new(); . /// ``` . #[inline] . #[rustc_const_stable(feature = "const_vec_new", since = "1.39.0")] . #[stable(feature = "rust1", since = "1.0.0")] . #[must_use] . pub const fn new() -> Self { 2,550,379 ( 0.06%) Vec { buf: RawVec::NEW, len: 0 } 1,523 ( 0.00%) } . . /// Constructs a new, empty `Vec` with the specified capacity. . /// . /// The vector will be able to hold exactly `capacity` elements without . /// reallocating. If `capacity` is 0, the vector will not allocate. . /// . /// It is important to note that although the returned vector has the . /// *capacity* specified, the vector will have a zero *length*. For an -- line 434 ---------------------------------------- -- line 601 ---------------------------------------- . /// vec.push(11); . /// assert_eq!(vec.len(), 11); . /// assert!(vec.capacity() >= 11); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[inline] . #[unstable(feature = "allocator_api", issue = "32838")] . pub fn with_capacity_in(capacity: usize, alloc: A) -> Self { 2,213,210 ( 0.05%) Vec { buf: RawVec::with_capacity_in(capacity, alloc), len: 0 } . } . . /// Creates a `Vec` directly from the raw components of another vector. . /// . /// # Safety . /// . /// This is highly unsafe, due to the number of invariants that aren't . /// checked: -- line 617 ---------------------------------------- -- line 677 ---------------------------------------- . /// // Put everything back together into a Vec . /// let rebuilt = Vec::from_raw_parts_in(p, len, cap, alloc.clone()); . /// assert_eq!(rebuilt, [4, 5, 6]); . /// } . /// ``` . #[inline] . #[unstable(feature = "allocator_api", issue = "32838")] . pub unsafe fn from_raw_parts_in(ptr: *mut T, length: usize, capacity: usize, alloc: A) -> Self { 73,666 ( 0.00%) unsafe { Vec { buf: RawVec::from_raw_parts_in(ptr, capacity, alloc), len: length } } . } . . /// Decomposes a `Vec` into its raw components. . /// . /// Returns the raw pointer to the underlying data, the length of . /// the vector (in elements), and the allocated capacity of the . /// data (in elements). These are the same arguments in the same . /// order as the arguments to [`from_raw_parts`]. -- line 693 ---------------------------------------- -- line 778 ---------------------------------------- . /// . /// ``` . /// let vec: Vec = Vec::with_capacity(10); . /// assert_eq!(vec.capacity(), 10); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn capacity(&self) -> usize { 675,693 ( 0.02%) self.buf.capacity() . } . . /// Reserves capacity for at least `additional` more elements to be inserted . /// in the given `Vec`. The collection may reserve more space to avoid . /// frequent reallocations. After calling `reserve`, capacity will be . /// greater than or equal to `self.len() + additional`. Does nothing if . /// capacity is already sufficient. . /// -- line 794 ---------------------------------------- -- line 801 ---------------------------------------- . /// ``` . /// let mut vec = vec![1]; . /// vec.reserve(10); . /// assert!(vec.capacity() >= 11); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn reserve(&mut self, additional: usize) { 286,344 ( 0.01%) self.buf.reserve(self.len, additional); . } . . /// Reserves the minimum capacity for exactly `additional` more elements to . /// be inserted in the given `Vec`. After calling `reserve_exact`, . /// capacity will be greater than or equal to `self.len() + additional`. . /// Does nothing if the capacity is already sufficient. . /// . /// Note that the allocator may give the collection more space than it -- line 817 ---------------------------------------- -- line 829 ---------------------------------------- . /// ``` . /// let mut vec = vec![1]; . /// vec.reserve_exact(10); . /// assert!(vec.capacity() >= 11); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn reserve_exact(&mut self, additional: usize) { 5,369 ( 0.00%) self.buf.reserve_exact(self.len, additional); . } . . /// Tries to reserve capacity for at least `additional` more elements to be inserted . /// in the given `Vec`. The collection may reserve more space to avoid . /// frequent reallocations. After calling `try_reserve`, capacity will be . /// greater than or equal to `self.len() + additional`. Does nothing if . /// capacity is already sufficient. . /// -- line 845 ---------------------------------------- -- line 930 ---------------------------------------- . /// assert!(vec.capacity() >= 3); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn shrink_to_fit(&mut self) { . // The capacity is never less than the length, and there's nothing to do when . // they are equal, so we can avoid the panic case in `RawVec::shrink_to_fit` . // by only calling it with a greater capacity. 1,420,149 ( 0.04%) if self.capacity() > self.len { 4,877 ( 0.00%) self.buf.shrink_to_fit(self.len); . } . } . . /// Shrinks the capacity of the vector with a lower bound. . /// . /// The capacity will remain at least as large as both the length . /// and the supplied value. . /// -- line 947 ---------------------------------------- -- line 990 ---------------------------------------- . /// let slice = vec.into_boxed_slice(); . /// assert_eq!(slice.into_vec().capacity(), 3); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn into_boxed_slice(mut self) -> Box<[T], A> { . unsafe { . self.shrink_to_fit(); 688,384 ( 0.02%) let me = ManuallyDrop::new(self); . let buf = ptr::read(&me.buf); . let len = me.len(); . buf.into_box(len).assume_init() . } . } . . /// Shortens the vector, keeping the first `len` elements and dropping . /// the rest. -- line 1006 ---------------------------------------- -- line 1040 ---------------------------------------- . /// let mut vec = vec![1, 2, 3]; . /// vec.truncate(0); . /// assert_eq!(vec, []); . /// ``` . /// . /// [`clear`]: Vec::clear . /// [`drain`]: Vec::drain . #[stable(feature = "rust1", since = "1.0.0")] 16,169,467 ( 0.40%) pub fn truncate(&mut self, len: usize) { . // This is safe because: . // . // * the slice passed to `drop_in_place` is valid; the `len > self.len` . // case avoids creating an invalid slice, and . // * the `len` of the vector is shrunk before calling `drop_in_place`, . // such that no value will be dropped twice in case `drop_in_place` . // were to panic once (if it panics twice, the program aborts). . unsafe { . // Note: It's intentional that this is `>` and not `>=`. . // Changing it to `>=` has negative performance . // implications in some cases. See #78884 for more. 9,735,659 ( 0.24%) if len > self.len { . return; . } . let remaining_len = self.len - len; . let s = ptr::slice_from_raw_parts_mut(self.as_mut_ptr().add(len), remaining_len); 3,359,038 ( 0.08%) self.len = len; 4,352 ( 0.00%) ptr::drop_in_place(s); . } 19,403,360 ( 0.48%) } . . /// Extracts a slice containing the entire vector. . /// . /// Equivalent to `&s[..]`. . /// . /// # Examples . /// . /// ``` -- line 1076 ---------------------------------------- -- line 1126 ---------------------------------------- . /// ``` . /// . /// [`as_mut_ptr`]: Vec::as_mut_ptr . #[stable(feature = "vec_as_ptr", since = "1.37.0")] . #[inline] . pub fn as_ptr(&self) -> *const T { . // We shadow the slice method of the same name to avoid going through . // `deref`, which creates an intermediate reference. 7,099,594 ( 0.18%) let ptr = self.buf.ptr(); . unsafe { . assume(!ptr.is_null()); . } . ptr . } . . /// Returns an unsafe mutable pointer to the vector's buffer. . /// -- line 1142 ---------------------------------------- -- line 1162 ---------------------------------------- . /// } . /// assert_eq!(&*x, &[0, 1, 2, 3]); . /// ``` . #[stable(feature = "vec_as_ptr", since = "1.37.0")] . #[inline] . pub fn as_mut_ptr(&mut self) -> *mut T { . // We shadow the slice method of the same name to avoid going through . // `deref_mut`, which creates an intermediate reference. 6,410,251 ( 0.16%) let ptr = self.buf.ptr(); . unsafe { . assume(!ptr.is_null()); . } . ptr . } . . /// Returns a reference to the underlying allocator. . #[unstable(feature = "allocator_api", issue = "32838")] -- line 1178 ---------------------------------------- -- line 1259 ---------------------------------------- . /// . /// Normally, here, one would use [`clear`] instead to correctly drop . /// the contents and thus not leak memory. . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub unsafe fn set_len(&mut self, new_len: usize) { . debug_assert!(new_len <= self.capacity()); . 1,020,475 ( 0.03%) self.len = new_len; 160 ( 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(); 6 ( 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")] 3,997 ( 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); . } . 572 ( 0.00%) let len = self.len(); 1,340 ( 0.00%) if index > len { . assert_failed(index, len); . } . . // space for the new element 1,414 ( 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.) 2,118 ( 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); . } 1,414 ( 0.00%) self.set_len(len + 1); . } 3,426 ( 0.00%) } . . /// Removes and returns the element at position `index` within the vector, . /// shifting all elements after it to the left. . /// . /// Note: Because this shifts over the remaining elements, it has a . /// worst-case performance of *O*(*n*). If you don't need the order of elements . /// to be preserved, use [`swap_remove`] instead. If you'd like to remove . /// elements from the beginning of the `Vec`, consider using -- line 1376 ---------------------------------------- -- line 1395 ---------------------------------------- . pub fn remove(&mut self, index: usize) -> T { . #[cold] . #[inline(never)] . #[track_caller] . fn assert_failed(index: usize, len: usize) -> ! { . panic!("removal index (is {}) should be < len (is {})", index, len); . } . 310 ( 0.00%) let len = self.len(); 1,237 ( 0.00%) if index >= len { . assert_failed(index, len); . } . unsafe { . // infallible . let ret; . { . // the place we are taking from. . let ptr = self.as_mut_ptr().add(index); . // copy it out, unsafely having a copy of the value on . // the stack and in the vector at the same time. 48 ( 0.00%) ret = ptr::read(ptr); . . // Shift everything down to fill in that spot. 816 ( 0.00%) ptr::copy(ptr.offset(1), ptr, len - index - 1); . } 455 ( 0.00%) self.set_len(len - 1); . ret . } . } . . /// Retains only the elements specified by the predicate. . /// . /// In other words, remove all elements `e` such that `f(&e)` returns `false`. . /// This method operates in place, visiting each element exactly once in the -- line 1428 ---------------------------------------- -- line 1442 ---------------------------------------- . /// ``` . /// let mut vec = vec![1, 2, 3, 4, 5]; . /// let keep = [false, true, true, false, true]; . /// let mut iter = keep.iter(); . /// vec.retain(|_| *iter.next().unwrap()); . /// assert_eq!(vec, [2, 3, 5]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 316,789 ( 0.01%) pub fn retain(&mut self, mut f: F) . where . F: FnMut(&T) -> bool, . { 51,203 ( 0.00%) self.retain_mut(|elem| f(elem)); 298,832 ( 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, . { 37,599 ( 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) { 37,010 ( 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), 35,111 ( 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, . { 315,151 ( 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) }; 74,675 ( 0.00%) if !f(cur) { . // Advance early to avoid double drop if `drop_in_place` panicked. 656 ( 0.00%) g.processed_len += 1; 256 ( 0.00%) g.deleted_cnt += 1; . // SAFETY: We never touch this element again after dropped. 216 ( 0.00%) unsafe { ptr::drop_in_place(cur) }; . // We already advanced the counter. . if DELETED { . continue; . } else { . break; . } . } . if DELETED { . // SAFETY: `deleted_cnt` > 0, so the hole slot must not overlap with current element. . // We use copy for move, and never touch this element again. . unsafe { 1,665 ( 0.00%) let hole_slot = g.v.as_mut_ptr().add(g.processed_len - g.deleted_cnt); . ptr::copy_nonoverlapping(cur, hole_slot, 1); . } . } 1,110 ( 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")] 28 ( 0.00%) pub fn dedup_by(&mut self, mut same_bucket: F) . where . F: FnMut(&mut T, &mut T) -> bool, . { 4 ( 0.00%) let len = self.len(); 716 ( 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 { 1,158 ( 0.00%) while gap.read < len { . let read_ptr = ptr.add(gap.read); . let prev_ptr = ptr.add(gap.write.wrapping_sub(1)); . 562 ( 0.00%) if same_bucket(&mut *read_ptr, &mut *prev_ptr) { . // Increase `gap.read` now since the drop may panic. . gap.read += 1; . /* We have found duplicate, drop it in-place */ . ptr::drop_in_place(read_ptr); . } else { . let write_ptr = ptr.add(gap.write); . . /* Because `read_ptr` can be equal to `write_ptr`, we either . * have to use `copy` or conditional `copy_nonoverlapping`. . * Looks like the first option is faster. */ . ptr::copy(read_ptr, write_ptr, 1); . . /* We have filled that place, so go further */ 392 ( 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); . } 32 ( 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")] 145 ( 0.00%) pub fn push(&mut self, value: T) { . // This will panic or abort if we would allocate > isize::MAX bytes . // or if the length increment would overflow for zero-sized types. 5,004,420 ( 0.12%) if self.len == self.buf.capacity() { 285,044 ( 0.01%) self.buf.reserve_for_push(self.len); . } . unsafe { 137,984 ( 0.00%) let end = self.as_mut_ptr().add(self.len); . ptr::write(end, value); 6,852,606 ( 0.17%) self.len += 1; . } 116 ( 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 { 2,159,487 ( 0.05%) if self.len == 0 { 42 ( 0.00%) None . } else { . unsafe { 1,510,219 ( 0.04%) self.len -= 1; 187,601 ( 0.00%) Some(ptr::read(self.as_ptr().add(self.len()))) . } . } . } . . /// Moves all the elements of `other` into `Self`, leaving `other` empty. . /// . /// # Panics . /// -- line 1769 ---------------------------------------- -- line 1776 ---------------------------------------- . /// let mut vec2 = vec![4, 5, 6]; . /// vec.append(&mut vec2); . /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]); . /// assert_eq!(vec2, []); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[inline] . #[stable(feature = "append", since = "1.4.0")] 448 ( 0.00%) pub fn append(&mut self, other: &mut Self) { . unsafe { . self.append_elements(other.as_slice() as _); . other.set_len(0); . } 384 ( 0.00%) } . . /// Appends elements to `Self` from other buffer. . #[cfg(not(no_global_oom_handling))] . #[inline] . unsafe fn append_elements(&mut self, other: *const [T]) { . let count = unsafe { (*other).len() }; . self.reserve(count); 44,782 ( 0.00%) let len = self.len(); . unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) }; 221,453 ( 0.01%) self.len += count; . } . . /// Creates a draining iterator that removes the specified range in the vector . /// and yields the removed items. . /// . /// When the iterator **is** dropped, all elements in the range are removed . /// from the vector, even if the iterator was not fully consumed. If the . /// iterator **is not** dropped (with [`mem::forget`] for example), it is -- line 1807 ---------------------------------------- -- line 1834 ---------------------------------------- . // When the Drain is first created, it shortens the length of . // the source vector to make sure no uninitialized or moved-from elements . // are accessible at all if the Drain's destructor never gets to run. . // . // Drain will ptr::read out the values to remove. . // When finished, remaining tail of the vec is copied back to cover . // the hole, and the vector length is restored to the new length. . // 10,352 ( 0.00%) let len = self.len(); . let Range { start, end } = slice::range(range, ..len); . . unsafe { . // set self.vec length's to start, to be safe in case Drain is leaked . self.set_len(start); . // Use the borrow in the IterMut to indicate borrowing behavior of the . // whole Drain iterator (like &mut T). 6 ( 0.00%) let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start), end - start); 93,621 ( 0.00%) Drain { . tail_start: end, 6 ( 0.00%) tail_len: len - end, . iter: range_slice.iter(), . vec: NonNull::from(self), . } . } . } . . /// Clears the vector, removing all values. . /// -- line 1861 ---------------------------------------- -- line 1869 ---------------------------------------- . /// . /// v.clear(); . /// . /// assert!(v.is_empty()); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn clear(&mut self) { 29,101,632 ( 0.72%) self.truncate(0) . } . . /// Returns the number of elements in the vector, also referred to . /// as its 'length'. . /// . /// # Examples . /// . /// ``` -- line 1885 ---------------------------------------- -- line 1900 ---------------------------------------- . /// let mut v = Vec::new(); . /// assert!(v.is_empty()); . /// . /// v.push(1); . /// assert!(!v.is_empty()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn is_empty(&self) -> bool { 1,081,409 ( 0.03%) self.len() == 0 . } . . /// Splits the collection into two at the given index. . /// . /// Returns a newly allocated vector containing the elements in the range . /// `[at, len)`. After the call, the original vector will be left containing . /// the elements `[0, at)` with its previous capacity unchanged. . /// -- line 1916 ---------------------------------------- -- line 1935 ---------------------------------------- . A: Clone, . { . #[cold] . #[inline(never)] . fn assert_failed(at: usize, len: usize) -> ! { . panic!("`at` split index (is {}) should be <= len (is {})", at, len); . } . 562 ( 0.00%) if at > self.len() { . assert_failed(at, self.len()); . } . 434 ( 0.00%) if at == 0 { . // the new vector can take over the original buffer and avoid the copy . return mem::replace( . self, . Vec::with_capacity_in(self.capacity(), self.allocator().clone()), . ); . } . . let other_len = self.len - at; -- line 1955 ---------------------------------------- -- line 1988 ---------------------------------------- . /// . /// let mut vec = vec![]; . /// let mut p = 1; . /// vec.resize_with(4, || { p *= 2; p }); . /// assert_eq!(vec, [2, 4, 8, 16]); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "vec_resize_with", since = "1.33.0")] 25,559 ( 0.00%) pub fn resize_with(&mut self, new_len: usize, f: F) . where . F: FnMut() -> T, . { 3,225 ( 0.00%) let len = self.len(); 6,450 ( 0.00%) if new_len > len { 21,141 ( 0.00%) self.extend_with(new_len - len, ExtendFunc(f)); . } else { . self.truncate(new_len); . } 22,334 ( 0.00%) } . . /// Consumes and leaks the `Vec`, returning a mutable reference to the contents, . /// `&'a mut [T]`. Note that the type `T` must outlive the chosen lifetime . /// `'a`. If the type has only static references, or none at all, then this . /// may be chosen to be `'static`. . /// . /// As of Rust 1.57, this method does not reallocate or shrink the `Vec`, . /// so the leaked allocation may include unused capacity that is not part -- line 2014 ---------------------------------------- -- line 2070 ---------------------------------------- . #[stable(feature = "vec_spare_capacity", since = "1.60.0")] . #[inline] . pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit] { . // Note: . // This method is not implemented in terms of `split_at_spare_mut`, . // to prevent invalidation of pointers to the buffer. . unsafe { . slice::from_raw_parts_mut( 2 ( 0.00%) self.as_mut_ptr().add(self.len) as *mut MaybeUninit, 63 ( 0.00%) self.buf.capacity() - self.len, . ) . } . } . . /// Returns vector content as a slice of `T`, along with the remaining spare . /// capacity of the vector as a slice of `MaybeUninit`. . /// . /// The returned spare capacity slice can be used to fill the vector with data -- line 2087 ---------------------------------------- -- line 2189 ---------------------------------------- . /// assert_eq!(vec, ["hello", "world", "world"]); . /// . /// let mut vec = vec![1, 2, 3, 4]; . /// vec.resize(2, 0); . /// assert_eq!(vec, [1, 2]); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "vec_resize", since = "1.5.0")] 90 ( 0.00%) pub fn resize(&mut self, new_len: usize, value: T) { 9 ( 0.00%) let len = self.len(); . 27 ( 0.00%) if new_len > len { 2,151 ( 0.00%) self.extend_with(new_len - len, ExtendElement(value)) . } else { . self.truncate(new_len); . } 9 ( 0.00%) } . . /// Clones and appends all elements in a slice to the `Vec`. . /// . /// Iterates over the slice `other`, clones each element, and then appends . /// it to this `Vec`. The `other` slice is traversed in-order. . /// . /// Note that this function is same as [`extend`] except that it is . /// specialized to work with slices instead. If and when Rust gets -- line 2213 ---------------------------------------- -- line 2271 ---------------------------------------- . trait ExtendWith { . fn next(&mut self) -> T; . fn last(self) -> T; . } . . struct ExtendElement(T); . impl ExtendWith for ExtendElement { . fn next(&mut self) -> T { 23 ( 0.00%) self.0.clone() . } . fn last(self) -> T { . self.0 . } . } . . struct ExtendFunc(F); . impl T> ExtendWith for ExtendFunc { -- line 2287 ---------------------------------------- -- line 2291 ---------------------------------------- . fn last(mut self) -> T { . (self.0)() . } . } . . impl Vec { . #[cfg(not(no_global_oom_handling))] . /// Extend the vector by `n` values, using the given generator. 336,063 ( 0.01%) fn extend_with>(&mut self, n: usize, mut value: E) { . self.reserve(n); . . unsafe { 4,212 ( 0.00%) let mut ptr = self.as_mut_ptr().add(self.len()); . // Use SetLenOnDrop to work around bug where compiler . // might not realize the store through `ptr` through self.set_len() . // don't alias. . let mut local_len = SetLenOnDrop::new(&mut self.len); . . // Write all elements except the last one . for _ in 1..n { . ptr::write(ptr, value.next()); . ptr = ptr.offset(1); . // Increment the length in every step in case next() panics . local_len.increment_len(1); . } . 185,269 ( 0.00%) if n > 0 { . // We can write the last element directly without cloning needlessly . ptr::write(ptr, value.last()); . local_len.increment_len(1); . } . . // len set by scope guard . } 250,701 ( 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) { 5 ( 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")] 22,016 ( 0.00%) pub fn from_elem(elem: T, n: usize) -> Vec { 301,273 ( 0.01%) ::from_elem(elem, n, Global) 31,100 ( 0.00%) } . . #[doc(hidden)] . #[cfg(not(no_global_oom_handling))] . #[unstable(feature = "allocator_api", issue = "32838")] . pub fn from_elem_in(elem: T, n: usize, alloc: A) -> Vec { . ::from_elem(elem, n, alloc) . } . -- line 2367 ---------------------------------------- -- line 2424 ---------------------------------------- . // Common trait implementations for Vec . //////////////////////////////////////////////////////////////////////////////// . . #[stable(feature = "rust1", since = "1.0.0")] . impl ops::Deref for Vec { . type Target = [T]; . . fn deref(&self) -> &[T] { 7,751,914 ( 0.19%) unsafe { slice::from_raw_parts(self.as_ptr(), self.len) } 24 ( 0.00%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl ops::DerefMut for Vec { . fn deref_mut(&mut self) -> &mut [T] { 1,660,148 ( 0.04%) unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) } . } . } . . #[cfg(not(no_global_oom_handling))] . trait SpecCloneFrom { . fn clone_from(this: &mut Self, other: &Self); . } . -- line 2447 ---------------------------------------- -- line 2468 ---------------------------------------- . this.extend_from_slice(other); . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl Clone for Vec { . #[cfg(not(test))] 334,756 ( 0.01%) fn clone(&self) -> Self { . let alloc = self.allocator().clone(); 2 ( 0.00%) <[T]>::to_vec_in(&**self, alloc) 403,977 ( 0.01%) } . . // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is . // required for this method definition, is not available. Instead use the . // `slice::to_vec` function which is only available with cfg(test) . // NB see the slice::hack module in slice.rs for more information . #[cfg(test)] . fn clone(&self) -> Self { . let alloc = self.allocator().clone(); -- line 2487 ---------------------------------------- -- line 2518 ---------------------------------------- . message = "vector indices are of type `usize` or ranges of `usize`", . label = "vector indices are of type `usize` or ranges of `usize`" . )] . impl, A: Allocator> Index for Vec { . type Output = I::Output; . . #[inline] . fn index(&self, index: I) -> &Self::Output { 231,585 ( 0.01%) Index::index(&**self, index) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_on_unimplemented( . message = "vector indices are of type `usize` or ranges of `usize`", . label = "vector indices are of type `usize` or ranges of `usize`" . )] . impl, A: Allocator> IndexMut for Vec { . #[inline] . fn index_mut(&mut self, index: I) -> &mut Self::Output { 76 ( 0.00%) IndexMut::index_mut(&mut **self, index) . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl FromIterator for Vec { . #[inline] . fn from_iter>(iter: I) -> Vec { 1,169,479 ( 0.03%) >::from_iter(iter.into_iter()) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl IntoIterator for Vec { . type Item = T; . type IntoIter = IntoIter; . -- line 2555 ---------------------------------------- -- line 2564 ---------------------------------------- . /// for s in v.into_iter() { . /// // s has type String, not &String . /// println!("{}", s); . /// } . /// ``` . #[inline] . fn into_iter(self) -> IntoIter { . unsafe { 472,985 ( 0.01%) let mut me = ManuallyDrop::new(self); . let alloc = ptr::read(me.allocator()); . let begin = me.as_mut_ptr(); . let end = if mem::size_of::() == 0 { . arith_offset(begin as *const i8, me.len() as isize) as *const T . } else { . begin.add(me.len()) as *const T . }; . let cap = me.buf.capacity(); 133,160 ( 0.00%) IntoIter { . buf: NonNull::new_unchecked(begin), . phantom: PhantomData, . cap, . alloc, . ptr: begin, . end, . } . } -- line 2589 ---------------------------------------- -- line 2591 ---------------------------------------- . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl<'a, T, A: Allocator> IntoIterator for &'a Vec { . type Item = &'a T; . type IntoIter = slice::Iter<'a, T>; . . fn into_iter(self) -> slice::Iter<'a, T> { 56 ( 0.00%) self.iter() . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl<'a, T, A: Allocator> IntoIterator for &'a mut Vec { . type Item = &'a mut T; . type IntoIter = slice::IterMut<'a, T>; . . fn into_iter(self) -> slice::IterMut<'a, T> { 1,076 ( 0.00%) self.iter_mut() . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl Extend for Vec { . #[inline] 832 ( 0.00%) fn extend>(&mut self, iter: I) { 646,929 ( 0.02%) >::spec_extend(self, iter.into_iter()) 832 ( 0.00%) } . . #[inline] . fn extend_one(&mut self, item: T) { . self.push(item); . } . . #[inline] . fn extend_reserve(&mut self, additional: usize) { -- line 2627 ---------------------------------------- -- line 2636 ---------------------------------------- . fn extend_desugared>(&mut self, mut iterator: I) { . // This is the case for a general iterator. . // . // This function should be the moral equivalent of: . // . // for item in iterator { . // self.push(item); . // } 35,620 ( 0.00%) while let Some(element) = iterator.next() { 17,767 ( 0.00%) let len = self.len(); 331,034 ( 0.01%) if len == self.capacity() { 289 ( 0.00%) let (lower, _) = iterator.size_hint(); . self.reserve(lower.saturating_add(1)); . } . unsafe { . ptr::write(self.as_mut_ptr().add(len), element); . // Since next() executes user code which can panic we have to bump the length . // after each step. . // NB can't overflow since we would have had to alloc the address space 202,400 ( 0.01%) self.set_len(len + 1); . } . } 4,486 ( 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, . { 320 ( 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, . { 1,330 ( 0.00%) let old_len = self.len(); . . // Guard against us getting leaked (leak amplification) . unsafe { . self.set_len(0); . } . 4,960 ( 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 { 868,932 ( 0.02%) 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 371,025 ( 0.01%) ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len)) . } . // RawVec handles deallocation 1,028,812 ( 0.03%) } . } . . #[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 ---------------------------------------- 1,333,788 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe/macro_parser.rs -------------------------------------------------------------------------------- Ir -- line 90 ---------------------------------------- . use std::collections::hash_map::Entry::{Occupied, Vacant}; . use std::mem; . use std::ops::{Deref, DerefMut}; . . // To avoid costly uniqueness checks, we require that `MatchSeq` always has a nonempty body. . . /// Either a sequence of token trees or a single one. This is used as the representation of the . /// sequence of tokens that make up a matcher. 7,885,609 ( 0.20%) #[derive(Clone)] . enum TokenTreeOrTokenTreeSlice<'tt> { . Tt(TokenTree), 1,969,140 ( 0.05%) TtSeq(&'tt [TokenTree]), . } . . impl<'tt> TokenTreeOrTokenTreeSlice<'tt> { . /// Returns the number of constituent top-level token trees of `self` (top-level in that it . /// will not recursively descend into subtrees). . fn len(&self) -> usize { 13,396,393 ( 0.33%) match *self { 48,362 ( 0.00%) TtSeq(ref v) => v.len(), . Tt(ref tt) => tt.len(), . } . } . . /// The `index`-th token tree of `self`. . fn get_tt(&self, index: usize) -> TokenTree { 2,640,692 ( 0.07%) match *self { 60,916 ( 0.00%) TtSeq(ref v) => v[index].clone(), 7,289,278 ( 0.18%) Tt(ref tt) => tt.get_tt(index), . } . } . } . . /// An unzipping of `TokenTree`s... see the `stack` field of `MatcherPos`. . /// . /// This is used by `inner_parse_loop` to keep track of delimited submatchers that we have . /// descended into. 1,307,194 ( 0.03%) #[derive(Clone)] . struct MatcherTtFrame<'tt> { . /// The "parent" matcher that we are descending into. . elts: TokenTreeOrTokenTreeSlice<'tt>, . /// The position of the "dot" in `elts` at the time we descended. 653,597 ( 0.02%) idx: usize, . } . . type NamedMatchVec = SmallVec<[NamedMatch; 4]>; . . /// Represents a single "position" (aka "matcher position", aka "item"), as . /// described in the module documentation. . /// . /// Here: -- line 140 ---------------------------------------- -- line 147 ---------------------------------------- . /// position refers to. . /// . /// It is important to distinguish these two lifetimes because we have a . /// `SmallVec>` below, and the destructor of . /// that is considered to possibly access the data from its elements (it lacks . /// a `#[may_dangle]` attribute). As a result, the compiler needs to know that . /// all the elements in that `SmallVec` strictly outlive the root stack slot . /// lifetime. By separating `'tt` from `'root`, we can show that. 31,114,752 ( 0.77%) #[derive(Clone)] . struct MatcherPos<'root, 'tt> { . /// The token or sequence of tokens that make up the matcher . top_elts: TokenTreeOrTokenTreeSlice<'tt>, . . /// The position of the "dot" in this matcher 662,016 ( 0.02%) idx: usize, . . /// For each named metavar in the matcher, we keep track of token trees matched against the . /// metavar by the black box parser. In particular, there may be more than one match per . /// metavar if we are in a repetition (each repetition matches each of the variables). . /// Moreover, matchers and repetitions can be nested; the `matches` field is shared (hence the . /// `Rc`) among all "nested" matchers. `match_lo`, `match_cur`, and `match_hi` keep track of . /// the current position of the `self` matcher position in the shared `matches` list. . /// . /// Also, note that while we are descending into a sequence, matchers are given their own . /// `matches` vector. Only once we reach the end of a full repetition of the sequence do we add . /// all bound matches from the submatcher into the shared top-level `matches` vector. If `sep` . /// and `up` are `Some`, then `matches` is _not_ the shared top-level list. Instead, if one . /// wants the shared `matches`, one should use `up.matches`. 2,648,064 ( 0.07%) matches: Box<[Lrc]>, . /// The position in `matches` corresponding to the first metavar in this matcher's sequence of . /// token trees. In other words, the first metavar in the first token of `top_elts` corresponds . /// to `matches[match_lo]`. 662,016 ( 0.02%) match_lo: usize, . /// The position in `matches` corresponding to the metavar we are currently trying to match . /// against the source token stream. `match_lo <= match_cur <= match_hi`. . match_cur: usize, . /// Similar to `match_lo` except `match_hi` is the position in `matches` of the _last_ metavar . /// in this matcher. 662,016 ( 0.02%) match_hi: usize, . . // The following fields are used if we are matching a repetition. If we aren't, they should be . // `None`. . /// The KleeneOp of this sequence if we are in a repetition. 662,016 ( 0.02%) seq_op: Option, . . /// The separator if we are in a repetition. . sep: Option, . . /// The "parent" matcher position if we are in a repetition. That is, the matcher position just . /// before we enter the sequence. 1,324,032 ( 0.03%) up: Option>, . . /// Specifically used to "unzip" token trees. By "unzip", we mean to unwrap the delimiters from . /// a delimited token tree (e.g., something wrapped in `(` `)`) or to get the contents of a doc . /// comment... . /// . /// When matching against matchers with nested delimited submatchers (e.g., `pat ( pat ( .. ) . /// pat ) pat`), we need to keep track of the matchers we are descending into. This stack does . /// that where the bottom of the stack is the outermost matcher. . /// Also, throughout the comments, this "descent" is often referred to as "unzipping"... . stack: SmallVec<[MatcherTtFrame<'tt>; 1]>, . } . . impl<'root, 'tt> MatcherPos<'root, 'tt> { . /// Adds `m` as a named match for the `idx`-th metavar. . fn push_match(&mut self, idx: usize, m: NamedMatch) { 5,265,612 ( 0.13%) let matches = Lrc::make_mut(&mut self.matches[idx]); . matches.push(m); . } . } . . // Lots of MatcherPos instances are created at runtime. Allocating them on the . // heap is slow. Furthermore, using SmallVec to allocate them all . // on the stack is also slow, because MatcherPos is quite a large type and . // instances get moved around a lot between vectors, which requires lots of -- line 221 ---------------------------------------- -- line 226 ---------------------------------------- . // and this type is used to encapsulate both cases. . enum MatcherPosHandle<'root, 'tt> { . Ref(&'root mut MatcherPos<'root, 'tt>), . Box(Box>), . } . . impl<'root, 'tt> Clone for MatcherPosHandle<'root, 'tt> { . // This always produces a new Box. 2,648,064 ( 0.07%) fn clone(&self) -> Self { 1,324,032 ( 0.03%) MatcherPosHandle::Box(match *self { 1,959,546 ( 0.05%) MatcherPosHandle::Ref(ref r) => Box::new((**r).clone()), . MatcherPosHandle::Box(ref b) => b.clone(), . }) 3,972,096 ( 0.10%) } . } . . impl<'root, 'tt> Deref for MatcherPosHandle<'root, 'tt> { . type Target = MatcherPos<'root, 'tt>; . fn deref(&self) -> &Self::Target { . match *self { . MatcherPosHandle::Ref(ref r) => r, . MatcherPosHandle::Box(ref b) => b, -- line 247 ---------------------------------------- -- line 272 ---------------------------------------- . . /// A `ParseResult` where the `Success` variant contains a mapping of . /// `MacroRulesNormalizedIdent`s to `NamedMatch`es. This represents the mapping . /// of metavars to the token trees they bind to. . crate type NamedParseResult = ParseResult>; . . /// Count how many metavars are named in the given matcher `ms`. . pub(super) fn count_names(ms: &[TokenTree]) -> usize { 111,508 ( 0.00%) ms.iter().fold(0, |count, elt| { 55,754 ( 0.00%) count 167,262 ( 0.00%) + match *elt { 26,988 ( 0.00%) TokenTree::Sequence(_, ref seq) => seq.num_captures, 8,107 ( 0.00%) TokenTree::Delimited(_, ref delim) => count_names(&delim.tts), . TokenTree::MetaVar(..) => 0, . TokenTree::MetaVarDecl(..) => 1, . TokenTree::Token(..) => 0, . } 139,385 ( 0.00%) }) . } . . /// `len` `Vec`s (initially shared and empty) that will store matches of metavars. . fn create_matches(len: usize) -> Box<[Lrc]> { 39,476 ( 0.00%) if len == 0 { . vec![] . } else { . let empty_matches = Lrc::new(SmallVec::new()); . vec![empty_matches; len] . } . .into_boxed_slice() . } . . /// Generates the top-level matcher position in which the "dot" is before the first token of the . /// matcher `ms`. . fn initial_matcher_pos<'root, 'tt>(ms: &'tt [TokenTree]) -> MatcherPos<'root, 'tt> { . let match_idx_hi = count_names(ms); . let matches = create_matches(match_idx_hi); 119,115 ( 0.00%) MatcherPos { . // Start with the top level matcher given to us . top_elts: TtSeq(ms), // "elts" is an abbr. for "elements" . // The "dot" is before the first token of the matcher . idx: 0, . . // Initialize `matches` to a bunch of empty `Vec`s -- one for each metavar in `top_elts`. . // `match_lo` for `top_elts` is 0 and `match_hi` is `matches.len()`. `match_cur` is 0 since . // we haven't actually matched anything yet. -- line 316 ---------------------------------------- -- line 340 ---------------------------------------- . /// particular token tree. . /// . /// The width of each `MatchedSeq` in the `NamedMatch`, and the identity of . /// the `MatchedNonterminal`s, will depend on the token tree it was applied . /// to: each `MatchedSeq` corresponds to a single `TTSeq` in the originating . /// token tree. The depth of the `NamedMatch` structure will therefore depend . /// only on the nesting depth of `ast::TTSeq`s in the originating . /// token tree it was derived from. 2,458 ( 0.00%) #[derive(Debug, Clone)] . crate enum NamedMatch { . MatchedSeq(Lrc), . MatchedNonterminal(Lrc), . } . . /// Takes a sequence of token trees `ms` representing a matcher which successfully matched input . /// and an iterator of items that matched input and produces a `NamedParseResult`. . fn nameize>( -- line 356 ---------------------------------------- -- line 357 ---------------------------------------- . sess: &ParseSess, . ms: &[TokenTree], . mut res: I, . ) -> NamedParseResult { . // Recursively descend into each type of matcher (e.g., sequences, delimited, metavars) and make . // sure that each metavar has _exactly one_ binding. If a metavar does not have exactly one . // binding, then there is an error. If it does, then we insert the binding into the . // `NamedParseResult`. 59,136 ( 0.00%) fn n_rec>( . sess: &ParseSess, . m: &TokenTree, . res: &mut I, . ret_val: &mut FxHashMap, . ) -> Result<(), (rustc_span::Span, String)> { 31,204 ( 0.00%) match *m { . TokenTree::Sequence(_, ref seq) => { 1,741 ( 0.00%) for next_m in &seq.tts { 11,316 ( 0.00%) n_rec(sess, next_m, res.by_ref(), ret_val)? . } . } . TokenTree::Delimited(_, ref delim) => { 988 ( 0.00%) for next_m in &delim.tts { 5,964 ( 0.00%) n_rec(sess, next_m, res.by_ref(), ret_val)?; . } . } . TokenTree::MetaVarDecl(span, _, None) => { . if sess.missing_fragment_specifiers.borrow_mut().remove(&span).is_some() { . return Err((span, "missing fragment specifier".to_string())); . } . } 12,972 ( 0.00%) TokenTree::MetaVarDecl(sp, bind_name, _) => match ret_val 8,648 ( 0.00%) .entry(MacroRulesNormalizedIdent::new(bind_name)) . { . Vacant(spot) => { . spot.insert(res.next().unwrap()); . } . Occupied(..) => return Err((sp, format!("duplicated bind name: {}", bind_name))), . }, . TokenTree::MetaVar(..) | TokenTree::Token(..) => (), . } . 5,376 ( 0.00%) Ok(()) 43,008 ( 0.00%) } . . let mut ret_val = FxHashMap::default(); . for m in ms { 24,698 ( 0.00%) match n_rec(sess, m, res.by_ref(), &mut ret_val) { . Ok(_) => {} . Err((sp, msg)) => return Error(sp, msg), . } . } . 8,523 ( 0.00%) Success(ret_val) . } . . /// Performs a token equality check, ignoring syntax context (that is, an unhygienic comparison) . fn token_name_eq(t1: &Token, t2: &Token) -> bool { 3,341,712 ( 0.08%) if let (Some((ident1, is_raw1)), Some((ident2, is_raw2))) = (t1.ident(), t2.ident()) { 66 ( 0.00%) ident1.name == ident2.name && is_raw1 == is_raw2 4,678,030 ( 0.12%) } else if let (Some(ident1), Some(ident2)) = (t1.lifetime(), t2.lifetime()) { . ident1.name == ident2.name . } else { 2,004,773 ( 0.05%) t1.kind == t2.kind . } . } . . /// Process the matcher positions of `cur_items` until it is empty. In the process, this will . /// produce more items in `next_items`, `eof_items`, and `bb_items`. . /// . /// For more info about the how this happens, see the module-level doc comments and the inline . /// comments of this function. -- line 427 ---------------------------------------- -- line 443 ---------------------------------------- . sess: &ParseSess, . cur_items: &mut SmallVec<[MatcherPosHandle<'root, 'tt>; 1]>, . next_items: &mut Vec>, . eof_items: &mut SmallVec<[MatcherPosHandle<'root, 'tt>; 1]>, . bb_items: &mut SmallVec<[MatcherPosHandle<'root, 'tt>; 1]>, . token: &Token, . ) -> ParseResult<()> { . // Pop items from `cur_items` until it is empty. 8,040,124 ( 0.20%) while let Some(mut item) = cur_items.pop() { . // When unzipped trees end, remove them. This corresponds to backtracking out of a . // delimited submatcher into which we already descended. In backtracking out again, we need . // to advance the "dot" past the delimiters in the outer matcher. 25,466,430 ( 0.63%) while item.idx >= item.top_elts.len() { 14,330 ( 0.00%) match item.stack.pop() { . Some(MatcherTtFrame { elts, idx }) => { 64,485 ( 0.00%) item.top_elts = elts; 28,660 ( 0.00%) item.idx = idx + 1; . } . None => break, . } . } . . // Get the current position of the "dot" (`idx`) in `item` and the number of token trees in . // the matcher (`len`). . let idx = item.idx; . let len = item.top_elts.len(); . . // If `idx >= len`, then we are at or past the end of the matcher of `item`. 4,689,053 ( 0.12%) if idx >= len { . // We are repeating iff there is a parent. If the matcher is inside of a repetition, . // then we could be at the end of a sequence or at the beginning of the next . // repetition. 663,434 ( 0.02%) if item.up.is_some() { . // At this point, regardless of whether there is a separator, we should add all . // matches from the complete repetition of the sequence to the shared, top-level . // `matches` list (actually, `up.matches`, which could itself not be the top-level, . // but anyway...). Moreover, we add another item to `cur_items` in which the "dot" . // is at the end of the `up` matcher. This ensures that the "dot" in the `up` . // matcher is also advanced sufficiently. . // . // NOTE: removing the condition `idx == len` allows trailing separators. 1,308,244 ( 0.03%) if idx == len { . // Get the `up` matcher . let mut new_pos = item.up.clone().unwrap(); . . // Add matches from this repetition to the `matches` of `up` 1,308,064 ( 0.03%) for idx in item.match_lo..item.match_hi { 3,270,535 ( 0.08%) let sub = item.matches[idx].clone(); 1,962,321 ( 0.05%) new_pos.push_match(idx, MatchedSeq(sub)); . } . . // Move the "dot" past the repetition in `up` 1,307,970 ( 0.03%) new_pos.match_cur = item.match_hi; 3,924,192 ( 0.10%) new_pos.idx += 1; . cur_items.push(new_pos); . } . . // Check if we need a separator. 654,032 ( 0.02%) if idx == len && item.sep.is_some() { . // We have a separator, and it is the current token. We can advance past the . // separator token. 188 ( 0.00%) if item.sep.as_ref().map_or(false, |sep| token_name_eq(token, sep)) { 630 ( 0.00%) item.idx += 1; . next_items.push(item); . } . } . // We don't need a separator. Move the "dot" back to the beginning of the matcher . // and try to match again UNLESS we are only allowed to have _one_ repetition. 654,028 ( 0.02%) else if item.seq_op != Some(mbe::KleeneOp::ZeroOrOne) { 1,307,948 ( 0.03%) item.match_cur = item.match_lo; 2,615,896 ( 0.06%) item.idx = 0; . cur_items.push(item); . } . } . // If we are not in a repetition, then being at the end of a matcher means that we have . // reached the potential end of the input. . else { . eof_items.push(item); . } . } . // We are in the middle of a matcher. . else { . // Look at what token in the matcher we are trying to match the current token (`token`) . // against. Depending on that, we may generate new items. 13,976,861 ( 0.35%) match item.top_elts.get_tt(idx) { . // Need to descend into a sequence 38,918 ( 0.00%) TokenTree::Sequence(sp, seq) => { . // Examine the case where there are 0 matches of this sequence. We are . // implicitly disallowing OneOrMore from having 0 matches here. Thus, that will . // result in a "no rules expected token" error by virtue of this matcher not . // working. 15,914 ( 0.00%) if seq.kleene.op == mbe::KleeneOp::ZeroOrMore . || seq.kleene.op == mbe::KleeneOp::ZeroOrOne . { 15,828 ( 0.00%) let mut new_item = item.clone(); 31,656 ( 0.00%) new_item.match_cur += seq.num_captures; 39,570 ( 0.00%) new_item.idx += 1; 47,484 ( 0.00%) for idx in item.match_cur..item.match_cur + seq.num_captures { 23,442 ( 0.00%) new_item.push_match(idx, MatchedSeq(Lrc::new(smallvec![]))); . } . cur_items.push(new_item); . } . 7,957 ( 0.00%) let matches = create_matches(item.matches.len()); 95,484 ( 0.00%) cur_items.push(MatcherPosHandle::Box(Box::new(MatcherPos { 7,957 ( 0.00%) stack: smallvec![], . sep: seq.separator.clone(), 7,957 ( 0.00%) seq_op: Some(seq.kleene.op), . idx: 0, 39,785 ( 0.00%) matches, 15,914 ( 0.00%) match_lo: item.match_cur, . match_cur: item.match_cur, 15,914 ( 0.00%) match_hi: item.match_cur + seq.num_captures, . up: Some(item), 55,699 ( 0.00%) top_elts: Tt(TokenTree::Sequence(sp, seq)), . }))); . } . . // We need to match a metavar (but the identifier is invalid)... this is an error . TokenTree::MetaVarDecl(span, _, None) => { . if sess.missing_fragment_specifiers.borrow_mut().remove(&span).is_some() { . return Error(span, "missing fragment specifier".to_string()); . } -- line 565 ---------------------------------------- -- line 568 ---------------------------------------- . // We need to match a metavar with a valid ident... call out to the black-box . // parser by adding an item to `bb_items`. . TokenTree::MetaVarDecl(_, _, Some(kind)) => { . // Built-in nonterminals never start with these tokens, so we can eliminate . // them from consideration. . // . // We use the span of the metavariable declaration to determine any . // edition-specific matching behavior for non-terminals. 3,311,790 ( 0.08%) if Parser::nonterminal_may_begin_with(kind, token) { . bb_items.push(item); . } . } . . // We need to descend into a delimited submatcher or a doc comment. To do this, we . // push the current matcher onto a stack and push a new item containing the . // submatcher onto `cur_items`. . // . // At the beginning of the loop, if we reach the end of the delimited submatcher, . // we pop the stack to backtrack out of the descent. 40,300 ( 0.00%) seq @ (TokenTree::Delimited(..) . | TokenTree::Token(Token { kind: DocComment(..), .. })) => { . let lower_elts = mem::replace(&mut item.top_elts, Tt(seq)); 8,060 ( 0.00%) let idx = item.idx; 56,420 ( 0.00%) item.stack.push(MatcherTtFrame { elts: lower_elts, idx }); 32,240 ( 0.00%) item.idx = 0; . cur_items.push(item); . } . . // We just matched a normal token. We can just advance the parser. 1,414,296 ( 0.04%) TokenTree::Token(t) if token_name_eq(&t, token) => { 109,067 ( 0.00%) item.idx += 1; . next_items.push(item); . } . . // There was another token that was not `token`... This means we can't add any . // rules. NOTE that this is not necessarily an error unless _all_ items in . // `cur_items` end up doing this. There may still be some other matchers that do . // end up working out. . TokenTree::Token(..) | TokenTree::MetaVar(..) => {} . } 7,360,907 ( 0.18%) } 2,677,074 ( 0.07%) } . . // Yay a successful parse (so far)! . Success(()) . } . . /// Use the given sequence of token trees (`ms`) as a matcher. Match the token . /// stream from the given `parser` against it and return the match. 79,410 ( 0.00%) pub(super) fn parse_tt( . parser: &mut Cow<'_, Parser<'_>>, . ms: &[TokenTree], . macro_name: Ident, . ) -> NamedParseResult { . // A queue of possible matcher positions. We initialize it with the matcher position in which . // the "dot" is before the first token of the first token tree in `ms`. `inner_parse_loop` then . // processes all of these possible matcher positions and produces possible next positions into . // `next_items`. After some post-processing, the contents of `next_items` replenish `cur_items` . // and we start over again. . // . // This MatcherPos instance is allocated on the stack. All others -- and . // there are frequently *no* others! -- are allocated on the heap. . let mut initial = initial_matcher_pos(ms); 39,705 ( 0.00%) let mut cur_items = smallvec![MatcherPosHandle::Ref(&mut initial)]; . let mut next_items = Vec::new(); . . loop { . // Matcher positions black-box parsed by parser.rs (`parser`) . let mut bb_items = SmallVec::new(); . . // Matcher positions that would be valid if the macro invocation was over now . let mut eof_items = SmallVec::new(); 678,004 ( 0.02%) assert!(next_items.is_empty()); . . // Process `cur_items` until either we have finished the input or we need to get some . // parsing from the black-box parser done. The result is that `next_items` will contain a . // bunch of possible next matcher positions in `next_items`. . match inner_parse_loop( . parser.sess, . &mut cur_items, . &mut next_items, -- line 648 ---------------------------------------- -- line 652 ---------------------------------------- . ) { . Success(_) => {} . Failure(token, msg) => return Failure(token, msg), . Error(sp, msg) => return Error(sp, msg), . ErrorReported => return ErrorReported, . } . . // inner parse loop handled all cur_items, so it's empty 678,004 ( 0.02%) assert!(cur_items.is_empty()); . . // We need to do some post processing after the `inner_parser_loop`. . // . // Error messages here could be improved with links to original rules. . . // If we reached the EOF, check that there is EXACTLY ONE possible matcher. Otherwise, . // either the parse is ambiguous (which should never happen) or there is a syntax error. 3,390,020 ( 0.08%) if parser.token == token::Eof { 3,788 ( 0.00%) if eof_items.len() == 1 { . let matches = 4,056 ( 0.00%) eof_items[0].matches.iter_mut().map(|dv| Lrc::make_mut(dv).pop().unwrap()); 2,841 ( 0.00%) return nameize(parser.sess, ms, matches); . } else if eof_items.len() > 1 { . return Error( . parser.token.span, . "ambiguity: multiple successful parses".to_string(), . ); . } else { . return Failure( . Token::new( -- line 680 ---------------------------------------- -- line 687 ---------------------------------------- . ), . "missing tokens in macro arguments", . ); . } . } . // Performance hack: eof_items may share matchers via Rc with other things that we want . // to modify. Dropping eof_items now may drop these refcounts to 1, preventing an . // unnecessary implicit clone later in Rc::make_mut. 2,708,228 ( 0.07%) drop(eof_items); . . // If there are no possible next positions AND we aren't waiting for the black-box parser, . // then there is a syntax error. 2,053,746 ( 0.05%) if bb_items.is_empty() && next_items.is_empty() { 90,922 ( 0.00%) return Failure(parser.token.clone(), "no rules expected this token in macro call"); . } . // Another possibility is that we need to call out to parse some rust nonterminal . // (black-box) parser. However, if there is not EXACTLY ONE of these, something is wrong. 2,617,928 ( 0.06%) else if (!bb_items.is_empty() && !next_items.is_empty()) || bb_items.len() > 1 { . let nts = bb_items . .iter() . .map(|item| match item.top_elts.get_tt(item.idx) { . TokenTree::MetaVarDecl(_, bind, Some(kind)) => format!("{} ('{}')", kind, bind), . _ => panic!(), . }) . .collect::>() . .join(" or "); -- line 712 ---------------------------------------- -- line 721 ---------------------------------------- . n => format!("built-in NTs {} or {} other options.", nts, n), . } . ), . ); . } . // Dump all possible `next_items` into `cur_items` for the next iteration. . else if !next_items.is_empty() { . // Now process the next token 46,743 ( 0.00%) cur_items.extend(next_items.drain(..)); 15,581 ( 0.00%) parser.to_mut().bump(); . } . // Finally, we have the case where we need to call the black-box parser to get some . // nonterminal. . else { . assert_eq!(bb_items.len(), 1); . 1,308,964 ( 0.03%) let mut item = bb_items.pop().unwrap(); 5,234,776 ( 0.13%) if let TokenTree::MetaVarDecl(span, _, Some(kind)) = item.top_elts.get_tt(item.idx) { 654,482 ( 0.02%) let match_cur = item.match_cur; . // We use the span of the metavariable declaration to determine any . // edition-specific matching behavior for non-terminals. 3,927,041 ( 0.10%) let nt = match parser.to_mut().parse_nonterminal(kind) { . Err(mut err) => { . err.span_label( . span, . format!("while parsing argument for this `{}` macro fragment", kind), . ) . .emit(); . return ErrorReported; . } 3,926,892 ( 0.10%) Ok(nt) => nt, . }; 2,617,928 ( 0.06%) item.push_match(match_cur, MatchedNonterminal(Lrc::new(nt))); 2,617,928 ( 0.06%) item.idx += 1; 3,926,892 ( 0.10%) item.match_cur += 1; . } else { . unreachable!() . } . cur_items.push(item); . } . 1,340,126 ( 0.03%) assert!(!cur_items.is_empty()); . } 71,469 ( 0.00%) } 24,777,598 ( 0.61%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/tokenstream.rs -------------------------------------------------------------------------------- Ir -- line 32 ---------------------------------------- . /// . /// If the syntax extension is an MBE macro, it will attempt to match its . /// LHS token tree against the provided token tree, and if it finds a . /// match, will transcribe the RHS token tree, splicing in any captured . /// `macro_parser::matched_nonterminals` into the `SubstNt`s it finds. . /// . /// The RHS of an MBE macro is the only place `SubstNt`s are substituted. . /// Nothing special happens to misnamed or misplaced `SubstNt`s. 26,754,316 ( 0.66%) #[derive(Debug, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)] . pub enum TokenTree { . /// A single token. 10,353,824 ( 0.26%) Token(Token), . /// A delimited sequence of token trees. 730,992 ( 0.02%) Delimited(DelimSpan, DelimToken, TokenStream), . } . . #[derive(Copy, Clone)] . pub enum CanSynthesizeMissingTokens { . Yes, . No, . } . -- line 53 ---------------------------------------- -- line 71 ---------------------------------------- . delim == delim2 && tts.eq_unspanned(&tts2) . } . _ => false, . } . } . . /// Retrieves the `TokenTree`'s span. . pub fn span(&self) -> Span { 8,786 ( 0.00%) match self { 3,263 ( 0.00%) TokenTree::Token(token) => token.span, 5,012 ( 0.00%) TokenTree::Delimited(sp, ..) => sp.entire(), . } 3,141 ( 0.00%) } . . /// Modify the `TokenTree`'s span in-place. . pub fn set_span(&mut self, span: Span) { 8,786 ( 0.00%) match self { 3,141 ( 0.00%) TokenTree::Token(token) => token.span = span, 2,504 ( 0.00%) TokenTree::Delimited(dspan, ..) => *dspan = DelimSpan::from_single(span), . } 4,393 ( 0.00%) } . 729 ( 0.00%) pub fn token(kind: TokenKind, span: Span) -> TokenTree { 2,841,288 ( 0.07%) TokenTree::Token(Token::new(kind, span)) 729 ( 0.00%) } . . /// Returns the opening delimiter as a token tree. 352,126 ( 0.01%) pub fn open_tt(span: DelimSpan, delim: DelimToken) -> TokenTree { 1,056,378 ( 0.03%) TokenTree::token(token::OpenDelim(delim), span.open) 352,126 ( 0.01%) } . . /// Returns the closing delimiter as a token tree. 357,467 ( 0.01%) pub fn close_tt(span: DelimSpan, delim: DelimToken) -> TokenTree { 1,072,401 ( 0.03%) TokenTree::token(token::CloseDelim(delim), span.close) 357,467 ( 0.01%) } . 1,074 ( 0.00%) pub fn uninterpolate(self) -> TokenTree { 716 ( 0.00%) match self { 3,222 ( 0.00%) TokenTree::Token(token) => TokenTree::Token(token.uninterpolate().into_owned()), . tt => tt, . } 1,432 ( 0.00%) } . } . . impl HashStable for TokenStream . where . CTX: crate::HashStableContext, . { 6,795 ( 0.00%) fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) { 42,746 ( 0.00%) for sub_tt in self.trees() { . sub_tt.hash_stable(hcx, hasher); . } 6,040 ( 0.00%) } . } . . pub trait CreateTokenStream: sync::Send + sync::Sync { . fn create_token_stream(&self) -> AttrAnnotatedTokenStream; . } . . impl CreateTokenStream for AttrAnnotatedTokenStream { . fn create_token_stream(&self) -> AttrAnnotatedTokenStream { -- line 131 ---------------------------------------- -- line 135 ---------------------------------------- . . /// A lazy version of [`TokenStream`], which defers creation . /// of an actual `TokenStream` until it is needed. . /// `Box` is here only to reduce the structure size. . #[derive(Clone)] . pub struct LazyTokenStream(Lrc>); . . impl LazyTokenStream { 216 ( 0.00%) pub fn new(inner: impl CreateTokenStream + 'static) -> LazyTokenStream { . LazyTokenStream(Lrc::new(Box::new(inner))) 216 ( 0.00%) } . . pub fn create_token_stream(&self) -> AttrAnnotatedTokenStream { 4 ( 0.00%) self.0.create_token_stream() . } . } . . impl fmt::Debug for LazyTokenStream { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . write!(f, "LazyTokenStream({:?})", self.create_token_stream()) . } . } -- line 156 ---------------------------------------- -- line 188 ---------------------------------------- . Delimited(DelimSpan, DelimToken, AttrAnnotatedTokenStream), . /// Stores the attributes for an attribute target, . /// along with the tokens for that attribute target. . /// See `AttributesData` for more information . Attributes(AttributesData), . } . . impl AttrAnnotatedTokenStream { 16,194 ( 0.00%) pub fn new(tokens: Vec<(AttrAnnotatedTokenTree, Spacing)>) -> AttrAnnotatedTokenStream { . AttrAnnotatedTokenStream(Lrc::new(tokens)) 16,194 ( 0.00%) } . . /// Converts this `AttrAnnotatedTokenStream` to a plain `TokenStream . /// During conversion, `AttrAnnotatedTokenTree::Attributes` get 'flattened' . /// back to a `TokenStream` of the form `outer_attr attr_target`. . /// If there are inner attributes, they are inserted into the proper . /// place in the attribute target tokens. 1 ( 0.00%) pub fn to_tokenstream(&self) -> TokenStream { 1 ( 0.00%) let trees: Vec<_> = self . .0 . .iter() 3 ( 0.00%) .flat_map(|tree| match &tree.0 { 2 ( 0.00%) AttrAnnotatedTokenTree::Token(inner) => { 5 ( 0.00%) smallvec![(TokenTree::Token(inner.clone()), tree.1)].into_iter() . } . AttrAnnotatedTokenTree::Delimited(span, delim, stream) => smallvec![( . TokenTree::Delimited(*span, *delim, stream.to_tokenstream()), . tree.1, . )] . .into_iter(), . AttrAnnotatedTokenTree::Attributes(data) => { . let mut outer_attrs = Vec::new(); -- line 219 ---------------------------------------- -- line 279 ---------------------------------------- . flat.extend(attr.tokens().to_tokenstream().0.clone().iter().cloned()); . } . flat.extend(target_tokens); . flat.into_iter() . } . }) . .collect(); . TokenStream::new(trees) 2 ( 0.00%) } . } . . /// Stores the tokens for an attribute target, along . /// with its attributes. . /// . /// This is constructed during parsing when we need to capture . /// tokens. . /// -- line 295 ---------------------------------------- -- line 316 ---------------------------------------- . pub struct TokenStream(pub(crate) Lrc>); . . pub type TreeAndSpacing = (TokenTree, Spacing); . . // `TokenStream` is used a lot. Make sure it doesn't unintentionally get bigger. . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . rustc_data_structures::static_assert_size!(TokenStream, 8); . 2,889,236 ( 0.07%) #[derive(Clone, Copy, Debug, PartialEq, Encodable, Decodable)] . pub enum Spacing { . Alone, . Joint, . } . . impl TokenStream { . /// Given a `TokenStream` with a `Stream` of only two arguments, return a new `TokenStream` . /// separating the two arguments with a comma for diagnostic suggestions. -- line 332 ---------------------------------------- -- line 371 ---------------------------------------- . impl From<(AttrAnnotatedTokenTree, Spacing)> for AttrAnnotatedTokenStream { . fn from((tree, spacing): (AttrAnnotatedTokenTree, Spacing)) -> AttrAnnotatedTokenStream { . AttrAnnotatedTokenStream::new(vec![(tree, spacing)]) . } . } . . impl From for TokenStream { . fn from(tree: TokenTree) -> TokenStream { 450 ( 0.00%) TokenStream::new(vec![(tree, Spacing::Alone)]) . } . } . . impl From for TreeAndSpacing { . fn from(tree: TokenTree) -> TreeAndSpacing { 822,969 ( 0.02%) (tree, Spacing::Alone) . } . } . . impl iter::FromIterator for TokenStream { . fn from_iter>(iter: I) -> Self { . TokenStream::new(iter.into_iter().map(Into::into).collect::>()) . } . } -- line 393 ---------------------------------------- -- line 401 ---------------------------------------- . } . . impl TokenStream { . pub fn new(streams: Vec) -> TokenStream { . TokenStream(Lrc::new(streams)) . } . . pub fn is_empty(&self) -> bool { 1,753 ( 0.00%) self.0.is_empty() 1,753 ( 0.00%) } . . pub fn len(&self) -> usize { 3,608,827 ( 0.09%) self.0.len() 930 ( 0.00%) } . . pub fn from_streams(mut streams: SmallVec<[TokenStream; 2]>) -> TokenStream { . match streams.len() { . 0 => TokenStream::default(), . 1 => streams.pop().unwrap(), . _ => { . // We are going to extend the first stream in `streams` with . // the elements from the subsequent streams. This requires -- line 422 ---------------------------------------- -- line 448 ---------------------------------------- . . // Create the final `TokenStream`. . TokenStream(first_stream_lrc) . } . } . } . . pub fn trees(&self) -> Cursor { 1,947 ( 0.00%) self.clone().into_trees() 3,894 ( 0.00%) } . 354,645 ( 0.01%) pub fn into_trees(self) -> Cursor { . Cursor::new(self) 709,290 ( 0.02%) } . . /// Compares two `TokenStream`s, checking equality without regarding span information. . pub fn eq_unspanned(&self, other: &TokenStream) -> bool { . let mut t1 = self.trees(); . let mut t2 = other.trees(); . for (t1, t2) in iter::zip(&mut t1, &mut t2) { . if !t1.eq_unspanned(&t2) { . return false; . } . } . t1.next().is_none() && t2.next().is_none() . } . . pub fn map_enumerated TokenTree>(self, mut f: F) -> TokenStream { 904 ( 0.00%) TokenStream(Lrc::new( . self.0 . .iter() . .enumerate() 26,358 ( 0.00%) .map(|(i, (tree, is_joint))| (f(i, tree), *is_joint)) . .collect(), . )) . } . } . . // 99.5%+ of the time we have 1 or 2 elements in this vector. . #[derive(Clone)] . pub struct TokenStreamBuilder(SmallVec<[TokenStream; 2]>); -- line 488 ---------------------------------------- -- line 572 ---------------------------------------- . pub struct Cursor { . pub stream: TokenStream, . index: usize, . } . . impl Iterator for Cursor { . type Item = TokenTree; . 39,747 ( 0.00%) fn next(&mut self) -> Option { 69,051 ( 0.00%) self.next_with_spacing().map(|(tree, _)| tree) 52,996 ( 0.00%) } . } . . impl Cursor { . fn new(stream: TokenStream) -> Self { . Cursor { stream, index: 0 } . } . 17,968,590 ( 0.45%) pub fn next_with_spacing(&mut self) -> Option { 10,820,901 ( 0.27%) if self.index < self.stream.len() { 5,774,302 ( 0.14%) self.index += 1; 20,135,122 ( 0.50%) Some(self.stream.0[self.index - 1].clone()) . } else { 1,434,544 ( 0.04%) None . } 21,562,308 ( 0.54%) } . . pub fn index(&self) -> usize { . self.index . } . . pub fn append(&mut self, new_stream: TokenStream) { . if new_stream.is_empty() { . return; . } . let index = self.index; . let stream = mem::take(&mut self.stream); . *self = TokenStream::from_streams(smallvec![stream, new_stream]).into_trees(); . self.index = index; . } . 51,538 ( 0.00%) pub fn look_ahead(&self, n: usize) -> Option<&TokenTree> { 103,076 ( 0.00%) self.stream.0[self.index..].get(n).map(|(tree, _)| tree) 103,076 ( 0.00%) } . } . 1,424,820 ( 0.04%) #[derive(Debug, Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)] . pub struct DelimSpan { . pub open: Span, . pub close: Span, . } . . impl DelimSpan { 5 ( 0.00%) pub fn from_single(sp: Span) -> Self { . DelimSpan { open: sp, close: sp } 10 ( 0.00%) } . 3,506 ( 0.00%) pub fn from_pair(open: Span, close: Span) -> Self { . DelimSpan { open, close } 1,753 ( 0.00%) } . . pub fn dummy() -> Self { . Self::from_single(DUMMY_SP) 8,658 ( 0.00%) } . 39,296 ( 0.00%) pub fn entire(self) -> Span { . self.open.with_hi(self.close.hi()) 29,472 ( 0.00%) } . } 30,929 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/mem/mod.rs -------------------------------------------------------------------------------- Ir -- line 326 ---------------------------------------- . /// ``` . #[inline] . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_size_of_val", issue = "46571")] . #[cfg_attr(not(test), rustc_diagnostic_item = "mem_size_of_val")] . pub const fn size_of_val(val: &T) -> usize { . // SAFETY: `val` is a reference, so it's a valid raw pointer 22,643 ( 0.00%) unsafe { intrinsics::size_of_val(val) } . } . . /// Returns the size of the pointed-to value in bytes. . /// . /// This is usually the same as `size_of::()`. However, when `T` *has* no . /// statically-known size, e.g., a slice [`[T]`][slice] or a [trait object], . /// then `size_of_val_raw` can be used to get the dynamically-known size. . /// -- line 342 ---------------------------------------- -- line 375 ---------------------------------------- . /// assert_eq!(13, unsafe { mem::size_of_val_raw(y) }); . /// ``` . #[inline] . #[must_use] . #[unstable(feature = "layout_for_ptr", issue = "69835")] . #[rustc_const_unstable(feature = "const_size_of_val_raw", issue = "46571")] . pub const unsafe fn size_of_val_raw(val: *const T) -> usize { . // SAFETY: the caller must provide a valid raw pointer 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 831 ---------------------------------------- . #[must_use = "if you don't need the old value, you can just assign the new value directly"] . #[rustc_const_unstable(feature = "const_replace", issue = "83164")] . #[cfg_attr(not(test), rustc_diagnostic_item = "mem_replace")] . pub const fn replace(dest: &mut T, src: T) -> T { . // SAFETY: We read from `dest` but directly write `src` into it afterwards, . // such that the old value is not duplicated. Nothing is dropped and . // nothing here can panic. . unsafe { 147,105 ( 0.00%) let result = ptr::read(dest); 15,569,981 ( 0.39%) ptr::write(dest, src); . result . } . } . . /// Disposes of a value. . /// . /// This does so by calling the argument's implementation of [`Drop`][drop]. . /// -- line 848 ---------------------------------------- -- line 901 ---------------------------------------- . /// . /// println!("x: {}, y: {}", x, y.0); // still available . /// ``` . /// . /// [`RefCell`]: crate::cell::RefCell . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[cfg_attr(not(test), rustc_diagnostic_item = "mem_drop")] 3 ( 0.00%) pub fn drop(_x: T) {} . . /// Interprets `src` as having type `&U`, and then reads `src` without moving . /// the contained value. . /// . /// This function will unsafely assume the pointer `src` is valid for [`size_of::`][size_of] . /// bytes by transmuting `&T` to `&U` and then reading the `&U` (except that this is done in a way . /// that is correct even when `&U` makes stricter alignment requirements than `&T`). It will also . /// unsafely create a copy of the contained value instead of moving out of `src`. -- line 917 ---------------------------------------- -- line 991 ---------------------------------------- . } . } . . #[stable(feature = "discriminant_value", since = "1.21.0")] . impl cmp::Eq for Discriminant {} . . #[stable(feature = "discriminant_value", since = "1.21.0")] . impl hash::Hash for Discriminant { 1,976 ( 0.00%) fn hash(&self, state: &mut H) { . self.0.hash(state); 3,450 ( 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 { 6,019 ( 0.00%) Discriminant(intrinsics::discriminant_value(v)) . } . . /// Returns the number of variants in the enum type `T`. . /// . /// If `T` is not an enum, calling this function will not result in undefined behavior, but the . /// return value is unspecified. Equally, if `T` is an enum with more variants than `usize::MAX` . /// the return value is unspecified. Uninhabited variants will be counted. . /// -- line 1047 ---------------------------------------- 4,401 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/span_encoding.rs -------------------------------------------------------------------------------- Ir -- line 55 ---------------------------------------- . /// `ctxt` values depend partly on the crate size and partly on the form of . /// the code. No crates in `rustc-perf` need more than 15 bits for `ctxt`, . /// but larger crates might need more than 16 bits. . /// . /// In order to reliably use parented spans in incremental compilation, . /// the dependency to the parent definition's span. This is performed . /// using the callback `SPAN_TRACK` to access the query engine. . /// 4,782,234 ( 0.12%) #[derive(Clone, Copy, Eq, PartialEq, Hash)] . // FIXME(@lcnr): Enable this attribute once the bootstrap . // compiler knows of `rustc_pass_by_value`. . // . // Right now, this lint would only trigger when compiling the . // stage 2 compiler, which is fairly annoying as there are . // a lot of places using `&Span` right now. After the next bootstrap bump, . // the lint will already trigger when using stage 1, which is a lot less annoying. . // . // #[cfg_attr(not(bootstrap), rustc_pass_by_value)] . pub struct Span { 6,473 ( 0.00%) base_or_index: u32, 2,886 ( 0.00%) len_or_tag: u16, 3,432 ( 0.00%) ctxt_or_zero: u16, . } . . const LEN_TAG: u16 = 0b1000_0000_0000_0000; . const MAX_LEN: u32 = 0b0111_1111_1111_1111; . const MAX_CTXT: u32 = 0b1111_1111_1111_1111; . . /// Dummy span, both position and length are zero, syntax context is zero as well. . pub const DUMMY_SP: Span = Span { base_or_index: 0, len_or_tag: 0, ctxt_or_zero: 0 }; -- line 84 ---------------------------------------- -- line 86 ---------------------------------------- . impl Span { . #[inline] . pub fn new( . mut lo: BytePos, . mut hi: BytePos, . ctxt: SyntaxContext, . parent: Option, . ) -> Self { 271,133 ( 0.01%) if lo > hi { . std::mem::swap(&mut lo, &mut hi); . } . 542,266 ( 0.01%) let (base, len, ctxt2) = (lo.0, hi.0 - lo.0, ctxt.as_u32()); . 2,490,630 ( 0.06%) if len <= MAX_LEN && ctxt2 <= MAX_CTXT && parent.is_none() { . // Inline format. . Span { base_or_index: base, len_or_tag: len as u16, ctxt_or_zero: ctxt2 as u16 } . } else { . // Interned format. . let index = 200 ( 0.00%) with_span_interner(|interner| interner.intern(&SpanData { lo, hi, ctxt, parent })); . Span { base_or_index: index, len_or_tag: LEN_TAG, ctxt_or_zero: 0 } . } 928,904 ( 0.02%) } . . #[inline] . pub fn data(self) -> SpanData { . let data = self.data_untracked(); . if let Some(parent) = data.parent { . (*SPAN_TRACK)(parent); . } . data . } . . /// Internal function to translate between an encoded span and the expanded representation. . /// This function must not be used outside the incremental engine. . #[inline] . pub fn data_untracked(self) -> SpanData { 12,775,516 ( 0.32%) if self.len_or_tag != LEN_TAG { . // Inline format. . debug_assert!(self.len_or_tag as u32 <= MAX_LEN); . SpanData { . lo: BytePos(self.base_or_index), 12,439,998 ( 0.31%) hi: BytePos(self.base_or_index + self.len_or_tag as u32), . ctxt: SyntaxContext::from_u32(self.ctxt_or_zero as u32), . parent: None, . } . } else { . // Interned format. . debug_assert!(self.ctxt_or_zero == 0); . let index = self.base_or_index; . with_span_interner(|interner| interner.spans[index as usize]) . } 393,208 ( 0.01%) } . } . 4 ( 0.00%) #[derive(Default)] . pub struct SpanInterner { . spans: FxIndexSet, . } . . impl SpanInterner { 60 ( 0.00%) fn intern(&mut self, span_data: &SpanData) -> u32 { 80 ( 0.00%) let (index, _) = self.spans.insert_full(*span_data); . index as u32 80 ( 0.00%) } . } . . // If an interner exists, return it. Otherwise, prepare a fresh one. . #[inline] . fn with_span_interner T>(f: F) -> T { . crate::with_session_globals(|session_globals| f(&mut *session_globals.span_interner.lock())) . } 2,902,039 ( 0.07%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs -------------------------------------------------------------------------------- Ir -- line 357 ---------------------------------------- . /// . /// ``` . /// use std::rc::Rc; . /// . /// let five = Rc::new(5); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] 9,280 ( 0.00%) pub fn new(value: T) -> Rc { . // There is an implicit weak pointer owned by all the strong . // pointers, which ensures that the weak destructor never frees . // the allocation while the strong destructor is running, even . // if the weak pointer is stored inside the strong one. . unsafe { . Self::from_inner( 5,826,405 ( 0.14%) Box::leak(box RcBox { strong: Cell::new(1), weak: Cell::new(1), value }).into(), . ) . } 9,280 ( 0.00%) } . . /// Constructs a new `Rc` using a closure `data_fn` that has access to a . /// weak reference to the constructing `Rc`. . /// . /// Generally, a structure circularly referencing itself, either directly or . /// indirectly, should not hold a strong reference to prevent a memory leak. . /// In `data_fn`, initialization of `T` can make use of the weak reference . /// by cloning and storing it inside `T` for use at a later time. -- line 383 ---------------------------------------- -- line 637 ---------------------------------------- . /// . /// let x = Rc::new(4); . /// let _y = Rc::clone(&x); . /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4); . /// ``` . #[inline] . #[stable(feature = "rc_unique", since = "1.4.0")] . pub fn try_unwrap(this: Self) -> Result { 2 ( 0.00%) if Rc::strong_count(&this) == 1 { . unsafe { . let val = ptr::read(&*this); // copy the contained object . . // Indicate to Weaks that they can't be promoted by decrementing . // the strong count, and then remove the implicit "strong weak" . // pointer while also handling drop logic by just crafting a . // fake Weak. . this.inner().dec_strong(); -- line 653 ---------------------------------------- -- line 931 ---------------------------------------- . /// let five = Rc::new(5); . /// let _weak_five = Rc::downgrade(&five); . /// . /// assert_eq!(1, Rc::weak_count(&five)); . /// ``` . #[inline] . #[stable(feature = "rc_counts", since = "1.15.0")] . pub fn weak_count(this: &Self) -> usize { 1,957,617 ( 0.05%) this.inner().weak() - 1 . } . . /// Gets the number of strong (`Rc`) pointers to this allocation. . /// . /// # Examples . /// . /// ``` . /// use std::rc::Rc; -- line 947 ---------------------------------------- -- line 1023 ---------------------------------------- . pub unsafe fn decrement_strong_count(ptr: *const T) { . unsafe { mem::drop(Rc::from_raw(ptr)) }; . } . . /// Returns `true` if there are no other `Rc` or [`Weak`] pointers to . /// this allocation. . #[inline] . fn is_unique(this: &Self) -> bool { 7,965 ( 0.00%) Rc::weak_count(this) == 0 && Rc::strong_count(this) == 1 . } . . /// Returns a mutable reference into the given `Rc`, if there are . /// no other `Rc` or [`Weak`] pointers to the same allocation. . /// . /// Returns [`None`] otherwise, because it is not safe to . /// mutate a shared value. . /// -- line 1039 ---------------------------------------- -- line 1053 ---------------------------------------- . /// assert_eq!(*x, 4); . /// . /// let _y = Rc::clone(&x); . /// assert!(Rc::get_mut(&mut x).is_none()); . /// ``` . #[inline] . #[stable(feature = "rc_unique", since = "1.4.0")] . pub fn get_mut(this: &mut Self) -> Option<&mut T> { 2,655 ( 0.00%) if Rc::is_unique(this) { unsafe { Some(Rc::get_mut_unchecked(this)) } } else { None } . } . . /// Returns a mutable reference into the given `Rc`, . /// without any check. . /// . /// See also [`get_mut`], which is safe and does appropriate checks. . /// . /// [`get_mut`]: Rc::get_mut -- line 1069 ---------------------------------------- -- line 1088 ---------------------------------------- . /// } . /// assert_eq!(*x, "foo"); . /// ``` . #[inline] . #[unstable(feature = "get_mut_unchecked", issue = "63292")] . pub unsafe fn get_mut_unchecked(this: &mut Self) -> &mut T { . // We are careful to *not* create a reference covering the "count" fields, as . // this would conflict with accesses to the reference counts (e.g. by `Weak`). 1,390,843 ( 0.03%) unsafe { &mut (*this.ptr.as_ptr()).value } . } . . #[inline] . #[stable(feature = "ptr_eq", since = "1.17.0")] . /// Returns `true` if the two `Rc`s point to the same allocation . /// (in a vein similar to [`ptr::eq`]). . /// . /// # Examples -- line 1104 ---------------------------------------- -- line 1109 ---------------------------------------- . /// let five = Rc::new(5); . /// let same_five = Rc::clone(&five); . /// let other_five = Rc::new(5); . /// . /// assert!(Rc::ptr_eq(&five, &same_five)); . /// assert!(!Rc::ptr_eq(&five, &other_five)); . /// ``` . pub fn ptr_eq(this: &Self, other: &Self) -> bool { 2,753 ( 0.00%) this.ptr.as_ptr() == other.ptr.as_ptr() . } . } . . impl Rc { . /// Makes a mutable reference into the given `Rc`. . /// . /// If there are other `Rc` pointers to the same allocation, then `make_mut` will . /// [`clone`] the inner value to a new allocation to ensure unique ownership. This is also -- line 1125 ---------------------------------------- -- line 1167 ---------------------------------------- . /// *Rc::make_mut(&mut data) += 1; . /// . /// assert!(76 == *data); . /// assert!(weak.upgrade().is_none()); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[inline] . #[stable(feature = "rc_unique", since = "1.4.0")] 6,592,841 ( 0.16%) pub fn make_mut(this: &mut Self) -> &mut T { 3,955,701 ( 0.10%) if Rc::strong_count(this) != 1 { . // Gotta clone the data, there are other Rcs. . // Pre-allocate memory to allow writing the cloned value directly. 668,803 ( 0.02%) let mut rc = Self::new_uninit(); . unsafe { . let data = Rc::get_mut_unchecked(&mut rc); . (**this).write_clone_into_raw(data.as_mut_ptr()); 1,337,606 ( 0.03%) *this = rc.assume_init(); . } 1,299,768 ( 0.03%) } else if Rc::weak_count(this) != 0 { . // Can just steal the data, all that's left is Weaks . let mut rc = Self::new_uninit(); . unsafe { . let data = Rc::get_mut_unchecked(&mut rc); . data.as_mut_ptr().copy_from_nonoverlapping(&**this, 1); . . this.inner().dec_strong(); . // Remove implicit strong-weak ref (no need to craft a fake -- line 1193 ---------------------------------------- -- line 1196 ---------------------------------------- . ptr::write(this, rc.assume_init()); . } . } . // This unsafety is ok because we're guaranteed that the pointer . // returned is the *only* pointer that will ever be returned to T. Our . // reference count is guaranteed to be 1 at this point, and we required . // the `Rc` itself to be `mut`, so we're returning the only possible . // reference to the allocation. 1,318,686 ( 0.03%) unsafe { &mut this.ptr.as_mut().value } 7,911,408 ( 0.20%) } . } . . impl Rc { . #[inline] . #[stable(feature = "rc_downcast", since = "1.29.0")] . /// Attempt to downcast the `Rc` to a concrete type. . /// . /// # Examples -- line 1213 ---------------------------------------- -- line 1344 ---------------------------------------- . ) . } . } . . /// Copy elements from slice into newly allocated Rc<\[T\]> . /// . /// Unsafe because the caller must either take ownership or bind `T: Copy` . #[cfg(not(no_global_oom_handling))] 2,453 ( 0.00%) unsafe fn copy_from_slice(v: &[T]) -> Rc<[T]> { . unsafe { . let ptr = Self::allocate_for_slice(v.len()); 509 ( 0.00%) ptr::copy_nonoverlapping(v.as_ptr(), &mut (*ptr).value as *mut [T] as *mut T, v.len()); . Self::from_ptr(ptr) . } 3,412 ( 0.00%) } . . /// Constructs an `Rc<[T]>` from an iterator known to be of a certain size. . /// . /// Behavior is undefined should the size be wrong. . #[cfg(not(no_global_oom_handling))] . unsafe fn from_iter_exact(iter: impl iter::Iterator, len: usize) -> Rc<[T]> { . // Panic guard while cloning T elements. . // In the event of a panic, elements that have been written -- line 1366 ---------------------------------------- -- line 1419 ---------------------------------------- . unsafe { Self::from_iter_exact(v.iter().cloned(), v.len()) } . } . } . . #[cfg(not(no_global_oom_handling))] . impl RcFromSlice for Rc<[T]> { . #[inline] . fn from_slice(v: &[T]) -> Self { 17 ( 0.00%) unsafe { Rc::copy_from_slice(v) } . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Deref for Rc { . type Target = T; . . #[inline(always)] . fn deref(&self) -> &T { 172,797 ( 0.00%) &self.inner().value . } . } . . #[unstable(feature = "receiver_trait", issue = "none")] . impl Receiver for Rc {} . . #[stable(feature = "rust1", since = "1.0.0")] . unsafe impl<#[may_dangle] T: ?Sized> Drop for Rc { -- line 1445 ---------------------------------------- -- line 1463 ---------------------------------------- . /// } . /// . /// let foo = Rc::new(Foo); . /// let foo2 = Rc::clone(&foo); . /// . /// drop(foo); // Doesn't print anything . /// drop(foo2); // Prints "dropped!" . /// ``` 5,858,426 ( 0.15%) fn drop(&mut self) { . unsafe { 4,041,706 ( 0.10%) self.inner().dec_strong(); 9,632,452 ( 0.24%) if self.inner().strong() == 0 { . // destroy the contained object 695,093 ( 0.02%) ptr::drop_in_place(Self::get_mut_unchecked(self)); . . // remove the implicit "strong weak" pointer now that we've . // destroyed the contents. 1 ( 0.00%) self.inner().dec_weak(); . 2,818,065 ( 0.07%) if self.inner().weak() == 0 { 400 ( 0.00%) Global.deallocate(self.ptr.cast(), Layout::for_value(self.ptr.as_ref())); . } . } . } 7,034,164 ( 0.17%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Clone for Rc { . /// Makes a clone of the `Rc` pointer. . /// . /// This creates another pointer to the same allocation, increasing the . /// strong reference count. -- line 1495 ---------------------------------------- -- line 1562 ---------------------------------------- . /// cost to pay off more easily. It's also more likely to have two `Rc` clones, that point to . /// the same value, than two `&T`s. . /// . /// We can only do this when `T: Eq` as a `PartialEq` might be deliberately irreflexive. . #[stable(feature = "rust1", since = "1.0.0")] . impl RcEqIdent for Rc { . #[inline] . fn eq(&self, other: &Rc) -> bool { 2,823 ( 0.00%) Rc::ptr_eq(self, other) || **self == **other . } . . #[inline] . fn ne(&self, other: &Rc) -> bool { . !Rc::ptr_eq(self, other) && **self != **other . } . } . -- line 1578 ---------------------------------------- -- line 1741 ---------------------------------------- . fn cmp(&self, other: &Rc) -> Ordering { . (**self).cmp(&**other) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Hash for Rc { . fn hash(&self, state: &mut H) { 1,412 ( 0.00%) (**self).hash(state); . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl fmt::Display for Rc { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . fmt::Display::fmt(&**self, f) . } -- line 1757 ---------------------------------------- -- line 1879 ---------------------------------------- . /// # use std::rc::Rc; . /// let original: Box> = Box::new(vec![1, 2, 3]); . /// let shared: Rc> = Rc::from(original); . /// assert_eq!(vec![1, 2, 3], *shared); . /// ``` . #[inline] . fn from(mut v: Vec) -> Rc<[T]> { . unsafe { 961 ( 0.00%) let rc = Rc::copy_from_slice(&v); . . // Allow the Vec to free its memory, but not destroy its contents . v.set_len(0); . . rc . } . } . } -- line 1895 ---------------------------------------- -- line 2080 ---------------------------------------- . #[must_use] . pub fn new() -> Weak { . Weak { ptr: NonNull::new(usize::MAX as *mut RcBox).expect("MAX is not 0") } . } . } . . pub(crate) fn is_dangling(ptr: *mut T) -> bool { . let address = ptr as *mut () as usize; 26 ( 0.00%) address == usize::MAX . } . . /// Helper type to allow accessing the reference counts without . /// making any assertions about the data field. . struct WeakInner<'a> { . weak: &'a Cell, . strong: &'a Cell, . } -- line 2096 ---------------------------------------- -- line 2299 ---------------------------------------- . }) . .unwrap_or(0) . } . . /// Returns `None` when the pointer is dangling and there is no allocated `RcBox`, . /// (i.e., when this `Weak` was created by `Weak::new`). . #[inline] . fn inner(&self) -> Option> { 1 ( 0.00%) if is_dangling(self.ptr.as_ptr()) { . None . } else { . // We are careful to *not* create a reference covering the "data" field, as . // the field may be mutated concurrently (for example, if the last `Rc` . // is dropped, the data field will be dropped in-place). . Some(unsafe { . let ptr = self.ptr.as_ptr(); . WeakInner { strong: &(*ptr).strong, weak: &(*ptr).weak } -- line 2315 ---------------------------------------- -- line 2391 ---------------------------------------- . /// assert!(other_weak_foo.upgrade().is_none()); . /// ``` . fn drop(&mut self) { . let inner = if let Some(inner) = self.inner() { inner } else { return }; . . inner.dec_weak(); . // the weak count starts at 1, and will only go to zero if all . // the strong pointers have disappeared. 2 ( 0.00%) if inner.weak() == 0 { . unsafe { . Global.deallocate(self.ptr.cast(), Layout::for_value_raw(self.ptr.as_ptr())); . } . } . } . } . . #[stable(feature = "rc_weak", since = "1.4.0")] -- line 2407 ---------------------------------------- -- line 2469 ---------------------------------------- . . #[inline] . fn strong(&self) -> usize { . self.strong_ref().get() . } . . #[inline] . fn inc_strong(&self) { 3,404,509 ( 0.08%) let strong = self.strong(); . . // We want to abort on overflow instead of dropping the value. . // The reference count will never be zero when this is called; . // nevertheless, we insert an abort here to hint LLVM at . // an otherwise missed optimization. 10,263,792 ( 0.25%) if strong == 0 || strong == usize::MAX { . abort(); . } 3,478 ( 0.00%) self.strong_ref().set(strong + 1); . } . . #[inline] . fn dec_strong(&self) { 17,156,194 ( 0.43%) self.strong_ref().set(self.strong() - 1); . } . . #[inline] . fn weak(&self) -> usize { . self.weak_ref().get() . } . . #[inline] -- line 2499 ---------------------------------------- -- line 2507 ---------------------------------------- . if weak == 0 || weak == usize::MAX { . abort(); . } . self.weak_ref().set(weak + 1); . } . . #[inline] . fn dec_weak(&self) { 4,222,344 ( 0.10%) self.weak_ref().set(self.weak() - 1); . } . } . . impl RcInnerPtr for RcBox { . #[inline(always)] . fn weak_ref(&self) -> &Cell { . &self.weak . } -- line 2523 ---------------------------------------- 5,510,543 ( 0.14%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/convert/mod.rs -------------------------------------------------------------------------------- Ir -- line 494 ---------------------------------------- . // As lifts over &mut . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_convert", issue = "88674")] . impl const AsRef for &mut T . where . T: ~const AsRef, . { . fn as_ref(&self) -> &U { 113,478 ( 0.00%) >::as_ref(*self) . } . } . . // FIXME (#45742): replace the above impls for &/&mut with the following more general one: . // // As lifts over Deref . // impl>, U: ?Sized> AsRef for D { . // fn as_ref(&self) -> &U { . // self.deref().as_ref() -- line 510 ---------------------------------------- -- line 514 ---------------------------------------- . // AsMut lifts over &mut . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_convert", issue = "88674")] . impl const AsMut for &mut T . where . T: ~const AsMut, . { . fn as_mut(&mut self) -> &mut U { 22,143 ( 0.00%) (*self).as_mut() . } . } . . // FIXME (#45742): replace the above impl for &mut with the following more general one: . // // AsMut lifts over DerefMut . // impl>, U: ?Sized> AsMut for D { . // fn as_mut(&mut self) -> &mut U { . // self.deref_mut().as_mut() -- line 530 ---------------------------------------- -- line 533 ---------------------------------------- . . // From implies Into . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_convert", issue = "88674")] . impl const Into for T . where . U: ~const From, . { 829,202 ( 0.02%) fn into(self) -> U { 12,022,834 ( 0.30%) U::from(self) 835,112 ( 0.02%) } . } . . // From (and thus Into) is reflexive . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_convert", issue = "88674")] . impl const From for T { . fn from(t: T) -> T { . t -- line 551 ---------------------------------------- 20,372 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/iter/adapters/take.rs -------------------------------------------------------------------------------- Ir -- line 27 ---------------------------------------- . impl Iterator for Take . where . I: Iterator, . { . type Item = ::Item; . . #[inline] . fn next(&mut self) -> Option<::Item> { 5,615,826 ( 0.14%) if self.n != 0 { 2,443 ( 0.00%) self.n -= 1; . self.iter.next() . } else { 1 ( 0.00%) None . } . } . . #[inline] . fn nth(&mut self, n: usize) -> Option { . if self.n > n { . self.n -= n + 1; . self.iter.nth(n) -- line 47 ---------------------------------------- -- line 51 ---------------------------------------- . self.n = 0; . } . None . } . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 3,444 ( 0.00%) if self.n == 0 { . return (0, Some(0)); . } . . let (lower, upper) = self.iter.size_hint(); . . let lower = cmp::min(lower, self.n); . 861 ( 0.00%) let upper = match upper { . Some(x) if x < self.n => Some(x), . _ => Some(self.n), . }; . . (lower, upper) . } . . #[inline] -- line 75 ---------------------------------------- -- line 79 ---------------------------------------- . Fold: FnMut(Acc, Self::Item) -> R, . R: Try, . { . fn check<'a, T, Acc, R: Try>( . n: &'a mut usize, . mut fold: impl FnMut(Acc, T) -> R + 'a, . ) -> impl FnMut(Acc, T) -> ControlFlow + 'a { . move |acc, x| { 4,170 ( 0.00%) *n -= 1; 1,058 ( 0.00%) let r = fold(acc, x); 5,770 ( 0.00%) if *n == 0 { ControlFlow::Break(r) } else { ControlFlow::from_try(r) } . } . } . 942 ( 0.00%) if self.n == 0 { . try { init } . } else { . let n = &mut self.n; . self.iter.try_fold(init, check(n, fold)).into_try() . } . } . . #[inline] -- line 101 ---------------------------------------- 43,708 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs -------------------------------------------------------------------------------- Ir -- line 36 ---------------------------------------- . use rustc_session::parse::ParseSess; . use rustc_span::source_map::{MultiSpan, Span, DUMMY_SP}; . use rustc_span::symbol::{kw, sym, Ident, Symbol}; . use tracing::debug; . . use std::ops::Range; . use std::{cmp, mem, slice}; . 22,116 ( 0.00%) bitflags::bitflags! { . struct Restrictions: u8 { . const STMT_EXPR = 1 << 0; . const NO_STRUCT_LITERAL = 1 << 1; . const CONST_EXPR = 1 << 2; . } . } . . #[derive(Clone, Copy, PartialEq, Debug)] -- line 52 ---------------------------------------- -- line 104 ---------------------------------------- . $self.bump(); . return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_token.span, ty); . } . } . } . }; . } . 502,570 ( 0.01%) #[derive(Clone)] . pub struct Parser<'a> { 18,622 ( 0.00%) pub sess: &'a ParseSess, . /// The current token. 17,556 ( 0.00%) pub token: Token, . /// The spacing for the current token 8,916 ( 0.00%) pub token_spacing: Spacing, . /// The previous token. 26,334 ( 0.00%) pub prev_token: Token, 9,054 ( 0.00%) pub capture_cfg: bool, 18,246 ( 0.00%) restrictions: Restrictions, 17,832 ( 0.00%) expected_tokens: Vec, . // Important: This must only be advanced from `next_tok` . // to ensure that `token_cursor.num_next_calls` is updated properly . token_cursor: TokenCursor, 17,832 ( 0.00%) desugar_doc_comments: bool, . /// This field is used to keep track of how many left angle brackets we have seen. This is . /// required in order to detect extra leading left angle brackets (`<` characters) and error . /// appropriately. . /// . /// See the comments in the `parse_path_segment` function for more details. 17,832 ( 0.00%) unmatched_angle_bracket_count: u32, 26,748 ( 0.00%) max_angle_bracket_count: u32, . /// A list of all unclosed delimiters found by the lexer. If an entry is used for error recovery . /// it gets removed from here. Every entry left at the end gets emitted as an independent . /// error. 8,916 ( 0.00%) pub(super) unclosed_delims: Vec, . last_unexpected_token_span: Option, . /// Span pointing at the `:` for the last type ascription the parser has seen, and whether it . /// looked like it could have been a mistyped path or literal `Option:Some(42)`). . pub last_type_ascription: Option<(Span, bool /* likely path typo */)>, . /// If present, this `Parser` is not parsing Rust code but rather a macro call. . subparser_name: Option<&'static str>, . capture_state: CaptureState, . /// This allows us to recover when the user forget to add braces around -- line 146 ---------------------------------------- -- line 173 ---------------------------------------- . /// the first macro inner attribute to invoke a proc-macro). . /// When create a `TokenStream`, the inner attributes get inserted . /// into the proper place in the token stream. . pub type ReplaceRange = (Range, Vec<(FlatToken, Spacing)>); . . /// Controls how we capture tokens. Capturing can be expensive, . /// so we try to avoid performing capturing in cases where . /// we will never need an `AttrAnnotatedTokenStream` 8,916 ( 0.00%) #[derive(Copy, Clone)] . pub enum Capturing { . /// We aren't performing any capturing - this is the default mode. . No, . /// We are capturing tokens . Yes, . } . 36,592 ( 0.00%) #[derive(Clone)] . struct CaptureState { 35,664 ( 0.00%) capturing: Capturing, 8,916 ( 0.00%) replace_ranges: Vec, . inner_attr_ranges: FxHashMap, . } . . impl<'a> Drop for Parser<'a> { . fn drop(&mut self) { 32,662 ( 0.00%) emit_unclosed_delims(&mut self.unclosed_delims, &self.sess); . } . } . 157,920 ( 0.00%) #[derive(Clone)] . struct TokenCursor { . frame: TokenCursorFrame, 36,160 ( 0.00%) stack: Vec, . desugar_doc_comments: bool, . // Counts the number of calls to `next` or `next_desugared`, . // depending on whether `desugar_doc_comments` is set. 11,936 ( 0.00%) num_next_calls: usize, . // During parsing, we may sometimes need to 'unglue' a . // glued token into two component tokens . // (e.g. '>>' into '>' and '>), so that the parser . // can consume them one at a time. This process . // bypasses the normal capturing mechanism . // (e.g. `num_next_calls` will not be incremented), . // since the 'unglued' tokens due not exist in . // the original `TokenStream`. -- line 217 ---------------------------------------- -- line 226 ---------------------------------------- . // in `Option>` requires us to unglue . // the trailing `>>` token. The `break_last_token` . // field is used to track this token - it gets . // appended to the captured stream when . // we evaluate a `LazyTokenStream` . break_last_token: bool, . } . 72,121 ( 0.00%) #[derive(Clone)] . struct TokenCursorFrame { 20,912 ( 0.00%) delim: token::DelimToken, . span: DelimSpan, . open_delim: bool, 41,824 ( 0.00%) tree_cursor: tokenstream::Cursor, . close_delim: bool, . } . . impl TokenCursorFrame { . fn new(span: DelimSpan, delim: DelimToken, tts: TokenStream) -> Self { 9,600 ( 0.00%) TokenCursorFrame { . delim, . span, . open_delim: false, 355,966 ( 0.01%) tree_cursor: tts.into_trees(), . close_delim: false, . } . } . } . . impl TokenCursor { 38,823,804 ( 0.96%) fn next(&mut self) -> (Token, Spacing) { . loop { 18,652,149 ( 0.46%) let (tree, spacing) = if !self.frame.open_delim { 352,126 ( 0.01%) self.frame.open_delim = true; 1,760,630 ( 0.04%) TokenTree::open_tt(self.frame.span, self.frame.delim).into() 38,094,842 ( 0.95%) } else if let Some(tree) = self.frame.tree_cursor.next_with_spacing() { . tree 1,433,876 ( 0.04%) } else if !self.frame.close_delim { 357,467 ( 0.01%) self.frame.close_delim = true; 1,787,335 ( 0.04%) TokenTree::close_tt(self.frame.span, self.frame.delim).into() 714,934 ( 0.02%) } else if let Some(frame) = self.stack.pop() { 4,647,071 ( 0.12%) self.frame = frame; . continue; . } else { 36,072 ( 0.00%) (TokenTree::Token(Token::new(token::Eof, DUMMY_SP)), Spacing::Alone) . }; . 7,174,886 ( 0.18%) match tree { . TokenTree::Token(token) => { 25,882,536 ( 0.64%) return (token, spacing); . } . TokenTree::Delimited(sp, delim, tts) => { . let frame = TokenCursorFrame::new(sp, delim, tts); . self.stack.push(mem::replace(&mut self.frame, frame)); . } . } . } 25,882,536 ( 0.64%) } . 28,511,040 ( 0.71%) fn next_desugared(&mut self) -> (Token, Spacing) { 8,553,312 ( 0.21%) let (data, attr_style, sp) = match self.next() { . (Token { kind: token::DocComment(_, attr_style, data), span }, _) => { . (data, attr_style, span) . } 14,255,520 ( 0.35%) tok => return tok, . }; . . // Searches for the occurrences of `"#*` and returns the minimum number of `#`s . // required to wrap the text. . let mut num_of_hashes = 0; . let mut count = 0; . for ch in data.as_str().chars() { . count = match ch { -- line 298 ---------------------------------------- -- line 332 ---------------------------------------- . .iter() . .cloned() . .collect::() . }, . ), . )); . . self.next() 25,659,936 ( 0.64%) } . } . 7,390 ( 0.00%) #[derive(Debug, Clone, PartialEq)] . enum TokenType { 5,912 ( 0.00%) Token(TokenKind), . Keyword(Symbol), . Operator, . Lifetime, . Ident, . Path, . Type, . Const, . } -- line 353 ---------------------------------------- -- line 378 ---------------------------------------- . /// The separator token. . sep: Option, . /// `true` if a trailing separator is allowed. . trailing_sep_allowed: bool, . } . . impl SeqSep { . fn trailing_allowed(t: TokenKind) -> SeqSep { 18 ( 0.00%) SeqSep { sep: Some(t), trailing_sep_allowed: true } . } . . fn none() -> SeqSep { . SeqSep { sep: None, trailing_sep_allowed: false } . } . } . . pub enum FollowedByType { . Yes, . No, . } . . fn token_descr_opt(token: &Token) -> Option<&'static str> { 80 ( 0.00%) Some(match token.kind { 160 ( 0.00%) _ if token.is_special_ident() => "reserved identifier", 160 ( 0.00%) _ if token.is_used_keyword() => "keyword", 160 ( 0.00%) _ if token.is_unused_keyword() => "reserved keyword", . token::DocComment(..) => "doc comment", . _ => return None, . }) . } . 280 ( 0.00%) pub(super) fn token_descr(token: &Token) -> String { 80 ( 0.00%) let token_str = pprust::token_to_string(token); . match token_descr_opt(token) { . Some(prefix) => format!("{} `{}`", prefix, token_str), 280 ( 0.00%) _ => format!("`{}`", token_str), . } 200 ( 0.00%) } . . impl<'a> Parser<'a> { 26,880 ( 0.00%) pub fn new( . sess: &'a ParseSess, . tokens: TokenStream, . desugar_doc_comments: bool, . subparser_name: Option<&'static str>, . ) -> Self { 1,920 ( 0.00%) let mut start_frame = TokenCursorFrame::new(DelimSpan::dummy(), token::NoDelim, tokens); 3,840 ( 0.00%) start_frame.open_delim = true; . start_frame.close_delim = true; . 59,520 ( 0.00%) let mut parser = Parser { . sess, 1,920 ( 0.00%) token: Token::dummy(), . token_spacing: Spacing::Alone, 1,920 ( 0.00%) prev_token: Token::dummy(), . capture_cfg: false, . restrictions: Restrictions::empty(), . expected_tokens: Vec::new(), . token_cursor: TokenCursor { 11,520 ( 0.00%) frame: start_frame, . stack: Vec::new(), . num_next_calls: 0, . desugar_doc_comments, . break_last_token: false, . }, . desugar_doc_comments, . unmatched_angle_bracket_count: 0, . max_angle_bracket_count: 0, -- line 445 ---------------------------------------- -- line 451 ---------------------------------------- . capturing: Capturing::No, . replace_ranges: Vec::new(), . inner_attr_ranges: Default::default(), . }, . current_closure: None, . }; . . // Make parser point to the first token. 3,840 ( 0.00%) parser.bump(); . . parser 17,280 ( 0.00%) } . . fn next_tok(&mut self, fallback_span: Span) -> (Token, Spacing) { . loop { 19,400,286 ( 0.48%) let (mut next, spacing) = if self.desugar_doc_comments { 11,404,416 ( 0.28%) self.token_cursor.next_desugared() . } else { 1,146,831 ( 0.03%) self.token_cursor.next() . }; 12,933,524 ( 0.32%) self.token_cursor.num_next_calls += 1; . // We've retrieved an token from the underlying . // cursor, so we no longer need to worry about . // an unglued token. See `break_and_eat` for more details 3,233,381 ( 0.08%) self.token_cursor.break_last_token = false; 12,933,524 ( 0.32%) if next.span.is_dummy() { . // Tweak the location for better diagnostics, but keep syntactic context intact. 7,740 ( 0.00%) next.span = fallback_span.with_ctxt(next.span.ctxt()); . } 10,767,097 ( 0.27%) if matches!( 6,466,762 ( 0.16%) next.kind, . token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) . ) { . continue; . } 12,933,524 ( 0.32%) return (next, spacing); . } . } . . pub fn unexpected(&mut self) -> PResult<'a, T> { . match self.expect_one_of(&[], &[]) { . Err(e) => Err(e), . // We can get `Ok(true)` from `recover_closing_delimiter` . // which is called in `expected_one_of_not_found`. . Ok(_) => FatalError.raise(), . } . } . . /// Expects and consumes the token `t`. Signals an error if the next token is not `t`. 58,491 ( 0.00%) pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> { 6,499 ( 0.00%) if self.expected_tokens.is_empty() { 2,460 ( 0.00%) if self.token == *t { 2,050 ( 0.00%) self.bump(); . Ok(false) . } else { . self.unexpected_try_recover(t) . } . } else { 73,068 ( 0.00%) self.expect_one_of(slice::from_ref(t), &[]) . } 97,485 ( 0.00%) } . . /// Expect next token to be edible or inedible token. If edible, . /// then consume it; if inedible, then return without consuming . /// anything. Signal a fatal error if next token is unexpected. 79,356 ( 0.00%) pub fn expect_one_of( . &mut self, . edible: &[TokenKind], . inedible: &[TokenKind], . ) -> PResult<'a, bool /* recovered */> { 13,226 ( 0.00%) if edible.contains(&self.token.kind) { 19,185 ( 0.00%) self.bump(); . Ok(false) . } else if inedible.contains(&self.token.kind) { . // leave it in the input . Ok(false) . } else if self.last_unexpected_token_span == Some(self.token.span) { . FatalError.raise(); . } else { . self.expected_one_of_not_found(edible, inedible) . } 99,195 ( 0.00%) } . . // Public for rustfmt usage. . pub fn parse_ident(&mut self) -> PResult<'a, Ident> { 55,409 ( 0.00%) self.parse_ident_common(true) . } . . fn ident_or_err(&mut self) -> PResult<'a, (Ident, /* is_raw */ bool)> { 42,408 ( 0.00%) self.token.ident().ok_or_else(|| match self.prev_token.kind { . TokenKind::DocComment(..) => { . self.span_err(self.prev_token.span, Error::UselessDocComment) . } . _ => self.expected_ident_found(), . }) . } . 97,958 ( 0.00%) fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> { 13,994 ( 0.00%) let (ident, is_raw) = self.ident_or_err()?; 83,964 ( 0.00%) if !is_raw && ident.is_reserved() { . let mut err = self.expected_ident_found(); . if recover { . err.emit(); . } else { . return Err(err); . } . } 55,976 ( 0.00%) self.bump(); . Ok(ident) 139,940 ( 0.00%) } . . /// Checks if the next token is `tok`, and returns `true` if so. . /// . /// This method will automatically add `tok` to `expected_tokens` if `tok` is not . /// encountered. 983,430 ( 0.02%) fn check(&mut self, tok: &TokenKind) -> bool { 430,506 ( 0.01%) let is_present = self.token == *tok; 296,388 ( 0.01%) if !is_present { 549,014 ( 0.01%) self.expected_tokens.push(TokenType::Token(tok.clone())); . } . is_present 983,430 ( 0.02%) } . . /// Consumes a token 'tok' if it exists. Returns whether the given token was present. 88 ( 0.00%) pub fn eat(&mut self, tok: &TokenKind) -> bool { 179,765 ( 0.00%) let is_present = self.check(tok); 117,712 ( 0.00%) if is_present { 35,123 ( 0.00%) self.bump() . } . is_present 110 ( 0.00%) } . . /// If the next token is the given keyword, returns `true` without eating it. . /// An expectation is also added for diagnostics purposes. 12,475 ( 0.00%) fn check_keyword(&mut self, kw: Symbol) -> bool { 2,560 ( 0.00%) self.expected_tokens.push(TokenType::Keyword(kw)); 84,385 ( 0.00%) self.token.is_keyword(kw) . } . . /// If the next token is the given keyword, eats it and returns `true`. . /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes. . // Public for rustfmt usage. 27,565 ( 0.00%) pub fn eat_keyword(&mut self, kw: Symbol) -> bool { 19,520 ( 0.00%) if self.check_keyword(kw) { 1,648 ( 0.00%) self.bump(); . true . } else { . false . } 27,565 ( 0.00%) } . . fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool { 2,418 ( 0.00%) if self.token.is_keyword(kw) { 594 ( 0.00%) self.bump(); . true . } else { . false . } . } . . /// If the given word is not a keyword, signals an error. . /// If the next token is not the given word, signals an error. . /// Otherwise, eats it. 440 ( 0.00%) fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> { . if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) } 352 ( 0.00%) } . . /// Is the given keyword `kw` followed by a non-reserved identifier? 14,288 ( 0.00%) fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool { 7,144 ( 0.00%) self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()) 16,074 ( 0.00%) } . 46,854 ( 0.00%) fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool { 16,478 ( 0.00%) if ok { . true . } else { 5,480 ( 0.00%) self.expected_tokens.push(typ); . false . } 46,854 ( 0.00%) } . . fn check_ident(&mut self) -> bool { 5,396 ( 0.00%) self.check_or_expected(self.token.is_ident(), TokenType::Ident) . } . 23,588 ( 0.00%) fn check_path(&mut self) -> bool { 51,148 ( 0.00%) self.check_or_expected(self.token.is_path_start(), TokenType::Path) 29,485 ( 0.00%) } . . fn check_type(&mut self) -> bool { 1,604 ( 0.00%) self.check_or_expected(self.token.can_begin_type(), TokenType::Type) . } . . fn check_const_arg(&mut self) -> bool { 1,592 ( 0.00%) self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const) . } . 6,120 ( 0.00%) fn check_inline_const(&self, dist: usize) -> bool { 3,400 ( 0.00%) self.is_keyword_ahead(dist, &[kw::Const]) . && self.look_ahead(dist + 1, |t| match t.kind { . token::Interpolated(ref nt) => matches!(**nt, token::NtBlock(..)), . token::OpenDelim(DelimToken::Brace) => true, . _ => false, . }) 6,120 ( 0.00%) } . . /// Checks to see if the next token is either `+` or `+=`. . /// Otherwise returns `false`. . fn check_plus(&mut self) -> bool { 2,224 ( 0.00%) self.check_or_expected( 1,112 ( 0.00%) self.token.is_like_plus(), 1,112 ( 0.00%) TokenType::Token(token::BinOp(token::Plus)), . ) . } . . /// Eats the expected token if it's present possibly breaking . /// compound tokens like multi-character operators in process. . /// Returns `true` if the token was eaten. 77,208 ( 0.00%) fn break_and_eat(&mut self, expected: TokenKind) -> bool { 45,038 ( 0.00%) if self.token.kind == expected { 964 ( 0.00%) self.bump(); . return true; . } 29,760 ( 0.00%) match self.token.kind.break_two_token_op() { 9,328 ( 0.00%) Some((first, second)) if first == expected => { 4 ( 0.00%) let first_span = self.sess.source_map().start_point(self.token.span); 5 ( 0.00%) let second_span = self.token.span.with_lo(first_span.hi()); 9 ( 0.00%) self.token = Token::new(first, first_span); . // Keep track of this token - if we end token capturing now, . // we'll want to append this token to the captured stream. . // . // If we consume any additional tokens, then this token . // is not needed (we'll capture the entire 'glued' token), . // and `next_tok` will set this field to `None` 1 ( 0.00%) self.token_cursor.break_last_token = true; . // Use the spacing of the glued token as the spacing . // of the unglued second token. 14 ( 0.00%) self.bump_with((Token::new(second, second_span), self.token_spacing)); . true . } . _ => { 17,853 ( 0.00%) self.expected_tokens.push(TokenType::Token(expected)); . false . } . } 84,817 ( 0.00%) } . . /// Eats `+` possibly breaking tokens like `+=` in process. . fn eat_plus(&mut self) -> bool { 24 ( 0.00%) self.break_and_eat(token::BinOp(token::Plus)) . } . . /// Eats `&` possibly breaking tokens like `&&` in process. . /// Signals an error if `&` is not eaten. . fn expect_and(&mut self) -> PResult<'a, ()> { 486 ( 0.00%) if self.break_and_eat(token::BinOp(token::And)) { Ok(()) } else { self.unexpected() } . } . . /// Eats `|` possibly breaking tokens like `||` in process. . /// Signals an error if `|` was not eaten. . fn expect_or(&mut self) -> PResult<'a, ()> { 36 ( 0.00%) if self.break_and_eat(token::BinOp(token::Or)) { Ok(()) } else { self.unexpected() } . } . . /// Eats `<` possibly breaking tokens like `<<` in process. 1,446 ( 0.00%) fn eat_lt(&mut self) -> bool { 18,757 ( 0.00%) let ate = self.break_and_eat(token::Lt); 12,478 ( 0.00%) if ate { . // See doc comment for `unmatched_angle_bracket_count`. 788 ( 0.00%) self.unmatched_angle_bracket_count += 1; 795 ( 0.00%) self.max_angle_bracket_count += 1; . debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count); . } . ate 1,446 ( 0.00%) } . . /// Eats `<` possibly breaking tokens like `<<` in process. . /// Signals an error if `<` was not eaten. . fn expect_lt(&mut self) -> PResult<'a, ()> { . if self.eat_lt() { Ok(()) } else { self.unexpected() } . } . . /// Eats `>` possibly breaking tokens like `>>` in process. . /// Signals an error if `>` was not eaten. . fn expect_gt(&mut self) -> PResult<'a, ()> { 1,182 ( 0.00%) if self.break_and_eat(token::Gt) { . // See doc comment for `unmatched_angle_bracket_count`. 591 ( 0.00%) if self.unmatched_angle_bracket_count > 0 { 394 ( 0.00%) self.unmatched_angle_bracket_count -= 1; . debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count); . } . Ok(()) . } else { . self.unexpected() . } . } . . fn expect_any_with_type(&mut self, kets: &[&TokenKind], expect: TokenExpectType) -> bool { . kets.iter().any(|k| match expect { 20,577 ( 0.00%) TokenExpectType::Expect => self.check(k), 90 ( 0.00%) TokenExpectType::NoExpect => self.token == **k, . }) . } . . fn parse_seq_to_before_tokens( . &mut self, . kets: &[&TokenKind], . sep: SeqSep, . expect: TokenExpectType, -- line 759 ---------------------------------------- -- line 761 ---------------------------------------- . ) -> PResult<'a, (Vec, bool /* trailing */, bool /* recovered */)> { . let mut first = true; . let mut recovered = false; . let mut trailing = false; . let mut v = vec![]; . let unclosed_delims = !self.unclosed_delims.is_empty(); . . while !self.expect_any_with_type(kets, expect) { 28,544 ( 0.00%) if let token::CloseDelim(..) | token::Eof = self.token.kind { . break; . } 21,544 ( 0.00%) if let Some(ref t) = sep.sep { 22,858 ( 0.00%) if first { . first = false; . } else { 13,628 ( 0.00%) match self.expect(t) { . Ok(false) => { . self.current_closure.take(); . } . Ok(true) => { . self.current_closure.take(); . recovered = true; . break; . } -- line 784 ---------------------------------------- -- line 857 ---------------------------------------- . e.cancel(); . break; . } . } . } . } . } . } 9,878 ( 0.00%) if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) { . trailing = true; . break; . } . 5,328 ( 0.00%) let t = f(self)?; 1,379 ( 0.00%) v.push(t); . } . 16,012 ( 0.00%) Ok((v, trailing, recovered)) . } . . fn recover_missing_braces_around_closure_body( . &mut self, . closure_spans: ClosureSpans, . mut expect_err: DiagnosticBuilder<'_>, . ) -> PResult<'a, ()> { . let initial_semicolon = self.token.span; -- line 882 ---------------------------------------- -- line 937 ---------------------------------------- . /// `f` must consume tokens until reaching the next separator or . /// closing bracket. . fn parse_seq_to_before_end( . &mut self, . ket: &TokenKind, . sep: SeqSep, . f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, . ) -> PResult<'a, (Vec, bool, bool)> { 15,871 ( 0.00%) self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f) . } . . /// Parses a sequence, including the closing delimiter. The function . /// `f` must consume tokens until reaching the next separator or . /// closing bracket. 34,760 ( 0.00%) fn parse_seq_to_end( . &mut self, . ket: &TokenKind, . sep: SeqSep, . f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, . ) -> PResult<'a, (Vec, bool /* trailing */)> { 11,501 ( 0.00%) let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?; 4,487 ( 0.00%) if !recovered { . self.eat(ket); . } 32,799 ( 0.00%) Ok((val, trailing)) 27,808 ( 0.00%) } . . /// Parses a sequence, including the closing delimiter. The function . /// `f` must consume tokens until reaching the next separator or . /// closing bracket. . fn parse_unspanned_seq( . &mut self, . bra: &TokenKind, . ket: &TokenKind, . sep: SeqSep, . f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, . ) -> PResult<'a, (Vec, bool)> { 11,005 ( 0.00%) self.expect(bra)?; 27,808 ( 0.00%) self.parse_seq_to_end(ket, sep, f) . } . . fn parse_delim_comma_seq( . &mut self, . delim: DelimToken, . f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, . ) -> PResult<'a, (Vec, bool)> { . self.parse_unspanned_seq( 3,815 ( 0.00%) &token::OpenDelim(delim), 4,166 ( 0.00%) &token::CloseDelim(delim), . SeqSep::trailing_allowed(token::Comma), . f, . ) . } . . fn parse_paren_comma_seq( . &mut self, . f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, . ) -> PResult<'a, (Vec, bool)> { . self.parse_delim_comma_seq(token::Paren, f) . } . . /// Advance the parser by one token using provided token as the next one. 42,033,966 ( 1.04%) fn bump_with(&mut self, (next_token, next_spacing): (Token, Spacing)) { . // Bumping after EOF is a bad sign, usually an infinite loop. 19,400,292 ( 0.48%) if self.prev_token.kind == TokenKind::Eof { . let msg = "attempted to bump the parser past EOF (may be stuck in a loop)"; . self.span_bug(self.token.span, msg); . } . . // Update the current and previous tokens. 12,933,528 ( 0.32%) self.prev_token = mem::replace(&mut self.token, next_token); 3,233,382 ( 0.08%) self.token_spacing = next_spacing; . . // Diagnostics. 3,233,382 ( 0.08%) self.expected_tokens.clear(); . } . . /// Advance the parser by one token. 25,867,048 ( 0.64%) pub fn bump(&mut self) { 12,933,524 ( 0.32%) let next_token = self.next_tok(self.token.span); 19,400,286 ( 0.48%) self.bump_with(next_token); 25,867,048 ( 0.64%) } . . /// Look-ahead `dist` tokens of `self.token` and get access to that token there. . /// When `dist == 0` then the current token is looked at. 80 ( 0.00%) pub fn look_ahead(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R { 2,198 ( 0.00%) if dist == 0 { 844 ( 0.00%) return looker(&self.token); . } . 23,627 ( 0.00%) let frame = &self.token_cursor.frame; 27,331 ( 0.00%) if frame.delim != DelimToken::NoDelim { . let all_normal = (0..dist).all(|i| { 74,720 ( 0.00%) let token = frame.tree_cursor.look_ahead(i); 102,183 ( 0.00%) !matches!(token, Some(TokenTree::Delimited(_, DelimToken::NoDelim, _))) . }); . if all_normal { 124,397 ( 0.00%) return match frame.tree_cursor.look_ahead(dist - 1) { 47,870 ( 0.00%) Some(tree) => match tree { 23,673 ( 0.00%) TokenTree::Token(token) => looker(token), . TokenTree::Delimited(dspan, delim, _) => { 4,343 ( 0.00%) looker(&Token::new(token::OpenDelim(*delim), dspan.open)) . } . }, 11,025 ( 0.00%) None => looker(&Token::new(token::CloseDelim(frame.delim), frame.span.close)), . }; . } . } . . let mut cursor = self.token_cursor.clone(); . let mut i = 0; 1,941 ( 0.00%) let mut token = Token::dummy(); 120 ( 0.00%) while i < dist { 13,634 ( 0.00%) token = cursor.next().0; 6,037 ( 0.00%) if matches!( 3,872 ( 0.00%) token.kind, . token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) . ) { . continue; . } 50 ( 0.00%) i += 1; . } 282 ( 0.00%) return looker(&token); 90 ( 0.00%) } . . /// Returns whether any of the given keywords are `dist` tokens ahead of the current one. 8,091 ( 0.00%) fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool { 1,975 ( 0.00%) self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw))) 8,091 ( 0.00%) } . . /// Parses asyncness: `async` or nothing. . fn parse_asyncness(&mut self) -> Async { . if self.eat_keyword(kw::Async) { . let span = self.prev_token.uninterpolated_span(); . Async::Yes { span, closure_id: DUMMY_NODE_ID, return_impl_trait_id: DUMMY_NODE_ID } . } else { . Async::No . } . } . . /// Parses unsafety: `unsafe` or nothing. 362 ( 0.00%) fn parse_unsafety(&mut self) -> Unsafe { . if self.eat_keyword(kw::Unsafe) { . Unsafe::Yes(self.prev_token.uninterpolated_span()) . } else { . Unsafe::No . } 1,448 ( 0.00%) } . . /// Parses constness: `const` or nothing. 4,008 ( 0.00%) fn parse_constness(&mut self) -> Const { . // Avoid const blocks to be parsed as const items 1,278 ( 0.00%) if self.look_ahead(1, |t| t != &token::OpenDelim(DelimToken::Brace)) . && self.eat_keyword(kw::Const) . { 10 ( 0.00%) Const::Yes(self.prev_token.uninterpolated_span()) . } else { . Const::No . } 7,014 ( 0.00%) } . . /// Parses inline const expressions. . fn parse_const_block(&mut self, span: Span, pat: bool) -> PResult<'a, P> { . if pat { . self.sess.gated_spans.gate(sym::inline_const_pat, span); . } else { . self.sess.gated_spans.gate(sym::inline_const, span); . } -- line 1104 ---------------------------------------- -- line 1110 ---------------------------------------- . }; . let blk_span = anon_const.value.span; . Ok(self.mk_expr(span.to(blk_span), ExprKind::ConstBlock(anon_const), AttrVec::new())) . } . . /// Parses mutability (`mut` or nothing). . fn parse_mutability(&mut self) -> Mutability { . if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not } 156 ( 0.00%) } . . /// Possibly parses mutability (`const` or `mut`). . fn parse_const_or_mut(&mut self) -> Option { . if self.eat_keyword(kw::Mut) { . Some(Mutability::Mut) . } else if self.eat_keyword(kw::Const) { . Some(Mutability::Not) . } else { . None . } . } . . fn parse_field_name(&mut self) -> PResult<'a, Ident> { 346 ( 0.00%) if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind . { . self.expect_no_suffix(self.token.span, "a tuple index", suffix); . self.bump(); . Ok(Ident::new(symbol, self.prev_token.span)) . } else { 519 ( 0.00%) self.parse_ident_common(true) . } . } . . fn parse_mac_args(&mut self) -> PResult<'a, P> { 3,557 ( 0.00%) self.parse_mac_args_common(true).map(P) . } . . fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> { 63 ( 0.00%) self.parse_mac_args_common(false) . } . 11,349 ( 0.00%) fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> { 10,088 ( 0.00%) Ok( 6,633 ( 0.00%) if self.check(&token::OpenDelim(DelimToken::Paren)) 249 ( 0.00%) || self.check(&token::OpenDelim(DelimToken::Bracket)) 243 ( 0.00%) || self.check(&token::OpenDelim(DelimToken::Brace)) . { 5,016 ( 0.00%) match self.parse_token_tree() { 6,270 ( 0.00%) TokenTree::Delimited(dspan, delim, tokens) => . // We've confirmed above that there is a delimiter so unwrapping is OK. . { 2,508 ( 0.00%) MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens) . } . _ => unreachable!(), . } 14 ( 0.00%) } else if !delimited_only { . if self.eat(&token::Eq) { 1 ( 0.00%) let eq_span = self.prev_token.span; . . // Collect tokens because they are used during lowering to HIR. 1 ( 0.00%) let expr = self.parse_expr_force_collect()?; 1 ( 0.00%) let span = expr.span; . 5 ( 0.00%) let token_kind = token::Interpolated(Lrc::new(token::NtExpr(expr))); 9 ( 0.00%) MacArgs::Eq(eq_span, Token::new(token_kind, span)) . } else { . MacArgs::Empty . } . } else { . return self.unexpected(); . }, . ) 8,827 ( 0.00%) } . . fn parse_or_use_outer_attributes( . &mut self, . already_parsed_attrs: Option, . ) -> PResult<'a, AttrWrapper> { 19,377 ( 0.00%) if let Some(attrs) = already_parsed_attrs { . Ok(attrs) . } else { 12,310 ( 0.00%) self.parse_outer_attributes() . } . } . . /// Parses a single token tree from the input. 5,241,224 ( 0.13%) pub(crate) fn parse_token_tree(&mut self) -> TokenTree { 4,254,323 ( 0.11%) match self.token.kind { . token::OpenDelim(..) => { . let depth = self.token_cursor.stack.len(); . . // We keep advancing the token cursor until we hit . // the matching `CloseDelim` token. 6,336,434 ( 0.16%) while !(depth == self.token_cursor.stack.len() . && matches!(self.token.kind, token::CloseDelim(_))) . { . // Advance one token at a time, so `TokenCursor::next()` . // can capture these tokens if necessary. 5,036,890 ( 0.13%) self.bump(); . } . // We are still inside the frame corresponding . // to the delimited stream we captured, so grab . // the tokens from this frame. . let frame = &self.token_cursor.frame; 165,874 ( 0.00%) let stream = frame.tree_cursor.stream.clone(); 165,874 ( 0.00%) let span = frame.span; 82,937 ( 0.00%) let delim = frame.delim; . // Consume close delimiter 165,874 ( 0.00%) self.bump(); 414,685 ( 0.01%) TokenTree::Delimited(span, delim, stream) . } . token::CloseDelim(_) | token::Eof => unreachable!(), . _ => { 1,144,432 ( 0.03%) self.bump(); 2,861,080 ( 0.07%) TokenTree::Token(self.prev_token.clone()) . } . } 4,586,071 ( 0.11%) } . . /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF. . pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec> { . let mut tts = Vec::new(); . while self.token != token::Eof { . tts.push(self.parse_token_tree()); . } . Ok(tts) -- line 1234 ---------------------------------------- -- line 1244 ---------------------------------------- . } . TokenStream::new(result) . } . . /// Evaluates the closure with restrictions in place. . /// . /// Afters the closure is evaluated, restrictions are reset. . fn with_res(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T { 6,457 ( 0.00%) let old = self.restrictions; 6,928 ( 0.00%) self.restrictions = res; . let res = f(self); 6,928 ( 0.00%) self.restrictions = old; . res . } . 7,504 ( 0.00%) fn is_crate_vis(&self) -> bool { 4,690 ( 0.00%) self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep) 8,442 ( 0.00%) } . . /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`, . /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`. . /// If the following element can't be a tuple (i.e., it's a function definition), then . /// it's not a tuple struct field), and the contents within the parentheses aren't valid, . /// so emit a proper diagnostic. . // Public for rustfmt usage. 7,100 ( 0.00%) pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> { 2,005 ( 0.00%) maybe_whole!(self, NtVis, |x| x); . 665 ( 0.00%) self.expected_tokens.push(TokenType::Keyword(kw::Crate)); 2,660 ( 0.00%) if self.is_crate_vis() { . self.bump(); // `crate` . self.sess.gated_spans.gate(sym::crate_visibility_modifier, self.prev_token.span); . return Ok(Visibility { . span: self.prev_token.span, . kind: VisibilityKind::Crate(CrateSugar::JustCrate), . tokens: None, . }); . } . . if !self.eat_keyword(kw::Pub) { . // We need a span for our `Spanned`, but there's inherently no . // keyword to grab a span from for inherited visibility; an empty span at the . // beginning of the current token would seem to be the "Schelling span". 552 ( 0.00%) return Ok(Visibility { 1,656 ( 0.00%) span: self.token.span.shrink_to_lo(), . kind: VisibilityKind::Inherited, . tokens: None, . }); . } 113 ( 0.00%) let lo = self.prev_token.span; . 565 ( 0.00%) if self.check(&token::OpenDelim(token::Paren)) { . // We don't `self.bump()` the `(` yet because this might be a struct definition where . // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`. . // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so . // by the following tokens. 972 ( 0.00%) if self.is_keyword_ahead(1, &[kw::Crate]) && self.look_ahead(2, |t| t != &token::ModSep) . // account for `pub(crate::foo)` . { . // Parse `pub(crate)`. 324 ( 0.00%) self.bump(); // `(` 216 ( 0.00%) self.bump(); // `crate` 324 ( 0.00%) self.expect(&token::CloseDelim(token::Paren))?; // `)` 108 ( 0.00%) let vis = VisibilityKind::Crate(CrateSugar::PubCrate); . return Ok(Visibility { 324 ( 0.00%) span: lo.to(self.prev_token.span), . kind: vis, . tokens: None, . }); . } else if self.is_keyword_ahead(1, &[kw::In]) { . // Parse `pub(in path)`. . self.bump(); // `(` . self.bump(); // `in` . let path = self.parse_path(PathStyle::Mod)?; // `path` -- line 1317 ---------------------------------------- -- line 1338 ---------------------------------------- . } else if let FollowedByType::No = fbt { . // Provide this diagnostic if a type cannot follow; . // in particular, if this is not a tuple struct. . self.recover_incorrect_vis_restriction()?; . // Emit diagnostic, but continue with public visibility. . } . } . 15 ( 0.00%) Ok(Visibility { span: lo, kind: VisibilityKind::Public, tokens: None }) 6,390 ( 0.00%) } . . /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }` . fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> { . self.bump(); // `(` . let path = self.parse_path(PathStyle::Mod)?; . self.expect(&token::CloseDelim(token::Paren))?; // `)` . . let msg = "incorrect visibility restriction"; -- line 1355 ---------------------------------------- -- line 1370 ---------------------------------------- . ) . .emit(); . . Ok(()) . } . . /// Parses `extern string_literal?`. . fn parse_extern(&mut self) -> Extern { 101 ( 0.00%) if self.eat_keyword(kw::Extern) { Extern::from_abi(self.parse_abi()) } else { Extern::None } . } . . /// Parses a string literal as an ABI spec. . fn parse_abi(&mut self) -> Option { . match self.parse_str_lit() { . Ok(str_lit) => Some(str_lit), . Err(Some(lit)) => match lit.kind { . ast::LitKind::Err(_) => None, -- line 1386 ---------------------------------------- -- line 1395 ---------------------------------------- . .emit(); . None . } . }, . Err(None) => None, . } . } . 1,110 ( 0.00%) pub fn collect_tokens_no_attrs( . &mut self, . f: impl FnOnce(&mut Self) -> PResult<'a, R>, . ) -> PResult<'a, R> { . // The only reason to call `collect_tokens_no_attrs` is if you want tokens, so use . // `ForceCollect::Yes` . self.collect_tokens_trailing_token( . AttrWrapper::empty(), . ForceCollect::Yes, 165 ( 0.00%) |this, _attrs| Ok((f(this)?, TrailingToken::None)), . ) 1,110 ( 0.00%) } . . /// `::{` or `::*` 105,528 ( 0.00%) fn is_import_coupler(&mut self) -> bool { 52,764 ( 0.00%) self.check(&token::ModSep) . && self.look_ahead(1, |t| { 106,339 ( 0.00%) *t == token::OpenDelim(token::Brace) || *t == token::BinOp(token::Star) . }) 60,138 ( 0.00%) } . . pub fn clear_expected_tokens(&mut self) { . self.expected_tokens.clear(); . } . } . . crate fn make_unclosed_delims_error( . unmatched: UnmatchedBrace, -- line 1430 ---------------------------------------- -- line 1450 ---------------------------------------- . err.span_label(sp, "closing delimiter possibly meant for this"); . } . if let Some(sp) = unmatched.unclosed_span { . err.span_label(sp, "unclosed delimiter"); . } . Some(err) . } . 86,688 ( 0.00%) pub fn emit_unclosed_delims(unclosed_delims: &mut Vec, sess: &ParseSess) { 43,344 ( 0.00%) *sess.reached_eof.borrow_mut() |= . unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none()); 43,344 ( 0.00%) for unmatched in unclosed_delims.drain(..) { . if let Some(mut e) = make_unclosed_delims_error(unmatched, sess) { . e.emit(); . } . } 86,688 ( 0.00%) } . . /// A helper struct used when building an `AttrAnnotatedTokenStream` from . /// a `LazyTokenStream`. Both delimiter and non-delimited tokens . /// are stored as `FlatToken::Token`. A vector of `FlatToken`s . /// is then 'parsed' to build up an `AttrAnnotatedTokenStream` with nested . /// `AttrAnnotatedTokenTree::Delimited` tokens . #[derive(Debug, Clone)] . pub enum FlatToken { -- line 1474 ---------------------------------------- 10,893,731 ( 0.27%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/std/src/alloc.rs -------------------------------------------------------------------------------- Ir -- line 342 ---------------------------------------- . . // for symbol names src/librustc_ast/expand/allocator.rs . // for signatures src/librustc_allocator/lib.rs . . // linkage directives are provided as part of the current compiler allocator . // ABI . . #[rustc_std_internal_symbol] 6,508,888 ( 0.16%) pub unsafe extern "C" fn __rdl_alloc(size: usize, align: usize) -> *mut u8 { . // SAFETY: see the guarantees expected by `Layout::from_size_align` and . // `GlobalAlloc::alloc`. . unsafe { . let layout = Layout::from_size_align_unchecked(size, align); . System.alloc(layout) . } . } . -- line 358 ---------------------------------------- -- line 359 ---------------------------------------- . #[rustc_std_internal_symbol] . pub unsafe extern "C" fn __rdl_dealloc(ptr: *mut u8, size: usize, align: usize) { . // SAFETY: see the guarantees expected by `Layout::from_size_align` and . // `GlobalAlloc::dealloc`. . unsafe { System.dealloc(ptr, Layout::from_size_align_unchecked(size, align)) } . } . . #[rustc_std_internal_symbol] 760,064 ( 0.02%) pub unsafe extern "C" fn __rdl_realloc( . ptr: *mut u8, . old_size: usize, . align: usize, . new_size: usize, . ) -> *mut u8 { . // SAFETY: see the guarantees expected by `Layout::from_size_align` and . // `GlobalAlloc::realloc`. . unsafe { . let old_layout = Layout::from_size_align_unchecked(old_size, align); . System.realloc(ptr, old_layout, new_size) . } . } . . #[rustc_std_internal_symbol] 30,704 ( 0.00%) pub unsafe extern "C" fn __rdl_alloc_zeroed(size: usize, align: usize) -> *mut u8 { . // SAFETY: see the guarantees expected by `Layout::from_size_align` and . // `GlobalAlloc::alloc_zeroed`. . unsafe { . let layout = Layout::from_size_align_unchecked(size, align); . System.alloc_zeroed(layout) . } . } . } -- line 390 ---------------------------------------- -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/clone.rs -------------------------------------------------------------------------------- Ir -- line 113 ---------------------------------------- . /// ``` . /// # #![allow(noop_method_call)] . /// let hello = "Hello"; // &str implements Clone . /// . /// assert_eq!("Hello", hello.clone()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[must_use = "cloning is often expensive and is not expected to have side effects"] 9,026 ( 0.00%) fn clone(&self) -> Self; . . /// Performs copy-assignment from `source`. . /// . /// `a.clone_from(&b)` is equivalent to `a = b.clone()` in functionality, . /// but can be overridden to reuse the resources of `a` to avoid unnecessary . /// allocations. . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] -- line 129 ---------------------------------------- -- line 176 ---------------------------------------- . . macro_rules! impl_clone { . ($($t:ty)*) => { . $( . #[stable(feature = "rust1", since = "1.0.0")] . impl Clone for $t { . #[inline] . fn clone(&self) -> Self { 6,013,098 ( 0.15%) *self . } . } . )* . } . } . . impl_clone! { . usize u8 u16 u32 u64 u128 -- line 192 ---------------------------------------- 1,992 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe.rs -------------------------------------------------------------------------------- Ir -- line 23 ---------------------------------------- . struct Delimited { . delim: token::DelimToken, . tts: Vec, . } . . impl Delimited { . /// Returns a `self::TokenTree` with a `Span` corresponding to the opening delimiter. . fn open_tt(&self, span: DelimSpan) -> TokenTree { 24,292 ( 0.00%) TokenTree::token(token::OpenDelim(self.delim), span.open) . } . . /// Returns a `self::TokenTree` with a `Span` corresponding to the closing delimiter. . fn close_tt(&self, span: DelimSpan) -> TokenTree { 2,617,508 ( 0.06%) TokenTree::token(token::CloseDelim(self.delim), span.close) . } . } . . #[derive(Clone, PartialEq, Encodable, Decodable, Debug)] . struct SequenceRepetition { . /// The sequence of token trees . tts: Vec, . /// The optional separator . separator: Option, . /// Whether the sequence can be repeated zero (*), or one or more times (+) . kleene: KleeneToken, . /// The number of `Match`s that appear in the sequence (and subsequences) . num_captures: usize, . } . 224 ( 0.00%) #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)] . struct KleeneToken { . span: Span, . op: KleeneOp, . } . . impl KleeneToken { . fn new(op: KleeneOp, span: Span) -> KleeneToken { . KleeneToken { span, op } 12 ( 0.00%) } . } . . /// A Kleene-style [repetition operator](https://en.wikipedia.org/wiki/Kleene_star) . /// for token sequences. 377 ( 0.00%) #[derive(Clone, PartialEq, Encodable, Decodable, Debug, Copy)] . enum KleeneOp { . /// Kleene star (`*`) for zero or more repetitions . ZeroOrMore, . /// Kleene plus (`+`) for one or more repetitions . OneOrMore, . /// Kleene optional (`?`) for zero or one repetitions . ZeroOrOne, . } . . /// Similar to `tokenstream::TokenTree`, except that `$i`, `$i:ident`, and `$(...)` . /// are "first-class" token trees. Useful for parsing macros. 20,486,153 ( 0.51%) #[derive(Debug, Clone, PartialEq, Encodable, Decodable)] . enum TokenTree { 22,184 ( 0.00%) Token(Token), 668,349 ( 0.02%) Delimited(DelimSpan, Lrc), . /// A kleene-style repetition sequence 9,780 ( 0.00%) Sequence(DelimSpan, Lrc), . /// e.g., `$var` . MetaVar(Span, Ident), . /// e.g., `$var:expr`. This is only used in the left hand side of MBE macros. 1,317,024 ( 0.03%) MetaVarDecl(Span, Ident /* name to bind */, Option), . } . . impl TokenTree { . /// Return the number of tokens in the tree. . fn len(&self) -> usize { 14,628,901 ( 0.36%) match *self { 4,038,459 ( 0.10%) TokenTree::Delimited(_, ref delimed) => match delimed.delim { . token::NoDelim => delimed.tts.len(), 2,692,306 ( 0.07%) _ => delimed.tts.len() + 2, . }, 6,581,780 ( 0.16%) TokenTree::Sequence(_, ref seq) => seq.tts.len(), . _ => 0, . } . } . . /// Returns `true` if the given token tree is delimited. . fn is_delimited(&self) -> bool { . matches!(*self, TokenTree::Delimited(..)) . } -- line 106 ---------------------------------------- -- line 109 ---------------------------------------- . fn is_token(&self, expected_kind: &TokenKind) -> bool { . match self { . TokenTree::Token(Token { kind: actual_kind, .. }) => actual_kind == expected_kind, . _ => false, . } . } . . /// Gets the `index`-th sub-token-tree. This only makes sense for delimited trees and sequences. 5,957,550 ( 0.15%) fn get_tt(&self, index: usize) -> TokenTree { 8,590,132 ( 0.21%) match (self, index) { 2,008,677 ( 0.05%) (&TokenTree::Delimited(_, ref delimed), _) if delimed.delim == token::NoDelim => { . delimed.tts[index].clone() . } . (&TokenTree::Delimited(span, ref delimed), _) => { 1,339,118 ( 0.03%) if index == 0 { . return delimed.open_tt(span); . } 3,968,994 ( 0.10%) if index == delimed.tts.len() + 1 { . return delimed.close_tt(span); . } 7,150 ( 0.00%) delimed.tts[index - 1].clone() . } 1,316,291 ( 0.03%) (&TokenTree::Sequence(_, ref seq), _) => seq.tts[index].clone(), . _ => panic!("Cannot expand a token tree"), . } 7,943,400 ( 0.20%) } . . /// Retrieves the `TokenTree`'s span. . fn span(&self) -> Span { 26,242 ( 0.00%) match *self { . TokenTree::Token(Token { span, .. }) . | TokenTree::MetaVar(span, _) . | TokenTree::MetaVarDecl(span, _, _) => span, 3,560 ( 0.00%) TokenTree::Delimited(span, _) | TokenTree::Sequence(span, _) => span.entire(), . } . } . . fn token(kind: TokenKind, span: Span) -> TokenTree { 815 ( 0.00%) TokenTree::Token(Token::new(kind, span)) . } . } 11,310,057 ( 0.28%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_serialize/src/leb128.rs -------------------------------------------------------------------------------- Ir -- line 17 ---------------------------------------- . #[inline] . pub fn $fn_name( . out: &mut [::std::mem::MaybeUninit; max_leb128_len!($int_ty)], . mut value: $int_ty, . ) -> &[u8] { . let mut i = 0; . . loop { 1,835 ( 0.00%) if value < 0x80 { . unsafe { 965 ( 0.00%) *out.get_unchecked_mut(i).as_mut_ptr() = value as u8; . } . 1,284 ( 0.00%) i += 1; . break; . } else { . unsafe { 708 ( 0.00%) *out.get_unchecked_mut(i).as_mut_ptr() = ((value & 0x7f) | 0x80) as u8; . } . 438 ( 0.00%) value >>= 7; . i += 1; . } . } . . unsafe { ::std::mem::MaybeUninit::slice_assume_init_ref(&out.get_unchecked(..i)) } . } . }; . } -- line 45 ---------------------------------------- -- line 53 ---------------------------------------- . macro_rules! impl_read_unsigned_leb128 { . ($fn_name:ident, $int_ty:ty) => { . #[inline] . pub fn $fn_name(slice: &[u8], position: &mut usize) -> $int_ty { . // The first iteration of this loop is unpeeled. This is a . // performance win because this code is hot and integer values less . // than 128 are very common, typically occurring 50-80% or more of . // the time, even for u64 and u128. 4,037,760 ( 0.10%) let byte = slice[*position]; 2,018,880 ( 0.05%) *position += 1; 2,018,880 ( 0.05%) if (byte & 0x80) == 0 { 86 ( 0.00%) return byte as $int_ty; . } 1,076 ( 0.00%) let mut result = (byte & 0x7F) as $int_ty; . let mut shift = 7; . loop { 2,289,807 ( 0.06%) let byte = slice[*position]; 1,520,140 ( 0.04%) *position += 1; 1,526,538 ( 0.04%) if (byte & 0x80) == 0 { 1,532,506 ( 0.04%) result |= (byte as $int_ty) << shift; . return result; . } else { . result |= ((byte & 0x7F) as $int_ty) << shift; . } . shift += 7; . } . } . }; -- line 80 ---------------------------------------- 2,516,533 ( 0.06%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/nonterminal.rs -------------------------------------------------------------------------------- Ir -- line 8 ---------------------------------------- . use crate::parser::pat::{RecoverColon, RecoverComma}; . use crate::parser::{FollowedByType, ForceCollect, Parser, PathStyle}; . . impl<'a> Parser<'a> { . /// Checks whether a non-terminal may begin with a particular token. . /// . /// Returning `false` is a *stability guarantee* that such a matcher will *never* begin with that . /// token. Be conservative (return true) if not sure. 1,324,716 ( 0.03%) pub fn nonterminal_may_begin_with(kind: NonterminalKind, token: &Token) -> bool { . /// Checks whether the non-terminal may contain a single (non-keyword) identifier. . fn may_be_ident(nt: &token::Nonterminal) -> bool { . match *nt { . token::NtItem(_) | token::NtBlock(_) | token::NtVis(_) | token::NtLifetime(_) => { . false . } . _ => true, . } . } . 6,623,580 ( 0.16%) match kind { . NonterminalKind::Expr => { 660 ( 0.00%) token.can_begin_expr() . // This exception is here for backwards compatibility. 330 ( 0.00%) && !token.is_keyword(kw::Let) . // This exception is here for backwards compatibility. 440 ( 0.00%) && !token.is_keyword(kw::Const) . } . NonterminalKind::Ty => token.can_begin_type(), . NonterminalKind::Ident => get_macro_ident(token).is_some(), . NonterminalKind::Literal => token.can_begin_literal_maybe_minus(), 195 ( 0.00%) NonterminalKind::Vis => match token.kind { . // The follow-set of :vis + "priv" keyword + interpolated . token::Comma | token::Ident(..) | token::Interpolated(..) => true, . _ => token.can_begin_type(), . }, . NonterminalKind::Block => match token.kind { . token::OpenDelim(token::Brace) => true, . token::Interpolated(ref nt) => !matches!( . **nt, -- line 46 ---------------------------------------- -- line 85 ---------------------------------------- . NonterminalKind::Lifetime => match token.kind { . token::Lifetime(_) => true, . token::Interpolated(ref nt) => { . matches!(**nt, token::NtLifetime(_) | token::NtTT(_)) . } . _ => false, . }, . NonterminalKind::TT | NonterminalKind::Item | NonterminalKind::Stmt => { 1,323,260 ( 0.03%) !matches!(token.kind, token::CloseDelim(_)) . } . } 1,324,574 ( 0.03%) } . . /// Parse a non-terminal (e.g. MBE `:pat` or `:ident`). 5,890,338 ( 0.15%) pub fn parse_nonterminal(&mut self, kind: NonterminalKind) -> PResult<'a, Nonterminal> { . // Any `Nonterminal` which stores its tokens (currently `NtItem` and `NtExpr`) . // needs to have them force-captured here. . // A `macro_rules!` invocation may pass a captured item/expr to a proc-macro, . // which requires having captured tokens available. Since we cannot determine . // in advance whether or not a proc-macro will be (transitively) invoked, . // we always capture tokens for any `Nonterminal` which needs them. 7,199,302 ( 0.18%) let mut nt = match kind { . NonterminalKind::Item => match self.parse_item(ForceCollect::Yes)? { . Some(item) => token::NtItem(item), . None => { . return Err(self.struct_span_err(self.token.span, "expected an item keyword")); . } . }, . NonterminalKind::Block => { . // While a block *expression* may have attributes (e.g. `#[my_attr] { ... }`), -- line 114 ---------------------------------------- -- line 126 ---------------------------------------- . NonterminalKind::PatParam { .. } => this.parse_pat_no_top_alt(None), . NonterminalKind::PatWithOr { .. } => { . this.parse_pat_allow_top_alt(None, RecoverComma::No, RecoverColon::No) . } . _ => unreachable!(), . })?) . } . 440 ( 0.00%) NonterminalKind::Expr => token::NtExpr(self.parse_expr_force_collect()?), . NonterminalKind::Literal => { . // The `:literal` matcher does not support attributes . token::NtLiteral( . self.collect_tokens_no_attrs(|this| this.parse_literal_maybe_minus())?, . ) . } . . NonterminalKind::Ty => { 108 ( 0.00%) token::NtTy(self.collect_tokens_no_attrs(|this| this.parse_ty())?) . } . // this could be handled like a token, since it is one . NonterminalKind::Ident 2,208 ( 0.00%) if let Some((ident, is_raw)) = get_macro_ident(&self.token) => . { 736 ( 0.00%) self.bump(); 2,576 ( 0.00%) token::NtIdent(ident, is_raw) . } . NonterminalKind::Ident => { . let token_str = pprust::token_to_string(&self.token); . let msg = &format!("expected ident, found {}", &token_str); . return Err(self.struct_span_err(self.token.span, msg)); . } . NonterminalKind::Path => token::NtPath( . self.collect_tokens_no_attrs(|this| this.parse_path(PathStyle::Type))?, . ), . NonterminalKind::Meta => token::NtMeta(P(self.parse_attr_item(true)?)), 3,269,495 ( 0.08%) NonterminalKind::TT => token::NtTT(self.parse_token_tree()), 153 ( 0.00%) NonterminalKind::Vis => token::NtVis( 153 ( 0.00%) self.collect_tokens_no_attrs(|this| this.parse_visibility(FollowedByType::Yes))?, . ), . NonterminalKind::Lifetime => { . if self.check_lifetime() { . token::NtLifetime(self.expect_lifetime().ident) . } else { . let token_str = pprust::token_to_string(&self.token); . let msg = &format!("expected a lifetime, found `{}`", &token_str); . return Err(self.struct_span_err(self.token.span, msg)); . } . } . }; . . // If tokens are supported at all, they should be collected. 1,963,876 ( 0.05%) if matches!(nt.tokens_mut(), Some(None)) { . panic!( . "Missing tokens for nt {:?} at {:?}: {:?}", . nt, . nt.span(), . pprust::nonterminal_to_string(&nt) . ); . } . 4,581,374 ( 0.11%) Ok(nt) 5,890,338 ( 0.15%) } . } . . /// The token is an identifier, but not `_`. . /// We prohibit passing `_` to macros expecting `ident` for now. . fn get_macro_ident(token: &Token) -> Option<(Ident, bool)> { 1,728 ( 0.00%) token.ident().filter(|(ident, _)| ident.name != kw::Underscore) . } 655,114 ( 0.02%) -------------------------------------------------------------------------------- -- 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)] 90,036,909 ( 2.23%) pub unsafe fn drop_in_place(to_drop: *mut T) { . // Code here does not matter - this is replaced by the . // real drop glue by the compiler. . . // SAFETY: see comment above . unsafe { drop_in_place(to_drop) } . } . . /// Creates a null raw pointer. -- line 196 ---------------------------------------- -- line 448 ---------------------------------------- . return; . } . } . . // Direct swapping, for the cases not going through the block optimization. . // SAFETY: the caller must guarantee that `x` and `y` are valid . // for writes, properly aligned, and non-overlapping. . unsafe { 28 ( 0.00%) let z = read(x); 8 ( 0.00%) copy_nonoverlapping(y, x, 1); . write(y, z); . } . } . . #[inline] . #[rustc_const_unstable(feature = "const_swap", issue = "83163")] . const unsafe fn swap_nonoverlapping_bytes(x: *mut u8, y: *mut u8, len: usize) { . // The approach here is to utilize simd to swap x & y efficiently. Testing reveals -- line 465 ---------------------------------------- -- line 693 ---------------------------------------- . let mut tmp = MaybeUninit::::uninit(); . // SAFETY: the caller must guarantee that `src` is valid for reads. . // `src` cannot overlap `tmp` because `tmp` was just allocated on . // the stack as a separate allocated object. . // . // Also, since we just wrote a valid value into `tmp`, it is guaranteed . // to be properly initialized. . unsafe { 13,065,711 ( 0.32%) copy_nonoverlapping(src, tmp.as_mut_ptr(), 1); 18,756,544 ( 0.47%) tmp.assume_init() . } . } . . /// Reads the value from `src` without moving it. This leaves the . /// memory in `src` unchanged. . /// . /// Unlike [`read`], `read_unaligned` works with unaligned pointers. . /// -- line 710 ---------------------------------------- -- line 884 ---------------------------------------- . #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")] . fn copy_nonoverlapping(src: *const T, dst: *mut T, count: usize); . } . . // SAFETY: the caller must guarantee that `dst` is valid for writes. . // `dst` cannot overlap `src` because the caller has mutable access . // to `dst` while `src` is owned by this function. . unsafe { 58,028,633 ( 1.44%) copy_nonoverlapping(&src as *const T, dst, 1); . intrinsics::forget(src); . } . } . . /// Overwrites a memory location with the given value without reading or . /// dropping the old value. . /// . /// Unlike [`write()`], the pointer may be unaligned. -- line 900 ---------------------------------------- -- line 1206 ---------------------------------------- . if stride == 1 { . // `stride == 1` case can be computed more simply through `-p (mod a)`, but doing so . // inhibits LLVM's ability to select instructions like `lea`. Instead we compute . // . // round_up_to_next_alignment(p, a) - p . // . // which distributes operations around the load-bearing, but pessimizing `and` sufficiently . // for LLVM to be able to utilize the various optimizations it knows about. 587 ( 0.00%) return wrapping_sub( 2,716 ( 0.00%) wrapping_add(p as usize, a_minus_one) & wrapping_sub(0, a), . p as usize, . ); . } . . let pmoda = p as usize & a_minus_one; . if pmoda == 0 { . // Already aligned. Yay! . return 0; -- line 1223 ---------------------------------------- -- line 1348 ---------------------------------------- . /// assert!(std::ptr::eq( . /// &wrapper as &dyn Trait as *const dyn Trait as *const u8, . /// &wrapper.member as &dyn Trait as *const dyn Trait as *const u8, . /// )); . /// ``` . #[stable(feature = "ptr_eq", since = "1.17.0")] . #[inline] . pub fn eq(a: *const T, b: *const T) -> bool { 703,116 ( 0.02%) a == b . } . . /// Hash a raw pointer. . /// . /// This can be used to hash a `&T` reference (which coerces to `*const T` implicitly) . /// by its address rather than the value it points to . /// (which is what the `Hash for &T` implementation does). . /// -- line 1364 ---------------------------------------- 7,819,858 ( 0.19%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/borrow.rs -------------------------------------------------------------------------------- Ir -- line 81 ---------------------------------------- . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl ToOwned for T . where . T: Clone, . { . type Owned = T; 70,650 ( 0.00%) fn to_owned(&self) -> T { 3 ( 0.00%) self.clone() 71,366 ( 0.00%) } . . fn clone_into(&self, target: &mut T) { . target.clone_from(self); . } . } . . /// A clone-on-write smart pointer. . /// -- line 99 ---------------------------------------- -- line 269 ---------------------------------------- . /// . /// assert_eq!( . /// cow, . /// Cow::Owned(String::from("FOO")) as Cow . /// ); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn to_mut(&mut self) -> &mut ::Owned { 1,341,175 ( 0.03%) match *self { 7,850 ( 0.00%) Borrowed(borrowed) => { 57,048 ( 0.00%) *self = Owned(borrowed.to_owned()); . match *self { . Borrowed(..) => unreachable!(), . Owned(ref mut owned) => owned, . } . } . Owned(ref mut owned) => owned, . } . } -- line 287 ---------------------------------------- -- line 316 ---------------------------------------- . /// let cow: Cow = Cow::Owned(String::from(s)); . /// . /// assert_eq!( . /// cow.into_owned(), . /// String::from(s) . /// ); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 200 ( 0.00%) pub fn into_owned(self) -> ::Owned { 40,143 ( 0.00%) match self { 34,336 ( 0.00%) Borrowed(borrowed) => borrowed.to_owned(), 275 ( 0.00%) Owned(owned) => owned, . } 225 ( 0.00%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_deref", issue = "88955")] . impl const Deref for Cow<'_, B> . where . B::Owned: ~const Borrow, . { . type Target = B; . . fn deref(&self) -> &B { 4,142,338 ( 0.10%) match *self { . Borrowed(borrowed) => borrowed, . Owned(ref owned) => owned.borrow(), . } . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Eq for Cow<'_, B> where B: Eq + ToOwned {} -- line 349 ---------------------------------------- -- line 396 ---------------------------------------- . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl fmt::Display for Cow<'_, B> . where . B: fmt::Display + ToOwned, . { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 220 ( 0.00%) match *self { . Borrowed(ref b) => fmt::Display::fmt(b, f), . Owned(ref o) => fmt::Display::fmt(o, f), . } . } . } . . #[stable(feature = "default", since = "1.11.0")] . impl Default for Cow<'_, B> -- line 412 ---------------------------------------- 148,194 ( 0.00%) -------------------------------------------------------------------------------- -- 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 . // . 13,017,776 ( 0.32%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 9,763,332 ( 0.24%) 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. 30,704 ( 0.00%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 46,056 ( 0.00%) libc::calloc(layout.size(), 1) as *mut u8 . } else { . let ptr = self.alloc(layout); . if !ptr.is_null() { . ptr::write_bytes(ptr, 0, layout.size()); . } . ptr . } . } . . #[inline] . unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) { 3,262,108 ( 0.08%) libc::free(ptr as *mut libc::c_void) . } . . #[inline] . unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { 380,032 ( 0.01%) if layout.align() <= MIN_ALIGN && layout.align() <= new_size { 760,064 ( 0.02%) 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/library/core/src/slice/iter/macros.rs -------------------------------------------------------------------------------- Ir -- line 70 ---------------------------------------- . . impl<'a, T> $name<'a, T> { . // Helper function for creating a slice from the iterator. . #[inline(always)] . fn make_slice(&self) -> &'a [T] { . // SAFETY: the iterator was created from a slice with pointer . // `self.ptr` and length `len!(self)`. This guarantees that all . // the prerequisites for `from_raw_parts` are fulfilled. 32,326 ( 0.00%) unsafe { from_raw_parts(self.ptr.as_ptr(), len!(self)) } . } . . // Helper function for moving the start of the iterator forwards by `offset` elements, . // returning the old start. . // Unsafe because the offset must not exceed `self.len()`. . #[inline(always)] . unsafe fn post_inc_start(&mut self, offset: isize) -> * $raw_mut T { . if mem::size_of::() == 0 { . zst_shrink!(self, offset); . self.ptr.as_ptr() . } else { . let old = self.ptr.as_ptr(); . // SAFETY: the caller guarantees that `offset` doesn't exceed `self.len()`, . // so this new pointer is inside `self` and thus guaranteed to be non-null. 223,532 ( 0.01%) self.ptr = unsafe { NonNull::new_unchecked(self.ptr.as_ptr().offset(offset)) }; . old . } . } . . // Helper function for moving the end of the iterator backwards by `offset` elements, . // returning the new end. . // Unsafe because the offset must not exceed `self.len()`. . #[inline(always)] -- line 101 ---------------------------------------- -- line 102 ---------------------------------------- . unsafe fn pre_dec_end(&mut self, offset: isize) -> * $raw_mut T { . if mem::size_of::() == 0 { . zst_shrink!(self, offset); . self.ptr.as_ptr() . } else { . // SAFETY: the caller guarantees that `offset` doesn't exceed `self.len()`, . // which is guaranteed to not overflow an `isize`. Also, the resulting pointer . // is in bounds of `slice`, which fulfills the other requirements for `offset`. 22 ( 0.00%) self.end = unsafe { self.end.offset(-offset) }; . self.end . } . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl ExactSizeIterator for $name<'_, T> { . #[inline(always)] . fn len(&self) -> usize { 79,243 ( 0.00%) len!(self) . } . . #[inline(always)] . fn is_empty(&self) -> bool { . is_empty!(self) . } . } . -- line 128 ---------------------------------------- -- line 134 ---------------------------------------- . fn next(&mut self) -> Option<$elem> { . // could be implemented with slices, but this avoids bounds checks . . // SAFETY: `assume` calls are safe since a slice's start pointer . // must be non-null, and slices over non-ZSTs must also have a . // non-null end pointer. The call to `next_unchecked!` is safe . // since we check if the iterator is empty first. . unsafe { 113,924 ( 0.00%) assume(!self.ptr.as_ptr().is_null()); . if mem::size_of::() != 0 { 31,188 ( 0.00%) assume(!self.end.is_null()); . } 43,394,781 ( 1.08%) if is_empty!(self) { . None . } else { 4 ( 0.00%) Some(next_unchecked!(self)) . } . } . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 7,000,460 ( 0.17%) let exact = len!(self); . (exact, Some(exact)) . } . . #[inline] . fn count(self) -> usize { . len!(self) . } . . #[inline] . fn nth(&mut self, n: usize) -> Option<$elem> { 23,841 ( 0.00%) if n >= len!(self) { . // This iterator is now empty. . if mem::size_of::() == 0 { . // We have to do it this way as `ptr` may never be 0, but `end` . // could be (due to wrapping). . self.end = self.ptr.as_ptr(); . } else { . // SAFETY: end can't be 0 if T isn't ZST because ptr isn't 0 and end >= ptr . unsafe { -- line 175 ---------------------------------------- -- line 203 ---------------------------------------- . // faster to compile. . #[inline] . fn for_each(mut self, mut f: F) . where . Self: Sized, . F: FnMut(Self::Item), . { . while let Some(x) = self.next() { 1,914 ( 0.00%) f(x); . } . } . . // We override the default implementation, which uses `try_fold`, . // because this simple implementation generates less LLVM IR and is . // faster to compile. . #[inline] . fn all(&mut self, mut f: F) -> bool . where . Self: Sized, . F: FnMut(Self::Item) -> bool, . { 464 ( 0.00%) while let Some(x) = self.next() { 12,194 ( 0.00%) if !f(x) { . return false; . } . } . true . } . . // We override the default implementation, which uses `try_fold`, . // because this simple implementation generates less LLVM IR and is . // faster to compile. . #[inline] . fn any(&mut self, mut f: F) -> bool . where . Self: Sized, . F: FnMut(Self::Item) -> bool, . { 482,629 ( 0.01%) while let Some(x) = self.next() { 183,788 ( 0.00%) if f(x) { . return true; . } . } . false . } . . // We override the default implementation, which uses `try_fold`, . // because this simple implementation generates less LLVM IR and is . // faster to compile. . #[inline] . fn find

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

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

(&mut self, mut predicate: P) -> Option where . P: FnMut(Self::Item) -> bool, . Self: Sized + ExactSizeIterator + DoubleEndedIterator . { . let n = len!(self); . let mut i = n; 2,330 ( 0.00%) while let Some(x) = self.next_back() { 30,062 ( 0.00%) i -= 1; 23,907 ( 0.00%) if predicate(x) { . // SAFETY: `i` must be lower than `n` since it starts at `n` . // and is only decreasing. . unsafe { assume(i < n) }; . return Some(i); . } . } . None . } -- line 326 ---------------------------------------- -- line 332 ---------------------------------------- . // the returned references is guaranteed to refer to an element . // of the slice and thus guaranteed to be valid. . // . // Also note that the caller also guarantees that we're never . // called with the same index again, and that no other methods . // that will access this subslice are called, so it is valid . // for the returned reference to be mutable in the case of . // `IterMut` 28,515 ( 0.00%) unsafe { & $( $mut_ )? * self.ptr.as_ptr().add(idx) } . } . . $($extra)* . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl<'a, T> DoubleEndedIterator for $name<'a, T> { . #[inline] -- line 348 ---------------------------------------- -- line 349 ---------------------------------------- . fn next_back(&mut self) -> Option<$elem> { . // could be implemented with slices, but this avoids bounds checks . . // SAFETY: `assume` calls are safe since a slice's start pointer must be non-null, . // and slices over non-ZSTs must also have a non-null end pointer. . // The call to `next_back_unchecked!` is safe since we check if the iterator is . // empty first. . unsafe { 28 ( 0.00%) assume(!self.ptr.as_ptr().is_null()); . if mem::size_of::() != 0 { 49 ( 0.00%) assume(!self.end.is_null()); . } 720,323 ( 0.02%) if is_empty!(self) { . None . } else { . Some(next_back_unchecked!(self)) . } . } . } . . #[inline] -- line 369 ---------------------------------------- 4,664,970 ( 0.12%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_metadata/src/rmeta/decoder.rs -------------------------------------------------------------------------------- Ir -- line 176 ---------------------------------------- . } . fn sess(self) -> Option<&'tcx Session> { . None . } . fn tcx(self) -> Option> { . None . } . 3,093 ( 0.00%) fn decoder(self, pos: usize) -> DecodeContext<'a, 'tcx> { 1,031 ( 0.00%) let tcx = self.tcx(); 436,589 ( 0.01%) DecodeContext { 38,713 ( 0.00%) opaque: opaque::Decoder::new(self.blob(), pos), 1,031 ( 0.00%) cdata: self.cdata(), . blob: self.blob(), 10,430 ( 0.00%) sess: self.sess().or(tcx.map(|tcx| tcx.sess)), . tcx, . last_source_file_index: 0, . lazy_state: LazyState::NoNode, . alloc_decoding_session: self . .cdata() 33,040 ( 0.00%) .map(|cdata| cdata.cdata.alloc_decoding_state.new_decoding_session()), . } 3,093 ( 0.00%) } . } . . impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a MetadataBlob { . #[inline] . fn blob(self) -> &'a MetadataBlob { . self . } . } -- line 206 ---------------------------------------- -- line 255 ---------------------------------------- . } . #[inline] . fn tcx(self) -> Option> { . Some(self.1) . } . } . . impl<'a, 'tcx, T: Decodable>> Lazy { 38,127 ( 0.00%) fn decode>(self, metadata: M) -> T { 19,842 ( 0.00%) let mut dcx = metadata.decoder(self.position.get()); 130,175 ( 0.00%) dcx.lazy_state = LazyState::NodeStart(self.position); 56,012 ( 0.00%) T::decode(&mut dcx) 48,619 ( 0.00%) } . } . . impl<'a: 'x, 'tcx: 'x, 'x, T: Decodable>> Lazy<[T]> { . fn decode>( . self, . metadata: M, . ) -> impl ExactSizeIterator + Captures<'a> + Captures<'tcx> + 'x { 35 ( 0.00%) let mut dcx = metadata.decoder(self.position.get()); 10 ( 0.00%) dcx.lazy_state = LazyState::NodeStart(self.position); 16,410 ( 0.00%) (0..self.meta).map(move |_| T::decode(&mut dcx)) . } . } . . impl<'a, 'tcx> DecodeContext<'a, 'tcx> { . #[inline] . fn tcx(&self) -> TyCtxt<'tcx> { . debug_assert!(self.tcx.is_some(), "missing TyCtxt in DecodeContext"); . self.tcx.unwrap() -- line 285 ---------------------------------------- -- line 292 ---------------------------------------- . . #[inline] . pub fn cdata(&self) -> CrateMetadataRef<'a> { . debug_assert!(self.cdata.is_some(), "missing CrateMetadata in DecodeContext"); . self.cdata.unwrap() . } . . fn map_encoded_cnum_to_current(&self, cnum: CrateNum) -> CrateNum { 97,488 ( 0.00%) if cnum == LOCAL_CRATE { self.cdata().cnum } else { self.cdata().cnum_map[cnum] } . } . 1,403,542 ( 0.03%) fn read_lazy_with_meta(&mut self, meta: T::Meta) -> Lazy { . let distance = self.read_usize(); 1,400,296 ( 0.03%) let position = match self.lazy_state { . LazyState::NoNode => bug!("read_lazy_with_meta: outside of a metadata node"), 12,897 ( 0.00%) LazyState::NodeStart(start) => { . let start = start.get(); 25,794 ( 0.00%) assert!(distance <= start); . start - distance . } 816,963 ( 0.02%) LazyState::Previous(last_pos) => last_pos.get() + distance, . }; 570,436 ( 0.01%) self.lazy_state = LazyState::Previous(NonZeroUsize::new(position).unwrap()); . Lazy::from_position_and_meta(NonZeroUsize::new(position).unwrap(), meta) 1,403,542 ( 0.03%) } . . #[inline] . pub fn read_raw_bytes(&mut self, len: usize) -> &'a [u8] { . self.opaque.read_raw_bytes(len) . } . } . . impl<'a, 'tcx> TyDecoder<'tcx> for DecodeContext<'a, 'tcx> { -- line 324 ---------------------------------------- -- line 326 ---------------------------------------- . . #[inline] . fn tcx(&self) -> TyCtxt<'tcx> { . self.tcx.expect("missing TyCtxt in DecodeContext") . } . . #[inline] . fn peek_byte(&self) -> u8 { 64,805 ( 0.00%) self.opaque.data[self.opaque.position()] . } . . #[inline] . fn position(&self) -> usize { . self.opaque.position() . } . 57,659 ( 0.00%) fn cached_ty_for_shorthand(&mut self, shorthand: usize, or_insert_with: F) -> Ty<'tcx> . where . F: FnOnce(&mut Self) -> Ty<'tcx>, . { 8,237 ( 0.00%) let tcx = self.tcx(); . 8,237 ( 0.00%) let key = ty::CReaderCacheKey { cnum: Some(self.cdata().cnum), pos: shorthand }; . 22,628 ( 0.00%) if let Some(&ty) = tcx.ty_rcache.borrow().get(&key) { . return ty; . } . 2,580 ( 0.00%) let ty = or_insert_with(self); . tcx.ty_rcache.borrow_mut().insert(key, ty); . ty 74,133 ( 0.00%) } . . fn with_position(&mut self, pos: usize, f: F) -> R . where . F: FnOnce(&mut Self) -> R, . { . let new_opaque = opaque::Decoder::new(self.opaque.data, pos); . let old_opaque = mem::replace(&mut self.opaque, new_opaque); . let old_state = mem::replace(&mut self.lazy_state, LazyState::NoNode); . let r = f(self); 13,675 ( 0.00%) self.opaque = old_opaque; 2,735 ( 0.00%) self.lazy_state = old_state; . r . } . . fn decode_alloc_id(&mut self) -> rustc_middle::mir::interpret::AllocId { . if let Some(alloc_decoding_session) = self.alloc_decoding_session { . alloc_decoding_session.decode_alloc_id(self) . } else { . bug!("Attempting to decode interpret::AllocId without CrateMetadata") . } . } . } . . impl<'a, 'tcx> Decodable> for CrateNum { . fn decode(d: &mut DecodeContext<'a, 'tcx>) -> CrateNum { 48,400 ( 0.00%) let cnum = CrateNum::from_u32(d.read_u32()); . d.map_encoded_cnum_to_current(cnum) . } . } . . impl<'a, 'tcx> Decodable> for DefIndex { 346 ( 0.00%) fn decode(d: &mut DecodeContext<'a, 'tcx>) -> DefIndex { 98,312 ( 0.00%) DefIndex::from_u32(d.read_u32()) 692 ( 0.00%) } . } . . impl<'a, 'tcx> Decodable> for ExpnIndex { . fn decode(d: &mut DecodeContext<'a, 'tcx>) -> ExpnIndex { . ExpnIndex::from_u32(d.read_u32()) . } . } . . impl<'a, 'tcx> Decodable> for SyntaxContext { 55,236 ( 0.00%) fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> SyntaxContext { 13,809 ( 0.00%) let cdata = decoder.cdata(); 13,809 ( 0.00%) let sess = decoder.sess.unwrap(); 27,618 ( 0.00%) let cname = cdata.root.name; . rustc_span::hygiene::decode_syntax_context(decoder, &cdata.hygiene_context, |_, id| { . debug!("SpecializedDecoder: decoding {}", id); 716 ( 0.00%) cdata . .root . .syntax_contexts . .get(cdata, id) . .unwrap_or_else(|| panic!("Missing SyntaxContext {:?} for crate {:?}", id, cname)) . .decode((cdata, sess)) . }) 69,045 ( 0.00%) } . } . . impl<'a, 'tcx> Decodable> for ExpnId { 5,796 ( 0.00%) fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> ExpnId { 828 ( 0.00%) let local_cdata = decoder.cdata(); 828 ( 0.00%) let sess = decoder.sess.unwrap(); . . let cnum = CrateNum::decode(decoder); . let index = u32::decode(decoder); . . let expn_id = rustc_span::hygiene::decode_expn_id(cnum, index, |expn_id| { . let ExpnId { krate: cnum, local_id: index } = expn_id; . // Lookup local `ExpnData`s in our own crate data. Foreign `ExpnData`s . // are stored in the owning crate, to avoid duplication. . debug_assert_ne!(cnum, LOCAL_CRATE); 205 ( 0.00%) let crate_data = if cnum == local_cdata.cnum { . local_cdata . } else { . local_cdata.cstore.get_crate_data(cnum) . }; 1,025 ( 0.00%) let expn_data = crate_data . .root . .expn_data . .get(crate_data, index) . .unwrap() . .decode((crate_data, sess)); 1,025 ( 0.00%) let expn_hash = crate_data . .root . .expn_hashes . .get(crate_data, index) . .unwrap() . .decode((crate_data, sess)); 2,050 ( 0.00%) (expn_data, expn_hash) . }); . expn_id 6,624 ( 0.00%) } . } . . impl<'a, 'tcx> Decodable> for Span { 106,176 ( 0.00%) fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Span { 13,272 ( 0.00%) let ctxt = SyntaxContext::decode(decoder); . let tag = u8::decode(decoder); . 26,544 ( 0.00%) if tag == TAG_PARTIAL_SPAN { . return DUMMY_SP.with_ctxt(ctxt); . } . . debug_assert!(tag == TAG_VALID_SPAN_LOCAL || tag == TAG_VALID_SPAN_FOREIGN); . . let lo = BytePos::decode(decoder); . let len = BytePos::decode(decoder); . let hi = lo + len; . 39,813 ( 0.00%) let Some(sess) = decoder.sess else { . bug!("Cannot decode Span without Session.") . }; . . // There are two possibilities here: . // 1. This is a 'local span', which is located inside a `SourceFile` . // that came from this crate. In this case, we use the source map data . // encoded in this crate. This branch should be taken nearly all of the time. . // 2. This is a 'foreign span', which is located inside a `SourceFile` -- line 476 ---------------------------------------- -- line 492 ---------------------------------------- . // a transitive dependency. . // . // When we encode a foreign span, we adjust its 'lo' and 'high' values . // to be based on the *foreign* crate (e.g. crate C), not the crate . // we are writing metadata for (e.g. crate B). This allows us to . // treat the 'local' and 'foreign' cases almost identically during deserialization: . // we can call `imported_source_files` for the proper crate, and binary search . // through the returned slice using our span. 30,831 ( 0.00%) let imported_source_files = if tag == TAG_VALID_SPAN_LOCAL { . decoder.cdata().imported_source_files(sess) . } else { . // When we encode a proc-macro crate, all `Span`s should be encoded . // with `TAG_VALID_SPAN_LOCAL` 14 ( 0.00%) if decoder.cdata().root.is_proc_macro_crate() { . // Decode `CrateNum` as u32 - using `CrateNum::decode` will ICE . // since we don't have `cnum_map` populated. . let cnum = u32::decode(decoder); . panic!( . "Decoding of crate {:?} tried to access proc-macro dep {:?}", . decoder.cdata().root.name, . cnum . ); -- line 513 ---------------------------------------- -- line 518 ---------------------------------------- . "SpecializedDecoder::specialized_decode: loading source files from cnum {:?}", . cnum . ); . . // Decoding 'foreign' spans should be rare enough that it's . // not worth it to maintain a per-CrateNum cache for `last_source_file_index`. . // We just set it to 0, to ensure that we don't try to access something out . // of bounds for our initial 'guess' 28 ( 0.00%) decoder.last_source_file_index = 0; . 14 ( 0.00%) let foreign_data = decoder.cdata().cstore.get_crate_data(cnum); . foreign_data.imported_source_files(sess) . }; . . let source_file = { . // Optimize for the case that most spans within a translated item . // originate from the same source_file. 39,813 ( 0.00%) let last_source_file = &imported_source_files[decoder.last_source_file_index]; . 52,880 ( 0.00%) if lo >= last_source_file.original_start_pos && lo <= last_source_file.original_end_pos . { . last_source_file . } else { . let index = imported_source_files . .binary_search_by_key(&lo, |source_file| source_file.original_start_pos) 8,566 ( 0.00%) .unwrap_or_else(|index| index - 1); . . // Don't try to cache the index for foreign spans, . // as this would require a map from CrateNums to indices 4,289 ( 0.00%) if tag == TAG_VALID_SPAN_LOCAL { 4,276 ( 0.00%) decoder.last_source_file_index = index; . } 8,578 ( 0.00%) &imported_source_files[index] . } . }; . . // Make sure our binary search above is correct. . debug_assert!( . lo >= source_file.original_start_pos && lo <= source_file.original_end_pos, . "Bad binary search: lo={:?} source_file.original_start_pos={:?} source_file.original_end_pos={:?}", . lo, -- line 558 ---------------------------------------- -- line 565 ---------------------------------------- . hi >= source_file.original_start_pos && hi <= source_file.original_end_pos, . "Bad binary search: hi={:?} source_file.original_start_pos={:?} source_file.original_end_pos={:?}", . hi, . source_file.original_start_pos, . source_file.original_end_pos . ); . . let lo = 53,084 ( 0.00%) (lo + source_file.translated_source_file.start_pos) - source_file.original_start_pos; . let hi = . (hi + source_file.translated_source_file.start_pos) - source_file.original_start_pos; . . // Do not try to decode parent for foreign spans. . Span::new(lo, hi, ctxt, None) 119,448 ( 0.00%) } . } . . impl<'a, 'tcx> Decodable> for &'tcx [thir::abstract_const::Node<'tcx>] { . fn decode(d: &mut DecodeContext<'a, 'tcx>) -> Self { . ty::codec::RefDecodable::decode(d) . } . } . -- line 587 ---------------------------------------- -- line 590 ---------------------------------------- . ty::codec::RefDecodable::decode(d) . } . } . . impl<'a, 'tcx, T: Decodable>> Decodable> . for Lazy . { . fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Self { 29,256 ( 0.00%) decoder.read_lazy_with_meta(()) . } . } . . impl<'a, 'tcx, T: Decodable>> Decodable> . for Lazy<[T]> . { . fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Self { . let len = decoder.read_usize(); 487,325 ( 0.01%) if len == 0 { Lazy::empty() } else { decoder.read_lazy_with_meta(len) } . } . } . . impl<'a, 'tcx, I: Idx, T: Decodable>> Decodable> . for Lazy> . where . Option: FixedSizeEncoding, . { . fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Self { . let len = decoder.read_usize(); 1,093,937 ( 0.03%) decoder.read_lazy_with_meta(len) . } . } . . implement_ty_decoder!(DecodeContext<'a, 'tcx>); . . impl<'tcx> MetadataBlob { . crate fn new(metadata_ref: MetadataRef) -> MetadataBlob { . MetadataBlob(Lrc::new(metadata_ref)) -- line 626 ---------------------------------------- -- line 630 ---------------------------------------- . self.blob().starts_with(METADATA_HEADER) . } . . crate fn get_rustc_version(&self) -> String { . Lazy::::from_position(NonZeroUsize::new(METADATA_HEADER.len() + 4).unwrap()) . .decode(self) . } . 19,419 ( 0.00%) crate fn get_root(&self) -> CrateRoot<'tcx> { 6,473 ( 0.00%) let slice = &self.blob()[..]; . let offset = METADATA_HEADER.len(); 32,365 ( 0.00%) let pos = (((slice[offset + 0] as u32) << 24) 12,946 ( 0.00%) | ((slice[offset + 1] as u32) << 16) 25,892 ( 0.00%) | ((slice[offset + 2] as u32) << 8) 19,419 ( 0.00%) | ((slice[offset + 3] as u32) << 0)) as usize; . Lazy::>::from_position(NonZeroUsize::new(pos).unwrap()).decode(self) 32,365 ( 0.00%) } . . crate fn list_crate_metadata(&self, out: &mut dyn io::Write) -> io::Result<()> { . let root = self.get_root(); . writeln!(out, "Crate info:")?; . writeln!(out, "name {}{}", root.name, root.extra_filename)?; . writeln!(out, "hash {} stable_crate_id {:?}", root.hash, root.stable_crate_id)?; . writeln!(out, "proc_macro {:?}", root.proc_macro_data.is_some())?; . writeln!(out, "=External Dependencies=")?; -- line 654 ---------------------------------------- -- line 666 ---------------------------------------- . } . write!(out, "\n")?; . Ok(()) . } . } . . impl CrateRoot<'_> { . crate fn is_proc_macro_crate(&self) -> bool { 40 ( 0.00%) self.proc_macro_data.is_some() . } . . crate fn name(&self) -> Symbol { 4 ( 0.00%) self.name . } . . crate fn hash(&self) -> Svh { 3,226 ( 0.00%) self.hash . } . . crate fn stable_crate_id(&self) -> StableCrateId { 40 ( 0.00%) self.stable_crate_id . } . . crate fn triple(&self) -> &TargetTriple { . &self.triple . } . . crate fn decode_crate_deps<'a>( . &self, . metadata: &'a MetadataBlob, . ) -> impl ExactSizeIterator + Captures<'a> { 40 ( 0.00%) self.crate_deps.decode(metadata) . } . } . . impl<'a, 'tcx> CrateMetadataRef<'a> { . fn raw_proc_macro(self, id: DefIndex) -> &'a ProcMacro { . // DefIndex's in root.proc_macro_data have a one-to-one correspondence . // with items in 'raw_proc_macros'. . let pos = self -- line 705 ---------------------------------------- -- line 709 ---------------------------------------- . .unwrap() . .macros . .decode(self) . .position(|i| i == id) . .unwrap(); . &self.raw_proc_macros.unwrap()[pos] . } . 36,784 ( 0.00%) fn opt_item_ident(self, item_index: DefIndex, sess: &Session) -> Option { 27,882 ( 0.00%) let name = self.def_key(item_index).disambiguated_data.data.get_opt_name()?; 17,493 ( 0.00%) let span = match self.root.tables.ident_span.get(self, item_index) { . Some(lazy_span) => lazy_span.decode((self, sess)), . None => { . // FIXME: this weird case of a name with no span is specific to `extern crate` . // items, which are supposed to be treated like `use` items and only be encoded . // to metadata as `Export`s, return `None` because that's what all the callers . // expect in this case. 63 ( 0.00%) assert_eq!(self.def_kind(item_index), DefKind::ExternCrate); . return None; . } . }; . Some(Ident::new(name, span)) 47,268 ( 0.00%) } . 293 ( 0.00%) fn item_ident(self, item_index: DefIndex, sess: &Session) -> Ident { 9,428 ( 0.00%) self.opt_item_ident(item_index, sess).expect("no encoded ident for item") 586 ( 0.00%) } . . fn maybe_kind(self, item_id: DefIndex) -> Option { 10,362 ( 0.00%) self.root.tables.kind.get(self, item_id).map(|k| k.decode(self)) . } . 41,448 ( 0.00%) fn kind(self, item_id: DefIndex) -> EntryKind { . self.maybe_kind(item_id).unwrap_or_else(|| { . bug!( . "CrateMetadata::kind({:?}): id not found, in crate {:?} with number {}", . item_id, . self.root.name, . self.cnum, . ) . }) 31,086 ( 0.00%) } . 11,823 ( 0.00%) fn def_kind(self, item_id: DefIndex) -> DefKind { 9,511 ( 0.00%) self.root.tables.def_kind.get(self, item_id).map(|k| k.decode(self)).unwrap_or_else(|| { . bug!( . "CrateMetadata::def_kind({:?}): id not found, in crate {:?} with number {}", . item_id, . self.root.name, . self.cnum, . ) . }) 6,756 ( 0.00%) } . 2,637 ( 0.00%) fn get_span(self, index: DefIndex, sess: &Session) -> Span { 5,440 ( 0.00%) self.root . .tables . .span . .get(self, index) . .unwrap_or_else(|| panic!("Missing span for {:?}", index)) . .decode((self, sess)) 1,465 ( 0.00%) } . . fn load_proc_macro(self, id: DefIndex, sess: &Session) -> SyntaxExtension { . let (name, kind, helper_attrs) = match *self.raw_proc_macro(id) { . ProcMacro::CustomDerive { trait_name, attributes, client } => { . let helper_attrs = . attributes.iter().cloned().map(Symbol::intern).collect::>(); . ( . trait_name, -- line 778 ---------------------------------------- -- line 795 ---------------------------------------- . self.get_span(id, sess), . helper_attrs, . self.root.edition, . Symbol::intern(name), . &attrs, . ) . } . 468 ( 0.00%) fn get_trait_def(self, item_id: DefIndex, sess: &Session) -> ty::TraitDef { 144 ( 0.00%) match self.kind(item_id) { 36 ( 0.00%) EntryKind::Trait(data) => { 216 ( 0.00%) let data = data.decode((self, sess)); 576 ( 0.00%) ty::TraitDef::new( . self.local_def_id(item_id), 72 ( 0.00%) data.unsafety, 72 ( 0.00%) data.paren_sugar, 72 ( 0.00%) data.has_auto_impl, 72 ( 0.00%) data.is_marker, 36 ( 0.00%) data.skip_array_during_method_dispatch, 36 ( 0.00%) data.specialization_kind, 144 ( 0.00%) self.def_path_hash(item_id), 36 ( 0.00%) data.must_implement_one_of, . ) . } . EntryKind::TraitAlias => ty::TraitDef::new( . self.local_def_id(item_id), . hir::Unsafety::Normal, . false, . false, . false, . false, . ty::trait_def::TraitSpecializationKind::None, . self.def_path_hash(item_id), . None, . ), . _ => bug!("def-index does not refer to trait or trait alias"), . } 324 ( 0.00%) } . 504 ( 0.00%) fn get_variant( . self, . kind: &EntryKind, . index: DefIndex, . parent_did: DefId, . sess: &Session, . ) -> ty::VariantDef { 224 ( 0.00%) let data = match kind { . EntryKind::Variant(data) | EntryKind::Struct(data, _) | EntryKind::Union(data, _) => { 280 ( 0.00%) data.decode(self) . } . _ => bug!(), . }; . 182 ( 0.00%) let adt_kind = match kind { . EntryKind::Variant(_) => ty::AdtKind::Enum, . EntryKind::Struct(..) => ty::AdtKind::Struct, . EntryKind::Union(..) => ty::AdtKind::Union, . _ => bug!(), . }; . . let variant_did = . if adt_kind == ty::AdtKind::Enum { Some(self.local_def_id(index)) } else { None }; 112 ( 0.00%) let ctor_did = data.ctor.map(|index| self.local_def_id(index)); . 1,232 ( 0.00%) ty::VariantDef::new( . self.item_ident(index, sess).name, . variant_did, . ctor_did, 224 ( 0.00%) data.discr, 336 ( 0.00%) self.root . .tables . .children . .get(self, index) . .unwrap_or_else(Lazy::empty) . .decode(self) . .map(|index| ty::FieldDef { 69 ( 0.00%) did: self.local_def_id(index), 138 ( 0.00%) name: self.item_ident(index, sess).name, 138 ( 0.00%) vis: self.get_visibility(index), . }) . .collect(), . data.ctor_kind, . adt_kind, . parent_did, . false, 56 ( 0.00%) data.is_non_exhaustive, . ) 504 ( 0.00%) } . 660 ( 0.00%) fn get_adt_def(self, item_id: DefIndex, tcx: TyCtxt<'tcx>) -> &'tcx ty::AdtDef { 176 ( 0.00%) let kind = self.kind(item_id); 88 ( 0.00%) let did = self.local_def_id(item_id); . 202 ( 0.00%) let (adt_kind, repr) = match kind { . EntryKind::Enum(repr) => (ty::AdtKind::Enum, repr), . EntryKind::Struct(_, repr) => (ty::AdtKind::Struct, repr), . EntryKind::Union(_, repr) => (ty::AdtKind::Union, repr), . _ => bug!("get_adt_def called on a non-ADT {:?}", did), . }; . . let variants = if let ty::AdtKind::Enum = adt_kind { 45 ( 0.00%) self.root . .tables . .children . .get(self, item_id) . .unwrap_or_else(Lazy::empty) . .decode(self) 357 ( 0.00%) .map(|index| self.get_variant(&self.kind(index), index, did, tcx.sess)) . .collect() . } else { 280 ( 0.00%) std::iter::once(self.get_variant(&kind, item_id, did, tcx.sess)).collect() . }; . 661 ( 0.00%) tcx.alloc_adt_def(did, adt_kind, variants, repr) 308 ( 0.00%) } . . fn get_explicit_predicates( . self, . item_id: DefIndex, . tcx: TyCtxt<'tcx>, . ) -> ty::GenericPredicates<'tcx> { 2,565 ( 0.00%) self.root.tables.explicit_predicates.get(self, item_id).unwrap().decode((self, tcx)) . } . . fn get_inferred_outlives( . self, . item_id: DefIndex, . tcx: TyCtxt<'tcx>, . ) -> &'tcx [(ty::Predicate<'tcx>, Span)] { 2,565 ( 0.00%) self.root . .tables . .inferred_outlives . .get(self, item_id) 16 ( 0.00%) .map(|predicates| tcx.arena.alloc_from_iter(predicates.decode((self, tcx)))) . .unwrap_or_default() . } . . fn get_super_predicates( . self, . item_id: DefIndex, . tcx: TyCtxt<'tcx>, . ) -> ty::GenericPredicates<'tcx> { 130 ( 0.00%) self.root.tables.super_predicates.get(self, item_id).unwrap().decode((self, tcx)) . } . . fn get_explicit_item_bounds( . self, . item_id: DefIndex, . tcx: TyCtxt<'tcx>, . ) -> &'tcx [(ty::Predicate<'tcx>, Span)] { 5 ( 0.00%) self.root . .tables . .explicit_item_bounds . .get(self, item_id) 4 ( 0.00%) .map(|bounds| tcx.arena.alloc_from_iter(bounds.decode((self, tcx)))) . .unwrap_or_default() . } . . fn get_generics(self, item_id: DefIndex, sess: &Session) -> ty::Generics { 22,922 ( 0.00%) self.root.tables.generics.get(self, item_id).unwrap().decode((self, sess)) . } . . fn get_type(self, id: DefIndex, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { 1,875 ( 0.00%) self.root . .tables . .ty . .get(self, id) . .unwrap_or_else(|| panic!("Not a type: {:?}", id)) . .decode((self, tcx)) . } . . fn get_stability(self, id: DefIndex) -> Option { 705 ( 0.00%) self.root.tables.stability.get(self, id).map(|stab| stab.decode(self)) . } . . fn get_const_stability(self, id: DefIndex) -> Option { 10 ( 0.00%) self.root.tables.const_stability.get(self, id).map(|stab| stab.decode(self)) . } . . fn get_deprecation(self, id: DefIndex) -> Option { 680 ( 0.00%) self.root.tables.deprecation.get(self, id).map(|depr| depr.decode(self)) . } . 318 ( 0.00%) fn get_visibility(self, id: DefIndex) -> ty::Visibility { 9,831 ( 0.00%) self.root.tables.visibility.get(self, id).unwrap().decode(self) 212 ( 0.00%) } . . fn get_impl_data(self, id: DefIndex) -> ImplData { 16,590 ( 0.00%) match self.kind(id) { 13,825 ( 0.00%) EntryKind::Impl(data) => data.decode(self), . _ => bug!(), . } . } . . fn get_parent_impl(self, id: DefIndex) -> Option { 7,365 ( 0.00%) self.get_impl_data(id).parent_impl . } . . fn get_impl_polarity(self, id: DefIndex) -> ty::ImplPolarity { 284 ( 0.00%) self.get_impl_data(id).polarity . } . . fn get_impl_defaultness(self, id: DefIndex) -> hir::Defaultness { 19 ( 0.00%) self.get_impl_data(id).defaultness . } . . fn get_impl_constness(self, id: DefIndex) -> hir::Constness { 7 ( 0.00%) self.get_impl_data(id).constness . } . . fn get_trait_item_def_id(self, id: DefIndex) -> Option { 8,030 ( 0.00%) self.root.tables.trait_item_def_id.get(self, id).map(|d| d.decode(self)) . } . . fn get_coerce_unsized_info(self, id: DefIndex) -> Option { . self.get_impl_data(id).coerce_unsized_info . } . . fn get_impl_trait(self, id: DefIndex, tcx: TyCtxt<'tcx>) -> Option> { 50,308 ( 0.00%) self.root.tables.impl_trait_ref.get(self, id).map(|tr| tr.decode((self, tcx))) . } . . fn get_expn_that_defined(self, id: DefIndex, sess: &Session) -> ExpnId { 2,220 ( 0.00%) self.root.tables.expn_that_defined.get(self, id).unwrap().decode((self, sess)) . } . . fn get_const_param_default( . self, . tcx: TyCtxt<'tcx>, . id: DefIndex, . ) -> rustc_middle::ty::Const<'tcx> { . self.root.tables.const_defaults.get(self, id).unwrap().decode((self, tcx)) -- line 1026 ---------------------------------------- -- line 1028 ---------------------------------------- . . /// Iterates over all the stability attributes in the given crate. . fn get_lib_features(self, tcx: TyCtxt<'tcx>) -> &'tcx [(Symbol, Option)] { . tcx.arena.alloc_from_iter(self.root.lib_features.decode(self)) . } . . /// Iterates over the language items in the given crate. . fn get_lang_items(self, tcx: TyCtxt<'tcx>) -> &'tcx [(DefId, usize)] { 60 ( 0.00%) tcx.arena.alloc_from_iter( 40 ( 0.00%) self.root . .lang_items . .decode(self) 564 ( 0.00%) .map(|(def_index, index)| (self.local_def_id(def_index), index)), . ) . } . . /// Iterates over the diagnostic items in the given crate. . fn get_diagnostic_items(self) -> DiagnosticItems { . let mut id_to_name = FxHashMap::default(); 8 ( 0.00%) let name_to_id = self . .root . .diagnostic_items . .decode(self) . .map(|(name, def_index)| { 130 ( 0.00%) let id = self.local_def_id(def_index); 130 ( 0.00%) id_to_name.insert(id, name); . (name, id) . }) . .collect(); 36 ( 0.00%) DiagnosticItems { id_to_name, name_to_id } . } . . /// Iterates over all named children of the given module, . /// including both proper items and reexports. . /// Module here is understood in name resolution sense - it can be a `mod` item, . /// or a crate root, or an enum, or a trait. . fn for_each_module_child( . self, . id: DefIndex, . mut callback: impl FnMut(ModChild), . sess: &Session, . ) { 220 ( 0.00%) if let Some(data) = &self.root.proc_macro_data { . // If we are loading as a proc macro, we want to return . // the view of this crate as a proc macro crate. . if id == CRATE_DEF_INDEX { . for def_index in data.macros.decode(self) { . let raw_macro = self.raw_proc_macro(def_index); . let res = Res::Def( . DefKind::Macro(macro_kind(raw_macro)), . self.local_def_id(def_index), -- line 1078 ---------------------------------------- -- line 1085 ---------------------------------------- . span: ident.span, . }); . } . } . return; . } . . // Iterate over all children. 440 ( 0.00%) if let Some(children) = self.root.tables.children.get(self, id) { 880 ( 0.00%) for child_index in children.decode((self, sess)) { 8,850 ( 0.00%) if let Some(ident) = self.opt_item_ident(child_index, sess) { 1,530 ( 0.00%) let kind = self.def_kind(child_index); 1,020 ( 0.00%) if matches!(kind, DefKind::Macro(..)) { . // FIXME: Macros are currently encoded twice, once as items and once as . // reexports. We ignore the items here and only use the reexports. . continue; . } . let def_id = self.local_def_id(child_index); . let res = Res::Def(kind, def_id); . let vis = self.get_visibility(child_index); . let span = self.get_span(child_index, sess); . . callback(ModChild { ident, res, vis, span }); . . // For non-re-export structs and variants add their constructors to children. . // Re-export lists automatically contain constructors when necessary. 1,934 ( 0.00%) match kind { . DefKind::Struct => { 41 ( 0.00%) if let Some((ctor_def_id, ctor_kind)) = . self.get_ctor_def_id_and_kind(child_index) . { . let ctor_res = . Res::Def(DefKind::Ctor(CtorOf::Struct, ctor_kind), ctor_def_id); . let vis = self.get_visibility(ctor_def_id.index); . callback(ModChild { ident, res: ctor_res, vis, span }); . } . } . DefKind::Variant => { . // Braced variants, unlike structs, generate unusable names in . // value namespace, they are reserved for possible future use. . // It's ok to use the variant's id as a ctor id since an . // error will be reported on any use of such resolution anyway. 39 ( 0.00%) let (ctor_def_id, ctor_kind) = self . .get_ctor_def_id_and_kind(child_index) . .unwrap_or((def_id, CtorKind::Fictive)); . let ctor_res = . Res::Def(DefKind::Ctor(CtorOf::Variant, ctor_kind), ctor_def_id); . let mut vis = self.get_visibility(ctor_def_id.index); 31 ( 0.00%) if ctor_def_id == def_id && vis.is_public() { . // For non-exhaustive variants lower the constructor visibility to . // within the crate. We only need this for fictive constructors, . // for other constructors correct visibilities . // were already encoded in metadata. 18 ( 0.00%) let mut attrs = self.get_item_attrs(def_id.index, sess); . if attrs.any(|item| item.has_name(sym::non_exhaustive)) { . let crate_def_id = self.local_def_id(CRATE_DEF_INDEX); . vis = ty::Visibility::Restricted(crate_def_id); . } . } . callback(ModChild { ident, res: ctor_res, vis, span }); . } . _ => {} . } . } . } . } . 545 ( 0.00%) match self.kind(id) { 44 ( 0.00%) EntryKind::Mod(exports) => { 1,412 ( 0.00%) for exp in exports.decode((self, sess)) { . callback(exp); . } . } . EntryKind::Enum(..) | EntryKind::Trait(..) => {} . _ => bug!("`for_each_module_child` is called on a non-module: {:?}", self.def_kind(id)), . } . } . . fn is_ctfe_mir_available(self, id: DefIndex) -> bool { 8 ( 0.00%) self.root.tables.mir_for_ctfe.get(self, id).is_some() . } . . fn is_item_mir_available(self, id: DefIndex) -> bool { . self.root.tables.mir.get(self, id).is_some() . } . . fn module_expansion(self, id: DefIndex, sess: &Session) -> ExpnId { 2,709 ( 0.00%) match self.kind(id) { . EntryKind::Mod(_) | EntryKind::Enum(_) | EntryKind::Trait(_) => { . self.get_expn_that_defined(id, sess) . } . _ => panic!("Expected module, found {:?}", self.local_def_id(id)), . } . } . . fn get_optimized_mir(self, tcx: TyCtxt<'tcx>, id: DefIndex) -> Body<'tcx> { -- line 1180 ---------------------------------------- -- line 1184 ---------------------------------------- . .get(self, id) . .unwrap_or_else(|| { . bug!("get_optimized_mir: missing MIR for `{:?}`", self.local_def_id(id)) . }) . .decode((self, tcx)) . } . . fn get_mir_for_ctfe(self, tcx: TyCtxt<'tcx>, id: DefIndex) -> Body<'tcx> { 10 ( 0.00%) self.root . .tables . .mir_for_ctfe . .get(self, id) . .unwrap_or_else(|| { . bug!("get_mir_for_ctfe: missing MIR for `{:?}`", self.local_def_id(id)) . }) . .decode((self, tcx)) . } -- line 1200 ---------------------------------------- -- line 1242 ---------------------------------------- . qualif, . _, . ) => qualif, . _ => bug!("mir_const_qualif: unexpected kind"), . } . } . . fn get_fn_has_self_parameter(self, id: DefIndex) -> bool { 565 ( 0.00%) match self.kind(id) { 452 ( 0.00%) EntryKind::AssocFn(data) => data.decode(self).has_self, . _ => false, . } . } . . fn get_associated_item_def_ids(self, tcx: TyCtxt<'tcx>, id: DefIndex) -> &'tcx [DefId] { 987 ( 0.00%) if let Some(children) = self.root.tables.children.get(self, id) { 423 ( 0.00%) tcx.arena.alloc_from_iter( 141 ( 0.00%) children.decode((self, tcx.sess)).map(|child_index| self.local_def_id(child_index)), . ) . } else { . &[] . } . } . 17,280 ( 0.00%) fn get_associated_item(self, id: DefIndex, sess: &Session) -> ty::AssocItem { 10,080 ( 0.00%) let def_key = self.def_key(id); . let parent = self.local_def_id(def_key.parent.unwrap()); . let ident = self.item_ident(id, sess); . 10,332 ( 0.00%) let (kind, container, has_self) = match self.kind(id) { 128 ( 0.00%) EntryKind::AssocConst(container, _, _) => (ty::AssocKind::Const, container, false), 1,346 ( 0.00%) EntryKind::AssocFn(data) => { . let data = data.decode(self); 9,422 ( 0.00%) (ty::AssocKind::Fn, data.container, data.has_self) . } 124 ( 0.00%) EntryKind::AssocType(container) => (ty::AssocKind::Type, container, false), . _ => bug!("cannot get associated-item of `{:?}`", def_key), . }; . 25,920 ( 0.00%) ty::AssocItem { . name: ident.name, . kind, . vis: self.get_visibility(id), . defaultness: container.defaultness(), . def_id: self.local_def_id(id), . trait_item_def_id: self.get_trait_item_def_id(id), . container: container.with_def_id(parent), . fn_has_self_parameter: has_self, . } 12,960 ( 0.00%) } . . fn get_item_variances(self, id: DefIndex) -> impl Iterator + 'a { 190 ( 0.00%) self.root.tables.variances.get(self, id).unwrap_or_else(Lazy::empty).decode(self) . } . . fn get_ctor_def_id_and_kind(self, node_id: DefIndex) -> Option<(DefId, CtorKind)> { 1,612 ( 0.00%) match self.kind(node_id) { . EntryKind::Struct(data, _) | EntryKind::Variant(data) => { 693 ( 0.00%) let vdata = data.decode(self); 597 ( 0.00%) vdata.ctor.map(|index| (self.local_def_id(index), vdata.ctor_kind)) . } . _ => None, . } 873 ( 0.00%) } . 408 ( 0.00%) fn get_item_attrs( . self, . id: DefIndex, . sess: &'a Session, . ) -> impl Iterator + 'a { 918 ( 0.00%) self.root . .tables . .attributes . .get(self, id) . .unwrap_or_else(|| { . // Structure and variant constructors don't have any attributes encoded for them, . // but we assume that someone passing a constructor ID actually wants to look at . // the attributes on the corresponding struct or variant. . let def_key = self.def_key(id); -- line 1320 ---------------------------------------- -- line 1322 ---------------------------------------- . let parent_id = def_key.parent.expect("no parent for a constructor"); . self.root . .tables . .attributes . .get(self, parent_id) . .expect("no encoded attributes for a structure or variant") . }) . .decode((self, sess)) 306 ( 0.00%) } . . fn get_struct_field_names( . self, . id: DefIndex, . sess: &'a Session, . ) -> impl Iterator> + 'a { 800 ( 0.00%) self.root . .tables . .children . .get(self, id) . .unwrap_or_else(Lazy::empty) . .decode(self) 2,930 ( 0.00%) .map(move |index| respan(self.get_span(index, sess), self.item_ident(index, sess).name)) . } . . fn get_struct_field_visibilities(self, id: DefIndex) -> impl Iterator + 'a { 290 ( 0.00%) self.root . .tables . .children . .get(self, id) . .unwrap_or_else(Lazy::empty) . .decode(self) 106 ( 0.00%) .map(move |field_index| self.get_visibility(field_index)) . } . . fn get_inherent_implementations_for_type( . self, . tcx: TyCtxt<'tcx>, . id: DefIndex, . ) -> &'tcx [DefId] { 92 ( 0.00%) tcx.arena.alloc_from_iter( 115 ( 0.00%) self.root . .tables . .inherent_impls . .get(self, id) . .unwrap_or_else(Lazy::empty) . .decode(self) 1,474 ( 0.00%) .map(|index| self.local_def_id(index)), . ) . } . . fn get_traits(self) -> impl Iterator + 'a { . self.root.traits.decode(self).map(move |index| self.local_def_id(index)) . } . . fn get_trait_impls(self) -> impl Iterator)> + 'a { -- line 1376 ---------------------------------------- -- line 1380 ---------------------------------------- . index: *trait_index, . }; . impls.decode(self).map(move |(impl_index, simplified_self_ty)| { . (trait_def_id, self.local_def_id(impl_index), simplified_self_ty) . }) . }) . } . 7,740 ( 0.00%) fn get_implementations_of_trait( . self, . tcx: TyCtxt<'tcx>, . trait_def_id: DefId, . ) -> &'tcx [(DefId, Option)] { 860 ( 0.00%) if self.trait_impls.is_empty() { . return &[]; . } . . // Do a reverse lookup beforehand to avoid touching the crate_num . // hash map in the loop below. 1,430 ( 0.00%) let key = match self.reverse_translate_def_id(trait_def_id) { . Some(def_id) => (def_id.krate.as_u32(), def_id.index), . None => return &[], . }; . . if let Some(impls) = self.trait_impls.get(&key) { 816 ( 0.00%) tcx.arena.alloc_from_iter( 408 ( 0.00%) impls . .decode(self) 6,804 ( 0.00%) .map(|(idx, simplified_self_ty)| (self.local_def_id(idx), simplified_self_ty)), . ) . } else { . &[] . } 6,880 ( 0.00%) } . . fn get_trait_of_item(self, id: DefIndex) -> Option { 312 ( 0.00%) let def_key = self.def_key(id); 390 ( 0.00%) match def_key.disambiguated_data.data { . DefPathData::TypeNs(..) | DefPathData::ValueNs(..) => (), . // Not an associated item . _ => return None, . } 702 ( 0.00%) def_key.parent.and_then(|parent_index| match self.kind(parent_index) { . EntryKind::Trait(_) | EntryKind::TraitAlias => Some(self.local_def_id(parent_index)), . _ => None, . }) . } . . fn get_native_libraries(self, sess: &'a Session) -> impl Iterator + 'a { 40 ( 0.00%) self.root.native_libraries.decode((self, sess)) . } . . fn get_proc_macro_quoted_span(self, index: usize, sess: &Session) -> Span { . self.root . .tables . .proc_macro_quoted_spans . .get(self, index) . .unwrap_or_else(|| panic!("Missing proc macro quoted span: {:?}", index)) -- line 1437 ---------------------------------------- -- line 1450 ---------------------------------------- . self.root.dylib_dependency_formats.decode(self).enumerate().flat_map(|(i, link)| { . let cnum = CrateNum::new(i + 1); . link.map(|link| (self.cnum_map[cnum], link)) . }), . ) . } . . fn get_missing_lang_items(self, tcx: TyCtxt<'tcx>) -> &'tcx [lang_items::LangItem] { 100 ( 0.00%) tcx.arena.alloc_from_iter(self.root.lang_items_missing.decode(self)) . } . . fn get_fn_param_names(self, tcx: TyCtxt<'tcx>, id: DefIndex) -> &'tcx [Ident] { . let param_names = match self.kind(id) { . EntryKind::Fn(data) | EntryKind::ForeignFn(data) => data.decode(self).param_names, . EntryKind::AssocFn(data) => data.decode(self).fn_data.param_names, . _ => Lazy::empty(), . }; -- line 1466 ---------------------------------------- -- line 1479 ---------------------------------------- . EntryKind::AnonConst(_, data) . | EntryKind::Const(_, data) . | EntryKind::AssocConst(_, _, data) => data.decode(self).0, . _ => bug!(), . } . } . . fn get_macro(self, id: DefIndex, sess: &Session) -> MacroDef { 66 ( 0.00%) match self.kind(id) { 11 ( 0.00%) EntryKind::MacroDef(macro_def) => macro_def.decode((self, sess)), . _ => bug!(), . } . } . . // This replicates some of the logic of the crate-local `is_const_fn_raw` query, because we . // don't serialize constness for tuple variant and tuple struct constructors. . fn is_const_fn_raw(self, id: DefIndex) -> bool { 162 ( 0.00%) let constness = match self.kind(id) { 34 ( 0.00%) EntryKind::AssocFn(data) => data.decode(self).fn_data.constness, 6 ( 0.00%) EntryKind::Fn(data) => data.decode(self).constness, . EntryKind::ForeignFn(data) => data.decode(self).constness, . EntryKind::Variant(..) | EntryKind::Struct(..) => hir::Constness::Const, . _ => hir::Constness::NotConst, . }; . constness == hir::Constness::Const . } . . fn asyncness(self, id: DefIndex) -> hir::IsAsync { -- line 1506 ---------------------------------------- -- line 1532 ---------------------------------------- . fn generator_kind(self, id: DefIndex) -> Option { . match self.kind(id) { . EntryKind::Generator(data) => Some(data), . _ => None, . } . } . . fn fn_sig(self, id: DefIndex, tcx: TyCtxt<'tcx>) -> ty::PolyFnSig<'tcx> { 550 ( 0.00%) self.root.tables.fn_sig.get(self, id).unwrap().decode((self, tcx)) . } . . #[inline] 54,733 ( 0.00%) fn def_key(self, index: DefIndex) -> DefKey { 15,638 ( 0.00%) *self . .def_key_cache . .lock() . .entry(index) 16,285 ( 0.00%) .or_insert_with(|| self.root.tables.def_keys.get(self, index).unwrap().decode(self)) 62,552 ( 0.00%) } . . // Returns the path leading to the thing with this `id`. . fn def_path(self, id: DefIndex) -> DefPath { . debug!("def_path(cnum={:?}, id={:?})", self.cnum, id); . DefPath::make(self.cnum, id, |parent| self.def_key(parent)) . } . . fn def_path_hash_unlocked( . self, . index: DefIndex, . def_path_hashes: &mut FxHashMap, . ) -> DefPathHash { 22,676 ( 0.00%) *def_path_hashes.entry(index).or_insert_with(|| { 555 ( 0.00%) self.root.tables.def_path_hashes.get(self, index).unwrap().decode(self) . }) . } . . #[inline] 79,366 ( 0.00%) fn def_path_hash(self, index: DefIndex) -> DefPathHash { . let mut def_path_hashes = self.def_path_hash_cache.lock(); . self.def_path_hash_unlocked(index, &mut def_path_hashes) 90,704 ( 0.00%) } . . #[inline] . fn def_path_hash_to_def_index(self, hash: DefPathHash) -> DefIndex { . self.def_path_hash_map.def_path_hash_to_def_index(&hash) . } . . fn expn_hash_to_expn_id(self, sess: &Session, index_guess: u32, hash: ExpnHash) -> ExpnId { . debug_assert_eq!(ExpnId::from_hash(hash), None); -- line 1580 ---------------------------------------- -- line 1635 ---------------------------------------- . /// Proc macro crates don't currently export spans, so this function does not have . /// to work for them. . fn imported_source_files(self, sess: &Session) -> &'a [ImportedSourceFile] { . // Translate the virtual `/rustc/$hash` prefix back to a real directory . // that should hold actual sources, where possible. . // . // NOTE: if you update this, you might need to also update bootstrap's code for generating . // the `rust-src` component in `Src::run` in `src/bootstrap/dist.rs`. 26,542 ( 0.00%) let virtual_rust_source_base_dir = option_env!("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR") . .map(Path::new) . .filter(|_| { . // Only spend time on further checks if we have what to translate *to*. . sess.opts.real_rust_source_base_dir.is_some() . }) . .filter(|virtual_dir| { . // Don't translate away `/rustc/$hash` if we're still remapping to it, . // since that means we're still building `std`/`rustc` that need it, . // and we don't want the real path to leak into codegen/debuginfo. . !sess.opts.remap_path_prefix.iter().any(|(_from, to)| to == virtual_dir) . }); 26,542 ( 0.00%) let try_to_translate_virtual_to_real = |name: &mut rustc_span::FileName| { . debug!( . "try_to_translate_virtual_to_real(name={:?}): \ . virtual_rust_source_base_dir={:?}, real_rust_source_base_dir={:?}", . name, virtual_rust_source_base_dir, sess.opts.real_rust_source_base_dir, . ); . 2,690 ( 0.00%) if let Some(virtual_dir) = virtual_rust_source_base_dir { . if let Some(real_dir) = &sess.opts.real_rust_source_base_dir { . if let rustc_span::FileName::Real(old_name) = name { . if let rustc_span::RealFileName::Remapped { local_path: _, virtual_name } = . old_name . { . if let Ok(rest) = virtual_name.strip_prefix(virtual_dir) { . let virtual_name = virtual_name.clone(); . -- line 1670 ---------------------------------------- -- line 1709 ---------------------------------------- . *old_name = new_name; . } . } . } . } . } . }; . 26,528 ( 0.00%) self.cdata.source_map_import_info.get_or_init(|| { 21 ( 0.00%) let external_source_map = self.root.source_map.decode(self); . . external_source_map . .map(|source_file_to_import| { . // We can't reuse an existing SourceFile, so allocate a new one . // containing the information we need. . let rustc_span::SourceFile { 11,298 ( 0.00%) mut name, 3,228 ( 0.00%) src_hash, 538 ( 0.00%) start_pos, 1,076 ( 0.00%) end_pos, 2,690 ( 0.00%) mut lines, 2,690 ( 0.00%) mut multibyte_chars, 3,228 ( 0.00%) mut non_narrow_chars, 2,690 ( 0.00%) mut normalized_pos, 3,228 ( 0.00%) name_hash, . .. . } = source_file_to_import; . . // If this file is under $sysroot/lib/rustlib/src/ but has not been remapped . // during rust bootstrapping by `remap-debuginfo = true`, and the user . // wish to simulate that behaviour by -Z simulate-remapped-rust-src-base, . // then we change `name` to a similar state as if the rust was bootstrapped . // with `remap-debuginfo = true`. . // This is useful for testing so that tests about the effects of . // `try_to_translate_virtual_to_real` don't have to worry about how the . // compiler is bootstrapped. 1,076 ( 0.00%) if let Some(virtual_dir) = . &sess.opts.debugging_opts.simulate_remapped_rust_src_base . { . if let Some(real_dir) = &sess.opts.real_rust_source_base_dir { . if let rustc_span::FileName::Real(ref mut old_name) = name { . if let rustc_span::RealFileName::LocalPath(local) = old_name { . if let Ok(rest) = local.strip_prefix(real_dir) { . *old_name = rustc_span::RealFileName::Remapped { . local_path: None, -- line 1753 ---------------------------------------- -- line 1767 ---------------------------------------- . let source_length = (end_pos - start_pos).to_usize(); . . // Translate line-start positions and multibyte character . // position into frame of reference local to file. . // `SourceMap::new_imported_source_file()` will then translate those . // coordinates to their new global frame of reference when the . // offset of the SourceFile is known. . for pos in &mut lines { 713,490 ( 0.02%) *pos = *pos - start_pos; . } . for mbc in &mut multibyte_chars { 1,598 ( 0.00%) mbc.pos = mbc.pos - start_pos; . } . for swc in &mut non_narrow_chars { 924 ( 0.00%) *swc = *swc - start_pos; . } . for np in &mut normalized_pos { . np.pos = np.pos - start_pos; . } . 9,684 ( 0.00%) let local_version = sess.source_map().new_imported_source_file( 6,994 ( 0.00%) name, 3,766 ( 0.00%) src_hash, . name_hash, . source_length, 1,076 ( 0.00%) self.cnum, 2,690 ( 0.00%) lines, 3,228 ( 0.00%) multibyte_chars, 2,690 ( 0.00%) non_narrow_chars, 2,152 ( 0.00%) normalized_pos, . start_pos, . end_pos, . ); . debug!( . "CrateMetaData::imported_source_files alloc \ . source_file {:?} original (start_pos {:?} end_pos {:?}) \ . translated (start_pos {:?} end_pos {:?})", . local_version.name, -- line 1804 ---------------------------------------- -- line 1808 ---------------------------------------- . local_version.end_pos . ); . . ImportedSourceFile { . original_start_pos: start_pos, . original_end_pos: end_pos, . translated_source_file: local_version, . } 1,614 ( 0.00%) }) . .collect() . }) . } . } . . impl CrateMetadata { 240 ( 0.00%) crate fn new( . sess: &Session, . blob: MetadataBlob, . root: CrateRoot<'static>, . raw_proc_macros: Option<&'static [ProcMacro]>, . cnum: CrateNum, . cnum_map: CrateNumMap, . dep_kind: CrateDepKind, . source: CrateSource, . private_dep: bool, . host_hash: Option, . ) -> CrateMetadata { 60 ( 0.00%) let trait_impls = root . .impls . .decode((&blob, sess)) . .map(|trait_impls| (trait_impls.trait_id, trait_impls.impls)) . .collect(); . let alloc_decoding_state = 60 ( 0.00%) AllocDecodingState::new(root.interpret_alloc_index.decode(&blob).collect()); . let dependencies = Lock::new(cnum_map.iter().cloned().collect()); . . // Pre-decode the DefPathHash->DefIndex table. This is a cheap operation . // that does not copy any data. It just does some data verification. 20 ( 0.00%) let def_path_hash_map = root.def_path_hash_map.decode(&blob); . 460 ( 0.00%) CrateMetadata { 20 ( 0.00%) blob, 60 ( 0.00%) root, 80 ( 0.00%) trait_impls, . raw_proc_macros, . source_map_import_info: OnceCell::new(), 80 ( 0.00%) def_path_hash_map, . expn_hash_map: Default::default(), 140 ( 0.00%) alloc_decoding_state, . cnum, 80 ( 0.00%) cnum_map, 100 ( 0.00%) dependencies, . dep_kind: Lock::new(dep_kind), 240 ( 0.00%) source, . private_dep, . host_hash, . extern_crate: Lock::new(None), . hygiene_context: Default::default(), . def_key_cache: Default::default(), . def_path_hash_cache: Default::default(), . } 180 ( 0.00%) } . . crate fn dependencies(&self) -> LockGuard<'_, Vec> { . self.dependencies.borrow() . } . 6 ( 0.00%) crate fn add_dependency(&self, cnum: CrateNum) { . self.dependencies.borrow_mut().push(cnum); 8 ( 0.00%) } . . crate fn update_extern_crate(&self, new_extern_crate: ExternCrate) -> bool { . let mut extern_crate = self.extern_crate.borrow_mut(); . let update = Some(new_extern_crate.rank()) > extern_crate.as_ref().map(ExternCrate::rank); . if update { 105 ( 0.00%) *extern_crate = Some(new_extern_crate); . } . update . } . . crate fn source(&self) -> &CrateSource { 13,064 ( 0.00%) &self.source . } . . crate fn dep_kind(&self) -> CrateDepKind { 1 ( 0.00%) *self.dep_kind.lock() . } . . crate fn update_dep_kind(&self, f: impl FnOnce(CrateDepKind) -> CrateDepKind) { 3,353 ( 0.00%) self.dep_kind.with_lock(|dep_kind| *dep_kind = f(*dep_kind)) . } . . crate fn panic_strategy(&self) -> PanicStrategy { 2 ( 0.00%) self.root.panic_strategy . } . . crate fn needs_panic_runtime(&self) -> bool { 58 ( 0.00%) self.root.needs_panic_runtime . } . . crate fn is_panic_runtime(&self) -> bool { 21 ( 0.00%) self.root.panic_runtime . } . . crate fn is_profiler_runtime(&self) -> bool { . self.root.profiler_runtime . } . . crate fn needs_allocator(&self) -> bool { 5 ( 0.00%) self.root.needs_allocator . } . . crate fn has_global_allocator(&self) -> bool { 20 ( 0.00%) self.root.has_global_allocator . } . . crate fn has_default_lib_allocator(&self) -> bool { 3 ( 0.00%) self.root.has_default_lib_allocator . } . . crate fn is_proc_macro_crate(&self) -> bool { . self.root.is_proc_macro_crate() . } . . crate fn name(&self) -> Symbol { 64,221 ( 0.00%) self.root.name . } . . crate fn stable_crate_id(&self) -> StableCrateId { . self.root.stable_crate_id . } . . crate fn hash(&self) -> Svh { . self.root.hash . } . . fn num_def_ids(&self) -> usize { . self.root.tables.def_keys.size() . } . . fn local_def_id(&self, index: DefIndex) -> DefId { 15,783 ( 0.00%) DefId { krate: self.cnum, index } . } . . // Translate a DefId from the current compilation environment to a DefId . // for an external crate. . fn reverse_translate_def_id(&self, did: DefId) -> Option { . for (local, &global) in self.cnum_map.iter_enumerated() { 2,901 ( 0.00%) if global == did.krate { . return Some(DefId { krate: local, index: did.index }); . } . } . . None . } . } . -- line 1964 ---------------------------------------- 497,496 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/mod.rs -------------------------------------------------------------------------------- Ir -- line 108 ---------------------------------------- . suppress_errors: bool, . }, . } . . impl RegionckMode { . /// Indicates that the MIR borrowck will repeat these region . /// checks, so we should ignore errors if NLL is (unconditionally) . /// enabled. 103 ( 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. 103 ( 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 }, . } 206 ( 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> { 24,905 ( 0.00%) fn new() -> InferCtxtInner<'tcx> { 169,354 ( 0.00%) 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(), 14,943 ( 0.00%) region_constraint_storage: Some(RegionConstraintStorage::new()), . region_obligations: vec![], . opaque_types: Default::default(), . opaque_types_vars: Default::default(), . } 29,886 ( 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> { 1,964 ( 0.00%) self.projection_cache.with_log(&mut self.undo_log) . } . . #[inline] . fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> { 361,066 ( 0.01%) 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>, . >, . > { 15,302 ( 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, . &mut ut::UnificationStorage, . &mut InferCtxtUndoLogs<'tcx>, . >, . > { 84 ( 0.00%) self.float_unification_storage.with_log(&mut self.undo_log) . } . . #[inline] . fn const_unification_table( . &mut self, . ) -> ut::UnificationTable< . ut::InPlace< . ty::ConstVid<'tcx>, . &mut ut::UnificationStorage>, . &mut InferCtxtUndoLogs<'tcx>, . >, . > { 3,992 ( 0.00%) self.const_unification_storage.with_log(&mut self.undo_log) . } . . #[inline] . pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> { 28,702 ( 0.00%) self.region_constraint_storage . .as_mut() . .expect("region constraints already solved") 31,457 ( 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. 43,456 ( 0.00%) #[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable)] . pub enum ValuePairs<'tcx> { . Types(ExpectedFound>), . Regions(ExpectedFound>), . Consts(ExpectedFound<&'tcx ty::Const<'tcx>>), . TraitRefs(ExpectedFound>), . PolyTraitRefs(ExpectedFound>), . } . -- line 377 ---------------------------------------- -- line 383 ---------------------------------------- . pub struct TypeTrace<'tcx> { . cause: ObligationCause<'tcx>, . values: ValuePairs<'tcx>, . } . . /// The origin of a `r1 <= r2` constraint. . /// . /// See `error_reporting` module for more details 36,664 ( 0.00%) #[derive(Clone, Debug)] . pub enum SubregionOrigin<'tcx> { . /// Arose from a subtyping relation 2,330 ( 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. 78 ( 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 117 ( 0.00%) DataBorrowed(Ty<'tcx>, Span), . . /// (&'a &'b T) where a >= b 79 ( 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> { 4,981 ( 0.00%) fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> { 14,943 ( 0.00%) InferCtxtBuilder { tcx: self, defining_use_anchor: None, fresh_typeck_results: None } 4,981 ( 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. 2,754 ( 0.00%) pub fn with_fresh_in_progress_typeck_results(mut self, table_owner: LocalDefId) -> Self { 3,366 ( 0.00%) self.fresh_typeck_results = Some(RefCell::new(ty::TypeckResults::new(table_owner))); 1,530 ( 0.00%) self.with_opaque_type_inference(table_owner) 2,142 ( 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. 220 ( 0.00%) pub fn with_opaque_type_inference(mut self, defining_use_anchor: LocalDefId) -> Self { 110 ( 0.00%) self.defining_use_anchor = Some(defining_use_anchor); 832 ( 0.00%) self 330 ( 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`). 8,709 ( 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| { 10,714 ( 0.00%) let (value, subst) = 669 ( 0.00%) infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical); 16,197 ( 0.00%) f(infcx, value, subst) . }) 9,356 ( 0.00%) } . 27,897 ( 0.00%) pub fn enter(&mut self, f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>) -> R) -> R { 13,996 ( 0.00%) let InferCtxtBuilder { tcx, defining_use_anchor, ref fresh_typeck_results } = *self; . let in_progress_typeck_results = fresh_typeck_results.as_ref(); 208,001 ( 0.01%) f(InferCtxt { . tcx, . defining_use_anchor, . in_progress_typeck_results, 4,981 ( 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), 4,981 ( 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), . }) 30,240 ( 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 { 124 ( 0.00%) let InferOk { value, obligations } = self; 500 ( 0.00%) for obligation in obligations { 195 ( 0.00%) fulfill_cx.register_predicate_obligation(infcx, obligation); . } . value . } . } . . impl<'tcx> InferOk<'tcx, ()> { 9,599 ( 0.00%) pub fn into_obligations(self) -> PredicateObligations<'tcx> { 38,396 ( 0.00%) self.obligations 9,599 ( 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() 31,152 ( 0.00%) } . 86,232 ( 0.00%) pub fn freshen>(&self, t: T) -> T { 97,011 ( 0.00%) t.fold_with(&mut self.freshener()) 97,011 ( 0.00%) } . . /// Returns the origin of the type variable identified by `vid`, or `None` . /// if this is not a type variable. . /// . /// No attempt is made to resolve `ty`. 192 ( 0.00%) pub fn type_var_origin(&'a self, ty: Ty<'tcx>) -> Option { 384 ( 0.00%) match *ty.kind() { 80 ( 0.00%) ty::Infer(ty::TyVar(vid)) => { 320 ( 0.00%) Some(*self.inner.borrow_mut().type_variables().var_origin(vid)) . } 16 ( 0.00%) _ => None, . } 384 ( 0.00%) } . 10,779 ( 0.00%) pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> { . freshen::TypeFreshener::new(self, false) 10,779 ( 0.00%) } . . /// Like `freshener`, but does not replace `'static` regions. 61,190 ( 0.00%) pub fn freshener_keep_static<'b>(&'b self) -> TypeFreshener<'b, 'tcx> { . freshen::TypeFreshener::new(self, true) 61,190 ( 0.00%) } . 476 ( 0.00%) pub fn unsolved_variables(&self) -> Vec> { 238 ( 0.00%) let mut inner = self.inner.borrow_mut(); 238 ( 0.00%) let mut vars: Vec> = inner . .type_variables() . .unsolved_variables() . .into_iter() 160 ( 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 }) 352 ( 0.00%) .filter(|&vid| inner.int_unification_table().probe_value(vid).is_none()) 16 ( 0.00%) .map(|v| self.tcx.mk_int_var(v)), . ); . vars.extend( . (0..inner.float_unification_table().len()) . .map(|i| ty::FloatVid { index: i as u32 }) 12 ( 0.00%) .filter(|&vid| inner.float_unification_table().probe_value(vid).is_none()) . .map(|v| self.tcx.mk_float_var(v)), . ); . vars 833 ( 0.00%) } . 29,950 ( 0.00%) fn combine_fields( . &'a self, . trace: TypeTrace<'tcx>, . param_env: ty::ParamEnv<'tcx>, . ) -> CombineFields<'a, 'tcx> { 119,884 ( 0.00%) CombineFields { . infcx: self, 299,710 ( 0.01%) trace, . cause: None, . param_env, . obligations: PredicateObligations::new(), . } 29,950 ( 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. 32 ( 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); 19,584 ( 0.00%) let result = func(self); . self.in_snapshot.set(flag); . result 36 ( 0.00%) } . 160,810 ( 0.00%) fn start_snapshot(&self) -> CombinedSnapshot<'a, 'tcx> { . debug!("start_snapshot()"); . . let in_snapshot = self.in_snapshot.replace(true); . . let mut inner = self.inner.borrow_mut(); . 482,430 ( 0.01%) CombinedSnapshot { . undo_snapshot: inner.undo_log.start_snapshot(), . region_constraints_snapshot: inner.unwrap_region_constraints().start_snapshot(), . universe: self.universe(), . was_in_snapshot: in_snapshot, . // Borrow typeck results "in progress" (i.e., during typeck) . // to ban writes from within a snapshot to them. 80,405 ( 0.00%) _in_progress_typeck_results: self . .in_progress_typeck_results . .map(|typeck_results| typeck_results.borrow()), . } 321,620 ( 0.01%) } . 326,062 ( 0.01%) #[instrument(skip(self, snapshot), level = "debug")] . fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) { . let CombinedSnapshot { 29,642 ( 0.00%) undo_snapshot, 29,642 ( 0.00%) region_constraints_snapshot, 29,642 ( 0.00%) universe, 29,642 ( 0.00%) was_in_snapshot, 59,284 ( 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(); 29,642 ( 0.00%) inner.rollback_to(undo_snapshot); . inner.unwrap_region_constraints().rollback_to(region_constraints_snapshot); . } . 761,445 ( 0.02%) #[instrument(skip(self, snapshot), level = "debug")] . fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) { . let CombinedSnapshot { 50,763 ( 0.00%) undo_snapshot, . region_constraints_snapshot: _, . universe: _, 50,763 ( 0.00%) was_in_snapshot, 101,526 ( 0.00%) _in_progress_typeck_results, . } = snapshot; . . self.in_snapshot.set(was_in_snapshot); . . self.inner.borrow_mut().commit(undo_snapshot); . } . . /// Executes `f` and commit the bindings. 22,478 ( 0.00%) #[instrument(skip(self, f), level = "debug")] 27,599 ( 0.00%) pub fn commit_unconditionally(&self, f: F) -> R . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R, . { 2,509 ( 0.00%) let snapshot = self.start_snapshot(); 8,079 ( 0.00%) let r = f(&snapshot); 17,563 ( 0.00%) self.commit_from(snapshot); 14,929 ( 0.00%) r . } . . /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`. 312,822 ( 0.01%) #[instrument(skip(self, f), level = "debug")] 385,839 ( 0.01%) pub fn commit_if_ok(&self, f: F) -> Result . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result, . { 63,160 ( 0.00%) let snapshot = self.start_snapshot(); 177,093 ( 0.00%) let r = f(&snapshot); . debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok()); 65,775 ( 0.00%) match r { . Ok(_) => { 339,579 ( 0.01%) self.commit_from(snapshot); . } . Err(_) => { 93,288 ( 0.00%) self.rollback_to("commit_if_ok -- error", snapshot); . } . } 361,869 ( 0.01%) r . } . . /// Execute `f` then unroll any bindings it creates. 135,263 ( 0.00%) #[instrument(skip(self, f), level = "debug")] 162,497 ( 0.00%) pub fn probe(&self, f: F) -> R . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R, . { 34,450 ( 0.00%) let snapshot = self.start_snapshot(); 79,199 ( 0.00%) let r = f(&snapshot); 182,819 ( 0.00%) self.rollback_to("probe", snapshot); 74,732 ( 0.00%) r . } . . /// If `should_skip` is true, then execute `f` then unroll any bindings it creates. . #[instrument(skip(self, f), level = "debug")] . pub fn probe_maybe_skip_leak_check(&self, should_skip: bool, f: F) -> R . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R, . { -- line 875 ---------------------------------------- -- line 884 ---------------------------------------- . r . } . . /// Scan the constraints produced since `snapshot` began and returns: . /// . /// - `None` -- if none of them involve "region outlives" constraints . /// - `Some(true)` -- if there are `'a: 'b` constraints where `'a` or `'b` is a placeholder . /// - `Some(false)` -- if there are `'a: 'b` constraints but none involve placeholders 3,336 ( 0.00%) pub fn region_constraints_added_in_snapshot( . &self, . snapshot: &CombinedSnapshot<'a, 'tcx>, . ) -> Option { 6,672 ( 0.00%) self.inner . .borrow_mut() . .unwrap_region_constraints() . .region_constraints_added_in_snapshot(&snapshot.undo_snapshot) 5,004 ( 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); . } . 396 ( 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. . }) . }) 297 ( 0.00%) } . 612 ( 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. . }) . }) 459 ( 0.00%) } . 8,950 ( 0.00%) #[instrument(skip(self), level = "debug")] . pub fn sub_regions( . &self, . origin: SubregionOrigin<'tcx>, . a: ty::Region<'tcx>, . b: ty::Region<'tcx>, . ) { 8,055 ( 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.) 30 ( 0.00%) pub fn coerce_predicate( . &self, . cause: &ObligationCause<'tcx>, . param_env: ty::ParamEnv<'tcx>, . predicate: ty::PolyCoercePredicate<'tcx>, . ) -> Option> { 20 ( 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, . }); 50 ( 0.00%) self.subtype_predicate(cause, param_env, subtype_predicate) 40 ( 0.00%) } . 1,152 ( 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. 96 ( 0.00%) let r_a = self.shallow_resolve(predicate.skip_binder().a); 96 ( 0.00%) let r_b = self.shallow_resolve(predicate.skip_binder().b); 706 ( 0.00%) match (r_a.kind(), r_b.kind()) { 150 ( 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); 150 ( 0.00%) return None; . } . _ => {} . } . . Some(self.commit_if_ok(|_snapshot| { 21 ( 0.00%) let ty::SubtypePredicate { a_is_expected, a, b } = . self.replace_bound_vars_with_placeholders(predicate); . 42 ( 0.00%) let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?; . . Ok(ok.unit()) . })) 864 ( 0.00%) } . 1,440 ( 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) . }); 1,200 ( 0.00%) self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b` . Ok(()) . }) 960 ( 0.00%) } . . /// Number of type variables created so far. 16 ( 0.00%) pub fn num_ty_vars(&self) -> usize { . self.inner.borrow_mut().type_variables().num_vars() 32 ( 0.00%) } . 15,544 ( 0.00%) pub fn next_ty_var_id(&self, origin: TypeVariableOrigin) -> TyVid { 77,720 ( 0.00%) self.inner.borrow_mut().type_variables().new_var(self.universe(), origin) 23,316 ( 0.00%) } . 14,938 ( 0.00%) pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> { 54,101 ( 0.00%) self.tcx.mk_ty_var(self.next_ty_var_id(origin)) 22,407 ( 0.00%) } . 3,534 ( 0.00%) pub fn next_ty_var_in_universe( . &self, . origin: TypeVariableOrigin, . universe: ty::UniverseIndex, . ) -> Ty<'tcx> { 19,437 ( 0.00%) let vid = self.inner.borrow_mut().type_variables().new_var(universe, origin); 1,767 ( 0.00%) self.tcx.mk_ty_var(vid) 5,301 ( 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 { 615 ( 0.00%) self.inner.borrow_mut().int_unification_table().new_key(None) . } . 369 ( 0.00%) pub fn next_int_var(&self) -> Ty<'tcx> { . self.tcx.mk_int_var(self.next_int_var_id()) 492 ( 0.00%) } . . fn next_float_var_id(&self) -> FloatVid { 10 ( 0.00%) self.inner.borrow_mut().float_unification_table().new_key(None) . } . 6 ( 0.00%) pub fn next_float_var(&self) -> Ty<'tcx> { . self.tcx.mk_float_var(self.next_float_var_id()) 8 ( 0.00%) } . . /// 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. 2,777 ( 0.00%) pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> { 76,708 ( 0.00%) self.next_region_var_in_universe(origin, self.universe()) 5,554 ( 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. 29,908 ( 0.00%) pub fn next_region_var_in_universe( . &self, . origin: RegionVariableOrigin, . universe: ty::UniverseIndex, . ) -> ty::Region<'tcx> { . let region_var = 194,402 ( 0.00%) self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin); 74,770 ( 0.00%) self.tcx.mk_region(ty::ReVar(region_var)) 44,862 ( 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. 1,842 ( 0.00%) pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex { . self.inner.borrow_mut().unwrap_region_constraints().universe(r) 2,763 ( 0.00%) } . . /// Number of region variables created so far. 894 ( 0.00%) pub fn num_region_vars(&self) -> usize { . self.inner.borrow_mut().unwrap_region_constraints().num_region_vars() 1,341 ( 0.00%) } . . /// Just a convenient wrapper of `next_region_var` for using during NLL. 5,763 ( 0.00%) pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin) -> ty::Region<'tcx> { . self.next_region_var(RegionVariableOrigin::Nll(origin)) 11,526 ( 0.00%) } . . /// Just a convenient wrapper of `next_region_var` for using during NLL. 173 ( 0.00%) pub fn next_nll_region_var_in_universe( . &self, . origin: NllRegionVariableOrigin, . universe: ty::UniverseIndex, . ) -> ty::Region<'tcx> { 1,755 ( 0.00%) self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe) 346 ( 0.00%) } . 111,000 ( 0.00%) pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> { 60,871 ( 0.00%) match param.kind { . GenericParamDefKind::Lifetime => { . // Create a region inference variable for the given . // region parameter definition. 4,252 ( 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)`. 37,968 ( 0.00%) let ty_var_id = self.inner.borrow_mut().type_variables().new_var( . self.universe(), 47,460 ( 0.00%) TypeVariableOrigin { . kind: TypeVariableOriginKind::TypeParameterDefinition( 9,492 ( 0.00%) param.name, 9,492 ( 0.00%) Some(param.def_id), . ), . span, . }, . ); . 9,492 ( 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 = 1,441 ( 0.00%) self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue { . origin, . val: ConstVariableValue::Unknown { universe: self.universe() }, . }); 131 ( 0.00%) self.tcx.mk_const_var(const_var_id, self.tcx.type_of(param.def_id)).into() . } . } 1,048 ( 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. 23,064 ( 0.00%) pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> { 102,023 ( 0.00%) InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param)) 15,376 ( 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). 398 ( 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() . ); . 12,115 ( 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() 597 ( 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`. 12,509 ( 0.00%) pub fn resolve_regions( . &self, . region_context: DefId, . outlives_env: &OutlivesEnvironment<'tcx>, . mode: RegionckMode, . ) -> Vec> { 33,953 ( 0.00%) let (var_infos, data) = { . let mut inner = self.inner.borrow_mut(); . let inner = &mut *inner; 1,787 ( 0.00%) assert!( 5,361 ( 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() 1,787 ( 0.00%) }; . . let region_rels = 1,787 ( 0.00%) &RegionRelations::new(self.tcx, region_context, outlives_env.free_region_map()); . 16,083 ( 0.00%) let (lexical_region_resolutions, errors) = 42,888 ( 0.00%) lexical_region_resolve::resolve(region_rels, var_infos, data, mode); . 7,148 ( 0.00%) let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions)); 1,787 ( 0.00%) assert!(old_value.is_none()); . . errors 16,083 ( 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`. 17,870 ( 0.00%) pub fn resolve_regions_and_report_errors( . &self, . region_context: DefId, . outlives_env: &OutlivesEnvironment<'tcx>, . mode: RegionckMode, . ) { 3,574 ( 0.00%) let errors = self.resolve_regions(region_context, outlives_env, mode); . 5,361 ( 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. 3,574 ( 0.00%) self.report_region_errors(&errors); . } 8,935 ( 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(); 3,256 ( 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. 550 ( 0.00%) pub fn take_region_var_origins(&self) -> VarInfos { . let mut inner = self.inner.borrow_mut(); 2,090 ( 0.00%) let (var_infos, data) = inner . .region_constraint_storage . .take() . .expect("regions already resolved") . .with_log(&mut inner.undo_log) 110 ( 0.00%) .into_infos_and_data(); 110 ( 0.00%) assert!(data.is_empty()); . var_infos 880 ( 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)`. 18,818 ( 0.00%) pub fn probe_ty_var(&self, vid: TyVid) -> Result, ty::UniverseIndex> { . use self::type_variable::TypeVariableValue; . 56,454 ( 0.00%) match self.inner.borrow_mut().type_variables().probe(vid) { . TypeVariableValue::Known { value } => Ok(value), . TypeVariableValue::Unknown { universe } => Err(universe), . } 65,863 ( 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>, . { 145,466 ( 0.00%) value.fold_with(&mut ShallowResolver { infcx: self }) . } . 7,146 ( 0.00%) pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid { . self.inner.borrow_mut().type_variables().root_var(var) 10,719 ( 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,572 ( 0.00%) pub fn resolve_vars_if_possible(&self, value: T) -> T . where . T: TypeFoldable<'tcx>, . { 133,325 ( 0.00%) if !value.needs_infer() { 184,965 ( 0.00%) return value; // Avoid duplicated subst-folding. . } 137,805 ( 0.00%) let mut r = resolve::OpportunisticVarResolver::new(self); 174,617 ( 0.00%) value.fold_with(&mut r) 1,965 ( 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) . } . 28,431 ( 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 = 32,760 ( 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 }, . ) . }; 126,138 ( 0.00%) self.tcx.replace_bound_vars(value, fld_r, fld_t, fld_c) 18,954 ( 0.00%) } . . /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method. 72 ( 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); . 27 ( 0.00%) self.inner . .borrow_mut() . .unwrap_region_constraints() 153 ( 0.00%) .verify_generic_bound(origin, kind, a, bound); 63 ( 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. 132 ( 0.00%) pub fn closure_kind(&self, closure_substs: SubstsRef<'tcx>) -> Option { 264 ( 0.00%) let closure_kind_ty = closure_substs.as_closure().kind_ty(); . let closure_kind_ty = self.shallow_resolve(closure_kind_ty); 198 ( 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 { 218,178 ( 0.01%) self.universe.get() 92,679 ( 0.00%) } . . /// Creates and return a fresh universe that extends all previous . /// universes. Updates `self.universe` to that new universe. 112 ( 0.00%) pub fn create_next_universe(&self) -> ty::UniverseIndex { 196 ( 0.00%) let u = self.universe.get().next_universe(); . self.universe.set(u); . u 112 ( 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`. 1,592,888 ( 0.04%) fn shallow_resolve_ty(&self, typ: Ty<'tcx>) -> Ty<'tcx> { 848,864 ( 0.02%) 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`. 465,100 ( 0.01%) let known = self.inner.borrow_mut().type_variables().probe(v).known(); . known.map_or(typ, |t| self.shallow_resolve_ty(t)) . } . 10,452 ( 0.00%) ty::Infer(ty::IntVar(v)) => self . .inner . .borrow_mut() . .int_unification_table() . .probe_value(v) 2,685 ( 0.00%) .map(|v| v.to_type(self.tcx)) . .unwrap_or(typ), . 144 ( 0.00%) ty::Infer(ty::FloatVar(v)) => self . .inner . .borrow_mut() . .float_unification_table() . .probe_value(v) 52 ( 0.00%) .map(|v| v.to_type(self.tcx)) . .unwrap_or(typ), . . _ => typ, . } 1,791,999 ( 0.04%) } . . /// `ty_or_const_infer_var_changed` is equivalent to one of these two: . /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`) . /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`) . /// . /// However, `ty_or_const_infer_var_changed` is more efficient. It's always . /// inlined, despite being large, because it has only two call sites that . /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on` -- line 1659 ---------------------------------------- -- line 1662 ---------------------------------------- . #[inline(always)] . pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar<'tcx>) -> bool { . match infer_var { . TyOrConstInferVar::Ty(v) => { . use self::type_variable::TypeVariableValue; . . // If `inlined_probe` returns a `Known` value, it never equals . // `ty::Infer(ty::TyVar(v))`. 661,789 ( 0.02%) 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(_)`. 8,452 ( 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`). 6,684 ( 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, . } 6,684 ( 0.00%) } . . /// Tries to extract an inference variable from a type, returns `None` . /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`). 148 ( 0.00%) pub fn maybe_from_ty(ty: Ty<'tcx>) -> Option { 61,232 ( 0.00%) match *ty.kind() { 13,448 ( 0.00%) ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)), 200 ( 0.00%) ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)), . ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)), . _ => None, . } 148 ( 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> { 300,227 ( 0.01%) self.infcx.shallow_resolve_ty(ty) . } . 1,380 ( 0.00%) fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> { 1,134 ( 0.00%) if let ty::Const { val: ty::ConstKind::Infer(InferConst::Var(vid)), .. } = ct { 1,110 ( 0.00%) self.infcx . .inner . .borrow_mut() . .const_unification_table() 666 ( 0.00%) .probe_value(*vid) . .val . .known() . .unwrap_or(ct) . } else { . ct . } 1,725 ( 0.00%) } . } . . impl<'tcx> TypeTrace<'tcx> { . pub fn span(&self) -> Span { 8 ( 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 { 20 ( 0.00%) match *self { 4 ( 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, . { 8,957 ( 0.00%) match *cause.code() { 1,000 ( 0.00%) traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => { 5,000 ( 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 ---------------------------------------- 1,630,502 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe/transcribe.rs -------------------------------------------------------------------------------- Ir -- line 16 ---------------------------------------- . use std::mem; . . // A Marker adds the given mark to the syntax context. . struct Marker(LocalExpnId, Transparency); . . impl MutVisitor for Marker { . const VISIT_TOKENS: bool = true; . 334,674 ( 0.01%) fn visit_span(&mut self, span: &mut Span) { 223,116 ( 0.01%) *span = span.apply_mark(self.0.to_expn_id(), self.1) 297,488 ( 0.01%) } . } . . /// An iterator over the token trees in a delimited token tree (`{ ... }`) or a sequence (`$(...)`). . enum Frame { . Delimited { forest: Lrc, idx: usize, span: DelimSpan }, . Sequence { forest: Lrc, idx: usize, sep: Option }, . } . . impl Frame { . /// Construct a new frame around the delimited set of tokens. . fn new(tts: Vec) -> Frame { . let forest = Lrc::new(mbe::Delimited { delim: token::NoDelim, tts }); 7,424 ( 0.00%) Frame::Delimited { forest, idx: 0, span: DelimSpan::dummy() } . } . } . . impl Iterator for Frame { . type Item = mbe::TokenTree; . . fn next(&mut self) -> Option { 797,840 ( 0.02%) match *self { 78,274 ( 0.00%) Frame::Delimited { ref forest, ref mut idx, .. } => { 117,411 ( 0.00%) *idx += 1; . forest.tts.get(*idx - 1).cloned() . } 480,969 ( 0.01%) Frame::Sequence { ref forest, ref mut idx, .. } => { 480,969 ( 0.01%) *idx += 1; . forest.tts.get(*idx - 1).cloned() . } . } . } . } . . /// This can do Macro-By-Example transcription. . /// - `interp` is a map of meta-variables to the tokens (non-terminals) they matched in the -- line 61 ---------------------------------------- -- line 72 ---------------------------------------- . /// foo!(bar); . /// ``` . /// . /// `interp` would contain `$id => bar` and `src` would contain `println!("{}", stringify!($id));`. . /// . /// `transcribe` would return a `TokenStream` containing `println!("{}", stringify!(bar));`. . /// . /// Along the way, we do some additional error checking. 9,280 ( 0.00%) pub(super) fn transcribe<'a>( . cx: &ExtCtxt<'a>, . interp: &FxHashMap, . src: Vec, . transparency: Transparency, . ) -> PResult<'a, TokenStream> { . // Nothing for us to transcribe... 928 ( 0.00%) if src.is_empty() { . return Ok(TokenStream::default()); . } . . // We descend into the RHS (`src`), expanding things as we go. This stack contains the things . // we have yet to expand/are still expanding. We start the stack off with the whole RHS. 7,424 ( 0.00%) let mut stack: SmallVec<[Frame; 1]> = smallvec![Frame::new(src)]; . . // As we descend in the RHS, we will need to be able to match nested sequences of matchers. . // `repeats` keeps track of where we are in matching at each level, with the last element being . // the most deeply nested sequence. This is used as a stack. . let mut repeats = Vec::new(); . . // `result` contains resulting token stream from the TokenTree we just finished processing. At . // the end, this will contain the full result of transcription, but at arbitrary points during -- line 101 ---------------------------------------- -- line 105 ---------------------------------------- . // `result_stack` and clear `results`. We will then produce the results of transcribing the . // TokenTree into `results`. Then, as we unwind back out of the `TokenTree`, we will pop the . // `result_stack` and append `results` too it to produce the new `results` up to that point. . // . // Thus, if we try to pop the `result_stack` and it is empty, we have reached the top-level . // again, and we are done transcribing. . let mut result: Vec = Vec::new(); . let mut result_stack = Vec::new(); 3,712 ( 0.00%) let mut marker = Marker(cx.current_expansion.id, transparency); . . loop { . // Look at the last frame on the stack. . // If it still has a TokenTree we have not looked at yet, use that tree. 909,727 ( 0.02%) let Some(tree) = stack.last_mut().unwrap().next() else { . // This else-case never produces a value for `tree` (it `continue`s or `return`s). . . // Otherwise, if we have just reached the end of a sequence and we can keep repeating, . // go back to the beginning of the sequence. 344,812 ( 0.01%) if let Frame::Sequence { idx, sep, .. } = stack.last_mut().unwrap() { . let (repeat_idx, repeat_len) = repeats.last_mut().unwrap(); 319,500 ( 0.01%) *repeat_idx += 1; 79,875 ( 0.00%) if repeat_idx < repeat_len { 78,462 ( 0.00%) *idx = 0; 156,924 ( 0.00%) if let Some(sep) = sep { 343 ( 0.00%) result.push(TokenTree::Token(sep.clone()).into()); . } . continue; . } . } . . // We are done with the top of the stack. Pop it. Depending on what it was, we do . // different things. Note that the outermost item must be the delimited, wrapped RHS . // that was passed in originally to `transcribe`. 15,482 ( 0.00%) match stack.pop().unwrap() { . // Done with a sequence. Pop from repeats. . Frame::Sequence { .. } => { . repeats.pop(); . } . . // We are done processing a Delimited. If this is the top-level delimited, we are . // done. Otherwise, we unwind the result_stack to append what we have produced to . // any previous results. 25,312 ( 0.00%) Frame::Delimited { forest, span, .. } => { 6,328 ( 0.00%) if result_stack.is_empty() { . // No results left to compute! We are back at the top-level. 5,568 ( 0.00%) return Ok(TokenStream::new(result)); . } . . // Step back into the parent Delimited. 70,200 ( 0.00%) let tree = TokenTree::Delimited(span, forest.delim, TokenStream::new(result)); 16,200 ( 0.00%) result = result_stack.pop().unwrap(); . result.push(tree.into()); . } 12,656 ( 0.00%) } . continue; . }; . . // At this point, we know we are in the middle of a TokenTree (the last one on `stack`). . // `tree` contains the next `TokenTree` to be processed. 679,542 ( 0.02%) match tree { . // We are descending into a sequence. We first make sure that the matchers in the RHS . // and the matches in `interp` have the same shape. Otherwise, either the caller or the . // macro writer has made a mistake. 6,916 ( 0.00%) seq @ mbe::TokenTree::Sequence(..) => { 12,103 ( 0.00%) match lockstep_iter_size(&seq, interp, &repeats) { . LockstepIterSize::Unconstrained => { . return Err(cx.struct_span_err( . seq.span(), /* blame macro writer */ . "attempted to repeat an expression containing no syntax variables \ . matched as repeating at this depth", . )); . } . -- line 177 ---------------------------------------- -- line 181 ---------------------------------------- . // sequence, but they come from different sequence matchers and repeat . // different amounts. . return Err(cx.struct_span_err(seq.span(), &msg)); . } . . LockstepIterSize::Constraint(len, _) => { . // We do this to avoid an extra clone above. We know that this is a . // sequence already. 12,103 ( 0.00%) let mbe::TokenTree::Sequence(sp, seq) = seq else { . unreachable!() . }; . . // Is the repetition empty? 3,458 ( 0.00%) if len == 0 { 316 ( 0.00%) if seq.kleene.op == mbe::KleeneOp::OneOrMore { . // FIXME: this really ought to be caught at macro definition . // time... It happens when the Kleene operator in the matcher and . // the body for the same meta-variable do not match. . return Err(cx.struct_span_err( . sp.entire(), . "this must repeat at least once", . )); . } -- line 203 ---------------------------------------- -- line 204 ---------------------------------------- . } else { . // 0 is the initial counter (we have done 0 repretitions so far). `len` . // is the total number of repetitions we should generate. . repeats.push((0, len)); . . // The first time we encounter the sequence we push it to the stack. It . // then gets reused (see the beginning of the loop) until we are done . // repeating. 12,717 ( 0.00%) stack.push(Frame::Sequence { . idx: 0, . sep: seq.separator.clone(), . forest: seq, . }); . } . } . } . } . . // Replace the meta-var with the matched token tree from the invocation. 482,826 ( 0.01%) mbe::TokenTree::MetaVar(mut sp, mut orignal_ident) => { . // Find the matched nonterminal from the macro invocation, and use it to replace . // the meta-var. 321,884 ( 0.01%) let ident = MacroRulesNormalizedIdent::new(orignal_ident); 482,826 ( 0.01%) if let Some(cur_matched) = lookup_cur_matched(ident, interp, &repeats) { 241,413 ( 0.01%) if let MatchedNonterminal(nt) = cur_matched { 241,413 ( 0.01%) let token = if let NtTT(tt) = &**nt { . // `tt`s are emitted into the output stream directly as "raw tokens", . // without wrapping them into groups. . tt.clone() . } else { . // Other variables are emitted into the output stream as groups with . // `Delimiter::None` to maintain parsing priorities. . // `Interpolated` is currenty used for such groups in rustc parser. 2,187 ( 0.00%) marker.visit_span(&mut sp); 4,374 ( 0.00%) TokenTree::token(token::Interpolated(nt.clone()), sp) . }; . result.push(token.into()); . } else { . // We were unable to descend far enough. This is an error. . return Err(cx.struct_span_err( . sp, /* blame the macro writer */ . &format!("variable '{}' is still repeating at this depth", ident), . )); -- line 246 ---------------------------------------- -- line 255 ---------------------------------------- . } . } . . // If we are entering a new delimiter, we push its contents to the `stack` to be . // processed, and we push all of the currently produced results to the `result_stack`. . // We will produce all of the results of the inside of the `Delimited` and then we will . // jump back out of the Delimited, pop the result_stack and add the new results back to . // the previous results (from outside the Delimited). 32,400 ( 0.00%) mbe::TokenTree::Delimited(mut span, delimited) => { . mut_visit::visit_delim_span(&mut span, &mut marker); 32,400 ( 0.00%) stack.push(Frame::Delimited { forest: delimited, idx: 0, span }); . result_stack.push(mem::take(&mut result)); . } . . // Nothing much to do here. Just push the token to the result, being careful to . // preserve syntax context. . mbe::TokenTree::Token(token) => { 153,942 ( 0.00%) let mut tt = TokenTree::Token(token); 76,971 ( 0.00%) mut_visit::visit_tt(&mut tt, &mut marker); . result.push(tt.into()); . } . . // There should be no meta-var declarations in the invocation of a macro. . mbe::TokenTree::MetaVarDecl(..) => panic!("unexpected `TokenTree::MetaVarDecl"), . } . } 11,136 ( 0.00%) } . . /// Lookup the meta-var named `ident` and return the matched token tree from the invocation using . /// the set of matches `interpolations`. . /// . /// See the definition of `repeats` in the `transcribe` function. `repeats` is used to descend . /// into the right place in nested matchers. If we attempt to descend too far, the macro writer has . /// made a mistake, and we return `None`. 740,439 ( 0.02%) fn lookup_cur_matched<'a>( . ident: MacroRulesNormalizedIdent, . interpolations: &'a FxHashMap, . repeats: &[(usize, usize)], . ) -> Option<&'a NamedMatch> { . interpolations.get(&ident).map(|matched| { . let mut matched = matched; . for &(idx, _) in repeats { 480,324 ( 0.01%) match matched { . MatchedNonterminal(_) => break, 80,054 ( 0.00%) MatchedSeq(ref ads) => matched = ads.get(idx).unwrap(), . } . } . . matched . }) 740,439 ( 0.02%) } . . /// An accumulator over a TokenTree to be used with `fold`. During transcription, we need to make . /// sure that the size of each sequence and all of its nested sequences are the same as the sizes . /// of all the matched (nested) sequences in the macro invocation. If they don't match, somebody . /// has made a mistake (either the macro writer or caller). . #[derive(Clone)] . enum LockstepIterSize { . /// No constraints on length of matcher. This is true for any TokenTree variants except a -- line 313 ---------------------------------------- -- line 322 ---------------------------------------- . Contradiction(String), . } . . impl LockstepIterSize { . /// Find incompatibilities in matcher/invocation sizes. . /// - `Unconstrained` is compatible with everything. . /// - `Contradiction` is incompatible with everything. . /// - `Constraint(len)` is only compatible with other constraints of the same length. 20,691 ( 0.00%) fn with(self, other: LockstepIterSize) -> LockstepIterSize { 7,205 ( 0.00%) match self { . LockstepIterSize::Unconstrained => other, . LockstepIterSize::Contradiction(_) => self, 1,220 ( 0.00%) LockstepIterSize::Constraint(l_len, ref l_id) => match other { . LockstepIterSize::Unconstrained => self, . LockstepIterSize::Contradiction(_) => other, 213 ( 0.00%) LockstepIterSize::Constraint(r_len, _) if l_len == r_len => self, . LockstepIterSize::Constraint(r_len, r_id) => { . let msg = format!( . "meta-variable `{}` repeats {} time{}, but `{}` repeats {} time{}", . l_id, . l_len, . pluralize!(l_len), . r_id, . r_len, . pluralize!(r_len), . ); . LockstepIterSize::Contradiction(msg) . } . }, . } 16,401 ( 0.00%) } . } . . /// Given a `tree`, make sure that all sequences have the same length as the matches for the . /// appropriate meta-vars in `interpolations`. . /// . /// Note that if `repeats` does not match the exact correct depth of a meta-var, . /// `lookup_cur_matched` will return `None`, which is why this still works even in the presence of . /// multiple nested matcher sequences. 40,280 ( 0.00%) fn lockstep_iter_size( . tree: &mbe::TokenTree, . interpolations: &FxHashMap, . repeats: &[(usize, usize)], . ) -> LockstepIterSize { . use mbe::TokenTree; 28,196 ( 0.00%) match *tree { . TokenTree::Delimited(_, ref delimed) => { 141 ( 0.00%) delimed.tts.iter().fold(LockstepIterSize::Unconstrained, |size, tt| { 4,019 ( 0.00%) size.with(lockstep_iter_size(tt, interpolations, repeats)) . }) . } . TokenTree::Sequence(_, ref seq) => { 1,749 ( 0.00%) seq.tts.iter().fold(LockstepIterSize::Unconstrained, |size, tt| { 35,278 ( 0.00%) size.with(lockstep_iter_size(tt, interpolations, repeats)) . }) . } . TokenTree::MetaVar(_, name) | TokenTree::MetaVarDecl(_, name, _) => { 3,600 ( 0.00%) let name = MacroRulesNormalizedIdent::new(name); 16,200 ( 0.00%) match lookup_cur_matched(name, interpolations, repeats) { 3,600 ( 0.00%) Some(matched) => match matched { . MatchedNonterminal(_) => LockstepIterSize::Unconstrained, 10,800 ( 0.00%) MatchedSeq(ref ads) => LockstepIterSize::Constraint(ads.len(), name), . }, . _ => LockstepIterSize::Unconstrained, . } . } . TokenTree::Token(..) => LockstepIterSize::Unconstrained, . } 32,224 ( 0.00%) } 2,252,496 ( 0.06%) -------------------------------------------------------------------------------- The following files chosen for auto-annotation could not be found: -------------------------------------------------------------------------------- ./elf/../sysdeps/x86_64/dl-machine.h ./elf/dl-lookup.c ./malloc/malloc.c ./stdlib/canonicalize.c ./string/../sysdeps/x86_64/multiarch/memcmp-avx2-movbe.S ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S -------------------------------------------------------------------------------- Ir -------------------------------------------------------------------------------- 2,311,411,337 (57.37%) events annotated