-------------------------------------------------------------------------------- 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 yansi 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 -C metadata=c2690a1b286819d8 -C extra-filename=-c2690a1b286819d8 --out-dir /usr/home/liquid/tmp/.tmpseuoej/target/debug/deps -L dependency=/usr/home/liquid/tmp/.tmpseuoej/target/debug/deps -Adeprecated -Aunknown-lints -Zincremental-verify-ich Data file: results/cgout-w-profiling-yansi-0.5.0-Check-Full Events recorded: Ir Events shown: Ir Event sort order: Ir Thresholds: 0.1 Include dirs: User annotated: Auto-annotation: on -------------------------------------------------------------------------------- Ir -------------------------------------------------------------------------------- 1,127,043,740 (100.0%) PROGRAM TOTALS -------------------------------------------------------------------------------- Ir file:function -------------------------------------------------------------------------------- 65,878,432 ( 5.85%) ./malloc/malloc.c:_int_free 48,269,913 ( 4.28%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe/macro_parser.rs:rustc_expand::mbe::macro_parser::parse_tt 43,915,325 ( 3.90%) ./malloc/malloc.c:_int_malloc 42,826,697 ( 3.80%) ./malloc/malloc.c:malloc 37,378,472 ( 3.32%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs:rustc_expand::mbe::macro_parser::parse_tt 26,676,155 ( 2.37%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::next 26,620,206 ( 2.36%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::bump 21,417,244 ( 1.90%) ./malloc/malloc.c:free 18,200,604 ( 1.61%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/tokenstream.rs:::next_with_spacing 15,670,946 ( 1.39%) ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:__memcpy_avx_unaligned_erms 12,098,100 ( 1.07%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::bump_with 11,210,664 ( 0.99%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe/transcribe.rs:rustc_expand::mbe::transcribe::transcribe 11,055,784 ( 0.98%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe/macro_parser.rs:::clone 10,923,384 ( 0.97%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe.rs:::get_tt 10,305,124 ( 0.91%) ./elf/dl-lookup.c:_dl_lookup_symbol_x 10,205,998 ( 0.91%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::clone 8,902,425 ( 0.79%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:rustc_expand::mbe::macro_parser::parse_tt 8,681,981 ( 0.77%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:core::ptr::drop_in_place:: 7,742,784 ( 0.69%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:>::truncate 7,563,088 ( 0.67%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe.rs:rustc_expand::mbe::macro_parser::parse_tt 7,559,516 ( 0.67%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs: as core::iter::traits::collect::Extend>::extend::>> 7,475,490 ( 0.66%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::next_desugared 7,472,694 ( 0.66%) ./malloc/malloc.c:malloc_consolidate 7,124,156 ( 0.63%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/nonterminal.rs:::parse_nonterminal 7,092,864 ( 0.63%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs:>>::make_mut 6,853,194 ( 0.61%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::ident 6,805,498 ( 0.60%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs: as core::iter::traits::collect::Extend>::extend::>> 6,469,981 ( 0.57%) /usr/home/liquid/rust/worktree-benchmarking/library/std/src/sys/unix/alloc.rs:__rdl_alloc 6,184,756 ( 0.55%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::lifetime 6,143,064 ( 0.55%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::parse_token_tree 5,811,023 ( 0.52%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs: as core::ops::drop::Drop>::drop 5,730,257 ( 0.51%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::eq 5,603,116 ( 0.50%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs:>::try_reserve 4,903,802 ( 0.44%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs:core::ptr::drop_in_place:: 4,835,679 ( 0.43%) ./elf/dl-lookup.c:do_lookup_x 4,753,412 ( 0.42%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs:>::try_reserve 4,732,677 ( 0.42%) ./malloc/malloc.c:unlink_chunk.constprop.0 4,355,316 ( 0.39%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:::bump_with 4,141,271 ( 0.37%) ./elf/../sysdeps/x86_64/dl-machine.h:_dl_relocate_object 3,991,996 ( 0.35%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe.rs:::clone 3,750,168 ( 0.33%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs: as core::ops::drop::Drop>::drop 3,696,090 ( 0.33%) ./malloc/malloc.c:realloc 3,609,367 ( 0.32%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs: as core::ops::drop::Drop>::drop 3,501,327 ( 0.31%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs:> as core::ops::drop::Drop>::drop 3,346,570 ( 0.30%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs: as core::ops::drop::Drop>::drop 3,095,066 ( 0.27%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/span_encoding.rs:::normalize_to_macro_rules 2,975,033 ( 0.26%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::clone 2,968,148 ( 0.26%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs: as core::ops::drop::Drop>::drop 2,927,338 ( 0.26%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:::bump_with 2,903,544 ( 0.26%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/span_encoding.rs:::bump 2,845,490 ( 0.25%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs:rustc_expand::mbe::macro_parser::parse_tt 2,839,848 ( 0.25%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe/transcribe.rs:rustc_expand::mbe::transcribe::lookup_cur_matched 2,814,162 ( 0.25%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs:rustc_expand::mbe::transcribe::transcribe 2,793,830 ( 0.25%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_serialize/src/opaque.rs:>::decode 2,752,008 ( 0.24%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:rustc_expand::mbe::transcribe::lookup_cur_matched 2,663,480 ( 0.24%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs: as core::iter::traits::collect::Extend>::extend::>> 2,653,763 ( 0.24%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs:::short_write_process_buffer:: 2,639,344 ( 0.23%) ./malloc/malloc.c:_int_realloc 2,629,633 ( 0.23%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/nonterminal.rs:::nonterminal_may_begin_with 2,592,823 ( 0.23%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/alloc.rs:rustc_expand::mbe::macro_parser::parse_tt 2,499,861 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/symbol.rs:::normalize_to_macro_rules 2,475,668 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:>::decode 2,435,318 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/option.rs:rustc_expand::mbe::transcribe::transcribe 2,378,700 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/boxed.rs:>]> as core::clone::Clone>::clone 2,352,142 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:core::ptr::drop_in_place:: 2,328,030 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:>::decode 2,206,438 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:>>::make_mut 2,171,705 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs: as core::ops::drop::Drop>::drop 2,162,544 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs:>]> as core::clone::Clone>::clone 2,162,270 ( 0.19%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, (), core::hash::BuildHasherDefault>>::from_hash::>::{closure#0}> 2,139,033 ( 0.19%) ./elf/do-rel.h:_dl_relocate_object 2,109,972 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe/macro_parser.rs:::clone 2,096,915 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/symbol.rs:::eq 2,011,618 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/convert/mod.rs:rustc_expand::mbe::transcribe::transcribe 1,939,068 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/iter/adapters/take.rs:>]> as core::clone::Clone>::clone 1,935,696 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/mem/mod.rs:::bump_with 1,891,064 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs: as core::ops::drop::Drop>::drop 1,874,172 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:>]> as core::clone::Clone>::clone 1,848,566 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/library/std/src/alloc.rs:__rdl_alloc 1,837,602 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/caching_source_map_view.rs:::span_data_to_lines_and_cols 1,780,164 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs:::short_write_process_buffer:: 1,770,713 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::is_keyword 1,751,932 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/span_encoding.rs:::eq 1,704,040 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs: as core::iter::traits::collect::Extend>::extend::>> 1,666,544 ( 0.15%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/rustc_entry.rs:>>::rustc_entry 1,640,715 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/borrow.rs:rustc_expand::mbe::macro_parser::parse_tt 1,609,703 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/index.rs:::get_tt 1,585,800 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/option.rs:::clone 1,568,178 ( 0.14%) /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 1,503,638 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_serialize/src/leb128.rs:::read_u32 1,490,671 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/span_encoding.rs:rustc_expand::mbe::transcribe::lookup_cur_matched 1,466,713 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/alloc.rs:core::ptr::drop_in_place:: 1,466,256 ( 0.13%) /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> 1,417,801 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:rustc_expand::mbe::transcribe::transcribe 1,362,217 ( 0.12%) ???:SetImpliedBits(llvm::FeatureBitset&, llvm::FeatureBitset const&, llvm::ArrayRef) 1,353,483 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/std/src/thread/local.rs:rustc_span::SESSION_GLOBALS::FOO::__getit 1,351,762 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe/macro_parser.rs:rustc_expand::mbe::macro_parser::count_names::{closure#0} 1,349,562 ( 0.12%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:)>>::remove_entry::>::{closure#0}> 1,332,612 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:::next 1,313,246 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe.rs:::clone 1,280,256 ( 0.11%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs:::clone 1,211,949 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:> as core::ops::drop::Drop>::drop 1,196,631 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_resolve/src/lib.rs:::early_resolve_ident_in_lexical_scope 1,188,248 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe/macro_parser.rs: as core::iter::traits::collect::Extend>::extend::>> 1,188,082 ( 0.11%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs:>>::make_mut 1,179,008 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe.rs:::clone 1,146,157 ( 0.10%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::from_key_hashed_nocheck:: 1,141,743 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:>::hash_stable 1,135,509 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/convert/mod.rs:::next -------------------------------------------------------------------------------- -- 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. . /// 1,133,721 ( 0.10%) #[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 { 672 ( 0.00%) base_or_index: u32, 113 ( 0.00%) len_or_tag: u16, 299 ( 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 { 237,776 ( 0.02%) if lo > hi { . std::mem::swap(&mut lo, &mut hi); . } . 475,528 ( 0.04%) let (base, len, ctxt2) = (lo.0, hi.0 - lo.0, ctxt.as_u32()); . 2,103,411 ( 0.19%) 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 = 220 ( 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 } . } 750,391 ( 0.07%) } . . #[inline] . pub fn data(self) -> SpanData { . let data = self.data_untracked(); . if let Some(parent) = data.parent { . (*SPAN_TRACK)(parent); . } . data . } . . /// Internal function to translate between an encoded span and the expanded representation. . /// This function must not be used outside the incremental engine. . #[inline] . pub fn data_untracked(self) -> SpanData { 3,992,752 ( 0.35%) 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), 3,676,149 ( 0.33%) hi: BytePos(self.base_or_index + self.len_or_tag as u32), . ctxt: SyntaxContext::from_u32(self.ctxt_or_zero as u32), . parent: None, . } . } else { . // Interned format. . debug_assert!(self.ctxt_or_zero == 0); . let index = self.base_or_index; . with_span_interner(|interner| interner.spans[index as usize]) . } 184,513 ( 0.02%) } . } . 4 ( 0.00%) #[derive(Default)] . pub struct SpanInterner { . spans: FxIndexSet, . } . . impl SpanInterner { 66 ( 0.00%) fn intern(&mut self, span_data: &SpanData) -> u32 { 88 ( 0.00%) let (index, _) = self.spans.insert_full(*span_data); . index as u32 88 ( 0.00%) } . } . . // If an interner exists, return it. Otherwise, prepare a fresh one. . #[inline] . fn with_span_interner T>(f: F) -> T { . crate::with_session_globals(|session_globals| f(&mut *session_globals.span_interner.lock())) . } 2,491,452 ( 0.22%) -------------------------------------------------------------------------------- -- 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 { 942,541 ( 0.08%) Vec { buf: RawVec::NEW, len: 0 } 66 ( 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 { 783,751 ( 0.07%) 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 { 42,385 ( 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 { 243,762 ( 0.02%) self.buf.capacity() . } . . /// Reserves capacity for at least `additional` more elements to be inserted . /// in the given `Vec`. The collection may reserve more space to avoid . /// frequent reallocations. After calling `reserve`, capacity will be . /// greater than or equal to `self.len() + additional`. Does nothing if . /// capacity is already sufficient. . /// -- line 794 ---------------------------------------- -- line 801 ---------------------------------------- . /// ``` . /// let mut vec = vec![1]; . /// vec.reserve(10); . /// assert!(vec.capacity() >= 11); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn reserve(&mut self, additional: usize) { 75,850 ( 0.01%) self.buf.reserve(self.len, additional); . } . . /// Reserves the minimum capacity for exactly `additional` more elements to . /// be inserted in the given `Vec`. After calling `reserve_exact`, . /// capacity will be greater than or equal to `self.len() + additional`. . /// Does nothing if the capacity is already sufficient. . /// . /// Note that the allocator may give the collection more space than it -- line 817 ---------------------------------------- -- line 829 ---------------------------------------- . /// ``` . /// let mut vec = vec![1]; . /// vec.reserve_exact(10); . /// assert!(vec.capacity() >= 11); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn reserve_exact(&mut self, additional: usize) { 2,649 ( 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. 373,548 ( 0.03%) if self.capacity() > self.len { 1,179 ( 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(); 175,514 ( 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")] 2,430,052 ( 0.22%) 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. 1,467,438 ( 0.13%) 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); 511,965 ( 0.05%) self.len = len; 1,152 ( 0.00%) ptr::drop_in_place(s); . } 2,916,062 ( 0.26%) } . . /// 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. 1,520,372 ( 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. 1,897,083 ( 0.17%) 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()); . 385,160 ( 0.03%) self.len = new_len; 176 ( 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 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")] 833 ( 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); . } . 206 ( 0.00%) let len = self.len(); 480 ( 0.00%) if index > len { . assert_failed(index, len); . } . . // space for the new element 930 ( 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.) 1,134 ( 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); . } 930 ( 0.00%) self.set_len(len + 1); . } 714 ( 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); . } . 58 ( 0.00%) let len = self.len(); 225 ( 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. 112 ( 0.00%) ret = ptr::read(ptr); . . // Shift everything down to fill in that spot. 156 ( 0.00%) ptr::copy(ptr.offset(1), ptr, len - index - 1); . } 72 ( 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")] 39,019 ( 0.00%) pub fn retain(&mut self, mut f: F) . where . F: FnMut(&T) -> bool, . { 2,992 ( 0.00%) self.retain_mut(|elem| f(elem)); 37,936 ( 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, . { 4,889 ( 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) { 4,098 ( 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), 2,592 ( 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, . { 57,644 ( 0.01%) while g.processed_len != original_len { . // SAFETY: Unchecked element must be valid. . let cur = unsafe { &mut *g.v.as_mut_ptr().add(g.processed_len) }; 14,233 ( 0.00%) if !f(cur) { . // Advance early to avoid double drop if `drop_in_place` panicked. 220 ( 0.00%) g.processed_len += 1; 114 ( 0.00%) g.deleted_cnt += 1; . // SAFETY: We never touch this element again after dropped. 155 ( 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 { 996 ( 0.00%) let hole_slot = g.v.as_mut_ptr().add(g.processed_len - g.deleted_cnt); . ptr::copy_nonoverlapping(cur, hole_slot, 1); . } . } 664 ( 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")] 2,751 ( 0.00%) pub fn dedup_by(&mut self, mut same_bucket: F) . where . F: FnMut(&mut T, &mut T) -> bool, . { 393 ( 0.00%) let len = self.len(); 1,228 ( 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 { 210 ( 0.00%) while gap.read < len { . let read_ptr = ptr.add(gap.read); . let prev_ptr = ptr.add(gap.write.wrapping_sub(1)); . 100 ( 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 */ 70 ( 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); . } 3,144 ( 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")] 95 ( 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. 2,838,421 ( 0.25%) if self.len == self.buf.capacity() { 188,186 ( 0.02%) self.buf.reserve_for_push(self.len); . } . unsafe { 92,112 ( 0.01%) let end = self.as_mut_ptr().add(self.len); . ptr::write(end, value); 3,372,767 ( 0.30%) self.len += 1; . } 76 ( 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 { 433,160 ( 0.04%) if self.len == 0 { 3,286 ( 0.00%) None . } else { . unsafe { 308,362 ( 0.03%) self.len -= 1; 22,944 ( 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")] 98 ( 0.00%) pub fn append(&mut self, other: &mut Self) { . unsafe { . self.append_elements(other.as_slice() as _); . other.set_len(0); . } 84 ( 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); 6,799 ( 0.00%) let len = self.len(); . unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) }; 96,320 ( 0.01%) self.len += count; . } . . /// Creates a draining iterator that removes the specified range in the vector . /// and yields the removed items. . /// . /// When the iterator **is** dropped, all elements in the range are removed . /// from the vector, even if the iterator was not fully consumed. If the . /// iterator **is not** dropped (with [`mem::forget`] for example), it is -- line 1807 ---------------------------------------- -- line 1834 ---------------------------------------- . // When the Drain is first created, it shortens the length of . // the source vector to make sure no uninitialized or moved-from elements . // are accessible at all if the Drain's destructor never gets to run. . // . // Drain will ptr::read out the values to remove. . // When finished, remaining tail of the vec is copied back to cover . // the hole, and the vector length is restored to the new length. . // 5,587 ( 0.00%) let len = self.len(); . let Range { start, end } = slice::range(range, ..len); . . unsafe { . // set self.vec length's to start, to be safe in case Drain is leaked . self.set_len(start); . // Use the borrow in the IterMut to indicate borrowing behavior of the . // whole Drain iterator (like &mut T). 6 ( 0.00%) let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start), end - start); 112,953 ( 0.01%) Drain { . tail_start: end, 6 ( 0.00%) tail_len: len - end, . iter: range_slice.iter(), . vec: NonNull::from(self), . } . } . } . . /// Clears the vector, removing all values. . /// -- line 1861 ---------------------------------------- -- line 1869 ---------------------------------------- . /// . /// v.clear(); . /// . /// assert!(v.is_empty()); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn clear(&mut self) { 4,359,735 ( 0.39%) 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 { 295,863 ( 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); . } . 528 ( 0.00%) if at > self.len() { . assert_failed(at, self.len()); . } . 426 ( 0.00%) if at == 0 { . // the new vector can take over the original buffer and avoid the copy . return mem::replace( . self, . Vec::with_capacity_in(self.capacity(), self.allocator().clone()), . ); . } . . let other_len = self.len - at; -- line 1955 ---------------------------------------- -- line 1988 ---------------------------------------- . /// . /// let mut vec = vec![]; . /// let mut p = 1; . /// vec.resize_with(4, || { p *= 2; p }); . /// assert_eq!(vec, [2, 4, 8, 16]); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "vec_resize_with", since = "1.33.0")] 7,062 ( 0.00%) pub fn resize_with(&mut self, new_len: usize, f: F) . where . F: FnMut() -> T, . { 956 ( 0.00%) let len = self.len(); 1,912 ( 0.00%) if new_len > len { 6,616 ( 0.00%) self.extend_with(new_len - len, ExtendFunc(f)); . } else { . self.truncate(new_len); . } 6,106 ( 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, 36 ( 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")] 630 ( 0.00%) pub fn resize(&mut self, new_len: usize, value: T) { 68 ( 0.00%) let len = self.len(); . 4,912 ( 0.00%) if new_len > len { 1,292 ( 0.00%) self.extend_with(new_len - len, ExtendElement(value)) . } else { . self.truncate(new_len); . } 468 ( 0.00%) } . . /// Clones and appends all elements in a slice to the `Vec`. . /// . /// Iterates over the slice `other`, clones each element, and then appends . /// it to this `Vec`. The `other` slice is traversed in-order. . /// . /// Note that this function is same as [`extend`] except that it is . /// specialized to work with slices instead. If and when Rust gets -- line 2213 ---------------------------------------- -- line 2220 ---------------------------------------- . /// let mut vec = vec![1]; . /// vec.extend_from_slice(&[2, 3, 4]); . /// assert_eq!(vec, [1, 2, 3, 4]); . /// ``` . /// . /// [`extend`]: Vec::extend . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "vec_extend_from_slice", since = "1.6.0")] 64 ( 0.00%) pub fn extend_from_slice(&mut self, other: &[T]) { . self.spec_extend(other.iter()) 48 ( 0.00%) } . . /// Copies elements from `src` range to the end of the vector. . /// . /// # Panics . /// . /// Panics if the starting point is greater than the end point or if . /// the end point is greater than the length of the vector. . /// -- line 2238 ---------------------------------------- -- line 2271 ---------------------------------------- . trait ExtendWith { . fn next(&mut self) -> T; . fn last(self) -> T; . } . . struct ExtendElement(T); . impl ExtendWith for ExtendElement { . fn next(&mut self) -> T { 22 ( 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. 173,182 ( 0.02%) fn extend_with>(&mut self, n: usize, mut value: E) { . self.reserve(n); . . unsafe { 1,863 ( 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); . } . 85,315 ( 0.01%) 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 . } 119,341 ( 0.01%) } . } . . impl Vec { . /// Removes consecutive repeated elements in the vector according to the . /// [`PartialEq`] trait implementation. . /// . /// If the vector is sorted, this removes all duplicates. . /// -- line 2333 ---------------------------------------- -- line 2338 ---------------------------------------- . /// . /// vec.dedup(); . /// . /// assert_eq!(vec, [1, 2, 3, 2]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . pub fn dedup(&mut self) { 394 ( 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")] 6,766 ( 0.00%) pub fn from_elem(elem: T, n: usize) -> Vec { 100,415 ( 0.01%) ::from_elem(elem, n, Global) 8,074 ( 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] { 1,881,749 ( 0.17%) unsafe { slice::from_raw_parts(self.as_ptr(), self.len) } 6 ( 0.00%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl ops::DerefMut for Vec { . fn deref_mut(&mut self) -> &mut [T] { 360,836 ( 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))] 357,534 ( 0.03%) fn clone(&self) -> Self { . let alloc = self.allocator().clone(); 2 ( 0.00%) <[T]>::to_vec_in(&**self, alloc) 434,873 ( 0.04%) } . . // 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 { 41,895 ( 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 { 32 ( 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 { 322,992 ( 0.03%) >::from_iter(iter.into_iter()) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl IntoIterator for Vec { . type Item = T; . type IntoIter = IntoIter; . -- line 2555 ---------------------------------------- -- line 2564 ---------------------------------------- . /// for s in v.into_iter() { . /// // s has type String, not &String . /// println!("{}", s); . /// } . /// ``` . #[inline] . fn into_iter(self) -> IntoIter { . unsafe { 152,781 ( 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(); 61,299 ( 0.01%) 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> { 60 ( 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,052 ( 0.00%) self.iter_mut() . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl Extend for Vec { . #[inline] 128 ( 0.00%) fn extend>(&mut self, iter: I) { 163,887 ( 0.01%) >::spec_extend(self, iter.into_iter()) 128 ( 0.00%) } . . #[inline] . fn extend_one(&mut self, item: T) { 48 ( 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); . // } 54,621 ( 0.00%) while let Some(element) = iterator.next() { 6,366 ( 0.00%) let len = self.len(); 64,606 ( 0.01%) if len == self.capacity() { 441 ( 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 54,411 ( 0.00%) self.set_len(len + 1); . } . } 576 ( 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 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, . { 621 ( 0.00%) let old_len = self.len(); . . // Guard against us getting leaked (leak amplification) . unsafe { . self.set_len(0); . } . 360 ( 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 { 423,463 ( 0.04%) fn drop(&mut self) { . unsafe { . // use drop for [T] . // use a raw slice to refer to the elements of the vector as weakest necessary type; . // could avoid questions of validity in certain cases 161,645 ( 0.01%) ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len)) . } . // RawVec handles deallocation 496,242 ( 0.04%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")] . impl const Default for Vec { . /// Creates an empty `Vec`. . fn default() -> Vec { . Vec::new() -- line 2827 ---------------------------------------- -- line 2976 ---------------------------------------- . /// newly-allocated buffer with exactly the right capacity. . /// . /// # Examples . /// . /// ``` . /// assert_eq!(Box::from(vec![1, 2, 3]), vec![1, 2, 3].into_boxed_slice()); . /// ``` . fn from(v: Vec) -> Self { 4 ( 0.00%) v.into_boxed_slice() . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl From<&str> for Vec { . /// Allocate a `Vec` and fill it with a UTF-8 string. . /// -- line 2992 ---------------------------------------- 451,781 ( 0.04%) -------------------------------------------------------------------------------- -- 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 . // . 3,697,132 ( 0.33%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 2,772,849 ( 0.25%) 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. 18,880 ( 0.00%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 28,320 ( 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) { 928,992 ( 0.08%) libc::free(ptr as *mut libc::c_void) . } . . #[inline] . unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { 157,288 ( 0.01%) if layout.align() <= MIN_ALIGN && layout.align() <= new_size { 314,576 ( 0.03%) libc::realloc(ptr as *mut libc::c_void, new_size) as *mut u8 . } else { . realloc_fallback(self, ptr, layout, new_size) . } . } . } . . cfg_if::cfg_if! { . if #[cfg(any( -- line 56 ---------------------------------------- -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_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}; . 11,413 ( 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); . } . } . } . }; . } . 562,443 ( 0.05%) #[derive(Clone)] . pub struct Parser<'a> { 21,093 ( 0.00%) pub sess: &'a ParseSess, . /// The current token. 20,042 ( 0.00%) pub token: Token, . /// The spacing for the current token 10,024 ( 0.00%) pub token_spacing: Spacing, . /// The previous token. 30,063 ( 0.00%) pub prev_token: Token, 10,027 ( 0.00%) pub capture_cfg: bool, 20,057 ( 0.00%) restrictions: Restrictions, 20,048 ( 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, 20,048 ( 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. 20,048 ( 0.00%) unmatched_angle_bracket_count: u32, 30,072 ( 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. 10,024 ( 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` 10,024 ( 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, . } . 41,144 ( 0.00%) #[derive(Clone)] . struct CaptureState { 40,096 ( 0.00%) capturing: Capturing, 10,024 ( 0.00%) replace_ranges: Vec, . inner_attr_ranges: FxHashMap, . } . . impl<'a> Drop for Parser<'a> { . fn drop(&mut self) { 36,822 ( 0.00%) emit_unclosed_delims(&mut self.unclosed_delims, &self.sess); . } . } . 245,005 ( 0.02%) #[derive(Clone)] . struct TokenCursor { . frame: TokenCursorFrame, 54,842 ( 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. 18,231 ( 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, . } . 111,654 ( 0.01%) #[derive(Clone)] . struct TokenCursorFrame { 29,179 ( 0.00%) delim: token::DelimToken, . span: DelimSpan, . open_delim: bool, 58,358 ( 0.01%) tree_cursor: tokenstream::Cursor, . close_delim: bool, . } . . impl TokenCursorFrame { . fn new(span: DelimSpan, delim: DelimToken, tts: TokenStream) -> Self { 11,150 ( 0.00%) TokenCursorFrame { . delim, . span, . open_delim: false, 71,369 ( 0.01%) tree_cursor: tts.into_trees(), . close_delim: false, . } . } . } . . impl TokenCursor { 5,854,872 ( 0.52%) fn next(&mut self) -> (Token, Spacing) { . loop { 2,906,501 ( 0.26%) let (tree, spacing) = if !self.frame.open_delim { 66,909 ( 0.01%) self.frame.open_delim = true; 334,545 ( 0.03%) TokenTree::open_tt(self.frame.span, self.frame.delim).into() 5,695,874 ( 0.51%) } else if let Some(tree) = self.frame.tree_cursor.next_with_spacing() { . tree 272,444 ( 0.02%) } else if !self.frame.close_delim { 66,693 ( 0.01%) self.frame.close_delim = true; 333,465 ( 0.03%) TokenTree::close_tt(self.frame.span, self.frame.delim).into() 132,426 ( 0.01%) } else if let Some(frame) = self.stack.pop() { 860,769 ( 0.08%) self.frame = frame; . continue; . } else { 59,688 ( 0.01%) (TokenTree::Token(Token::new(token::Eof, DUMMY_SP)), Spacing::Alone) . }; . 1,109,630 ( 0.10%) match tree { . TokenTree::Token(token) => { 3,903,248 ( 0.35%) return (token, spacing); . } . TokenTree::Delimited(sp, delim, tts) => { . let frame = TokenCursorFrame::new(sp, delim, tts); . self.stack.push(mem::replace(&mut self.frame, frame)); . } . } . } 3,903,248 ( 0.35%) } . 2,768,700 ( 0.25%) fn next_desugared(&mut self) -> (Token, Spacing) { 830,610 ( 0.07%) let (data, attr_style, sp) = match self.next() { . (Token { kind: token::DocComment(_, attr_style, data), span }, _) => { . (data, attr_style, span) . } 1,384,350 ( 0.12%) tok => return tok, . }; . . // Searches for the occurrences of `"#*` and returns the minimum number of `#`s . // required to wrap the text. . let mut num_of_hashes = 0; . let mut count = 0; . for ch in data.as_str().chars() { . count = match ch { -- line 298 ---------------------------------------- -- line 332 ---------------------------------------- . .iter() . .cloned() . .collect::() . }, . ), . )); . . self.next() 2,491,830 ( 0.22%) } . } . 2,050 ( 0.00%) #[derive(Debug, Clone, PartialEq)] . enum TokenType { 1,640 ( 0.00%) Token(TokenKind), . Keyword(Symbol), . Operator, . Lifetime, . Ident, . Path, . Type, . Const, . } -- line 353 ---------------------------------------- -- line 392 ---------------------------------------- . } . . pub enum FollowedByType { . Yes, . No, . } . . fn token_descr_opt(token: &Token) -> Option<&'static str> { 164 ( 0.00%) Some(match token.kind { 328 ( 0.00%) _ if token.is_special_ident() => "reserved identifier", 328 ( 0.00%) _ if token.is_used_keyword() => "keyword", 328 ( 0.00%) _ if token.is_unused_keyword() => "reserved keyword", . token::DocComment(..) => "doc comment", . _ => return None, . }) . } . 574 ( 0.00%) pub(super) fn token_descr(token: &Token) -> String { 164 ( 0.00%) let token_str = pprust::token_to_string(token); . match token_descr_opt(token) { . Some(prefix) => format!("{} `{}`", prefix, token_str), 574 ( 0.00%) _ => format!("`{}`", token_str), . } 410 ( 0.00%) } . . impl<'a> Parser<'a> { 31,220 ( 0.00%) pub fn new( . sess: &'a ParseSess, . tokens: TokenStream, . desugar_doc_comments: bool, . subparser_name: Option<&'static str>, . ) -> Self { 2,230 ( 0.00%) let mut start_frame = TokenCursorFrame::new(DelimSpan::dummy(), token::NoDelim, tokens); 4,460 ( 0.00%) start_frame.open_delim = true; . start_frame.close_delim = true; . 69,130 ( 0.01%) let mut parser = Parser { . sess, 2,230 ( 0.00%) token: Token::dummy(), . token_spacing: Spacing::Alone, 2,230 ( 0.00%) prev_token: Token::dummy(), . capture_cfg: false, . restrictions: Restrictions::empty(), . expected_tokens: Vec::new(), . token_cursor: TokenCursor { 13,380 ( 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. 4,460 ( 0.00%) parser.bump(); . . parser 20,070 ( 0.00%) } . . fn next_tok(&mut self, fallback_span: Span) -> (Token, Spacing) { . loop { 2,903,544 ( 0.26%) let (mut next, spacing) = if self.desugar_doc_comments { 1,107,480 ( 0.10%) self.token_cursor.next_desugared() . } else { 621,162 ( 0.06%) self.token_cursor.next() . }; 1,935,696 ( 0.17%) 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 483,924 ( 0.04%) self.token_cursor.break_last_token = false; 1,935,696 ( 0.17%) if next.span.is_dummy() { . // Tweak the location for better diagnostics, but keep syntactic context intact. 8,948 ( 0.00%) next.span = fallback_span.with_ctxt(next.span.ctxt()); . } 1,652,027 ( 0.15%) if matches!( 967,848 ( 0.09%) next.kind, . token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) . ) { . continue; . } 1,935,696 ( 0.17%) 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`. 14,760 ( 0.00%) pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> { 1,640 ( 0.00%) if self.expected_tokens.is_empty() { 258 ( 0.00%) if self.token == *t { 215 ( 0.00%) self.bump(); . Ok(false) . } else { . self.unexpected_try_recover(t) . } . } else { 19,164 ( 0.00%) self.expect_one_of(slice::from_ref(t), &[]) . } 24,600 ( 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. 21,096 ( 0.00%) pub fn expect_one_of( . &mut self, . edible: &[TokenKind], . inedible: &[TokenKind], . ) -> PResult<'a, bool /* recovered */> { 3,516 ( 0.00%) if edible.contains(&self.token.kind) { 4,839 ( 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) . } 26,370 ( 0.00%) } . . // Public for rustfmt usage. . pub fn parse_ident(&mut self) -> PResult<'a, Ident> { 12,097 ( 0.00%) self.parse_ident_common(true) . } . . fn ident_or_err(&mut self) -> PResult<'a, (Ident, /* is_raw */ bool)> { 9,147 ( 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(), . }) . } . 21,196 ( 0.00%) fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> { 3,028 ( 0.00%) let (ident, is_raw) = self.ident_or_err()?; 18,168 ( 0.00%) if !is_raw && ident.is_reserved() { . let mut err = self.expected_ident_found(); . if recover { . err.emit(); . } else { . return Err(err); . } . } 12,112 ( 0.00%) self.bump(); . Ok(ident) 30,280 ( 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. 298,340 ( 0.03%) fn check(&mut self, tok: &TokenKind) -> bool { 128,556 ( 0.01%) let is_present = self.token == *tok; 86,142 ( 0.01%) if !is_present { 176,857 ( 0.02%) self.expected_tokens.push(TokenType::Token(tok.clone())); . } . is_present 298,340 ( 0.03%) } . . /// Consumes a token 'tok' if it exists. Returns whether the given token was present. 6,528 ( 0.00%) pub fn eat(&mut self, tok: &TokenKind) -> bool { 60,959 ( 0.01%) let is_present = self.check(tok); 41,480 ( 0.00%) if is_present { 17,281 ( 0.00%) self.bump() . } . is_present 8,160 ( 0.00%) } . . /// If the next token is the given keyword, returns `true` without eating it. . /// An expectation is also added for diagnostics purposes. 54,835 ( 0.00%) fn check_keyword(&mut self, kw: Symbol) -> bool { 7,207 ( 0.00%) self.expected_tokens.push(TokenType::Keyword(kw)); 240,984 ( 0.02%) 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. 47,295 ( 0.00%) pub fn eat_keyword(&mut self, kw: Symbol) -> bool { 38,308 ( 0.00%) if self.check_keyword(kw) { 802 ( 0.00%) self.bump(); . true . } else { . false . } 47,295 ( 0.00%) } . . fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool { 784 ( 0.00%) if self.token.is_keyword(kw) { 184 ( 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. 130 ( 0.00%) fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> { . if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) } 104 ( 0.00%) } . . /// Is the given keyword `kw` followed by a non-reserved identifier? 21,680 ( 0.00%) fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool { 10,840 ( 0.00%) self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()) 24,390 ( 0.00%) } . 22,206 ( 0.00%) fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool { 7,720 ( 0.00%) if ok { . true . } else { 5,100 ( 0.00%) self.expected_tokens.push(typ); . false . } 22,206 ( 0.00%) } . . fn check_ident(&mut self) -> bool { 902 ( 0.00%) self.check_or_expected(self.token.is_ident(), TokenType::Ident) . } . 13,388 ( 0.00%) fn check_path(&mut self) -> bool { 27,091 ( 0.00%) self.check_or_expected(self.token.is_path_start(), TokenType::Path) 16,735 ( 0.00%) } . . fn check_type(&mut self) -> bool { 264 ( 0.00%) self.check_or_expected(self.token.can_begin_type(), TokenType::Type) . } . . fn check_const_arg(&mut self) -> bool { 264 ( 0.00%) self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const) . } . 990 ( 0.00%) fn check_inline_const(&self, dist: usize) -> bool { 550 ( 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, . }) 990 ( 0.00%) } . . /// Checks to see if the next token is either `+` or `+=`. . /// Otherwise returns `false`. . fn check_plus(&mut self) -> bool { 680 ( 0.00%) self.check_or_expected( 340 ( 0.00%) self.token.is_like_plus(), 340 ( 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. 17,460 ( 0.00%) fn break_and_eat(&mut self, expected: TokenKind) -> bool { 10,185 ( 0.00%) if self.token.kind == expected { 204 ( 0.00%) self.bump(); . return true; . } 6,765 ( 0.00%) match self.token.kind.break_two_token_op() { . Some((first, second)) if first == expected => { . let first_span = self.sess.source_map().start_point(self.token.span); . let second_span = self.token.span.with_lo(first_span.hi()); . 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 -- line 682 ---------------------------------------- -- line 684 ---------------------------------------- . // and `next_tok` will set this field to `None` . self.token_cursor.break_last_token = true; . // Use the spacing of the glued token as the spacing . // of the unglued second token. . self.bump_with((Token::new(second, second_span), self.token_spacing)); . true . } . _ => { 4,059 ( 0.00%) self.expected_tokens.push(TokenType::Token(expected)); . false . } . } 18,507 ( 0.00%) } . . /// Eats `+` possibly breaking tokens like `+=` in process. . fn eat_plus(&mut self) -> bool { 16 ( 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, ()> { 156 ( 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, ()> { . if self.break_and_eat(token::BinOp(token::Or)) { Ok(()) } else { self.unexpected() } . } . . /// Eats `<` possibly breaking tokens like `<<` in process. 392 ( 0.00%) fn eat_lt(&mut self) -> bool { 4,291 ( 0.00%) let ate = self.break_and_eat(token::Lt); 2,804 ( 0.00%) if ate { . // See doc comment for `unmatched_angle_bracket_count`. 152 ( 0.00%) self.unmatched_angle_bracket_count += 1; 160 ( 0.00%) self.max_angle_bracket_count += 1; . debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count); . } . ate 392 ( 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, ()> { 228 ( 0.00%) if self.break_and_eat(token::Gt) { . // See doc comment for `unmatched_angle_bracket_count`. 114 ( 0.00%) if self.unmatched_angle_bracket_count > 0 { 76 ( 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 { 1,623 ( 0.00%) TokenExpectType::Expect => self.check(k), . TokenExpectType::NoExpect => self.token == **k, . }) . } . . fn parse_seq_to_before_tokens( . &mut self, . kets: &[&TokenKind], . sep: SeqSep, -- line 758 ---------------------------------------- -- 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) { 1,644 ( 0.00%) if let token::CloseDelim(..) | token::Eof = self.token.kind { . break; . } 1,341 ( 0.00%) if let Some(ref t) = sep.sep { 1,485 ( 0.00%) if first { . first = false; . } else { 462 ( 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; . } . } . } . } . } . } 588 ( 0.00%) if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) { . trailing = true; . break; . } . 571 ( 0.00%) let t = f(self)?; 515 ( 0.00%) v.push(t); . } . 1,064 ( 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)> { 1,288 ( 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. 1,540 ( 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 */)> { 694 ( 0.00%) let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?; 370 ( 0.00%) if !recovered { . self.eat(ket); . } 1,806 ( 0.00%) Ok((val, trailing)) 1,232 ( 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)> { 582 ( 0.00%) self.expect(bra)?; 1,232 ( 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( 256 ( 0.00%) &token::OpenDelim(delim), 359 ( 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. 6,291,012 ( 0.56%) fn bump_with(&mut self, (next_token, next_spacing): (Token, Spacing)) { . // Bumping after EOF is a bad sign, usually an infinite loop. 2,903,544 ( 0.26%) if self.prev_token.kind == TokenKind::Eof { . let msg = "attempted to bump the parser past EOF (may be stuck in a loop)"; . self.span_bug(self.token.span, msg); . } . . // Update the current and previous tokens. 1,935,696 ( 0.17%) self.prev_token = mem::replace(&mut self.token, next_token); 483,924 ( 0.04%) self.token_spacing = next_spacing; . . // Diagnostics. 483,924 ( 0.04%) self.expected_tokens.clear(); . } . . /// Advance the parser by one token. 3,871,392 ( 0.34%) pub fn bump(&mut self) { 1,935,696 ( 0.17%) let next_token = self.next_tok(self.token.span); 2,903,544 ( 0.26%) self.bump_with(next_token); 3,871,392 ( 0.34%) } . . /// Look-ahead `dist` tokens of `self.token` and get access to that token there. . /// When `dist == 0` then the current token is looked at. 64 ( 0.00%) pub fn look_ahead(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R { 510 ( 0.00%) if dist == 0 { 199 ( 0.00%) return looker(&self.token); . } . 7,073 ( 0.00%) let frame = &self.token_cursor.frame; 7,205 ( 0.00%) if frame.delim != DelimToken::NoDelim { . let all_normal = (0..dist).all(|i| { 9,841 ( 0.00%) let token = frame.tree_cursor.look_ahead(i); 12,818 ( 0.00%) !matches!(token, Some(TokenTree::Delimited(_, DelimToken::NoDelim, _))) . }); . if all_normal { 16,282 ( 0.00%) return match frame.tree_cursor.look_ahead(dist - 1) { 5,925 ( 0.00%) Some(tree) => match tree { 2,868 ( 0.00%) TokenTree::Token(token) => looker(token), . TokenTree::Delimited(dspan, delim, _) => { 645 ( 0.00%) looker(&Token::new(token::OpenDelim(*delim), dspan.open)) . } . }, 2,042 ( 0.00%) None => looker(&Token::new(token::CloseDelim(frame.delim), frame.span.close)), . }; . } . } . . let mut cursor = self.token_cursor.clone(); . let mut i = 0; 3,983 ( 0.00%) let mut token = Token::dummy(); 210 ( 0.00%) while i < dist { 27,984 ( 0.00%) token = cursor.next().0; 12,051 ( 0.00%) if matches!( 7,964 ( 0.00%) token.kind, . token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) . ) { . continue; . } 100 ( 0.00%) i += 1; . } 6 ( 0.00%) return looker(&token); 72 ( 0.00%) } . . /// Returns whether any of the given keywords are `dist` tokens ahead of the current one. 2,106 ( 0.00%) fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool { 635 ( 0.00%) self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw))) 2,106 ( 0.00%) } . . /// Parses asyncness: `async` or nothing. . fn parse_asyncness(&mut self) -> Async { . if self.eat_keyword(kw::Async) { . let span = self.prev_token.uninterpolated_span(); . Async::Yes { span, closure_id: DUMMY_NODE_ID, return_impl_trait_id: DUMMY_NODE_ID } . } else { . Async::No . } . } . . /// Parses unsafety: `unsafe` or nothing. 210 ( 0.00%) fn parse_unsafety(&mut self) -> Unsafe { . if self.eat_keyword(kw::Unsafe) { 15 ( 0.00%) Unsafe::Yes(self.prev_token.uninterpolated_span()) . } else { . Unsafe::No . } 840 ( 0.00%) } . . /// Parses constness: `const` or nothing. 18,064 ( 0.00%) fn parse_constness(&mut self) -> Const { . // Avoid const blocks to be parsed as const items 6,653 ( 0.00%) if self.look_ahead(1, |t| t != &token::OpenDelim(DelimToken::Brace)) . && self.eat_keyword(kw::Const) . { 70 ( 0.00%) Const::Yes(self.prev_token.uninterpolated_span()) . } else { . Const::No . } 31,612 ( 0.00%) } . . /// Parses inline const expressions. . fn parse_const_block(&mut self, span: Span, pat: bool) -> PResult<'a, P> { . if pat { . self.sess.gated_spans.gate(sym::inline_const_pat, span); . } else { . self.sess.gated_spans.gate(sym::inline_const, span); . } -- line 1104 ---------------------------------------- -- line 1110 ---------------------------------------- . }; . let blk_span = anon_const.value.span; . Ok(self.mk_expr(span.to(blk_span), ExprKind::ConstBlock(anon_const), AttrVec::new())) . } . . /// Parses mutability (`mut` or nothing). . fn parse_mutability(&mut self) -> Mutability { . if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not } 53 ( 0.00%) } . . /// Possibly parses mutability (`const` or `mut`). 12 ( 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 . } 12 ( 0.00%) } . . fn parse_field_name(&mut self) -> PResult<'a, Ident> { 6 ( 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 { 9 ( 0.00%) self.parse_ident_common(true) . } . } . . fn parse_mac_args(&mut self) -> PResult<'a, P> { 5,608 ( 0.00%) self.parse_mac_args_common(true).map(P) . } . . fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> { 333 ( 0.00%) self.parse_mac_args_common(false) . } . 17,838 ( 0.00%) fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> { 15,856 ( 0.00%) Ok( 10,306 ( 0.00%) if self.check(&token::OpenDelim(DelimToken::Paren)) 297 ( 0.00%) || self.check(&token::OpenDelim(DelimToken::Bracket)) 297 ( 0.00%) || self.check(&token::OpenDelim(DelimToken::Brace)) . { 7,552 ( 0.00%) match self.parse_token_tree() { 9,440 ( 0.00%) TokenTree::Delimited(dspan, delim, tokens) => . // We've confirmed above that there is a delimiter so unwrapping is OK. . { 3,776 ( 0.00%) MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens) . } . _ => unreachable!(), . } 188 ( 0.00%) } else if !delimited_only { . if self.eat(&token::Eq) { 32 ( 0.00%) let eq_span = self.prev_token.span; . . // Collect tokens because they are used during lowering to HIR. 32 ( 0.00%) let expr = self.parse_expr_force_collect()?; 32 ( 0.00%) let span = expr.span; . 160 ( 0.00%) let token_kind = token::Interpolated(Lrc::new(token::NtExpr(expr))); 288 ( 0.00%) MacArgs::Eq(eq_span, Token::new(token_kind, span)) . } else { . MacArgs::Empty . } . } else { . return self.unexpected(); . }, . ) 13,874 ( 0.00%) } . . fn parse_or_use_outer_attributes( . &mut self, . already_parsed_attrs: Option, . ) -> PResult<'a, AttrWrapper> { 11,256 ( 0.00%) if let Some(attrs) = already_parsed_attrs { . Ok(attrs) . } else { 7,344 ( 0.00%) self.parse_outer_attributes() . } . } . . /// Parses a single token tree from the input. 1,267,120 ( 0.11%) pub(crate) fn parse_token_tree(&mut self) -> TokenTree { 977,370 ( 0.09%) 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. 837,146 ( 0.07%) 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. 581,248 ( 0.05%) 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; 65,680 ( 0.01%) let stream = frame.tree_cursor.stream.clone(); 65,680 ( 0.01%) let span = frame.span; 32,840 ( 0.00%) let delim = frame.delim; . // Consume close delimiter 65,680 ( 0.01%) self.bump(); 164,200 ( 0.01%) TokenTree::Delimited(span, delim, stream) . } . token::CloseDelim(_) | token::Eof => unreachable!(), . _ => { 251,100 ( 0.02%) self.bump(); 627,750 ( 0.06%) TokenTree::Token(self.prev_token.clone()) . } . } 1,108,730 ( 0.10%) } . . /// 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 { 3,923 ( 0.00%) let old = self.restrictions; 4,120 ( 0.00%) self.restrictions = res; . let res = f(self); 4,043 ( 0.00%) self.restrictions = old; . res . } . 19,272 ( 0.00%) fn is_crate_vis(&self) -> bool { 12,045 ( 0.00%) self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep) 21,681 ( 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. 22,900 ( 0.00%) pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> { 4,628 ( 0.00%) maybe_whole!(self, NtVis, |x| x); . 2,290 ( 0.00%) self.expected_tokens.push(TokenType::Keyword(kw::Crate)); 9,160 ( 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". 2,199 ( 0.00%) return Ok(Visibility { 6,597 ( 0.00%) span: self.token.span.shrink_to_lo(), . kind: VisibilityKind::Inherited, . tokens: None, . }); . } 91 ( 0.00%) let lo = self.prev_token.span; . 455 ( 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. 54 ( 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)`. 18 ( 0.00%) self.bump(); // `(` 12 ( 0.00%) self.bump(); // `crate` 18 ( 0.00%) self.expect(&token::CloseDelim(token::Paren))?; // `)` 6 ( 0.00%) let vis = VisibilityKind::Crate(CrateSugar::PubCrate); . return Ok(Visibility { 18 ( 0.00%) span: lo.to(self.prev_token.span), . kind: vis, . tokens: None, . }); . } else if self.is_keyword_ahead(1, &[kw::In]) { . // Parse `pub(in path)`. . self.bump(); // `(` . self.bump(); // `in` . let path = self.parse_path(PathStyle::Mod)?; // `path` -- line 1317 ---------------------------------------- -- line 1338 ---------------------------------------- . } else if let FollowedByType::No = fbt { . // Provide this diagnostic if a type cannot follow; . // in particular, if this is not a tuple struct. . self.recover_incorrect_vis_restriction()?; . // Emit diagnostic, but continue with public visibility. . } . } . 255 ( 0.00%) Ok(Visibility { span: lo, kind: VisibilityKind::Public, tokens: None }) 20,610 ( 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 { 84 ( 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. 10 ( 0.00%) fn parse_abi(&mut self) -> Option { . match self.parse_str_lit() { 6 ( 0.00%) Ok(str_lit) => Some(str_lit), . Err(Some(lit)) => match lit.kind { . ast::LitKind::Err(_) => None, . _ => { . self.struct_span_err(lit.span, "non-string ABI literal") . .span_suggestion( . lit.span, . "specify the ABI with a string literal", . "\"C\"".to_string(), -- line 1392 ---------------------------------------- -- line 1393 ---------------------------------------- . Applicability::MaybeIncorrect, . ) . .emit(); . None . } . }, . Err(None) => None, . } 8 ( 0.00%) } . 17,080 ( 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,711 ( 0.00%) |this, _attrs| Ok((f(this)?, TrailingToken::None)), . ) 17,080 ( 0.00%) } . . /// `::{` or `::*` 22,448 ( 0.00%) fn is_import_coupler(&mut self) -> bool { 11,224 ( 0.00%) self.check(&token::ModSep) . && self.look_ahead(1, |t| { 2,303 ( 0.00%) *t == token::OpenDelim(token::Brace) || *t == token::BinOp(token::Star) . }) 24,075 ( 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) . } . 98,288 ( 0.01%) pub fn emit_unclosed_delims(unclosed_delims: &mut Vec, sess: &ParseSess) { 49,144 ( 0.00%) *sess.reached_eof.borrow_mut() |= . unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none()); 49,144 ( 0.00%) for unmatched in unclosed_delims.drain(..) { . if let Some(mut e) = make_unclosed_delims_error(unmatched, sess) { . e.emit(); . } . } 98,288 ( 0.01%) } . . /// A helper struct used when building an `AttrAnnotatedTokenStream` from . /// a `LazyTokenStream`. Both delimiter and non-delimited tokens . /// are stored as `FlatToken::Token`. A vector of `FlatToken`s . /// is then 'parsed' to build up an `AttrAnnotatedTokenStream` with nested . /// `AttrAnnotatedTokenTree::Delimited` tokens . #[derive(Debug, Clone)] . pub enum FlatToken { -- line 1474 ---------------------------------------- 1,852,255 ( 0.16%) -------------------------------------------------------------------------------- -- 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); . /// }); . /// # } . /// ``` 954,993 ( 0.08%) pub fn with(&'static self, f: F) -> R . where F: FnOnce(&T) -> R . { 231,861 ( 0.02%) let val = self.inner.with(|c| c.get()); 541,382 ( 0.05%) assert!(val != 0, "cannot access a scoped thread local \ . variable without calling `set` first"); . unsafe { 218,029 ( 0.02%) f(&*(val as *const T)) . } 964,136 ( 0.09%) } . . /// 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 ---------------------------------------- 13,293 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs -------------------------------------------------------------------------------- Ir -- line 57 ---------------------------------------- . /// # Examples . /// . /// Basic usage: . /// . /// ``` . #[doc = concat!("assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 60 ( 0.00%) pub fn from_str_radix(src: &str, radix: u32) -> Result { 30 ( 0.00%) from_str_radix(src, radix) 90 ( 0.00%) } . . /// Returns the number of ones in the binary representation of `self`. . /// . /// # Examples . /// . /// Basic usage: . /// . /// ``` -- line 75 ---------------------------------------- -- line 80 ---------------------------------------- . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_math", since = "1.32.0")] . #[doc(alias = "popcount")] . #[doc(alias = "popcnt")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn count_ones(self) -> u32 { 23,670 ( 0.00%) intrinsics::ctpop(self as $ActualT) as u32 . } . . /// Returns the number of zeros in the binary representation of `self`. . /// . /// # Examples . /// . /// Basic usage: . /// -- line 96 ---------------------------------------- -- line 118 ---------------------------------------- . /// assert_eq!(n.leading_zeros(), 2); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn leading_zeros(self) -> u32 { 161,042 ( 0.01%) intrinsics::ctlz(self as $ActualT) as u32 . } . . /// Returns the number of trailing zeros in the binary representation . /// of `self`. . /// . /// # Examples . /// . /// Basic usage: -- line 134 ---------------------------------------- -- line 139 ---------------------------------------- . /// assert_eq!(n.trailing_zeros(), 3); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn trailing_zeros(self) -> u32 { 129,953 ( 0.01%) intrinsics::cttz(self) as u32 . } . . /// Returns the number of leading ones in the binary representation of `self`. . /// . /// # Examples . /// . /// Basic usage: . /// -- line 155 ---------------------------------------- -- line 204 ---------------------------------------- . #[doc = concat!("assert_eq!(n.rotate_left(", $rot, "), m);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn rotate_left(self, n: u32) -> Self { 3,383,396 ( 0.30%) intrinsics::rotate_left(self, n as $SelfT) . } . . /// Shifts the bits to the right by a specified amount, `n`, . /// wrapping the truncated bits to the beginning of the resulting . /// integer. . /// . /// Please note this isn't the same operation as the `>>` shifting operator! . /// -- line 220 ---------------------------------------- -- line 430 ---------------------------------------- . #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline] . pub const fn checked_add(self, rhs: Self) -> Option { 2 ( 0.00%) let (a, b) = self.overflowing_add(rhs); . if unlikely!(b) {None} else {Some(a)} . } . . /// Unchecked integer addition. Computes `self + rhs`, assuming overflow . /// cannot occur. . /// . /// # Safety . /// -- line 446 ---------------------------------------- -- line 456 ---------------------------------------- . )] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")] . #[inline(always)] . pub const unsafe fn unchecked_add(self, rhs: Self) -> Self { . // SAFETY: the caller must uphold the safety contract for . // `unchecked_add`. 330,445 ( 0.03%) unsafe { intrinsics::unchecked_add(self, rhs) } . } . . /// Checked addition with a signed integer. Computes `self + rhs`, . /// returning `None` if overflow occurred. . /// . /// # Examples . /// . /// Basic usage: -- line 472 ---------------------------------------- -- line 525 ---------------------------------------- . )] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")] . #[inline(always)] . pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self { . // SAFETY: the caller must uphold the safety contract for . // `unchecked_sub`. 13,352 ( 0.00%) unsafe { intrinsics::unchecked_sub(self, rhs) } . } . . /// Checked integer multiplication. Computes `self * rhs`, returning . /// `None` if overflow occurred. . /// . /// # Examples . /// . /// Basic usage: -- line 541 ---------------------------------------- -- line 1035 ---------------------------------------- . #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_add(127), ", stringify!($SelfT), "::MAX);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")] . #[inline(always)] . pub const fn saturating_add(self, rhs: Self) -> Self { 28,109 ( 0.00%) intrinsics::saturating_add(self, rhs) . } . . /// Saturating addition with a signed integer. Computes `self + rhs`, . /// saturating at the numeric bounds instead of overflowing. . /// . /// # Examples . /// . /// Basic usage: -- line 1051 ---------------------------------------- -- line 1084 ---------------------------------------- . #[doc = concat!("assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")] . #[inline(always)] . pub const fn saturating_sub(self, rhs: Self) -> Self { 846 ( 0.00%) intrinsics::saturating_sub(self, rhs) . } . . /// Saturating integer multiplication. Computes `self * rhs`, . /// saturating at the numeric bounds instead of overflowing. . /// . /// # Examples . /// . /// Basic usage: -- line 1100 ---------------------------------------- -- line 1175 ---------------------------------------- . #[doc = concat!("assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::MAX), 199);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn wrapping_add(self, rhs: Self) -> Self { 1,731,115 ( 0.15%) intrinsics::wrapping_add(self, rhs) . } . . /// Wrapping (modular) addition with a signed integer. Computes . /// `self + rhs`, wrapping around at the boundary of the type. . /// . /// # Examples . /// . /// Basic usage: -- line 1191 ---------------------------------------- -- line 1217 ---------------------------------------- . #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::MAX), 101);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn wrapping_sub(self, rhs: Self) -> Self { 589,583 ( 0.05%) intrinsics::wrapping_sub(self, rhs) . } . . /// Wrapping (modular) multiplication. Computes `self * . /// rhs`, wrapping around at the boundary of the type. . /// . /// # Examples . /// . /// Basic usage: -- line 1233 ---------------------------------------- -- line 1240 ---------------------------------------- . /// assert_eq!(25u8.wrapping_mul(12), 44); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn wrapping_mul(self, rhs: Self) -> Self { 1,984,160 ( 0.18%) intrinsics::wrapping_mul(self, rhs) . } . . /// Wrapping (modular) division. Computes `self / rhs`. . /// Wrapped division on unsigned types is just normal division. . /// There's no way wrapping could ever happen. . /// This function exists, so that all operations . /// are accounted for in the wrapping operations. . /// -- line 1256 ---------------------------------------- -- line 1397 ---------------------------------------- . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn wrapping_shl(self, rhs: u32) -> Self { . // SAFETY: the masking by the bitsize of the type ensures that we do not shift . // out of bounds . unsafe { 128 ( 0.00%) intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT) . } . } . . /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`, . /// where `mask` removes any high-order bits of `rhs` that . /// would cause the shift to exceed the bitwidth of the type. . /// . /// Note that this is *not* the same as a rotate-right; the -- line 1413 ---------------------------------------- -- line 1492 ---------------------------------------- . #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));")] . /// ``` . #[stable(feature = "wrapping", since = "1.7.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) { 291,833 ( 0.03%) let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT); . (a as Self, b) . } . . /// Calculates `self + rhs + carry` without the ability to overflow. . /// . /// Performs "ternary addition" which takes in an extra bit to add, and may return an . /// additional bit of overflow. This allows for chaining together multiple additions . /// to create "big integers" which represent larger values. -- line 1508 ---------------------------------------- -- line 1588 ---------------------------------------- . #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));")] . /// ``` . #[stable(feature = "wrapping", since = "1.7.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) { 65,787 ( 0.01%) let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT); . (a as Self, b) . } . . /// Calculates `self - rhs - borrow` without the ability to overflow. . /// . /// Performs "ternary subtraction" which takes in an extra bit to subtract, and may return . /// an additional bit of overflow. This allows for chaining together multiple subtractions . /// to create "big integers" which represent larger values. -- line 1604 ---------------------------------------- -- line 1674 ---------------------------------------- . /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true)); . /// ``` . #[stable(feature = "wrapping", since = "1.7.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) { 1,040,902 ( 0.09%) let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT); . (a as Self, b) . } . . /// Calculates the divisor when `self` is divided by `rhs`. . /// . /// Returns a tuple of the divisor along with a boolean indicating . /// whether an arithmetic overflow would occur. Note that for unsigned . /// integers overflow never occurs, so the second value is always -- line 1690 ---------------------------------------- -- line 1838 ---------------------------------------- . #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));")] . /// ``` . #[stable(feature = "wrapping", since = "1.7.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) { 48 ( 0.00%) (self.wrapping_shl(rhs), (rhs > ($BITS - 1))) . } . . /// Shifts self right by `rhs` bits. . /// . /// Returns a tuple of the shifted version of self along with a boolean . /// indicating whether the shift value was larger than or equal to the . /// number of bits. If the shift value is too large, then value is . /// masked (N-1) where N is the number of bits, and this value is then -- line 1854 ---------------------------------------- -- line 2132 ---------------------------------------- . #[doc = concat!("assert!(16", stringify!($SelfT), ".is_power_of_two());")] . #[doc = concat!("assert!(!10", stringify!($SelfT), ".is_power_of_two());")] . /// ``` . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")] . #[inline(always)] . pub const fn is_power_of_two(self) -> bool { 150 ( 0.00%) self.count_ones() == 1 . } . . // Returns one less than next power of two. . // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8) . // . // 8u8.one_less_than_next_power_of_two() == 7 . // 6u8.one_less_than_next_power_of_two() == 7 . // . // This method cannot overflow, as in the `next_power_of_two` . // overflow cases it instead ends up returning the maximum value . // of the type, and can return 0 for 0. . #[inline] . #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")] . const fn one_less_than_next_power_of_two(self) -> Self { 41,410 ( 0.00%) if self <= 1 { return 0; } . 25,250 ( 0.00%) let p = self - 1; . // SAFETY: Because `p > 0`, it cannot consist entirely of leading zeros. . // That means the shift is always in-bounds, and some processors . // (such as intel pre-haswell) have more efficient ctlz . // intrinsics when the argument is non-zero. 75,719 ( 0.01%) let z = unsafe { intrinsics::ctlz_nonzero(p) }; 25,241 ( 0.00%) <$SelfT>::MAX >> z . } . . /// Returns the smallest power of two greater than or equal to `self`. . /// . /// When return value overflows (i.e., `self > (1 << (N-1))` for type . /// `uN`), it panics in debug mode and the return value is wrapped to 0 in . /// release mode (the only situation in which method can return 0). . /// -- line 2171 ---------------------------------------- -- line 2179 ---------------------------------------- . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline] . #[rustc_inherit_overflow_checks] . pub const fn next_power_of_two(self) -> Self { 9,070 ( 0.00%) self.one_less_than_next_power_of_two() + 1 . } . . /// Returns the smallest power of two greater than or equal to `n`. If . /// the next power of two is greater than the type's maximum value, . /// `None` is returned, otherwise the power of two is wrapped in `Some`. . /// . /// # Examples . /// -- line 2195 ---------------------------------------- 27,194 ( 0.00%) -------------------------------------------------------------------------------- -- 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; . 180,864 ( 0.02%) fn visit_span(&mut self, span: &mut Span) { 120,576 ( 0.01%) *span = span.apply_mark(self.0.to_expn_id(), self.1) 160,768 ( 0.01%) } . } . . /// An iterator over the token trees in a delimited token tree (`{ ... }`) or a sequence (`$(...)`). . enum Frame { . Delimited { forest: Lrc, idx: usize, span: DelimSpan }, . Sequence { forest: Lrc, idx: usize, sep: Option }, . } . . impl Frame { . /// Construct a new frame around the delimited set of tokens. . fn new(tts: Vec) -> Frame { . let forest = Lrc::new(mbe::Delimited { delim: token::NoDelim, tts }); 8,384 ( 0.00%) Frame::Delimited { forest, idx: 0, span: DelimSpan::dummy() } . } . } . . impl Iterator for Frame { . type Item = mbe::TokenTree; . . fn next(&mut self) -> Option { 977,928 ( 0.09%) match *self { 45,260 ( 0.00%) Frame::Delimited { ref forest, ref mut idx, .. } => { 67,890 ( 0.01%) *idx += 1; . forest.tts.get(*idx - 1).cloned() . } 665,556 ( 0.06%) Frame::Sequence { ref forest, ref mut idx, .. } => { 665,556 ( 0.06%) *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. 10,480 ( 0.00%) pub(super) fn transcribe<'a>( . cx: &ExtCtxt<'a>, . interp: &FxHashMap, . src: Vec, . transparency: Transparency, . ) -> PResult<'a, TokenStream> { . // Nothing for us to transcribe... 1,048 ( 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. 8,384 ( 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(); 4,192 ( 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. 1,029,638 ( 0.09%) 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. 463,656 ( 0.04%) if let Frame::Sequence { idx, sep, .. } = stack.last_mut().unwrap() { . let (repeat_idx, repeat_len) = repeats.last_mut().unwrap(); 442,520 ( 0.04%) *repeat_idx += 1; 110,630 ( 0.01%) if repeat_idx < repeat_len { 107,520 ( 0.01%) *idx = 0; 215,040 ( 0.02%) if let Some(sep) = sep { 11,872 ( 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`. 16,788 ( 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. 21,136 ( 0.00%) Frame::Delimited { forest, span, .. } => { 5,284 ( 0.00%) if result_stack.is_empty() { . // No results left to compute! We are back at the top-level. 6,288 ( 0.00%) return Ok(TokenStream::new(result)); . } . . // Step back into the parent Delimited. 55,068 ( 0.00%) let tree = TokenTree::Delimited(span, forest.delim, TokenStream::new(result)); 12,708 ( 0.00%) result = result_stack.pop().unwrap(); . result.push(tree.into()); . } 10,568 ( 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. 771,408 ( 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. 12,568 ( 0.00%) seq @ mbe::TokenTree::Sequence(..) => { 21,994 ( 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. 21,994 ( 0.00%) let mbe::TokenTree::Sequence(sp, seq) = seq else { . unreachable!() . }; . . // Is the repetition empty? 6,284 ( 0.00%) if len == 0 { 32 ( 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. 27,990 ( 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. 668,988 ( 0.06%) mbe::TokenTree::MetaVar(mut sp, mut orignal_ident) => { . // Find the matched nonterminal from the macro invocation, and use it to replace . // the meta-var. 445,992 ( 0.04%) let ident = MacroRulesNormalizedIdent::new(orignal_ident); 668,988 ( 0.06%) if let Some(cur_matched) = lookup_cur_matched(ident, interp, &repeats) { 334,494 ( 0.03%) if let MatchedNonterminal(nt) = cur_matched { 334,494 ( 0.03%) 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. 5,796 ( 0.00%) marker.visit_span(&mut sp); 11,592 ( 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). 25,416 ( 0.00%) mbe::TokenTree::Delimited(mut span, delimited) => { . mut_visit::visit_delim_span(&mut span, &mut marker); 25,416 ( 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) => { 58,152 ( 0.01%) let mut tt = TokenTree::Token(token); 29,076 ( 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"), . } . } 12,576 ( 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`. 1,032,003 ( 0.09%) 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 { 665,076 ( 0.06%) match matched { . MatchedNonterminal(_) => break, 110,766 ( 0.01%) MatchedSeq(ref ads) => matched = ads.get(idx).unwrap(), . } . } . . matched . }) 1,032,003 ( 0.09%) } . . /// 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. 35,343 ( 0.00%) fn with(self, other: LockstepIterSize) -> LockstepIterSize { 12,185 ( 0.00%) match self { . LockstepIterSize::Unconstrained => other, . LockstepIterSize::Contradiction(_) => self, 1,448 ( 0.00%) LockstepIterSize::Constraint(l_len, ref l_id) => match other { . LockstepIterSize::Unconstrained => self, . LockstepIterSize::Contradiction(_) => other, 51 ( 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) . } . }, . } 27,893 ( 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. 70,690 ( 0.01%) fn lockstep_iter_size( . tree: &mbe::TokenTree, . interpolations: &FxHashMap, . repeats: &[(usize, usize)], . ) -> LockstepIterSize { . use mbe::TokenTree; 49,483 ( 0.00%) match *tree { . TokenTree::Delimited(_, ref delimed) => { 204 ( 0.00%) delimed.tts.iter().fold(LockstepIterSize::Unconstrained, |size, tt| { 7,325 ( 0.00%) size.with(lockstep_iter_size(tt, interpolations, repeats)) . }) . } . TokenTree::Sequence(_, ref seq) => { 3,142 ( 0.00%) seq.tts.iter().fold(LockstepIterSize::Unconstrained, |size, tt| { 60,456 ( 0.01%) size.with(lockstep_iter_size(tt, interpolations, repeats)) . }) . } . TokenTree::MetaVar(_, name) | TokenTree::MetaVarDecl(_, name, _) => { 6,338 ( 0.00%) let name = MacroRulesNormalizedIdent::new(name); 28,521 ( 0.00%) match lookup_cur_matched(name, interpolations, repeats) { 6,338 ( 0.00%) Some(matched) => match matched { . MatchedNonterminal(_) => LockstepIterSize::Unconstrained, 18,954 ( 0.00%) MatchedSeq(ref ads) => LockstepIterSize::Constraint(ads.len(), name), . }, . _ => LockstepIterSize::Unconstrained, . } . } . TokenTree::Token(..) => LockstepIterSize::Unconstrained, . } 56,552 ( 0.01%) } 2,793,568 ( 0.25%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs -------------------------------------------------------------------------------- Ir -- line 84 ---------------------------------------- . pub struct SessionGlobals { . symbol_interner: symbol::Interner, . span_interner: Lock, . hygiene_data: Lock, . source_map: Lock>>, . } . . impl SessionGlobals { 12 ( 0.00%) pub fn new(edition: Edition) -> SessionGlobals { 50 ( 0.00%) SessionGlobals { 2 ( 0.00%) symbol_interner: symbol::Interner::fresh(), . span_interner: Lock::new(span_encoding::SpanInterner::default()), 6 ( 0.00%) hygiene_data: Lock::new(hygiene::HygieneData::new(edition)), . source_map: Lock::new(None), . } 10 ( 0.00%) } . } . . #[inline] . pub fn create_session_globals_then(edition: Edition, f: impl FnOnce() -> R) -> R { 1 ( 0.00%) assert!( . !SESSION_GLOBALS.is_set(), . "SESSION_GLOBALS should never be overwritten! \ . Use another thread if you need another SessionGlobals" . ); 3 ( 0.00%) let session_globals = SessionGlobals::new(edition); 7 ( 0.00%) SESSION_GLOBALS.set(&session_globals, f) 1 ( 0.00%) } . . #[inline] . pub fn set_session_globals_then(session_globals: &SessionGlobals, f: impl FnOnce() -> R) -> R { . assert!( . !SESSION_GLOBALS.is_set(), . "SESSION_GLOBALS should never be overwritten! \ . Use another thread if you need another SessionGlobals" . ); -- line 119 ---------------------------------------- -- line 120 ---------------------------------------- . SESSION_GLOBALS.set(session_globals, f) . } . . #[inline] . pub fn create_default_session_if_not_set_then(f: F) -> R . where . F: FnOnce(&SessionGlobals) -> R, . { 4 ( 0.00%) create_session_if_not_set_then(edition::DEFAULT_EDITION, f) . } . . #[inline] . pub fn create_session_if_not_set_then(edition: Edition, f: F) -> R . where . F: FnOnce(&SessionGlobals) -> R, . { 1 ( 0.00%) if !SESSION_GLOBALS.is_set() { 3 ( 0.00%) let session_globals = SessionGlobals::new(edition); 11 ( 0.00%) SESSION_GLOBALS.set(&session_globals, || SESSION_GLOBALS.with(f)) 1 ( 0.00%) } else { . SESSION_GLOBALS.with(f) . } . } . . #[inline] . pub fn with_session_globals(f: F) -> R . where . F: FnOnce(&SessionGlobals) -> R, . { 1,363,229 ( 0.12%) SESSION_GLOBALS.with(f) . } . . #[inline] . pub fn create_default_session_globals_then(f: impl FnOnce() -> R) -> R { . create_session_globals_then(edition::DEFAULT_EDITION, f) . } . . // If this ever becomes non thread-local, `decode_syntax_context` . // and `decode_expn_id` will need to be updated to handle concurrent . // deserialization. . scoped_tls::scoped_thread_local!(static SESSION_GLOBALS: SessionGlobals); . . // FIXME: We should use this enum or something like it to get rid of the . // use of magic `/rust/1.x/...` paths across the board. 65 ( 0.00%) #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd)] 1,040 ( 0.00%) #[derive(Decodable)] . pub enum RealFileName { 8 ( 0.00%) LocalPath(PathBuf), . /// For remapped paths (namely paths into libstd that have been mapped . /// to the appropriate spot on the local host's file system, and local file . /// system paths that have been remapped with `FilePathMapping`), . Remapped { . /// `local_path` is the (host-dependent) local path to the file. This is . /// None if the file was imported from another crate . local_path: Option, . /// `virtual_name` is the stable path rustc will store internally within -- line 175 ---------------------------------------- -- line 179 ---------------------------------------- . } . . impl Hash for RealFileName { . fn hash(&self, state: &mut H) { . // To prevent #70924 from happening again we should only hash the . // remapped (virtualized) path if that exists. This is because . // virtualized paths to sysroot crates (/rust/$hash or /rust/$version) . // remain stable even if the corresponding local_path changes 2,739 ( 0.00%) self.remapped_path_if_available().hash(state) . } . } . . // This is functionally identical to #[derive(Encodable)], with the exception of . // an added assert statement . impl Encodable for RealFileName { . fn encode(&self, encoder: &mut S) -> Result<(), S::Error> { 14 ( 0.00%) encoder.emit_enum(|encoder| match *self { . RealFileName::LocalPath(ref local_path) => { 56 ( 0.00%) encoder.emit_enum_variant("LocalPath", 0, 1, |encoder| { . encoder.emit_enum_variant_arg(true, |encoder| local_path.encode(encoder))?; . Ok(()) . }) . } . . RealFileName::Remapped { ref local_path, ref virtual_name } => encoder . .emit_enum_variant("Remapped", 1, 2, |encoder| { . // For privacy and build reproducibility, we must not embed host-dependant path in artifacts -- line 205 ---------------------------------------- -- line 224 ---------------------------------------- . p.as_ref().map(PathBuf::as_path) . } . } . } . . /// Returns the path suitable for reading from the file system on the local host, . /// if this information exists. . /// Avoid embedding this in build artifacts; see `remapped_path_if_available()` for that. 2 ( 0.00%) pub fn into_local_path(self) -> Option { 2 ( 0.00%) match self { . RealFileName::LocalPath(p) => Some(p), . RealFileName::Remapped { local_path: p, virtual_name: _ } => p, . } 3 ( 0.00%) } . . /// Returns the path suitable for embedding into build artifacts. This would still . /// be a local path if it has not been remapped. A remapped path will not correspond . /// to a valid file system path: see `local_path_if_available()` for something that . /// is more likely to return paths into the local host file system. . pub fn remapped_path_if_available(&self) -> &Path { 2,168 ( 0.00%) match self { . RealFileName::LocalPath(p) . | RealFileName::Remapped { local_path: _, virtual_name: p } => &p, . } 8 ( 0.00%) } . . /// Returns the path suitable for reading from the file system on the local host, . /// if this information exists. Otherwise returns the remapped name. . /// Avoid embedding this in build artifacts; see `remapped_path_if_available()` for that. . pub fn local_path_if_available(&self) -> &Path { 23 ( 0.00%) match self { . RealFileName::LocalPath(path) . | RealFileName::Remapped { local_path: None, virtual_name: path } . | RealFileName::Remapped { local_path: Some(path), virtual_name: _ } => path, . } . } . . pub fn to_string_lossy(&self, display_pref: FileNameDisplayPreference) -> Cow<'_, str> { 23 ( 0.00%) match display_pref { . FileNameDisplayPreference::Local => self.local_path_if_available().to_string_lossy(), . FileNameDisplayPreference::Remapped => { . self.remapped_path_if_available().to_string_lossy() . } . } . } . } . . /// Differentiates between real files and common virtual files. 7,235 ( 0.00%) #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash)] 6,361 ( 0.00%) #[derive(Decodable, Encodable)] . pub enum FileName { . Real(RealFileName), . /// Call to `quote!`. . QuoteExpansion(u64), . /// Command line. . Anon(u64), . /// Hack in `src/librustc_ast/parse.rs`. . // FIXME(jseyfried) 32 ( 0.00%) MacroExpansion(u64), . ProcMacroSourceCode(u64), . /// Strings provided as `--cfg [cfgspec]` stored in a `crate_cfg`. . CfgSpec(u64), . /// Strings provided as crate attributes in the CLI. . CliCrateAttr(u64), . /// Custom sources for explicit parser calls from plugins and drivers. . Custom(String), . DocTest(PathBuf, isize), . /// Post-substitution inline assembly from LLVM. . InlineAsm(u64), . } . . impl From for FileName { 49 ( 0.00%) fn from(p: PathBuf) -> Self { 14 ( 0.00%) assert!(!p.to_string_lossy().ends_with('>')); 42 ( 0.00%) FileName::Real(RealFileName::LocalPath(p)) 49 ( 0.00%) } . } . 2 ( 0.00%) #[derive(Clone, Copy, Eq, PartialEq, Hash, Debug)] . pub enum FileNameDisplayPreference { . Remapped, . Local, . } . . pub struct FileNameDisplay<'a> { . inner: &'a FileName, . display_pref: FileNameDisplayPreference, . } . . impl fmt::Display for FileNameDisplay<'_> { 92 ( 0.00%) fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { . use FileName::*; 138 ( 0.00%) match *self.inner { . Real(ref name) => { 138 ( 0.00%) write!(fmt, "{}", name.to_string_lossy(self.display_pref)) . } . QuoteExpansion(_) => write!(fmt, ""), . MacroExpansion(_) => write!(fmt, ""), . Anon(_) => write!(fmt, ""), . ProcMacroSourceCode(_) => write!(fmt, ""), . CfgSpec(_) => write!(fmt, ""), . CliCrateAttr(_) => write!(fmt, ""), . Custom(ref s) => write!(fmt, "<{}>", s), . DocTest(ref path, _) => write!(fmt, "{}", path.display()), . InlineAsm(_) => write!(fmt, ""), . } 115 ( 0.00%) } . } . . impl FileNameDisplay<'_> { . pub fn to_string_lossy(&self) -> Cow<'_, str> { . match self.inner { . FileName::Real(ref inner) => inner.to_string_lossy(self.display_pref), . _ => Cow::from(format!("{}", self)), . } . } . } . . impl FileName { . pub fn is_real(&self) -> bool { . use FileName::*; 1,066 ( 0.00%) match *self { . Real(_) => true, . Anon(_) . | MacroExpansion(_) . | ProcMacroSourceCode(_) . | CfgSpec(_) . | CliCrateAttr(_) . | Custom(_) . | QuoteExpansion(_) -- line 353 ---------------------------------------- -- line 357 ---------------------------------------- . } . . pub fn prefer_remapped(&self) -> FileNameDisplay<'_> { . FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Remapped } . } . . // This may include transient local filesystem information. . // Must not be embedded in build outputs. 7 ( 0.00%) pub fn prefer_local(&self) -> FileNameDisplay<'_> { . FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Local } 14 ( 0.00%) } . . pub fn display(&self, display_pref: FileNameDisplayPreference) -> FileNameDisplay<'_> { . FileNameDisplay { inner: self, display_pref } . } . 160 ( 0.00%) pub fn macro_expansion_source_code(src: &str) -> FileName { . let mut hasher = StableHasher::new(); . src.hash(&mut hasher); 64 ( 0.00%) FileName::MacroExpansion(hasher.finish()) 160 ( 0.00%) } . . pub fn anon_source_code(src: &str) -> FileName { . let mut hasher = StableHasher::new(); . src.hash(&mut hasher); . FileName::Anon(hasher.finish()) . } . . pub fn proc_macro_source_code(src: &str) -> FileName { -- line 385 ---------------------------------------- -- line 423 ---------------------------------------- . /// that the length of the span is equal to `span.hi - span.lo`; there may be space in the . /// [`BytePos`] range between files. . /// . /// `SpanData` is public because `Span` uses a thread-local interner and can't be . /// sent to other threads, but some pieces of performance infra run in a separate thread. . /// Using `Span` is generally preferred. . #[derive(Clone, Copy, Hash, PartialEq, Eq)] . pub struct SpanData { 9 ( 0.00%) pub lo: BytePos, 9 ( 0.00%) pub hi: BytePos, . /// Information about where the macro came from, if this piece of . /// code was created by a macro expansion. 27 ( 0.00%) pub ctxt: SyntaxContext, 9 ( 0.00%) pub parent: Option, . } . . // Order spans by position in the file. . impl Ord for SpanData { . fn cmp(&self, other: &Self) -> Ordering { . let SpanData { . lo: s_lo, . hi: s_hi, -- line 444 ---------------------------------------- -- line 485 ---------------------------------------- . } . #[inline] . pub fn with_parent(&self, parent: Option) -> Span { . Span::new(self.lo, self.hi, self.ctxt, parent) . } . /// Returns `true` if this is a dummy span with any hygienic context. . #[inline] . pub fn is_dummy(self) -> bool { 531,877 ( 0.05%) self.lo.0 == 0 && self.hi.0 == 0 . } . /// Returns `true` if `self` fully encloses `other`. . pub fn contains(self, other: Self) -> bool { 465 ( 0.00%) self.lo <= other.lo && other.hi <= self.hi . } . } . . // The interner is pointed to by a thread local value which is only set on the main thread . // with parallelization is disabled. So we don't allow `Span` to transfer between threads . // to avoid panics and other errors, even though it would be memory safe to do so. . #[cfg(not(parallel_compiler))] . impl !Send for Span {} . #[cfg(not(parallel_compiler))] . impl !Sync for Span {} . . impl PartialOrd for Span { 16,496 ( 0.00%) fn partial_cmp(&self, rhs: &Self) -> Option { 12,372 ( 0.00%) PartialOrd::partial_cmp(&self.data(), &rhs.data()) 16,496 ( 0.00%) } . } . impl Ord for Span { . fn cmp(&self, rhs: &Self) -> Ordering { . Ord::cmp(&self.data(), &rhs.data()) . } . } . . /// A collection of `Span`s. . /// . /// Spans have two orthogonal attributes: . /// . /// - They can be *primary spans*. In this case they are the locus of . /// the error, and would be rendered with `^^^`. . /// - They can have a *label*. In this case, the label is written next . /// to the mark in the snippet when we render. 253 ( 0.00%) #[derive(Clone, Debug, Hash, PartialEq, Eq, Encodable, Decodable)] . pub struct MultiSpan { . primary_spans: Vec, 46 ( 0.00%) span_labels: Vec<(Span, String)>, . } . . impl Span { . #[inline] . pub fn lo(self) -> BytePos { . self.data().lo . } . #[inline] 14,832 ( 0.00%) pub fn with_lo(self, lo: BytePos) -> Span { . self.data().with_lo(lo) 9,888 ( 0.00%) } . #[inline] 1,988 ( 0.00%) pub fn hi(self) -> BytePos { . self.data().hi 1,988 ( 0.00%) } . #[inline] 6,390 ( 0.00%) pub fn with_hi(self, hi: BytePos) -> Span { . self.data().with_hi(hi) 4,260 ( 0.00%) } . #[inline] . pub fn ctxt(self) -> SyntaxContext { . self.data_untracked().ctxt . } . #[inline] 12,755 ( 0.00%) pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span { . self.data_untracked().with_ctxt(ctxt) 7,653 ( 0.00%) } . #[inline] . pub fn parent(self) -> Option { . self.data().parent . } . #[inline] . pub fn with_parent(self, ctxt: Option) -> Span { . self.data().with_parent(ctxt) . } -- line 566 ---------------------------------------- -- line 600 ---------------------------------------- . /// Returns a new span representing an empty span at the beginning of this span. . #[inline] . pub fn shrink_to_lo(self) -> Span { . let span = self.data_untracked(); . span.with_hi(span.lo) . } . /// Returns a new span representing an empty span at the end of this span. . #[inline] 15 ( 0.00%) pub fn shrink_to_hi(self) -> Span { . let span = self.data_untracked(); . span.with_lo(span.hi) 10 ( 0.00%) } . . #[inline] . /// Returns `true` if `hi == lo`. . pub fn is_empty(self) -> bool { . let span = self.data_untracked(); . span.hi == span.lo . } . . /// Returns `self` if `self` is not the dummy span, and `other` otherwise. . pub fn substitute_dummy(self, other: Span) -> Span { . if self.is_dummy() { other } else { self } . } . . /// Returns `true` if `self` fully encloses `other`. 1,395 ( 0.00%) pub fn contains(self, other: Span) -> bool { . let span = self.data(); . let other = other.data(); . span.contains(other) 930 ( 0.00%) } . . /// Returns `true` if `self` touches `other`. . pub fn overlaps(self, other: Span) -> bool { . let span = self.data(); . let other = other.data(); . span.lo < other.hi && other.lo < span.hi . } . -- line 638 ---------------------------------------- -- line 663 ---------------------------------------- . /// The `Span` for the tokens in the previous macro expansion from which `self` was generated, . /// if any. . pub fn parent_callsite(self) -> Option { . let expn_data = self.ctxt().outer_expn_data(); . if !expn_data.is_root() { Some(expn_data.call_site) } else { None } . } . . /// Walk down the expansion ancestors to find a span that's contained within `outer`. 590 ( 0.00%) pub fn find_ancestor_inside(mut self, outer: Span) -> Option { 295 ( 0.00%) while !outer.contains(self) { . self = self.parent_callsite()?; . } . Some(self) 649 ( 0.00%) } . . /// Edition of the crate from which this span came. 3,810 ( 0.00%) pub fn edition(self) -> edition::Edition { . self.ctxt().edition() 2,540 ( 0.00%) } . . #[inline] . pub fn rust_2015(self) -> bool { 832 ( 0.00%) self.edition() == edition::Edition::Edition2015 . } . . #[inline] . pub fn rust_2018(self) -> bool { 377 ( 0.00%) self.edition() >= edition::Edition::Edition2018 . } . . #[inline] . pub fn rust_2021(self) -> bool { 457 ( 0.00%) self.edition() >= edition::Edition::Edition2021 . } . . /// Returns the source callee. . /// . /// Returns `None` if the supplied span has no expansion trace, . /// else returns the `ExpnData` for the macro definition . /// corresponding to the source callsite. . pub fn source_callee(self) -> Option { -- line 703 ---------------------------------------- -- line 707 ---------------------------------------- . } . let expn_data = self.ctxt().outer_expn_data(); . if !expn_data.is_root() { Some(source_callee(expn_data)) } else { None } . } . . /// Checks if a span is "internal" to a macro in which `#[unstable]` . /// items can be used (that is, a macro marked with . /// `#[allow_internal_unstable]`). 530 ( 0.00%) pub fn allows_unstable(self, feature: Symbol) -> bool { 106 ( 0.00%) self.ctxt() . .outer_expn_data() . .allow_internal_unstable . .map_or(false, |features| features.iter().any(|&f| f == feature)) 424 ( 0.00%) } . . /// Checks if this span arises from a compiler desugaring of kind `kind`. 2,926 ( 0.00%) pub fn is_desugaring(self, kind: DesugaringKind) -> bool { 2,508 ( 0.00%) match self.ctxt().outer_expn_data().kind { . ExpnKind::Desugaring(k) => k == kind, . _ => false, . } 2,090 ( 0.00%) } . . /// Returns the compiler desugaring that created this span, or `None` . /// if this span is not from a desugaring. 65 ( 0.00%) pub fn desugaring_kind(self) -> Option { 78 ( 0.00%) match self.ctxt().outer_expn_data().kind { . ExpnKind::Desugaring(k) => Some(k), . _ => None, . } 52 ( 0.00%) } . . /// Checks if a span is "internal" to a macro in which `unsafe` . /// can be used without triggering the `unsafe_code` lint. . // (that is, a macro marked with `#[allow_internal_unsafe]`). . pub fn allows_unsafe(self) -> bool { . self.ctxt().outer_expn_data().allow_internal_unsafe . } . 20 ( 0.00%) pub fn macro_backtrace(mut self) -> impl Iterator { . let mut prev_span = DUMMY_SP; . std::iter::from_fn(move || { . loop { 32 ( 0.00%) let expn_data = self.ctxt().outer_expn_data(); 24 ( 0.00%) if expn_data.is_root() { 4 ( 0.00%) return None; . } . . let is_recursive = expn_data.call_site.source_equal(prev_span); . . prev_span = self; . self = expn_data.call_site; . . // Don't print recursive invocations. . if !is_recursive { . return Some(expn_data); . } . } . }) 40 ( 0.00%) } . . /// Returns a `Span` that would enclose both `self` and `end`. . /// . /// ```text . /// ____ ___ . /// self lorem ipsum end . /// ^^^^^^^^^^^^^^^^^^^^ . /// ``` 125,444 ( 0.01%) pub fn to(self, end: Span) -> Span { . let span_data = self.data(); . let end_data = end.data(); . // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480). . // Return the macro span on its own to avoid weird diagnostic output. It is preferable to . // have an incomplete span than a completely nonsensical one. 22,374 ( 0.00%) if span_data.ctxt != end_data.ctxt { 434 ( 0.00%) if span_data.ctxt == SyntaxContext::root() { . return end; 390 ( 0.00%) } else if end_data.ctxt == SyntaxContext::root() { . return self; . } . // Both spans fall within a macro. . // FIXME(estebank): check if it is the *same* macro. . } . Span::new( . cmp::min(span_data.lo, end_data.lo), . cmp::max(span_data.hi, end_data.hi), . if span_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt }, 76,867 ( 0.01%) if span_data.parent == end_data.parent { span_data.parent } else { None }, . ) 102,636 ( 0.01%) } . . /// Returns a `Span` between the end of `self` to the beginning of `end`. . /// . /// ```text . /// ____ ___ . /// self lorem ipsum end . /// ^^^^^^^^^^^^^ . /// ``` 132 ( 0.00%) pub fn between(self, end: Span) -> Span { . let span = self.data(); . let end = end.data(); . Span::new( . span.hi, . end.lo, . if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt }, 84 ( 0.00%) if span.parent == end.parent { span.parent } else { None }, . ) 96 ( 0.00%) } . . /// Returns a `Span` from the beginning of `self` until the beginning of `end`. . /// . /// ```text . /// ____ ___ . /// self lorem ipsum end . /// ^^^^^^^^^^^^^^^^^ . /// ``` 506 ( 0.00%) pub fn until(self, end: Span) -> Span { . // Most of this function's body is copied from `to`. . // We can't just do `self.to(end.shrink_to_lo())`, . // because to also does some magic where it uses min/max so . // it can handle overlapping spans. Some advanced mis-use of . // `until` with different ctxts makes this visible. . let span_data = self.data(); . let end_data = end.data(); . // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480). . // Return the macro span on its own to avoid weird diagnostic output. It is preferable to . // have an incomplete span than a completely nonsensical one. 92 ( 0.00%) if span_data.ctxt != end_data.ctxt { . if span_data.ctxt == SyntaxContext::root() { . return end; . } else if end_data.ctxt == SyntaxContext::root() { . return self; . } . // Both spans fall within a macro. . // FIXME(estebank): check if it is the *same* macro. . } . Span::new( . span_data.lo, . end_data.lo, . if end_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt }, 322 ( 0.00%) if span_data.parent == end_data.parent { span_data.parent } else { None }, . ) 414 ( 0.00%) } . 88 ( 0.00%) pub fn from_inner(self, inner: InnerSpan) -> Span { . let span = self.data(); . Span::new( . span.lo + BytePos::from_usize(inner.start), . span.lo + BytePos::from_usize(inner.end), . span.ctxt, . span.parent, . ) 56 ( 0.00%) } . . /// Equivalent of `Span::def_site` from the proc macro API, . /// except that the location is taken from the `self` span. . pub fn with_def_site_ctxt(self, expn_id: ExpnId) -> Span { 2,372 ( 0.00%) self.with_ctxt_from_mark(expn_id, Transparency::Opaque) . } . . /// Equivalent of `Span::call_site` from the proc macro API, . /// except that the location is taken from the `self` span. . pub fn with_call_site_ctxt(self, expn_id: ExpnId) -> Span { 2 ( 0.00%) self.with_ctxt_from_mark(expn_id, Transparency::Transparent) . } . . /// Equivalent of `Span::mixed_site` from the proc macro API, . /// except that the location is taken from the `self` span. . pub fn with_mixed_site_ctxt(self, expn_id: ExpnId) -> Span { . self.with_ctxt_from_mark(expn_id, Transparency::SemiTransparent) . } . . /// Produces a span with the same location as `self` and context produced by a macro with the . /// given ID and transparency, assuming that macro was defined directly and not produced by . /// some other macro (which is the case for built-in and procedural macros). 14,244 ( 0.00%) pub fn with_ctxt_from_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span { . self.with_ctxt(SyntaxContext::root().apply_mark(expn_id, transparency)) 8,309 ( 0.00%) } . . #[inline] . pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span { . let span = self.data(); 180,864 ( 0.02%) span.with_ctxt(span.ctxt.apply_mark(expn_id, transparency)) . } . . #[inline] . pub fn remove_mark(&mut self) -> ExpnId { . let mut span = self.data(); . let mark = span.ctxt.remove_mark(); . *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark -- line 897 ---------------------------------------- -- line 901 ---------------------------------------- . pub fn adjust(&mut self, expn_id: ExpnId) -> Option { . let mut span = self.data(); . let mark = span.ctxt.adjust(expn_id); . *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark . } . . #[inline] 14,292 ( 0.00%) pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option { 9,528 ( 0.00%) let mut span = self.data(); 7,860 ( 0.00%) let mark = span.ctxt.normalize_to_macros_2_0_and_adjust(expn_id); 14,292 ( 0.00%) *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark 15,800 ( 0.00%) } . . #[inline] . pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option> { . let mut span = self.data(); . let mark = span.ctxt.glob_adjust(expn_id, glob_span); . *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark . } -- line 922 ---------------------------------------- -- line 929 ---------------------------------------- . ) -> Option> { . let mut span = self.data(); . let mark = span.ctxt.reverse_glob_adjust(expn_id, glob_span); . *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark . } . . #[inline] 11,320 ( 0.00%) pub fn normalize_to_macros_2_0(self) -> Span { . let span = self.data(); . span.with_ctxt(span.ctxt.normalize_to_macros_2_0()) 9,905 ( 0.00%) } . . #[inline] . pub fn normalize_to_macro_rules(self) -> Span { . let span = self.data(); . span.with_ctxt(span.ctxt.normalize_to_macro_rules()) . } . } . -- line 948 ---------------------------------------- -- line 958 ---------------------------------------- . . /// What label should we attach to this span (if any)? . pub label: Option, . } . . impl Default for Span { . fn default() -> Self { . DUMMY_SP 2 ( 0.00%) } . } . . impl Encodable for Span { . default fn encode(&self, s: &mut E) -> Result<(), E::Error> { . let span = self.data(); . s.emit_struct(false, |s| { . s.emit_struct_field("lo", true, |s| span.lo.encode(s))?; . s.emit_struct_field("hi", false, |s| span.hi.encode(s)) -- line 974 ---------------------------------------- -- line 990 ---------------------------------------- . /// any spans that are debug-printed during the closure's execution. . /// . /// Normally, the global `TyCtxt` is used to retrieve the `SourceMap` . /// (see `rustc_interface::callbacks::span_debug1`). However, some parts . /// of the compiler (e.g. `rustc_parse`) may debug-print `Span`s before . /// a `TyCtxt` is available. In this case, we fall back to . /// the `SourceMap` provided to this function. If that is not available, . /// we fall back to printing the raw `Span` field values. 9 ( 0.00%) pub fn with_source_map T>(source_map: Lrc, f: F) -> T { . with_session_globals(|session_globals| { 2 ( 0.00%) *session_globals.source_map.borrow_mut() = Some(source_map); . }); . struct ClearSourceMap; . impl Drop for ClearSourceMap { . fn drop(&mut self) { . with_session_globals(|session_globals| { 1 ( 0.00%) session_globals.source_map.borrow_mut().take(); . }); . } . } . . let _guard = ClearSourceMap; 4 ( 0.00%) f() 8 ( 0.00%) } . . pub fn debug_with_source_map( . span: Span, . f: &mut fmt::Formatter<'_>, . source_map: &SourceMap, . ) -> fmt::Result { . write!(f, "{} ({:?})", source_map.span_to_diagnostic_string(span), span.ctxt()) . } -- line 1021 ---------------------------------------- -- line 1044 ---------------------------------------- . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . (*SPAN_DEBUG)(Span::new(self.lo, self.hi, self.ctxt, self.parent), f) . } . } . . impl MultiSpan { . #[inline] . pub fn new() -> MultiSpan { 50 ( 0.00%) MultiSpan { primary_spans: vec![], span_labels: vec![] } . } . 5 ( 0.00%) pub fn from_span(primary_span: Span) -> MultiSpan { 635 ( 0.00%) MultiSpan { primary_spans: vec![primary_span], span_labels: vec![] } 5 ( 0.00%) } . . pub fn from_spans(mut vec: Vec) -> MultiSpan { . vec.sort(); 25 ( 0.00%) MultiSpan { primary_spans: vec, span_labels: vec![] } . } . 12 ( 0.00%) pub fn push_span_label(&mut self, span: Span, label: String) { 4 ( 0.00%) self.span_labels.push((span, label)); 10 ( 0.00%) } . . /// Selects the first primary span (if any). . pub fn primary_span(&self) -> Option { . self.primary_spans.first().cloned() 108 ( 0.00%) } . . /// Returns all primary spans. . pub fn primary_spans(&self) -> &[Span] { . &self.primary_spans 68 ( 0.00%) } . . /// Returns `true` if any of the primary spans are displayable. 84 ( 0.00%) pub fn has_primary_spans(&self) -> bool { 12 ( 0.00%) self.primary_spans.iter().any(|sp| !sp.is_dummy()) 98 ( 0.00%) } . . /// Returns `true` if this contains only a dummy primary span with any hygienic context. . pub fn is_dummy(&self) -> bool { . let mut is_dummy = true; . for span in &self.primary_spans { . if !span.is_dummy() { . is_dummy = false; . } -- line 1089 ---------------------------------------- -- line 1110 ---------------------------------------- . replacements_occurred . } . . /// Returns the strings to highlight. We always ensure that there . /// is an entry for each of the primary spans -- for each primary . /// span `P`, if there is at least one label with span `P`, we return . /// those labels (marked as primary). But otherwise we return . /// `SpanLabel` instances with empty labels. 392 ( 0.00%) pub fn span_labels(&self) -> Vec { 56 ( 0.00%) let is_primary = |span| self.primary_spans.contains(&span); . . let mut span_labels = self . .span_labels . .iter() . .map(|&(span, ref label)| SpanLabel { . span, . is_primary: is_primary(span), . label: Some(label.clone()), . }) . .collect::>(); . 16 ( 0.00%) for &span in &self.primary_spans { . if !span_labels.iter().any(|sl| sl.span == span) { . span_labels.push(SpanLabel { span, is_primary: true, label: None }); . } . } . . span_labels 392 ( 0.00%) } . . /// Returns `true` if any of the span labels is displayable. 60 ( 0.00%) pub fn has_span_labels(&self) -> bool { . self.span_labels.iter().any(|(sp, _)| !sp.is_dummy()) 70 ( 0.00%) } . } . . impl From for MultiSpan { 630 ( 0.00%) fn from(span: Span) -> MultiSpan { . MultiSpan::from_span(span) 630 ( 0.00%) } . } . . impl From> for MultiSpan { 25 ( 0.00%) fn from(spans: Vec) -> MultiSpan { 20 ( 0.00%) MultiSpan::from_spans(spans) 25 ( 0.00%) } . } . . /// Identifies an offset of a multi-byte character in a `SourceFile`. 44 ( 0.00%) #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)] . pub struct MultiByteChar { . /// The absolute offset of the character in the `SourceMap`. . pub pos: BytePos, . /// The number of bytes, `>= 2`. . pub bytes: u8, . } . . /// Identifies an offset of a non-narrow character in a `SourceFile`. 352 ( 0.00%) #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)] . pub enum NonNarrowChar { . /// Represents a zero-width character. . ZeroWidth(BytePos), . /// Represents a wide (full-width) character. . Wide(BytePos), . /// Represents a tab character, represented visually with a width of 4 characters. . Tab(BytePos), . } . . impl NonNarrowChar { . fn new(pos: BytePos, width: usize) -> Self { 16 ( 0.00%) match width { . 0 => NonNarrowChar::ZeroWidth(pos), . 2 => NonNarrowChar::Wide(pos), . 4 => NonNarrowChar::Tab(pos), . _ => panic!("width {} given for non-narrow character", width), . } . } . . /// Returns the absolute offset of the character in the `SourceMap`. -- line 1188 ---------------------------------------- -- line 1201 ---------------------------------------- . } . } . } . . impl Add for NonNarrowChar { . type Output = Self; . . fn add(self, rhs: BytePos) -> Self { 532 ( 0.00%) match self { . NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs), . NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs), . NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs), . } . } . } . . impl Sub for NonNarrowChar { . type Output = Self; . 154 ( 0.00%) fn sub(self, rhs: BytePos) -> Self { 532 ( 0.00%) match self { . NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs), . NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs), . NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs), . } 462 ( 0.00%) } . } . . /// Identifies an offset of a character that was normalized away from `SourceFile`. . #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)] . pub struct NormalizedPos { . /// The absolute offset of the character in the `SourceMap`. . pub pos: BytePos, . /// The difference between original and normalized string at position. . pub diff: u32, . } . 21 ( 0.00%) #[derive(PartialEq, Eq, Clone, Debug)] . pub enum ExternalSource { . /// No external source has to be loaded, since the `SourceFile` represents a local crate. . Unneeded, . Foreign { . kind: ExternalSourceKind, . /// This SourceFile's byte-offset within the source_map of its original crate. . original_start_pos: BytePos, . /// The end of this SourceFile within the source_map of its original crate. -- line 1246 ---------------------------------------- -- line 1257 ---------------------------------------- . AbsentOk, . /// A failed attempt has been made to load the external source. . AbsentErr, . Unneeded, . } . . impl ExternalSource { . pub fn get_source(&self) -> Option<&Lrc> { 176 ( 0.00%) match self { . ExternalSource::Foreign { kind: ExternalSourceKind::Present(ref src), .. } => Some(src), . _ => None, . } . } . } . . #[derive(Debug)] . pub struct OffsetOverflowError; . 1,052 ( 0.00%) #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)] . pub enum SourceFileHashAlgorithm { . Md5, . Sha1, . Sha256, . } . . impl FromStr for SourceFileHashAlgorithm { . type Err = (); -- line 1283 ---------------------------------------- -- line 1290 ---------------------------------------- . _ => Err(()), . } . } . } . . rustc_data_structures::impl_stable_hash_via_hash!(SourceFileHashAlgorithm); . . /// The hash of the on-disk source file used for debug info. 42 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, Debug)] 2,104 ( 0.00%) #[derive(HashStable_Generic, Encodable, Decodable)] . pub struct SourceFileHash { . pub kind: SourceFileHashAlgorithm, . value: [u8; 32], . } . . impl SourceFileHash { . pub fn new(kind: SourceFileHashAlgorithm, src: &str) -> SourceFileHash { . let mut hash = SourceFileHash { kind, value: Default::default() }; . let len = hash.hash_len(); . let value = &mut hash.value[..len]; . let data = src.as_bytes(); . match kind { . SourceFileHashAlgorithm::Md5 => { 93 ( 0.00%) value.copy_from_slice(&Md5::digest(data)); . } . SourceFileHashAlgorithm::Sha1 => { . value.copy_from_slice(&Sha1::digest(data)); . } . SourceFileHashAlgorithm::Sha256 => { . value.copy_from_slice(&Sha256::digest(data)); . } . } -- line 1321 ---------------------------------------- -- line 1329 ---------------------------------------- . . /// The bytes of the hash. . pub fn hash_bytes(&self) -> &[u8] { . let len = self.hash_len(); . &self.value[..len] . } . . fn hash_len(&self) -> usize { 93 ( 0.00%) match self.kind { . SourceFileHashAlgorithm::Md5 => 16, . SourceFileHashAlgorithm::Sha1 => 20, . SourceFileHashAlgorithm::Sha256 => 32, . } . } . } . . /// A single source in the [`SourceMap`]. 406 ( 0.00%) #[derive(Clone)] . pub struct SourceFile { . /// The name of the file that the source came from. Source that doesn't . /// originate from files has names between angle brackets by convention . /// (e.g., ``). . pub name: FileName, . /// The complete source code. 7 ( 0.00%) pub src: Option>, . /// The source code's hash. . pub src_hash: SourceFileHash, . /// The external source code (used for external crates, which will have a `None` . /// value as `self.src`. . pub external_src: Lock, . /// The start position of this source in the `SourceMap`. . pub start_pos: BytePos, . /// The end position of this source in the `SourceMap`. -- line 1361 ---------------------------------------- -- line 1364 ---------------------------------------- . pub lines: Vec, . /// Locations of multi-byte characters in the source code. . pub multibyte_chars: Vec, . /// Width of characters that are not narrow in the source code. . pub non_narrow_chars: Vec, . /// Locations of characters removed during normalization. . pub normalized_pos: Vec, . /// A hash of the filename, used for speeding up hashing in incremental compilation. 7 ( 0.00%) pub name_hash: u128, . /// Indicates which crate this `SourceFile` was imported from. 7 ( 0.00%) pub cnum: CrateNum, . } . . impl Encodable for SourceFile { . fn encode(&self, s: &mut S) -> Result<(), S::Error> { . s.emit_struct(false, |s| { . s.emit_struct_field("name", true, |s| self.name.encode(s))?; . s.emit_struct_field("src_hash", false, |s| self.src_hash.encode(s))?; . s.emit_struct_field("start_pos", false, |s| self.start_pos.encode(s))?; . s.emit_struct_field("end_pos", false, |s| self.end_pos.encode(s))?; . s.emit_struct_field("lines", false, |s| { . let lines = &self.lines[..]; . // Store the length. . s.emit_u32(lines.len() as u32)?; . 28 ( 0.00%) if !lines.is_empty() { . // In order to preserve some space, we exploit the fact that . // the lines list is sorted and individual lines are . // probably not that long. Because of that we can store lines . // as a difference list, using as little space as possible . // for the differences. . let max_line_length = if lines.len() == 1 { . 0 . } else { -- line 1397 ---------------------------------------- -- line 1399 ---------------------------------------- . .array_windows() . .map(|&[fst, snd]| snd - fst) . .map(|bp| bp.to_usize()) . .max() . .unwrap() . }; . . let bytes_per_diff: u8 = match max_line_length { 14 ( 0.00%) 0..=0xFF => 1, . 0x100..=0xFFFF => 2, . _ => 4, . }; . . // Encode the number of bytes used per diff. . bytes_per_diff.encode(s)?; . . // Encode the first element. . lines[0].encode(s)?; . . let diff_iter = lines.array_windows().map(|&[fst, snd]| snd - fst); . 14 ( 0.00%) match bytes_per_diff { . 1 => { . for diff in diff_iter { . (diff.0 as u8).encode(s)? . } . } . 2 => { . for diff in diff_iter { . (diff.0 as u16).encode(s)? -- line 1428 ---------------------------------------- -- line 1436 ---------------------------------------- . _ => unreachable!(), . } . } . . Ok(()) . })?; . s.emit_struct_field("multibyte_chars", false, |s| self.multibyte_chars.encode(s))?; . s.emit_struct_field("non_narrow_chars", false, |s| self.non_narrow_chars.encode(s))?; 21 ( 0.00%) s.emit_struct_field("name_hash", false, |s| self.name_hash.encode(s))?; . s.emit_struct_field("normalized_pos", false, |s| self.normalized_pos.encode(s))?; 77 ( 0.00%) s.emit_struct_field("cnum", false, |s| self.cnum.encode(s)) . }) . } . } . . impl Decodable for SourceFile { 4,734 ( 0.00%) fn decode(d: &mut D) -> SourceFile { . d.read_struct(|d| { . let name: FileName = d.read_struct_field("name", |d| Decodable::decode(d)); . let src_hash: SourceFileHash = . d.read_struct_field("src_hash", |d| Decodable::decode(d)); . let start_pos: BytePos = d.read_struct_field("start_pos", |d| Decodable::decode(d)); . let end_pos: BytePos = d.read_struct_field("end_pos", |d| Decodable::decode(d)); . let lines: Vec = d.read_struct_field("lines", |d| { . let num_lines: u32 = Decodable::decode(d); 526 ( 0.00%) let mut lines = Vec::with_capacity(num_lines as usize); . . if num_lines > 0 { . // Read the number of bytes used per diff. . let bytes_per_diff: u8 = Decodable::decode(d); . . // Read the first element. . let mut line_start: BytePos = Decodable::decode(d); . lines.push(line_start); . . for _ in 1..num_lines { 865,776 ( 0.08%) let diff = match bytes_per_diff { . 1 => d.read_u8() as u32, . 2 => d.read_u16() as u32, . 4 => d.read_u32(), . _ => unreachable!(), . }; . . line_start = line_start + BytePos(diff); . -- line 1480 ---------------------------------------- -- line 1483 ---------------------------------------- . } . . lines . }); . let multibyte_chars: Vec = . d.read_struct_field("multibyte_chars", |d| Decodable::decode(d)); . let non_narrow_chars: Vec = . d.read_struct_field("non_narrow_chars", |d| Decodable::decode(d)); 1,052 ( 0.00%) let name_hash: u128 = d.read_struct_field("name_hash", |d| Decodable::decode(d)); . let normalized_pos: Vec = . d.read_struct_field("normalized_pos", |d| Decodable::decode(d)); . let cnum: CrateNum = d.read_struct_field("cnum", |d| Decodable::decode(d)); 5,786 ( 0.00%) SourceFile { 4,208 ( 0.00%) name, . start_pos, . end_pos, . src: None, 2,104 ( 0.00%) src_hash, . // Unused - the metadata decoder will construct . // a new SourceFile, filling in `external_src` properly . external_src: Lock::new(ExternalSource::Unneeded), 2,104 ( 0.00%) lines, 2,104 ( 0.00%) multibyte_chars, 2,104 ( 0.00%) non_narrow_chars, 2,104 ( 0.00%) normalized_pos, . name_hash, . cnum, . } . }) 4,734 ( 0.00%) } . } . . impl fmt::Debug for SourceFile { . fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { . write!(fmt, "SourceFile({:?})", self.name) . } . } . . impl SourceFile { 341 ( 0.00%) pub fn new( . name: FileName, . mut src: String, . start_pos: BytePos, . hash_kind: SourceFileHashAlgorithm, . ) -> Self { . // Compute the file hash before any normalization. . let src_hash = SourceFileHash::new(hash_kind, &src); 93 ( 0.00%) let normalized_pos = normalize_src(&mut src, start_pos); . . let name_hash = { . let mut hasher: StableHasher = StableHasher::new(); 62 ( 0.00%) name.hash(&mut hasher); . hasher.finish::() . }; 62 ( 0.00%) let end_pos = start_pos.to_usize() + src.len(); 93 ( 0.00%) assert!(end_pos <= u32::MAX as usize); . 372 ( 0.00%) let (lines, multibyte_chars, non_narrow_chars) = 62 ( 0.00%) analyze_source_file::analyze_source_file(&src, start_pos); . 527 ( 0.00%) SourceFile { . name, . src: Some(Lrc::new(src)), 341 ( 0.00%) src_hash, . external_src: Lock::new(ExternalSource::Unneeded), . start_pos, . end_pos: Pos::from_usize(end_pos), 124 ( 0.00%) lines, 124 ( 0.00%) multibyte_chars, 124 ( 0.00%) non_narrow_chars, 124 ( 0.00%) normalized_pos, . name_hash, . cnum: LOCAL_CRATE, . } 279 ( 0.00%) } . . /// Returns the `BytePos` of the beginning of the current line. . pub fn line_begin_pos(&self, pos: BytePos) -> BytePos { . let line_index = self.lookup_line(pos).unwrap(); . self.lines[line_index] . } . . /// Add externally loaded source. . /// If the hash of the input doesn't match or no input is supplied via None, . /// it is interpreted as an error and the corresponding enum variant is set. . /// The return value signifies whether some kind of source is present. 987 ( 0.00%) pub fn add_external_src(&self, get_src: F) -> bool . where . F: FnOnce() -> Option, . { 141 ( 0.00%) if matches!( 282 ( 0.00%) *self.external_src.borrow(), . ExternalSource::Foreign { kind: ExternalSourceKind::AbsentOk, .. } . ) { . let src = get_src(); . let mut external_src = self.external_src.borrow_mut(); . // Check that no-one else have provided the source while we were getting it . if let ExternalSource::Foreign { . kind: src_kind @ ExternalSourceKind::AbsentOk, .. . } = &mut *external_src -- line 1582 ---------------------------------------- -- line 1592 ---------------------------------------- . *src_kind = ExternalSourceKind::AbsentErr; . } . . false . } else { . self.src.is_some() || external_src.get_source().is_some() . } . } else { 141 ( 0.00%) self.src.is_some() || self.external_src.borrow().get_source().is_some() . } 1,269 ( 0.00%) } . . /// Gets a line from the list of pre-computed line-beginnings. . /// The line number here is 0-based. 280 ( 0.00%) pub fn get_line(&self, line_number: usize) -> Option> { 280 ( 0.00%) fn get_until_newline(src: &str, begin: usize) -> &str { . // We can't use `lines.get(line_number+1)` because we might . // be parsing when we call this function and thus the current . // line is the last one we have line info for. . let slice = &src[begin..]; . match slice.find('\n') { . Some(e) => &slice[..e], . None => slice, . } 320 ( 0.00%) } . . let begin = { 40 ( 0.00%) let line = self.lines.get(line_number)?; 40 ( 0.00%) let begin: BytePos = *line - self.start_pos; . begin.to_usize() . }; . 120 ( 0.00%) if let Some(ref src) = self.src { 200 ( 0.00%) Some(Cow::from(get_until_newline(src, begin))) . } else if let Some(src) = self.external_src.borrow().get_source() { . Some(Cow::Owned(String::from(get_until_newline(src, begin)))) . } else { . None . } 320 ( 0.00%) } . . pub fn is_real_file(&self) -> bool { . self.name.is_real() 533 ( 0.00%) } . . pub fn is_imported(&self) -> bool { . self.src.is_none() 7,109 ( 0.00%) } . . pub fn count_lines(&self) -> usize { . self.lines.len() . } . . /// Finds the line containing the given position. The return value is the . /// index into the `lines` array of this `SourceFile`, not the 1-based line . /// number. If the source_file is empty or the position is located before the . /// first line, `None` is returned. . pub fn lookup_line(&self, pos: BytePos) -> Option { 6,901 ( 0.00%) match self.lines.binary_search(&pos) { . Ok(idx) => Some(idx), . Err(0) => None, . Err(idx) => Some(idx - 1), . } . } . . pub fn line_bounds(&self, line_index: usize) -> Range { 24,608 ( 0.00%) if self.is_empty() { . return self.start_pos..self.end_pos; . } . 15,319 ( 0.00%) assert!(line_index < self.lines.len()); 22,605 ( 0.00%) if line_index == (self.lines.len() - 1) { 3,183 ( 0.00%) self.lines[line_index]..self.end_pos . } else { 12,920 ( 0.00%) self.lines[line_index]..self.lines[line_index + 1] . } . } . . /// Returns whether or not the file contains the given `SourceMap` byte . /// position. The position one past the end of the file is considered to be . /// contained by the file. This implies that files for which `is_empty` . /// returns true still contain one byte position according to this function. . #[inline] -- line 1674 ---------------------------------------- -- line 1678 ---------------------------------------- . . #[inline] . pub fn is_empty(&self) -> bool { . self.start_pos == self.end_pos . } . . /// Calculates the original byte position relative to the start of the file . /// based on the given byte position. 24 ( 0.00%) pub fn original_relative_byte_pos(&self, pos: BytePos) -> BytePos { . // Diff before any records is 0. Otherwise use the previously recorded . // diff as that applies to the following characters until a new diff . // is recorded. . let diff = match self.normalized_pos.binary_search_by(|np| np.pos.cmp(&pos)) { . Ok(i) => self.normalized_pos[i].diff, . Err(i) if i == 0 => 0, . Err(i) => self.normalized_pos[i - 1].diff, . }; . 96 ( 0.00%) BytePos::from_u32(pos.0 - self.start_pos.0 + diff) 72 ( 0.00%) } . . /// Converts an absolute `BytePos` to a `CharPos` relative to the `SourceFile`. 282 ( 0.00%) pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos { . // The number of extra bytes due to multibyte chars in the `SourceFile`. . let mut total_extra_bytes = 0; . 846 ( 0.00%) for mbc in self.multibyte_chars.iter() { . debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos); 4 ( 0.00%) if mbc.pos < bpos { . // Every character is at least one byte, so we only . // count the actual extra bytes. . total_extra_bytes += mbc.bytes as u32 - 1; . // We should never see a byte position in the middle of a . // character. . assert!(bpos.to_u32() >= mbc.pos.to_u32() + mbc.bytes as u32); . } else { . break; . } . } . 1,692 ( 0.00%) assert!(self.start_pos.to_u32() + total_extra_bytes <= bpos.to_u32()); 1,410 ( 0.00%) CharPos(bpos.to_usize() - self.start_pos.to_usize() - total_extra_bytes as usize) 564 ( 0.00%) } . . /// Looks up the file's (1-based) line number and (0-based `CharPos`) column offset, for a . /// given `BytePos`. 987 ( 0.00%) pub fn lookup_file_pos(&self, pos: BytePos) -> (usize, CharPos) { 282 ( 0.00%) let chpos = self.bytepos_to_file_charpos(pos); 140 ( 0.00%) match self.lookup_line(pos) { . Some(a) => { . let line = a + 1; // Line numbers start at 1 141 ( 0.00%) let linebpos = self.lines[a]; 282 ( 0.00%) let linechpos = self.bytepos_to_file_charpos(linebpos); . let col = chpos - linechpos; . debug!("byte pos {:?} is on the line at byte pos {:?}", pos, linebpos); . debug!("char pos {:?} is on the line at char pos {:?}", chpos, linechpos); . debug!("byte is on line: {}", line); 141 ( 0.00%) assert!(chpos >= linechpos); . (line, col) . } . None => (0, chpos), . } 1,128 ( 0.00%) } . . /// Looks up the file's (1-based) line number, (0-based `CharPos`) column offset, and (0-based) . /// column offset when displayed, for a given `BytePos`. 1,128 ( 0.00%) pub fn lookup_file_pos_with_col_display(&self, pos: BytePos) -> (usize, CharPos, usize) { 423 ( 0.00%) let (line, col_or_chpos) = self.lookup_file_pos(pos); 282 ( 0.00%) if line > 0 { . let col = col_or_chpos; 141 ( 0.00%) let linebpos = self.lines[line - 1]; . let col_display = { . let start_width_idx = self . .non_narrow_chars . .binary_search_by_key(&linebpos, |x| x.pos()) . .unwrap_or_else(|x| x); . let end_width_idx = self . .non_narrow_chars . .binary_search_by_key(&pos, |x| x.pos()) . .unwrap_or_else(|x| x); 3 ( 0.00%) let special_chars = end_width_idx - start_width_idx; . let non_narrow: usize = self.non_narrow_chars[start_width_idx..end_width_idx] . .iter() . .map(|x| x.width()) . .sum(); 705 ( 0.00%) col.0 - special_chars + non_narrow . }; . (line, col, col_display) . } else { . let chpos = col_or_chpos; . let col_display = { . let end_width_idx = self . .non_narrow_chars . .binary_search_by_key(&pos, |x| x.pos()) . .unwrap_or_else(|x| x); . let non_narrow: usize = . self.non_narrow_chars[0..end_width_idx].iter().map(|x| x.width()).sum(); . chpos.0 - end_width_idx + non_narrow . }; . (0, chpos, col_display) . } 987 ( 0.00%) } . } . . /// Normalizes the source code and records the normalizations. 310 ( 0.00%) fn normalize_src(src: &mut String, start_pos: BytePos) -> Vec { . let mut normalized_pos = vec![]; . remove_bom(src, &mut normalized_pos); . normalize_newlines(src, &mut normalized_pos); . . // Offset all the positions by start_pos to match the final file positions. . for np in &mut normalized_pos { . np.pos.0 += start_pos.0; . } . . normalized_pos 279 ( 0.00%) } . . /// Removes UTF-8 BOM, if any. . fn remove_bom(src: &mut String, normalized_pos: &mut Vec) { 31 ( 0.00%) if src.starts_with('\u{feff}') { . src.drain(..3); . normalized_pos.push(NormalizedPos { pos: BytePos(0), diff: 3 }); . } . } . . /// Replaces `\r\n` with `\n` in-place in `src`. . /// . /// Returns error if there's a lone `\r` in the string. . fn normalize_newlines(src: &mut String, normalized_pos: &mut Vec) { 31 ( 0.00%) if !src.as_bytes().contains(&b'\r') { . return; . } . . // We replace `\r\n` with `\n` in-place, which doesn't break utf-8 encoding. . // While we *can* call `as_mut_vec` and do surgery on the live string . // directly, let's rather steal the contents of `src`. This makes the code . // safe even if a panic occurs. . -- line 1816 ---------------------------------------- -- line 1877 ---------------------------------------- . ( . $( . $(#[$attr:meta])* . $vis:vis struct $ident:ident($inner_vis:vis $inner_ty:ty); . )* . ) => { . $( . $(#[$attr])* 18,055 ( 0.00%) $vis struct $ident($inner_vis $inner_ty); . . impl Pos for $ident { . #[inline(always)] . fn from_usize(n: usize) -> $ident { 1,071 ( 0.00%) $ident(n as $inner_ty) . } . . #[inline(always)] . fn to_usize(&self) -> usize { 18,110 ( 0.00%) self.0 as usize . } . . #[inline(always)] . fn from_u32(n: u32) -> $ident { . $ident(n as $inner_ty) . } . . #[inline(always)] -- line 1903 ---------------------------------------- -- line 1906 ---------------------------------------- . } . } . . impl Add for $ident { . type Output = $ident; . . #[inline(always)] . fn add(self, rhs: $ident) -> $ident { 1,501,912 ( 0.13%) $ident(self.0 + rhs.0) . } . } . . impl Sub for $ident { . type Output = $ident; . . #[inline(always)] . fn sub(self, rhs: $ident) -> $ident { 959,014 ( 0.09%) $ident(self.0 - rhs.0) . } . } . )* . }; . } . . impl_pos! { . /// A byte offset. -- line 1931 ---------------------------------------- -- line 1939 ---------------------------------------- . /// Because of multibyte UTF-8 characters, a byte offset . /// is not equivalent to a character offset. The [`SourceMap`] will convert [`BytePos`] . /// values to `CharPos` values as necessary. . #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] . pub struct CharPos(pub usize); . } . . impl Encodable for BytePos { 20 ( 0.00%) fn encode(&self, s: &mut S) -> Result<(), S::Error> { . s.emit_u32(self.0) 24 ( 0.00%) } . } . . impl Decodable for BytePos { . fn decode(d: &mut D) -> BytePos { 65,824 ( 0.01%) BytePos(d.read_u32()) . } . } . . // _____________________________________________________________________________ . // Loc, SourceFileAndLine, SourceFileAndBytePos . // . . /// A source code location used for error reporting. 16 ( 0.00%) #[derive(Debug, Clone)] . pub struct Loc { . /// Information about the original source. . pub file: Lrc, . /// The (1-based) line number. 4 ( 0.00%) pub line: usize, . /// The (0-based) column offset. . pub col: CharPos, . /// The (0-based) column offset when displayed. 4 ( 0.00%) pub col_display: usize, . } . . // Used to be structural records. . #[derive(Debug)] . pub struct SourceFileAndLine { . pub sf: Lrc, . /// Index of line, starting from 0. . pub line: usize, -- line 1980 ---------------------------------------- -- line 2042 ---------------------------------------- . /// Range inside of a `Span` used for diagnostics when we only have access to relative positions. . #[derive(Copy, Clone, PartialEq, Eq, Debug)] . pub struct InnerSpan { . pub start: usize, . pub end: usize, . } . . impl InnerSpan { 68 ( 0.00%) pub fn new(start: usize, end: usize) -> InnerSpan { . InnerSpan { start, end } 34 ( 0.00%) } . } . . /// Requirements for a `StableHashingContext` to be used in this crate. . /// . /// This is a hack to allow using the [`HashStable_Generic`] derive macro . /// instead of implementing everything in rustc_middle. . pub trait HashStableContext { . fn def_path_hash(&self, def_id: DefId) -> DefPathHash; -- line 2060 ---------------------------------------- -- line 2079 ---------------------------------------- . /// offsets into the `SourceMap`). Instead, we hash the (file name, line, column) . /// triple, which stays the same even if the containing `SourceFile` has moved . /// within the `SourceMap`. . /// . /// Also note that we are hashing byte offsets for the column, not unicode . /// codepoint offsets. For the purpose of the hash that's sufficient. . /// Also, hashing filenames is expensive so we avoid doing it twice when the . /// span starts and ends in the same file, which is almost always the case. 149,975 ( 0.01%) fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) { . const TAG_VALID_SPAN: u8 = 0; . const TAG_INVALID_SPAN: u8 = 1; . const TAG_RELATIVE_SPAN: u8 = 2; . 29,015 ( 0.00%) if !ctx.hash_spans() { . return; . } . 120,960 ( 0.01%) let span = self.data_untracked(); 41,505 ( 0.00%) span.ctxt.hash_stable(ctx, hasher); 64,275 ( 0.01%) span.parent.hash_stable(ctx, hasher); . 43,195 ( 0.00%) if span.is_dummy() { . Hash::hash(&TAG_INVALID_SPAN, hasher); . return; . } . 42,160 ( 0.00%) if let Some(parent) = span.parent { . let def_span = ctx.def_span(parent).data_untracked(); . if def_span.contains(span) { . // This span is enclosed in a definition: only hash the relative position. . Hash::hash(&TAG_RELATIVE_SPAN, hasher); . (span.lo - def_span.lo).to_u32().hash_stable(ctx, hasher); . (span.hi - def_span.lo).to_u32().hash_stable(ctx, hasher); . return; . } . } . . // If this is not an empty or invalid span, we want to hash the last . // position that belongs to it, as opposed to hashing the first . // position past it. 84,320 ( 0.01%) let (file, line_lo, col_lo, line_hi, col_hi) = match ctx.span_data_to_lines_and_cols(&span) . { 42,160 ( 0.00%) Some(pos) => pos, . None => { . Hash::hash(&TAG_INVALID_SPAN, hasher); . return; . } . }; . . Hash::hash(&TAG_VALID_SPAN, hasher); . // We truncate the stable ID hash and line and column numbers. The chances -- line 2129 ---------------------------------------- -- line 2134 ---------------------------------------- . // hash only the length, for example, then two otherwise equal spans with . // different end locations will have the same hash. This can cause a problem . // during incremental compilation wherein a previous result for a query that . // depends on the end location of a span will be incorrectly reused when the . // end location of the span it depends on has changed (see issue #74890). A . // similar analysis applies if some query depends specifically on the length . // of the span, but we only hash the end location. So hash both. . 21,080 ( 0.00%) let col_lo_trunc = (col_lo.0 as u64) & 0xFF; . let line_lo_trunc = ((line_lo as u64) & 0xFF_FF_FF) << 8; . let col_hi_trunc = (col_hi.0 as u64) & 0xFF << 32; . let line_hi_trunc = ((line_hi as u64) & 0xFF_FF_FF) << 40; . let col_line = col_lo_trunc | line_lo_trunc | col_hi_trunc | line_hi_trunc; 21,080 ( 0.00%) let len = (span.hi - span.lo).0; . Hash::hash(&col_line, hasher); . Hash::hash(&len, hasher); 171,400 ( 0.02%) } . } 1,539,042 ( 0.14%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/caching_source_map_view.rs -------------------------------------------------------------------------------- Ir -- line 27 ---------------------------------------- . impl CacheEntry { . #[inline] . fn update( . &mut self, . new_file_and_idx: Option<(Lrc, usize)>, . pos: BytePos, . time_stamp: usize, . ) { 6,030 ( 0.00%) if let Some((file, file_idx)) = new_file_and_idx { 8,682 ( 0.00%) self.file = file; 11,355 ( 0.00%) self.file_index = file_idx; . } . 856 ( 0.00%) let line_index = self.file.lookup_line(pos).unwrap(); . let line_bounds = self.file.line_bounds(line_index); 15,070 ( 0.00%) self.line_number = line_index + 1; 24,359 ( 0.00%) self.line = line_bounds; . self.touch(time_stamp); . } . . #[inline] . fn touch(&mut self, time_stamp: usize) { 36,628 ( 0.00%) self.time_stamp = time_stamp; . } . } . . #[derive(Clone)] . pub struct CachingSourceMapView<'sm> { . source_map: &'sm SourceMap, . line_cache: [CacheEntry; 3], . time_stamp: usize, . } . . impl<'sm> CachingSourceMapView<'sm> { 4,598 ( 0.00%) pub fn new(source_map: &'sm SourceMap) -> CachingSourceMapView<'sm> { . let files = source_map.files(); 2,299 ( 0.00%) let first_file = files[0].clone(); . let entry = CacheEntry { . time_stamp: 0, . line_number: 0, . line: BytePos(0)..BytePos(0), . file: first_file, . file_index: 0, . }; . 11,495 ( 0.00%) CachingSourceMapView { . source_map, 16,093 ( 0.00%) line_cache: [entry.clone(), entry.clone(), entry], . time_stamp: 0, . } 9,196 ( 0.00%) } . . pub fn byte_pos_to_line_and_col( . &mut self, . pos: BytePos, . ) -> Option<(Lrc, usize, BytePos)> { . self.time_stamp += 1; . . // Check if the position is in one of the cached lines -- line 85 ---------------------------------------- -- line 106 ---------------------------------------- . }; . . let cache_entry = &mut self.line_cache[oldest]; . cache_entry.update(new_file_and_idx, pos, self.time_stamp); . . Some((cache_entry.file.clone(), cache_entry.line_number, pos - cache_entry.line.start)) . } . 147,560 ( 0.01%) pub fn span_data_to_lines_and_cols( . &mut self, . span_data: &SpanData, . ) -> Option<(Lrc, usize, BytePos, usize, BytePos)> { 84,320 ( 0.01%) self.time_stamp += 1; . . // Check if lo and hi are in the cached lines. 21,080 ( 0.00%) let lo_cache_idx = self.cache_entry_index(span_data.lo); 21,080 ( 0.00%) let hi_cache_idx = self.cache_entry_index(span_data.hi); . 31,210 ( 0.00%) if lo_cache_idx != -1 && hi_cache_idx != -1 { . // Cache hit for span lo and hi. Check if they belong to the same file. . let result = { 31,096 ( 0.00%) let lo = &self.line_cache[lo_cache_idx as usize]; . let hi = &self.line_cache[hi_cache_idx as usize]; . 93,288 ( 0.01%) if lo.file_index != hi.file_index { . return None; . } . . ( 31,096 ( 0.00%) lo.file.clone(), . lo.line_number, . span_data.lo - lo.line.start, 15,548 ( 0.00%) hi.line_number, . span_data.hi - hi.line.start, . ) . }; . 15,548 ( 0.00%) self.line_cache[lo_cache_idx as usize].touch(self.time_stamp); 15,548 ( 0.00%) self.line_cache[hi_cache_idx as usize].touch(self.time_stamp); . 62,192 ( 0.01%) return Some(result); . } . . // No cache hit or cache hit for only one of span lo and hi. 10,950 ( 0.00%) let oldest = if lo_cache_idx != -1 || hi_cache_idx != -1 { . let avoid_idx = if lo_cache_idx != -1 { lo_cache_idx } else { hi_cache_idx }; . self.oldest_cache_entry_index_avoid(avoid_idx as usize) . } else { . self.oldest_cache_entry_index() . }; . . // If the entry doesn't point to the correct file, get the new file and index. . // Return early if the file containing beginning of span doesn't contain end of span. 44,016 ( 0.00%) let new_file_and_idx = if !file_contains(&self.line_cache[oldest].file, span_data.lo) { 23,380 ( 0.00%) let new_file_and_idx = self.file_for_position(span_data.lo)?; 28,056 ( 0.00%) if !file_contains(&new_file_and_idx.0, span_data.hi) { . return None; . } . 18,704 ( 0.00%) Some(new_file_and_idx) . } else { . let file = &self.line_cache[oldest].file; 2,568 ( 0.00%) if !file_contains(&file, span_data.hi) { . return None; . } . 2,568 ( 0.00%) None . }; . . // Update the cache entries. 27,660 ( 0.00%) let (lo_idx, hi_idx) = match (lo_cache_idx, hi_cache_idx) { . // Oldest cache entry is for span_data.lo line. . (-1, -1) => { . let lo = &mut self.line_cache[oldest]; . lo.update(new_file_and_idx, span_data.lo, self.time_stamp); . 15,678 ( 0.00%) if !lo.line.contains(&span_data.hi) { . let new_file_and_idx = Some((lo.file.clone(), lo.file_index)); . let next_oldest = self.oldest_cache_entry_index_avoid(oldest); . let hi = &mut self.line_cache[next_oldest]; . hi.update(new_file_and_idx, span_data.hi, self.time_stamp); . (oldest, next_oldest) . } else { . (oldest, oldest) . } . } . // Oldest cache entry is for span_data.lo line. . (-1, _) => { . let lo = &mut self.line_cache[oldest]; . lo.update(new_file_and_idx, span_data.lo, self.time_stamp); 114 ( 0.00%) let hi = &mut self.line_cache[hi_cache_idx as usize]; 171 ( 0.00%) hi.touch(self.time_stamp); . (oldest, hi_cache_idx as usize) . } . // Oldest cache entry is for span_data.hi line. . (_, -1) => { . let hi = &mut self.line_cache[oldest]; 249 ( 0.00%) hi.update(new_file_and_idx, span_data.hi, self.time_stamp); 498 ( 0.00%) let lo = &mut self.line_cache[lo_cache_idx as usize]; 996 ( 0.00%) lo.touch(self.time_stamp); . (lo_cache_idx as usize, oldest) . } . _ => { . panic!(); . } . }; . . let lo = &self.line_cache[lo_idx]; . let hi = &self.line_cache[hi_idx]; . . // Span lo and hi may equal line end when last line doesn't . // end in newline, hence the inclusive upper bounds below. 11,064 ( 0.00%) assert!(span_data.lo >= lo.line.start); 5,532 ( 0.00%) assert!(span_data.lo <= lo.line.end); 11,064 ( 0.00%) assert!(span_data.hi >= hi.line.start); 5,532 ( 0.00%) assert!(span_data.hi <= hi.line.end); 27,660 ( 0.00%) assert!(lo.file.contains(span_data.lo)); 16,596 ( 0.00%) assert!(lo.file.contains(span_data.hi)); 16,596 ( 0.00%) assert_eq!(lo.file_index, hi.file_index); . 16,596 ( 0.00%) Some(( 5,532 ( 0.00%) lo.file.clone(), . lo.line_number, . span_data.lo - lo.line.start, 5,532 ( 0.00%) hi.line_number, . span_data.hi - hi.line.start, . )) 189,720 ( 0.02%) } . . fn cache_entry_index(&self, pos: BytePos) -> isize { . for (idx, cache_entry) in self.line_cache.iter().enumerate() { 249,402 ( 0.02%) if cache_entry.line.contains(&pos) { . return idx as isize; . } . } . . -1 . } . . fn oldest_cache_entry_index(&self) -> usize { . let mut oldest = 0; . . for idx in 1..self.line_cache.len() { 31,356 ( 0.00%) if self.line_cache[idx].time_stamp < self.line_cache[oldest].time_stamp { . oldest = idx; . } . } . . oldest . } . . fn oldest_cache_entry_index_avoid(&self, avoid_idx: usize) -> usize { . let mut oldest = if avoid_idx != 0 { 0 } else { 1 }; . . for idx in 0..self.line_cache.len() { 12,053 ( 0.00%) if idx != avoid_idx 8,712 ( 0.00%) && self.line_cache[idx].time_stamp < self.line_cache[oldest].time_stamp . { . oldest = idx; . } . } . . oldest . } . 23,380 ( 0.00%) fn file_for_position(&self, pos: BytePos) -> Option<(Lrc, usize)> { 4,676 ( 0.00%) if !self.source_map.files().is_empty() { 9,352 ( 0.00%) let file_idx = self.source_map.lookup_source_file_idx(pos); . let file = &self.source_map.files()[file_idx]; . 37,408 ( 0.00%) if file_contains(file, pos) { . return Some((file.clone(), file_idx)); . } . } . . None 23,380 ( 0.00%) } . } . . #[inline] . fn file_contains(file: &SourceFile, pos: BytePos) -> bool { . // `SourceMap::lookup_source_file_idx` and `SourceFile::contains` both consider the position . // one past the end of a file to belong to it. Normally, that's what we want. But for the . // purposes of converting a byte position to a line and column number, we can't come up with a . // line and column number if the file is empty, because an empty file doesn't contain any -- line 290 ---------------------------------------- 385,853 ( 0.03%) -------------------------------------------------------------------------------- -- 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 { 2,794,841 ( 0.25%) 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) { 3,151,323 ( 0.28%) 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 { 149,733 ( 0.01%) unsafe { __rust_realloc(ptr, layout.size(), layout.align(), new_size) } . } . . /// Allocate zero-initialized memory with the global allocator. . /// . /// This function forwards calls to the [`GlobalAlloc::alloc_zeroed`] method . /// of the allocator registered with the `#[global_allocator]` attribute . /// if there is one, or the `std` crate’s default. . /// -- line 132 ---------------------------------------- -- line 150 ---------------------------------------- . /// . /// dealloc(ptr, layout); . /// } . /// ``` . #[stable(feature = "global_alloc", since = "1.28.0")] . #[must_use = "losing the pointer will leak memory"] . #[inline] . pub unsafe fn alloc_zeroed(layout: Layout) -> *mut u8 { 15,166 ( 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> { 347,846 ( 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) }; 1,670,366 ( 0.15%) let ptr = NonNull::new(raw_ptr).ok_or(AllocError)?; . Ok(NonNull::slice_from_raw_parts(ptr, size)) . }, . } . } . . // SAFETY: Same as `Allocator::grow` . #[inline] . unsafe fn grow_impl( -- line 178 ---------------------------------------- -- line 182 ---------------------------------------- . new_layout: Layout, . zeroed: bool, . ) -> Result, AllocError> { . debug_assert!( . new_layout.size() >= old_layout.size(), . "`new_layout.size()` must be greater than or equal to `old_layout.size()`" . ); . 57,252 ( 0.01%) 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) { 395,765 ( 0.04%) if layout.size() != 0 { . // SAFETY: `layout` is non-zero in size, . // other conditions must be upheld by the caller . unsafe { dealloc(ptr.as_ptr(), layout) } . } . } . . #[inline] . unsafe fn grow( -- line 247 ---------------------------------------- -- line 272 ---------------------------------------- . old_layout: Layout, . new_layout: Layout, . ) -> Result, AllocError> { . debug_assert!( . new_layout.size() <= old_layout.size(), . "`new_layout.size()` must be smaller than or equal to `old_layout.size()`" . ); . 416 ( 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); 416 ( 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] 262 ( 0.00%) unsafe fn exchange_malloc(size: usize, align: usize) -> *mut u8 { . let layout = unsafe { Layout::from_size_align_unchecked(size, align) }; 5,393 ( 0.00%) match Global.allocate(layout) { . Ok(ptr) => ptr.as_mut_ptr(), . Err(_) => handle_alloc_error(layout), . } 500 ( 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 { 4,026 ( 0.00%) let size = size_of_val(ptr.as_ref()); 3,280 ( 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] 423 ( 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. 179,440 ( 0.02%) unsafe { target.write(self.clone()) }; 376 ( 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 ---------------------------------------- 1,894,207 ( 0.17%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_serialize/src/leb128.rs -------------------------------------------------------------------------------- Ir -- line 17 ---------------------------------------- . #[inline] . pub fn $fn_name( . out: &mut [::std::mem::MaybeUninit; max_leb128_len!($int_ty)], . mut value: $int_ty, . ) -> &[u8] { . let mut i = 0; . . loop { 149,055 ( 0.01%) if value < 0x80 { . unsafe { 67,861 ( 0.01%) *out.get_unchecked_mut(i).as_mut_ptr() = value as u8; . } . 97,198 ( 0.01%) i += 1; . break; . } else { . unsafe { 68,844 ( 0.01%) *out.get_unchecked_mut(i).as_mut_ptr() = ((value & 0x7f) | 0x80) as u8; . } . 30,723 ( 0.00%) value >>= 7; . i += 1; . } . } . . unsafe { ::std::mem::MaybeUninit::slice_assume_init_ref(&out.get_unchecked(..i)) } . } . }; . } -- line 45 ---------------------------------------- -- line 53 ---------------------------------------- . macro_rules! impl_read_unsigned_leb128 { . ($fn_name:ident, $int_ty:ty) => { . #[inline] . pub fn $fn_name(slice: &[u8], position: &mut usize) -> $int_ty { . // The first iteration of this loop is unpeeled. This is a . // performance win because this code is hot and integer values less . // than 128 are very common, typically occurring 50-80% or more of . // the time, even for u64 and u128. 1,515,980 ( 0.13%) let byte = slice[*position]; 757,990 ( 0.07%) *position += 1; 757,990 ( 0.07%) if (byte & 0x80) == 0 { 8 ( 0.00%) return byte as $int_ty; . } 1,054 ( 0.00%) let mut result = (byte & 0x7F) as $int_ty; . let mut shift = 7; . loop { 492,900 ( 0.04%) let byte = slice[*position]; 322,029 ( 0.03%) *position += 1; 328,600 ( 0.03%) if (byte & 0x80) == 0 { 263,750 ( 0.02%) result |= (byte as $int_ty) << shift; . return result; . } else { . result |= ((byte & 0x7F) as $int_ty) << shift; . } . shift += 7; . } . } . }; -- line 80 ---------------------------------------- 548,510 ( 0.05%) -------------------------------------------------------------------------------- -- 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. 114,917 ( 0.01%) unsafe { from_raw_parts(self.ptr.as_ptr(), len!(self)) } . } . . // Helper function for moving the start of the iterator forwards by `offset` elements, . // returning the old start. . // Unsafe because the offset must not exceed `self.len()`. . #[inline(always)] . unsafe fn post_inc_start(&mut self, offset: isize) -> * $raw_mut T { . if mem::size_of::() == 0 { . zst_shrink!(self, offset); . self.ptr.as_ptr() . } else { . let old = self.ptr.as_ptr(); . // SAFETY: the caller guarantees that `offset` doesn't exceed `self.len()`, . // so this new pointer is inside `self` and thus guaranteed to be non-null. 151,313 ( 0.01%) self.ptr = unsafe { NonNull::new_unchecked(self.ptr.as_ptr().offset(offset)) }; . old . } . } . . // Helper function for moving the end of the iterator backwards by `offset` elements, . // returning the new end. . // Unsafe because the offset must not exceed `self.len()`. . #[inline(always)] -- line 101 ---------------------------------------- -- line 102 ---------------------------------------- . unsafe fn pre_dec_end(&mut self, offset: isize) -> * $raw_mut T { . if mem::size_of::() == 0 { . zst_shrink!(self, offset); . self.ptr.as_ptr() . } else { . // SAFETY: the caller guarantees that `offset` doesn't exceed `self.len()`, . // which is guaranteed to not overflow an `isize`. Also, the resulting pointer . // is in bounds of `slice`, which fulfills the other requirements for `offset`. 19 ( 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 { 55,324 ( 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 { 70,667 ( 0.01%) assume(!self.ptr.as_ptr().is_null()); . if mem::size_of::() != 0 { 42,911 ( 0.00%) assume(!self.end.is_null()); . } 13,884,747 ( 1.23%) if is_empty!(self) { . None . } else { . Some(next_unchecked!(self)) . } . } . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 1,773,902 ( 0.16%) let exact = len!(self); . (exact, Some(exact)) . } . . #[inline] . fn count(self) -> usize { . len!(self) . } . . #[inline] . fn nth(&mut self, n: usize) -> Option<$elem> { 2,769 ( 0.00%) if n >= len!(self) { . // This iterator is now empty. . if mem::size_of::() == 0 { . // We have to do it this way as `ptr` may never be 0, but `end` . // could be (due to wrapping). . self.end = self.ptr.as_ptr(); . } else { . // SAFETY: end can't be 0 if T isn't ZST because ptr isn't 0 and end >= ptr . unsafe { -- line 175 ---------------------------------------- -- line 203 ---------------------------------------- . // faster to compile. . #[inline] . fn for_each(mut self, mut f: F) . where . Self: Sized, . F: FnMut(Self::Item), . { . while let Some(x) = self.next() { 1,093 ( 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, . { 318 ( 0.00%) while let Some(x) = self.next() { 4,480 ( 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] 16 ( 0.00%) fn any(&mut self, mut f: F) -> bool . where . Self: Sized, . F: FnMut(Self::Item) -> bool, . { 124,967 ( 0.01%) while let Some(x) = self.next() { 194,428 ( 0.02%) if f(x) { . return true; . } . } . false 16 ( 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, . { 5,118 ( 0.00%) while let Some(x) = self.next() { 19,569 ( 0.00%) if predicate(&x) { . return Some(x); . } . } . None 322 ( 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, . { 6,683 ( 0.00%) while let Some(x) = self.next() { 29,097 ( 0.00%) if let Some(y) = f(x) { 2,621 ( 0.00%) return Some(y); . } . } . None 1,135 ( 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() { 44,771 ( 0.00%) if predicate(x) { . // SAFETY: we are guaranteed to be in bounds by the loop invariant: . // when `i >= n`, `self.next()` returns `None` and the loop breaks. . unsafe { assume(i < n) }; . return Some(i); . } . i += 1; . } . None -- line 303 ---------------------------------------- -- line 308 ---------------------------------------- . // faster to compile. Also, the `assume` avoids a bounds check. . #[inline] . fn rposition

(&mut self, mut predicate: P) -> Option where . P: FnMut(Self::Item) -> bool, . Self: Sized + ExactSizeIterator + DoubleEndedIterator . { . let n = len!(self); . let mut i = n; 2,367 ( 0.00%) while let Some(x) = self.next_back() { 28,366 ( 0.00%) i -= 1; 23,370 ( 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` 14,096 ( 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 { 20 ( 0.00%) assume(!self.end.is_null()); . } 152,921 ( 0.01%) if is_empty!(self) { . None . } else { . Some(next_back_unchecked!(self)) . } . } . } . . #[inline] -- line 369 ---------------------------------------- 1,391,918 ( 0.12%) -------------------------------------------------------------------------------- -- 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. 530,016 ( 0.05%) 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. 24,715 ( 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 3,497,123 ( 0.31%) &(*slice)[self] . } . . #[inline] . fn index_mut(self, slice: &mut [T]) -> &mut T { . // N.B., use intrinsic indexing 524,602 ( 0.05%) &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]> { 5,046 ( 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. 188,047 ( 0.02%) unsafe { ptr::slice_from_raw_parts(slice.as_ptr().add(self.start), self.end - self.start) } . } . . #[inline] . unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T] { . // SAFETY: see comments for `get_unchecked` above. . unsafe { 12,773 ( 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] { 9,767 ( 0.00%) if self.start > self.end { . slice_index_order_fail(self.start, self.end); 105,951 ( 0.01%) } else if self.end > slice.len() { . slice_end_index_len_fail(self.end, slice.len()); . } . // SAFETY: `self` is checked to be valid and in bounds above. . unsafe { &*self.get_unchecked(slice) } . } . . #[inline] . fn index_mut(self, slice: &mut [T]) -> &mut [T] { 2,208 ( 0.00%) if self.start > self.end { . slice_index_order_fail(self.start, self.end); 11,305 ( 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] { 32,910 ( 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] { 1,088 ( 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, . }; . 4,786 ( 0.00%) if start > end { . slice_index_order_fail(start, end); . } 30 ( 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 ---------------------------------------- 401,026 ( 0.04%) -------------------------------------------------------------------------------- -- 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 { 32,592 ( 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 { 7,397 ( 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, . { 262,461 ( 0.02%) fn into(self) -> U { 4,439,384 ( 0.39%) U::from(self) 262,983 ( 0.02%) } . } . . // From (and thus Into) is reflexive . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_convert", issue = "88674")] . impl const From for T { . fn from(t: T) -> T { . t -- line 551 ---------------------------------------- 5,930 ( 0.00%) -------------------------------------------------------------------------------- -- 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. 4,289,722 ( 0.38%) #[derive(Debug, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)] . pub enum TokenTree { . /// A single token. 1,717,078 ( 0.15%) Token(Token), . /// A delimited sequence of token trees. 180,878 ( 0.02%) Delimited(DelimSpan, DelimToken, TokenStream), . } . . #[derive(Copy, Clone)] . pub enum CanSynthesizeMissingTokens { . Yes, . No, . } . -- line 53 ---------------------------------------- -- line 71 ---------------------------------------- . delim == delim2 && tts.eq_unspanned(&tts2) . } . _ => false, . } . } . . /// Retrieves the `TokenTree`'s span. . pub fn span(&self) -> Span { 8,136 ( 0.00%) match self { 3,330 ( 0.00%) TokenTree::Token(token) => token.span, 4,052 ( 0.00%) TokenTree::Delimited(sp, ..) => sp.entire(), . } 3,056 ( 0.00%) } . . /// Modify the `TokenTree`'s span in-place. . pub fn set_span(&mut self, span: Span) { 8,136 ( 0.00%) match self { 3,056 ( 0.00%) TokenTree::Token(token) => token.span = span, 2,024 ( 0.00%) TokenTree::Delimited(dspan, ..) => *dspan = DelimSpan::from_single(span), . } 4,068 ( 0.00%) } . 1,932 ( 0.00%) pub fn token(kind: TokenKind, span: Span) -> TokenTree { 542,136 ( 0.05%) TokenTree::Token(Token::new(kind, span)) 1,932 ( 0.00%) } . . /// Returns the opening delimiter as a token tree. 66,909 ( 0.01%) pub fn open_tt(span: DelimSpan, delim: DelimToken) -> TokenTree { 200,727 ( 0.02%) TokenTree::token(token::OpenDelim(delim), span.open) 66,909 ( 0.01%) } . . /// Returns the closing delimiter as a token tree. 66,693 ( 0.01%) pub fn close_tt(span: DelimSpan, delim: DelimToken) -> TokenTree { 200,079 ( 0.02%) TokenTree::token(token::CloseDelim(delim), span.close) 66,693 ( 0.01%) } . 1,491 ( 0.00%) pub fn uninterpolate(self) -> TokenTree { 994 ( 0.00%) match self { 4,473 ( 0.00%) TokenTree::Token(token) => TokenTree::Token(token.uninterpolate().into_owned()), . tt => tt, . } 1,988 ( 0.00%) } . } . . impl HashStable for TokenStream . where . CTX: crate::HashStableContext, . { 6,336 ( 0.00%) fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) { 38,186 ( 0.00%) for sub_tt in self.trees() { . sub_tt.hash_stable(hcx, hasher); . } 5,632 ( 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 { 12 ( 0.00%) pub fn new(inner: impl CreateTokenStream + 'static) -> LazyTokenStream { . LazyTokenStream(Lrc::new(Box::new(inner))) 12 ( 0.00%) } . . pub fn create_token_stream(&self) -> AttrAnnotatedTokenStream { . self.0.create_token_stream() . } . } . . impl fmt::Debug for LazyTokenStream { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { -- line 153 ---------------------------------------- -- line 188 ---------------------------------------- . Delimited(DelimSpan, DelimToken, AttrAnnotatedTokenStream), . /// Stores the attributes for an attribute target, . /// along with the tokens for that attribute target. . /// See `AttributesData` for more information . Attributes(AttributesData), . } . . impl AttrAnnotatedTokenStream { 11,924 ( 0.00%) pub fn new(tokens: Vec<(AttrAnnotatedTokenTree, Spacing)>) -> AttrAnnotatedTokenStream { . AttrAnnotatedTokenStream(Lrc::new(tokens)) 11,924 ( 0.00%) } . . /// Converts this `AttrAnnotatedTokenStream` to a plain `TokenStream . /// During conversion, `AttrAnnotatedTokenTree::Attributes` get 'flattened' . /// back to a `TokenStream` of the form `outer_attr attr_target`. . /// If there are inner attributes, they are inserted into the proper . /// place in the attribute target tokens. . pub fn to_tokenstream(&self) -> TokenStream { . let trees: Vec<_> = self -- line 206 ---------------------------------------- -- line 316 ---------------------------------------- . pub struct TokenStream(pub(crate) Lrc>); . . pub type TreeAndSpacing = (TokenTree, Spacing); . . // `TokenStream` is used a lot. Make sure it doesn't unintentionally get bigger. . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . rustc_data_structures::static_assert_size!(TokenStream, 8); . 434,798 ( 0.04%) #[derive(Clone, Copy, Debug, PartialEq, Encodable, Decodable)] . pub enum Spacing { . Alone, . Joint, . } . . impl TokenStream { . /// Given a `TokenStream` with a `Stream` of only two arguments, return a new `TokenStream` . /// separating the two arguments with a comma for diagnostic suggestions. -- line 332 ---------------------------------------- -- line 371 ---------------------------------------- . impl From<(AttrAnnotatedTokenTree, Spacing)> for AttrAnnotatedTokenStream { . fn from((tree, spacing): (AttrAnnotatedTokenTree, Spacing)) -> AttrAnnotatedTokenStream { . AttrAnnotatedTokenStream::new(vec![(tree, spacing)]) . } . } . . impl From for TokenStream { . fn from(tree: TokenTree) -> TokenStream { 720 ( 0.00%) TokenStream::new(vec![(tree, Spacing::Alone)]) . } . } . . impl From for TreeAndSpacing { . fn from(tree: TokenTree) -> TreeAndSpacing { 261,559 ( 0.02%) (tree, Spacing::Alone) . } . } . . impl iter::FromIterator for TokenStream { . fn from_iter>(iter: I) -> Self { . TokenStream::new(iter.into_iter().map(Into::into).collect::>()) . } . } -- line 393 ---------------------------------------- -- line 401 ---------------------------------------- . } . . impl TokenStream { . pub fn new(streams: Vec) -> TokenStream { . TokenStream(Lrc::new(streams)) . } . . pub fn is_empty(&self) -> bool { 639 ( 0.00%) self.0.is_empty() 639 ( 0.00%) } . . pub fn len(&self) -> usize { 570,204 ( 0.05%) self.0.len() 1,112 ( 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 { 2,336 ( 0.00%) self.clone().into_trees() 4,672 ( 0.00%) } . 69,547 ( 0.01%) pub fn into_trees(self) -> Cursor { . Cursor::new(self) 139,094 ( 0.01%) } . . /// 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 { 1,012 ( 0.00%) TokenStream(Lrc::new( . self.0 . .iter() . .enumerate() 24,408 ( 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; . 35,826 ( 0.00%) fn next(&mut self) -> Option { 64,701 ( 0.01%) self.next_with_spacing().map(|(tree, _)| tree) 47,768 ( 0.00%) } . } . . impl Cursor { . fn new(stream: TokenStream) -> Self { . Cursor { stream, index: 0 } . } . 2,780,190 ( 0.25%) pub fn next_with_spacing(&mut self) -> Option { 1,703,940 ( 0.15%) if self.index < self.stream.len() { 856,372 ( 0.08%) self.index += 1; 2,932,468 ( 0.26%) Some(self.stream.0[self.index - 1].clone()) . } else { 274,228 ( 0.02%) None . } 3,336,228 ( 0.30%) } . . 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; . } . 6,553 ( 0.00%) pub fn look_ahead(&self, n: usize) -> Option<&TokenTree> { 13,106 ( 0.00%) self.stream.0[self.index..].get(n).map(|(tree, _)| tree) 13,106 ( 0.00%) } . } . 371,987 ( 0.03%) #[derive(Debug, Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)] . pub struct DelimSpan { . pub open: Span, . pub close: Span, . } . . impl DelimSpan { 32 ( 0.00%) pub fn from_single(sp: Span) -> Self { . DelimSpan { open: sp, close: sp } 64 ( 0.00%) } . 1,278 ( 0.00%) pub fn from_pair(open: Span, close: Span) -> Self { . DelimSpan { open, close } 639 ( 0.00%) } . . pub fn dummy() -> Self { . Self::from_single(DUMMY_SP) 9,960 ( 0.00%) } . 41,440 ( 0.00%) pub fn entire(self) -> Span { . self.open.with_hi(self.close.hi()) 31,080 ( 0.00%) } . } 26,489 ( 0.00%) -------------------------------------------------------------------------------- -- 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)] 25,968,894 ( 2.30%) pub unsafe fn drop_in_place(to_drop: *mut T) { . // Code here does not matter - this is replaced by the . // real drop glue by the compiler. . . // SAFETY: see comment above . unsafe { drop_in_place(to_drop) } . } . . /// Creates a null raw pointer. -- line 196 ---------------------------------------- -- line 448 ---------------------------------------- . return; . } . } . . // Direct swapping, for the cases not going through the block optimization. . // SAFETY: the caller must guarantee that `x` and `y` are valid . // for writes, properly aligned, and non-overlapping. . unsafe { 6 ( 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 { 3,345,543 ( 0.30%) copy_nonoverlapping(src, tmp.as_mut_ptr(), 1); 3,576,945 ( 0.32%) 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 { 18,262,619 ( 1.62%) 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. 674 ( 0.00%) return wrapping_sub( 3,950 ( 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 { 147,127 ( 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 ---------------------------------------- 2,451,243 ( 0.22%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs -------------------------------------------------------------------------------- Ir -- line 294 ---------------------------------------- . #[allow(deprecated)] . impl From for CollectionAllocErr { . fn from(_: LayoutErr) -> Self { . CollectionAllocErr::CapacityOverflow . } . } . . fn infallible(result: Result) -> T { 772,820 ( 0.07%) match result { . Ok(x) => x, . Err(CollectionAllocErr::CapacityOverflow) => panic!("capacity overflow"), . Err(CollectionAllocErr::AllocErr { layout }) => alloc::alloc::handle_alloc_error(layout), . } . } . . /// FIXME: use `Layout::array` when we require a Rust version where it’s stable . /// https://github.com/rust-lang/rust/issues/55724 -- line 310 ---------------------------------------- -- line 422 ---------------------------------------- . #[cfg(feature = "union")] . impl SmallVecData { . #[inline] . unsafe fn inline(&self) -> *const A::Item { . self.inline.as_ptr() as *const A::Item . } . #[inline] . unsafe fn inline_mut(&mut self) -> *mut A::Item { 12,856 ( 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) { 352,828 ( 0.03%) 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::() . ); 1,095,704 ( 0.10%) 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(), 1,323 ( 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(); 18,768 ( 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 { . A::size() . } else { -- line 703 ---------------------------------------- -- 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 { 563,489 ( 0.05%) self.len() == 0 . } . . /// The number of items the vector can hold without reallocating . #[inline] . pub fn capacity(&self) -> usize { . self.triple().2 . } . . /// Returns a tuple with (data ptr, len, capacity) . /// Useful to get all SmallVec properties with a single check of the current storage variant. . #[inline] . fn triple(&self) -> (*const A::Item, usize, usize) { . unsafe { 1,931,744 ( 0.17%) 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 { 21,932,459 ( 1.95%) if self.spilled() { 2,030 ( 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 { 11,558,711 ( 1.03%) 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] 15,710 ( 0.00%) pub fn push(&mut self, value: A::Item) { . unsafe { . let (mut ptr, mut len, cap) = self.triple_mut(); 3,238,260 ( 0.29%) if *len == cap { 103 ( 0.00%) self.reserve(1); 20,790 ( 0.00%) let &mut (heap_ptr, ref mut heap_len) = self.data.heap_mut(); . ptr = heap_ptr; . len = heap_len; . } 38,425 ( 0.00%) ptr::write(ptr.add(*len), value); 3,969,481 ( 0.35%) *len += 1; . } 12,568 ( 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(); 1,813,170 ( 0.16%) if *len_ptr == 0 { . return None; . } 543,582 ( 0.05%) let last_index = *len_ptr - 1; 701,839 ( 0.06%) *len_ptr = last_index; 9,162 ( 0.00%) Some(ptr::read(ptr.add(last_index))) . } . } . . /// Moves all the elements of `other` into `self`, leaving `other` empty. . /// . /// # Example . /// . /// ``` -- line 861 ---------------------------------------- -- 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 450 ( 0.00%) pub fn try_grow(&mut self, new_cap: usize) -> Result<(), CollectionAllocErr> { . unsafe { 30 ( 0.00%) let (ptr, &mut len, cap) = self.triple_mut(); . let unspilled = !self.spilled(); 41,398 ( 0.00%) assert!(new_cap >= len); 41,398 ( 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); 41,398 ( 0.00%) } else if new_cap != cap { 41,224 ( 0.00%) let layout = layout_array::(new_cap)?; . debug_assert!(layout.size() > 0); . let new_alloc; 20,699 ( 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`. 21,197 ( 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(); . } 41,398 ( 0.00%) self.data = SmallVecData::from_heap(new_alloc, len); 61,781 ( 0.01%) self.capacity = new_cap; . } . Ok(()) . } 480 ( 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] 22,430 ( 0.00%) pub fn reserve(&mut self, additional: usize) { 815,109 ( 0.07%) infallible(self.try_reserve(additional)) 25,520 ( 0.00%) } . . /// Reserve capacity for `additional` more elements to be inserted. . /// . /// May reserve more space to avoid frequent reallocations. 3,094,826 ( 0.27%) 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() 756 ( 0.00%) let (_, &mut len, cap) = self.triple_mut(); 1,996,434 ( 0.18%) 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)?; 120 ( 0.00%) self.try_grow(new_cap) 3,477,480 ( 0.31%) } . . /// 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(); 15,069 ( 0.00%) if cap - len >= additional { . return Ok(()); . } . let new_cap = len . .checked_add(additional) . .ok_or(CollectionAllocErr::CapacityOverflow)?; . self.try_grow(new_cap) . } . -- line 974 ---------------------------------------- -- 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(); 7,226 ( 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 1047 ---------------------------------------- . . /// Remove and return the element at position `index`, shifting all elements after it to the . /// left. . /// . /// Panics if `index` is out of bounds. . pub fn remove(&mut self, index: usize) -> A::Item { . unsafe { . let (mut ptr, len_ptr, _) = self.triple_mut(); 308 ( 0.00%) let len = *len_ptr; 1,260 ( 0.00%) assert!(index < len); 3,430 ( 0.00%) *len_ptr = len - 1; . ptr = ptr.add(index); . let item = ptr::read(ptr); 840 ( 0.00%) ptr::copy(ptr.add(1), ptr, len - index - 1); . item . } . } . . /// Insert an element at position `index`, shifting all elements after it to the right. . /// . /// Panics if `index` is out of bounds. 6,873 ( 0.00%) pub fn insert(&mut self, index: usize, element: A::Item) { . self.reserve(1); . . unsafe { . let (mut ptr, len_ptr, _) = self.triple_mut(); 639 ( 0.00%) let len = *len_ptr; 1,264 ( 0.00%) assert!(index <= len); 2,528 ( 0.00%) *len_ptr = len + 1; . ptr = ptr.add(index); 1,264 ( 0.00%) ptr::copy(ptr, ptr.add(1), len - index); . ptr::write(ptr, element); . } 4,376 ( 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. 13,374 ( 0.00%) pub fn retain bool>(&mut self, mut f: F) { . let mut del = 0; . let len = self.len(); . for i in 0..len { 5,040 ( 0.00%) if !f(&mut self[i]) { . del += 1; 1,434 ( 0.00%) } else if del > 0 { . self.swap(i - del, i); . } . } 2,972 ( 0.00%) self.truncate(len - del); 11,888 ( 0.00%) } . . /// Removes consecutive duplicate elements. 84 ( 0.00%) pub fn dedup(&mut self) . where . A::Item: PartialEq, . { . self.dedup_by(|a, b| a == b); 96 ( 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(); 24 ( 0.00%) if len <= 1 { . return; . } . . let ptr = self.as_mut_ptr(); . let mut w: usize = 1; . . unsafe { . for r in 1..len { -- line 1246 ---------------------------------------- -- 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, . ); 142 ( 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`. 37,784 ( 0.00%) pub fn insert_from_slice(&mut self, index: usize, slice: &[A::Item]) { . self.reserve(slice.len()); . . let len = self.len(); 10,974 ( 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()); 7,316 ( 0.00%) self.set_len(len + slice.len()); . } 29,264 ( 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(); 9,632 ( 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 { 352,923 ( 0.03%) 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(); 557,695 ( 0.05%) v.extend(iterable); . v . } . } . . impl Extend for SmallVec { 3,656,589 ( 0.32%) fn extend>(&mut self, iterable: I) { 142,256 ( 0.01%) let mut iter = iterable.into_iter(); . let (lower_size_bound, _) = iter.size_hint(); 4,807 ( 0.00%) self.reserve(lower_size_bound); . . unsafe { . let (ptr, len_ptr, cap) = self.triple_mut(); . let mut len = SetLenOnDrop::new(len_ptr); 1,448,728 ( 0.13%) while len.get() < cap { 345,746 ( 0.03%) if let Some(out) = iter.next() { . ptr::write(ptr.add(len.get()), out); . len.increment_len(1); . } else { . return; . } . } . } . 91,650 ( 0.01%) for elem in iter { 5,016 ( 0.00%) self.push(elem); . } 2,969,840 ( 0.26%) } . } . . 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 { 5,133,267 ( 0.46%) fn drop(&mut self) { . unsafe { 1,664,091 ( 0.15%) if self.spilled() { . let (ptr, len) = self.data.heap(); . Vec::from_raw_parts(ptr, len, self.capacity); . } else { . ptr::drop_in_place(&mut self[..]); . } . } 5,141,246 ( 0.46%) } . } . . #[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 { 243 ( 0.00%) fn drop(&mut self) { 13,171 ( 0.00%) for _ in self {} 216 ( 0.00%) } . } . . impl Iterator for IntoIter { . type Item = A::Item; . . #[inline] . fn next(&mut self) -> Option { 75,959 ( 0.01%) if self.current == self.end { . None . } else { . unsafe { . let current = self.current; 39,588 ( 0.00%) self.current += 1; 816 ( 0.00%) Some(ptr::read(self.data.as_ptr().add(current))) . } . } . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 1,918 ( 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); 3,938 ( 0.00%) IntoIter { 43,527 ( 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 { 373,207 ( 0.03%) local_len: *len, . len, . } . } . . #[inline] . fn get(&self) -> usize { . self.local_len . } . . #[inline] . fn increment_len(&mut self, increment: usize) { 177,653 ( 0.02%) self.local_len += increment; . } . } . . impl<'a> Drop for SetLenOnDrop<'a> { . #[inline] . fn drop(&mut self) { 549,263 ( 0.05%) *self.len = self.local_len; . } . } . . #[cfg(feature = "const_new")] . impl SmallVec<[T; N]> { . /// Construct an empty vector. . /// . /// This is a `const` version of [`SmallVec::new`] that is enabled by the feature `const_new`, with the limitation that it only works for arrays. -- line 2035 ---------------------------------------- 5,871,411 ( 0.52%) -------------------------------------------------------------------------------- -- 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] 1,848,566 ( 0.16%) pub unsafe extern "C" fn __rdl_alloc(size: usize, align: usize) -> *mut u8 { . // SAFETY: see the guarantees expected by `Layout::from_size_align` and . // `GlobalAlloc::alloc`. . unsafe { . let layout = Layout::from_size_align_unchecked(size, align); . System.alloc(layout) . } . } . -- line 358 ---------------------------------------- -- line 359 ---------------------------------------- . #[rustc_std_internal_symbol] . pub unsafe extern "C" fn __rdl_dealloc(ptr: *mut u8, size: usize, align: usize) { . // SAFETY: see the guarantees expected by `Layout::from_size_align` and . // `GlobalAlloc::dealloc`. . unsafe { System.dealloc(ptr, Layout::from_size_align_unchecked(size, align)) } . } . . #[rustc_std_internal_symbol] 314,576 ( 0.03%) 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] 18,880 ( 0.00%) pub unsafe extern "C" fn __rdl_alloc_zeroed(size: usize, align: usize) -> *mut u8 { . // SAFETY: see the guarantees expected by `Layout::from_size_align` and . // `GlobalAlloc::alloc_zeroed`. . unsafe { . let layout = Layout::from_size_align_unchecked(size, align); . System.alloc_zeroed(layout) . } . } . } -- line 390 ---------------------------------------- -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/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 { 521,850 ( 0.05%) 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")] 53 ( 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. 362 ( 0.00%) match Box::try_new_uninit_in(alloc) { . Ok(m) => m, . Err(_) => handle_alloc_error(layout), . } 106 ( 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]> { 66 ( 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), . }; 14 ( 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] 632 ( 0.00%) fn clone(&self) -> Self { . // Pre-allocate memory to allow writing the cloned value directly. 53 ( 0.00%) let mut boxed = Self::new_uninit_in(self.1.clone()); . unsafe { 179,293 ( 0.02%) (**self).write_clone_into_raw(boxed.as_mut_ptr()); . boxed.assume_init() . } 711 ( 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 { 229 ( 0.00%) fn hash(&self, state: &mut H) { 458 ( 0.00%) (**self).hash(state); 229 ( 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 { 615 ( 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 { 24 ( 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 { 276 ( 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 { 2,406 ( 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]> { 213 ( 0.00%) fn from_iter>(iter: T) -> Self { . iter.into_iter().collect::>().into_boxed_slice() 252 ( 0.00%) } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "box_slice_clone", since = "1.3.0")] . impl Clone for Box<[T], A> { 634,320 ( 0.06%) fn clone(&self) -> Self { . let alloc = Box::allocator(self).clone(); 317,160 ( 0.03%) self.to_vec_in(alloc).into_boxed_slice() 951,480 ( 0.08%) } . . 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 { 320 ( 0.00%) &**self . } . } . . #[stable(feature = "box_borrow", since = "1.1.0")] . impl borrow::BorrowMut for Box { . fn borrow_mut(&mut self) -> &mut T { 315 ( 0.00%) &mut **self . } . } . . #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")] . impl AsRef for Box { . fn as_ref(&self) -> &T { 562 ( 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 ---------------------------------------- 1,294,157 ( 0.11%) -------------------------------------------------------------------------------- -- 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. 1,830,076 ( 0.16%) #[derive(Clone)] . enum TokenTreeOrTokenTreeSlice<'tt> { 1,848 ( 0.00%) Tt(TokenTree), 453,332 ( 0.04%) 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 { 3,434,514 ( 0.30%) match *self { 52,158 ( 0.00%) TtSeq(ref v) => v.len(), . Tt(ref tt) => tt.len(), . } . } . . /// The `index`-th token tree of `self`. . fn get_tt(&self, index: usize) -> TokenTree { 652,447 ( 0.06%) match *self { 59,888 ( 0.01%) TtSeq(ref v) => v[index].clone(), 1,818,326 ( 0.16%) 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. 295,984 ( 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. 147,992 ( 0.01%) 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. 7,453,260 ( 0.66%) #[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 158,580 ( 0.01%) 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`. 634,320 ( 0.06%) 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]`. 158,580 ( 0.01%) 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. 158,580 ( 0.01%) 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. 158,580 ( 0.01%) 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. 317,160 ( 0.03%) up: Option>, . . /// Specifically used to "unzip" token trees. By "unzip", we mean to unwrap the delimiters from . /// a delimited token tree (e.g., something wrapped in `(` `)`) or to get the contents of a doc . /// comment... . /// . /// When matching against matchers with nested delimited submatchers (e.g., `pat ( pat ( .. ) . /// pat ) pat`), we need to keep track of the matchers we are descending into. This stack does . /// that where the bottom of the stack is the outermost matcher. . /// Also, throughout the comments, this "descent" is often referred to as "unzipping"... . stack: SmallVec<[MatcherTtFrame<'tt>; 1]>, . } . . impl<'root, 'tt> MatcherPos<'root, 'tt> { . /// Adds `m` as a named match for the `idx`-th metavar. . fn push_match(&mut self, idx: usize, m: NamedMatch) { 1,267,432 ( 0.11%) 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. 634,320 ( 0.06%) fn clone(&self) -> Self { 317,160 ( 0.03%) MatcherPosHandle::Box(match *self { 207,012 ( 0.02%) MatcherPosHandle::Ref(ref r) => Box::new((**r).clone()), . MatcherPosHandle::Box(ref b) => b.clone(), . }) 951,480 ( 0.08%) } . } . . 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 { 292,380 ( 0.03%) ms.iter().fold(0, |count, elt| { 146,190 ( 0.01%) count 438,570 ( 0.04%) + match *elt { 60,944 ( 0.01%) TokenTree::Sequence(_, ref seq) => seq.num_captures, 20,601 ( 0.00%) TokenTree::Delimited(_, ref delim) => count_names(&delim.tts), . TokenTree::MetaVar(..) => 0, . TokenTree::MetaVarDecl(..) => 1, . TokenTree::Token(..) => 0, . } 365,475 ( 0.03%) }) . } . . /// `len` `Vec`s (initially shared and empty) that will store matches of metavars. . fn create_matches(len: usize) -> Box<[Lrc]> { 42,701 ( 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); 164,355 ( 0.01%) 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. 5,486 ( 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`. 112,398 ( 0.01%) fn n_rec>( . sess: &ParseSess, . m: &TokenTree, . res: &mut I, . ret_val: &mut FxHashMap, . ) -> Result<(), (rustc_span::Span, String)> { 58,770 ( 0.01%) match *m { . TokenTree::Sequence(_, ref seq) => { 3,184 ( 0.00%) for next_m in &seq.tts { 19,410 ( 0.00%) n_rec(sess, next_m, res.by_ref(), ret_val)? . } . } . TokenTree::Delimited(_, ref delim) => { 2,161 ( 0.00%) for next_m in &delim.tts { 22,326 ( 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())); . } . } 23,040 ( 0.00%) TokenTree::MetaVarDecl(sp, bind_name, _) => match ret_val 15,360 ( 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(..) => (), . } . 10,218 ( 0.00%) Ok(()) 81,744 ( 0.01%) } . . let mut ret_val = FxHashMap::default(); . for m in ms { 31,441 ( 0.00%) match n_rec(sess, m, res.by_ref(), &mut ret_val) { . Ok(_) => {} . Err((sp, msg)) => return Error(sp, msg), . } . } . 9,621 ( 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 { 865,199 ( 0.08%) if let (Some((ident1, is_raw1)), Some((ident2, is_raw2))) = (t1.ident(), t2.ident()) { 1,352 ( 0.00%) ident1.name == ident2.name && is_raw1 == is_raw2 1,200,829 ( 0.11%) } else if let (Some(ident1), Some(ident2)) = (t1.lifetime(), t2.lifetime()) { . ident1.name == ident2.name . } else { 512,809 ( 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. 2,073,144 ( 0.18%) 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. 6,563,125 ( 0.58%) while item.idx >= item.top_elts.len() { 7,760 ( 0.00%) match item.stack.pop() { . Some(MatcherTtFrame { elts, idx }) => { 34,920 ( 0.00%) item.top_elts = elts; 15,520 ( 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`. 1,207,759 ( 0.11%) 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. 167,440 ( 0.01%) 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. 312,548 ( 0.03%) if idx == len { . // Get the `up` matcher . let mut new_pos = item.up.clone().unwrap(); . . // Add matches from this repetition to the `matches` of `up` 309,260 ( 0.03%) for idx in item.match_lo..item.match_hi { 773,430 ( 0.07%) let sub = item.matches[idx].clone(); 464,058 ( 0.04%) new_pos.push_match(idx, MatchedSeq(sub)); . } . . // Move the "dot" past the repetition in `up` 309,236 ( 0.03%) new_pos.match_cur = item.match_hi; 927,780 ( 0.08%) new_pos.idx += 1; . cur_items.push(new_pos); . } . . // Check if we need a separator. 154,630 ( 0.01%) if idx == len && item.sep.is_some() { . // We have a separator, and it is the current token. We can advance past the . // separator token. 3,664 ( 0.00%) if item.sep.as_ref().map_or(false, |sep| token_name_eq(token, sep)) { 11,508 ( 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. 154,442 ( 0.01%) else if item.seq_op != Some(mbe::KleeneOp::ZeroOrOne) { 308,884 ( 0.03%) item.match_cur = item.match_lo; 617,768 ( 0.05%) 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. 3,517,891 ( 0.31%) match item.top_elts.get_tt(idx) { . // Need to descend into a sequence 23,468 ( 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. 9,830 ( 0.00%) if seq.kleene.op == mbe::KleeneOp::ZeroOrMore . || seq.kleene.op == mbe::KleeneOp::ZeroOrOne . { 7,900 ( 0.00%) let mut new_item = item.clone(); 15,800 ( 0.00%) new_item.match_cur += seq.num_captures; 19,750 ( 0.00%) new_item.idx += 1; 23,700 ( 0.00%) for idx in item.match_cur..item.match_cur + seq.num_captures { 11,745 ( 0.00%) new_item.push_match(idx, MatchedSeq(Lrc::new(smallvec![]))); . } . cur_items.push(new_item); . } . 4,915 ( 0.00%) let matches = create_matches(item.matches.len()); 58,980 ( 0.01%) cur_items.push(MatcherPosHandle::Box(Box::new(MatcherPos { 4,915 ( 0.00%) stack: smallvec![], . sep: seq.separator.clone(), 4,915 ( 0.00%) seq_op: Some(seq.kleene.op), . idx: 0, 24,575 ( 0.00%) matches, 9,830 ( 0.00%) match_lo: item.match_cur, . match_cur: item.match_cur, 9,830 ( 0.00%) match_hi: item.match_cur + seq.num_captures, . up: Some(item), 34,405 ( 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. 816,000 ( 0.07%) 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. 61,440 ( 0.01%) seq @ (TokenTree::Delimited(..) . | TokenTree::Token(Token { kind: DocComment(..), .. })) => { . let lower_elts = mem::replace(&mut item.top_elts, Tt(seq)); 12,288 ( 0.00%) let idx = item.idx; 86,016 ( 0.01%) item.stack.push(MatcherTtFrame { elts: lower_elts, idx }); 49,152 ( 0.00%) item.idx = 0; . cur_items.push(item); . } . . // We just matched a normal token. We can just advance the parser. 425,445 ( 0.04%) TokenTree::Token(t) if token_name_eq(&t, token) => { 120,421 ( 0.01%) 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(..) => {} . } 1,863,233 ( 0.17%) } 677,116 ( 0.06%) } . . // 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. 109,570 ( 0.01%) 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); 54,785 ( 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(); 188,037 ( 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 188,037 ( 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. 940,185 ( 0.08%) if parser.token == token::Eof { 4,276 ( 0.00%) if eof_items.len() == 1 { . let matches = 5,978 ( 0.00%) eof_items[0].matches.iter_mut().map(|dv| Lrc::make_mut(dv).pop().unwrap()); 3,207 ( 0.00%) return nameize(parser.sess, ms, matches); . } else if eof_items.len() > 1 { . return Error( . parser.token.span, . "ambiguity: multiple successful parses".to_string(), . ); . } else { . return Failure( . Token::new( -- line 680 ---------------------------------------- -- line 687 ---------------------------------------- . ), . "missing tokens in macro arguments", . ); . } . } . // Performance hack: eof_items may share matchers via Rc with other things that we want . // to modify. Dropping eof_items now may drop these refcounts to 1, preventing an . // unnecessary implicit clone later in Rc::make_mut. 747,872 ( 0.07%) drop(eof_items); . . // If there are no possible next positions AND we aren't waiting for the black-box parser, . // then there is a syntax error. 589,615 ( 0.05%) if bb_items.is_empty() && next_items.is_empty() { 128,544 ( 0.01%) 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. 633,028 ( 0.06%) else if (!bb_items.is_empty() && !next_items.is_empty()) || bb_items.len() > 1 { . let nts = bb_items . .iter() . .map(|item| match item.top_elts.get_tt(item.idx) { . TokenTree::MetaVarDecl(_, bind, Some(kind)) => format!("{} ('{}')", kind, bind), . _ => panic!(), . }) . .collect::>() . .join(" or "); -- line 712 ---------------------------------------- -- line 721 ---------------------------------------- . n => format!("built-in NTs {} or {} other options.", nts, n), . } . ), . ); . } . // Dump all possible `next_items` into `cur_items` for the next iteration. . else if !next_items.is_empty() { . // Now process the next token 56,469 ( 0.01%) cur_items.extend(next_items.drain(..)); 18,823 ( 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); . 316,514 ( 0.03%) let mut item = bb_items.pop().unwrap(); 1,265,879 ( 0.11%) if let TokenTree::MetaVarDecl(span, _, Some(kind)) = item.top_elts.get_tt(item.idx) { 158,257 ( 0.01%) let match_cur = item.match_cur; . // We use the span of the metavariable declaration to determine any . // edition-specific matching behavior for non-terminals. 949,619 ( 0.08%) 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; . } 949,542 ( 0.08%) Ok(nt) => nt, . }; 633,028 ( 0.06%) item.push_match(match_cur, MatchedNonterminal(Lrc::new(nt))); 633,028 ( 0.06%) item.idx += 1; 949,542 ( 0.08%) item.match_cur += 1; . } else { . unreachable!() . } . cur_items.push(item); . } . 354,160 ( 0.03%) assert!(!cur_items.is_empty()); . } 98,613 ( 0.01%) } 6,405,849 ( 0.57%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/rustc_entry.rs -------------------------------------------------------------------------------- Ir -- line 26 ---------------------------------------- . /// } . /// . /// assert_eq!(letters[&'s'], 2); . /// assert_eq!(letters[&'t'], 3); . /// assert_eq!(letters[&'u'], 1); . /// assert_eq!(letters.get(&'y'), None); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 1,430,019 ( 0.13%) pub fn rustc_entry(&mut self, key: K) -> RustcEntry<'_, K, V, A> { . let hash = make_insert_hash(&self.hash_builder, &key); 349 ( 0.00%) if let Some(elem) = self.table.find(hash, |q| q.0.eq(&key)) { 131,181 ( 0.01%) RustcEntry::Occupied(RustcOccupiedEntry { 293,475 ( 0.03%) key: Some(key), . elem, . table: &mut self.table, . }) . } else { . // Ideally we would put this in VacantEntry::insert, but Entry is not . // generic over the BuildHasher and adding a generic parameter would be . // a breaking change. . self.reserve(1); . 193,834 ( 0.02%) RustcEntry::Vacant(RustcVacantEntry { . hash, 59,854 ( 0.01%) key, . table: &mut self.table, . }) . } 917,553 ( 0.08%) } . } . . /// A view into a single entry in a map, which may either be vacant or occupied. . /// . /// This `enum` is constructed from the [`entry`] method on [`HashMap`]. . /// . /// [`HashMap`]: struct.HashMap.html . /// [`entry`]: struct.HashMap.html#method.rustc_entry -- line 62 ---------------------------------------- -- line 405 ---------------------------------------- . /// if let RustcEntry::Occupied(o) = map.rustc_entry("poneyland") { . /// *o.into_mut() += 10; . /// } . /// . /// assert_eq!(map["poneyland"], 22); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn into_mut(self) -> &'a mut V { 4,616 ( 0.00%) unsafe { &mut self.elem.as_mut().1 } . } . . /// Sets the value of the entry, and returns the entry's old value. . /// . /// # Examples . /// . /// ``` . /// use hashbrown::HashMap; -- line 421 ---------------------------------------- -- line 568 ---------------------------------------- . /// let mut map: HashMap<&str, u32> = HashMap::new(); . /// . /// if let RustcEntry::Vacant(o) = map.rustc_entry("poneyland") { . /// o.insert(37); . /// } . /// assert_eq!(map["poneyland"], 37); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 3,592 ( 0.00%) pub fn insert(self, value: V) -> &'a mut V { . unsafe { 55,960 ( 0.00%) let bucket = self.table.insert_no_grow(self.hash, (self.key, value)); 1,527 ( 0.00%) &mut bucket.as_mut().1 . } 4,755 ( 0.00%) } . . /// Sets the value of the entry with the RustcVacantEntry's key, . /// and returns a RustcOccupiedEntry. . /// . /// # Examples . /// . /// ``` . /// use hashbrown::HashMap; -- line 589 ---------------------------------------- 235,468 ( 0.02%) -------------------------------------------------------------------------------- -- 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%) } . 462,349 ( 0.04%) #[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 } 1,022,640 ( 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. 2 ( 0.00%) pub fn from_str(string: &str) -> Ident { 2 ( 0.00%) Ident::with_dummy_span(Symbol::intern(string)) 8 ( 0.00%) } . . /// Maps a string and a span to an identifier. 230 ( 0.00%) pub fn from_str_and_span(string: &str, span: Span) -> Ident { 115 ( 0.00%) Ident::new(Symbol::intern(string), span) 230 ( 0.00%) } . . /// Replaces `lo` and `hi` with those from `span`, but keep hygiene context. 21,896 ( 0.00%) pub fn with_span_pos(self, span: Span) -> Ident { . Ident::new(self.name, span.with_ctxt(self.span.ctxt())) 13,685 ( 0.00%) } . . pub fn without_first_quote(self) -> Ident { . Ident::new(Symbol::intern(self.as_str().trim_start_matches('\'')), self.span) . } . . /// "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. 87,471 ( 0.01%) pub fn normalize_to_macros_2_0(self) -> Ident { . Ident::new(self.name, self.span.normalize_to_macros_2_0()) 68,033 ( 0.01%) } . . /// "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. 1,071,369 ( 0.10%) pub fn normalize_to_macro_rules(self) -> Ident { . Ident::new(self.name, self.span.normalize_to_macro_rules()) 833,287 ( 0.07%) } . . /// 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 { 79 ( 0.00%) self.name.as_str() . } . } . . impl PartialEq for Ident { 406,983 ( 0.04%) fn eq(&self, rhs: &Self) -> bool { 1,022,150 ( 0.09%) self.name == rhs.name && self.span.ctxt() == rhs.span.ctxt() 542,644 ( 0.05%) } . } . . impl Hash for Ident { . fn hash(&self, state: &mut H) { 2,142 ( 0.00%) self.name.hash(state); 19,466 ( 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 { 84 ( 0.00%) fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 105 ( 0.00%) fmt::Display::fmt(&IdentPrinter::new(self.name, self.is_raw_guess(), None), f) 84 ( 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. 578 ( 0.00%) pub fn new(symbol: Symbol, is_raw: bool, convert_dollar_crate: Option) -> IdentPrinter { 3,257 ( 0.00%) IdentPrinter { symbol, is_raw, convert_dollar_crate } 578 ( 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. 420 ( 0.00%) pub fn for_ast_ident(ident: Ident, is_raw: bool) -> IdentPrinter { 420 ( 0.00%) IdentPrinter::new(ident.name, is_raw, Some(ident.span)) 210 ( 0.00%) } . } . . impl fmt::Display for IdentPrinter { 4,045 ( 0.00%) fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 1,618 ( 0.00%) if self.is_raw { . f.write_str("r#")?; 809 ( 0.00%) } else if self.symbol == kw::DollarCrate { . if let Some(span) = self.convert_dollar_crate { . let converted = span.ctxt().dollar_crate_name(); . if !converted.is_path_segment_keyword() { . f.write_str("::")?; . } . return fmt::Display::fmt(&converted, f); . } . } -- line 1654 ---------------------------------------- -- line 1656 ---------------------------------------- . } . } . . /// An newtype around `Ident` that calls [Ident::normalize_to_macro_rules] on . /// construction. . // FIXME(matthewj, petrochenkov) Use this more often, add a similar . // `ModernIdent` struct and use that as well. . #[derive(Copy, Clone, Eq, PartialEq, Hash)] 574,203 ( 0.05%) pub struct MacroRulesNormalizedIdent(Ident); . . impl MacroRulesNormalizedIdent { . pub fn new(ident: Ident) -> Self { 118,738 ( 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)] 38,592 ( 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)) 150 ( 0.00%) } . . /// Maps a string to its interned representation. 231,831 ( 0.02%) pub fn intern(string: &str) -> Self { . with_session_globals(|session_globals| session_globals.symbol_interner.intern(string)) 231,831 ( 0.02%) } . . /// 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. 56,745 ( 0.01%) pub fn as_str(&self) -> &str { 18,915 ( 0.00%) with_session_globals(|session_globals| unsafe { . std::mem::transmute::<&str, &str>(session_globals.symbol_interner.get(*self)) . }) 75,660 ( 0.01%) } . . pub fn as_u32(self) -> u32 { . self.0.as_u32() . } . . pub fn is_empty(self) -> bool { . self == kw::Empty . } -- line 1730 ---------------------------------------- -- line 1740 ---------------------------------------- . . 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 { 264 ( 0.00%) fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 8,073 ( 0.00%) fmt::Display::fmt(self.as_str(), f) . } . } . . impl Encodable for Symbol { . fn encode(&self, s: &mut S) -> Result<(), S::Error> { 38,993 ( 0.00%) s.emit_str(self.as_str()) . } . } . . impl Decodable for Symbol { . #[inline] 10,720 ( 0.00%) fn decode(d: &mut D) -> Symbol { 58,685 ( 0.01%) Symbol::intern(&d.read_str()) . } . } . . impl HashStable for Symbol { . #[inline] 12,648 ( 0.00%) fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) { 14,533 ( 0.00%) self.as_str().hash_stable(hcx, hasher); 12,582 ( 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(); 38,872 ( 0.00%) if let Some(&name) = inner.names.get(string) { . return name; . } . 6,323 ( 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 { 56,745 ( 0.01%) 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. 257 ( 0.00%) pub fn integer + Copy + ToString>(n: N) -> Symbol { 227 ( 0.00%) if let Result::Ok(idx) = n.try_into() { 20 ( 0.00%) if idx < 10 { 300 ( 0.00%) return Symbol::new(super::SYMBOL_DIGITS_BASE + idx as u32); . } . } . Symbol::intern(&n.to_string()) . } . } . . impl Symbol { . fn is_special(self) -> bool { . self <= kw::Underscore . } . . fn is_used_keyword_always(self) -> bool { 246 ( 0.00%) self >= kw::As && self <= kw::While . } . . fn is_used_keyword_conditional(self, edition: impl FnOnce() -> Edition) -> bool { 19,413 ( 0.00%) (self >= kw::Async && self <= kw::Dyn) && edition() >= Edition::Edition2018 . } . . fn is_unused_keyword_always(self) -> bool { 246 ( 0.00%) self >= kw::Abstract && self <= kw::Yield . } . . fn is_unused_keyword_conditional(self, edition: impl FnOnce() -> Edition) -> bool { 82 ( 0.00%) self == kw::Try && edition() >= Edition::Edition2018 . } . . pub fn is_reserved(self, edition: impl Copy + FnOnce() -> Edition) -> bool { 32,220 ( 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 { 88,760 ( 0.01%) 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 { 717 ( 0.00%) self == kw::True || self == kw::False 717 ( 0.00%) } . . /// Returns `true` if this symbol can be a raw identifier. . pub fn can_be_raw(self) -> bool { 434 ( 0.00%) self != kw::Empty && self != kw::Underscore && !self.is_path_segment_keyword() 2 ( 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() 82 ( 0.00%) } . . /// Returns `true` if the token is a keyword used in the language. 82 ( 0.00%) pub fn is_used_keyword(self) -> bool { . // Note: `span.edition()` is relatively expensive, don't call it unless necessary. 82 ( 0.00%) self.name.is_used_keyword_always() . || self.name.is_used_keyword_conditional(|| self.span.edition()) 164 ( 0.00%) } . . /// Returns `true` if the token is a keyword reserved for possible future use. 82 ( 0.00%) pub fn is_unused_keyword(self) -> bool { . // Note: `span.edition()` is relatively expensive, don't call it unless necessary. 82 ( 0.00%) self.name.is_unused_keyword_always() . || self.name.is_unused_keyword_conditional(|| self.span.edition()) 164 ( 0.00%) } . . /// Returns `true` if the token is either a special identifier or a keyword. 6,233 ( 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()) 12,466 ( 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() 12,680 ( 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. 190 ( 0.00%) pub fn is_raw_guess(self) -> bool { . self.name.can_be_raw() && self.is_reserved() 380 ( 0.00%) } . } 170,993 ( 0.02%) -------------------------------------------------------------------------------- -- 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 10,688 ( 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 { 42,513 ( 0.00%) let result = ptr::read(dest); 2,657,920 ( 0.24%) ptr::write(dest, src); . result . } . } . . /// Disposes of a value. . /// . /// This does so by calling the argument's implementation of [`Drop`][drop]. . /// -- line 848 ---------------------------------------- -- line 901 ---------------------------------------- . /// . /// println!("x: {}, y: {}", x, y.0); // still available . /// ``` . /// . /// [`RefCell`]: crate::cell::RefCell . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[cfg_attr(not(test), rustc_diagnostic_item = "mem_drop")] 3 ( 0.00%) pub fn drop(_x: T) {} . . /// Interprets `src` as having type `&U`, and then reads `src` without moving . /// the contained value. . /// . /// This function will unsafely assume the pointer `src` is valid for [`size_of::`][size_of] . /// bytes by transmuting `&T` to `&U` and then reading the `&U` (except that this is done in a way . /// that is correct even when `&U` makes stricter alignment requirements than `&T`). It will also . /// unsafely create a copy of the contained value instead of moving out of `src`. -- line 917 ---------------------------------------- -- line 991 ---------------------------------------- . } . } . . #[stable(feature = "discriminant_value", since = "1.21.0")] . impl cmp::Eq for Discriminant {} . . #[stable(feature = "discriminant_value", since = "1.21.0")] . impl hash::Hash for Discriminant { 386 ( 0.00%) fn hash(&self, state: &mut H) { . self.0.hash(state); 694 ( 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 { 4,860 ( 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 ---------------------------------------- 3,107 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe.rs -------------------------------------------------------------------------------- Ir -- line 23 ---------------------------------------- . struct Delimited { . delim: token::DelimToken, . tts: Vec, . } . . impl Delimited { . /// Returns a `self::TokenTree` with a `Span` corresponding to the opening delimiter. . fn open_tt(&self, span: DelimSpan) -> TokenTree { 36,996 ( 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 { 593,220 ( 0.05%) 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, . } . 237 ( 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 } 20 ( 0.00%) } . } . . /// A Kleene-style [repetition operator](https://en.wikipedia.org/wiki/Kleene_star) . /// for token sequences. 99 ( 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. 6,179,751 ( 0.55%) #[derive(Debug, Clone, PartialEq, Encodable, Decodable)] . enum TokenTree { 8,615 ( 0.00%) Token(Token), 165,560 ( 0.01%) Delimited(DelimSpan, Lrc), . /// A kleene-style repetition sequence 8,093 ( 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. 321,652 ( 0.03%) MetaVarDecl(Span, Ident /* name to bind */, Option), . } . . impl TokenTree { . /// Return the number of tokens in the tree. . fn len(&self) -> usize { 3,678,338 ( 0.33%) match *self { 1,070,184 ( 0.09%) TokenTree::Delimited(_, ref delimed) => match delimed.delim { . token::NoDelim => delimed.tts.len(), 713,456 ( 0.06%) _ => delimed.tts.len() + 2, . }, 1,578,915 ( 0.14%) 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. 1,482,393 ( 0.13%) fn get_tt(&self, index: usize) -> TokenTree { 2,110,767 ( 0.19%) match (self, index) { 539,832 ( 0.05%) (&TokenTree::Delimited(_, ref delimed), _) if delimed.delim == token::NoDelim => { . delimed.tts[index].clone() . } . (&TokenTree::Delimited(span, ref delimed), _) => { 359,888 ( 0.03%) if index == 0 { . return delimed.open_tt(span); . } 1,005,936 ( 0.09%) if index == delimed.tts.len() + 1 { . return delimed.close_tt(span); . } 19,384 ( 0.00%) delimed.tts[index - 1].clone() . } 314,187 ( 0.03%) (&TokenTree::Sequence(_, ref seq), _) => seq.tts[index].clone(), . _ => panic!("Cannot expand a token tree"), . } 1,976,524 ( 0.18%) } . . /// Retrieves the `TokenTree`'s span. . fn span(&self) -> Span { 24,980 ( 0.00%) match *self { . TokenTree::Token(Token { span, .. }) . | TokenTree::MetaVar(span, _) . | TokenTree::MetaVarDecl(span, _, _) => span, 3,208 ( 0.00%) TokenTree::Delimited(span, _) | TokenTree::Sequence(span, _) => span.entire(), . } . } . . fn token(kind: TokenKind, span: Span) -> TokenTree { 837 ( 0.00%) TokenTree::Token(Token::new(kind, span)) . } . } 2,860,696 ( 0.25%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_serialize/src/opaque.rs -------------------------------------------------------------------------------- Ir -- line 14 ---------------------------------------- . . pub type EncodeResult = Result<(), !>; . . pub struct Encoder { . pub data: Vec, . } . . impl Encoder { 1 ( 0.00%) pub fn new(data: Vec) -> Encoder { 4 ( 0.00%) Encoder { data } 1 ( 0.00%) } . 1 ( 0.00%) pub fn into_inner(self) -> Vec { 4 ( 0.00%) self.data 1 ( 0.00%) } . . #[inline] . pub fn position(&self) -> usize { 7,664 ( 0.00%) self.data.len() . } . } . . macro_rules! write_leb128 { . ($enc:expr, $value:expr, $int_ty:ty, $fun:ident) => {{ . const MAX_ENCODED_LEN: usize = max_leb128_len!($int_ty); . let old_len = $enc.data.len(); . -- line 40 ---------------------------------------- -- line 67 ---------------------------------------- . . #[inline] . fn emit_unit(&mut self) -> EncodeResult { . Ok(()) . } . . #[inline] . fn emit_usize(&mut self, v: usize) -> EncodeResult { 194,803 ( 0.02%) write_leb128!(self, v, usize, write_usize_leb128) . } . . #[inline] . fn emit_u128(&mut self, v: u128) -> EncodeResult { 343 ( 0.00%) write_leb128!(self, v, u128, write_u128_leb128) . } . . #[inline] . fn emit_u64(&mut self, v: u64) -> EncodeResult { 448 ( 0.00%) write_leb128!(self, v, u64, write_u64_leb128) . } . . #[inline] . fn emit_u32(&mut self, v: u32) -> EncodeResult { 242,837 ( 0.02%) write_leb128!(self, v, u32, write_u32_leb128) . } . . #[inline] . fn emit_u16(&mut self, v: u16) -> EncodeResult { . self.data.extend_from_slice(&v.to_le_bytes()); . Ok(()) . } . -- line 98 ---------------------------------------- -- line 131 ---------------------------------------- . #[inline] . fn emit_i8(&mut self, v: i8) -> EncodeResult { . let as_u8: u8 = unsafe { std::mem::transmute(v) }; . self.emit_u8(as_u8) . } . . #[inline] . fn emit_bool(&mut self, v: bool) -> EncodeResult { 3,387 ( 0.00%) self.emit_u8(if v { 1 } else { 0 }) . } . . #[inline] . fn emit_f64(&mut self, v: f64) -> EncodeResult { . let as_u64: u64 = v.to_bits(); . self.emit_u64(as_u64) . } . -- line 147 ---------------------------------------- -- line 549 ---------------------------------------- . #[inline] . pub fn advance(&mut self, bytes: usize) { . self.position += bytes; . } . . #[inline] . pub fn read_raw_bytes(&mut self, bytes: usize) -> &'a [u8] { . let start = self.position; 19 ( 0.00%) self.position += bytes; 19 ( 0.00%) &self.data[start..self.position] . } . } . . macro_rules! read_leb128 { . ($dec:expr, $fun:ident) => {{ leb128::$fun($dec.data, &mut $dec.position) }}; . } . . impl<'a> serialize::Decoder for Decoder<'a> { . #[inline] . fn read_unit(&mut self) -> () { . () . } . . #[inline] . fn read_u128(&mut self) -> u128 { 531 ( 0.00%) read_leb128!(self, read_u128_leb128) . } . . #[inline] . fn read_u64(&mut self) -> u64 { 2,874 ( 0.00%) read_leb128!(self, read_u64_leb128) . } . . #[inline] 31,255 ( 0.00%) fn read_u32(&mut self) -> u32 { 148,996 ( 0.01%) read_leb128!(self, read_u32_leb128) 62,510 ( 0.01%) } . . #[inline] . fn read_u16(&mut self) -> u16 { 561,386 ( 0.05%) let bytes = [self.data[self.position], self.data[self.position + 1]]; 80,198 ( 0.01%) let value = u16::from_le_bytes(bytes); 160,396 ( 0.01%) self.position += 2; . value . } . . #[inline] . fn read_u8(&mut self) -> u8 { 1,807,965 ( 0.16%) let value = self.data[self.position]; 345,110 ( 0.03%) self.position += 1; . value . } . . #[inline] 226,560 ( 0.02%) fn read_usize(&mut self) -> usize { 226,594 ( 0.02%) read_leb128!(self, read_usize_leb128) 453,120 ( 0.04%) } . . #[inline] . fn read_i128(&mut self) -> i128 { . read_leb128!(self, read_i128_leb128) . } . . #[inline] . fn read_i64(&mut self) -> i64 { -- line 613 ---------------------------------------- -- line 637 ---------------------------------------- . #[inline] . fn read_isize(&mut self) -> isize { . read_leb128!(self, read_isize_leb128) . } . . #[inline] . fn read_bool(&mut self) -> bool { . let value = self.read_u8(); 8,291 ( 0.00%) value != 0 . } . . #[inline] . fn read_f64(&mut self) -> f64 { . let bits = self.read_u64(); . f64::from_bits(bits) . } . -- line 653 ---------------------------------------- -- line 660 ---------------------------------------- . #[inline] . fn read_char(&mut self) -> char { . let bits = self.read_u32(); . std::char::from_u32(bits).unwrap() . } . . #[inline] . fn read_str(&mut self) -> Cow<'_, str> { 34,385 ( 0.00%) let len = self.read_usize(); 179,666 ( 0.02%) let sentinel = self.data[self.position + len]; 44,942 ( 0.00%) assert!(sentinel == STR_SENTINEL); . let s = unsafe { . std::str::from_utf8_unchecked(&self.data[self.position..self.position + len]) . }; 112,355 ( 0.01%) self.position += len + 1; 35,838 ( 0.00%) Cow::Borrowed(s) . } . . #[inline] . fn read_raw_bytes_into(&mut self, s: &mut [u8]) { 106 ( 0.00%) let start = self.position; 1,867 ( 0.00%) self.position += s.len(); 106 ( 0.00%) s.copy_from_slice(&self.data[start..self.position]); . } . } . . // Specializations for contiguous byte sequences follow. The default implementations for slices . // encode and decode each element individually. This isn't necessary for `u8` slices when using . // opaque encoders and decoders, because each `u8` is unchanged by encoding and decoding. . // Therefore, we can use more efficient implementations that process the entire sequence at once. . -- line 690 ---------------------------------------- 574,397 ( 0.05%) -------------------------------------------------------------------------------- -- 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. 326,400 ( 0.03%) pub fn nonterminal_may_begin_with(kind: NonterminalKind, token: &Token) -> bool { . /// Checks whether the non-terminal may contain a single (non-keyword) identifier. . fn may_be_ident(nt: &token::Nonterminal) -> bool { . match *nt { . token::NtItem(_) | token::NtBlock(_) | token::NtVis(_) | token::NtLifetime(_) => { . false . } . _ => true, . } . } . 1,632,000 ( 0.14%) match kind { . NonterminalKind::Expr => { 10,056 ( 0.00%) token.can_begin_expr() . // This exception is here for backwards compatibility. 5,028 ( 0.00%) && !token.is_keyword(kw::Let) . // This exception is here for backwards compatibility. 6,704 ( 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(), . NonterminalKind::Vis => match token.kind { . // The follow-set of :vis + "priv" keyword + interpolated . token::Comma | token::Ident(..) | token::Interpolated(..) => true, . _ => token.can_begin_type(), -- line 41 ---------------------------------------- -- line 85 ---------------------------------------- . NonterminalKind::Lifetime => match token.kind { . token::Lifetime(_) => true, . token::Interpolated(ref nt) => { . matches!(**nt, token::NtLifetime(_) | token::NtTT(_)) . } . _ => false, . }, . NonterminalKind::TT | NonterminalKind::Item | NonterminalKind::Stmt => { 322,890 ( 0.03%) !matches!(token.kind, token::CloseDelim(_)) . } . } 326,394 ( 0.03%) } . . /// Parse a non-terminal (e.g. MBE `:pat` or `:ident`). 1,424,313 ( 0.13%) 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. 1,740,827 ( 0.15%) let mut nt = match kind { . NonterminalKind::Item => match self.parse_item(ForceCollect::Yes)? { . Some(item) => token::NtItem(item), . None => { . return Err(self.struct_span_err(self.token.span, "expected an item keyword")); . } . }, . NonterminalKind::Block => { . // While a block *expression* may have attributes (e.g. `#[my_attr] { ... }`), -- line 114 ---------------------------------------- -- line 126 ---------------------------------------- . NonterminalKind::PatParam { .. } => this.parse_pat_no_top_alt(None), . NonterminalKind::PatWithOr { .. } => { . this.parse_pat_allow_top_alt(None, RecoverComma::No, RecoverColon::No) . } . _ => unreachable!(), . })?) . } . 6,704 ( 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 => { 6 ( 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 456 ( 0.00%) if let Some((ident, is_raw)) = get_macro_ident(&self.token) => . { 152 ( 0.00%) self.bump(); 532 ( 0.00%) token::NtIdent(ident, is_raw) . } . NonterminalKind::Ident => { . let token_str = pprust::token_to_string(&self.token); . let msg = &format!("expected ident, found {}", &token_str); . return Err(self.struct_span_err(self.token.span, msg)); . } . NonterminalKind::Path => token::NtPath( . self.collect_tokens_no_attrs(|this| this.parse_path(PathStyle::Type))?, . ), . NonterminalKind::Meta => token::NtMeta(P(self.parse_attr_item(true)?)), 782,510 ( 0.07%) NonterminalKind::TT => token::NtTT(self.parse_token_tree()), . NonterminalKind::Vis => token::NtVis( . self.collect_tokens_no_attrs(|this| this.parse_visibility(FollowedByType::Yes))?, . ), . NonterminalKind::Lifetime => { . if self.check_lifetime() { . token::NtLifetime(self.expect_lifetime().ident) . } else { . let token_str = pprust::token_to_string(&self.token); . let msg = &format!("expected a lifetime, found `{}`", &token_str); . return Err(self.struct_span_err(self.token.span, msg)); . } . } . }; . . // If tokens are supported at all, they should be collected. 478,129 ( 0.04%) if matches!(nt.tokens_mut(), Some(None)) { . panic!( . "Missing tokens for nt {:?} at {:?}: {:?}", . nt, . nt.span(), . pprust::nonterminal_to_string(&nt) . ); . } . 1,107,799 ( 0.10%) Ok(nt) 1,424,313 ( 0.13%) } . } . . /// 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)> { 304 ( 0.00%) token.ident().filter(|(ident, _)| ident.name != kw::Underscore) . } 158,272 ( 0.01%) -------------------------------------------------------------------------------- -- 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")] 4,876 ( 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( 1,529,902 ( 0.14%) Box::leak(box RcBox { strong: Cell::new(1), weak: Cell::new(1), value }).into(), . ) . } 4,876 ( 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 { 453,669 ( 0.04%) 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 { 312 ( 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> { 104 ( 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`). 360,649 ( 0.03%) unsafe { &mut (*this.ptr.as_ptr()).value } . } . . #[inline] . #[stable(feature = "ptr_eq", since = "1.17.0")] . /// Returns `true` if the two `Rc`s point to the same allocation . /// (in a vein similar to [`ptr::eq`]). . /// . /// # Examples -- line 1104 ---------------------------------------- -- line 1109 ---------------------------------------- . /// let five = Rc::new(5); . /// let same_five = Rc::clone(&five); . /// let other_five = Rc::new(5); . /// . /// assert!(Rc::ptr_eq(&five, &same_five)); . /// assert!(!Rc::ptr_eq(&five, &other_five)); . /// ``` . pub fn ptr_eq(this: &Self, other: &Self) -> bool { 258 ( 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")] 1,604,002 ( 0.14%) pub fn make_mut(this: &mut Self) -> &mut T { 962,286 ( 0.09%) if Rc::strong_count(this) != 1 { . // Gotta clone the data, there are other Rcs. . // Pre-allocate memory to allow writing the cloned value directly. 169,726 ( 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()); 339,452 ( 0.03%) *this = rc.assume_init(); . } 302,238 ( 0.03%) } else if Rc::weak_count(this) != 0 { . // Can just steal the data, all that's left is Weaks . let mut rc = Self::new_uninit(); . unsafe { . let data = Rc::get_mut_unchecked(&mut rc); . data.as_mut_ptr().copy_from_nonoverlapping(&**this, 1); . . this.inner().dec_strong(); . // Remove implicit strong-weak ref (no need to craft a fake -- line 1193 ---------------------------------------- -- line 1196 ---------------------------------------- . ptr::write(this, rc.assume_init()); . } . } . // This unsafety is ok because we're guaranteed that the pointer . // returned is the *only* pointer that will ever be returned to T. Our . // reference count is guaranteed to be 1 at this point, and we required . // the `Rc` itself to be `mut`, so we're returning the only possible . // reference to the allocation. 320,845 ( 0.03%) unsafe { &mut this.ptr.as_mut().value } 1,924,764 ( 0.17%) } . } . . 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))] 1,740 ( 0.00%) unsafe fn copy_from_slice(v: &[T]) -> Rc<[T]> { . unsafe { . let ptr = Self::allocate_for_slice(v.len()); 368 ( 0.00%) ptr::copy_nonoverlapping(v.as_ptr(), &mut (*ptr).value as *mut [T] as *mut T, v.len()); . Self::from_ptr(ptr) . } 2,242 ( 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 { 92,641 ( 0.01%) &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!" . /// ``` 1,849,117 ( 0.16%) fn drop(&mut self) { . unsafe { 1,357,088 ( 0.12%) self.inner().dec_strong(); 3,108,038 ( 0.28%) if self.inner().strong() == 0 { . // destroy the contained object 169,543 ( 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(); . 744,811 ( 0.07%) if self.inner().weak() == 0 { 252 ( 0.00%) Global.deallocate(self.ptr.cast(), Layout::for_value(self.ptr.as_ref())); . } . } . } 2,166,264 ( 0.19%) } . } . . #[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 { 262 ( 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 { 514 ( 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; 33 ( 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) { 1,173,973 ( 0.10%) 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. 3,573,984 ( 0.32%) if strong == 0 || strong == usize::MAX { . abort(); . } 4,715 ( 0.00%) self.strong_ref().set(strong + 1); . } . . #[inline] . fn dec_strong(&self) { 5,358,512 ( 0.48%) 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) { 1,116,203 ( 0.10%) self.weak_ref().set(self.weak() - 1); . } . } . . impl RcInnerPtr for RcBox { . #[inline(always)] . fn weak_ref(&self) -> &Cell { . &self.weak . } -- line 2523 ---------------------------------------- 1,421,099 ( 0.13%) -------------------------------------------------------------------------------- -- 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}; . 11,808 ( 0.00%) #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub enum CommentKind { . Line, . Block, . } . 69 ( 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. 188,621 ( 0.02%) #[derive(Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug, Copy)] . #[derive(HashStable_Generic)] . pub enum DelimToken { . /// A round parenthesis (i.e., `(` or `)`). . Paren, . /// A square bracket (i.e., `[` or `]`). . Bracket, . /// A curly brace (i.e., `{` or `}`). . Brace, . /// An empty delimiter. . NoDelim, . } . 1,332 ( 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. 150,575 ( 0.01%) #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub struct Lit { . pub kind: LitKind, . pub symbol: Symbol, . pub suffix: Option, . } . . impl fmt::Display for Lit { 240 ( 0.00%) fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 432 ( 0.00%) let Lit { kind, symbol, suffix } = *self; . match kind { . Byte => write!(f, "b'{}'", symbol)?, . Char => write!(f, "'{}'", symbol)?, 96 ( 0.00%) Str => write!(f, "\"{}\"", symbol)?, . StrRaw(n) => write!( . f, . "r{delim}\"{string}\"{delim}", . delim = "#".repeat(n as usize), . string = symbol . )?, . ByteStr => write!(f, "b\"{}\"", symbol)?, . ByteStrRaw(n) => write!( . f, . "br{delim}\"{string}\"{delim}", . delim = "#".repeat(n as usize), . string = symbol . )?, 48 ( 0.00%) Integer | Float | Bool | Err => write!(f, "{}", symbol)?, . } . 96 ( 0.00%) if let Some(suffix) = suffix { . write!(f, "{}", suffix)?; . } . . Ok(()) 240 ( 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,245 ( 0.00%) } . } . 3,288 ( 0.00%) pub fn ident_can_begin_expr(name: Symbol, span: Span, is_raw: bool) -> bool { 5,754 ( 0.00%) let ident_token = Token::new(Ident(name, is_raw), span); . 1,644 ( 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) 4,110 ( 0.00%) } . . fn ident_can_begin_type(name: Symbol, span: Span, is_raw: bool) -> bool { 138 ( 0.00%) let ident_token = Token::new(Ident(name, is_raw), span); . 48 ( 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) . } . 15,013,044 ( 1.33%) #[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, 10,353 ( 0.00%) BinOp(BinOpToken), 9 ( 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., `{`). 48,711 ( 0.00%) OpenDelim(DelimToken), . /// A closing delimiter (e.g., `}`). 4,047 ( 0.00%) CloseDelim(DelimToken), . . /* Literals */ 218,778 ( 0.02%) 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. 194,686 ( 0.02%) Ident(Symbol, /* is_raw */ bool), . /// Lifetime identifier token. . /// Do not forget about `NtLifetime` when you want to match on lifetime identifiers. . /// It's recommended to use `Token::(lifetime,uninterpolate,uninterpolated_span)` to . /// treat regular and interpolated lifetime identifiers in the same way. . Lifetime(Symbol), . 28,420 ( 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. 2,343 ( 0.00%) DocComment(CommentKind, ast::AttrStyle, Symbol), . . Eof, . } . . // `TokenKind` is used a lot. Make sure it doesn't unintentionally get bigger. . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . rustc_data_structures::static_assert_size!(TokenKind, 16); . 1,998,283 ( 0.18%) #[derive(Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub struct Token { 269,411 ( 0.02%) pub kind: TokenKind, 16 ( 0.00%) pub span: Span, . } . . impl TokenKind { . pub fn lit(kind: LitKind, symbol: Symbol, suffix: Option) -> TokenKind { . Literal(Lit::new(kind, symbol, suffix)) . } . . // An approximation to proc-macro-style single-character operators used by rustc parser. . // If the operator token can be broken into two tokens, the first of which is single-character, . // then this function performs that operation, otherwise it returns `None`. 1,353 ( 0.00%) pub fn break_two_token_op(&self) -> Option<(TokenKind, TokenKind)> { 5,412 ( 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), 1,353 ( 0.00%) _ => return None, . }) 1,353 ( 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 { 120 ( 0.00%) matches!(self, Gt | Ge | BinOp(Shr) | BinOpEq(Shr)) 30 ( 0.00%) } . } . . impl Token { 170,045 ( 0.02%) pub fn new(kind: TokenKind, span: Span) -> Self { 538,934 ( 0.05%) Token { kind, span } 170,045 ( 0.02%) } . . /// Some token that will be thrown away later. 8,473 ( 0.00%) pub fn dummy() -> Self { . Token::new(TokenKind::Question, DUMMY_SP) 8,473 ( 0.00%) } . . /// Recovers a `Token` from an `Ident`. This creates a raw identifier if necessary. . pub fn from_ast_ident(ident: Ident) -> Self { 672 ( 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. 4,324 ( 0.00%) pub fn take(&mut self) -> Self { . mem::replace(self, Token::dummy()) 4,324 ( 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 { 370 ( 0.00%) match &self.kind { . Interpolated(nt) => nt.span(), 185 ( 0.00%) _ => self.span, . } 185 ( 0.00%) } . . pub fn is_op(&self) -> bool { 12,972 ( 0.00%) !matches!( 4,324 ( 0.00%) self.kind, . OpenDelim(..) . | CloseDelim(..) . | Literal(..) . | DocComment(..) . | Ident(..) . | Lifetime(..) . | Interpolated(..) . | Eof . ) 4,324 ( 0.00%) } . . pub fn is_like_plus(&self) -> bool { 1,785 ( 0.00%) matches!(self.kind, BinOp(Plus) | BinOpEq(Plus)) 357 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of an expression. 1,680 ( 0.00%) pub fn can_begin_expr(&self) -> bool { 8,400 ( 0.00%) match self.uninterpolate().kind { 7,398 ( 0.00%) Ident(name, is_raw) => 2,466 ( 0.00%) ident_can_begin_expr(name, self.span, is_raw), // value name or keyword . OpenDelim(..) | // tuple, array or block . Literal(..) | // literal . Not | // operator not . BinOp(Minus) | // unary minus . BinOp(Star) | // dereference . BinOp(Or) | OrOr | // closure . BinOp(And) | // reference . AndAnd | // double reference -- line 371 ---------------------------------------- -- line 376 ---------------------------------------- . Lifetime(..) | // labeled loop . Pound => true, // expression attributes . Interpolated(ref nt) => matches!(**nt, NtLiteral(..) | . NtExpr(..) | . NtBlock(..) | . NtPath(..)), . _ => false, . } 3,360 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of a type. 164 ( 0.00%) pub fn can_begin_type(&self) -> bool { 245 ( 0.00%) match self.uninterpolate().kind { 207 ( 0.00%) Ident(name, is_raw) => 23 ( 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 88 ( 0.00%) Interpolated(ref nt) => matches!(**nt, NtTy(..) | NtPath(..)), . _ => false, . } 246 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of a const param. . pub fn can_begin_const_arg(&self) -> bool { 165 ( 0.00%) match self.kind { . OpenDelim(Brace) => true, 64 ( 0.00%) Interpolated(ref nt) => matches!(**nt, NtExpr(..) | NtBlock(..) | NtLiteral(..)), 25 ( 0.00%) _ => self.can_begin_literal_maybe_minus(), . } 8 ( 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. 26 ( 0.00%) pub fn can_begin_literal_maybe_minus(&self) -> bool { 230 ( 0.00%) match self.uninterpolate().kind { . Literal(..) | BinOp(Minus) => true, 80 ( 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, . } 52 ( 0.00%) } . . // A convenience function for matching on identifiers during parsing. . // Turns interpolated identifier (`$i: ident`) or lifetime (`$l: lifetime`) token . // into the regular identifier or lifetime token it refers to, . // otherwise returns the original token. 4,071 ( 0.00%) pub fn uninterpolate(&self) -> Cow<'_, Token> { 1,666,124 ( 0.15%) match &self.kind { 23,252 ( 0.00%) Interpolated(nt) => match **nt { 3,128 ( 0.00%) NtIdent(ident, is_raw) => { 7,828 ( 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), . } 4,071 ( 0.00%) } . . /// Returns an identifier if this token is an identifier. 363,972 ( 0.03%) pub fn ident(&self) -> Option<(Ident, /* is_raw */ bool)> { . let token = self.uninterpolate(); 889,287 ( 0.08%) match token.kind { 1,189,951 ( 0.11%) Ident(name, is_raw) => Some((Ident::new(name, token.span), is_raw)), . _ => None, . } 2,213,752 ( 0.20%) } . . /// Returns a lifetime identifier if this token is a lifetime. 343,114 ( 0.03%) pub fn lifetime(&self) -> Option { . let token = self.uninterpolate(); 686,396 ( 0.06%) match token.kind { . Lifetime(name) => Some(Ident::new(name, token.span)), . _ => None, . } 2,401,798 ( 0.21%) } . . /// Returns `true` if the token is an identifier. . pub fn is_ident(&self) -> bool { . self.ident().is_some() 483 ( 0.00%) } . . /// Returns `true` if the token is a lifetime. 84 ( 0.00%) pub fn is_lifetime(&self) -> bool { . self.lifetime().is_some() 168 ( 0.00%) } . . /// Returns `true` if the token is an identifier whose name is the given . /// string slice. 1,094 ( 0.00%) pub fn is_ident_named(&self, name: Symbol) -> bool { . self.ident().map_or(false, |(ident, _)| ident.name == name) 2,188 ( 0.00%) } . . /// Returns `true` if the token is an interpolated path. . fn is_path(&self) -> bool { 14,084 ( 0.00%) if let Interpolated(ref nt) = self.kind { 64 ( 0.00%) if let NtPath(..) = **nt { . return true; . } . } . false . } . . /// Would `maybe_whole_expr` in `parser.rs` return `Ok(..)`? . /// That is, is this a pre-parsed expression dropped into the token stream -- line 516 ---------------------------------------- -- line 522 ---------------------------------------- . } . } . . false . } . . // Is the token an interpolated block (`$b:block`)? . pub fn is_whole_block(&self) -> bool { 6 ( 0.00%) if let Interpolated(ref nt) = self.kind { . if let NtBlock(..) = **nt { . return true; . } . } . false 3 ( 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) . } . 238 ( 0.00%) pub fn is_qpath_start(&self) -> bool { 7,280 ( 0.00%) self == &Lt || self == &BinOp(Shl) . } . 14,088 ( 0.00%) pub fn is_path_start(&self) -> bool { 19,044 ( 0.00%) self == &ModSep . || self.is_qpath_start() . || self.is_path() . || self.is_path_segment_keyword() 3,361 ( 0.00%) || self.is_ident() && !self.is_reserved_ident() 17,610 ( 0.00%) } . . /// Returns `true` if the token is a given keyword, `kw`. 70,594 ( 0.01%) pub fn is_keyword(&self, kw: Symbol) -> bool { . self.is_non_raw_ident_where(|id| id.name == kw) 141,188 ( 0.01%) } . 94 ( 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. 82 ( 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. 82 ( 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. 82 ( 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`. 94 ( 0.00%) pub fn is_bool_lit(&self) -> bool { 188 ( 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. 64 ( 0.00%) pub fn is_non_raw_ident_where(&self, pred: impl FnOnce(Ident) -> bool) -> bool { 490,342 ( 0.04%) match self.ident() { 2,377 ( 0.00%) Some((id, false)) => pred(id), . _ => false, . } 80 ( 0.00%) } . 9,420 ( 0.00%) pub fn glue(&self, joint: &Token) -> Option { 4,710 ( 0.00%) let kind = match self.kind { 219 ( 0.00%) Eq => match joint.kind { . Eq => EqEq, . Gt => FatArrow, . _ => return None, . }, 30 ( 0.00%) Lt => match joint.kind { . Eq => Le, . Lt => BinOp(Shl), . Le => BinOpEq(Shl), . BinOp(Minus) => LArrow, . _ => return None, . }, 10 ( 0.00%) Gt => match joint.kind { . Eq => Ge, . Gt => BinOp(Shr), . Ge => BinOpEq(Shr), . _ => return None, . }, 6 ( 0.00%) Not => match joint.kind { . Eq => Ne, . _ => return None, . }, 439 ( 0.00%) BinOp(op) => match joint.kind { . Eq => BinOpEq(op), 3 ( 0.00%) BinOp(And) if op == And => AndAnd, . BinOp(Or) if op == Or => OrOr, 50 ( 0.00%) Gt if op == Minus => RArrow, . _ => return None, . }, 20 ( 0.00%) Dot => match joint.kind { . Dot => DotDot, . DotDot => DotDotDot, . _ => return None, . }, . DotDot => match joint.kind { . Dot => DotDotDot, . Eq => DotDotEq, . _ => return None, . }, 184 ( 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, . }; . 2,704 ( 0.00%) Some(Token::new(kind, self.span.to(joint.span))) 8,478 ( 0.00%) } . } . . impl PartialEq for Token { . fn eq(&self, rhs: &TokenKind) -> bool { 278,449 ( 0.02%) self.kind == *rhs . } . } . . #[derive(Clone, Encodable, Decodable)] . /// For interpolation during macro expansion. . pub enum Nonterminal { . NtItem(P), . NtBlock(P), -- line 675 ---------------------------------------- -- line 711 ---------------------------------------- . Path, . Vis, . TT, . } . . impl NonterminalKind { . /// The `edition` closure is used to get the edition for the given symbol. Doing . /// `span.edition()` is expensive, so we do it lazily. 380 ( 0.00%) pub fn from_symbol( . symbol: Symbol, . edition: impl FnOnce() -> Edition, . ) -> Option { 910 ( 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, . }) 380 ( 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 { 32 ( 0.00%) pub fn span(&self) -> Span { 160 ( 0.00%) match self { . NtItem(item) => item.span, . NtBlock(block) => block.span, . NtStmt(stmt) => stmt.span, . NtPat(pat) => pat.span, 32 ( 0.00%) NtExpr(expr) | NtLiteral(expr) => expr.span, . NtTy(ty) => ty.span, . NtIdent(ident, _) | NtLifetime(ident) => ident.span, . NtMeta(attr_item) => attr_item.span(), . NtPath(path) => path.span, . NtVis(vis) => vis.span, . NtTT(tt) => tt.span(), . } 64 ( 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 ---------------------------------------- 6,470,062 ( 0.57%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs -------------------------------------------------------------------------------- Ir -- line 91 ---------------------------------------- . // maximum of number bytes needed to fill an 8-byte-sized element on which . // SipHash operates. Note that for variable-sized copies which are known to be . // less than 8 bytes, this function will perform more work than necessary unless . // the compiler is able to optimize the extra work away. . #[inline] . unsafe fn copy_nonoverlapping_small(src: *const u8, dst: *mut u8, count: usize) { . debug_assert!(count <= 8); . 18,516 ( 0.00%) if count == 8 { . ptr::copy_nonoverlapping(src, dst, 8); . return; . } . . let mut i = 0; 24,196 ( 0.00%) if i + 3 < count { . ptr::copy_nonoverlapping(src.add(i), dst.add(i), 4); . i += 4; . } . 52,098 ( 0.00%) if i + 1 < count { . ptr::copy_nonoverlapping(src.add(i), dst.add(i), 2); 6,962 ( 0.00%) i += 2 . } . 24,196 ( 0.00%) if i < count { 13,467 ( 0.00%) *dst.add(i) = *src.add(i); . i += 1; . } . . debug_assert_eq!(i, count); . } . . // # Implementation . // -- line 124 ---------------------------------------- -- line 201 ---------------------------------------- . . hasher . } . . // A specialized write function for values with size <= 8. . #[inline] . fn short_write(&mut self, x: T) { . let size = mem::size_of::(); 181,430 ( 0.02%) let nbuf = self.nbuf; . debug_assert!(size <= 8); . debug_assert!(nbuf < BUFFER_SIZE); . debug_assert!(nbuf + size < BUFFER_WITH_SPILL_SIZE); . 1,255,030 ( 0.11%) if nbuf + size < BUFFER_SIZE { . unsafe { . // The memcpy call is optimized away because the size is known. . let dst = (self.buf.as_mut_ptr() as *mut u8).add(nbuf); . ptr::copy_nonoverlapping(&x as *const _ as *const u8, dst, size); . } . 397,461 ( 0.04%) self.nbuf = nbuf + size; . . return; . } . 59,810 ( 0.01%) unsafe { self.short_write_process_buffer(x) } . } . . // A specialized write function for values with size <= 8 that should only . // be called when the write would cause the buffer to fill. . // . // SAFETY: the write of `x` into `self.buf` starting at byte offset . // `self.nbuf` must cause `self.buf` to become fully initialized (and not . // overflow) if it wasn't already. . #[inline(never)] 18,668 ( 0.00%) unsafe fn short_write_process_buffer(&mut self, x: T) { . let size = mem::size_of::(); 18,668 ( 0.00%) let nbuf = self.nbuf; . debug_assert!(size <= 8); . debug_assert!(nbuf < BUFFER_SIZE); . debug_assert!(nbuf + size >= BUFFER_SIZE); . debug_assert!(nbuf + size < BUFFER_WITH_SPILL_SIZE); . . // Copy first part of input into end of buffer, possibly into spill . // element. The memcpy call is optimized away because the size is known. . let dst = (self.buf.as_mut_ptr() as *mut u8).add(nbuf); . ptr::copy_nonoverlapping(&x as *const _ as *const u8, dst, size); . . // Process buffer. . for i in 0..BUFFER_CAPACITY { 186,680 ( 0.02%) let elem = self.buf.get_unchecked(i).assume_init().to_le(); 149,344 ( 0.01%) self.state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut self.state); 168,012 ( 0.01%) self.state.v0 ^= elem; . } . . // Copy remaining input into start of buffer by copying size - 1 . // elements from spill (at most size - 1 bytes could have overflowed . // into the spill). The memcpy call is optimized away because the size . // is known. And the whole copy is optimized away for size == 1. . let src = self.buf.get_unchecked(BUFFER_SPILL_INDEX) as *const _ as *const u8; . ptr::copy_nonoverlapping(src, self.buf.as_mut_ptr() as *mut u8, size - 1); . . // This function should only be called when the write fills the buffer. . // Therefore, when size == 1, the new `self.nbuf` must be zero. The size . // is statically known, so the branch is optimized away. 88,884 ( 0.01%) self.nbuf = if size == 1 { 0 } else { nbuf + size - BUFFER_SIZE }; 74,672 ( 0.01%) self.processed += BUFFER_SIZE; 37,336 ( 0.00%) } . . // A write function for byte slices. . #[inline] . fn slice_write(&mut self, msg: &[u8]) { . let length = msg.len(); 6,885 ( 0.00%) let nbuf = self.nbuf; . debug_assert!(nbuf < BUFFER_SIZE); . 70,668 ( 0.01%) if nbuf + length < BUFFER_SIZE { . unsafe { . let dst = (self.buf.as_mut_ptr() as *mut u8).add(nbuf); . 25,992 ( 0.00%) if length <= 8 { . copy_nonoverlapping_small(msg.as_ptr(), dst, length); . } else { . // This memcpy is *not* optimized away. . ptr::copy_nonoverlapping(msg.as_ptr(), dst, length); . } . } . 13,055 ( 0.00%) self.nbuf = nbuf + length; . . return; . } . 7,030 ( 0.00%) unsafe { self.slice_write_process_buffer(msg) } . } . . // A write function for byte slices that should only be called when the . // write would cause the buffer to fill. . // . // SAFETY: `self.buf` must be initialized up to the byte offset `self.nbuf`, . // and `msg` must contain enough bytes to initialize the rest of the element . // containing the byte offset `self.nbuf`. . #[inline(never)] 5,310 ( 0.00%) unsafe fn slice_write_process_buffer(&mut self, msg: &[u8]) { . let length = msg.len(); 1,062 ( 0.00%) let nbuf = self.nbuf; . debug_assert!(nbuf < BUFFER_SIZE); . debug_assert!(nbuf + length >= BUFFER_SIZE); . . // Always copy first part of input into current element of buffer. . // This function should only be called when the write fills the buffer, . // so we know that there is enough input to fill the current element. 3,186 ( 0.00%) let valid_in_elem = nbuf % ELEM_SIZE; 1,062 ( 0.00%) let needed_in_elem = ELEM_SIZE - valid_in_elem; . . let src = msg.as_ptr(); . let dst = (self.buf.as_mut_ptr() as *mut u8).add(nbuf); . copy_nonoverlapping_small(src, dst, needed_in_elem); . . // Process buffer. . . // Using `nbuf / ELEM_SIZE + 1` rather than `(nbuf + needed_in_elem) / . // ELEM_SIZE` to show the compiler that this loop's upper bound is > 0. . // We know that is true, because last step ensured we have a full . // element in the buffer. 2,124 ( 0.00%) let last = nbuf / ELEM_SIZE + 1; . . for i in 0..last { 8,056 ( 0.00%) let elem = self.buf.get_unchecked(i).assume_init().to_le(); 9,118 ( 0.00%) self.state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut self.state); 16,112 ( 0.00%) self.state.v0 ^= elem; . } . . // Process the remaining element-sized chunks of input. . let mut processed = needed_in_elem; 2,124 ( 0.00%) let input_left = length - processed; 852 ( 0.00%) let elems_left = input_left / ELEM_SIZE; . let extra_bytes_left = input_left % ELEM_SIZE; . . for _ in 0..elems_left { 1,712 ( 0.00%) let elem = (msg.as_ptr().add(processed) as *const u64).read_unaligned().to_le(); 1,712 ( 0.00%) self.state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut self.state); 1,712 ( 0.00%) self.state.v0 ^= elem; 3,424 ( 0.00%) processed += ELEM_SIZE; . } . . // Copy remaining input into start of buffer. . let src = msg.as_ptr().add(processed); . let dst = self.buf.as_mut_ptr() as *mut u8; . copy_nonoverlapping_small(src, dst, extra_bytes_left); . 1,062 ( 0.00%) self.nbuf = extra_bytes_left; 5,310 ( 0.00%) self.processed += nbuf + processed; 6,372 ( 0.00%) } . . #[inline] . pub fn finish128(mut self) -> (u64, u64) { . debug_assert!(self.nbuf < BUFFER_SIZE); . . // Process full elements in buffer. 12,489 ( 0.00%) let last = self.nbuf / ELEM_SIZE; . . // Since we're consuming self, avoid updating members for a potential . // performance gain. 16,652 ( 0.00%) let mut state = self.state; . . for i in 0..last { 14,333 ( 0.00%) let elem = unsafe { self.buf.get_unchecked(i).assume_init().to_le() }; 14,333 ( 0.00%) state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut state); 14,333 ( 0.00%) state.v0 ^= elem; . } . . // Get remaining partial element. 8,326 ( 0.00%) let elem = if self.nbuf % ELEM_SIZE != 0 { . unsafe { . // Ensure element is initialized by writing zero bytes. At most . // `ELEM_SIZE - 1` are required given the above check. It's safe . // to write this many because we have the spill and we maintain . // `self.nbuf` such that this write will start before the spill. . let dst = (self.buf.as_mut_ptr() as *mut u8).add(self.nbuf); . ptr::write_bytes(dst, 0, ELEM_SIZE - 1); 2,998 ( 0.00%) self.buf.get_unchecked(last).assume_init().to_le() . } . } else { . 0 . }; . . // Finalize the hash. 11,324 ( 0.00%) let length = self.processed + self.nbuf; 8,324 ( 0.00%) let b: u64 = ((length as u64 & 0xff) << 56) | elem; . 4,162 ( 0.00%) state.v3 ^= b; . Sip24Rounds::c_rounds(&mut state); 4,162 ( 0.00%) state.v0 ^= b; . 4,162 ( 0.00%) state.v2 ^= 0xee; . Sip24Rounds::d_rounds(&mut state); 10,710 ( 0.00%) let _0 = state.v0 ^ state.v1 ^ state.v2 ^ state.v3; . 2,384 ( 0.00%) state.v1 ^= 0xdd; . Sip24Rounds::d_rounds(&mut state); 2,384 ( 0.00%) let _1 = state.v0 ^ state.v1 ^ state.v2 ^ state.v3; . . (_0, _1) . } . } . . impl Hasher for SipHasher128 { . #[inline] . fn write_u8(&mut self, i: u8) { -- line 414 ---------------------------------------- -- line 471 ---------------------------------------- . } . . #[derive(Debug, Clone, Default)] . struct Sip24Rounds; . . impl Sip24Rounds { . #[inline] . fn c_rounds(state: &mut State) { 732,282 ( 0.06%) compress!(state); 790,600 ( 0.07%) compress!(state); . } . . #[inline] . fn d_rounds(state: &mut State) { 21,416 ( 0.00%) compress!(state); 21,416 ( 0.00%) compress!(state); 21,416 ( 0.00%) compress!(state); 17,255 ( 0.00%) compress!(state); . } . } 126,916 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs -------------------------------------------------------------------------------- Ir -- line 111 ---------------------------------------- . const EMPTY: u8 = 0b1111_1111; . . /// Control byte value for a deleted bucket. . const DELETED: u8 = 0b1000_0000; . . /// Checks whether a control byte represents a full bucket (top bit is clear). . #[inline] . fn is_full(ctrl: u8) -> bool { 630,165 ( 0.06%) ctrl & 0x80 == 0 . } . . /// Checks whether a control byte represents a special value (top bit is set). . #[inline] . fn is_special(ctrl: u8) -> bool { . ctrl & 0x80 != 0 . } . . /// Checks whether a special control value is EMPTY (just check 1 bit). . #[inline] . fn special_is_empty(ctrl: u8) -> bool { . debug_assert!(is_special(ctrl)); 50,012 ( 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::()); 7,807,682 ( 0.69%) 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" . ); . 72,140 ( 0.01%) self.stride += Group::WIDTH; 72,140 ( 0.01%) self.pos += self.stride; 61,431 ( 0.01%) self.pos &= bucket_mask; . } . } . . /// Returns the number of buckets needed to hold the given number of items, . /// taking the maximum load factor into account. . /// . /// Returns `None` if an overflow occurs. . // Workaround for emscripten bug emscripten-core/emscripten-fastcomp#258 . #[cfg_attr(target_os = "emscripten", inline(never))] . #[cfg_attr(not(target_os = "emscripten"), inline)] . 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. 36,294 ( 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. 76,995 ( 0.01%) return Some(if cap < 4 { 4 } else { 8 }); . } . . // Otherwise require 1/8 buckets to be empty (87.5% load) . // . // Be careful when modifying this, calculate_layout relies on the . // overflow check here. 16,488 ( 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 { 91,883 ( 0.01%) if bucket_mask < 8 { . // For tables with 1/2/4/8 buckets, we always reserve one empty slot. . // Keep in mind that the bucket mask is one less than the bucket count. . bucket_mask . } else { . // For larger tables we reserve 12.5% of the slots as empty. 24,364 ( 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 = 78,543 ( 0.01%) size.checked_mul(buckets)?.checked_add(ctrl_align - 1)? & !(ctrl_align - 1); 101,417 ( 0.01%) let len = ctrl_offset.checked_add(buckets + Group::WIDTH)?; . . Some(( . unsafe { Layout::from_size_align_unchecked(len, ctrl_align) }, . ctrl_offset, . )) . } . } . -- line 263 ---------------------------------------- -- line 337 ---------------------------------------- . } . } . #[cfg_attr(feature = "inline-more", inline)] . pub unsafe fn drop(&self) { . self.as_ptr().drop_in_place(); . } . #[inline] . pub unsafe fn read(&self) -> T { 382 ( 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 { 30,072 ( 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 { 50 ( 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 { 4,683 ( 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")] 3,990 ( 0.00%) pub unsafe fn erase_no_drop(&mut self, item: &Bucket) { 3,990 ( 0.00%) let index = self.bucket_index(item); . self.table.erase(index); 7,980 ( 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. 2,162 ( 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 { 5,818 ( 0.00%) self.erase_no_drop(&item); 40 ( 0.00%) item.read() . } . . /// Finds and removes an element from the table, returning it. . #[cfg_attr(feature = "inline-more", inline)] 191,603 ( 0.02%) pub fn remove_entry(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option { . // Avoid `Option::map` because it bloats LLVM IR. 92 ( 0.00%) match self.find(hash, eq) { 1,725 ( 0.00%) Some(bucket) => Some(unsafe { self.remove(bucket) }), 33,577 ( 0.00%) None => None, . } 288,389 ( 0.03%) } . . /// 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) { 6,248 ( 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) { 117,853 ( 0.01%) if additional > self.table.growth_left { . // Avoid `Result::unwrap_or_else` because it bloats LLVM IR. 62,898 ( 0.01%) 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)] 141,263 ( 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 . }, . ) . } 96,840 ( 0.01%) } . . /// Allocates a new table of a different size and moves the contents of the . /// current table into it. . fn resize( . &mut self, . capacity: usize, . hasher: impl Fn(&T) -> u64, . fallibility: Fallibility, -- line 706 ---------------------------------------- -- line 714 ---------------------------------------- . ) . } . } . . /// Inserts a new element into the table, and returns its raw bucket. . /// . /// This does not check if the given element already exists in the table. . #[cfg_attr(feature = "inline-more", inline)] 874,312 ( 0.08%) 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. 1,344 ( 0.00%) let old_ctrl = *self.table.ctrl(index); 564,122 ( 0.05%) if unlikely(self.table.growth_left == 0 && special_is_empty(old_ctrl)) { . self.reserve(1, hasher); . index = self.table.find_insert_slot(hash); . } . . self.table.record_item_insert_at(index, old_ctrl, hash); . . let bucket = self.bucket(index); 2 ( 0.00%) bucket.write(value); . bucket . } 644,785 ( 0.06%) } . . /// 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)] 215,880 ( 0.02%) pub fn insert_entry(&mut self, hash: u64, value: T, hasher: impl Fn(&T) -> u64) -> &mut T { 40 ( 0.00%) unsafe { self.insert(hash, value, hasher).as_mut() } 161,910 ( 0.01%) } . . /// Inserts a new element into the table, without growing the table. . /// . /// There must be enough space in the table to insert the new element. . /// . /// This does not check if the given element already exists in the table. . #[cfg_attr(feature = "inline-more", inline)] . #[cfg(any(feature = "raw", feature = "rustc-internal-api"))] 2,240 ( 0.00%) pub unsafe fn insert_no_grow(&mut self, hash: u64, value: T) -> Bucket { 139,031 ( 0.01%) let (index, old_ctrl) = self.table.prepare_insert_slot(hash); 6,030 ( 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. 289,712 ( 0.03%) self.table.growth_left -= special_is_empty(old_ctrl) as usize; . . bucket.write(value); 240,214 ( 0.02%) self.table.items += 1; . bucket 4,444 ( 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] 728 ( 0.00%) pub fn find(&self, hash: u64, mut eq: impl FnMut(&T) -> bool) -> Option> { 786 ( 0.00%) let result = self.table.find_inner(hash, &mut |index| unsafe { 7,762 ( 0.00%) eq(self.bucket(index).as_ref()) 180 ( 0.00%) }); . . // Avoid `Option::map` because it bloats LLVM IR. . match result { 59 ( 0.00%) Some(index) => Some(unsafe { self.bucket(index) }), . None => None, . } 728 ( 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. 232,253 ( 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] . pub fn get_mut(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option<&mut T> { . // Avoid `Option::map` because it bloats LLVM IR. 504 ( 0.00%) match self.find(hash, eq) { . Some(bucket) => Some(unsafe { bucket.as_mut() }), . None => None, . } . } . . /// Attempts to get mutable references to `N` entries in the table at once. . /// . /// Returns an array of length `N` with the results of each query. -- line 855 ---------------------------------------- -- line 920 ---------------------------------------- . #[inline] . pub fn len(&self) -> usize { . self.table.items . } . . /// Returns `true` if the table contains no elements. . #[inline] . pub fn is_empty(&self) -> bool { 345,889 ( 0.03%) self.len() == 0 . } . . /// Returns the number of buckets in the table. . #[inline] . pub fn buckets(&self) -> usize { . self.table.bucket_mask + 1 . } . -- line 936 ---------------------------------------- -- line 938 ---------------------------------------- . /// 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 { . let data = Bucket::from_base_index(self.data_end(), 0); . RawIter { . iter: RawIterRange::new(self.table.ctrl.as_ptr(), data, self.table.buckets()), 27,035 ( 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(); 2,304 ( 0.00%) let allocation = self.into_allocation(); 1,728 ( 0.00%) RawIntoIter { 2,880 ( 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)> { 1,007 ( 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(( 236 ( 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 { 199,779 ( 0.02%) 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)] 131,281 ( 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()); . } . 32,256 ( 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)); 77,502 ( 0.01%) Ok(Self { . ctrl, 31,074 ( 0.00%) bucket_mask: buckets - 1, . items: 0, . growth_left: bucket_mask_to_capacity(buckets - 1), . alloc, . }) 96,132 ( 0.01%) } . . #[inline] 13,385 ( 0.00%) fn fallible_with_capacity( . alloc: A, . table_layout: TableLayout, . capacity: usize, . fallibility: Fallibility, . ) -> Result { 3,434 ( 0.00%) if capacity == 0 { 2,043 ( 0.00%) Ok(Self::new_in(alloc)) . } else { . unsafe { . let buckets = . capacity_to_buckets(capacity).ok_or_else(|| fallibility.capacity_overflow())?; . 60,855 ( 0.01%) let result = Self::new_uninitialized(alloc, table_layout, buckets, fallibility)?; . result.ctrl(0).write_bytes(EMPTY, result.num_ctrl_bytes()); . 7,710 ( 0.00%) Ok(result) . } . } 13,385 ( 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] 47,799 ( 0.00%) unsafe fn prepare_insert_slot(&self, hash: u64) -> (usize, u8) { . let index = self.find_insert_slot(hash); 47,799 ( 0.00%) let old_ctrl = *self.ctrl(index); . self.set_ctrl_h2(index, hash); . (index, old_ctrl) 95,598 ( 0.01%) } . . /// Searches for an empty or deleted bucket which is suitable for inserting . /// a new element. . /// . /// There must be at least 1 empty bucket in the table. . #[inline] . 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)); 405,922 ( 0.04%) if let Some(bit) = group.match_empty_or_deleted().lowest_set_bit() { 1,188,896 ( 0.11%) 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). 536,542 ( 0.05%) if unlikely(is_full(*self.ctrl(result))) { . debug_assert!(self.bucket_mask < Group::WIDTH); . debug_assert_ne!(probe_seq.pos, 0); . return Group::load_aligned(self.ctrl(0)) . .match_empty_or_deleted() . .lowest_set_bit_nonzero(); . } . . return result; -- line 1165 ---------------------------------------- -- line 1171 ---------------------------------------- . . /// Searches for an element in the table. This uses dynamic dispatch to reduce the amount of . /// code generated, but it is eliminated by LLVM optimizations. . #[inline] . fn find_inner(&self, hash: u64, eq: &mut dyn FnMut(usize) -> bool) -> Option { . let h2_hash = h2(hash); . let mut probe_seq = self.probe_seq(hash); . 11,136 ( 0.00%) loop { . let group = unsafe { Group::load(self.ctrl(probe_seq.pos)) }; . 1,023,190 ( 0.09%) for bit in group.match_byte(h2_hash) { 1,894,010 ( 0.17%) let index = (probe_seq.pos + bit) & self.bucket_mask; . 1,379,271 ( 0.12%) if likely(eq(index)) { . return Some(index); . } . } . 352,696 ( 0.03%) if likely(group.match_empty().any_bit_set()) { . return None; . } . . probe_seq.move_next(self.bucket_mask); . } . } . . #[allow(clippy::mut_mut)] -- line 1198 ---------------------------------------- -- line 1225 ---------------------------------------- . Bucket::from_base_index(self.data_end(), index) . } . . #[inline] . unsafe fn bucket_ptr(&self, index: usize, size_of: usize) -> *mut u8 { . debug_assert_ne!(self.bucket_mask, 0); . debug_assert!(index < self.buckets()); . let base: *mut u8 = self.data_end().as_ptr(); 1,547,216 ( 0.14%) base.sub((index + 1) * size_of) . } . . #[inline] . unsafe fn data_end(&self) -> NonNull { . NonNull::new_unchecked(self.ctrl.as_ptr().cast()) . } . . /// Returns an iterator-like object for a probe sequence on the table. . /// . /// This iterator never terminates, but is guaranteed to visit each bucket . /// group exactly once. The loop using `probe_seq` must terminate upon . /// reaching a group containing an empty bucket. . #[inline] . fn probe_seq(&self, hash: u64) -> ProbeSeq { . ProbeSeq { 6,447,052 ( 0.57%) 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) { 705,005 ( 0.06%) self.growth_left -= special_is_empty(old_ctrl) as usize; . self.set_ctrl_h2(index, hash); 564,004 ( 0.05%) self.items += 1; . } . . #[inline] . fn is_in_same_group(&self, i: usize, new_i: usize, hash: u64) -> bool { . let probe_seq_pos = self.probe_seq(hash).pos; . let probe_index = . |pos: usize| (pos.wrapping_sub(probe_seq_pos) & self.bucket_mask) / Group::WIDTH; . probe_index(i) == probe_index(new_i) -- line 1281 ---------------------------------------- -- line 1312 ---------------------------------------- . // replicate the buckets at the end of the trailing group. For example . // with 2 buckets and a group size of 4, the control bytes will look . // like this: . // . // Real | Replicated . // --------------------------------------------- . // | [A] | [B] | [EMPTY] | [EMPTY] | [A] | [B] | . // --------------------------------------------- 1,153,245 ( 0.10%) let index2 = ((index.wrapping_sub(Group::WIDTH)) & self.bucket_mask) + Group::WIDTH; . 384,415 ( 0.03%) *self.ctrl(index) = ctrl; 384,640 ( 0.03%) *self.ctrl(index2) = ctrl; . } . . /// Returns a pointer to a control byte. . #[inline] . unsafe fn ctrl(&self, index: usize) -> *mut u8 { . debug_assert!(index < self.num_ctrl_bytes()); . self.ctrl.as_ptr().add(index) . } . . #[inline] . fn buckets(&self) -> usize { 88,395 ( 0.01%) self.bucket_mask + 1 . } . . #[inline] . fn num_ctrl_bytes(&self) -> usize { 78,335 ( 0.01%) self.bucket_mask + 1 + Group::WIDTH . } . . #[inline] . fn is_empty_singleton(&self) -> bool { 400,883 ( 0.04%) 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. 1,551 ( 0.00%) let mut new_table = RawTableInner::fallible_with_capacity( . self.alloc.clone(), . table_layout, . capacity, . fallibility, . )?; 39,967 ( 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_| { 17,379 ( 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. 34,761 ( 0.00%) let new_items = match self.items.checked_add(additional) { . Some(new_items) => new_items, . None => return Err(fallibility.capacity_overflow()), . }; 34,758 ( 0.00%) let full_capacity = bucket_mask_to_capacity(self.bucket_mask); 73,314 ( 0.01%) if new_items <= full_capacity / 2 { . // Rehash in-place without re-allocating if we have plenty of spare . // capacity that is locked up due to DELETED entries. . self.rehash_in_place(hasher, layout.size, drop); . Ok(()) . } else { . // Otherwise, conservatively resize to at least the next size up . // to avoid churning deletes into frequent rehashes. . self.resize_inner( 17,379 ( 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> { 3,732 ( 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() { 234,624 ( 0.02%) if !is_full(*self.ctrl(i)) { . continue; . } . . // This may panic. . let hash = hasher(self, i); . . // We can use a simpler version of insert() here since: . // - there are no DELETED entries. -- line 1444 ---------------------------------------- -- line 1454 ---------------------------------------- . } . . // We successfully copied all elements without panicking. Now replace . // self with the new table. The old table will have its memory freed but . // the items will not be dropped (since they have been moved into the . // new table). . mem::swap(self, &mut new_table); . 17,379 ( 0.00%) Ok(()) . } . . /// Rehashes the contents of the table in place (i.e. without changing the . /// allocation). . /// . /// If `hasher` panics then some the table's contents may be lost. . /// . /// This uses dynamic dispatch to reduce the amount of -- line 1470 ---------------------------------------- -- line 1554 ---------------------------------------- . #[inline] . unsafe fn free_buckets(&mut self, table_layout: TableLayout) { . // Avoid `Option::unwrap_or_else` because it bloats LLVM IR. . let (layout, ctrl_offset) = match table_layout.calculate_layout_for(self.buckets()) { . Some(lco) => lco, . None => hint::unreachable_unchecked(), . }; . self.alloc.deallocate( 11,715 ( 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) { 3,457 ( 0.00%) if !self.is_empty_singleton() { . unsafe { . self.ctrl(0).write_bytes(EMPTY, self.num_ctrl_bytes()); . } . } 4,898 ( 0.00%) self.items = 0; 3,457 ( 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))); 40,055 ( 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. 160,220 ( 0.01%) let ctrl = if empty_before.leading_zeros() + empty_after.trailing_zeros() >= Group::WIDTH { . DELETED . } else { 199,680 ( 0.02%) self.growth_left += 1; . EMPTY . }; . self.set_ctrl(index, ctrl); 160,220 ( 0.01%) self.items -= 1; . } . } . . impl Clone for RawTable { 80,208 ( 0.01%) fn clone(&self) -> Self { 10,044 ( 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) . } . } 90,234 ( 0.01%) } . . 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; 20 ( 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)] 352,304 ( 0.03%) fn drop(&mut self) { 166,116 ( 0.01%) if !self.table.is_empty_singleton() { . unsafe { . self.drop_elements(); . self.free_buckets(); . } . } 380,068 ( 0.03%) } . } . #[cfg(not(feature = "nightly"))] . impl Drop for RawTable { . #[cfg_attr(feature = "inline-more", inline)] . fn drop(&mut self) { . if !self.table.is_empty_singleton() { . unsafe { . self.drop_elements(); -- line 1813 ---------------------------------------- -- line 1817 ---------------------------------------- . } . } . . impl IntoIterator for RawTable { . type Item = T; . type IntoIter = RawIntoIter; . . #[cfg_attr(feature = "inline-more", inline)] 2,304 ( 0.00%) fn into_iter(self) -> RawIntoIter { . unsafe { . let iter = self.iter(); . self.into_iter_from(iter) . } 2,880 ( 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 { 62,129 ( 0.01%) if let Some(index) = self.current_group.lowest_set_bit() { 9,581 ( 0.00%) self.current_group = self.current_group.remove_lowest_bit(); 16,419 ( 0.00%) return Some(self.data.next_n(index)); . } . 61,565 ( 0.01%) 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). 2,133 ( 0.00%) self.current_group = Group::load_aligned(self.next_ctrl).match_full(); 1,296 ( 0.00%) self.data = self.data.next_n(Group::WIDTH); 2,800 ( 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) { 3,557 ( 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)] 11,410 ( 0.00%) fn next(&mut self) -> Option> { 23,756 ( 0.00%) if let Some(b) = self.iter.next() { 75,683 ( 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 . } 22,820 ( 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)] 910 ( 0.00%) fn drop(&mut self) { . unsafe { . // Drop all remaining elements . self.iter.drop_elements(); . . // Free the table 4,809 ( 0.00%) if let Some((ptr, layout)) = self.allocation { . self.alloc.deallocate(ptr, layout); . } . } 198 ( 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)] 2,355 ( 0.00%) fn next(&mut self) -> Option { 3,288 ( 0.00%) unsafe { Some(self.iter.next()?.read()) } 4,710 ( 0.00%) } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 88 ( 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)] 8,392 ( 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. 1,049 ( 0.00%) self.orig_table . .as_ptr() . .copy_from_nonoverlapping(&*self.table, 1); . } 8,392 ( 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 ---------------------------------------- 3,247,133 ( 0.29%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/std/src/thread/local.rs -------------------------------------------------------------------------------- Ir -- line 173 ---------------------------------------- . #[unstable(feature = "thread_local_internals", reason = "should not be necessary", issue = "none")] . #[macro_export] . #[allow_internal_unstable(thread_local_internals, cfg_target_thread_local, thread_local)] . #[allow_internal_unsafe] . macro_rules! __thread_local_inner { . // used to generate the `LocalKey` value for const-initialized thread locals . (@key $t:ty, const $init:expr) => {{ . #[cfg_attr(not(windows), inline)] // see comments below 4 ( 0.00%) unsafe fn __getit() -> $crate::option::Option<&'static $t> { . const INIT_EXPR: $t = $init; . . // wasm without atomics maps directly to `static mut`, and dtors . // aren't implemented because thread dtors aren't really a thing . // on wasm right now . // . // FIXME(#84224) this should come after the `target_thread_local` . // block. -- line 189 ---------------------------------------- -- line 211 ---------------------------------------- . } . . // 0 == dtor not registered . // 1 == dtor registered, dtor not run . // 2 == dtor registered and is running or has run . #[thread_local] . static mut STATE: u8 = 0; . 8 ( 0.00%) unsafe extern "C" fn destroy(ptr: *mut u8) { . let ptr = ptr as *mut $t; . . unsafe { . debug_assert_eq!(STATE, 1); 12 ( 0.00%) STATE = 2; . $crate::ptr::drop_in_place(ptr); . } 8 ( 0.00%) } . . unsafe { 60 ( 0.00%) match STATE { . // 0 == we haven't registered a destructor, so do . // so now. . 0 => { . $crate::thread::__FastLocalKeyInner::<$t>::register_dtor( . $crate::ptr::addr_of_mut!(VAL) as *mut u8, . destroy, . ); 8 ( 0.00%) STATE = 1; . Some(&VAL) . } . // 1 == the destructor is registered and the value . // is valid, so return the pointer. . 1 => Some(&VAL), . // otherwise the destructor has already run, so we . // can't give access. . _ => None, -- line 246 ---------------------------------------- -- line 257 ---------------------------------------- . { . #[inline] . const fn __init() -> $t { INIT_EXPR } . static __KEY: $crate::thread::__OsLocalKeyInner<$t> = . $crate::thread::__OsLocalKeyInner::new(); . #[allow(unused_unsafe)] . unsafe { __KEY.get(__init) } . } 97,520 ( 0.01%) } . . unsafe { . $crate::thread::LocalKey::new(__getit) . } . }}; . . // used to generate the `LocalKey` value for `thread_local!` . (@key $t:ty, $init:expr) => { -- line 273 ---------------------------------------- -- line 318 ---------------------------------------- . static __KEY: $crate::thread::__OsLocalKeyInner<$t> = . $crate::thread::__OsLocalKeyInner::new(); . . // FIXME: remove the #[allow(...)] marker when macros don't . // raise warning for missing/extraneous unsafe blocks anymore. . // See https://github.com/rust-lang/rust/issues/74838. . #[allow(unused_unsafe)] . unsafe { __KEY.get(__init) } 1,083,476 ( 0.10%) } . . unsafe { . $crate::thread::LocalKey::new(__getit) . } . } . }; . ($(#[$attr:meta])* $vis:vis $name:ident, $t:ty, $($init:tt)*) => { . $(#[$attr])* $vis const $name: $crate::thread::LocalKey<$t> = -- line 334 ---------------------------------------- -- line 377 ---------------------------------------- . /// this key yet. . /// . /// # Panics . /// . /// This function will `panic!()` if the key currently has its . /// destructor running, and it **may** panic if the destructor has . /// previously been run for this thread. . #[stable(feature = "rust1", since = "1.0.0")] 12 ( 0.00%) pub fn with(&'static self, f: F) -> R . where . F: FnOnce(&T) -> R, . { 17 ( 0.00%) self.try_with(f).expect( . "cannot access a Thread Local Storage value \ . during or after destruction", . ) 16 ( 0.00%) } . . /// Acquires a reference to the value in this TLS key. . /// . /// This will lazily initialize the value if this thread has not referenced . /// this key yet. If the key has been destroyed (which may happen if this is called . /// in a destructor), this function will return an [`AccessError`]. . /// . /// # Panics -- line 401 ---------------------------------------- -- line 404 ---------------------------------------- . /// key's initializer panics. . #[stable(feature = "thread_local_try_with", since = "1.26.0")] . #[inline] . pub fn try_with(&'static self, f: F) -> Result . where . F: FnOnce(&T) -> R, . { . unsafe { 845,313 ( 0.08%) let thread_local = (self.inner)().ok_or(AccessError)?; 427,896 ( 0.04%) Ok(f(thread_local)) . } . } . } . . mod lazy { . use crate::cell::UnsafeCell; . use crate::hint; . use crate::mem; -- line 421 ---------------------------------------- -- line 434 ---------------------------------------- . // the inner cell nor mutable reference to the Option inside said . // cell. This make it safe to hand a reference, though the lifetime . // of 'static is itself unsafe, making the get method unsafe. . unsafe { (*self.inner.get()).as_ref() } . } . . /// The caller must ensure that no reference is active: this method . /// needs unique access. 9 ( 0.00%) pub unsafe fn initialize T>(&self, init: F) -> &'static T { . // Execute the initialization up front, *then* move it into our slot, . // just in case initialization fails. . let value = init(); . let ptr = self.inner.get(); . . // SAFETY: . // . // note that this can in theory just be `*ptr = Some(value)`, but due to -- line 450 ---------------------------------------- -- line 475 ---------------------------------------- . // always work it empirically doesn't seem to always get optimized away, . // which means that using something like `try_with` can pull in . // panicking code and cause a large size bloat. . match *ptr { . Some(ref x) => x, . None => hint::unreachable_unchecked(), . } . } 10 ( 0.00%) } . . /// The other methods hand out references while taking &self. . /// As such, callers of this method must ensure no `&` and `&mut` are . /// available and used at the same time. . #[allow(unused)] . pub unsafe fn take(&mut self) -> Option { . // SAFETY: See doc comment for this method. . unsafe { (*self.inner.get()).take() } -- line 491 ---------------------------------------- -- line 596 ---------------------------------------- . // SAFETY: See the definitions of `LazyKeyInner::get` and . // `try_initialize` for more information. . // . // The caller must ensure no mutable references are ever active to . // the inner cell or the inner T when this is called. . // The `try_initialize` is dependant on the passed `init` function . // for this. . unsafe { 330,441 ( 0.03%) match self.inner.get() { . Some(val) => Some(val), 18 ( 0.00%) None => self.try_initialize(init), . } . } . } . . // `try_initialize` is only called once per fast thread local variable, . // except in corner cases where thread_local dtors reference other . // thread_local's, or it is being recursively initialized. . // . // Macos: Inlining this function can cause two `tlv_get_addr` calls to . // be performed for every call to `Key::get`. . // LLVM issue: https://bugs.llvm.org/show_bug.cgi?id=41722 . #[inline(never)] 8 ( 0.00%) unsafe fn try_initialize T>(&self, init: F) -> Option<&'static T> { . // SAFETY: See comment above (this function doc). . if !mem::needs_drop::() || unsafe { self.try_register_dtor() } { . // SAFETY: See comment above (his function doc). 6 ( 0.00%) Some(unsafe { self.inner.initialize(init) }) . } else { . None . } 8 ( 0.00%) } . . // `try_register_dtor` is only called once per fast thread local . // variable, except in corner cases where thread_local dtors reference . // other thread_local's, or it is being recursively initialized. . unsafe fn try_register_dtor(&self) -> bool { 6 ( 0.00%) match self.dtor_state.get() { . DtorState::Unregistered => { . // SAFETY: dtor registration happens before initialization. . // Passing `self` as a pointer while using `destroy_value` . // is safe because the function will build a pointer to a . // Key, which is the type of self and so find the correct . // size. 6 ( 0.00%) unsafe { register_dtor(self as *const _ as *mut u8, destroy_value::) }; . self.dtor_state.set(DtorState::Registered); . true . } . DtorState::Registered => { . // recursively initialized . true . } . DtorState::RunningOrHasRun => false, . } . } . } . 4 ( 0.00%) unsafe extern "C" fn destroy_value(ptr: *mut u8) { . let ptr = ptr as *mut Key; . . // SAFETY: . // . // The pointer `ptr` has been built just above and comes from . // `try_register_dtor` where it is originally a Key coming from `self`, . // making it non-NUL and of the correct type. . // -- line 661 ---------------------------------------- 4 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_resolve/src/lib.rs -------------------------------------------------------------------------------- Ir -- line 91 ---------------------------------------- . mod late; . mod macros; . . enum Weak { . Yes, . No, . } . 1,041 ( 0.00%) #[derive(Copy, Clone, PartialEq, Debug)] . pub enum Determinacy { . Determined, . Undetermined, . } . . impl Determinacy { . fn determined(determined: bool) -> Determinacy { . if determined { Determinacy::Determined } else { Determinacy::Undetermined } 694 ( 0.00%) } . } . . /// A specific scope in which a name can be looked up. . /// This enum is currently used only for early resolution (imports and macros), . /// but not for late resolution yet. . #[derive(Clone, Copy)] . enum Scope<'a> { . DeriveHelpers(LocalExpnId), -- line 116 ---------------------------------------- -- line 157 ---------------------------------------- . macro_rules: MacroRulesScopeRef<'a>, . derives: &'a [ast::Path], . } . . impl<'a> ParentScope<'a> { . /// Creates a parent scope with the passed argument used as the module scope component, . /// and other scope components set to default empty values. . pub fn module(module: Module<'a>, resolver: &Resolver<'a>) -> ParentScope<'a> { 8 ( 0.00%) ParentScope { . module, . expansion: LocalExpnId::ROOT, 1,111 ( 0.00%) macro_rules: resolver.arenas.alloc_macro_rules_scope(MacroRulesScope::Empty), . derives: &[], . } . } . } . . #[derive(Copy, Debug, Clone)] . enum ImplTraitContext { . Existential, -- line 176 ---------------------------------------- -- line 278 ---------------------------------------- . FailedToResolve(Span, String, Option), . ExpectedFound(Span, String, Res), . Indeterminate(Span), . ModuleOnly(Span), . } . . /// A minimal representation of a path segment. We use this in resolve because we synthesize 'path . /// segments' which don't have the rest of an AST or HIR `PathSegment`. 30 ( 0.00%) #[derive(Clone, Copy, Debug)] . pub struct Segment { . ident: Ident, . id: Option, . /// Signals whether this `PathSegment` has generic arguments. Used to avoid providing . /// nonsensical suggestions. . has_generic_args: bool, . } . -- line 294 ---------------------------------------- -- line 303 ---------------------------------------- . . fn names_to_string(segments: &[Segment]) -> String { . names_to_string(&segments.iter().map(|seg| seg.ident.name).collect::>()) . } . } . . impl<'a> From<&'a ast::PathSegment> for Segment { . fn from(seg: &'a ast::PathSegment) -> Segment { 90 ( 0.00%) Segment { ident: seg.ident, id: Some(seg.id), has_generic_args: seg.args.is_some() } . } . } . . struct UsePlacementFinder { . target_module: NodeId, . span: Option, . found_use: bool, . } -- line 319 ---------------------------------------- -- line 391 ---------------------------------------- . #[derive(Debug)] . enum LexicalScopeBinding<'a> { . Item(&'a NameBinding<'a>), . Res(Res), . } . . impl<'a> LexicalScopeBinding<'a> { . fn res(self) -> Res { 332 ( 0.00%) match self { . LexicalScopeBinding::Item(binding) => binding.res(), 498 ( 0.00%) LexicalScopeBinding::Res(res) => res, . } . } . } . . #[derive(Copy, Clone, Debug)] . enum ModuleOrUniformRoot<'a> { . /// Regular module. . Module(Module<'a>), -- line 409 ---------------------------------------- -- line 418 ---------------------------------------- . /// Virtual module that denotes resolution in current scope. . /// Used only for resolving single-segment imports. The reason it exists is that import paths . /// are always split into two parts, the first of which should be some kind of module. . CurrentScope, . } . . impl ModuleOrUniformRoot<'_> { . fn same_def(lhs: Self, rhs: Self) -> bool { 84 ( 0.00%) match (lhs, rhs) { . (ModuleOrUniformRoot::Module(lhs), ModuleOrUniformRoot::Module(rhs)) => { . ptr::eq(lhs, rhs) . } . ( . ModuleOrUniformRoot::CrateRootAndExternPrelude, . ModuleOrUniformRoot::CrateRootAndExternPrelude, . ) . | (ModuleOrUniformRoot::ExternPrelude, ModuleOrUniformRoot::ExternPrelude) -- line 434 ---------------------------------------- -- line 491 ---------------------------------------- . /// A key that identifies a binding in a given `Module`. . /// . /// Multiple bindings in the same module can have the same key (in a valid . /// program) if all but one of them come from glob imports. . #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] . struct BindingKey { . /// The identifier for the binding, aways the `normalize_to_macros_2_0` version of the . /// identifier. 89,580 ( 0.01%) ident: Ident, 29,570 ( 0.00%) ns: Namespace, . /// 0 if ident is not `_`, otherwise a value that's unique to the specific . /// `_` in the expanded AST that introduced this binding. 21,960 ( 0.00%) disambiguator: u32, . } . . type Resolutions<'a> = RefCell>>>; . . /// One node in the tree of modules. . /// . /// Note that a "module" in resolve is broader than a `mod` that you declare in Rust code. It may be one of these: . /// -- line 511 ---------------------------------------- -- line 551 ---------------------------------------- . impl<'a> ModuleData<'a> { . fn new( . parent: Option>, . kind: ModuleKind, . expansion: ExpnId, . span: Span, . no_implicit_prelude: bool, . ) -> Self { 2,450 ( 0.00%) let is_foreign = match kind { . ModuleKind::Def(_, def_id, _) => !def_id.is_local(), . ModuleKind::Block(_) => false, . }; 8,050 ( 0.00%) ModuleData { . parent, . kind, . lazy_resolutions: Default::default(), . populate_on_access: Cell::new(is_foreign), . unexpanded_invocations: Default::default(), . no_implicit_prelude, . glob_importers: RefCell::new(Vec::new()), . globs: RefCell::new(Vec::new()), . traits: RefCell::new(None), . span, . expansion, . } . } . 111 ( 0.00%) fn for_each_child(&'a self, resolver: &mut R, mut f: F) . where . R: AsMut>, . F: FnMut(&mut R, Ident, Namespace, &'a NameBinding<'a>), . { 43 ( 0.00%) for (key, name_resolution) in resolver.as_mut().resolutions(self).borrow().iter() { 2,692 ( 0.00%) if let Some(binding) = name_resolution.borrow().binding { 186 ( 0.00%) f(resolver, key.ident, key.ns, binding); . } . } 88 ( 0.00%) } . . /// This modifies `self` in place. The traits will be stored in `self.traits`. . fn ensure_traits(&'a self, resolver: &mut R) . where . R: AsMut>, . { . let mut traits = self.traits.borrow_mut(); 574 ( 0.00%) if traits.is_none() { . let mut collected_traits = Vec::new(); . self.for_each_child(resolver, |_, name, ns, binding| { 103 ( 0.00%) if ns != TypeNS { . return; . } 258 ( 0.00%) if let Res::Def(DefKind::Trait | DefKind::TraitAlias, _) = binding.res() { . collected_traits.push((name, binding)) . } . }); 24 ( 0.00%) *traits = Some(collected_traits.into_boxed_slice()); . } . } . . fn res(&self) -> Option { 3,046 ( 0.00%) match self.kind { 4,843 ( 0.00%) ModuleKind::Def(kind, def_id, _) => Some(Res::Def(kind, def_id)), . _ => None, . } . } . . // Public for rustdoc. . pub fn def_id(&self) -> DefId { . self.opt_def_id().expect("`ModuleData::def_id` is called on a block module") . } . . fn opt_def_id(&self) -> Option { 3,421 ( 0.00%) match self.kind { . ModuleKind::Def(_, def_id, _) => Some(def_id), . _ => None, . } . } . . // `self` resolves to the first module ancestor that `is_normal`. . fn is_normal(&self) -> bool { 1,896 ( 0.00%) matches!(self.kind, ModuleKind::Def(DefKind::Mod, _, _)) . } . . fn is_trait(&self) -> bool { 1 ( 0.00%) matches!(self.kind, ModuleKind::Def(DefKind::Trait, _, _)) . } . . fn nearest_item_scope(&'a self) -> Module<'a> { 30,527 ( 0.00%) match self.kind { . ModuleKind::Def(DefKind::Enum | DefKind::Trait, ..) => { . self.parent.expect("enum or trait module without a parent") . } . _ => self, . } . } . . /// The [`DefId`] of the nearest `mod` item ancestor (which may be this module). . /// This may be the crate root. 4,328 ( 0.00%) fn nearest_parent_mod(&self) -> DefId { 17,312 ( 0.00%) match self.kind { 8,656 ( 0.00%) ModuleKind::Def(DefKind::Mod, def_id, _) => def_id, . _ => self.parent.expect("non-root module without parent").nearest_parent_mod(), . } 8,656 ( 0.00%) } . . fn is_ancestor_of(&self, mut other: &Self) -> bool { . while !ptr::eq(self, other) { . if let Some(parent) = other.parent { . other = parent; . } else { . return false; . } -- line 662 ---------------------------------------- -- line 773 ---------------------------------------- . b1: &'a NameBinding<'a>, . b2: &'a NameBinding<'a>, . misc1: AmbiguityErrorMisc, . misc2: AmbiguityErrorMisc, . } . . impl<'a> NameBinding<'a> { . fn module(&self) -> Option> { 48,955 ( 0.00%) match self.kind { 8,651 ( 0.00%) NameBindingKind::Module(module) => Some(module), 589 ( 0.00%) NameBindingKind::Import { binding, .. } => binding.module(), . _ => None, . } . } . . fn res(&self) -> Res { 98,185 ( 0.01%) match self.kind { 92,874 ( 0.01%) NameBindingKind::Res(res, _) => res, 1,409 ( 0.00%) NameBindingKind::Module(module) => module.res().unwrap(), 5,222 ( 0.00%) NameBindingKind::Import { binding, .. } => binding.res(), . } . } . . fn is_ambiguity(&self) -> bool { 48 ( 0.00%) self.ambiguity.is_some() 52 ( 0.00%) || match self.kind { 26 ( 0.00%) NameBindingKind::Import { binding, .. } => binding.is_ambiguity(), . _ => false, . } . } . . fn is_possibly_imported_variant(&self) -> bool { . match self.kind { . NameBindingKind::Import { binding, .. } => binding.is_possibly_imported_variant(), . NameBindingKind::Res( -- line 807 ---------------------------------------- -- line 822 ---------------------------------------- . kind: ModuleKind::Def(DefKind::Mod, def_id, _), . .. . }) => def_id.index == CRATE_DEF_INDEX, . _ => false, . } . } . . fn is_import(&self) -> bool { 124 ( 0.00%) matches!(self.kind, NameBindingKind::Import { .. }) . } . . fn is_glob_import(&self) -> bool { 5,572 ( 0.00%) match self.kind { 46 ( 0.00%) NameBindingKind::Import { import, .. } => import.is_glob(), . _ => false, . } . } . . fn is_importable(&self) -> bool { 62 ( 0.00%) !matches!( . self.res(), . Res::Def(DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy, _) . ) . } . . fn is_macro_def(&self) -> bool { 40 ( 0.00%) matches!(self.kind, NameBindingKind::Res(Res::Def(DefKind::Macro(..), _), _)) . } . . fn macro_kind(&self) -> Option { . self.res().macro_kind() . } . . // Suppose that we resolved macro invocation with `invoc_parent_expansion` to binding `binding` . // at some expansion round `max(invoc, binding)` when they both emerged from macros. -- line 856 ---------------------------------------- -- line 1065 ---------------------------------------- . /// they are declared in the static array generated by proc_macro_harness. . proc_macros: Vec, . confused_type_with_std_module: FxHashMap, . . access_levels: AccessLevels, . } . . /// Nothing really interesting here; it just provides memory for the rest of the crate. 7 ( 0.00%) #[derive(Default)] . pub struct ResolverArenas<'a> { . modules: TypedArena>, . local_modules: RefCell>>, . imports: TypedArena>, . name_resolutions: TypedArena>>, . ast_paths: TypedArena, . dropless: DroplessArena, . } . . impl<'a> ResolverArenas<'a> { 4,550 ( 0.00%) fn new_module( . &'a self, . parent: Option>, . kind: ModuleKind, . expn_id: ExpnId, . span: Span, . no_implicit_prelude: bool, . module_map: &mut FxHashMap>, . ) -> Module<'a> { . let module = . self.modules.alloc(ModuleData::new(parent, kind, expn_id, span, no_implicit_prelude)); . let def_id = module.opt_def_id(); 1,050 ( 0.00%) if def_id.map_or(true, |def_id| def_id.is_local()) { . self.local_modules.borrow_mut().push(module); . } 350 ( 0.00%) if let Some(def_id) = def_id { . module_map.insert(def_id, module); . } . module 3,150 ( 0.00%) } . fn local_modules(&'a self) -> std::cell::Ref<'a, Vec>> { . self.local_modules.borrow() . } . fn alloc_name_binding(&'a self, name_binding: NameBinding<'a>) -> &'a NameBinding<'a> { . self.dropless.alloc(name_binding) . } 14 ( 0.00%) fn alloc_import(&'a self, import: Import<'a>) -> &'a Import<'_> { 554 ( 0.00%) self.imports.alloc(import) 14 ( 0.00%) } . fn alloc_name_resolution(&'a self) -> &'a RefCell> { 1,737 ( 0.00%) self.name_resolutions.alloc(Default::default()) . } . fn alloc_macro_rules_scope(&'a self, scope: MacroRulesScope<'a>) -> MacroRulesScopeRef<'a> { . PtrKey(self.dropless.alloc(Cell::new(scope))) . } . fn alloc_macro_rules_binding( . &'a self, . binding: MacroRulesBinding<'a>, . ) -> &'a MacroRulesBinding<'a> { -- line 1122 ---------------------------------------- -- line 1133 ---------------------------------------- . impl<'a> AsMut> for Resolver<'a> { . fn as_mut(&mut self) -> &mut Resolver<'a> { . self . } . } . . impl<'a, 'b> DefIdTree for &'a Resolver<'b> { . fn parent(self, id: DefId) -> Option { 154 ( 0.00%) match id.as_local() { . Some(id) => self.definitions.def_key(id).parent, . None => self.cstore().def_key(id).parent, . } . .map(|index| DefId { index, ..id }) . } . } . . /// This interface is used through the AST→HIR step, to embed full paths into the HIR. After that . /// the resolver is no longer needed as all the relevant information is inline. . impl ResolverAstLowering for Resolver<'_> { . fn def_key(&mut self, id: DefId) -> DefKey { . if let Some(id) = id.as_local() { . self.definitions().def_key(id) . } else { 12,795 ( 0.00%) self.cstore().def_key(id) . } . } . . #[inline] . fn def_span(&self, id: LocalDefId) -> Span { . self.definitions.def_span(id) . } . 2,268 ( 0.00%) fn item_generics_num_lifetimes(&self, def_id: DefId) -> usize { 790 ( 0.00%) if let Some(def_id) = def_id.as_local() { 206 ( 0.00%) self.item_generics_num_lifetimes[&def_id] . } else { 1,376 ( 0.00%) self.cstore().item_generics_num_lifetimes(def_id, self.session) . } 824 ( 0.00%) } . 348 ( 0.00%) fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option> { 174 ( 0.00%) self.legacy_const_generic_args(expr) 522 ( 0.00%) } . 3,909 ( 0.00%) fn get_partial_res(&self, id: NodeId) -> Option { . self.partial_res_map.get(&id).cloned() 11,727 ( 0.00%) } . 180 ( 0.00%) fn get_import_res(&mut self, id: NodeId) -> PerNS> { 45 ( 0.00%) self.import_res_map.get(&id).cloned().unwrap_or_default() 225 ( 0.00%) } . . fn get_label_res(&mut self, id: NodeId) -> Option { . self.label_res_map.get(&id).cloned() . } . . fn definitions(&mut self) -> &mut Definitions { 219 ( 0.00%) &mut self.definitions 219 ( 0.00%) } . 1,948 ( 0.00%) fn create_stable_hashing_context(&self) -> StableHashingContext<'_> { 14,339 ( 0.00%) StableHashingContext::new(self.session, &self.definitions, self.crate_loader.cstore()) 2,435 ( 0.00%) } . . fn lint_buffer(&mut self) -> &mut LintBuffer { . &mut self.lint_buffer . } . . fn next_node_id(&mut self) -> NodeId { . self.next_node_id() . } . 26,036 ( 0.00%) fn take_trait_map(&mut self, node: NodeId) -> Option> { . self.trait_map.remove(&node) 26,036 ( 0.00%) } . 26,988 ( 0.00%) fn opt_local_def_id(&self, node: NodeId) -> Option { 1,869 ( 0.00%) self.node_id_to_def_id.get(&node).copied() 26,988 ( 0.00%) } . 1,200 ( 0.00%) fn local_def_id(&self, node: NodeId) -> LocalDefId { . self.opt_local_def_id(node).unwrap_or_else(|| panic!("no entry for node id: `{:?}`", node)) 1,200 ( 0.00%) } . . fn def_path_hash(&self, def_id: DefId) -> DefPathHash { . match def_id.as_local() { . Some(def_id) => self.definitions.def_path_hash(def_id), . None => self.cstore().def_path_hash(def_id), . } . } . . /// Adds a definition with a parent definition. 4,710 ( 0.00%) fn create_def( . &mut self, . parent: LocalDefId, . node_id: ast::NodeId, . data: DefPathData, . expn_id: ExpnId, . span: Span, . ) -> LocalDefId { 628 ( 0.00%) assert!( 628 ( 0.00%) !self.node_id_to_def_id.contains_key(&node_id), . "adding a def'n for node-id {:?} and data {:?} but a previous def'n exists: {:?}", . node_id, . data, . self.definitions.def_key(self.node_id_to_def_id[&node_id]), . ); . . // Find the next free disambiguator for this key. 314 ( 0.00%) let next_disambiguator = &mut self.next_disambiguator; . let next_disambiguator = |parent, data| { 1,570 ( 0.00%) let next_disamb = next_disambiguator.entry((parent, data)).or_insert(0); 314 ( 0.00%) let disambiguator = *next_disamb; 314 ( 0.00%) *next_disamb = next_disamb.checked_add(1).expect("disambiguator overflow"); . disambiguator . }; . 3,140 ( 0.00%) let def_id = self.definitions.create_def(parent, data, expn_id, next_disambiguator, span); . . // Some things for which we allocate `LocalDefId`s don't correspond to . // anything in the AST, so they don't have a `NodeId`. For these cases . // we don't need a mapping from `NodeId` to `LocalDefId`. 942 ( 0.00%) if node_id != ast::DUMMY_NODE_ID { . debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id); . self.node_id_to_def_id.insert(node_id, def_id); . } 942 ( 0.00%) assert_eq!(self.def_id_to_node_id.push(node_id), def_id); . . def_id 2,826 ( 0.00%) } . } . . impl<'a> Resolver<'a> { 16 ( 0.00%) pub fn new( . session: &'a Session, . krate: &Crate, . crate_name: &str, . metadata_loader: Box, . arenas: &'a ResolverArenas<'a>, . ) -> Resolver<'a> { . let root_def_id = CRATE_DEF_ID.to_def_id(); . let mut module_map = FxHashMap::default(); 14 ( 0.00%) let graph_root = arenas.new_module( . None, . ModuleKind::Def(DefKind::Mod, root_def_id, kw::Empty), 1 ( 0.00%) ExpnId::root(), 1 ( 0.00%) krate.span, 2 ( 0.00%) session.contains_name(&krate.attrs, sym::no_implicit_prelude), . &mut module_map, . ); 12 ( 0.00%) let empty_module = arenas.new_module( . None, . ModuleKind::Def(DefKind::Mod, root_def_id, kw::Empty), 1 ( 0.00%) ExpnId::root(), . DUMMY_SP, . true, . &mut FxHashMap::default(), . ); . 4 ( 0.00%) let definitions = Definitions::new(session.local_stable_crate_id(), krate.span); 2 ( 0.00%) let root = definitions.get_root_def(); . . let mut visibilities = FxHashMap::default(); . visibilities.insert(CRATE_DEF_ID, ty::Visibility::Public); . . let mut def_id_to_node_id = IndexVec::default(); 2 ( 0.00%) assert_eq!(def_id_to_node_id.push(CRATE_NODE_ID), root); . let mut node_id_to_def_id = FxHashMap::default(); . node_id_to_def_id.insert(CRATE_NODE_ID, root); . . let mut invocation_parents = FxHashMap::default(); . invocation_parents.insert(LocalExpnId::ROOT, (root, ImplTraitContext::Existential)); . 3 ( 0.00%) let mut extern_prelude: FxHashMap> = session . .opts . .externs . .iter() . .filter(|(_, entry)| entry.add_prelude) . .map(|(name, _)| (Ident::from_str(name), Default::default())) . .collect(); . 9 ( 0.00%) if !session.contains_name(&krate.attrs, sym::no_core) { . extern_prelude.insert(Ident::with_dummy_span(sym::core), Default::default()); 7 ( 0.00%) if !session.contains_name(&krate.attrs, sym::no_std) { . extern_prelude.insert(Ident::with_dummy_span(sym::std), Default::default()); . } . } . 8 ( 0.00%) let (registered_attrs, registered_tools) = 4 ( 0.00%) macros::registered_attrs_and_tools(session, &krate.attrs); . . let features = session.features_untracked(); . 237 ( 0.00%) let mut resolver = Resolver { . session, . 2 ( 0.00%) definitions, . . // The outermost module has def ID 0; this is not reflected in the . // AST. . graph_root, . prelude: None, 4 ( 0.00%) extern_prelude, . . has_self: FxHashSet::default(), . field_names: FxHashMap::default(), . . determined_imports: Vec::new(), . indeterminate_imports: Vec::new(), . . last_import_segment: false, -- line 1343 ---------------------------------------- -- line 1347 ---------------------------------------- . partial_res_map: Default::default(), . import_res_map: Default::default(), . label_res_map: Default::default(), . extern_crate_map: Default::default(), . reexport_map: FxHashMap::default(), . trait_map: NodeMap::default(), . underscore_disambiguator: 0, . empty_module, 4 ( 0.00%) module_map, . block_map: Default::default(), . binding_parent_modules: FxHashMap::default(), . ast_transform_scopes: FxHashMap::default(), . . glob_map: Default::default(), 4 ( 0.00%) visibilities, . used_imports: FxHashSet::default(), . maybe_unused_trait_imports: Default::default(), . maybe_unused_extern_crates: Vec::new(), . . privacy_errors: Vec::new(), . ambiguity_errors: Vec::new(), . use_injections: Vec::new(), . macro_expanded_macro_export_errors: BTreeSet::new(), -- line 1369 ---------------------------------------- -- line 1372 ---------------------------------------- . dummy_binding: arenas.alloc_name_binding(NameBinding { . kind: NameBindingKind::Res(Res::Err, false), . ambiguity: None, . expansion: LocalExpnId::ROOT, . span: DUMMY_SP, . vis: ty::Visibility::Public, . }), . 6 ( 0.00%) crate_loader: CrateLoader::new(session, metadata_loader, crate_name), . macro_names: FxHashSet::default(), . builtin_macros: Default::default(), 4 ( 0.00%) registered_attrs, 4 ( 0.00%) registered_tools, . macro_use_prelude: FxHashMap::default(), . all_macros: FxHashMap::default(), . macro_map: FxHashMap::default(), 7 ( 0.00%) dummy_ext_bang: Lrc::new(SyntaxExtension::dummy_bang(session.edition())), 6 ( 0.00%) dummy_ext_derive: Lrc::new(SyntaxExtension::dummy_derive(session.edition())), 5 ( 0.00%) non_macro_attr: Lrc::new(SyntaxExtension::non_macro_attr(session.edition())), . invocation_parent_scopes: Default::default(), . output_macro_rules_scopes: Default::default(), . helper_attrs: Default::default(), . derive_data: Default::default(), . local_macro_def_scopes: FxHashMap::default(), . name_already_seen: FxHashMap::default(), . potentially_unused_imports: Vec::new(), . struct_constructors: Default::default(), -- line 1398 ---------------------------------------- -- line 1405 ---------------------------------------- . active_features: features . .declared_lib_features . .iter() . .map(|(feat, ..)| *feat) . .chain(features.declared_lang_features.iter().map(|(feat, ..)| *feat)) . .collect(), . lint_buffer: LintBuffer::default(), . next_node_id: CRATE_NODE_ID, 4 ( 0.00%) node_id_to_def_id, 4 ( 0.00%) def_id_to_node_id, . placeholder_field_indices: Default::default(), 4 ( 0.00%) invocation_parents, . next_disambiguator: Default::default(), . trait_impl_items: Default::default(), . legacy_const_generic_args: Default::default(), . item_generics_num_lifetimes: Default::default(), . main_def: Default::default(), . trait_impls: Default::default(), . proc_macros: Default::default(), . confused_type_with_std_module: Default::default(), . access_levels: Default::default(), . }; . . let root_parent_scope = ParentScope::module(graph_root, &resolver); . resolver.invocation_parent_scopes.insert(LocalExpnId::ROOT, root_parent_scope); . . resolver 9 ( 0.00%) } . . fn new_module( . &mut self, . parent: Option>, . kind: ModuleKind, . expn_id: ExpnId, . span: Span, . no_implicit_prelude: bool, . ) -> Module<'a> { 7 ( 0.00%) let module_map = &mut self.module_map; 3,477 ( 0.00%) self.arenas.new_module(parent, kind, expn_id, span, no_implicit_prelude, module_map) . } . . pub fn next_node_id(&mut self) -> NodeId { . let next = 7,201 ( 0.00%) self.next_node_id.as_u32().checked_add(1).expect("input too large; ran out of NodeIds"); . mem::replace(&mut self.next_node_id, ast::NodeId::from_u32(next)) . } . . pub fn lint_buffer(&mut self) -> &mut LintBuffer { 4 ( 0.00%) &mut self.lint_buffer 4 ( 0.00%) } . 1 ( 0.00%) pub fn arenas() -> ResolverArenas<'a> { . Default::default() 1 ( 0.00%) } . 9 ( 0.00%) pub fn into_outputs(self) -> ResolverOutputs { . let proc_macros = self.proc_macros.iter().map(|id| self.local_def_id(*id)).collect(); 1 ( 0.00%) let definitions = self.definitions; 4 ( 0.00%) let visibilities = self.visibilities; 4 ( 0.00%) let extern_crate_map = self.extern_crate_map; 4 ( 0.00%) let reexport_map = self.reexport_map; 4 ( 0.00%) let maybe_unused_trait_imports = self.maybe_unused_trait_imports; 4 ( 0.00%) let maybe_unused_extern_crates = self.maybe_unused_extern_crates; 4 ( 0.00%) let glob_map = self.glob_map; 6 ( 0.00%) let main_def = self.main_def; 4 ( 0.00%) let confused_type_with_std_module = self.confused_type_with_std_module; 6 ( 0.00%) let access_levels = self.access_levels; 37 ( 0.00%) ResolverOutputs { 2 ( 0.00%) definitions, 11 ( 0.00%) cstore: Box::new(self.crate_loader.into_cstore()), 4 ( 0.00%) visibilities, 4 ( 0.00%) access_levels, 4 ( 0.00%) extern_crate_map, 4 ( 0.00%) reexport_map, 4 ( 0.00%) glob_map, 4 ( 0.00%) maybe_unused_trait_imports, 4 ( 0.00%) maybe_unused_extern_crates, . extern_prelude: self . .extern_prelude . .iter() 2 ( 0.00%) .map(|(ident, entry)| (ident.name, entry.introduced_by_item)) . .collect(), 6 ( 0.00%) main_def, 4 ( 0.00%) trait_impls: self.trait_impls, 4 ( 0.00%) proc_macros, 4 ( 0.00%) confused_type_with_std_module, 5 ( 0.00%) registered_tools: self.registered_tools, . } 19 ( 0.00%) } . . pub fn clone_outputs(&self) -> ResolverOutputs { . let proc_macros = self.proc_macros.iter().map(|id| self.local_def_id(*id)).collect(); . ResolverOutputs { . definitions: self.definitions.clone(), . access_levels: self.access_levels.clone(), . cstore: Box::new(self.cstore().clone()), . visibilities: self.visibilities.clone(), -- line 1501 ---------------------------------------- -- line 1513 ---------------------------------------- . trait_impls: self.trait_impls.clone(), . proc_macros, . confused_type_with_std_module: self.confused_type_with_std_module.clone(), . registered_tools: self.registered_tools.clone(), . } . } . . pub fn cstore(&self) -> &CStore { 18,959 ( 0.00%) self.crate_loader.cstore() . } . . fn dummy_ext(&self, macro_kind: MacroKind) -> Lrc { . match macro_kind { . MacroKind::Bang => self.dummy_ext_bang.clone(), . MacroKind::Derive => self.dummy_ext_derive.clone(), . MacroKind::Attr => self.non_macro_attr.clone(), . } . } . . /// Runs the function on each namespace. 164 ( 0.00%) fn per_ns(&mut self, mut f: F) { 388 ( 0.00%) f(self, TypeNS); 376 ( 0.00%) f(self, ValueNS); 376 ( 0.00%) f(self, MacroNS); 144 ( 0.00%) } . . fn is_builtin_macro(&mut self, res: Res) -> bool { . self.get_macro(res).map_or(false, |ext| ext.builtin_name.is_some()) . } . . fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId { . loop { . match ctxt.outer_expn_data().macro_def_id { . Some(def_id) => return def_id, . None => ctxt.remove_mark(), . }; . } . } . . /// Entry point to crate resolution. 2 ( 0.00%) pub fn resolve_crate(&mut self, krate: &Crate) { 4 ( 0.00%) self.session.time("resolve_crate", || { 3 ( 0.00%) self.session.time("finalize_imports", || ImportResolver { r: self }.finalize_imports()); . self.session.time("resolve_access_levels", || { 3 ( 0.00%) AccessLevelsVisitor::compute_access_levels(self, krate) . }); 2 ( 0.00%) self.session.time("finalize_macro_resolutions", || self.finalize_macro_resolutions()); 3 ( 0.00%) self.session.time("late_resolve_crate", || self.late_resolve_crate(krate)); 2 ( 0.00%) self.session.time("resolve_main", || self.resolve_main()); 3 ( 0.00%) self.session.time("resolve_check_unused", || self.check_unused(krate)); 3 ( 0.00%) self.session.time("resolve_report_errors", || self.report_errors(krate)); 4 ( 0.00%) self.session.time("resolve_postprocess", || self.crate_loader.postprocess(krate)); . }); . } . 3,444 ( 0.00%) pub fn traits_in_scope( . &mut self, . current_trait: Option>, . parent_scope: &ParentScope<'a>, . ctxt: SyntaxContext, . assoc_item: Option<(Symbol, Namespace)>, . ) -> Vec { . let mut found_traits = Vec::new(); . 574 ( 0.00%) if let Some(module) = current_trait { . if self.trait_may_have_item(Some(module), assoc_item) { . let def_id = module.def_id(); 9 ( 0.00%) found_traits.push(TraitCandidate { def_id, import_ids: smallvec![] }); . } . } . . self.visit_scopes(ScopeSet::All(TypeNS, false), parent_scope, ctxt, |this, scope, _, _| { . match scope { . Scope::Module(module, _) => { . this.traits_in_module(module, assoc_item, &mut found_traits); . } . Scope::StdLibPrelude => { 861 ( 0.00%) if let Some(module) = this.prelude { . this.traits_in_module(module, assoc_item, &mut found_traits); . } . } . Scope::ExternPrelude | Scope::ToolPrelude | Scope::BuiltinTypes => {} . _ => unreachable!(), . } . None::<()> . }); . . found_traits 2,296 ( 0.00%) } . . fn traits_in_module( . &mut self, . module: Module<'a>, . assoc_item: Option<(Symbol, Namespace)>, . found_traits: &mut Vec, . ) { . module.ensure_traits(self); . let traits = module.traits.borrow(); 16,434 ( 0.00%) for (trait_name, trait_binding) in traits.as_ref().unwrap().iter() { . if self.trait_may_have_item(trait_binding.module(), assoc_item) { . let def_id = trait_binding.res().def_id(); 24 ( 0.00%) let import_ids = self.find_transitive_imports(&trait_binding.kind, *trait_name); 72 ( 0.00%) found_traits.push(TraitCandidate { def_id, import_ids }); . } . } . } . . // List of traits in scope is pruned on best effort basis. We reject traits not having an . // associated item with the given name and namespace (if specified). This is a conservative . // optimization, proper hygienic type-based resolution of associated items is done in typeck. . // We don't reject trait aliases (`trait_module == None`) because we don't have access to their . // associated items. . fn trait_may_have_item( . &mut self, . trait_module: Option>, . assoc_item: Option<(Symbol, Namespace)>, . ) -> bool { 8,120 ( 0.00%) match (trait_module, assoc_item) { . (Some(trait_module), Some((name, ns))) => { 16,145 ( 0.00%) self.resolutions(trait_module).borrow().iter().any(|resolution| { . let (&BindingKey { ident: assoc_ident, ns: assoc_ns, .. }, _) = resolution; 62,025 ( 0.01%) assoc_ns == ns && assoc_ident.name == name . }) . } . _ => true, . } . } . . fn find_transitive_imports( . &mut self, . mut kind: &NameBindingKind<'_>, . trait_name: Ident, . ) -> SmallVec<[LocalDefId; 1]> { . let mut import_ids = smallvec![]; 41 ( 0.00%) while let NameBindingKind::Import { import, binding, .. } = kind { 15 ( 0.00%) let id = self.local_def_id(import.id); . self.maybe_unused_trait_imports.insert(id); 5 ( 0.00%) self.add_to_glob_map(&import, trait_name); . import_ids.push(id); 5 ( 0.00%) kind = &binding.kind; . } . import_ids . } . . fn new_key(&mut self, ident: Ident, ns: Namespace) -> BindingKey { 30,689 ( 0.00%) let ident = ident.normalize_to_macros_2_0(); 9,054 ( 0.00%) let disambiguator = if ident.name == kw::Underscore { . self.underscore_disambiguator += 1; . self.underscore_disambiguator . } else { . 0 . }; . BindingKey { ident, ns, disambiguator } . } . 136,776 ( 0.01%) fn resolutions(&mut self, module: Module<'a>) -> &'a Resolutions<'a> { 17,097 ( 0.00%) if module.populate_on_access.get() { . module.populate_on_access.set(false); . self.build_reduced_graph_external(module); . } 17,097 ( 0.00%) &module.lazy_resolutions 153,873 ( 0.01%) } . 81,513 ( 0.01%) fn resolution( . &mut self, . module: Module<'a>, . key: BindingKey, . ) -> &'a RefCell> { 27,171 ( 0.00%) *self . .resolutions(module) . .borrow_mut() 54,342 ( 0.00%) .entry(key) 18,114 ( 0.00%) .or_insert_with(|| self.arenas.alloc_name_resolution()) 72,456 ( 0.01%) } . 44,616 ( 0.00%) fn record_use( . &mut self, . ident: Ident, . used_binding: &'a NameBinding<'a>, . is_lexical_scope: bool, . ) { 12,168 ( 0.00%) if let Some((b2, kind)) = used_binding.ambiguity { . self.ambiguity_errors.push(AmbiguityError { . kind, . ident, . b1: used_binding, . b2, . misc1: AmbiguityErrorMisc::None, . misc2: AmbiguityErrorMisc::None, . }); . } 9,986 ( 0.00%) if let NameBindingKind::Import { import, binding, ref used } = used_binding.kind { . // Avoid marking `extern crate` items that refer to a name from extern prelude, . // but not introduce it, as used if they are accessed from lexical scope. 1,874 ( 0.00%) if is_lexical_scope { 22 ( 0.00%) if let Some(entry) = self.extern_prelude.get(&ident.normalize_to_macros_2_0()) { . if let Some(crate_item) = entry.extern_crate_item { . if ptr::eq(used_binding, crate_item) && !entry.introduced_by_item { . return; . } . } . } . } . used.set(true); . import.used.set(true); 937 ( 0.00%) self.used_imports.insert(import.id); 4,685 ( 0.00%) self.add_to_glob_map(&import, ident); 5,622 ( 0.00%) self.record_use(ident, binding, false); . } 32,448 ( 0.00%) } . . #[inline] 2,811 ( 0.00%) fn add_to_glob_map(&mut self, import: &Import<'_>, ident: Ident) { 942 ( 0.00%) if import.is_glob() { . let def_id = self.local_def_id(import.id); . self.glob_map.entry(def_id).or_default().insert(ident.name); . } 3,748 ( 0.00%) } . . /// A generic scope visitor. . /// Visits scopes in order to resolve some identifier in them or perform other actions. . /// If the callback returns `Some` result, we stop visiting scopes and return it. . fn visit_scopes( . &mut self, . scope_set: ScopeSet<'a>, . parent_scope: &ParentScope<'a>, -- line 1738 ---------------------------------------- -- line 1780 ---------------------------------------- . // ambiguities with `macro_rules`. . // 4. `macro_use` prelude (open, the open part is from macro expansions, not controlled). . // 4a. User-defined prelude from macro-use . // (open, the open part is from macro expansions, not controlled). . // 4b. "Standard library prelude" part implemented through `macro-use` (closed, controlled). . // 4c. Standard library prelude (de-facto closed, controlled). . // 6. Language prelude: builtin attributes (closed, controlled). . 44,052 ( 0.00%) let rust_2015 = ctxt.edition() == Edition::Edition2015; . let (ns, macro_kind, is_absolute_path) = match scope_set { . ScopeSet::All(ns, _) => (ns, None, false), . ScopeSet::AbsolutePath(ns) => (ns, None, true), . ScopeSet::Macro(macro_kind) => (MacroNS, Some(macro_kind), false), . ScopeSet::Late(ns, ..) => (ns, None, false), . }; 134,372 ( 0.01%) let module = match scope_set { . // Start with the specified module. . ScopeSet::Late(_, module, _) => module, . // Jump out of trait or enum modules, they do not act as scopes. 4,320 ( 0.00%) _ => parent_scope.module.nearest_item_scope(), . }; 9,598 ( 0.00%) let mut scope = match ns { 23,995 ( 0.00%) _ if is_absolute_path => Scope::CrateRoot, . TypeNS | ValueNS => Scope::Module(module, None), 12,099 ( 0.00%) MacroNS => Scope::DeriveHelpers(parent_scope.expansion), . }; 10,172 ( 0.00%) let mut ctxt = ctxt.normalize_to_macros_2_0(); 22,640 ( 0.00%) let mut use_prelude = !module.no_implicit_prelude; . . loop { 275,654 ( 0.02%) let visit = match scope { . // Derive helpers are not in scope when resolving derives in the same container. . Scope::DeriveHelpers(expn_id) => { 12,164 ( 0.00%) !(expn_id == parent_scope.expansion && macro_kind == Some(MacroKind::Derive)) . } . Scope::DeriveHelpersCompat => true, . Scope::MacroRules(macro_rules_scope) => { . // Use "path compression" on `macro_rules` scope chains. This is an optimization . // used to avoid long scope chains, see the comments on `MacroRulesScopeRef`. . // As another consequence of this optimization visitors never observe invocation . // scopes for macros that were already expanded. 29,726 ( 0.00%) while let MacroRulesScope::Invocation(invoc_id) = macro_rules_scope.get() { . if let Some(next_scope) = self.output_macro_rules_scopes.get(&invoc_id) { . macro_rules_scope.set(next_scope.get()); . } else { . break; . } . } . true . } . Scope::CrateRoot => true, . Scope::Module(..) => true, 3,001 ( 0.00%) Scope::RegisteredAttrs => use_prelude, . Scope::MacroUsePrelude => use_prelude || rust_2015, . Scope::BuiltinAttrs => true, 273 ( 0.00%) Scope::ExternPrelude => use_prelude || is_absolute_path, 91 ( 0.00%) Scope::ToolPrelude => use_prelude, 16,276 ( 0.00%) Scope::StdLibPrelude => use_prelude || ns == MacroNS, . Scope::BuiltinTypes => true, . }; . 9,189 ( 0.00%) if visit { 37,845 ( 0.00%) if let break_result @ Some(..) = visitor(self, scope, use_prelude, ctxt) { . return break_result; . } . } . 76,968 ( 0.01%) scope = match scope { . Scope::DeriveHelpers(LocalExpnId::ROOT) => Scope::DeriveHelpersCompat, . Scope::DeriveHelpers(expn_id) => { . // Derive helpers are not visible to code generated by bang or derive macros. . let expn_data = expn_id.expn_data(); 34,902 ( 0.00%) match expn_data.kind { . ExpnKind::Root . | ExpnKind::Macro(MacroKind::Bang | MacroKind::Derive, _) => { . Scope::DeriveHelpersCompat . } 65 ( 0.00%) _ => Scope::DeriveHelpers(expn_data.parent.expect_local()), . } . } 12,099 ( 0.00%) Scope::DeriveHelpersCompat => Scope::MacroRules(parent_scope.macro_rules), 49,174 ( 0.00%) Scope::MacroRules(macro_rules_scope) => match macro_rules_scope.get() { . MacroRulesScope::Binding(binding) => { 32,376 ( 0.00%) Scope::MacroRules(binding.parent_macro_rules_scope) . } . MacroRulesScope::Invocation(invoc_id) => { . Scope::MacroRules(self.invocation_parent_scopes[&invoc_id].macro_rules) . } . MacroRulesScope::Empty => Scope::Module(module, None), . }, . Scope::CrateRoot => match ns { . TypeNS => { . ctxt.adjust(ExpnId::root()); . Scope::ExternPrelude . } . ValueNS | MacroNS => break, . }, . Scope::Module(module, prev_lint_id) => { 15,338 ( 0.00%) use_prelude = !module.no_implicit_prelude; . let derive_fallback_lint_id = match scope_set { . ScopeSet::Late(.., lint_id) => lint_id, . _ => None, . }; 24,155 ( 0.00%) match self.hygienic_lexical_parent(module, &mut ctxt, derive_fallback_lint_id) { . Some((parent_module, lint_id)) => { . Scope::Module(parent_module, lint_id.or(prev_lint_id)) . } . None => { 18,897 ( 0.00%) ctxt.adjust(ExpnId::root()); 13,558 ( 0.00%) match ns { . TypeNS => Scope::ExternPrelude, . ValueNS => Scope::StdLibPrelude, . MacroNS => Scope::RegisteredAttrs, . } . } . } . } . Scope::RegisteredAttrs => Scope::MacroUsePrelude, . Scope::MacroUsePrelude => Scope::StdLibPrelude, . Scope::BuiltinAttrs => break, // nowhere else to search 182 ( 0.00%) Scope::ExternPrelude if is_absolute_path => break, . Scope::ExternPrelude => Scope::ToolPrelude, . Scope::ToolPrelude => Scope::StdLibPrelude, 9,964 ( 0.00%) Scope::StdLibPrelude => match ns { . TypeNS => Scope::BuiltinTypes, . ValueNS => break, // nowhere else to search . MacroNS => Scope::BuiltinAttrs, . }, . Scope::BuiltinTypes => break, // nowhere else to search . }; . } . -- line 1911 ---------------------------------------- -- line 1924 ---------------------------------------- . /// let g = || {}; . /// fn g() {} . /// g(); // This resolves to the local variable `g` since it shadows the item. . /// } . /// ``` . /// . /// Invariant: This must only be called during main resolution, not during . /// import resolution. 15,090 ( 0.00%) fn resolve_ident_in_lexical_scope( . &mut self, . mut ident: Ident, . ns: Namespace, . parent_scope: &ParentScope<'a>, . record_used_id: Option, . path_span: Span, . ribs: &[Rib<'a>], . ) -> Option> { 3,018 ( 0.00%) assert!(ns == TypeNS || ns == ValueNS); . let orig_ident = ident; 10,563 ( 0.00%) if ident.name == kw::Empty { . return Some(LexicalScopeBinding::Res(Res::Err)); . } . let (general_span, normalized_span) = if ident.name == kw::SelfUpper { . // FIXME(jseyfried) improve `Self` hygiene . let empty_span = ident.span.with_ctxt(SyntaxContext::root()); . (empty_span, empty_span) 1,412 ( 0.00%) } else if ns == TypeNS { 2,585 ( 0.00%) let normalized_span = ident.span.normalize_to_macros_2_0(); . (normalized_span, normalized_span) . } else { 4,475 ( 0.00%) (ident.span.normalize_to_macro_rules(), ident.span.normalize_to_macros_2_0()) . }; . ident.span = general_span; . let normalized_ident = Ident { span: normalized_span, ..ident }; . . // Walk backwards up the ribs in scope. . let record_used = record_used_id.is_some(); 4,527 ( 0.00%) let mut module = self.graph_root; . for i in (0..ribs.len()).rev() { . debug!("walk rib\n{:?}", ribs[i].bindings); . // Use the rib kind to determine whether we are resolving parameters . // (macro 2.0 hygiene) or local variables (`macro_rules` hygiene). 6,540 ( 0.00%) let rib_ident = if ribs[i].kind.contains_params() { normalized_ident } else { ident }; . if let Some((original_rib_ident_def, res)) = ribs[i].bindings.get_key_value(&rib_ident) . { . // The ident resolves to a type parameter or local variable. 7,920 ( 0.00%) return Some(LexicalScopeBinding::Res(self.validate_res_from_ribs( . i, 1,320 ( 0.00%) rib_ident, 3,300 ( 0.00%) *res, . record_used, . path_span, . *original_rib_ident_def, . ribs, . ))); . } . 37,764 ( 0.00%) module = match ribs[i].kind { 849 ( 0.00%) ModuleRibKind(module) => module, . MacroDefinition(def) if def == self.macro_def(ident.span.ctxt()) => { . // If an invocation of this macro created `ident`, give up on `ident` . // and switch to `ident`'s source from the macro definition. . ident.span.remove_mark(); . continue; . } . _ => continue, . }; . 2,547 ( 0.00%) match module.kind { . ModuleKind::Block(..) => {} // We can see through blocks . _ => break, . } . . let item = self.resolve_ident_in_module_unadjusted( . ModuleOrUniformRoot::Module(module), . ident, . ns, -- line 2000 ---------------------------------------- -- line 2002 ---------------------------------------- . record_used, . path_span, . ); . if let Ok(binding) = item { . // The ident resolves to an item. . return Some(LexicalScopeBinding::Item(binding)); . } . } 14,433 ( 0.00%) self.early_resolve_ident_in_lexical_scope( . orig_ident, . ScopeSet::Late(ns, module, record_used_id), . parent_scope, . record_used, . record_used, . path_span, . ) . .ok() . .map(LexicalScopeBinding::Item) 13,581 ( 0.00%) } . 43,758 ( 0.00%) fn hygienic_lexical_parent( . &mut self, . module: Module<'a>, . ctxt: &mut SyntaxContext, . derive_fallback_lint_id: Option, . ) -> Option<(Module<'a>, Option)> { 27,846 ( 0.00%) if !module.expansion.outer_expn_is_descendant_of(*ctxt) { 1,536 ( 0.00%) return Some((self.expn_def_scope(ctxt.remove_mark()), None)); . } . 7,444 ( 0.00%) if let ModuleKind::Block(..) = module.kind { . return Some((module.parent.unwrap().nearest_item_scope(), None)); . } . . // We need to support the next case under a deprecation warning . // ``` . // struct MyStruct; . // ---- begin: this comes from a proc macro derive . // mod implementation_details { . // // Note that `MyStruct` is not in scope here. . // impl SomeTrait for MyStruct { ... } . // } . // ---- end . // ``` . // So we have to fall back to the module's parent during lexical resolution in this case. 3,722 ( 0.00%) if derive_fallback_lint_id.is_some() { 201 ( 0.00%) if let Some(parent) = module.parent { . // Inner module is inside the macro, parent module is outside of the macro. 335 ( 0.00%) if module.expansion != parent.expansion . && module.expansion.is_descendant_of(parent.expansion) . { . // The macro is a proc macro derive . if let Some(def_id) = module.expansion.expn_data().macro_def_id { . let ext = self.get_macro_by_def_id(def_id); . if ext.builtin_name.is_none() . && ext.macro_kind() == MacroKind::Derive . && parent.expansion.outer_expn_is_descendant_of(*ctxt) -- line 2058 ---------------------------------------- -- line 2060 ---------------------------------------- . return Some((parent, derive_fallback_lint_id)); . } . } . } . } . } . . None 39,780 ( 0.00%) } . . fn resolve_ident_in_module( . &mut self, . module: ModuleOrUniformRoot<'a>, . ident: Ident, . ns: Namespace, . parent_scope: &ParentScope<'a>, . record_used: bool, . path_span: Span, . ) -> Result<&'a NameBinding<'a>, Determinacy> { 9,872 ( 0.00%) self.resolve_ident_in_module_ext(module, ident, ns, parent_scope, record_used, path_span) . .map_err(|(determinacy, _)| determinacy) . } . 22,120 ( 0.00%) fn resolve_ident_in_module_ext( . &mut self, . module: ModuleOrUniformRoot<'a>, . mut ident: Ident, . ns: Namespace, . parent_scope: &ParentScope<'a>, . record_used: bool, . path_span: Span, . ) -> Result<&'a NameBinding<'a>, (Determinacy, Weak)> { . let tmp_parent_scope; . let mut adjusted_parent_scope = parent_scope; . match module { . ModuleOrUniformRoot::Module(m) => { 6,642 ( 0.00%) if let Some(def) = ident.span.normalize_to_macros_2_0_and_adjust(m.expansion) { 1,100 ( 0.00%) tmp_parent_scope = 1,320 ( 0.00%) ParentScope { module: self.expn_def_scope(def), ..*parent_scope }; . adjusted_parent_scope = &tmp_parent_scope; . } . } . ModuleOrUniformRoot::ExternPrelude => { . ident.span.normalize_to_macros_2_0_and_adjust(ExpnId::root()); . } . ModuleOrUniformRoot::CrateRootAndExternPrelude | ModuleOrUniformRoot::CurrentScope => { . // No adjustments . } . } 12,176 ( 0.00%) self.resolve_ident_in_module_unadjusted_ext( . module, 2,214 ( 0.00%) ident, . ns, . adjusted_parent_scope, . false, . record_used, . path_span, . ) 7,742 ( 0.00%) } . 22,930 ( 0.00%) fn resolve_crate_root(&mut self, ident: Ident) -> Module<'a> { . debug!("resolve_crate_root({:?})", ident); 2,293 ( 0.00%) let mut ctxt = ident.span.ctxt(); 2,293 ( 0.00%) let mark = if ident.name == kw::DollarCrate { . // When resolving `$crate` from a `macro_rules!` invoked in a `macro`, . // we don't want to pretend that the `macro_rules!` definition is in the `macro` . // as described in `SyntaxContext::apply_mark`, so we ignore prepended opaque marks. . // FIXME: This is only a guess and it doesn't work correctly for `macro_rules!` . // definitions actually produced by `macro` and `macro` definitions produced by . // `macro_rules!`, but at least such configurations are not stable yet. 4,504 ( 0.00%) ctxt = ctxt.normalize_to_macro_rules(); . debug!( . "resolve_crate_root: marks={:?}", . ctxt.marks().into_iter().map(|(i, t)| (i.expn_data(), t)).collect::>() . ); 4,504 ( 0.00%) let mut iter = ctxt.marks().into_iter().rev().peekable(); . let mut result = None; . // Find the last opaque mark from the end if it exists. 10,215 ( 0.00%) while let Some(&(mark, transparency)) = iter.peek() { . if transparency == Transparency::Opaque { . result = Some(mark); . iter.next(); . } else { . break; . } . } . debug!( . "resolve_crate_root: found opaque mark {:?} {:?}", . result, . result.map(|r| r.expn_data()) . ); . // Then find the last semi-transparent mark from the end if it exists. 6,756 ( 0.00%) for (mark, transparency) in iter { . if transparency == Transparency::SemiTransparent { . result = Some(mark); . } else { . break; . } . } . debug!( . "resolve_crate_root: found semi-transparent mark {:?} {:?}", . result, . result.map(|r| r.expn_data()) . ); . result . } else { . debug!("resolve_crate_root: not DollarCrate"); 41 ( 0.00%) ctxt = ctxt.normalize_to_macros_2_0(); 287 ( 0.00%) ctxt.adjust(ExpnId::root()) . }; 4,586 ( 0.00%) let module = match mark { 11,260 ( 0.00%) Some(def) => self.expn_def_scope(def), . None => { . debug!( . "resolve_crate_root({:?}): found no mark (ident.span = {:?})", . ident, ident.span . ); 82 ( 0.00%) return self.graph_root; . } . }; . let module = self.expect_module( . module.opt_def_id().map_or(LOCAL_CRATE, |def_id| def_id.krate).as_def_id(), . ); . debug!( . "resolve_crate_root({:?}): got module {:?} ({:?}) (ident.span = {:?})", . ident, . module, . module.kind.name(), . ident.span . ); . module 16,051 ( 0.00%) } . 18 ( 0.00%) fn resolve_self(&mut self, ctxt: &mut SyntaxContext, module: Module<'a>) -> Module<'a> { 4 ( 0.00%) let mut module = self.expect_module(module.nearest_parent_mod()); 8 ( 0.00%) while module.span.ctxt().normalize_to_macros_2_0() != *ctxt { . let parent = module.parent.unwrap_or_else(|| self.expn_def_scope(ctxt.remove_mark())); . module = self.expect_module(parent.nearest_parent_mod()); . } . module 18 ( 0.00%) } . . fn resolve_path( . &mut self, . path: &[Segment], . opt_ns: Option, // `None` indicates a module path in import . parent_scope: &ParentScope<'a>, . record_used: bool, . path_span: Span, . crate_lint: CrateLint, . ) -> PathResult<'a> { 927 ( 0.00%) self.resolve_path_with_ribs( . path, . opt_ns, . parent_scope, . record_used, . path_span, . crate_lint, . None, . ) . } . 21,540 ( 0.00%) fn resolve_path_with_ribs( . &mut self, . path: &[Segment], . opt_ns: Option, // `None` indicates a module path in import . parent_scope: &ParentScope<'a>, . record_used: bool, . path_span: Span, . crate_lint: CrateLint, . ribs: Option<&PerNS>>>, . ) -> PathResult<'a> { 1,436 ( 0.00%) let mut module = None; . let mut allow_super = true; . let mut second_binding = None; . . debug!( . "resolve_path(path={:?}, opt_ns={:?}, record_used={:?}, \ . path_span={:?}, crate_lint={:?})", . path, opt_ns, record_used, path_span, crate_lint, . ); . 14,028 ( 0.00%) for (i, &Segment { ident, id, has_generic_args: _ }) in path.iter().enumerate() { . debug!("resolve_path ident {} {:?} {:?}", i, ident, id); 15,437 ( 0.00%) let record_segment_res = |this: &mut Self, res| { 3,747 ( 0.00%) if record_used { 6,068 ( 0.00%) if let Some(id) = id { 2,424 ( 0.00%) if !this.partial_res_map.contains_key(&id) { 2,242 ( 0.00%) assert!(id != ast::DUMMY_NODE_ID, "Trying to resolve dummy id"); 4,484 ( 0.00%) this.record_partial_res(id, PartialRes::new(res)); . } . } . } 4,996 ( 0.00%) }; . 5,834 ( 0.00%) let is_last = i == path.len() - 1; 11,690 ( 0.00%) let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS }; 2,338 ( 0.00%) let name = ident.name; . 3,860 ( 0.00%) allow_super &= ns == TypeNS && (name == kw::SelfLower || name == kw::Super); . . if ns == TypeNS { 3,040 ( 0.00%) if allow_super && name == kw::Super { . let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0(); . let self_module = match i { . 0 => Some(self.resolve_self(&mut ctxt, parent_scope.module)), . _ => match module { . Some(ModuleOrUniformRoot::Module(module)) => Some(module), . _ => None, . }, . }; -- line 2270 ---------------------------------------- -- line 2279 ---------------------------------------- . let msg = "there are too many leading `super` keywords".to_string(); . return PathResult::Failed { . span: ident.span, . label: msg, . suggestion: None, . is_error_from_last_segment: false, . }; . } 3,044 ( 0.00%) if i == 0 { 2,532 ( 0.00%) if name == kw::SelfLower { 10 ( 0.00%) let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0(); . module = Some(ModuleOrUniformRoot::Module( 10 ( 0.00%) self.resolve_self(&mut ctxt, parent_scope.module), . )); . continue; . } 123 ( 0.00%) if name == kw::PathRoot && ident.span.rust_2018() { . module = Some(ModuleOrUniformRoot::ExternPrelude); . continue; . } 246 ( 0.00%) if name == kw::PathRoot && ident.span.rust_2015() && self.session.rust_2018() { . // `::a::b` from 2015 macro on 2018 global edition . module = Some(ModuleOrUniformRoot::CrateRootAndExternPrelude); . continue; . } . if name == kw::PathRoot || name == kw::Crate || name == kw::DollarCrate { . // `::a::b`, `crate::a::b` or `$crate::a::b` 1,524 ( 0.00%) module = Some(ModuleOrUniformRoot::Module(self.resolve_crate_root(ident))); . continue; . } . } . } . . // Report special messages for path segment keywords in wrong positions. 10,053 ( 0.00%) if ident.is_path_segment_keyword() && i != 0 { . let name_str = if name == kw::PathRoot { . "crate root".to_string() . } else { . format!("`{}`", name) . }; . let label = if i == 1 && path[0].ident.name == kw::PathRoot { . format!("global paths cannot start with {}", name_str) . } else { -- line 2321 ---------------------------------------- -- line 2328 ---------------------------------------- . is_error_from_last_segment: false, . }; . } . . enum FindBindingResult<'a> { . Binding(Result<&'a NameBinding<'a>, Determinacy>), . PathResult(PathResult<'a>), . } 62,560 ( 0.01%) let find_binding_in_ns = |this: &mut Self, ns| { 8,722 ( 0.00%) let binding = if let Some(module) = module { . this.resolve_ident_in_module( . module, 2,706 ( 0.00%) ident, . ns, . parent_scope, 1,804 ( 0.00%) record_used, 902 ( 0.00%) path_span, . ) 6,318 ( 0.00%) } else if ribs.is_none() || opt_ns.is_none() || opt_ns == Some(MacroNS) { . let scopes = ScopeSet::All(ns, opt_ns.is_none()); . this.early_resolve_ident_in_lexical_scope( . ident, . scopes, . parent_scope, . record_used, . record_used, . path_span, . ) . } else { 4,212 ( 0.00%) let record_used_id = if record_used { 920 ( 0.00%) crate_lint.node_id().or(Some(CRATE_NODE_ID)) . } else { . None . }; 14,739 ( 0.00%) match this.resolve_ident_in_lexical_scope( 3,159 ( 0.00%) ident, . ns, 1,053 ( 0.00%) parent_scope, . record_used_id, 2,106 ( 0.00%) path_span, . &ribs.unwrap()[ns], . ) { . // we found a locally-imported or available item/module 1,194 ( 0.00%) Some(LexicalScopeBinding::Item(binding)) => Ok(binding), . // we found a local variable or type param . Some(LexicalScopeBinding::Res(res)) 1,056 ( 0.00%) if opt_ns == Some(TypeNS) || opt_ns == Some(ValueNS) => . { 4,752 ( 0.00%) record_segment_res(this, res); 4,224 ( 0.00%) return FindBindingResult::PathResult(PathResult::NonModule( 3,696 ( 0.00%) PartialRes::with_unresolved_segments(res, path.len() - 1), . )); . } 381 ( 0.00%) _ => Err(Determinacy::determined(record_used)), . } . }; 9,989 ( 0.00%) FindBindingResult::Binding(binding) 15,640 ( 0.00%) }; 13,685 ( 0.00%) let binding = match find_binding_in_ns(self, ns) { 7,392 ( 0.00%) FindBindingResult::PathResult(x) => return x, . FindBindingResult::Binding(binding) => binding, . }; 3,235 ( 0.00%) match binding { . Ok(binding) => { 6,500 ( 0.00%) if i == 1 { . second_binding = Some(binding); . } . let res = binding.res(); 12,640 ( 0.00%) let maybe_assoc = opt_ns != Some(MacroNS) && PathSource::Type.is_expected(res); . if let Some(next_module) = binding.module() { 1,442 ( 0.00%) module = Some(ModuleOrUniformRoot::Module(next_module)); 6,489 ( 0.00%) record_segment_res(self, res); 4,053 ( 0.00%) } else if res == Res::ToolMod && i + 1 != path.len() { . if binding.is_import() { . self.session . .struct_span_err( . ident.span, . "cannot use a tool module through an import", . ) . .span_note(binding.span, "the tool module imported here") . .emit(); . } . let res = Res::NonMacroAttr(NonMacroAttrKind::Tool); . return PathResult::NonModule(PartialRes::new(res)); 2,895 ( 0.00%) } else if res == Res::Err { . return PathResult::NonModule(PartialRes::new(Res::Err)); 1,737 ( 0.00%) } else if opt_ns.is_some() && (is_last || maybe_assoc) { 4,053 ( 0.00%) self.lint_if_path_starts_with_module( 1,158 ( 0.00%) crate_lint, . path, 579 ( 0.00%) path_span, . second_binding, . ); 1,737 ( 0.00%) return PathResult::NonModule(PartialRes::with_unresolved_segments( 2,316 ( 0.00%) res, 2,316 ( 0.00%) path.len() - i - 1, . )); . } else { . let label = format!( . "`{}` is {} {}, not a module", . ident, . res.article(), . res.descr(), . ); -- line 2431 ---------------------------------------- -- line 2433 ---------------------------------------- . return PathResult::Failed { . span: ident.span, . label, . suggestion: None, . is_error_from_last_segment: is_last, . }; . } . } 254 ( 0.00%) Err(Undetermined) => return PathResult::Indeterminate, . Err(Determined) => { . if let Some(ModuleOrUniformRoot::Module(module)) = module { . if opt_ns.is_some() && !module.is_normal() { . return PathResult::NonModule(PartialRes::with_unresolved_segments( . module.res().unwrap(), . path.len() - i, . )); . } -- line 2449 ---------------------------------------- -- line 2612 ---------------------------------------- . label, . suggestion, . is_error_from_last_segment: is_last, . }; . } . } . } . 2,222 ( 0.00%) self.lint_if_path_starts_with_module(crate_lint, path, path_span, second_binding); . 1,212 ( 0.00%) PathResult::Module(match module { 404 ( 0.00%) Some(module) => module, . None if path.is_empty() => ModuleOrUniformRoot::CurrentScope, . _ => span_bug!(path_span, "resolve_path: non-empty path `{:?}` has no module", path), . }) 12,924 ( 0.00%) } . 9,420 ( 0.00%) fn lint_if_path_starts_with_module( . &mut self, . crate_lint: CrateLint, . path: &[Segment], . path_span: Span, . second_binding: Option<&NameBinding<'_>>, . ) { 3,925 ( 0.00%) let (diag_id, diag_span) = match crate_lint { . CrateLint::No => return, . CrateLint::SimplePath(id) => (id, path_span), . CrateLint::UsePath { root_id, root_span } => (root_id, root_span), . CrateLint::QPathTrait { qpath_id, qpath_span } => (qpath_id, qpath_span), . }; . 743 ( 0.00%) let first_name = match path.get(0) { . // In the 2018 edition this lint is a hard error, so nothing to do 3,218 ( 0.00%) Some(seg) if seg.ident.span.rust_2015() && self.session.rust_2015() => seg.ident.name, . _ => return, . }; . . // We're only interested in `use` paths which should start with . // `{{root}}` currently. 1,299 ( 0.00%) if first_name != kw::PathRoot { . return; . } . . match path.get(1) { . // If this import looks like `crate::...` it's already good 37 ( 0.00%) Some(Segment { ident, .. }) if ident.name == kw::Crate => return, . // Otherwise go below to see if it's an extern crate . Some(_) => {} . // If the path has length one (and it's `PathRoot` most likely) . // then we don't know whether we're gonna be importing a crate or an . // item in our crate. Defer this lint to elsewhere . None => return, . } . . // If the first element of our path was actually resolved to an . // `ExternCrate` (also used for `crate::...`) then no need to issue a . // warning, this looks all good! 74 ( 0.00%) if let Some(binding) = second_binding { 98 ( 0.00%) if let NameBindingKind::Import { import, .. } = binding.kind { . // Careful: we still want to rewrite paths from renamed extern crates. 88 ( 0.00%) if let ImportKind::ExternCrate { source: None, .. } = import.kind { . return; . } . } . } . . let diag = BuiltinLintDiagnostics::AbsPathWithModule(diag_span); 17 ( 0.00%) self.lint_buffer.buffer_lint_with_diagnostic( 34 ( 0.00%) lint::builtin::ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE, . diag_id, . diag_span, . "absolute paths must start with `self`, `super`, \ . `crate`, or an external crate name in the 2018 edition", 51 ( 0.00%) diag, . ); 6,280 ( 0.00%) } . . // Validate a local resolution (from ribs). . fn validate_res_from_ribs( . &mut self, . rib_index: usize, . rib_ident: Ident, . mut res: Res, . record_used: bool, . span: Span, . original_rib_ident_def: Ident, . all_ribs: &[Rib<'a>], . ) -> Res { . const CG_BUG_STR: &str = "min_const_generics resolve check didn't stop compilation"; . debug!("validate_res_from_ribs({:?})", res); 1,320 ( 0.00%) let ribs = &all_ribs[rib_index + 1..]; . . // An invalid forward use of a generic parameter from a previous default. 2,640 ( 0.00%) if let ForwardGenericParamBanRibKind = all_ribs[rib_index].kind { . if record_used { . let res_error = if rib_ident.name == kw::SelfUpper { . ResolutionError::SelfInGenericParamDefault . } else { . ResolutionError::ForwardDeclaredGenericParam . }; . self.report_error(span, res_error); . } . assert_eq!(res, Res::Err); . return Res::Err; . } . 4,547 ( 0.00%) match res { . Res::Local(_) => { . use ResolutionError::*; 442 ( 0.00%) let mut res_err = None; . . for rib in ribs { 3,576 ( 0.00%) match rib.kind { . NormalRibKind . | ClosureOrAsyncRibKind . | ModuleRibKind(..) . | MacroDefinition(..) . | ForwardGenericParamBanRibKind => { . // Nothing to do. Continue. . } . ItemRibKind(_) | FnItemRibKind | AssocItemRibKind => { . // This was an attempt to access an upvar inside a . // named function item. This is not allowed, so we . // report an error. 319 ( 0.00%) if record_used { . // We don't immediately trigger a resolve error, because . // we want certain other resolution errors (namely those . // emitted for `ConstantItemRibKind` below) to take . // precedence. . res_err = Some(CannotCaptureDynamicEnvironmentInFnItem); . } . } . ConstantItemRibKind(_, item) => { -- line 2744 ---------------------------------------- -- line 2773 ---------------------------------------- . ConstParamTyRibKind => { . if record_used { . self.report_error(span, ParamInTyOfConstParam(rib_ident.name)); . } . return Res::Err; . } . } . } 638 ( 0.00%) if let Some(res_err) = res_err { . self.report_error(span, res_err); . return Res::Err; . } . } . Res::Def(DefKind::TyParam, _) | Res::SelfTy(..) => { . for rib in ribs { 2,217 ( 0.00%) let has_generic_params: HasGenericParams = match rib.kind { . NormalRibKind . | ClosureOrAsyncRibKind . | AssocItemRibKind . | ModuleRibKind(..) . | MacroDefinition(..) . | ForwardGenericParamBanRibKind => { . // Nothing to do. Continue. . continue; . } . 8 ( 0.00%) ConstantItemRibKind(trivial, _) => { . let features = self.session.features_untracked(); . // HACK(min_const_generics): We currently only allow `N` or `{ N }`. 16 ( 0.00%) if !(trivial || features.generic_const_exprs) { . // HACK(min_const_generics): If we encounter `Self` in an anonymous constant . // we can't easily tell if it's generic at this stage, so we instead remember . // this and then enforce the self type to be concrete later on. . if let Res::SelfTy(trait_def, Some((impl_def, _))) = res { 207 ( 0.00%) res = Res::SelfTy(trait_def, Some((impl_def, true))); . } else { . if record_used { . self.report_error( . span, . ResolutionError::ParamInNonTrivialAnonConst { . name: rib_ident.name, . is_type: true, . }, -- line 2815 ---------------------------------------- -- line 2912 ---------------------------------------- . ), . ); . } . return Res::Err; . } . } . _ => {} . } 2,640 ( 0.00%) res . } . . fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) { . debug!("(recording res) recording {:?} for {}", resolution, node_id); 6,100 ( 0.00%) if let Some(prev_res) = self.partial_res_map.insert(node_id, resolution) { . panic!("path resolved multiple times ({:?} before, {:?} now)", prev_res, resolution); . } . } . . fn record_pat_span(&mut self, node: NodeId, span: Span) { . debug!("(recording pat) recording {:?} for {:?}", node, span); . self.pat_span_map.insert(node, span); . } . . fn is_accessible_from(&self, vis: ty::Visibility, module: Module<'a>) -> bool { 13,624 ( 0.00%) vis.is_accessible_from(module.nearest_parent_mod(), self) . } . . fn set_binding_parent_module(&mut self, binding: &'a NameBinding<'a>, module: Module<'a>) { 4,700 ( 0.00%) if let Some(old_module) = self.binding_parent_modules.insert(PtrKey(binding), module) { . if !ptr::eq(module, old_module) { . span_bug!(binding.span, "parent module is reset for binding"); . } . } . } . . fn disambiguate_macro_rules_vs_modularized( . &self, -- line 2948 ---------------------------------------- -- line 2959 ---------------------------------------- . (Some(macro_rules), Some(modularized)) => { . macro_rules.nearest_parent_mod() == modularized.nearest_parent_mod() . && modularized.is_ancestor_of(macro_rules) . } . _ => false, . } . } . 7 ( 0.00%) fn report_errors(&mut self, krate: &Crate) { . self.report_with_use_injections(krate); . 6 ( 0.00%) for &(span_use, span_def) in &self.macro_expanded_macro_export_errors { . let msg = "macro-expanded `macro_export` macros from the current crate \ . cannot be referred to by absolute paths"; . self.lint_buffer.buffer_lint_with_diagnostic( . lint::builtin::MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS, . CRATE_NODE_ID, . span_use, . msg, . BuiltinLintDiagnostics::MacroExpandedMacroExportsAccessedByAbsolutePaths(span_def), -- line 2978 ---------------------------------------- -- line 2984 ---------------------------------------- . } . . let mut reported_spans = FxHashSet::default(); . for error in &self.privacy_errors { . if reported_spans.insert(error.dedup_span) { . self.report_privacy_error(error); . } . } 8 ( 0.00%) } . . fn report_with_use_injections(&mut self, krate: &Crate) { . for UseError { mut err, candidates, def_id, instead, suggestion } in 10 ( 0.00%) self.use_injections.drain(..) . { . let (span, found_use) = if let Some(def_id) = def_id.as_local() { . UsePlacementFinder::check(krate, self.def_id_to_node_id[def_id]) . } else { . (None, false) . }; . if !candidates.is_empty() { . diagnostics::show_candidates( -- line 3004 ---------------------------------------- -- line 3284 ---------------------------------------- . } . . return; . } . . err.span_suggestion(span, message, String::new(), Applicability::MachineApplicable); . } . 910 ( 0.00%) fn extern_prelude_get( . &mut self, . ident: Ident, . speculative: bool, . ) -> Option<&'a NameBinding<'a>> { 455 ( 0.00%) if ident.is_path_segment_keyword() { . // Make sure `self`, `super` etc produce an error when passed to here. . return None; . } 819 ( 0.00%) self.extern_prelude.get(&ident.normalize_to_macros_2_0()).cloned().and_then(|entry| { . if let Some(binding) = entry.extern_crate_item { . if !speculative && entry.introduced_by_item { . self.record_use(ident, binding, false); . } . Some(binding) . } else { . let crate_id = if !speculative { . let Some(crate_id) = -- line 3309 ---------------------------------------- -- line 3314 ---------------------------------------- . }; . let crate_root = self.expect_module(crate_id.as_def_id()); . Some( . (crate_root, ty::Visibility::Public, DUMMY_SP, LocalExpnId::ROOT) . .to_name_binding(self.arenas), . ) . } . }) 728 ( 0.00%) } . . /// Rustdoc uses this to resolve things in a recoverable way. `ResolutionError<'a>` . /// isn't something that can be returned because it can't be made to live that long, . /// and also it's a private type. Fortunately rustdoc doesn't need to know the error, . /// just that an error occurred. . // FIXME(Manishearth): intra-doc links won't get warned of epoch changes. . pub fn resolve_str_path_error( . &mut self, -- line 3330 ---------------------------------------- -- line 3422 ---------------------------------------- . #[inline] . pub fn opt_span(&self, def_id: DefId) -> Option { . def_id.as_local().map(|def_id| self.definitions.def_span(def_id)) . } . . /// Checks if an expression refers to a function marked with . /// `#[rustc_legacy_const_generics]` and returns the argument index list . /// from the attribute. 2,784 ( 0.00%) pub fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option> { 1,392 ( 0.00%) if let ExprKind::Path(None, path) = &expr.kind { . // Don't perform legacy const generics rewriting if the path already . // has generic arguments. 348 ( 0.00%) if path.segments.last().unwrap().args.is_some() { . return None; . } . . let partial_res = self.partial_res_map.get(&expr.id)?; 696 ( 0.00%) if partial_res.unresolved_segments() != 0 { . return None; . } . 752 ( 0.00%) if let Res::Def(def::DefKind::Fn, def_id) = partial_res.base_res() { . // We only support cross-crate argument rewriting. Uses . // within the same crate should be updated to use the new . // const generics style. 34 ( 0.00%) if def_id.is_local() { . return None; . } . . if let Some(v) = self.legacy_const_generic_args.get(&def_id) { . return v.clone(); . } . 156 ( 0.00%) let attr = self . .cstore() 52 ( 0.00%) .item_attrs_untracked(def_id, self.session) . .find(|a| a.has_name(sym::rustc_legacy_const_generics))?; . let mut ret = Vec::new(); . for meta in attr.meta_item_list()? { . match meta.literal()?.kind { . LitKind::Int(a, _) => ret.push(a as usize), . _ => panic!("invalid arg index"), . } . } . // Cache the lookup to avoid parsing attributes for an iterm multiple times. . self.legacy_const_generic_args.insert(def_id, Some(ret.clone())); . return Some(ret); . } . } . None 3,132 ( 0.00%) } . 7 ( 0.00%) fn resolve_main(&mut self) { 2 ( 0.00%) let module = self.graph_root; . let ident = Ident::with_dummy_span(sym::main); . let parent_scope = &ParentScope::module(module, self); . . let name_binding = match self.resolve_ident_in_module( . ModuleOrUniformRoot::Module(module), . ident, . ValueNS, . parent_scope, -- line 3483 ---------------------------------------- -- line 3490 ---------------------------------------- . . let res = name_binding.res(); . let is_import = name_binding.is_import(); . let span = name_binding.span; . if let Res::Def(DefKind::Fn, _) = res { . self.record_use(ident, name_binding, false); . } . self.main_def = Some(MainDefinition { res, is_import, span }); 8 ( 0.00%) } . } . . fn names_to_string(names: &[Symbol]) -> String { . let mut result = String::new(); . for (i, name) in names.iter().filter(|name| **name != kw::PathRoot).enumerate() { . if i > 0 { . result.push_str("::"); . } -- line 3506 ---------------------------------------- -- line 3558 ---------------------------------------- . /// This is the "trait item" from a fully qualified path. For example, . /// we might be resolving `X::Y::Z` from a path like `::Z`. . /// The `path_span` is the span of the to the trait itself (`X::Y`). . QPathTrait { qpath_id: NodeId, qpath_span: Span }, . } . . impl CrateLint { . fn node_id(&self) -> Option { 2,760 ( 0.00%) match *self { . CrateLint::No => None, . CrateLint::SimplePath(id) . | CrateLint::UsePath { root_id: id, .. } . | CrateLint::QPathTrait { qpath_id: id, .. } => Some(id), . } . } . } . . pub fn provide(providers: &mut Providers) { . late::lifetimes::provide(providers); 1 ( 0.00%) } 308,822 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/iter/adapters/take.rs -------------------------------------------------------------------------------- Ir -- line 27 ---------------------------------------- . impl Iterator for Take . where . I: Iterator, . { . type Item = ::Item; . . #[inline] . fn next(&mut self) -> Option<::Item> { 2,152,058 ( 0.19%) if self.n != 0 { 531 ( 0.00%) self.n -= 1; . self.iter.next() . } else { . None . } . } . . #[inline] . fn nth(&mut self, n: usize) -> Option { -- line 44 ---------------------------------------- -- line 51 ---------------------------------------- . self.n = 0; . } . None . } . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 704 ( 0.00%) if self.n == 0 { . return (0, Some(0)); . } . . let (lower, upper) = self.iter.size_hint(); . . let lower = cmp::min(lower, self.n); . 176 ( 0.00%) let upper = match upper { . Some(x) if x < self.n => Some(x), . _ => Some(self.n), . }; . . (lower, upper) . } . . #[inline] -- line 75 ---------------------------------------- -- line 79 ---------------------------------------- . Fold: FnMut(Acc, Self::Item) -> R, . R: Try, . { . fn check<'a, T, Acc, R: Try>( . n: &'a mut usize, . mut fold: impl FnMut(Acc, T) -> R + 'a, . ) -> impl FnMut(Acc, T) -> ControlFlow + 'a { . move |acc, x| { 312 ( 0.00%) *n -= 1; 68 ( 0.00%) let r = fold(acc, x); 486 ( 0.00%) if *n == 0 { ControlFlow::Break(r) } else { ControlFlow::from_try(r) } . } . } . 1,956 ( 0.00%) if self.n == 0 { . try { init } . } else { . let n = &mut self.n; . self.iter.try_fold(init, check(n, fold)).into_try() . } . } . . #[inline] -- line 101 ---------------------------------------- 31,154 ( 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. 436,883 ( 0.04%) #[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")] 481 ( 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 { 721,846 ( 0.06%) 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> { 1,229,840 ( 0.11%) match *self { . Some(ref x) => Some(x), . None => None, . } . } . . /// Converts from `&mut Option` to `Option<&mut T>`. . /// . /// # Examples -- line 632 ---------------------------------------- -- line 638 ---------------------------------------- . /// None => {}, . /// } . /// assert_eq!(x, Some(42)); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] . pub const fn as_mut(&mut self) -> Option<&mut T> { 159,332 ( 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 { 277,785 ( 0.02%) match self { 58,966 ( 0.01%) Some(val) => val, . None => expect_failed(msg), . } . } . . /// Returns the contained [`Some`] value, consuming the `self` value. . /// . /// Because this function may panic, its use is generally discouraged. . /// Instead, prefer to use pattern matching and handle the [`None`] -- line 722 ---------------------------------------- -- line 742 ---------------------------------------- . /// let x: Option<&str> = None; . /// assert_eq!(x.unwrap(), "air"); // fails . /// ``` . #[inline] . #[track_caller] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] . pub const fn unwrap(self) -> T { 2,467,996 ( 0.22%) match self { 175,803 ( 0.02%) 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, . { 176,205 ( 0.02%) match self { . Some(x) => x, 22,824 ( 0.00%) None => default, . } 333 ( 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")] 23 ( 0.00%) pub const fn unwrap_or_else(self, f: F) -> T . where . F: ~const FnOnce() -> T, . F: ~const Drop, . { 186,178 ( 0.02%) match self { 46,511 ( 0.00%) Some(x) => x, 1,134 ( 0.00%) None => f(), . } 49 ( 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, . { 1,114 ( 0.00%) match self { 708 ( 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")] 15,043 ( 0.00%) pub const fn map(self, f: F) -> Option . where . F: ~const FnOnce(T) -> U, . F: ~const Drop, . { 550,321 ( 0.05%) match self { 444,651 ( 0.04%) Some(x) => Some(f(x)), 20,827 ( 0.00%) None => None, . } 56,396 ( 0.01%) } . . /// 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, . { 146,034 ( 0.01%) match self { 7,322 ( 0.00%) Some(t) => f(t), 1,174 ( 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, . { 1,953 ( 0.00%) match self { 101 ( 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, . { 257,708 ( 0.02%) match self { 488 ( 0.00%) Some(v) => Ok(v), 242 ( 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 1054 ---------------------------------------- . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn ok_or_else(self, err: F) -> Result . where . F: ~const FnOnce() -> E, . F: ~const Drop, . { 12,122 ( 0.00%) match self { 8,966 ( 0.00%) Some(v) => Ok(v), 3,001 ( 0.00%) None => Err(err()), . } . } . . /// 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`]. . /// -- line 1072 ---------------------------------------- -- 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, . { 2,685 ( 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")] 196 ( 0.00%) pub const fn and_then(self, f: F) -> Option . where . F: ~const FnOnce(T) -> Option, . F: ~const Drop, . { 47,549 ( 0.00%) match self { 3,731 ( 0.00%) Some(x) => f(x), . None => None, . } 6,689 ( 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, . { 1,833 ( 0.00%) if let Some(x) = self { 1,029 ( 0.00%) if predicate(&x) { . return Some(x); . } . } . None 228 ( 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, . { 1,458 ( 0.00%) match self { 28 ( 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, . { 6,528 ( 0.00%) match self { 3,054 ( 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, . { 9,615 ( 0.00%) if let None = *self { 22,435 ( 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, . { 59,757 ( 0.01%) if let None = *self { . // the compiler isn't smart enough to know that we are not dropping a `T` . // here and wants us to ensure `T` can be dropped at compile time. . mem::forget(mem::replace(self, Some(f()))) . } . . // SAFETY: a `None` variant for `self` would have been replaced by a `Some` . // variant in the code above. . unsafe { self.as_mut().unwrap_unchecked() } -- line 1515 ---------------------------------------- -- line 1558 ---------------------------------------- . /// let old = x.replace(3); . /// assert_eq!(x, Some(3)); . /// assert_eq!(old, None); . /// ``` . #[inline] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] . #[stable(feature = "option_replace", since = "1.31.0")] . pub const fn replace(&mut self, value: T) -> Option { 568 ( 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 6,461 ( 0.00%) match self { 91,204 ( 0.01%) Some(&v) => Some(v), 316 ( 0.00%) None => None, . } 6 ( 0.00%) } . . /// Maps an `Option<&T>` to an `Option` by cloning the contents of the . /// option. . /// . /// # Examples . /// . /// ``` . /// let x = 12; -- line 1732 ---------------------------------------- -- line 1733 ---------------------------------------- . /// let opt_x = Some(&x); . /// assert_eq!(opt_x, Some(&12)); . /// let cloned = opt_x.cloned(); . /// assert_eq!(cloned, Some(12)); . /// ``` . #[must_use = "`self` will be dropped if the result is not used"] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_cloned", issue = "91582")] 4,590 ( 0.00%) pub const fn cloned(self) -> Option . where . T: ~const Clone, . { 283,549 ( 0.03%) match self { 814,145 ( 0.07%) Some(t) => Some(t.clone()), 118,212 ( 0.01%) None => None, . } 10,165 ( 0.00%) } . } . . impl Option<&mut T> { . /// Maps an `Option<&mut T>` to an `Option` by copying the contents of the . /// option. . /// . /// # Examples . /// -- line 1757 ---------------------------------------- -- line 1843 ---------------------------------------- . ///////////////////////////////////////////////////////////////////////////// . // Trait implementations . ///////////////////////////////////////////////////////////////////////////// . . #[stable(feature = "rust1", since = "1.0.0")] . impl Clone for Option { . #[inline] . fn clone(&self) -> Self { 1,911,339 ( 0.17%) match self { 166,316 ( 0.01%) Some(x) => Some(x.clone()), 168,682 ( 0.01%) None => None, . } 311,027 ( 0.03%) } . . #[inline] . fn clone_from(&mut self, source: &Self) { . match (self, source) { . (Some(to), Some(from)) => to.clone_from(from), . (to, from) => *to = from.clone(), . } . } -- line 1863 ---------------------------------------- -- line 2006 ---------------------------------------- . . #[inline] . fn next(&mut self) -> Option { . self.opt.take() . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 9,423 ( 0.00%) match self.opt { . Some(_) => (1, Some(1)), . None => (0, Some(0)), . } . } . } . . impl DoubleEndedIterator for Item { . #[inline] -- line 2022 ---------------------------------------- -- 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) 710 ( 0.00%) } . . #[inline] . fn branch(self) -> ControlFlow { 107,550 ( 0.01%) match self { 17,298 ( 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 { 11,762 ( 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 { 18 ( 0.00%) match self { 99 ( 0.00%) Some(inner) => inner, . None => None, . } . } . } 1,331,592 ( 0.12%) -------------------------------------------------------------------------------- -- 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; 80,757 ( 0.01%) fn to_owned(&self) -> T { 8 ( 0.00%) self.clone() 81,751 ( 0.01%) } . . 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 { 354,214 ( 0.03%) match *self { 8,973 ( 0.00%) Borrowed(borrowed) => { 62,919 ( 0.01%) *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")] 56 ( 0.00%) pub fn into_owned(self) -> ::Owned { 1,582 ( 0.00%) match self { 2,480 ( 0.00%) Borrowed(borrowed) => borrowed.to_owned(), 77 ( 0.00%) Owned(owned) => owned, . } 63 ( 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 { 1,194,504 ( 0.11%) 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 { 420 ( 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 ---------------------------------------- 144,167 ( 0.01%) -------------------------------------------------------------------------------- The following files chosen for auto-annotation could not be found: -------------------------------------------------------------------------------- ./elf/../sysdeps/x86_64/dl-machine.h ./elf/dl-lookup.c ./elf/do-rel.h ./malloc/malloc.c ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S -------------------------------------------------------------------------------- Ir -------------------------------------------------------------------------------- 595,761,434 (52.86%) events annotated