-------------------------------------------------------------------------------- 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 bitflags --edition=2018 src/lib.rs --error-format=json --json=diagnostic-rendered-ansi,artifacts,future-incompat --crate-type lib --emit=dep-info,metadata,link -C opt-level=3 -C embed-bitcode=no --cfg feature="default" -C metadata=8e11aa371eb748c3 -C extra-filename=-8e11aa371eb748c3 --out-dir /usr/home/liquid/tmp/.tmpQEETJ2/target/release/deps -L dependency=/usr/home/liquid/tmp/.tmpQEETJ2/target/release/deps -Adeprecated -Aunknown-lints -Zincremental-verify-ich Data file: results/cgout-w-profiling-bitflags-1.3.2-Opt-Full Events recorded: Ir Events shown: Ir Event sort order: Ir Thresholds: 0.1 Include dirs: User annotated: Auto-annotation: on -------------------------------------------------------------------------------- Ir -------------------------------------------------------------------------------- 73,155,707 (100.0%) PROGRAM TOTALS -------------------------------------------------------------------------------- Ir file:function -------------------------------------------------------------------------------- 10,308,534 (14.09%) ./elf/dl-lookup.c:_dl_lookup_symbol_x 4,843,695 ( 6.62%) ./elf/dl-lookup.c:do_lookup_x 4,141,271 ( 5.66%) ./elf/../sysdeps/x86_64/dl-machine.h:_dl_relocate_object 2,266,423 ( 3.10%) ./malloc/malloc.c:_int_malloc 2,139,033 ( 2.92%) ./elf/do-rel.h:_dl_relocate_object 1,990,381 ( 2.72%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_serialize/src/opaque.rs:>::decode 1,671,154 ( 2.28%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:>::decode 1,619,973 ( 2.21%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:>::decode 1,493,398 ( 2.04%) ./malloc/malloc.c:_int_free 1,437,784 ( 1.97%) ???:SetImpliedBits(llvm::FeatureBitset&, llvm::FeatureBitset const&, llvm::ArrayRef) 1,041,513 ( 1.42%) ./malloc/malloc.c:malloc 866,116 ( 1.18%) ./elf/dl-lookup.c:check_match 811,467 ( 1.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/mod.rs:::next_token 763,510 ( 1.04%) ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:__memcpy_avx_unaligned_erms 723,023 ( 0.99%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:, >::decode::{closure#0}>, ::imported_source_files::{closure#3}::{closure#0}> as core::iter::traits::iterator::Iterator>::fold::<(), core::iter::traits::iterator::Iterator::for_each::call as alloc::vec::spec_extend::SpecExtend, >::decode::{closure#0}>, ::imported_source_files::{closure#3}::{closure#0}>>>::spec_extend::{closure#0}>::{closure#0}> 720,640 ( 0.99%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:::new_imported_source_file 719,048 ( 0.98%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:::new_imported_source_file 656,578 ( 0.90%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::next 645,591 ( 0.88%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lexer/src/lib.rs:::advance_token 645,520 ( 0.88%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::bump 641,989 ( 0.88%) ???:llvm::PassRegistry::enumerateWith(llvm::PassRegistrationListener*) 622,893 ( 0.85%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/tokentrees.rs:::parse_token_tree 531,119 ( 0.73%) ./string/../sysdeps/x86_64/strcmp.S:strcmp 520,505 ( 0.71%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_metadata/src/rmeta/decoder.rs:, >::decode::{closure#0}>, ::imported_source_files::{closure#3}::{closure#0}> as core::iter::traits::iterator::Iterator>::fold::<(), core::iter::traits::iterator::Iterator::for_each::call as alloc::vec::spec_extend::SpecExtend, >::decode::{closure#0}>, ::imported_source_files::{closure#3}::{closure#0}>>>::spec_extend::{closure#0}>::{closure#0}> 501,924 ( 0.69%) ???:llvm::StringMapImpl::LookupBucketFor(llvm::StringRef) 488,495 ( 0.67%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/tokenstream.rs:::next_with_spacing 482,636 ( 0.66%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/tokenstream.rs:::next 482,195 ( 0.66%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs:::short_write_process_buffer:: 479,637 ( 0.66%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:, >::decode::{closure#0}>, ::imported_source_files::{closure#3}::{closure#0}> as core::iter::traits::iterator::Iterator>::fold::<(), core::iter::traits::iterator::Iterator::for_each::call as alloc::vec::spec_extend::SpecExtend, >::decode::{closure#0}>, ::imported_source_files::{closure#3}::{closure#0}>>>::spec_extend::{closure#0}>::{closure#0}> 453,718 ( 0.62%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::clone 421,654 ( 0.58%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/caching_source_map_view.rs:::span_data_to_lines_and_cols 384,273 ( 0.53%) ./malloc/malloc.c:free 328,125 ( 0.45%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/md-5-0.9.1/src/utils.rs:md5::utils::compress 323,460 ( 0.44%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs:::short_write_process_buffer:: 292,825 ( 0.40%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::bump_with 287,000 ( 0.39%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs:md5::utils::compress 284,955 ( 0.39%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:>::hash_stable 270,416 ( 0.37%) ./string/../sysdeps/x86_64/multiarch/memcmp-avx2-movbe.S:__memcmp_avx2_movbe 269,339 ( 0.37%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/tokentrees.rs:::push 254,599 ( 0.35%) ???:llvm::PMTopLevelManager::setLastUser(llvm::ArrayRef, llvm::Pass*) 252,811 ( 0.35%) ./malloc/malloc.c:malloc_consolidate 252,524 ( 0.35%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/source_map.rs:::new_imported_source_file 241,932 ( 0.33%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs:>::hash_stable 238,468 ( 0.33%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/iter/range.rs:>::decode 238,468 ( 0.33%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:>::decode 238,468 ( 0.33%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cmp.rs:>::decode 238,190 ( 0.33%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/str/validations.rs:::advance_token 232,355 ( 0.32%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:::enter_lint_attrs 226,005 ( 0.31%) ???:llvm::PMTopLevelManager::AUFoldingSetNode::Profile(llvm::FoldingSetNodeID&, llvm::AnalysisUsage const&) 224,335 ( 0.31%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:::advance_token 221,269 ( 0.30%) ./stdlib/cxa_finalize.c:__cxa_finalize 211,360 ( 0.29%) ???:(anonymous namespace)::GetCFGOnlyPasses::passEnumerate(llvm::PassInfo const*) [clone .llvm.764396836974782617] 197,820 ( 0.27%) ./malloc/malloc.c:unlink_chunk.constprop.0 187,408 ( 0.26%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:>::truncate 184,406 ( 0.25%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/rustc-hash-1.1.0/src/lib.rs:<&str as core::hash::Hash>::hash:: 183,647 ( 0.25%) ???:llvm::StringMapImpl::RehashTable(unsigned int) 183,389 ( 0.25%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/str/mod.rs:::next_token 177,727 ( 0.24%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::check 166,467 ( 0.23%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs:> as core::ops::drop::Drop>::drop 165,385 ( 0.23%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::eq 159,651 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/mod.rs:::span_data_to_lines_and_cols 158,841 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::ident 158,510 ( 0.22%) ./malloc/malloc.c:realloc 158,097 ( 0.22%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>::insert::>::{closure#0}> 157,426 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:::next_token 154,468 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/attr/mod.rs:::enter_lint_attrs 151,680 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_metadata/src/rmeta/encoder.rs:>::encode 144,936 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::is_keyword 138,162 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lint/src/builtin.rs:::check_tokens 137,251 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/str/traits.rs:::next_token 128,353 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::next_desugared 119,191 ( 0.16%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/unicode-xid-0.2.2/src/lib.rs:::eat_while:: 117,519 ( 0.16%) ???:llvm::AnalysisUsage::pushUnique(llvm::SmallVectorImpl&, void const*) 114,173 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/memchr.rs:core::slice::memchr::memchr_general_case 113,614 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::clone 113,246 ( 0.15%) ./stdio-common/vfscanf-internal.c:__vfscanf_internal 112,907 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/span_encoding.rs:::next_token 112,565 ( 0.15%) ./malloc/malloc.c:_int_realloc 110,244 ( 0.15%) ???:llvm::PMDataManager::removeNotPreservedAnalysis(llvm::Pass*) 109,513 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/option.rs:::next_token 106,751 ( 0.15%) ./string/../sysdeps/x86_64/multiarch/memset-vec-unaligned-erms.S:__memset_avx2_erms 105,418 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe/quoted.rs:rustc_expand::mbe::quoted::parse 105,417 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:::bump_with 104,961 ( 0.14%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs:>>::insert 104,672 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/span_encoding.rs:::to 101,629 ( 0.14%) ???:llvm::BitstreamCursor::readRecord(unsigned int, llvm::SmallVectorImpl&, llvm::StringRef*) 100,179 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs:>::hash_stable 99,926 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs:::slice_write_process_buffer 99,736 ( 0.14%) ???:llvm::X86_MC::initLLVMToSEHAndCVRegMapping(llvm::MCRegisterInfo*) 99,056 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lexer/src/lib.rs:rustc_lexer::first_token 98,738 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs:::slice_write_process_buffer 96,200 ( 0.13%) ???:llvm::PMTopLevelManager::findAnalysisUsage(llvm::Pass*) 95,517 ( 0.13%) ???:llvm::PassRegistry::registerPass(llvm::PassInfo const&, bool) 94,967 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/library/std/src/path.rs:::hash:: 93,646 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/tokenstream.rs:>::hash_stable 91,598 ( 0.13%) ???:(anonymous namespace)::CommandLineParser::addOption(llvm::cl::Option*, llvm::cl::SubCommand*) 87,924 ( 0.12%) ???:std::pair, bool> llvm::StringMap::try_emplace(llvm::StringRef, llvm::cl::Option*&&) 86,278 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:::eat_while:: 84,022 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cmp.rs:::hash:: 83,816 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/span_encoding.rs:>::hash_stable 83,747 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_serialize/src/leb128.rs:::read_u32 82,974 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:>::truncate 80,896 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_serialize/src/leb128.rs:>::encode 80,533 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:::to 80,454 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/str/validations.rs:::eat_while:: 79,102 ( 0.11%) ./string/../sysdeps/x86_64/multiarch/strlen-avx2.S:__strlen_avx2 78,471 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/std/src/sys/unix/alloc.rs:__rdl_alloc 77,846 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/symbol.rs:::intern 77,550 ( 0.11%) /tmp/gcc-build/x86_64-unknown-linux-gnu/libstdc++-v3/src/c++98/../../../../../gcc-5.5.0/libstdc++-v3/src/c++98/tree.cc:std::_Rb_tree_insert_and_rebalance(bool, std::_Rb_tree_node_base*, std::_Rb_tree_node_base*, std::_Rb_tree_node_base&) 76,841 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs: as core::ops::drop::Drop>::drop 76,009 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/span_encoding.rs:>::encode 75,097 ( 0.10%) /tmp/gcc-build/x86_64-unknown-linux-gnu/libstdc++-v3/libsupc++/../../../../gcc-5.5.0/libstdc++-v3/libsupc++/new_op.cc:operator new(unsigned long) 74,624 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:::from_lit_token 74,487 ( 0.10%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:::intern 73,559 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:> as core::ops::drop::Drop>::drop -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/unicode-xid-0.2.2/src/lib.rs -------------------------------------------------------------------------------- Ir -- line 70 ---------------------------------------- . /// mostly similar to 'ID_Continue' but modified for closure under NFKx. . fn is_xid_continue(self) -> bool; . } . . impl UnicodeXID for char { . #[inline] . fn is_xid_start(self) -> bool { . // Fast-path for ascii idents 42,120 ( 0.06%) ('a' <= self && self <= 'z') . || ('A' <= self && self <= 'Z') 11,674 ( 0.02%) || (self > '\x7f' && derived_property::XID_Start(self)) . } . . #[inline] . fn is_xid_continue(self) -> bool { . // Fast-path for ascii idents 95,398 ( 0.13%) ('a' <= self && self <= 'z') . || ('A' <= self && self <= 'Z') . || ('0' <= self && self <= '9') . || self == '_' 5,824 ( 0.01%) || (self > '\x7f' && derived_property::XID_Continue(self)) . } . } 18,153 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs -------------------------------------------------------------------------------- Ir -- line 180 ---------------------------------------- . /// assert_eq!(v, &[0.into()]); . /// . /// // Ensure that the last item was dropped. . /// assert!(weak.upgrade().is_none()); . /// ``` . #[stable(feature = "drop_in_place", since = "1.8.0")] . #[lang = "drop_in_place"] . #[allow(unconditional_recursion)] 427,711 ( 0.58%) 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 { 14 ( 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,804 ( 0.01%) copy_nonoverlapping(src, tmp.as_mut_ptr(), 1); 110,284 ( 0.15%) 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 { 553,859 ( 0.76%) 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 1207 ---------------------------------------- . // `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. . return wrapping_sub( 1,058 ( 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 { 30 ( 0.00%) 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 ---------------------------------------- 60,193 ( 0.08%) -------------------------------------------------------------------------------- -- 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}; . 3,412 ( 0.00%) #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub enum CommentKind { . Line, . Block, . } . 43 ( 0.00%) #[derive(Clone, PartialEq, Encodable, Decodable, Hash, Debug, Copy)] . #[derive(HashStable_Generic)] . pub enum BinOpToken { . Plus, . Minus, . Star, . Slash, . Percent, . Caret, . And, . Or, . Shl, . Shr, . } . . /// A delimiter token. 3,479 ( 0.00%) #[derive(Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug, Copy)] . #[derive(HashStable_Generic)] . pub enum DelimToken { . /// A round parenthesis (i.e., `(` or `)`). . Paren, . /// A square bracket (i.e., `[` or `]`). . Bracket, . /// A curly brace (i.e., `{` or `}`). . Brace, . /// An empty delimiter. . NoDelim, . } . 158 ( 0.00%) #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub enum LitKind { . Bool, // AST only, must never appear in a `Token` . Byte, . Char, . Integer, . Float, . Str, . StrRaw(u16), // raw string delimited by `n` hash symbols . ByteStr, . ByteStrRaw(u16), // raw byte string delimited by `n` hash symbols . Err, . } . . /// A literal token. 1,880 ( 0.00%) #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub struct Lit { . pub kind: LitKind, . pub symbol: Symbol, . pub suffix: Option, . } . . impl fmt::Display for Lit { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { -- line 78 ---------------------------------------- -- line 130 ---------------------------------------- . crate fn may_have_suffix(self) -> bool { . matches!(self, Integer | Float | Err) . } . } . . impl Lit { . pub fn new(kind: LitKind, symbol: Symbol, suffix: Option) -> Lit { . Lit { kind, symbol, suffix } 570 ( 0.00%) } . } . . pub fn ident_can_begin_expr(name: Symbol, span: Span, is_raw: bool) -> bool { . let ident_token = Token::new(Ident(name, is_raw), span); . . !ident_token.is_reserved_ident() . || ident_token.is_path_segment_keyword() . || [ -- line 146 ---------------------------------------- -- line 172 ---------------------------------------- . let ident_token = Token::new(Ident(name, is_raw), span); . . !ident_token.is_reserved_ident() . || ident_token.is_path_segment_keyword() . || [kw::Underscore, kw::For, kw::Impl, kw::Fn, kw::Unsafe, kw::Extern, kw::Typeof, kw::Dyn] . .contains(&name) . } . 603,716 ( 0.83%) #[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, 4,353 ( 0.01%) BinOp(BinOpToken), 159 ( 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., `{`). 2,907 ( 0.00%) OpenDelim(DelimToken), . /// A closing delimiter (e.g., `}`). 1,326 ( 0.00%) CloseDelim(DelimToken), . . /* Literals */ 2,634 ( 0.00%) Literal(Lit), . . /// Identifier token. . /// Do not forget about `NtIdent` when you want to match on identifiers. . /// It's recommended to use `Token::(ident,uninterpolate,uninterpolated_span)` to . /// treat regular and interpolated identifiers in the same way. 10,878 ( 0.01%) Ident(Symbol, /* is_raw */ bool), . /// Lifetime identifier token. . /// Do not forget about `NtLifetime` when you want to match on lifetime identifiers. . /// It's recommended to use `Token::(lifetime,uninterpolate,uninterpolated_span)` to . /// treat regular and interpolated lifetime identifiers in the same way. . Lifetime(Symbol), . . Interpolated(Lrc), . . /// A doc comment token. . /// `Symbol` is the doc comment's data excluding its "quotes" (`///`, `/**`, etc) . /// similarly to symbols in string literal tokens. 2,973 ( 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); . 137,381 ( 0.19%) #[derive(Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub struct Token { 1,140 ( 0.00%) pub kind: TokenKind, 24 ( 0.00%) pub span: Span, . } . . impl TokenKind { . pub fn lit(kind: LitKind, symbol: Symbol, suffix: Option) -> TokenKind { . Literal(Lit::new(kind, symbol, suffix)) 470 ( 0.00%) } . . // An approximation to proc-macro-style single-character operators used by rustc parser. . // If the operator token can be broken into two tokens, the first of which is single-character, . // then this function performs that operation, otherwise it returns `None`. 181 ( 0.00%) pub fn break_two_token_op(&self) -> Option<(TokenKind, TokenKind)> { 724 ( 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), 181 ( 0.00%) _ => return None, . }) 181 ( 0.00%) } . . /// Returns tokens that are likely to be typed accidentally instead of the current token. . /// Enables better error recovery when the wrong token is found. . pub fn similar_tokens(&self) -> Option> { . match *self { . Comma => Some(vec![Dot, Lt, Semi]), . Semi => Some(vec![Colon, Comma]), . FatArrow => Some(vec![Eq, RArrow]), -- line 298 ---------------------------------------- -- line 301 ---------------------------------------- . } . . pub fn should_end_const_arg(&self) -> bool { . matches!(self, Gt | Ge | BinOp(Shr) | BinOpEq(Shr)) . } . } . . impl Token { 9,186 ( 0.01%) pub fn new(kind: TokenKind, span: Span) -> Self { 27,717 ( 0.04%) Token { kind, span } 9,186 ( 0.01%) } . . /// Some token that will be thrown away later. 53 ( 0.00%) pub fn dummy() -> Self { . Token::new(TokenKind::Question, DUMMY_SP) 53 ( 0.00%) } . . /// Recovers a `Token` from an `Ident`. This creates a raw identifier if necessary. . pub fn from_ast_ident(ident: Ident) -> Self { . Token::new(Ident(ident.name, ident.is_raw_guess()), ident.span) . } . . /// Return this token by value and leave a dummy token in its place. 6,775 ( 0.01%) pub fn take(&mut self) -> Self { . mem::replace(self, Token::dummy()) 6,775 ( 0.01%) } . . /// 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 { 104 ( 0.00%) match &self.kind { . Interpolated(nt) => nt.span(), 52 ( 0.00%) _ => self.span, . } 52 ( 0.00%) } . . pub fn is_op(&self) -> bool { 20,325 ( 0.03%) !matches!( 6,775 ( 0.01%) self.kind, . OpenDelim(..) . | CloseDelim(..) . | Literal(..) . | DocComment(..) . | Ident(..) . | Lifetime(..) . | Interpolated(..) . | Eof . ) 6,775 ( 0.01%) } . . pub fn is_like_plus(&self) -> bool { 145 ( 0.00%) matches!(self.kind, BinOp(Plus) | BinOpEq(Plus)) 29 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of an expression. 1 ( 0.00%) pub fn can_begin_expr(&self) -> bool { 5 ( 0.00%) match self.uninterpolate().kind { . Ident(name, is_raw) => . ident_can_begin_expr(name, self.span, is_raw), // value name or keyword . OpenDelim(..) | // tuple, array or block . Literal(..) | // literal . Not | // operator not . BinOp(Minus) | // unary minus . BinOp(Star) | // dereference . BinOp(Or) | OrOr | // closure -- line 369 ---------------------------------------- -- line 376 ---------------------------------------- . Lifetime(..) | // labeled loop . Pound => true, // expression attributes . Interpolated(ref nt) => matches!(**nt, NtLiteral(..) | . NtExpr(..) | . NtBlock(..) | . NtPath(..)), . _ => false, . } 2 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of a type. . pub fn can_begin_type(&self) -> bool { . match self.uninterpolate().kind { . Ident(name, is_raw) => . ident_can_begin_type(name, self.span, is_raw), // type name or keyword . OpenDelim(Paren) | // tuple . OpenDelim(Bracket) | // array -- line 392 ---------------------------------------- -- line 427 ---------------------------------------- . } . . /// Returns `true` if the token is any literal, a minus (which can prefix a literal, . /// for example a '-42', or one of the boolean idents). . /// . /// In other words, would this token be a valid start of `parse_literal_maybe_minus`? . /// . /// Keep this in sync with and `Lit::from_token`, excluding unary negation. 1 ( 0.00%) pub fn can_begin_literal_maybe_minus(&self) -> bool { 10 ( 0.00%) match self.uninterpolate().kind { . Literal(..) | BinOp(Minus) => true, 4 ( 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, . } 2 ( 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. 258 ( 0.00%) pub fn uninterpolate(&self) -> Cow<'_, Token> { 34,985 ( 0.05%) match &self.kind { . Interpolated(nt) => match **nt { . NtIdent(ident, is_raw) => { . Cow::Owned(Token::new(Ident(ident.name, is_raw), ident.span)) . } . NtLifetime(ident) => Cow::Owned(Token::new(Lifetime(ident.name), ident.span)), . _ => Cow::Borrowed(self), . }, . _ => Cow::Borrowed(self), . } 258 ( 0.00%) } . . /// Returns an identifier if this token is an identifier. 6,383 ( 0.01%) pub fn ident(&self) -> Option<(Ident, /* is_raw */ bool)> { . let token = self.uninterpolate(); 26,325 ( 0.04%) match token.kind { 117,061 ( 0.16%) Ident(name, is_raw) => Some((Ident::new(name, token.span), is_raw)), . _ => None, . } 42,878 ( 0.06%) } . . /// Returns a lifetime identifier if this token is a lifetime. 109 ( 0.00%) pub fn lifetime(&self) -> Option { . let token = self.uninterpolate(); 234 ( 0.00%) match token.kind { . Lifetime(name) => Some(Ident::new(name, token.span)), . _ => None, . } 763 ( 0.00%) } . . /// Returns `true` if the token is an identifier. . pub fn is_ident(&self) -> bool { . self.ident().is_some() 336 ( 0.00%) } . . /// Returns `true` if the token is a lifetime. 8 ( 0.00%) pub fn is_lifetime(&self) -> bool { . self.lifetime().is_some() 16 ( 0.00%) } . . /// Returns `true` if the token is an identifier whose name is the given . /// string slice. 132 ( 0.00%) pub fn is_ident_named(&self, name: Symbol) -> bool { . self.ident().map_or(false, |(ident, _)| ident.name == name) 264 ( 0.00%) } . . /// Returns `true` if the token is an interpolated path. . fn is_path(&self) -> bool { 1,684 ( 0.00%) if let Interpolated(ref nt) = self.kind { . if let NtPath(..) = **nt { . return true; . } . } . false . } . . /// Would `maybe_whole_expr` in `parser.rs` return `Ok(..)`? -- line 515 ---------------------------------------- -- line 522 ---------------------------------------- . } . } . . false . } . . // Is the token an interpolated block (`$b:block`)? . pub fn is_whole_block(&self) -> bool { 22 ( 0.00%) if let Interpolated(ref nt) = self.kind { . if let NtBlock(..) = **nt { . return true; . } . } . false 11 ( 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) . } . 490 ( 0.00%) pub fn is_qpath_start(&self) -> bool { 1,332 ( 0.00%) self == &Lt || self == &BinOp(Shl) . } . 1,684 ( 0.00%) pub fn is_path_start(&self) -> bool { 2,508 ( 0.00%) self == &ModSep . || self.is_qpath_start() . || self.is_path() . || self.is_path_segment_keyword() 420 ( 0.00%) || self.is_ident() && !self.is_reserved_ident() 2,105 ( 0.00%) } . . /// Returns `true` if the token is a given keyword, `kw`. 5,112 ( 0.01%) pub fn is_keyword(&self, kw: Symbol) -> bool { . self.is_non_raw_ident_where(|id| id.name == kw) 10,224 ( 0.01%) } . 60 ( 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. 11 ( 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. 11 ( 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. 11 ( 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`. 60 ( 0.00%) pub fn is_bool_lit(&self) -> bool { 120 ( 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. 32 ( 0.00%) pub fn is_non_raw_ident_where(&self, pred: impl FnOnce(Ident) -> bool) -> bool { 35,123 ( 0.05%) match self.ident() { 435 ( 0.00%) Some((id, false)) => pred(id), . _ => false, . } 40 ( 0.00%) } . 19,250 ( 0.03%) pub fn glue(&self, joint: &Token) -> Option { 9,625 ( 0.01%) let kind = match self.kind { 73 ( 0.00%) Eq => match joint.kind { . Eq => EqEq, . Gt => FatArrow, . _ => return None, . }, 15 ( 0.00%) Lt => match joint.kind { . Eq => Le, . Lt => BinOp(Shl), . Le => BinOpEq(Shl), . BinOp(Minus) => LArrow, . _ => return None, . }, 37 ( 0.00%) Gt => match joint.kind { . Eq => Ge, . Gt => BinOp(Shr), . Ge => BinOpEq(Shr), . _ => return None, . }, 4 ( 0.00%) Not => match joint.kind { . Eq => Ne, . _ => return None, . }, 358 ( 0.00%) BinOp(op) => match joint.kind { . Eq => BinOpEq(op), 9 ( 0.00%) BinOp(And) if op == And => AndAnd, 1 ( 0.00%) BinOp(Or) if op == Or => OrOr, 31 ( 0.00%) Gt if op == Minus => RArrow, . _ => return None, . }, 3 ( 0.00%) Dot => match joint.kind { . Dot => DotDot, . DotDot => DotDotDot, . _ => return None, . }, 3 ( 0.00%) DotDot => match joint.kind { . Dot => DotDotDot, . Eq => DotDotEq, . _ => return None, . }, 952 ( 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, . }; . 7,228 ( 0.01%) Some(Token::new(kind, self.span.to(joint.span))) 17,325 ( 0.02%) } . } . . impl PartialEq for Token { . fn eq(&self, rhs: &TokenKind) -> bool { 15,629 ( 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. 200 ( 0.00%) pub fn from_symbol( . symbol: Symbol, . edition: impl FnOnce() -> Edition, . ) -> Option { 486 ( 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, . }) 200 ( 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 ---------------------------------------- 152,473 ( 0.21%) -------------------------------------------------------------------------------- -- 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 { 41,995 ( 0.06%) if value < 0x80 { . unsafe { 21,037 ( 0.03%) *out.get_unchecked_mut(i).as_mut_ptr() = value as u8; . } . 26,771 ( 0.04%) i += 1; . break; . } else { . unsafe { 20,272 ( 0.03%) *out.get_unchecked_mut(i).as_mut_ptr() = ((value & 0x7f) | 0x80) as u8; . } . 11,411 ( 0.02%) 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. 47,168 ( 0.06%) let byte = slice[*position]; 23,584 ( 0.03%) *position += 1; 23,584 ( 0.03%) if (byte & 0x80) == 0 { . return byte as $int_ty; . } 626 ( 0.00%) let mut result = (byte & 0x7F) as $int_ty; . let mut shift = 7; . loop { 37,590 ( 0.05%) let byte = slice[*position]; 21,995 ( 0.03%) *position += 1; 25,060 ( 0.03%) if (byte & 0x80) == 0 { 13,900 ( 0.02%) result |= (byte as $int_ty) << shift; . return result; . } else { . result |= ((byte & 0x7F) as $int_ty) << shift; . } . shift += 7; . } . } . }; -- line 80 ---------------------------------------- 51,568 ( 0.07%) -------------------------------------------------------------------------------- -- 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); . 7,644 ( 0.01%) if count == 8 { . ptr::copy_nonoverlapping(src, dst, 8); . return; . } . . let mut i = 0; 10,988 ( 0.02%) if i + 3 < count { . ptr::copy_nonoverlapping(src.add(i), dst.add(i), 4); . i += 4; . } . 24,092 ( 0.03%) if i + 1 < count { . ptr::copy_nonoverlapping(src.add(i), dst.add(i), 2); 2,828 ( 0.00%) i += 2 . } . 10,988 ( 0.02%) if i < count { 5,534 ( 0.01%) *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::(); 38,172 ( 0.05%) let nbuf = self.nbuf; . debug_assert!(size <= 8); . debug_assert!(nbuf < BUFFER_SIZE); . debug_assert!(nbuf + size < BUFFER_WITH_SPILL_SIZE); . 244,124 ( 0.33%) 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); . } . 70,375 ( 0.10%) self.nbuf = nbuf + size; . . return; . } . 8,959 ( 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)] 3,600 ( 0.00%) unsafe fn short_write_process_buffer(&mut self, x: T) { . let size = mem::size_of::(); 3,600 ( 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 { 36,000 ( 0.05%) let elem = self.buf.get_unchecked(i).assume_init().to_le(); 28,800 ( 0.04%) self.state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut self.state); 32,400 ( 0.04%) self.state.v0 ^= elem; . } . . // Copy remaining input into start of buffer by copying size - 1 . // elements from spill (at most size - 1 bytes could have overflowed . // into the spill). The memcpy call is optimized away because the size . // is known. And the whole copy is optimized away for size == 1. . let src = self.buf.get_unchecked(BUFFER_SPILL_INDEX) as *const _ as *const u8; . ptr::copy_nonoverlapping(src, self.buf.as_mut_ptr() as *mut u8, size - 1); . . // This function should only be called when the write fills the buffer. . // Therefore, when size == 1, the new `self.nbuf` must be zero. The size . // is statically known, so the branch is optimized away. 16,820 ( 0.02%) self.nbuf = if size == 1 { 0 } else { nbuf + size - BUFFER_SIZE }; 14,400 ( 0.02%) self.processed += BUFFER_SIZE; 7,200 ( 0.01%) } . . // A write function for byte slices. . #[inline] . fn slice_write(&mut self, msg: &[u8]) { . let length = msg.len(); 4,042 ( 0.01%) let nbuf = self.nbuf; . debug_assert!(nbuf < BUFFER_SIZE); . 29,358 ( 0.04%) if nbuf + length < BUFFER_SIZE { . unsafe { . let dst = (self.buf.as_mut_ptr() as *mut u8).add(nbuf); . 10,650 ( 0.01%) 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); . } . } . 5,330 ( 0.01%) self.nbuf = nbuf + length; . . return; . } . 3,727 ( 0.01%) 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)] 2,725 ( 0.00%) unsafe fn slice_write_process_buffer(&mut self, msg: &[u8]) { . let length = msg.len(); 545 ( 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. 1,635 ( 0.00%) let valid_in_elem = nbuf % ELEM_SIZE; 545 ( 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. 1,090 ( 0.00%) let last = nbuf / ELEM_SIZE + 1; . . for i in 0..last { 3,998 ( 0.01%) let elem = self.buf.get_unchecked(i).assume_init().to_le(); 4,543 ( 0.01%) self.state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut self.state); 7,996 ( 0.01%) self.state.v0 ^= elem; . } . . // Process the remaining element-sized chunks of input. . let mut processed = needed_in_elem; 1,090 ( 0.00%) let input_left = length - processed; 546 ( 0.00%) let elems_left = input_left / ELEM_SIZE; . let extra_bytes_left = input_left % ELEM_SIZE; . . for _ in 0..elems_left { 739 ( 0.00%) let elem = (msg.as_ptr().add(processed) as *const u64).read_unaligned().to_le(); 739 ( 0.00%) self.state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut self.state); 739 ( 0.00%) self.state.v0 ^= elem; 1,478 ( 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); . 545 ( 0.00%) self.nbuf = extra_bytes_left; 2,725 ( 0.00%) self.processed += nbuf + processed; 3,270 ( 0.00%) } . . #[inline] . pub fn finish128(mut self) -> (u64, u64) { . debug_assert!(self.nbuf < BUFFER_SIZE); . . // Process full elements in buffer. 1,092 ( 0.00%) let last = self.nbuf / ELEM_SIZE; . . // Since we're consuming self, avoid updating members for a potential . // performance gain. 1,456 ( 0.00%) let mut state = self.state; . . for i in 0..last { 1,126 ( 0.00%) let elem = unsafe { self.buf.get_unchecked(i).assume_init().to_le() }; 1,126 ( 0.00%) state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut state); 1,126 ( 0.00%) state.v0 ^= elem; . } . . // Get remaining partial element. 728 ( 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); 315 ( 0.00%) self.buf.get_unchecked(last).assume_init().to_le() . } . } else { . 0 . }; . . // Finalize the hash. 1,043 ( 0.00%) let length = self.processed + self.nbuf; 726 ( 0.00%) let b: u64 = ((length as u64 & 0xff) << 56) | elem; . 363 ( 0.00%) state.v3 ^= b; . Sip24Rounds::c_rounds(&mut state); 363 ( 0.00%) state.v0 ^= b; . 363 ( 0.00%) state.v2 ^= 0xee; . Sip24Rounds::d_rounds(&mut state); 806 ( 0.00%) let _0 = state.v0 ^ state.v1 ^ state.v2 ^ state.v3; . 78 ( 0.00%) state.v1 ^= 0xdd; . Sip24Rounds::d_rounds(&mut state); 78 ( 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) { 145,339 ( 0.20%) compress!(state); 162,898 ( 0.22%) compress!(state); . } . . #[inline] . fn d_rounds(state: &mut State) { 1,608 ( 0.00%) compress!(state); 1,608 ( 0.00%) compress!(state); 1,608 ( 0.00%) compress!(state); 1,246 ( 0.00%) compress!(state); . } . } 13,939 ( 0.02%) -------------------------------------------------------------------------------- -- 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. . /// 23,606 ( 0.03%) #[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 { 64 ( 0.00%) base_or_index: u32, 15 ( 0.00%) len_or_tag: u16, 100 ( 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 { 16,382 ( 0.02%) if lo > hi { . std::mem::swap(&mut lo, &mut hi); . } . 32,764 ( 0.04%) let (base, len, ctxt2) = (lo.0, hi.0 - lo.0, ctxt.as_u32()); . 89,261 ( 0.12%) 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 = 15 ( 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 } . } 38,106 ( 0.05%) } . . #[inline] . pub fn data(self) -> SpanData { . let data = self.data_untracked(); 4 ( 0.00%) if let Some(parent) = data.parent { . (*SPAN_TRACK)(parent); . } . data . } . . /// Internal function to translate between an encoded span and the expanded representation. . /// This function must not be used outside the incremental engine. . #[inline] . pub fn data_untracked(self) -> SpanData { 116,318 ( 0.16%) 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), 113,714 ( 0.16%) 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); 6 ( 0.00%) let index = self.base_or_index; 28 ( 0.00%) with_span_interner(|interner| interner.spans[index as usize]) . } 55,727 ( 0.08%) } . } . 4 ( 0.00%) #[derive(Default)] . pub struct SpanInterner { . spans: FxIndexSet, . } . . impl SpanInterner { 3 ( 0.00%) fn intern(&mut self, span_data: &SpanData) -> u32 { 4 ( 0.00%) let (index, _) = self.spans.insert_full(*span_data); . index as u32 4 ( 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())) . } 92,213 ( 0.13%) -------------------------------------------------------------------------------- -- 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. 16,789 ( 0.02%) 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. 57,448 ( 0.08%) 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`. 3 ( 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 { 17,277 ( 0.02%) 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 { 231 ( 0.00%) assume(!self.ptr.as_ptr().is_null()); . if mem::size_of::() != 0 { 13,528 ( 0.02%) assume(!self.end.is_null()); . } 1,992,630 ( 2.72%) if is_empty!(self) { . None . } else { . Some(next_unchecked!(self)) . } . } . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 1,455 ( 0.00%) let exact = len!(self); . (exact, Some(exact)) . } . . #[inline] . fn count(self) -> usize { . len!(self) . } . -- line 164 ---------------------------------------- -- line 217 ---------------------------------------- . // faster to compile. . #[inline] . fn all(&mut self, mut f: F) -> bool . where . Self: Sized, . F: FnMut(Self::Item) -> bool, . { . while let Some(x) = self.next() { 1,659 ( 0.00%) if !f(x) { . return false; . } . } . true . } . . // We override the default implementation, which uses `try_fold`, . // because this simple implementation generates less LLVM IR and is . // faster to compile. . #[inline] . fn any(&mut self, mut f: F) -> bool . where . Self: Sized, . F: FnMut(Self::Item) -> bool, . { 1,787 ( 0.00%) while let Some(x) = self.next() { 41,045 ( 0.06%) if f(x) { . return true; . } . } . false . } . . // We override the default implementation, which uses `try_fold`, . // because this simple implementation generates less LLVM IR and is . // faster to compile. . #[inline] . fn find

(&mut self, mut predicate: P) -> Option . where . Self: Sized, . P: FnMut(&Self::Item) -> bool, . { 131 ( 0.00%) while let Some(x) = self.next() { 1,789 ( 0.00%) if predicate(&x) { . return Some(x); . } . } . None 48 ( 0.00%) } . . // We override the default implementation, which uses `try_fold`, . // because this simple implementation generates less LLVM IR and is . // faster to compile. . #[inline] . fn find_map(&mut self, mut f: F) -> Option . where . Self: Sized, . F: FnMut(Self::Item) -> Option, . { 24 ( 0.00%) while let Some(x) = self.next() { 399 ( 0.00%) if let Some(y) = f(x) { . return Some(y); . } . } . None 35 ( 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() { 11,472 ( 0.02%) 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; 280 ( 0.00%) while let Some(x) = self.next_back() { 5,337 ( 0.01%) i -= 1; 5,037 ( 0.01%) if predicate(x) { . // SAFETY: `i` must be lower than `n` since it starts at `n` . // and is only decreasing. . unsafe { assume(i < n) }; . return Some(i); . } . } . None . } -- line 326 ---------------------------------------- -- line 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 { 4 ( 0.00%) assume(!self.end.is_null()); . } 4,486 ( 0.01%) if is_empty!(self) { . None . } else { . Some(next_back_unchecked!(self)) . } . } . } . . #[inline] -- line 369 ---------------------------------------- 189,115 ( 0.26%) -------------------------------------------------------------------------------- -- 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")] 24 ( 0.00%) pub fn from_str_radix(src: &str, radix: u32) -> Result { 12 ( 0.00%) from_str_radix(src, radix) 36 ( 0.00%) } . . /// Returns the number of ones in the binary representation of `self`. . /// . /// # Examples . /// . /// Basic usage: . /// . /// ``` -- line 75 ---------------------------------------- -- 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 { 941 ( 0.00%) 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 { 7,657 ( 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 { 532,273 ( 0.73%) intrinsics::rotate_left(self, n as $SelfT) . } . . /// Shifts the bits to the right by a specified amount, `n`, . /// wrapping the truncated bits to the beginning of the resulting . /// integer. . /// . /// Please note this isn't the same operation as the `>>` shifting operator! . /// -- line 220 ---------------------------------------- -- line 456 ---------------------------------------- . )] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")] . #[inline(always)] . pub const unsafe fn unchecked_add(self, rhs: Self) -> Self { . // SAFETY: the caller must uphold the safety contract for . // `unchecked_add`. 16,016 ( 0.02%) unsafe { intrinsics::unchecked_add(self, rhs) } . } . . /// Checked addition with a signed integer. Computes `self + rhs`, . /// returning `None` if overflow occurred. . /// . /// # Examples . /// . /// Basic usage: -- line 472 ---------------------------------------- -- line 525 ---------------------------------------- . )] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")] . #[inline(always)] . pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self { . // SAFETY: the caller must uphold the safety contract for . // `unchecked_sub`. 7 ( 0.00%) unsafe { intrinsics::unchecked_sub(self, rhs) } . } . . /// Checked integer multiplication. Computes `self * rhs`, returning . /// `None` if overflow occurred. . /// . /// # Examples . /// . /// Basic usage: -- line 541 ---------------------------------------- -- line 596 ---------------------------------------- . without modifying the original"] . #[inline] . pub const fn checked_div(self, rhs: Self) -> Option { . if unlikely!(rhs == 0) { . None . } else { . // SAFETY: div by zero has been checked above and unsigned types have no other . // failure modes for division 24 ( 0.00%) Some(unsafe { intrinsics::unchecked_div(self, rhs) }) . } . } . . /// Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None` . /// if `rhs == 0`. . /// . /// # Examples . /// -- line 612 ---------------------------------------- -- line 1035 ---------------------------------------- . #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_add(127), ", stringify!($SelfT), "::MAX);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")] . #[inline(always)] . pub const fn saturating_add(self, rhs: Self) -> Self { 112 ( 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 { 4 ( 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 { 518,540 ( 0.71%) 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 { 24,537 ( 0.03%) intrinsics::wrapping_sub(self, rhs) . } . . /// Wrapping (modular) multiplication. Computes `self * . /// rhs`, wrapping around at the boundary of the type. . /// . /// # Examples . /// . /// Basic usage: -- line 1233 ---------------------------------------- -- line 1240 ---------------------------------------- . /// assert_eq!(25u8.wrapping_mul(12), 44); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn wrapping_mul(self, rhs: Self) -> Self { 56,822 ( 0.08%) intrinsics::wrapping_mul(self, rhs) . } . . /// Wrapping (modular) division. Computes `self / rhs`. . /// Wrapped division on unsigned types is just normal division. . /// There's no way wrapping could ever happen. . /// This function exists, so that all operations . /// are accounted for in the wrapping operations. . /// -- line 1256 ---------------------------------------- -- line 1492 ---------------------------------------- . #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));")] . /// ``` . #[stable(feature = "wrapping", since = "1.7.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) { 10,370 ( 0.01%) 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) { 1,122 ( 0.00%) let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT); . (a as Self, b) . } . . /// Calculates `self - rhs - borrow` without the ability to overflow. . /// . /// Performs "ternary subtraction" which takes in an extra bit to subtract, and may return . /// an additional bit of overflow. This allows for chaining together multiple subtractions . /// to create "big integers" which represent larger values. -- line 1604 ---------------------------------------- -- line 1674 ---------------------------------------- . /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true)); . /// ``` . #[stable(feature = "wrapping", since = "1.7.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) { 16,851 ( 0.02%) let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT); . (a as Self, b) . } . . /// Calculates the divisor when `self` is divided by `rhs`. . /// . /// Returns a tuple of the divisor along with a boolean indicating . /// whether an arithmetic overflow would occur. Note that for unsigned . /// integers overflow never occurs, so the second value is always -- line 1690 ---------------------------------------- -- line 2132 ---------------------------------------- . #[doc = concat!("assert!(16", stringify!($SelfT), ".is_power_of_two());")] . #[doc = concat!("assert!(!10", stringify!($SelfT), ".is_power_of_two());")] . /// ``` . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")] . #[inline(always)] . pub const fn is_power_of_two(self) -> bool { 24 ( 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 { 148 ( 0.00%) if self <= 1 { return 0; } . 164 ( 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. 492 ( 0.00%) let z = unsafe { intrinsics::ctlz_nonzero(p) }; 164 ( 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 { 180 ( 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 ---------------------------------------- 474 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/str/validations.rs -------------------------------------------------------------------------------- Ir -- line 4 ---------------------------------------- . . use super::Utf8Error; . . /// Returns the initial codepoint accumulator for the first byte. . /// The first byte is special, only want bottom 5 bits for width 2, 4 bits . /// for width 3, and 3 bits for width 4. . #[inline] . const fn utf8_first_byte(byte: u8, width: u32) -> u32 { 6 ( 0.00%) (byte & (0x7F >> width)) as u32 . } . . /// Returns the value of `ch` updated with continuation byte `byte`. . #[inline] . const fn utf8_acc_cont_byte(ch: u32, byte: u8) -> u32 { 18 ( 0.00%) (ch << 6) | (byte & CONT_MASK) as u32 . } . . /// Checks whether the byte is a UTF-8 continuation byte (i.e., starts with the . /// bits `10`). . #[inline] . pub(super) const fn utf8_is_cont_byte(byte: u8) -> bool { . (byte as i8) < -64 . } -- line 26 ---------------------------------------- -- line 30 ---------------------------------------- . /// . /// # Safety . /// . /// `bytes` must produce a valid UTF-8-like (UTF-8 or WTF-8) string . #[unstable(feature = "str_internals", issue = "none")] . #[inline] . pub unsafe fn next_code_point<'a, I: Iterator>(bytes: &mut I) -> Option { . // Decode UTF-8 141,865 ( 0.19%) let x = *bytes.next()?; 276,070 ( 0.38%) if x < 128 { . return Some(x as u32); . } . . // Multibyte case follows . // Decode from a byte combination out of: [[[x y] z] w] . // NOTE: Performance is sensitive to the exact formulation here . let init = utf8_first_byte(x, 2); . // SAFETY: `bytes` produces an UTF-8-like string, . // so the iterator must produce a value here. . let y = unsafe { *bytes.next().unwrap_unchecked() }; . let mut ch = utf8_acc_cont_byte(init, y); 6 ( 0.00%) if x >= 0xE0 { . // [[x y z] w] case . // 5th bit in 0xE0 .. 0xEF is always clear, so `init` is still valid . // SAFETY: `bytes` produces an UTF-8-like string, . // so the iterator must produce a value here. . let z = unsafe { *bytes.next().unwrap_unchecked() }; . let y_z = utf8_acc_cont_byte((y & CONT_MASK) as u32, z); . ch = init << 12 | y_z; 6 ( 0.00%) if x >= 0xF0 { . // [x y z w] case . // use only the lower 3 bits of `init` . // SAFETY: `bytes` produces an UTF-8-like string, . // so the iterator must produce a value here. . let w = unsafe { *bytes.next().unwrap_unchecked() }; . ch = (init & 7) << 18 | utf8_acc_cont_byte(y_z, w); . } . } -- line 67 ---------------------------------------- -- line 77 ---------------------------------------- . /// `bytes` must produce a valid UTF-8-like (UTF-8 or WTF-8) string . #[inline] . pub(super) unsafe fn next_code_point_reverse<'a, I>(bytes: &mut I) -> Option . where . I: DoubleEndedIterator, . { . // Decode UTF-8 . let w = match *bytes.next_back()? { 18 ( 0.00%) next_byte if next_byte < 128 => return Some(next_byte as u32), . back_byte => back_byte, . }; . . // Multibyte case follows . // Decode from a byte combination out of: [x [y [z w]]] . let mut ch; . // SAFETY: `bytes` produces an UTF-8-like string, . // so the iterator must produce a value here. -- line 93 ---------------------------------------- -- line 113 ---------------------------------------- . } . . // use truncation to fit u64 into usize . const NONASCII_MASK: usize = 0x80808080_80808080u64 as usize; . . /// Returns `true` if any byte in the word `x` is nonascii (>= 128). . #[inline] . const fn contains_nonascii(x: usize) -> bool { 3,618 ( 0.00%) (x & NONASCII_MASK) != 0 . } . . /// Walks through `v` checking that it's a valid UTF-8 sequence, . /// returning `Ok(())` in that case, or, if it is invalid, `Err(err)`. . #[inline(always)] . #[rustc_const_unstable(feature = "str_internals", issue = "none")] . pub(super) const fn run_utf8_validation(v: &[u8]) -> Result<(), Utf8Error> { . let mut index = 0; . let len = v.len(); . . let usize_bytes = mem::size_of::(); . let ascii_block_size = 2 * usize_bytes; 330 ( 0.00%) let blocks_end = if len >= ascii_block_size { len - ascii_block_size + 1 } else { 0 }; . let align = v.as_ptr().align_offset(usize_bytes); . 552 ( 0.00%) while index < len { . let old_offset = index; . macro_rules! err { . ($error_len: expr) => { . return Err(Utf8Error { valid_up_to: old_offset, error_len: $error_len }) . }; . } . . macro_rules! next { -- line 145 ---------------------------------------- -- line 148 ---------------------------------------- . // we needed data, but there was none: error! . if index >= len { . err!(None) . } . v[index] . }}; . } . 266 ( 0.00%) let first = v[index]; 532 ( 0.00%) if first >= 128 { . let w = utf8_char_width(first); . // 2-byte encoding is for codepoints \u{0080} to \u{07ff} . // first C2 80 last DF BF . // 3-byte encoding is for codepoints \u{0800} to \u{ffff} . // first E0 A0 80 last EF BF BF . // excluding surrogates codepoints \u{d800} to \u{dfff} . // ED A0 80 to ED BF BF . // 4-byte encoding is for codepoints \u{1000}0 to \u{10ff}ff -- line 165 ---------------------------------------- -- line 169 ---------------------------------------- . // . // https://tools.ietf.org/html/rfc3629 . // UTF8-1 = %x00-7F . // UTF8-2 = %xC2-DF UTF8-tail . // UTF8-3 = %xE0 %xA0-BF UTF8-tail / %xE1-EC 2( UTF8-tail ) / . // %xED %x80-9F UTF8-tail / %xEE-EF 2( UTF8-tail ) . // UTF8-4 = %xF0 %x90-BF 2( UTF8-tail ) / %xF1-F3 3( UTF8-tail ) / . // %xF4 %x80-8F 2( UTF8-tail ) 4 ( 0.00%) match w { . 2 => { . if next!() as i8 >= -64 { . err!(Some(1)) . } . } . 3 => { 8 ( 0.00%) match (first, next!()) { . (0xE0, 0xA0..=0xBF) 7 ( 0.00%) | (0xE1..=0xEC, 0x80..=0xBF) . | (0xED, 0x80..=0x9F) . | (0xEE..=0xEF, 0x80..=0xBF) => {} . _ => err!(Some(1)), . } 5 ( 0.00%) if next!() as i8 >= -64 { . err!(Some(2)) . } . } . 4 => { . match (first, next!()) { . (0xF0, 0x90..=0xBF) | (0xF1..=0xF3, 0x80..=0xBF) | (0xF4, 0x80..=0x8F) => {} . _ => err!(Some(1)), . } -- line 199 ---------------------------------------- -- line 201 ---------------------------------------- . err!(Some(2)) . } . if next!() as i8 >= -64 { . err!(Some(3)) . } . } . _ => err!(Some(1)), . } 3 ( 0.00%) index += 1; . } else { . // Ascii case, try to skip forward quickly. . // When the pointer is aligned, read 2 words of data per iteration . // until we find a word containing a non-ascii byte. 902 ( 0.00%) if align != usize::MAX && align.wrapping_sub(index) % usize_bytes == 0 { . let ptr = v.as_ptr(); 7,448 ( 0.01%) while index < blocks_end { . // SAFETY: since `align - index` and `ascii_block_size` are . // multiples of `usize_bytes`, `block = ptr.add(index)` is . // always aligned with a `usize` so it's safe to dereference . // both `block` and `block.offset(1)`. . unsafe { . let block = ptr.add(index) as *const usize; . // break if there is a nonascii byte 3,618 ( 0.00%) let zu = contains_nonascii(*block); . let zv = contains_nonascii(*block.offset(1)); 7,236 ( 0.01%) if zu || zv { . break; . } . } 7,234 ( 0.01%) index += ascii_block_size; . } . // step from the point where the wordwise loop stopped 3,770 ( 0.01%) while index < len && v[index] < 128 { 813 ( 0.00%) index += 1; . } . } else { 158 ( 0.00%) index += 1; . } . } . } . . Ok(()) . } . . // https://tools.ietf.org/html/rfc3629 -- line 245 ---------------------------------------- -- line 263 ---------------------------------------- . 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // F . ]; . . /// Given a first byte, determines how many bytes are in this UTF-8 character. . #[unstable(feature = "str_internals", issue = "none")] . #[must_use] . #[inline] . pub const fn utf8_char_width(b: u8) -> usize { 2 ( 0.00%) UTF8_CHAR_WIDTH[b as usize] as usize . } . . /// Mask of the value bits of a continuation byte. . const CONT_MASK: u8 = 0b0011_1111; . . // truncate `&str` to length at most equal to `max` . // return `true` if it were truncated, and the new str. . pub(super) fn truncate_to_char_boundary(s: &str, mut max: usize) -> (bool, &str) { -- line 279 ---------------------------------------- 21,646 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/mod.rs -------------------------------------------------------------------------------- Ir -- line 141 ---------------------------------------- . /// ``` . /// let a = [1, 2, 3]; . /// assert!(!a.is_empty()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_slice_is_empty", since = "1.39.0")] . #[inline] . pub const fn is_empty(&self) -> bool { 1,100 ( 0.00%) self.len() == 0 . } . . /// Returns the first element of the slice, or `None` if it is empty. . /// . /// # Examples . /// . /// ``` . /// let v = [10, 40, 30]; -- line 157 ---------------------------------------- -- line 159 ---------------------------------------- . /// . /// let w: &[i32] = &[]; . /// assert_eq!(None, w.first()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")] . #[inline] . pub const fn first(&self) -> Option<&T> { 11 ( 0.00%) if let [first, ..] = self { Some(first) } else { None } . } . . /// Returns a mutable pointer to the first element of the slice, or `None` if it is empty. . /// . /// # Examples . /// . /// ``` . /// let x = &mut [0, 1, 2]; -- line 175 ---------------------------------------- -- line 276 ---------------------------------------- . /// . /// let w: &[i32] = &[]; . /// assert_eq!(None, w.last()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")] . #[inline] . pub const fn last(&self) -> Option<&T> { 16,184 ( 0.02%) if let [.., last] = self { Some(last) } else { None } . } . . /// Returns a mutable pointer to the last item in the slice. . /// . /// # Examples . /// . /// ``` . /// let x = &mut [0, 1, 2]; -- line 292 ---------------------------------------- -- line 295 ---------------------------------------- . /// *last = 10; . /// } . /// assert_eq!(x, &[0, 1, 10]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")] . #[inline] . pub const fn last_mut(&mut self) -> Option<&mut T> { 102 ( 0.00%) if let [.., last] = self { Some(last) } else { None } . } . . /// Returns a reference to an element or subslice depending on the type of . /// index. . /// . /// - If given a position, returns a reference to the element at that . /// position or `None` if out of bounds. . /// - If given a range, returns the subslice corresponding to that range, -- line 311 ---------------------------------------- -- line 448 ---------------------------------------- . /// } . /// ``` . /// . /// [`as_mut_ptr`]: slice::as_mut_ptr . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_slice_as_ptr", since = "1.32.0")] . #[inline] . pub const fn as_ptr(&self) -> *const T { 265 ( 0.00%) self as *const [T] as *const T . } . . /// Returns an unsafe mutable pointer to the slice's buffer. . /// . /// The caller must ensure that the slice outlives the pointer this . /// function returns, or else it will end up pointing to garbage. . /// . /// Modifying the container referenced by this slice may cause its buffer -- line 464 ---------------------------------------- -- line 476 ---------------------------------------- . /// } . /// } . /// assert_eq!(x, &[3, 4, 6]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")] . #[inline] . pub const fn as_mut_ptr(&mut self) -> *mut T { 1 ( 0.00%) self as *mut [T] as *mut T . } . . /// Returns the two raw pointers spanning the slice. . /// . /// The returned range is half-open, which means that the end pointer . /// points *one past* the last element of the slice. This way, an empty . /// slice is represented by two equal pointers, and the difference between . /// the two pointers represents the size of the slice. -- line 492 ---------------------------------------- -- line 677 ---------------------------------------- . . // Because this function is first compiled in isolation, . // this check tells LLVM that the indexing below is . // in-bounds. Then after inlining -- once the actual . // lengths of the slices are known -- it's removed. . let (a, b) = (&mut a[..n], &mut b[..n]); . . for i in 0..n { 338 ( 0.00%) mem::swap(&mut a[i], &mut b[n - 1 - i]); . } . } . } . . /// Returns an iterator over the slice. . /// . /// # Examples . /// -- line 693 ---------------------------------------- -- line 1499 ---------------------------------------- . /// assert_eq!(left, [1, 2, 3, 4, 5, 6]); . /// assert_eq!(right, []); . /// } . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . #[track_caller] . pub fn split_at(&self, mid: usize) -> (&[T], &[T]) { 66 ( 0.00%) assert!(mid <= self.len()); . // SAFETY: `[ptr; mid]` and `[mid; len]` are inside `self`, which . // fulfills the requirements of `from_raw_parts_mut`. . unsafe { self.split_at_unchecked(mid) } . } . . /// Divides one mutable slice into two at an index. . /// . /// The first will contain all indices from `[0, mid)` (excluding -- line 1515 ---------------------------------------- -- line 1530 ---------------------------------------- . /// left[1] = 2; . /// right[1] = 4; . /// assert_eq!(v, [1, 2, 3, 4, 5, 6]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . #[track_caller] . pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) { 36 ( 0.00%) assert!(mid <= self.len()); . // SAFETY: `[ptr; mid]` and `[mid; len]` are inside `self`, which . // fulfills the requirements of `from_raw_parts_mut`. . unsafe { self.split_at_mut_unchecked(mid) } . } . . /// Divides one slice into two at an index, without doing bounds checking. . /// . /// The first will contain all indices from `[0, mid)` (excluding -- line 1546 ---------------------------------------- -- line 1628 ---------------------------------------- . pub unsafe fn split_at_mut_unchecked(&mut self, mid: usize) -> (&mut [T], &mut [T]) { . let len = self.len(); . let ptr = self.as_mut_ptr(); . . // SAFETY: Caller has to check that `0 <= mid <= self.len()`. . // . // `[ptr; mid]` and `[mid; len]` are not overlapping, so returning a mutable reference . // is fine. 9 ( 0.00%) unsafe { (from_raw_parts_mut(ptr, mid), from_raw_parts_mut(ptr.add(mid), len - mid)) } . } . . /// Divides one slice into an array and a remainder slice at an index. . /// . /// The array will contain all indices from `[0, N)` (excluding . /// the index `N` itself) and the slice will contain all . /// indices from `[N, len)` (excluding the index `len` itself). . /// -- line 1644 ---------------------------------------- -- line 2142 ---------------------------------------- . /// assert!(v.starts_with(&[])); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn starts_with(&self, needle: &[T]) -> bool . where . T: PartialEq, . { . let n = needle.len(); 707 ( 0.00%) self.len() >= n && needle == &self[..n] . } . . /// Returns `true` if `needle` is a suffix of the slice. . /// . /// # Examples . /// . /// ``` . /// let v = [10, 40, 30]; -- line 2158 ---------------------------------------- -- line 2171 ---------------------------------------- . /// assert!(v.ends_with(&[])); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn ends_with(&self, needle: &[T]) -> bool . where . T: PartialEq, . { . let (m, n) = (self.len(), needle.len()); 350 ( 0.00%) m >= n && needle == &self[m - n..] . } . . /// Returns a subslice with the prefix removed. . /// . /// If the slice starts with `prefix`, returns the subslice after the prefix, wrapped in `Some`. . /// If `prefix` is empty, simply returns the original slice. . /// . /// If the slice does not start with `prefix`, returns `None`. -- line 2187 ---------------------------------------- -- line 2293 ---------------------------------------- . /// s.insert(idx, num); . /// assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn binary_search(&self, x: &T) -> Result . where . T: Ord, . { 3 ( 0.00%) self.binary_search_by(|p| p.cmp(x)) . } . . /// Binary searches this sorted slice with a comparator function. . /// . /// The comparator function should implement an order consistent . /// with the sort order of the underlying slice, returning an . /// order code that indicates whether its argument is `Less`, . /// `Equal` or `Greater` the desired target. -- line 2309 ---------------------------------------- -- line 2345 ---------------------------------------- . #[inline] . pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result . where . F: FnMut(&'a T) -> Ordering, . { . let mut size = self.len(); . let mut left = 0; . let mut right = size; 40,358 ( 0.06%) while left < right { 69,998 ( 0.10%) let mid = left + size / 2; . . // SAFETY: the call is made safe by the following invariants: . // - `mid >= 0` . // - `mid < size`: `mid` is limited by `[left; right)` bound. 4,997 ( 0.01%) let cmp = f(unsafe { self.get_unchecked(mid) }); . . // The reason why we use if/else control flow rather than match . // is because match reorders comparison operations, which is perf sensitive. . // This is x86 asm for u8: https://rust.godbolt.org/z/8Y8Pra. 18,286 ( 0.02%) if cmp == Less { 40,859 ( 0.06%) left = mid + 1; 9,344 ( 0.01%) } else if cmp == Greater { . right = mid; . } else { . // SAFETY: same as the `get_unchecked` above . unsafe { crate::intrinsics::assume(mid < self.len()) }; . return Ok(mid); . } . 52,697 ( 0.07%) size = right - left; . } . Err(left) . } . . /// Binary searches this sorted slice with a key extraction function. . /// . /// Assumes that the slice is sorted by the key, for instance with . /// [`sort_by_key`] using the same key extraction function. -- line 2382 ---------------------------------------- -- line 3203 ---------------------------------------- . #[track_caller] . fn len_mismatch_fail(dst_len: usize, src_len: usize) -> ! { . panic!( . "source slice length ({}) does not match destination slice length ({})", . src_len, dst_len, . ); . } . 16 ( 0.00%) if self.len() != src.len() { . len_mismatch_fail(self.len(), src.len()); . } . . // SAFETY: `self` is valid for `self.len()` elements by definition, and `src` was . // checked to have the same length. The slices cannot overlap because . // mutable references are exclusive. . unsafe { . ptr::copy_nonoverlapping(src.as_ptr(), self.as_mut_ptr(), self.len()); -- line 3219 ---------------------------------------- 31,109 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs -------------------------------------------------------------------------------- Ir -- line 187 ---------------------------------------- . /// ``` . pub struct HashMap { . pub(crate) hash_builder: S, . pub(crate) table: RawTable<(K, V), A>, . } . . impl Clone for HashMap { . fn clone(&self) -> Self { 34 ( 0.00%) HashMap { . hash_builder: self.hash_builder.clone(), 7 ( 0.00%) table: self.table.clone(), . } . } . . fn clone_from(&mut self, source: &Self) { . self.table.clone_from(&source.table); . . // Update hash_builder only if we successfully cloned all elements. . self.hash_builder.clone_from(&source.hash_builder); -- line 205 ---------------------------------------- -- line 210 ---------------------------------------- . /// instances of any functions like RawTable::reserve from being generated . #[cfg_attr(feature = "inline-more", inline)] . pub(crate) fn make_hasher(hash_builder: &S) -> impl Fn(&(Q, V)) -> u64 + '_ . where . K: Borrow, . Q: Hash, . S: BuildHasher, . { 1,023 ( 0.00%) move |val| make_hash::(hash_builder, &val.0) . } . . /// Ensures that a single closure type across uses of this which, in turn prevents multiple . /// instances of any functions like RawTable::reserve from being generated . #[cfg_attr(feature = "inline-more", inline)] . fn equivalent_key(k: &Q) -> impl Fn(&(K, V)) -> bool + '_ . where . K: Borrow, . Q: ?Sized + Eq, . { 563 ( 0.00%) move |x| k.eq(x.0.borrow()) . } . . /// Ensures that a single closure type across uses of this which, in turn prevents multiple . /// instances of any functions like RawTable::reserve from being generated . #[cfg_attr(feature = "inline-more", inline)] . fn equivalent(k: &Q) -> impl Fn(&K) -> bool + '_ . where . K: Borrow, . Q: ?Sized + Eq, . { 21 ( 0.00%) move |x| k.eq(x.borrow()) . } . . #[cfg(not(feature = "nightly"))] . #[cfg_attr(feature = "inline-more", inline)] . pub(crate) fn make_hash(hash_builder: &S, val: &Q) -> u64 . where . K: Borrow, . Q: Hash + ?Sized, -- line 248 ---------------------------------------- -- line 251 ---------------------------------------- . use core::hash::Hasher; . let mut state = hash_builder.build_hasher(); . val.hash(&mut state); . state.finish() . } . . #[cfg(feature = "nightly")] . #[cfg_attr(feature = "inline-more", inline)] 6 ( 0.00%) pub(crate) fn make_hash(hash_builder: &S, val: &Q) -> u64 . where . K: Borrow, . Q: Hash + ?Sized, . S: BuildHasher, . { . hash_builder.hash_one(val) 12 ( 0.00%) } . . #[cfg(not(feature = "nightly"))] . #[cfg_attr(feature = "inline-more", inline)] . pub(crate) fn make_insert_hash(hash_builder: &S, val: &K) -> u64 . where . K: Hash, . S: BuildHasher, . { -- line 274 ---------------------------------------- -- line 367 ---------------------------------------- . /// let s = DefaultHashBuilder::default(); . /// let mut map = HashMap::with_hasher(s); . /// map.insert(1, 2); . /// ``` . /// . /// [`BuildHasher`]: ../../std/hash/trait.BuildHasher.html . #[cfg_attr(feature = "inline-more", inline)] . pub const fn with_hasher(hash_builder: S) -> Self { 2,457 ( 0.00%) Self { . hash_builder, . table: RawTable::new(), . } . } . . /// Creates an empty `HashMap` with the specified capacity, using `hash_builder` . /// to hash the keys. . /// -- line 383 ---------------------------------------- -- line 437 ---------------------------------------- . /// use hashbrown::hash_map::DefaultHashBuilder; . /// . /// let s = DefaultHashBuilder::default(); . /// let mut map = HashMap::with_hasher(s); . /// map.insert(1, 2); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn with_hasher_in(hash_builder: S, alloc: A) -> Self { 13 ( 0.00%) Self { . hash_builder, . table: RawTable::new_in(alloc), . } . } . . /// Creates an empty `HashMap` with the specified capacity, using `hash_builder` . /// to hash the keys. It will be allocated with the given allocator. . /// -- line 453 ---------------------------------------- -- line 527 ---------------------------------------- . /// map.insert("c", 3); . /// . /// for key in map.keys() { . /// println!("{}", key); . /// } . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn keys(&self) -> Keys<'_, K, V> { 6 ( 0.00%) Keys { inner: self.iter() } . } . . /// An iterator visiting all values in arbitrary order. . /// The iterator element type is `&'a V`. . /// . /// # Examples . /// . /// ``` -- line 543 ---------------------------------------- -- line 663 ---------------------------------------- . /// . /// let mut a = HashMap::new(); . /// assert_eq!(a.len(), 0); . /// a.insert(1, "a"); . /// assert_eq!(a.len(), 1); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn len(&self) -> usize { 39 ( 0.00%) self.table.len() . } . . /// Returns `true` if the map contains no elements. . /// . /// # Examples . /// . /// ``` . /// use hashbrown::HashMap; -- line 679 ---------------------------------------- -- line 680 ---------------------------------------- . /// . /// let mut a = HashMap::new(); . /// assert!(a.is_empty()); . /// a.insert(1, "a"); . /// assert!(!a.is_empty()); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn is_empty(&self) -> bool { 826 ( 0.00%) self.len() == 0 . } . . /// Clears the map, returning all key-value pairs as an iterator. Keeps the . /// allocated memory for reuse. . /// . /// # Examples . /// . /// ``` -- line 696 ---------------------------------------- -- line 790 ---------------------------------------- . /// use hashbrown::HashMap; . /// . /// let mut a = HashMap::new(); . /// a.insert(1, "a"); . /// a.clear(); . /// assert!(a.is_empty()); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 6 ( 0.00%) pub fn clear(&mut self) { . self.table.clear(); 6 ( 0.00%) } . . /// Creates a consuming iterator visiting all the keys in arbitrary order. . /// The map cannot be used after calling this. . /// The iterator element type is `K`. . /// . /// # Examples . /// . /// ``` -- line 808 ---------------------------------------- -- line 1047 ---------------------------------------- . /// ``` . #[inline] . pub fn get(&self, k: &Q) -> Option<&V> . where . K: Borrow, . Q: Hash + Eq, . { . // Avoid `Option::map` because it bloats LLVM IR. 788 ( 0.00%) match self.get_inner(k) { . Some(&(_, ref v)) => Some(v), . None => None, . } . } . . /// Returns the key-value pair corresponding to the supplied key. . /// . /// The supplied key may be any borrowed form of the map's key type, but -- line 1063 ---------------------------------------- -- line 1091 ---------------------------------------- . } . . #[inline] . fn get_inner(&self, k: &Q) -> Option<&(K, V)> . where . K: Borrow, . Q: Hash + Eq, . { 8,000 ( 0.01%) if self.table.is_empty() { . None . } else { 3 ( 0.00%) let hash = make_hash::(&self.hash_builder, k); . self.table.get(hash, equivalent_key(k)) . } . } . . /// Returns the key-value pair corresponding to the supplied key, with a mutable reference to value. . /// . /// The supplied key may be any borrowed form of the map's key type, but . /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for -- line 1110 ---------------------------------------- -- line 1155 ---------------------------------------- . /// use hashbrown::HashMap; . /// . /// let mut map = HashMap::new(); . /// map.insert(1, "a"); . /// assert_eq!(map.contains_key(&1), true); . /// assert_eq!(map.contains_key(&2), false); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 3,308 ( 0.00%) pub fn contains_key(&self, k: &Q) -> bool . where . K: Borrow, . Q: Hash + Eq, . { . self.get_inner(k).is_some() 6,550 ( 0.01%) } . . /// Returns a mutable reference to the value corresponding to the key. . /// . /// The key may be any borrowed form of the map's key type, but . /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for . /// the key type. . /// . /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html -- line 1177 ---------------------------------------- -- line 1185 ---------------------------------------- . /// let mut map = HashMap::new(); . /// map.insert(1, "a"); . /// if let Some(x) = map.get_mut(&1) { . /// *x = "b"; . /// } . /// assert_eq!(map[&1], "b"); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 1 ( 0.00%) pub fn get_mut(&mut self, k: &Q) -> Option<&mut V> . where . K: Borrow, . Q: Hash + Eq, . { . // Avoid `Option::map` because it bloats LLVM IR. 3 ( 0.00%) match self.get_inner_mut(k) { . Some(&mut (_, ref mut v)) => Some(v), . None => None, . } 2 ( 0.00%) } . . #[inline] . fn get_inner_mut(&mut self, k: &Q) -> Option<&mut (K, V)> . where . K: Borrow, . Q: Hash + Eq, . { 1 ( 0.00%) if self.table.is_empty() { . None . } else { . let hash = make_hash::(&self.hash_builder, k); . self.table.get_mut(hash, equivalent_key(k)) . } . } . . /// Attempts to get mutable references to `N` values in the map at once. -- line 1219 ---------------------------------------- -- line 1495 ---------------------------------------- . /// assert_eq!(map.insert(37, "a"), None); . /// assert_eq!(map.is_empty(), false); . /// . /// map.insert(37, "b"); . /// assert_eq!(map.insert(37, "c"), Some("b")); . /// assert_eq!(map[&37], "c"); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 66,605 ( 0.09%) pub fn insert(&mut self, k: K, v: V) -> Option { . let hash = make_insert_hash::(&self.hash_builder, &k); . if let Some((_, item)) = self.table.get_mut(hash, equivalent_key(&k)) { . Some(mem::replace(item, v)) . } else { 29,015 ( 0.04%) self.table 32,140 ( 0.04%) .insert(hash, (k, v), make_hasher::(&self.hash_builder)); 700 ( 0.00%) None . } 56,886 ( 0.08%) } . . /// Insert a key-value pair into the map without checking . /// if the key already exists in the map. . /// . /// Returns a reference to the key and value just inserted. . /// . /// This operation is safe if a key does not exist in the map. . /// -- line 1520 ---------------------------------------- -- line 1592 ---------------------------------------- . /// use hashbrown::HashMap; . /// . /// let mut map = HashMap::new(); . /// map.insert(1, "a"); . /// assert_eq!(map.remove(&1), Some("a")); . /// assert_eq!(map.remove(&1), None); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 2 ( 0.00%) pub fn remove(&mut self, k: &Q) -> Option . where . K: Borrow, . Q: Hash + Eq, . { . // Avoid `Option::map` because it bloats LLVM IR. 4,728 ( 0.01%) match self.remove_entry(k) { . Some((_, v)) => Some(v), 11 ( 0.00%) None => None, . } 4 ( 0.00%) } . . /// Removes a key from the map, returning the stored key and value if the . /// key was previously in the map. . /// . /// The key may be any borrowed form of the map's key type, but . /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for . /// the key type. . /// -- line 1618 ---------------------------------------- -- line 1631 ---------------------------------------- . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn remove_entry(&mut self, k: &Q) -> Option<(K, V)> . where . K: Borrow, . Q: Hash + Eq, . { . let hash = make_hash::(&self.hash_builder, k); 1,974 ( 0.00%) self.table.remove_entry(hash, equivalent_key(k)) . } . } . . impl HashMap { . /// Creates a raw entry builder for the HashMap. . /// . /// Raw entries provide the lowest level of control for searching and . /// manipulating a map. They must be manually initialized with a hash and -- line 1647 ---------------------------------------- -- line 2209 ---------------------------------------- . /// Creates a `RawEntryMut` from the given key and its hash. . #[inline] . #[allow(clippy::wrong_self_convention)] . pub fn from_key_hashed_nocheck(self, hash: u64, k: &Q) -> RawEntryMut<'a, K, V, S, A> . where . K: Borrow, . Q: Eq, . { 52 ( 0.00%) self.from_hash(hash, equivalent(k)) . } . } . . impl<'a, K, V, S, A: Allocator + Clone> RawEntryBuilderMut<'a, K, V, S, A> { . /// Creates a `RawEntryMut` from the given hash. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::wrong_self_convention)] 212 ( 0.00%) pub fn from_hash(self, hash: u64, is_match: F) -> RawEntryMut<'a, K, V, S, A> . where . for<'b> F: FnMut(&'b K) -> bool, . { . self.search(hash, is_match) 208 ( 0.00%) } . . #[cfg_attr(feature = "inline-more", inline)] . fn search(self, hash: u64, mut is_match: F) -> RawEntryMut<'a, K, V, S, A> . where . for<'b> F: FnMut(&'b K) -> bool, . { . match self.map.table.find(hash, |(k, _)| is_match(k)) { . Some(elem) => RawEntryMut::Occupied(RawOccupiedEntryMut { . elem, . table: &mut self.map.table, . hash_builder: &self.map.hash_builder, . }), 103 ( 0.00%) None => RawEntryMut::Vacant(RawVacantEntryMut { . table: &mut self.map.table, . hash_builder: &self.map.hash_builder, . }), . } . } . } . . impl<'a, K, V, S, A: Allocator + Clone> RawEntryBuilder<'a, K, V, S, A> { -- line 2251 ---------------------------------------- -- line 2260 ---------------------------------------- . { . let hash = make_hash::(&self.map.hash_builder, k); . self.from_key_hashed_nocheck(hash, k) . } . . /// Access an entry by a key and its hash. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::wrong_self_convention)] 1,270 ( 0.00%) pub fn from_key_hashed_nocheck(self, hash: u64, k: &Q) -> Option<(&'a K, &'a V)> . where . K: Borrow, . Q: Eq, . { 1,431 ( 0.00%) self.from_hash(hash, equivalent(k)) 2,540 ( 0.00%) } . . #[cfg_attr(feature = "inline-more", inline)] . fn search(self, hash: u64, mut is_match: F) -> Option<(&'a K, &'a V)> . where . F: FnMut(&K) -> bool, . { 3,762 ( 0.01%) match self.map.table.get(hash, |(k, _)| is_match(k)) { . Some(&(ref key, ref value)) => Some((key, value)), . None => None, . } . } . . /// Access an entry by hash. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::wrong_self_convention)] -- line 2289 ---------------------------------------- -- line 2624 ---------------------------------------- . /// and returns a mutable reference to it. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::shadow_unrelated)] . pub fn insert_hashed_nocheck(self, hash: u64, key: K, value: V) -> (&'a mut K, &'a mut V) . where . K: Hash, . S: BuildHasher, . { 156 ( 0.00%) let &mut (ref mut k, ref mut v) = self.table.insert_entry( . hash, . (key, value), . make_hasher::(self.hash_builder), . ); . (k, v) . } . . /// Set the value of an entry with a custom hasher function. -- line 2640 ---------------------------------------- -- line 2975 ---------------------------------------- . /// map.insert("b", 2); . /// map.insert("c", 3); . /// . /// // Not possible with .iter() . /// let vec: Vec<(&str, i32)> = map.into_iter().collect(); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . fn into_iter(self) -> IntoIter { 137 ( 0.00%) IntoIter { 182 ( 0.00%) inner: self.table.into_iter(), . } . } . } . . impl<'a, K, V> Iterator for Iter<'a, K, V> { . type Item = (&'a K, &'a V); . . #[cfg_attr(feature = "inline-more", inline)] . fn next(&mut self) -> Option<(&'a K, &'a V)> { . // Avoid `Option::map` because it bloats LLVM IR. 178 ( 0.00%) match self.inner.next() { . Some(x) => unsafe { . let r = x.as_ref(); . Some((&r.0, &r.1)) . }, . None => None, . } . } . #[cfg_attr(feature = "inline-more", inline)] . fn size_hint(&self) -> (usize, Option) { 1 ( 0.00%) self.inner.size_hint() . } . } . impl ExactSizeIterator for Iter<'_, K, V> { . #[cfg_attr(feature = "inline-more", inline)] . fn len(&self) -> usize { . self.inner.len() . } . } -- line 3013 ---------------------------------------- -- line 3051 ---------------------------------------- . } . } . . impl Iterator for IntoIter { . type Item = (K, V); . . #[cfg_attr(feature = "inline-more", inline)] . fn next(&mut self) -> Option<(K, V)> { 19 ( 0.00%) self.inner.next() . } . #[cfg_attr(feature = "inline-more", inline)] . fn size_hint(&self) -> (usize, Option) { . self.inner.size_hint() . } . } . impl ExactSizeIterator for IntoIter { . #[cfg_attr(feature = "inline-more", inline)] -- line 3067 ---------------------------------------- -- line 4557 ---------------------------------------- . /// keys with new values returned from the iterator. . impl Extend<(K, V)> for HashMap . where . K: Eq + Hash, . S: BuildHasher, . A: Allocator + Clone, . { . #[cfg_attr(feature = "inline-more", inline)] 140 ( 0.00%) fn extend>(&mut self, iter: T) { . // Keys may be already present or show multiple times in the iterator. . // Reserve the entire hint lower bound if the map is empty. . // Otherwise reserve half the hint (rounded up), so the map . // will only resize twice in the worst case. 133 ( 0.00%) let iter = iter.into_iter(); 26 ( 0.00%) let reserve = if self.is_empty() { . iter.size_hint().0 . } else { 7 ( 0.00%) (iter.size_hint().0 + 1) / 2 . }; . self.reserve(reserve); . iter.for_each(move |(k, v)| { 11,461 ( 0.02%) self.insert(k, v); . }); 70 ( 0.00%) } . . #[inline] . #[cfg(feature = "nightly")] . fn extend_one(&mut self, (k, v): (K, V)) { . self.insert(k, v); . } . . #[inline] -- line 4588 ---------------------------------------- 8,875 ( 0.01%) -------------------------------------------------------------------------------- -- 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}; . 587 ( 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); . } . } . } . }; . } . 370 ( 0.00%) #[derive(Clone)] . pub struct Parser<'a> { 10 ( 0.00%) pub sess: &'a ParseSess, . /// The current token. 8 ( 0.00%) pub token: Token, . /// The spacing for the current token 6 ( 0.00%) pub token_spacing: Spacing, . /// The previous token. 12 ( 0.00%) pub prev_token: Token, 8 ( 0.00%) pub capture_cfg: bool, 18 ( 0.00%) restrictions: Restrictions, 12 ( 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, 12 ( 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. 12 ( 0.00%) unmatched_angle_bracket_count: u32, 18 ( 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. 6 ( 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` 6 ( 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, . } . 24 ( 0.00%) #[derive(Clone)] . struct CaptureState { 24 ( 0.00%) capturing: Capturing, 6 ( 0.00%) replace_ranges: Vec, . inner_attr_ranges: FxHashMap, . } . . impl<'a> Drop for Parser<'a> { . fn drop(&mut self) { 83 ( 0.00%) emit_unclosed_delims(&mut self.unclosed_delims, &self.sess); . } . } . 6,424 ( 0.01%) #[derive(Clone)] . struct TokenCursor { . frame: TokenCursorFrame, 1,734 ( 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. 477 ( 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, . } . 2,955 ( 0.00%) #[derive(Clone)] . struct TokenCursorFrame { 1,313 ( 0.00%) delim: token::DelimToken, . span: DelimSpan, . open_delim: bool, 2,626 ( 0.00%) tree_cursor: tokenstream::Cursor, . close_delim: bool, . } . . impl TokenCursorFrame { . fn new(span: DelimSpan, delim: DelimToken, tts: TokenStream) -> Self { 85 ( 0.00%) TokenCursorFrame { . delim, . span, . open_delim: false, 1,798 ( 0.00%) tree_cursor: tts.into_trees(), . close_delim: false, . } . } . } . . impl TokenCursor { 144,468 ( 0.20%) fn next(&mut self) -> (Token, Spacing) { . loop { 71,409 ( 0.10%) let (tree, spacing) = if !self.frame.open_delim { 1,670 ( 0.00%) self.frame.open_delim = true; 8,350 ( 0.01%) TokenTree::open_tt(self.frame.span, self.frame.delim).into() 139,859 ( 0.19%) } else if let Some(tree) = self.frame.tree_cursor.next_with_spacing() { . tree 6,710 ( 0.01%) } else if !self.frame.close_delim { 1,669 ( 0.00%) self.frame.close_delim = true; 8,345 ( 0.01%) TokenTree::close_tt(self.frame.span, self.frame.delim).into() 3,334 ( 0.00%) } else if let Some(frame) = self.stack.pop() { 21,671 ( 0.03%) self.frame = frame; . continue; . } else { 342 ( 0.00%) (TokenTree::Token(Token::new(token::Eof, DUMMY_SP)), Spacing::Alone) . }; . 27,230 ( 0.04%) match tree { . TokenTree::Token(token) => { 96,312 ( 0.13%) return (token, spacing); . } . TokenTree::Delimited(sp, delim, tts) => { . let frame = TokenCursorFrame::new(sp, delim, tts); . self.stack.push(mem::replace(&mut self.frame, frame)); . } . } . } 96,312 ( 0.13%) } . 34,270 ( 0.05%) fn next_desugared(&mut self) -> (Token, Spacing) { 10,469 ( 0.01%) let (data, attr_style, sp) = match self.next() { 282 ( 0.00%) (Token { kind: token::DocComment(_, attr_style, data), span }, _) => { . (data, attr_style, span) . } 16,665 ( 0.02%) 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; 22,364 ( 0.03%) for ch in data.as_str().chars() { . count = match ch { . '"' => 1, 2 ( 0.00%) '#' if count > 0 => count + 1, . _ => 0, . }; . num_of_hashes = cmp::max(num_of_hashes, count); . } . 376 ( 0.00%) let delim_span = DelimSpan::from_single(sp); 470 ( 0.00%) let body = TokenTree::Delimited( . delim_span, . token::Bracket, 1,128 ( 0.00%) [ 658 ( 0.00%) TokenTree::token(token::Ident(sym::doc, false), sp), 376 ( 0.00%) TokenTree::token(token::Eq, sp), 752 ( 0.00%) TokenTree::token(TokenKind::lit(token::StrRaw(num_of_hashes), data, None), sp), . ] . .iter() . .cloned() . .collect::(), 94 ( 0.00%) ); . . self.stack.push(mem::replace( . &mut self.frame, . TokenCursorFrame::new( . delim_span, . token::NoDelim, 94 ( 0.00%) if attr_style == AttrStyle::Inner { . [TokenTree::token(token::Pound, sp), TokenTree::token(token::Not, sp), body] . .iter() . .cloned() . .collect::() . } else { 1,128 ( 0.00%) [TokenTree::token(token::Pound, sp), body] . .iter() . .cloned() . .collect::() . }, . ), . )); . 282 ( 0.00%) self.next() 30,843 ( 0.04%) } . } . 160 ( 0.00%) #[derive(Debug, Clone, PartialEq)] . enum TokenType { 128 ( 0.00%) Token(TokenKind), . Keyword(Symbol), . Operator, . Lifetime, . Ident, . Path, . Type, . Const, . } -- line 353 ---------------------------------------- -- line 378 ---------------------------------------- . /// The separator token. . sep: Option, . /// `true` if a trailing separator is allowed. . trailing_sep_allowed: bool, . } . . impl SeqSep { . fn trailing_allowed(t: TokenKind) -> SeqSep { 3 ( 0.00%) SeqSep { sep: Some(t), trailing_sep_allowed: true } . } . . fn none() -> SeqSep { . SeqSep { sep: None, trailing_sep_allowed: false } . } . } . . pub enum FollowedByType { . Yes, . No, . } . . fn token_descr_opt(token: &Token) -> Option<&'static str> { 22 ( 0.00%) Some(match token.kind { 44 ( 0.00%) _ if token.is_special_ident() => "reserved identifier", 44 ( 0.00%) _ if token.is_used_keyword() => "keyword", 44 ( 0.00%) _ if token.is_unused_keyword() => "reserved keyword", . token::DocComment(..) => "doc comment", . _ => return None, . }) . } . 77 ( 0.00%) pub(super) fn token_descr(token: &Token) -> String { 22 ( 0.00%) let token_str = pprust::token_to_string(token); . match token_descr_opt(token) { . Some(prefix) => format!("{} `{}`", prefix, token_str), 77 ( 0.00%) _ => format!("`{}`", token_str), . } 55 ( 0.00%) } . . impl<'a> Parser<'a> { 238 ( 0.00%) pub fn new( . sess: &'a ParseSess, . tokens: TokenStream, . desugar_doc_comments: bool, . subparser_name: Option<&'static str>, . ) -> Self { 17 ( 0.00%) let mut start_frame = TokenCursorFrame::new(DelimSpan::dummy(), token::NoDelim, tokens); 34 ( 0.00%) start_frame.open_delim = true; . start_frame.close_delim = true; . 527 ( 0.00%) let mut parser = Parser { . sess, 17 ( 0.00%) token: Token::dummy(), . token_spacing: Spacing::Alone, 17 ( 0.00%) prev_token: Token::dummy(), . capture_cfg: false, . restrictions: Restrictions::empty(), . expected_tokens: Vec::new(), . token_cursor: TokenCursor { 102 ( 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. 34 ( 0.00%) parser.bump(); . . parser 153 ( 0.00%) } . . fn next_tok(&mut self, fallback_span: Span) -> (Token, Spacing) { . loop { 71,406 ( 0.10%) let (mut next, spacing) = if self.desugar_doc_comments { 13,708 ( 0.02%) self.token_cursor.next_desugared() . } else { 25,422 ( 0.03%) self.token_cursor.next() . }; 47,604 ( 0.07%) 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 11,901 ( 0.02%) self.token_cursor.break_last_token = false; 47,604 ( 0.07%) if next.span.is_dummy() { . // Tweak the location for better diagnostics, but keep syntactic context intact. 72 ( 0.00%) next.span = fallback_span.with_ctxt(next.span.ctxt()); . } 40,692 ( 0.06%) if matches!( 23,802 ( 0.03%) next.kind, . token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) . ) { . continue; . } 46,852 ( 0.06%) 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`. 2,385 ( 0.00%) pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> { 265 ( 0.00%) if self.expected_tokens.is_empty() { 108 ( 0.00%) if self.token == *t { 90 ( 0.00%) self.bump(); . Ok(false) . } else { . self.unexpected_try_recover(t) . } . } else { 2,964 ( 0.00%) self.expect_one_of(slice::from_ref(t), &[]) . } 3,975 ( 0.01%) } . . /// 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. 3,492 ( 0.00%) pub fn expect_one_of( . &mut self, . edible: &[TokenKind], . inedible: &[TokenKind], . ) -> PResult<'a, bool /* recovered */> { 582 ( 0.00%) if edible.contains(&self.token.kind) { 741 ( 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) . } 4,365 ( 0.01%) } . . // Public for rustfmt usage. . pub fn parse_ident(&mut self) -> PResult<'a, Ident> { 3,008 ( 0.00%) self.parse_ident_common(true) . } . . fn ident_or_err(&mut self) -> PResult<'a, (Ident, /* is_raw */ bool)> { 2,247 ( 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(), . }) . } . 5,243 ( 0.01%) fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> { 749 ( 0.00%) let (ident, is_raw) = self.ident_or_err()?; 4,494 ( 0.01%) if !is_raw && ident.is_reserved() { . let mut err = self.expected_ident_found(); . if recover { . err.emit(); . } else { . return Err(err); . } . } 2,996 ( 0.00%) self.bump(); . Ok(ident) 7,490 ( 0.01%) } . . /// Checks if the next token is `tok`, and returns `true` if so. . /// . /// This method will automatically add `tok` to `expected_tokens` if `tok` is not . /// encountered. 54,348 ( 0.07%) fn check(&mut self, tok: &TokenKind) -> bool { 23,418 ( 0.03%) let is_present = self.token == *tok; 15,772 ( 0.02%) if !is_present { 30,333 ( 0.04%) self.expected_tokens.push(TokenType::Token(tok.clone())); . } . is_present 54,348 ( 0.07%) } . . /// Consumes a token 'tok' if it exists. Returns whether the given token was present. . pub fn eat(&mut self, tok: &TokenKind) -> bool { 11,676 ( 0.02%) let is_present = self.check(tok); 7,680 ( 0.01%) if is_present { 2,330 ( 0.00%) self.bump() . } . is_present . } . . /// If the next token is the given keyword, returns `true` without eating it. . /// An expectation is also added for diagnostics purposes. 1,040 ( 0.00%) fn check_keyword(&mut self, kw: Symbol) -> bool { 593 ( 0.00%) self.expected_tokens.push(TokenType::Keyword(kw)); 10,371 ( 0.01%) self.token.is_keyword(kw) . } . . /// If the next token is the given keyword, eats it and returns `true`. . /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes. . // Public for rustfmt usage. 2,425 ( 0.00%) pub fn eat_keyword(&mut self, kw: Symbol) -> bool { 2,544 ( 0.00%) if self.check_keyword(kw) { 402 ( 0.00%) self.bump(); . true . } else { . false . } 2,425 ( 0.00%) } . . fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool { 66 ( 0.00%) if self.token.is_keyword(kw) { 15 ( 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. 60 ( 0.00%) fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> { . if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) } 48 ( 0.00%) } . . /// Is the given keyword `kw` followed by a non-reserved identifier? 8,296 ( 0.01%) fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool { 4,148 ( 0.01%) self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()) 9,333 ( 0.01%) } . 1,434 ( 0.00%) fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool { 992 ( 0.00%) if ok { . true . } else { 152 ( 0.00%) self.expected_tokens.push(typ); . false . } 1,434 ( 0.00%) } . . fn check_ident(&mut self) -> bool { 547 ( 0.00%) self.check_or_expected(self.token.is_ident(), TokenType::Ident) . } . 652 ( 0.00%) fn check_path(&mut self) -> bool { 1,570 ( 0.00%) self.check_or_expected(self.token.is_path_start(), TokenType::Path) 815 ( 0.00%) } . . fn check_type(&mut self) -> bool { . self.check_or_expected(self.token.can_begin_type(), TokenType::Type) . } . . fn check_const_arg(&mut self) -> bool { . self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const) . } . 558 ( 0.00%) fn check_inline_const(&self, dist: usize) -> bool { 310 ( 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, . }) 558 ( 0.00%) } . . /// Checks to see if the next token is either `+` or `+=`. . /// Otherwise returns `false`. . fn check_plus(&mut self) -> bool { 56 ( 0.00%) self.check_or_expected( 28 ( 0.00%) self.token.is_like_plus(), 28 ( 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. 2,268 ( 0.00%) fn break_and_eat(&mut self, expected: TokenKind) -> bool { 1,323 ( 0.00%) if self.token.kind == expected { 16 ( 0.00%) self.bump(); . return true; . } 905 ( 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 . } . _ => { 543 ( 0.00%) self.expected_tokens.push(TokenType::Token(expected)); . false . } . } 2,425 ( 0.00%) } . . /// Eats `+` possibly breaking tokens like `+=` in process. . fn eat_plus(&mut self) -> bool { 4 ( 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, ()> { 30 ( 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, ()> { 6 ( 0.00%) if self.break_and_eat(token::BinOp(token::Or)) { Ok(()) } else { self.unexpected() } . } . . /// Eats `<` possibly breaking tokens like `<<` in process. 30 ( 0.00%) fn eat_lt(&mut self) -> bool { 592 ( 0.00%) let ate = self.break_and_eat(token::Lt); 362 ( 0.00%) if ate { . // See doc comment for `unmatched_angle_bracket_count`. 4 ( 0.00%) self.unmatched_angle_bracket_count += 1; 5 ( 0.00%) self.max_angle_bracket_count += 1; . debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count); . } . ate 30 ( 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, ()> { 6 ( 0.00%) if self.break_and_eat(token::Gt) { . // See doc comment for `unmatched_angle_bracket_count`. 3 ( 0.00%) if self.unmatched_angle_bracket_count > 0 { 2 ( 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 { 345 ( 0.00%) TokenExpectType::Expect => self.check(k), 15 ( 0.00%) TokenExpectType::NoExpect => self.token == **k, . }) . } . . fn parse_seq_to_before_tokens( . &mut self, . kets: &[&TokenKind], . sep: SeqSep, . expect: TokenExpectType, -- line 759 ---------------------------------------- -- line 761 ---------------------------------------- . ) -> PResult<'a, (Vec, bool /* trailing */, bool /* recovered */)> { . let mut first = true; . let mut recovered = false; . let mut trailing = false; . let mut v = vec![]; . let unclosed_delims = !self.unclosed_delims.is_empty(); . . while !self.expect_any_with_type(kets, expect) { 305 ( 0.00%) if let token::CloseDelim(..) | token::Eof = self.token.kind { . break; . } 284 ( 0.00%) if let Some(ref t) = sep.sep { 480 ( 0.00%) if first { . first = false; . } else { 21 ( 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; . } . } . } . } . } . } 104 ( 0.00%) if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) { . trailing = true; . break; . } . 50 ( 0.00%) let t = f(self)?; 36 ( 0.00%) v.push(t); . } . 536 ( 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)> { 669 ( 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. 780 ( 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 */)> { 345 ( 0.00%) let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?; 187 ( 0.00%) if !recovered { . self.eat(ket); . } 914 ( 0.00%) Ok((val, trailing)) 624 ( 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)> { 288 ( 0.00%) self.expect(bra)?; 624 ( 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( 129 ( 0.00%) &token::OpenDelim(delim), 180 ( 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. 152,269 ( 0.21%) fn bump_with(&mut self, (next_token, next_spacing): (Token, Spacing)) { . // Bumping after EOF is a bad sign, usually an infinite loop. 70,278 ( 0.10%) 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. 46,852 ( 0.06%) self.prev_token = mem::replace(&mut self.token, next_token); 11,713 ( 0.02%) self.token_spacing = next_spacing; . . // Diagnostics. 11,713 ( 0.02%) self.expected_tokens.clear(); . } . . /// Advance the parser by one token. 93,704 ( 0.13%) pub fn bump(&mut self) { 46,852 ( 0.06%) let next_token = self.next_tok(self.token.span); 70,278 ( 0.10%) self.bump_with(next_token); 93,704 ( 0.13%) } . . /// Look-ahead `dist` tokens of `self.token` and get access to that token there. . /// When `dist == 0` then the current token is looked at. . pub fn look_ahead(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R { 136 ( 0.00%) if dist == 0 { 63 ( 0.00%) return looker(&self.token); . } . 779 ( 0.00%) let frame = &self.token_cursor.frame; 835 ( 0.00%) if frame.delim != DelimToken::NoDelim { . let all_normal = (0..dist).all(|i| { 2,454 ( 0.00%) let token = frame.tree_cursor.look_ahead(i); 3,224 ( 0.00%) !matches!(token, Some(TokenTree::Delimited(_, DelimToken::NoDelim, _))) . }); . if all_normal { 4,058 ( 0.01%) return match frame.tree_cursor.look_ahead(dist - 1) { 1,526 ( 0.00%) Some(tree) => match tree { 742 ( 0.00%) TokenTree::Token(token) => looker(token), . TokenTree::Delimited(dspan, delim, _) => { 130 ( 0.00%) looker(&Token::new(token::OpenDelim(*delim), dspan.open)) . } . }, 423 ( 0.00%) None => looker(&Token::new(token::CloseDelim(frame.delim), frame.span.close)), . }; . } . } . . let mut cursor = self.token_cursor.clone(); . let mut i = 0; 26 ( 0.00%) let mut token = Token::dummy(); . while i < dist { 158 ( 0.00%) token = cursor.next().0; 65 ( 0.00%) if matches!( 40 ( 0.00%) token.kind, . token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) . ) { . continue; . } . i += 1; . } . return looker(&token); . } . . /// Returns whether any of the given keywords are `dist` tokens ahead of the current one. 594 ( 0.00%) fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool { 135 ( 0.00%) self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw))) 594 ( 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. 114 ( 0.00%) fn parse_unsafety(&mut self) -> Unsafe { . if self.eat_keyword(kw::Unsafe) { . Unsafe::Yes(self.prev_token.uninterpolated_span()) . } else { . Unsafe::No . } 456 ( 0.00%) } . . /// Parses constness: `const` or nothing. 696 ( 0.00%) fn parse_constness(&mut self) -> Const { . // Avoid const blocks to be parsed as const items 180 ( 0.00%) if self.look_ahead(1, |t| t != &token::OpenDelim(DelimToken::Brace)) . && self.eat_keyword(kw::Const) . { 40 ( 0.00%) Const::Yes(self.prev_token.uninterpolated_span()) . } else { . Const::No . } 1,218 ( 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 } 10 ( 0.00%) } . . /// Possibly parses mutability (`const` or `mut`). . fn parse_const_or_mut(&mut self) -> Option { . if self.eat_keyword(kw::Mut) { . Some(Mutability::Mut) . } else if self.eat_keyword(kw::Const) { . Some(Mutability::Not) . } else { -- line 1126 ---------------------------------------- -- line 1135 ---------------------------------------- . self.bump(); . Ok(Ident::new(symbol, self.prev_token.span)) . } else { . self.parse_ident_common(true) . } . } . . fn parse_mac_args(&mut self) -> PResult<'a, P> { 434 ( 0.00%) self.parse_mac_args_common(true).map(P) . } . . fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> { 171 ( 0.00%) self.parse_mac_args_common(false) . } . 2,421 ( 0.00%) fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> { 2,152 ( 0.00%) Ok( 1,597 ( 0.00%) if self.check(&token::OpenDelim(DelimToken::Paren)) 189 ( 0.00%) || self.check(&token::OpenDelim(DelimToken::Bracket)) 189 ( 0.00%) || self.check(&token::OpenDelim(DelimToken::Brace)) . { 888 ( 0.00%) match self.parse_token_tree() { 1,110 ( 0.00%) TokenTree::Delimited(dspan, delim, tokens) => . // We've confirmed above that there is a delimiter so unwrapping is OK. . { 444 ( 0.00%) MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens) . } . _ => unreachable!(), . } 94 ( 0.00%) } else if !delimited_only { . if self.eat(&token::Eq) { . let eq_span = self.prev_token.span; . . // Collect tokens because they are used during lowering to HIR. . let expr = self.parse_expr_force_collect()?; . let span = expr.span; . . let token_kind = token::Interpolated(Lrc::new(token::NtExpr(expr))); -- line 1172 ---------------------------------------- -- line 1173 ---------------------------------------- . MacArgs::Eq(eq_span, Token::new(token_kind, span)) . } else { . MacArgs::Empty . } . } else { . return self.unexpected(); . }, . ) 1,883 ( 0.00%) } . . fn parse_or_use_outer_attributes( . &mut self, . already_parsed_attrs: Option, . ) -> PResult<'a, AttrWrapper> { 474 ( 0.00%) if let Some(attrs) = already_parsed_attrs { . Ok(attrs) . } else { 308 ( 0.00%) self.parse_outer_attributes() . } . } . . /// Parses a single token tree from the input. 1,968 ( 0.00%) pub(crate) fn parse_token_tree(&mut self) -> TokenTree { 738 ( 0.00%) match self.token.kind { . token::OpenDelim(..) => { . let depth = self.token_cursor.stack.len(); . . // We keep advancing the token cursor until we hit . // the matching `CloseDelim` token. 22,006 ( 0.03%) 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. 17,556 ( 0.02%) 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; 492 ( 0.00%) let stream = frame.tree_cursor.stream.clone(); 492 ( 0.00%) let span = frame.span; 246 ( 0.00%) let delim = frame.delim; . // Consume close delimiter 492 ( 0.00%) self.bump(); 1,230 ( 0.00%) TokenTree::Delimited(span, delim, stream) . } . token::CloseDelim(_) | token::Eof => unreachable!(), . _ => { . self.bump(); . TokenTree::Token(self.prev_token.clone()) . } . } 1,722 ( 0.00%) } . . /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF. . pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec> { . let mut tts = Vec::new(); . while self.token != token::Eof { . tts.push(self.parse_token_tree()); . } . Ok(tts) -- line 1234 ---------------------------------------- -- line 1244 ---------------------------------------- . } . TokenStream::new(result) . } . . /// Evaluates the closure with restrictions in place. . /// . /// Afters the closure is evaluated, restrictions are reset. . fn with_res(&mut self, res: Restrictions, f: impl FnOnce(&mut Self) -> T) -> T { 236 ( 0.00%) let old = self.restrictions; 314 ( 0.00%) self.restrictions = res; . let res = f(self); 244 ( 0.00%) self.restrictions = old; . res . } . 2,680 ( 0.00%) fn is_crate_vis(&self) -> bool { 1,675 ( 0.00%) self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep) 3,015 ( 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. 900 ( 0.00%) pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> { 180 ( 0.00%) maybe_whole!(self, NtVis, |x| x); . 90 ( 0.00%) self.expected_tokens.push(TokenType::Keyword(kw::Crate)); 360 ( 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". 85 ( 0.00%) return Ok(Visibility { 255 ( 0.00%) span: self.token.span.shrink_to_lo(), . kind: VisibilityKind::Inherited, . tokens: None, . }); . } 5 ( 0.00%) let lo = self.prev_token.span; . 25 ( 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. 7 ( 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)`. . self.bump(); // `(` . self.bump(); // `crate` . self.expect(&token::CloseDelim(token::Paren))?; // `)` . let vis = VisibilityKind::Crate(CrateSugar::PubCrate); . return Ok(Visibility { . span: lo.to(self.prev_token.span), . kind: vis, . tokens: None, . }); 7 ( 0.00%) } else if self.is_keyword_ahead(1, &[kw::In]) { . // Parse `pub(in path)`. . self.bump(); // `(` . self.bump(); // `in` . let path = self.parse_path(PathStyle::Mod)?; // `path` . self.expect(&token::CloseDelim(token::Paren))?; // `)` . let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID }; . return Ok(Visibility { . span: lo.to(self.prev_token.span), . kind: vis, . tokens: None, . }); 4 ( 0.00%) } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) 5 ( 0.00%) && self.is_keyword_ahead(1, &[kw::Super, kw::SelfLower]) . { . // Parse `pub(self)` or `pub(super)`. 3 ( 0.00%) self.bump(); // `(` 1 ( 0.00%) let path = self.parse_path(PathStyle::Mod)?; // `super`/`self` 3 ( 0.00%) self.expect(&token::CloseDelim(token::Paren))?; // `)` 11 ( 0.00%) let vis = VisibilityKind::Restricted { path: P(path), id: ast::DUMMY_NODE_ID }; . return Ok(Visibility { 4 ( 0.00%) span: lo.to(self.prev_token.span), . kind: vis, . tokens: None, . }); . } else if let FollowedByType::No = fbt { . // Provide this diagnostic if a type cannot follow; . // in particular, if this is not a tuple struct. . self.recover_incorrect_vis_restriction()?; . // Emit diagnostic, but continue with public visibility. . } . } . 12 ( 0.00%) Ok(Visibility { span: lo, kind: VisibilityKind::Public, tokens: None }) 810 ( 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 { 48 ( 0.00%) if self.eat_keyword(kw::Extern) { Extern::from_abi(self.parse_abi()) } else { Extern::None } . } . . /// Parses a string literal as an ABI spec. . fn parse_abi(&mut self) -> Option { . match self.parse_str_lit() { . Ok(str_lit) => Some(str_lit), . Err(Some(lit)) => match lit.kind { . ast::LitKind::Err(_) => None, -- line 1386 ---------------------------------------- -- line 1409 ---------------------------------------- . self.collect_tokens_trailing_token( . AttrWrapper::empty(), . ForceCollect::Yes, . |this, _attrs| Ok((f(this)?, TrailingToken::None)), . ) . } . . /// `::{` or `::*` 4,664 ( 0.01%) fn is_import_coupler(&mut self) -> bool { 2,332 ( 0.00%) self.check(&token::ModSep) . && self.look_ahead(1, |t| { 1,893 ( 0.00%) *t == token::OpenDelim(token::Brace) || *t == token::BinOp(token::Star) . }) 4,185 ( 0.01%) } . . 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) . } . 184 ( 0.00%) pub fn emit_unclosed_delims(unclosed_delims: &mut Vec, sess: &ParseSess) { 92 ( 0.00%) *sess.reached_eof.borrow_mut() |= . unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none()); 92 ( 0.00%) for unmatched in unclosed_delims.drain(..) { . if let Some(mut e) = make_unclosed_delims_error(unmatched, sess) { . e.emit(); . } . } 184 ( 0.00%) } . . /// A helper struct used when building an `AttrAnnotatedTokenStream` from . /// a `LazyTokenStream`. Both delimiter and non-delimited tokens . /// are stored as `FlatToken::Token`. A vector of `FlatToken`s . /// is then 'parsed' to build up an `AttrAnnotatedTokenStream` with nested . /// `AttrAnnotatedTokenTree::Delimited` tokens . #[derive(Debug, Clone)] . pub enum FlatToken { -- line 1474 ---------------------------------------- 55,409 ( 0.08%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/str/mod.rs -------------------------------------------------------------------------------- Ir -- line 159 ---------------------------------------- . /// let s = "not empty"; . /// assert!(!s.is_empty()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_str_is_empty", since = "1.39.0")] . #[must_use] . #[inline] . pub const fn is_empty(&self) -> bool { 28,642 ( 0.04%) self.len() == 0 . } . . /// Checks that `index`-th byte is the first byte in a UTF-8 code point . /// sequence or the end of the string. . /// . /// The start and end of the string (when `index == self.len()`) are . /// considered to be boundaries. . /// -- line 175 ---------------------------------------- -- line 193 ---------------------------------------- . #[must_use] . #[stable(feature = "is_char_boundary", since = "1.9.0")] . #[inline] . pub fn is_char_boundary(&self, index: usize) -> bool { . // 0 is always ok. . // Test for 0 explicitly so that it can optimize out the check . // easily and skip reading string data for that case. . // Note that optimizing `self.get(..index)` relies on this. 100,653 ( 0.14%) if index == 0 { . return true; . } . 50,319 ( 0.07%) match self.as_bytes().get(index) { . // For `None` we have two options: . // . // - index == self.len() . // Empty strings are valid, so return true . // - index > self.len() . // In this case return false . // . // The check is placed exactly here, because it improves generated . // code on higher opt-levels. See PR #84751 for more details. 21,377 ( 0.03%) None => index == self.len(), . . // This is bit magic equivalent to: b < 128 || b >= 192 28,945 ( 0.04%) Some(&b) => (b as i8) >= -0x40, . } . } . . /// Converts a string slice to a byte slice. To convert the byte slice back . /// into a string slice, use the [`from_utf8`] function. . /// . /// # Examples . /// -- line 226 ---------------------------------------- -- line 808 ---------------------------------------- . /// . /// assert_eq!(None, iter.next()); . /// ``` . #[must_use = "this returns the split string as an iterator, \ . without modifying the original"] . #[stable(feature = "split_whitespace", since = "1.1.0")] . #[inline] . pub fn split_whitespace(&self) -> SplitWhitespace<'_> { 9 ( 0.00%) SplitWhitespace { inner: self.split(IsWhitespace).filter(IsNotEmpty) } . } . . /// Splits a string slice by ASCII whitespace. . /// . /// The iterator returned will return string slices that are sub-slices of . /// the original string slice, separated by any amount of ASCII whitespace. . /// . /// To split by Unicode `Whitespace` instead, use [`split_whitespace`]. -- line 824 ---------------------------------------- -- line 1056 ---------------------------------------- . /// ``` . /// let s = "Löwe 老虎 Léopard"; . /// let x: &[_] = &['1', '2']; . /// . /// assert_eq!(s.find(x), None); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] 6 ( 0.00%) pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option { 1 ( 0.00%) pat.into_searcher(self).next_match().map(|(i, _)| i) 2 ( 0.00%) } . . /// Returns the byte index for the first character of the rightmost match of the pattern in . /// this string slice. . /// . /// Returns [`None`] if the pattern doesn't match. . /// . /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a . /// function or closure that determines if a character matches. -- line 1074 ---------------------------------------- -- line 1472 ---------------------------------------- . /// . /// ``` . /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect(); . /// assert_eq!(v, ["abc", "defXghi"]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . pub fn splitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> SplitN<'a, P> { 188 ( 0.00%) SplitN(SplitNInternal { iter: self.split(pat).0, count: n }) . } . . /// An iterator over substrings of this string slice, separated by a . /// pattern, starting from the end of the string, restricted to returning . /// at most `n` items. . /// . /// If `n` substrings are returned, the last substring (the `n`th substring) . /// will contain the remainder of the string. -- line 1488 ---------------------------------------- -- line 1540 ---------------------------------------- . /// ``` . /// assert_eq!("cfg".split_once('='), None); . /// assert_eq!("cfg=foo".split_once('='), Some(("cfg", "foo"))); . /// assert_eq!("cfg=foo=bar".split_once('='), Some(("cfg", "foo=bar"))); . /// ``` . #[stable(feature = "str_split_once", since = "1.52.0")] . #[inline] . pub fn split_once<'a, P: Pattern<'a>>(&'a self, delimiter: P) -> Option<(&'a str, &'a str)> { 20 ( 0.00%) let (start, end) = delimiter.into_searcher(self).next_match()?; . // SAFETY: `Searcher` is known to return valid indices. . unsafe { Some((self.get_unchecked(..start), self.get_unchecked(end..))) } . } . . /// Splits the string on the last occurrence of the specified delimiter and . /// returns prefix before delimiter and suffix after delimiter. . /// . /// # Examples -- line 1556 ---------------------------------------- -- line 1749 ---------------------------------------- . /// . /// assert_eq!("Hello\tworld", s.trim()); . /// ``` . #[inline] . #[must_use = "this returns the trimmed string as a slice, \ . without modifying the original"] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn trim(&self) -> &str { 11 ( 0.00%) self.trim_matches(|c: char| c.is_whitespace()) . } . . /// Returns a string slice with leading whitespace removed. . /// . /// 'Whitespace' is defined according to the terms of the Unicode Derived . /// Core Property `White_Space`. . /// . /// # Text directionality -- line 1765 ---------------------------------------- -- line 1945 ---------------------------------------- . /// A more complex pattern, using a closure: . /// . /// ``` . /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar"); . /// ``` . #[must_use = "this returns the trimmed string as a new slice, \ . without modifying the original"] . #[stable(feature = "rust1", since = "1.0.0")] 48 ( 0.00%) pub fn trim_matches<'a, P>(&'a self, pat: P) -> &'a str . where . P: Pattern<'a, Searcher: DoubleEndedSearcher<'a>>, . { . let mut i = 0; . let mut j = 0; . let mut matcher = pat.into_searcher(self); . if let Some((a, b)) = matcher.next_reject() { . i = a; -- line 1961 ---------------------------------------- -- line 1962 ---------------------------------------- . j = b; // Remember earliest known match, correct it below if . // last match is different . } . if let Some((_, b)) = matcher.next_reject_back() { . j = b; . } . // SAFETY: `Searcher` is known to return valid indices. . unsafe { self.get_unchecked(i..j) } 48 ( 0.00%) } . . /// Returns a string slice with all prefixes that match a pattern . /// repeatedly removed. . /// . /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a . /// function or closure that determines if a character matches. . /// . /// [`char`]: prim@char -- line 1978 ---------------------------------------- -- line 1994 ---------------------------------------- . /// assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123"); . /// . /// let x: &[_] = &['1', '2']; . /// assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12"); . /// ``` . #[must_use = "this returns the trimmed string as a new slice, \ . without modifying the original"] . #[stable(feature = "trim_direction", since = "1.30.0")] 6 ( 0.00%) pub fn trim_start_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str { . let mut i = self.len(); . let mut matcher = pat.into_searcher(self); . if let Some((a, _)) = matcher.next_reject() { . i = a; . } . // SAFETY: `Searcher` is known to return valid indices. . unsafe { self.get_unchecked(i..self.len()) } 6 ( 0.00%) } . . /// Returns a string slice with the prefix removed. . /// . /// If the string starts with the pattern `prefix`, returns substring after the prefix, wrapped . /// in `Some`. Unlike `trim_start_matches`, this method removes the prefix exactly once. . /// . /// If the string does not start with `prefix`, returns `None`. . /// -- line 2018 ---------------------------------------- -- line 2240 ---------------------------------------- . /// ``` . /// let nope = "j".parse::(); . /// . /// assert!(nope.is_err()); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn parse(&self) -> Result { 15 ( 0.00%) FromStr::from_str(self) . } . . /// Checks if all characters in this string are within the ASCII range. . /// . /// # Examples . /// . /// ``` . /// let ascii = "hello!\n"; -- line 2256 ---------------------------------------- 37 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe/quoted.rs -------------------------------------------------------------------------------- Ir -- line 33 ---------------------------------------- . /// - `sess`: the parsing session. Any errors will be emitted to this session. . /// - `node_id`: the NodeId of the macro we are parsing. . /// - `features`: language features so we can do feature gating. . /// - `edition`: the edition of the crate defining the macro . /// . /// # Returns . /// . /// A collection of `self::TokenTree`. There may also be some errors emitted to `sess`. 5,057 ( 0.01%) pub(super) fn parse( . input: tokenstream::TokenStream, . expect_matchers: bool, . sess: &ParseSess, . node_id: NodeId, . features: &Features, . edition: Edition, . ) -> Vec { . // Will contain the final collection of `self::TokenTree` . let mut result = Vec::new(); . . // For each token tree in `input`, parse the token into a `self::TokenTree`, consuming . // additional trees if need be. 5,057 ( 0.01%) let mut trees = input.trees(); 11,665 ( 0.02%) while let Some(tree) = trees.next() { . // Given the parsed tree, if there is a metavar and we are expecting matchers, actually . // parse out the matcher (i.e., in `$id:ident` this would parse the `:` and `ident`). 9,720 ( 0.01%) let tree = parse_tree(tree, &mut trees, expect_matchers, sess, node_id, features, edition); 1,412 ( 0.00%) match tree { 300 ( 0.00%) TokenTree::MetaVar(start_sp, ident) if expect_matchers => { 350 ( 0.00%) let span = match trees.next() { 50 ( 0.00%) Some(tokenstream::TokenTree::Token(Token { kind: token::Colon, span })) => { 250 ( 0.00%) match trees.next() { 450 ( 0.00%) Some(tokenstream::TokenTree::Token(token)) => match token.ident() { 100 ( 0.00%) Some((frag, _)) => { 300 ( 0.00%) let span = token.span.with_lo(start_sp.lo()); . . let kind = 200 ( 0.00%) token::NonterminalKind::from_symbol(frag.name, || { . // FIXME(#85708) - once we properly decode a foreign . // crate's `SyntaxContext::root`, then we can replace . // this with just `span.edition()`. A . // `SyntaxContext::root()` from the current crate will . // have the edition of the current crate, and a . // `SyntaxContext::root()` from a foreign crate will . // have the edition of that crate (which we manually . // retrieve via the `edition` parameter). -- line 77 ---------------------------------------- -- line 89 ---------------------------------------- . ); . sess.span_diagnostic . .struct_span_err(span, &msg) . .help(VALID_FRAGMENT_NAMES_MSG) . .emit(); . token::NonterminalKind::Ident . }, . ); 400 ( 0.00%) result.push(TokenTree::MetaVarDecl(span, ident, Some(kind))); . continue; . } . _ => token.span, . }, . tree => tree.as_ref().map_or(span, tokenstream::TokenTree::span), . } 100 ( 0.00%) } . tree => tree.as_ref().map_or(start_sp, tokenstream::TokenTree::span), . }; . if node_id != DUMMY_NODE_ID { . // Macros loaded from other crates have dummy node ids. . sess.missing_fragment_specifiers.borrow_mut().insert(span, node_id); . } . result.push(TokenTree::MetaVarDecl(span, ident, None)); . } . . // Not a metavar or no matchers allowed, so just return the tree 26,516 ( 0.04%) _ => result.push(tree), . } . } . result 3,501 ( 0.00%) } . . /// Takes a `tokenstream::TokenTree` and returns a `self::TokenTree`. Specifically, this takes a . /// generic `TokenTree`, such as is used in the rest of the compiler, and returns a `TokenTree` . /// for use in parsing a macro. . /// . /// Converting the given tree may involve reading more tokens. . /// . /// # Parameters -- line 127 ---------------------------------------- -- line 138 ---------------------------------------- . outer_trees: &mut impl Iterator, . expect_matchers: bool, . sess: &ParseSess, . node_id: NodeId, . features: &Features, . edition: Edition, . ) -> TokenTree { . // Depending on what `tree` is, we could be parsing different parts of a macro 7,204 ( 0.01%) match tree { . // `tree` is a `$` token. Look at the next token in `trees` 252 ( 0.00%) tokenstream::TokenTree::Token(Token { kind: token::Dollar, span }) => { . // FIXME: Handle `None`-delimited groups in a more systematic way . // during parsing. 756 ( 0.00%) let mut next = outer_trees.next(); . let mut trees: Box>; 914 ( 0.00%) if let Some(tokenstream::TokenTree::Delimited(_, token::NoDelim, tts)) = next { . trees = Box::new(tts.into_trees()); . next = trees.next(); . } else { 1,008 ( 0.00%) trees = Box::new(outer_trees); . } . 850 ( 0.00%) match next { . // `tree` is followed by a delimited set of token trees. This indicates the beginning . // of a repetition sequence in the macro (e.g. `$(pat)*`). 553 ( 0.00%) Some(tokenstream::TokenTree::Delimited(span, delim, tts)) => { . // Must have `(` not `{` or `[` 79 ( 0.00%) if delim != token::Paren { . let tok = pprust::token_kind_to_string(&token::OpenDelim(delim)); . let msg = format!("expected `(`, found `{}`", tok); . sess.span_diagnostic.span_err(span.entire(), &msg); . } . // Parse the contents of the sequence itself 711 ( 0.00%) let sequence = parse(tts, expect_matchers, sess, node_id, features, edition); . // Get the Kleene operator and optional separator 474 ( 0.00%) let (separator, kleene) = 79 ( 0.00%) parse_sep_and_kleene_op(&mut trees, span.entire(), sess); . // Count the number of captured "names" (i.e., named metavars) . let name_captures = macro_parser::count_names(&sequence); 632 ( 0.00%) TokenTree::Sequence( . span, . Lrc::new(SequenceRepetition { 316 ( 0.00%) tts: sequence, 395 ( 0.00%) separator, . kleene, . num_captures: name_captures, . }), . ) . } . . // `tree` is followed by an `ident`. This could be `$meta_var` or the `$crate` special . // metavariable that names the crate of the invocation. 1,384 ( 0.00%) Some(tokenstream::TokenTree::Token(token)) if token.is_ident() => { 346 ( 0.00%) let (ident, is_raw) = token.ident().unwrap(); 519 ( 0.00%) let span = ident.span.with_lo(span.lo()); 1,211 ( 0.00%) if ident.name == kw::Crate && !is_raw { 148 ( 0.00%) TokenTree::token(token::Ident(kw::DollarCrate, is_raw), span) . } else { 680 ( 0.00%) TokenTree::MetaVar(span, ident) . } . } . . // `tree` is followed by a random token. This is an error. . Some(tokenstream::TokenTree::Token(token)) => { . let msg = format!( . "expected identifier, found `{}`", . pprust::token_to_string(&token), -- line 204 ---------------------------------------- -- line 208 ---------------------------------------- . } . . // There are no more tokens. Just return the `$` we already have. . None => TokenTree::token(token::Dollar, span), . } . } . . // `tree` is an arbitrary token. Keep it. 7,030 ( 0.01%) tokenstream::TokenTree::Token(token) => TokenTree::Token(token), . . // `tree` is the beginning of a delimited set of tokens (e.g., `(` or `{`). We need to . // descend into the delimited set and further parse it. 2,002 ( 0.00%) tokenstream::TokenTree::Delimited(span, delim, tts) => TokenTree::Delimited( . span, 1,144 ( 0.00%) Lrc::new(Delimited { . delim, 2,288 ( 0.00%) tts: parse(tts, expect_matchers, sess, node_id, features, edition), . }), . ), . } 1,260 ( 0.00%) } . . /// Takes a token and returns `Some(KleeneOp)` if the token is `+` `*` or `?`. Otherwise, return . /// `None`. . fn kleene_op(token: &Token) -> Option { 632 ( 0.00%) match token.kind { . token::BinOp(token::Star) => Some(KleeneOp::ZeroOrMore), . token::BinOp(token::Plus) => Some(KleeneOp::OneOrMore), . token::Question => Some(KleeneOp::ZeroOrOne), . _ => None, . } . } . . /// Parse the next token tree of the input looking for a KleeneOp. Returns . /// . /// - Ok(Ok((op, span))) if the next token tree is a KleeneOp . /// - Ok(Err(tok, span)) if the next token tree is a token but not a KleeneOp . /// - Err(span) if the next token tree is not a token 400 ( 0.00%) fn parse_kleene_op( . input: &mut impl Iterator, . span: Span, . ) -> Result, Span> { 160 ( 0.00%) match input.next() { 160 ( 0.00%) Some(tokenstream::TokenTree::Token(token)) => match kleene_op(&token) { 237 ( 0.00%) Some(op) => Ok(Ok((op, token.span))), 9 ( 0.00%) None => Ok(Err(token)), . }, . tree => Err(tree.as_ref().map_or(span, tokenstream::TokenTree::span)), . } 320 ( 0.00%) } . . /// Attempt to parse a single Kleene star, possibly with a separator. . /// . /// For example, in a pattern such as `$(a),*`, `a` is the pattern to be repeated, `,` is the . /// separator, and `*` is the Kleene operator. This function is specifically concerned with parsing . /// the last two tokens of such a pattern: namely, the optional separator and the Kleene operator . /// itself. Note that here we are parsing the _macro_ itself, rather than trying to match some . /// stream of tokens in an invocation of a macro. -- line 265 ---------------------------------------- -- line 269 ---------------------------------------- . /// operator and separator, then a tuple with `(separator, KleeneOp)` is returned. Otherwise, an . /// error with the appropriate span is emitted to `sess` and a dummy value is returned. . fn parse_sep_and_kleene_op( . input: &mut impl Iterator, . span: Span, . sess: &ParseSess, . ) -> (Option, KleeneToken) { . // We basically look at two token trees here, denoted as #1 and #2 below 632 ( 0.00%) let span = match parse_kleene_op(input, span) { . // #1 is a `?`, `+`, or `*` KleeneOp 234 ( 0.00%) Ok(Ok((op, span))) => return (None, KleeneToken::new(op, span)), . . // #1 is a separator followed by #2, a KleeneOp 15 ( 0.00%) Ok(Err(token)) => match parse_kleene_op(input, token.span) { . // #2 is the `?` Kleene op, which does not take a separator (error) . Ok(Ok((KleeneOp::ZeroOrOne, span))) => { . // Error! . sess.span_diagnostic.span_err( . token.span, . "the `?` macro repetition operator does not take a separator", . ); . . // Return a dummy . return (None, KleeneToken::new(KleeneOp::ZeroOrMore, span)); . } . . // #2 is a KleeneOp :D 6 ( 0.00%) Ok(Ok((op, span))) => return (Some(token), KleeneToken::new(op, span)), . . // #2 is a random token or not a token at all :( . Ok(Err(Token { span, .. })) | Err(span) => span, . }, . . // #1 is not a token . Err(span) => span, . }; -- line 304 ---------------------------------------- 7,183 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/std/src/sys/unix/alloc.rs -------------------------------------------------------------------------------- Ir -- line 5 ---------------------------------------- . #[stable(feature = "alloc_system_type", since = "1.28.0")] . unsafe impl GlobalAlloc for System { . #[inline] . unsafe fn alloc(&self, layout: Layout) -> *mut u8 { . // jemalloc provides alignment less than MIN_ALIGN for small allocations. . // So only rely on MIN_ALIGN if size >= align. . // Also see and . // . 44,838 ( 0.06%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 33,627 ( 0.05%) 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. 28 ( 0.00%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 42 ( 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) { 11,206 ( 0.02%) libc::free(ptr as *mut libc::c_void) . } . . #[inline] . unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { 5,356 ( 0.01%) if layout.align() <= MIN_ALIGN && layout.align() <= new_size { 10,712 ( 0.01%) libc::realloc(ptr as *mut libc::c_void, new_size) as *mut u8 . } else { . realloc_fallback(self, ptr, layout, new_size) . } . } . } . . cfg_if::cfg_if! { . if #[cfg(any( -- line 56 ---------------------------------------- -- line 84 ---------------------------------------- . } else if #[cfg(target_os = "wasi")] { . #[inline] . unsafe fn aligned_malloc(layout: &Layout) -> *mut u8 { . libc::aligned_alloc(layout.align(), layout.size()) as *mut u8 . } . } else { . #[inline] . unsafe fn aligned_malloc(layout: &Layout) -> *mut u8 { 1 ( 0.00%) let mut out = ptr::null_mut(); . // posix_memalign requires that the alignment be a multiple of `sizeof(void*)`. . // Since these are all powers of 2, we can just use max. . let align = layout.align().max(crate::mem::size_of::()); 2 ( 0.00%) let ret = libc::posix_memalign(&mut out, align, layout.size()); 2 ( 0.00%) if ret != 0 { ptr::null_mut() } else { out as *mut u8 } . } . } . } 1 ( 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. 42,946 ( 0.06%) #[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`. -- line 520 ---------------------------------------- -- 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 { 10,604 ( 0.01%) 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> { 26,692 ( 0.04%) 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> { 12,816 ( 0.02%) 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 { 4,384 ( 0.01%) match self { 164 ( 0.00%) Some(val) => val, . None => expect_failed(msg), . } . } . . /// Returns the contained [`Some`] value, consuming the `self` value. . /// . /// Because this function may panic, its use is generally discouraged. . /// Instead, prefer to use pattern matching and handle the [`None`] -- line 722 ---------------------------------------- -- line 742 ---------------------------------------- . /// let x: Option<&str> = None; . /// assert_eq!(x.unwrap(), "air"); // fails . /// ``` . #[inline] . #[track_caller] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] . pub const fn unwrap(self) -> T { 13,759 ( 0.02%) match self { 1,032 ( 0.00%) 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, . { 4,147 ( 0.01%) match self { . Some(x) => x, 4 ( 0.00%) None => default, . } 73 ( 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); -- line 789 ---------------------------------------- -- line 792 ---------------------------------------- . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn unwrap_or_else(self, f: F) -> T . where . F: ~const FnOnce() -> T, . F: ~const Drop, . { 26,257 ( 0.04%) match self { 756 ( 0.00%) Some(x) => x, . None => f(), . } 6 ( 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, . { 36 ( 0.00%) match self { 9 ( 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 897 ---------------------------------------- . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn map(self, f: F) -> Option . where . F: ~const FnOnce(T) -> U, . F: ~const Drop, . { 11,101 ( 0.02%) match self { 19,116 ( 0.03%) Some(x) => Some(f(x)), 3,463 ( 0.00%) None => None, . } 388 ( 0.00%) } . . /// Calls the provided closure with a reference to the contained value (if [`Some`]). . /// . /// # Examples . /// . /// ``` . /// #![feature(result_option_inspect)] . /// -- line 917 ---------------------------------------- -- line 960 ---------------------------------------- . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn map_or(self, default: U, f: F) -> U . where . F: ~const FnOnce(T) -> U, . F: ~const Drop, . U: ~const Drop, . { 3,025 ( 0.00%) match self { 336 ( 0.00%) Some(t) => f(t), . None => default, . } . } . . /// Computes a default function result (if none), or . /// applies a different function to the contained value (if any). . /// . /// # Examples -- line 977 ---------------------------------------- -- 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, . { 10 ( 0.00%) match self { . Some(t) => f(t), . None => default(), . } . } . . /// Transforms the `Option` into a [`Result`], mapping [`Some(v)`] to . /// [`Ok(v)`] and [`None`] to [`Err(err)`]. . /// -- line 1006 ---------------------------------------- -- 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, . { 4,786 ( 0.01%) match self { . Some(v) => Ok(v), . None => Err(err), . } . } . . /// Transforms the `Option` into a [`Result`], mapping [`Some(v)`] to . /// [`Ok(v)`] and [`None`] to [`Err(err())`]. . /// -- line 1040 ---------------------------------------- -- 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, . { 1,606 ( 0.00%) match self { 45 ( 0.00%) Some(v) => Ok(v), 57 ( 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, . { 7 ( 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 1218 ---------------------------------------- . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn and_then(self, f: F) -> Option . where . F: ~const FnOnce(T) -> Option, . F: ~const Drop, . { 3,134 ( 0.00%) match self { 119 ( 0.00%) Some(x) => f(x), . None => None, . } . } . . /// 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 -- line 1235 ---------------------------------------- -- 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, . { 33 ( 0.00%) if let Some(x) = self { . if predicate(&x) { . return Some(x); . } . } . None . } . . /// Returns the option if it contains a value, otherwise returns `optb`. -- line 1273 ---------------------------------------- -- 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, . { 27 ( 0.00%) match self { . Some(x) => Some(x), . None => optb, . } . } . . /// Returns the option if it contains a value, otherwise calls `f` and . /// returns the result. . /// -- line 1315 ---------------------------------------- -- line 1326 ---------------------------------------- . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn or_else(self, f: F) -> Option . where . F: ~const FnOnce() -> Option, . F: ~const Drop, . { 116 ( 0.00%) match self { 12 ( 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 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, . { 5,701 ( 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 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 57 ( 0.00%) match self { 2,088 ( 0.00%) Some(&v) => Some(v), . None => None, . } . } . . /// Maps an `Option<&T>` to an `Option` by cloning the contents of the . /// option. . /// . /// # Examples -- line 1729 ---------------------------------------- -- line 1737 ---------------------------------------- . /// ``` . #[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")] . pub const fn cloned(self) -> Option . where . T: ~const Clone, . { 52 ( 0.00%) match self { 118 ( 0.00%) Some(t) => Some(t.clone()), 10 ( 0.00%) None => None, . } 55 ( 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 { 2,294 ( 0.00%) match self { 75 ( 0.00%) Some(x) => Some(x.clone()), 68 ( 0.00%) None => None, . } 363 ( 0.00%) } . . #[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 2245 ---------------------------------------- . . #[inline] . fn from_output(output: Self::Output) -> Self { . Some(output) . } . . #[inline] . fn branch(self) -> ControlFlow { 3,361 ( 0.00%) match self { 7,885 ( 0.01%) 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 { 21 ( 0.00%) None => None, . } . } . } . . #[unstable(feature = "try_trait_v2_residual", issue = "91285")] . impl ops::Residual for Option { . type TryType = Option; . } -- line 2274 ---------------------------------------- 113,241 ( 0.15%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_metadata/src/rmeta/encoder.rs -------------------------------------------------------------------------------- Ir -- line 83 ---------------------------------------- . if $self.is_proc_macro { . return Lazy::empty(); . } . }; . } . . macro_rules! encoder_methods { . ($($name:ident($ty:ty);)*) => { 7,145 ( 0.01%) $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> { . self.opaque.$name(value) 8,574 ( 0.01%) })* . } . } . . impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> { . type Error = ::Error; . . #[inline] . fn emit_unit(&mut self) -> Result<(), Self::Error> { -- line 101 ---------------------------------------- -- line 125 ---------------------------------------- . emit_raw_bytes(&[u8]); . } . } . . impl<'a, 'tcx, T: Encodable>> Encodable> . for Lazy . { . fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { 23 ( 0.00%) e.emit_lazy_distance(*self) . } . } . . impl<'a, 'tcx, T: Encodable>> Encodable> . for Lazy<[T]> . { 5 ( 0.00%) fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { . e.emit_usize(self.meta)?; 28 ( 0.00%) if self.meta == 0 { . return Ok(()); . } 21 ( 0.00%) e.emit_lazy_distance(*self) . } . } . . impl<'a, 'tcx, I: Idx, T: Encodable>> Encodable> . for Lazy> . where . Option: FixedSizeEncoding, . { . fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { . e.emit_usize(self.meta)?; 144 ( 0.00%) e.emit_lazy_distance(*self) . } . } . . impl<'a, 'tcx> Encodable> for CrateNum { 91 ( 0.00%) fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { 40 ( 0.00%) if *self != LOCAL_CRATE && s.is_proc_macro { . panic!("Attempted to encode non-local CrateNum {:?} for proc-macro crate", self); . } . s.emit_u32(self.as_u32()) 78 ( 0.00%) } . } . . impl<'a, 'tcx> Encodable> for DefIndex { 35 ( 0.00%) fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { . s.emit_u32(self.as_u32()) 42 ( 0.00%) } . } . . impl<'a, 'tcx> Encodable> for ExpnIndex { . fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { . s.emit_u32(self.as_u32()) . } . } . . impl<'a, 'tcx> Encodable> for SyntaxContext { 15,865 ( 0.02%) fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { 9,519 ( 0.01%) rustc_span::hygiene::raw_encode_syntax_context(*self, &s.hygiene_ctxt, s) 19,038 ( 0.03%) } . } . . impl<'a, 'tcx> Encodable> for ExpnId { . fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { 11 ( 0.00%) if self.krate == LOCAL_CRATE { . // We will only write details for local expansions. Non-local expansions will fetch . // data from the corresponding crate's metadata. . // FIXME(#43047) FIXME(#74731) We may eventually want to avoid relying on external . // metadata from proc-macro crates. 40 ( 0.00%) s.hygiene_ctxt.schedule_expn_data_for_encoding(*self); . } 28 ( 0.00%) self.krate.encode(s)?; . self.local_id.encode(s) . } . } . . impl<'a, 'tcx> Encodable> for Span { 25,336 ( 0.03%) fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { 19,002 ( 0.03%) let span = self.data(); . . // Don't serialize any `SyntaxContext`s from a proc-macro crate, . // since we don't load proc-macro dependencies during serialization. . // This means that any hygiene information from macros used *within* . // a proc-macro crate (e.g. invoking a macro that expands to a proc-macro . // definition) will be lost. . // . // This can show up in two ways: -- line 211 ---------------------------------------- -- line 228 ---------------------------------------- . // None of these user-visible effects should result in any . // cross-crate inconsistencies (getting one behavior in the same . // crate, and a different behavior in another crate) due to the . // limited surface that proc-macros can expose. . // . // IMPORTANT: If this is ever changed, be sure to update . // `rustc_span::hygiene::raw_encode_expn_id` to handle . // encoding `ExpnData` for proc-macro crates. 6,334 ( 0.01%) if s.is_proc_macro { . SyntaxContext::root().encode(s)?; . } else { 3,167 ( 0.00%) span.ctxt.encode(s)?; . } . 3,167 ( 0.00%) if self.is_dummy() { . return TAG_PARTIAL_SPAN.encode(s); . } . . // The Span infrastructure should make sure that this invariant holds: . debug_assert!(span.lo <= span.hi); . 15,755 ( 0.02%) if !s.source_file_cache.0.contains(span.lo) { . let source_map = s.tcx.sess.source_map(); . let source_file_index = source_map.lookup_source_file_idx(span.lo); . s.source_file_cache = . (source_map.files()[source_file_index].clone(), source_file_index); . } . 9,453 ( 0.01%) if !s.source_file_cache.0.contains(span.hi) { . // Unfortunately, macro expansion still sometimes generates Spans . // that malformed in this way. . return TAG_PARTIAL_SPAN.encode(s); . } . . let source_files = s.required_source_files.as_mut().expect("Already encoded SourceMap!"); . // Record the fact that we need to encode the data for this `SourceFile` 3,151 ( 0.00%) source_files.insert(s.source_file_cache.1); . . // There are two possible cases here: . // 1. This span comes from a 'foreign' crate - e.g. some crate upstream of the . // crate we are writing metadata for. When the metadata for *this* crate gets . // deserialized, the deserializer will need to know which crate it originally came . // from. We use `TAG_VALID_SPAN_FOREIGN` to indicate that a `CrateNum` should . // be deserialized after the rest of the span data, which tells the deserializer . // which crate contains the source map information. -- line 272 ---------------------------------------- -- line 274 ---------------------------------------- . // write `TAG_VALID_SPAN_LOCAL` to let the deserializer know that it should use . // our own source map information. . // . // If we're a proc-macro crate, we always treat this as a local `Span`. . // In `encode_source_map`, we serialize foreign `SourceFile`s into our metadata . // if we're a proc-macro crate. . // This allows us to avoid loading the dependencies of proc-macro crates: all of . // the information we need to decode `Span`s is stored in the proc-macro crate. 18,906 ( 0.03%) let (tag, lo, hi) = if s.source_file_cache.0.is_imported() && !s.is_proc_macro { . // To simplify deserialization, we 'rebase' this span onto the crate it originally came from . // (the crate that 'owns' the file it references. These rebased 'lo' and 'hi' values . // are relative to the source map information for the 'foreign' crate whose CrateNum . // we write into the metadata. This allows `imported_source_files` to binary . // search through the 'foreign' crate's source map information, using the . // deserialized 'lo' and 'hi' values directly. . // . // All of this logic ensures that the final result of deserialization is a 'normal' -- line 290 ---------------------------------------- -- line 296 ---------------------------------------- . src => panic!("Unexpected external source {:?}", src), . } . }; . let lo = (span.lo - s.source_file_cache.0.start_pos) + external_start_pos; . let hi = (span.hi - s.source_file_cache.0.start_pos) + external_start_pos; . . (TAG_VALID_SPAN_FOREIGN, lo, hi) . } else { 9,453 ( 0.01%) (TAG_VALID_SPAN_LOCAL, span.lo, span.hi) . }; . . tag.encode(s)?; . lo.encode(s)?; . . // Encode length which is usually less than span.hi and profits more . // from the variable-length integer encoding that we use. . let len = hi - lo; . len.encode(s)?; . 6,302 ( 0.01%) if tag == TAG_VALID_SPAN_FOREIGN { . // This needs to be two lines to avoid holding the `s.source_file_cache` . // while calling `cnum.encode(s)` . let cnum = s.source_file_cache.0.cnum; . cnum.encode(s)?; . } . . Ok(()) 25,336 ( 0.03%) } . } . . impl<'a, 'tcx> TyEncoder<'tcx> for EncodeContext<'a, 'tcx> { . const CLEAR_CROSS_CRATE: bool = true; . . fn position(&self) -> usize { . self.opaque.position() . } -- line 331 ---------------------------------------- -- line 361 ---------------------------------------- . } . . /// Helper trait to allow overloading `EncodeContext::lazy` for iterators. . trait EncodeContentsForLazy<'a, 'tcx, T: ?Sized + LazyMeta> { . fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> T::Meta; . } . . impl<'a, 'tcx, T: Encodable>> EncodeContentsForLazy<'a, 'tcx, T> for &T { 70 ( 0.00%) fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) { 27 ( 0.00%) self.encode(ecx).unwrap() 6 ( 0.00%) } . } . . impl<'a, 'tcx, T: Encodable>> EncodeContentsForLazy<'a, 'tcx, T> for T { 131 ( 0.00%) fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) { 65 ( 0.00%) self.encode(ecx).unwrap() 75 ( 0.00%) } . } . . impl<'a, 'tcx, I, T: Encodable>> EncodeContentsForLazy<'a, 'tcx, [T]> for I . where . I: IntoIterator, . I::Item: EncodeContentsForLazy<'a, 'tcx, T>, . { 7 ( 0.00%) fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> usize { 1,391 ( 0.00%) self.into_iter().map(|value| value.encode_contents_for_lazy(ecx)).count() 9 ( 0.00%) } . } . . // Shorthand for `$self.$tables.$table.set($def_id.index, $self.lazy($value))`, which would . // normally need extra variables to avoid errors about multiple mutable borrows. . macro_rules! record { . ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{ . { . let value = $value; . let lazy = $self.lazy(value); . $self.$tables.$table.set($def_id.index, lazy); . } . }}; . } . . impl<'a, 'tcx> EncodeContext<'a, 'tcx> { 210 ( 0.00%) fn emit_lazy_distance( . &mut self, . lazy: Lazy, . ) -> Result<(), ::Error> { . let pos = lazy.position.get(); 200 ( 0.00%) let distance = match self.lazy_state { . LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"), 5 ( 0.00%) LazyState::NodeStart(start) => { . let start = start.get(); 10 ( 0.00%) assert!(pos <= start); . start - pos . } 37 ( 0.00%) LazyState::Previous(last_pos) => { 37 ( 0.00%) assert!( . last_pos <= lazy.position, . "make sure that the calls to `lazy*` \ . are in the same order as the metadata fields", . ); 111 ( 0.00%) lazy.position.get() - last_pos.get() . } . }; 84 ( 0.00%) self.lazy_state = LazyState::Previous(NonZeroUsize::new(pos).unwrap()); . self.emit_usize(distance) 210 ( 0.00%) } . 48 ( 0.00%) fn lazy( . &mut self, . value: impl EncodeContentsForLazy<'a, 'tcx, T>, . ) -> Lazy { . let pos = NonZeroUsize::new(self.position()).unwrap(); . 86 ( 0.00%) assert_eq!(self.lazy_state, LazyState::NoNode); 230 ( 0.00%) self.lazy_state = LazyState::NodeStart(pos); 121 ( 0.00%) let meta = value.encode_contents_for_lazy(self); 87 ( 0.00%) self.lazy_state = LazyState::NoNode; . 171 ( 0.00%) assert!(pos.get() <= self.position()); . . Lazy::from_position_and_meta(pos, meta) 72 ( 0.00%) } . . fn encode_info_for_items(&mut self) { 9 ( 0.00%) self.encode_info_for_mod(CRATE_DEF_ID, self.tcx.hir().root_module()); . . // Proc-macro crates only export proc-macro items, which are looked . // up using `proc_macro_data` 2 ( 0.00%) if self.is_proc_macro { . return; . } . 6 ( 0.00%) self.tcx.hir().visit_all_item_likes(&mut self.as_deep_visitor()); . } . . fn encode_def_path_table(&mut self) { 4 ( 0.00%) let table = self.tcx.resolutions(()).definitions.def_path_table(); 2 ( 0.00%) if self.is_proc_macro { . for def_index in std::iter::once(CRATE_DEF_INDEX) . .chain(self.tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index)) . { . let def_key = self.lazy(table.def_key(def_index)); . let def_path_hash = self.lazy(table.def_path_hash(def_index)); . self.tables.def_keys.set(def_index, def_key); . self.tables.def_path_hashes.set(def_index, def_path_hash); . } . } else { 5 ( 0.00%) for (def_index, def_key, def_path_hash) in table.enumerated_keys_and_path_hashes() { . let def_key = self.lazy(def_key); . let def_path_hash = self.lazy(def_path_hash); 32 ( 0.00%) self.tables.def_keys.set(def_index, def_key); 32 ( 0.00%) self.tables.def_path_hashes.set(def_index, def_path_hash); . } . } . } . . fn encode_def_path_hash_map(&mut self) -> Lazy> { . self.lazy(DefPathHashMapRef::BorrowedFromTcx( 2 ( 0.00%) self.tcx.resolutions(()).definitions.def_path_hash_to_def_index_map(), . )) . } . . fn encode_source_map(&mut self) -> Lazy<[rustc_span::SourceFile]> { 2 ( 0.00%) let source_map = self.tcx.sess.source_map(); 3 ( 0.00%) let all_source_files = source_map.files(); . . // By replacing the `Option` with `None`, we ensure that we can't . // accidentally serialize any more `Span`s after the source map encoding . // is done. . let required_source_files = self.required_source_files.take().unwrap(); . . let adapted = all_source_files . .iter() . .enumerate() . .filter(|(idx, source_file)| { . // Only serialize `SourceFile`s that were used . // during the encoding of a `Span` 627 ( 0.00%) required_source_files.contains(*idx) && . // Don't serialize imported `SourceFile`s, unless . // we're in a proc-macro crate. 5 ( 0.00%) (!source_file.is_imported() || self.is_proc_macro) . }) . .map(|(_, source_file)| { 3 ( 0.00%) let mut adapted = match source_file.name { . FileName::Real(ref realname) => { 2 ( 0.00%) let mut adapted = (**source_file).clone(); 16 ( 0.00%) adapted.name = FileName::Real(match realname { . RealFileName::LocalPath(path_to_file) => { . // Prepend path of working directory onto potentially . // relative paths, because they could become relative . // to a wrong directory. . // We include `working_dir` as part of the crate hash, . // so it's okay for us to use it as part of the encoded . // metadata. 2 ( 0.00%) let working_dir = &self.tcx.sess.opts.working_dir; 2 ( 0.00%) match working_dir { . RealFileName::LocalPath(absolute) => { . // Although neither working_dir or the file name were subject . // to path remapping, the concatenation between the two may . // be. Hence we need to do a remapping here. . let joined = Path::new(absolute).join(path_to_file); 7 ( 0.00%) let (joined, remapped) = 11 ( 0.00%) source_map.path_mapping().map_prefix(joined); 2 ( 0.00%) if remapped { . RealFileName::Remapped { . local_path: None, . virtual_name: joined, . } . } else { . RealFileName::LocalPath(joined) . } . } -- line 532 ---------------------------------------- -- line 544 ---------------------------------------- . RealFileName::Remapped { local_path: _, virtual_name } => { . RealFileName::Remapped { . // We do not want any local path to be exported into metadata . local_path: None, . virtual_name: virtual_name.clone(), . } . } . }); 2 ( 0.00%) adapted.name_hash = { . let mut hasher: StableHasher = StableHasher::new(); 1 ( 0.00%) adapted.name.hash(&mut hasher); . hasher.finish::() . }; 1 ( 0.00%) Lrc::new(adapted) . } . . // expanded code, not from a file . _ => source_file.clone(), . }; . . // We're serializing this `SourceFile` into our crate metadata, . // so mark it as coming from this crate. . // This also ensures that we don't try to deserialize the . // `CrateNum` for a proc-macro dependency - since proc macro . // dependencies aren't loaded when we deserialize a proc-macro, . // trying to remap the `CrateNum` would fail. 2 ( 0.00%) if self.is_proc_macro { . Lrc::make_mut(&mut adapted).cnum = LOCAL_CRATE; . } . adapted . }) . .collect::>(); . . self.lazy(adapted.iter().map(|rc| &**rc)) . } . 8 ( 0.00%) fn encode_crate_root(&mut self) -> Lazy> { . let mut i = self.position(); . . // Encode the crate deps . let crate_deps = self.encode_crate_deps(); . let dylib_dependency_formats = self.encode_dylib_dependency_formats(); 5 ( 0.00%) let dep_bytes = self.position() - i; . . // Encode the lib features. . i = self.position(); . let lib_features = self.encode_lib_features(); 7 ( 0.00%) let lib_feature_bytes = self.position() - i; . . // Encode the language items. . i = self.position(); . let lang_items = self.encode_lang_items(); . let lang_items_missing = self.encode_lang_items_missing(); 5 ( 0.00%) let lang_item_bytes = self.position() - i; . . // Encode the diagnostic items. . i = self.position(); . let diagnostic_items = self.encode_diagnostic_items(); 5 ( 0.00%) let diagnostic_item_bytes = self.position() - i; . . // Encode the native libraries used . i = self.position(); . let native_libraries = self.encode_native_libraries(); 4 ( 0.00%) let native_lib_bytes = self.position() - i; . . let foreign_modules = self.encode_foreign_modules(); . . // Encode DefPathTable . i = self.position(); . self.encode_def_path_table(); 5 ( 0.00%) let def_path_table_bytes = self.position() - i; . . // Encode the def IDs of traits, for rustdoc and diagnostics. . i = self.position(); . let traits = self.encode_traits(); 5 ( 0.00%) let traits_bytes = self.position() - i; . . // Encode the def IDs of impls, for coherence checking. . i = self.position(); . let impls = self.encode_impls(); 5 ( 0.00%) let impls_bytes = self.position() - i; . 3 ( 0.00%) let tcx = self.tcx; . . // Encode MIR. . i = self.position(); . self.encode_mir(); 5 ( 0.00%) let mir_bytes = self.position() - i; . . // Encode the items. . i = self.position(); . self.encode_def_ids(); . self.encode_info_for_items(); 4 ( 0.00%) let item_bytes = self.position() - i; . . // Encode the allocation index . let interpret_alloc_index = { . let mut interpret_alloc_index = Vec::new(); . let mut n = 0; . trace!("beginning to encode alloc ids"); . loop { . let new_n = self.interpret_allocs.len(); . // if we have found new ids, serialize those, too 2 ( 0.00%) if n == new_n { . // otherwise, abort . break; . } . trace!("encoding {} further alloc ids", new_n - n); . for idx in n..new_n { . let id = self.interpret_allocs[idx]; . let pos = self.position() as u32; . interpret_alloc_index.push(pos); . interpret::specialized_encode_alloc_id(self, tcx, id).unwrap(); . } . n = new_n; . } 6 ( 0.00%) self.lazy(interpret_alloc_index) . }; . . // Encode the proc macro data. This affects 'tables', . // so we need to do this before we encode the tables . i = self.position(); . let proc_macro_data = self.encode_proc_macros(); 4 ( 0.00%) let proc_macro_data_bytes = self.position() - i; . . i = self.position(); 4 ( 0.00%) let tables = self.tables.encode(&mut self.opaque); 4 ( 0.00%) let tables_bytes = self.position() - i; . . // Encode exported symbols info. This is prefetched in `encode_metadata` so we encode . // this as late as possible to give the prefetching as much time as possible to complete. . i = self.position(); . let exported_symbols = tcx.exported_symbols(LOCAL_CRATE); . let exported_symbols = self.encode_exported_symbols(&exported_symbols); 4 ( 0.00%) let exported_symbols_bytes = self.position() - i; . . // Encode the hygiene data, . // IMPORTANT: this *must* be the last thing that we encode (other than `SourceMap`). The process . // of encoding other items (e.g. `optimized_mir`) may cause us to load . // data from the incremental cache. If this causes us to deserialize a `Span`, . // then we may load additional `SyntaxContext`s into the global `HygieneData`. . // Therefore, we need to encode the hygiene data last to ensure that we encode . // any `SyntaxContext`s that might be used. . i = self.position(); . let (syntax_contexts, expn_data, expn_hashes) = self.encode_hygiene(); 5 ( 0.00%) let hygiene_bytes = self.position() - i; . . i = self.position(); . let def_path_hash_map = self.encode_def_path_hash_map(); 1 ( 0.00%) let def_path_hash_map_bytes = self.position() - i; . . // Encode source_map. This needs to be done last, . // since encoding `Span`s tells us which `SourceFiles` we actually . // need to encode. . i = self.position(); . let source_map = self.encode_source_map(); 4 ( 0.00%) let source_map_bytes = self.position() - i; . 3 ( 0.00%) let attrs = tcx.hir().krate_attrs(); 7 ( 0.00%) let has_default_lib_allocator = tcx.sess.contains_name(&attrs, sym::default_lib_allocator); . 118 ( 0.00%) let root = self.lazy(CrateRoot { . name: tcx.crate_name(LOCAL_CRATE), 3 ( 0.00%) extra_filename: tcx.sess.opts.cg.extra_filename.clone(), 1 ( 0.00%) triple: tcx.sess.opts.target_triple.clone(), . hash: tcx.crate_hash(LOCAL_CRATE), . stable_crate_id: tcx.def_path_hash(LOCAL_CRATE.as_def_id()).stable_crate_id(), 3 ( 0.00%) panic_strategy: tcx.sess.panic_strategy(), 3 ( 0.00%) panic_in_drop_strategy: tcx.sess.opts.debugging_opts.panic_in_drop, 2 ( 0.00%) edition: tcx.sess.edition(), . has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE), . has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE), . has_default_lib_allocator, . proc_macro_data, 6 ( 0.00%) compiler_builtins: tcx.sess.contains_name(&attrs, sym::compiler_builtins), 6 ( 0.00%) needs_allocator: tcx.sess.contains_name(&attrs, sym::needs_allocator), 6 ( 0.00%) needs_panic_runtime: tcx.sess.contains_name(&attrs, sym::needs_panic_runtime), 6 ( 0.00%) no_builtins: tcx.sess.contains_name(&attrs, sym::no_builtins), 5 ( 0.00%) panic_runtime: tcx.sess.contains_name(&attrs, sym::panic_runtime), 5 ( 0.00%) profiler_runtime: tcx.sess.contains_name(&attrs, sym::profiler_runtime), 2 ( 0.00%) symbol_mangling_version: tcx.sess.opts.get_symbol_mangling_version(), . . crate_deps, . dylib_dependency_formats, . lib_features, . lang_items, . diagnostic_items, . lang_items_missing, . native_libraries, . foreign_modules, . source_map, . traits, . impls, . exported_symbols, . interpret_alloc_index, 2 ( 0.00%) tables, . syntax_contexts, . expn_data, . expn_hashes, . def_path_hash_map, . }); . 1 ( 0.00%) let total_bytes = self.position(); . 4 ( 0.00%) if tcx.sess.meta_stats() { . let mut zero_bytes = 0; . for e in self.opaque.data.iter() { . if *e == 0 { . zero_bytes += 1; . } . } . . eprintln!("metadata stats:"); -- line 756 ---------------------------------------- -- line 770 ---------------------------------------- . eprintln!(" item bytes: {}", item_bytes); . eprintln!(" table bytes: {}", tables_bytes); . eprintln!(" hygiene bytes: {}", hygiene_bytes); . eprintln!(" zero bytes: {}", zero_bytes); . eprintln!(" total bytes: {}", total_bytes); . } . . root 9 ( 0.00%) } . } . . fn should_encode_visibility(def_kind: DefKind) -> bool { . match def_kind { . DefKind::Mod . | DefKind::Struct . | DefKind::Union . | DefKind::Enum -- line 786 ---------------------------------------- -- line 969 ---------------------------------------- . | DefKind::LifetimeParam . | DefKind::GlobalAsm . | DefKind::ExternCrate => false, . } . } . . impl<'a, 'tcx> EncodeContext<'a, 'tcx> { . fn encode_def_ids(&mut self) { 2 ( 0.00%) if self.is_proc_macro { . return; . } 1 ( 0.00%) let tcx = self.tcx; 3 ( 0.00%) let hir = tcx.hir(); 45 ( 0.00%) for local_id in hir.iter_local_def_id() { . let def_id = local_id.to_def_id(); . let def_kind = tcx.opt_def_kind(local_id); 48 ( 0.00%) let def_kind = if let Some(def_kind) = def_kind { def_kind } else { continue }; 128 ( 0.00%) record!(self.tables.def_kind[def_id] <- match def_kind { . // Replace Ctor by the enclosing object to avoid leaking details in children crates. . DefKind::Ctor(CtorOf::Struct, _) => DefKind::Struct, . DefKind::Ctor(CtorOf::Variant, _) => DefKind::Variant, . def_kind => def_kind, . }); 24 ( 0.00%) record!(self.tables.span[def_id] <- tcx.def_span(def_id)); 96 ( 0.00%) record!(self.tables.attributes[def_id] <- tcx.get_attrs(def_id)); 64 ( 0.00%) record!(self.tables.expn_that_defined[def_id] <- self.tcx.expn_that_defined(def_id)); . if should_encode_visibility(def_kind) { 30 ( 0.00%) record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id)); . } . if should_encode_stability(def_kind) { . self.encode_stability(def_id); . self.encode_const_stability(def_id); 24 ( 0.00%) self.encode_deprecation(def_id); . } . if should_encode_variances(def_kind) { . let v = self.tcx.variances_of(def_id); . record!(self.tables.variances[def_id] <- v); . } . if should_encode_generics(def_kind) { . let g = tcx.generics_of(def_id); . record!(self.tables.generics[def_id] <- g); . record!(self.tables.explicit_predicates[def_id] <- self.tcx.explicit_predicates_of(def_id)); . let inferred_outlives = self.tcx.inferred_outlives_of(def_id); . if !inferred_outlives.is_empty() { . record!(self.tables.inferred_outlives[def_id] <- inferred_outlives); . } . } 56 ( 0.00%) if let DefKind::Trait | DefKind::TraitAlias = def_kind { . record!(self.tables.super_predicates[def_id] <- self.tcx.super_predicates_of(def_id)); . } . } . let inherent_impls = tcx.crate_inherent_impls(()); . for (def_id, implementations) in inherent_impls.inherent_impls.iter() { . if implementations.is_empty() { . continue; . } -- line 1024 ---------------------------------------- -- line 1078 ---------------------------------------- . . record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data))); . self.encode_item_type(def_id); . if variant.ctor_kind == CtorKind::Fn { . record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); . } . } . 10 ( 0.00%) fn encode_info_for_mod(&mut self, local_def_id: LocalDefId, md: &hir::Mod<'_>) { 2 ( 0.00%) let tcx = self.tcx; . let def_id = local_def_id.to_def_id(); . debug!("EncodeContext::encode_info_for_mod({:?})", def_id); . . // If we are encoding a proc-macro crates, `encode_info_for_mod` will . // only ever get called for the crate root. We still want to encode . // the crate root for consistency with other crates (some of the resolver . // code uses it). However, we skip encoding anything relating to child . // items - we encode information about proc-macros later on. 3 ( 0.00%) let reexports = if !self.is_proc_macro { 2 ( 0.00%) match tcx.module_reexports(local_def_id) { . Some(exports) => self.lazy(exports), . _ => Lazy::empty(), . } . } else { . Lazy::empty() . }; . 4 ( 0.00%) record!(self.tables.kind[def_id] <- EntryKind::Mod(reexports)); 2 ( 0.00%) if self.is_proc_macro { . // Encode this here because we don't do it in encode_def_ids. . record!(self.tables.expn_that_defined[def_id] <- tcx.expn_that_defined(local_def_id)); . } else { . let direct_children = md.item_ids.iter().map(|item_id| item_id.def_id.local_def_index); . // Foreign items are planted into their parent modules from name resolution point of view. 2 ( 0.00%) let tcx = self.tcx; . let foreign_item_children = md . .item_ids . .iter() 35 ( 0.00%) .filter_map(|item_id| match tcx.hir().item(*item_id).kind { . hir::ItemKind::ForeignMod { items, .. } => { . Some(items.iter().map(|fi_ref| fi_ref.id.def_id.local_def_index)) . } . _ => None, . }) . .flatten(); . 7 ( 0.00%) record!(self.tables.children[def_id] <- direct_children.chain(foreign_item_children)); . } 8 ( 0.00%) } . . fn encode_field( . &mut self, . adt_def: &ty::AdtDef, . variant_index: VariantIdx, . field_index: usize, . ) { . let variant = &adt_def.variants[variant_index]; -- line 1134 ---------------------------------------- -- line 1305 ---------------------------------------- . self.lazy(self.tcx.hir().body_param_names(body_id)) . } . . fn encode_fn_param_names(&mut self, param_names: &[Ident]) -> Lazy<[Ident]> { . self.lazy(param_names.iter()) . } . . fn encode_mir(&mut self) { 3 ( 0.00%) if self.is_proc_macro { . return; . } . . let keys_and_jobs = self . .tcx . .mir_keys(()) . .iter() . .filter_map(|&def_id| { -- line 1321 ---------------------------------------- -- line 1322 ---------------------------------------- . let (encode_const, encode_opt) = should_encode_mir(self.tcx, def_id); . if encode_const || encode_opt { . Some((def_id, encode_const, encode_opt)) . } else { . None . } . }) . .collect::>(); 5 ( 0.00%) for (def_id, encode_const, encode_opt) in keys_and_jobs.into_iter() { . debug_assert!(encode_const || encode_opt); . . debug!("EntryBuilder::encode_mir({:?})", def_id); . if encode_opt { . record!(self.tables.mir[def_id.to_def_id()] <- self.tcx.optimized_mir(def_id)); . } . if encode_const { . record!(self.tables.mir_for_ctfe[def_id.to_def_id()] <- self.tcx.mir_for_ctfe(def_id)); -- line 1338 ---------------------------------------- -- line 1354 ---------------------------------------- . } . } . . fn encode_stability(&mut self, def_id: DefId) { . debug!("EncodeContext::encode_stability({:?})", def_id); . . // The query lookup can take a measurable amount of time in crates with many items. Check if . // the stability attributes are even enabled before using their queries. 32 ( 0.00%) if self.feat.staged_api || self.tcx.sess.opts.debugging_opts.force_unstable_if_unmarked { . if let Some(stab) = self.tcx.lookup_stability(def_id) { . record!(self.tables.stability[def_id] <- stab) . } . } . } . . fn encode_const_stability(&mut self, def_id: DefId) { . debug!("EncodeContext::encode_const_stability({:?})", def_id); . . // The query lookup can take a measurable amount of time in crates with many items. Check if . // the stability attributes are even enabled before using their queries. 28 ( 0.00%) if self.feat.staged_api || self.tcx.sess.opts.debugging_opts.force_unstable_if_unmarked { . if let Some(stab) = self.tcx.lookup_const_stability(def_id) { . record!(self.tables.const_stability[def_id] <- stab) . } . } . } . 24 ( 0.00%) fn encode_deprecation(&mut self, def_id: DefId) { . debug!("EncodeContext::encode_deprecation({:?})", def_id); 20 ( 0.00%) if let Some(depr) = self.tcx.lookup_deprecation(def_id) { . record!(self.tables.deprecation[def_id] <- depr); . } 20 ( 0.00%) } . . fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> Lazy { . let hir = self.tcx.hir(); . let body = hir.body(body_id); . let rendered = rustc_hir_pretty::to_string(&(&hir as &dyn intravisit::Map<'_>), |s| { . s.print_expr(&body.value) . }); . let rendered_const = &RenderedConst(rendered); . self.lazy(rendered_const) . } . 27 ( 0.00%) fn encode_info_for_item(&mut self, def_id: DefId, item: &'tcx hir::Item<'tcx>) { . let tcx = self.tcx; . . debug!("EncodeContext::encode_info_for_item({:?})", def_id); . . self.encode_ident_span(def_id, item.ident); . 18 ( 0.00%) let entry_kind = match item.kind { . hir::ItemKind::Static(_, hir::Mutability::Mut, _) => EntryKind::MutStatic, . hir::ItemKind::Static(_, hir::Mutability::Not, _) => EntryKind::ImmStatic, . hir::ItemKind::Const(_, body_id) => { . let qualifs = self.tcx.at(item.span).mir_const_qualif(def_id); . EntryKind::Const(qualifs, self.encode_rendered_const_for_body(body_id)) . } . hir::ItemKind::Fn(ref sig, .., body) => { . let data = FnData { . asyncness: sig.header.asyncness, . constness: sig.header.constness, . param_names: self.encode_fn_param_names_for_body(body), . }; . . EntryKind::Fn(self.lazy(data)) . } 3 ( 0.00%) hir::ItemKind::Macro(ref macro_def) => { . EntryKind::MacroDef(self.lazy(macro_def.clone())) . } . hir::ItemKind::Mod(ref m) => { . return self.encode_info_for_mod(item.def_id, m); . } . hir::ItemKind::ForeignMod { .. } => EntryKind::ForeignMod, . hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm, . hir::ItemKind::TyAlias(..) => EntryKind::Type, -- line 1429 ---------------------------------------- -- line 1518 ---------------------------------------- . } . hir::ItemKind::TraitAlias(..) => EntryKind::TraitAlias, . hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => { . bug!("cannot encode info for item {:?}", item) . } . }; . record!(self.tables.kind[def_id] <- entry_kind); . // FIXME(eddyb) there should be a nicer way to do this. 15 ( 0.00%) match item.kind { . hir::ItemKind::Enum(..) => record!(self.tables.children[def_id] <- . self.tcx.adt_def(def_id).variants.iter().map(|v| { . assert!(v.def_id.is_local()); . v.def_id.index . }) . ), . hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => { . record!(self.tables.children[def_id] <- -- line 1534 ---------------------------------------- -- line 1544 ---------------------------------------- . associated_item_def_ids.iter().map(|&def_id| { . assert!(def_id.is_local()); . def_id.index . }) . ); . } . _ => {} . } 6 ( 0.00%) match item.kind { . hir::ItemKind::Static(..) . | hir::ItemKind::Const(..) . | hir::ItemKind::Fn(..) . | hir::ItemKind::TyAlias(..) . | hir::ItemKind::OpaqueTy(..) . | hir::ItemKind::Enum(..) . | hir::ItemKind::Struct(..) . | hir::ItemKind::Union(..) . | hir::ItemKind::Impl { .. } => self.encode_item_type(def_id), . _ => {} . } 6 ( 0.00%) if let hir::ItemKind::Fn(..) = item.kind { . record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); . } 6 ( 0.00%) if let hir::ItemKind::Impl { .. } = item.kind { . if let Some(trait_ref) = self.tcx.impl_trait_ref(def_id) { . record!(self.tables.impl_trait_ref[def_id] <- trait_ref); . } . } 24 ( 0.00%) } . . fn encode_info_for_generic_param(&mut self, def_id: DefId, kind: EntryKind, encode_type: bool) { . record!(self.tables.kind[def_id] <- kind); . if encode_type { . self.encode_item_type(def_id); . } . } . -- line 1580 ---------------------------------------- -- line 1611 ---------------------------------------- . let const_data = self.encode_rendered_const_for_body(body_id); . let qualifs = self.tcx.mir_const_qualif(def_id); . . record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::AnonConst(qualifs, const_data)); . self.encode_item_type(def_id.to_def_id()); . } . . fn encode_native_libraries(&mut self) -> Lazy<[NativeLib]> { 2 ( 0.00%) empty_proc_macro!(self); 2 ( 0.00%) let used_libraries = self.tcx.native_libraries(LOCAL_CRATE); . self.lazy(used_libraries.iter()) . } . . fn encode_foreign_modules(&mut self) -> Lazy<[ForeignModule]> { 5 ( 0.00%) empty_proc_macro!(self); 2 ( 0.00%) let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE); . self.lazy(foreign_modules.iter().map(|(_, m)| m).cloned()) . } . . fn encode_hygiene(&mut self) -> (SyntaxContextTable, ExpnDataTable, ExpnHashTable) { . let mut syntax_contexts: TableBuilder<_, _> = Default::default(); . let mut expn_data_table: TableBuilder<_, _> = Default::default(); . let mut expn_hash_table: TableBuilder<_, _> = Default::default(); . 2 ( 0.00%) let _: Result<(), !> = self.hygiene_ctxt.encode( 8 ( 0.00%) &mut (&mut *self, &mut syntax_contexts, &mut expn_data_table, &mut expn_hash_table), . |(this, syntax_contexts, _, _), index, ctxt_data| { . syntax_contexts.set(index, this.lazy(ctxt_data)); . Ok(()) . }, . |(this, _, expn_data_table, expn_hash_table), index, expn_data, hash| { . if let Some(index) = index.as_local() { 4 ( 0.00%) expn_data_table.set(index.as_raw(), this.lazy(expn_data)); 4 ( 0.00%) expn_hash_table.set(index.as_raw(), this.lazy(hash)); . } . Ok(()) . }, . ); . . ( . syntax_contexts.encode(&mut self.opaque), . expn_data_table.encode(&mut self.opaque), . expn_hash_table.encode(&mut self.opaque), . ) . } . . fn encode_proc_macros(&mut self) -> Option { 6 ( 0.00%) let is_proc_macro = self.tcx.sess.crate_types().contains(&CrateType::ProcMacro); . if is_proc_macro { . let tcx = self.tcx; . let hir = tcx.hir(); . . let proc_macro_decls_static = tcx.proc_macro_decls_static(()).unwrap().local_def_index; . let stability = tcx.lookup_stability(DefId::local(CRATE_DEF_INDEX)).copied(); . let macros = . self.lazy(tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index)); -- line 1666 ---------------------------------------- -- line 1725 ---------------------------------------- . . Some(ProcMacroData { proc_macro_decls_static, stability, macros }) . } else { . None . } . } . . fn encode_crate_deps(&mut self) -> Lazy<[CrateDep]> { 7 ( 0.00%) empty_proc_macro!(self); . 1 ( 0.00%) let deps = self . .tcx . .crates(()) . .iter() . .map(|&cnum| { . let dep = CrateDep { 3 ( 0.00%) name: self.tcx.crate_name(cnum), 3 ( 0.00%) hash: self.tcx.crate_hash(cnum), 3 ( 0.00%) host_hash: self.tcx.crate_host_hash(cnum), 3 ( 0.00%) kind: self.tcx.dep_kind(cnum), 3 ( 0.00%) extra_filename: self.tcx.extra_filename(cnum), . }; 15 ( 0.00%) (cnum, dep) . }) . .collect::>(); . . { . // Sanity-check the crate numbers . let mut expected_cnum = 1; 6 ( 0.00%) for &(n, _) in &deps { 8 ( 0.00%) assert_eq!(n, CrateNum::new(expected_cnum)); . expected_cnum += 1; . } . } . . // We're just going to write a list of crate 'name-hash-version's, with . // the assumption that they are numbered 1 to n. . // FIXME (#2166): This is not nearly enough to support correct versioning . // but is enough to get transitive crate dependencies working. . self.lazy(deps.iter().map(|&(_, ref dep)| dep)) . } . . fn encode_lib_features(&mut self) -> Lazy<[(Symbol, Option)]> { 2 ( 0.00%) empty_proc_macro!(self); 1 ( 0.00%) let tcx = self.tcx; . let lib_features = tcx.lib_features(()); 2 ( 0.00%) self.lazy(lib_features.to_vec()) . } . . fn encode_diagnostic_items(&mut self) -> Lazy<[(Symbol, DefIndex)]> { 3 ( 0.00%) empty_proc_macro!(self); 1 ( 0.00%) let tcx = self.tcx; . let diagnostic_items = &tcx.diagnostic_items(LOCAL_CRATE).name_to_id; . self.lazy(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index))) . } . . fn encode_lang_items(&mut self) -> Lazy<[(DefIndex, usize)]> { 4 ( 0.00%) empty_proc_macro!(self); 1 ( 0.00%) let tcx = self.tcx; 1 ( 0.00%) let lang_items = tcx.lang_items(); 2 ( 0.00%) let lang_items = lang_items.items().iter(); . self.lazy(lang_items.enumerate().filter_map(|(i, &opt_def_id)| { 568 ( 0.00%) if let Some(def_id) = opt_def_id { . if def_id.is_local() { . return Some((def_id.index, i)); . } . } . None . })) . } . . fn encode_lang_items_missing(&mut self) -> Lazy<[lang_items::LangItem]> { 2 ( 0.00%) empty_proc_macro!(self); 1 ( 0.00%) let tcx = self.tcx; 1 ( 0.00%) self.lazy(&tcx.lang_items().missing) . } . . fn encode_traits(&mut self) -> Lazy<[DefIndex]> { 3 ( 0.00%) empty_proc_macro!(self); 1 ( 0.00%) self.lazy(self.tcx.traits_in_crate(LOCAL_CRATE).iter().map(|def_id| def_id.index)) . } . . /// Encodes an index, mapping each trait to its (local) implementations. . fn encode_impls(&mut self) -> Lazy<[TraitImpls]> { . debug!("EncodeContext::encode_traits_and_impls()"); 2 ( 0.00%) empty_proc_macro!(self); 2 ( 0.00%) let tcx = self.tcx; 5 ( 0.00%) let mut visitor = ImplsVisitor { tcx, impls: FxHashMap::default() }; 4 ( 0.00%) tcx.hir().visit_all_item_likes(&mut visitor); . . let mut all_impls: Vec<_> = visitor.impls.into_iter().collect(); . . // Bring everything into deterministic order for hashing . all_impls.sort_by_cached_key(|&(trait_def_id, _)| tcx.def_path_hash(trait_def_id)); . . let all_impls: Vec<_> = all_impls . .into_iter() -- line 1821 ---------------------------------------- -- line 1840 ---------------------------------------- . // This pass is seeded off the reachability list calculated in the . // middle::reachable module but filters out items that either don't have a . // symbol associated with them (they weren't translated) or if they're an FFI . // definition (as that's not defined in this crate). . fn encode_exported_symbols( . &mut self, . exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportLevel)], . ) -> Lazy<[(ExportedSymbol<'tcx>, SymbolExportLevel)]> { 2 ( 0.00%) empty_proc_macro!(self); . // The metadata symbol name is special. It should not show up in . // downstream crates. 9 ( 0.00%) let metadata_symbol_name = SymbolName::new(self.tcx, &metadata_symbol_name(self.tcx)); . . self.lazy( . exported_symbols . .iter() . .filter(|&&(ref exported_symbol, _)| match *exported_symbol { . ExportedSymbol::NoDefId(symbol_name) => symbol_name != metadata_symbol_name, . _ => true, . }) . .cloned(), . ) . } . . fn encode_dylib_dependency_formats(&mut self) -> Lazy<[Option]> { 2 ( 0.00%) empty_proc_macro!(self); 2 ( 0.00%) let formats = self.tcx.dependency_formats(()); 4 ( 0.00%) for (ty, arr) in formats.iter() { 2 ( 0.00%) if *ty != CrateType::Dylib { . continue; . } . return self.lazy(arr.iter().map(|slot| match *slot { . Linkage::NotLinked | Linkage::IncludedFromDylib => None, . . Linkage::Dynamic => Some(LinkagePreference::RequireDynamic), . Linkage::Static => Some(LinkagePreference::RequireStatic), . })); -- line 1876 ---------------------------------------- -- line 1925 ---------------------------------------- . intravisit::walk_expr(self, ex); . self.encode_info_for_expr(ex); . } . fn visit_anon_const(&mut self, c: &'tcx AnonConst) { . intravisit::walk_anon_const(self, c); . self.encode_info_for_anon_const(c.hir_id); . } . fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { 21 ( 0.00%) intravisit::walk_item(self, item); 14 ( 0.00%) match item.kind { . hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {} // ignore these 12 ( 0.00%) _ => self.encode_info_for_item(item.def_id.to_def_id(), item), . } 28 ( 0.00%) self.encode_addl_info_for_item(item); . } . fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem<'tcx>) { . intravisit::walk_foreign_item(self, ni); . self.encode_info_for_foreign_item(ni.def_id.to_def_id(), ni); . } . fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) { . intravisit::walk_generics(self, generics); . self.encode_info_for_generics(generics); -- line 1946 ---------------------------------------- -- line 1988 ---------------------------------------- . fn encode_ident_span(&mut self, def_id: DefId, ident: Ident) { . record!(self.tables.ident_span[def_id] <- ident.span); . } . . /// In some cases, along with the item itself, we also . /// encode some sub-items. Usually we want some info from the item . /// so it's easier to do that here then to wait until we would encounter . /// normally in the visitor walk. 63 ( 0.00%) fn encode_addl_info_for_item(&mut self, item: &hir::Item<'_>) { 35 ( 0.00%) match item.kind { . hir::ItemKind::Static(..) . | hir::ItemKind::Const(..) . | hir::ItemKind::Fn(..) . | hir::ItemKind::Macro(..) . | hir::ItemKind::Mod(..) . | hir::ItemKind::ForeignMod { .. } . | hir::ItemKind::GlobalAsm(..) . | hir::ItemKind::ExternCrate(..) -- line 2005 ---------------------------------------- -- line 2044 ---------------------------------------- . } . hir::ItemKind::Trait(..) => { . for &item_def_id in self.tcx.associated_item_def_ids(item.def_id.to_def_id()).iter() . { . self.encode_info_for_trait_item(item_def_id); . } . } . } 56 ( 0.00%) } . } . . struct ImplsVisitor<'tcx> { . tcx: TyCtxt<'tcx>, . impls: FxHashMap)>>, . } . . impl<'tcx, 'v> ItemLikeVisitor<'v> for ImplsVisitor<'tcx> { 49 ( 0.00%) fn visit_item(&mut self, item: &hir::Item<'_>) { 14 ( 0.00%) match item.kind { . hir::ItemKind::Impl(..) => { . if let Some(trait_ref) = self.tcx.impl_trait_ref(item.def_id.to_def_id()) { . let simplified_self_ty = fast_reject::simplify_type( . self.tcx, . trait_ref.self_ty(), . SimplifyParams::No, . StripReferences::No, . ); -- line 2070 ---------------------------------------- -- line 2072 ---------------------------------------- . self.impls . .entry(trait_ref.def_id) . .or_default() . .push((item.def_id.local_def_index, simplified_self_ty)); . } . } . _ => {} . } 56 ( 0.00%) } . . fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem<'v>) {} . . fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem<'v>) { . // handled in `visit_item` above . } . . fn visit_foreign_item(&mut self, _foreign_item: &'v hir::ForeignItem<'v>) {} -- line 2088 ---------------------------------------- -- line 2146 ---------------------------------------- . } . . #[inline] . pub fn raw_data(&self) -> &[u8] { . &self.raw_data . } . } . 10 ( 0.00%) pub fn encode_metadata(tcx: TyCtxt<'_>) -> EncodedMetadata { 5 ( 0.00%) let _prof_timer = tcx.prof.verbose_generic_activity("generate_crate_metadata"); . . // Since encoding metadata is not in a query, and nothing is cached, . // there's no need to do dep-graph tracking for any of it. . tcx.dep_graph.assert_ignored(); . 7 ( 0.00%) join( 3 ( 0.00%) || encode_metadata_impl(tcx), . || { 5 ( 0.00%) if tcx.sess.threads() == 1 { . return; . } . // Prefetch some queries used by metadata encoding. . // This is not necessary for correctness, but is only done for performance reasons. . // It can be removed if it turns out to cause trouble or be detrimental to performance. . join(|| prefetch_mir(tcx), || tcx.exported_symbols(LOCAL_CRATE)); . }, . ) . .0 9 ( 0.00%) } . 9 ( 0.00%) fn encode_metadata_impl(tcx: TyCtxt<'_>) -> EncodedMetadata { 1 ( 0.00%) let mut encoder = opaque::Encoder::new(vec![]); . encoder.emit_raw_bytes(METADATA_HEADER).unwrap(); . . // Will be filled with the root position after encoding everything. . encoder.emit_raw_bytes(&[0, 0, 0, 0]).unwrap(); . 2 ( 0.00%) let source_map_files = tcx.sess.source_map().files(); 3 ( 0.00%) let source_file_cache = (source_map_files[0].clone(), 0); 2 ( 0.00%) let required_source_files = Some(GrowableBitSet::with_capacity(source_map_files.len())); . drop(source_map_files); . . let hygiene_ctxt = HygieneEncodeContext::default(); . 35 ( 0.00%) let mut ecx = EncodeContext { 4 ( 0.00%) opaque: encoder, . tcx, 2 ( 0.00%) feat: tcx.features(), . tables: Default::default(), . lazy_state: LazyState::NoNode, . type_shorthands: Default::default(), . predicate_shorthands: Default::default(), 4 ( 0.00%) source_file_cache, . interpret_allocs: Default::default(), 4 ( 0.00%) required_source_files, 2 ( 0.00%) is_proc_macro: tcx.sess.crate_types().contains(&CrateType::ProcMacro), . hygiene_ctxt: &hygiene_ctxt, . }; . . // Encode the rustc version string in a predictable location. . rustc_version().encode(&mut ecx).unwrap(); . . // Encode all the entries and extra information in the crate, . // culminating in the `CrateRoot` which points to all of it. 1 ( 0.00%) let root = ecx.encode_crate_root(); . 7 ( 0.00%) let mut result = ecx.opaque.into_inner(); . . // Encode the root position. . let header = METADATA_HEADER.len(); . let pos = root.position.get(); 3 ( 0.00%) result[header + 0] = (pos >> 24) as u8; 3 ( 0.00%) result[header + 1] = (pos >> 16) as u8; 1 ( 0.00%) result[header + 2] = (pos >> 8) as u8; 5 ( 0.00%) result[header + 3] = (pos >> 0) as u8; . . // Record metadata size for self-profiling . tcx.prof.artifact_size("crate_metadata", "crate_metadata", result.len() as u64); . 5 ( 0.00%) EncodedMetadata { raw_data: result } 12 ( 0.00%) } . . pub fn provide(providers: &mut Providers) { 2 ( 0.00%) *providers = Providers { . traits_in_crate: |tcx, cnum| { 1 ( 0.00%) assert_eq!(cnum, LOCAL_CRATE); . 1 ( 0.00%) #[derive(Default)] . struct TraitsVisitor { . traits: Vec, . } . impl ItemLikeVisitor<'_> for TraitsVisitor { . fn visit_item(&mut self, item: &hir::Item<'_>) { 28 ( 0.00%) if let hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) = item.kind { . self.traits.push(item.def_id.to_def_id()); . } . } . fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem<'_>) {} . fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem<'_>) {} . fn visit_foreign_item(&mut self, _foreign_item: &hir::ForeignItem<'_>) {} . } . . let mut visitor = TraitsVisitor::default(); 4 ( 0.00%) tcx.hir().visit_all_item_likes(&mut visitor); . // Bring everything into deterministic order. . visitor.traits.sort_by_cached_key(|&def_id| tcx.def_path_hash(def_id)); . tcx.arena.alloc_slice(&visitor.traits) . }, . . ..*providers . }; . } -- line 2257 ---------------------------------------- 6,710 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lexer/src/lib.rs -------------------------------------------------------------------------------- Ir -- line 38 ---------------------------------------- . #[derive(Debug)] . pub struct Token { . pub kind: TokenKind, . pub len: usize, . } . . impl Token { . fn new(kind: TokenKind, len: usize) -> Token { 111,438 ( 0.15%) Token { kind, len } . } . } . . /// Enum representing common lexeme types. . // perf note: Changing all `usize` to `u32` doesn't change performance. See #77629 29,080 ( 0.04%) #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] . pub enum TokenKind { . // Multi-char tokens: . /// "// comment" . LineComment { doc_style: Option }, . /// `/* block comment */` . /// . /// Block comments can be recursive, so the sequence like `/* /* */` . /// will not be considered terminated and will result in a parsing error. -- line 60 ---------------------------------------- -- line 192 ---------------------------------------- . /// Literal starts with "0x". . Hexadecimal, . /// Literal doesn't contain a prefix. . Decimal, . } . . /// `rustc` allows files to have a shebang, e.g. "#!/usr/bin/rustrun", . /// but shebang isn't a part of rust syntax. 14 ( 0.00%) pub fn strip_shebang(input: &str) -> Option { . // Shebang must start with `#!` literally, without any preceding whitespace. . // For simplicity we consider any line starting with `#!` a shebang, . // regardless of restrictions put on shebangs by specific platforms. . if let Some(input_tail) = input.strip_prefix("#!") { . // Ok, this is a shebang but if the next non-whitespace token is `[`, . // then it may be valid Rust code, so consider it Rust code. . let next_non_whitespace_token = tokenize(input_tail).map(|tok| tok.kind).find(|tok| { . !matches!( -- line 208 ---------------------------------------- -- line 213 ---------------------------------------- . ) . }); . if next_non_whitespace_token != Some(TokenKind::OpenBracket) { . // No other choice than to consider this a shebang. . return Some(2 + input_tail.lines().next().unwrap_or_default().len()); . } . } . None 16 ( 0.00%) } . . /// Parses the first token from the provided input string. 37,146 ( 0.05%) pub fn first_token(input: &str) -> Token { . debug_assert!(!input.is_empty()); 12,382 ( 0.02%) Cursor::new(input).advance_token() 49,528 ( 0.07%) } . . /// Creates an iterator that produces tokens from the input string. . pub fn tokenize(input: &str) -> impl Iterator + '_ { . let mut cursor = Cursor::new(input); . std::iter::from_fn(move || { . if cursor.is_eof() { . None . } else { -- line 235 ---------------------------------------- -- line 243 ---------------------------------------- . /// See [Rust language reference](https://doc.rust-lang.org/reference/whitespace.html) . /// for definitions of these classes. . pub fn is_whitespace(c: char) -> bool { . // This is Pattern_White_Space. . // . // Note that this set is stable (ie, it doesn't change with different . // Unicode versions), so it's ok to just hard-code the values. . 38,678 ( 0.05%) matches!( . c, . // Usual ASCII suspects . '\u{0009}' // \t . | '\u{000A}' // \n . | '\u{000B}' // vertical tab . | '\u{000C}' // form feed . | '\u{000D}' // \r . | '\u{0020}' // space -- line 259 ---------------------------------------- -- line 271 ---------------------------------------- . ) . } . . /// True if `c` is valid as a first character of an identifier. . /// See [Rust language reference](https://doc.rust-lang.org/reference/identifiers.html) for . /// a formal definition of valid identifier name. . pub fn is_id_start(c: char) -> bool { . // This is XID_Start OR '_' (which formally is not a XID_Start). 372 ( 0.00%) c == '_' || unicode_xid::UnicodeXID::is_xid_start(c) . } . . /// True if `c` is valid as a non-first character of an identifier. . /// See [Rust language reference](https://doc.rust-lang.org/reference/identifiers.html) for . /// a formal definition of valid identifier name. . pub fn is_id_continue(c: char) -> bool { . unicode_xid::UnicodeXID::is_xid_continue(c) . } -- line 287 ---------------------------------------- -- line 293 ---------------------------------------- . is_id_start(start) && chars.all(is_id_continue) . } else { . false . } . } . . impl Cursor<'_> { . /// Parses a token from the input string. 99,056 ( 0.14%) fn advance_token(&mut self) -> Token { . let first_char = self.bump().unwrap(); 45,003 ( 0.06%) let token_kind = match first_char { . // Slash, comment or block comment. 2,112 ( 0.00%) '/' => match self.first() { . '/' => self.line_comment(), . '*' => self.block_comment(), . _ => Slash, . }, . . // Whitespace sequence. . c if is_whitespace(c) => self.whitespace(), . . // Raw identifier, raw string literal or identifier. 100 ( 0.00%) 'r' => match (self.first(), self.second()) { . ('#', c1) if is_id_start(c1) => self.raw_ident(), . ('#', _) | ('"', _) => { 22 ( 0.00%) let (n_hashes, err) = self.raw_double_quoted_string(1); . let suffix_start = self.len_consumed(); 2 ( 0.00%) if err.is_none() { . self.eat_literal_suffix(); . } . let kind = RawStr { n_hashes, err }; 14 ( 0.00%) Literal { kind, suffix_start } . } . _ => self.ident_or_unknown_prefix(), . }, . . // Byte literal, byte string literal, raw byte string literal or identifier. 2,160 ( 0.00%) 'b' => match (self.first(), self.second()) { . ('\'', _) => { . self.bump(); . let terminated = self.single_quoted_string(); . let suffix_start = self.len_consumed(); . if terminated { . self.eat_literal_suffix(); . } . let kind = Byte { terminated }; -- line 338 ---------------------------------------- -- line 361 ---------------------------------------- . _ => self.ident_or_unknown_prefix(), . }, . . // Identifier (this should be checked after other variant that can . // start as identifier). . c if is_id_start(c) => self.ident_or_unknown_prefix(), . . // Numeric literal. 16,965 ( 0.02%) c @ '0'..='9' => { . let literal_kind = self.number(c); . let suffix_start = self.len_consumed(); . self.eat_literal_suffix(); 460 ( 0.00%) TokenKind::Literal { kind: literal_kind, suffix_start } . } . . // One-symbol tokens. 750 ( 0.00%) ';' => Semi, 586 ( 0.00%) ',' => Comma, 466 ( 0.00%) '.' => Dot, 1,454 ( 0.00%) '(' => OpenParen, 1,454 ( 0.00%) ')' => CloseParen, 446 ( 0.00%) '{' => OpenBrace, 446 ( 0.00%) '}' => CloseBrace, 316 ( 0.00%) '[' => OpenBracket, 316 ( 0.00%) ']' => CloseBracket, . '@' => At, 302 ( 0.00%) '#' => Pound, . '~' => Tilde, 40 ( 0.00%) '?' => Question, 2,170 ( 0.00%) ':' => Colon, 500 ( 0.00%) '$' => Dollar, 374 ( 0.00%) '=' => Eq, 582 ( 0.00%) '!' => Bang, 48 ( 0.00%) '<' => Lt, 120 ( 0.00%) '>' => Gt, 82 ( 0.00%) '-' => Minus, 156 ( 0.00%) '&' => And, 160 ( 0.00%) '|' => Or, 8 ( 0.00%) '+' => Plus, 148 ( 0.00%) '*' => Star, 20 ( 0.00%) '^' => Caret, . '%' => Percent, . . // Lifetime or character literal. . '\'' => self.lifetime_or_char(), . . // String literal. . '"' => { 273 ( 0.00%) let terminated = self.double_quoted_string(); . let suffix_start = self.len_consumed(); 182 ( 0.00%) if terminated { . self.eat_literal_suffix(); . } . let kind = Str { terminated }; 182 ( 0.00%) Literal { kind, suffix_start } . } . // Identifier starting with an emoji. Only lexed for graceful error recovery. . c if !c.is_ascii() && unic_emoji_char::is_emoji(c) => { . self.fake_ident_or_unknown_prefix() . } . _ => Unknown, . }; . Token::new(token_kind, self.len_consumed()) 111,438 ( 0.15%) } . . fn line_comment(&mut self) -> TokenKind { . debug_assert!(self.prev() == '/' && self.first() == '/'); . self.bump(); . 1,792 ( 0.00%) let doc_style = match self.first() { . // `//!` is an inner line doc comment. . '!' => Some(DocStyle::Inner), . // `////` (more than 3 slashes) is not considered a doc comment. 480 ( 0.00%) '/' if self.second() != '/' => Some(DocStyle::Outer), . _ => None, . }; . 17,060 ( 0.02%) self.eat_while(|c| c != '\n'); 1,584 ( 0.00%) LineComment { doc_style } . } . . fn block_comment(&mut self) -> TokenKind { . debug_assert!(self.prev() == '/' && self.first() == '*'); . self.bump(); . . let doc_style = match self.first() { . // `/*!` is an inner block doc comment. -- line 447 ---------------------------------------- -- line 474 ---------------------------------------- . } . . BlockComment { doc_style, terminated: depth == 0 } . } . . fn whitespace(&mut self) -> TokenKind { . debug_assert!(is_whitespace(self.prev())); . self.eat_while(is_whitespace); 3,289 ( 0.00%) Whitespace . } . . fn raw_ident(&mut self) -> TokenKind { . debug_assert!(self.prev() == 'r' && self.first() == '#' && is_id_start(self.second())); . // Eat "#" symbol. . self.bump(); . // Eat the identifier part of RawIdent. . self.eat_identifier(); . RawIdent . } . 14,540 ( 0.02%) fn ident_or_unknown_prefix(&mut self) -> TokenKind { . debug_assert!(is_id_start(self.prev())); . // Start is already eaten, eat the rest of identifier. 5,816 ( 0.01%) self.eat_while(is_id_continue); . // Known prefixes must have been handled earlier. So if . // we see a prefix here, it is definitely an unknown prefix. 5,816 ( 0.01%) match self.first() { . '#' | '"' | '\'' => UnknownPrefix, 2,908 ( 0.00%) c if !c.is_ascii() && unic_emoji_char::is_emoji(c) => { . self.fake_ident_or_unknown_prefix() . } 2,908 ( 0.00%) _ => Ident, . } 11,632 ( 0.02%) } . . fn fake_ident_or_unknown_prefix(&mut self) -> TokenKind { . // Start is already eaten, eat the rest of identifier. . self.eat_while(|c| { . unicode_xid::UnicodeXID::is_xid_continue(c) . || (!c.is_ascii() && unic_emoji_char::is_emoji(c)) . || c == '\u{200d}' . }); -- line 515 ---------------------------------------- -- line 519 ---------------------------------------- . '#' | '"' | '\'' => UnknownPrefix, . _ => InvalidIdent, . } . } . . fn number(&mut self, first_digit: char) -> LiteralKind { . debug_assert!('0' <= self.prev() && self.prev() <= '9'); . let mut base = Base::Decimal; 184 ( 0.00%) if first_digit == '0' { . // Attempt to parse encoding base. 270 ( 0.00%) let has_digits = match self.first() { . 'b' => { . base = Base::Binary; . self.bump(); 255 ( 0.00%) self.eat_decimal_digits() . } . 'o' => { . base = Base::Octal; . self.bump(); 4 ( 0.00%) self.eat_decimal_digits() . } . 'x' => { . base = Base::Hexadecimal; . self.bump(); . self.eat_hexadecimal_digits() . } . // Not a base prefix. 45 ( 0.00%) '0'..='9' | '_' | '.' | 'e' | 'E' => { . self.eat_decimal_digits(); . true . } . // Just a 0. . _ => return Int { base, empty_int: false }, . }; . // Base prefix was provided, but there were no digits . // after it, e.g. "0x". 104 ( 0.00%) if !has_digits { . return Int { base, empty_int: true }; . } . } else { . // No base prefix, parse number in the usual way. . self.eat_decimal_digits(); . }; . 464 ( 0.00%) match self.first() { . // Don't be greedy if this is actually an . // integer literal followed by field/method access or a range pattern . // (`0..2` and `12.foo()`) 2 ( 0.00%) '.' if self.second() != '.' && !is_id_start(self.second()) => { . // might have stuff after the ., and if it does, it needs to start . // with a number . self.bump(); . let mut empty_exponent = false; . if self.first().is_digit(10) { . self.eat_decimal_digits(); . match self.first() { . 'e' | 'E' => { -- line 575 ---------------------------------------- -- line 677 ---------------------------------------- . false . } . . /// Eats double-quoted string and returns true . /// if string is terminated. . fn double_quoted_string(&mut self) -> bool { . debug_assert!(self.prev() == '"'); . while let Some(c) = self.bump() { 4,542 ( 0.01%) match c { . '"' => { . return true; . } . '\\' if self.first() == '\\' || self.first() == '"' => { . // Bump again to skip escaped character. . self.bump(); . } . _ => (), . } . } . // End of file reached. . false 91 ( 0.00%) } . . /// Eats the double-quoted string and returns `n_hashes` and an error if encountered. 14 ( 0.00%) fn raw_double_quoted_string(&mut self, prefix_len: usize) -> (u16, Option) { . // Wrap the actual function to handle the error with too many hashes. . // This way, it eats the whole raw string. . let (n_hashes, err) = self.raw_string_unvalidated(prefix_len); . // Only up to 65535 `#`s are allowed in raw strings 2 ( 0.00%) match u16::try_from(n_hashes) { 14 ( 0.00%) Ok(num) => (num, err), . // We lie about the number of hashes here :P . Err(_) => (0, Some(RawStrError::TooManyDelimiters { found: n_hashes })), . } 16 ( 0.00%) } . . fn raw_string_unvalidated(&mut self, prefix_len: usize) -> (usize, Option) { . debug_assert!(self.prev() == 'r'); . let start_pos = self.len_consumed(); . let mut possible_terminator_offset = None; . let mut max_hashes = 0; . . // Count opening '#' symbols. . let mut eaten = 0; 8 ( 0.00%) while self.first() == '#' { 6 ( 0.00%) eaten += 1; . self.bump(); . } . let n_start_hashes = eaten; . . // Check that string is started. 8 ( 0.00%) match self.bump() { . Some('"') => (), . c => { . let c = c.unwrap_or(EOF_CHAR); . return (n_start_hashes, Some(RawStrError::InvalidStarter { bad_char: c })); . } . } . . // Skip the string contents and on each '#' character met, check if this is . // a raw string termination. . loop { 23 ( 0.00%) self.eat_while(|c| c != '"'); . 6 ( 0.00%) if self.is_eof() { . return ( . n_start_hashes, . Some(RawStrError::NoTerminator { . expected: n_start_hashes, . found: max_hashes, . possible_terminator_offset, . }), . ); -- line 749 ---------------------------------------- -- line 753 ---------------------------------------- . self.bump(); . . // Check that amount of closing '#' symbols . // is equal to the amount of opening ones. . // Note that this will not consume extra trailing `#` characters: . // `r###"abcde"####` is lexed as a `RawStr { n_hashes: 3 }` . // followed by a `#` token. . let mut n_end_hashes = 0; 32 ( 0.00%) while self.first() == '#' && n_end_hashes < n_start_hashes { 4 ( 0.00%) n_end_hashes += 1; . self.bump(); . } . 12 ( 0.00%) if n_end_hashes == n_start_hashes { . return (n_start_hashes, None); 8 ( 0.00%) } else if n_end_hashes > max_hashes { . // Keep track of possible terminators to give a hint about . // where there might be a missing terminator . possible_terminator_offset = . Some(self.len_consumed() - start_pos - n_end_hashes + prefix_len); . max_hashes = n_end_hashes; . } . } . } . . fn eat_decimal_digits(&mut self) -> bool { . let mut has_digits = false; . loop { 666 ( 0.00%) match self.first() { . '_' => { . self.bump(); . } 981 ( 0.00%) '0'..='9' => { . has_digits = true; . self.bump(); . } . _ => break, . } . } . has_digits 136 ( 0.00%) } . . fn eat_hexadecimal_digits(&mut self) -> bool { . let mut has_digits = false; . loop { 594 ( 0.00%) match self.first() { . '_' => { . self.bump(); . } 783 ( 0.00%) '0'..='9' | 'a'..='f' | 'A'..='F' => { . has_digits = true; . self.bump(); . } . _ => break, . } . } . has_digits 20 ( 0.00%) } . . /// Eats the float exponent. Returns true if at least one digit was met, . /// and returns false otherwise. . fn eat_float_exponent(&mut self) -> bool { . debug_assert!(self.prev() == 'e' || self.prev() == 'E'); . if self.first() == '-' || self.first() == '+' { . self.bump(); . } . self.eat_decimal_digits() . } . . // Eats the suffix of the literal, e.g. "_u8". . fn eat_literal_suffix(&mut self) { 370 ( 0.00%) self.eat_identifier(); . } . . // Eats the identifier. 555 ( 0.00%) fn eat_identifier(&mut self) { . if !is_id_start(self.first()) { . return; . } . self.bump(); . 20 ( 0.00%) self.eat_while(is_id_continue); 724 ( 0.00%) } . } 189,955 ( 0.26%) -------------------------------------------------------------------------------- -- 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 { 16,176 ( 0.02%) ctrl & 0x80 == 0 . } . . /// Checks whether a control byte represents a special value (top bit is set). . #[inline] . fn is_special(ctrl: u8) -> bool { . ctrl & 0x80 != 0 . } . . /// Checks whether a special control value is EMPTY (just check 1 bit). . #[inline] . fn special_is_empty(ctrl: u8) -> bool { . debug_assert!(is_special(ctrl)); 732 ( 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::()); 88,721 ( 0.12%) 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" . ); . 1,690 ( 0.00%) self.stride += Group::WIDTH; 1,690 ( 0.00%) self.pos += self.stride; 1,445 ( 0.00%) self.pos &= bucket_mask; . } . } . . /// Returns the number of buckets needed to hold the given number of items, . /// taking the maximum load factor into account. . /// . /// Returns `None` if an overflow occurs. . // Workaround for emscripten bug emscripten-core/emscripten-fastcomp#258 . #[cfg_attr(target_os = "emscripten", inline(never))] . #[cfg_attr(not(target_os = "emscripten"), inline)] . fn capacity_to_buckets(cap: usize) -> Option { . debug_assert_ne!(cap, 0); . . // For small tables we require at least 1 empty bucket so that lookups are . // guaranteed to terminate if an element doesn't exist in the table. 856 ( 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. 1,795 ( 0.00%) return Some(if cap < 4 { 4 } else { 8 }); . } . . // Otherwise require 1/8 buckets to be empty (87.5% load) . // . // Be careful when modifying this, calculate_layout relies on the . // overflow check here. 414 ( 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 { 2,040 ( 0.00%) if bucket_mask < 8 { . // For tables with 1/2/4/8 buckets, we always reserve one empty slot. . // Keep in mind that the bucket mask is one less than the bucket count. . bucket_mask . } else { . // For larger tables we reserve 12.5% of the slots as empty. 402 ( 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 = 1,981 ( 0.00%) size.checked_mul(buckets)?.checked_add(ctrl_align - 1)? & !(ctrl_align - 1); 2,460 ( 0.00%) let len = ctrl_offset.checked_add(buckets + Group::WIDTH)?; . . Some(( . unsafe { Layout::from_size_align_unchecked(len, ctrl_align) }, . ctrl_offset, . )) . } . } . -- line 263 ---------------------------------------- -- line 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 { 18 ( 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 { 10 ( 0.00%) table: RawTableInner::new_uninitialized( . alloc, . TableLayout::new::(), . buckets, . fallibility, . )?, . marker: PhantomData, . }) . } -- line 456 ---------------------------------------- -- line 569 ---------------------------------------- . #[allow(deprecated)] . pub unsafe fn remove(&mut self, item: Bucket) -> T { . self.erase_no_drop(&item); . item.read() . } . . /// Finds and removes an element from the table, returning it. . #[cfg_attr(feature = "inline-more", inline)] 5,483 ( 0.01%) pub fn remove_entry(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option { . // Avoid `Option::map` because it bloats LLVM IR. . match self.find(hash, eq) { . Some(bucket) => Some(unsafe { self.remove(bucket) }), 3,372 ( 0.00%) None => None, . } 9,310 ( 0.01%) } . . /// Marks all table buckets as empty without dropping their contents. . #[cfg_attr(feature = "inline-more", inline)] . pub fn clear_no_drop(&mut self) { . self.table.clear_no_drop(); . } . . /// Removes all elements from the table without freeing the backing memory. . #[cfg_attr(feature = "inline-more", inline)] . pub fn clear(&mut self) { . // Ensure that the table is reset even if one of the drops panic . let mut self_ = guard(self, |self_| self_.clear_no_drop()); . unsafe { 1 ( 0.00%) self_.drop_elements(); . } . } . 7 ( 0.00%) unsafe fn drop_elements(&mut self) { 108 ( 0.00%) if mem::needs_drop::() && !self.is_empty() { . for item in self.iter() { . item.drop(); . } . } 8 ( 0.00%) } . . /// Shrinks the table to fit `max(self.len(), min_size)` elements. . #[cfg_attr(feature = "inline-more", inline)] . pub fn shrink_to(&mut self, min_size: usize, hasher: impl Fn(&T) -> u64) { . // Calculate the minimal number of elements that we need to reserve . // space for. . let min_size = usize::max(self.table.items, min_size); . if min_size == 0 { -- line 615 ---------------------------------------- -- line 642 ---------------------------------------- . } . } . } . . /// Ensures that at least `additional` items can be inserted into the table . /// without reallocation. . #[cfg_attr(feature = "inline-more", inline)] . pub fn reserve(&mut self, additional: usize, hasher: impl Fn(&T) -> u64) { 1,540 ( 0.00%) if additional > self.table.growth_left { . // Avoid `Result::unwrap_or_else` because it bloats LLVM IR. 1,609 ( 0.00%) if self . .reserve_rehash(additional, hasher, Fallibility::Infallible) . .is_err() . { . unsafe { hint::unreachable_unchecked() } . } . } . } . -- line 660 ---------------------------------------- -- line 671 ---------------------------------------- . } else { . Ok(()) . } . } . . /// Out-of-line slow path for `reserve` and `try_reserve`. . #[cold] . #[inline(never)] 3,569 ( 0.00%) 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 . }, . ) . } 2,440 ( 0.00%) } . . /// Allocates a new table of a different size and moves the contents of the . /// current table into it. . fn resize( . &mut self, . capacity: usize, . hasher: impl Fn(&T) -> u64, . fallibility: Fallibility, -- line 706 ---------------------------------------- -- line 714 ---------------------------------------- . ) . } . } . . /// Inserts a new element into the table, and returns its raw bucket. . /// . /// This does not check if the given element already exists in the table. . #[cfg_attr(feature = "inline-more", inline)] 48,058 ( 0.07%) 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. 6 ( 0.00%) let old_ctrl = *self.table.ctrl(index); 23,380 ( 0.03%) if unlikely(self.table.growth_left == 0 && special_is_empty(old_ctrl)) { . self.reserve(1, hasher); . index = self.table.find_insert_slot(hash); . } . . self.table.record_item_insert_at(index, old_ctrl, hash); . . let bucket = self.bucket(index); 4 ( 0.00%) bucket.write(value); . bucket . } 35,656 ( 0.05%) } . . /// 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)] 208 ( 0.00%) pub fn insert_entry(&mut self, hash: u64, value: T, hasher: impl Fn(&T) -> u64) -> &mut T { . unsafe { self.insert(hash, value, hasher).as_mut() } 156 ( 0.00%) } . . /// Inserts a new element into the table, without growing the table. . /// . /// There must be enough space in the table to insert the new element. . /// . /// This does not check if the given element already exists in the table. . #[cfg_attr(feature = "inline-more", inline)] . #[cfg(any(feature = "raw", feature = "rustc-internal-api"))] 17 ( 0.00%) pub unsafe fn insert_no_grow(&mut self, hash: u64, value: T) -> Bucket { 1,916 ( 0.00%) let (index, old_ctrl) = self.table.prepare_insert_slot(hash); 370 ( 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. 4,039 ( 0.01%) self.table.growth_left -= special_is_empty(old_ctrl) as usize; . . bucket.write(value); 3,335 ( 0.00%) self.table.items += 1; . bucket 19 ( 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 815 ---------------------------------------- . false . } . } . . /// Searches for an element in the table. . #[inline] . pub fn find(&self, hash: u64, mut eq: impl FnMut(&T) -> bool) -> Option> { . let result = self.table.find_inner(hash, &mut |index| unsafe { 386 ( 0.00%) eq(self.bucket(index).as_ref()) . }); . . // Avoid `Option::map` because it bloats LLVM IR. . match result { . Some(index) => Some(unsafe { self.bucket(index) }), . None => None, . } . } . . /// 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. 190 ( 0.00%) match self.find(hash, eq) { . Some(bucket) => Some(unsafe { bucket.as_ref() }), . None => None, . } . } . . /// Gets a mutable reference to an element in the table. . #[inline] . pub fn get_mut(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option<&mut T> { -- line 845 ---------------------------------------- -- 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 { 8,043 ( 0.01%) 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()), 1,675 ( 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(); 92 ( 0.00%) let allocation = self.into_allocation(); 69 ( 0.00%) RawIntoIter { 115 ( 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)> { 23 ( 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(( 14 ( 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 { 3,211 ( 0.00%) 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)] 2,878 ( 0.00%) 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()); . } . 858 ( 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)); 1,956 ( 0.00%) Ok(Self { . ctrl, 756 ( 0.00%) bucket_mask: buckets - 1, . items: 0, . growth_left: bucket_mask_to_capacity(buckets - 1), . alloc, . }) 2,136 ( 0.00%) } . . #[inline] 360 ( 0.00%) fn fallible_with_capacity( . alloc: A, . table_layout: TableLayout, . capacity: usize, . fallibility: Fallibility, . ) -> Result { 90 ( 0.00%) if capacity == 0 { . Ok(Self::new_in(alloc)) . } else { . unsafe { . let buckets = . capacity_to_buckets(capacity).ok_or_else(|| fallibility.capacity_overflow())?; . 1,384 ( 0.00%) let result = Self::new_uninitialized(alloc, table_layout, buckets, fallibility)?; . result.ctrl(0).write_bytes(EMPTY, result.num_ctrl_bytes()); . 270 ( 0.00%) Ok(result) . } . } 360 ( 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] 730 ( 0.00%) unsafe fn prepare_insert_slot(&self, hash: u64) -> (usize, u8) { . let index = self.find_insert_slot(hash); 730 ( 0.00%) let old_ctrl = *self.ctrl(index); . self.set_ctrl_h2(index, hash); . (index, old_ctrl) 1,460 ( 0.00%) } . . /// Searches for an empty or deleted bucket which is suitable for inserting . /// a new element. . /// . /// There must be at least 1 empty bucket in the table. . #[inline] . fn find_insert_slot(&self, hash: u64) -> usize { . let mut probe_seq = self.probe_seq(hash); . loop { . unsafe { . let group = Group::load(self.ctrl(probe_seq.pos)); 11,280 ( 0.02%) if let Some(bit) = group.match_empty_or_deleted().lowest_set_bit() { 33,105 ( 0.05%) 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). 16,880 ( 0.02%) if unlikely(is_full(*self.ctrl(result))) { . debug_assert!(self.bucket_mask < Group::WIDTH); . debug_assert_ne!(probe_seq.pos, 0); . return Group::load_aligned(self.ctrl(0)) . .match_empty_or_deleted() . .lowest_set_bit_nonzero(); . } . . return result; -- line 1165 ---------------------------------------- -- line 1174 ---------------------------------------- . #[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); . . loop { . let group = unsafe { Group::load(self.ctrl(probe_seq.pos)) }; . 25,125 ( 0.03%) for bit in group.match_byte(h2_hash) { 35,379 ( 0.05%) let index = (probe_seq.pos + bit) & self.bucket_mask; . 16,574 ( 0.02%) if likely(eq(index)) { . return Some(index); . } . } . 10,048 ( 0.01%) 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(); 33,576 ( 0.05%) 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 { 207,531 ( 0.28%) 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) { 29,225 ( 0.04%) self.growth_left -= special_is_empty(old_ctrl) as usize; . self.set_ctrl_h2(index, hash); 23,380 ( 0.03%) self.items += 1; . } . . #[inline] . fn is_in_same_group(&self, i: usize, new_i: usize, hash: u64) -> bool { . let probe_seq_pos = self.probe_seq(hash).pos; . let probe_index = . |pos: usize| (pos.wrapping_sub(probe_seq_pos) & self.bucket_mask) / Group::WIDTH; . probe_index(i) == probe_index(new_i) -- line 1281 ---------------------------------------- -- line 1312 ---------------------------------------- . // replicate the buckets at the end of the trailing group. For example . // with 2 buckets and a group size of 4, the control bytes will look . // like this: . // . // Real | Replicated . // --------------------------------------------- . // | [A] | [B] | [EMPTY] | [EMPTY] | [A] | [B] | . // --------------------------------------------- 32,322 ( 0.04%) let index2 = ((index.wrapping_sub(Group::WIDTH)) & self.bucket_mask) + Group::WIDTH; . 10,774 ( 0.01%) *self.ctrl(index) = ctrl; 10,805 ( 0.01%) *self.ctrl(index2) = ctrl; . } . . /// Returns a pointer to a control byte. . #[inline] . unsafe fn ctrl(&self, index: usize) -> *mut u8 { . debug_assert!(index < self.num_ctrl_bytes()); . self.ctrl.as_ptr().add(index) . } . . #[inline] . fn buckets(&self) -> usize { 3,513 ( 0.00%) self.bucket_mask + 1 . } . . #[inline] . fn num_ctrl_bytes(&self) -> usize { 1,636 ( 0.00%) self.bucket_mask + 1 + Group::WIDTH . } . . #[inline] . fn is_empty_singleton(&self) -> bool { 6,872 ( 0.01%) 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. 135 ( 0.00%) let mut new_table = RawTableInner::fallible_with_capacity( . self.alloc.clone(), . table_layout, . capacity, . fallibility, . )?; 905 ( 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_| { 428 ( 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. 856 ( 0.00%) let new_items = match self.items.checked_add(additional) { . Some(new_items) => new_items, . None => return Err(fallibility.capacity_overflow()), . }; 856 ( 0.00%) let full_capacity = bucket_mask_to_capacity(self.bucket_mask); 1,815 ( 0.00%) if new_items <= full_capacity / 2 { . // Rehash in-place without re-allocating if we have plenty of spare . // capacity that is locked up due to DELETED entries. . self.rehash_in_place(hasher, layout.size, drop); . Ok(()) . } else { . // Otherwise, conservatively resize to at least the next size up . // to avoid churning deletes into frequent rehashes. . self.resize_inner( 428 ( 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> { 332 ( 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() { 5,141 ( 0.01%) if !is_full(*self.ctrl(i)) { . continue; . } . . // This may panic. . let hash = hasher(self, i); . . // We can use a simpler version of insert() here since: . // - there are no DELETED entries. -- line 1444 ---------------------------------------- -- line 1454 ---------------------------------------- . } . . // We successfully copied all elements without panicking. Now replace . // self with the new table. The old table will have its memory freed but . // the items will not be dropped (since they have been moved into the . // new table). . mem::swap(self, &mut new_table); . 428 ( 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( 283 ( 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) { 2 ( 0.00%) if !self.is_empty_singleton() { . unsafe { . self.ctrl(0).write_bytes(EMPTY, self.num_ctrl_bytes()); . } . } 4 ( 0.00%) self.items = 0; 2 ( 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))); 226 ( 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. 904 ( 0.00%) let ctrl = if empty_before.leading_zeros() + empty_after.trailing_zeros() >= Group::WIDTH { . DELETED . } else { 1,130 ( 0.00%) self.growth_left += 1; . EMPTY . }; . self.set_ctrl(index, ctrl); 904 ( 0.00%) self.items -= 1; . } . } . . impl Clone for RawTable { 64 ( 0.00%) fn clone(&self) -> Self { 8 ( 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) . } . } 72 ( 0.00%) } . . fn clone_from(&mut self, source: &Self) { . if source.table.is_empty_singleton() { . *self = Self::new_in(self.table.alloc.clone()); . } else { . unsafe { . // First, drop all our elements without clearing the control bytes. . self.drop_elements(); -- line 1640 ---------------------------------------- -- line 1687 ---------------------------------------- . .table . .ctrl(0) . .copy_to_nonoverlapping(self.table.ctrl(0), self.table.num_ctrl_bytes()); . source . .data_start() . .copy_to_nonoverlapping(self.data_start(), self.table.buckets()); . . self.table.items = source.table.items; 4 ( 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)] 3,648 ( 0.00%) fn drop(&mut self) { 2,664 ( 0.00%) if !self.table.is_empty_singleton() { . unsafe { . self.drop_elements(); . self.free_buckets(); . } . } 3,746 ( 0.01%) } . } . #[cfg(not(feature = "nightly"))] . impl Drop for RawTable { . #[cfg_attr(feature = "inline-more", inline)] . fn drop(&mut self) { . if !self.table.is_empty_singleton() { . unsafe { . self.drop_elements(); -- line 1813 ---------------------------------------- -- line 1817 ---------------------------------------- . } . } . . impl IntoIterator for RawTable { . type Item = T; . type IntoIter = RawIntoIter; . . #[cfg_attr(feature = "inline-more", inline)] 92 ( 0.00%) fn into_iter(self) -> RawIntoIter { . unsafe { . let iter = self.iter(); . self.into_iter_from(iter) . } 115 ( 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 { 2,300 ( 0.00%) if let Some(index) = self.current_group.lowest_set_bit() { 32 ( 0.00%) self.current_group = self.current_group.remove_lowest_bit(); 66 ( 0.00%) return Some(self.data.next_n(index)); . } . 2,211 ( 0.00%) if self.next_ctrl >= self.end { . return None; . } . . // We might read past self.end up to the next group boundary, . // but this is fine because it only occurs on tables smaller . // than the group size where the trailing control bytes are all . // EMPTY. On larger tables self.end is guaranteed to be aligned . // to the group size (since tables are power-of-two sized). 15 ( 0.00%) self.current_group = Group::load_aligned(self.next_ctrl).match_full(); . self.data = self.data.next_n(Group::WIDTH); 21 ( 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) { 51 ( 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)] 67 ( 0.00%) fn next(&mut self) -> Option> { 158 ( 0.00%) if let Some(b) = self.iter.next() { 2,352 ( 0.00%) 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 . } 134 ( 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)] 100 ( 0.00%) fn drop(&mut self) { . unsafe { . // Drop all remaining elements . self.iter.drop_elements(); . . // Free the table 99 ( 0.00%) if let Some((ptr, layout)) = self.allocation { . self.alloc.deallocate(ptr, layout); . } . } 42 ( 0.00%) } . } . #[cfg(not(feature = "nightly"))] . impl Drop for RawIntoIter { . #[cfg_attr(feature = "inline-more", inline)] . fn drop(&mut self) { . unsafe { . // Drop all remaining elements . self.iter.drop_elements(); -- line 2203 ---------------------------------------- -- line 2209 ---------------------------------------- . } . } . } . . impl Iterator for RawIntoIter { . type Item = T; . . #[cfg_attr(feature = "inline-more", inline)] 10 ( 0.00%) fn next(&mut self) -> Option { 6 ( 0.00%) unsafe { Some(self.iter.next()?.read()) } 21 ( 0.00%) } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 2 ( 0.00%) self.iter.size_hint() . } . } . . impl ExactSizeIterator for RawIntoIter {} . impl FusedIterator for RawIntoIter {} . . /// Iterator which consumes elements without freeing the table storage. . pub struct RawDrain<'a, T, A: Allocator + Clone = Global> { -- line 2231 ---------------------------------------- -- line 2259 ---------------------------------------- . where . T: Sync, . A: Sync, . { . } . . impl Drop for RawDrain<'_, T, A> { . #[cfg_attr(feature = "inline-more", inline)] 8 ( 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 ( 0.00%) self.orig_table . .as_ptr() . .copy_from_nonoverlapping(&*self.table, 1); . } 8 ( 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 ---------------------------------------- 66,436 ( 0.09%) -------------------------------------------------------------------------------- -- 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 { 29,109 ( 0.04%) Vec { buf: RawVec::NEW, len: 0 } 8 ( 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 { 8,277 ( 0.01%) 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 { 465 ( 0.00%) unsafe { Vec { buf: RawVec::from_raw_parts_in(ptr, capacity, alloc), len: length } } . } . . /// Decomposes a `Vec` into its raw components. . /// . /// Returns the raw pointer to the underlying data, the length of . /// the vector (in elements), and the allocated capacity of the . /// data (in elements). These are the same arguments in the same . /// order as the arguments to [`from_raw_parts`]. -- line 693 ---------------------------------------- -- line 778 ---------------------------------------- . /// . /// ``` . /// let vec: Vec = Vec::with_capacity(10); . /// assert_eq!(vec.capacity(), 10); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn capacity(&self) -> usize { 20,505 ( 0.03%) self.buf.capacity() . } . . /// Reserves capacity for at least `additional` more elements to be inserted . /// in the given `Vec`. The collection may reserve more space to avoid . /// frequent reallocations. After calling `reserve`, capacity will be . /// greater than or equal to `self.len() + additional`. Does nothing if . /// capacity is already sufficient. . /// -- line 794 ---------------------------------------- -- line 801 ---------------------------------------- . /// ``` . /// let mut vec = vec![1]; . /// vec.reserve(10); . /// assert!(vec.capacity() >= 11); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn reserve(&mut self, additional: usize) { 703 ( 0.00%) self.buf.reserve(self.len, additional); . } . . /// Reserves the minimum capacity for exactly `additional` more elements to . /// be inserted in the given `Vec`. After calling `reserve_exact`, . /// capacity will be greater than or equal to `self.len() + additional`. . /// Does nothing if the capacity is already sufficient. . /// . /// Note that the allocator may give the collection more space than it -- line 817 ---------------------------------------- -- line 829 ---------------------------------------- . /// ``` . /// let mut vec = vec![1]; . /// vec.reserve_exact(10); . /// assert!(vec.capacity() >= 11); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn reserve_exact(&mut self, additional: usize) { 55 ( 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. 575 ( 0.00%) if self.capacity() > self.len { 2 ( 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(); 112 ( 0.00%) 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")] 59,847 ( 0.08%) 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. 35,947 ( 0.05%) 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); 12,016 ( 0.02%) self.len = len; . ptr::drop_in_place(s); . } 71,814 ( 0.10%) } . . /// 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. 45,796 ( 0.06%) 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. 299,411 ( 0.41%) 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()); . 22,273 ( 0.03%) self.len = new_len; . } . . /// 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 1275 ---------------------------------------- -- 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")] 315 ( 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); . } . 45 ( 0.00%) let len = self.len(); 90 ( 0.00%) if index > len { . assert_failed(index, len); . } . . // space for the new element 106 ( 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.) 159 ( 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); . } 106 ( 0.00%) self.set_len(len + 1); . } 270 ( 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); . } . 30 ( 0.00%) let len = self.len(); 118 ( 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. 32 ( 0.00%) ret = ptr::read(ptr); . . // Shift everything down to fill in that spot. 60 ( 0.00%) ptr::copy(ptr.offset(1), ptr, len - index - 1); . } 30 ( 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")] 72 ( 0.00%) pub fn retain(&mut self, mut f: F) . where . F: FnMut(&T) -> bool, . { . self.retain_mut(|elem| f(elem)); 72 ( 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, . { 10 ( 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) { 14 ( 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), . 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, . { 52 ( 0.00%) while g.processed_len != original_len { . // SAFETY: Unchecked element must be valid. . let cur = unsafe { &mut *g.v.as_mut_ptr().add(g.processed_len) }; . if !f(cur) { . // Advance early to avoid double drop if `drop_in_place` panicked. . g.processed_len += 1; . g.deleted_cnt += 1; . // SAFETY: We never touch this element again after dropped. . unsafe { ptr::drop_in_place(cur) }; -- line 1541 ---------------------------------------- -- 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")] 7 ( 0.00%) pub fn dedup_by(&mut self, mut same_bucket: F) . where . F: FnMut(&mut T, &mut T) -> bool, . { 1 ( 0.00%) let len = self.len(); 18 ( 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 1699 ---------------------------------------- . } . . /* 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); . } 8 ( 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 1720 ---------------------------------------- . /// assert_eq!(vec, [1, 2, 3]); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . 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. 829,724 ( 1.13%) if self.len == self.buf.capacity() { 8,858 ( 0.01%) self.buf.reserve_for_push(self.len); . } . unsafe { 3,642 ( 0.00%) let end = self.as_mut_ptr().add(self.len); . ptr::write(end, value); 873,335 ( 1.19%) self.len += 1; . } . } . . /// 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. -- line 1742 ---------------------------------------- -- 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 { 9,940 ( 0.01%) if self.len == 0 { 3 ( 0.00%) None . } else { . unsafe { 6,947 ( 0.01%) self.len -= 1; 32 ( 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")] 56 ( 0.00%) pub fn append(&mut self, other: &mut Self) { . unsafe { . self.append_elements(other.as_slice() as _); . other.set_len(0); . } 48 ( 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); 314 ( 0.00%) let len = self.len(); . unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) }; 7,350 ( 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. . // 28 ( 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). 22 ( 0.00%) let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start), end - start); 199 ( 0.00%) Drain { . tail_start: end, 22 ( 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) { 106,049 ( 0.14%) self.truncate(0) . } . . /// Returns the number of elements in the vector, also referred to . /// as its 'length'. . /// . /// # Examples . /// . /// ``` -- line 1885 ---------------------------------------- -- line 1900 ---------------------------------------- . /// let mut v = Vec::new(); . /// assert!(v.is_empty()); . /// . /// v.push(1); . /// assert!(!v.is_empty()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn is_empty(&self) -> bool { 6,693 ( 0.01%) 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 1994 ---------------------------------------- . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "vec_resize_with", since = "1.33.0")] . pub fn resize_with(&mut self, new_len: usize, f: F) . where . F: FnMut() -> T, . { . let len = self.len(); . if new_len > len { 39 ( 0.00%) self.extend_with(new_len - len, ExtendFunc(f)); . } else { . self.truncate(new_len); . } . } . . /// 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 -- line 2010 ---------------------------------------- -- 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, 20 ( 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 2193 ---------------------------------------- . /// assert_eq!(vec, [1, 2]); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "vec_resize", since = "1.5.0")] . pub fn resize(&mut self, new_len: usize, value: T) { . let len = self.len(); . . if new_len > len { 27 ( 0.00%) self.extend_with(new_len - len, ExtendElement(value)) . } else { . self.truncate(new_len); . } . } . . /// Clones and appends all elements in a slice to the `Vec`. . /// . /// Iterates over the slice `other`, clones each element, and then appends -- line 2209 ---------------------------------------- -- 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. 251 ( 0.00%) fn extend_with>(&mut self, n: usize, mut value: E) { . self.reserve(n); . . unsafe { 39 ( 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); . } . 443 ( 0.00%) if n > 0 { . // We can write the last element directly without cloning needlessly . ptr::write(ptr, value.last()); . local_len.increment_len(1); . } . . // len set by scope guard . } 173 ( 0.00%) } . } . . impl Vec { . /// Removes consecutive repeated elements in the vector according to the . /// [`PartialEq`] trait implementation. . /// . /// If the vector is sorted, this removes all duplicates. . /// -- line 2333 ---------------------------------------- -- line 2338 ---------------------------------------- . /// . /// vec.dedup(); . /// . /// assert_eq!(vec, [1, 2, 3, 2]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . pub fn dedup(&mut self) { 2 ( 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")] 40 ( 0.00%) pub fn from_elem(elem: T, n: usize) -> Vec { 189 ( 0.00%) ::from_elem(elem, n, Global) 35 ( 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] { 28,660 ( 0.04%) unsafe { slice::from_raw_parts(self.as_ptr(), self.len) } . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl ops::DerefMut for Vec { . fn deref_mut(&mut self) -> &mut [T] { 5,430 ( 0.01%) 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))] 3,837 ( 0.01%) fn clone(&self) -> Self { . let alloc = self.allocator().clone(); 2 ( 0.00%) <[T]>::to_vec_in(&**self, alloc) 4,997 ( 0.01%) } . . // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is . // required for this method definition, is not available. Instead use the . // `slice::to_vec` function which is only available with cfg(test) . // NB see the slice::hack module in slice.rs for more information . #[cfg(test)] . fn clone(&self) -> Self { . let alloc = self.allocator().clone(); -- line 2487 ---------------------------------------- -- line 2539 ---------------------------------------- . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl FromIterator for Vec { . #[inline] . fn from_iter>(iter: I) -> Vec { 2,674 ( 0.00%) >::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 { 5,782 ( 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(); 1,213 ( 0.00%) IntoIter { . buf: NonNull::new_unchecked(begin), . phantom: PhantomData, . cap, . alloc, . ptr: begin, . end, . } . } -- line 2589 ---------------------------------------- -- line 2601 ---------------------------------------- . } . . #[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> { 626 ( 0.00%) self.iter_mut() . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl Extend for Vec { . #[inline] . fn extend>(&mut self, iter: I) { 468 ( 0.00%) >::spec_extend(self, iter.into_iter()) . } . . #[inline] . fn extend_one(&mut self, item: T) { . self.push(item); . } . . #[inline] -- line 2626 ---------------------------------------- -- 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); . // } 633 ( 0.00%) while let Some(element) = iterator.next() { 6 ( 0.00%) let len = self.len(); 882 ( 0.00%) if len == self.capacity() { . 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 965 ( 0.00%) self.set_len(len + 1); . } . } 8 ( 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, . { 7 ( 0.00%) let old_len = self.len(); . . // Guard against us getting leaked (leak amplification) . unsafe { . self.set_len(0); . } . . DrainFilter { vec: self, idx: 0, del: 0, old_len, pred: filter, panic_flag: false } . } -- line 2761 ---------------------------------------- -- 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 { 6,865 ( 0.01%) fn drop(&mut self) { . unsafe { . // use drop for [T] . // use a raw slice to refer to the elements of the vector as weakest necessary type; . // could avoid questions of validity in certain cases 4,736 ( 0.01%) ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len)) . } . // RawVec handles deallocation 8,170 ( 0.01%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")] . impl const Default for Vec { . /// Creates an empty `Vec`. . fn default() -> Vec { . Vec::new() -- line 2827 ---------------------------------------- -- line 2976 ---------------------------------------- . /// newly-allocated buffer with exactly the right capacity. . /// . /// # Examples . /// . /// ``` . /// assert_eq!(Box::from(vec![1, 2, 3]), vec![1, 2, 3].into_boxed_slice()); . /// ``` . fn from(v: Vec) -> Self { 4 ( 0.00%) v.into_boxed_slice() . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl From<&str> for Vec { . /// Allocate a `Vec` and fill it with a UTF-8 string. . /// -- line 2992 ---------------------------------------- 14,638 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/attr/mod.rs -------------------------------------------------------------------------------- Ir -- line 17 ---------------------------------------- . . use std::iter; . . pub struct MarkedAttrs(GrowableBitSet); . . impl MarkedAttrs { . // We have no idea how many attributes there will be, so just . // initiate the vectors with 0 bits. We'll grow them as necessary. 12 ( 0.00%) pub fn new() -> Self { 15 ( 0.00%) MarkedAttrs(GrowableBitSet::new_empty()) 12 ( 0.00%) } . . pub fn mark(&mut self, attr: &Attribute) { . self.0.insert(attr.id); . } . . pub fn is_marked(&self, attr: &Attribute) -> bool { 13 ( 0.00%) self.0.contains(attr.id) 13 ( 0.00%) } . } . . impl NestedMetaItem { . /// Returns the `MetaItem` if `self` is a `NestedMetaItem::MetaItem`. . pub fn meta_item(&self) -> Option<&MetaItem> { 1,236 ( 0.00%) match *self { . NestedMetaItem::MetaItem(ref item) => Some(item), . _ => None, . } 8 ( 0.00%) } . . /// Returns the `Lit` if `self` is a `NestedMetaItem::Literal`s. . pub fn literal(&self) -> Option<&Lit> { . match *self { . NestedMetaItem::Literal(ref lit) => Some(lit), . _ => None, . } . } . . /// Returns `true` if this list item is a MetaItem with a name of `name`. . pub fn has_name(&self, name: Symbol) -> bool { . self.meta_item().map_or(false, |meta_item| meta_item.has_name(name)) 20 ( 0.00%) } . . /// For a single-segment meta item, returns its name; otherwise, returns `None`. . pub fn ident(&self) -> Option { . self.meta_item().and_then(|meta_item| meta_item.ident()) . } . pub fn name_or_empty(&self) -> Symbol { . self.ident().unwrap_or_else(Ident::empty).name . } -- line 66 ---------------------------------------- -- line 90 ---------------------------------------- . /// Gets a list of inner meta items from a list `MetaItem` type. . pub fn meta_item_list(&self) -> Option<&[NestedMetaItem]> { . self.meta_item().and_then(|meta_item| meta_item.meta_item_list()) . } . . /// Returns `true` if the variant is `MetaItem`. . pub fn is_meta_item(&self) -> bool { . self.meta_item().is_some() 2 ( 0.00%) } . . /// Returns `true` if `self` is a `MetaItem` and the meta item is a word. . pub fn is_word(&self) -> bool { . self.meta_item().map_or(false, |meta_item| meta_item.is_word()) . } . . /// See [`MetaItem::name_value_literal_span`]. . pub fn name_value_literal_span(&self) -> Option { . self.meta_item()?.name_value_literal_span() . } . } . . impl Attribute { . #[inline] . pub fn has_name(&self, name: Symbol) -> bool { 187,824 ( 0.26%) match self.kind { . AttrKind::Normal(ref item, _) => item.path == name, . AttrKind::DocComment(..) => false, . } . } . . /// For a single-segment attribute, returns its name; otherwise, returns `None`. 1,252 ( 0.00%) pub fn ident(&self) -> Option { 7,402 ( 0.01%) match self.kind { . AttrKind::Normal(ref item, _) => { 652 ( 0.00%) if item.path.segments.len() == 1 { 520 ( 0.00%) Some(item.path.segments[0].ident) . } else { . None . } . } . AttrKind::DocComment(..) => None, . } 7,512 ( 0.01%) } . pub fn name_or_empty(&self) -> Symbol { 132 ( 0.00%) self.ident().unwrap_or_else(Ident::empty).name 2,449 ( 0.00%) } . . pub fn value_str(&self) -> Option { . match self.kind { . AttrKind::Normal(ref item, _) => item.meta_kind().and_then(|kind| kind.value_str()), . AttrKind::DocComment(..) => None, . } . } . 864 ( 0.00%) pub fn meta_item_list(&self) -> Option> { 576 ( 0.00%) match self.kind { 576 ( 0.00%) AttrKind::Normal(ref item, _) => match item.meta_kind() { 1,988 ( 0.00%) Some(MetaItemKind::List(list)) => Some(list), 4 ( 0.00%) _ => None, . }, . AttrKind::DocComment(..) => None, . } 1,152 ( 0.00%) } . . pub fn is_word(&self) -> bool { 6 ( 0.00%) if let AttrKind::Normal(item, _) = &self.kind { . matches!(item.args, MacArgs::Empty) . } else { . false . } 2 ( 0.00%) } . } . . impl MetaItem { . /// For a single-segment meta item, returns its name; otherwise, returns `None`. . pub fn ident(&self) -> Option { 58 ( 0.00%) if self.path.segments.len() == 1 { Some(self.path.segments[0].ident) } else { None } 30 ( 0.00%) } . pub fn name_or_empty(&self) -> Symbol { 11 ( 0.00%) self.ident().unwrap_or_else(Ident::empty).name 11 ( 0.00%) } . . // Example: . // #[attribute(name = "value")] . // ^^^^^^^^^^^^^^ . pub fn name_value_literal(&self) -> Option<&Lit> { . match &self.kind { . MetaItemKind::NameValue(v) => Some(v), . _ => None, . } . } . 7 ( 0.00%) pub fn value_str(&self) -> Option { 14 ( 0.00%) match self.kind { 8 ( 0.00%) MetaItemKind::NameValue(ref v) => match v.kind { 4 ( 0.00%) LitKind::Str(ref s, _) => Some(*s), . _ => None, . }, . _ => None, . } 7 ( 0.00%) } . . pub fn meta_item_list(&self) -> Option<&[NestedMetaItem]> { 18 ( 0.00%) match self.kind { . MetaItemKind::List(ref l) => Some(&l[..]), . _ => None, . } 6 ( 0.00%) } . . pub fn is_word(&self) -> bool { . matches!(self.kind, MetaItemKind::Word) . } . . pub fn has_name(&self, name: Symbol) -> bool { . self.path == name 32 ( 0.00%) } . . /// This is used in case you want the value span instead of the whole attribute. Example: . /// . /// ```text . /// #[doc(alias = "foo")] . /// ``` . /// . /// In here, it'll return a span for `"foo"`. -- line 213 ---------------------------------------- -- line 216 ---------------------------------------- . } . } . . impl AttrItem { . pub fn span(&self) -> Span { . self.args.span().map_or(self.path.span, |args_span| self.path.span.to(args_span)) . } . 56 ( 0.00%) pub fn meta(&self, span: Span) -> Option { 70 ( 0.00%) Some(MetaItem { . path: self.path.clone(), . kind: MetaItemKind::from_mac_args(&self.args)?, . span, . }) 49 ( 0.00%) } . . pub fn meta_kind(&self) -> Option { . Some(MetaItemKind::from_mac_args(&self.args)?) . } . } . . impl Attribute { . pub fn is_doc_comment(&self) -> bool { 3,238 ( 0.00%) match self.kind { . AttrKind::Normal(..) => false, . AttrKind::DocComment(..) => true, . } 1,619 ( 0.00%) } . . pub fn doc_str_and_comment_kind(&self) -> Option<(Symbol, CommentKind)> { . match self.kind { . AttrKind::DocComment(kind, data) => Some((data, kind)), . AttrKind::Normal(ref item, _) if item.path == sym::doc => item . .meta_kind() . .and_then(|kind| kind.value_str()) . .map(|data| (data, CommentKind::Line)), -- line 251 ---------------------------------------- -- line 258 ---------------------------------------- . AttrKind::DocComment(.., data) => Some(data), . AttrKind::Normal(ref item, _) if item.path == sym::doc => { . item.meta_kind().and_then(|kind| kind.value_str()) . } . _ => None, . } . } . 26 ( 0.00%) pub fn get_normal_item(&self) -> &AttrItem { 52 ( 0.00%) match self.kind { 26 ( 0.00%) AttrKind::Normal(ref item, _) => item, . AttrKind::DocComment(..) => panic!("unexpected doc comment"), . } 78 ( 0.00%) } . . pub fn unwrap_normal_item(self) -> AttrItem { . match self.kind { . AttrKind::Normal(item, _) => item, . AttrKind::DocComment(..) => panic!("unexpected doc comment"), . } . } . . /// Extracts the MetaItem from inside this Attribute. 14 ( 0.00%) pub fn meta(&self) -> Option { 14 ( 0.00%) match self.kind { 28 ( 0.00%) AttrKind::Normal(ref item, _) => item.meta(self.span), . AttrKind::DocComment(..) => None, . } 21 ( 0.00%) } . . pub fn meta_kind(&self) -> Option { . match self.kind { . AttrKind::Normal(ref item, _) => item.meta_kind(), . AttrKind::DocComment(..) => None, . } . } . 14 ( 0.00%) pub fn tokens(&self) -> AttrAnnotatedTokenStream { 4 ( 0.00%) match self.kind { . AttrKind::Normal(_, ref tokens) => tokens . .as_ref() . .unwrap_or_else(|| panic!("attribute is missing tokens: {:?}", self)) . .create_token_stream(), . AttrKind::DocComment(comment_kind, data) => AttrAnnotatedTokenStream::from(( . AttrAnnotatedTokenTree::Token(Token::new( . token::DocComment(comment_kind, self.style, data), . self.span, -- line 304 ---------------------------------------- -- line 321 ---------------------------------------- . let span = ident.span.to(lit_span); . MetaItem { path: Path::from_ident(ident), span, kind: MetaItemKind::NameValue(lit) } . } . . pub fn mk_list_item(ident: Ident, items: Vec) -> MetaItem { . MetaItem { path: Path::from_ident(ident), span: ident.span, kind: MetaItemKind::List(items) } . } . 18 ( 0.00%) pub fn mk_word_item(ident: Ident) -> MetaItem { 21 ( 0.00%) MetaItem { path: Path::from_ident(ident), span: ident.span, kind: MetaItemKind::Word } 15 ( 0.00%) } . . pub fn mk_nested_word_item(ident: Ident) -> NestedMetaItem { . NestedMetaItem::MetaItem(mk_word_item(ident)) . } . 56 ( 0.00%) crate fn mk_attr_id() -> AttrId { . use std::sync::atomic::AtomicU32; . use std::sync::atomic::Ordering; . . static NEXT_ATTR_ID: AtomicU32 = AtomicU32::new(0); . . let id = NEXT_ATTR_ID.fetch_add(1, Ordering::SeqCst); 838 ( 0.00%) assert!(id != u32::MAX); . AttrId::from_u32(id) 56 ( 0.00%) } . . pub fn mk_attr(style: AttrStyle, path: Path, args: MacArgs, span: Span) -> Attribute { 36 ( 0.00%) mk_attr_from_item(AttrItem { path, args, tokens: None }, None, style, span) . } . 114 ( 0.00%) pub fn mk_attr_from_item( . item: AttrItem, . tokens: Option, . style: AttrStyle, . span: Span, . ) -> Attribute { 1,923 ( 0.00%) Attribute { kind: AttrKind::Normal(item, tokens), id: mk_attr_id(), style, span } 228 ( 0.00%) } . . /// Returns an inner attribute with the given value and span. . pub fn mk_attr_inner(item: MetaItem) -> Attribute { . mk_attr(AttrStyle::Inner, item.path, item.kind.mac_args(item.span), item.span) . } . . /// Returns an outer attribute with the given value and span. 18 ( 0.00%) pub fn mk_attr_outer(item: MetaItem) -> Attribute { 36 ( 0.00%) mk_attr(AttrStyle::Outer, item.path, item.kind.mac_args(item.span), item.span) 18 ( 0.00%) } . 662 ( 0.00%) pub fn mk_doc_comment( . comment_kind: CommentKind, . style: AttrStyle, . data: Symbol, . span: Span, . ) -> Attribute { 6,951 ( 0.01%) Attribute { kind: AttrKind::DocComment(comment_kind, data), id: mk_attr_id(), style, span } 1,324 ( 0.00%) } . . pub fn list_contains_name(items: &[NestedMetaItem], name: Symbol) -> bool { . items.iter().any(|item| item.has_name(name)) 280 ( 0.00%) } . . impl MetaItem { . fn token_trees_and_spacings(&self) -> Vec { . let mut idents = vec![]; . let mut last_pos = BytePos(0_u32); . for (i, segment) in self.path.segments.iter().enumerate() { . let is_first = i == 0; . if !is_first { -- line 390 ---------------------------------------- -- line 399 ---------------------------------------- . idents . } . . fn from_tokens(tokens: &mut iter::Peekable) -> Option . where . I: Iterator, . { . // FIXME: Share code with `parse_path`. 2,320 ( 0.00%) let path = match tokens.next().map(TokenTree::uninterpolate) { . Some(TokenTree::Token(Token { 580 ( 0.00%) kind: kind @ (token::Ident(..) | token::ModSep), 290 ( 0.00%) span, . })) => 'arm: { 870 ( 0.00%) let mut segments = if let token::Ident(name, _) = kind { 1,382 ( 0.00%) if let Some(TokenTree::Token(Token { kind: token::ModSep, .. })) = tokens.peek() . { . tokens.next(); . vec![PathSegment::from_ident(Ident::new(name, span))] . } else { . break 'arm Path::from_ident(Ident::new(name, span)); . } . } else { . vec![PathSegment::path_root(span)] -- line 421 ---------------------------------------- -- line 439 ---------------------------------------- . Path { span, segments, tokens: None } . } . Some(TokenTree::Token(Token { kind: token::Interpolated(nt), .. })) => match *nt { . token::Nonterminal::NtMeta(ref item) => return item.meta(item.path.span), . token::Nonterminal::NtPath(ref path) => path.clone(), . _ => return None, . }, . _ => return None, 580 ( 0.00%) }; . let list_closing_paren_pos = tokens.peek().map(|tt| tt.span().hi()); 290 ( 0.00%) let kind = MetaItemKind::from_tokens(tokens)?; 1,160 ( 0.00%) let hi = match kind { 546 ( 0.00%) MetaItemKind::NameValue(ref lit) => lit.span.hi(), . MetaItemKind::List(..) => list_closing_paren_pos.unwrap_or(path.span.hi()), 51 ( 0.00%) _ => path.span.hi(), . }; 1,416 ( 0.00%) let span = path.span.with_hi(hi); 8,700 ( 0.01%) Some(MetaItem { path, kind, span }) . } . } . . impl MetaItemKind { . pub fn value_str(&self) -> Option { . match self { . MetaItemKind::NameValue(ref v) => match v.kind { . LitKind::Str(ref s, _) => Some(*s), . _ => None, . }, . _ => None, . } . } . 24 ( 0.00%) pub fn mac_args(&self, span: Span) -> MacArgs { 9 ( 0.00%) match self { 6 ( 0.00%) MetaItemKind::Word => MacArgs::Empty, . MetaItemKind::NameValue(lit) => MacArgs::Eq(span, lit.to_token()), . MetaItemKind::List(list) => { . let mut tts = Vec::new(); . for (i, item) in list.iter().enumerate() { . if i > 0 { . tts.push(TokenTree::token(token::Comma, span).into()); . } . tts.extend(item.token_trees_and_spacings()) -- line 481 ---------------------------------------- -- line 482 ---------------------------------------- . } . MacArgs::Delimited( . DelimSpan::from_single(span), . MacDelimiter::Parenthesis, . TokenStream::new(tts), . ) . } . } 27 ( 0.00%) } . . fn token_trees_and_spacings(&self, span: Span) -> Vec { . match *self { . MetaItemKind::Word => vec![], . MetaItemKind::NameValue(ref lit) => { . vec![ . TokenTree::token(token::Eq, span).into(), . TokenTree::Token(lit.to_token()).into(), -- line 498 ---------------------------------------- -- line 513 ---------------------------------------- . TokenStream::new(tokens), . ) . .into(), . ] . } . } . } . 2,312 ( 0.00%) fn list_from_tokens(tokens: TokenStream) -> Option { . let mut tokens = tokens.into_trees().peekable(); . let mut result = Vec::new(); 579 ( 0.00%) while tokens.peek().is_some() { 870 ( 0.00%) let item = NestedMetaItem::from_tokens(&mut tokens)?; 2,320 ( 0.00%) result.push(item); 1,162 ( 0.00%) match tokens.next() { . None | Some(TokenTree::Token(Token { kind: token::Comma, .. })) => {} . _ => return None, . } . } 2,023 ( 0.00%) Some(MetaItemKind::List(result)) 2,312 ( 0.00%) } . . fn name_value_from_tokens( . tokens: &mut impl Iterator, . ) -> Option { 1,365 ( 0.00%) match tokens.next() { . Some(TokenTree::Delimited(_, token::NoDelim, inner_tokens)) => { . MetaItemKind::name_value_from_tokens(&mut inner_tokens.trees()) . } 1,638 ( 0.00%) Some(TokenTree::Token(token)) => { 273 ( 0.00%) Lit::from_token(&token).ok().map(MetaItemKind::NameValue) . } . _ => None, . } 1,092 ( 0.00%) } . . fn from_mac_args(args: &MacArgs) -> Option { 2,041 ( 0.00%) match args { . MacArgs::Delimited(_, MacDelimiter::Parenthesis, tokens) => { 578 ( 0.00%) MetaItemKind::list_from_tokens(tokens.clone()) . } . MacArgs::Delimited(..) => None, . MacArgs::Eq(_, token) => Lit::from_token(token).ok().map(MetaItemKind::NameValue), . MacArgs::Empty => Some(MetaItemKind::Word), . } . } . . fn from_tokens( . tokens: &mut iter::Peekable>, . ) -> Option { 1,382 ( 0.00%) match tokens.peek() { . Some(TokenTree::Delimited(_, token::Paren, inner_tokens)) => { . let inner_tokens = inner_tokens.clone(); . tokens.next(); . MetaItemKind::list_from_tokens(inner_tokens) . } . Some(TokenTree::Delimited(..)) => None, . Some(TokenTree::Token(Token { kind: token::Eq, .. })) => { . tokens.next(); . MetaItemKind::name_value_from_tokens(tokens) . } 17 ( 0.00%) _ => Some(MetaItemKind::Word), . } . } . } . . impl NestedMetaItem { . pub fn span(&self) -> Span { . match *self { . NestedMetaItem::MetaItem(ref item) => item.span, -- line 582 ---------------------------------------- -- line 586 ---------------------------------------- . . fn token_trees_and_spacings(&self) -> Vec { . match *self { . NestedMetaItem::MetaItem(ref item) => item.token_trees_and_spacings(), . NestedMetaItem::Literal(ref lit) => vec![TokenTree::Token(lit.to_token()).into()], . } . } . 2,610 ( 0.00%) fn from_tokens(tokens: &mut iter::Peekable) -> Option . where . I: Iterator, . { 870 ( 0.00%) match tokens.peek() { 580 ( 0.00%) Some(TokenTree::Token(token)) 870 ( 0.00%) if let Ok(lit) = Lit::from_token(token) => . { . tokens.next(); . return Some(NestedMetaItem::Literal(lit)); . } . Some(TokenTree::Delimited(_, token::NoDelim, inner_tokens)) => { . let inner_tokens = inner_tokens.clone(); . tokens.next(); . return NestedMetaItem::from_tokens(&mut inner_tokens.into_trees().peekable()); . } . _ => {} . } . MetaItem::from_tokens(tokens).map(NestedMetaItem::MetaItem) 2,320 ( 0.00%) } . } 6,634 ( 0.01%) -------------------------------------------------------------------------------- -- 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%) } . 337 ( 0.00%) #[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 } 15,201 ( 0.02%) } . . /// 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. . pub fn from_str_and_span(string: &str, span: Span) -> Ident { . Ident::new(Symbol::intern(string), span) . } . . /// Replaces `lo` and `hi` with those from `span`, but keep hygiene context. 24 ( 0.00%) pub fn with_span_pos(self, span: Span) -> Ident { . Ident::new(self.name, span.with_ctxt(self.span.ctxt())) 15 ( 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. 2,331 ( 0.00%) pub fn normalize_to_macros_2_0(self) -> Ident { . Ident::new(self.name, self.span.normalize_to_macros_2_0()) 1,813 ( 0.00%) } . . /// "Normalize" ident for use in comparisons using "local variable hygiene". . /// Identifiers with same string value become same if they came from the same non-transparent . /// macro (e.g., `macro` or `macro_rules!` items) and stay different if they came from different . /// non-transparent macros. . /// Technically, this operation strips all transparent marks from ident's syntactic context. 1,368 ( 0.00%) pub fn normalize_to_macro_rules(self) -> Ident { . Ident::new(self.name, self.span.normalize_to_macro_rules()) 1,064 ( 0.00%) } . . /// Access the underlying string. This is a slowish operation because it . /// requires locking the symbol interner. . /// . /// Note that the lifetime of the return value is a lie. See . /// `Symbol::as_str()` for details. . pub fn as_str(&self) -> &str { 5 ( 0.00%) self.name.as_str() . } . } . . impl PartialEq for Ident { 477 ( 0.00%) fn eq(&self, rhs: &Self) -> bool { 1,044 ( 0.00%) self.name == rhs.name && self.span.ctxt() == rhs.span.ctxt() 636 ( 0.00%) } . } . . impl Hash for Ident { . fn hash(&self, state: &mut H) { 59 ( 0.00%) self.name.hash(state); 638 ( 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) . } -- line 1596 ---------------------------------------- -- 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. 11 ( 0.00%) pub fn new(symbol: Symbol, is_raw: bool, convert_dollar_crate: Option) -> IdentPrinter { 44 ( 0.00%) IdentPrinter { symbol, is_raw, convert_dollar_crate } 11 ( 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. . pub fn for_ast_ident(ident: Ident, is_raw: bool) -> IdentPrinter { . IdentPrinter::new(ident.name, is_raw, Some(ident.span)) . } . } . . impl fmt::Display for IdentPrinter { 55 ( 0.00%) fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 22 ( 0.00%) if self.is_raw { . f.write_str("r#")?; 11 ( 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)] 642 ( 0.00%) pub struct MacroRulesNormalizedIdent(Ident); . . impl MacroRulesNormalizedIdent { . pub fn new(ident: Ident) -> Self { 152 ( 0.00%) 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)] 995 ( 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)) . } . . /// Maps a string to its interned representation. 34,767 ( 0.05%) pub fn intern(string: &str) -> Self { . with_session_globals(|session_globals| session_globals.symbol_interner.intern(string)) 34,767 ( 0.05%) } . . /// 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. 13,971 ( 0.02%) pub fn as_str(&self) -> &str { 4,657 ( 0.01%) with_session_globals(|session_globals| unsafe { . std::mem::transmute::<&str, &str>(session_globals.symbol_interner.get(*self)) . }) 18,628 ( 0.03%) } . . 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 { 50 ( 0.00%) fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 249 ( 0.00%) fmt::Display::fmt(self.as_str(), f) . } . } . . impl Encodable for Symbol { . fn encode(&self, s: &mut S) -> Result<(), S::Error> { 9,266 ( 0.01%) s.emit_str(self.as_str()) . } . } . . impl Decodable for Symbol { . #[inline] 290 ( 0.00%) fn decode(d: &mut D) -> Symbol { 598 ( 0.00%) Symbol::intern(&d.read_str()) . } . } . . impl HashStable for Symbol { . #[inline] 6 ( 0.00%) fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) { 4,286 ( 0.01%) self.as_str().hash_stable(hcx, hasher); . } . } . . impl ToStableHashKey for Symbol { . type KeyType = String; . #[inline] . fn to_stable_hash_key(&self, _: &CTX) -> String { . self.as_str().to_string() -- line 1777 ---------------------------------------- -- 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(); 6,556 ( 0.01%) if let Some(&name) = inner.names.get(string) { . return name; . } . 585 ( 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 { 13,971 ( 0.02%) 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 1879 ---------------------------------------- . } . . impl Symbol { . fn is_special(self) -> bool { . self <= kw::Underscore . } . . fn is_used_keyword_always(self) -> bool { 33 ( 0.00%) self >= kw::As && self <= kw::While . } . . fn is_used_keyword_conditional(self, edition: impl FnOnce() -> Edition) -> bool { 3,432 ( 0.00%) (self >= kw::Async && self <= kw::Dyn) && edition() >= Edition::Edition2018 . } . . fn is_unused_keyword_always(self) -> bool { 33 ( 0.00%) self >= kw::Abstract && self <= kw::Yield . } . . fn is_unused_keyword_conditional(self, edition: impl FnOnce() -> Edition) -> bool { 11 ( 0.00%) self == kw::Try && edition() >= Edition::Edition2018 . } . . pub fn is_reserved(self, edition: impl Copy + FnOnce() -> Edition) -> bool { 5,800 ( 0.01%) 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 { 7,798 ( 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 { 366 ( 0.00%) self == kw::True || self == kw::False 366 ( 0.00%) } . . /// Returns `true` if this symbol can be a raw identifier. . pub fn can_be_raw(self) -> bool { . self != kw::Empty && self != kw::Underscore && !self.is_path_segment_keyword() . } . } . . 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() 11 ( 0.00%) } . . /// Returns `true` if the token is a keyword used in the language. 11 ( 0.00%) pub fn is_used_keyword(self) -> bool { . // Note: `span.edition()` is relatively expensive, don't call it unless necessary. 11 ( 0.00%) self.name.is_used_keyword_always() . || self.name.is_used_keyword_conditional(|| self.span.edition()) 22 ( 0.00%) } . . /// Returns `true` if the token is a keyword reserved for possible future use. 11 ( 0.00%) pub fn is_unused_keyword(self) -> bool { . // Note: `span.edition()` is relatively expensive, don't call it unless necessary. 11 ( 0.00%) self.name.is_unused_keyword_always() . || self.name.is_unused_keyword_conditional(|| self.span.edition()) 22 ( 0.00%) } . . /// Returns `true` if the token is either a special identifier or a keyword. 1,160 ( 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()) 2,320 ( 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() 1,114 ( 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. . pub fn is_raw_guess(self) -> bool { . self.name.can_be_raw() && self.is_reserved() . } . } 6,067 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cmp.rs -------------------------------------------------------------------------------- Ir -- line 223 ---------------------------------------- . fn eq(&self, other: &Rhs) -> bool; . . /// This method tests for `!=`. . #[inline] . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[default_method_body_is_const] . fn ne(&self, other: &Rhs) -> bool { 1,938 ( 0.00%) !self.eq(other) . } . } . . /// Derive macro generating an impl of the trait `PartialEq`. . #[rustc_builtin_macro] . #[stable(feature = "builtin_macro_prelude", since = "1.38.0")] . #[allow_internal_unstable(core_intrinsics, structural_match)] . pub macro PartialEq($item:item) { -- line 239 ---------------------------------------- -- line 569 ---------------------------------------- . /// let result = x.0.cmp(&y.0).then_with(|| x.1.cmp(&y.1)).then_with(|| x.2.cmp(&y.2)); . /// . /// assert_eq!(result, Ordering::Less); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "ordering_chaining", since = "1.17.0")] . pub fn then_with Ordering>(self, f: F) -> Ordering { 1 ( 0.00%) match self { . Equal => f(), . _ => self, . } . } . } . . /// A helper struct for reverse ordering. . /// -- line 585 ---------------------------------------- -- line 1097 ---------------------------------------- . /// let result = 2.0 < 1.0; . /// assert_eq!(result, false); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[default_method_body_is_const] . fn lt(&self, other: &Rhs) -> bool { 10,698 ( 0.01%) matches!(self.partial_cmp(other), Some(Less)) . } . . /// This method tests less than or equal to (for `self` and `other`) and is used by the `<=` . /// operator. . /// . /// # Examples . /// . /// ``` -- line 1113 ---------------------------------------- -- line 1121 ---------------------------------------- . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[default_method_body_is_const] . fn le(&self, other: &Rhs) -> bool { . // Pattern `Some(Less | Eq)` optimizes worse than negating `None | Some(Greater)`. . // FIXME: The root cause was fixed upstream in LLVM with: . // https://github.com/llvm/llvm-project/commit/9bad7de9a3fb844f1ca2965f35d0c2a3d1e11775 . // Revert this workaround once support for LLVM 12 gets dropped. 35,180 ( 0.05%) !matches!(self.partial_cmp(other), None | Some(Greater)) . } . . /// This method tests greater than (for `self` and `other`) and is used by the `>` operator. . /// . /// # Examples . /// . /// ``` . /// let result = 1.0 > 2.0; -- line 1137 ---------------------------------------- -- line 1140 ---------------------------------------- . /// let result = 2.0 > 2.0; . /// assert_eq!(result, false); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[default_method_body_is_const] . fn gt(&self, other: &Rhs) -> bool { 25,373 ( 0.03%) matches!(self.partial_cmp(other), Some(Greater)) . } . . /// This method tests greater than or equal to (for `self` and `other`) and is used by the `>=` . /// operator. . /// . /// # Examples . /// . /// ``` -- line 1156 ---------------------------------------- -- line 1160 ---------------------------------------- . /// let result = 2.0 >= 2.0; . /// assert_eq!(result, true); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[default_method_body_is_const] . fn ge(&self, other: &Rhs) -> bool { 2 ( 0.00%) matches!(self.partial_cmp(other), Some(Greater | Equal)) . } . } . . /// Derive macro generating an impl of the trait `PartialOrd`. . #[rustc_builtin_macro] . #[stable(feature = "builtin_macro_prelude", since = "1.38.0")] . #[allow_internal_unstable(core_intrinsics)] . pub macro PartialOrd($item:item) { -- line 1176 ---------------------------------------- -- line 1210 ---------------------------------------- . /// . /// assert_eq!(cmp::min_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 1); . /// assert_eq!(cmp::min_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "cmp_min_max_by", since = "1.53.0")] . pub fn min_by Ordering>(v1: T, v2: T, compare: F) -> T { 5,266 ( 0.01%) match compare(&v1, &v2) { . Ordering::Less | Ordering::Equal => v1, . Ordering::Greater => v2, . } . } . . /// Returns the element that gives the minimum value from the specified function. . /// . /// Returns the first argument if the comparison determines them to be equal. -- line 1226 ---------------------------------------- -- line 1273 ---------------------------------------- . /// . /// assert_eq!(cmp::max_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2); . /// assert_eq!(cmp::max_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 2); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "cmp_min_max_by", since = "1.53.0")] . pub fn max_by Ordering>(v1: T, v2: T, compare: F) -> T { 12,529 ( 0.02%) match compare(&v1, &v2) { . Ordering::Less | Ordering::Equal => v2, . Ordering::Greater => v1, . } . } . . /// Returns the element that gives the maximum value from the specified function. . /// . /// Returns the second argument if the comparison determines them to be equal. -- line 1289 ---------------------------------------- -- line 1308 ---------------------------------------- . use crate::cmp::Ordering::{self, Equal, Greater, Less}; . use crate::hint::unreachable_unchecked; . . macro_rules! partial_eq_impl { . ($($t:ty)*) => ($( . #[stable(feature = "rust1", since = "1.0.0")] . impl PartialEq for $t { . #[inline] 138 ( 0.00%) fn eq(&self, other: &$t) -> bool { (*self) == (*other) } . #[inline] . fn ne(&self, other: &$t) -> bool { (*self) != (*other) } . } . )*) . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl PartialEq for () { -- line 1324 ---------------------------------------- -- line 1392 ---------------------------------------- . ($($t:ty)*) => ($( . #[stable(feature = "rust1", since = "1.0.0")] . impl PartialOrd for $t { . #[inline] . fn partial_cmp(&self, other: &$t) -> Option { . Some(self.cmp(other)) . } . #[inline] 356,248 ( 0.49%) fn lt(&self, other: &$t) -> bool { (*self) < (*other) } . #[inline] . fn le(&self, other: &$t) -> bool { (*self) <= (*other) } . #[inline] . fn ge(&self, other: &$t) -> bool { (*self) >= (*other) } . #[inline] . fn gt(&self, other: &$t) -> bool { (*self) > (*other) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Ord for $t { . #[inline] . fn cmp(&self, other: &$t) -> Ordering { . // The order here is important to generate more optimal assembly. . // See for more info. 42,741 ( 0.06%) if *self < *other { Less } . else if *self == *other { Equal } . else { Greater } . } . } . )*) . } . . #[stable(feature = "rust1", since = "1.0.0")] -- line 1423 ---------------------------------------- -- line 1430 ---------------------------------------- . . #[stable(feature = "rust1", since = "1.0.0")] . impl Ord for bool { . #[inline] . fn cmp(&self, other: &bool) -> Ordering { . // Casting to i8's and converting the difference to an Ordering generates . // more optimal assembly. . // See for more info. 28 ( 0.00%) match (*self as i8) - (*other as i8) { . -1 => Less, . 0 => Equal, . 1 => Greater, . // SAFETY: bool as i8 returns 0 or 1, so the difference can't be anything else . _ => unsafe { unreachable_unchecked() }, . } . } . } -- line 1446 ---------------------------------------- -- line 1475 ---------------------------------------- . . #[stable(feature = "rust1", since = "1.0.0")] . impl PartialEq<&B> for &A . where . A: PartialEq, . { . #[inline] . fn eq(&self, other: &&B) -> bool { 981 ( 0.00%) PartialEq::eq(*self, *other) . } . #[inline] . fn ne(&self, other: &&B) -> bool { 9 ( 0.00%) PartialEq::ne(*self, *other) . } . } . #[stable(feature = "rust1", since = "1.0.0")] . impl PartialOrd<&B> for &A . where . A: PartialOrd, . { . #[inline] -- line 1495 ---------------------------------------- 36,468 ( 0.05%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/iter/range.rs -------------------------------------------------------------------------------- Ir -- line 198 ---------------------------------------- . } . . #[inline] . #[allow(arithmetic_overflow)] . #[rustc_inherit_overflow_checks] . fn forward(start: Self, n: usize) -> Self { . // In debug builds, trigger a panic on overflow. . // This should optimize completely out in release builds. 2,912 ( 0.00%) if Self::forward_checked(start, n).is_none() { . let _ = Self::MAX + 1; . } . // Do wrapping math to allow e.g. `Step::forward(-128i8, 255)`. . start.wrapping_add(n as Self) . } . . #[inline] . #[allow(arithmetic_overflow)] -- line 214 ---------------------------------------- -- line 613 ---------------------------------------- . . if taken < n { Err(taken) } else { Ok(()) } . } . } . . impl RangeIteratorImpl for ops::Range { . #[inline] . fn spec_next(&mut self) -> Option { 297,190 ( 0.41%) if self.start < self.end { . // SAFETY: just checked precondition . let n = unsafe { Step::forward_unchecked(self.start.clone(), 1) }; . Some(mem::replace(&mut self.start, n)) . } else { . None . } . } . -- line 629 ---------------------------------------- -- line 657 ---------------------------------------- . // Otherwise 0 is returned which always safe to use. . self.start = unsafe { Step::forward_unchecked(self.start.clone(), taken) }; . . if taken < n { Err(taken) } else { Ok(()) } . } . . #[inline] . fn spec_next_back(&mut self) -> Option { 56 ( 0.00%) if self.start < self.end { . // SAFETY: just checked precondition . self.end = unsafe { Step::backward_unchecked(self.end.clone(), 1) }; . Some(self.end.clone()) . } else { . None . } . } . -- line 673 ---------------------------------------- -- line 708 ---------------------------------------- . . #[inline] . fn next(&mut self) -> Option { . self.spec_next() . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 61 ( 0.00%) if self.start < self.end { . let hint = Step::steps_between(&self.start, &self.end); . (hint.unwrap_or(usize::MAX), hint) . } else { . (0, Some(0)) . } . } . . #[inline] -- line 724 ---------------------------------------- 34,253 ( 0.05%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/mod.rs -------------------------------------------------------------------------------- Ir -- line 26 ---------------------------------------- . pub struct UnmatchedBrace { . pub expected_delim: token::DelimToken, . pub found_delim: Option, . pub found_span: Span, . pub unclosed_span: Option, . pub candidate_span: Option, . } . 28 ( 0.00%) crate fn parse_token_trees<'a>( . sess: &'a ParseSess, . src: &'a str, . start_pos: BytePos, . override_span: Option, . ) -> (PResult<'a, TokenStream>, Vec) { . StringReader { sess, start_pos, pos: start_pos, end_src_index: src.len(), src, override_span } . .into_token_trees() 18 ( 0.00%) } . . struct StringReader<'a> { . sess: &'a ParseSess, . /// Initial position, read-only. . start_pos: BytePos, . /// The absolute offset within the source_map of the current character. . pos: BytePos, . /// Stop reading src at this index. -- line 50 ---------------------------------------- -- line 51 ---------------------------------------- . end_src_index: usize, . /// Source text to tokenize. . src: &'a str, . override_span: Option, . } . . impl<'a> StringReader<'a> { . fn mk_sp(&self, lo: BytePos, hi: BytePos) -> Span { 11,903 ( 0.02%) self.override_span.unwrap_or_else(|| Span::with_root_ctxt(lo, hi)) . } . . /// Returns the next token, and info about preceding whitespace, if any. 62,951 ( 0.09%) fn next_token(&mut self) -> (Spacing, Token) { . let mut spacing = Spacing::Joint; . . // Skip `#!` at the start of the file 17,986 ( 0.02%) let start_src_index = self.src_index(self.pos); 26,979 ( 0.04%) let text: &str = &self.src[start_src_index..self.end_src_index]; . let is_beginning_of_file = self.pos == self.start_pos; 8,993 ( 0.01%) if is_beginning_of_file { 8 ( 0.00%) if let Some(shebang_len) = rustc_lexer::strip_shebang(text) { . self.pos = self.pos + BytePos::from_usize(shebang_len); . spacing = Spacing::Alone; . } . } . . // Skip trivial (whitespace & comments) tokens . loop { 15,775 ( 0.02%) let start_src_index = self.src_index(self.pos); 37,152 ( 0.05%) let text: &str = &self.src[start_src_index..self.end_src_index]; . 12,384 ( 0.02%) if text.is_empty() { . let span = self.mk_sp(self.pos, self.pos); 10 ( 0.00%) return (spacing, Token::new(token::Eof, span)); . } . 37,146 ( 0.05%) let token = rustc_lexer::first_token(text); . 24,764 ( 0.03%) let start = self.pos; 12,382 ( 0.02%) self.pos = self.pos + BytePos::from_usize(token.len); . . debug!("next_token: {:?}({:?})", token.kind, self.str_from(start)); . 100,760 ( 0.14%) match self.cook_lexer_token(token.kind, start) { 71,928 ( 0.10%) Some(kind) => { . let span = self.mk_sp(start, self.pos); 53,946 ( 0.07%) return (spacing, Token::new(kind, span)); . } . None => spacing = Spacing::Alone, . } . } 80,937 ( 0.11%) } . . /// Report a fatal lexical error with a given span. . fn fatal_span(&self, sp: Span, m: &str) -> FatalError { . self.sess.span_diagnostic.span_fatal(sp, m) . } . . /// Report a lexical error with a given span. . fn err_span(&self, sp: Span, m: &str) { -- line 110 ---------------------------------------- -- line 130 ---------------------------------------- . ) -> DiagnosticBuilder<'a> { . self.sess . .span_diagnostic . .struct_span_fatal(self.mk_sp(from_pos, to_pos), &format!("{}: {}", m, escaped_char(c))) . } . . /// Detect usages of Unicode codepoints changing the direction of the text on screen and loudly . /// complain about it. 714 ( 0.00%) fn lint_unicode_text_flow(&self, start: BytePos) { . // Opening delimiter of the length 2 is not included into the comment text. . let content_start = start + BytePos(2); . let content = self.str_from(content_start); . if contains_text_flow_control_chars(content) { . let span = self.mk_sp(start, self.pos); . self.sess.buffer_lint_with_diagnostic( . &TEXT_DIRECTION_CODEPOINT_IN_COMMENT, . span, . ast::CRATE_NODE_ID, . "unicode codepoint changing visible direction of text present in comment", . BuiltinLintDiagnostics::UnicodeTextFlow(span, content.to_string()), . ); . } 816 ( 0.00%) } . . /// Turns simple `rustc_lexer::TokenKind` enum into a rich . /// `rustc_ast::TokenKind`. This turns strings into interned . /// symbols and runs additional validation. . fn cook_lexer_token(&self, token: rustc_lexer::TokenKind, start: BytePos) -> Option { 61,910 ( 0.08%) Some(match token { 528 ( 0.00%) rustc_lexer::TokenKind::LineComment { doc_style } => { . // Skip non-doc comments 2,334 ( 0.00%) let doc_style = if let Some(doc_style) = doc_style { . doc_style . } else { . self.lint_unicode_text_flow(start); . return None; . }; . . // Opening delimiter of the length 3 is not included into the symbol. . let content_start = start + BytePos(3); . let content = self.str_from(content_start); 2,130 ( 0.00%) self.cook_doc_comment(content_start, content, CommentKind::Line, doc_style) . } . rustc_lexer::TokenKind::BlockComment { doc_style, terminated } => { . if !terminated { . let msg = match doc_style { . Some(_) => "unterminated block doc-comment", . None => "unterminated block comment", . }; . let last_bpos = self.pos; -- line 179 ---------------------------------------- -- line 198 ---------------------------------------- . let content_end = self.pos - BytePos(if terminated { 2 } else { 0 }); . let content = self.str_from_to(content_start, content_end); . self.cook_doc_comment(content_start, content, CommentKind::Block, doc_style) . } . rustc_lexer::TokenKind::Whitespace => return None, . rustc_lexer::TokenKind::Ident . | rustc_lexer::TokenKind::RawIdent . | rustc_lexer::TokenKind::UnknownPrefix => { 11,632 ( 0.02%) let is_raw_ident = token == rustc_lexer::TokenKind::RawIdent; 14,540 ( 0.02%) let is_unknown_prefix = token == rustc_lexer::TokenKind::UnknownPrefix; . let mut ident_start = start; 5,816 ( 0.01%) if is_raw_ident { . ident_start = ident_start + BytePos(2); . } 8,724 ( 0.01%) if is_unknown_prefix { . self.report_unknown_prefix(start); . } 14,540 ( 0.02%) let sym = nfc_normalize(self.str_from(ident_start)); . let span = self.mk_sp(start, self.pos); 11,632 ( 0.02%) self.sess.symbol_gallery.insert(sym, span); 5,816 ( 0.01%) if is_raw_ident { . if !sym.can_be_raw() { . self.err_span(span, &format!("`{}` cannot be a raw identifier", sym)); . } . self.sess.raw_identifier_spans.borrow_mut().push(span); . } 20,356 ( 0.03%) token::Ident(sym, is_raw_ident) . } . rustc_lexer::TokenKind::InvalidIdent . // Do not recover an identifier with emoji if the codepoint is a confusable . // with a recoverable substitution token, like `➖`. . if UNICODE_ARRAY . .iter() . .find(|&&(c, _, _)| { . let sym = self.str_from(start); -- line 232 ---------------------------------------- -- line 234 ---------------------------------------- . }) . .is_none() => . { . let sym = nfc_normalize(self.str_from(start)); . let span = self.mk_sp(start, self.pos); . self.sess.bad_unicode_identifiers.borrow_mut().entry(sym).or_default().push(span); . token::Ident(sym, false) . } 2,960 ( 0.00%) rustc_lexer::TokenKind::Literal { kind, suffix_start } => { . let suffix_start = start + BytePos(suffix_start as u32); . let (kind, symbol) = self.cook_lexer_literal(start, suffix_start, kind); 555 ( 0.00%) let suffix = if suffix_start < self.pos { . let string = self.str_from(suffix_start); . if string == "_" { . self.sess . .span_diagnostic . .struct_span_warn( . self.mk_sp(suffix_start, self.pos), . "underscore literal suffix is not allowed", . ) -- line 253 ---------------------------------------- -- line 259 ---------------------------------------- . .note( . "see issue #42326 \ . \ . for more information", . ) . .emit(); . None . } else { 20 ( 0.00%) Some(Symbol::intern(string)) . } . } else { . None . }; 1,480 ( 0.00%) token::Literal(token::Lit { kind, symbol, suffix }) . } . rustc_lexer::TokenKind::Lifetime { starts_with_number } => { . // Include the leading `'` in the real identifier, for macro . // expansion purposes. See #12512 for the gory details of why . // this is necessary. . let lifetime_name = self.str_from(start); . if starts_with_number { . self.err_span_(start, self.pos, "lifetimes cannot start with a number"); -- line 280 ---------------------------------------- -- line 324 ---------------------------------------- . err.help("source files must contain UTF-8 encoded text, unexpected null bytes might occur when a different encoding is used"); . } . err.emit(); . token? . } . }) . } . 5,112 ( 0.01%) fn cook_doc_comment( . &self, . content_start: BytePos, . content: &str, . comment_kind: CommentKind, . doc_style: DocStyle, . ) -> TokenKind { 426 ( 0.00%) if content.contains('\r') { . for (idx, _) in content.char_indices().filter(|&(_, c)| c == '\r') { . self.err_span_( . content_start + BytePos(idx as u32), . content_start + BytePos(idx as u32 + 1), . match comment_kind { . CommentKind::Line => "bare CR not allowed in doc-comment", . CommentKind::Block => "bare CR not allowed in block doc-comment", . }, -- line 347 ---------------------------------------- -- line 349 ---------------------------------------- . } . } . . let attr_style = match doc_style { . DocStyle::Outer => AttrStyle::Outer, . DocStyle::Inner => AttrStyle::Inner, . }; . 1,278 ( 0.00%) token::DocComment(comment_kind, attr_style, Symbol::intern(content)) 6,390 ( 0.01%) } . . fn cook_lexer_literal( . &self, . start: BytePos, . suffix_start: BytePos, . kind: rustc_lexer::LiteralKind, . ) -> (token::LitKind, Symbol) { . // prefix means `"` or `br"` or `r###"`, ... -- line 366 ---------------------------------------- -- line 380 ---------------------------------------- . self.sess.span_diagnostic.span_fatal_with_code( . self.mk_sp(start + BytePos(1), suffix_start), . "unterminated byte constant", . error_code!(E0763), . ) . } . (token::Byte, Mode::Byte, 2, 1) // b' ' . } 91 ( 0.00%) rustc_lexer::LiteralKind::Str { terminated } => { 91 ( 0.00%) if !terminated { . self.sess.span_diagnostic.span_fatal_with_code( . self.mk_sp(start, suffix_start), . "unterminated double quote string", . error_code!(E0765), . ) . } . (token::Str, Mode::Str, 1, 1) // " " . } -- line 397 ---------------------------------------- -- line 403 ---------------------------------------- . error_code!(E0766), . ) . } . (token::ByteStr, Mode::ByteStr, 2, 1) // b" " . } . rustc_lexer::LiteralKind::RawStr { n_hashes, err } => { . self.report_raw_str_error(start, err); . let n = u32::from(n_hashes); 10 ( 0.00%) (token::StrRaw(n_hashes), Mode::RawStr, 2 + n, 1 + n) // r##" "## . } . rustc_lexer::LiteralKind::RawByteStr { n_hashes, err } => { . self.report_raw_str_error(start, err); . let n = u32::from(n_hashes); . (token::ByteStrRaw(n_hashes), Mode::RawByteStr, 3 + n, 1 + n) // br##" "## . } 184 ( 0.00%) rustc_lexer::LiteralKind::Int { base, empty_int } => { 92 ( 0.00%) return if empty_int { . self.sess . .span_diagnostic . .struct_span_err_with_code( . self.mk_sp(start, suffix_start), . "no valid digits found for number", . error_code!(E0768), . ) . .emit(); . (token::Integer, sym::integer(0)) . } else { . self.validate_int_literal(base, start, suffix_start); 276 ( 0.00%) (token::Integer, self.symbol_from_to(start, suffix_start)) . }; . } . rustc_lexer::LiteralKind::Float { base, empty_exponent } => { . if empty_exponent { . self.err_span_(start, self.pos, "expected at least one digit in exponent"); . } . . match base { -- line 439 ---------------------------------------- -- line 452 ---------------------------------------- . } . . let id = self.symbol_from_to(start, suffix_start); . return (token::Float, id); . } . }; . let content_start = start + BytePos(prefix_len); . let content_end = suffix_start - BytePos(postfix_len); 279 ( 0.00%) let id = self.symbol_from_to(content_start, content_end); . self.validate_literal_escape(mode, content_start, content_end, prefix_len, postfix_len); . (lit_kind, id) . } . . #[inline] . fn src_index(&self, pos: BytePos) -> usize { . (pos - self.start_pos).to_usize() . } . . /// Slice of the source text from `start` up to but excluding `self.pos`, . /// meaning the slice does not include the character `self.ch`. . fn str_from(&self, start: BytePos) -> &str { 21,674 ( 0.03%) self.str_from_to(start, self.pos) . } . . /// As symbol_from, with an explicit endpoint. . fn symbol_from_to(&self, start: BytePos, end: BytePos) -> Symbol { . debug!("taking an ident from {:?} to {:?}", start, end); 1,760 ( 0.00%) Symbol::intern(self.str_from_to(start, end)) . } . . /// Slice of the source text spanning from `start` up to but excluding `end`. 3,770 ( 0.01%) fn str_from_to(&self, start: BytePos, end: BytePos) -> &str { . &self.src[self.src_index(start)..self.src_index(end)] 15,080 ( 0.02%) } . . fn report_raw_str_error(&self, start: BytePos, opt_err: Option) { 4 ( 0.00%) match opt_err { . Some(RawStrError::InvalidStarter { bad_char }) => { . self.report_non_started_raw_string(start, bad_char) . } . Some(RawStrError::NoTerminator { expected, found, possible_terminator_offset }) => self . .report_unterminated_raw_string(start, expected, possible_terminator_offset, found), . Some(RawStrError::TooManyDelimiters { found }) => { . self.report_too_many_hashes(start, found) . } -- line 496 ---------------------------------------- -- line 609 ---------------------------------------- . fn validate_literal_escape( . &self, . mode: Mode, . content_start: BytePos, . content_end: BytePos, . prefix_len: u32, . postfix_len: u32, . ) { 558 ( 0.00%) let lit_content = self.str_from_to(content_start, content_end); 10,566 ( 0.01%) unescape::unescape_literal(lit_content, mode, &mut |range, result| { . // Here we only check for errors. The actual unescaping is done later. 2,130 ( 0.00%) if let Err(err) = result { . let span_with_quotes = self . .mk_sp(content_start - BytePos(prefix_len), content_end + BytePos(postfix_len)); . let (start, end) = (range.start as u32, range.end as u32); . let lo = content_start + BytePos(start); . let hi = lo + BytePos(end - start); . let span = self.mk_sp(lo, hi); . emit_unescape_error( . &self.sess.span_diagnostic, -- line 628 ---------------------------------------- -- line 629 ---------------------------------------- . lit_content, . span_with_quotes, . span, . mode, . range, . err, . ); . } 9,585 ( 0.01%) }); . } . . fn validate_int_literal(&self, base: Base, content_start: BytePos, content_end: BytePos) { 266 ( 0.00%) let base = match base { . Base::Binary => 2, . Base::Octal => 8, . _ => return, . }; 312 ( 0.00%) let s = self.str_from_to(content_start + BytePos(2), content_end); 522 ( 0.00%) for (idx, c) in s.char_indices() { . let idx = idx as u32; 1,040 ( 0.00%) if c != '_' && c.to_digit(base).is_none() { . let lo = content_start + BytePos(2 + idx); . let hi = content_start + BytePos(2 + idx + c.len_utf8() as u32); . self.err_span_(lo, hi, &format!("invalid digit for a base {} literal", base)); . } . } . } . } . 26,172 ( 0.04%) pub fn nfc_normalize(string: &str) -> Symbol { . use unicode_normalization::{is_nfc_quick, IsNormalized, UnicodeNormalization}; 5,816 ( 0.01%) match is_nfc_quick(string.chars()) { 29,080 ( 0.04%) IsNormalized::Yes => Symbol::intern(string), . _ => { . let normalized_str: String = string.chars().nfc().collect(); . Symbol::intern(&normalized_str) . } . } . } 43,361 ( 0.06%) -------------------------------------------------------------------------------- -- 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. 258,867 ( 0.35%) #[derive(Debug, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)] . pub enum TokenTree { . /// A single token. 86,904 ( 0.12%) Token(Token), . /// A delimited sequence of token trees. 7,546 ( 0.01%) Delimited(DelimSpan, DelimToken, TokenStream), . } . . #[derive(Copy, Clone)] . pub enum CanSynthesizeMissingTokens { . Yes, . No, . } . -- line 53 ---------------------------------------- -- line 72 ---------------------------------------- . } . _ => false, . } . } . . /// Retrieves the `TokenTree`'s span. . pub fn span(&self) -> Span { . match self { 273 ( 0.00%) TokenTree::Token(token) => token.span, . TokenTree::Delimited(sp, ..) => sp.entire(), . } . } . . /// Modify the `TokenTree`'s span in-place. . pub fn set_span(&mut self, span: Span) { . match self { . TokenTree::Token(token) => token.span = span, . TokenTree::Delimited(dspan, ..) => *dspan = DelimSpan::from_single(span), . } . } . 376 ( 0.00%) pub fn token(kind: TokenKind, span: Span) -> TokenTree { 14,860 ( 0.02%) TokenTree::Token(Token::new(kind, span)) 376 ( 0.00%) } . . /// Returns the opening delimiter as a token tree. 1,670 ( 0.00%) pub fn open_tt(span: DelimSpan, delim: DelimToken) -> TokenTree { 5,010 ( 0.01%) TokenTree::token(token::OpenDelim(delim), span.open) 1,670 ( 0.00%) } . . /// Returns the closing delimiter as a token tree. 1,669 ( 0.00%) pub fn close_tt(span: DelimSpan, delim: DelimToken) -> TokenTree { 5,007 ( 0.01%) TokenTree::token(token::CloseDelim(delim), span.close) 1,669 ( 0.00%) } . 870 ( 0.00%) pub fn uninterpolate(self) -> TokenTree { 580 ( 0.00%) match self { 2,610 ( 0.00%) TokenTree::Token(token) => TokenTree::Token(token.uninterpolate().into_owned()), . tt => tt, . } 1,160 ( 0.00%) } . } . . impl HashStable for TokenStream . where . CTX: crate::HashStableContext, . { 6,633 ( 0.01%) fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) { 52,664 ( 0.07%) for sub_tt in self.trees() { . sub_tt.hash_stable(hcx, hasher); . } 5,896 ( 0.01%) } . } . . 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 140 ---------------------------------------- . pub struct LazyTokenStream(Lrc>); . . impl LazyTokenStream { . pub fn new(inner: impl CreateTokenStream + 'static) -> LazyTokenStream { . LazyTokenStream(Lrc::new(Box::new(inner))) . } . . pub fn create_token_stream(&self) -> AttrAnnotatedTokenStream { 26 ( 0.00%) self.0.create_token_stream() . } . } . . impl fmt::Debug for LazyTokenStream { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . write!(f, "LazyTokenStream({:?})", self.create_token_stream()) . } . } -- line 156 ---------------------------------------- -- line 188 ---------------------------------------- . Delimited(DelimSpan, DelimToken, AttrAnnotatedTokenStream), . /// Stores the attributes for an attribute target, . /// along with the tokens for that attribute target. . /// See `AttributesData` for more information . Attributes(AttributesData), . } . . impl AttrAnnotatedTokenStream { 2,620 ( 0.00%) pub fn new(tokens: Vec<(AttrAnnotatedTokenTree, Spacing)>) -> AttrAnnotatedTokenStream { . AttrAnnotatedTokenStream(Lrc::new(tokens)) 2,620 ( 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. 2 ( 0.00%) pub fn to_tokenstream(&self) -> TokenStream { 8 ( 0.00%) let trees: Vec<_> = self . .0 . .iter() 72 ( 0.00%) .flat_map(|tree| match &tree.0 { 28 ( 0.00%) AttrAnnotatedTokenTree::Token(inner) => { 70 ( 0.00%) smallvec![(TokenTree::Token(inner.clone()), tree.1)].into_iter() . } 120 ( 0.00%) AttrAnnotatedTokenTree::Delimited(span, delim, stream) => smallvec![( 18 ( 0.00%) TokenTree::Delimited(*span, *delim, stream.to_tokenstream()), 6 ( 0.00%) tree.1, . )] . .into_iter(), . AttrAnnotatedTokenTree::Attributes(data) => { . let mut outer_attrs = Vec::new(); . let mut inner_attrs = Vec::new(); . for attr in &data.attrs { . match attr.style { . crate::AttrStyle::Outer => { -- line 223 ---------------------------------------- -- line 279 ---------------------------------------- . flat.extend(attr.tokens().to_tokenstream().0.clone().iter().cloned()); . } . flat.extend(target_tokens); . flat.into_iter() . } . }) . .collect(); . TokenStream::new(trees) 4 ( 0.00%) } . } . . /// Stores the tokens for an attribute target, along . /// with its attributes. . /// . /// This is constructed during parsing when we need to capture . /// tokens. . /// -- line 295 ---------------------------------------- -- line 316 ---------------------------------------- . pub struct TokenStream(pub(crate) Lrc>); . . pub type TreeAndSpacing = (TokenTree, Spacing); . . // `TokenStream` is used a lot. Make sure it doesn't unintentionally get bigger. . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . rustc_data_structures::static_assert_size!(TokenStream, 8); . 15,936 ( 0.02%) #[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 { 120 ( 0.00%) TokenStream::new(vec![(tree, Spacing::Alone)]) . } . } . . impl From for TreeAndSpacing { . fn from(tree: TokenTree) -> TreeAndSpacing { 4,917 ( 0.01%) (tree, Spacing::Alone) . } . } . . impl iter::FromIterator for TokenStream { . fn from_iter>(iter: I) -> Self { 188 ( 0.00%) TokenStream::new(iter.into_iter().map(Into::into).collect::>()) . } . } . . impl Eq for TokenStream {} . . impl PartialEq for TokenStream { . fn eq(&self, other: &TokenStream) -> bool { . self.trees().eq(other.trees()) -- line 399 ---------------------------------------- -- line 401 ---------------------------------------- . } . . impl TokenStream { . pub fn new(streams: Vec) -> TokenStream { . TokenStream(Lrc::new(streams)) . } . . pub fn is_empty(&self) -> bool { 1,110 ( 0.00%) self.0.is_empty() 1,110 ( 0.00%) } . . pub fn len(&self) -> usize { 31,652 ( 0.04%) self.0.len() . } . . 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 -- line 421 ---------------------------------------- -- line 448 ---------------------------------------- . . // Create the final `TokenStream`. . TokenStream(first_stream_lrc) . } . } . } . . pub fn trees(&self) -> Cursor { 1,500 ( 0.00%) self.clone().into_trees() 3,000 ( 0.00%) } . 2,527 ( 0.00%) pub fn into_trees(self) -> Cursor { . Cursor::new(self) 5,054 ( 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; -- line 469 ---------------------------------------- -- line 572 ---------------------------------------- . pub struct Cursor { . pub stream: TokenStream, . index: usize, . } . . impl Iterator for Cursor { . type Item = TokenTree; . 49,875 ( 0.07%) fn next(&mut self) -> Option { 92,752 ( 0.13%) self.next_with_spacing().map(|(tree, _)| tree) 66,500 ( 0.09%) } . } . . impl Cursor { . fn new(stream: TokenStream) -> Self { . Cursor { stream, index: 0 } . } . 75,135 ( 0.10%) pub fn next_with_spacing(&mut self) -> Option { 94,956 ( 0.13%) if self.index < self.stream.len() { 50,762 ( 0.07%) self.index += 1; 77,658 ( 0.11%) Some(self.stream.0[self.index - 1].clone()) . } else { 7,866 ( 0.01%) None . } 90,162 ( 0.12%) } . . 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; . } . 1,649 ( 0.00%) pub fn look_ahead(&self, n: usize) -> Option<&TokenTree> { 3,298 ( 0.00%) self.stream.0[self.index..].get(n).map(|(tree, _)| tree) 3,298 ( 0.00%) } . } . 17,262 ( 0.02%) #[derive(Debug, Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)] . pub struct DelimSpan { . pub open: Span, . pub close: Span, . } . . impl DelimSpan { 96 ( 0.00%) pub fn from_single(sp: Span) -> Self { . DelimSpan { open: sp, close: sp } 192 ( 0.00%) } . 2,228 ( 0.00%) pub fn from_pair(open: Span, close: Span) -> Self { . DelimSpan { open, close } 1,114 ( 0.00%) } . . pub fn dummy() -> Self { . Self::from_single(DUMMY_SP) 75 ( 0.00%) } . 920 ( 0.00%) pub fn entire(self) -> Span { . self.open.with_hi(self.close.hi()) 690 ( 0.00%) } . } 13,949 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/rustc-hash-1.1.0/src/lib.rs -------------------------------------------------------------------------------- Ir -- line 71 ---------------------------------------- . fn default() -> FxHasher { . FxHasher { hash: 0 } . } . } . . impl FxHasher { . #[inline] . fn add_to_hash(&mut self, i: usize) { 10,273 ( 0.01%) self.hash = self.hash.rotate_left(5).bitxor(i).wrapping_mul(K); . } . } . . impl Hasher for FxHasher { . #[inline] 504 ( 0.00%) fn write(&mut self, mut bytes: &[u8]) { . #[cfg(target_pointer_width = "32")] . let read_usize = |bytes: &[u8]| u32::from_ne_bytes(bytes[..4].try_into().unwrap()); . #[cfg(target_pointer_width = "64")] . let read_usize = |bytes: &[u8]| u64::from_ne_bytes(bytes[..8].try_into().unwrap()); . 10,360 ( 0.01%) let mut hash = FxHasher { hash: self.hash }; . assert!(size_of::() <= 8); 116,816 ( 0.16%) while bytes.len() >= size_of::() { . hash.add_to_hash(read_usize(bytes) as usize); . bytes = &bytes[size_of::()..]; . } 20,566 ( 0.03%) if (size_of::() > 4) && (bytes.len() >= 4) { . hash.add_to_hash(u32::from_ne_bytes(bytes[..4].try_into().unwrap()) as usize); . bytes = &bytes[4..]; . } 20,566 ( 0.03%) if (size_of::() > 2) && bytes.len() >= 2 { . hash.add_to_hash(u16::from_ne_bytes(bytes[..2].try_into().unwrap()) as usize); . bytes = &bytes[2..]; . } 22,855 ( 0.03%) if (size_of::() > 1) && bytes.len() >= 1 { 5,627 ( 0.01%) hash.add_to_hash(bytes[0] as usize); . } 582 ( 0.00%) self.hash = hash.hash; 504 ( 0.00%) } . . #[inline] . fn write_u8(&mut self, i: u8) { . self.add_to_hash(i as usize); . } . . #[inline] . fn write_u16(&mut self, i: u16) { 36 ( 0.00%) self.add_to_hash(i as usize); . } . . #[inline] . fn write_u32(&mut self, i: u32) { 21,313 ( 0.03%) self.add_to_hash(i as usize); . } . . #[cfg(target_pointer_width = "32")] . #[inline] . fn write_u64(&mut self, i: u64) { . self.add_to_hash(i as usize); . self.add_to_hash((i >> 32) as usize); . } -- line 131 ---------------------------------------- 1 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/md-5-0.9.1/src/utils.rs -------------------------------------------------------------------------------- Ir . #![allow(clippy::many_single_char_names)] . use crate::consts::RC; . use core::convert::TryInto; . . #[inline(always)] . fn op_f(w: u32, x: u32, y: u32, z: u32, m: u32, c: u32, s: u32) -> u32 { 93,625 ( 0.13%) ((x & y) | (!x & z)) . .wrapping_add(w) . .wrapping_add(m) . .wrapping_add(c) . .rotate_left(s) . .wrapping_add(x) . } . #[inline(always)] . fn op_g(w: u32, x: u32, y: u32, z: u32, m: u32, c: u32, s: u32) -> u32 { 89,250 ( 0.12%) ((x & z) | (y & !z)) . .wrapping_add(w) . .wrapping_add(m) . .wrapping_add(c) . .rotate_left(s) . .wrapping_add(x) . } . . #[inline(always)] . fn op_h(w: u32, x: u32, y: u32, z: u32, m: u32, c: u32, s: u32) -> u32 { 43,750 ( 0.06%) (x ^ y ^ z) . .wrapping_add(w) . .wrapping_add(m) . .wrapping_add(c) . .rotate_left(s) . .wrapping_add(x) . } . . #[inline(always)] . fn op_i(w: u32, x: u32, y: u32, z: u32, m: u32, c: u32, s: u32) -> u32 { 56,000 ( 0.08%) (y ^ (x | !z)) . .wrapping_add(w) . .wrapping_add(m) . .wrapping_add(c) . .rotate_left(s) . .wrapping_add(x) . } . . #[inline] 7,875 ( 0.01%) pub fn compress(state: &mut [u32; 4], input: &[u8; 64]) { 1,750 ( 0.00%) let mut a = state[0]; 875 ( 0.00%) let mut b = state[1]; 875 ( 0.00%) let mut c = state[2]; 875 ( 0.00%) let mut d = state[3]; . . let mut data = [0u32; 16]; . for (o, chunk) in data.iter_mut().zip(input.chunks_exact(4)) { 21,875 ( 0.03%) *o = u32::from_le_bytes(chunk.try_into().unwrap()); . } . . // round 1 . a = op_f(a, b, c, d, data[0], RC[0], 7); . d = op_f(d, a, b, c, data[1], RC[1], 12); . c = op_f(c, d, a, b, data[2], RC[2], 17); . b = op_f(b, c, d, a, data[3], RC[3], 22); . -- line 61 ---------------------------------------- -- line 132 ---------------------------------------- . c = op_i(c, d, a, b, data[6], RC[58], 15); . b = op_i(b, c, d, a, data[13], RC[59], 21); . . a = op_i(a, b, c, d, data[4], RC[60], 6); . d = op_i(d, a, b, c, data[11], RC[61], 10); . c = op_i(c, d, a, b, data[2], RC[62], 15); . b = op_i(b, c, d, a, data[9], RC[63], 21); . 1,750 ( 0.00%) state[0] = state[0].wrapping_add(a); 875 ( 0.00%) state[1] = state[1].wrapping_add(b); 875 ( 0.00%) state[2] = state[2].wrapping_add(c); 875 ( 0.00%) state[3] = state[3].wrapping_add(d); 7,000 ( 0.01%) } -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs -------------------------------------------------------------------------------- Ir -- line 364 ---------------------------------------- . #[stable(feature = "rust1", since = "1.0.0")] . 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( 26,990 ( 0.04%) Box::leak(box RcBox { strong: Cell::new(1), weak: Cell::new(1), value }).into(), . ) . } . } . . /// 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 -- line 380 ---------------------------------------- -- 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 { 84 ( 0.00%) this.inner().weak() - 1 . } . . /// Gets the number of strong (`Rc`) pointers to this allocation. . /// . /// # Examples . /// . /// ``` . /// use std::rc::Rc; -- line 947 ---------------------------------------- -- 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`). 791 ( 0.00%) 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 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")] 280 ( 0.00%) pub fn make_mut(this: &mut Self) -> &mut T { 168 ( 0.00%) if Rc::strong_count(this) != 1 { . // Gotta clone the data, there are other Rcs. . // Pre-allocate memory to allow writing the cloned value directly. 28 ( 0.00%) let mut rc = Self::new_uninit(); . unsafe { . let data = Rc::get_mut_unchecked(&mut rc); . (**this).write_clone_into_raw(data.as_mut_ptr()); 56 ( 0.00%) *this = rc.assume_init(); . } 56 ( 0.00%) } 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. 56 ( 0.00%) unsafe { &mut this.ptr.as_mut().value } 336 ( 0.00%) } . } . . 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))] 30 ( 0.00%) unsafe fn copy_from_slice(v: &[T]) -> Rc<[T]> { . unsafe { . let ptr = Self::allocate_for_slice(v.len()); 5 ( 0.00%) ptr::copy_nonoverlapping(v.as_ptr(), &mut (*ptr).value as *mut [T] as *mut T, v.len()); . Self::from_ptr(ptr) . } 40 ( 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 { 21,431 ( 0.03%) &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!" . /// ``` 73,882 ( 0.10%) fn drop(&mut self) { . unsafe { 16,238 ( 0.02%) self.inner().dec_strong(); 32,607 ( 0.04%) if self.inner().strong() == 0 { . // destroy the contained object 350 ( 0.00%) 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(); . 4,508 ( 0.01%) if self.inner().weak() == 0 { 6 ( 0.00%) Global.deallocate(self.ptr.cast(), Layout::for_value(self.ptr.as_ref())); . } . } . } 76,412 ( 0.10%) } . } . . #[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 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 { 2 ( 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; 43 ( 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) { 13,711 ( 0.02%) 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. 41,213 ( 0.06%) if strong == 0 || strong == usize::MAX { . abort(); . } 20 ( 0.00%) self.strong_ref().set(strong + 1); . } . . #[inline] . fn dec_strong(&self) { 49,141 ( 0.07%) 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) { 6,765 ( 0.01%) self.weak_ref().set(self.weak() - 1); . } . } . . impl RcInnerPtr for RcBox { . #[inline(always)] . fn weak_ref(&self) -> &Cell { . &self.weak . } -- line 2523 ---------------------------------------- 1,793 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/source_map.rs -------------------------------------------------------------------------------- Ir -- line 72 ---------------------------------------- . fn deref(&self) -> &Self::Target { . &self.0 . } . } . . impl !DerefMut for MonotonicVec {} . } . 98 ( 0.00%) #[derive(Clone, Encodable, Decodable, Debug, Copy, HashStable_Generic)] . pub struct Spanned { . pub node: T, . pub span: Span, . } . . pub fn respan(sp: Span, t: T) -> Spanned { 49 ( 0.00%) Spanned { node: t, span: sp } . } . . pub fn dummy_spanned(t: T) -> Spanned { . respan(DUMMY_SP, t) . } . . // _____________________________________________________________________________ . // SourceFile, MultiByteChar, FileName, FileLines -- line 95 ---------------------------------------- -- line 107 ---------------------------------------- . /// A FileLoader that uses std::fs to load real files. . pub struct RealFileLoader; . . impl FileLoader for RealFileLoader { . fn file_exists(&self, path: &Path) -> bool { . path.exists() . } . 2 ( 0.00%) fn read_file(&self, path: &Path) -> io::Result { . fs::read_to_string(path) 3 ( 0.00%) } . } . . /// This is a [SourceFile] identifier that is used to correlate source files between . /// subsequent compilation sessions (which is something we need to do during . /// incremental compilation). . /// . /// The [StableSourceFileId] also contains the CrateNum of the crate the source . /// file was originally parsed for. This way we get two separate entries in -- line 125 ---------------------------------------- -- line 128 ---------------------------------------- . /// at the point where we discover that there's a local use of the file in . /// addition to the upstream one, we might already have made decisions based on . /// the assumption that it's an upstream file. Treating the two files as . /// different has no real downsides. . #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)] . pub struct StableSourceFileId { . // A hash of the source file's FileName. This is hash so that it's size . // is more predictable than if we included the actual FileName value. 31 ( 0.00%) pub file_name_hash: u64, . . // The CrateNum of the crate this source file was originally parsed for. . // We cannot include this information in the hash because at the time . // of hashing we don't have the context to map from the CrateNum's numeric . // value to a StableCrateId. . pub cnum: CrateNum, . } . . // FIXME: we need a more globally consistent approach to the problem solved by . // StableSourceFileId, perhaps built atop source_file.name_hash. . impl StableSourceFileId { . pub fn new(source_file: &SourceFile) -> StableSourceFileId { 626 ( 0.00%) StableSourceFileId::new_from_name(&source_file.name, source_file.cnum) . } . 1,575 ( 0.00%) fn new_from_name(name: &FileName, cnum: CrateNum) -> StableSourceFileId { . let mut hasher = StableHasher::new(); 315 ( 0.00%) name.hash(&mut hasher); . StableSourceFileId { file_name_hash: hasher.finish(), cnum } 1,890 ( 0.00%) } . } . . // _____________________________________________________________________________ . // SourceMap . // . . #[derive(Default)] . pub(super) struct SourceMapFiles { -- line 164 ---------------------------------------- -- line 176 ---------------------------------------- . // `--remap-path-prefix` to all `SourceFile`s allocated within this `SourceMap`. . path_mapping: FilePathMapping, . . /// The algorithm used for hashing the contents of each source file. . hash_kind: SourceFileHashAlgorithm, . } . . impl SourceMap { 1 ( 0.00%) pub fn new(path_mapping: FilePathMapping) -> SourceMap { . Self::with_file_loader_and_hash_kind( . Box::new(RealFileLoader), 4 ( 0.00%) path_mapping, . SourceFileHashAlgorithm::Md5, . ) 1 ( 0.00%) } . 1 ( 0.00%) pub fn with_file_loader_and_hash_kind( . file_loader: Box, . path_mapping: FilePathMapping, . hash_kind: SourceFileHashAlgorithm, . ) -> SourceMap { 11 ( 0.00%) SourceMap { . used_address_space: AtomicU32::new(0), . files: Default::default(), . file_loader, 4 ( 0.00%) path_mapping, . hash_kind, . } 1 ( 0.00%) } . . pub fn path_mapping(&self) -> &FilePathMapping { 5 ( 0.00%) &self.path_mapping 5 ( 0.00%) } . . pub fn file_exists(&self, path: &Path) -> bool { . self.file_loader.file_exists(path) . } . 11 ( 0.00%) pub fn load_file(&self, path: &Path) -> io::Result> { 4 ( 0.00%) let src = self.file_loader.read_file(path)?; . let filename = path.to_owned().into(); 18 ( 0.00%) Ok(self.new_source_file(filename, src)) 9 ( 0.00%) } . . /// Loads source file as a binary blob. . /// . /// Unlike `load_file`, guarantees that no normalization like BOM-removal . /// takes place. . pub fn load_binary_file(&self, path: &Path) -> io::Result> { . // Ideally, this should use `self.file_loader`, but it can't . // deal with binary files yet. -- line 226 ---------------------------------------- -- line 233 ---------------------------------------- . // empty string. . let text = std::str::from_utf8(&bytes).unwrap_or("").to_string(); . self.new_source_file(path.to_owned().into(), text); . Ok(bytes) . } . . // By returning a `MonotonicVec`, we ensure that consumers cannot invalidate . // any existing indices pointing into `files`. 4 ( 0.00%) pub fn files(&self) -> MappedReadGuard<'_, monotonic::MonotonicVec>> { . ReadGuard::map(self.files.borrow(), |files| &files.source_files) 12 ( 0.00%) } . 8 ( 0.00%) pub fn source_file_by_stable_id( . &self, . stable_id: StableSourceFileId, . ) -> Option> { . self.files.borrow().stable_id_to_source_file.get(&stable_id).cloned() 10 ( 0.00%) } . . fn allocate_address_space(&self, size: usize) -> Result { 315 ( 0.00%) let size = u32::try_from(size).map_err(|_| OffsetOverflowError)?; . . loop { 315 ( 0.00%) let current = self.used_address_space.load(Ordering::Relaxed); 945 ( 0.00%) let next = current . .checked_add(size) . // Add one so there is some space between files. This lets us distinguish . // positions in the `SourceMap`, even in the presence of zero-length files. . .and_then(|next| next.checked_add(1)) . .ok_or(OffsetOverflowError)?; . . if self . .used_address_space -- line 265 ---------------------------------------- -- line 269 ---------------------------------------- . return Ok(usize::try_from(current).unwrap()); . } . } . } . . /// Creates a new `SourceFile`. . /// If a file already exists in the `SourceMap` with the same ID, that file is returned . /// unmodified. 16 ( 0.00%) pub fn new_source_file(&self, filename: FileName, src: String) -> Lrc { 24 ( 0.00%) self.try_new_source_file(filename, src).unwrap_or_else(|OffsetOverflowError| { . eprintln!("fatal error: rustc does not support files larger than 4GB"); . crate::fatal_error::FatalError.raise() . }) 18 ( 0.00%) } . . fn try_new_source_file( . &self, . filename: FileName, . src: String, . ) -> Result, OffsetOverflowError> { . // Note that filename may not be a valid path, eg it may be `` etc, . // but this is okay because the directory determined by `path.pop()` will . // be empty, so the working directory will be used. 26 ( 0.00%) let (filename, _) = self.path_mapping.map_filename_prefix(&filename); . 4 ( 0.00%) let file_id = StableSourceFileId::new_from_name(&filename, LOCAL_CRATE); . 12 ( 0.00%) let lrc_sf = match self.source_file_by_stable_id(file_id) { . Some(lrc_sf) => lrc_sf, . None => { . let start_pos = self.allocate_address_space(src.len())?; . 12 ( 0.00%) let source_file = Lrc::new(SourceFile::new( 18 ( 0.00%) filename, 6 ( 0.00%) src, . Pos::from_usize(start_pos), . self.hash_kind, . )); . . // Let's make sure the file_id we generated above actually matches . // the ID we generate for the SourceFile we just created. . debug_assert_eq!(StableSourceFileId::new(&source_file), file_id); . -- line 311 ---------------------------------------- -- line 319 ---------------------------------------- . }; . Ok(lrc_sf) . } . . /// Allocates a new `SourceFile` representing a source file from an external . /// crate. The source code of such an "imported `SourceFile`" is not available, . /// but we still know enough to generate accurate debuginfo location . /// information for things inlined from other crates. 2,504 ( 0.00%) pub fn new_imported_source_file( . &self, . filename: FileName, . src_hash: SourceFileHash, . name_hash: u128, . source_len: usize, . cnum: CrateNum, . mut file_local_lines: Vec, . mut file_local_multibyte_chars: Vec, -- line 335 ---------------------------------------- -- line 341 ---------------------------------------- . let start_pos = self . .allocate_address_space(source_len) . .expect("not enough address space for imported source file"); . . let end_pos = Pos::from_usize(start_pos + source_len); . let start_pos = Pos::from_usize(start_pos); . . for pos in &mut file_local_lines { 238,468 ( 0.33%) *pos = *pos + start_pos; . } . . for mbc in &mut file_local_multibyte_chars { 568 ( 0.00%) mbc.pos = mbc.pos + start_pos; . } . . for swc in &mut file_local_non_narrow_chars { 536 ( 0.00%) *swc = *swc + start_pos; . } . . for nc in &mut file_local_normalized_pos { . nc.pos = nc.pos + start_pos; . } . 939 ( 0.00%) let source_file = Lrc::new(SourceFile { 2,504 ( 0.00%) name: filename, . src: None, . src_hash, . external_src: Lock::new(ExternalSource::Foreign { . kind: ExternalSourceKind::AbsentOk, . original_start_pos, . original_end_pos, . }), . start_pos, -- line 373 ---------------------------------------- -- line 383 ---------------------------------------- . let mut files = self.files.borrow_mut(); . . files.source_files.push(source_file.clone()); . files . .stable_id_to_source_file . .insert(StableSourceFileId::new(&source_file), source_file.clone()); . . source_file 2,817 ( 0.00%) } . . // If there is a doctest offset, applies it to the line. . pub fn doctest_offset_line(&self, file: &FileName, orig: usize) -> usize { . match file { . FileName::DocTest(_, offset) => { . if *offset < 0 { . orig - (-(*offset)) as usize . } else { -- line 399 ---------------------------------------- -- line 400 ---------------------------------------- . orig + *offset as usize . } . } . _ => orig, . } . } . . /// Return the SourceFile that contains the given `BytePos` 3 ( 0.00%) pub fn lookup_source_file(&self, pos: BytePos) -> Lrc { 1 ( 0.00%) let idx = self.lookup_source_file_idx(pos); 1 ( 0.00%) (*self.files.borrow().source_files)[idx].clone() 3 ( 0.00%) } . . /// Looks up source information about a `BytePos`. . pub fn lookup_char_pos(&self, pos: BytePos) -> Loc { 5 ( 0.00%) let sf = self.lookup_source_file(pos); 6 ( 0.00%) let (line, col, col_display) = sf.lookup_file_pos_with_col_display(pos); 3 ( 0.00%) Loc { file: sf, line, col, col_display } . } . . // If the corresponding `SourceFile` is empty, does not return a line number. . pub fn lookup_line(&self, pos: BytePos) -> Result> { . let f = self.lookup_source_file(pos); . . match f.lookup_line(pos) { . Some(line) => Ok(SourceFileAndLine { sf: f, line }), -- line 425 ---------------------------------------- -- line 451 ---------------------------------------- . . /// Format the span location to be printed in diagnostics. Must not be emitted . /// to build artifacts as this may leak local file paths. Use span_to_embeddable_string . /// for string suitable for embedding. . pub fn span_to_diagnostic_string(&self, sp: Span) -> String { . self.span_to_string(sp, self.path_mapping.filename_display_for_diagnostics) . } . 11 ( 0.00%) pub fn span_to_filename(&self, sp: Span) -> FileName { 3 ( 0.00%) self.lookup_char_pos(sp.lo()).file.name.clone() 8 ( 0.00%) } . . pub fn filename_for_diagnostics<'a>(&self, filename: &'a FileName) -> FileNameDisplay<'a> { . filename.display(self.path_mapping.filename_display_for_diagnostics) . } . 2,002 ( 0.00%) pub fn is_multiline(&self, sp: Span) -> bool { 728 ( 0.00%) let lo = self.lookup_source_file_idx(sp.lo()); 728 ( 0.00%) let hi = self.lookup_source_file_idx(sp.hi()); 364 ( 0.00%) if lo != hi { . return true; . } 364 ( 0.00%) let f = (*self.files.borrow().source_files)[lo].clone(); . f.lookup_line(sp.lo()) != f.lookup_line(sp.hi()) 1,638 ( 0.00%) } . . #[instrument(skip(self), level = "trace")] . pub fn is_valid_span(&self, sp: Span) -> Result<(Loc, Loc), SpanLinesError> { . let lo = self.lookup_char_pos(sp.lo()); . trace!(?lo); . let hi = self.lookup_char_pos(sp.hi()); . trace!(?hi); . if lo.file.start_pos != hi.file.start_pos { -- line 483 ---------------------------------------- -- line 909 ---------------------------------------- . let sf = (*self.files.borrow().source_files)[idx].clone(); . let offset = bpos - sf.start_pos; . SourceFileAndBytePos { sf, pos: offset } . } . . // Returns the index of the `SourceFile` (in `self.files`) that contains `pos`. . // This index is guaranteed to be valid for the lifetime of this `SourceMap`, . // since `source_files` is a `MonotonicVec` 1,095 ( 0.00%) pub fn lookup_source_file_idx(&self, pos: BytePos) -> usize { . self.files . .borrow() . .source_files . .binary_search_by_key(&pos, |key| key.start_pos) 730 ( 0.00%) .unwrap_or_else(|p| p - 1) 1,460 ( 0.00%) } . . pub fn count_lines(&self) -> usize { . self.files().iter().fold(0, |a, f| a + f.count_lines()) . } . . pub fn generate_fn_name_span(&self, span: Span) -> Option { . let prev_span = self.span_extend_to_prev_str(span, "fn", true); . if let Ok(snippet) = self.span_to_snippet(prev_span) { -- line 931 ---------------------------------------- -- line 1053 ---------------------------------------- . let span = span.shrink_to_hi().with_hi(BytePos(span.hi().0.checked_add(1)?)); . if self.span_to_snippet(span).as_deref() != Ok(";") { . return None; . } . Some(span) . } . } . 16 ( 0.00%) #[derive(Clone)] . pub struct FilePathMapping { 8 ( 0.00%) mapping: Vec<(PathBuf, PathBuf)>, 4 ( 0.00%) filename_display_for_diagnostics: FileNameDisplayPreference, . } . . impl FilePathMapping { 1 ( 0.00%) pub fn empty() -> FilePathMapping { . FilePathMapping::new(Vec::new()) 1 ( 0.00%) } . 3 ( 0.00%) pub fn new(mapping: Vec<(PathBuf, PathBuf)>) -> FilePathMapping { . let filename_display_for_diagnostics = if mapping.is_empty() { . FileNameDisplayPreference::Local . } else { . FileNameDisplayPreference::Remapped . }; . 16 ( 0.00%) FilePathMapping { mapping, filename_display_for_diagnostics } 3 ( 0.00%) } . . /// Applies any path prefix substitution as defined by the mapping. . /// The return value is the remapped path and a boolean indicating whether . /// the path was affected by the mapping. 72 ( 0.00%) pub fn map_prefix(&self, path: PathBuf) -> (PathBuf, bool) { . // NOTE: We are iterating over the mapping entries from last to first . // because entries specified later on the command line should . // take precedence. . for &(ref from, ref to) in self.mapping.iter().rev() { . if let Ok(rest) = path.strip_prefix(from) { . return (to.join(rest), true); . } . } . 40 ( 0.00%) (path, false) 72 ( 0.00%) } . 16 ( 0.00%) fn map_filename_prefix(&self, file: &FileName) -> (FileName, bool) { 4 ( 0.00%) match file { 2 ( 0.00%) FileName::Real(realfile) if let RealFileName::LocalPath(local_path) = realfile => { 14 ( 0.00%) let (mapped_path, mapped) = self.map_prefix(local_path.to_path_buf()); 1 ( 0.00%) let realfile = if mapped { . RealFileName::Remapped { . local_path: Some(local_path.clone()), . virtual_name: mapped_path, . } . } else { . realfile.clone() . }; 10 ( 0.00%) (FileName::Real(realfile), mapped) 4 ( 0.00%) } . FileName::Real(_) => unreachable!("attempted to remap an already remapped filename"), 11 ( 0.00%) other => (other.clone(), false), . } 8 ( 0.00%) } . } 2,594 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/str/traits.rs -------------------------------------------------------------------------------- Ir -- line 159 ---------------------------------------- . /// // byte 100 is outside the string . /// // &s[3 .. 100]; . /// ``` . #[stable(feature = "str_checked_slicing", since = "1.20.0")] . unsafe impl SliceIndex for ops::Range { . type Output = str; . #[inline] . fn get(self, slice: &str) -> Option<&Self::Output> { 100,598 ( 0.14%) if self.start <= self.end . && slice.is_char_boundary(self.start) . && slice.is_char_boundary(self.end) . { . // SAFETY: just checked that `start` and `end` are on a char boundary, . // and we are passing in a safe reference, so the return value will also be one. . // We also checked char boundaries, so this is valid UTF-8. . Some(unsafe { &*self.get_unchecked(slice) }) . } else { -- line 175 ---------------------------------------- -- line 190 ---------------------------------------- . } . } . #[inline] . unsafe fn get_unchecked(self, slice: *const str) -> *const Self::Output { . let slice = slice as *const [u8]; . // SAFETY: the caller guarantees that `self` is in bounds of `slice` . // which satisfies all the conditions for `add`. . let ptr = unsafe { slice.as_ptr().add(self.start) }; 50,698 ( 0.07%) let len = self.end - self.start; . ptr::slice_from_raw_parts(ptr, len) as *const str . } . #[inline] . unsafe fn get_unchecked_mut(self, slice: *mut str) -> *mut Self::Output { . let slice = slice as *mut [u8]; . // SAFETY: see comments for `get_unchecked`. . let ptr = unsafe { slice.as_mut_ptr().add(self.start) }; . let len = self.end - self.start; -- line 206 ---------------------------------------- -- line 316 ---------------------------------------- . /// . /// Panics if `begin` does not point to the starting byte offset of . /// a character (as defined by `is_char_boundary`), or if `begin > len`. . #[stable(feature = "str_checked_slicing", since = "1.20.0")] . unsafe impl SliceIndex for ops::RangeFrom { . type Output = str; . #[inline] . fn get(self, slice: &str) -> Option<&Self::Output> { 28 ( 0.00%) if slice.is_char_boundary(self.start) { . // SAFETY: just checked that `start` is on a char boundary, . // and we are passing in a safe reference, so the return value will also be one. . Some(unsafe { &*self.get_unchecked(slice) }) . } else { . None . } . } . #[inline] -- line 332 ---------------------------------------- -- line 340 ---------------------------------------- . } . } . #[inline] . unsafe fn get_unchecked(self, slice: *const str) -> *const Self::Output { . let slice = slice as *const [u8]; . // SAFETY: the caller guarantees that `self` is in bounds of `slice` . // which satisfies all the conditions for `add`. . let ptr = unsafe { slice.as_ptr().add(self.start) }; 84 ( 0.00%) let len = slice.len() - self.start; . ptr::slice_from_raw_parts(ptr, len) as *const str . } . #[inline] . unsafe fn get_unchecked_mut(self, slice: *mut str) -> *mut Self::Output { . let slice = slice as *mut [u8]; . // SAFETY: identical to `get_unchecked`. . let ptr = unsafe { slice.as_mut_ptr().add(self.start) }; . let len = slice.len() - self.start; -- line 356 ---------------------------------------- 9,098 ( 0.01%) -------------------------------------------------------------------------------- -- 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 { 105 ( 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 { 69,836 ( 0.10%) write_leb128!(self, v, usize, write_usize_leb128) . } . . #[inline] . fn emit_u128(&mut self, v: u128) -> EncodeResult { 7 ( 0.00%) write_leb128!(self, v, u128, write_u128_leb128) . } . . #[inline] . fn emit_u64(&mut self, v: u64) -> EncodeResult { 35 ( 0.00%) write_leb128!(self, v, u64, write_u64_leb128) . } . . #[inline] . fn emit_u32(&mut self, v: u32) -> EncodeResult { 60,549 ( 0.08%) 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 { 976 ( 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; 3 ( 0.00%) self.position += bytes; 3 ( 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 { 313 ( 0.00%) read_leb128!(self, read_u128_leb128) . } . . #[inline] . fn read_u64(&mut self) -> u64 { 26 ( 0.00%) read_leb128!(self, read_u64_leb128) . } . . #[inline] 1,409 ( 0.00%) fn read_u32(&mut self) -> u32 { 5,587 ( 0.01%) read_leb128!(self, read_u32_leb128) 2,818 ( 0.00%) } . . #[inline] . fn read_u16(&mut self) -> u16 { 561,386 ( 0.77%) let bytes = [self.data[self.position], self.data[self.position + 1]]; 80,198 ( 0.11%) let value = u16::from_le_bytes(bytes); 160,396 ( 0.22%) self.position += 2; . value . } . . #[inline] . fn read_u8(&mut self) -> u8 { 988,141 ( 1.35%) let value = self.data[self.position]; 181,185 ( 0.25%) self.position += 1; . value . } . . #[inline] 5,866 ( 0.01%) fn read_usize(&mut self) -> usize { 5,866 ( 0.01%) read_leb128!(self, read_usize_leb128) 11,732 ( 0.02%) } . . #[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(); 111 ( 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> { 967 ( 0.00%) let len = self.read_usize(); 5,048 ( 0.01%) let sentinel = self.data[self.position + len]; 1,262 ( 0.00%) assert!(sentinel == STR_SENTINEL); . let s = unsafe { . std::str::from_utf8_unchecked(&self.data[self.position..self.position + len]) . }; 3,155 ( 0.00%) self.position += len + 1; 1,008 ( 0.00%) Cow::Borrowed(s) . } . . #[inline] . fn read_raw_bytes_into(&mut self, s: &mut [u8]) { 3 ( 0.00%) let start = self.position; 24 ( 0.00%) self.position += s.len(); 3 ( 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 ---------------------------------------- 125,082 ( 0.17%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/std/src/path.rs -------------------------------------------------------------------------------- Ir -- line 316 ---------------------------------------- . . //////////////////////////////////////////////////////////////////////////////// . // Cross-platform, iterator-independent parsing . //////////////////////////////////////////////////////////////////////////////// . . /// Says whether the first byte after the prefix is a separator. . fn has_physical_root(s: &[u8], prefix: Option>) -> bool { . let path = if let Some(p) = prefix { &s[p.len()..] } else { s }; 111 ( 0.00%) !path.is_empty() && is_sep_byte(path[0]) . } . . // basic workhorse for splitting stem and extension . fn rsplit_file_at_dot(file: &OsStr) -> (Option<&OsStr>, Option<&OsStr>) { . if os_str_as_u8_slice(file) == b".." { . return (Some(file), None); . } . . // The unsafety here stems from converting between &OsStr and &[u8] . // and back. This is safe to do because (1) we only look at ASCII . // contents of the encoding and (2) new &OsStr values are produced . // only from ASCII-bounded slices of existing &OsStr values. 300 ( 0.00%) let mut iter = os_str_as_u8_slice(file).rsplitn(2, |b| *b == b'.'); . let after = iter.next(); . let before = iter.next(); . if before == Some(b"") { . (Some(file), None) . } else { . unsafe { (before.map(|s| u8_slice_as_os_str(s)), after.map(|s| u8_slice_as_os_str(s))) } . } . } -- line 345 ---------------------------------------- -- line 368 ---------------------------------------- . //////////////////////////////////////////////////////////////////////////////// . . /// Component parsing works by a double-ended state machine; the cursors at the . /// front and back of the path each keep track of what parts of the path have . /// been consumed so far. . /// . /// Going front to back, a path is made up of a prefix, a starting . /// directory component, and a body (of normal components) 125 ( 0.00%) #[derive(Copy, Clone, PartialEq, PartialOrd, Debug)] . enum State { . Prefix = 0, // c: . StartDir = 1, // / or . or nothing . Body = 2, // foo/bar/baz . Done = 3, . } . . /// A structure wrapping a Windows path prefix as well as its unparsed string -- line 384 ---------------------------------------- -- line 493 ---------------------------------------- . /// let components = path.components().collect::>(); . /// assert_eq!(&components, &[ . /// Component::RootDir, . /// Component::Normal("tmp".as_ref()), . /// Component::Normal("foo".as_ref()), . /// Component::Normal("bar.txt".as_ref()), . /// ]); . /// ``` 2 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] . #[stable(feature = "rust1", since = "1.0.0")] . pub enum Component<'a> { . /// A Windows path prefix, e.g., `C:` or `\\server\share`. . /// . /// There is a large variety of prefix types, see [`Prefix`]'s documentation . /// for more. . /// . /// Does not occur on Unix. -- line 509 ---------------------------------------- -- line 586 ---------------------------------------- . /// let path = Path::new("/tmp/foo/bar.txt"); . /// . /// for component in path.components() { . /// println!("{:?}", component); . /// } . /// ``` . /// . /// [`components`]: Path::components 72 ( 0.00%) #[derive(Clone)] . #[must_use = "iterators are lazy and do nothing unless consumed"] . #[stable(feature = "rust1", since = "1.0.0")] . pub struct Components<'a> { . // The path left to parse components from 12 ( 0.00%) path: &'a [u8], . . // The prefix as it was originally parsed, if any . prefix: Option>, . . // true if path *physically* has a root separator; for most Windows . // prefixes, it may have a "logical" root separator for the purposes of . // normalization, e.g., \\server\share == \\server\share\. . has_physical_root: bool, . . // The iterator is double-ended, and these two states keep track of what has . // been produced from either end 6 ( 0.00%) front: State, 6 ( 0.00%) back: State, . } . . /// An iterator over the [`Component`]s of a [`Path`], as [`OsStr`] slices. . /// . /// This `struct` is created by the [`iter`] method on [`Path`]. . /// See its documentation for more. . /// . /// [`iter`]: Path::iter -- line 620 ---------------------------------------- -- line 650 ---------------------------------------- . #[inline] . fn prefix_verbatim(&self) -> bool { . self.prefix.as_ref().map(Prefix::is_verbatim).unwrap_or(false) . } . . /// how much of the prefix is left from the point of view of iteration? . #[inline] . fn prefix_remaining(&self) -> usize { 113 ( 0.00%) if self.front == State::Prefix { self.prefix_len() } else { 0 } . } . . // Given the iteration so far, how much of the pre-State::Body path is left? . #[inline] 791 ( 0.00%) fn len_before_body(&self) -> usize { 452 ( 0.00%) let root = if self.front <= State::StartDir && self.has_physical_root { 1 } else { 0 }; 125 ( 0.00%) let cur_dir = if self.front <= State::StartDir && self.include_cur_dir() { 1 } else { 0 }; 452 ( 0.00%) self.prefix_remaining() + root + cur_dir 1,017 ( 0.00%) } . . // is the iteration complete? . #[inline] . fn finished(&self) -> bool { . self.front == State::Done || self.back == State::Done || self.front > self.back . } . . #[inline] -- line 675 ---------------------------------------- -- line 687 ---------------------------------------- . /// let mut components = Path::new("/tmp/foo/bar.txt").components(); . /// components.next(); . /// components.next(); . /// . /// assert_eq!(Path::new("foo/bar.txt"), components.as_path()); . /// ``` . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] 36 ( 0.00%) pub fn as_path(&self) -> &'a Path { . let mut comps = self.clone(); 6 ( 0.00%) if comps.front == State::Body { . comps.trim_left(); . } 6 ( 0.00%) if comps.back == State::Body { . comps.trim_right(); . } . unsafe { Path::from_u8_slice(comps.path) } 54 ( 0.00%) } . . /// Is the *original* path rooted? . fn has_root(&self) -> bool { 226 ( 0.00%) if self.has_physical_root { . return true; . } 15 ( 0.00%) if let Some(p) = self.prefix { . if p.has_implicit_root() { . return true; . } . } . false . } . . /// Should the normalized path include a leading . ? . fn include_cur_dir(&self) -> bool { 6 ( 0.00%) if self.has_root() { . return false; . } 11 ( 0.00%) let mut iter = self.path[self.prefix_len()..].iter(); 4 ( 0.00%) match (iter.next(), iter.next()) { . (Some(&b'.'), None) => true, . (Some(&b'.'), Some(&b)) => self.is_sep_byte(b), . _ => false, . } . } . . // parse a given byte sequence into the corresponding path component . fn parse_single_component<'b>(&self, comp: &'b [u8]) -> Option> { . match comp { 336 ( 0.00%) b"." if self.prefix_verbatim() => Some(Component::CurDir), . b"." => None, // . components are normalized away, except at . // the beginning of a path, which is treated . // separately via `include_cur_dir` . b".." => Some(Component::ParentDir), . b"" => None, . _ => Some(Component::Normal(unsafe { u8_slice_as_os_str(comp) })), . } . } -- line 743 ---------------------------------------- -- line 750 ---------------------------------------- . None => (0, self.path), . Some(i) => (1, &self.path[..i]), . }; . (comp.len() + extra, self.parse_single_component(comp)) . } . . // parse a component from the right, saying how many bytes to consume to . // remove the component 280 ( 0.00%) fn parse_next_component_back(&self) -> (usize, Option>) { . debug_assert!(self.back == State::Body); 112 ( 0.00%) let start = self.len_before_body(); 56 ( 0.00%) let (extra, comp) = match self.path[start..].iter().rposition(|b| self.is_sep_byte(*b)) { . None => (0, &self.path[start..]), 220 ( 0.00%) Some(i) => (1, &self.path[start + i + 1..]), . }; 336 ( 0.00%) (comp.len() + extra, self.parse_single_component(comp)) 224 ( 0.00%) } . . // trim away repeated separators (i.e., empty components) on the left . fn trim_left(&mut self) { . while !self.path.is_empty() { . let (size, comp) = self.parse_next_component(); . if comp.is_some() { . return; . } else { . self.path = &self.path[size..]; . } . } . } . . // trim away repeated separators (i.e., empty components) on the right . fn trim_right(&mut self) { 18 ( 0.00%) while self.path.len() > self.len_before_body() { 18 ( 0.00%) let (size, comp) = self.parse_next_component_back(); 6 ( 0.00%) if comp.is_some() { . return; . } else { . self.path = &self.path[..self.path.len() - size]; . } . } . } . } . -- line 792 ---------------------------------------- -- line 930 ---------------------------------------- . } . } . None . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl<'a> DoubleEndedIterator for Components<'a> { 510 ( 0.00%) fn next_back(&mut self) -> Option> { 257 ( 0.00%) while !self.finished() { 112 ( 0.00%) match self.back { 255 ( 0.00%) State::Body if self.path.len() > self.len_before_body() => { 600 ( 0.00%) let (size, comp) = self.parse_next_component_back(); 200 ( 0.00%) self.path = &self.path[..self.path.len() - size]; 50 ( 0.00%) if comp.is_some() { 400 ( 0.00%) return comp; . } . } . State::Body => { 3 ( 0.00%) self.back = State::StartDir; . } . State::StartDir => { 2 ( 0.00%) self.back = State::Prefix; 51 ( 0.00%) if self.has_physical_root { . self.path = &self.path[..self.path.len() - 1]; . return Some(Component::RootDir); 12 ( 0.00%) } else if let Some(p) = self.prefix { . if p.has_implicit_root() && !p.is_verbatim() { . return Some(Component::RootDir); . } . } else if self.include_cur_dir() { . self.path = &self.path[..self.path.len() - 1]; . return Some(Component::CurDir); . } . } -- line 964 ---------------------------------------- -- line 965 ---------------------------------------- . State::Prefix if self.prefix_len() > 0 => { . self.back = State::Done; . return Some(Component::Prefix(PrefixComponent { . raw: unsafe { u8_slice_as_os_str(self.path) }, . parsed: self.prefix.unwrap(), . })); . } . State::Prefix => { 1 ( 0.00%) self.back = State::Done; . return None; . } . State::Done => unreachable!(), . } . } . None 459 ( 0.00%) } . } . . #[stable(feature = "fused", since = "1.26.0")] . impl FusedIterator for Components<'_> {} . . #[stable(feature = "rust1", since = "1.0.0")] . impl<'a> cmp::PartialEq for Components<'a> { . #[inline] -- line 988 ---------------------------------------- -- line 1001 ---------------------------------------- . // possible future improvement: this could bail out earlier if there were a . // reverse memcmp/bcmp comparing back to front . if self.path == other.path { . return true; . } . } . . // compare back to front since absolute paths often share long prefixes 1 ( 0.00%) Iterator::eq(self.clone().rev(), other.clone().rev()) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl cmp::Eq for Components<'_> {} . . #[stable(feature = "rust1", since = "1.0.0")] . impl<'a> cmp::PartialOrd for Components<'a> { -- line 1017 ---------------------------------------- -- line 1179 ---------------------------------------- . /// use std::path::PathBuf; . /// . /// let path = PathBuf::new(); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[must_use] . #[inline] . pub fn new() -> PathBuf { 36 ( 0.00%) PathBuf { inner: OsString::new() } . } . . /// Creates a new `PathBuf` with a given capacity used to create the . /// internal [`OsString`]. See [`with_capacity`] defined on [`OsString`]. . /// . /// # Examples . /// . /// ``` -- line 1195 ---------------------------------------- -- line 1260 ---------------------------------------- . /// use std::path::PathBuf; . /// . /// let mut path = PathBuf::from("/tmp"); . /// path.push("/etc"); . /// assert_eq!(path, PathBuf::from("/etc")); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn push>(&mut self, path: P) { 236 ( 0.00%) self._push(path.as_ref()) . } . 472 ( 0.00%) fn _push(&mut self, path: &Path) { . // in general, a separator is needed if the rightmost byte is not a separator . let mut need_sep = self.as_mut_vec().last().map(|c| !is_sep_byte(*c)).unwrap_or(false); . . // in the special case of `C:` on Windows, do *not* add a separator . let comps = self.components(); . . if comps.prefix_len() > 0 . && comps.prefix_len() == comps.path.len() -- line 1279 ---------------------------------------- -- line 1327 ---------------------------------------- . return; . . // `path` has a root but no prefix, e.g., `\windows` (Windows only) . } else if path.has_root() { . let prefix_len = self.components().prefix_remaining(); . self.as_mut_vec().truncate(prefix_len); . . // `path` is a pure relative path 58 ( 0.00%) } else if need_sep { . self.inner.push(MAIN_SEP_STR); . } . . self.inner.push(path); 354 ( 0.00%) } . . /// Truncates `self` to [`self.parent`]. . /// . /// Returns `false` and does nothing if [`self.parent`] is [`None`]. . /// Otherwise, returns `true`. . /// . /// [`self.parent`]: Path::parent . /// -- line 1348 ---------------------------------------- -- line 1354 ---------------------------------------- . /// let mut p = PathBuf::from("/spirited/away.rs"); . /// . /// p.pop(); . /// assert_eq!(Path::new("/spirited"), p); . /// p.pop(); . /// assert_eq!(Path::new("/"), p); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 16 ( 0.00%) pub fn pop(&mut self) -> bool { 4 ( 0.00%) match self.parent().map(|p| p.as_u8_slice().len()) { . Some(len) => { . self.as_mut_vec().truncate(len); . true . } . None => false, . } 16 ( 0.00%) } . . /// Updates [`self.file_name`] to `file_name`. . /// . /// If [`self.file_name`] was [`None`], this is equivalent to pushing . /// `file_name`. . /// . /// Otherwise it is equivalent to calling [`pop`] and then pushing . /// `file_name`. The new path will be a sibling of the original path. -- line 1378 ---------------------------------------- -- line 1428 ---------------------------------------- . /// p.set_extension("force"); . /// assert_eq!(Path::new("/feel/the.force"), p.as_path()); . /// . /// p.set_extension("dark_side"); . /// assert_eq!(Path::new("/feel/the.dark_side"), p.as_path()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn set_extension>(&mut self, extension: S) -> bool { 40 ( 0.00%) self._set_extension(extension.as_ref()) . } . 120 ( 0.00%) fn _set_extension(&mut self, extension: &OsStr) -> bool { 96 ( 0.00%) let file_stem = match self.file_stem() { . None => return false, . Some(f) => os_str_as_u8_slice(f), . }; . . // truncate until right after the file stem . let end_file_stem = file_stem[file_stem.len()..].as_ptr() as usize; . let start = os_str_as_u8_slice(&self.inner).as_ptr() as usize; . let v = self.as_mut_vec(); . v.truncate(end_file_stem.wrapping_sub(start)); . . // add the new extension, if any . let new = os_str_as_u8_slice(extension); 12 ( 0.00%) if !new.is_empty() { 33 ( 0.00%) v.reserve_exact(new.len() + 1); . v.push(b'.'); . v.extend_from_slice(new); . } . . true 96 ( 0.00%) } . . /// Consumes the `PathBuf`, yielding its internal [`OsString`] storage. . /// . /// # Examples . /// . /// ``` . /// use std::path::PathBuf; . /// -- line 1468 ---------------------------------------- -- line 1558 ---------------------------------------- . self.inner.shrink_to(min_capacity) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Clone for PathBuf { . #[inline] . fn clone(&self) -> Self { 6 ( 0.00%) PathBuf { inner: self.inner.clone() } . } . . #[inline] . fn clone_from(&mut self, source: &Self) { . self.inner.clone_from(&source.inner) . } . } . -- line 1574 ---------------------------------------- -- line 1642 ---------------------------------------- . . #[stable(feature = "rust1", since = "1.0.0")] . impl From for PathBuf { . /// Converts an [`OsString`] into a [`PathBuf`] . /// . /// This conversion does not allocate or copy memory. . #[inline] . fn from(s: OsString) -> PathBuf { 192 ( 0.00%) PathBuf { inner: s } . } . } . . #[stable(feature = "from_path_buf_for_os_string", since = "1.14.0")] . impl From for OsString { . /// Converts a [`PathBuf`] into an [`OsString`] . /// . /// This conversion does not allocate or copy memory. -- line 1658 ---------------------------------------- -- line 1825 ---------------------------------------- . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl ToOwned for Path { . type Owned = PathBuf; . #[inline] . fn to_owned(&self) -> PathBuf { 5 ( 0.00%) self.to_path_buf() . } . #[inline] . fn clone_into(&self, target: &mut PathBuf) { . self.inner.clone_into(&mut target.inner); . } . } . . #[stable(feature = "rust1", since = "1.0.0")] -- line 1841 ---------------------------------------- -- line 1843 ---------------------------------------- . #[inline] . fn eq(&self, other: &PathBuf) -> bool { . self.components() == other.components() . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Hash for PathBuf { 30 ( 0.00%) fn hash(&self, h: &mut H) { . self.as_path().hash(h) 24 ( 0.00%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl cmp::Eq for PathBuf {} . . #[stable(feature = "rust1", since = "1.0.0")] . impl cmp::PartialOrd for PathBuf { . #[inline] -- line 1861 ---------------------------------------- -- line 1936 ---------------------------------------- . . impl Path { . // The following (private!) function allows construction of a path from a u8 . // slice, which is only safe when it is known to follow the OsStr encoding. . unsafe fn from_u8_slice(s: &[u8]) -> &Path { . unsafe { Path::new(u8_slice_as_os_str(s)) } . } . // The following (private!) function reveals the byte encoding used for OsStr. 640 ( 0.00%) fn as_u8_slice(&self) -> &[u8] { . os_str_as_u8_slice(&self.inner) 320 ( 0.00%) } . . /// Directly wraps a string slice as a `Path` slice. . /// . /// This is a cost-free conversion. . /// . /// # Examples . /// . /// ``` -- line 1954 ---------------------------------------- -- line 1964 ---------------------------------------- . /// . /// let string = String::from("foo.txt"); . /// let from_string = Path::new(&string); . /// let from_path = Path::new(&from_string); . /// assert_eq!(from_string, from_path); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn new + ?Sized>(s: &S) -> &Path { 4 ( 0.00%) unsafe { &*(s.as_ref() as *const OsStr as *const Path) } . } . . /// Yields the underlying [`OsStr`] slice. . /// . /// # Examples . /// . /// ``` . /// use std::path::Path; -- line 1980 ---------------------------------------- -- line 2050 ---------------------------------------- . /// . /// let path_buf = Path::new("foo.txt").to_path_buf(); . /// assert_eq!(path_buf, std::path::PathBuf::from("foo.txt")); . /// ``` . #[rustc_conversion_suggestion] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[stable(feature = "rust1", since = "1.0.0")] 72 ( 0.00%) pub fn to_path_buf(&self) -> PathBuf { . PathBuf::from(self.inner.to_os_string()) 63 ( 0.00%) } . . /// Returns `true` if the `Path` is absolute, i.e., if it is independent of . /// the current directory. . /// . /// * On Unix, a path is absolute if it starts with the root, so . /// `is_absolute` and [`has_root`] are equivalent. . /// . /// * On Windows, a path is absolute if it has a prefix and starts with the -- line 2068 ---------------------------------------- -- line 2082 ---------------------------------------- . #[allow(deprecated)] . pub fn is_absolute(&self) -> bool { . if cfg!(target_os = "redox") { . // FIXME: Allow Redox prefixes . self.has_root() || has_redox_scheme(self.as_u8_slice()) . } else { . self.has_root() && (cfg!(any(unix, target_os = "wasi")) || self.prefix().is_some()) . } 2 ( 0.00%) } . . /// Returns `true` if the `Path` is relative, i.e., not absolute. . /// . /// See [`is_absolute`]'s documentation for more details. . /// . /// # Examples . /// . /// ``` -- line 2098 ---------------------------------------- -- line 2150 ---------------------------------------- . /// assert_eq!(parent, Path::new("/foo")); . /// . /// let grand_parent = parent.parent().unwrap(); . /// assert_eq!(grand_parent, Path::new("/")); . /// assert_eq!(grand_parent.parent(), None); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[must_use] 2 ( 0.00%) pub fn parent(&self) -> Option<&Path> { . let mut comps = self.components(); 6 ( 0.00%) let comp = comps.next_back(); 8 ( 0.00%) comp.and_then(|p| match p { . Component::Normal(_) | Component::CurDir | Component::ParentDir => { 10 ( 0.00%) Some(comps.as_path()) . } . _ => None, . }) 4 ( 0.00%) } . . /// Produces an iterator over `Path` and its ancestors. . /// . /// The iterator will yield the `Path` that is returned if the [`parent`] method is used zero . /// or more times. That means, the iterator will yield `&self`, `&self.parent().unwrap()`, . /// `&self.parent().unwrap().parent().unwrap()` and so on. If the [`parent`] method returns . /// [`None`], the iterator will do likewise. The iterator will always yield at least one value, . /// namely `&self`. -- line 2175 ---------------------------------------- -- line 2217 ---------------------------------------- . /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("tmp/foo.txt").file_name()); . /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.").file_name()); . /// assert_eq!(Some(OsStr::new("foo.txt")), Path::new("foo.txt/.//").file_name()); . /// assert_eq!(None, Path::new("foo.txt/..").file_name()); . /// assert_eq!(None, Path::new("/").file_name()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[must_use] 31 ( 0.00%) pub fn file_name(&self) -> Option<&OsStr> { 129 ( 0.00%) self.components().next_back().and_then(|p| match p { . Component::Normal(p) => Some(p), . _ => None, . }) 62 ( 0.00%) } . . /// Returns a path that, when joined onto `base`, yields `self`. . /// . /// # Errors . /// . /// If `base` is not a prefix of `self` (i.e., [`starts_with`] . /// returns `false`), returns [`Err`]. . /// -- line 2238 ---------------------------------------- -- line 2354 ---------------------------------------- . /// # See Also . /// This method is similar to [`Path::file_prefix`], which extracts the portion of the file name . /// before the *first* `.` . /// . /// [`Path::file_prefix`]: Path::file_prefix . /// . #[stable(feature = "rust1", since = "1.0.0")] . #[must_use] 12 ( 0.00%) pub fn file_stem(&self) -> Option<&OsStr> { . self.file_name().map(rsplit_file_at_dot).and_then(|(before, after)| before.or(after)) 24 ( 0.00%) } . . /// Extracts the prefix of [`self.file_name`]. . /// . /// The prefix is: . /// . /// * [`None`], if there is no file name; . /// * The entire file name if there is no embedded `.`; . /// * The portion of the file name before the first non-beginning `.`; -- line 2372 ---------------------------------------- -- line 2431 ---------------------------------------- . /// ``` . /// use std::path::{Path, PathBuf}; . /// . /// assert_eq!(Path::new("/etc").join("passwd"), PathBuf::from("/etc/passwd")); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[must_use] . pub fn join>(&self, path: P) -> PathBuf { 68 ( 0.00%) self._join(path.as_ref()) . } . 288 ( 0.00%) fn _join(&self, path: &Path) -> PathBuf { . let mut buf = self.to_path_buf(); . buf.push(path); . buf 216 ( 0.00%) } . . /// Creates an owned [`PathBuf`] like `self` but with the given file name. . /// . /// See [`PathBuf::set_file_name`] for more details. . /// . /// # Examples . /// . /// ``` -- line 2454 ---------------------------------------- -- line 2531 ---------------------------------------- . /// assert_eq!(components.next(), Some(Component::Normal(OsStr::new("foo.txt")))); . /// assert_eq!(components.next(), None) . /// ``` . /// . /// [`CurDir`]: Component::CurDir . #[stable(feature = "rust1", since = "1.0.0")] . pub fn components(&self) -> Components<'_> { . let prefix = parse_prefix(self.as_os_str()); 343 ( 0.00%) Components { . path: self.as_u8_slice(), . prefix, 110 ( 0.00%) has_physical_root: has_physical_root(self.as_u8_slice(), prefix) . || has_redox_scheme(self.as_u8_slice()), . front: State::Prefix, . back: State::Body, . } . } . . /// Produces an iterator over the path's components viewed as [`OsStr`] . /// slices. -- line 2550 ---------------------------------------- -- line 2775 ---------------------------------------- . /// . /// When the goal is simply to read from (or write to) the source, the most . /// reliable way to test the source can be read (or written to) is to open . /// it. Only using `is_file` can break workflows like `diff <( prog_a )` on . /// a Unix-like system for example. See [`fs::File::open`] or . /// [`fs::OpenOptions::open`] for more information. . #[stable(feature = "path_ext", since = "1.5.0")] . #[must_use] 5 ( 0.00%) pub fn is_file(&self) -> bool { . fs::metadata(self).map(|m| m.is_file()).unwrap_or(false) 3 ( 0.00%) } . . /// Returns `true` if the path exists on disk and is pointing at a directory. . /// . /// This function will traverse symbolic links to query information about the . /// destination file. . /// . /// If you cannot access the metadata of the file, e.g. because of a . /// permission error or broken symbolic links, this will return `false`. -- line 2793 ---------------------------------------- -- line 2802 ---------------------------------------- . /// . /// # See Also . /// . /// This is a convenience function that coerces errors to false. If you want to . /// check errors, call [`fs::metadata`] and handle its [`Result`]. Then call . /// [`fs::Metadata::is_dir`] if it was [`Ok`]. . #[stable(feature = "path_ext", since = "1.5.0")] . #[must_use] 15 ( 0.00%) pub fn is_dir(&self) -> bool { . fs::metadata(self).map(|m| m.is_dir()).unwrap_or(false) 9 ( 0.00%) } . . /// Returns `true` if the path exists on disk and is pointing at a symbolic link. . /// . /// This function will not traverse symbolic links. . /// In case of a broken symbolic link this will also return true. . /// . /// If you cannot access the directory containing the file, e.g., because of a . /// permission error, this will return false. -- line 2820 ---------------------------------------- -- line 2898 ---------------------------------------- . impl fmt::Debug for Display<'_> { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . fmt::Debug::fmt(&self.path, f) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl fmt::Display for Display<'_> { 6 ( 0.00%) fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 6 ( 0.00%) self.path.inner.display(f) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl cmp::PartialEq for Path { . #[inline] . fn eq(&self, other: &Path) -> bool { . self.components() == other.components() . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Hash for Path { 2,512 ( 0.00%) fn hash(&self, h: &mut H) { 326 ( 0.00%) let bytes = self.as_u8_slice(); . let prefix_len = match parse_prefix(&self.inner) { . Some(prefix) => { . prefix.hash(h); . prefix.len() . } . None => 0, . }; . let bytes = &bytes[prefix_len..]; . . let mut component_start = 0; . let mut bytes_hashed = 0; . . for i in 0..bytes.len() { 32,362 ( 0.04%) if is_sep_byte(bytes[i]) { 11,358 ( 0.02%) if i > component_start { . let to_hash = &bytes[component_start..i]; 8 ( 0.00%) h.write(to_hash); 6,936 ( 0.01%) bytes_hashed += to_hash.len(); . } . . // skip over separator and optionally a following CurDir item . // since components() would normalize these away 15,566 ( 0.02%) component_start = i + match bytes[i..] { 7,572 ( 0.01%) [_, b'.', b'/', ..] | [_, b'.'] => 2, . _ => 1, . }; . } . } . 640 ( 0.00%) if component_start < bytes.len() { . let to_hash = &bytes[component_start..]; 3 ( 0.00%) h.write(to_hash); 640 ( 0.00%) bytes_hashed += to_hash.len(); . } . . h.write_usize(bytes_hashed); 2,472 ( 0.00%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl cmp::Eq for Path {} . . #[stable(feature = "rust1", since = "1.0.0")] . impl cmp::PartialOrd for Path { . #[inline] -- line 2967 ---------------------------------------- 19,260 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/tokentrees.rs -------------------------------------------------------------------------------- Ir -- line 8 ---------------------------------------- . }; . use rustc_ast_pretty::pprust::token_to_string; . use rustc_data_structures::fx::FxHashMap; . use rustc_errors::PResult; . use rustc_span::Span; . . impl<'a> StringReader<'a> { . pub(super) fn into_token_trees(self) -> (PResult<'a, TokenStream>, Vec) { 38 ( 0.00%) let mut tt_reader = TokenTreesReader { . string_reader: self, 2 ( 0.00%) token: Token::dummy(), . open_braces: Vec::new(), . unmatched_braces: Vec::new(), . matching_delim_spans: Vec::new(), . last_unclosed_found_span: None, . last_delim_empty_block_spans: FxHashMap::default(), . matching_block_spans: Vec::new(), . }; 2 ( 0.00%) let res = tt_reader.parse_all_token_trees(); 12 ( 0.00%) (res, tt_reader.unmatched_braces) . } . } . . struct TokenTreesReader<'a> { . string_reader: StringReader<'a>, . token: Token, . /// Stack of open delimiters and their spans. Used for error message. . open_braces: Vec<(token::DelimToken, Span)>, -- line 35 ---------------------------------------- -- line 43 ---------------------------------------- . last_delim_empty_block_spans: FxHashMap, . /// Collect the spans of braces (Open, Close). Used only . /// for detecting if blocks are empty and only braces. . matching_block_spans: Vec<(Span, Span)>, . } . . impl<'a> TokenTreesReader<'a> { . // Parse a stream of tokens into a list of `TokenTree`s, up to an `Eof`. 16 ( 0.00%) fn parse_all_token_trees(&mut self) -> PResult<'a, TokenStream> { . let mut buf = TokenStreamBuilder::default(); . . self.bump(); 768 ( 0.00%) while self.token != token::Eof { 3,056 ( 0.00%) buf.push(self.parse_token_tree()?); . } . . Ok(buf.into_token_stream()) 18 ( 0.00%) } . . // Parse a stream of tokens into a list of `TokenTree`s, up to a `CloseDelim`. . fn parse_token_trees_until_close_delim(&mut self) -> TokenStream { . let mut buf = TokenStreamBuilder::default(); . loop { 17,218 ( 0.02%) if let token::CloseDelim(..) = self.token.kind { . return buf.into_token_stream(); . } . 37,505 ( 0.05%) match self.parse_token_tree() { 67,509 ( 0.09%) Ok(tree) => buf.push(tree), . Err(mut e) => { . e.emit(); . return buf.into_token_stream(); . } . } . } . } . 70,947 ( 0.10%) fn parse_token_tree(&mut self) -> PResult<'a, TreeAndSpacing> { 15,766 ( 0.02%) let sm = self.string_reader.sess.source_map(); . 66,515 ( 0.09%) match self.token.kind { . token::Eof => { . let msg = "this file contains an unclosed delimiter"; . let mut err = . self.string_reader.sess.span_diagnostic.struct_span_err(self.token.span, msg); . for &(_, sp) in &self.open_braces { . err.span_label(sp, "unclosed delimiter"); . self.unmatched_braces.push(UnmatchedBrace { . expected_delim: token::DelimToken::Brace, -- line 91 ---------------------------------------- -- line 113 ---------------------------------------- . err.span_label( . *close_sp, . "...as it matches this but it has different indentation", . ); . } . } . Err(err) . } 1,108 ( 0.00%) token::OpenDelim(delim) => { . // The span for beginning of the delimited section 1,108 ( 0.00%) let pre_span = self.token.span; . . // Parse the open delimiter. 7,756 ( 0.01%) self.open_braces.push((delim, self.token.span)); . self.bump(); . . // Parse the token trees within the delimiters. . // We stop at any delimiter so we can try to recover if the user . // uses an incorrect delimiter. 1,108 ( 0.00%) let tts = self.parse_token_trees_until_close_delim(); . . // Expand to cover the entire delimited token tree 5,540 ( 0.01%) let delim_span = DelimSpan::from_pair(pre_span, self.token.span); . 2,216 ( 0.00%) match self.token.kind { . // Correct delimiter. 2,216 ( 0.00%) token::CloseDelim(d) if d == delim => { . let (open_brace, open_brace_span) = self.open_braces.pop().unwrap(); 2,216 ( 0.00%) let close_brace_span = self.token.span; . 3,324 ( 0.00%) if tts.is_empty() { 546 ( 0.00%) let empty_block_span = open_brace_span.to(close_brace_span); 728 ( 0.00%) if !sm.is_multiline(empty_block_span) { . // Only track if the block is in the form of `{}`, otherwise it is . // likely that it was written on purpose. . self.last_delim_empty_block_spans.insert(delim, empty_block_span); . } . } . . //only add braces 4,432 ( 0.01%) if let (DelimToken::Brace, DelimToken::Brace) = (open_brace, delim) { . self.matching_block_spans.push((open_brace_span, close_brace_span)); . } . 1,108 ( 0.00%) if self.open_braces.is_empty() { . // Clear up these spans to avoid suggesting them as we've found . // properly matched delimiters so far for an entire block. . self.matching_delim_spans.clear(); . } else { . self.matching_delim_spans.push(( . open_brace, . open_brace_span, . close_brace_span, -- line 165 ---------------------------------------- -- line 218 ---------------------------------------- . token::Eof => { . // Silently recover, the EOF token will be seen again . // and an error emitted then. Thus we don't pop from . // self.open_braces here. . } . _ => {} . } . 7,756 ( 0.01%) Ok(TokenTree::Delimited(delim_span, delim, tts).into()) . } . token::CloseDelim(delim) => { . // An unexpected closing delimiter (i.e., there is no . // matching opening delimiter). . let token_str = token_to_string(&self.token); . let msg = format!("unexpected closing delimiter: `{}`", token_str); . let mut err = . self.string_reader.sess.span_diagnostic.struct_span_err(self.token.span, &msg); -- line 234 ---------------------------------------- -- line 253 ---------------------------------------- . err.span_label(parent.1, "...matches this closing brace"); . } . } . . err.span_label(self.token.span, "unexpected closing delimiter"); . Err(err) . } . _ => { 33,875 ( 0.05%) let tt = TokenTree::Token(self.token.take()); . let mut spacing = self.bump(); 13,550 ( 0.02%) if !self.token.is_op() { . spacing = Alone; . } 40,650 ( 0.06%) Ok((tt, spacing)) . } . } 63,064 ( 0.09%) } . . fn bump(&mut self) -> Spacing { 75,391 ( 0.10%) let (spacing, token) = self.string_reader.next_token(); 39,433 ( 0.05%) self.token = token; . spacing . } . } . 1,108 ( 0.00%) #[derive(Default)] . struct TokenStreamBuilder { . buf: Vec, . } . . impl TokenStreamBuilder { 102,479 ( 0.14%) fn push(&mut self, (tree, joint): TreeAndSpacing) { 48,640 ( 0.07%) if let Some((TokenTree::Token(prev_token), Joint)) = self.buf.last() { 3,850 ( 0.01%) if let TokenTree::Token(token) = &tree { 7,999 ( 0.01%) if let Some(glued) = prev_token.glue(token) { . self.buf.pop(); 6,672 ( 0.01%) self.buf.push((TokenTree::Token(glued), joint)); . return; . } . } . } 36,635 ( 0.05%) self.buf.push((tree, joint)) 63,064 ( 0.09%) } . . fn into_token_stream(self) -> TokenStream { 11,098 ( 0.02%) TokenStream::new(self.buf) . } . } 28,152 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/memchr.rs -------------------------------------------------------------------------------- Ir -- line 16 ---------------------------------------- . /// . /// From *Matters Computational*, J. Arndt: . /// . /// "The idea is to subtract one from each of the bytes and then look for . /// bytes where the borrow propagated all the way to the most significant . /// bit." . #[inline] . fn contains_zero_byte(x: usize) -> bool { 23,255 ( 0.03%) x.wrapping_sub(LO_USIZE) & !x & HI_USIZE != 0 . } . . #[cfg(target_pointer_width = "16")] . #[inline] . fn repeat_byte(b: u8) -> usize { . (b as usize) << 8 | b as usize . } . -- line 32 ---------------------------------------- -- line 36 ---------------------------------------- . (b as usize) * (usize::MAX / 255) . } . . /// Returns the first index matching the byte `x` in `text`. . #[must_use] . #[inline] . pub fn memchr(x: u8, text: &[u8]) -> Option { . // Fast path for small slices 2,414 ( 0.00%) if text.len() < 2 * USIZE_BYTES { 1,915 ( 0.00%) return text.iter().position(|elt| *elt == x); . } . 2,091 ( 0.00%) memchr_general_case(x, text) . } . 2,116 ( 0.00%) fn memchr_general_case(x: u8, text: &[u8]) -> Option { . // Scan for a single byte value by reading two `usize` words at a time. . // . // Split `text` in three parts . // - unaligned initial part, before the first word aligned address in text . // - body, scan by 2 words at a time . // - the last remaining part, < 2 word size . . // search up to an aligned boundary . let len = text.len(); . let ptr = text.as_ptr(); . let mut offset = ptr.align_offset(USIZE_BYTES); . 1,058 ( 0.00%) if offset > 0 { . offset = cmp::min(offset, len); 1,845 ( 0.00%) if let Some(index) = text[..offset].iter().position(|elt| *elt == x) { . return Some(index); . } . } . . // search the body of the text . let repeated_x = repeat_byte(x); 10,824 ( 0.01%) while offset <= len - 2 * USIZE_BYTES { . // SAFETY: the while's predicate guarantees a distance of at least 2 * usize_bytes . // between the offset and the end of the slice. . unsafe { . let u = *(ptr.add(offset) as *const usize); 13,953 ( 0.02%) let v = *(ptr.add(offset + USIZE_BYTES) as *const usize); . . // break if there is a matching byte 13,953 ( 0.02%) let zu = contains_zero_byte(u ^ repeated_x); 13,953 ( 0.02%) let zv = contains_zero_byte(v ^ repeated_x); 9,302 ( 0.01%) if zu || zv { . break; . } . } 9,252 ( 0.01%) offset += USIZE_BYTES * 2; . } . . // Find the byte after the point the body loop stopped. 4,229 ( 0.01%) text[offset..].iter().position(|elt| *elt == x).map(|i| offset + i) 2,645 ( 0.00%) } . . /// Returns the last index matching the byte `x` in `text`. . #[must_use] . pub fn memrchr(x: u8, text: &[u8]) -> Option { . // Scan for a single byte value by reading two `usize` words at a time. . // . // Split `text` in three parts: . // - unaligned tail, after the last word aligned address in text, -- line 100 ---------------------------------------- 8,180 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lint/src/builtin.rs -------------------------------------------------------------------------------- Ir -- line 161 ---------------------------------------- . }); . } . } . } . } . } . . impl<'tcx> LateLintPass<'tcx> for BoxPointers { 63 ( 0.00%) fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) { 28 ( 0.00%) match it.kind { . hir::ItemKind::Fn(..) . | hir::ItemKind::TyAlias(..) . | hir::ItemKind::Enum(..) . | hir::ItemKind::Struct(..) . | hir::ItemKind::Union(..) => { . self.check_heap_type(cx, it.span, cx.tcx.type_of(it.def_id)) . } . _ => (), . } . . // If it's a struct, we also have to check the fields' types 21 ( 0.00%) match it.kind { . hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => { . for struct_field in struct_def.fields() { . let def_id = cx.tcx.hir().local_def_id(struct_field.hir_id); . self.check_heap_type(cx, struct_field.span, cx.tcx.type_of(def_id)); . } . } . _ => (), . } 56 ( 0.00%) } . . fn check_expr(&mut self, cx: &LateContext<'_>, e: &hir::Expr<'_>) { . let ty = cx.typeck_results().node_type(e.hir_id); . self.check_heap_type(cx, e.span, ty); . } . } . . declare_lint! { -- line 199 ---------------------------------------- -- line 337 ---------------------------------------- . override them", . ) . .emit(); . }) . } . } . . impl EarlyLintPass for UnsafeCode { 1,026 ( 0.00%) fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &ast::Attribute) { 11 ( 0.00%) if attr.has_name(sym::allow_internal_unsafe) { . self.report_unsafe(cx, attr.span, |lint| { . lint.build( . "`allow_internal_unsafe` allows defining \ . macros using unsafe without triggering \ . the `unsafe_code` lint at their call site", . ) . .emit() . }); . } 1,368 ( 0.00%) } . . fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) { . if let ast::ExprKind::Block(ref blk, _) = e.kind { . // Don't warn about generated blocks; that'll just pollute the output. . if blk.rules == ast::BlockCheckMode::Unsafe(ast::UserProvided) { . self.report_unsafe(cx, blk.span, |lint| { . lint.build("usage of an `unsafe` block").emit() . }); . } . } . } . 42 ( 0.00%) fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) { 35 ( 0.00%) match it.kind { . ast::ItemKind::Trait(box ast::Trait { unsafety: ast::Unsafe::Yes(_), .. }) => self . .report_unsafe(cx, it.span, |lint| { . lint.build("declaration of an `unsafe` trait").emit() . }), . . ast::ItemKind::Impl(box ast::Impl { unsafety: ast::Unsafe::Yes(_), .. }) => self . .report_unsafe(cx, it.span, |lint| { . lint.build("implementation of an `unsafe` trait").emit() -- line 378 ---------------------------------------- -- line 409 ---------------------------------------- . attr.span, . "declaration of a static with `export_name`", . ); . } . } . . _ => {} . } 49 ( 0.00%) } . . fn check_impl_item(&mut self, cx: &EarlyContext<'_>, it: &ast::AssocItem) { . if let ast::AssocItemKind::Fn(..) = it.kind { . if let Some(attr) = cx.sess().find_by_name(&it.attrs, sym::no_mangle) { . self.report_overriden_symbol_name( . cx, . attr.span, . "declaration of a `no_mangle` method", -- line 425 ---------------------------------------- -- line 487 ---------------------------------------- . . /// Private traits or trait items that leaked through. Don't check their methods. . private_traits: FxHashSet, . } . . impl_lint_pass!(MissingDoc => [MISSING_DOCS]); . . fn has_doc(attr: &ast::Attribute) -> bool { 8 ( 0.00%) if attr.is_doc_comment() { . return true; . } . . if !attr.has_name(sym::doc) { . return false; . } . . if attr.value_str().is_some() { -- line 503 ---------------------------------------- -- line 512 ---------------------------------------- . } . } . . false . } . . impl MissingDoc { . pub fn new() -> MissingDoc { 4 ( 0.00%) MissingDoc { doc_hidden_stack: vec![false], private_traits: FxHashSet::default() } . } . . fn doc_hidden(&self) -> bool { 354 ( 0.00%) *self.doc_hidden_stack.last().expect("empty doc_hidden_stack") . } . 52 ( 0.00%) fn check_missing_docs_attrs( . &self, . cx: &LateContext<'_>, . def_id: LocalDefId, . sp: Span, . article: &'static str, . desc: &'static str, . ) { . // If we're building a test harness, then warning about . // documentation is probably not really relevant right now. 8 ( 0.00%) if cx.sess().opts.test { . return; . } . . // `#[doc(hidden)]` disables missing_docs check. 4 ( 0.00%) if self.doc_hidden() { . return; . } . . // Only check publicly-visible items, using the result from the privacy pass. . // It's an option so the crate root can also use this function (it doesn't . // have a `NodeId`). 2 ( 0.00%) if def_id != CRATE_DEF_ID { 4 ( 0.00%) if !cx.access_levels.is_exported(def_id) { . return; . } . } . 7 ( 0.00%) let attrs = cx.tcx.get_attrs(def_id.to_def_id()); . let has_doc = attrs.iter().any(has_doc); . if !has_doc { . cx.struct_span_lint( . MISSING_DOCS, . cx.tcx.sess.source_map().guess_head_span(sp), . |lint| { . lint.build(&format!("missing documentation for {} {}", article, desc)).emit() . }, . ); . } 32 ( 0.00%) } . } . . impl<'tcx> LateLintPass<'tcx> for MissingDoc { 2,450 ( 0.00%) fn enter_lint_attrs(&mut self, _cx: &LateContext<'_>, attrs: &[ast::Attribute]) { 350 ( 0.00%) let doc_hidden = self.doc_hidden() . || attrs.iter().any(|attr| { 625 ( 0.00%) attr.has_name(sym::doc) 1,385 ( 0.00%) && match attr.meta_item_list() { . None => false, 1,939 ( 0.00%) Some(l) => attr::list_contains_name(&l, sym::hidden), . } . }); . self.doc_hidden_stack.push(doc_hidden); 2,800 ( 0.00%) } . . fn exit_lint_attrs(&mut self, _: &LateContext<'_>, _attrs: &[ast::Attribute]) { . self.doc_hidden_stack.pop().expect("empty doc_hidden_stack"); . } . 6 ( 0.00%) fn check_crate(&mut self, cx: &LateContext<'_>) { 10 ( 0.00%) self.check_missing_docs_attrs( . cx, . CRATE_DEF_ID, 1 ( 0.00%) cx.tcx.def_span(CRATE_DEF_ID), . "the", . "crate", . ); 4 ( 0.00%) } . 42 ( 0.00%) fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) { 21 ( 0.00%) match it.kind { . hir::ItemKind::Trait(.., trait_item_refs) => { . // Issue #11592: traits are always considered exported, even when private. . if let hir::VisibilityKind::Inherited = it.vis.node { . self.private_traits.insert(it.hir_id()); . for trait_item_ref in trait_item_refs { . self.private_traits.insert(trait_item_ref.id.hir_id()); . } . return; -- line 605 ---------------------------------------- -- line 627 ---------------------------------------- . | hir::ItemKind::Struct(..) . | hir::ItemKind::Union(..) . | hir::ItemKind::Const(..) . | hir::ItemKind::Static(..) => {} . . _ => return, . }; . 27 ( 0.00%) let (article, desc) = cx.tcx.article_and_description(it.def_id.to_def_id()); . 18 ( 0.00%) self.check_missing_docs_attrs(cx, it.def_id, it.span, article, desc); 49 ( 0.00%) } . . fn check_trait_item(&mut self, cx: &LateContext<'_>, trait_item: &hir::TraitItem<'_>) { . if self.private_traits.contains(&trait_item.hir_id()) { . return; . } . . let (article, desc) = cx.tcx.article_and_description(trait_item.def_id.to_def_id()); . -- line 646 ---------------------------------------- -- line 724 ---------------------------------------- . pub MISSING_COPY_IMPLEMENTATIONS, . Allow, . "detects potentially-forgotten implementations of `Copy`" . } . . declare_lint_pass!(MissingCopyImplementations => [MISSING_COPY_IMPLEMENTATIONS]); . . impl<'tcx> LateLintPass<'tcx> for MissingCopyImplementations { 63 ( 0.00%) fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) { 32 ( 0.00%) if !cx.access_levels.is_reachable(item.def_id) { . return; . } 28 ( 0.00%) let (def, ty) = match item.kind { . hir::ItemKind::Struct(_, ref ast_generics) => { . if !ast_generics.params.is_empty() { . return; . } . let def = cx.tcx.adt_def(item.def_id); . (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[]))) . } . hir::ItemKind::Union(_, ref ast_generics) => { -- line 744 ---------------------------------------- -- line 768 ---------------------------------------- . cx.struct_span_lint(MISSING_COPY_IMPLEMENTATIONS, item.span, |lint| { . lint.build( . "type could implement `Copy`; consider adding `impl \ . Copy`", . ) . .emit() . }) . } 56 ( 0.00%) } . } . . declare_lint! { . /// The `missing_debug_implementations` lint detects missing . /// implementations of [`fmt::Debug`]. . /// . /// [`fmt::Debug`]: https://doc.rust-lang.org/std/fmt/trait.Debug.html . /// -- line 784 ---------------------------------------- -- line 811 ---------------------------------------- . #[derive(Default)] . pub struct MissingDebugImplementations { . impling_types: Option, . } . . impl_lint_pass!(MissingDebugImplementations => [MISSING_DEBUG_IMPLEMENTATIONS]); . . impl<'tcx> LateLintPass<'tcx> for MissingDebugImplementations { 49 ( 0.00%) fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) { 32 ( 0.00%) if !cx.access_levels.is_reachable(item.def_id) { . return; . } . 16 ( 0.00%) match item.kind { . hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) | hir::ItemKind::Enum(..) => {} . _ => return, . } . . let Some(debug) = cx.tcx.get_diagnostic_item(sym::Debug) else { . return . }; . -- line 832 ---------------------------------------- -- line 849 ---------------------------------------- . lint.build(&format!( . "type does not implement `{}`; consider adding `#[derive(Debug)]` \ . or a manual implementation", . cx.tcx.def_path_str(debug) . )) . .emit() . }); . } 35 ( 0.00%) } . } . . declare_lint! { . /// The `anonymous_parameters` lint detects anonymous parameters in trait . /// definitions. . /// . /// ### Example . /// -- line 865 ---------------------------------------- -- line 956 ---------------------------------------- . // compute it for every attribute. . depr_attrs: Vec<&'static BuiltinAttribute>, . } . . impl_lint_pass!(DeprecatedAttr => []); . . impl DeprecatedAttr { . pub fn new() -> DeprecatedAttr { 1 ( 0.00%) DeprecatedAttr { depr_attrs: deprecated_attributes() } . } . } . . fn lint_deprecated_attr( . cx: &EarlyContext<'_>, . attr: &ast::Attribute, . msg: &str, . suggestion: Option<&str>, -- line 972 ---------------------------------------- -- line 979 ---------------------------------------- . String::new(), . Applicability::MachineApplicable, . ) . .emit(); . }) . } . . impl EarlyLintPass for DeprecatedAttr { 3,078 ( 0.00%) fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &ast::Attribute) { 1,710 ( 0.00%) for BuiltinAttribute { name, gate, .. } in &self.depr_attrs { 1,390 ( 0.00%) if attr.ident().map(|ident| ident.name) == Some(*name) { . if let &AttributeGate::Gated( . Stability::Deprecated(link, suggestion), . name, . reason, . _, . ) = gate . { . let msg = . format!("use of deprecated attribute `{}`: {}. See {}", name, reason, link); . lint_deprecated_attr(cx, attr, &msg, suggestion); . } . return; . } . } 44 ( 0.00%) if attr.has_name(sym::no_start) || attr.has_name(sym::crate_id) { . let path_str = pprust::path_to_string(&attr.get_normal_item().path); . let msg = format!("use of deprecated attribute `{}`: no longer used.", path_str); . lint_deprecated_attr(cx, attr, &msg, None); . } 2,736 ( 0.00%) } . } . . fn warn_if_doc(cx: &EarlyContext<'_>, node_span: Span, node_kind: &str, attrs: &[ast::Attribute]) { . use rustc_ast::token::CommentKind; . . let mut attrs = attrs.iter().peekable(); . . // Accumulate a single span for sugared doc comments. -- line 1017 ---------------------------------------- -- line 1133 ---------------------------------------- . NO_MANGLE_GENERIC_ITEMS, . Warn, . "generic items must be mangled" . } . . declare_lint_pass!(InvalidNoMangleItems => [NO_MANGLE_CONST_ITEMS, NO_MANGLE_GENERIC_ITEMS]); . . impl<'tcx> LateLintPass<'tcx> for InvalidNoMangleItems { 63 ( 0.00%) fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) { 49 ( 0.00%) let attrs = cx.tcx.hir().attrs(it.hir_id()); . let check_no_mangle_on_generic_fn = |no_mangle_attr: &ast::Attribute, . impl_generics: Option<&hir::Generics<'_>>, . generics: &hir::Generics<'_>, . span| { . for param in . generics.params.iter().chain(impl_generics.map(|g| g.params).into_iter().flatten()) . { . match param.kind { -- line 1150 ---------------------------------------- -- line 1162 ---------------------------------------- . ) . .emit(); . }); . break; . } . } . } . }; 49 ( 0.00%) match it.kind { . hir::ItemKind::Fn(.., ref generics, _) => { . if let Some(no_mangle_attr) = cx.sess().find_by_name(attrs, sym::no_mangle) { . check_no_mangle_on_generic_fn(no_mangle_attr, None, generics, it.span); . } . } . hir::ItemKind::Const(..) => { . if cx.sess().contains_name(attrs, sym::no_mangle) { . // Const items do not refer to a particular location in memory, and therefore -- line 1178 ---------------------------------------- -- line 1215 ---------------------------------------- . it.span, . ); . } . } . } . } . _ => {} . } 56 ( 0.00%) } . } . . declare_lint! { . /// The `mutable_transmutes` lint catches transmuting from `&T` to `&mut . /// T` because it is [undefined behavior]. . /// . /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html . /// -- line 1231 ---------------------------------------- -- line 1301 ---------------------------------------- . } . . declare_lint_pass!( . /// Forbids using the `#[feature(...)]` attribute . UnstableFeatures => [UNSTABLE_FEATURES] . ); . . impl<'tcx> LateLintPass<'tcx> for UnstableFeatures { 2,394 ( 0.00%) fn check_attribute(&mut self, cx: &LateContext<'_>, attr: &ast::Attribute) { 11 ( 0.00%) if attr.has_name(sym::feature) { . if let Some(items) = attr.meta_item_list() { . for item in items { . cx.struct_span_lint(UNSTABLE_FEATURES, item.span(), |lint| { . lint.build("unstable feature").emit() . }); . } . } . } 2,736 ( 0.00%) } . } . . declare_lint! { . /// The `unreachable_pub` lint triggers for `pub` items not reachable from . /// the crate root. . /// . /// ### Example . /// -- line 1327 ---------------------------------------- -- line 1352 ---------------------------------------- . } . . declare_lint_pass!( . /// Lint for items marked `pub` that aren't reachable from other crates. . UnreachablePub => [UNREACHABLE_PUB] . ); . . impl UnreachablePub { 56 ( 0.00%) fn perform_lint( . &self, . cx: &LateContext<'_>, . what: &str, . def_id: LocalDefId, . vis: &hir::Visibility<'_>, . span: Span, . exportable: bool, . ) { 7 ( 0.00%) let mut applicability = Applicability::MachineApplicable; 14 ( 0.00%) match vis.node { 4 ( 0.00%) hir::VisibilityKind::Public if !cx.access_levels.is_reachable(def_id) => { . if span.from_expansion() { . applicability = Applicability::MaybeIncorrect; . } . let def_span = cx.tcx.sess.source_map().guess_head_span(span); . cx.struct_span_lint(UNREACHABLE_PUB, def_span, |lint| { . let mut err = lint.build(&format!("unreachable `pub` {}", what)); . let replacement = if cx.tcx.features().crate_visibility_modifier { . "crate" -- line 1379 ---------------------------------------- -- line 1391 ---------------------------------------- . if exportable { . err.help("or consider exporting it for use by other crates"); . } . err.emit(); . }); . } . _ => {} . } 35 ( 0.00%) } . } . . impl<'tcx> LateLintPass<'tcx> for UnreachablePub { . fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) { 56 ( 0.00%) self.perform_lint(cx, "item", item.def_id, &item.vis, item.span, true); . } . . fn check_foreign_item(&mut self, cx: &LateContext<'_>, foreign_item: &hir::ForeignItem<'tcx>) { . self.perform_lint( . cx, . "item", . foreign_item.def_id, . &foreign_item.vis, -- line 1412 ---------------------------------------- -- line 1493 ---------------------------------------- . . // Let's go for a walk! . let mut visitor = WalkAssocTypes { err }; . visitor.visit_ty(ty); . } . } . . impl<'tcx> LateLintPass<'tcx> for TypeAliasBounds { 49 ( 0.00%) fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) { 14 ( 0.00%) let hir::ItemKind::TyAlias(ty, type_alias_generics) = &item.kind else { . return . }; . if let hir::TyKind::OpaqueDef(..) = ty.kind { . // Bounds are respected for `type X = impl Trait` . return; . } . let mut suggested_changing_assoc_types = false; . // There must not be a where clause -- line 1510 ---------------------------------------- -- line 1554 ---------------------------------------- . if !suggested_changing_assoc_types { . TypeAliasBounds::suggest_changing_assoc_types(ty, &mut err); . suggested_changing_assoc_types = true; . } . err.emit(); . }); . } . } 56 ( 0.00%) } . } . . declare_lint_pass!( . /// Lint constants that are erroneous. . /// Without this lint, we might not get any diagnostic if the constant is . /// unused within this crate, even though downstream crates can't use it . /// without producing an error. . UnusedBrokenConst => [] . ); . . impl<'tcx> LateLintPass<'tcx> for UnusedBrokenConst { . fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) { 35 ( 0.00%) match it.kind { . hir::ItemKind::Const(_, body_id) => { . let def_id = cx.tcx.hir().body_owner_def_id(body_id).to_def_id(); . // trigger the query once for all constants since that will already report the errors . // FIXME: Use ensure here . let _ = cx.tcx.const_eval_poly(def_id); . } . hir::ItemKind::Static(_, _, body_id) => { . let def_id = cx.tcx.hir().body_owner_def_id(body_id).to_def_id(); -- line 1583 ---------------------------------------- -- line 1626 ---------------------------------------- . . declare_lint_pass!( . /// Lint for trait and lifetime bounds that don't depend on type parameters . /// which either do nothing, or stop the item from being used. . TrivialConstraints => [TRIVIAL_BOUNDS] . ); . . impl<'tcx> LateLintPass<'tcx> for TrivialConstraints { 63 ( 0.00%) fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'tcx>) { . use rustc_middle::ty::fold::TypeFoldable; . use rustc_middle::ty::PredicateKind::*; . 28 ( 0.00%) if cx.tcx.features().trivial_bounds { . let predicates = cx.tcx.predicates_of(item.def_id); . for &(predicate, span) in predicates.predicates { . let predicate_kind_name = match predicate.kind().skip_binder() { . Trait(..) => "trait", . TypeOutlives(..) | . RegionOutlives(..) => "lifetime", . . // Ignore projections, as they can only be global -- line 1646 ---------------------------------------- -- line 1663 ---------------------------------------- . or lifetime parameters", . predicate_kind_name, predicate . )) . .emit() . }); . } . } . } 56 ( 0.00%) } . } . . declare_lint_pass!( . /// Does nothing as a lint pass, but registers some `Lint`s . /// which are used by other parts of the compiler. . SoftLints => [ . WHILE_TRUE, . BOX_POINTERS, -- line 1679 ---------------------------------------- -- line 1880 ---------------------------------------- . . impl UnnameableTestItems { . pub fn new() -> Self { . Self { boundary: None, items_nameable: true } . } . } . . impl<'tcx> LateLintPass<'tcx> for UnnameableTestItems { 35 ( 0.00%) fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) { 14 ( 0.00%) if self.items_nameable { 14 ( 0.00%) if let hir::ItemKind::Mod(..) = it.kind { . } else { 7 ( 0.00%) self.items_nameable = false; 21 ( 0.00%) self.boundary = Some(it.def_id); . } . return; . } . . let attrs = cx.tcx.hir().attrs(it.hir_id()); . if let Some(attr) = cx.sess().find_by_name(attrs, sym::rustc_test_marker) { . cx.struct_span_lint(UNNAMEABLE_TEST_ITEMS, attr.span, |lint| { . lint.build("cannot test inner items").emit() . }); . } 42 ( 0.00%) } . . fn check_item_post(&mut self, _cx: &LateContext<'_>, it: &hir::Item<'_>) { 42 ( 0.00%) if !self.items_nameable && self.boundary == Some(it.def_id) { 7 ( 0.00%) self.items_nameable = true; . } . } . } . . declare_lint! { . /// The `keyword_idents` lint detects edition keywords being used as an . /// identifier. . /// -- line 1916 ---------------------------------------- -- line 1958 ---------------------------------------- . declare_lint_pass!( . /// Check for uses of edition keywords used as an identifier. . KeywordIdents => [KEYWORD_IDENTS] . ); . . struct UnderMacro(bool); . . impl KeywordIdents { 6,720 ( 0.01%) fn check_tokens(&mut self, cx: &EarlyContext<'_>, tokens: TokenStream) { 65,382 ( 0.09%) for tt in tokens.into_trees() { 9,444 ( 0.01%) match tt { . // Only report non-raw idents. 16,376 ( 0.02%) TokenTree::Token(token) => { 22,334 ( 0.03%) if let Some((ident, false)) = token.ident() { 7,944 ( 0.01%) self.check_ident_token(cx, UnderMacro(true), ident); . } . } 1,256 ( 0.00%) TokenTree::Delimited(_, _, tts) => self.check_tokens(cx, tts), . } . } 6,720 ( 0.01%) } . 32,088 ( 0.04%) fn check_ident_token( . &mut self, . cx: &EarlyContext<'_>, . UnderMacro(under_macro): UnderMacro, . ident: Ident, . ) { 10,696 ( 0.01%) let next_edition = match cx.sess().edition() { . Edition::Edition2015 => { . match ident.name { . kw::Async | kw::Await | kw::Try => Edition::Edition2018, . . // rust-lang/rust#56327: Conservatively do not . // attempt to report occurrences of `dyn` within . // macro definitions or invocations, because `dyn` . // can legitimately occur as a contextual keyword -- line 1994 ---------------------------------------- -- line 2020 ---------------------------------------- . .span_suggestion( . ident.span, . "you can use a raw identifier to stay compatible", . format!("r#{}", ident), . Applicability::MachineApplicable, . ) . .emit() . }); 18,718 ( 0.03%) } . } . . impl EarlyLintPass for KeywordIdents { . fn check_mac_def(&mut self, cx: &EarlyContext<'_>, mac_def: &ast::MacroDef, _id: ast::NodeId) { 15 ( 0.00%) self.check_tokens(cx, mac_def.body.inner_tokens()); . } . fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &ast::MacCall) { 1,045 ( 0.00%) self.check_tokens(cx, mac.args.inner_tokens()); . } . fn check_ident(&mut self, cx: &EarlyContext<'_>, ident: Ident) { 1,376 ( 0.00%) self.check_ident_token(cx, UnderMacro(false), ident); . } . } . 2 ( 0.00%) declare_lint_pass!(ExplicitOutlivesRequirements => [EXPLICIT_OUTLIVES_REQUIREMENTS]); . . impl ExplicitOutlivesRequirements { . fn lifetimes_outliving_lifetime<'tcx>( . inferred_outlives: &'tcx [(ty::Predicate<'tcx>, Span)], . index: u32, . ) -> Vec> { . inferred_outlives . .iter() -- line 2051 ---------------------------------------- -- line 2179 ---------------------------------------- . } . } . merged . } . } . } . . impl<'tcx> LateLintPass<'tcx> for ExplicitOutlivesRequirements { 63 ( 0.00%) fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) { . use rustc_middle::middle::resolve_lifetime::Region; . 28 ( 0.00%) let infer_static = cx.tcx.features().infer_static_outlives_requirements; 7 ( 0.00%) let def_id = item.def_id; 49 ( 0.00%) if let hir::ItemKind::Struct(_, ref hir_generics) . | hir::ItemKind::Enum(_, ref hir_generics) . | hir::ItemKind::Union(_, ref hir_generics) = item.kind . { . let inferred_outlives = cx.tcx.inferred_outlives_of(def_id); . if inferred_outlives.is_empty() { . return; . } . -- line 2200 ---------------------------------------- -- line 2338 ---------------------------------------- . .map(|span| (span, "".to_owned())) . .collect::>(), . Applicability::MachineApplicable, . ) . .emit(); . }); . } . } 56 ( 0.00%) } . } . . declare_lint! { . /// The `incomplete_features` lint detects unstable features enabled with . /// the [`feature` attribute] that may function improperly in some or all . /// cases. . /// . /// [`feature` attribute]: https://doc.rust-lang.org/nightly/unstable-book/ -- line 2354 ---------------------------------------- 2,349 ( 0.00%) -------------------------------------------------------------------------------- -- 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, . { 3,800 ( 0.01%) SESSION_GLOBALS.with(f) . } . . #[inline] . pub fn create_default_session_globals_then(f: impl FnOnce() -> R) -> R { . create_session_globals_then(edition::DEFAULT_EDITION, f) . } . . // If this ever becomes non thread-local, `decode_syntax_context` . // and `decode_expn_id` will need to be updated to handle concurrent . // deserialization. . scoped_tls::scoped_thread_local!(static SESSION_GLOBALS: SessionGlobals); . . // FIXME: We should use this enum or something like it to get rid of the . // use of magic `/rust/1.x/...` paths across the board. 13 ( 0.00%) #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd)] 620 ( 0.00%) #[derive(Decodable)] . pub enum RealFileName { . LocalPath(PathBuf), . /// For remapped paths (namely paths into libstd that have been mapped . /// to the appropriate spot on the local host's file system, and local file . /// system paths that have been remapped with `FilePathMapping`), . Remapped { . /// `local_path` is the (host-dependent) local path to the file. This is . /// None if the file was imported from another crate -- line 173 ---------------------------------------- -- line 179 ---------------------------------------- . } . . impl Hash for RealFileName { . fn hash(&self, state: &mut H) { . // To prevent #70924 from happening again we should only hash the . // remapped (virtualized) path if that exists. This is because . // virtualized paths to sysroot crates (/rust/$hash or /rust/$version) . // remain stable even if the corresponding local_path changes 1,575 ( 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> { 2 ( 0.00%) encoder.emit_enum(|encoder| match *self { . RealFileName::LocalPath(ref local_path) => { 8 ( 0.00%) encoder.emit_enum_variant("LocalPath", 0, 1, |encoder| { . encoder.emit_enum_variant_arg(true, |encoder| local_path.encode(encoder))?; . Ok(()) . }) . } . . RealFileName::Remapped { ref local_path, ref virtual_name } => encoder . .emit_enum_variant("Remapped", 1, 2, |encoder| { . // For privacy and build reproducibility, we must not embed host-dependant path in artifacts -- line 205 ---------------------------------------- -- line 224 ---------------------------------------- . p.as_ref().map(PathBuf::as_path) . } . } . } . . /// Returns the path suitable for reading from the file system on the local host, . /// if this information exists. . /// Avoid embedding this in build artifacts; see `remapped_path_if_available()` for that. 2 ( 0.00%) pub fn into_local_path(self) -> Option { 2 ( 0.00%) match self { . RealFileName::LocalPath(p) => Some(p), . RealFileName::Remapped { local_path: p, virtual_name: _ } => p, . } 3 ( 0.00%) } . . /// Returns the path suitable for embedding into build artifacts. This would still . /// be a local path if it has not been remapped. A remapped path will not correspond . /// to a valid file system path: see `local_path_if_available()` for something that . /// is more likely to return paths into the local host file system. . pub fn remapped_path_if_available(&self) -> &Path { 1,256 ( 0.00%) match self { . RealFileName::LocalPath(p) . | RealFileName::Remapped { local_path: _, virtual_name: p } => &p, . } 2 ( 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 { 1 ( 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> { 1 ( 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. 3,268 ( 0.00%) #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash)] 3,748 ( 0.01%) #[derive(Decodable, Encodable)] . pub enum FileName { . Real(RealFileName), . /// Call to `quote!`. 1 ( 0.00%) QuoteExpansion(u64), . /// Command line. . Anon(u64), . /// Hack in `src/librustc_ast/parse.rs`. . // FIXME(jseyfried) . MacroExpansion(u64), . ProcMacroSourceCode(u64), . /// Strings provided as `--cfg [cfgspec]` stored in a `crate_cfg`. . CfgSpec(u64), -- line 285 ---------------------------------------- -- line 288 ---------------------------------------- . /// Custom sources for explicit parser calls from plugins and drivers. . Custom(String), . DocTest(PathBuf, isize), . /// Post-substitution inline assembly from LLVM. . InlineAsm(u64), . } . . impl From for FileName { 7 ( 0.00%) fn from(p: PathBuf) -> Self { 2 ( 0.00%) assert!(!p.to_string_lossy().ends_with('>')); 6 ( 0.00%) FileName::Real(RealFileName::LocalPath(p)) 7 ( 0.00%) } . } . 4 ( 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<'_> { 4 ( 0.00%) fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { . use FileName::*; 6 ( 0.00%) match *self.inner { . Real(ref name) => { 6 ( 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, ""), . } 5 ( 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::*; 628 ( 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. 1 ( 0.00%) pub fn prefer_local(&self) -> FileNameDisplay<'_> { . FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Local } 2 ( 0.00%) } . . pub fn display(&self, display_pref: FileNameDisplayPreference) -> FileNameDisplay<'_> { . FileNameDisplay { inner: self, display_pref } . } . . pub fn macro_expansion_source_code(src: &str) -> FileName { . let mut hasher = StableHasher::new(); . src.hash(&mut hasher); -- line 375 ---------------------------------------- -- line 383 ---------------------------------------- . } . . pub fn proc_macro_source_code(src: &str) -> FileName { . let mut hasher = StableHasher::new(); . src.hash(&mut hasher); . FileName::ProcMacroSourceCode(hasher.finish()) . } . 5 ( 0.00%) pub fn cfg_spec_source_code(src: &str) -> FileName { . let mut hasher = StableHasher::new(); . src.hash(&mut hasher); 2 ( 0.00%) FileName::QuoteExpansion(hasher.finish()) 5 ( 0.00%) } . . pub fn cli_crate_attr_source_code(src: &str) -> FileName { . let mut hasher = StableHasher::new(); . src.hash(&mut hasher); . FileName::CliCrateAttr(hasher.finish()) . } . . pub fn doc_test_source_code(path: PathBuf, line: isize) -> FileName { -- line 403 ---------------------------------------- -- line 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 { 23,837 ( 0.03%) self.lo.0 == 0 && self.hi.0 == 0 . } . /// Returns `true` if `self` fully encloses `other`. . pub fn contains(self, other: Self) -> bool { . 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 -- line 501 ---------------------------------------- -- line 502 ---------------------------------------- . // 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 { 17,960 ( 0.02%) fn partial_cmp(&self, rhs: &Self) -> Option { 13,470 ( 0.02%) PartialOrd::partial_cmp(&self.data(), &rhs.data()) 17,960 ( 0.02%) } . } . impl Ord for Span { . fn cmp(&self, rhs: &Self) -> Ordering { . Ord::cmp(&self.data(), &rhs.data()) . } . } . . /// A collection of `Span`s. -- line 520 ---------------------------------------- -- line 532 ---------------------------------------- . } . . impl Span { . #[inline] . pub fn lo(self) -> BytePos { . self.data().lo . } . #[inline] 2,007 ( 0.00%) pub fn with_lo(self, lo: BytePos) -> Span { . self.data().with_lo(lo) 1,338 ( 0.00%) } . #[inline] 1,160 ( 0.00%) pub fn hi(self) -> BytePos { . self.data().hi 1,160 ( 0.00%) } . #[inline] 2,610 ( 0.00%) pub fn with_hi(self, hi: BytePos) -> Span { . self.data().with_hi(hi) 1,740 ( 0.00%) } . #[inline] . pub fn ctxt(self) -> SyntaxContext { . self.data_untracked().ctxt . } . #[inline] 90 ( 0.00%) pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span { . self.data_untracked().with_ctxt(ctxt) 54 ( 0.00%) } . #[inline] . pub fn parent(self) -> Option { . self.data().parent . } . #[inline] . pub fn with_parent(self, ctxt: Option) -> Span { . self.data().with_parent(ctxt) . } -- line 566 ---------------------------------------- -- line 671 ---------------------------------------- . pub fn find_ancestor_inside(mut self, outer: Span) -> Option { . while !outer.contains(self) { . self = self.parent_callsite()?; . } . Some(self) . } . . /// Edition of the crate from which this span came. 147 ( 0.00%) pub fn edition(self) -> edition::Edition { . self.ctxt().edition() 98 ( 0.00%) } . . #[inline] . pub fn rust_2015(self) -> bool { 5 ( 0.00%) self.edition() == edition::Edition::Edition2015 . } . . #[inline] . pub fn rust_2018(self) -> bool { 88 ( 0.00%) self.edition() >= edition::Edition::Edition2018 . } . . #[inline] . pub fn rust_2021(self) -> bool { . self.edition() >= edition::Edition::Edition2021 . } . . /// Returns the source callee. -- line 698 ---------------------------------------- -- line 707 ---------------------------------------- . } . let expn_data = self.ctxt().outer_expn_data(); . if !expn_data.is_root() { Some(source_callee(expn_data)) } else { None } . } . . /// Checks if a span is "internal" to a macro in which `#[unstable]` . /// items can be used (that is, a macro marked with . /// `#[allow_internal_unstable]`). 5 ( 0.00%) pub fn allows_unstable(self, feature: Symbol) -> bool { 1 ( 0.00%) self.ctxt() . .outer_expn_data() . .allow_internal_unstable . .map_or(false, |features| features.iter().any(|&f| f == feature)) 4 ( 0.00%) } . . /// Checks if this span arises from a compiler desugaring of kind `kind`. . pub fn is_desugaring(self, kind: DesugaringKind) -> bool { . match self.ctxt().outer_expn_data().kind { . ExpnKind::Desugaring(k) => k == kind, . _ => false, . } . } -- line 728 ---------------------------------------- -- line 767 ---------------------------------------- . . /// Returns a `Span` that would enclose both `self` and `end`. . /// . /// ```text . /// ____ ___ . /// self lorem ipsum end . /// ^^^^^^^^^^^^^^^^^^^^ . /// ``` 29,524 ( 0.04%) 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. 5,368 ( 0.01%) if span_data.ctxt != end_data.ctxt { . if span_data.ctxt == SyntaxContext::root() { . return end; . } else if end_data.ctxt == SyntaxContext::root() { . return self; . } . // Both spans fall within a macro. . // FIXME(estebank): check if it is the *same* macro. . } . Span::new( . cmp::min(span_data.lo, end_data.lo), . cmp::max(span_data.hi, end_data.hi), . if span_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt }, 18,788 ( 0.03%) if span_data.parent == end_data.parent { span_data.parent } else { None }, . ) 24,156 ( 0.03%) } . . /// Returns a `Span` between the end of `self` to the beginning of `end`. . /// . /// ```text . /// ____ ___ . /// self lorem ipsum end . /// ^^^^^^^^^^^^^ . /// ``` -- line 804 ---------------------------------------- -- line 815 ---------------------------------------- . . /// Returns a `Span` from the beginning of `self` until the beginning of `end`. . /// . /// ```text . /// ____ ___ . /// self lorem ipsum end . /// ^^^^^^^^^^^^^^^^^ . /// ``` 11 ( 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. 2 ( 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 }, 7 ( 0.00%) if span_data.parent == end_data.parent { span_data.parent } else { None }, . ) 9 ( 0.00%) } . . pub fn from_inner(self, inner: InnerSpan) -> Span { . let span = self.data(); . Span::new( . span.lo + BytePos::from_usize(inner.start), . span.lo + BytePos::from_usize(inner.end), . span.ctxt, . span.parent, . ) . } . . /// Equivalent of `Span::def_site` from the proc macro API, . /// except that the location is taken from the `self` span. . pub fn with_def_site_ctxt(self, expn_id: ExpnId) -> Span { 2 ( 0.00%) self.with_ctxt_from_mark(expn_id, Transparency::Opaque) . } . . /// Equivalent of `Span::call_site` from the proc macro API, . /// except that the location is taken from the `self` span. . pub fn with_call_site_ctxt(self, expn_id: ExpnId) -> Span { 2 ( 0.00%) self.with_ctxt_from_mark(expn_id, Transparency::Transparent) . } . . /// Equivalent of `Span::mixed_site` from the proc macro API, . /// except that the location is taken from the `self` span. . pub fn with_mixed_site_ctxt(self, expn_id: ExpnId) -> Span { . self.with_ctxt_from_mark(expn_id, Transparency::SemiTransparent) . } . . /// Produces a span with the same location as `self` and context produced by a macro with the . /// given ID and transparency, assuming that macro was defined directly and not produced by . /// some other macro (which is the case for built-in and procedural macros). 24 ( 0.00%) pub fn with_ctxt_from_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span { . self.with_ctxt(SyntaxContext::root().apply_mark(expn_id, transparency)) 14 ( 0.00%) } . . #[inline] . pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span { . let span = self.data(); . span.with_ctxt(span.ctxt.apply_mark(expn_id, transparency)) . } . . #[inline] -- line 892 ---------------------------------------- -- line 901 ---------------------------------------- . pub fn adjust(&mut self, expn_id: ExpnId) -> Option { . let mut span = self.data(); . let mark = span.ctxt.adjust(expn_id); . *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark . } . . #[inline] 45 ( 0.00%) pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option { 30 ( 0.00%) let mut span = self.data(); 25 ( 0.00%) let mark = span.ctxt.normalize_to_macros_2_0_and_adjust(expn_id); 45 ( 0.00%) *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark 50 ( 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] 16 ( 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()) 14 ( 0.00%) } . . #[inline] . pub fn normalize_to_macro_rules(self) -> Span { . let span = self.data(); . span.with_ctxt(span.ctxt.normalize_to_macro_rules()) . } . } . -- line 948 ---------------------------------------- -- line 958 ---------------------------------------- . . /// What label should we attach to this span (if any)? . pub label: Option, . } . . impl Default for Span { . fn default() -> Self { . DUMMY_SP 2 ( 0.00%) } . } . . impl Encodable for Span { . default fn encode(&self, s: &mut E) -> Result<(), E::Error> { . let span = self.data(); . s.emit_struct(false, |s| { . s.emit_struct_field("lo", true, |s| span.lo.encode(s))?; . s.emit_struct_field("hi", false, |s| span.hi.encode(s)) -- line 974 ---------------------------------------- -- line 990 ---------------------------------------- . /// any spans that are debug-printed during the closure's execution. . /// . /// Normally, the global `TyCtxt` is used to retrieve the `SourceMap` . /// (see `rustc_interface::callbacks::span_debug1`). However, some parts . /// of the compiler (e.g. `rustc_parse`) may debug-print `Span`s before . /// a `TyCtxt` is available. In this case, we fall back to . /// the `SourceMap` provided to this function. If that is not available, . /// we fall back to printing the raw `Span` field values. 9 ( 0.00%) pub fn with_source_map T>(source_map: Lrc, f: F) -> T { . with_session_globals(|session_globals| { 2 ( 0.00%) *session_globals.source_map.borrow_mut() = Some(source_map); . }); . struct ClearSourceMap; . impl Drop for ClearSourceMap { . fn drop(&mut self) { . with_session_globals(|session_globals| { 1 ( 0.00%) session_globals.source_map.borrow_mut().take(); . }); . } . } . . let _guard = ClearSourceMap; 4 ( 0.00%) f() 8 ( 0.00%) } . . pub fn debug_with_source_map( . span: Span, . f: &mut fmt::Formatter<'_>, . source_map: &SourceMap, . ) -> fmt::Result { . write!(f, "{} ({:?})", source_map.span_to_diagnostic_string(span), span.ctxt()) . } -- line 1021 ---------------------------------------- -- line 1048 ---------------------------------------- . . impl MultiSpan { . #[inline] . pub fn new() -> MultiSpan { . MultiSpan { primary_spans: vec![], span_labels: vec![] } . } . . pub fn from_span(primary_span: Span) -> MultiSpan { 55 ( 0.00%) MultiSpan { primary_spans: vec![primary_span], span_labels: vec![] } . } . . pub fn from_spans(mut vec: Vec) -> MultiSpan { . vec.sort(); . MultiSpan { primary_spans: vec, span_labels: vec![] } . } . . pub fn push_span_label(&mut self, span: Span, label: String) { . self.span_labels.push((span, label)); . } . . /// Selects the first primary span (if any). . pub fn primary_span(&self) -> Option { . self.primary_spans.first().cloned() 11 ( 0.00%) } . . /// Returns all primary spans. . pub fn primary_spans(&self) -> &[Span] { . &self.primary_spans . } . . /// Returns `true` if any of the primary spans are displayable. . pub fn has_primary_spans(&self) -> bool { -- line 1079 ---------------------------------------- -- line 1139 ---------------------------------------- . . /// Returns `true` if any of the span labels is displayable. . pub fn has_span_labels(&self) -> bool { . self.span_labels.iter().any(|(sp, _)| !sp.is_dummy()) . } . } . . impl From for MultiSpan { 55 ( 0.00%) fn from(span: Span) -> MultiSpan { . MultiSpan::from_span(span) 55 ( 0.00%) } . } . . impl From> for MultiSpan { . fn from(spans: Vec) -> MultiSpan { . MultiSpan::from_spans(spans) . } . } . . /// Identifies an offset of a multi-byte character in a `SourceFile`. 11 ( 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`. 268 ( 0.00%) #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)] . pub enum NonNarrowChar { . /// Represents a zero-width character. . ZeroWidth(BytePos), . /// Represents a wide (full-width) character. . Wide(BytePos), . /// Represents a tab character, represented visually with a width of 4 characters. . Tab(BytePos), . } -- line 1176 ---------------------------------------- -- line 1201 ---------------------------------------- . } . } . } . . impl Add for NonNarrowChar { . type Output = Self; . . fn add(self, rhs: BytePos) -> Self { 466 ( 0.00%) match self { . NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs), . NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs), . NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs), . } . } . } . . impl Sub for NonNarrowChar { . type Output = Self; . 134 ( 0.00%) fn sub(self, rhs: BytePos) -> Self { 466 ( 0.00%) match self { . NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs), . NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs), . NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs), . } 402 ( 0.00%) } . } . . /// Identifies an offset of a character that was normalized away from `SourceFile`. . #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)] . pub struct NormalizedPos { . /// The absolute offset of the character in the `SourceMap`. . pub pos: BytePos, . /// The difference between original and normalized string at position. . pub diff: u32, . } . 3 ( 0.00%) #[derive(PartialEq, Eq, Clone, Debug)] . pub enum ExternalSource { . /// No external source has to be loaded, since the `SourceFile` represents a local crate. . Unneeded, . Foreign { . kind: ExternalSourceKind, . /// This SourceFile's byte-offset within the source_map of its original crate. . original_start_pos: BytePos, . /// The end of this SourceFile within the source_map of its original crate. -- line 1246 ---------------------------------------- -- line 1267 ---------------------------------------- . _ => None, . } . } . } . . #[derive(Debug)] . pub struct OffsetOverflowError; . 626 ( 0.00%) #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)] . pub enum SourceFileHashAlgorithm { . Md5, . Sha1, . Sha256, . } . . impl FromStr for SourceFileHashAlgorithm { . type Err = (); -- line 1283 ---------------------------------------- -- line 1290 ---------------------------------------- . _ => Err(()), . } . } . } . . rustc_data_structures::impl_stable_hash_via_hash!(SourceFileHashAlgorithm); . . /// The hash of the on-disk source file used for debug info. 6 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, Debug)] 1,252 ( 0.00%) #[derive(HashStable_Generic, Encodable, Decodable)] . pub struct SourceFileHash { . pub kind: SourceFileHashAlgorithm, . value: [u8; 32], . } . . impl SourceFileHash { . pub fn new(kind: SourceFileHashAlgorithm, src: &str) -> SourceFileHash { . let mut hash = SourceFileHash { kind, value: Default::default() }; . let len = hash.hash_len(); . let value = &mut hash.value[..len]; . let data = src.as_bytes(); . match kind { . SourceFileHashAlgorithm::Md5 => { 6 ( 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 { 6 ( 0.00%) match self.kind { . SourceFileHashAlgorithm::Md5 => 16, . SourceFileHashAlgorithm::Sha1 => 20, . SourceFileHashAlgorithm::Sha256 => 32, . } . } . } . . /// A single source in the [`SourceMap`]. 58 ( 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. 1 ( 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. 1 ( 0.00%) pub name_hash: u128, . /// Indicates which crate this `SourceFile` was imported from. 1 ( 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)?; . 4 ( 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 { 2 ( 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); . 2 ( 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))?; 3 ( 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))?; 11 ( 0.00%) s.emit_struct_field("cnum", false, |s| self.cnum.encode(s)) . }) . } . } . . impl Decodable for SourceFile { 2,817 ( 0.00%) fn decode(d: &mut D) -> SourceFile { . d.read_struct(|d| { . let name: FileName = d.read_struct_field("name", |d| Decodable::decode(d)); . let src_hash: SourceFileHash = . d.read_struct_field("src_hash", |d| Decodable::decode(d)); . let start_pos: BytePos = d.read_struct_field("start_pos", |d| Decodable::decode(d)); . let end_pos: BytePos = d.read_struct_field("end_pos", |d| Decodable::decode(d)); . let lines: Vec = d.read_struct_field("lines", |d| { . let num_lines: u32 = Decodable::decode(d); 313 ( 0.00%) let mut lines = Vec::with_capacity(num_lines as usize); . . if num_lines > 0 { . // Read the number of bytes used per diff. . let bytes_per_diff: u8 = Decodable::decode(d); . . // Read the first element. . let mut line_start: BytePos = Decodable::decode(d); . lines.push(line_start); . . for _ in 1..num_lines { 636,706 ( 0.87%) let diff = match bytes_per_diff { . 1 => d.read_u8() as u32, . 2 => d.read_u16() as u32, . 4 => d.read_u32(), . _ => unreachable!(), . }; . . line_start = line_start + BytePos(diff); . -- line 1480 ---------------------------------------- -- line 1483 ---------------------------------------- . } . . lines . }); . let multibyte_chars: Vec = . d.read_struct_field("multibyte_chars", |d| Decodable::decode(d)); . let non_narrow_chars: Vec = . d.read_struct_field("non_narrow_chars", |d| Decodable::decode(d)); 626 ( 0.00%) let name_hash: u128 = d.read_struct_field("name_hash", |d| Decodable::decode(d)); . let normalized_pos: Vec = . d.read_struct_field("normalized_pos", |d| Decodable::decode(d)); . let cnum: CrateNum = d.read_struct_field("cnum", |d| Decodable::decode(d)); 3,443 ( 0.00%) SourceFile { 2,504 ( 0.00%) name, . start_pos, . end_pos, . src: None, 1,252 ( 0.00%) src_hash, . // Unused - the metadata decoder will construct . // a new SourceFile, filling in `external_src` properly . external_src: Lock::new(ExternalSource::Unneeded), 1,252 ( 0.00%) lines, 1,252 ( 0.00%) multibyte_chars, 1,252 ( 0.00%) non_narrow_chars, 1,252 ( 0.00%) normalized_pos, . name_hash, . cnum, . } . }) 2,817 ( 0.00%) } . } . . impl fmt::Debug for SourceFile { . fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { . write!(fmt, "SourceFile({:?})", self.name) . } . } . . impl SourceFile { 22 ( 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); 6 ( 0.00%) let normalized_pos = normalize_src(&mut src, start_pos); . . let name_hash = { . let mut hasher: StableHasher = StableHasher::new(); 4 ( 0.00%) name.hash(&mut hasher); . hasher.finish::() . }; 4 ( 0.00%) let end_pos = start_pos.to_usize() + src.len(); 6 ( 0.00%) assert!(end_pos <= u32::MAX as usize); . 24 ( 0.00%) let (lines, multibyte_chars, non_narrow_chars) = 4 ( 0.00%) analyze_source_file::analyze_source_file(&src, start_pos); . 34 ( 0.00%) SourceFile { . name, . src: Some(Lrc::new(src)), 22 ( 0.00%) src_hash, . external_src: Lock::new(ExternalSource::Unneeded), . start_pos, . end_pos: Pos::from_usize(end_pos), 8 ( 0.00%) lines, 8 ( 0.00%) multibyte_chars, 8 ( 0.00%) non_narrow_chars, 8 ( 0.00%) normalized_pos, . name_hash, . cnum: LOCAL_CRATE, . } 18 ( 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. -- line 1565 ---------------------------------------- -- line 1627 ---------------------------------------- . Some(Cow::Owned(String::from(get_until_newline(src, begin)))) . } else { . None . } . } . . pub fn is_real_file(&self) -> bool { . self.name.is_real() 314 ( 0.00%) } . . pub fn is_imported(&self) -> bool { . self.src.is_none() 3,463 ( 0.00%) } . . pub fn count_lines(&self) -> usize { . self.lines.len() . } . . /// Finds the line containing the given position. The return value is the . /// index into the `lines` array of this `SourceFile`, not the 1-based line . /// number. If the source_file is empty or the position is located before the . /// first line, `None` is returned. . pub fn lookup_line(&self, pos: BytePos) -> Option { 2,272 ( 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 { 3,028 ( 0.00%) if self.is_empty() { . return self.start_pos..self.end_pos; . } . 2,024 ( 0.00%) assert!(line_index < self.lines.len()); 3,027 ( 0.00%) if line_index == (self.lines.len() - 1) { 3 ( 0.00%) self.lines[line_index]..self.end_pos . } else { 2,016 ( 0.00%) self.lines[line_index]..self.lines[line_index + 1] . } . } . . /// Returns whether or not the file contains the given `SourceMap` byte . /// position. The position one past the end of the file is considered to be . /// contained by the file. This implies that files for which `is_empty` . /// returns true still contain one byte position according to this function. . #[inline] -- line 1674 ---------------------------------------- -- line 1692 ---------------------------------------- . Err(i) if i == 0 => 0, . Err(i) => self.normalized_pos[i - 1].diff, . }; . . BytePos::from_u32(pos.0 - self.start_pos.0 + diff) . } . . /// Converts an absolute `BytePos` to a `CharPos` relative to the `SourceFile`. 2 ( 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; . 6 ( 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; . } . } . 12 ( 0.00%) assert!(self.start_pos.to_u32() + total_extra_bytes <= bpos.to_u32()); 10 ( 0.00%) CharPos(bpos.to_usize() - self.start_pos.to_usize() - total_extra_bytes as usize) 4 ( 0.00%) } . . /// Looks up the file's (1-based) line number and (0-based `CharPos`) column offset, for a . /// given `BytePos`. 7 ( 0.00%) pub fn lookup_file_pos(&self, pos: BytePos) -> (usize, CharPos) { 2 ( 0.00%) let chpos = self.bytepos_to_file_charpos(pos); . match self.lookup_line(pos) { . Some(a) => { . let line = a + 1; // Line numbers start at 1 1 ( 0.00%) let linebpos = self.lines[a]; 2 ( 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); 1 ( 0.00%) assert!(chpos >= linechpos); . (line, col) . } . None => (0, chpos), . } 8 ( 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`. 8 ( 0.00%) pub fn lookup_file_pos_with_col_display(&self, pos: BytePos) -> (usize, CharPos, usize) { 3 ( 0.00%) let (line, col_or_chpos) = self.lookup_file_pos(pos); 2 ( 0.00%) if line > 0 { . let col = col_or_chpos; 1 ( 0.00%) let linebpos = self.lines[line - 1]; . let col_display = { . let start_width_idx = self . .non_narrow_chars . .binary_search_by_key(&linebpos, |x| x.pos()) . .unwrap_or_else(|x| x); . let end_width_idx = self . .non_narrow_chars . .binary_search_by_key(&pos, |x| x.pos()) . .unwrap_or_else(|x| x); . let special_chars = end_width_idx - start_width_idx; . let non_narrow: usize = self.non_narrow_chars[start_width_idx..end_width_idx] . .iter() . .map(|x| x.width()) . .sum(); 5 ( 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) . } 7 ( 0.00%) } . } . . /// Normalizes the source code and records the normalizations. 20 ( 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 18 ( 0.00%) } . . /// Removes UTF-8 BOM, if any. . fn remove_bom(src: &mut String, normalized_pos: &mut Vec) { 2 ( 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) { 2 ( 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])* 10,007 ( 0.01%) $vis struct $ident($inner_vis $inner_ty); . . impl Pos for $ident { . #[inline(always)] . fn from_usize(n: usize) -> $ident { 1,404 ( 0.00%) $ident(n as $inner_ty) . } . . #[inline(always)] . fn to_usize(&self) -> usize { 26,878 ( 0.04%) 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 { 994,241 ( 1.36%) $ident(self.0 + rhs.0) . } . } . . impl Sub for $ident { . type Output = $ident; . . #[inline(always)] . fn sub(self, rhs: $ident) -> $ident { 609,824 ( 0.83%) $ident(self.0 - rhs.0) . } . } . )* . }; . } . . impl_pos! { . /// A byte offset. -- line 1931 ---------------------------------------- -- line 1946 ---------------------------------------- . impl Encodable for BytePos { . fn encode(&self, s: &mut S) -> Result<(), S::Error> { . s.emit_u32(self.0) . } . } . . impl Decodable for BytePos { . fn decode(d: &mut D) -> BytePos { 6,716 ( 0.01%) BytePos(d.read_u32()) . } . } . . // _____________________________________________________________________________ . // Loc, SourceFileAndLine, SourceFileAndBytePos . // . . /// A source code location used for error reporting. -- line 1962 ---------------------------------------- -- line 2079 ---------------------------------------- . /// offsets into the `SourceMap`). Instead, we hash the (file name, line, column) . /// triple, which stays the same even if the containing `SourceFile` has moved . /// within the `SourceMap`. . /// . /// Also note that we are hashing byte offsets for the column, not unicode . /// codepoint offsets. For the purpose of the hash that's sufficient. . /// Also, hashing filenames is expensive so we avoid doing it twice when the . /// span starts and ends in the same file, which is almost always the case. 39,116 ( 0.05%) 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; . 11,140 ( 0.02%) if !ctx.hash_spans() { . return; . } . 27,976 ( 0.04%) let span = self.data_untracked(); 112 ( 0.00%) span.ctxt.hash_stable(ctx, hasher); 16,764 ( 0.02%) span.parent.hash_stable(ctx, hasher); . 11,201 ( 0.02%) if span.is_dummy() { . Hash::hash(&TAG_INVALID_SPAN, hasher); . return; . } . 11,126 ( 0.02%) 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. 22,252 ( 0.03%) let (file, line_lo, col_lo, line_hi, col_hi) = match ctx.span_data_to_lines_and_cols(&span) . { 11,126 ( 0.02%) 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. . 5,563 ( 0.01%) 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; 5,563 ( 0.01%) let len = (span.hi - span.lo).0; . Hash::hash(&col_line, hasher); . Hash::hash(&len, hasher); 44,704 ( 0.06%) } . } 829,347 ( 1.13%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_metadata/src/rmeta/decoder.rs -------------------------------------------------------------------------------- Ir -- line 178 ---------------------------------------- . None . } . fn tcx(self) -> Option> { . None . } . . fn decoder(self, pos: usize) -> DecodeContext<'a, 'tcx> { . let tcx = self.tcx(); 11,714 ( 0.02%) DecodeContext { 1,126 ( 0.00%) opaque: opaque::Decoder::new(self.blob(), pos), . cdata: self.cdata(), . blob: self.blob(), . sess: self.sess().or(tcx.map(|tcx| tcx.sess)), . tcx, . last_source_file_index: 0, . lazy_state: LazyState::NoNode, . alloc_decoding_session: self . .cdata() 910 ( 0.00%) .map(|cdata| cdata.cdata.alloc_decoding_state.new_decoding_session()), . } . } . } . . impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a MetadataBlob { . #[inline] . fn blob(self) -> &'a MetadataBlob { . self -- line 204 ---------------------------------------- -- line 257 ---------------------------------------- . fn tcx(self) -> Option> { . Some(self.1) . } . } . . impl<'a, 'tcx, T: Decodable>> Lazy { . fn decode>(self, metadata: M) -> T { . let mut dcx = metadata.decoder(self.position.get()); 3,260 ( 0.00%) dcx.lazy_state = LazyState::NodeStart(self.position); 1,605 ( 0.00%) T::decode(&mut dcx) . } . } . . impl<'a: 'x, 'tcx: 'x, 'x, T: Decodable>> Lazy<[T]> { . fn decode>( . self, . metadata: M, . ) -> impl ExactSizeIterator + Captures<'a> + Captures<'tcx> + 'x { . let mut dcx = metadata.decoder(self.position.get()); . dcx.lazy_state = LazyState::NodeStart(self.position); 1,042 ( 0.00%) (0..self.meta).map(move |_| T::decode(&mut dcx)) . } . } . . impl<'a, 'tcx> DecodeContext<'a, 'tcx> { . #[inline] . fn tcx(&self) -> TyCtxt<'tcx> { . debug_assert!(self.tcx.is_some(), "missing TyCtxt in DecodeContext"); . self.tcx.unwrap() -- line 285 ---------------------------------------- -- line 292 ---------------------------------------- . . #[inline] . pub fn cdata(&self) -> CrateMetadataRef<'a> { . debug_assert!(self.cdata.is_some(), "missing CrateMetadata in DecodeContext"); . self.cdata.unwrap() . } . . fn map_encoded_cnum_to_current(&self, cnum: CrateNum) -> CrateNum { 1,807 ( 0.00%) if cnum == LOCAL_CRATE { self.cdata().cnum } else { self.cdata().cnum_map[cnum] } . } . 3,122 ( 0.00%) fn read_lazy_with_meta(&mut self, meta: T::Meta) -> Lazy { . let distance = self.read_usize(); 2,998 ( 0.00%) let position = match self.lazy_state { . LazyState::NoNode => bug!("read_lazy_with_meta: outside of a metadata node"), 96 ( 0.00%) LazyState::NodeStart(start) => { . let start = start.get(); 192 ( 0.00%) assert!(distance <= start); . start - distance . } 1,626 ( 0.00%) LazyState::Previous(last_pos) => last_pos.get() + distance, . }; 1,276 ( 0.00%) self.lazy_state = LazyState::Previous(NonZeroUsize::new(position).unwrap()); . Lazy::from_position_and_meta(NonZeroUsize::new(position).unwrap(), meta) 3,122 ( 0.00%) } . . #[inline] . pub fn read_raw_bytes(&mut self, len: usize) -> &'a [u8] { . self.opaque.read_raw_bytes(len) . } . } . . impl<'a, 'tcx> TyDecoder<'tcx> for DecodeContext<'a, 'tcx> { -- line 324 ---------------------------------------- -- line 375 ---------------------------------------- . } else { . bug!("Attempting to decode interpret::AllocId without CrateMetadata") . } . } . } . . impl<'a, 'tcx> Decodable> for CrateNum { . fn decode(d: &mut DecodeContext<'a, 'tcx>) -> CrateNum { 1,513 ( 0.00%) let cnum = CrateNum::from_u32(d.read_u32()); . d.map_encoded_cnum_to_current(cnum) . } . } . . impl<'a, 'tcx> Decodable> for DefIndex { . fn decode(d: &mut DecodeContext<'a, 'tcx>) -> DefIndex { 1,529 ( 0.00%) DefIndex::from_u32(d.read_u32()) . } . } . . impl<'a, 'tcx> Decodable> for ExpnIndex { . fn decode(d: &mut DecodeContext<'a, 'tcx>) -> ExpnIndex { . ExpnIndex::from_u32(d.read_u32()) . } . } . . impl<'a, 'tcx> Decodable> for SyntaxContext { 2,496 ( 0.00%) fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> SyntaxContext { 624 ( 0.00%) let cdata = decoder.cdata(); 624 ( 0.00%) let sess = decoder.sess.unwrap(); 1,248 ( 0.00%) let cname = cdata.root.name; . rustc_span::hygiene::decode_syntax_context(decoder, &cdata.hygiene_context, |_, id| { . debug!("SpecializedDecoder: decoding {}", id); 4 ( 0.00%) cdata . .root . .syntax_contexts . .get(cdata, id) . .unwrap_or_else(|| panic!("Missing SyntaxContext {:?} for crate {:?}", id, cname)) . .decode((cdata, sess)) . }) 3,120 ( 0.00%) } . } . . impl<'a, 'tcx> Decodable> for ExpnId { 973 ( 0.00%) fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> ExpnId { 139 ( 0.00%) let local_cdata = decoder.cdata(); 139 ( 0.00%) let sess = decoder.sess.unwrap(); . . let cnum = CrateNum::decode(decoder); . let index = u32::decode(decoder); . . let expn_id = rustc_span::hygiene::decode_expn_id(cnum, index, |expn_id| { . let ExpnId { krate: cnum, local_id: index } = expn_id; . // Lookup local `ExpnData`s in our own crate data. Foreign `ExpnData`s . // are stored in the owning crate, to avoid duplication. . debug_assert_ne!(cnum, LOCAL_CRATE); 4 ( 0.00%) let crate_data = if cnum == local_cdata.cnum { . local_cdata . } else { . local_cdata.cstore.get_crate_data(cnum) . }; 20 ( 0.00%) let expn_data = crate_data . .root . .expn_data . .get(crate_data, index) . .unwrap() . .decode((crate_data, sess)); 20 ( 0.00%) let expn_hash = crate_data . .root . .expn_hashes . .get(crate_data, index) . .unwrap() . .decode((crate_data, sess)); 40 ( 0.00%) (expn_data, expn_hash) . }); . expn_id 1,112 ( 0.00%) } . } . . impl<'a, 'tcx> Decodable> for Span { 4,968 ( 0.01%) fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Span { 621 ( 0.00%) let ctxt = SyntaxContext::decode(decoder); . let tag = u8::decode(decoder); . 1,242 ( 0.00%) if tag == TAG_PARTIAL_SPAN { . return DUMMY_SP.with_ctxt(ctxt); . } . . debug_assert!(tag == TAG_VALID_SPAN_LOCAL || tag == TAG_VALID_SPAN_FOREIGN); . . let lo = BytePos::decode(decoder); . let len = BytePos::decode(decoder); . let hi = lo + len; . 1,851 ( 0.00%) let Some(sess) = decoder.sess else { . bug!("Cannot decode Span without Session.") . }; . . // There are two possibilities here: . // 1. This is a 'local span', which is located inside a `SourceFile` . // that came from this crate. In this case, we use the source map data . // encoded in this crate. This branch should be taken nearly all of the time. . // 2. This is a 'foreign span', which is located inside a `SourceFile` -- line 476 ---------------------------------------- -- line 492 ---------------------------------------- . // a transitive dependency. . // . // When we encode a foreign span, we adjust its 'lo' and 'high' values . // to be based on the *foreign* crate (e.g. crate C), not the crate . // we are writing metadata for (e.g. crate B). This allows us to . // treat the 'local' and 'foreign' cases almost identically during deserialization: . // we can call `imported_source_files` for the proper crate, and binary search . // through the returned slice using our span. 1,510 ( 0.00%) let imported_source_files = if tag == TAG_VALID_SPAN_LOCAL { . decoder.cdata().imported_source_files(sess) . } else { . // When we encode a proc-macro crate, all `Span`s should be encoded . // with `TAG_VALID_SPAN_LOCAL` . if decoder.cdata().root.is_proc_macro_crate() { . // Decode `CrateNum` as u32 - using `CrateNum::decode` will ICE . // since we don't have `cnum_map` populated. . let cnum = u32::decode(decoder); -- line 508 ---------------------------------------- -- line 527 ---------------------------------------- . . let foreign_data = decoder.cdata().cstore.get_crate_data(cnum); . foreign_data.imported_source_files(sess) . }; . . let source_file = { . // Optimize for the case that most spans within a translated item . // originate from the same source_file. 1,851 ( 0.00%) let last_source_file = &imported_source_files[decoder.last_source_file_index]; . 2,393 ( 0.00%) if lo >= last_source_file.original_start_pos && lo <= last_source_file.original_end_pos . { . last_source_file . } else { . let index = imported_source_files . .binary_search_by_key(&lo, |source_file| source_file.original_start_pos) 552 ( 0.00%) .unwrap_or_else(|index| index - 1); . . // Don't try to cache the index for foreign spans, . // as this would require a map from CrateNums to indices 276 ( 0.00%) if tag == TAG_VALID_SPAN_LOCAL { 276 ( 0.00%) decoder.last_source_file_index = index; . } 552 ( 0.00%) &imported_source_files[index] . } . }; . . // Make sure our binary search above is correct. . debug_assert!( . lo >= source_file.original_start_pos && lo <= source_file.original_end_pos, . "Bad binary search: lo={:?} source_file.original_start_pos={:?} source_file.original_end_pos={:?}", . lo, -- line 558 ---------------------------------------- -- line 565 ---------------------------------------- . hi >= source_file.original_start_pos && hi <= source_file.original_end_pos, . "Bad binary search: hi={:?} source_file.original_start_pos={:?} source_file.original_end_pos={:?}", . hi, . source_file.original_start_pos, . source_file.original_end_pos . ); . . let lo = 2,468 ( 0.00%) (lo + source_file.translated_source_file.start_pos) - source_file.original_start_pos; . let hi = . (hi + source_file.translated_source_file.start_pos) - source_file.original_start_pos; . . // Do not try to decode parent for foreign spans. . Span::new(lo, hi, ctxt, None) 5,589 ( 0.01%) } . } . . impl<'a, 'tcx> Decodable> for &'tcx [thir::abstract_const::Node<'tcx>] { . fn decode(d: &mut DecodeContext<'a, 'tcx>) -> Self { . ty::codec::RefDecodable::decode(d) . } . } . -- line 587 ---------------------------------------- -- line 590 ---------------------------------------- . ty::codec::RefDecodable::decode(d) . } . } . . impl<'a, 'tcx, T: Decodable>> Decodable> . for Lazy . { . fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Self { 77 ( 0.00%) decoder.read_lazy_with_meta(()) . } . } . . impl<'a, 'tcx, T: Decodable>> Decodable> . for Lazy<[T]> . { . fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Self { . let len = decoder.read_usize(); 2,295 ( 0.00%) if len == 0 { Lazy::empty() } else { decoder.read_lazy_with_meta(len) } . } . } . . impl<'a, 'tcx, I: Idx, T: Decodable>> Decodable> . for Lazy> . where . Option: FixedSizeEncoding, . { . fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Self { . let len = decoder.read_usize(); 1,521 ( 0.00%) decoder.read_lazy_with_meta(len) . } . } . . implement_ty_decoder!(DecodeContext<'a, 'tcx>); . . impl<'tcx> MetadataBlob { . crate fn new(metadata_ref: MetadataRef) -> MetadataBlob { . MetadataBlob(Lrc::new(metadata_ref)) -- line 626 ---------------------------------------- -- line 630 ---------------------------------------- . self.blob().starts_with(METADATA_HEADER) . } . . crate fn get_rustc_version(&self) -> String { . Lazy::::from_position(NonZeroUsize::new(METADATA_HEADER.len() + 4).unwrap()) . .decode(self) . } . 27 ( 0.00%) crate fn get_root(&self) -> CrateRoot<'tcx> { 9 ( 0.00%) let slice = &self.blob()[..]; . let offset = METADATA_HEADER.len(); 45 ( 0.00%) let pos = (((slice[offset + 0] as u32) << 24) 18 ( 0.00%) | ((slice[offset + 1] as u32) << 16) 36 ( 0.00%) | ((slice[offset + 2] as u32) << 8) 27 ( 0.00%) | ((slice[offset + 3] as u32) << 0)) as usize; . Lazy::>::from_position(NonZeroUsize::new(pos).unwrap()).decode(self) 45 ( 0.00%) } . . crate fn list_crate_metadata(&self, out: &mut dyn io::Write) -> io::Result<()> { . let root = self.get_root(); . writeln!(out, "Crate info:")?; . writeln!(out, "name {}{}", root.name, root.extra_filename)?; . writeln!(out, "hash {} stable_crate_id {:?}", root.hash, root.stable_crate_id)?; . writeln!(out, "proc_macro {:?}", root.proc_macro_data.is_some())?; . writeln!(out, "=External Dependencies=")?; -- line 654 ---------------------------------------- -- line 666 ---------------------------------------- . } . write!(out, "\n")?; . Ok(()) . } . } . . impl CrateRoot<'_> { . crate fn is_proc_macro_crate(&self) -> bool { 6 ( 0.00%) self.proc_macro_data.is_some() . } . . crate fn name(&self) -> Symbol { 4 ( 0.00%) self.name . } . . crate fn hash(&self) -> Svh { 3 ( 0.00%) self.hash . } . . crate fn stable_crate_id(&self) -> StableCrateId { 6 ( 0.00%) self.stable_crate_id . } . . crate fn triple(&self) -> &TargetTriple { . &self.triple . } . . crate fn decode_crate_deps<'a>( . &self, . metadata: &'a MetadataBlob, . ) -> impl ExactSizeIterator + Captures<'a> { 6 ( 0.00%) self.crate_deps.decode(metadata) . } . } . . impl<'a, 'tcx> CrateMetadataRef<'a> { . fn raw_proc_macro(self, id: DefIndex) -> &'a ProcMacro { . // DefIndex's in root.proc_macro_data have a one-to-one correspondence . // with items in 'raw_proc_macros'. . let pos = self -- line 705 ---------------------------------------- -- line 709 ---------------------------------------- . .unwrap() . .macros . .decode(self) . .position(|i| i == id) . .unwrap(); . &self.raw_proc_macros.unwrap()[pos] . } . 1,144 ( 0.00%) fn opt_item_ident(self, item_index: DefIndex, sess: &Session) -> Option { 832 ( 0.00%) let name = self.def_key(item_index).disambiguated_data.data.get_opt_name()?; 707 ( 0.00%) let span = match self.root.tables.ident_span.get(self, item_index) { . Some(lazy_span) => lazy_span.decode((self, sess)), . None => { . // FIXME: this weird case of a name with no span is specific to `extern crate` . // items, which are supposed to be treated like `use` items and only be encoded . // to metadata as `Export`s, return `None` because that's what all the callers . // expect in this case. 18 ( 0.00%) assert_eq!(self.def_kind(item_index), DefKind::ExternCrate); . return None; . } . }; . Some(Ident::new(name, span)) 1,456 ( 0.00%) } . . fn item_ident(self, item_index: DefIndex, sess: &Session) -> Ident { 7 ( 0.00%) self.opt_item_ident(item_index, sess).expect("no encoded ident for item") . } . . fn maybe_kind(self, item_id: DefIndex) -> Option { 278 ( 0.00%) self.root.tables.kind.get(self, item_id).map(|k| k.decode(self)) . } . 1,112 ( 0.00%) fn kind(self, item_id: DefIndex) -> EntryKind { . self.maybe_kind(item_id).unwrap_or_else(|| { . bug!( . "CrateMetadata::kind({:?}): id not found, in crate {:?} with number {}", . item_id, . self.root.name, . self.cnum, . ) . }) 834 ( 0.00%) } . 1,638 ( 0.00%) fn def_kind(self, item_id: DefIndex) -> DefKind { 941 ( 0.00%) self.root.tables.def_kind.get(self, item_id).map(|k| k.decode(self)).unwrap_or_else(|| { . bug!( . "CrateMetadata::def_kind({:?}): id not found, in crate {:?} with number {}", . item_id, . self.root.name, . self.cnum, . ) . }) 936 ( 0.00%) } . . fn get_span(self, index: DefIndex, sess: &Session) -> Span { 737 ( 0.00%) self.root . .tables . .span . .get(self, index) . .unwrap_or_else(|| panic!("Missing span for {:?}", index)) . .decode((self, sess)) . } . . fn load_proc_macro(self, id: DefIndex, sess: &Session) -> SyntaxExtension { -- line 772 ---------------------------------------- -- line 959 ---------------------------------------- . .tables . .ty . .get(self, id) . .unwrap_or_else(|| panic!("Not a type: {:?}", id)) . .decode((self, tcx)) . } . . fn get_stability(self, id: DefIndex) -> Option { 5 ( 0.00%) self.root.tables.stability.get(self, id).map(|stab| stab.decode(self)) . } . . fn get_const_stability(self, id: DefIndex) -> Option { . self.root.tables.const_stability.get(self, id).map(|stab| stab.decode(self)) . } . . fn get_deprecation(self, id: DefIndex) -> Option { 5 ( 0.00%) self.root.tables.deprecation.get(self, id).map(|depr| depr.decode(self)) . } . . fn get_visibility(self, id: DefIndex) -> ty::Visibility { 201 ( 0.00%) self.root.tables.visibility.get(self, id).unwrap().decode(self) . } . . fn get_impl_data(self, id: DefIndex) -> ImplData { . match self.kind(id) { . EntryKind::Impl(data) => data.decode(self), . _ => bug!(), . } . } -- line 987 ---------------------------------------- -- line 1010 ---------------------------------------- . self.get_impl_data(id).coerce_unsized_info . } . . fn get_impl_trait(self, id: DefIndex, tcx: TyCtxt<'tcx>) -> Option> { . self.root.tables.impl_trait_ref.get(self, id).map(|tr| tr.decode((self, tcx))) . } . . fn get_expn_that_defined(self, id: DefIndex, sess: &Session) -> ExpnId { 670 ( 0.00%) self.root.tables.expn_that_defined.get(self, id).unwrap().decode((self, sess)) . } . . fn get_const_param_default( . self, . tcx: TyCtxt<'tcx>, . id: DefIndex, . ) -> rustc_middle::ty::Const<'tcx> { . self.root.tables.const_defaults.get(self, id).unwrap().decode((self, tcx)) -- line 1026 ---------------------------------------- -- line 1028 ---------------------------------------- . . /// Iterates over all the stability attributes in the given crate. . fn get_lib_features(self, tcx: TyCtxt<'tcx>) -> &'tcx [(Symbol, Option)] { . tcx.arena.alloc_from_iter(self.root.lib_features.decode(self)) . } . . /// Iterates over the language items in the given crate. . fn get_lang_items(self, tcx: TyCtxt<'tcx>) -> &'tcx [(DefId, usize)] { 9 ( 0.00%) tcx.arena.alloc_from_iter( 6 ( 0.00%) self.root . .lang_items . .decode(self) 508 ( 0.00%) .map(|(def_index, index)| (self.local_def_id(def_index), index)), . ) . } . . /// Iterates over the diagnostic items in the given crate. . fn get_diagnostic_items(self) -> DiagnosticItems { . let mut id_to_name = FxHashMap::default(); . let name_to_id = self . .root -- line 1048 ---------------------------------------- -- line 1062 ---------------------------------------- . /// Module here is understood in name resolution sense - it can be a `mod` item, . /// or a crate root, or an enum, or a trait. . fn for_each_module_child( . self, . id: DefIndex, . mut callback: impl FnMut(ModChild), . sess: &Session, . ) { 16 ( 0.00%) if let Some(data) = &self.root.proc_macro_data { . // If we are loading as a proc macro, we want to return . // the view of this crate as a proc macro crate. . if id == CRATE_DEF_INDEX { . for def_index in data.macros.decode(self) { . let raw_macro = self.raw_proc_macro(def_index); . let res = Res::Def( . DefKind::Macro(macro_kind(raw_macro)), . self.local_def_id(def_index), -- line 1078 ---------------------------------------- -- line 1085 ---------------------------------------- . span: ident.span, . }); . } . } . return; . } . . // Iterate over all children. 32 ( 0.00%) if let Some(children) = self.root.tables.children.get(self, id) { 64 ( 0.00%) for child_index in children.decode((self, sess)) { 618 ( 0.00%) if let Some(ident) = self.opt_item_ident(child_index, sess) { 294 ( 0.00%) let kind = self.def_kind(child_index); 196 ( 0.00%) if matches!(kind, DefKind::Macro(..)) { . // FIXME: Macros are currently encoded twice, once as items and once as . // reexports. We ignore the items here and only use the reexports. . continue; . } . let def_id = self.local_def_id(child_index); . let res = Res::Def(kind, def_id); . let vis = self.get_visibility(child_index); . let span = self.get_span(child_index, sess); . . callback(ModChild { ident, res, vis, span }); . . // For non-re-export structs and variants add their constructors to children. . // Re-export lists automatically contain constructors when necessary. 392 ( 0.00%) match kind { . DefKind::Struct => { . if let Some((ctor_def_id, ctor_kind)) = . self.get_ctor_def_id_and_kind(child_index) . { . let ctor_res = . Res::Def(DefKind::Ctor(CtorOf::Struct, ctor_kind), ctor_def_id); . let vis = self.get_visibility(ctor_def_id.index); . callback(ModChild { ident, res: ctor_res, vis, span }); -- line 1119 ---------------------------------------- -- line 1144 ---------------------------------------- . callback(ModChild { ident, res: ctor_res, vis, span }); . } . _ => {} . } . } . } . } . 36 ( 0.00%) match self.kind(id) { 8 ( 0.00%) EntryKind::Mod(exports) => { 274 ( 0.00%) for exp in exports.decode((self, sess)) { . callback(exp); . } . } . EntryKind::Enum(..) | EntryKind::Trait(..) => {} . _ => bug!("`for_each_module_child` is called on a non-module: {:?}", self.def_kind(id)), . } . } . -- line 1162 ---------------------------------------- -- line 1164 ---------------------------------------- . self.root.tables.mir_for_ctfe.get(self, id).is_some() . } . . fn is_item_mir_available(self, id: DefIndex) -> bool { . self.root.tables.mir.get(self, id).is_some() . } . . fn module_expansion(self, id: DefIndex, sess: &Session) -> ExpnId { 938 ( 0.00%) match self.kind(id) { . EntryKind::Mod(_) | EntryKind::Enum(_) | EntryKind::Trait(_) => { . self.get_expn_that_defined(id, sess) . } . _ => panic!("Expected module, found {:?}", self.local_def_id(id)), . } . } . . fn get_optimized_mir(self, tcx: TyCtxt<'tcx>, id: DefIndex) -> Body<'tcx> { -- line 1180 ---------------------------------------- -- line 1299 ---------------------------------------- . EntryKind::Struct(data, _) | EntryKind::Variant(data) => { . let vdata = data.decode(self); . vdata.ctor.map(|index| (self.local_def_id(index), vdata.ctor_kind)) . } . _ => None, . } . } . 12 ( 0.00%) fn get_item_attrs( . self, . id: DefIndex, . sess: &'a Session, . ) -> impl Iterator + 'a { 3 ( 0.00%) self.root . .tables . .attributes . .get(self, id) . .unwrap_or_else(|| { . // Structure and variant constructors don't have any attributes encoded for them, . // but we assume that someone passing a constructor ID actually wants to look at . // the attributes on the corresponding struct or variant. . let def_key = self.def_key(id); -- line 1320 ---------------------------------------- -- line 1322 ---------------------------------------- . let parent_id = def_key.parent.expect("no parent for a constructor"); . self.root . .tables . .attributes . .get(self, parent_id) . .expect("no encoded attributes for a structure or variant") . }) . .decode((self, sess)) 9 ( 0.00%) } . . fn get_struct_field_names( . self, . id: DefIndex, . sess: &'a Session, . ) -> impl Iterator> + 'a { . self.root . .tables -- line 1338 ---------------------------------------- -- line 1421 ---------------------------------------- . } . def_key.parent.and_then(|parent_index| match self.kind(parent_index) { . EntryKind::Trait(_) | EntryKind::TraitAlias => Some(self.local_def_id(parent_index)), . _ => None, . }) . } . . fn get_native_libraries(self, sess: &'a Session) -> impl Iterator + 'a { 6 ( 0.00%) self.root.native_libraries.decode((self, sess)) . } . . fn get_proc_macro_quoted_span(self, index: usize, sess: &Session) -> Span { . self.root . .tables . .proc_macro_quoted_spans . .get(self, index) . .unwrap_or_else(|| panic!("Missing proc macro quoted span: {:?}", index)) -- line 1437 ---------------------------------------- -- line 1450 ---------------------------------------- . self.root.dylib_dependency_formats.decode(self).enumerate().flat_map(|(i, link)| { . let cnum = CrateNum::new(i + 1); . link.map(|link| (self.cnum_map[cnum], link)) . }), . ) . } . . fn get_missing_lang_items(self, tcx: TyCtxt<'tcx>) -> &'tcx [lang_items::LangItem] { 15 ( 0.00%) tcx.arena.alloc_from_iter(self.root.lang_items_missing.decode(self)) . } . . fn get_fn_param_names(self, tcx: TyCtxt<'tcx>, id: DefIndex) -> &'tcx [Ident] { . let param_names = match self.kind(id) { . EntryKind::Fn(data) | EntryKind::ForeignFn(data) => data.decode(self).param_names, . EntryKind::AssocFn(data) => data.decode(self).fn_data.param_names, . _ => Lazy::empty(), . }; -- line 1466 ---------------------------------------- -- line 1479 ---------------------------------------- . EntryKind::AnonConst(_, data) . | EntryKind::Const(_, data) . | EntryKind::AssocConst(_, _, data) => data.decode(self).0, . _ => bug!(), . } . } . . fn get_macro(self, id: DefIndex, sess: &Session) -> MacroDef { 6 ( 0.00%) match self.kind(id) { 1 ( 0.00%) EntryKind::MacroDef(macro_def) => macro_def.decode((self, sess)), . _ => bug!(), . } . } . . // This replicates some of the logic of the crate-local `is_const_fn_raw` query, because we . // don't serialize constness for tuple variant and tuple struct constructors. . fn is_const_fn_raw(self, id: DefIndex) -> bool { . let constness = match self.kind(id) { -- line 1496 ---------------------------------------- -- line 1536 ---------------------------------------- . } . } . . fn fn_sig(self, id: DefIndex, tcx: TyCtxt<'tcx>) -> ty::PolyFnSig<'tcx> { . self.root.tables.fn_sig.get(self, id).unwrap().decode((self, tcx)) . } . . #[inline] 1,666 ( 0.00%) fn def_key(self, index: DefIndex) -> DefKey { 476 ( 0.00%) *self . .def_key_cache . .lock() . .entry(index) 700 ( 0.00%) .or_insert_with(|| self.root.tables.def_keys.get(self, index).unwrap().decode(self)) 1,904 ( 0.00%) } . . // Returns the path leading to the thing with this `id`. . fn def_path(self, id: DefIndex) -> DefPath { . debug!("def_path(cnum={:?}, id={:?})", self.cnum, id); . DefPath::make(self.cnum, id, |parent| self.def_key(parent)) . } . . fn def_path_hash_unlocked( . self, . index: DefIndex, . def_path_hashes: &mut FxHashMap, . ) -> DefPathHash { 12 ( 0.00%) *def_path_hashes.entry(index).or_insert_with(|| { 15 ( 0.00%) self.root.tables.def_path_hashes.get(self, index).unwrap().decode(self) . }) . } . . #[inline] 42 ( 0.00%) fn def_path_hash(self, index: DefIndex) -> DefPathHash { . let mut def_path_hashes = self.def_path_hash_cache.lock(); . self.def_path_hash_unlocked(index, &mut def_path_hashes) 48 ( 0.00%) } . . #[inline] . fn def_path_hash_to_def_index(self, hash: DefPathHash) -> DefIndex { . self.def_path_hash_map.def_path_hash_to_def_index(&hash) . } . . fn expn_hash_to_expn_id(self, sess: &Session, index_guess: u32, hash: ExpnHash) -> ExpnId { . debug_assert_eq!(ExpnId::from_hash(hash), None); -- line 1580 ---------------------------------------- -- line 1635 ---------------------------------------- . /// Proc macro crates don't currently export spans, so this function does not have . /// to work for them. . fn imported_source_files(self, sess: &Session) -> &'a [ImportedSourceFile] { . // Translate the virtual `/rustc/$hash` prefix back to a real directory . // that should hold actual sources, where possible. . // . // NOTE: if you update this, you might need to also update bootstrap's code for generating . // the `rust-src` component in `Src::run` in `src/bootstrap/dist.rs`. 1,234 ( 0.00%) let virtual_rust_source_base_dir = option_env!("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR") . .map(Path::new) . .filter(|_| { . // Only spend time on further checks if we have what to translate *to*. . sess.opts.real_rust_source_base_dir.is_some() . }) . .filter(|virtual_dir| { . // Don't translate away `/rustc/$hash` if we're still remapping to it, . // since that means we're still building `std`/`rustc` that need it, . // and we don't want the real path to leak into codegen/debuginfo. . !sess.opts.remap_path_prefix.iter().any(|(_from, to)| to == virtual_dir) . }); 1,234 ( 0.00%) let try_to_translate_virtual_to_real = |name: &mut rustc_span::FileName| { . debug!( . "try_to_translate_virtual_to_real(name={:?}): \ . virtual_rust_source_base_dir={:?}, real_rust_source_base_dir={:?}", . name, virtual_rust_source_base_dir, sess.opts.real_rust_source_base_dir, . ); . 1,565 ( 0.00%) if let Some(virtual_dir) = virtual_rust_source_base_dir { . if let Some(real_dir) = &sess.opts.real_rust_source_base_dir { . if let rustc_span::FileName::Real(old_name) = name { . if let rustc_span::RealFileName::Remapped { local_path: _, virtual_name } = . old_name . { . if let Ok(rest) = virtual_name.strip_prefix(virtual_dir) { . let virtual_name = virtual_name.clone(); . -- line 1670 ---------------------------------------- -- line 1709 ---------------------------------------- . *old_name = new_name; . } . } . } . } . } . }; . 1,234 ( 0.00%) self.cdata.source_map_import_info.get_or_init(|| { 9 ( 0.00%) let external_source_map = self.root.source_map.decode(self); . . external_source_map . .map(|source_file_to_import| { . // We can't reuse an existing SourceFile, so allocate a new one . // containing the information we need. . let rustc_span::SourceFile { 6,573 ( 0.01%) mut name, 1,878 ( 0.00%) src_hash, 313 ( 0.00%) start_pos, 626 ( 0.00%) end_pos, 1,565 ( 0.00%) mut lines, 1,565 ( 0.00%) mut multibyte_chars, 1,878 ( 0.00%) mut non_narrow_chars, 1,565 ( 0.00%) mut normalized_pos, 1,878 ( 0.00%) name_hash, . .. . } = source_file_to_import; . . // If this file is under $sysroot/lib/rustlib/src/ but has not been remapped . // during rust bootstrapping by `remap-debuginfo = true`, and the user . // wish to simulate that behaviour by -Z simulate-remapped-rust-src-base, . // then we change `name` to a similar state as if the rust was bootstrapped . // with `remap-debuginfo = true`. . // This is useful for testing so that tests about the effects of . // `try_to_translate_virtual_to_real` don't have to worry about how the . // compiler is bootstrapped. 626 ( 0.00%) if let Some(virtual_dir) = . &sess.opts.debugging_opts.simulate_remapped_rust_src_base . { . if let Some(real_dir) = &sess.opts.real_rust_source_base_dir { . if let rustc_span::FileName::Real(ref mut old_name) = name { . if let rustc_span::RealFileName::LocalPath(local) = old_name { . if let Ok(rest) = local.strip_prefix(real_dir) { . *old_name = rustc_span::RealFileName::Remapped { . local_path: None, -- line 1753 ---------------------------------------- -- line 1767 ---------------------------------------- . let source_length = (end_pos - start_pos).to_usize(); . . // Translate line-start positions and multibyte character . // position into frame of reference local to file. . // `SourceMap::new_imported_source_file()` will then translate those . // coordinates to their new global frame of reference when the . // offset of the SourceFile is known. . for pos in &mut lines { 476,936 ( 0.65%) *pos = *pos - start_pos; . } . for mbc in &mut multibyte_chars { 1,136 ( 0.00%) mbc.pos = mbc.pos - start_pos; . } . for swc in &mut non_narrow_chars { 804 ( 0.00%) *swc = *swc - start_pos; . } . for np in &mut normalized_pos { . np.pos = np.pos - start_pos; . } . 5,634 ( 0.01%) let local_version = sess.source_map().new_imported_source_file( 4,069 ( 0.01%) name, 2,191 ( 0.00%) src_hash, . name_hash, . source_length, 626 ( 0.00%) self.cnum, 1,565 ( 0.00%) lines, 1,878 ( 0.00%) multibyte_chars, 1,565 ( 0.00%) non_narrow_chars, 1,252 ( 0.00%) normalized_pos, . start_pos, . end_pos, . ); . debug!( . "CrateMetaData::imported_source_files alloc \ . source_file {:?} original (start_pos {:?} end_pos {:?}) \ . translated (start_pos {:?} end_pos {:?})", . local_version.name, -- line 1804 ---------------------------------------- -- line 1808 ---------------------------------------- . local_version.end_pos . ); . . ImportedSourceFile { . original_start_pos: start_pos, . original_end_pos: end_pos, . translated_source_file: local_version, . } 939 ( 0.00%) }) . .collect() . }) . } . } . . impl CrateMetadata { 36 ( 0.00%) crate fn new( . sess: &Session, . blob: MetadataBlob, . root: CrateRoot<'static>, . raw_proc_macros: Option<&'static [ProcMacro]>, . cnum: CrateNum, . cnum_map: CrateNumMap, . dep_kind: CrateDepKind, . source: CrateSource, . private_dep: bool, . host_hash: Option, . ) -> CrateMetadata { 9 ( 0.00%) let trait_impls = root . .impls . .decode((&blob, sess)) . .map(|trait_impls| (trait_impls.trait_id, trait_impls.impls)) . .collect(); . let alloc_decoding_state = 9 ( 0.00%) AllocDecodingState::new(root.interpret_alloc_index.decode(&blob).collect()); . let dependencies = Lock::new(cnum_map.iter().cloned().collect()); . . // Pre-decode the DefPathHash->DefIndex table. This is a cheap operation . // that does not copy any data. It just does some data verification. 3 ( 0.00%) let def_path_hash_map = root.def_path_hash_map.decode(&blob); . 69 ( 0.00%) CrateMetadata { 3 ( 0.00%) blob, 9 ( 0.00%) root, 12 ( 0.00%) trait_impls, . raw_proc_macros, . source_map_import_info: OnceCell::new(), 12 ( 0.00%) def_path_hash_map, . expn_hash_map: Default::default(), 21 ( 0.00%) alloc_decoding_state, . cnum, 12 ( 0.00%) cnum_map, 15 ( 0.00%) dependencies, . dep_kind: Lock::new(dep_kind), 36 ( 0.00%) source, . private_dep, . host_hash, . extern_crate: Lock::new(None), . hygiene_context: Default::default(), . def_key_cache: Default::default(), . def_path_hash_cache: Default::default(), . } 27 ( 0.00%) } . . crate fn dependencies(&self) -> LockGuard<'_, Vec> { . self.dependencies.borrow() . } . . crate fn add_dependency(&self, cnum: CrateNum) { . self.dependencies.borrow_mut().push(cnum); . } . . crate fn update_extern_crate(&self, new_extern_crate: ExternCrate) -> bool { . let mut extern_crate = self.extern_crate.borrow_mut(); . let update = Some(new_extern_crate.rank()) > extern_crate.as_ref().map(ExternCrate::rank); . if update { 15 ( 0.00%) *extern_crate = Some(new_extern_crate); . } . update . } . . crate fn source(&self) -> &CrateSource { 4 ( 0.00%) &self.source . } . . crate fn dep_kind(&self) -> CrateDepKind { . *self.dep_kind.lock() . } . . crate fn update_dep_kind(&self, f: impl FnOnce(CrateDepKind) -> CrateDepKind) { 3 ( 0.00%) self.dep_kind.with_lock(|dep_kind| *dep_kind = f(*dep_kind)) . } . . crate fn panic_strategy(&self) -> PanicStrategy { . self.root.panic_strategy . } . . crate fn needs_panic_runtime(&self) -> bool { . self.root.needs_panic_runtime -- line 1905 ---------------------------------------- -- line 1909 ---------------------------------------- . self.root.panic_runtime . } . . crate fn is_profiler_runtime(&self) -> bool { . self.root.profiler_runtime . } . . crate fn needs_allocator(&self) -> bool { 3 ( 0.00%) self.root.needs_allocator . } . . crate fn has_global_allocator(&self) -> bool { . self.root.has_global_allocator . } . . crate fn has_default_lib_allocator(&self) -> bool { . self.root.has_default_lib_allocator . } . . crate fn is_proc_macro_crate(&self) -> bool { . self.root.is_proc_macro_crate() . } . . crate fn name(&self) -> Symbol { 2 ( 0.00%) self.root.name . } . . crate fn stable_crate_id(&self) -> StableCrateId { . self.root.stable_crate_id . } . . crate fn hash(&self) -> Svh { . self.root.hash . } . . fn num_def_ids(&self) -> usize { . self.root.tables.def_keys.size() . } . . fn local_def_id(&self, index: DefIndex) -> DefId { 617 ( 0.00%) DefId { krate: self.cnum, index } . } . . // Translate a DefId from the current compilation environment to a DefId . // for an external crate. . fn reverse_translate_def_id(&self, did: DefId) -> Option { . for (local, &global) in self.cnum_map.iter_enumerated() { . if global == did.krate { . return Some(DefId { krate: local, index: did.index }); -- line 1957 ---------------------------------------- 14,330 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/caching_source_map_view.rs -------------------------------------------------------------------------------- Ir -- line 27 ---------------------------------------- . impl CacheEntry { . #[inline] . fn update( . &mut self, . new_file_and_idx: Option<(Lrc, usize)>, . pos: BytePos, . time_stamp: usize, . ) { 1,020 ( 0.00%) if let Some((file, file_idx)) = new_file_and_idx { 2 ( 0.00%) self.file = file; 1 ( 0.00%) self.file_index = file_idx; . } . 1,008 ( 0.00%) let line_index = self.file.lookup_line(pos).unwrap(); . let line_bounds = self.file.line_bounds(line_index); 2,018 ( 0.00%) self.line_number = line_index + 1; 3,022 ( 0.00%) self.line = line_bounds; . self.touch(time_stamp); . } . . #[inline] . fn touch(&mut self, time_stamp: usize) { 10,118 ( 0.01%) self.time_stamp = time_stamp; . } . } . . #[derive(Clone)] . pub struct CachingSourceMapView<'sm> { . source_map: &'sm SourceMap, . line_cache: [CacheEntry; 3], . time_stamp: usize, . } . . impl<'sm> CachingSourceMapView<'sm> { 20 ( 0.00%) pub fn new(source_map: &'sm SourceMap) -> CachingSourceMapView<'sm> { . let files = source_map.files(); 10 ( 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, . }; . 50 ( 0.00%) CachingSourceMapView { . source_map, 70 ( 0.00%) line_cache: [entry.clone(), entry.clone(), entry], . time_stamp: 0, . } 40 ( 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)) . } . 38,941 ( 0.05%) pub fn span_data_to_lines_and_cols( . &mut self, . span_data: &SpanData, . ) -> Option<(Lrc, usize, BytePos, usize, BytePos)> { 22,252 ( 0.03%) self.time_stamp += 1; . . // Check if lo and hi are in the cached lines. 5,563 ( 0.01%) let lo_cache_idx = self.cache_entry_index(span_data.lo); 5,563 ( 0.01%) let hi_cache_idx = self.cache_entry_index(span_data.hi); . 9,110 ( 0.01%) if lo_cache_idx != -1 && hi_cache_idx != -1 { . // Cache hit for span lo and hi. Check if they belong to the same file. . let result = { 9,110 ( 0.01%) let lo = &self.line_cache[lo_cache_idx as usize]; . let hi = &self.line_cache[hi_cache_idx as usize]; . 27,330 ( 0.04%) if lo.file_index != hi.file_index { . return None; . } . . ( 9,110 ( 0.01%) lo.file.clone(), . lo.line_number, . span_data.lo - lo.line.start, 4,555 ( 0.01%) hi.line_number, . span_data.hi - hi.line.start, . ) . }; . 4,555 ( 0.01%) self.line_cache[lo_cache_idx as usize].touch(self.time_stamp); 4,555 ( 0.01%) self.line_cache[hi_cache_idx as usize].touch(self.time_stamp); . 18,220 ( 0.02%) return Some(result); . } . . // No cache hit or cache hit for only one of span lo and hi. 2,016 ( 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. 8,064 ( 0.01%) let new_file_and_idx = if !file_contains(&self.line_cache[oldest].file, span_data.lo) { . let new_file_and_idx = self.file_for_position(span_data.lo)?; . if !file_contains(&new_file_and_idx.0, span_data.hi) { . return None; . } . . Some(new_file_and_idx) . } else { . let file = &self.line_cache[oldest].file; 3,024 ( 0.00%) if !file_contains(&file, span_data.hi) { . return None; . } . 3,024 ( 0.00%) None . }; . . // Update the cache entries. 5,040 ( 0.01%) 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); . 3,006 ( 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) . } -- line 190 ---------------------------------------- -- line 195 ---------------------------------------- . lo.update(new_file_and_idx, span_data.lo, self.time_stamp); . let hi = &mut self.line_cache[hi_cache_idx as usize]; . 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]; 6 ( 0.00%) hi.update(new_file_and_idx, span_data.hi, self.time_stamp); 12 ( 0.00%) let lo = &mut self.line_cache[lo_cache_idx as usize]; 24 ( 0.00%) lo.touch(self.time_stamp); . (lo_cache_idx as usize, oldest) . } . _ => { . panic!(); . } . }; . . let lo = &self.line_cache[lo_idx]; . let hi = &self.line_cache[hi_idx]; . . // Span lo and hi may equal line end when last line doesn't . // end in newline, hence the inclusive upper bounds below. 2,016 ( 0.00%) assert!(span_data.lo >= lo.line.start); 1,008 ( 0.00%) assert!(span_data.lo <= lo.line.end); 2,016 ( 0.00%) assert!(span_data.hi >= hi.line.start); 1,008 ( 0.00%) assert!(span_data.hi <= hi.line.end); 5,040 ( 0.01%) assert!(lo.file.contains(span_data.lo)); 3,024 ( 0.00%) assert!(lo.file.contains(span_data.hi)); 3,024 ( 0.00%) assert_eq!(lo.file_index, hi.file_index); . 3,024 ( 0.00%) Some(( 1,008 ( 0.00%) lo.file.clone(), . lo.line_number, . span_data.lo - lo.line.start, 1,008 ( 0.00%) hi.line_number, . span_data.hi - hi.line.start, . )) 50,067 ( 0.07%) } . . fn cache_entry_index(&self, pos: BytePos) -> isize { . for (idx, cache_entry) in self.line_cache.iter().enumerate() { 68,527 ( 0.09%) 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() { 6,012 ( 0.01%) 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() { 46 ( 0.00%) if idx != avoid_idx 22 ( 0.00%) && self.line_cache[idx].time_stamp < self.line_cache[oldest].time_stamp . { . oldest = idx; . } . } . . oldest . } . -- line 270 ---------------------------------------- 74,535 ( 0.10%) -------------------------------------------------------------------------------- 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 ./stdio-common/vfscanf-internal.c ./stdlib/cxa_finalize.c ./string/../sysdeps/x86_64/multiarch/memcmp-avx2-movbe.S ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S ./string/../sysdeps/x86_64/multiarch/memset-vec-unaligned-erms.S ./string/../sysdeps/x86_64/multiarch/strlen-avx2.S ./string/../sysdeps/x86_64/strcmp.S /tmp/gcc-build/x86_64-unknown-linux-gnu/libstdc++-v3/libsupc++/../../../../gcc-5.5.0/libstdc++-v3/libsupc++/new_op.cc /tmp/gcc-build/x86_64-unknown-linux-gnu/libstdc++-v3/src/c++98/../../../../../gcc-5.5.0/libstdc++-v3/src/c++98/tree.cc -------------------------------------------------------------------------------- Ir -------------------------------------------------------------------------------- 27,342,541 (37.38%) events annotated