-------------------------------------------------------------------------------- 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 async_std --edition=2018 src/lib.rs --error-format=json --json=diagnostic-rendered-ansi,artifacts,future-incompat --crate-type lib --emit=dep-info,metadata -C embed-bitcode=no -C debuginfo=2 --cfg feature="alloc" --cfg feature="async-channel" --cfg feature="async-global-executor" --cfg feature="async-io" --cfg feature="async-lock" --cfg feature="crossbeam-utils" --cfg feature="default" --cfg feature="futures-channel" --cfg feature="futures-core" --cfg feature="futures-io" --cfg feature="futures-lite" --cfg feature="gloo-timers" --cfg feature="kv-log-macro" --cfg feature="log" --cfg feature="memchr" --cfg feature="num_cpus" --cfg feature="once_cell" --cfg feature="pin-project-lite" --cfg feature="pin-utils" --cfg feature="slab" --cfg feature="std" --cfg feature="wasm-bindgen-futures" -C metadata=bcba600717a7d0fd -C extra-filename=-bcba600717a7d0fd --out-dir /usr/home/liquid/tmp/.tmpxZYYdH/target/debug/deps -L dependency=/usr/home/liquid/tmp/.tmpxZYYdH/target/debug/deps --extern async_channel=/usr/home/liquid/tmp/.tmpxZYYdH/target/debug/deps/libasync_channel-f212cf7a7da065f5.rmeta --extern async_global_executor=/usr/home/liquid/tmp/.tmpxZYYdH/target/debug/deps/libasync_global_executor-fc2dd3b1126ed812.rmeta --extern async_io=/usr/home/liquid/tmp/.tmpxZYYdH/target/debug/deps/libasync_io-91a82f0593c01483.rmeta --extern async_lock=/usr/home/liquid/tmp/.tmpxZYYdH/target/debug/deps/libasync_lock-a98377858f35939f.rmeta --extern crossbeam_utils=/usr/home/liquid/tmp/.tmpxZYYdH/target/debug/deps/libcrossbeam_utils-161632d0d3aded87.rmeta --extern futures_core=/usr/home/liquid/tmp/.tmpxZYYdH/target/debug/deps/libfutures_core-3deb98774204e9fe.rmeta --extern futures_io=/usr/home/liquid/tmp/.tmpxZYYdH/target/debug/deps/libfutures_io-90db538fb3843962.rmeta --extern futures_lite=/usr/home/liquid/tmp/.tmpxZYYdH/target/debug/deps/libfutures_lite-8451ad65c9379c4a.rmeta --extern kv_log_macro=/usr/home/liquid/tmp/.tmpxZYYdH/target/debug/deps/libkv_log_macro-af04f9b5fc4d3638.rmeta --extern log=/usr/home/liquid/tmp/.tmpxZYYdH/target/debug/deps/liblog-b1746310b1f65158.rmeta --extern memchr=/usr/home/liquid/tmp/.tmpxZYYdH/target/debug/deps/libmemchr-aedb334f67854ac5.rmeta --extern num_cpus=/usr/home/liquid/tmp/.tmpxZYYdH/target/debug/deps/libnum_cpus-e758aaa0a8ea1231.rmeta --extern once_cell=/usr/home/liquid/tmp/.tmpxZYYdH/target/debug/deps/libonce_cell-48aa91c5d5c765a6.rmeta --extern pin_project_lite=/usr/home/liquid/tmp/.tmpxZYYdH/target/debug/deps/libpin_project_lite-59182566af91ca39.rmeta --extern pin_utils=/usr/home/liquid/tmp/.tmpxZYYdH/target/debug/deps/libpin_utils-3d8c7d312473ec07.rmeta --extern slab=/usr/home/liquid/tmp/.tmpxZYYdH/target/debug/deps/libslab-2f0ac9014ffeabfc.rmeta -Adeprecated -Aunknown-lints -Zincremental-verify-ich Data file: results/cgout-w-profiling-async-std-1.10.0-Check-Full Events recorded: Ir Events shown: Ir Event sort order: Ir Thresholds: 0.1 Include dirs: User annotated: Auto-annotation: on -------------------------------------------------------------------------------- Ir -------------------------------------------------------------------------------- 24,102,427,199 (100.0%) PROGRAM TOTALS -------------------------------------------------------------------------------- Ir file:function -------------------------------------------------------------------------------- 1,607,566,197 ( 6.67%) ./malloc/malloc.c:_int_free 1,444,259,798 ( 5.99%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe/macro_parser.rs:rustc_expand::mbe::macro_parser::parse_tt 1,225,520,922 ( 5.08%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs:rustc_expand::mbe::macro_parser::parse_tt 1,107,960,065 ( 4.60%) ./malloc/malloc.c:_int_malloc 1,106,970,338 ( 4.59%) ./malloc/malloc.c:malloc 916,101,598 ( 3.80%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::bump 892,567,722 ( 3.70%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::next 629,343,472 ( 2.61%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/tokenstream.rs:::next_with_spacing 548,207,020 ( 2.27%) ./malloc/malloc.c:free 416,538,325 ( 1.73%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::bump_with 370,096,966 ( 1.54%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe/macro_parser.rs:::clone 339,224,797 ( 1.41%) ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:__memcpy_avx_unaligned_erms 324,005,774 ( 1.34%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::clone 302,559,852 ( 1.26%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe.rs:::get_tt 292,525,437 ( 1.21%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::next_desugared 278,508,333 ( 1.16%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:rustc_expand::mbe::macro_parser::parse_tt 266,584,528 ( 1.11%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:>::truncate 265,454,527 ( 1.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe/transcribe.rs:rustc_expand::mbe::transcribe::transcribe 250,238,876 ( 1.04%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs: as core::iter::traits::collect::Extend>::extend::>> 241,380,939 ( 1.00%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/nonterminal.rs:::parse_nonterminal 236,705,152 ( 0.98%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs:>>::make_mut 229,310,753 ( 0.95%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:core::ptr::drop_in_place:: 218,527,468 ( 0.91%) ./malloc/malloc.c:malloc_consolidate 216,236,496 ( 0.90%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs: as core::iter::traits::collect::Extend>::extend::>> 214,659,014 ( 0.89%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::parse_token_tree 205,126,132 ( 0.85%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe.rs:rustc_expand::mbe::macro_parser::parse_tt 166,456,052 ( 0.69%) /usr/home/liquid/rust/worktree-benchmarking/library/std/src/sys/unix/alloc.rs:__rdl_alloc 166,210,924 ( 0.69%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs: as core::ops::drop::Drop>::drop 161,595,636 ( 0.67%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::eq 159,989,334 ( 0.66%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs:>::try_reserve 159,932,273 ( 0.66%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::ident 156,306,828 ( 0.65%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs:>::try_reserve 149,953,797 ( 0.62%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:::bump_with 142,048,138 ( 0.59%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs:core::ptr::drop_in_place:: 141,293,167 ( 0.59%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::lifetime 129,063,826 ( 0.54%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe.rs:::clone 123,869,243 ( 0.51%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs: as core::ops::drop::Drop>::drop 116,459,210 ( 0.48%) ./malloc/malloc.c:unlink_chunk.constprop.0 112,784,070 ( 0.47%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs: as core::ops::drop::Drop>::drop 104,552,678 ( 0.43%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs: as core::ops::drop::Drop>::drop 100,079,815 ( 0.42%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:::bump_with 99,976,044 ( 0.41%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/span_encoding.rs:::bump 92,709,687 ( 0.38%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs: as core::ops::drop::Drop>::drop 88,827,639 ( 0.37%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs:rustc_expand::mbe::macro_parser::parse_tt 86,700,897 ( 0.36%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs: as core::iter::traits::collect::Extend>::extend::>> 86,121,827 ( 0.36%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/nonterminal.rs:::nonterminal_may_begin_with 86,072,828 ( 0.36%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs:>]> as core::clone::Clone>::clone 85,592,384 ( 0.36%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::clone 80,647,155 ( 0.33%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/boxed.rs:>]> as core::clone::Clone>::clone 80,532,367 ( 0.33%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:core::ptr::drop_in_place:: 75,796,437 ( 0.31%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe/macro_parser.rs:::clone 75,401,786 ( 0.31%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/span_encoding.rs:::normalize_to_macro_rules 75,307,575 ( 0.31%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/iter/adapters/take.rs:>]> as core::clone::Clone>::clone 71,880,434 ( 0.30%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe/transcribe.rs:rustc_expand::mbe::transcribe::lookup_cur_matched 70,259,839 ( 0.29%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:>>::make_mut 69,918,799 ( 0.29%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:>]> as core::clone::Clone>::clone 69,133,460 ( 0.29%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:rustc_expand::mbe::transcribe::lookup_cur_matched 68,035,067 ( 0.28%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/alloc.rs:rustc_expand::mbe::macro_parser::parse_tt 67,966,060 ( 0.28%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs:> as core::ops::drop::Drop>::drop 67,945,283 ( 0.28%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:core::ptr::drop_in_place::> 66,646,132 ( 0.28%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/mem/mod.rs:::bump_with 62,060,597 ( 0.26%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs:rustc_expand::mbe::transcribe::transcribe 60,901,449 ( 0.25%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/symbol.rs:::normalize_to_macro_rules 55,807,134 ( 0.23%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/option.rs:rustc_expand::mbe::transcribe::transcribe 54,071,002 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs: as core::iter::traits::collect::Extend>::extend::>> 53,776,838 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/option.rs:::clone 53,710,204 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/index.rs:::get_tt 50,194,180 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs: as core::ops::drop::Drop>::drop 49,189,171 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/convert/mod.rs:rustc_expand::mbe::transcribe::transcribe 49,022,772 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs: as core::ops::drop::Drop>::drop 47,796,225 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/symbol.rs:::eq 47,558,872 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/library/std/src/alloc.rs:__rdl_alloc 44,738,998 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/borrow.rs:rustc_expand::mbe::macro_parser::parse_tt 44,540,546 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs:core::ptr::drop_in_place::> 43,036,414 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/mem/maybe_uninit.rs:>]> as core::clone::Clone>::clone 43,011,816 ( 0.18%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs:::clone 41,363,226 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/span_encoding.rs:::eq 41,003,707 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs: as core::ops::drop::Drop>::drop 39,592,032 ( 0.16%) /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 39,143,492 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/option.rs:rustc_expand::mbe::macro_parser::parse_tt 37,832,221 ( 0.16%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs:>>::make_mut 37,635,339 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/alloc.rs:>]> as core::clone::Clone>::clone 37,635,339 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:>]> as core::clone::Clone>::clone 37,544,249 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/ast_like.rs:::tokens_mut 37,446,942 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/span_encoding.rs:rustc_expand::mbe::transcribe::lookup_cur_matched 36,525,128 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:::next 34,999,104 ( 0.15%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/scoped-tls-1.0.0/src/lib.rs:>::with::<::with::normalize_to_macro_rules::{closure#0}>::{closure#0}, rustc_span::hygiene::SyntaxContext> 34,987,331 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/alloc.rs:core::ptr::drop_in_place:: 34,181,730 ( 0.14%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, (), core::hash::BuildHasherDefault>>::from_hash::>::{closure#0}> 32,207,428 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/iter/range.rs:rustc_expand::mbe::macro_parser::parse_tt 31,167,712 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/clone.rs:::clone 31,051,451 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/convert/mod.rs:::next 30,501,266 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe.rs:::clone 30,480,584 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe/macro_parser.rs: as core::iter::traits::collect::Extend>::extend::>> 30,116,197 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/boxed.rs:::clone 30,116,197 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/alloc.rs:::clone 29,904,345 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:rustc_expand::mbe::transcribe::transcribe 29,880,500 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/alloc.rs:core::ptr::drop_in_place::> 29,648,515 ( 0.12%) ./malloc/malloc.c:realloc 29,562,981 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe.rs:::clone 27,506,439 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:::next 27,023,015 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/alloc.rs:>>::make_mut 25,261,187 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:> as core::ops::drop::Drop>::drop -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs -------------------------------------------------------------------------------- Ir -- line 293 ---------------------------------------- . . #[allow(deprecated)] . impl From for CollectionAllocErr { . fn from(_: LayoutErr) -> Self { . CollectionAllocErr::CapacityOverflow . } . } . 2 ( 0.00%) fn infallible(result: Result) -> T { 22,329,369 ( 0.09%) match result { . Ok(x) => x, . Err(CollectionAllocErr::CapacityOverflow) => panic!("capacity overflow"), . Err(CollectionAllocErr::AllocErr { layout }) => alloc::alloc::handle_alloc_error(layout), . } 4 ( 0.00%) } . . /// FIXME: use `Layout::array` when we require a Rust version where it’s stable . /// https://github.com/rust-lang/rust/issues/55724 . fn layout_array(n: usize) -> Result { . let size = mem::size_of::() . .checked_mul(n) . .ok_or(CollectionAllocErr::CapacityOverflow)?; . let align = mem::align_of::(); -- line 315 ---------------------------------------- -- 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 { 181,060 ( 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) { 8,615,332 ( 0.04%) 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::() . ); 33,315,657 ( 0.14%) 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 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(), 17,199 ( 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(); 380,824 ( 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 { 20 ( 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 { 16,591,694 ( 0.07%) 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 { 49,935,375 ( 0.21%) 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 { 694,833,828 ( 2.88%) if self.spilled() { 20,287 ( 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 { 354,900,235 ( 1.47%) 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] 232,150 ( 0.00%) pub fn push(&mut self, value: A::Item) { . unsafe { . let (mut ptr, mut len, cap) = self.triple_mut(); 108,102,361 ( 0.45%) if *len == cap { 2,185 ( 0.00%) self.reserve(1); 93,901 ( 0.00%) let &mut (heap_ptr, ref mut heap_len) = self.data.heap_mut(); . ptr = heap_ptr; . len = heap_len; . } 171,940 ( 0.00%) ptr::write(ptr.add(*len), value); 130,624,137 ( 0.54%) *len += 1; . } 185,720 ( 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(); 58,115,845 ( 0.24%) if *len_ptr == 0 { 1 ( 0.00%) return None; . } 16,501,736 ( 0.07%) let last_index = *len_ptr - 1; 21,864,135 ( 0.09%) *len_ptr = last_index; 151,058 ( 0.00%) Some(ptr::read(ptr.add(last_index))) . } 29 ( 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 5,705 ( 0.00%) pub fn try_grow(&mut self, new_cap: usize) -> Result<(), CollectionAllocErr> { . unsafe { 327 ( 0.00%) let (ptr, &mut len, cap) = self.triple_mut(); . let unspilled = !self.spilled(); 204,694 ( 0.00%) assert!(new_cap >= len); 204,694 ( 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); 204,694 ( 0.00%) } else if new_cap != cap { 191,211 ( 0.00%) let layout = layout_array::(new_cap)?; . debug_assert!(layout.size() > 0); . let new_alloc; 102,347 ( 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`. 125,204 ( 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(); . } 204,694 ( 0.00%) self.data = SmallVecData::from_heap(new_alloc, len); 302,280 ( 0.00%) self.capacity = new_cap; . } . Ok(()) . } 6,032 ( 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] 292,369 ( 0.00%) pub fn reserve(&mut self, additional: usize) { 22,529,168 ( 0.09%) infallible(self.try_reserve(additional)) 331,352 ( 0.00%) } . . /// Reserve capacity for `additional` more elements to be inserted. . /// . /// May reserve more space to avoid frequent reallocations. 89,366,752 ( 0.37%) 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() 14,361 ( 0.00%) let (_, &mut len, cap) = self.triple_mut(); 57,078,604 ( 0.24%) 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)?; 1,127 ( 0.00%) self.try_grow(new_cap) 100,479,284 ( 0.42%) } . . /// Reserve the minimum capacity for `additional` more elements to be inserted. . /// . /// Panics if the new capacity overflows `usize`. . pub fn reserve_exact(&mut self, additional: usize) { . infallible(self.try_reserve_exact(additional)) . } . . /// Reserve the minimum capacity for `additional` more elements to be inserted. . pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), CollectionAllocErr> { . let (_, &mut len, cap) = self.triple_mut(); 166,788 ( 0.00%) if cap - len >= additional { . return Ok(()); . } . let new_cap = len . .checked_add(additional) . .ok_or(CollectionAllocErr::CapacityOverflow)?; 210 ( 0.00%) self.try_grow(new_cap) 210 ( 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(); 93,324 ( 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. 36 ( 0.00%) pub fn remove(&mut self, index: usize) -> A::Item { . unsafe { . let (mut ptr, len_ptr, _) = self.triple_mut(); 5,967 ( 0.00%) let len = *len_ptr; 20,139 ( 0.00%) assert!(index < len); 33,967 ( 0.00%) *len_ptr = len - 1; . ptr = ptr.add(index); . let item = ptr::read(ptr); 13,426 ( 0.00%) ptr::copy(ptr.add(1), ptr, len - index - 1); . item . } 45 ( 0.00%) } . . /// Insert an element at position `index`, shifting all elements after it to the right. . /// . /// Panics if `index` is out of bounds. 94,719 ( 0.00%) pub fn insert(&mut self, index: usize, element: A::Item) { . self.reserve(1); . . unsafe { . let (mut ptr, len_ptr, _) = self.triple_mut(); 142,638 ( 0.00%) let len = *len_ptr; 151,258 ( 0.00%) assert!(index <= len); 302,516 ( 0.00%) *len_ptr = len + 1; . ptr = ptr.add(index); 151,258 ( 0.00%) ptr::copy(ptr, ptr.add(1), len - index); . ptr::write(ptr, element); . } 60,278 ( 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. 223,452 ( 0.00%) pub fn retain bool>(&mut self, mut f: F) { . let mut del = 0; . let len = self.len(); . for i in 0..len { 135,924 ( 0.00%) if !f(&mut self[i]) { 168 ( 0.00%) del += 1; 39,994 ( 0.00%) } else if del > 0 { 57 ( 0.00%) self.swap(i - del, i); . } . } 49,656 ( 0.00%) self.truncate(len - del); 198,624 ( 0.00%) } . . /// Removes consecutive duplicate elements. 168 ( 0.00%) pub fn dedup(&mut self) . where . A::Item: PartialEq, . { . self.dedup_by(|a, b| a == b); 192 ( 0.00%) } . . /// Removes consecutive duplicate elements using the given equality relation. . pub fn dedup_by(&mut self, mut same_bucket: F) . where . F: FnMut(&mut A::Item, &mut A::Item) -> bool, . { . // See the implementation of Vec::dedup_by in the . // standard library for an explanation of this algorithm. . let len = self.len(); 48 ( 0.00%) if len <= 1 { . return; . } . . let ptr = self.as_mut_ptr(); . let mut w: usize = 1; . . unsafe { . for r in 1..len { . let p_r = ptr.add(r); 112 ( 0.00%) let p_wm1 = ptr.add(w - 1); . if !same_bucket(&mut *p_r, &mut *p_wm1) { 48 ( 0.00%) if r != w { . let p_w = p_wm1.add(1); . mem::swap(&mut *p_r, &mut *p_w); . } 48 ( 0.00%) w += 1; . } . } . } . . self.truncate(w); . } . . /// Removes consecutive elements that map to the same key. -- line 1262 ---------------------------------------- -- 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, . ); 4,845 ( 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`. 468,891 ( 0.00%) pub fn insert_from_slice(&mut self, index: usize, slice: &[A::Item]) { . self.reserve(slice.len()); . . let len = self.len(); 143,379 ( 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()); 95,586 ( 0.00%) self.set_len(len + slice.len()); . } 382,344 ( 0.00%) } . . /// Copy elements from a slice and append them to the vector. . /// . /// For slices of `Copy` types, this is more efficient than `extend`. . #[inline] . pub fn extend_from_slice(&mut self, slice: &[A::Item]) { . let len = self.len(); 121,369 ( 0.00%) self.insert_from_slice(len, slice); . } . } . . impl SmallVec . where . A::Item: Clone, . { . /// Resizes the vector so that its length is equal to `len`. -- line 1473 ---------------------------------------- -- line 1522 ---------------------------------------- . } . } . } . . impl ops::DerefMut for SmallVec { . #[inline] . fn deref_mut(&mut self) -> &mut [A::Item] { . unsafe { 8,690,725 ( 0.04%) let (ptr, &mut len, _) = self.triple_mut(); . slice::from_raw_parts_mut(ptr, len) . } . } . } . . impl AsRef<[A::Item]> for SmallVec { . #[inline] . fn as_ref(&self) -> &[A::Item] { -- line 1538 ---------------------------------------- -- line 1716 ---------------------------------------- . SmallVec::extend_from_slice(self, other) . } . } . . impl FromIterator for SmallVec { . #[inline] . fn from_iter>(iterable: I) -> SmallVec { . let mut v = SmallVec::new(); 17,267,940 ( 0.07%) v.extend(iterable); . v . } . } . . impl Extend for SmallVec { 111,528,151 ( 0.46%) fn extend>(&mut self, iterable: I) { 931,923 ( 0.00%) let mut iter = iterable.into_iter(); 16 ( 0.00%) let (lower_size_bound, _) = iter.size_hint(); 64,571 ( 0.00%) self.reserve(lower_size_bound); . . unsafe { . let (ptr, len_ptr, cap) = self.triple_mut(); . let mut len = SetLenOnDrop::new(len_ptr); 38,882,475 ( 0.16%) while len.get() < cap { 6,708,125 ( 0.03%) if let Some(out) = iter.next() { 216 ( 0.00%) ptr::write(ptr.add(len.get()), out); . len.increment_len(1); . } else { . return; . } . } . } . 555,949 ( 0.00%) for elem in iter { 10,634 ( 0.00%) self.push(elem); . } 89,646,341 ( 0.37%) } . } . . 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 { 149,553,116 ( 0.62%) fn drop(&mut self) { . unsafe { 46,133,384 ( 0.19%) if self.spilled() { . let (ptr, len) = self.data.heap(); . Vec::from_raw_parts(ptr, len, self.capacity); . } else { . ptr::drop_in_place(&mut self[..]); . } . } 149,669,688 ( 0.62%) } . } . . #[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 { 19,090 ( 0.00%) fn drop(&mut self) { 139,105 ( 0.00%) for _ in self {} 19,184 ( 0.00%) } . } . . impl Iterator for IntoIter { . type Item = A::Item; . . #[inline] . fn next(&mut self) -> Option { 1,140,420 ( 0.00%) if self.current == self.end { 1,329 ( 0.00%) None . } else { . unsafe { . let current = self.current; 705,715 ( 0.00%) self.current += 1; 23,271 ( 0.00%) Some(ptr::read(self.data.as_ptr().add(current))) . } . } . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 25,895 ( 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); 65,690 ( 0.00%) IntoIter { 559,252 ( 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 { 11,223,718 ( 0.05%) local_len: *len, . len, . } . } . . #[inline] . fn get(&self) -> usize { . self.local_len . } . . #[inline] . fn increment_len(&mut self, increment: usize) { 4,196,027 ( 0.02%) self.local_len += increment; . } . } . . impl<'a> Drop for SetLenOnDrop<'a> { . #[inline] . fn drop(&mut self) { 16,691,506 ( 0.07%) *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 ---------------------------------------- 163,116,798 ( 0.68%) -------------------------------------------------------------------------------- -- 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 { 62,757 ( 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 { 15,248,744 ( 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, . } . 2,041 ( 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 } 160 ( 0.00%) } . } . . /// A Kleene-style [repetition operator](https://en.wikipedia.org/wiki/Kleene_star) . /// for token sequences. 4,474 ( 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. 176,380,863 ( 0.73%) #[derive(Debug, Clone, PartialEq, Encodable, Decodable)] . enum TokenTree { 407,561 ( 0.00%) Token(Token), 3,855,220 ( 0.02%) Delimited(DelimSpan, Lrc), . /// A kleene-style repetition sequence 37,397 ( 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. 10,744,389 ( 0.04%) MetaVarDecl(Span, Ident /* name to bind */, Option), . } . . impl TokenTree { . /// Return the number of tokens in the tree. . fn len(&self) -> usize { 103,036,865 ( 0.43%) match *self { 23,183,157 ( 0.10%) TokenTree::Delimited(_, ref delimed) => match delimed.delim { . token::NoDelim => delimed.tts.len(), 15,455,438 ( 0.06%) _ => delimed.tts.len() + 2, . }, 53,665,225 ( 0.22%) 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. 43,769,622 ( 0.18%) fn get_tt(&self, index: usize) -> TokenTree { 65,233,338 ( 0.27%) match (self, index) { 11,574,048 ( 0.05%) (&TokenTree::Delimited(_, ref delimed), _) if delimed.delim == token::NoDelim => { . delimed.tts[index].clone() . } . (&TokenTree::Delimited(span, ref delimed), _) => { 7,716,032 ( 0.03%) if index == 0 { . return delimed.open_tt(span); . } 23,024,478 ( 0.10%) if index == delimed.tts.len() + 1 { . return delimed.close_tt(span); . } 25,457 ( 0.00%) delimed.tts[index - 1].clone() . } 10,731,858 ( 0.04%) (&TokenTree::Sequence(_, ref seq), _) => seq.tts[index].clone(), . _ => panic!("Cannot expand a token tree"), . } 58,359,496 ( 0.24%) } . . /// Retrieves the `TokenTree`'s span. . fn span(&self) -> Span { 141,946 ( 0.00%) match *self { . TokenTree::Token(Token { span, .. }) . | TokenTree::MetaVar(span, _) . | TokenTree::MetaVarDecl(span, _, _) => span, 16,370 ( 0.00%) TokenTree::Delimited(span, _) | TokenTree::Sequence(span, _) => span.entire(), . } . } . . fn token(kind: TokenKind, span: Span) -> TokenTree { 6,054 ( 0.00%) TokenTree::Token(Token::new(kind, span)) . } . } 74,634,723 ( 0.31%) -------------------------------------------------------------------------------- -- 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; . 877,293 ( 0.00%) fn visit_span(&mut self, span: &mut Span) { 584,862 ( 0.00%) *span = span.apply_mark(self.0.to_expn_id(), self.1) 779,816 ( 0.00%) } . } . . /// 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 }); 31,072 ( 0.00%) Frame::Delimited { forest, idx: 0, span: DelimSpan::dummy() } . } . } . . impl Iterator for Frame { . type Item = mbe::TokenTree; . . fn next(&mut self) -> Option { 23,308,612 ( 0.10%) match *self { 208,818 ( 0.00%) Frame::Delimited { ref forest, ref mut idx, .. } => { 313,227 ( 0.00%) *idx += 1; . forest.tts.get(*idx - 1).cloned() . } 17,168,232 ( 0.07%) Frame::Sequence { ref forest, ref mut idx, .. } => { 17,168,232 ( 0.07%) *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. 40,700 ( 0.00%) pub(super) fn transcribe<'a>( . cx: &ExtCtxt<'a>, . interp: &FxHashMap, . src: Vec, . transparency: Transparency, . ) -> PResult<'a, TokenStream> { . // Nothing for us to transcribe... 4,070 ( 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. 31,072 ( 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(); 15,536 ( 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. 23,581,725 ( 0.10%) 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. 11,520,660 ( 0.05%) if let Frame::Sequence { idx, sep, .. } = stack.last_mut().unwrap() { . let (repeat_idx, repeat_len) = repeats.last_mut().unwrap(); 11,427,584 ( 0.05%) *repeat_idx += 1; 2,856,896 ( 0.01%) if repeat_idx < repeat_len { 2,847,308 ( 0.01%) *idx = 0; 5,694,616 ( 0.02%) if let Some(sep) = sep { 6,041 ( 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`. 65,714 ( 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. 93,076 ( 0.00%) Frame::Delimited { forest, span, .. } => { 23,269 ( 0.00%) if result_stack.is_empty() { . // No results left to compute! We are back at the top-level. 23,304 ( 0.00%) return Ok(TokenStream::new(result)); . } . . // Step back into the parent Delimited. 252,005 ( 0.00%) let tree = TokenTree::Delimited(span, forest.delim, TokenStream::new(result)); 58,155 ( 0.00%) result = result_stack.pop().unwrap(); . result.push(tree.into()); . } 46,538 ( 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. 17,681,928 ( 0.07%) 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. 54,256 ( 0.00%) seq @ mbe::TokenTree::Sequence(..) => { 94,948 ( 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. 94,948 ( 0.00%) let mbe::TokenTree::Sequence(sp, seq) = seq else { . unreachable!() . }; . . // Is the repetition empty? 27,128 ( 0.00%) if len == 0 { 3,976 ( 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. 86,292 ( 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. 17,187,426 ( 0.07%) mbe::TokenTree::MetaVar(mut sp, mut orignal_ident) => { . // Find the matched nonterminal from the macro invocation, and use it to replace . // the meta-var. 11,458,284 ( 0.05%) let ident = MacroRulesNormalizedIdent::new(orignal_ident); 17,187,426 ( 0.07%) if let Some(cur_matched) = lookup_cur_matched(ident, interp, &repeats) { 8,593,713 ( 0.04%) if let MatchedNonterminal(nt) = cur_matched { 8,593,713 ( 0.04%) 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. 27,717 ( 0.00%) marker.visit_span(&mut sp); 55,434 ( 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). 116,310 ( 0.00%) mbe::TokenTree::Delimited(mut span, delimited) => { . mut_visit::visit_delim_span(&mut span, &mut marker); 116,310 ( 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) => { 296,808 ( 0.00%) let mut tt = TokenTree::Token(token); 148,404 ( 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"), . } . } 48,468 ( 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`. 25,924,806 ( 0.11%) 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 { 17,168,608 ( 0.07%) match matched { . MatchedNonterminal(_) => break, 2,862,214 ( 0.01%) MatchedSeq(ref ads) => matched = ads.get(idx).unwrap(), . } . } . . matched . }) 25,924,806 ( 0.11%) } . . /// 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. 258,633 ( 0.00%) fn with(self, other: LockstepIterSize) -> LockstepIterSize { 94,149 ( 0.00%) match self { . LockstepIterSize::Unconstrained => other, . LockstepIterSize::Contradiction(_) => self, 32,397 ( 0.00%) LockstepIterSize::Constraint(l_len, ref l_id) => match other { . LockstepIterSize::Unconstrained => self, . LockstepIterSize::Contradiction(_) => other, 6,921 ( 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) . } . }, . } 209,097 ( 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. 423,010 ( 0.00%) fn lockstep_iter_size( . tree: &mbe::TokenTree, . interpolations: &FxHashMap, . repeats: &[(usize, usize)], . ) -> LockstepIterSize { . use mbe::TokenTree; 296,107 ( 0.00%) match *tree { . TokenTree::Delimited(_, ref delimed) => { 2,144 ( 0.00%) delimed.tts.iter().fold(LockstepIterSize::Unconstrained, |size, tt| { 56,714 ( 0.00%) size.with(lockstep_iter_size(tt, interpolations, repeats)) . }) . } . TokenTree::Sequence(_, ref seq) => { 16,327 ( 0.00%) seq.tts.iter().fold(LockstepIterSize::Unconstrained, |size, tt| { 409,222 ( 0.00%) size.with(lockstep_iter_size(tt, interpolations, repeats)) . }) . } . TokenTree::MetaVar(_, name) | TokenTree::MetaVarDecl(_, name, _) => { 31,926 ( 0.00%) let name = MacroRulesNormalizedIdent::new(name); 143,667 ( 0.00%) match lookup_cur_matched(name, interpolations, repeats) { 31,926 ( 0.00%) Some(matched) => match matched { . MatchedNonterminal(_) => LockstepIterSize::Unconstrained, 95,226 ( 0.00%) MatchedSeq(ref ads) => LockstepIterSize::Constraint(ads.len(), name), . }, . _ => LockstepIterSize::Unconstrained, . } . } . TokenTree::Token(..) => LockstepIterSize::Unconstrained, . } 338,408 ( 0.00%) } 66,989,500 ( 0.28%) -------------------------------------------------------------------------------- -- 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. 10,619,195 ( 0.04%) 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. 387,668 ( 0.00%) 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 78,698,094 ( 0.33%) &(*slice)[self] . } . . #[inline] . fn index_mut(self, slice: &mut [T]) -> &mut T { . // N.B., use intrinsic indexing 7,123,650 ( 0.03%) &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]> { 40,968 ( 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. 702,555 ( 0.00%) 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 { 84,666 ( 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] { 84,375 ( 0.00%) if self.start > self.end { . slice_index_order_fail(self.start, self.end); 603,007 ( 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 { &*self.get_unchecked(slice) } . } . . #[inline] . fn index_mut(self, slice: &mut [T]) -> &mut [T] { 10,550 ( 0.00%) if self.start > self.end { . slice_index_order_fail(self.start, self.end); 70,041 ( 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] { 403,271 ( 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] { 21,545 ( 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, . }; . 41,320 ( 0.00%) if start > end { . slice_index_order_fail(start, end); . } 288 ( 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 ---------------------------------------- 4,461,437 ( 0.02%) -------------------------------------------------------------------------------- -- 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"] 41,068 ( 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 { 41,017,202 ( 0.17%) *self . } . } . )* . } . } . . impl_clone! { . usize u8 u16 u32 u64 u128 -- line 192 ---------------------------------------- 3,969 ( 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 74,826 ( 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 { 470,617 ( 0.00%) let result = ptr::read(dest); 80,225,474 ( 0.33%) 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")] 123 ( 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 { 3,181 ( 0.00%) fn hash(&self, state: &mut H) { . self.0.hash(state); 5,650 ( 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 { 50,504 ( 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 ---------------------------------------- 40,595 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/symbol.rs -------------------------------------------------------------------------------- Ir -- line 15 ---------------------------------------- . use std::str; . . use crate::{with_session_globals, Edition, Span, DUMMY_SP}; . . #[cfg(test)] . mod tests; . . // The proc macro code for this is in `compiler/rustc_macros/src/symbols.rs`. 8 ( 0.00%) symbols! { . // After modifying this list adjust `is_special`, `is_used_keyword`/`is_unused_keyword`, . // this should be rarely necessary though if the keywords are kept in alphabetic order. . Keywords { . // Special reserved identifiers used internally for elided lifetimes, . // unnamed method parameters, crate root module, error recovery etc. . Empty: "", . PathRoot: "{{root}}", . DollarCrate: "$crate", -- line 31 ---------------------------------------- -- line 1498 ---------------------------------------- . write_str, . writeln_macro, . x87_reg, . xer, . xmm_reg, . ymm_reg, . zmm_reg, . } 10 ( 0.00%) } . 13,987,875 ( 0.06%) #[derive(Copy, Clone, Eq, HashStable_Generic, Encodable, Decodable)] . pub struct Ident { . pub name: Symbol, . pub span: Span, . } . . impl Ident { . #[inline] . /// Constructs a new identifier from a symbol and a span. . pub const fn new(name: Symbol, span: Span) -> Ident { . Ident { name, span } 20,845,378 ( 0.09%) } . . /// Constructs a new identifier with a dummy span. . #[inline] . pub const fn with_dummy_span(name: Symbol) -> Ident { . Ident::new(name, DUMMY_SP) . } . . #[inline] . pub fn empty() -> Ident { . Ident::with_dummy_span(kw::Empty) . } . . /// Maps a string to an identifier with a dummy span. 18 ( 0.00%) pub fn from_str(string: &str) -> Ident { 18 ( 0.00%) Ident::with_dummy_span(Symbol::intern(string)) 72 ( 0.00%) } . . /// Maps a string and a span to an identifier. 368 ( 0.00%) pub fn from_str_and_span(string: &str, span: Span) -> Ident { 184 ( 0.00%) Ident::new(Symbol::intern(string), span) 368 ( 0.00%) } . . /// Replaces `lo` and `hi` with those from `span`, but keep hygiene context. 69,800 ( 0.00%) pub fn with_span_pos(self, span: Span) -> Ident { . Ident::new(self.name, span.with_ctxt(self.span.ctxt())) 43,625 ( 0.00%) } . 10,712 ( 0.00%) pub fn without_first_quote(self) -> Ident { 10,712 ( 0.00%) Ident::new(Symbol::intern(self.as_str().trim_start_matches('\'')), self.span) 6,695 ( 0.00%) } . . /// "Normalize" ident for use in comparisons using "item hygiene". . /// Identifiers with same string value become same if they came from the same macro 2.0 macro . /// (e.g., `macro` item, but not `macro_rules` item) and stay different if they came from . /// different macro 2.0 macros. . /// Technically, this operation strips all non-opaque marks from ident's syntactic context. 696,924 ( 0.00%) pub fn normalize_to_macros_2_0(self) -> Ident { . Ident::new(self.name, self.span.normalize_to_macros_2_0()) 542,052 ( 0.00%) } . . /// "Normalize" ident for use in comparisons using "local variable hygiene". . /// Identifiers with same string value become same if they came from the same non-transparent . /// macro (e.g., `macro` or `macro_rules!` items) and stay different if they came from different . /// non-transparent macros. . /// Technically, this operation strips all transparent marks from ident's syntactic context. 26,100,621 ( 0.11%) pub fn normalize_to_macro_rules(self) -> Ident { . Ident::new(self.name, self.span.normalize_to_macro_rules()) 20,300,483 ( 0.08%) } . . /// Access the underlying string. This is a slowish operation because it . /// requires locking the symbol interner. . /// . /// Note that the lifetime of the return value is a lie. See . /// `Symbol::as_str()` for details. . pub fn as_str(&self) -> &str { 5,855 ( 0.00%) self.name.as_str() . } . } . . impl PartialEq for Ident { 9,038,202 ( 0.04%) fn eq(&self, rhs: &Self) -> bool { 23,752,570 ( 0.10%) self.name == rhs.name && self.span.ctxt() == rhs.span.ctxt() 12,050,936 ( 0.05%) } . } . . impl Hash for Ident { . fn hash(&self, state: &mut H) { 8,079 ( 0.00%) self.name.hash(state); 138,601 ( 0.00%) self.span.ctxt().hash(state); . } . } . . impl fmt::Debug for Ident { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . fmt::Display::fmt(self, f)?; . fmt::Debug::fmt(&self.span.ctxt(), f) . } . } . . /// This implementation is supposed to be used in error messages, so it's expected to be identical . /// to printing the original identifier token written in source code (`token_to_string`), . /// except that AST identifiers don't keep the rawness flag, so we have to guess it. . impl fmt::Display for Ident { 6,988 ( 0.00%) fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 8,800 ( 0.00%) fmt::Display::fmt(&IdentPrinter::new(self.name, self.is_raw_guess(), None), f) 6,988 ( 0.00%) } . } . . /// This is the most general way to print identifiers. . /// AST pretty-printer is used as a fallback for turning AST structures into token streams for . /// proc macros. Additionally, proc macros may stringify their input and expect it survive the . /// stringification (especially true for proc macro derives written between Rust 1.15 and 1.30). . /// So we need to somehow pretty-print `$crate` in a way preserving at least some of its . /// hygiene data, most importantly name of the crate it refers to. -- line 1613 ---------------------------------------- -- line 1622 ---------------------------------------- . is_raw: bool, . /// Span used for retrieving the crate name to which `$crate` refers to, . /// if this field is `None` then the `$crate` conversion doesn't happen. . convert_dollar_crate: Option, . } . . impl IdentPrinter { . /// The most general `IdentPrinter` constructor. Do not use this. 2,377 ( 0.00%) pub fn new(symbol: Symbol, is_raw: bool, convert_dollar_crate: Option) -> IdentPrinter { 60,685 ( 0.00%) IdentPrinter { symbol, is_raw, convert_dollar_crate } 2,377 ( 0.00%) } . . /// This implementation is supposed to be used when printing identifiers . /// as a part of pretty-printing for larger AST pieces. . /// Do not use this either. 21,026 ( 0.00%) pub fn for_ast_ident(ident: Ident, is_raw: bool) -> IdentPrinter { 21,026 ( 0.00%) IdentPrinter::new(ident.name, is_raw, Some(ident.span)) 10,513 ( 0.00%) } . } . . impl fmt::Display for IdentPrinter { 73,510 ( 0.00%) fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 29,404 ( 0.00%) if self.is_raw { . f.write_str("r#")?; 14,702 ( 0.00%) } else if self.symbol == kw::DollarCrate { 2,750 ( 0.00%) if let Some(span) = self.convert_dollar_crate { 550 ( 0.00%) let converted = span.ctxt().dollar_crate_name(); . if !converted.is_path_segment_keyword() { 4,950 ( 0.00%) f.write_str("::")?; . } . return fmt::Display::fmt(&converted, f); . } . } . fmt::Display::fmt(&self.symbol, f) 2,200 ( 0.00%) } . } . . /// An newtype around `Ident` that calls [Ident::normalize_to_macro_rules] on . /// construction. . // FIXME(matthewj, petrochenkov) Use this more often, add a similar . // `ModernIdent` struct and use that as well. . #[derive(Copy, Clone, Eq, PartialEq, Hash)] 14,408,483 ( 0.06%) pub struct MacroRulesNormalizedIdent(Ident); . . impl MacroRulesNormalizedIdent { . pub fn new(ident: Ident) -> Self { 2,897,464 ( 0.01%) Self(ident.normalize_to_macro_rules()) . } . } . . impl fmt::Debug for MacroRulesNormalizedIdent { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . fmt::Debug::fmt(&self.0, f) . } . } -- line 1676 ---------------------------------------- -- line 1686 ---------------------------------------- . /// Internally, a `Symbol` is implemented as an index, and all operations . /// (including hashing, equality, and ordering) operate on that index. The use . /// of `rustc_index::newtype_index!` means that `Option` only takes up 4 bytes, . /// because `rustc_index::newtype_index!` reserves the last 256 values for tagging purposes. . /// . /// Note that `Symbol` cannot directly be a `rustc_index::newtype_index!` because it . /// implements `fmt::Debug`, `Encodable`, and `Decodable` in special ways. . #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] 206,968 ( 0.00%) pub struct Symbol(SymbolIndex); . . rustc_index::newtype_index! { . struct SymbolIndex { .. } . } . . impl Symbol { . const fn new(n: u32) -> Self { . Symbol(SymbolIndex::from_u32(n)) 676 ( 0.00%) } . . /// Maps a string to its interned representation. 946,035 ( 0.00%) pub fn intern(string: &str) -> Self { . with_session_globals(|session_globals| session_globals.symbol_interner.intern(string)) 946,035 ( 0.00%) } . . /// Access the underlying string. This is a slowish operation because it . /// requires locking the symbol interner. . /// . /// Note that the lifetime of the return value is a lie. It's not the same . /// as `&self`, but actually tied to the lifetime of the underlying . /// interner. Interners are long-lived, and there are very few of them, and . /// this function is typically used for short-lived things, so in practice . /// it works out ok. 513,633 ( 0.00%) pub fn as_str(&self) -> &str { 171,211 ( 0.00%) with_session_globals(|session_globals| unsafe { . std::mem::transmute::<&str, &str>(session_globals.symbol_interner.get(*self)) . }) 684,844 ( 0.00%) } . . pub fn as_u32(self) -> u32 { . self.0.as_u32() . } . . pub fn is_empty(self) -> bool { . self == kw::Empty . } . . /// This method is supposed to be used in error messages, so it's expected to be . /// identical to printing the original identifier token written in source code . /// (`token_to_string`, `Ident::to_string`), except that symbols don't keep the rawness flag . /// or edition, so we have to guess the rawness using the global edition. 390 ( 0.00%) pub fn to_ident_string(self) -> String { . Ident::with_dummy_span(self).to_string() 390 ( 0.00%) } . } . . impl fmt::Debug for Symbol { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . fmt::Debug::fmt(self.as_str(), f) . } . } . . impl fmt::Display for Symbol { 8,080 ( 0.00%) fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 154,358 ( 0.00%) fmt::Display::fmt(self.as_str(), f) . } . } . . impl Encodable for Symbol { . fn encode(&self, s: &mut S) -> Result<(), S::Error> { 276,908 ( 0.00%) s.emit_str(self.as_str()) . } . } . . impl Decodable for Symbol { . #[inline] 68,532 ( 0.00%) fn decode(d: &mut D) -> Symbol { 155,037 ( 0.00%) Symbol::intern(&d.read_str()) . } . } . . impl HashStable for Symbol { . #[inline] 28,998 ( 0.00%) fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) { 121,729 ( 0.00%) self.as_str().hash_stable(hcx, hasher); 28,812 ( 0.00%) } . } . . impl ToStableHashKey for Symbol { . type KeyType = String; . #[inline] . fn to_stable_hash_key(&self, _: &CTX) -> String { . self.as_str().to_string() . } -- line 1778 ---------------------------------------- -- line 1785 ---------------------------------------- . // . // The `FxHashMap`+`Vec` pair could be replaced by `FxIndexSet`, but #75278 . // found that to regress performance up to 2% in some cases. This might be . // revisited after further improvements to `indexmap`. . // . // This type is private to prevent accidentally constructing more than one . // `Interner` on the same thread, which makes it easy to mixup `Symbol`s . // between `Interner`s. 2 ( 0.00%) #[derive(Default)] . struct InternerInner { . arena: DroplessArena, . names: FxHashMap<&'static str, Symbol>, . strings: Vec<&'static str>, . } . . impl Interner { . fn prefill(init: &[&'static str]) -> Self { 30 ( 0.00%) Interner(Lock::new(InternerInner { . strings: init.into(), . names: init.iter().copied().zip((0..).map(Symbol::new)).collect(), . ..Default::default() . })) . } . . #[inline] . fn intern(&self, string: &str) -> Symbol { . let mut inner = self.0.lock(); 181,374 ( 0.00%) if let Some(&name) = inner.names.get(string) { . return name; . } . 14,428 ( 0.00%) let name = Symbol::new(inner.strings.len() as u32); . . // SAFETY: we convert from `&str` to `&[u8]`, clone it into the arena, . // and immediately convert the clone back to `&[u8], all because there . // is no `inner.arena.alloc_str()` method. This is clearly safe. . let string: &str = . unsafe { str::from_utf8_unchecked(inner.arena.alloc_slice(string.as_bytes())) }; . . // SAFETY: we can extend the arena allocation to `'static` because we -- line 1824 ---------------------------------------- -- line 1831 ---------------------------------------- . // #91445 for details. . inner.names.insert(string, name); . name . } . . // Get the symbol as a string. `Symbol::as_str()` should be used in . // preference to this function. . fn get(&self, symbol: Symbol) -> &str { 513,633 ( 0.00%) self.0.lock().strings[symbol.0.as_usize()] . } . } . . // This module has a very short name because it's used a lot. . /// This module contains all the defined keyword `Symbol`s. . /// . /// Given that `kw` is imported, use them like `kw::keyword_name`. . /// For example `kw::Loop` or `kw::Break`. -- line 1847 ---------------------------------------- -- line 1863 ---------------------------------------- . . // Used from a macro in `librustc_feature/accepted.rs` . pub use super::kw::MacroRules as macro_rules; . . /// Get the symbol for an integer. . /// . /// The first few non-negative integers each have a static symbol and therefore . /// are fast. 1,088 ( 0.00%) pub fn integer + Copy + ToString>(n: N) -> Symbol { 830 ( 0.00%) if let Result::Ok(idx) = n.try_into() { 172 ( 0.00%) if idx < 10 { 1,352 ( 0.00%) return Symbol::new(super::SYMBOL_DIGITS_BASE + idx as u32); . } . } 3 ( 0.00%) Symbol::intern(&n.to_string()) 12 ( 0.00%) } . } . . impl Symbol { . fn is_special(self) -> bool { . self <= kw::Underscore . } . . fn is_used_keyword_always(self) -> bool { 7,146 ( 0.00%) self >= kw::As && self <= kw::While . } . . fn is_used_keyword_conditional(self, edition: impl FnOnce() -> Edition) -> bool { 198,525 ( 0.00%) (self >= kw::Async && self <= kw::Dyn) && edition() >= Edition::Edition2018 . } . . fn is_unused_keyword_always(self) -> bool { 7,131 ( 0.00%) self >= kw::Abstract && self <= kw::Yield . } . . fn is_unused_keyword_conditional(self, edition: impl FnOnce() -> Edition) -> bool { 2,377 ( 0.00%) self == kw::Try && edition() >= Edition::Edition2018 . } . . pub fn is_reserved(self, edition: impl Copy + FnOnce() -> Edition) -> bool { 328,561 ( 0.00%) self.is_special() . || self.is_used_keyword_always() . || self.is_unused_keyword_always() . || self.is_used_keyword_conditional(edition) . || self.is_unused_keyword_conditional(edition) . } . . /// A keyword or reserved identifier that can be used as a path segment. . pub fn is_path_segment_keyword(self) -> bool { 758,178 ( 0.00%) self == kw::Super . || self == kw::SelfLower . || self == kw::SelfUpper . || self == kw::Crate . || self == kw::PathRoot . || self == kw::DollarCrate . } . . /// Returns `true` if the symbol is `true` or `false`. . pub fn is_bool_lit(self) -> bool { 14,848 ( 0.00%) self == kw::True || self == kw::False 14,848 ( 0.00%) } . . /// Returns `true` if this symbol can be a raw identifier. . pub fn can_be_raw(self) -> bool { 27,052 ( 0.00%) self != kw::Empty && self != kw::Underscore && !self.is_path_segment_keyword() 3 ( 0.00%) } . } . . impl Ident { . // Returns `true` for reserved identifiers used internally for elided lifetimes, . // unnamed method parameters, crate root module, error recovery etc. . pub fn is_special(self) -> bool { . self.name.is_special() 2,377 ( 0.00%) } . . /// Returns `true` if the token is a keyword used in the language. 2,382 ( 0.00%) pub fn is_used_keyword(self) -> bool { . // Note: `span.edition()` is relatively expensive, don't call it unless necessary. 2,382 ( 0.00%) self.name.is_used_keyword_always() . || self.name.is_used_keyword_conditional(|| self.span.edition()) 4,764 ( 0.00%) } . . /// Returns `true` if the token is a keyword reserved for possible future use. 2,377 ( 0.00%) pub fn is_unused_keyword(self) -> bool { . // Note: `span.edition()` is relatively expensive, don't call it unless necessary. 2,377 ( 0.00%) self.name.is_unused_keyword_always() . || self.name.is_unused_keyword_conditional(|| self.span.edition()) 4,754 ( 0.00%) } . . /// Returns `true` if the token is either a special identifier or a keyword. 54,074 ( 0.00%) pub fn is_reserved(self) -> bool { . // Note: `span.edition()` is relatively expensive, don't call it unless necessary. . self.name.is_reserved(|| self.span.edition()) 108,148 ( 0.00%) } . . /// A keyword or reserved identifier that can be used as a path segment. . pub fn is_path_segment_keyword(self) -> bool { . self.name.is_path_segment_keyword() 108,154 ( 0.00%) } . . /// We see this identifier in a normal identifier position, like variable name or a type. . /// How was it written originally? Did it use the raw form? Let's try to guess. 10,787 ( 0.00%) pub fn is_raw_guess(self) -> bool { . self.name.can_be_raw() && self.is_reserved() 21,574 ( 0.00%) } . } 3,192,565 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/tokenstream.rs -------------------------------------------------------------------------------- Ir -- line 32 ---------------------------------------- . /// . /// If the syntax extension is an MBE macro, it will attempt to match its . /// LHS token tree against the provided token tree, and if it finds a . /// match, will transcribe the RHS token tree, splicing in any captured . /// `macro_parser::matched_nonterminals` into the `SubstNt`s it finds. . /// . /// The RHS of an MBE macro is the only place `SubstNt`s are substituted. . /// Nothing special happens to misnamed or misplaced `SubstNt`s. 146,904,723 ( 0.61%) #[derive(Debug, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)] . pub enum TokenTree { . /// A single token. 59,649,993 ( 0.25%) Token(Token), . /// A delimited sequence of token trees. 4,497,524 ( 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 { 35,978 ( 0.00%) match self { 15,463 ( 0.00%) TokenTree::Token(token) => token.span, 22,256 ( 0.00%) TokenTree::Delimited(sp, ..) => sp.entire(), . } 14,118 ( 0.00%) } . . /// Modify the `TokenTree`'s span in-place. . pub fn set_span(&mut self, span: Span) { 35,978 ( 0.00%) match self { 14,118 ( 0.00%) TokenTree::Token(token) => token.span = span, 7,742 ( 0.00%) TokenTree::Delimited(dspan, ..) => *dspan = DelimSpan::from_single(span), . } 17,989 ( 0.00%) } . 12,035 ( 0.00%) pub fn token(kind: TokenKind, span: Span) -> TokenTree { 14,660,948 ( 0.06%) TokenTree::Token(Token::new(kind, span)) 12,035 ( 0.00%) } . . /// Returns the opening delimiter as a token tree. 1,827,367 ( 0.01%) pub fn open_tt(span: DelimSpan, delim: DelimToken) -> TokenTree { 5,482,101 ( 0.02%) TokenTree::token(token::OpenDelim(delim), span.open) 1,827,367 ( 0.01%) } . . /// Returns the closing delimiter as a token tree. 1,825,835 ( 0.01%) pub fn close_tt(span: DelimSpan, delim: DelimToken) -> TokenTree { 5,477,505 ( 0.02%) TokenTree::token(token::CloseDelim(delim), span.close) 1,825,835 ( 0.01%) } . 34,353 ( 0.00%) pub fn uninterpolate(self) -> TokenTree { 22,902 ( 0.00%) match self { 103,059 ( 0.00%) TokenTree::Token(token) => TokenTree::Token(token.uninterpolate().into_owned()), . tt => tt, . } 45,804 ( 0.00%) } . } . . impl HashStable for TokenStream . where . CTX: crate::HashStableContext, . { 18,432 ( 0.00%) fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) { 81,848 ( 0.00%) for sub_tt in self.trees() { . sub_tt.hash_stable(hcx, hasher); . } 16,384 ( 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 { 1,500 ( 0.00%) pub fn new(inner: impl CreateTokenStream + 'static) -> LazyTokenStream { . LazyTokenStream(Lrc::new(Box::new(inner))) 1,500 ( 0.00%) } . . pub fn create_token_stream(&self) -> AttrAnnotatedTokenStream { 1,356 ( 0.00%) self.0.create_token_stream() . } . } . . impl fmt::Debug for LazyTokenStream { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . write!(f, "LazyTokenStream({:?})", self.create_token_stream()) . } . } -- line 156 ---------------------------------------- -- line 177 ---------------------------------------- . /// A `AttrAnnotatedTokenStream` is similar to a `TokenStream`, but with extra . /// information about the tokens for attribute targets. This is used . /// during expansion to perform early cfg-expansion, and to process attributes . /// during proc-macro invocations. . #[derive(Clone, Debug, Default, Encodable, Decodable)] . pub struct AttrAnnotatedTokenStream(pub Lrc>); . . /// Like `TokenTree`, but for `AttrAnnotatedTokenStream` 59 ( 0.00%) #[derive(Clone, Debug, Encodable, Decodable)] . pub enum AttrAnnotatedTokenTree { 24 ( 0.00%) Token(Token), 2 ( 0.00%) Delimited(DelimSpan, DelimToken, AttrAnnotatedTokenStream), . /// Stores the attributes for an attribute target, . /// along with the tokens for that attribute target. . /// See `AttributesData` for more information . Attributes(AttributesData), . } . . impl AttrAnnotatedTokenStream { 65,808 ( 0.00%) pub fn new(tokens: Vec<(AttrAnnotatedTokenTree, Spacing)>) -> AttrAnnotatedTokenStream { . AttrAnnotatedTokenStream(Lrc::new(tokens)) 65,808 ( 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. 319 ( 0.00%) pub fn to_tokenstream(&self) -> TokenStream { 346 ( 0.00%) let trees: Vec<_> = self . .0 . .iter() 1,385 ( 0.00%) .flat_map(|tree| match &tree.0 { 830 ( 0.00%) AttrAnnotatedTokenTree::Token(inner) => { 2,075 ( 0.00%) smallvec![(TokenTree::Token(inner.clone()), tree.1)].into_iter() . } 540 ( 0.00%) AttrAnnotatedTokenTree::Delimited(span, delim, stream) => smallvec![( 81 ( 0.00%) TokenTree::Delimited(*span, *delim, stream.to_tokenstream()), 27 ( 0.00%) tree.1, . )] . .into_iter(), . AttrAnnotatedTokenTree::Attributes(data) => { . let mut outer_attrs = Vec::new(); . let mut inner_attrs = Vec::new(); . for attr in &data.attrs { 16 ( 0.00%) match attr.style { . crate::AttrStyle::Outer => { . outer_attrs.push(attr); . } . crate::AttrStyle::Inner => { . inner_attrs.push(attr); . } . } . } . 2 ( 0.00%) let mut target_tokens: Vec<_> = data . .tokens . .create_token_stream() . .to_tokenstream() . .0 . .iter() . .cloned() . .collect(); 1 ( 0.00%) if !inner_attrs.is_empty() { . let mut found = false; . // Check the last two trees (to account for a trailing semi) . for (tree, _) in target_tokens.iter_mut().rev().take(2) { . if let TokenTree::Delimited(span, delim, delim_tokens) = tree { . // Inner attributes are only supported on extern blocks, functions, impls, . // and modules. All of these have their inner attributes placed at . // the beginning of the rightmost outermost braced group: . // e.g. fn foo() { #![my_attr} } -- line 248 ---------------------------------------- -- line 269 ---------------------------------------- . . assert!( . found, . "Failed to find trailing delimited group in: {:?}", . target_tokens . ); . } . let mut flat: SmallVec<[_; 1]> = SmallVec::new(); 29 ( 0.00%) for attr in outer_attrs { . // FIXME: Make this more efficient 48 ( 0.00%) flat.extend(attr.tokens().to_tokenstream().0.clone().iter().cloned()); . } 8 ( 0.00%) flat.extend(target_tokens); 10 ( 0.00%) flat.into_iter() 1 ( 0.00%) } . }) . .collect(); . TokenStream::new(trees) 638 ( 0.00%) } . } . . /// Stores the tokens for an attribute target, along . /// with its attributes. . /// . /// This is constructed during parsing when we need to capture . /// tokens. . /// -- line 295 ---------------------------------------- -- line 298 ---------------------------------------- . /// and a `tokens` field storing the (unparesd) tokens `struct Foo {}` . #[derive(Clone, Debug, Encodable, Decodable)] . pub struct AttributesData { . /// Attributes, both outer and inner. . /// These are stored in the original order that they were parsed in. . pub attrs: AttrVec, . /// The underlying tokens for the attribute target that `attrs` . /// are applied to 4 ( 0.00%) pub tokens: LazyTokenStream, . } . . /// A `TokenStream` is an abstract sequence of tokens, organized into [`TokenTree`]s. . /// . /// The goal is for procedural macros to work with `TokenStream`s and `TokenTree`s . /// instead of a representation of the abstract syntax tree. . /// Today's `TokenTree`s can still contain AST via `token::Interpolated` for . /// backwards compatibility. -- line 314 ---------------------------------------- -- line 316 ---------------------------------------- . pub struct TokenStream(pub(crate) Lrc>); . . pub type TreeAndSpacing = (TokenTree, Spacing); . . // `TokenStream` is used a lot. Make sure it doesn't unintentionally get bigger. . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . rustc_data_structures::static_assert_size!(TokenStream, 8); . 14,947,520 ( 0.06%) #[derive(Clone, Copy, Debug, PartialEq, Encodable, Decodable)] . pub enum Spacing { . Alone, . Joint, . } . . impl TokenStream { . /// Given a `TokenStream` with a `Stream` of only two arguments, return a new `TokenStream` . /// separating the two arguments with a comma for diagnostic suggestions. -- line 332 ---------------------------------------- -- line 365 ---------------------------------------- . return Some((TokenStream::new(new_stream), sp)); . } . None . } . } . . impl From<(AttrAnnotatedTokenTree, Spacing)> for AttrAnnotatedTokenStream { . fn from((tree, spacing): (AttrAnnotatedTokenTree, Spacing)) -> AttrAnnotatedTokenStream { 40 ( 0.00%) AttrAnnotatedTokenStream::new(vec![(tree, spacing)]) . } . } . . impl From for TokenStream { . fn from(tree: TokenTree) -> TokenStream { 4,130 ( 0.00%) TokenStream::new(vec![(tree, Spacing::Alone)]) . } . } . . impl From for TreeAndSpacing { . fn from(tree: TokenTree) -> TreeAndSpacing { 6,599,272 ( 0.03%) (tree, Spacing::Alone) . } . } . . impl iter::FromIterator for TokenStream { . fn from_iter>(iter: I) -> Self { 1,398 ( 0.00%) TokenStream::new(iter.into_iter().map(Into::into).collect::>()) . } . } . . impl Eq for TokenStream {} . . impl PartialEq for TokenStream { . fn eq(&self, other: &TokenStream) -> bool { . self.trees().eq(other.trees()) -- line 399 ---------------------------------------- -- line 401 ---------------------------------------- . } . . impl TokenStream { . pub fn new(streams: Vec) -> TokenStream { . TokenStream(Lrc::new(streams)) . } . . pub fn is_empty(&self) -> bool { 7,744 ( 0.00%) self.0.is_empty() 7,744 ( 0.00%) } . . pub fn len(&self) -> usize { 18,598,384 ( 0.08%) self.0.len() 4,690 ( 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 { 6,505 ( 0.00%) self.clone().into_trees() 13,010 ( 0.00%) } . 1,840,901 ( 0.01%) pub fn into_trees(self) -> Cursor { . Cursor::new(self) 3,681,802 ( 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 { 3,711 ( 0.00%) TokenStream(Lrc::new( . self.0 . .iter() . .enumerate() 107,934 ( 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; . 140,439 ( 0.00%) fn next(&mut self) -> Option { 385,236 ( 0.00%) self.next_with_spacing().map(|(tree, _)| tree) 187,252 ( 0.00%) } . } . . impl Cursor { . fn new(stream: TokenStream) -> Self { . Cursor { stream, index: 0 } . } . 92,710,955 ( 0.38%) pub fn next_with_spacing(&mut self) -> Option { 55,767,012 ( 0.23%) if self.index < self.stream.len() { 29,796,398 ( 0.12%) self.index += 1; 104,021,512 ( 0.43%) Some(self.stream.0[self.index - 1].clone()) . } else { 7,363,950 ( 0.03%) None . } 111,253,146 ( 0.46%) } . . 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; . } . 74,072 ( 0.00%) pub fn look_ahead(&self, n: usize) -> Option<&TokenTree> { 148,144 ( 0.00%) self.stream.0[self.index..].get(n).map(|(tree, _)| tree) 148,144 ( 0.00%) } . } . 8,104,707 ( 0.03%) #[derive(Debug, Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)] . pub struct DelimSpan { . pub open: Span, . pub close: Span, . } . . impl DelimSpan { 1,021 ( 0.00%) pub fn from_single(sp: Span) -> Self { . DelimSpan { open: sp, close: sp } 2,042 ( 0.00%) } . 15,432 ( 0.00%) pub fn from_pair(open: Span, close: Span) -> Self { . DelimSpan { open, close } 7,716 ( 0.00%) } . . pub fn dummy() -> Self { . Self::from_single(DUMMY_SP) 43,725 ( 0.00%) } . 167,336 ( 0.00%) pub fn entire(self) -> Span { . self.open.with_hi(self.close.hi()) 125,502 ( 0.00%) } . } 145,298 ( 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. 4,324,927 ( 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")] 13,378 ( 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 { 16,519,067 ( 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> { 14,721,179 ( 0.06%) match *self { . Some(ref x) => Some(x), . None => None, . } . } . . /// Converts from `&mut Option` to `Option<&mut T>`. . /// . /// # Examples -- line 632 ---------------------------------------- -- line 638 ---------------------------------------- . /// None => {}, . /// } . /// assert_eq!(x, Some(42)); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] . pub const fn as_mut(&mut self) -> Option<&mut T> { 1,961,378 ( 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 { 2,153,277 ( 0.01%) match self { 1,166,447 ( 0.00%) 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 { 52,900,890 ( 0.22%) match self { 1,938,224 ( 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, . { 1,684,827 ( 0.01%) match self { . Some(x) => x, 51,564 ( 0.00%) None => default, . } 4,647 ( 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")] 797 ( 0.00%) pub const fn unwrap_or_else(self, f: F) -> T . where . F: ~const FnOnce() -> T, . F: ~const Drop, . { 1,774,354 ( 0.01%) match self { 150,109 ( 0.00%) Some(x) => x, 9,988 ( 0.00%) None => f(), . } 1,159 ( 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, . { 19,458 ( 0.00%) match self { 32,254 ( 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")] 40,404 ( 0.00%) pub const fn map(self, f: F) -> Option . where . F: ~const FnOnce(T) -> U, . F: ~const Drop, . { 4,901,081 ( 0.02%) match self { 4,769,322 ( 0.02%) Some(x) => Some(f(x)), 188,088 ( 0.00%) None => None, . } 228,138 ( 0.00%) } . . /// Calls the provided closure with a reference to the contained value (if [`Some`]). . /// . /// # Examples . /// . /// ``` . /// #![feature(result_option_inspect)] . /// -- line 917 ---------------------------------------- -- line 960 ---------------------------------------- . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn map_or(self, default: U, f: F) -> U . where . F: ~const FnOnce(T) -> U, . F: ~const Drop, . U: ~const Drop, . { 1,487,741 ( 0.01%) match self { 76,053 ( 0.00%) Some(t) => f(t), 26,405 ( 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, . { 72,929 ( 0.00%) match self { 7,111 ( 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, . { 1,601,147 ( 0.01%) match self { 4,472 ( 0.00%) Some(v) => Ok(v), 2,090 ( 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")] 40 ( 0.00%) pub const fn ok_or_else(self, err: F) -> Result . where . F: ~const FnOnce() -> E, . F: ~const Drop, . { 135,684 ( 0.00%) match self { 96,373 ( 0.00%) Some(v) => Ok(v), 34,237 ( 0.00%) None => Err(err()), . } 50 ( 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, . { 45,448 ( 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")] 1,807 ( 0.00%) pub const fn and_then(self, f: F) -> Option . where . F: ~const FnOnce(T) -> Option, . F: ~const Drop, . { 374,709 ( 0.00%) match self { 54,949 ( 0.00%) Some(x) => f(x), . None => None, . } 75,492 ( 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, . { 82,940 ( 0.00%) if let Some(x) = self { 9,715 ( 0.00%) if predicate(&x) { . return Some(x); . } . } . None 15,759 ( 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, . { 17,253 ( 0.00%) match self { 3,136 ( 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, . { 73,491 ( 0.00%) match self { 31,950 ( 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, . { 94,476 ( 0.00%) if let None = *self { 220,338 ( 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, . { 807,151 ( 0.00%) 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. 126 ( 0.00%) mem::forget(mem::replace(self, Some(f()))) . } . . // SAFETY: a `None` variant for `self` would have been replaced by a `Some` . // variant in the code above. . unsafe { self.as_mut().unwrap_unchecked() } . } . . ///////////////////////////////////////////////////////////////////////// -- line 1518 ---------------------------------------- -- line 1558 ---------------------------------------- . /// let old = x.replace(3); . /// assert_eq!(x, Some(3)); . /// assert_eq!(old, None); . /// ``` . #[inline] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] . #[stable(feature = "option_replace", since = "1.31.0")] . pub const fn replace(&mut self, value: T) -> Option { 6,392 ( 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 119,967 ( 0.00%) match self { 1,164,543 ( 0.00%) Some(&v) => Some(v), 10,542 ( 0.00%) None => None, . } 559 ( 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")] 54,804 ( 0.00%) pub const fn cloned(self) -> Option . where . T: ~const Clone, . { 6,100,718 ( 0.03%) match self { 18,341,371 ( 0.08%) Some(t) => Some(t.clone()), 2,907,025 ( 0.01%) None => None, . } 125,828 ( 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 { 48,203,000 ( 0.20%) match self { 5,518,608 ( 0.02%) Some(x) => Some(x.clone()), 5,417,473 ( 0.02%) None => None, . } 2,153,263 ( 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 1895 ---------------------------------------- . /// assert_eq!(v, ["string"]); . /// . /// let x = None; . /// let v: Vec<&str> = x.into_iter().collect(); . /// assert!(v.is_empty()); . /// ``` . #[inline] . fn into_iter(self) -> IntoIter { 22 ( 0.00%) IntoIter { inner: Item { opt: self } } . } . } . . #[stable(since = "1.4.0", feature = "option_iter")] . impl<'a, T> IntoIterator for &'a Option { . type Item = &'a T; . type IntoIter = Iter<'a, T>; . -- line 1911 ---------------------------------------- -- line 2006 ---------------------------------------- . . #[inline] . fn next(&mut self) -> Option { . self.opt.take() . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 92,613 ( 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) { 120 ( 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) 7,990 ( 0.00%) } . . #[inline] . fn branch(self) -> ControlFlow { 1,376,461 ( 0.01%) match self { 331,414 ( 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 { 201,643 ( 0.00%) None => None, . } . } . } . . #[unstable(feature = "try_trait_v2_residual", issue = "91285")] . impl ops::Residual for Option { . type TryType = Option; . } -- line 2274 ---------------------------------------- -- line 2297 ---------------------------------------- . /// let x: Option>> = Some(Some(Some(6))); . /// assert_eq!(Some(Some(6)), x.flatten()); . /// assert_eq!(Some(6), x.flatten().flatten()); . /// ``` . #[inline] . #[stable(feature = "option_flattening", since = "1.40.0")] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] . pub const fn flatten(self) -> Option { 14 ( 0.00%) match self { 77 ( 0.00%) Some(inner) => inner, . None => None, . } . } . } 23,856,103 ( 0.10%) -------------------------------------------------------------------------------- -- 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")] 41,536 ( 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( 44,795,665 ( 0.19%) Box::leak(box RcBox { strong: Cell::new(1), weak: Cell::new(1), value }).into(), . ) . } 41,536 ( 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 { 16,055,064 ( 0.07%) 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 { 2,433 ( 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> { 811 ( 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`). 10,996,437 ( 0.05%) 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 { 8,396 ( 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")] 53,776,645 ( 0.22%) pub fn make_mut(this: &mut Self) -> &mut T { 32,264,871 ( 0.13%) if Rc::strong_count(this) != 1 { . // Gotta clone the data, there are other Rcs. . // Pre-allocate memory to allow writing the cloned value directly. 5,404,841 ( 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()); 10,809,682 ( 0.04%) *this = rc.assume_init(); . } 10,701,754 ( 0.04%) } 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. 10,755,718 ( 0.04%) unsafe { &mut this.ptr.as_mut().value } 64,531,602 ( 0.27%) } . } . . 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))] 16,986 ( 0.00%) unsafe fn copy_from_slice(v: &[T]) -> Rc<[T]> { . unsafe { . let ptr = Self::allocate_for_slice(v.len()); 3,629 ( 0.00%) ptr::copy_nonoverlapping(v.as_ptr(), &mut (*ptr).value as *mut [T] as *mut T, v.len()); . Self::from_ptr(ptr) . } 21,850 ( 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 { 13 ( 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 { 600,486 ( 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!" . /// ``` 35,683,769 ( 0.15%) fn drop(&mut self) { . unsafe { 40,636,329 ( 0.17%) self.inner().dec_strong(); 92,823,491 ( 0.39%) if self.inner().strong() == 0 { . // destroy the contained object 5,486,909 ( 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(); . 22,141,825 ( 0.09%) if self.inner().weak() == 0 { 2,493 ( 0.00%) Global.deallocate(self.ptr.cast(), Layout::for_value(self.ptr.as_ref())); . } . } . } 42,853,144 ( 0.18%) } . } . . #[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 { 8,604 ( 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 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 { 4,894 ( 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; 27 ( 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) { 35,328,897 ( 0.15%) 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. 106,223,921 ( 0.44%) if strong == 0 || strong == usize::MAX { . abort(); . } 20,485 ( 0.00%) self.strong_ref().set(strong + 1); . } . . #[inline] . fn dec_strong(&self) { 161,042,575 ( 0.67%) 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) { 33,211,375 ( 0.14%) self.weak_ref().set(self.weak() - 1); . } . } . . impl RcInnerPtr for RcBox { . #[inline(always)] . fn weak_ref(&self) -> &Cell { . &self.weak . } -- line 2523 ---------------------------------------- 40,751,880 ( 0.17%) -------------------------------------------------------------------------------- -- 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)] 678,718,649 ( 2.82%) pub unsafe fn drop_in_place(to_drop: *mut T) { . // Code here does not matter - this is replaced by the . // real drop glue by the compiler. . . // SAFETY: see comment above . unsafe { drop_in_place(to_drop) } . } . . /// Creates a null raw pointer. -- line 196 ---------------------------------------- -- line 366 ---------------------------------------- . let mut tmp = MaybeUninit::::uninit(); . . // Perform the swap . // SAFETY: the caller must guarantee that `x` and `y` are . // valid for writes and properly aligned. `tmp` cannot be . // overlapping either `x` or `y` because `tmp` was just allocated . // on the stack as a separate allocated object. . unsafe { 23 ( 0.00%) copy_nonoverlapping(x, tmp.as_mut_ptr(), 1); 23 ( 0.00%) copy(y, x, 1); // `x` and `y` may overlap . copy_nonoverlapping(tmp.as_ptr(), y, 1); . } . } . . /// Swaps `count * size_of::()` bytes between the two regions of memory . /// beginning at `x` and `y`. The two regions must *not* overlap. . /// . /// # Safety -- line 383 ---------------------------------------- -- line 448 ---------------------------------------- . return; . } . } . . // Direct swapping, for the cases not going through the block optimization. . // SAFETY: the caller must guarantee that `x` and `y` are valid . // for writes, properly aligned, and non-overlapping. . unsafe { 45 ( 0.00%) let z = read(x); . copy_nonoverlapping(y, x, 1); . write(y, z); . } . } . . #[inline] . #[rustc_const_unstable(feature = "const_swap", issue = "83163")] . const unsafe fn swap_nonoverlapping_bytes(x: *mut u8, y: *mut u8, len: usize) { -- line 464 ---------------------------------------- -- line 693 ---------------------------------------- . let mut tmp = MaybeUninit::::uninit(); . // SAFETY: the caller must guarantee that `src` is valid for reads. . // `src` cannot overlap `tmp` because `tmp` was just allocated on . // the stack as a separate allocated object. . // . // Also, since we just wrote a valid value into `tmp`, it is guaranteed . // to be properly initialized. . unsafe { 104,121,677 ( 0.43%) copy_nonoverlapping(src, tmp.as_mut_ptr(), 1); 96,156,010 ( 0.40%) 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 { 410,906,673 ( 1.70%) 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. 8,240 ( 0.00%) return wrapping_sub( 47,170 ( 0.00%) wrapping_add(p as usize, a_minus_one) & wrapping_sub(0, a), . p as usize, . ); . } . . let pmoda = p as usize & a_minus_one; . if pmoda == 0 { . // Already aligned. Yay! . return 0; -- line 1223 ---------------------------------------- -- line 1348 ---------------------------------------- . /// assert!(std::ptr::eq( . /// &wrapper as &dyn Trait as *const dyn Trait as *const u8, . /// &wrapper.member as &dyn Trait as *const dyn Trait as *const u8, . /// )); . /// ``` . #[stable(feature = "ptr_eq", since = "1.17.0")] . #[inline] . pub fn eq(a: *const T, b: *const T) -> bool { 2,951,485 ( 0.01%) a == b . } . . /// Hash a raw pointer. . /// . /// This can be used to hash a `&T` reference (which coerces to `*const T` implicitly) . /// by its address rather than the value it points to . /// (which is what the `Hash for &T` implementation does). . /// -- line 1364 ---------------------------------------- 53,676,223 ( 0.22%) -------------------------------------------------------------------------------- -- 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 . // . 95,117,744 ( 0.39%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 71,338,308 ( 0.30%) 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. 214,364 ( 0.00%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 321,546 ( 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) { 23,833,016 ( 0.10%) libc::free(ptr as *mut libc::c_void) . } . . #[inline] . unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { 1,261,752 ( 0.01%) if layout.align() <= MIN_ALIGN && layout.align() <= new_size { 2,523,504 ( 0.01%) libc::realloc(ptr as *mut libc::c_void, new_size) as *mut u8 . } else { . realloc_fallback(self, ptr, layout, new_size) . } . } . } . . cfg_if::cfg_if! { . if #[cfg(any( -- line 56 ---------------------------------------- -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/iter/adapters/take.rs -------------------------------------------------------------------------------- Ir -- line 14 ---------------------------------------- . #[stable(feature = "rust1", since = "1.0.0")] . pub struct Take { . iter: I, . n: usize, . } . . impl Take { . pub(in crate::iter) fn new(iter: I, n: usize) -> Take { 1 ( 0.00%) Take { iter, n } . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Iterator for Take . where . I: Iterator, . { . type Item = ::Item; . . #[inline] . fn next(&mut self) -> Option<::Item> { 76,565,144 ( 0.32%) if self.n != 0 { 35,724 ( 0.00%) self.n -= 1; . self.iter.next() . } else { 328 ( 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) { 55,668 ( 0.00%) if self.n == 0 { . return (0, Some(0)); . } . . let (lower, upper) = self.iter.size_hint(); . . let lower = cmp::min(lower, self.n); . 13,922 ( 0.00%) let upper = match upper { . Some(x) if x < self.n => Some(x), . _ => Some(self.n), . }; . . (lower, upper) . } . . #[inline] -- line 75 ---------------------------------------- -- line 78 ---------------------------------------- . Self: Sized, . 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 { 6 ( 0.00%) move |acc, x| { 40,894 ( 0.00%) *n -= 1; 11,103 ( 0.00%) let r = fold(acc, x); 59,346 ( 0.00%) if *n == 0 { ControlFlow::Break(r) } else { ControlFlow::from_try(r) } . } . } . 55,012 ( 0.00%) if self.n == 0 { . try { init } . } else { . let n = &mut self.n; 1 ( 0.00%) self.iter.try_fold(init, check(n, fold)).into_try() . } . } . . #[inline] . fn fold(mut self, init: Acc, fold: Fold) -> Acc . where . Self: Sized, . Fold: FnMut(Acc, Self::Item) -> Acc, -- line 105 ---------------------------------------- 258,490 ( 0.00%) -------------------------------------------------------------------------------- -- 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 { 75,683,961 ( 0.31%) 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) { 81,879,399 ( 0.34%) 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 { 1,152,356 ( 0.00%) 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 { 173,131 ( 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> { 7,031,712 ( 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) }; 46,078,853 ( 0.19%) 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()`" . ); . 504,630 ( 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) { 11,431,163 ( 0.05%) 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()`" . ); . 6,874 ( 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); 6,874 ( 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] 6,858 ( 0.00%) unsafe fn exchange_malloc(size: usize, align: usize) -> *mut u8 { . let layout = unsafe { Layout::from_size_align_unchecked(size, align) }; 74,103 ( 0.00%) match Global.allocate(layout) { . Ok(ptr) => ptr.as_mut_ptr(), . Err(_) => handle_alloc_error(layout), . } 11,820 ( 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 { 34,701 ( 0.00%) let size = size_of_val(ptr.as_ref()); 28,151 ( 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] 11,088 ( 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. 3,234,149 ( 0.01%) unsafe { target.write(self.clone()) }; 9,856 ( 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 ---------------------------------------- 46,272,802 ( 0.19%) -------------------------------------------------------------------------------- -- 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 { 8,568,264 ( 0.04%) Vec { buf: RawVec::NEW, len: 0 } 507 ( 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 { 14,208,964 ( 0.06%) 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 { 231,465 ( 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 { 6,170,751 ( 0.03%) 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) { 849,366 ( 0.00%) 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) { 40,234 ( 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. 11,044,557 ( 0.05%) if self.capacity() > self.len { 14,795 ( 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(); 5,469,152 ( 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")] 83,337,987 ( 0.35%) 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. 50,134,112 ( 0.21%) 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); 17,062,576 ( 0.07%) self.len = len; 15,967 ( 0.00%) ptr::drop_in_place(s); . } 100,005,584 ( 0.41%) } . . /// 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. 32,324,895 ( 0.13%) 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. 32,129,604 ( 0.13%) 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()); . 7,320,272 ( 0.03%) self.len = new_len; 20,411 ( 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(); 57 ( 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")] 14,301 ( 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); . } . 2,435 ( 0.00%) let len = self.len(); 5,512 ( 0.00%) if index > len { . assert_failed(index, len); . } . . // space for the new element 9,190 ( 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.) 12,135 ( 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); . } 9,158 ( 0.00%) self.set_len(len + 1); . } 12,258 ( 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); . } . 871 ( 0.00%) let len = self.len(); 2,961 ( 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. 8,368 ( 0.00%) ret = ptr::read(ptr); . . // Shift everything down to fill in that spot. 1,904 ( 0.00%) ptr::copy(ptr.offset(1), ptr, len - index - 1); . } 2,687 ( 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")] 676,780 ( 0.00%) pub fn retain(&mut self, mut f: F) . where . F: FnMut(&T) -> bool, . { 38,716 ( 0.00%) self.retain_mut(|elem| f(elem)); 659,560 ( 0.00%) } . . /// 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, . { 86,395 ( 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) { 71,468 ( 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), 55,197 ( 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, . { 849,393 ( 0.00%) 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) }; 219,158 ( 0.00%) if !f(cur) { . // Advance early to avoid double drop if `drop_in_place` panicked. 18,544 ( 0.00%) g.processed_len += 1; 8,302 ( 0.00%) g.deleted_cnt += 1; . // SAFETY: We never touch this element again after dropped. 246 ( 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 { 12,000 ( 0.00%) let hole_slot = g.v.as_mut_ptr().add(g.processed_len - g.deleted_cnt); 13 ( 0.00%) ptr::copy_nonoverlapping(cur, hole_slot, 1); . } . } 10,651 ( 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")] 18,578 ( 0.00%) pub fn dedup_by(&mut self, mut same_bucket: F) . where . F: FnMut(&mut T, &mut T) -> bool, . { 3,231 ( 0.00%) let len = self.len(); 14,150 ( 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 { 18,116 ( 0.00%) while gap.read < len { . let read_ptr = ptr.add(gap.read); . let prev_ptr = ptr.add(gap.write.wrapping_sub(1)); . 7,409 ( 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 */ 9,887 ( 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); . } 21,232 ( 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")] 1,215 ( 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. 24,735,116 ( 0.10%) if self.len == self.buf.capacity() { 1,382,290 ( 0.01%) self.buf.reserve_for_push(self.len); . } . unsafe { 648,656 ( 0.00%) let end = self.as_mut_ptr().add(self.len); . ptr::write(end, value); 29,904,002 ( 0.12%) self.len += 1; . } 972 ( 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 { 8,263,987 ( 0.03%) if self.len == 0 { 62 ( 0.00%) None . } else { . unsafe { 5,728,524 ( 0.02%) self.len -= 1; 401,859 ( 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")] 4,662 ( 0.00%) pub fn append(&mut self, other: &mut Self) { . unsafe { . self.append_elements(other.as_slice() as _); . other.set_len(0); . } 3,996 ( 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); 94,020 ( 0.00%) let len = self.len(); . unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) }; 983,744 ( 0.00%) 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. . // 53,112 ( 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). 214 ( 0.00%) let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start), end - start); 555,937 ( 0.00%) Drain { . tail_start: end, 174 ( 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) { 149,969,373 ( 0.62%) 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 { 6,563,152 ( 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); . } . 6,006 ( 0.00%) if at > self.len() { . assert_failed(at, self.len()); . } . 4,710 ( 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()), . ); . } . 68 ( 0.00%) let other_len = self.len - at; . let mut other = Vec::with_capacity_in(other_len, self.allocator().clone()); . . // Unsafely `set_len` and copy items to `other`. . unsafe { . self.set_len(at); . other.set_len(other_len); . . ptr::copy_nonoverlapping(self.as_ptr().add(at), other.as_mut_ptr(), other.len()); -- line 1963 ---------------------------------------- -- 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")] 71,135 ( 0.00%) pub fn resize_with(&mut self, new_len: usize, f: F) . where . F: FnMut() -> T, . { 9,599 ( 0.00%) let len = self.len(); 19,198 ( 0.00%) if new_len > len { 91,684 ( 0.00%) self.extend_with(new_len - len, ExtendFunc(f)); . } else { . self.truncate(new_len); . } 61,536 ( 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, 506 ( 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")] 24,790 ( 0.00%) pub fn resize(&mut self, new_len: usize, value: T) { 2,479 ( 0.00%) let len = self.len(); . 7,437 ( 0.00%) if new_len > len { 23,187 ( 0.00%) self.extend_with(new_len - len, ExtendElement(value)) . } else { . self.truncate(new_len); . } 2,767 ( 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 { 172 ( 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. 1,156,835 ( 0.00%) fn extend_with>(&mut self, n: usize, mut value: E) { . self.reserve(n); . . unsafe { 18,418 ( 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); . } . 929,090 ( 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 . } 831,533 ( 0.00%) } . } . . 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) { 2,702 ( 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")] 135,996 ( 0.00%) pub fn from_elem(elem: T, n: usize) -> Vec { 920,173 ( 0.00%) ::from_elem(elem, n, Global) 163,913 ( 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] { 31,151,731 ( 0.13%) unsafe { slice::from_raw_parts(self.as_ptr(), self.len) } 1,883 ( 0.00%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl ops::DerefMut for Vec { . fn deref_mut(&mut self) -> &mut [T] { 6,572,711 ( 0.03%) 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))] 1,804,931 ( 0.01%) fn clone(&self) -> Self { . let alloc = self.allocator().clone(); 2 ( 0.00%) <[T]>::to_vec_in(&**self, alloc) 2,219,626 ( 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 { 449,277 ( 0.00%) 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 { 836 ( 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 { 4,504,920 ( 0.02%) >::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 { 1,724,260 ( 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(); 638,671 ( 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> { 20,033 ( 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,248 ( 0.00%) self.iter_mut() . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl Extend for Vec { . #[inline] 11,912 ( 0.00%) fn extend>(&mut self, iter: I) { 2,058,020 ( 0.01%) >::spec_extend(self, iter.into_iter()) 11,912 ( 0.00%) } . . #[inline] . fn extend_one(&mut self, item: T) { 160 ( 0.00%) self.push(item); . } . . #[inline] . fn extend_reserve(&mut self, additional: usize) { . self.reserve(additional); . } . } . -- line 2631 ---------------------------------------- -- 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); . // } 374,615 ( 0.00%) while let Some(element) = iterator.next() { 66,095 ( 0.00%) let len = self.len(); 767,520 ( 0.00%) if len == self.capacity() { 1,740 ( 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 567,752 ( 0.00%) self.set_len(len + 1); . } . } 6,949 ( 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, . { 829 ( 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, . { 9,102 ( 0.00%) let old_len = self.len(); . . // Guard against us getting leaked (leak amplification) . unsafe { . self.set_len(0); . } . 32,144 ( 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 { 2,805,536 ( 0.01%) 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 1,185,375 ( 0.00%) ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len)) . } . // RawVec handles deallocation 3,294,264 ( 0.01%) } . } . . #[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 ---------------------------------------- 4,273,775 ( 0.02%) -------------------------------------------------------------------------------- -- 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. 304,835 ( 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. 1,117,660 ( 0.00%) 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`. 235 ( 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 { 302,794 ( 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 { 589,428 ( 0.00%) assume(!self.ptr.as_ptr().is_null()); . if mem::size_of::() != 0 { 145,290 ( 0.00%) assume(!self.end.is_null()); . } 256,267,684 ( 1.06%) if is_empty!(self) { . None . } else { 7 ( 0.00%) Some(next_unchecked!(self)) . } . } . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 51,488,703 ( 0.21%) let exact = len!(self); . (exact, Some(exact)) . } . . #[inline] . fn count(self) -> usize { . len!(self) . } . . #[inline] . fn nth(&mut self, n: usize) -> Option<$elem> { 47,683 ( 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() { 9,877 ( 0.00%) f(x); . } . } . . // We override the default implementation, which uses `try_fold`, . // because this simple implementation generates less LLVM IR and is . // faster to compile. . #[inline] . fn all(&mut self, mut f: F) -> bool . where . Self: Sized, . F: FnMut(Self::Item) -> bool, . { 6,861 ( 0.00%) while let Some(x) = self.next() { 35,097 ( 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] 160 ( 0.00%) fn any(&mut self, mut f: F) -> bool . where . Self: Sized, . F: FnMut(Self::Item) -> bool, . { 1,035,190 ( 0.00%) while let Some(x) = self.next() { 1,212,251 ( 0.01%) if f(x) { . return true; . } . } . false 160 ( 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

(&mut self, mut predicate: P) -> Option . where . Self: Sized, . P: FnMut(&Self::Item) -> bool, . { 40,741 ( 0.00%) while let Some(x) = self.next() { 170,156 ( 0.00%) if predicate(&x) { . return Some(x); . } . } . None 13,164 ( 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, . { 123,253 ( 0.00%) while let Some(x) = self.next() { 536,282 ( 0.00%) if let Some(y) = f(x) { 85,412 ( 0.00%) return Some(y); . } . } . None 21,049 ( 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() { 974,700 ( 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; 29,590 ( 0.00%) while let Some(x) = self.next_back() { 346,608 ( 0.00%) i -= 1; 283,773 ( 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` 197,467 ( 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 351 ---------------------------------------- . . // 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 { . assume(!self.ptr.as_ptr().is_null()); . if mem::size_of::() != 0 { 50 ( 0.00%) assume(!self.end.is_null()); . } 1,771,902 ( 0.01%) if is_empty!(self) { . None . } else { . Some(next_back_unchecked!(self)) . } . } . } . . #[inline] -- line 369 ---------------------------------------- 16,928,310 ( 0.07%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/mem/maybe_uninit.rs -------------------------------------------------------------------------------- Ir -- line 488 ---------------------------------------- . /// unsafe { Pin::new_unchecked(ref_) } . /// } . /// } . /// ``` . #[stable(feature = "maybe_uninit_write", since = "1.55.0")] . #[rustc_const_unstable(feature = "const_maybe_uninit_write", issue = "63567")] . #[inline(always)] . pub const fn write(&mut self, val: T) -> &mut T { 45,240,838 ( 0.19%) *self = MaybeUninit::new(val); . // SAFETY: We just initialized this value. . unsafe { self.assume_init_mut() } . } . . /// Gets a pointer to the contained value. Reading from this pointer or turning it . /// into a reference is undefined behavior unless the `MaybeUninit` is initialized. . /// Writing to memory that this pointer (non-transitively) points to is undefined behavior . /// (except inside an `UnsafeCell`). -- line 504 ---------------------------------------- -- line 626 ---------------------------------------- . #[inline(always)] . #[rustc_diagnostic_item = "assume_init"] . #[track_caller] . pub const unsafe fn assume_init(self) -> T { . // SAFETY: the caller must guarantee that `self` is initialized. . // This also means that `self` must be a `value` variant. . unsafe { . intrinsics::assert_inhabited::(); 73,920 ( 0.00%) ManuallyDrop::into_inner(self.value) . } . } . . /// Reads the value from the `MaybeUninit` container. The resulting `T` is subject . /// to the usual drop handling. . /// . /// Whenever possible, it is preferable to use [`assume_init`] instead, which . /// prevents duplicating the content of the `MaybeUninit`. -- line 642 ---------------------------------------- -- line 696 ---------------------------------------- . #[rustc_const_unstable(feature = "const_maybe_uninit_assume_init_read", issue = "63567")] . #[inline(always)] . #[track_caller] . pub const unsafe fn assume_init_read(&self) -> T { . // SAFETY: the caller must guarantee that `self` is initialized. . // Reading from `self.as_ptr()` is safe since `self` should be initialized. . unsafe { . intrinsics::assert_inhabited::(); 262 ( 0.00%) self.as_ptr().read() . } . } . . /// Drops the contained value in place. . /// . /// If you have ownership of the `MaybeUninit`, you can also use . /// [`assume_init`] as an alternative. . /// -- line 712 ---------------------------------------- -- line 723 ---------------------------------------- . /// this does not constitute a stable guarantee), because the only . /// requirement the compiler knows about it is that the data pointer must be . /// non-null. Dropping such a `Vec` however will cause undefined . /// behaviour. . /// . /// [`assume_init`]: MaybeUninit::assume_init . /// [`Vec`]: ../../std/vec/struct.Vec.html . #[stable(feature = "maybe_uninit_extra", since = "1.60.0")] 66,891 ( 0.00%) pub unsafe fn assume_init_drop(&mut self) { . // SAFETY: the caller must guarantee that `self` is initialized and . // satisfies all invariants of `T`. . // Dropping the value in place is safe if that is the case. 5 ( 0.00%) unsafe { ptr::drop_in_place(self.as_mut_ptr()) } 32,464 ( 0.00%) } . . /// Gets a shared reference to the contained value. . /// . /// This can be useful when we want to access a `MaybeUninit` that has been . /// initialized but don't have ownership of the `MaybeUninit` (preventing the use . /// of `.assume_init()`). . /// . /// # Safety -- line 744 ---------------------------------------- -------------------------------------------------------------------------------- -- 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 { 2,783,960 ( 0.01%) 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")] 1,160 ( 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. 570 ( 0.00%) match Box::try_new_uninit_in(alloc) { . Ok(m) => m, . Err(_) => handle_alloc_error(layout), . } 2,320 ( 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]> { 105 ( 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), . }; 100 ( 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] 2,399 ( 0.00%) fn clone(&self) -> Self { . // Pre-allocate memory to allow writing the cloned value directly. 1,160 ( 0.00%) let mut boxed = Self::new_uninit_in(self.1.clone()); . unsafe { 3,237,628 ( 0.01%) (**self).write_clone_into_raw(boxed.as_mut_ptr()); . boxed.assume_init() . } 2,700 ( 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,199 ( 0.00%) fn hash(&self, state: &mut H) { 2,398 ( 0.00%) (**self).hash(state); 1,199 ( 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 { 3,695 ( 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 { 468 ( 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 { 297,120 ( 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]> { 4,808 ( 0.00%) fn from_iter>(iter: T) -> Self { . iter.into_iter().collect::>().into_boxed_slice() 5,893 ( 0.00%) } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "box_slice_clone", since = "1.3.0")] . impl Clone for Box<[T], A> { 21,505,915 ( 0.09%) fn clone(&self) -> Self { . let alloc = Box::allocator(self).clone(); 10,752,956 ( 0.04%) self.to_vec_in(alloc).into_boxed_slice() 32,258,872 ( 0.13%) } . . 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 { 8,822 ( 0.00%) &**self . } . } . . #[stable(feature = "box_borrow", since = "1.1.0")] . impl borrow::BorrowMut for Box { . fn borrow_mut(&mut self) -> &mut T { 8,812 ( 0.00%) &mut **self . } . } . . #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")] . impl AsRef for Box { . fn as_ref(&self) -> &T { 4,463 ( 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 ---------------------------------------- 43,209,338 ( 0.18%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/scoped-tls-1.0.0/src/lib.rs -------------------------------------------------------------------------------- Ir -- line 111 ---------------------------------------- . /// }); . /// . /// // Recursive calls restore the previous value. . /// let val = FOO.with(|v| *v); . /// assert_eq!(val, 100); . /// }); . /// # } . /// ``` 8 ( 0.00%) pub fn set(&'static self, t: &T, f: F) -> R . where F: FnOnce() -> R . { . struct Reset { . key: &'static LocalKey>, . val: usize, . } . impl Drop for Reset { 6 ( 0.00%) fn drop(&mut self) { 4 ( 0.00%) self.key.with(|c| c.set(self.val)); 6 ( 0.00%) } . } 2 ( 0.00%) let prev = self.inner.with(|c| { 2 ( 0.00%) let prev = c.get(); . c.set(t as *const T as usize); . prev . }); 6 ( 0.00%) let _reset = Reset { key: self.inner, val: prev }; 3 ( 0.00%) f() 6 ( 0.00%) } . . /// Gets a value out of this scoped variable. . /// . /// This function takes a closure which receives the value of this . /// variable. . /// . /// # Panics . /// -- line 146 ---------------------------------------- -- line 156 ---------------------------------------- . /// . /// # fn main() { . /// FOO.with(|slot| { . /// // work with `slot` . /// # drop(slot); . /// }); . /// # } . /// ``` 13,917,202 ( 0.06%) pub fn with(&'static self, f: F) -> R . where F: FnOnce(&T) -> R . { 3,516,447 ( 0.01%) let val = self.inner.with(|c| c.get()); 7,490,072 ( 0.03%) assert!(val != 0, "cannot access a scoped thread local \ . variable without calling `set` first"); . unsafe { 3,432,975 ( 0.01%) f(&*(val as *const T)) . } 13,897,599 ( 0.06%) } . . /// Test whether this TLS key has been `set` for the current thread. . pub fn is_set(&'static self) -> bool { 6 ( 0.00%) self.inner.with(|c| c.get() != 0) . } . } . . #[cfg(test)] . mod tests { . use std::cell::Cell; . use std::sync::mpsc::{channel, Sender}; . use std::thread; -- line 185 ---------------------------------------- 46,810 ( 0.00%) -------------------------------------------------------------------------------- -- 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 { 4,675,700 ( 0.02%) 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)); 369,826 ( 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::()); 108,361,381 ( 0.45%) 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" . ); . 610,880 ( 0.00%) self.stride += Group::WIDTH; 610,880 ( 0.00%) self.pos += self.stride; 513,579 ( 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. 424,630 ( 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. 918,265 ( 0.00%) return Some(if cap < 4 { 4 } else { 8 }); . } . . // Otherwise require 1/8 buckets to be empty (87.5% load) . // . // Be careful when modifying this, calculate_layout relies on the . // overflow check here. 171,972 ( 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 { 1,110,436 ( 0.00%) if bucket_mask < 8 { . // For tables with 1/2/4/8 buckets, we always reserve one empty slot. . // Keep in mind that the bucket mask is one less than the bucket count. . bucket_mask . } else { . // For larger tables we reserve 12.5% of the slots as empty. 190,038 ( 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 = 857,045 ( 0.00%) size.checked_mul(buckets)?.checked_add(ctrl_align - 1)? & !(ctrl_align - 1); 1,150,256 ( 0.00%) let len = ctrl_offset.checked_add(buckets + Group::WIDTH)?; . . Some(( . unsafe { Layout::from_size_align_unchecked(len, ctrl_align) }, . ctrl_offset, . )) . } . } . -- line 263 ---------------------------------------- -- line 337 ---------------------------------------- . } . } . #[cfg_attr(feature = "inline-more", inline)] . pub unsafe fn drop(&self) { . self.as_ptr().drop_in_place(); . } . #[inline] . pub unsafe fn read(&self) -> T { 3,638 ( 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 { 128,913 ( 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 { 675 ( 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 { 33,370 ( 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")] 66,714 ( 0.00%) pub unsafe fn erase_no_drop(&mut self, item: &Bucket) { 66,714 ( 0.00%) let index = self.bucket_index(item); . self.table.erase(index); 133,428 ( 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. 24,186 ( 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 { 109,242 ( 0.00%) self.erase_no_drop(&item); 3,537 ( 0.00%) item.read() . } . . /// Finds and removes an element from the table, returning it. . #[cfg_attr(feature = "inline-more", inline)] 1,825,770 ( 0.01%) pub fn remove_entry(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option { . // Avoid `Option::map` because it bloats LLVM IR. 3,778 ( 0.00%) match self.find(hash, eq) { 20,027 ( 0.00%) Some(bucket) => Some(unsafe { self.remove(bucket) }), 356,355 ( 0.00%) None => None, . } 2,519,078 ( 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) { 50,790 ( 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) { 1,003,934 ( 0.00%) if additional > self.table.growth_left { . // Avoid `Result::unwrap_or_else` because it bloats LLVM IR. 732,324 ( 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)] 1,686,101 ( 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 . }, . ) . } 1,201,544 ( 0.00%) } . . /// Allocates a new table of a different size and moves the contents of the . /// current table into it. . fn resize( . &mut self, . capacity: usize, . hasher: impl Fn(&T) -> u64, . fallibility: Fallibility, -- line 706 ---------------------------------------- -- line 714 ---------------------------------------- . ) . } . } . . /// Inserts a new element into the table, and returns its raw bucket. . /// . /// This does not check if the given element already exists in the table. . #[cfg_attr(feature = "inline-more", inline)] 6,674,676 ( 0.03%) 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. 18,354 ( 0.00%) let old_ctrl = *self.table.ctrl(index); 4,383,034 ( 0.02%) 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 . } 4,915,476 ( 0.02%) } . . /// 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)] 1,475,720 ( 0.01%) pub fn insert_entry(&mut self, hash: u64, value: T, hasher: impl Fn(&T) -> u64) -> &mut T { 923 ( 0.00%) unsafe { self.insert(hash, value, hasher).as_mut() } 1,106,790 ( 0.00%) } . . /// 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"))] 13,727 ( 0.00%) pub unsafe fn insert_no_grow(&mut self, hash: u64, value: T) -> Bucket { 1,006,233 ( 0.00%) let (index, old_ctrl) = self.table.prepare_insert_slot(hash); 34,956 ( 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. 2,166,831 ( 0.01%) self.table.growth_left -= special_is_empty(old_ctrl) as usize; . . bucket.write(value); 1,729,914 ( 0.01%) self.table.items += 1; . bucket 27,424 ( 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] 16,638 ( 0.00%) pub fn find(&self, hash: u64, mut eq: impl FnMut(&T) -> bool) -> Option> { 10,339 ( 0.00%) let result = self.table.find_inner(hash, &mut |index| unsafe { 83,336 ( 0.00%) eq(self.bucket(index).as_ref()) 1,660 ( 0.00%) }); . . // Avoid `Option::map` because it bloats LLVM IR. . match result { 650 ( 0.00%) Some(index) => Some(unsafe { self.bucket(index) }), . None => None, . } 18,436 ( 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. 5,812,489 ( 0.02%) 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] 8,895 ( 0.00%) pub fn get_mut(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option<&mut T> { . // Avoid `Option::map` because it bloats LLVM IR. 10,315 ( 0.00%) match self.find(hash, eq) { . Some(bucket) => Some(unsafe { bucket.as_mut() }), . None => None, . } 11,860 ( 0.00%) } . . /// Attempts to get mutable references to `N` entries in the table at once. . /// . /// Returns an array of length `N` with the results of each query. . /// . /// At most one mutable reference will be returned to any entry. `None` will be returned if any . /// of the hashes are duplicates. `None` will be returned if the hash is not found. . /// -- line 859 ---------------------------------------- -- line 920 ---------------------------------------- . #[inline] . pub fn len(&self) -> usize { . self.table.items . } . . /// Returns `true` if the table contains no elements. . #[inline] . pub fn is_empty(&self) -> bool { 5,028,728 ( 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 { 5 ( 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()), 295,154 ( 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(); 36,996 ( 0.00%) let allocation = self.into_allocation(); 27,747 ( 0.00%) RawIntoIter { 46,245 ( 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,066 ( 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(( 5,258 ( 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 { 2,133,934 ( 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)] 1,508,854 ( 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()); . } . 350,974 ( 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)); 838,686 ( 0.00%) Ok(Self { . ctrl, 352,231 ( 0.00%) bucket_mask: buckets - 1, . items: 0, . growth_left: bucket_mask_to_capacity(buckets - 1), . alloc, . }) 1,099,090 ( 0.00%) } . . #[inline] 97,582 ( 0.00%) fn fallible_with_capacity( . alloc: A, . table_layout: TableLayout, . capacity: usize, . fallibility: Fallibility, . ) -> Result { 25,150 ( 0.00%) if capacity == 0 { 16,213 ( 0.00%) Ok(Self::new_in(alloc)) . } else { . unsafe { . let buckets = . capacity_to_buckets(capacity).ok_or_else(|| fallibility.capacity_overflow())?; . 684,540 ( 0.00%) let result = Self::new_uninitialized(alloc, table_layout, buckets, fallibility)?; . result.ctrl(0).write_bytes(EMPTY, result.num_ctrl_bytes()); . 54,807 ( 0.00%) Ok(result) . } . } 97,582 ( 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] 356,124 ( 0.00%) unsafe fn prepare_insert_slot(&self, hash: u64) -> (usize, u8) { . let index = self.find_insert_slot(hash); 356,124 ( 0.00%) let old_ctrl = *self.ctrl(index); . self.set_ctrl_h2(index, hash); . (index, old_ctrl) 712,248 ( 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)); 3,033,439 ( 0.01%) if let Some(bit) = group.match_empty_or_deleted().lowest_set_bit() { 8,898,846 ( 0.04%) 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). 4,057,482 ( 0.02%) 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); . 190,152 ( 0.00%) loop { . let group = unsafe { Group::load(self.ctrl(probe_seq.pos)) }; . 12,122,854 ( 0.05%) for bit in group.match_byte(h2_hash) { 26,178,537 ( 0.11%) let index = (probe_seq.pos + bit) & self.bucket_mask; . 19,906,814 ( 0.08%) if likely(eq(index)) { . return Some(index); . } . } . 2,922,601 ( 0.01%) 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. 9 ( 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. 9 ( 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(); 10,821,080 ( 0.04%) 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 { 64,808,486 ( 0.27%) 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) { 5,476,080 ( 0.02%) self.growth_left -= special_is_empty(old_ctrl) as usize; . self.set_ctrl_h2(index, hash); 4,380,864 ( 0.02%) 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; 102 ( 0.00%) probe_index(i) == probe_index(new_i) . } . . /// Sets a control byte to the hash, and possibly also the replicated control byte at . /// the end of the array. . #[inline] . unsafe fn set_ctrl_h2(&self, index: usize, hash: u64) { . self.set_ctrl(index, h2(hash)); . } -- line 1289 ---------------------------------------- -- 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] | . // --------------------------------------------- 8,453,031 ( 0.04%) let index2 = ((index.wrapping_sub(Group::WIDTH)) & self.bucket_mask) + Group::WIDTH; . 2,817,677 ( 0.01%) *self.ctrl(index) = ctrl; 2,818,911 ( 0.01%) *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 { 971,470 ( 0.00%) self.bucket_mask + 1 . } . . #[inline] . fn num_ctrl_bytes(&self) -> usize { 818,079 ( 0.00%) self.bucket_mask + 1 + Group::WIDTH . } . . #[inline] . fn is_empty_singleton(&self) -> bool { 4,100,197 ( 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. 11,943 ( 0.00%) let mut new_table = RawTableInner::fallible_with_capacity( . self.alloc.clone(), . table_layout, . capacity, . fallibility, . )?; 449,589 ( 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_| { 207,145 ( 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. 414,298 ( 0.00%) let new_items = match self.items.checked_add(additional) { . Some(new_items) => new_items, . None => return Err(fallibility.capacity_overflow()), . }; 414,296 ( 0.00%) let full_capacity = bucket_mask_to_capacity(self.bucket_mask); 868,259 ( 0.00%) if new_items <= full_capacity / 2 { . // Rehash in-place without re-allocating if we have plenty of spare . // capacity that is locked up due to DELETED entries. . self.rehash_in_place(hasher, layout.size, drop); 6 ( 0.00%) Ok(()) . } else { . // Otherwise, conservatively resize to at least the next size up . // to avoid churning deletes into frequent rehashes. . self.resize_inner( 207,145 ( 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> { 28,388 ( 0.00%) let mut new_table = self.prepare_resize(layout, capacity, fallibility)?; . . // Copy all elements to the new table. . for i in 0..self.buckets() { 1,713,434 ( 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); . 207,145 ( 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() { 192 ( 0.00%) if *guard.ctrl(i) != DELETED { . continue; . } . . let i_p = guard.bucket_ptr(i, size_of); . . 'inner: loop { . // Hash the current item . let hash = hasher(*guard, i); -- line 1512 ---------------------------------------- -- line 1515 ---------------------------------------- . let new_i = guard.find_insert_slot(hash); . let new_i_p = guard.bucket_ptr(new_i, size_of); . . // Probing works by scanning through all of the control . // bytes in groups, which may not be aligned to the group . // size. If both the new and old position fall within the . // same unaligned group, then there is no benefit in moving . // it and we can just continue to the next item. 34 ( 0.00%) if likely(guard.is_in_same_group(i, new_i, hash)) { . guard.set_ctrl_h2(i, hash); . continue 'outer; . } . . // We are moving the current item to a new position. Write . // our H2 to the control byte of the new position. . let prev_ctrl = guard.replace_ctrl_h2(new_i, hash); . if prev_ctrl == EMPTY { -- line 1531 ---------------------------------------- -- line 1541 ---------------------------------------- . // swapped into the old slot. . debug_assert_eq!(prev_ctrl, DELETED); . ptr::swap_nonoverlapping(i_p, new_i_p, size_of); . continue 'inner; . } . } . } . 9 ( 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( 139,770 ( 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) { 24,747 ( 0.00%) if !self.is_empty_singleton() { . unsafe { . self.ctrl(0).write_bytes(EMPTY, self.num_ctrl_bytes()); . } . } 32,782 ( 0.00%) self.items = 0; 24,747 ( 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))); 311,473 ( 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. 1,245,892 ( 0.01%) let ctrl = if empty_before.leading_zeros() + empty_after.trailing_zeros() >= Group::WIDTH { . DELETED . } else { 1,542,580 ( 0.01%) self.growth_left += 1; . EMPTY . }; . self.set_ctrl(index, ctrl); 1,245,892 ( 0.01%) self.items -= 1; . } . } . . impl Clone for RawTable { 343,784 ( 0.00%) fn clone(&self) -> Self { 43,138 ( 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) . } . } 386,757 ( 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; 270 ( 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)] 2,705,926 ( 0.01%) fn drop(&mut self) { 1,720,908 ( 0.01%) if !self.table.is_empty_singleton() { . unsafe { . self.drop_elements(); . self.free_buckets(); . } . } 2,923,372 ( 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)] 36,996 ( 0.00%) fn into_iter(self) -> RawIntoIter { . unsafe { . let iter = self.iter(); . self.into_iter_from(iter) . } 46,245 ( 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 { 1,082,627 ( 0.00%) if let Some(index) = self.current_group.lowest_set_bit() { 99,998 ( 0.00%) self.current_group = self.current_group.remove_lowest_bit(); 158,711 ( 0.00%) return Some(self.data.next_n(index)); . } . 672,630 ( 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). 20,049 ( 0.00%) self.current_group = Group::load_aligned(self.next_ctrl).match_full(); 10,494 ( 0.00%) self.data = self.data.next_n(Group::WIDTH); 38,740 ( 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) { 16,561 ( 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)] 111,359 ( 0.00%) fn next(&mut self) -> Option> { 1,009,796 ( 0.00%) if let Some(b) = self.iter.next() { 1,603,403 ( 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 . } 222,718 ( 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)] 11,234 ( 0.00%) fn drop(&mut self) { . unsafe { . // Drop all remaining elements . self.iter.drop_elements(); . . // Free the table 66,596 ( 0.00%) if let Some((ptr, layout)) = self.allocation { . self.alloc.deallocate(ptr, layout); . } . } 1,822 ( 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)] 11,811 ( 0.00%) fn next(&mut self) -> Option { 10,362 ( 0.00%) unsafe { Some(self.iter.next()?.read()) } 23,622 ( 0.00%) } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 3,078 ( 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)] 32,568 ( 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. 4,071 ( 0.00%) self.orig_table . .as_ptr() . .copy_from_nonoverlapping(&*self.table, 1); . } 32,568 ( 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 ---------------------------------------- 35,378,697 ( 0.15%) -------------------------------------------------------------------------------- -- 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; 349,587 ( 0.00%) fn to_owned(&self) -> T { 277 ( 0.00%) self.clone() 372,489 ( 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 { 10,910,586 ( 0.05%) match *self { 38,843 ( 0.00%) Borrowed(borrowed) => { 273,009 ( 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")] 768 ( 0.00%) pub fn into_owned(self) -> ::Owned { 3,584 ( 0.00%) match self { 26,146 ( 0.00%) Borrowed(borrowed) => borrowed.to_owned(), 1,056 ( 0.00%) Owned(owned) => owned, . } 864 ( 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 { 33,360,560 ( 0.14%) 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 { 10,144 ( 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 ---------------------------------------- 717,324 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs -------------------------------------------------------------------------------- Ir -- line 12 ---------------------------------------- . use rustc_data_structures::sync::Lrc; . use rustc_macros::HashStable_Generic; . use rustc_span::symbol::{kw, sym}; . use rustc_span::symbol::{Ident, Symbol}; . use rustc_span::{self, edition::Edition, Span, DUMMY_SP}; . use std::borrow::Cow; . use std::{fmt, mem}; . 68,882 ( 0.00%) #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub enum CommentKind { . Line, . Block, . } . 1,769 ( 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. 3,935,840 ( 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, . } . 11,587 ( 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. 1,007,967 ( 0.00%) #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub struct Lit { 2 ( 0.00%) pub kind: LitKind, 2 ( 0.00%) pub symbol: Symbol, 2 ( 0.00%) pub suffix: Option, . } . . impl fmt::Display for Lit { 15 ( 0.00%) fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 27 ( 0.00%) let Lit { kind, symbol, suffix } = *self; . match kind { . Byte => write!(f, "b'{}'", symbol)?, . Char => write!(f, "'{}'", symbol)?, . Str => write!(f, "\"{}\"", symbol)?, . StrRaw(n) => write!( . f, . "r{delim}\"{string}\"{delim}", . delim = "#".repeat(n as usize), -- line 87 ---------------------------------------- -- line 89 ---------------------------------------- . )?, . ByteStr => write!(f, "b\"{}\"", symbol)?, . ByteStrRaw(n) => write!( . f, . "br{delim}\"{string}\"{delim}", . delim = "#".repeat(n as usize), . string = symbol . )?, 9 ( 0.00%) Integer | Float | Bool | Err => write!(f, "{}", symbol)?, . } . 6 ( 0.00%) if let Some(suffix) = suffix { . write!(f, "{}", suffix)?; . } . . Ok(()) 15 ( 0.00%) } . } . . impl LitKind { . /// An English article for the literal token kind. . pub fn article(self) -> &'static str { . match self { . Integer | Err => "an", . _ => "a", -- line 113 ---------------------------------------- -- line 123 ---------------------------------------- . Float => "float", . Str | StrRaw(..) => "string", . ByteStr | ByteStrRaw(..) => "byte string", . Err => "error", . } . } . . crate fn may_have_suffix(self) -> bool { 2 ( 0.00%) matches!(self, Integer | Float | Err) . } . } . . impl Lit { . pub fn new(kind: LitKind, symbol: Symbol, suffix: Option) -> Lit { . Lit { kind, symbol, suffix } 6,519 ( 0.00%) } . } . 1,288 ( 0.00%) pub fn ident_can_begin_expr(name: Symbol, span: Span, is_raw: bool) -> bool { 2,254 ( 0.00%) let ident_token = Token::new(Ident(name, is_raw), span); . 920 ( 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) 1,610 ( 0.00%) } . . fn ident_can_begin_type(name: Symbol, span: Span, is_raw: bool) -> bool { 17,394 ( 0.00%) let ident_token = Token::new(Ident(name, is_raw), span); . 6,440 ( 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) . } . 450,635,626 ( 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, 1,794,411 ( 0.01%) BinOp(BinOpToken), 51 ( 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., `{`). 239,964 ( 0.00%) OpenDelim(DelimToken), . /// A closing delimiter (e.g., `}`). 43,209 ( 0.00%) CloseDelim(DelimToken), . . /* Literals */ 1,474,490 ( 0.01%) Literal(Lit), . . /// Identifier token. . /// Do not forget about `NtIdent` when you want to match on identifiers. . /// It's recommended to use `Token::(ident,uninterpolate,uninterpolated_span)` to . /// treat regular and interpolated identifiers in the same way. 9,973,448 ( 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. 592,785 ( 0.00%) Lifetime(Symbol), . 226,738 ( 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. 24,909 ( 0.00%) DocComment(CommentKind, ast::AttrStyle, Symbol), . . Eof, . } . . // `TokenKind` is used a lot. Make sure it doesn't unintentionally get bigger. . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . rustc_data_structures::static_assert_size!(TokenKind, 16); . 63,466,375 ( 0.26%) #[derive(Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub struct Token { 9,187,406 ( 0.04%) pub kind: TokenKind, 915 ( 0.00%) pub span: Span, . } . . impl TokenKind { . pub fn lit(kind: LitKind, symbol: Symbol, suffix: Option) -> TokenKind { . Literal(Lit::new(kind, symbol, suffix)) 3,495 ( 0.00%) } . . // An approximation to proc-macro-style single-character operators used by rustc parser. . // If the operator token can be broken into two tokens, the first of which is single-character, . // then this function performs that operation, otherwise it returns `None`. 13,770 ( 0.00%) pub fn break_two_token_op(&self) -> Option<(TokenKind, TokenKind)> { 57,488 ( 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), 13,502 ( 0.00%) _ => return None, . }) 13,770 ( 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 { 11,866 ( 0.00%) matches!(self, Gt | Ge | BinOp(Shr) | BinOpEq(Shr)) 2,578 ( 0.00%) } . } . . impl Token { 3,936,917 ( 0.02%) pub fn new(kind: TokenKind, span: Span) -> Self { 11,947,658 ( 0.05%) Token { kind, span } 3,936,917 ( 0.02%) } . . /// Some token that will be thrown away later. 41,341 ( 0.00%) pub fn dummy() -> Self { . Token::new(TokenKind::Question, DUMMY_SP) 41,341 ( 0.00%) } . . /// Recovers a `Token` from an `Ident`. This creates a raw identifier if necessary. . pub fn from_ast_ident(ident: Ident) -> Self { 2,224 ( 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. 64,890 ( 0.00%) pub fn take(&mut self) -> Self { . mem::replace(self, Token::dummy()) 64,890 ( 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 { 5,118 ( 0.00%) match &self.kind { 392 ( 0.00%) Interpolated(nt) => nt.span(), 2,363 ( 0.00%) _ => self.span, . } 2,363 ( 0.00%) } . . pub fn is_op(&self) -> bool { 194,670 ( 0.00%) !matches!( 64,890 ( 0.00%) self.kind, . OpenDelim(..) . | CloseDelim(..) . | Literal(..) . | DocComment(..) . | Ident(..) . | Lifetime(..) . | Interpolated(..) . | Eof . ) 64,890 ( 0.00%) } . . pub fn is_like_plus(&self) -> bool { 72,451 ( 0.00%) matches!(self.kind, BinOp(Plus) | BinOpEq(Plus)) 14,307 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of an expression. 392 ( 0.00%) pub fn can_begin_expr(&self) -> bool { 1,984 ( 0.00%) match self.uninterpolate().kind { 2,898 ( 0.00%) Ident(name, is_raw) => 966 ( 0.00%) ident_can_begin_expr(name, self.span, is_raw), // value name or keyword . OpenDelim(..) | // tuple, array or block . Literal(..) | // literal . Not | // operator not . BinOp(Minus) | // unary minus . BinOp(Star) | // dereference . BinOp(Or) | OrOr | // closure . BinOp(And) | // reference . AndAnd | // double reference . // DotDotDot is no longer supported, but we need some way to display the error . DotDot | DotDotDot | DotDotEq | // range notation . Lt | BinOp(Shl) | // associated path . ModSep | // global path . Lifetime(..) | // labeled loop . Pound => true, // expression attributes 320 ( 0.00%) Interpolated(ref nt) => matches!(**nt, NtLiteral(..) | . NtExpr(..) | . NtBlock(..) | . NtPath(..)), . _ => false, . } 784 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of a type. 23,256 ( 0.00%) pub fn can_begin_type(&self) -> bool { 35,331 ( 0.00%) match self.uninterpolate().kind { 26,091 ( 0.00%) Ident(name, is_raw) => 2,899 ( 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 7,216 ( 0.00%) Interpolated(ref nt) => matches!(**nt, NtTy(..) | NtPath(..)), . _ => false, . } 34,884 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of a const param. . pub fn can_begin_const_arg(&self) -> bool { 14,230 ( 0.00%) match self.kind { . OpenDelim(Brace) => true, 6,808 ( 0.00%) Interpolated(ref nt) => matches!(**nt, NtExpr(..) | NtBlock(..) | NtLiteral(..)), 1,995 ( 0.00%) _ => self.can_begin_literal_maybe_minus(), . } 851 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of a generic bound. . pub fn can_begin_bound(&self) -> bool { . self.is_path_start() . || self.is_lifetime() . || self.is_keyword(kw::For) . || self == &Question . || self == &OpenDelim(Paren) -- line 421 ---------------------------------------- -- line 427 ---------------------------------------- . } . . /// Returns `true` if the token is any literal, a minus (which can prefix a literal, . /// for example a '-42', or one of the boolean idents). . /// . /// In other words, would this token be a valid start of `parse_literal_maybe_minus`? . /// . /// Keep this in sync with and `Lit::from_token`, excluding unary negation. 1,998 ( 0.00%) pub fn can_begin_literal_maybe_minus(&self) -> bool { 18,936 ( 0.00%) match self.uninterpolate().kind { . Literal(..) | BinOp(Minus) => true, 5,576 ( 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, . } 3,996 ( 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. 12,809 ( 0.00%) pub fn uninterpolate(&self) -> Cow<'_, Token> { 33,095,218 ( 0.14%) match &self.kind { 1,099,573 ( 0.00%) Interpolated(nt) => match **nt { 92,882 ( 0.00%) NtIdent(ident, is_raw) => { 232,407 ( 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), . } 12,809 ( 0.00%) } . . /// Returns an identifier if this token is an identifier. 8,003,222 ( 0.03%) pub fn ident(&self) -> Option<(Ident, /* is_raw */ bool)> { . let token = self.uninterpolate(); 16,916,009 ( 0.07%) match token.kind { 28,381,685 ( 0.12%) Ident(name, is_raw) => Some((Ident::new(name, token.span), is_raw)), . _ => None, . } 48,246,352 ( 0.20%) } . . /// Returns a lifetime identifier if this token is a lifetime. 7,809,245 ( 0.03%) pub fn lifetime(&self) -> Option { . let token = self.uninterpolate(); 15,638,792 ( 0.06%) match token.kind { 322,128 ( 0.00%) Lifetime(name) => Some(Ident::new(name, token.span)), . _ => None, . } 54,664,715 ( 0.23%) } . . /// Returns `true` if the token is an identifier. . pub fn is_ident(&self) -> bool { . self.ident().is_some() 7,484 ( 0.00%) } . . /// Returns `true` if the token is a lifetime. 10,151 ( 0.00%) pub fn is_lifetime(&self) -> bool { . self.lifetime().is_some() 20,302 ( 0.00%) } . . /// Returns `true` if the token is an identifier whose name is the given . /// string slice. 4,749 ( 0.00%) pub fn is_ident_named(&self, name: Symbol) -> bool { . self.ident().map_or(false, |(ident, _)| ident.name == name) 9,498 ( 0.00%) } . . /// Returns `true` if the token is an interpolated path. . fn is_path(&self) -> bool { 88,660 ( 0.00%) if let Interpolated(ref nt) = self.kind { 3,402 ( 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 { 4 ( 0.00%) if let Interpolated(ref nt) = self.kind { . if let NtExpr(_) | NtLiteral(_) | NtPath(_) | NtIdent(..) | NtBlock(_) = **nt { . return true; . } . } . . false 2 ( 0.00%) } . . // Is the token an interpolated block (`$b:block`)? . pub fn is_whole_block(&self) -> bool { 656 ( 0.00%) if let Interpolated(ref nt) = self.kind { . if let NtBlock(..) = **nt { . return true; . } . } . false 328 ( 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) . } . 2,856 ( 0.00%) pub fn is_qpath_start(&self) -> bool { 47,520 ( 0.00%) self == &Lt || self == &BinOp(Shl) 192 ( 0.00%) } . 89,328 ( 0.00%) pub fn is_path_start(&self) -> bool { 127,553 ( 0.00%) self == &ModSep . || self.is_qpath_start() . || self.is_path() . || self.is_path_segment_keyword() 16,291 ( 0.00%) || self.is_ident() && !self.is_reserved_ident() 111,660 ( 0.00%) } . . /// Returns `true` if the token is a given keyword, `kw`. 384,714 ( 0.00%) pub fn is_keyword(&self, kw: Symbol) -> bool { . self.is_non_raw_ident_where(|id| id.name == kw) 769,428 ( 0.00%) } . 2,011 ( 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. 2,377 ( 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. 2,382 ( 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. 2,377 ( 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`. 2,011 ( 0.00%) pub fn is_bool_lit(&self) -> bool { 4,022 ( 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. 472 ( 0.00%) pub fn is_non_raw_ident_where(&self, pred: impl FnOnce(Ident) -> bool) -> bool { 2,501,271 ( 0.01%) match self.ident() { 14,190 ( 0.00%) Some((id, false)) => pred(id), . _ => false, . } 590 ( 0.00%) } . 211,170 ( 0.00%) pub fn glue(&self, joint: &Token) -> Option { 105,585 ( 0.00%) let kind = match self.kind { 1,251 ( 0.00%) Eq => match joint.kind { . Eq => EqEq, . Gt => FatArrow, . _ => return None, . }, 1,298 ( 0.00%) Lt => match joint.kind { . Eq => Le, . Lt => BinOp(Shl), . Le => BinOpEq(Shl), . BinOp(Minus) => LArrow, . _ => return None, . }, 5,577 ( 0.00%) Gt => match joint.kind { . Eq => Ge, . Gt => BinOp(Shr), . Ge => BinOpEq(Shr), . _ => return None, . }, 10 ( 0.00%) Not => match joint.kind { . Eq => Ne, . _ => return None, . }, 6,988 ( 0.00%) BinOp(op) => match joint.kind { . Eq => BinOpEq(op), 62 ( 0.00%) BinOp(And) if op == And => AndAnd, 84 ( 0.00%) BinOp(Or) if op == Or => OrOr, 809 ( 0.00%) Gt if op == Minus => RArrow, . _ => return None, . }, 69 ( 0.00%) Dot => match joint.kind { . Dot => DotDot, . DotDot => DotDotDot, . _ => return None, . }, 15 ( 0.00%) DotDot => match joint.kind { . Dot => DotDotDot, . Eq => DotDotEq, . _ => return None, . }, 7,280 ( 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, . }; . 66,716 ( 0.00%) Some(Token::new(kind, self.span.to(joint.span))) 190,053 ( 0.00%) } . } . . impl PartialEq for Token { . fn eq(&self, rhs: &TokenKind) -> bool { 6,229,228 ( 0.03%) self.kind == *rhs . } . } . 1,666 ( 0.00%) #[derive(Clone, Encodable, Decodable)] . /// For interpolation during macro expansion. . pub enum Nonterminal { . NtItem(P), . NtBlock(P), . NtStmt(ast::Stmt), . NtPat(P), 476 ( 0.00%) NtExpr(P), . NtTy(P), . NtIdent(Ident, /* is_raw */ bool), . NtLifetime(Ident), . NtLiteral(P), . /// Stuff inside brackets for attributes . NtMeta(P), . NtPath(ast::Path), . NtVis(ast::Visibility), -- line 686 ---------------------------------------- -- line 711 ---------------------------------------- . Path, . Vis, . TT, . } . . impl NonterminalKind { . /// The `edition` closure is used to get the edition for the given symbol. Doing . /// `span.edition()` is expensive, so we do it lazily. 1,824 ( 0.00%) pub fn from_symbol( . symbol: Symbol, . edition: impl FnOnce() -> Edition, . ) -> Option { 4,324 ( 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, . }) 1,824 ( 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 { 196 ( 0.00%) pub fn span(&self) -> Span { 980 ( 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, 196 ( 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(), . } 392 ( 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 ---------------------------------------- 140,838,026 ( 0.58%) -------------------------------------------------------------------------------- -- 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,881 ( 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); . } . } . } . }; . } . 2,411,432 ( 0.01%) #[derive(Clone)] . pub struct Parser<'a> { 89,954 ( 0.00%) pub sess: &'a ParseSess, . /// The current token. 85,826 ( 0.00%) pub token: Token, . /// The spacing for the current token 42,971 ( 0.00%) pub token_spacing: Spacing, . /// The previous token. 128,739 ( 0.00%) pub prev_token: Token, 43,029 ( 0.00%) pub capture_cfg: bool, 86,116 ( 0.00%) restrictions: Restrictions, 85,942 ( 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, 85,942 ( 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. 85,942 ( 0.00%) unmatched_angle_bracket_count: u32, 128,913 ( 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. 42,971 ( 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` 42,971 ( 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, . } . 175,954 ( 0.00%) #[derive(Clone)] . struct CaptureState { 171,884 ( 0.00%) capturing: Capturing, 42,971 ( 0.00%) replace_ranges: Vec, . inner_attr_ranges: FxHashMap, . } . . impl<'a> Drop for Parser<'a> { . fn drop(&mut self) { 162,880 ( 0.00%) emit_unclosed_delims(&mut self.unclosed_delims, &self.sess); . } . } . 1,097,055 ( 0.00%) #[derive(Clone)] . struct TokenCursor { . frame: TokenCursorFrame, 247,768 ( 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. 81,789 ( 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, . } . 500,966 ( 0.00%) #[derive(Clone)] . struct TokenCursorFrame { 96,447 ( 0.00%) delim: token::DelimToken, . span: DelimSpan, . open_delim: bool, 192,894 ( 0.00%) tree_cursor: tokenstream::Cursor, . close_delim: bool, . } . . impl TokenCursorFrame { . fn new(span: DelimSpan, delim: DelimToken, tts: TokenStream) -> Self { 52,905 ( 0.00%) TokenCursorFrame { . delim, . span, . open_delim: false, 1,849,228 ( 0.01%) tree_cursor: tts.into_trees(), . close_delim: false, . } . } . } . . impl TokenCursor { 200,207,892 ( 0.83%) fn next(&mut self) -> (Token, Spacing) { . loop { 96,204,573 ( 0.40%) let (tree, spacing) = if !self.frame.open_delim { 1,827,367 ( 0.01%) self.frame.open_delim = true; 9,136,835 ( 0.04%) TokenTree::open_tt(self.frame.span, self.frame.delim).into() 196,444,801 ( 0.82%) } else if let Some(tree) = self.frame.tree_cursor.next_with_spacing() { . tree 7,332,106 ( 0.03%) } else if !self.frame.close_delim { 1,825,835 ( 0.01%) self.frame.close_delim = true; 9,129,175 ( 0.04%) TokenTree::close_tt(self.frame.span, self.frame.delim).into() 3,651,278 ( 0.02%) } else if let Some(frame) = self.stack.pop() { 23,733,307 ( 0.10%) self.frame = frame; . continue; . } else { 262,422 ( 0.00%) (TokenTree::Token(Token::new(token::Eof, DUMMY_SP)), Spacing::Alone) . }; . 37,021,318 ( 0.15%) match tree { . TokenTree::Token(token) => { 133,471,928 ( 0.55%) return (token, spacing); . } . TokenTree::Delimited(sp, delim, tts) => { . let frame = TokenCursorFrame::new(sp, delim, tts); . self.stack.push(mem::replace(&mut self.frame, frame)); . } . } . } 133,471,928 ( 0.55%) } . 108,269,200 ( 0.45%) fn next_desugared(&mut self) -> (Token, Spacing) { 32,482,158 ( 0.13%) let (data, attr_style, sp) = match self.next() { 2,097 ( 0.00%) (Token { kind: token::DocComment(_, attr_style, data), span }, _) => { . (data, attr_style, span) . } 54,131,105 ( 0.22%) 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; 115,207 ( 0.00%) for ch in data.as_str().chars() { . count = match ch { . '"' => 1, 260 ( 0.00%) '#' if count > 0 => count + 1, . _ => 0, . }; . num_of_hashes = cmp::max(num_of_hashes, count); . } . 2,796 ( 0.00%) let delim_span = DelimSpan::from_single(sp); 3,495 ( 0.00%) let body = TokenTree::Delimited( . delim_span, . token::Bracket, 8,388 ( 0.00%) [ 4,893 ( 0.00%) TokenTree::token(token::Ident(sym::doc, false), sp), 2,796 ( 0.00%) TokenTree::token(token::Eq, sp), 5,592 ( 0.00%) TokenTree::token(TokenKind::lit(token::StrRaw(num_of_hashes), data, None), sp), . ] . .iter() . .cloned() . .collect::(), 699 ( 0.00%) ); . . self.stack.push(mem::replace( . &mut self.frame, . TokenCursorFrame::new( . delim_span, . token::NoDelim, 699 ( 0.00%) if attr_style == AttrStyle::Inner { . [TokenTree::token(token::Pound, sp), TokenTree::token(token::Not, sp), body] . .iter() . .cloned() . .collect::() . } else { 8,388 ( 0.00%) [TokenTree::token(token::Pound, sp), body] . .iter() . .cloned() . .collect::() . }, . ), . )); . 2,097 ( 0.00%) self.next() 97,442,280 ( 0.40%) } . } . 102,170 ( 0.00%) #[derive(Debug, Clone, PartialEq)] . enum TokenType { 81,736 ( 0.00%) Token(TokenKind), . Keyword(Symbol), . Operator, . Lifetime, . Ident, . Path, . Type, . Const, . } -- line 353 ---------------------------------------- -- line 378 ---------------------------------------- . /// The separator token. . sep: Option, . /// `true` if a trailing separator is allowed. . trailing_sep_allowed: bool, . } . . impl SeqSep { . fn trailing_allowed(t: TokenKind) -> SeqSep { 135 ( 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> { 4,754 ( 0.00%) Some(match token.kind { 9,508 ( 0.00%) _ if token.is_special_ident() => "reserved identifier", 9,508 ( 0.00%) _ if token.is_used_keyword() => "keyword", 9,508 ( 0.00%) _ if token.is_unused_keyword() => "reserved keyword", . token::DocComment(..) => "doc comment", . _ => return None, . }) . } . 16,639 ( 0.00%) pub(super) fn token_descr(token: &Token) -> String { 4,754 ( 0.00%) let token_str = pprust::token_to_string(token); . match token_descr_opt(token) { . Some(prefix) => format!("{} `{}`", prefix, token_str), 16,639 ( 0.00%) _ => format!("`{}`", token_str), . } 11,885 ( 0.00%) } . . impl<'a> Parser<'a> { 148,134 ( 0.00%) pub fn new( . sess: &'a ParseSess, . tokens: TokenStream, . desugar_doc_comments: bool, . subparser_name: Option<&'static str>, . ) -> Self { 10,581 ( 0.00%) let mut start_frame = TokenCursorFrame::new(DelimSpan::dummy(), token::NoDelim, tokens); 21,162 ( 0.00%) start_frame.open_delim = true; . start_frame.close_delim = true; . 328,011 ( 0.00%) let mut parser = Parser { . sess, 10,581 ( 0.00%) token: Token::dummy(), . token_spacing: Spacing::Alone, 10,581 ( 0.00%) prev_token: Token::dummy(), . capture_cfg: false, . restrictions: Restrictions::empty(), . expected_tokens: Vec::new(), . token_cursor: TokenCursor { 63,486 ( 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. 21,162 ( 0.00%) parser.bump(); . . parser 95,229 ( 0.00%) } . . fn next_tok(&mut self, fallback_span: Span) -> (Token, Spacing) { . loop { 99,976,044 ( 0.41%) let (mut next, spacing) = if self.desugar_doc_comments { 43,307,680 ( 0.18%) self.token_cursor.next_desugared() . } else { 17,507,262 ( 0.07%) self.token_cursor.next() . }; 66,650,696 ( 0.28%) 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 16,662,674 ( 0.07%) self.token_cursor.break_last_token = false; 66,650,696 ( 0.28%) if next.span.is_dummy() { . // Tweak the location for better diagnostics, but keep syntactic context intact. 43,252 ( 0.00%) next.span = fallback_span.with_ctxt(next.span.ctxt()); . } 55,466,299 ( 0.23%) if matches!( 33,325,348 ( 0.14%) next.kind, . token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) . ) { . continue; . } 66,645,088 ( 0.28%) 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`. 161,208 ( 0.00%) pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> { 17,912 ( 0.00%) if self.expected_tokens.is_empty() { 21,564 ( 0.00%) if self.token == *t { 17,970 ( 0.00%) self.bump(); . Ok(false) . } else { . self.unexpected_try_recover(t) . } . } else { 171,816 ( 0.00%) self.expect_one_of(slice::from_ref(t), &[]) . } 268,680 ( 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. 196,044 ( 0.00%) pub fn expect_one_of( . &mut self, . edible: &[TokenKind], . inedible: &[TokenKind], . ) -> PResult<'a, bool /* recovered */> { 32,674 ( 0.00%) if edible.contains(&self.token.kind) { 44,874 ( 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) . } 245,055 ( 0.00%) } . . // Public for rustfmt usage. . pub fn parse_ident(&mut self) -> PResult<'a, Ident> { 133,912 ( 0.00%) self.parse_ident_common(true) . } . . fn ident_or_err(&mut self) -> PResult<'a, (Ident, /* is_raw */ bool)> { 104,646 ( 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(), . }) . } . 239,918 ( 0.00%) fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> { 34,274 ( 0.00%) let (ident, is_raw) = self.ident_or_err()?; 205,644 ( 0.00%) if !is_raw && ident.is_reserved() { . let mut err = self.expected_ident_found(); . if recover { . err.emit(); . } else { . return Err(err); . } . } 137,096 ( 0.00%) self.bump(); . Ok(ident) 342,740 ( 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. 2,555,105 ( 0.01%) fn check(&mut self, tok: &TokenKind) -> bool { 1,127,515 ( 0.00%) let is_present = self.token == *tok; 759,816 ( 0.00%) if !is_present { 1,553,724 ( 0.01%) self.expected_tokens.push(TokenType::Token(tok.clone())); . } . is_present 2,555,105 ( 0.01%) } . . /// Consumes a token 'tok' if it exists. Returns whether the given token was present. 184 ( 0.00%) pub fn eat(&mut self, tok: &TokenKind) -> bool { 542,071 ( 0.00%) let is_present = self.check(tok); 356,805 ( 0.00%) if is_present { 93,499 ( 0.00%) self.bump() . } . is_present 230 ( 0.00%) } . . /// If the next token is the given keyword, returns `true` without eating it. . /// An expectation is also added for diagnostics purposes. 241,775 ( 0.00%) fn check_keyword(&mut self, kw: Symbol) -> bool { 40,270 ( 0.00%) self.expected_tokens.push(TokenType::Keyword(kw)); 1,290,559 ( 0.01%) self.token.is_keyword(kw) . } . . /// If the next token is the given keyword, eats it and returns `true`. . /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes. . // Public for rustfmt usage. 279,240 ( 0.00%) pub fn eat_keyword(&mut self, kw: Symbol) -> bool { 225,508 ( 0.00%) if self.check_keyword(kw) { 16,458 ( 0.00%) self.bump(); . true . } else { . false . } 279,240 ( 0.00%) } . . fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool { 39,540 ( 0.00%) if self.token.is_keyword(kw) { 7,287 ( 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. 4,815 ( 0.00%) fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> { . if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) } 3,852 ( 0.00%) } . . /// Is the given keyword `kw` followed by a non-reserved identifier? 123,144 ( 0.00%) fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool { 61,572 ( 0.00%) self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()) 138,537 ( 0.00%) } . 213,234 ( 0.00%) fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool { 75,822 ( 0.00%) if ok { . true . } else { 53,192 ( 0.00%) self.expected_tokens.push(typ); . false . } 213,234 ( 0.00%) } . . fn check_ident(&mut self) -> bool { 26,839 ( 0.00%) self.check_or_expected(self.token.is_ident(), TokenType::Ident) . } . 73,508 ( 0.00%) fn check_path(&mut self) -> bool { 164,144 ( 0.00%) self.check_or_expected(self.token.is_path_start(), TokenType::Path) 91,885 ( 0.00%) } . . fn check_type(&mut self) -> bool { 26,344 ( 0.00%) self.check_or_expected(self.token.can_begin_type(), TokenType::Type) . } . . fn check_const_arg(&mut self) -> bool { 22,768 ( 0.00%) self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const) . } . 20,673 ( 0.00%) fn check_inline_const(&self, dist: usize) -> bool { 11,485 ( 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, . }) 20,673 ( 0.00%) } . . /// Checks to see if the next token is either `+` or `+=`. . /// Otherwise returns `false`. . fn check_plus(&mut self) -> bool { 24,144 ( 0.00%) self.check_or_expected( 12,072 ( 0.00%) self.token.is_like_plus(), 12,072 ( 0.00%) TokenType::Token(token::BinOp(token::Plus)), . ) . } . . /// Eats the expected token if it's present possibly breaking . /// compound tokens like multi-character operators in process. . /// Returns `true` if the token was eaten. 270,480 ( 0.00%) fn break_and_eat(&mut self, expected: TokenKind) -> bool { 157,780 ( 0.00%) if self.token.kind == expected { 17,540 ( 0.00%) self.bump(); . return true; . } 68,850 ( 0.00%) match self.token.kind.break_two_token_op() { 1,848 ( 0.00%) Some((first, second)) if first == expected => { 1,044 ( 0.00%) let first_span = self.sess.source_map().start_point(self.token.span); 1,305 ( 0.00%) let second_span = self.token.span.with_lo(first_span.hi()); 2,349 ( 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` 261 ( 0.00%) self.token_cursor.break_last_token = true; . // Use the spacing of the glued token as the spacing . // of the unglued second token. 3,654 ( 0.00%) self.bump_with((Token::new(second, second_span), self.token_spacing)); . true . } . _ => { 40,527 ( 0.00%) self.expected_tokens.push(TokenType::Token(expected)); . false . } . } 256,903 ( 0.00%) } . . /// Eats `+` possibly breaking tokens like `+=` in process. . fn eat_plus(&mut self) -> bool { 4,216 ( 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, ()> { 9,324 ( 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, ()> { 270 ( 0.00%) if self.break_and_eat(token::BinOp(token::Or)) { Ok(()) } else { self.unexpected() } . } . . /// Eats `<` possibly breaking tokens like `<<` in process. 15,552 ( 0.00%) fn eat_lt(&mut self) -> bool { 53,508 ( 0.00%) let ate = self.break_and_eat(token::Lt); 35,290 ( 0.00%) if ate { . // See doc comment for `unmatched_angle_bracket_count`. 14,636 ( 0.00%) self.unmatched_angle_bracket_count += 1; 15,688 ( 0.00%) self.max_angle_bracket_count += 1; . debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count); . } . ate 15,552 ( 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, ()> { 21,378 ( 0.00%) if self.break_and_eat(token::Gt) { . // See doc comment for `unmatched_angle_bracket_count`. 10,689 ( 0.00%) if self.unmatched_angle_bracket_count > 0 { 7,126 ( 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 { 33,012 ( 0.00%) TokenExpectType::Expect => self.check(k), 675 ( 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) { 29,911 ( 0.00%) if let token::CloseDelim(..) | token::Eof = self.token.kind { . break; . } 21,819 ( 0.00%) if let Some(ref t) = sep.sep { 27,079 ( 0.00%) if first { . first = false; . } else { 11,599 ( 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; . } . } . } . } . } . } 10,810 ( 0.00%) if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) { . trailing = true; . break; . } . 8,635 ( 0.00%) let t = f(self)?; 11,923 ( 0.00%) v.push(t); . } . 20,076 ( 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)> { 21,337 ( 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. 25,790 ( 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 */)> { 12,803 ( 0.00%) let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?; 7,093 ( 0.00%) if !recovered { . self.eat(ket); . } 31,793 ( 0.00%) Ok((val, trailing)) 20,632 ( 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,378 ( 0.00%) self.expect(bra)?; 20,632 ( 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( 4,879 ( 0.00%) &token::OpenDelim(delim), 7,188 ( 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. 216,599,929 ( 0.90%) fn bump_with(&mut self, (next_token, next_spacing): (Token, Spacing)) { . // Bumping after EOF is a bad sign, usually an infinite loop. 99,969,198 ( 0.41%) 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. 66,646,132 ( 0.28%) self.prev_token = mem::replace(&mut self.token, next_token); 16,661,533 ( 0.07%) self.token_spacing = next_spacing; . . // Diagnostics. 16,661,533 ( 0.07%) self.expected_tokens.clear(); . } . . /// Advance the parser by one token. 133,290,176 ( 0.55%) pub fn bump(&mut self) { 66,645,088 ( 0.28%) let next_token = self.next_tok(self.token.span); 99,967,632 ( 0.41%) self.bump_with(next_token); 133,290,176 ( 0.55%) } . . /// Look-ahead `dist` tokens of `self.token` and get access to that token there. . /// When `dist == 0` then the current token is looked at. 280 ( 0.00%) pub fn look_ahead(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R { 11,536 ( 0.00%) if dist == 0 { 4,398 ( 0.00%) return looker(&self.token); . } . 51,933 ( 0.00%) let frame = &self.token_cursor.frame; 55,933 ( 0.00%) if frame.delim != DelimToken::NoDelim { . let all_normal = (0..dist).all(|i| { 111,546 ( 0.00%) let token = frame.tree_cursor.look_ahead(i); 146,110 ( 0.00%) !matches!(token, Some(TokenTree::Delimited(_, DelimToken::NoDelim, _))) . }); . if all_normal { 182,635 ( 0.00%) return match frame.tree_cursor.look_ahead(dist - 1) { 62,918 ( 0.00%) Some(tree) => match tree { 29,088 ( 0.00%) TokenTree::Token(token) => looker(token), . TokenTree::Delimited(dspan, delim, _) => { 21,262 ( 0.00%) looker(&Token::new(token::OpenDelim(*delim), dspan.open)) . } . }, 34,174 ( 0.00%) None => looker(&Token::new(token::CloseDelim(frame.delim), frame.span.close)), . }; . } . } . . let mut cursor = self.token_cursor.clone(); . let mut i = 0; 20,082 ( 0.00%) let mut token = Token::dummy(); 16,324 ( 0.00%) while i < dist { 149,982 ( 0.00%) token = cursor.next().0; 64,366 ( 0.00%) if matches!( 40,869 ( 0.00%) token.kind, . token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) . ) { . continue; . } 8,530 ( 0.00%) i += 1; . } 1,320 ( 0.00%) return looker(&token); 270 ( 0.00%) } . . /// Returns whether any of the given keywords are `dist` tokens ahead of the current one. 42,876 ( 0.00%) fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool { 12,228 ( 0.00%) self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw))) 42,876 ( 0.00%) } . . /// Parses asyncness: `async` or nothing. . fn parse_asyncness(&mut self) -> Async { . if self.eat_keyword(kw::Async) { 355 ( 0.00%) 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. 3,778 ( 0.00%) fn parse_unsafety(&mut self) -> Unsafe { . if self.eat_keyword(kw::Unsafe) { 105 ( 0.00%) Unsafe::Yes(self.prev_token.uninterpolated_span()) . } else { . Unsafe::No . } 15,112 ( 0.00%) } . . /// Parses constness: `const` or nothing. 79,224 ( 0.00%) fn parse_constness(&mut self) -> Const { . // Avoid const blocks to be parsed as const items 28,135 ( 0.00%) if self.look_ahead(1, |t| t != &token::OpenDelim(DelimToken::Brace)) . && self.eat_keyword(kw::Const) . { 245 ( 0.00%) Const::Yes(self.prev_token.uninterpolated_span()) . } else { . Const::No . } 138,642 ( 0.00%) } . . /// Parses inline const expressions. . fn parse_const_block(&mut self, span: Span, pat: bool) -> PResult<'a, P> { . if pat { . self.sess.gated_spans.gate(sym::inline_const_pat, span); . } else { . self.sess.gated_spans.gate(sym::inline_const, span); . } -- line 1104 ---------------------------------------- -- line 1108 ---------------------------------------- . id: DUMMY_NODE_ID, . value: self.mk_expr(blk.span, ExprKind::Block(blk, None), AttrVec::new()), . }; . let blk_span = anon_const.value.span; . Ok(self.mk_expr(span.to(blk_span), ExprKind::ConstBlock(anon_const), AttrVec::new())) . } . . /// Parses mutability (`mut` or nothing). 8 ( 0.00%) fn parse_mutability(&mut self) -> Mutability { . if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not } 3,129 ( 0.00%) } . . /// Possibly parses mutability (`const` or `mut`). 90 ( 0.00%) fn parse_const_or_mut(&mut self) -> Option { . if self.eat_keyword(kw::Mut) { . Some(Mutability::Mut) . } else if self.eat_keyword(kw::Const) { . Some(Mutability::Not) . } else { . None . } 90 ( 0.00%) } . . fn parse_field_name(&mut self) -> PResult<'a, Ident> { 1,188 ( 0.00%) if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind . { . self.expect_no_suffix(self.token.span, "a tuple index", suffix); . self.bump(); . Ok(Ident::new(symbol, self.prev_token.span)) . } else { 1,782 ( 0.00%) self.parse_ident_common(true) . } . } . . fn parse_mac_args(&mut self) -> PResult<'a, P> { 12,293 ( 0.00%) self.parse_mac_args_common(true).map(P) . } . . fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> { 8,199 ( 0.00%) self.parse_mac_args_common(false) . } . 62,658 ( 0.00%) fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> { 55,696 ( 0.00%) Ok( 43,038 ( 0.00%) if self.check(&token::OpenDelim(DelimToken::Paren)) 6,186 ( 0.00%) || self.check(&token::OpenDelim(DelimToken::Bracket)) 6,156 ( 0.00%) || self.check(&token::OpenDelim(DelimToken::Brace)) . { 24,468 ( 0.00%) match self.parse_token_tree() { 30,585 ( 0.00%) TokenTree::Delimited(dspan, delim, tokens) => . // We've confirmed above that there is a delimiter so unwrapping is OK. . { 12,234 ( 0.00%) MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens) . } . _ => unreachable!(), . } 1,690 ( 0.00%) } else if !delimited_only { . if self.eat(&token::Eq) { 724 ( 0.00%) let eq_span = self.prev_token.span; . . // Collect tokens because they are used during lowering to HIR. 724 ( 0.00%) let expr = self.parse_expr_force_collect()?; 724 ( 0.00%) let span = expr.span; . 3,620 ( 0.00%) let token_kind = token::Interpolated(Lrc::new(token::NtExpr(expr))); 6,516 ( 0.00%) MacArgs::Eq(eq_span, Token::new(token_kind, span)) . } else { . MacArgs::Empty . } . } else { . return self.unexpected(); . }, . ) 48,734 ( 0.00%) } . . fn parse_or_use_outer_attributes( . &mut self, . already_parsed_attrs: Option, . ) -> PResult<'a, AttrWrapper> { 22,348 ( 0.00%) if let Some(attrs) = already_parsed_attrs { . Ok(attrs) . } else { 12,640 ( 0.00%) self.parse_outer_attributes() . } . } . . /// Parses a single token tree from the input. 42,876,176 ( 0.18%) pub(crate) fn parse_token_tree(&mut self) -> TokenTree { 34,243,958 ( 0.14%) 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. 33,829,492 ( 0.14%) 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. 22,130,688 ( 0.09%) 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; 1,636,348 ( 0.01%) let stream = frame.tree_cursor.stream.clone(); 1,636,348 ( 0.01%) let span = frame.span; 818,174 ( 0.00%) let delim = frame.delim; . // Consume close delimiter 1,636,348 ( 0.01%) self.bump(); 4,090,870 ( 0.02%) TokenTree::Delimited(span, delim, stream) . } . token::CloseDelim(_) | token::Eof => unreachable!(), . _ => { 9,082,696 ( 0.04%) self.bump(); 22,706,740 ( 0.09%) TokenTree::Token(self.prev_token.clone()) . } . } 37,516,654 ( 0.16%) } . . /// 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 { 8,109 ( 0.00%) let old = self.restrictions; 10,031 ( 0.00%) self.restrictions = res; . let res = f(self); 9,955 ( 0.00%) self.restrictions = old; . res . } . 95,936 ( 0.00%) fn is_crate_vis(&self) -> bool { 59,960 ( 0.00%) self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep) 107,928 ( 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. 122,840 ( 0.00%) pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> { 41,446 ( 0.00%) maybe_whole!(self, NtVis, |x| x); . 10,628 ( 0.00%) self.expected_tokens.push(TokenType::Keyword(kw::Crate)); 42,512 ( 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". 9,854 ( 0.00%) return Ok(Visibility { 29,562 ( 0.00%) span: self.token.span.shrink_to_lo(), . kind: VisibilityKind::Inherited, . tokens: None, . }); . } 774 ( 0.00%) let lo = self.prev_token.span; . 3,870 ( 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. 1,781 ( 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)`. 519 ( 0.00%) self.bump(); // `(` 346 ( 0.00%) self.bump(); // `crate` 519 ( 0.00%) self.expect(&token::CloseDelim(token::Paren))?; // `)` 173 ( 0.00%) let vis = VisibilityKind::Crate(CrateSugar::PubCrate); . return Ok(Visibility { 519 ( 0.00%) span: lo.to(self.prev_token.span), . kind: vis, . tokens: None, . }); 224 ( 0.00%) } 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` . self.expect(&token::CloseDelim(token::Paren))?; // `)` . let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID }; . return Ok(Visibility { . span: lo.to(self.prev_token.span), . kind: vis, . tokens: None, . }); 128 ( 0.00%) } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) 160 ( 0.00%) && self.is_keyword_ahead(1, &[kw::Super, kw::SelfLower]) . { . // Parse `pub(self)` or `pub(super)`. 96 ( 0.00%) self.bump(); // `(` 32 ( 0.00%) let path = self.parse_path(PathStyle::Mod)?; // `super`/`self` 96 ( 0.00%) self.expect(&token::CloseDelim(token::Paren))?; // `)` 352 ( 0.00%) let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID }; . return Ok(Visibility { 128 ( 0.00%) span: lo.to(self.prev_token.span), . kind: vis, . tokens: None, . }); . } 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. . } . } . 1,707 ( 0.00%) Ok(Visibility { span: lo, kind: VisibilityKind::Public, tokens: None }) 110,556 ( 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 { 959 ( 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, . } . } . 9,130 ( 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, 1,814 ( 0.00%) |this, _attrs| Ok((f(this)?, TrailingToken::None)), . ) 9,130 ( 0.00%) } . . /// `::{` or `::*` 265,736 ( 0.00%) fn is_import_coupler(&mut self) -> bool { 132,868 ( 0.00%) self.check(&token::ModSep) . && self.look_ahead(1, |t| { 95,272 ( 0.00%) *t == token::OpenDelim(token::Brace) || *t == token::BinOp(token::Star) . }) 263,808 ( 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) . } . 428,416 ( 0.00%) pub fn emit_unclosed_delims(unclosed_delims: &mut Vec, sess: &ParseSess) { 214,208 ( 0.00%) *sess.reached_eof.borrow_mut() |= . unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none()); 214,208 ( 0.00%) for unmatched in unclosed_delims.drain(..) { . if let Some(mut e) = make_unclosed_delims_error(unmatched, sess) { . e.emit(); . } . } 428,416 ( 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 71 ( 0.00%) #[derive(Debug, Clone)] . pub enum FlatToken { . /// A token - this holds both delimiter (e.g. '{' and '}') . /// and non-delimiter tokens . Token(Token), . /// Holds the `AttributesData` for an AST node. The . /// `AttributesData` is inserted directly into the . /// constructed `AttrAnnotatedTokenStream` as . /// an `AttrAnnotatedTokenTree::Attributes` -- line 1481 ---------------------------------------- 57,067,292 ( 0.24%) -------------------------------------------------------------------------------- -- 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. 53,564,386 ( 0.22%) #[derive(Clone)] . enum TokenTreeOrTokenTreeSlice<'tt> { . Tt(TokenTree), 12,994,325 ( 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 { 105,295,280 ( 0.44%) match *self { 3,385,786 ( 0.01%) TtSeq(ref v) => v.len(), . Tt(ref tt) => tt.len(), . } . } . . /// The `index`-th token tree of `self`. . fn get_tt(&self, index: usize) -> TokenTree { 19,957,495 ( 0.08%) match *self { 537,144 ( 0.00%) TtSeq(ref v) => v[index].clone(), 53,002,319 ( 0.22%) 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. 7,620,146 ( 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. 3,810,073 ( 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. 252,694,419 ( 1.05%) #[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 5,376,477 ( 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`. 21,505,908 ( 0.09%) 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]`. 5,376,477 ( 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. 5,376,477 ( 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. 5,376,477 ( 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. 10,752,954 ( 0.04%) 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) { 42,954,160 ( 0.18%) 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. 21,505,908 ( 0.09%) fn clone(&self) -> Self { 10,752,954 ( 0.04%) MatcherPosHandle::Box(match *self { 11,278,713 ( 0.05%) MatcherPosHandle::Ref(ref r) => Box::new((**r).clone()), . MatcherPosHandle::Box(ref b) => b.clone(), . }) 32,258,862 ( 0.13%) } . } . . 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 { 3,090,900 ( 0.01%) ms.iter().fold(0, |count, elt| { 1,545,450 ( 0.01%) count 4,636,350 ( 0.02%) + match *elt { 351,994 ( 0.00%) TokenTree::Sequence(_, ref seq) => seq.num_captures, 194,917 ( 0.00%) TokenTree::Delimited(_, ref delim) => count_names(&delim.tts), . TokenTree::MetaVar(..) => 0, . TokenTree::MetaVarDecl(..) => 1, . TokenTree::Token(..) => 0, . } 3,863,625 ( 0.02%) }) . } . . /// `len` `Vec`s (initially shared and empty) that will store matches of metavars. . fn create_matches(len: usize) -> Box<[Lrc]> { 210,495 ( 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); 847,350 ( 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. 17,452 ( 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`. 523,930 ( 0.00%) fn n_rec>( . sess: &ParseSess, . m: &TokenTree, . res: &mut I, . ret_val: &mut FxHashMap, . ) -> Result<(), (rustc_span::Span, String)> { 269,744 ( 0.00%) match *m { . TokenTree::Sequence(_, ref seq) => { 11,464 ( 0.00%) for next_m in &seq.tts { 88,056 ( 0.00%) n_rec(sess, next_m, res.by_ref(), ret_val)? . } . } . TokenTree::Delimited(_, ref delim) => { 8,232 ( 0.00%) for next_m in &delim.tts { 56,436 ( 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())); . } . } 94,782 ( 0.00%) TokenTree::MetaVarDecl(sp, bind_name, _) => match ret_val 63,188 ( 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(..) => (), . } . 47,630 ( 0.00%) Ok(()) 381,040 ( 0.00%) } . . let mut ret_val = FxHashMap::default(); . for m in ms { 208,954 ( 0.00%) match n_rec(sess, m, res.by_ref(), &mut ret_val) { . Ok(_) => {} . Err((sp, msg)) => return Error(sp, msg), . } . } . 37,125 ( 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 { 19,814,543 ( 0.08%) if let (Some((ident1, is_raw1)), Some((ident2, is_raw2))) = (t1.ident(), t2.ident()) { 55,530 ( 0.00%) ident1.name == ident2.name && is_raw1 == is_raw2 27,324,577 ( 0.11%) } else if let (Some(ident1), Some(ident2)) = (t1.lifetime(), t2.lifetime()) { . ident1.name == ident2.name . } else { 11,709,654 ( 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. 65,120,988 ( 0.27%) 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. 204,633,863 ( 0.85%) while item.idx >= item.top_elts.len() { 38,202 ( 0.00%) match item.stack.pop() { . Some(MatcherTtFrame { elts, idx }) => { 171,909 ( 0.00%) item.top_elts = elts; 76,404 ( 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`. 38,044,215 ( 0.16%) 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. 6,918,486 ( 0.03%) 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. 10,709,314 ( 0.04%) 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` 10,708,134 ( 0.04%) for idx in item.match_lo..item.match_hi { 26,780,465 ( 0.11%) let sub = item.matches[idx].clone(); 16,068,279 ( 0.07%) new_pos.push_match(idx, MatchedSeq(sub)); . } . . // Move the "dot" past the repetition in `up` 10,707,664 ( 0.04%) new_pos.match_cur = item.match_hi; 32,124,402 ( 0.13%) new_pos.idx += 1; . cur_items.push(new_pos); . } . . // Check if we need a separator. 5,354,067 ( 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. 1,758 ( 0.00%) if item.sep.as_ref().map_or(false, |sep| token_name_eq(token, sep)) { 4,130 ( 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. 5,353,778 ( 0.02%) else if item.seq_op != Some(mbe::KleeneOp::ZeroOrOne) { 10,705,826 ( 0.04%) item.match_cur = item.match_lo; 21,411,652 ( 0.09%) 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. 97,878,630 ( 0.41%) match item.top_elts.get_tt(idx) { . // Need to descend into a sequence 99,203 ( 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. 41,088 ( 0.00%) if seq.kleene.op == mbe::KleeneOp::ZeroOrMore . || seq.kleene.op == mbe::KleeneOp::ZeroOrOne . { 40,224 ( 0.00%) let mut new_item = item.clone(); 80,448 ( 0.00%) new_item.match_cur += seq.num_captures; 100,560 ( 0.00%) new_item.idx += 1; 120,672 ( 0.00%) for idx in item.match_cur..item.match_cur + seq.num_captures { 60,144 ( 0.00%) new_item.push_match(idx, MatchedSeq(Lrc::new(smallvec![]))); . } . cur_items.push(new_item); . } . 20,544 ( 0.00%) let matches = create_matches(item.matches.len()); 246,528 ( 0.00%) cur_items.push(MatcherPosHandle::Box(Box::new(MatcherPos { 20,544 ( 0.00%) stack: smallvec![], . sep: seq.separator.clone(), 20,544 ( 0.00%) seq_op: Some(seq.kleene.op), . idx: 0, 102,720 ( 0.00%) matches, 41,088 ( 0.00%) match_lo: item.match_cur, . match_cur: item.match_cur, 41,088 ( 0.00%) match_hi: item.match_cur + seq.num_captures, . up: Some(item), 143,808 ( 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. 26,905,540 ( 0.11%) 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. 103,015 ( 0.00%) seq @ (TokenTree::Delimited(..) . | TokenTree::Token(Token { kind: DocComment(..), .. })) => { . let lower_elts = mem::replace(&mut item.top_elts, Tt(seq)); 20,603 ( 0.00%) let idx = item.idx; 144,221 ( 0.00%) item.stack.push(MatcherTtFrame { elts: lower_elts, idx }); 82,412 ( 0.00%) item.idx = 0; . cur_items.push(item); . } . . // We just matched a normal token. We can just advance the parser. 8,267,909 ( 0.03%) TokenTree::Token(t) if token_name_eq(&t, token) => { 647,703 ( 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(..) => {} . } 50,645,296 ( 0.21%) } 18,682,316 ( 0.08%) } . . // 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. 564,900 ( 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); 282,450 ( 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(); 5,511,504 ( 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 5,511,504 ( 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. 27,557,520 ( 0.11%) if parser.token == token::Eof { 16,634 ( 0.00%) if eof_items.len() == 1 { . let matches = 24,047 ( 0.00%) eof_items[0].matches.iter_mut().map(|dv| Lrc::make_mut(dv).pop().unwrap()); 12,375 ( 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 { 603 ( 0.00%) return Failure( 201 ( 0.00%) Token::new( . token::Eof, 268 ( 0.00%) if parser.token.span.is_dummy() { . parser.token.span . } else { . parser.token.span.shrink_to_hi() . }, . ), . "missing tokens in macro arguments", . ); . } . } . // Performance hack: eof_items may share matchers via Rc with other things that we want . // to modify. Dropping eof_items now may drop these refcounts to 1, preventing an . // unnecessary implicit clone later in Rc::make_mut. 22,029,248 ( 0.09%) 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. 16,666,849 ( 0.07%) if bb_items.is_empty() && next_items.is_empty() { 679,874 ( 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. 21,449,596 ( 0.09%) 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 277,845 ( 0.00%) cur_items.extend(next_items.drain(..)); 92,615 ( 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); . 10,724,798 ( 0.04%) let mut item = bb_items.pop().unwrap(); 42,883,526 ( 0.18%) if let TokenTree::MetaVarDecl(span, _, Some(kind)) = item.top_elts.get_tt(item.idx) { 5,362,399 ( 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. 32,174,749 ( 0.13%) 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; . } 32,174,394 ( 0.13%) Ok(nt) => nt, . }; 21,449,596 ( 0.09%) item.push_match(match_cur, MatchedNonterminal(Lrc::new(nt))); 21,449,596 ( 0.09%) item.idx += 1; 32,174,394 ( 0.13%) item.match_cur += 1; . } else { . unreachable!() . } . cur_items.push(item); . } . 10,910,028 ( 0.05%) assert!(!cur_items.is_empty()); . } 508,410 ( 0.00%) } 195,514,554 ( 0.81%) -------------------------------------------------------------------------------- -- 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. . /// 34,593,042 ( 0.14%) #[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 { 23,246 ( 0.00%) base_or_index: u32, 8,290 ( 0.00%) len_or_tag: u16, 12,247 ( 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 { 3,640,926 ( 0.02%) if lo > hi { . std::mem::swap(&mut lo, &mut hi); . } . 7,281,693 ( 0.03%) let (base, len, ctxt2) = (lo.0, hi.0 - lo.0, ctxt.as_u32()); . 32,447,639 ( 0.13%) 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 = 880 ( 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 } . } 11,119,096 ( 0.05%) } . . #[inline] . pub fn data(self) -> SpanData { . let data = self.data_untracked(); 2,296 ( 0.00%) 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 { 96,982,589 ( 0.40%) 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), 90,658,801 ( 0.38%) 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); 4,206 ( 0.00%) let index = self.base_or_index; 23,978 ( 0.00%) with_span_interner(|interner| interner.spans[index as usize]) . } 1,826,556 ( 0.01%) } . } . 4 ( 0.00%) #[derive(Default)] . pub struct SpanInterner { . spans: FxIndexSet, . } . . impl SpanInterner { 249 ( 0.00%) fn intern(&mut self, span_data: &SpanData) -> u32 { 332 ( 0.00%) let (index, _) = self.spans.insert_full(*span_data); . index as u32 332 ( 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())) . } 41,940,035 ( 0.17%) -------------------------------------------------------------------------------- -- 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 { 435,440 ( 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 { 75,785 ( 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, . { 6,608,986 ( 0.03%) fn into(self) -> U { 111,050,438 ( 0.46%) U::from(self) 6,615,996 ( 0.03%) } . } . . // 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 ---------------------------------------- -- line 573 ---------------------------------------- . #[rustc_const_unstable(feature = "const_convert", issue = "88674")] . impl const TryInto for T . where . U: ~const TryFrom, . { . type Error = U::Error; . . fn try_into(self) -> Result { 568 ( 0.00%) U::try_from(self) . } . } . . // Infallible conversions are semantically equivalent to fallible conversions . // with an uninhabited error type. . #[stable(feature = "try_from", since = "1.34.0")] . #[rustc_const_unstable(feature = "const_convert", issue = "88674")] . impl const TryFrom for T -- line 589 ---------------------------------------- 150,457 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/iter/range.rs -------------------------------------------------------------------------------- Ir -- line 198 ---------------------------------------- . } . . #[inline] . #[allow(arithmetic_overflow)] . #[rustc_inherit_overflow_checks] . fn forward(start: Self, n: usize) -> Self { . // In debug builds, trigger a panic on overflow. . // This should optimize completely out in release builds. 46,340 ( 0.00%) if Self::forward_checked(start, n).is_none() { . let _ = Self::MAX + 1; . } . // Do wrapping math to allow e.g. `Step::forward(-128i8, 255)`. . start.wrapping_add(n as Self) . } . . #[inline] . #[allow(arithmetic_overflow)] -- line 214 ---------------------------------------- -- line 613 ---------------------------------------- . . if taken < n { Err(taken) } else { Ok(()) } . } . } . . impl RangeIteratorImpl for ops::Range { . #[inline] . fn spec_next(&mut self) -> Option { 18,431,951 ( 0.08%) if self.start < self.end { . // SAFETY: just checked precondition . let n = unsafe { Step::forward_unchecked(self.start.clone(), 1) }; . Some(mem::replace(&mut self.start, n)) . } else { . None . } . } . -- line 629 ---------------------------------------- -- line 657 ---------------------------------------- . // Otherwise 0 is returned which always safe to use. . self.start = unsafe { Step::forward_unchecked(self.start.clone(), taken) }; . . if taken < n { Err(taken) } else { Ok(()) } . } . . #[inline] . fn spec_next_back(&mut self) -> Option { 774,204 ( 0.00%) if self.start < self.end { . // SAFETY: just checked precondition . self.end = unsafe { Step::backward_unchecked(self.end.clone(), 1) }; . Some(self.end.clone()) . } else { . None . } . } . -- line 673 ---------------------------------------- -- line 708 ---------------------------------------- . . #[inline] . fn next(&mut self) -> Option { . self.spec_next() . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 442,110 ( 0.00%) if self.start < self.end { . let hint = Step::steps_between(&self.start, &self.end); . (hint.unwrap_or(usize::MAX), hint) . } else { . (0, Some(0)) . } . } . . #[inline] -- line 724 ---------------------------------------- -- line 857 ---------------------------------------- . impl FusedIterator for ops::Range {} . . #[stable(feature = "rust1", since = "1.0.0")] . impl Iterator for ops::RangeFrom { . type Item = A; . . #[inline] . fn next(&mut self) -> Option { 42,914 ( 0.00%) let n = Step::forward(self.start.clone(), 1); . Some(mem::replace(&mut self.start, n)) . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { . (usize::MAX, None) . } . -- line 873 ---------------------------------------- -- line 998 ---------------------------------------- . . try { accum } . } . } . . impl RangeInclusiveIteratorImpl for ops::RangeInclusive { . #[inline] . fn spec_next(&mut self) -> Option { 93,214 ( 0.00%) if self.is_empty() { . return None; . } . let is_iterating = self.start < self.end; 62,770 ( 0.00%) Some(if is_iterating { . // SAFETY: just checked precondition . let n = unsafe { Step::forward_unchecked(self.start.clone(), 1) }; . mem::replace(&mut self.start, n) . } else { . self.exhausted = true; . self.start.clone() . }) . } -- line 1018 ---------------------------------------- -- line 1025 ---------------------------------------- . R: Try, . { . if self.is_empty() { . return try { init }; . } . . let mut accum = init; . 57,655 ( 0.00%) while self.start < self.end { . // SAFETY: just checked precondition . let n = unsafe { Step::forward_unchecked(self.start.clone(), 1) }; . let n = mem::replace(&mut self.start, n); . accum = f(accum, n)?; . } . . self.exhausted = true; . 4,561 ( 0.00%) if self.start == self.end { . accum = f(accum, self.start.clone())?; . } . . try { accum } . } . . #[inline] . fn spec_next_back(&mut self) -> Option { -- line 1050 ---------------------------------------- -- line 1098 ---------------------------------------- . . #[inline] . fn next(&mut self) -> Option { . self.spec_next() . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 55,524 ( 0.00%) if self.is_empty() { . return (0, Some(0)); . } . . match Step::steps_between(&self.start, &self.end) { . Some(hint) => (hint.saturating_add(1), hint.checked_add(1)), . None => (usize::MAX, None), . } . } -- line 1114 ---------------------------------------- 23,521,289 ( 0.10%) -------------------------------------------------------------------------------- -- 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] { 53,795 ( 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> { 3,064 ( 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> { 32,174,394 ( 0.13%) 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, . } 5,363,300 ( 0.02%) } . } . . fn visit_attrvec(attrs: &mut AttrVec, f: impl FnOnce(&mut Vec)) { 179,419 ( 0.00%) crate::mut_visit::visit_clobber(attrs, |attrs| { . let mut vec = attrs.into(); . f(&mut vec); 59,792 ( 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] { 62,706 ( 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, . } 764 ( 0.00%) } . . fn visit_attrs(&mut self, f: impl FnOnce(&mut Vec)) { 8,945 ( 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 => {} 313 ( 0.00%) StmtKind::MacCall(mac) => visit_attrvec(&mut mac.attrs, f), . } . } . fn tokens_mut(&mut self) -> Option<&mut Option> { 11,952 ( 0.00%) Some(match self { 628 ( 0.00%) StmtKind::Local(local) => &mut local.tokens, . StmtKind::Item(item) => &mut item.tokens, 1,036 ( 0.00%) StmtKind::Expr(expr) | StmtKind::Semi(expr) => &mut expr.tokens, . StmtKind::Empty => return None, 328 ( 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() 8,194 ( 0.00%) } . 24 ( 0.00%) fn visit_attrs(&mut self, f: impl FnOnce(&mut Vec)) { 68 ( 0.00%) self.kind.visit_attrs(f); 24 ( 0.00%) } . fn tokens_mut(&mut self) -> Option<&mut Option> { . self.kind.tokens_mut() 1,992 ( 0.00%) } . } . . impl AstLike for Attribute { . const SUPPORTS_CUSTOM_INNER_ATTRS: bool = false; . . fn attrs(&self) -> &[Attribute] { . &[] 35,016 ( 0.00%) } . fn visit_attrs(&mut self, _f: impl FnOnce(&mut Vec)) {} 5,361 ( 0.00%) fn tokens_mut(&mut self) -> Option<&mut Option> { 10,722 ( 0.00%) Some(match &mut self.kind { 5,361 ( 0.00%) AttrKind::Normal(_, tokens) => tokens, . kind @ AttrKind::DocComment(..) => { . panic!("Called tokens_mut on doc comment attr {:?}", kind) . } . }) 16,083 ( 0.00%) } . } . . impl AstLike for Option { . const SUPPORTS_CUSTOM_INNER_ATTRS: bool = T::SUPPORTS_CUSTOM_INNER_ATTRS; . . fn attrs(&self) -> &[Attribute] { 7,314 ( 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> { 6,807 ( 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 { 58,193 ( 0.00%) fn visit(&mut self, f: impl FnOnce(&mut Vec)) { 14,578 ( 0.00%) f(self) 58,192 ( 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 30,050 ( 0.00%) } . . fn visit_attrs(&mut self, f: impl FnOnce(&mut Vec)) { 67,069 ( 0.00%) VecOrAttrVec::visit(&mut self.attrs, f) . } . . fn tokens_mut(&mut self) -> Option<&mut Option> { 8,899 ( 0.00%) Some(&mut self.tokens) 8,594 ( 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 5,297 ( 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 6 ( 0.00%) } . } . )* } . } . . macro_rules! derive_has_tokens_no_attrs { . ($($ty:path),*) => { $( . impl AstLike for $ty { . const SUPPORTS_CUSTOM_INNER_ATTRS: bool = false; . . fn attrs(&self) -> &[Attribute] { . &[] 38,541 ( 0.00%) } . . fn visit_attrs(&mut self, _f: impl FnOnce(&mut Vec)) {} . fn tokens_mut(&mut self) -> Option<&mut Option> { 6,145 ( 0.00%) Some(&mut self.tokens) 3,780 ( 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 ---------------------------------------- 96,555 ( 0.00%) -------------------------------------------------------------------------------- -- 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] 47,558,872 ( 0.20%) 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] 2,523,504 ( 0.01%) 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] 214,364 ( 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/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. 10,762,216 ( 0.04%) 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, . } . } . 53,811,080 ( 0.22%) match kind { . NonterminalKind::Expr => { 1,134 ( 0.00%) token.can_begin_expr() . // This exception is here for backwards compatibility. 567 ( 0.00%) && !token.is_keyword(kw::Let) . // This exception is here for backwards compatibility. 756 ( 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(), 8,139 ( 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 49 ---------------------------------------- . | token::NtTy(_) . | token::NtIdent(..) . | token::NtMeta(_) . | token::NtPath(_) . | token::NtVis(_) . ), . _ => false, . }, 5,693 ( 0.00%) NonterminalKind::Path | NonterminalKind::Meta => match token.kind { . token::ModSep | token::Ident(..) => true, 3,504 ( 0.00%) token::Interpolated(ref nt) => match **nt { . token::NtPath(_) | token::NtMeta(_) => true, . _ => may_be_ident(&nt), . }, . _ => false, . }, . NonterminalKind::PatParam { .. } | NonterminalKind::PatWithOr { .. } => { . match token.kind { . token::Ident(..) | // box, ref, mut, and other identifiers (can stricten) -- line 67 ---------------------------------------- -- line 77 ---------------------------------------- . token::Lt | // path (UFCS constant) . token::BinOp(token::Shl) => true, // path (double UFCS) . // leading vert `|` or-pattern . token::BinOp(token::Or) => matches!(kind, NonterminalKind::PatWithOr {..}), . token::Interpolated(ref nt) => may_be_ident(nt), . _ => false, . } . } 395 ( 0.00%) 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 => { 10,732,992 ( 0.04%) !matches!(token.kind, token::CloseDelim(_)) . } . } 10,757,726 ( 0.04%) } . . /// Parse a non-terminal (e.g. MBE `:pat` or `:ident`). 48,261,591 ( 0.20%) 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. 58,986,389 ( 0.24%) let mut nt = match kind { . NonterminalKind::Item => match self.parse_item(ForceCollect::Yes)? { 915 ( 0.00%) 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] { ... }`), . // the ':block' matcher does not support them . token::NtBlock(self.collect_tokens_no_attrs(|this| this.parse_block())?) -- line 116 ---------------------------------------- -- 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!(), . })?) . } . 756 ( 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 => { 2,328 ( 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 31,518 ( 0.00%) if let Some((ident, is_raw)) = get_macro_ident(&self.token) => . { 10,506 ( 0.00%) self.bump(); 36,771 ( 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)); . } 72 ( 0.00%) NonterminalKind::Path => token::NtPath( . self.collect_tokens_no_attrs(|this| this.parse_path(PathStyle::Type))?, . ), 5,286 ( 0.00%) NonterminalKind::Meta => token::NtMeta(P(self.parse_attr_item(true)?)), 26,767,025 ( 0.11%) NonterminalKind::TT => token::NtTT(self.parse_token_tree()), 4,248 ( 0.00%) NonterminalKind::Vis => token::NtVis( 4,248 ( 0.00%) self.collect_tokens_no_attrs(|this| this.parse_visibility(FollowedByType::Yes))?, . ), . NonterminalKind::Lifetime => { 50 ( 0.00%) if self.check_lifetime() { 100 ( 0.00%) 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. 16,094,629 ( 0.07%) if matches!(nt.tokens_mut(), Some(None)) { . panic!( . "Missing tokens for nt {:?} at {:?}: {:?}", . nt, . nt.span(), . pprust::nonterminal_to_string(&nt) . ); . } . 37,536,793 ( 0.16%) Ok(nt) 48,261,591 ( 0.20%) } . } . . /// 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)> { 30,134 ( 0.00%) token.ident().filter(|(ident, _)| ident.name != kw::Underscore) . } 5,383,614 ( 0.02%) -------------------------------------------------------------------------------- The following files chosen for auto-annotation could not be found: -------------------------------------------------------------------------------- ./malloc/malloc.c ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S -------------------------------------------------------------------------------- Ir -------------------------------------------------------------------------------- 14,887,938,373 (61.77%) events annotated