-------------------------------------------------------------------------------- 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 pin_project_lite --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 -C metadata=cd2aada116703df8 -C extra-filename=-cd2aada116703df8 --out-dir /usr/home/liquid/tmp/.tmpdqXgIr/target/release/deps -L dependency=/usr/home/liquid/tmp/.tmpdqXgIr/target/release/deps -Adeprecated -Aunknown-lints -Zincremental-verify-ich Data file: results/cgout-w-profiling-pin-project-lite-0.2.8-Opt-Full Events recorded: Ir Events shown: Ir Event sort order: Ir Thresholds: 0.1 Include dirs: User annotated: Auto-annotation: on -------------------------------------------------------------------------------- Ir -------------------------------------------------------------------------------- 91,614,128 (100.0%) PROGRAM TOTALS -------------------------------------------------------------------------------- Ir file:function -------------------------------------------------------------------------------- 10,308,380 (11.25%) ./elf/dl-lookup.c:_dl_lookup_symbol_x 4,843,311 ( 5.29%) ./elf/dl-lookup.c:do_lookup_x 4,141,271 ( 4.52%) ./elf/../sysdeps/x86_64/dl-machine.h:_dl_relocate_object 2,794,632 ( 3.05%) ./malloc/malloc.c:_int_malloc 2,229,653 ( 2.43%) ./malloc/malloc.c:_int_free 2,139,033 ( 2.33%) ./elf/do-rel.h:_dl_relocate_object 1,990,381 ( 2.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_serialize/src/opaque.rs:>::decode 1,671,154 ( 1.82%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:>::decode 1,619,973 ( 1.77%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:>::decode 1,479,766 ( 1.62%) ./malloc/malloc.c:malloc 1,437,784 ( 1.57%) ???:SetImpliedBits(llvm::FeatureBitset&, llvm::FeatureBitset const&, llvm::ArrayRef) 1,116,857 ( 1.22%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs:::short_write_process_buffer:: 1,063,759 ( 1.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/caching_source_map_view.rs:::span_data_to_lines_and_cols 1,015,705 ( 1.11%) ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:__memcpy_avx_unaligned_erms 941,956 ( 1.03%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/tokenstream.rs:::next 866,056 ( 0.95%) ./elf/dl-lookup.c:check_match 796,163 ( 0.87%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::next 781,252 ( 0.85%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::bump 749,196 ( 0.82%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs:::short_write_process_buffer:: 725,617 ( 0.79%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:>::hash_stable 723,023 ( 0.79%) /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.79%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:::new_imported_source_file 719,048 ( 0.78%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:::new_imported_source_file 697,610 ( 0.76%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::clone 641,989 ( 0.70%) ???:llvm::PassRegistry::enumerateWith(llvm::PassRegistrationListener*) 633,294 ( 0.69%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/mod.rs:::next_token 621,218 ( 0.68%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/tokenstream.rs:::next_with_spacing 614,051 ( 0.67%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs:>::hash_stable 601,594 ( 0.66%) ./malloc/malloc.c:free 549,537 ( 0.60%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lexer/src/lib.rs:::advance_token 530,982 ( 0.58%) ./string/../sysdeps/x86_64/strcmp.S:strcmp 520,505 ( 0.57%) /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}> 518,425 ( 0.57%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/tokentrees.rs:::parse_token_tree 502,096 ( 0.55%) ???:llvm::StringMapImpl::LookupBucketFor(llvm::StringRef) 479,637 ( 0.52%) /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}> 384,009 ( 0.42%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/mod.rs:::span_data_to_lines_and_cols 355,175 ( 0.39%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::bump_with 354,615 ( 0.39%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_metadata/src/rmeta/encoder.rs:>::encode 323,070 ( 0.35%) ./malloc/malloc.c:malloc_consolidate 317,888 ( 0.35%) ./string/../sysdeps/x86_64/multiarch/memcmp-avx2-movbe.S:__memcmp_avx2_movbe 304,500 ( 0.33%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/md-5-0.9.1/src/utils.rs:md5::utils::compress 292,631 ( 0.32%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs:> as core::ops::drop::Drop>::drop 266,336 ( 0.29%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs:md5::utils::compress 263,549 ( 0.29%) ???:llvm::PMTopLevelManager::setLastUser(llvm::ArrayRef, llvm::Pass*) 255,939 ( 0.28%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe/quoted.rs:rustc_expand::mbe::quoted::parse 252,524 ( 0.28%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/source_map.rs:::new_imported_source_file 251,668 ( 0.27%) ./malloc/malloc.c:unlink_chunk.constprop.0 246,134 ( 0.27%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/tokenstream.rs:>::hash_stable 238,468 ( 0.26%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cmp.rs:>::decode 238,468 ( 0.26%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:>::decode 238,468 ( 0.26%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/iter/range.rs:>::decode 230,899 ( 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:: 227,312 ( 0.25%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:>::truncate 226,005 ( 0.25%) ???:llvm::PMTopLevelManager::AUFoldingSetNode::Profile(llvm::FoldingSetNodeID&, llvm::AnalysisUsage const&) 223,812 ( 0.24%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/str/validations.rs:::advance_token 221,269 ( 0.24%) ./stdlib/cxa_finalize.c:__cxa_finalize 216,443 ( 0.24%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs:>::hash_stable 213,142 ( 0.23%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/span_encoding.rs:>::hash_stable 211,360 ( 0.23%) ???:(anonymous namespace)::GetCFGOnlyPasses::passEnumerate(llvm::PassInfo const*) [clone .llvm.764396836974782617] 206,784 ( 0.23%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/tokentrees.rs:::push 201,241 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_serialize/src/leb128.rs:::read_u32 201,217 ( 0.22%) ./malloc/malloc.c:realloc 200,489 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_serialize/src/leb128.rs:>::encode 198,983 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:::advance_token 190,073 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs: as core::ops::drop::Drop>::drop 184,257 ( 0.20%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>::insert::>::{closure#0}> 183,647 ( 0.20%) ???:llvm::StringMapImpl::RehashTable(unsigned int) 182,223 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::next_desugared 177,531 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/span_encoding.rs:>::encode 169,648 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_index/src/bit_set.rs:>::ensure 160,926 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_serialize/src/leb128.rs:::read_u32 159,087 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lint/src/builtin.rs:::check_tokens 157,941 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs:::short_write_process_buffer:: 151,259 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/str/mod.rs:::next_token 147,880 ( 0.16%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::insert 144,887 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_metadata/src/rmeta/decoder.rs:>::decode 141,828 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/library/std/src/sys/unix/alloc.rs:__rdl_alloc 141,103 ( 0.15%) ./malloc/malloc.c:_int_realloc 140,587 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::ident 137,530 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs:::slice_write_process_buffer 133,083 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs:::slice_write_process_buffer 132,554 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:::enter_lint_attrs 129,717 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:::next_token 127,863 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:::bump_with 122,335 ( 0.13%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs:>>::insert 117,519 ( 0.13%) ???:llvm::AnalysisUsage::pushUnique(llvm::SmallVectorImpl&, void const*) 113,499 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/str/traits.rs:::next_token 113,246 ( 0.12%) ./stdio-common/vfscanf-internal.c:__vfscanf_internal 110,244 ( 0.12%) ???:llvm::PMDataManager::removeNotPreservedAnalysis(llvm::Pass*) 110,243 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/symbol.rs:::intern 109,559 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:>::encode 108,822 ( 0.12%) ./string/../sysdeps/x86_64/multiarch/memset-vec-unaligned-erms.S:__memset_avx2_erms 108,514 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs:::short_write_process_buffer:: 108,195 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cmp.rs:::span_data_to_lines_and_cols 107,485 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/intrinsics.rs:>::hash_stable 105,948 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs:::short_write_process_buffer:: 104,498 ( 0.11%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:::intern 104,354 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/memchr.rs:core::slice::memchr::memchr_general_case 104,160 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::eq 103,642 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_metadata/src/rmeta/encoder.rs:>::encode 103,432 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:>::encode 103,264 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_serialize/src/opaque.rs:>::encode 103,035 ( 0.11%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/unicode-xid-0.2.2/src/lib.rs:::eat_while:: 102,793 ( 0.11%) ???:llvm::BitstreamCursor::readRecord(unsigned int, llvm::SmallVectorImpl&, llvm::StringRef*) 102,352 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/attr/mod.rs:::from_tokens:: 101,524 ( 0.11%) ???:llvm::PMTopLevelManager::findAnalysisUsage(llvm::Pass*) 100,690 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/iter/traits/iterator.rs:::try_fold::<(), core::iter::traits::iterator::Iterator::all::check::process_token_stream::can_skip::{closure#0}>::{closure#0}, core::ops::control_flow::ControlFlow<()>> 99,736 ( 0.11%) ???:llvm::X86_MC::initLLVMToSEHAndCVRegMapping(llvm::MCRegisterInfo*) 95,517 ( 0.10%) ???:llvm::PassRegistry::registerPass(llvm::PassInfo const&, bool) 94,967 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/library/std/src/path.rs:::hash:: 93,019 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_serialize/src/leb128.rs:::read_usize -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/str/validations.rs -------------------------------------------------------------------------------- Ir -- 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 117,146 ( 0.13%) let x = *bytes.next()?; 229,244 ( 0.25%) if x < 128 { 32 ( 0.00%) 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. -- line 48 ---------------------------------------- -- 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()? { 87 ( 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,372 ( 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; 318 ( 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); . 540 ( 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] . }}; . } . 258 ( 0.00%) let first = v[index]; 516 ( 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 206 ---------------------------------------- . } . _ => err!(Some(1)), . } . 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. 876 ( 0.00%) if align != usize::MAX && align.wrapping_sub(index) % usize_bytes == 0 { . let ptr = v.as_ptr(); 6,948 ( 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,372 ( 0.00%) let zu = contains_nonascii(*block); . let zv = contains_nonascii(*block.offset(1)); 6,744 ( 0.01%) if zu || zv { . break; . } . } 6,744 ( 0.01%) index += ascii_block_size; . } . // step from the point where the wordwise loop stopped 3,994 ( 0.00%) while index < len && v[index] < 128 { 877 ( 0.00%) index += 1; . } . } else { 156 ( 0.00%) index += 1; . } . } . } . . Ok(()) . } . . // https://tools.ietf.org/html/rfc3629 -- line 245 ---------------------------------------- 2,097 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lint/src/builtin.rs -------------------------------------------------------------------------------- Ir -- line 90 ---------------------------------------- . fn pierce_parens(mut expr: &ast::Expr) -> &ast::Expr { . while let ast::ExprKind::Paren(sub) = &expr.kind { . expr = sub; . } . expr . } . . impl EarlyLintPass for WhileTrue { 144 ( 0.00%) fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) { 48 ( 0.00%) if let ast::ExprKind::While(cond, _, label) = &e.kind { . if let ast::ExprKind::Lit(ref lit) = pierce_parens(cond).kind { . if let ast::LitKind::Bool(true) = lit.kind { . if !lit.span.from_expansion() { . let msg = "denote infinite loops with `loop { ... }`"; . let condition_span = e.span.with_hi(cond.span.hi()); . cx.struct_span_lint(WHILE_TRUE, condition_span, |lint| { . lint.build(msg) . .span_suggestion_short( -- line 107 ---------------------------------------- -- line 117 ---------------------------------------- . Applicability::MachineApplicable, . ) . .emit(); . }) . } . } . } . } 168 ( 0.00%) } . } . . declare_lint! { . /// The `box_pointers` lints use of the Box type. . /// . /// ### Example . /// . /// ```rust,compile_fail -- line 133 ---------------------------------------- -- line 147 ---------------------------------------- . BOX_POINTERS, . Allow, . "use of owned (Box type) heap memory" . } . . declare_lint_pass!(BoxPointers => [BOX_POINTERS]); . . impl BoxPointers { 385 ( 0.00%) fn check_heap_type(&self, cx: &LateContext<'_>, span: Span, ty: Ty<'_>) { 832 ( 0.00%) for leaf in ty.walk() { . if let GenericArgKind::Type(leaf_ty) = leaf.unpack() { 14 ( 0.00%) if leaf_ty.is_box() { . cx.struct_span_lint(BOX_POINTERS, span, |lint| { . lint.build(&format!("type uses owned (Box type) pointers: {}", ty)).emit() . }); . } . } . } 280 ( 0.00%) } . } . . impl<'tcx> LateLintPass<'tcx> for BoxPointers { 207 ( 0.00%) fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) { 92 ( 0.00%) match it.kind { . hir::ItemKind::Fn(..) . | hir::ItemKind::TyAlias(..) . | hir::ItemKind::Enum(..) . | hir::ItemKind::Struct(..) . | hir::ItemKind::Union(..) => { 15 ( 0.00%) 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 72 ( 0.00%) match it.kind { . hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => { 9 ( 0.00%) for struct_field in struct_def.fields() { 28 ( 0.00%) let def_id = cx.tcx.hir().local_def_id(struct_field.hir_id); 24 ( 0.00%) self.check_heap_type(cx, struct_field.span, cx.tcx.type_of(def_id)); . } . } . _ => (), . } 184 ( 0.00%) } . . fn check_expr(&mut self, cx: &LateContext<'_>, e: &hir::Expr<'_>) { 84 ( 0.00%) let ty = cx.typeck_results().node_type(e.hir_id); 112 ( 0.00%) self.check_heap_type(cx, e.span, ty); . } . } . . declare_lint! { . /// The `non_shorthand_field_patterns` lint detects using `Struct { x: x }` . /// instead of `Struct { x }` in a pattern. . /// . /// ### Example -- line 203 ---------------------------------------- -- line 230 ---------------------------------------- . NON_SHORTHAND_FIELD_PATTERNS, . Warn, . "using `Struct { x: x }` instead of `Struct { x }` in a pattern" . } . . declare_lint_pass!(NonShorthandFieldPatterns => [NON_SHORTHAND_FIELD_PATTERNS]); . . impl<'tcx> LateLintPass<'tcx> for NonShorthandFieldPatterns { 35 ( 0.00%) fn check_pat(&mut self, cx: &LateContext<'_>, pat: &hir::Pat<'_>) { 10 ( 0.00%) if let PatKind::Struct(ref qpath, field_pats, _) = pat.kind { . let variant = cx . .typeck_results() . .pat_ty(pat) . .ty_adt_def() . .expect("struct pattern type is not an ADT") . .variant_of_res(cx.qpath_res(qpath, pat.hir_id)); . for fieldpat in field_pats { . if fieldpat.is_shorthand { -- line 247 ---------------------------------------- -- line 278 ---------------------------------------- . Applicability::MachineApplicable, . ); . err.emit(); . }); . } . } . } . } 40 ( 0.00%) } . } . . declare_lint! { . /// The `unsafe_code` lint catches usage of `unsafe` code. . /// . /// ### Example . /// . /// ```rust,compile_fail -- line 294 ---------------------------------------- -- line 316 ---------------------------------------- . impl UnsafeCode { . fn report_unsafe( . &self, . cx: &EarlyContext<'_>, . span: Span, . decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>), . ) { . // This comes from a macro that has `#[allow_internal_unsafe]`. 18 ( 0.00%) if span.allows_unsafe() { . return; . } . . cx.struct_span_lint(UNSAFE_CODE, span, decorate); . } . . fn report_overriden_symbol_name(&self, cx: &EarlyContext<'_>, span: Span, msg: &str) { . self.report_unsafe(cx, span, |lint| { -- line 332 ---------------------------------------- -- line 337 ---------------------------------------- . override them", . ) . .emit(); . }) . } . } . . impl EarlyLintPass for UnsafeCode { 882 ( 0.00%) fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &ast::Attribute) { 17 ( 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,176 ( 0.00%) } . 72 ( 0.00%) fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) { 48 ( 0.00%) if let ast::ExprKind::Block(ref blk, _) = e.kind { . // Don't warn about generated blocks; that'll just pollute the output. 2 ( 0.00%) if blk.rules == ast::BlockCheckMode::Unsafe(ast::UserProvided) { 2 ( 0.00%) self.report_unsafe(cx, blk.span, |lint| { . lint.build("usage of an `unsafe` block").emit() . }); . } . } 96 ( 0.00%) } . 96 ( 0.00%) fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) { 95 ( 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`", . ); . } . } . . _ => {} . } 112 ( 0.00%) } . 24 ( 0.00%) fn check_impl_item(&mut self, cx: &EarlyContext<'_>, it: &ast::AssocItem) { 8 ( 0.00%) if let ast::AssocItemKind::Fn(..) = it.kind { 28 ( 0.00%) 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", . ); . } 28 ( 0.00%) if let Some(attr) = cx.sess().find_by_name(&it.attrs, sym::export_name) { . self.report_overriden_symbol_name( . cx, . attr.span, . "declaration of a method with `export_name`", . ); . } . } 28 ( 0.00%) } . . fn check_fn(&mut self, cx: &EarlyContext<'_>, fk: FnKind<'_>, span: Span, _: ast::NodeId) { 16 ( 0.00%) if let FnKind::Fn( . ctxt, . _, . ast::FnSig { header: ast::FnHeader { unsafety: ast::Unsafe::Yes(_), .. }, .. }, . _, . body, . ) = fk . { 18 ( 0.00%) let msg = match ctxt { . FnCtxt::Foreign => return, . FnCtxt::Free => "declaration of an `unsafe` function", . FnCtxt::Assoc(_) if body.is_none() => "declaration of an `unsafe` method", . FnCtxt::Assoc(_) => "implementation of an `unsafe` method", . }; . self.report_unsafe(cx, span, |lint| lint.build(msg).emit()); . } . } -- line 455 ---------------------------------------- -- 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 { 379 ( 0.00%) *self.doc_hidden_stack.last().expect("empty doc_hidden_stack") . } . 117 ( 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. 18 ( 0.00%) if cx.sess().opts.test { . return; . } . . // `#[doc(hidden)]` disables missing_docs check. 9 ( 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() . }, . ); . } 72 ( 0.00%) } . } . . impl<'tcx> LateLintPass<'tcx> for MissingDoc { 2,590 ( 0.00%) fn enter_lint_attrs(&mut self, _cx: &LateContext<'_>, attrs: &[ast::Attribute]) { 370 ( 0.00%) let doc_hidden = self.doc_hidden() . || attrs.iter().any(|attr| { 610 ( 0.00%) attr.has_name(sym::doc) 600 ( 0.00%) && match attr.meta_item_list() { . None => false, 840 ( 0.00%) Some(l) => attr::list_contains_name(&l, sym::hidden), . } . }); . self.doc_hidden_stack.push(doc_hidden); 2,960 ( 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%) } . 138 ( 0.00%) fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) { 79 ( 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; . } . } 6 ( 0.00%) hir::ItemKind::Impl(hir::Impl { of_trait: Some(ref trait_ref), items, .. }) => { . // If the trait is private, add the impl items to `private_traits` so they don't get . // reported for missing docs. 9 ( 0.00%) let real_trait = trait_ref.path.res.def_id(); 3 ( 0.00%) let Some(def_id) = real_trait.as_local() else { return }; . let Some(Node::Item(item)) = cx.tcx.hir().find_by_def_id(def_id) else { return }; . if let hir::VisibilityKind::Inherited = item.vis.node { . for impl_item_ref in items { . self.private_traits.insert(impl_item_ref.id.hir_id()); . } . } . return; . } -- line 620 ---------------------------------------- -- line 627 ---------------------------------------- . | hir::ItemKind::Struct(..) . | hir::ItemKind::Union(..) . | hir::ItemKind::Const(..) . | hir::ItemKind::Static(..) => {} . . _ => return, . }; . 54 ( 0.00%) let (article, desc) = cx.tcx.article_and_description(it.def_id.to_def_id()); . 36 ( 0.00%) self.check_missing_docs_attrs(cx, it.def_id, it.span, article, desc); 161 ( 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()); . . self.check_missing_docs_attrs(cx, trait_item.def_id, trait_item.span, article, desc); . } . 40 ( 0.00%) fn check_impl_item(&mut self, cx: &LateContext<'_>, impl_item: &hir::ImplItem<'_>) { . // If the method is an impl for a trait, don't doc. 24 ( 0.00%) if method_context(cx, impl_item.hir_id()) == MethodLateContext::TraitImpl { . return; . } . . // If the method is an impl for an item with docs_hidden, don't doc. 10 ( 0.00%) if method_context(cx, impl_item.hir_id()) == MethodLateContext::PlainImpl { 12 ( 0.00%) let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id()); 2 ( 0.00%) let impl_ty = cx.tcx.type_of(parent); 10 ( 0.00%) let outerdef = match impl_ty.kind() { 8 ( 0.00%) ty::Adt(def, _) => Some(def.did), . ty::Foreign(def_id) => Some(*def_id), . _ => None, . }; . let is_hidden = match outerdef { 4 ( 0.00%) Some(id) => cx.tcx.is_doc_hidden(id), . None => false, . }; 4 ( 0.00%) if is_hidden { . return; . } . } . . let (article, desc) = cx.tcx.article_and_description(impl_item.def_id.to_def_id()); . self.check_missing_docs_attrs(cx, impl_item.def_id, impl_item.span, article, desc); 32 ( 0.00%) } . . fn check_foreign_item(&mut self, cx: &LateContext<'_>, foreign_item: &hir::ForeignItem<'_>) { . let (article, desc) = cx.tcx.article_and_description(foreign_item.def_id.to_def_id()); . self.check_missing_docs_attrs(cx, foreign_item.def_id, foreign_item.span, article, desc); . } . . fn check_field_def(&mut self, cx: &LateContext<'_>, sf: &hir::FieldDef<'_>) { 16 ( 0.00%) if !sf.is_positional() { 12 ( 0.00%) let def_id = cx.tcx.hir().local_def_id(sf.hir_id); 22 ( 0.00%) self.check_missing_docs_attrs(cx, def_id, sf.span, "a", "struct field") . } . } . . fn check_variant(&mut self, cx: &LateContext<'_>, v: &hir::Variant<'_>) { . self.check_missing_docs_attrs(cx, cx.tcx.hir().local_def_id(v.id), v.span, "a", "variant"); . } . } . -- line 694 ---------------------------------------- -- 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 { 207 ( 0.00%) fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) { 110 ( 0.00%) if !cx.access_levels.is_reachable(item.def_id) { . return; . } 120 ( 0.00%) let (def, ty) = match item.kind { . hir::ItemKind::Struct(_, ref ast_generics) => { 3 ( 0.00%) 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) => { . if !ast_generics.params.is_empty() { . return; -- line 746 ---------------------------------------- -- line 768 ---------------------------------------- . cx.struct_span_lint(MISSING_COPY_IMPLEMENTATIONS, item.span, |lint| { . lint.build( . "type could implement `Copy`; consider adding `impl \ . Copy`", . ) . .emit() . }) . } 184 ( 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 { 161 ( 0.00%) fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) { 110 ( 0.00%) if !cx.access_levels.is_reachable(item.def_id) { . return; . } . 72 ( 0.00%) match item.kind { . hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) | hir::ItemKind::Enum(..) => {} . _ => return, . } . 21 ( 0.00%) let Some(debug) = cx.tcx.get_diagnostic_item(sym::Debug) else { . return . }; . 3 ( 0.00%) if self.impling_types.is_none() { . let mut impls = LocalDefIdSet::default(); 3,008 ( 0.00%) cx.tcx.for_each_impl(debug, |d| { 1,913 ( 0.00%) if let Some(ty_def) = cx.tcx.type_of(d).ty_adt_def() { 313 ( 0.00%) if let Some(def_id) = ty_def.did.as_local() { . impls.insert(def_id); . } . } 3,432 ( 0.00%) }); . 4 ( 0.00%) self.impling_types = Some(impls); . debug!("{:?}", self.impling_types); . } . 6 ( 0.00%) if !self.impling_types.as_ref().unwrap().contains(&item.def_id) { 18 ( 0.00%) cx.struct_span_lint(MISSING_DEBUG_IMPLEMENTATIONS, item.span, |lint| { . lint.build(&format!( . "type does not implement `{}`; consider adding `#[derive(Debug)]` \ . or a manual implementation", . cx.tcx.def_path_str(debug) . )) . .emit() . }); . } 115 ( 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 { 2,646 ( 0.00%) fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &ast::Attribute) { 1,470 ( 0.00%) for BuiltinAttribute { name, gate, .. } in &self.depr_attrs { 1,210 ( 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; . } . } 68 ( 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,352 ( 0.00%) } . } . 384 ( 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. . let mut sugared_span: Option = None; . . while let Some(attr) = attrs.next() { -- line 1020 ---------------------------------------- -- line 1044 ---------------------------------------- . AttrKind::DocComment(CommentKind::Block, _) => { . err.help("use `/* */` for a plain comment"); . } . } . err.emit(); . }); . } . } 256 ( 0.00%) } . . impl EarlyLintPass for UnusedDocComment { . fn check_stmt(&mut self, cx: &EarlyContext<'_>, stmt: &ast::Stmt) { 16 ( 0.00%) let kind = match stmt.kind { . ast::StmtKind::Local(..) => "statements", . // Disabled pending discussion in #78306 . ast::StmtKind::Item(..) => return, . // expressions will be reported by `check_expr`. . ast::StmtKind::Empty . | ast::StmtKind::Semi(_) . | ast::StmtKind::Expr(_) . | ast::StmtKind::MacCall(_) => return, -- line 1064 ---------------------------------------- -- line 1068 ---------------------------------------- . } . . fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) { . let arm_span = arm.pat.span.with_hi(arm.body.span.hi()); . warn_if_doc(cx, arm_span, "match arms", &arm.attrs); . } . . fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) { 192 ( 0.00%) warn_if_doc(cx, expr.span, "expressions", &expr.attrs); . } . . fn check_generic_param(&mut self, cx: &EarlyContext<'_>, param: &ast::GenericParam) { 64 ( 0.00%) warn_if_doc(cx, param.ident.span, "generic parameters", ¶m.attrs); . } . } . . declare_lint! { . /// The `no_mangle_const_items` lint detects any `const` items with the . /// [`no_mangle` attribute]. . /// . /// [`no_mangle` attribute]: https://doc.rust-lang.org/reference/abi.html#the-no_mangle-attribute -- line 1088 ---------------------------------------- -- 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 { 207 ( 0.00%) fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) { 161 ( 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; . } . } . } . }; 161 ( 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 1196 ---------------------------------------- . "try a static value", . "pub static".to_owned(), . Applicability::MachineApplicable, . ); . err.emit(); . }); . } . } 5 ( 0.00%) hir::ItemKind::Impl(hir::Impl { ref generics, items, .. }) => { . for it in items { 16 ( 0.00%) if let hir::AssocItemKind::Fn { .. } = it.kind { 24 ( 0.00%) if let Some(no_mangle_attr) = cx . .sess() 20 ( 0.00%) .find_by_name(cx.tcx.hir().attrs(it.id.hir_id()), sym::no_mangle) . { . check_no_mangle_on_generic_fn( . no_mangle_attr, . Some(generics), . cx.tcx.hir().get_generics(it.id.def_id).unwrap(), . it.span, . ); . } . } . } . } . _ => {} . } 184 ( 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 1248 ---------------------------------------- . MUTABLE_TRANSMUTES, . Deny, . "transmuting &T to &mut T is undefined behavior, even if the reference is unused" . } . . declare_lint_pass!(MutableTransmutes => [MUTABLE_TRANSMUTES]); . . impl<'tcx> LateLintPass<'tcx> for MutableTransmutes { 196 ( 0.00%) fn check_expr(&mut self, cx: &LateContext<'_>, expr: &hir::Expr<'_>) { . use rustc_target::spec::abi::Abi::RustIntrinsic; . if let Some((&ty::Ref(_, _, from_mt), &ty::Ref(_, _, to_mt))) = . get_transmute_from_to(cx, expr).map(|(ty1, ty2)| (ty1.kind(), ty2.kind())) . { . if to_mt == hir::Mutability::Mut && from_mt == hir::Mutability::Not { . let msg = "transmuting &T to &mut T is undefined behavior, \ . even if the reference is unused, consider instead using an UnsafeCell"; . cx.struct_span_lint(MUTABLE_TRANSMUTES, expr.span, |lint| lint.build(msg).emit()); . } . } . . fn get_transmute_from_to<'tcx>( . cx: &LateContext<'tcx>, . expr: &hir::Expr<'_>, . ) -> Option<(Ty<'tcx>, Ty<'tcx>)> { 67 ( 0.00%) let def = if let hir::ExprKind::Path(ref qpath) = expr.kind { 44 ( 0.00%) cx.qpath_res(qpath, expr.hir_id) . } else { . return None; . }; 36 ( 0.00%) if let Res::Def(DefKind::Fn, did) = def { . if !def_id_is_transmute(cx, did) { . return None; . } . let sig = cx.typeck_results().node_type(expr.hir_id).fn_sig(cx.tcx); . let from = sig.inputs().skip_binder()[0]; . let to = sig.output().skip_binder(); . return Some((from, to)); . } . None . } . . fn def_id_is_transmute(cx: &LateContext<'_>, def_id: DefId) -> bool { 12 ( 0.00%) cx.tcx.fn_sig(def_id).abi() == RustIntrinsic . && cx.tcx.item_name(def_id) == sym::transmute . } 224 ( 0.00%) } . } . . declare_lint! { . /// The `unstable_features` is deprecated and should no longer be used. . UNSTABLE_FEATURES, . Allow, . "enabling unstable features (deprecated. do not use)" . } . . declare_lint_pass!( . /// Forbids using the `#[feature(...)]` attribute . UnstableFeatures => [UNSTABLE_FEATURES] . ); . . impl<'tcx> LateLintPass<'tcx> for UnstableFeatures { 2,121 ( 0.00%) fn check_attribute(&mut self, cx: &LateContext<'_>, attr: &ast::Attribute) { 26 ( 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,424 ( 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 { 248 ( 0.00%) fn perform_lint( . &self, . cx: &LateContext<'_>, . what: &str, . def_id: LocalDefId, . vis: &hir::Visibility<'_>, . span: Span, . exportable: bool, . ) { 31 ( 0.00%) let mut applicability = Applicability::MachineApplicable; 62 ( 0.00%) match vis.node { 48 ( 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(); . }); . } . _ => {} . } 155 ( 0.00%) } . } . . impl<'tcx> LateLintPass<'tcx> for UnreachablePub { . fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) { 184 ( 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, . foreign_item.span, . true, . ); . } . . fn check_field_def(&mut self, cx: &LateContext<'_>, field: &hir::FieldDef<'_>) { 20 ( 0.00%) let def_id = cx.tcx.hir().local_def_id(field.hir_id); 32 ( 0.00%) self.perform_lint(cx, "field", def_id, &field.vis, field.span, false); . } . . fn check_impl_item(&mut self, cx: &LateContext<'_>, impl_item: &hir::ImplItem<'_>) { 40 ( 0.00%) self.perform_lint(cx, "item", impl_item.def_id, &impl_item.vis, impl_item.span, false); . } . } . . declare_lint! { . /// The `type_alias_bounds` lint detects bounds in type aliases. . /// . /// ### Example . /// -- line 1432 ---------------------------------------- -- line 1493 ---------------------------------------- . . // Let's go for a walk! . let mut visitor = WalkAssocTypes { err }; . visitor.visit_ty(ty); . } . } . . impl<'tcx> LateLintPass<'tcx> for TypeAliasBounds { 161 ( 0.00%) fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) { 46 ( 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(); . }); . } . } 184 ( 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<'_>) { 115 ( 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 { 207 ( 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::*; . 92 ( 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() . }); . } . } . } 184 ( 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 1732 ---------------------------------------- . /// If `Some(_)`, suppress all subsequent pattern . /// warnings for better diagnostics. . node_id: Option, . } . . impl_lint_pass!(EllipsisInclusiveRangePatterns => [ELLIPSIS_INCLUSIVE_RANGE_PATTERNS]); . . impl EarlyLintPass for EllipsisInclusiveRangePatterns { 35 ( 0.00%) fn check_pat(&mut self, cx: &EarlyContext<'_>, pat: &ast::Pat) { 5 ( 0.00%) if self.node_id.is_some() { . // Don't recursively warn about patterns inside range endpoints. . return; . } . . use self::ast::{PatKind, RangeSyntax::DotDotDot}; . . /// If `pat` is a `...` pattern, return the start and end of the range, as well as the span . /// corresponding to the ellipsis. . fn matches_ellipsis_pat(pat: &ast::Pat) -> Option<(Option<&Expr>, &Expr, Span)> { 10 ( 0.00%) match &pat.kind { . PatKind::Range( . a, . Some(b), . Spanned { span, node: RangeEnd::Included(DotDotDot) }, . ) => Some((a.as_deref(), b, *span)), . _ => None, . } . } . 15 ( 0.00%) let (parenthesise, endpoints) = match &pat.kind { . PatKind::Ref(subpat, _) => (true, matches_ellipsis_pat(&subpat)), . _ => (false, matches_ellipsis_pat(pat)), . }; . . if let Some((start, end, join)) = endpoints { . let msg = "`...` range patterns are deprecated"; . let suggestion = "use `..=` for an inclusive range"; . if parenthesise { -- line 1769 ---------------------------------------- -- line 1816 ---------------------------------------- . replace, . Applicability::MachineApplicable, . ) . .emit(); . }); . } . }; . } 40 ( 0.00%) } . . fn check_pat_post(&mut self, _cx: &EarlyContext<'_>, pat: &ast::Pat) { 15 ( 0.00%) if let Some(node_id) = self.node_id { . if pat.id == node_id { . self.node_id = None . } . } . } . } . . declare_lint! { -- line 1835 ---------------------------------------- -- line 1880 ---------------------------------------- . . impl UnnameableTestItems { . pub fn new() -> Self { . Self { boundary: None, items_nameable: true } . } . } . . impl<'tcx> LateLintPass<'tcx> for UnnameableTestItems { 115 ( 0.00%) fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) { 46 ( 0.00%) if self.items_nameable { 46 ( 0.00%) if let hir::ItemKind::Mod(..) = it.kind { . } else { 22 ( 0.00%) self.items_nameable = false; 66 ( 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() . }); . } 138 ( 0.00%) } . . fn check_item_post(&mut self, _cx: &LateContext<'_>, it: &hir::Item<'_>) { 134 ( 0.00%) if !self.items_nameable && self.boundary == Some(it.def_id) { 22 ( 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 { 9,416 ( 0.01%) fn check_tokens(&mut self, cx: &EarlyContext<'_>, tokens: TokenStream) { 79,959 ( 0.09%) for tt in tokens.into_trees() { 11,114 ( 0.01%) match tt { . // Only report non-raw idents. 17,528 ( 0.02%) TokenTree::Token(token) => { 21,944 ( 0.02%) if let Some((ident, false)) = token.ident() { 5,888 ( 0.01%) self.check_ident_token(cx, UnderMacro(true), ident); . } . } 2,350 ( 0.00%) TokenTree::Delimited(_, _, tts) => self.check_tokens(cx, tts), . } . } 9,416 ( 0.01%) } . 18,792 ( 0.02%) fn check_ident_token( . &mut self, . cx: &EarlyContext<'_>, . UnderMacro(under_macro): UnderMacro, . ident: Ident, . ) { 6,264 ( 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() . }); 10,962 ( 0.01%) } . } . . impl EarlyLintPass for KeywordIdents { . fn check_mac_def(&mut self, cx: &EarlyContext<'_>, mac_def: &ast::MacroDef, _id: ast::NodeId) { 10 ( 0.00%) self.check_tokens(cx, mac_def.body.inner_tokens()); . } . fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &ast::MacCall) { . self.check_tokens(cx, mac.args.inner_tokens()); . } . fn check_ident(&mut self, cx: &EarlyContext<'_>, ident: Ident) { 188 ( 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 { 207 ( 0.00%) fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) { . use rustc_middle::middle::resolve_lifetime::Region; . 92 ( 0.00%) let infer_static = cx.tcx.features().infer_static_outlives_requirements; 23 ( 0.00%) let def_id = item.def_id; 155 ( 0.00%) if let hir::ItemKind::Struct(_, ref hir_generics) . | hir::ItemKind::Enum(_, ref hir_generics) . | hir::ItemKind::Union(_, ref hir_generics) = item.kind . { 3 ( 0.00%) let inferred_outlives = cx.tcx.inferred_outlives_of(def_id); 6 ( 0.00%) if inferred_outlives.is_empty() { . return; . } . . let ty_generics = cx.tcx.generics_of(def_id); . . let mut bound_count = 0; . let mut lint_spans = Vec::new(); . -- line 2205 ---------------------------------------- -- line 2338 ---------------------------------------- . .map(|span| (span, "".to_owned())) . .collect::>(), . Applicability::MachineApplicable, . ) . .emit(); . }); . } . } 184 ( 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 ---------------------------------------- -- line 2448 ---------------------------------------- . pub INVALID_VALUE, . Warn, . "an invalid value is being created (such as a null reference)" . } . . declare_lint_pass!(InvalidValue => [INVALID_VALUE]); . . impl<'tcx> LateLintPass<'tcx> for InvalidValue { 196 ( 0.00%) fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &hir::Expr<'_>) { . #[derive(Debug, Copy, Clone, PartialEq)] . enum InitKind { . Zeroed, . Uninit, . } . . /// Information about why a type cannot be initialized this way. . /// Contains an error message and optionally a span to point at. -- line 2464 ---------------------------------------- -- line 2478 ---------------------------------------- . } . Tup(tup) => tup.iter().all(is_zero), . _ => false, . } . } . . /// Determine if this expression is a "dangerous initialization". . fn is_dangerous_init(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> Option { 140 ( 0.00%) if let hir::ExprKind::Call(ref path_expr, ref args) = expr.kind { . // Find calls to `mem::{uninitialized,zeroed}` methods. 20 ( 0.00%) if let hir::ExprKind::Path(ref qpath) = path_expr.kind { 43 ( 0.00%) let def_id = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id()?; 32 ( 0.00%) match cx.tcx.get_diagnostic_name(def_id) { . Some(sym::mem_zeroed) => return Some(InitKind::Zeroed), . Some(sym::mem_uninitialized) => return Some(InitKind::Uninit), . Some(sym::transmute) if is_zero(&args[0]) => return Some(InitKind::Zeroed), . _ => {} . } . } . } else if let hir::ExprKind::MethodCall(_, ref args, _) = expr.kind { . // Find problematic calls to `MaybeUninit::assume_init`. -- line 2498 ---------------------------------------- -- line 2655 ---------------------------------------- . err.span_note(span, &msg); . } else { . err.note(&msg); . } . err.emit(); . }); . } . } 168 ( 0.00%) } . } . . declare_lint! { . /// The `clashing_extern_declarations` lint detects when an `extern fn` . /// has been declared with the same name but different types. . /// . /// ### Example . /// -- line 2671 ---------------------------------------- -- line 3078 ---------------------------------------- . pub DEREF_NULLPTR, . Warn, . "detects when an null pointer is dereferenced" . } . . declare_lint_pass!(DerefNullPtr => [DEREF_NULLPTR]); . . impl<'tcx> LateLintPass<'tcx> for DerefNullPtr { 84 ( 0.00%) fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &hir::Expr<'_>) { . /// test if expression is a null ptr . fn is_null_ptr(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> bool { 6 ( 0.00%) match &expr.kind { . rustc_hir::ExprKind::Cast(ref expr, ref ty) => { . if let rustc_hir::TyKind::Ptr(_) = ty.kind { . return is_zero(expr) || is_null_ptr(cx, expr); . } . } . // check for call to `core::ptr::null` or `core::ptr::null_mut` . rustc_hir::ExprKind::Call(ref path, _) => { . if let rustc_hir::ExprKind::Path(ref qpath) = path.kind { -- line 3097 ---------------------------------------- -- line 3116 ---------------------------------------- . return a == 0; . } . } . _ => {} . } . false . } . 59 ( 0.00%) if let rustc_hir::ExprKind::Unary(rustc_hir::UnOp::Deref, expr_deref) = expr.kind { . if is_null_ptr(cx, expr_deref) { . cx.struct_span_lint(DEREF_NULLPTR, expr.span, |lint| { . let mut err = lint.build("dereferencing a null pointer"); . err.span_label(expr.span, "this code causes undefined behavior when executed"); . err.emit(); . }); . } . } 112 ( 0.00%) } . } . . declare_lint! { . /// The `named_asm_labels` lint detects the use of named labels in the . /// inline `asm!` macro. . /// . /// ### Example . /// -- line 3141 ---------------------------------------- -- line 3162 ---------------------------------------- . pub NAMED_ASM_LABELS, . Deny, . "named labels in inline assembly", . } . . declare_lint_pass!(NamedAsmLabels => [NAMED_ASM_LABELS]); . . impl<'tcx> LateLintPass<'tcx> for NamedAsmLabels { 196 ( 0.00%) fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) { 56 ( 0.00%) if let hir::Expr { . kind: hir::ExprKind::InlineAsm(hir::InlineAsm { template_strs, .. }), . .. . } = expr . { . for (template_sym, template_snippet, template_span) in template_strs.iter() { . let template_str = template_sym.as_str(); . let find_label_span = |needle: &str| -> Option { . if let Some(template_snippet) = template_snippet { -- line 3179 ---------------------------------------- -- line 3242 ---------------------------------------- . BuiltinLintDiagnostics::NamedAsmLabel( . "only local labels of the form `:` should be used in inline asm" . .to_string(), . ), . ); . } . } . } 224 ( 0.00%) } . } 2,356 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/span_encoding.rs -------------------------------------------------------------------------------- Ir -- line 55 ---------------------------------------- . /// `ctxt` values depend partly on the crate size and partly on the form of . /// the code. No crates in `rustc-perf` need more than 15 bits for `ctxt`, . /// but larger crates might need more than 16 bits. . /// . /// In order to reliably use parented spans in incremental compilation, . /// the dependency to the parent definition's span. This is performed . /// using the callback `SPAN_TRACK` to access the query engine. . /// 36,891 ( 0.04%) #[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 { 578 ( 0.00%) base_or_index: u32, 582 ( 0.00%) len_or_tag: u16, 542 ( 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 { 17,789 ( 0.02%) if lo > hi { . std::mem::swap(&mut lo, &mut hi); . } . 35,578 ( 0.04%) let (base, len, ctxt2) = (lo.0, hi.0 - lo.0, ctxt.as_u32()); . 112,274 ( 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 = 60 ( 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 } . } 44,807 ( 0.05%) } . . #[inline] . pub fn data(self) -> SpanData { . let data = self.data_untracked(); 22 ( 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 { 184,638 ( 0.20%) 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), 182,366 ( 0.20%) 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); 28 ( 0.00%) let index = self.base_or_index; 121 ( 0.00%) with_span_interner(|interner| interner.spans[index as usize]) . } 137,423 ( 0.15%) } . } . 4 ( 0.00%) #[derive(Default)] . pub struct SpanInterner { . spans: FxIndexSet, . } . . impl SpanInterner { 6 ( 0.00%) fn intern(&mut self, span_data: &SpanData) -> u32 { 8 ( 0.00%) let (index, _) = self.spans.insert_full(*span_data); . index as u32 8 ( 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())) . } 152,271 ( 0.17%) -------------------------------------------------------------------------------- -- 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 { 22,320 ( 0.02%) 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 1,959 ( 0.00%) if text.len() < 2 * USIZE_BYTES { 1,579 ( 0.00%) return text.iter().position(|elt| *elt == x); . } . 1,813 ( 0.00%) memchr_general_case(x, text) . } . 1,836 ( 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); . 918 ( 0.00%) if offset > 0 { . offset = cmp::min(offset, len); 1,588 ( 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); 9,928 ( 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); 12,936 ( 0.01%) let v = *(ptr.add(offset + USIZE_BYTES) as *const usize); . . // break if there is a matching byte 12,936 ( 0.01%) let zu = contains_zero_byte(u ^ repeated_x); 12,936 ( 0.01%) let zv = contains_zero_byte(v ^ repeated_x); 8,624 ( 0.01%) if zu || zv { . break; . } . } 8,566 ( 0.01%) offset += USIZE_BYTES * 2; . } . . // Find the byte after the point the body loop stopped. 3,313 ( 0.00%) text[offset..].iter().position(|elt| *elt == x).map(|i| offset + i) 2,295 ( 0.00%) } . . /// Returns the last index matching the byte `x` in `text`. . #[must_use] 360 ( 0.00%) 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, . // - body, scanned by 2 words at a time, . // - the first remaining bytes, < 2 word size. . let len = text.len(); . let ptr = text.as_ptr(); -- line 104 ---------------------------------------- -- line 105 ---------------------------------------- . type Chunk = usize; . . let (min_aligned_offset, max_aligned_offset) = { . // We call this just to obtain the length of the prefix and suffix. . // In the middle we always process two chunks at once. . // SAFETY: transmuting `[u8]` to `[usize]` is safe except for size differences . // which are handled by `align_to`. . let (prefix, _, suffix) = unsafe { text.align_to::<(Chunk, Chunk)>() }; 360 ( 0.00%) (prefix.len(), len - suffix.len()) . }; . . let mut offset = max_aligned_offset; 1,576 ( 0.00%) if let Some(index) = text[offset..].iter().rposition(|elt| *elt == x) { 8 ( 0.00%) return Some(offset + index); . } . . // Search the body of the text, make sure we don't cross min_aligned_offset. . // offset is always aligned, so just testing `>` is sufficient and avoids possible . // overflow. . let repeated_x = repeat_byte(x); . let chunk_bytes = mem::size_of::(); . 304 ( 0.00%) while offset > min_aligned_offset { . // SAFETY: offset starts at len - suffix.len(), as long as it is greater than . // min_aligned_offset (prefix.len()) the remaining distance is at least 2 * chunk_bytes. . unsafe { 536 ( 0.00%) let u = *(ptr.offset(offset as isize - 2 * chunk_bytes as isize) as *const Chunk); . let v = *(ptr.offset(offset as isize - chunk_bytes as isize) as *const Chunk); . . // Break if there is a matching byte. 456 ( 0.00%) let zu = contains_zero_byte(u ^ repeated_x); 456 ( 0.00%) let zv = contains_zero_byte(v ^ repeated_x); 304 ( 0.00%) if zu || zv { . break; . } . } 108 ( 0.00%) offset -= 2 * chunk_bytes; . } . . // Find the byte before the point the body loop stopped. 1,616 ( 0.00%) text[..offset].iter().rposition(|elt| *elt == x) 480 ( 0.00%) } 8,008 ( 0.01%) -------------------------------------------------------------------------------- -- 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) { 18,057 ( 0.02%) self.hash = self.hash.rotate_left(5).bitxor(i).wrapping_mul(K); . } . } . . impl Hasher for FxHasher { . #[inline] 521 ( 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()); . 12,568 ( 0.01%) let mut hash = FxHasher { hash: self.hash }; . assert!(size_of::() <= 8); 145,181 ( 0.16%) while bytes.len() >= size_of::() { . hash.add_to_hash(read_usize(bytes) as usize); . bytes = &bytes[size_of::()..]; . } 24,988 ( 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..]; . } 24,988 ( 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..]; . } 27,925 ( 0.03%) if (size_of::() > 1) && bytes.len() >= 1 { 6,697 ( 0.01%) hash.add_to_hash(bytes[0] as usize); . } 599 ( 0.00%) self.hash = hash.hash; 521 ( 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) { 273 ( 0.00%) self.add_to_hash(i as usize); . } . . #[inline] . fn write_u32(&mut self, i: u32) { 41,197 ( 0.04%) 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/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,992 ( 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 { 345,473 ( 0.38%) 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 { 2,282 ( 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) { 2,930 ( 0.00%) if self.start < self.end { . let hint = Step::steps_between(&self.start, &self.end); . (hint.unwrap_or(usize::MAX), hint) . } else { . (0, Some(0)) . } . } . . #[inline] -- line 724 ---------------------------------------- -- line 857 ---------------------------------------- . impl FusedIterator for ops::Range {} . . #[stable(feature = "rust1", since = "1.0.0")] . impl Iterator for ops::RangeFrom { . type Item = A; . . #[inline] . fn next(&mut self) -> Option { 80 ( 0.00%) let n = Step::forward(self.start.clone(), 1); . Some(mem::replace(&mut self.start, n)) . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { . (usize::MAX, None) . } . -- line 873 ---------------------------------------- -- line 998 ---------------------------------------- . . try { accum } . } . } . . impl RangeInclusiveIteratorImpl for ops::RangeInclusive { . #[inline] . fn spec_next(&mut self) -> Option { 16 ( 0.00%) if self.is_empty() { . return None; . } . let is_iterating = self.start < self.end; 10 ( 0.00%) Some(if is_iterating { . // SAFETY: just checked precondition . let n = unsafe { Step::forward_unchecked(self.start.clone(), 1) }; . mem::replace(&mut self.start, n) . } else { . self.exhausted = true; . self.start.clone() . }) . } -- line 1018 ---------------------------------------- -- line 1025 ---------------------------------------- . R: Try, . { . if self.is_empty() { . return try { init }; . } . . let mut accum = init; . 63 ( 0.00%) while self.start < self.end { . // SAFETY: just checked precondition . let n = unsafe { Step::forward_unchecked(self.start.clone(), 1) }; . let n = mem::replace(&mut self.start, n); . accum = f(accum, n)?; . } . . self.exhausted = true; . 7 ( 0.00%) if self.start == self.end { . accum = f(accum, self.start.clone())?; . } . . try { accum } . } . . #[inline] . fn spec_next_back(&mut self) -> Option { -- line 1050 ---------------------------------------- -- line 1098 ---------------------------------------- . . #[inline] . fn next(&mut self) -> Option { . self.spec_next() . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 64 ( 0.00%) if self.is_empty() { . return (0, Some(0)); . } . . match Step::steps_between(&self.start, &self.end) { . Some(hint) => (hint.saturating_add(1), hint.checked_add(1)), . None => (usize::MAX, None), . } . } -- line 1114 ---------------------------------------- 45,324 ( 0.05%) -------------------------------------------------------------------------------- -- 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`. 16,588 ( 0.02%) 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. 16,588 ( 0.02%) let mut trees = input.trees(); 21,645 ( 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`). 15,265 ( 0.02%) let tree = parse_tree(tree, &mut trees, expect_matchers, sess, node_id, features, edition); 6,974 ( 0.01%) match tree { 1,704 ( 0.00%) TokenTree::MetaVar(start_sp, ident) if expect_matchers => { 1,988 ( 0.00%) let span = match trees.next() { 284 ( 0.00%) Some(tokenstream::TokenTree::Token(Token { kind: token::Colon, span })) => { 1,420 ( 0.00%) match trees.next() { 2,556 ( 0.00%) Some(tokenstream::TokenTree::Token(token)) => match token.ident() { 568 ( 0.00%) Some((frag, _)) => { 1,704 ( 0.00%) let span = token.span.with_lo(start_sp.lo()); . . let kind = 1,136 ( 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 . }, . ); 2,272 ( 0.00%) result.push(TokenTree::MetaVarDecl(span, ident, Some(kind))); . continue; . } . _ => token.span, . }, . tree => tree.as_ref().map_or(span, tokenstream::TokenTree::span), . } 568 ( 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 38,766 ( 0.04%) _ => result.push(tree), . } . } . result 11,484 ( 0.01%) } . . /// 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 10,906 ( 0.01%) match tree { . // `tree` is a `$` token. Look at the next token in `trees` 1,257 ( 0.00%) tokenstream::TokenTree::Token(Token { kind: token::Dollar, span }) => { . // FIXME: Handle `None`-delimited groups in a more systematic way . // during parsing. 3,771 ( 0.00%) let mut next = outer_trees.next(); . let mut trees: Box>; 4,821 ( 0.01%) if let Some(tokenstream::TokenTree::Delimited(_, token::NoDelim, tts)) = next { . trees = Box::new(tts.into_trees()); . next = trees.next(); . } else { 5,028 ( 0.01%) trees = Box::new(outer_trees); . } . 3,978 ( 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)*`). 3,675 ( 0.00%) Some(tokenstream::TokenTree::Delimited(span, delim, tts)) => { . // Must have `(` not `{` or `[` 525 ( 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 4,725 ( 0.01%) let sequence = parse(tts, expect_matchers, sess, node_id, features, edition); . // Get the Kleene operator and optional separator 3,150 ( 0.00%) let (separator, kleene) = 525 ( 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); 4,200 ( 0.00%) TokenTree::Sequence( . span, . Lrc::new(SequenceRepetition { 2,100 ( 0.00%) tts: sequence, 2,625 ( 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. 5,856 ( 0.01%) Some(tokenstream::TokenTree::Token(token)) if token.is_ident() => { 1,464 ( 0.00%) let (ident, is_raw) = token.ident().unwrap(); 2,196 ( 0.00%) let span = ident.span.with_lo(span.lo()); 5,124 ( 0.01%) if ident.name == kw::Crate && !is_raw { 256 ( 0.00%) TokenTree::token(token::Ident(kw::DollarCrate, is_raw), span) . } else { 3,340 ( 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. 5,715 ( 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. 4,571 ( 0.00%) tokenstream::TokenTree::Delimited(span, delim, tts) => TokenTree::Delimited( . span, 2,612 ( 0.00%) Lrc::new(Delimited { . delim, 5,224 ( 0.01%) tts: parse(tts, expect_matchers, sess, node_id, features, edition), . }), . ), . } 6,285 ( 0.01%) } . . /// Takes a token and returns `Some(KleeneOp)` if the token is `+` `*` or `?`. Otherwise, return . /// `None`. . fn kleene_op(token: &Token) -> Option { 2,956 ( 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 2,960 ( 0.00%) fn parse_kleene_op( . input: &mut impl Iterator, . span: Span, . ) -> Result, Span> { 1,184 ( 0.00%) match input.next() { 1,184 ( 0.00%) Some(tokenstream::TokenTree::Token(token)) => match kleene_op(&token) { 1,575 ( 0.00%) Some(op) => Ok(Ok((op, token.span))), 603 ( 0.00%) None => Ok(Err(token)), . }, . tree => Err(tree.as_ref().map_or(span, tokenstream::TokenTree::span)), . } 2,368 ( 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 4,200 ( 0.00%) let span = match parse_kleene_op(input, span) { . // #1 is a `?`, `+`, or `*` KleeneOp 1,374 ( 0.00%) Ok(Ok((op, span))) => return (None, KleeneToken::new(op, span)), . . // #1 is a separator followed by #2, a KleeneOp 1,005 ( 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 402 ( 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 ---------------------------------------- 15,528 ( 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, . ) { 2,475 ( 0.00%) if let Some((file, file_idx)) = new_file_and_idx { 18 ( 0.00%) self.file = file; 9 ( 0.00%) self.file_index = file_idx; . } . 2,423 ( 0.00%) let line_index = self.file.lookup_line(pos).unwrap(); . let line_bounds = self.file.line_bounds(line_index); 4,864 ( 0.01%) self.line_number = line_index + 1; 7,279 ( 0.01%) self.line = line_bounds; . self.touch(time_stamp); . } . . #[inline] . fn touch(&mut self, time_stamp: usize) { 25,939 ( 0.03%) 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> { 84 ( 0.00%) pub fn new(source_map: &'sm SourceMap) -> CachingSourceMapView<'sm> { . let files = source_map.files(); 42 ( 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, . }; . 210 ( 0.00%) CachingSourceMapView { . source_map, 294 ( 0.00%) line_cache: [entry.clone(), entry.clone(), entry], . time_stamp: 0, . } 168 ( 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)) . } . 99,267 ( 0.11%) pub fn span_data_to_lines_and_cols( . &mut self, . span_data: &SpanData, . ) -> Option<(Lrc, usize, BytePos, usize, BytePos)> { 56,724 ( 0.06%) self.time_stamp += 1; . . // Check if lo and hi are in the cached lines. 14,181 ( 0.02%) let lo_cache_idx = self.cache_entry_index(span_data.lo); 14,181 ( 0.02%) let hi_cache_idx = self.cache_entry_index(span_data.hi); . 23,516 ( 0.03%) 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 = { 23,516 ( 0.03%) let lo = &self.line_cache[lo_cache_idx as usize]; . let hi = &self.line_cache[hi_cache_idx as usize]; . 70,548 ( 0.08%) if lo.file_index != hi.file_index { . return None; . } . . ( 23,516 ( 0.03%) lo.file.clone(), . lo.line_number, . span_data.lo - lo.line.start, 11,758 ( 0.01%) hi.line_number, . span_data.hi - hi.line.start, . ) . }; . 11,758 ( 0.01%) self.line_cache[lo_cache_idx as usize].touch(self.time_stamp); 11,758 ( 0.01%) self.line_cache[hi_cache_idx as usize].touch(self.time_stamp); . 47,032 ( 0.05%) return Some(result); . } . . // No cache hit or cache hit for only one of span lo and hi. 4,846 ( 0.01%) 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. 19,384 ( 0.02%) 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; 7,269 ( 0.01%) if !file_contains(&file, span_data.hi) { . return None; . } . 7,269 ( 0.01%) None . }; . . // Update the cache entries. 12,115 ( 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); . 7,191 ( 0.01%) 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]; 26 ( 0.00%) hi.update(new_file_and_idx, span_data.hi, self.time_stamp); 52 ( 0.00%) let lo = &mut self.line_cache[lo_cache_idx as usize]; 104 ( 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. 4,846 ( 0.01%) assert!(span_data.lo >= lo.line.start); 2,423 ( 0.00%) assert!(span_data.lo <= lo.line.end); 4,846 ( 0.01%) assert!(span_data.hi >= hi.line.start); 2,423 ( 0.00%) assert!(span_data.hi <= hi.line.end); 12,115 ( 0.01%) assert!(lo.file.contains(span_data.lo)); 7,269 ( 0.01%) assert!(lo.file.contains(span_data.hi)); 7,269 ( 0.01%) assert_eq!(lo.file_index, hi.file_index); . 7,269 ( 0.01%) Some(( 2,423 ( 0.00%) lo.file.clone(), . lo.line_number, . span_data.lo - lo.line.start, 2,423 ( 0.00%) hi.line_number, . span_data.hi - hi.line.start, . )) 127,629 ( 0.14%) } . . fn cache_entry_index(&self, pos: BytePos) -> isize { . for (idx, cache_entry) in self.line_cache.iter().enumerate() { 172,109 ( 0.19%) 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() { 14,382 ( 0.02%) 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() { 215 ( 0.00%) if idx != avoid_idx 108 ( 0.00%) && self.line_cache[idx].time_stamp < self.line_cache[oldest].time_stamp . { . oldest = idx; . } . } . . oldest . } . -- line 270 ---------------------------------------- 186,992 ( 0.20%) -------------------------------------------------------------------------------- -- 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);)*) => { 9,480 ( 0.01%) $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> { . self.opaque.$name(value) 11,376 ( 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 { 94 ( 0.00%) e.emit_lazy_distance(*self) . } . } . . impl<'a, 'tcx, T: Encodable>> Encodable> . for Lazy<[T]> . { 10 ( 0.00%) fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { . e.emit_usize(self.meta)?; 42 ( 0.00%) if self.meta == 0 { . return Ok(()); . } 68 ( 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 { 329 ( 0.00%) fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { 366 ( 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()) 282 ( 0.00%) } . } . . impl<'a, 'tcx> Encodable> for DefIndex { 280 ( 0.00%) fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { . s.emit_u32(self.as_u32()) 336 ( 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 { 37,015 ( 0.04%) fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { 22,209 ( 0.02%) rustc_span::hygiene::raw_encode_syntax_context(*self, &s.hygiene_ctxt, s) 44,418 ( 0.05%) } . } . . impl<'a, 'tcx> Encodable> for ExpnId { . fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { 45 ( 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. 142 ( 0.00%) s.hygiene_ctxt.schedule_expn_data_for_encoding(*self); . } 96 ( 0.00%) self.krate.encode(s)?; . self.local_id.encode(s) . } . } . . impl<'a, 'tcx> Encodable> for Span { 59,176 ( 0.06%) fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { 44,382 ( 0.05%) 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. 14,794 ( 0.02%) if s.is_proc_macro { . SyntaxContext::root().encode(s)?; . } else { 7,397 ( 0.01%) span.ctxt.encode(s)?; . } . 7,397 ( 0.01%) 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); . 36,880 ( 0.04%) 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); . } . 22,128 ( 0.02%) 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` 7,376 ( 0.01%) 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. 44,256 ( 0.05%) 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 { 22,128 ( 0.02%) (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)?; . 14,752 ( 0.02%) 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(()) 59,176 ( 0.06%) } . } . . 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 { 267 ( 0.00%) fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) { 186 ( 0.00%) self.encode(ecx).unwrap() 6 ( 0.00%) } . } . . impl<'a, 'tcx, T: Encodable>> EncodeContentsForLazy<'a, 'tcx, T> for T { 669 ( 0.00%) fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) { 389 ( 0.00%) self.encode(ecx).unwrap() 429 ( 0.00%) } . } . . impl<'a, 'tcx, I, T: Encodable>> EncodeContentsForLazy<'a, 'tcx, [T]> for I . where . I: IntoIterator, . I::Item: EncodeContentsForLazy<'a, 'tcx, T>, . { 77 ( 0.00%) fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> usize { 1,250 ( 0.00%) self.into_iter().map(|value| value.encode_contents_for_lazy(ecx)).count() 99 ( 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> { 315 ( 0.00%) fn emit_lazy_distance( . &mut self, . lazy: Lazy, . ) -> Result<(), ::Error> { . let pos = lazy.position.get(); 267 ( 0.00%) let distance = match self.lazy_state { . LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"), 24 ( 0.00%) LazyState::NodeStart(start) => { . let start = start.get(); 48 ( 0.00%) assert!(pos <= start); . start - pos . } 39 ( 0.00%) LazyState::Previous(last_pos) => { 39 ( 0.00%) assert!( . last_pos <= lazy.position, . "make sure that the calls to `lazy*` \ . are in the same order as the metadata fields", . ); 117 ( 0.00%) lazy.position.get() - last_pos.get() . } . }; 126 ( 0.00%) self.lazy_state = LazyState::Previous(NonZeroUsize::new(pos).unwrap()); . self.emit_usize(distance) 315 ( 0.00%) } . 394 ( 0.00%) fn lazy( . &mut self, . value: impl EncodeContentsForLazy<'a, 'tcx, T>, . ) -> Lazy { . let pos = NonZeroUsize::new(self.position()).unwrap(); . 469 ( 0.00%) assert_eq!(self.lazy_state, LazyState::NoNode); 1,378 ( 0.00%) self.lazy_state = LazyState::NodeStart(pos); 880 ( 0.00%) let meta = value.encode_contents_for_lazy(self); 553 ( 0.00%) self.lazy_state = LazyState::NoNode; . 997 ( 0.00%) assert!(pos.get() <= self.position()); . . Lazy::from_position_and_meta(pos, meta) 578 ( 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); 212 ( 0.00%) self.tables.def_keys.set(def_index, def_key); 212 ( 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 853 ---------------------------------------- . /// Whether we should encode MIR. . /// . /// Computing, optimizing and encoding the MIR is a relatively expensive operation. . /// We want to avoid this work when not required. Therefore: . /// - we only compute `mir_for_ctfe` on items with const-eval semantics; . /// - we skip `optimized_mir` for check runs. . /// . /// Return a pair, resp. for CTFE and for LLVM. 54 ( 0.00%) fn should_encode_mir(tcx: TyCtxt<'_>, def_id: LocalDefId) -> (bool, bool) { 30 ( 0.00%) match tcx.def_kind(def_id) { . // Constructors . DefKind::Ctor(_, _) => { 12 ( 0.00%) let mir_opt_base = tcx.sess.opts.output_types.should_codegen() . || tcx.sess.opts.debugging_opts.always_encode_mir; . (true, mir_opt_base) . } . // Constants . DefKind::AnonConst . | DefKind::InlineConst . | DefKind::AssocConst . | DefKind::Static . | DefKind::Const => (true, false), . // Full-fledged functions . DefKind::AssocFn | DefKind::Fn => { . let generics = tcx.generics_of(def_id); 16 ( 0.00%) let needs_inline = (generics.requires_monomorphization(tcx) . || tcx.codegen_fn_attrs(def_id).requests_inline()) 12 ( 0.00%) && tcx.sess.opts.output_types.should_codegen(); . // The function has a `const` modifier or is annotated with `default_method_body_is_const`. 4 ( 0.00%) let is_const_fn = tcx.is_const_fn_raw(def_id.to_def_id()) 20 ( 0.00%) || tcx.has_attr(def_id.to_def_id(), sym::default_method_body_is_const); . let always_encode_mir = tcx.sess.opts.debugging_opts.always_encode_mir; 8 ( 0.00%) (is_const_fn, needs_inline || always_encode_mir) . } . // Closures can't be const fn. . DefKind::Closure => { . let generics = tcx.generics_of(def_id); . let needs_inline = (generics.requires_monomorphization(tcx) . || tcx.codegen_fn_attrs(def_id).requests_inline()) . && tcx.sess.opts.output_types.should_codegen(); . let always_encode_mir = tcx.sess.opts.debugging_opts.always_encode_mir; . (false, needs_inline || always_encode_mir) . } . // Generators require optimized MIR to compute layout. . DefKind::Generator => (false, true), . // The others don't have MIR. . _ => (false, false), . } 54 ( 0.00%) } . . fn should_encode_variances(def_kind: DefKind) -> bool { . match def_kind { . DefKind::Struct . | DefKind::Union . | DefKind::Enum . | DefKind::Variant . | DefKind::Fn -- line 909 ---------------------------------------- -- 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); 318 ( 0.00%) let def_kind = if let Some(def_kind) = def_kind { def_kind } else { continue }; 672 ( 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, . }); 126 ( 0.00%) record!(self.tables.span[def_id] <- tcx.def_span(def_id)); 504 ( 0.00%) record!(self.tables.attributes[def_id] <- tcx.get_attrs(def_id)); 336 ( 0.00%) record!(self.tables.expn_that_defined[def_id] <- self.tcx.expn_that_defined(def_id)); . if should_encode_visibility(def_kind) { 192 ( 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); 180 ( 0.00%) self.encode_deprecation(def_id); . } . if should_encode_variances(def_kind) { 18 ( 0.00%) let v = self.tcx.variances_of(def_id); 63 ( 0.00%) record!(self.tables.variances[def_id] <- v); . } . if should_encode_generics(def_kind) { . let g = tcx.generics_of(def_id); 104 ( 0.00%) record!(self.tables.generics[def_id] <- g); 312 ( 0.00%) record!(self.tables.explicit_predicates[def_id] <- self.tcx.explicit_predicates_of(def_id)); 26 ( 0.00%) let inferred_outlives = self.tcx.inferred_outlives_of(def_id); 34 ( 0.00%) if !inferred_outlives.is_empty() { . record!(self.tables.inferred_outlives[def_id] <- inferred_outlives); . } . } 294 ( 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() { 2 ( 0.00%) if implementations.is_empty() { . continue; . } 18 ( 0.00%) record!(self.tables.inherent_impls[def_id.to_def_id()] <- implementations.iter().map(|&def_id| { 2 ( 0.00%) assert!(def_id.is_local()); . def_id.index . })); . } . } . 126 ( 0.00%) fn encode_item_type(&mut self, def_id: DefId) { . debug!("EncodeContext::encode_item_type({:?})", def_id); 108 ( 0.00%) record!(self.tables.ty[def_id] <- self.tcx.type_of(def_id)); 144 ( 0.00%) } . . fn encode_enum_variant_info(&mut self, def: &ty::AdtDef, index: VariantIdx) { . let tcx = self.tcx; . let variant = &def.variants[index]; . let def_id = variant.def_id; . debug!("EncodeContext::encode_enum_variant_info({:?})", def_id); . . let data = VariantData { -- line 1043 ---------------------------------------- -- 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)); . } . } . 20 ( 0.00%) fn encode_info_for_mod(&mut self, local_def_id: LocalDefId, md: &hir::Mod<'_>) { 4 ( 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. 6 ( 0.00%) let reexports = if !self.is_proc_macro { 4 ( 0.00%) match tcx.module_reexports(local_def_id) { . Some(exports) => self.lazy(exports), . _ => Lazy::empty(), . } . } else { . Lazy::empty() . }; . 8 ( 0.00%) record!(self.tables.kind[def_id] <- EntryKind::Mod(reexports)); 4 ( 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. 4 ( 0.00%) let tcx = self.tcx; . let foreign_item_children = md . .item_ids . .iter() 115 ( 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(); . 14 ( 0.00%) record!(self.tables.children[def_id] <- direct_children.chain(foreign_item_children)); . } 16 ( 0.00%) } . . fn encode_field( . &mut self, . adt_def: &ty::AdtDef, . variant_index: VariantIdx, . field_index: usize, . ) { . let variant = &adt_def.variants[variant_index]; . let field = &variant.fields[field_index]; . . let def_id = field.did; . debug!("EncodeContext::encode_field({:?})", def_id); . . record!(self.tables.kind[def_id] <- EntryKind::Field); 8 ( 0.00%) self.encode_ident_span(def_id, field.ident(self.tcx)); 12 ( 0.00%) self.encode_item_type(def_id); . } . . fn encode_struct_ctor(&mut self, adt_def: &ty::AdtDef, def_id: DefId) { . debug!("EncodeContext::encode_struct_ctor({:?})", def_id); 2 ( 0.00%) let tcx = self.tcx; 6 ( 0.00%) let variant = adt_def.non_enum_variant(); . . let data = VariantData { 2 ( 0.00%) ctor_kind: variant.ctor_kind, . discr: variant.discr, . ctor: Some(def_id.index), 2 ( 0.00%) is_non_exhaustive: variant.is_field_list_non_exhaustive(), . }; . 14 ( 0.00%) record!(self.tables.kind[def_id] <- EntryKind::Struct(self.lazy(data), adt_def.repr)); 10 ( 0.00%) self.encode_item_type(def_id); 2 ( 0.00%) if variant.ctor_kind == CtorKind::Fn { 2 ( 0.00%) record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); . } . } . . fn encode_explicit_item_bounds(&mut self, def_id: DefId) { . debug!("EncodeContext::encode_explicit_item_bounds({:?})", def_id); . let bounds = self.tcx.explicit_item_bounds(def_id); . if !bounds.is_empty() { . record!(self.tables.explicit_item_bounds[def_id] <- bounds); -- line 1168 ---------------------------------------- -- line 1234 ---------------------------------------- . } . if trait_item.kind == ty::AssocKind::Fn { . record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); . } . } . . fn encode_info_for_impl_item(&mut self, def_id: DefId) { . debug!("EncodeContext::encode_info_for_impl_item({:?})", def_id); 8 ( 0.00%) let tcx = self.tcx; . 24 ( 0.00%) let ast_item = self.tcx.hir().expect_impl_item(def_id.expect_local()); 4 ( 0.00%) let impl_item = self.tcx.associated_item(def_id); . 16 ( 0.00%) let container = match impl_item.defaultness { . hir::Defaultness::Default { has_value: true } => AssocContainer::ImplDefault, . hir::Defaultness::Final => AssocContainer::ImplFinal, . hir::Defaultness::Default { has_value: false } => { . span_bug!(ast_item.span, "impl items always have values (currently)") . } . }; . 24 ( 0.00%) match impl_item.kind { . ty::AssocKind::Const => { . if let hir::ImplItemKind::Const(_, body_id) = ast_item.kind { . let qualifs = self.tcx.at(ast_item.span).mir_const_qualif(def_id); . . record!(self.tables.kind[def_id] <- EntryKind::AssocConst( . container, . qualifs, . self.encode_rendered_const_for_body(body_id)) . ); . } else { . bug!() . } . } . ty::AssocKind::Fn => { 8 ( 0.00%) let fn_data = if let hir::ImplItemKind::Fn(ref sig, body) = ast_item.kind { . FnData { . asyncness: sig.header.asyncness, . // Can be inside `impl const Trait`, so using sig.header.constness is not reliable 4 ( 0.00%) constness: if self.tcx.is_const_fn_raw(def_id) { . hir::Constness::Const . } else { . hir::Constness::NotConst . }, . param_names: self.encode_fn_param_names_for_body(body), . } . } else { . bug!() -- line 1282 ---------------------------------------- -- line 1286 ---------------------------------------- . container, . has_self: impl_item.fn_has_self_parameter, . }))); . } . ty::AssocKind::Type => { . record!(self.tables.kind[def_id] <- EntryKind::AssocType(container)); . } . } 12 ( 0.00%) self.encode_ident_span(def_id, impl_item.ident(self.tcx)); 20 ( 0.00%) self.encode_item_type(def_id); 16 ( 0.00%) if let Some(trait_item_def_id) = impl_item.trait_item_def_id { . record!(self.tables.trait_item_def_id[def_id] <- trait_item_def_id); . } 4 ( 0.00%) if impl_item.kind == ty::AssocKind::Fn { . record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); . } . } . . fn encode_fn_param_names_for_body(&mut self, body_id: hir::BodyId) -> Lazy<[Ident]> { 28 ( 0.00%) 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| { 30 ( 0.00%) let (encode_const, encode_opt) = should_encode_mir(self.tcx, def_id); 36 ( 0.00%) if encode_const || encode_opt { 12 ( 0.00%) Some((def_id, encode_const, encode_opt)) . } else { . None . } 12 ( 0.00%) }) . .collect::>(); 35 ( 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); 6 ( 0.00%) if encode_opt { 24 ( 0.00%) record!(self.tables.mir[def_id.to_def_id()] <- self.tcx.optimized_mir(def_id)); . } 6 ( 0.00%) if encode_const { 8 ( 0.00%) record!(self.tables.mir_for_ctfe[def_id.to_def_id()] <- self.tcx.mir_for_ctfe(def_id)); . . // FIXME(generic_const_exprs): this feels wrong to have in `encode_mir` 2 ( 0.00%) let abstract_const = self.tcx.thir_abstract_const(def_id); 8 ( 0.00%) if let Ok(Some(abstract_const)) = abstract_const { . record!(self.tables.thir_abstract_consts[def_id.to_def_id()] <- abstract_const); . } . } 24 ( 0.00%) record!(self.tables.promoted_mir[def_id.to_def_id()] <- self.tcx.promoted_mir(def_id)); . . let instance = . ty::InstanceDef::Item(ty::WithOptConstParam::unknown(def_id.to_def_id())); 6 ( 0.00%) let unused = self.tcx.unused_generic_params(instance); 6 ( 0.00%) if !unused.is_empty() { . record!(self.tables.unused_generic_params[def_id.to_def_id()] <- unused); . } . } . } . . 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. 240 ( 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. 210 ( 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) . } . } . } . 180 ( 0.00%) fn encode_deprecation(&mut self, def_id: DefId) { . debug!("EncodeContext::encode_deprecation({:?})", def_id); 150 ( 0.00%) if let Some(depr) = self.tcx.lookup_deprecation(def_id) { . record!(self.tables.deprecation[def_id] <- depr); . } 150 ( 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) . } . 99 ( 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); . 66 ( 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)) . } 2 ( 0.00%) hir::ItemKind::Macro(ref macro_def) => { . EntryKind::MacroDef(self.lazy(macro_def.clone())) . } . hir::ItemKind::Mod(ref m) => { 12 ( 0.00%) 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, . hir::ItemKind::OpaqueTy(..) => { . self.encode_explicit_item_bounds(def_id); . EntryKind::OpaqueTy . } . hir::ItemKind::Enum(..) => EntryKind::Enum(self.tcx.adt_def(def_id).repr), . hir::ItemKind::Struct(ref struct_def, _) => { 6 ( 0.00%) let adt_def = self.tcx.adt_def(def_id); 9 ( 0.00%) let variant = adt_def.non_enum_variant(); . . // Encode def_ids for each field and method . // for methods, write all the stuff get_trait_method . // needs to know 12 ( 0.00%) let ctor = struct_def . .ctor_hir_id() 8 ( 0.00%) .map(|ctor_hir_id| self.tcx.hir().local_def_id(ctor_hir_id).local_def_index); . . EntryKind::Struct( . self.lazy(VariantData { 3 ( 0.00%) ctor_kind: variant.ctor_kind, 12 ( 0.00%) discr: variant.discr, . ctor, . is_non_exhaustive: variant.is_field_list_non_exhaustive(), . }), 9 ( 0.00%) adt_def.repr, . ) . } . hir::ItemKind::Union(..) => { . let adt_def = self.tcx.adt_def(def_id); . let variant = adt_def.non_enum_variant(); . . EntryKind::Union( . self.lazy(VariantData { -- line 1461 ---------------------------------------- -- line 1462 ---------------------------------------- . ctor_kind: variant.ctor_kind, . discr: variant.discr, . ctor: None, . is_non_exhaustive: variant.is_field_list_non_exhaustive(), . }), . adt_def.repr, . ) . } 20 ( 0.00%) hir::ItemKind::Impl(hir::Impl { defaultness, constness, .. }) => { 16 ( 0.00%) let trait_ref = self.tcx.impl_trait_ref(def_id); 10 ( 0.00%) let polarity = self.tcx.impl_polarity(def_id); 10 ( 0.00%) let parent = if let Some(trait_ref) = trait_ref { 3 ( 0.00%) let trait_def = self.tcx.trait_def(trait_ref.def_id); 18 ( 0.00%) trait_def.ancestors(self.tcx, def_id).ok().and_then(|mut an| { 18 ( 0.00%) an.nth(1).and_then(|node| match node { . specialization_graph::Node::Impl(parent) => Some(parent), . _ => None, . }) . }) . } else { . None . }; . . // if this is an impl of `CoerceUnsized`, create its . // "unsized info", else just store None . let coerce_unsized_info = trait_ref.and_then(|t| { 18 ( 0.00%) if Some(t.def_id) == self.tcx.lang_items().coerce_unsized_trait() { . Some(self.tcx.at(item.span).coerce_unsized_info(def_id)) . } else { . None . } . }); . . let data = ImplData { . polarity, -- line 1496 ---------------------------------------- -- 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. 50 ( 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] <- 9 ( 0.00%) self.tcx.adt_def(def_id).non_enum_variant().fields.iter().map(|f| { 4 ( 0.00%) assert!(f.did.is_local()); . f.did.index . }) . ) . } . hir::ItemKind::Impl { .. } | hir::ItemKind::Trait(..) => { 10 ( 0.00%) let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id); . record!(self.tables.children[def_id] <- . associated_item_def_ids.iter().map(|&def_id| { 4 ( 0.00%) assert!(def_id.is_local()); . def_id.index . }) . ); . } . _ => {} . } 28 ( 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(..) 32 ( 0.00%) | hir::ItemKind::Impl { .. } => self.encode_item_type(def_id), . _ => {} . } 28 ( 0.00%) if let hir::ItemKind::Fn(..) = item.kind { . record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); . } 20 ( 0.00%) if let hir::ItemKind::Impl { .. } = item.kind { 25 ( 0.00%) if let Some(trait_ref) = self.tcx.impl_trait_ref(def_id) { 15 ( 0.00%) record!(self.tables.impl_trait_ref[def_id] <- trait_ref); . } . } 80 ( 0.00%) } . . fn encode_info_for_generic_param(&mut self, def_id: DefId, kind: EntryKind, encode_type: bool) { 24 ( 0.00%) record!(self.tables.kind[def_id] <- kind); 8 ( 0.00%) if encode_type { . self.encode_item_type(def_id); . } . } . . fn encode_info_for_closure(&mut self, hir_id: hir::HirId) { . let def_id = self.tcx.hir().local_def_id(hir_id); . debug!("EncodeContext::encode_info_for_closure({:?})", def_id); . -- line 1584 ---------------------------------------- -- 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 2 ( 0.00%) all_impls.sort_by_cached_key(|&(trait_def_id, _)| tcx.def_path_hash(trait_def_id)); . . let all_impls: Vec<_> = all_impls . .into_iter() 30 ( 0.00%) .map(|(trait_def_id, mut impls)| { . // Bring everything into deterministic order for hashing 1 ( 0.00%) impls.sort_by_cached_key(|&(index, _)| { 2 ( 0.00%) tcx.hir().def_path_hash(LocalDefId { local_def_index: index }) . }); . 8 ( 0.00%) TraitImpls { . trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index), 6 ( 0.00%) impls: self.lazy(&impls), . } 16 ( 0.00%) }) . .collect(); . . self.lazy(&all_impls) . } . . // Encodes all symbols exported from this crate into the metadata. . // . // 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 1914 ---------------------------------------- . } . } . . // FIXME(eddyb) make metadata encoding walk over all definitions, instead of HIR. . impl<'a, 'tcx> Visitor<'tcx> for EncodeContext<'a, 'tcx> { . type NestedFilter = nested_filter::OnlyBodies; . . fn nested_visit_map(&mut self) -> Self::Map { 4 ( 0.00%) self.tcx.hir() . } 252 ( 0.00%) fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) { 28 ( 0.00%) intravisit::walk_expr(self, ex); . self.encode_info_for_expr(ex); 224 ( 0.00%) } . 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>) { 69 ( 0.00%) intravisit::walk_item(self, item); 46 ( 0.00%) match item.kind { . hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {} // ignore these 44 ( 0.00%) _ => self.encode_info_for_item(item.def_id.to_def_id(), item), . } 92 ( 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); . } 108 ( 0.00%) fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) { . intravisit::walk_generics(self, generics); . self.encode_info_for_generics(generics); 96 ( 0.00%) } . } . . impl<'a, 'tcx> EncodeContext<'a, 'tcx> { 21 ( 0.00%) fn encode_fields(&mut self, adt_def: &ty::AdtDef) { . for (variant_index, variant) in adt_def.variants.iter_enumerated() { . for (field_index, _field) in variant.fields.iter().enumerate() { . self.encode_field(adt_def, variant_index, field_index); . } . } 24 ( 0.00%) } . . fn encode_info_for_generics(&mut self, generics: &hir::Generics<'tcx>) { . for param in generics.params { 48 ( 0.00%) let def_id = self.tcx.hir().local_def_id(param.hir_id); 72 ( 0.00%) match param.kind { . GenericParamKind::Lifetime { .. } => continue, . GenericParamKind::Type { default, .. } => { . self.encode_info_for_generic_param( . def_id.to_def_id(), . EntryKind::TypeParam, . default.is_some(), . ); . } -- line 1970 ---------------------------------------- -- line 1975 ---------------------------------------- . record!(self.tables.const_defaults[def_id] <- self.tcx.const_param_default(def_id)) . } . } . } . } . } . . fn encode_info_for_expr(&mut self, expr: &hir::Expr<'_>) { 56 ( 0.00%) if let hir::ExprKind::Closure(..) = expr.kind { . self.encode_info_for_closure(expr.hir_id); . } . } . . 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. 207 ( 0.00%) fn encode_addl_info_for_item(&mut self, item: &hir::Item<'_>) { 115 ( 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 2017 ---------------------------------------- . self.encode_enum_variant_info(def, i); . . if let Some(_ctor_def_id) = variant.ctor_def_id { . self.encode_enum_variant_ctor(def, i); . } . } . } . hir::ItemKind::Struct(ref struct_def, _) => { 3 ( 0.00%) let def = self.tcx.adt_def(item.def_id.to_def_id()); 6 ( 0.00%) self.encode_fields(def); . . // If the struct has a constructor, encode it. 12 ( 0.00%) if let Some(ctor_hir_id) = struct_def.ctor_hir_id() { 12 ( 0.00%) let ctor_def_id = self.tcx.hir().local_def_id(ctor_hir_id); . self.encode_struct_ctor(def, ctor_def_id.to_def_id()); . } . } . hir::ItemKind::Union(..) => { . let def = self.tcx.adt_def(item.def_id.to_def_id()); . self.encode_fields(def); . } . hir::ItemKind::Impl { .. } => { 16 ( 0.00%) for &trait_item_def_id in 5 ( 0.00%) self.tcx.associated_item_def_ids(item.def_id.to_def_id()).iter() . { . self.encode_info_for_impl_item(trait_item_def_id); . } . } . 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); . } . } . } 184 ( 0.00%) } . } . . struct ImplsVisitor<'tcx> { . tcx: TyCtxt<'tcx>, . impls: FxHashMap)>>, . } . . impl<'tcx, 'v> ItemLikeVisitor<'v> for ImplsVisitor<'tcx> { 161 ( 0.00%) fn visit_item(&mut self, item: &hir::Item<'_>) { 46 ( 0.00%) match item.kind { . hir::ItemKind::Impl(..) => { 16 ( 0.00%) if let Some(trait_ref) = self.tcx.impl_trait_ref(item.def_id.to_def_id()) { 18 ( 0.00%) let simplified_self_ty = fast_reject::simplify_type( . self.tcx, . trait_ref.self_ty(), . SimplifyParams::No, . StripReferences::No, . ); . . self.impls . .entry(trait_ref.def_id) . .or_default() . .push((item.def_id.local_def_index, simplified_self_ty)); . } . } . _ => {} . } 184 ( 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<'_>) { 92 ( 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 ---------------------------------------- 16,798 ( 0.02%) -------------------------------------------------------------------------------- -- 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 { 27,166 ( 0.03%) 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. 79,098 ( 0.09%) if index == 0 { . return true; . } . 39,646 ( 0.04%) 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. 17,651 ( 0.02%) None => index == self.len(), . . // This is bit magic equivalent to: b < 128 || b >= 192 22,030 ( 0.02%) 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 1102 ---------------------------------------- . /// ``` . /// let s = "Löwe 老虎 Léopard"; . /// let x: &[_] = &['1', '2']; . /// . /// assert_eq!(s.rfind(x), None); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] 96 ( 0.00%) pub fn rfind<'a, P>(&'a self, pat: P) -> Option . where . P: Pattern<'a, Searcher: ReverseSearcher<'a>>, . { . pat.into_searcher(self).next_match_back().map(|(i, _)| i) 96 ( 0.00%) } . . /// An iterator over substrings of this string slice, separated by . /// characters matched by a pattern. . /// . /// 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 1123 ---------------------------------------- -- line 1225 ---------------------------------------- . /// ``` . /// . /// Use [`split_whitespace`] for this behavior. . /// . /// [`split_whitespace`]: str::split_whitespace . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> { 60 ( 0.00%) Split(SplitInternal { . start: 0, . end: self.len(), . matcher: pat.into_searcher(self), . allow_trailing_empty: true, . finished: false, . }) . } . -- line 1241 ---------------------------------------- -- 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> { 177 ( 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 1825 ---------------------------------------- . /// let s = " עברית "; . /// assert!(Some('ת') == s.trim_end().chars().rev().next()); . /// ``` . #[inline] . #[must_use = "this returns the trimmed string as a new slice, \ . without modifying the original"] . #[stable(feature = "trim_direction", since = "1.30.0")] . pub fn trim_end(&self) -> &str { 5 ( 0.00%) self.trim_end_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 1841 ---------------------------------------- -- 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")] 232 ( 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) } 232 ( 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")] 78 ( 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()) } 78 ( 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 2098 ---------------------------------------- . /// A more complex pattern, using a closure: . /// . /// ``` . /// assert_eq!("1fooX".trim_end_matches(|c| c == '1' || c == 'X'), "1foo"); . /// ``` . #[must_use = "this returns the trimmed string as a new slice, \ . without modifying the original"] . #[stable(feature = "trim_direction", since = "1.30.0")] 45 ( 0.00%) pub fn trim_end_matches<'a, P>(&'a self, pat: P) -> &'a str . where . P: Pattern<'a, Searcher: ReverseSearcher<'a>>, . { . let mut j = 0; . let mut matcher = pat.into_searcher(self); . if let Some((_, b)) = matcher.next_reject_back() { . j = b; . } . // SAFETY: `Searcher` is known to return valid indices. . unsafe { self.get_unchecked(0..j) } 50 ( 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 2125 ---------------------------------------- -- 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 ---------------------------------------- 60 ( 0.00%) -------------------------------------------------------------------------------- -- 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 { 19 ( 0.00%) HashMap { . hash_builder: self.hash_builder.clone(), 4 ( 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, . { 2,802 ( 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, . { 3,005 ( 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, . { 935 ( 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)] 4 ( 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) 8 ( 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 { 1,572 ( 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 { 199 ( 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 { 485 ( 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 963 ---------------------------------------- . /// } . /// . /// assert_eq!(letters[&'s'], 2); . /// assert_eq!(letters[&'t'], 3); . /// assert_eq!(letters[&'u'], 1); . /// assert_eq!(letters.get(&'y'), None); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 8 ( 0.00%) pub fn entry(&mut self, key: K) -> Entry<'_, K, V, S, A> { . let hash = make_insert_hash::(&self.hash_builder, &key); . if let Some(elem) = self.table.find(hash, equivalent_key(&key)) { . Entry::Occupied(OccupiedEntry { . hash, . key: Some(key), . elem, . table: self, . }) . } else { 10 ( 0.00%) Entry::Vacant(VacantEntry { . hash, . key, . table: self, . }) . } 10 ( 0.00%) } . . /// Gets the given key's corresponding entry by reference in the map for in-place manipulation. . /// . /// # Examples . /// . /// ``` . /// use hashbrown::HashMap; . /// -- line 995 ---------------------------------------- -- line 1047 ---------------------------------------- . /// ``` . #[inline] . pub fn get(&self, k: &Q) -> Option<&V> . where . K: Borrow, . Q: Hash + Eq, . { . // Avoid `Option::map` because it bloats LLVM IR. 5,543 ( 0.01%) 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, . { 19,435 ( 0.02%) if self.table.is_empty() { . None . } else { 2 ( 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)] 8,652 ( 0.01%) pub fn contains_key(&self, k: &Q) -> bool . where . K: Borrow, . Q: Hash + Eq, . { . self.get_inner(k).is_some() 16,502 ( 0.02%) } . . /// Returns a mutable reference to the value corresponding to the key. . /// . /// The key may be any borrowed form of the map's key type, but . /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for . /// the key type. . /// . /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html -- line 1177 ---------------------------------------- -- line 1185 ---------------------------------------- . /// let mut map = HashMap::new(); . /// map.insert(1, "a"); . /// if let Some(x) = map.get_mut(&1) { . /// *x = "b"; . /// } . /// assert_eq!(map[&1], "b"); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 2 ( 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. 6 ( 0.00%) match self.get_inner_mut(k) { . Some(&mut (_, ref mut v)) => Some(v), . None => None, . } 4 ( 0.00%) } . . #[inline] . fn get_inner_mut(&mut self, k: &Q) -> Option<&mut (K, V)> . where . K: Borrow, . Q: Hash + Eq, . { 2 ( 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)] 118,930 ( 0.13%) pub fn insert(&mut self, k: K, v: V) -> Option { . let hash = make_insert_hash::(&self.hash_builder, &k); 2 ( 0.00%) if let Some((_, item)) = self.table.get_mut(hash, equivalent_key(&k)) { . Some(mem::replace(item, v)) . } else { 53,435 ( 0.06%) self.table 51,803 ( 0.06%) .insert(hash, (k, v), make_hasher::(&self.hash_builder)); 2,190 ( 0.00%) None . } 105,719 ( 0.12%) } . . /// 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)] 234 ( 0.00%) pub fn remove(&mut self, k: &Q) -> Option . where . K: Borrow, . Q: Hash + Eq, . { . // Avoid `Option::map` because it bloats LLVM IR. 12,241 ( 0.01%) match self.remove_entry(k) { 39 ( 0.00%) Some((_, v)) => Some(v), 285 ( 0.00%) None => None, . } 521 ( 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); 2,857 ( 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, . { 6,990 ( 0.01%) 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)] 18,427 ( 0.02%) 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) 19,897 ( 0.02%) } . . #[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, . { 1,424 ( 0.00%) match self.map.table.find(hash, |(k, _)| is_match(k)) { 7,078 ( 0.01%) Some(elem) => RawEntryMut::Occupied(RawOccupiedEntryMut { . elem, . table: &mut self.map.table, . hash_builder: &self.map.hash_builder, . }), 4,314 ( 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)] 8,663 ( 0.01%) pub fn from_key_hashed_nocheck(self, hash: u64, k: &Q) -> Option<(&'a K, &'a V)> . where . K: Borrow, . Q: Eq, . { 11,741 ( 0.01%) self.from_hash(hash, equivalent(k)) 16,690 ( 0.02%) } . . #[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, . { 18,642 ( 0.02%) 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, . { 6,718 ( 0.01%) let &mut (ref mut k, ref mut v) = self.table.insert_entry( . hash, . (key, value), . make_hasher::(self.hash_builder), . ); . (k, v) . } . . /// Set the value of an entry with a custom hasher function. -- line 2640 ---------------------------------------- -- line 2974 ---------------------------------------- . /// map.insert("a", 1); . /// map.insert("b", 2); . /// map.insert("c", 3); . /// . /// // Not possible with .iter() . /// let vec: Vec<(&str, i32)> = map.into_iter().collect(); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 22 ( 0.00%) fn into_iter(self) -> IntoIter { 565 ( 0.00%) IntoIter { 429 ( 0.00%) inner: self.table.into_iter(), . } 66 ( 0.00%) } . } . . impl<'a, K, V> Iterator for Iter<'a, K, V> { . type Item = (&'a K, &'a V); . . #[cfg_attr(feature = "inline-more", inline)] . fn next(&mut self) -> Option<(&'a K, &'a V)> { . // Avoid `Option::map` because it bloats LLVM IR. 1,288 ( 0.00%) match self.inner.next() { . Some(x) => unsafe { . let r = x.as_ref(); 14 ( 0.00%) 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)> { 31 ( 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 3819 ---------------------------------------- . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn insert(self, value: V) -> &'a mut V . where . K: Hash, . S: BuildHasher, . { . let table = &mut self.table.table; 4 ( 0.00%) let entry = table.insert_entry( . self.hash, . (self.key, value), . make_hasher::(&self.table.hash_builder), . ); . &mut entry.1 . } . . #[cfg_attr(feature = "inline-more", inline)] -- line 3835 ---------------------------------------- -- line 4557 ---------------------------------------- . /// keys with new values returned from the iterator. . impl Extend<(K, V)> for HashMap . where . K: Eq + Hash, . S: BuildHasher, . A: Allocator + Clone, . { . #[cfg_attr(feature = "inline-more", inline)] 548 ( 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. 543 ( 0.00%) let iter = iter.into_iter(); 143 ( 0.00%) let reserve = if self.is_empty() { . iter.size_hint().0 . } else { 3 ( 0.00%) (iter.size_hint().0 + 1) / 2 . }; . self.reserve(reserve); . iter.for_each(move |(k, v)| { 12,325 ( 0.01%) self.insert(k, v); . }); 245 ( 0.00%) } . . #[inline] . #[cfg(feature = "nightly")] . fn extend_one(&mut self, (k, v): (K, V)) { . self.insert(k, v); . } . . #[inline] -- line 4588 ---------------------------------------- 25,718 ( 0.03%) -------------------------------------------------------------------------------- -- 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. 429,437 ( 0.47%) #[derive(Debug, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)] . pub enum TokenTree { . /// A single token. 131,624 ( 0.14%) Token(Token), . /// A delimited sequence of token trees. 17,614 ( 0.02%) 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 { 422 ( 0.00%) TokenTree::Token(token) => token.span, 1,632 ( 0.00%) 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), . } . } . . pub fn token(kind: TokenKind, span: Span) -> TokenTree { 19,320 ( 0.02%) TokenTree::Token(Token::new(kind, span)) . } . . /// Returns the opening delimiter as a token tree. 2,415 ( 0.00%) pub fn open_tt(span: DelimSpan, delim: DelimToken) -> TokenTree { 7,245 ( 0.01%) TokenTree::token(token::OpenDelim(delim), span.open) 2,415 ( 0.00%) } . . /// Returns the closing delimiter as a token tree. 2,415 ( 0.00%) pub fn close_tt(span: DelimSpan, delim: DelimToken) -> TokenTree { 7,245 ( 0.01%) TokenTree::token(token::CloseDelim(delim), span.close) 2,415 ( 0.00%) } . 3,288 ( 0.00%) pub fn uninterpolate(self) -> TokenTree { 2,192 ( 0.00%) match self { 9,864 ( 0.01%) TokenTree::Token(token) => TokenTree::Token(token.uninterpolate().into_owned()), . tt => tt, . } 4,384 ( 0.00%) } . } . . impl HashStable for TokenStream . where . CTX: crate::HashStableContext, . { 21,402 ( 0.02%) fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) { 131,372 ( 0.14%) for sub_tt in self.trees() { . sub_tt.hash_stable(hcx, hasher); . } 19,024 ( 0.02%) } . } . . 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 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,468 ( 0.00%) pub fn new(tokens: Vec<(AttrAnnotatedTokenTree, Spacing)>) -> AttrAnnotatedTokenStream { . AttrAnnotatedTokenStream(Lrc::new(tokens)) 2,468 ( 0.00%) } . . /// Converts this `AttrAnnotatedTokenStream` to a plain `TokenStream . /// During conversion, `AttrAnnotatedTokenTree::Attributes` get 'flattened' . /// back to a `TokenStream` of the form `outer_attr attr_target`. . /// If there are inner attributes, they are inserted into the proper . /// place in the attribute target tokens. . pub fn to_tokenstream(&self) -> TokenStream { . let trees: Vec<_> = self -- line 206 ---------------------------------------- -- line 316 ---------------------------------------- . pub struct TokenStream(pub(crate) Lrc>); . . pub type TreeAndSpacing = (TokenTree, Spacing); . . // `TokenStream` is used a lot. Make sure it doesn't unintentionally get bigger. . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . rustc_data_structures::static_assert_size!(TokenStream, 8); . 25,413 ( 0.03%) #[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 { 490 ( 0.00%) TokenStream::new(vec![(tree, Spacing::Alone)]) . } . } . . impl From for TreeAndSpacing { . fn from(tree: TokenTree) -> TreeAndSpacing { 6,063 ( 0.01%) (tree, Spacing::Alone) . } . } . . impl iter::FromIterator for TokenStream { . fn from_iter>(iter: I) -> Self { . TokenStream::new(iter.into_iter().map(Into::into).collect::>()) . } . } -- line 393 ---------------------------------------- -- line 401 ---------------------------------------- . } . . impl TokenStream { . pub fn new(streams: Vec) -> TokenStream { . TokenStream(Lrc::new(streams)) . } . . pub fn is_empty(&self) -> bool { 1,233 ( 0.00%) self.0.is_empty() 1,233 ( 0.00%) } . . pub fn len(&self) -> usize { 53,615 ( 0.06%) 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 { 4,846 ( 0.01%) self.clone().into_trees() 9,692 ( 0.01%) } . 3,607 ( 0.00%) pub fn into_trees(self) -> Cursor { . Cursor::new(self) 7,214 ( 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; . 101,424 ( 0.11%) fn next(&mut self) -> Option { 183,275 ( 0.20%) self.next_with_spacing().map(|(tree, _)| tree) 135,232 ( 0.15%) } . } . . impl Cursor { . fn new(stream: TokenStream) -> Self { . Cursor { stream, index: 0 } . } . 99,035 ( 0.11%) pub fn next_with_spacing(&mut self) -> Option { 160,845 ( 0.18%) if self.index < self.stream.len() { 83,230 ( 0.09%) self.index += 1; 96,810 ( 0.11%) Some(self.stream.0[self.index - 1].clone()) . } else { 11,954 ( 0.01%) None . } 118,842 ( 0.13%) } . . 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; . } . 297 ( 0.00%) pub fn look_ahead(&self, n: usize) -> Option<&TokenTree> { 594 ( 0.00%) self.stream.0[self.index..].get(n).map(|(tree, _)| tree) 594 ( 0.00%) } . } . 45,110 ( 0.05%) #[derive(Debug, Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)] . pub struct DelimSpan { . pub open: Span, . pub close: Span, . } . . impl DelimSpan { . pub fn from_single(sp: Span) -> Self { . DelimSpan { open: sp, close: sp } . } . 2,466 ( 0.00%) pub fn from_pair(open: Span, close: Span) -> Self { . DelimSpan { open, close } 1,233 ( 0.00%) } . . pub fn dummy() -> Self { . Self::from_single(DUMMY_SP) 63 ( 0.00%) } . 9,624 ( 0.01%) pub fn entire(self) -> Span { . self.open.with_hi(self.close.hi()) 7,218 ( 0.01%) } . } 24,389 ( 0.03%) -------------------------------------------------------------------------------- -- 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, . { 12,941 ( 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,215 ( 0.00%) #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash)] 3,748 ( 0.00%) #[derive(Decodable, Encodable)] . pub enum FileName { . Real(RealFileName), . /// Call to `quote!`. . QuoteExpansion(u64), . /// Command line. . Anon(u64), . /// Hack in `src/librustc_ast/parse.rs`. . // FIXME(jseyfried) -- line 281 ---------------------------------------- -- 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 423 ---------------------------------------- . /// that the length of the span is equal to `span.hi - span.lo`; there may be space in the . /// [`BytePos`] range between files. . /// . /// `SpanData` is public because `Span` uses a thread-local interner and can't be . /// sent to other threads, but some pieces of performance infra run in a separate thread. . /// Using `Span` is generally preferred. . #[derive(Clone, Copy, Hash, PartialEq, Eq)] . pub struct SpanData { 6 ( 0.00%) pub lo: BytePos, 6 ( 0.00%) pub hi: BytePos, . /// Information about where the macro came from, if this piece of . /// code was created by a macro expansion. 18 ( 0.00%) pub ctxt: SyntaxContext, 6 ( 0.00%) pub parent: Option, . } . . // Order spans by position in the file. . impl Ord for SpanData { . fn cmp(&self, other: &Self) -> Ordering { . let SpanData { . lo: s_lo, . hi: s_hi, -- line 444 ---------------------------------------- -- line 485 ---------------------------------------- . } . #[inline] . pub fn with_parent(&self, parent: Option) -> Span { . Span::new(self.lo, self.hi, self.ctxt, parent) . } . /// Returns `true` if this is a dummy span with any hygienic context. . #[inline] . pub fn is_dummy(self) -> bool { 43,393 ( 0.05%) 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 { 10,000 ( 0.01%) fn partial_cmp(&self, rhs: &Self) -> Option { 7,500 ( 0.01%) PartialOrd::partial_cmp(&self.data(), &rhs.data()) 10,000 ( 0.01%) } . } . 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] 9,288 ( 0.01%) pub fn with_lo(self, lo: BytePos) -> Span { . self.data().with_lo(lo) 6,192 ( 0.01%) } . #[inline] 4,384 ( 0.00%) pub fn hi(self) -> BytePos { . self.data().hi 4,384 ( 0.00%) } . #[inline] 9,909 ( 0.01%) pub fn with_hi(self, hi: BytePos) -> Span { . self.data().with_hi(hi) 6,606 ( 0.01%) } . #[inline] . pub fn ctxt(self) -> SyntaxContext { . self.data_untracked().ctxt . } . #[inline] 80 ( 0.00%) pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span { . self.data_untracked().with_ctxt(ctxt) 48 ( 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. 165 ( 0.00%) pub fn edition(self) -> edition::Edition { . self.ctxt().edition() 110 ( 0.00%) } . . #[inline] . pub fn rust_2015(self) -> bool { 58 ( 0.00%) self.edition() == edition::Edition::Edition2015 . } . . #[inline] . pub fn rust_2018(self) -> bool { 4 ( 0.00%) self.edition() >= edition::Edition::Edition2018 . } . . #[inline] . pub fn rust_2021(self) -> bool { 2 ( 0.00%) self.edition() >= edition::Edition::Edition2021 . } . . /// Returns the source callee. . /// . /// Returns `None` if the supplied span has no expansion trace, . /// else returns the `ExpnData` for the macro definition . /// corresponding to the source callsite. . pub fn source_callee(self) -> Option { -- line 703 ---------------------------------------- -- line 707 ---------------------------------------- . } . let expn_data = self.ctxt().outer_expn_data(); . if !expn_data.is_root() { Some(source_callee(expn_data)) } else { None } . } . . /// Checks if a span is "internal" to a macro in which `#[unstable]` . /// items can be used (that is, a macro marked with . /// `#[allow_internal_unstable]`). 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`. 70 ( 0.00%) pub fn is_desugaring(self, kind: DesugaringKind) -> bool { 60 ( 0.00%) match self.ctxt().outer_expn_data().kind { . ExpnKind::Desugaring(k) => k == kind, . _ => false, . } 50 ( 0.00%) } . . /// Returns the compiler desugaring that created this span, or `None` . /// if this span is not from a desugaring. . pub fn desugaring_kind(self) -> Option { . match self.ctxt().outer_expn_data().kind { . ExpnKind::Desugaring(k) => Some(k), . _ => None, . } . } . . /// Checks if a span is "internal" to a macro in which `unsafe` . /// can be used without triggering the `unsafe_code` lint. . // (that is, a macro marked with `#[allow_internal_unsafe]`). 16 ( 0.00%) pub fn allows_unsafe(self) -> bool { 4 ( 0.00%) self.ctxt().outer_expn_data().allow_internal_unsafe 16 ( 0.00%) } . . pub fn macro_backtrace(mut self) -> impl Iterator { . let mut prev_span = DUMMY_SP; . std::iter::from_fn(move || { . loop { . let expn_data = self.ctxt().outer_expn_data(); . if expn_data.is_root() { . return None; -- line 752 ---------------------------------------- -- line 767 ---------------------------------------- . . /// Returns a `Span` that would enclose both `self` and `end`. . /// . /// ```text . /// ____ ___ . /// self lorem ipsum end . /// ^^^^^^^^^^^^^^^^^^^^ . /// ``` 8,041 ( 0.01%) pub fn to(self, end: Span) -> Span { . let span_data = self.data(); . let end_data = end.data(); . // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480). . // Return the macro span on its own to avoid weird diagnostic output. It is preferable to . // have an incomplete span than a completely nonsensical one. 1,462 ( 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( . 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 }, 5,117 ( 0.01%) if span_data.parent == end_data.parent { span_data.parent } else { None }, . ) 6,579 ( 0.01%) } . . /// Returns a `Span` between the end of `self` to the beginning of `end`. . /// . /// ```text . /// ____ ___ . /// self lorem ipsum end . /// ^^^^^^^^^^^^^ . /// ``` 55 ( 0.00%) pub fn between(self, end: Span) -> Span { . let span = self.data(); . let end = end.data(); . Span::new( . span.hi, . end.lo, . if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt }, 35 ( 0.00%) if span.parent == end.parent { span.parent } else { None }, . ) 40 ( 0.00%) } . . /// Returns a `Span` from the beginning of `self` until the beginning of `end`. . /// . /// ```text . /// ____ ___ . /// self lorem ipsum end . /// ^^^^^^^^^^^^^^^^^ . /// ``` 33 ( 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. 6 ( 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 }, 21 ( 0.00%) if span_data.parent == end_data.parent { span_data.parent } else { None }, . ) 27 ( 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] 576 ( 0.00%) pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option { 384 ( 0.00%) let mut span = self.data(); 316 ( 0.00%) let mark = span.ctxt.normalize_to_macros_2_0_and_adjust(expn_id); 576 ( 0.00%) *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark 636 ( 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] 496 ( 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()) 434 ( 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 1047 ---------------------------------------- . } . . impl MultiSpan { . #[inline] . pub fn new() -> MultiSpan { . MultiSpan { primary_spans: vec![], span_labels: vec![] } . } . 30 ( 0.00%) pub fn from_span(primary_span: Span) -> MultiSpan { 180 ( 0.00%) MultiSpan { primary_spans: vec![primary_span], span_labels: vec![] } 30 ( 0.00%) } . . pub fn from_spans(mut vec: Vec) -> MultiSpan { . vec.sort(); . MultiSpan { primary_spans: vec, span_labels: vec![] } . } . 72 ( 0.00%) pub fn push_span_label(&mut self, span: Span, label: String) { 24 ( 0.00%) self.span_labels.push((span, label)); 60 ( 0.00%) } . . /// Selects the first primary span (if any). . pub fn primary_span(&self) -> Option { . self.primary_spans.first().cloned() 23 ( 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 { 150 ( 0.00%) fn from(span: Span) -> MultiSpan { . MultiSpan::from_span(span) 150 ( 0.00%) } . } . . impl From> for MultiSpan { . fn from(spans: Vec) -> MultiSpan { . MultiSpan::from_spans(spans) . } . } . -- line 1157 ---------------------------------------- -- line 1160 ---------------------------------------- . 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 => { 3 ( 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 { 3 ( 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.69%) 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 { 11 ( 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); 3 ( 0.00%) let normalized_pos = normalize_src(&mut src, start_pos); . . let name_hash = { . let mut hasher: StableHasher = StableHasher::new(); 2 ( 0.00%) name.hash(&mut hasher); . hasher.finish::() . }; 2 ( 0.00%) let end_pos = start_pos.to_usize() + src.len(); 3 ( 0.00%) assert!(end_pos <= u32::MAX as usize); . 12 ( 0.00%) let (lines, multibyte_chars, non_narrow_chars) = 2 ( 0.00%) analyze_source_file::analyze_source_file(&src, start_pos); . 17 ( 0.00%) SourceFile { . name, . src: Some(Lrc::new(src)), 11 ( 0.00%) src_hash, . external_src: Lock::new(ExternalSource::Unneeded), . start_pos, . end_pos: Pos::from_usize(end_pos), 4 ( 0.00%) lines, 4 ( 0.00%) multibyte_chars, 4 ( 0.00%) non_narrow_chars, 4 ( 0.00%) normalized_pos, . name_hash, . cnum: LOCAL_CRATE, . } 9 ( 0.00%) } . . /// Returns the `BytePos` of the beginning of the current line. . pub fn line_begin_pos(&self, pos: BytePos) -> BytePos { . let line_index = self.lookup_line(pos).unwrap(); . self.lines[line_index] . } . . /// Add externally loaded source. . /// If the hash of the input doesn't match or no input is supplied via None, . /// it is interpreted as an error and the corresponding enum variant is set. . /// The return value signifies whether some kind of source is present. 35 ( 0.00%) pub fn add_external_src(&self, get_src: F) -> bool . where . F: FnOnce() -> Option, . { 5 ( 0.00%) if matches!( 10 ( 0.00%) *self.external_src.borrow(), . ExternalSource::Foreign { kind: ExternalSourceKind::AbsentOk, .. } . ) { . let src = get_src(); . let mut external_src = self.external_src.borrow_mut(); . // Check that no-one else have provided the source while we were getting it . if let ExternalSource::Foreign { . kind: src_kind @ ExternalSourceKind::AbsentOk, .. . } = &mut *external_src -- line 1582 ---------------------------------------- -- line 1592 ---------------------------------------- . *src_kind = ExternalSourceKind::AbsentErr; . } . . false . } else { . self.src.is_some() || external_src.get_source().is_some() . } . } else { 5 ( 0.00%) self.src.is_some() || self.external_src.borrow().get_source().is_some() . } 45 ( 0.00%) } . . /// Gets a line from the list of pre-computed line-beginnings. . /// The line number here is 0-based. . pub fn get_line(&self, line_number: usize) -> Option> { . fn get_until_newline(src: &str, begin: usize) -> &str { . // We can't use `lines.get(line_number+1)` because we might . // be parsing when we call this function and thus the current . // line is the last one we have line info for. -- line 1610 ---------------------------------------- -- line 1627 ---------------------------------------- . Some(Cow::Owned(String::from(get_until_newline(src, begin)))) . } else { . None . } . } . . pub fn is_real_file(&self) -> bool { . self.name.is_real() 314 ( 0.00%) } . . pub fn is_imported(&self) -> bool { . self.src.is_none() 7,688 ( 0.01%) } . . 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,637 ( 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 { 7,305 ( 0.01%) if self.is_empty() { . return self.start_pos..self.end_pos; . } . 4,890 ( 0.01%) assert!(line_index < self.lines.len()); 7,296 ( 0.01%) if line_index == (self.lines.len() - 1) { 6 ( 0.00%) self.lines[line_index]..self.end_pos . } else { 4,860 ( 0.01%) 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); . 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. 10 ( 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 9 ( 0.00%) } . . /// Removes UTF-8 BOM, if any. . fn remove_bom(src: &mut String, normalized_pos: &mut Vec) { 1 ( 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) { 1 ( 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,143 ( 0.01%) $vis struct $ident($inner_vis $inner_ty); . . impl Pos for $ident { . #[inline(always)] . fn from_usize(n: usize) -> $ident { 1,332 ( 0.00%) $ident(n as $inner_ty) . } . . #[inline(always)] . fn to_usize(&self) -> usize { 21,294 ( 0.02%) 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 { 999,526 ( 1.09%) $ident(self.0 + rhs.0) . } . } . . impl Sub for $ident { . type Output = $ident; . . #[inline(always)] . fn sub(self, rhs: $ident) -> $ident { 658,865 ( 0.72%) $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 { 18,296 ( 0.02%) 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. 99,470 ( 0.11%) 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; . 28,060 ( 0.03%) if !ctx.hash_spans() { . return; . } . 71,410 ( 0.08%) let span = self.data_untracked(); 1,088 ( 0.00%) span.ctxt.hash_stable(ctx, hasher); 42,630 ( 0.05%) span.parent.hash_stable(ctx, hasher); . 28,449 ( 0.03%) if span.is_dummy() { . Hash::hash(&TAG_INVALID_SPAN, hasher); . return; . } . 28,362 ( 0.03%) 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. 56,724 ( 0.06%) let (file, line_lo, col_lo, line_hi, col_hi) = match ctx.span_data_to_lines_and_cols(&span) . { 28,362 ( 0.03%) 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. . 14,181 ( 0.02%) 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; 14,181 ( 0.02%) let len = (span.hi - span.lo).0; . Hash::hash(&col_line, hasher); . Hash::hash(&len, hasher); 113,680 ( 0.12%) } . } 924,006 ( 1.01%) -------------------------------------------------------------------------------- -- 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); . 8,364 ( 0.01%) if count == 8 { . ptr::copy_nonoverlapping(src, dst, 8); . return; . } . . let mut i = 0; 12,046 ( 0.01%) if i + 3 < count { . ptr::copy_nonoverlapping(src.add(i), dst.add(i), 4); . i += 4; . } . 26,249 ( 0.03%) if i + 1 < count { . ptr::copy_nonoverlapping(src.add(i), dst.add(i), 2); 3,294 ( 0.00%) i += 2 . } . 12,046 ( 0.01%) if i < count { 7,317 ( 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::(); 91,036 ( 0.10%) let nbuf = self.nbuf; . debug_assert!(size <= 8); . debug_assert!(nbuf < BUFFER_SIZE); . debug_assert!(nbuf + size < BUFFER_WITH_SPILL_SIZE); . 590,420 ( 0.64%) 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); . } . 169,314 ( 0.18%) self.nbuf = nbuf + size; . . return; . } . 21,521 ( 0.02%) 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)] 8,592 ( 0.01%) unsafe fn short_write_process_buffer(&mut self, x: T) { . let size = mem::size_of::(); 8,592 ( 0.01%) 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 { 85,920 ( 0.09%) let elem = self.buf.get_unchecked(i).assume_init().to_le(); 68,736 ( 0.08%) self.state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut self.state); 77,328 ( 0.08%) 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. 40,264 ( 0.04%) self.nbuf = if size == 1 { 0 } else { nbuf + size - BUFFER_SIZE }; 34,368 ( 0.04%) self.processed += BUFFER_SIZE; 17,184 ( 0.02%) } . . // A write function for byte slices. . #[inline] . fn slice_write(&mut self, msg: &[u8]) { . let length = msg.len(); 4,097 ( 0.00%) let nbuf = self.nbuf; . debug_assert!(nbuf < BUFFER_SIZE); . 35,011 ( 0.04%) if nbuf + length < BUFFER_SIZE { . unsafe { . let dst = (self.buf.as_mut_ptr() as *mut u8).add(nbuf); . 12,458 ( 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); . } . } . 6,234 ( 0.01%) self.nbuf = nbuf + length; . . return; . } . 5,743 ( 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)] 3,845 ( 0.00%) unsafe fn slice_write_process_buffer(&mut self, msg: &[u8]) { . let length = msg.len(); 769 ( 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. 2,307 ( 0.00%) let valid_in_elem = nbuf % ELEM_SIZE; 769 ( 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,538 ( 0.00%) let last = nbuf / ELEM_SIZE + 1; . . for i in 0..last { 5,923 ( 0.01%) let elem = self.buf.get_unchecked(i).assume_init().to_le(); 6,692 ( 0.01%) self.state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut self.state); 11,846 ( 0.01%) self.state.v0 ^= elem; . } . . // Process the remaining element-sized chunks of input. . let mut processed = needed_in_elem; 1,538 ( 0.00%) let input_left = length - processed; 870 ( 0.00%) let elems_left = input_left / ELEM_SIZE; . let extra_bytes_left = input_left % ELEM_SIZE; . . for _ in 0..elems_left { 435 ( 0.00%) let elem = (msg.as_ptr().add(processed) as *const u64).read_unaligned().to_le(); 435 ( 0.00%) self.state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut self.state); 435 ( 0.00%) self.state.v0 ^= elem; 870 ( 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); . 769 ( 0.00%) self.nbuf = extra_bytes_left; 3,845 ( 0.00%) self.processed += nbuf + processed; 4,614 ( 0.01%) } . . #[inline] . pub fn finish128(mut self) -> (u64, u64) { . debug_assert!(self.nbuf < BUFFER_SIZE); . . // Process full elements in buffer. 1,452 ( 0.00%) let last = self.nbuf / ELEM_SIZE; . . // Since we're consuming self, avoid updating members for a potential . // performance gain. 1,936 ( 0.00%) let mut state = self.state; . . for i in 0..last { 1,565 ( 0.00%) let elem = unsafe { self.buf.get_unchecked(i).assume_init().to_le() }; 1,565 ( 0.00%) state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut state); 1,565 ( 0.00%) state.v0 ^= elem; . } . . // Get remaining partial element. 968 ( 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); 424 ( 0.00%) self.buf.get_unchecked(last).assume_init().to_le() . } . } else { . 0 . }; . . // Finalize the hash. 1,392 ( 0.00%) let length = self.processed + self.nbuf; 966 ( 0.00%) let b: u64 = ((length as u64 & 0xff) << 56) | elem; . 483 ( 0.00%) state.v3 ^= b; . Sip24Rounds::c_rounds(&mut state); 483 ( 0.00%) state.v0 ^= b; . 483 ( 0.00%) state.v2 ^= 0xee; . Sip24Rounds::d_rounds(&mut state); 1,198 ( 0.00%) let _0 = state.v0 ^ state.v1 ^ state.v2 ^ state.v3; . 230 ( 0.00%) state.v1 ^= 0xdd; . Sip24Rounds::d_rounds(&mut state); 230 ( 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) { 319,467 ( 0.35%) compress!(state); 352,113 ( 0.38%) compress!(state); . } . . #[inline] . fn d_rounds(state: &mut State) { 2,392 ( 0.00%) compress!(state); 2,392 ( 0.00%) compress!(state); 2,392 ( 0.00%) compress!(state); 1,910 ( 0.00%) compress!(state); . } . } 30,531 ( 0.03%) -------------------------------------------------------------------------------- -- 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> { 78,963 ( 0.09%) 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) }; 40,099 ( 0.04%) 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> { 150 ( 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) }; 205 ( 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 ---------------------------------------- 7,807 ( 0.01%) -------------------------------------------------------------------------------- -- 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)] 585,644 ( 0.64%) 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 { 9,041 ( 0.01%) copy_nonoverlapping(src, tmp.as_mut_ptr(), 1); 137,563 ( 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 { 816,045 ( 0.89%) copy_nonoverlapping(&src as *const T, dst, 1); . intrinsics::forget(src); . } . } . . /// Overwrites a memory location with the given value without reading or . /// dropping the old value. . /// . /// Unlike [`write()`], the pointer may be unaligned. -- line 900 ---------------------------------------- -- line 1206 ---------------------------------------- . if stride == 1 { . // `stride == 1` case can be computed more simply through `-p (mod a)`, but doing so . // inhibits LLVM's ability to select instructions like `lea`. Instead we compute . // . // round_up_to_next_alignment(p, a) - p . // . // which distributes operations around the load-bearing, but pessimizing `and` sufficiently . // for LLVM to be able to utilize the various optimizations it knows about. 120 ( 0.00%) return wrapping_sub( 1,158 ( 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 { 3,614 ( 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 ---------------------------------------- 71,240 ( 0.08%) -------------------------------------------------------------------------------- -- 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 { 17 ( 0.00%) self.0.contains(attr.id) 17 ( 0.00%) } . } . . impl NestedMetaItem { . /// Returns the `MetaItem` if `self` is a `NestedMetaItem::MetaItem`. . pub fn meta_item(&self) -> Option<&MetaItem> { 772 ( 0.00%) match *self { . NestedMetaItem::MetaItem(ref item) => Some(item), . _ => None, . } 22 ( 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)) 47 ( 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 { 2 ( 0.00%) self.ident().unwrap_or_else(Ident::empty).name 2 ( 0.00%) } . . /// Gets the string value if `self` is a `MetaItem` and the `MetaItem` is a . /// `MetaItemKind::NameValue` variant containing a string, otherwise `None`. . pub fn value_str(&self) -> Option { . self.meta_item().and_then(|meta_item| meta_item.value_str()) . } . . /// Returns a name and single literal value tuple of the `MetaItem`. -- line 74 ---------------------------------------- -- line 85 ---------------------------------------- . None . }) . }) . } . . /// 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()) 1 ( 0.00%) } . . /// Returns `true` if the variant is `MetaItem`. . pub fn is_meta_item(&self) -> bool { . self.meta_item().is_some() . } . . /// Returns `true` if `self` is a `MetaItem` and the meta item is a word. . pub fn is_word(&self) -> bool { -- line 101 ---------------------------------------- -- line 106 ---------------------------------------- . 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 { 119,199 ( 0.13%) 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,188 ( 0.00%) pub fn ident(&self) -> Option { 6,576 ( 0.01%) match self.kind { . AttrKind::Normal(ref item, _) => { 672 ( 0.00%) if item.path.segments.len() == 1 { 511 ( 0.00%) Some(item.path.segments[0].ident) . } else { . None . } . } . AttrKind::DocComment(..) => None, . } 7,128 ( 0.01%) } . pub fn name_or_empty(&self) -> Symbol { 161 ( 0.00%) self.ident().unwrap_or_else(Ident::empty).name 2,100 ( 0.00%) } . 4 ( 0.00%) pub fn value_str(&self) -> Option { 2 ( 0.00%) match self.kind { . AttrKind::Normal(ref item, _) => item.meta_kind().and_then(|kind| kind.value_str()), . AttrKind::DocComment(..) => None, . } 5 ( 0.00%) } . 435 ( 0.00%) pub fn meta_item_list(&self) -> Option> { 290 ( 0.00%) match self.kind { 290 ( 0.00%) AttrKind::Normal(ref item, _) => match item.meta_kind() { 973 ( 0.00%) Some(MetaItemKind::List(list)) => Some(list), 6 ( 0.00%) _ => None, . }, . AttrKind::DocComment(..) => None, . } 580 ( 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 { 63 ( 0.00%) if self.path.segments.len() == 1 { Some(self.path.segments[0].ident) } else { None } . } . pub fn name_or_empty(&self) -> Symbol { 19 ( 0.00%) self.ident().unwrap_or_else(Ident::empty).name 19 ( 0.00%) } . . // Example: . // #[attribute(name = "value")] . // ^^^^^^^^^^^^^^ . pub fn name_value_literal(&self) -> Option<&Lit> { . match &self.kind { . MetaItemKind::NameValue(v) => Some(v), . _ => None, . } . } . 2 ( 0.00%) pub fn value_str(&self) -> Option { 4 ( 0.00%) match self.kind { 4 ( 0.00%) MetaItemKind::NameValue(ref v) => match v.kind { 2 ( 0.00%) LitKind::Str(ref s, _) => Some(*s), . _ => None, . }, . _ => None, . } 2 ( 0.00%) } . . pub fn meta_item_list(&self) -> Option<&[NestedMetaItem]> { 50 ( 0.00%) match self.kind { . MetaItemKind::List(ref l) => Some(&l[..]), . _ => None, . } 16 ( 0.00%) } . . pub fn is_word(&self) -> bool { 30 ( 0.00%) matches!(self.kind, MetaItemKind::Word) 15 ( 0.00%) } . . pub fn has_name(&self, name: Symbol) -> bool { . self.path == name . } . . /// This is used in case you want the value span instead of the whole attribute. Example: . /// . /// ```text -- line 209 ---------------------------------------- -- 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)) . } . 152 ( 0.00%) pub fn meta(&self, span: Span) -> Option { 190 ( 0.00%) Some(MetaItem { . path: self.path.clone(), . kind: MetaItemKind::from_mac_args(&self.args)?, . span, . }) 133 ( 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,176 ( 0.00%) match self.kind { . AttrKind::Normal(..) => false, . AttrKind::DocComment(..) => true, . } 1,588 ( 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, . } . } . 34 ( 0.00%) pub fn get_normal_item(&self) -> &AttrItem { 68 ( 0.00%) match self.kind { 34 ( 0.00%) AttrKind::Normal(ref item, _) => item, . AttrKind::DocComment(..) => panic!("unexpected doc comment"), . } 102 ( 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. 38 ( 0.00%) pub fn meta(&self) -> Option { 38 ( 0.00%) match self.kind { 76 ( 0.00%) AttrKind::Normal(ref item, _) => item.meta(self.span), . AttrKind::DocComment(..) => None, . } 57 ( 0.00%) } . 15 ( 0.00%) pub fn meta_kind(&self) -> Option { 6 ( 0.00%) match self.kind { . AttrKind::Normal(ref item, _) => item.meta_kind(), . AttrKind::DocComment(..) => None, . } 15 ( 0.00%) } . . pub fn tokens(&self) -> AttrAnnotatedTokenStream { . 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(( -- line 301 ---------------------------------------- -- 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)) . } . 1,848 ( 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); 2,436 ( 0.00%) assert!(id != u32::MAX); . AttrId::from_u32(id) 1,848 ( 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) . } . 28 ( 0.00%) pub fn mk_attr_from_item( . item: AttrItem, . tokens: Option, . style: AttrStyle, . span: Span, . ) -> Attribute { 547 ( 0.00%) Attribute { kind: AttrKind::Normal(item, tokens), id: mk_attr_id(), style, span } 56 ( 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%) } . 554 ( 0.00%) pub fn mk_doc_comment( . comment_kind: CommentKind, . style: AttrStyle, . data: Symbol, . span: Span, . ) -> Attribute { 5,817 ( 0.01%) Attribute { kind: AttrKind::DocComment(comment_kind, data), id: mk_attr_id(), style, span } 1,108 ( 0.00%) } . . pub fn list_contains_name(items: &[NestedMetaItem], name: Symbol) -> bool { . items.iter().any(|item| item.has_name(name)) 121 ( 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`. 8,704 ( 0.01%) let path = match tokens.next().map(TokenTree::uninterpolate) { . Some(TokenTree::Token(Token { 2,176 ( 0.00%) kind: kind @ (token::Ident(..) | token::ModSep), 1,088 ( 0.00%) span, . })) => 'arm: { 3,264 ( 0.00%) let mut segments = if let token::Ident(name, _) = kind { 3,608 ( 0.00%) if let Some(TokenTree::Token(Token { kind: token::ModSep, .. })) = tokens.peek() . { 8 ( 0.00%) tokens.next(); 40 ( 0.00%) vec![PathSegment::from_ident(Ident::new(name, span))] . } else { . break 'arm Path::from_ident(Ident::new(name, span)); . } . } else { . vec![PathSegment::path_root(span)] . }; . loop { 48 ( 0.00%) if let Some(TokenTree::Token(Token { kind: token::Ident(name, _), span })) = . tokens.next().map(TokenTree::uninterpolate) . { . segments.push(PathSegment::from_ident(Ident::new(name, span))); . } else { . return None; . } 24 ( 0.00%) if let Some(TokenTree::Token(Token { kind: token::ModSep, .. })) = tokens.peek() . { . tokens.next(); . } else { . break; . } . } 40 ( 0.00%) let span = span.with_hi(segments.last().unwrap().ident.span.hi()); 40 ( 0.00%) 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, 2,176 ( 0.00%) }; . let list_closing_paren_pos = tokens.peek().map(|tt| tt.span().hi()); 1,088 ( 0.00%) let kind = MetaItemKind::from_tokens(tokens)?; 3,536 ( 0.00%) let hi = match kind { 4 ( 0.00%) MetaItemKind::NameValue(ref lit) => lit.span.hi(), 1,224 ( 0.00%) MetaItemKind::List(..) => list_closing_paren_pos.unwrap_or(path.span.hi()), 2,034 ( 0.00%) _ => path.span.hi(), . }; 3,268 ( 0.00%) let span = path.span.with_hi(hi); 32,640 ( 0.04%) Some(MetaItem { path, kind, span }) . } . } . . impl MetaItemKind { . pub fn value_str(&self) -> Option { 6 ( 0.00%) match self { 3 ( 0.00%) MetaItemKind::NameValue(ref v) => match v.kind { 2 ( 0.00%) 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(), . ] . } . } . } . 4,520 ( 0.00%) fn list_from_tokens(tokens: TokenStream) -> Option { . let mut tokens = tokens.into_trees().peekable(); . let mut result = Vec::new(); 1,653 ( 0.00%) while tokens.peek().is_some() { 3,264 ( 0.00%) let item = NestedMetaItem::from_tokens(&mut tokens)?; 8,704 ( 0.01%) result.push(item); 4,978 ( 0.01%) match tokens.next() { . None | Some(TokenTree::Token(Token { kind: token::Comma, .. })) => {} . _ => return None, . } . } 3,955 ( 0.00%) Some(MetaItemKind::List(result)) 4,520 ( 0.00%) } . . fn name_value_from_tokens( . tokens: &mut impl Iterator, . ) -> Option { 10 ( 0.00%) match tokens.next() { . Some(TokenTree::Delimited(_, token::NoDelim, inner_tokens)) => { . MetaItemKind::name_value_from_tokens(&mut inner_tokens.trees()) . } 12 ( 0.00%) Some(TokenTree::Token(token)) => { 2 ( 0.00%) Lit::from_token(&token).ok().map(MetaItemKind::NameValue) . } . _ => None, . } 8 ( 0.00%) } . . fn from_mac_args(args: &MacArgs) -> Option { 1,134 ( 0.00%) match args { . MacArgs::Delimited(_, MacDelimiter::Parenthesis, tokens) => { 314 ( 0.00%) MetaItemKind::list_from_tokens(tokens.clone()) . } . MacArgs::Delimited(..) => None, 3 ( 0.00%) MacArgs::Eq(_, token) => Lit::from_token(token).ok().map(MetaItemKind::NameValue), . MacArgs::Empty => Some(MetaItemKind::Word), . } . } . . fn from_tokens( . tokens: &mut iter::Peekable>, . ) -> Option { 4,408 ( 0.00%) match tokens.peek() { . Some(TokenTree::Delimited(_, token::Paren, inner_tokens)) => { 816 ( 0.00%) let inner_tokens = inner_tokens.clone(); . tokens.next(); 1,224 ( 0.00%) 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) . } 678 ( 0.00%) _ => Some(MetaItemKind::Word), . } . } . } . . impl NestedMetaItem { . pub fn span(&self) -> Span { 60 ( 0.00%) match *self { . NestedMetaItem::MetaItem(ref item) => item.span, . NestedMetaItem::Literal(ref lit) => lit.span, . } 15 ( 0.00%) } . . 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()], . } . } . 9,792 ( 0.01%) fn from_tokens(tokens: &mut iter::Peekable) -> Option . where . I: Iterator, . { 3,264 ( 0.00%) match tokens.peek() { 2,176 ( 0.00%) Some(TokenTree::Token(token)) 3,264 ( 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) 8,704 ( 0.01%) } . } 9,042 ( 0.01%) -------------------------------------------------------------------------------- -- 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,062 ( 0.00%) #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub enum CommentKind { . Line, . Block, . } . 28 ( 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,595 ( 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, . } . 98 ( 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. 723 ( 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 164 ---------------------------------------- . kw::While, . kw::Yield, . kw::Static, . ] . .contains(&name) . } . . fn ident_can_begin_type(name: Symbol, span: Span, is_raw: bool) -> bool { 42 ( 0.00%) let ident_token = Token::new(Ident(name, is_raw), span); . 14 ( 0.00%) !ident_token.is_reserved_ident() . || ident_token.is_path_segment_keyword() . || [kw::Underscore, kw::For, kw::Impl, kw::Fn, kw::Unsafe, kw::Extern, kw::Typeof, kw::Dyn] . .contains(&name) . } . 681,578 ( 0.74%) #[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, 6,834 ( 0.01%) BinOp(BinOpToken), . BinOpEq(BinOpToken), . . /* Structural symbols */ . At, . Dot, . DotDot, . DotDotDot, . DotDotEq, -- line 202 ---------------------------------------- -- 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., `{`). 633 ( 0.00%) OpenDelim(DelimToken), . /// A closing delimiter (e.g., `}`). 756 ( 0.00%) CloseDelim(DelimToken), . . /* Literals */ 205 ( 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. 12,918 ( 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. 336 ( 0.00%) 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. 831 ( 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); . 247,145 ( 0.27%) #[derive(Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub struct Token { 1,005 ( 0.00%) pub kind: TokenKind, 877 ( 0.00%) pub span: Span, . } . . impl TokenKind { . pub fn lit(kind: LitKind, symbol: Symbol, suffix: Option) -> TokenKind { . Literal(Lit::new(kind, symbol, suffix)) . } . . // An approximation to proc-macro-style single-character operators used by rustc parser. . // If the operator token can be broken into two tokens, the first of which is single-character, . // then this function performs that operation, otherwise it returns `None`. 40 ( 0.00%) pub fn break_two_token_op(&self) -> Option<(TokenKind, TokenKind)> { 160 ( 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), 40 ( 0.00%) _ => return None, . }) 40 ( 0.00%) } . . /// Returns tokens that are likely to be typed accidentally instead of the current token. . /// Enables better error recovery when the wrong token is found. . pub fn similar_tokens(&self) -> Option> { . match *self { . Comma => Some(vec![Dot, Lt, Semi]), . Semi => Some(vec![Colon, Comma]), . FatArrow => Some(vec![Eq, RArrow]), . _ => None, . } . } . . pub fn should_end_const_arg(&self) -> bool { 28 ( 0.00%) matches!(self, Gt | Ge | BinOp(Shr) | BinOpEq(Shr)) 7 ( 0.00%) } . } . . impl Token { 8,119 ( 0.01%) pub fn new(kind: TokenKind, span: Span) -> Self { 24,520 ( 0.03%) Token { kind, span } 8,119 ( 0.01%) } . . /// Some token that will be thrown away later. 45 ( 0.00%) pub fn dummy() -> Self { . Token::new(TokenKind::Question, DUMMY_SP) 45 ( 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. 5,128 ( 0.01%) pub fn take(&mut self) -> Self { . mem::replace(self, Token::dummy()) 5,128 ( 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 { 8 ( 0.00%) match &self.kind { . Interpolated(nt) => nt.span(), 4 ( 0.00%) _ => self.span, . } 4 ( 0.00%) } . . pub fn is_op(&self) -> bool { 15,384 ( 0.02%) !matches!( 5,128 ( 0.01%) self.kind, . OpenDelim(..) . | CloseDelim(..) . | Literal(..) . | DocComment(..) . | Ident(..) . | Lifetime(..) . | Interpolated(..) . | Eof . ) 5,128 ( 0.01%) } . . pub fn is_like_plus(&self) -> bool { 220 ( 0.00%) matches!(self.kind, BinOp(Plus) | BinOpEq(Plus)) 44 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of an expression. . pub fn can_begin_expr(&self) -> bool { . 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 -- line 365 ---------------------------------------- -- line 379 ---------------------------------------- . NtExpr(..) | . NtBlock(..) | . NtPath(..)), . _ => false, . } . } . . /// Returns `true` if the token can appear at the start of a type. 36 ( 0.00%) pub fn can_begin_type(&self) -> bool { 53 ( 0.00%) match self.uninterpolate().kind { 63 ( 0.00%) Ident(name, is_raw) => 7 ( 0.00%) ident_can_begin_type(name, self.span, is_raw), // type name or keyword . OpenDelim(Paren) | // tuple . OpenDelim(Bracket) | // array . Not | // never . BinOp(Star) | // raw pointer . BinOp(And) | // reference . AndAnd | // double reference . Question | // maybe bound in trait object . Lifetime(..) | // lifetime bound in trait object . Lt | BinOp(Shl) | // associated path . ModSep => true, // global path . Interpolated(ref nt) => matches!(**nt, NtTy(..) | NtPath(..)), . _ => false, . } 54 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of a const param. . pub fn can_begin_const_arg(&self) -> bool { 35 ( 0.00%) match self.kind { . OpenDelim(Brace) => true, . Interpolated(ref nt) => matches!(**nt, NtExpr(..) | NtBlock(..) | NtLiteral(..)), 7 ( 0.00%) _ => self.can_begin_literal_maybe_minus(), . } . } . . /// Returns `true` if the token can appear at the start of a generic bound. . pub fn can_begin_bound(&self) -> bool { . self.is_path_start() . || self.is_lifetime() . || self.is_keyword(kw::For) -- line 419 ---------------------------------------- -- line 427 ---------------------------------------- . } . . /// Returns `true` if the token is any literal, a minus (which can prefix a literal, . /// for example a '-42', or one of the boolean idents). . /// . /// In other words, would this token be a valid start of `parse_literal_maybe_minus`? . /// . /// Keep this in sync with and `Lit::from_token`, excluding unary negation. 7 ( 0.00%) pub fn can_begin_literal_maybe_minus(&self) -> bool { 70 ( 0.00%) match self.uninterpolate().kind { . Literal(..) | BinOp(Minus) => true, 28 ( 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, . } 14 ( 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. 22 ( 0.00%) pub fn uninterpolate(&self) -> Cow<'_, Token> { 22,873 ( 0.02%) 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), . } 22 ( 0.00%) } . . /// Returns an identifier if this token is an identifier. 6,043 ( 0.01%) pub fn ident(&self) -> Option<(Ident, /* is_raw */ bool)> { . let token = self.uninterpolate(); 15,748 ( 0.02%) match token.kind { 50,830 ( 0.06%) Ident(name, is_raw) => Some((Ident::new(name, token.span), is_raw)), . _ => None, . } 37,008 ( 0.04%) } . . /// Returns a lifetime identifier if this token is a lifetime. 394 ( 0.00%) pub fn lifetime(&self) -> Option { . let token = self.uninterpolate(); 850 ( 0.00%) match token.kind { . Lifetime(name) => Some(Ident::new(name, token.span)), . _ => None, . } 2,758 ( 0.00%) } . . /// Returns `true` if the token is an identifier. . pub fn is_ident(&self) -> bool { . self.ident().is_some() 761 ( 0.00%) } . . /// Returns `true` if the token is a lifetime. 31 ( 0.00%) pub fn is_lifetime(&self) -> bool { . self.lifetime().is_some() 62 ( 0.00%) } . . /// Returns `true` if the token is an identifier whose name is the given . /// string slice. 9 ( 0.00%) pub fn is_ident_named(&self, name: Symbol) -> bool { . self.ident().map_or(false, |(ident, _)| ident.name == name) 18 ( 0.00%) } . . /// Returns `true` if the token is an interpolated path. . fn is_path(&self) -> bool { 184 ( 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 { 4 ( 0.00%) if let Interpolated(ref nt) = self.kind { . if let NtBlock(..) = **nt { . return true; . } . } . false 2 ( 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) . } . 8 ( 0.00%) pub fn is_qpath_start(&self) -> bool { 100 ( 0.00%) self == &Lt || self == &BinOp(Shl) . } . 184 ( 0.00%) pub fn is_path_start(&self) -> bool { 262 ( 0.00%) self == &ModSep . || self.is_qpath_start() . || self.is_path() . || self.is_path_segment_keyword() 39 ( 0.00%) || self.is_ident() && !self.is_reserved_ident() 230 ( 0.00%) } . . /// Returns `true` if the token is a given keyword, `kw`. 885 ( 0.00%) pub fn is_keyword(&self, kw: Symbol) -> bool { . self.is_non_raw_ident_where(|id| id.name == kw) 1,770 ( 0.00%) } . 3 ( 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. 23 ( 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. 23 ( 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. 23 ( 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`. 3 ( 0.00%) pub fn is_bool_lit(&self) -> bool { 6 ( 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. 8 ( 0.00%) pub fn is_non_raw_ident_where(&self, pred: impl FnOnce(Ident) -> bool) -> bool { 5,793 ( 0.01%) match self.ident() { 32 ( 0.00%) Some((id, false)) => pred(id), . _ => false, . } 10 ( 0.00%) } . 10,210 ( 0.01%) pub fn glue(&self, joint: &Token) -> Option { 5,105 ( 0.01%) let kind = match self.kind { 320 ( 0.00%) Eq => match joint.kind { . Eq => EqEq, . Gt => FatArrow, . _ => return None, . }, 95 ( 0.00%) Lt => match joint.kind { . Eq => Le, . Lt => BinOp(Shl), . Le => BinOpEq(Shl), . BinOp(Minus) => LArrow, . _ => return None, . }, 63 ( 0.00%) Gt => match joint.kind { . Eq => Ge, . Gt => BinOp(Shr), . Ge => BinOpEq(Shr), . _ => return None, . }, . Not => match joint.kind { . Eq => Ne, . _ => return None, . }, 187 ( 0.00%) BinOp(op) => match joint.kind { . Eq => BinOpEq(op), 1 ( 0.00%) BinOp(And) if op == And => AndAnd, . BinOp(Or) if op == Or => OrOr, 25 ( 0.00%) Gt if op == Minus => RArrow, . _ => return None, . }, 15 ( 0.00%) Dot => match joint.kind { . Dot => DotDot, . DotDot => DotDotDot, . _ => return None, . }, . DotDot => match joint.kind { . Dot => DotDotDot, . Eq => DotDotEq, . _ => return None, . }, 244 ( 0.00%) Colon => match joint.kind { . Colon => ModSep, . _ => return None, . }, . SingleQuote => match joint.kind { . Ident(name, false) => Lifetime(Symbol::intern(&format!("'{}", name))), . _ => return None, . }, . . Le | EqEq | Ne | Ge | AndAnd | OrOr | Tilde | BinOpEq(..) | At | DotDotDot . | DotDotEq | Comma | Semi | ModSep | RArrow | LArrow | FatArrow | Pound | Dollar . | Question | OpenDelim(..) | CloseDelim(..) | Literal(..) | Ident(..) . | Lifetime(..) | Interpolated(..) | DocComment(..) | Eof => return None, . }; . 2,496 ( 0.00%) Some(Token::new(kind, self.span.to(joint.span))) 9,189 ( 0.01%) } . } . . impl PartialEq for Token { . fn eq(&self, rhs: &TokenKind) -> bool { 2,628 ( 0.00%) 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. 1,136 ( 0.00%) pub fn from_symbol( . symbol: Symbol, . edition: impl FnOnce() -> Edition, . ) -> Option { 2,800 ( 0.00%) Some(match symbol { . sym::item => NonterminalKind::Item, . sym::block => NonterminalKind::Block, . sym::stmt => NonterminalKind::Stmt, . sym::pat => match edition() { . Edition::Edition2015 | Edition::Edition2018 => { . NonterminalKind::PatParam { inferred: true } . } . Edition::Edition2021 => NonterminalKind::PatWithOr, -- line 731 ---------------------------------------- -- line 737 ---------------------------------------- . sym::lifetime => NonterminalKind::Lifetime, . sym::literal => NonterminalKind::Literal, . sym::meta => NonterminalKind::Meta, . sym::path => NonterminalKind::Path, . sym::vis => NonterminalKind::Vis, . sym::tt => NonterminalKind::TT, . _ => return None, . }) 1,136 ( 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 ---------------------------------------- 143,454 ( 0.16%) -------------------------------------------------------------------------------- -- 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}; . 42 ( 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); . } . } . } . }; . } . 168 ( 0.00%) #[derive(Clone)] . pub struct Parser<'a> { 6 ( 0.00%) pub sess: &'a ParseSess, . /// The current token. 6 ( 0.00%) pub token: Token, . /// The spacing for the current token 3 ( 0.00%) pub token_spacing: Spacing, . /// The previous token. 9 ( 0.00%) pub prev_token: Token, 3 ( 0.00%) pub capture_cfg: bool, 6 ( 0.00%) restrictions: Restrictions, 6 ( 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, 6 ( 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. 6 ( 0.00%) unmatched_angle_bracket_count: u32, 9 ( 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. 3 ( 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` 3 ( 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, . } . 12 ( 0.00%) #[derive(Clone)] . struct CaptureState { 12 ( 0.00%) capturing: Capturing, 3 ( 0.00%) replace_ranges: Vec, . inner_attr_ranges: FxHashMap, . } . . impl<'a> Drop for Parser<'a> { . fn drop(&mut self) { 66 ( 0.00%) emit_unclosed_delims(&mut self.unclosed_delims, &self.sess); . } . } . 763 ( 0.00%) #[derive(Clone)] . struct TokenCursor { . frame: TokenCursorFrame, 172 ( 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. 56 ( 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, . } . 361 ( 0.00%) #[derive(Clone)] . struct TokenCursorFrame { 106 ( 0.00%) delim: token::DelimToken, . span: DelimSpan, . open_delim: bool, 212 ( 0.00%) tree_cursor: tokenstream::Cursor, . close_delim: bool, . } . . impl TokenCursorFrame { . fn new(span: DelimSpan, delim: DelimToken, tts: TokenStream) -> Self { 75 ( 0.00%) TokenCursorFrame { . delim, . span, . open_delim: false, 2,445 ( 0.00%) tree_cursor: tts.into_trees(), . close_delim: false, . } . } . } . . impl TokenCursor { 170,676 ( 0.19%) fn next(&mut self) -> (Token, Spacing) { . loop { 88,020 ( 0.10%) let (tree, spacing) = if !self.frame.open_delim { 2,415 ( 0.00%) self.frame.open_delim = true; 12,075 ( 0.01%) TokenTree::open_tt(self.frame.span, self.frame.delim).into() 165,727 ( 0.18%) } else if let Some(tree) = self.frame.tree_cursor.next_with_spacing() { . tree 9,694 ( 0.01%) } else if !self.frame.close_delim { 2,415 ( 0.00%) self.frame.close_delim = true; 12,075 ( 0.01%) TokenTree::close_tt(self.frame.span, self.frame.delim).into() 4,830 ( 0.01%) } else if let Some(frame) = self.stack.pop() { 31,395 ( 0.03%) self.frame = frame; . continue; . } else { 306 ( 0.00%) (TokenTree::Token(Token::new(token::Eof, DUMMY_SP)), Spacing::Alone) . }; . 33,276 ( 0.04%) match tree { . TokenTree::Token(token) => { 113,784 ( 0.12%) return (token, spacing); . } . TokenTree::Delimited(sp, delim, tts) => { . let frame = TokenCursorFrame::new(sp, delim, tts); . self.stack.push(mem::replace(&mut self.frame, frame)); . } . } . } 113,784 ( 0.12%) } . 67,490 ( 0.07%) fn next_desugared(&mut self) -> (Token, Spacing) { 20,247 ( 0.02%) let (data, attr_style, sp) = match self.next() { . (Token { kind: token::DocComment(_, attr_style, data), span }, _) => { . (data, attr_style, span) . } 33,745 ( 0.04%) tok => return tok, . }; . . // Searches for the occurrences of `"#*` and returns the minimum number of `#`s . // required to wrap the text. . let mut num_of_hashes = 0; . let mut count = 0; . for ch in data.as_str().chars() { . count = match ch { -- line 298 ---------------------------------------- -- line 332 ---------------------------------------- . .iter() . .cloned() . .collect::() . }, . ), . )); . . self.next() 60,741 ( 0.07%) } . } . 290 ( 0.00%) #[derive(Debug, Clone, PartialEq)] . enum TokenType { 232 ( 0.00%) Token(TokenKind), . Keyword(Symbol), . Operator, . Lifetime, . Ident, . Path, . Type, . Const, . } -- line 353 ---------------------------------------- -- line 392 ---------------------------------------- . } . . pub enum FollowedByType { . Yes, . No, . } . . fn token_descr_opt(token: &Token) -> Option<&'static str> { 46 ( 0.00%) Some(match token.kind { 92 ( 0.00%) _ if token.is_special_ident() => "reserved identifier", 92 ( 0.00%) _ if token.is_used_keyword() => "keyword", 92 ( 0.00%) _ if token.is_unused_keyword() => "reserved keyword", . token::DocComment(..) => "doc comment", . _ => return None, . }) . } . 161 ( 0.00%) pub(super) fn token_descr(token: &Token) -> String { 46 ( 0.00%) let token_str = pprust::token_to_string(token); . match token_descr_opt(token) { . Some(prefix) => format!("{} `{}`", prefix, token_str), 161 ( 0.00%) _ => format!("`{}`", token_str), . } 115 ( 0.00%) } . . impl<'a> Parser<'a> { 210 ( 0.00%) pub fn new( . sess: &'a ParseSess, . tokens: TokenStream, . desugar_doc_comments: bool, . subparser_name: Option<&'static str>, . ) -> Self { 15 ( 0.00%) let mut start_frame = TokenCursorFrame::new(DelimSpan::dummy(), token::NoDelim, tokens); 30 ( 0.00%) start_frame.open_delim = true; . start_frame.close_delim = true; . 465 ( 0.00%) let mut parser = Parser { . sess, 15 ( 0.00%) token: Token::dummy(), . token_spacing: Spacing::Alone, 15 ( 0.00%) prev_token: Token::dummy(), . capture_cfg: false, . restrictions: Restrictions::empty(), . expected_tokens: Vec::new(), . token_cursor: TokenCursor { 90 ( 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. 30 ( 0.00%) parser.bump(); . . parser 135 ( 0.00%) } . . fn next_tok(&mut self, fallback_span: Span) -> (Token, Spacing) { . loop { 85,242 ( 0.09%) let (mut next, spacing) = if self.desugar_doc_comments { 26,996 ( 0.03%) self.token_cursor.next_desugared() . } else { 22,374 ( 0.02%) self.token_cursor.next() . }; 56,828 ( 0.06%) 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 14,207 ( 0.02%) self.token_cursor.break_last_token = false; 56,828 ( 0.06%) if next.span.is_dummy() { . // Tweak the location for better diagnostics, but keep syntactic context intact. 64 ( 0.00%) next.span = fallback_span.with_ctxt(next.span.ctxt()); . } 49,866 ( 0.05%) if matches!( 28,414 ( 0.03%) next.kind, . token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) . ) { . continue; . } 56,828 ( 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`. 612 ( 0.00%) pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> { 68 ( 0.00%) if self.expected_tokens.is_empty() { 114 ( 0.00%) if self.token == *t { 95 ( 0.00%) self.bump(); . Ok(false) . } else { . self.unexpected_try_recover(t) . } . } else { 588 ( 0.00%) self.expect_one_of(slice::from_ref(t), &[]) . } 1,020 ( 0.00%) } . . /// Expect next token to be edible or inedible token. If edible, . /// then consume it; if inedible, then return without consuming . /// anything. Signal a fatal error if next token is unexpected. 660 ( 0.00%) pub fn expect_one_of( . &mut self, . edible: &[TokenKind], . inedible: &[TokenKind], . ) -> PResult<'a, bool /* recovered */> { 110 ( 0.00%) if edible.contains(&self.token.kind) { 150 ( 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) . } 825 ( 0.00%) } . . // Public for rustfmt usage. . pub fn parse_ident(&mut self) -> PResult<'a, Ident> { 440 ( 0.00%) self.parse_ident_common(true) . } . . fn ident_or_err(&mut self) -> PResult<'a, (Ident, /* is_raw */ bool)> { 345 ( 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(), . }) . } . 791 ( 0.00%) fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> { 113 ( 0.00%) let (ident, is_raw) = self.ident_or_err()?; 678 ( 0.00%) if !is_raw && ident.is_reserved() { . let mut err = self.expected_ident_found(); . if recover { . err.emit(); . } else { . return Err(err); . } . } 452 ( 0.00%) self.bump(); . Ok(ident) 1,130 ( 0.00%) } . . /// Checks if the next token is `tok`, and returns `true` if so. . /// . /// This method will automatically add `tok` to `expected_tokens` if `tok` is not . /// encountered. 9,499 ( 0.01%) fn check(&mut self, tok: &TokenKind) -> bool { 4,144 ( 0.00%) let is_present = self.token == *tok; 2,782 ( 0.00%) if !is_present { 6,064 ( 0.01%) self.expected_tokens.push(TokenType::Token(tok.clone())); . } . is_present 9,499 ( 0.01%) } . . /// Consumes a token 'tok' if it exists. Returns whether the given token was present. . pub fn eat(&mut self, tok: &TokenKind) -> bool { 1,665 ( 0.00%) let is_present = self.check(tok); 1,116 ( 0.00%) if is_present { 220 ( 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. 445 ( 0.00%) fn check_keyword(&mut self, kw: Symbol) -> bool { 103 ( 0.00%) self.expected_tokens.push(TokenType::Keyword(kw)); 2,824 ( 0.00%) self.token.is_keyword(kw) . } . . /// If the next token is the given keyword, eats it and returns `true`. . /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes. . // Public for rustfmt usage. 525 ( 0.00%) pub fn eat_keyword(&mut self, kw: Symbol) -> bool { 504 ( 0.00%) if self.check_keyword(kw) { 72 ( 0.00%) self.bump(); . true . } else { . false . } 525 ( 0.00%) } . . fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool { 144 ( 0.00%) if self.token.is_keyword(kw) { 24 ( 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. 40 ( 0.00%) fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> { . if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) } 32 ( 0.00%) } . . /// Is the given keyword `kw` followed by a non-reserved identifier? 224 ( 0.00%) fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool { 112 ( 0.00%) self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()) 252 ( 0.00%) } . 510 ( 0.00%) fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool { 182 ( 0.00%) if ok { . true . } else { 144 ( 0.00%) self.expected_tokens.push(typ); . false . } 510 ( 0.00%) } . . fn check_ident(&mut self) -> bool { 83 ( 0.00%) self.check_or_expected(self.token.is_ident(), TokenType::Ident) . } . 140 ( 0.00%) fn check_path(&mut self) -> bool { 331 ( 0.00%) self.check_or_expected(self.token.is_path_start(), TokenType::Path) 175 ( 0.00%) } . . fn check_type(&mut self) -> bool { 56 ( 0.00%) self.check_or_expected(self.token.can_begin_type(), TokenType::Type) . } . . fn check_const_arg(&mut self) -> bool { 56 ( 0.00%) self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const) . } . 27 ( 0.00%) fn check_inline_const(&self, dist: usize) -> bool { 15 ( 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, . }) 27 ( 0.00%) } . . /// Checks to see if the next token is either `+` or `+=`. . /// Otherwise returns `false`. . fn check_plus(&mut self) -> bool { 80 ( 0.00%) self.check_or_expected( 40 ( 0.00%) self.token.is_like_plus(), 40 ( 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. 852 ( 0.00%) fn break_and_eat(&mut self, expected: TokenKind) -> bool { 497 ( 0.00%) if self.token.kind == expected { 62 ( 0.00%) self.bump(); . return true; . } 200 ( 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 . } . _ => { 120 ( 0.00%) self.expected_tokens.push(TokenType::Token(expected)); . false . } . } 799 ( 0.00%) } . . /// Eats `+` possibly breaking tokens like `+=` in process. . fn eat_plus(&mut self) -> bool { 20 ( 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, ()> { 6 ( 0.00%) if self.break_and_eat(token::BinOp(token::And)) { Ok(()) } else { self.unexpected() } . } . . /// Eats `|` possibly breaking tokens like `||` in process. . /// Signals an error if `|` was not eaten. . fn expect_or(&mut self) -> PResult<'a, ()> { . if self.break_and_eat(token::BinOp(token::Or)) { Ok(()) } else { self.unexpected() } . } . . /// Eats `<` possibly breaking tokens like `<<` in process. 48 ( 0.00%) fn eat_lt(&mut self) -> bool { 169 ( 0.00%) let ate = self.break_and_eat(token::Lt); 107 ( 0.00%) if ate { . // See doc comment for `unmatched_angle_bracket_count`. 60 ( 0.00%) self.unmatched_angle_bracket_count += 1; 68 ( 0.00%) self.max_angle_bracket_count += 1; . debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count); . } . ate 48 ( 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, ()> { 90 ( 0.00%) if self.break_and_eat(token::Gt) { . // See doc comment for `unmatched_angle_bracket_count`. 45 ( 0.00%) if self.unmatched_angle_bracket_count > 0 { 30 ( 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 { 189 ( 0.00%) TokenExpectType::Expect => self.check(k), . TokenExpectType::NoExpect => self.token == **k, . }) . } . . fn parse_seq_to_before_tokens( . &mut self, . kets: &[&TokenKind], . sep: SeqSep, -- line 758 ---------------------------------------- -- line 761 ---------------------------------------- . ) -> PResult<'a, (Vec, bool /* trailing */, bool /* recovered */)> { . let mut first = true; . let mut recovered = false; . let mut trailing = false; . let mut v = vec![]; . let unclosed_delims = !self.unclosed_delims.is_empty(); . . while !self.expect_any_with_type(kets, expect) { 160 ( 0.00%) if let token::CloseDelim(..) | token::Eof = self.token.kind { . break; . } 108 ( 0.00%) if let Some(ref t) = sep.sep { 127 ( 0.00%) if first { . first = false; . } else { 84 ( 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; . } . } . } . } . } . } 58 ( 0.00%) if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) { . trailing = true; . break; . } . 26 ( 0.00%) let t = f(self)?; 141 ( 0.00%) v.push(t); . } . 68 ( 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)> { 72 ( 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. 50 ( 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 */)> { 43 ( 0.00%) let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?; 25 ( 0.00%) if !recovered { . self.eat(ket); . } 93 ( 0.00%) Ok((val, trailing)) 40 ( 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)> { 35 ( 0.00%) self.expect(bra)?; 40 ( 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( 17 ( 0.00%) &token::OpenDelim(delim), 29 ( 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. 184,691 ( 0.20%) fn bump_with(&mut self, (next_token, next_spacing): (Token, Spacing)) { . // Bumping after EOF is a bad sign, usually an infinite loop. 85,242 ( 0.09%) 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. 56,828 ( 0.06%) self.prev_token = mem::replace(&mut self.token, next_token); 14,207 ( 0.02%) self.token_spacing = next_spacing; . . // Diagnostics. 14,207 ( 0.02%) self.expected_tokens.clear(); . } . . /// Advance the parser by one token. 113,656 ( 0.12%) pub fn bump(&mut self) { 56,828 ( 0.06%) let next_token = self.next_tok(self.token.span); 85,242 ( 0.09%) self.bump_with(next_token); 113,656 ( 0.12%) } . . /// 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 { 50 ( 0.00%) if dist == 0 { 11 ( 0.00%) return looker(&self.token); . } . 123 ( 0.00%) let frame = &self.token_cursor.frame; 154 ( 0.00%) if frame.delim != DelimToken::NoDelim { . let all_normal = (0..dist).all(|i| { 458 ( 0.00%) let token = frame.tree_cursor.look_ahead(i); 632 ( 0.00%) !matches!(token, Some(TokenTree::Delimited(_, DelimToken::NoDelim, _))) . }); . if all_normal { 750 ( 0.00%) return match frame.tree_cursor.look_ahead(dist - 1) { 264 ( 0.00%) Some(tree) => match tree { 111 ( 0.00%) TokenTree::Token(token) => looker(token), . TokenTree::Delimited(dspan, delim, _) => { 196 ( 0.00%) looker(&Token::new(token::OpenDelim(*delim), dspan.open)) . } . }, 76 ( 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 { 124 ( 0.00%) token = cursor.next().0; 50 ( 0.00%) if matches!( 32 ( 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. 180 ( 0.00%) fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool { 53 ( 0.00%) self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw))) 180 ( 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. 20 ( 0.00%) fn parse_unsafety(&mut self) -> Unsafe { . if self.eat_keyword(kw::Unsafe) { 10 ( 0.00%) Unsafe::Yes(self.prev_token.uninterpolated_span()) . } else { . Unsafe::No . } 80 ( 0.00%) } . . /// Parses constness: `const` or nothing. 192 ( 0.00%) fn parse_constness(&mut self) -> Const { . // Avoid const blocks to be parsed as const items 54 ( 0.00%) if self.look_ahead(1, |t| t != &token::OpenDelim(DelimToken::Brace)) . && self.eat_keyword(kw::Const) . { . Const::Yes(self.prev_token.uninterpolated_span()) . } else { . Const::No . } 336 ( 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 } 2 ( 0.00%) } . . /// Possibly parses mutability (`const` or `mut`). 24 ( 0.00%) fn parse_const_or_mut(&mut self) -> Option { . if self.eat_keyword(kw::Mut) { . Some(Mutability::Mut) . } else if self.eat_keyword(kw::Const) { . Some(Mutability::Not) . } else { . None . } 24 ( 0.00%) } . . fn parse_field_name(&mut self) -> PResult<'a, Ident> { 2 ( 0.00%) if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind . { . self.expect_no_suffix(self.token.span, "a tuple index", suffix); . self.bump(); . Ok(Ident::new(symbol, self.prev_token.span)) . } else { 3 ( 0.00%) self.parse_ident_common(true) . } . } . . fn parse_mac_args(&mut self) -> PResult<'a, P> { 6 ( 0.00%) self.parse_mac_args_common(true).map(P) . } . . fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> { 42 ( 0.00%) self.parse_mac_args_common(false) . } . 144 ( 0.00%) fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> { 128 ( 0.00%) Ok( 100 ( 0.00%) if self.check(&token::OpenDelim(DelimToken::Paren)) 15 ( 0.00%) || self.check(&token::OpenDelim(DelimToken::Bracket)) 15 ( 0.00%) || self.check(&token::OpenDelim(DelimToken::Brace)) . { 52 ( 0.00%) match self.parse_token_tree() { 65 ( 0.00%) TokenTree::Delimited(dspan, delim, tokens) => . // We've confirmed above that there is a delimiter so unwrapping is OK. . { 26 ( 0.00%) MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens) . } . _ => unreachable!(), . } 6 ( 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(); . }, . ) 112 ( 0.00%) } . . fn parse_or_use_outer_attributes( . &mut self, . already_parsed_attrs: Option, . ) -> PResult<'a, AttrWrapper> { 39 ( 0.00%) if let Some(attrs) = already_parsed_attrs { . Ok(attrs) . } else { 18 ( 0.00%) self.parse_outer_attributes() . } . } . . /// Parses a single token tree from the input. 888 ( 0.00%) pub(crate) fn parse_token_tree(&mut self) -> TokenTree { 333 ( 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. 28,758 ( 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. 26,676 ( 0.03%) 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; 222 ( 0.00%) let stream = frame.tree_cursor.stream.clone(); 222 ( 0.00%) let span = frame.span; 111 ( 0.00%) let delim = frame.delim; . // Consume close delimiter 222 ( 0.00%) self.bump(); 555 ( 0.00%) TokenTree::Delimited(span, delim, stream) . } . token::CloseDelim(_) | token::Eof => unreachable!(), . _ => { . self.bump(); . TokenTree::Token(self.prev_token.clone()) . } . } 777 ( 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 { 17 ( 0.00%) let old = self.restrictions; 23 ( 0.00%) self.restrictions = res; . let res = f(self); 23 ( 0.00%) self.restrictions = old; . res . } . 232 ( 0.00%) fn is_crate_vis(&self) -> bool { 145 ( 0.00%) self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep) 261 ( 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. 250 ( 0.00%) pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> { 50 ( 0.00%) maybe_whole!(self, NtVis, |x| x); . 25 ( 0.00%) self.expected_tokens.push(TokenType::Keyword(kw::Crate)); 100 ( 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". 18 ( 0.00%) return Ok(Visibility { 54 ( 0.00%) span: self.token.span.shrink_to_lo(), . kind: VisibilityKind::Inherited, . tokens: None, . }); . } 7 ( 0.00%) let lo = self.prev_token.span; . 35 ( 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. . if self.is_keyword_ahead(1, &[kw::Crate]) && self.look_ahead(2, |t| t != &token::ModSep) . // account for `pub(crate::foo)` . { . // Parse `pub(crate)`. -- line 1303 ---------------------------------------- -- line 1338 ---------------------------------------- . } else if let FollowedByType::No = fbt { . // Provide this diagnostic if a type cannot follow; . // in particular, if this is not a tuple struct. . self.recover_incorrect_vis_restriction()?; . // Emit diagnostic, but continue with public visibility. . } . } . 21 ( 0.00%) Ok(Visibility { span: lo, kind: VisibilityKind::Public, tokens: None }) 225 ( 0.00%) } . . /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }` . fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> { . self.bump(); // `(` . let path = self.parse_path(PathStyle::Mod)?; . self.expect(&token::CloseDelim(token::Paren))?; // `)` . . let msg = "incorrect visibility restriction"; -- line 1355 ---------------------------------------- -- line 1370 ---------------------------------------- . ) . .emit(); . . Ok(()) . } . . /// Parses `extern string_literal?`. . fn parse_extern(&mut self) -> Extern { 4 ( 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 `::*` 824 ( 0.00%) fn is_import_coupler(&mut self) -> bool { 412 ( 0.00%) self.check(&token::ModSep) . && self.look_ahead(1, |t| { 154 ( 0.00%) *t == token::OpenDelim(token::Brace) || *t == token::BinOp(token::Star) . }) 855 ( 0.00%) } . . pub fn clear_expected_tokens(&mut self) { . self.expected_tokens.clear(); . } . } . . crate fn make_unclosed_delims_error( . unmatched: UnmatchedBrace, -- line 1430 ---------------------------------------- -- line 1450 ---------------------------------------- . err.span_label(sp, "closing delimiter possibly meant for this"); . } . if let Some(sp) = unmatched.unclosed_span { . err.span_label(sp, "unclosed delimiter"); . } . Some(err) . } . 144 ( 0.00%) pub fn emit_unclosed_delims(unclosed_delims: &mut Vec, sess: &ParseSess) { 72 ( 0.00%) *sess.reached_eof.borrow_mut() |= . unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none()); 72 ( 0.00%) for unmatched in unclosed_delims.drain(..) { . if let Some(mut e) = make_unclosed_delims_error(unmatched, sess) { . e.emit(); . } . } 144 ( 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 ---------------------------------------- 49,311 ( 0.05%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_metadata/src/rmeta/decoder.rs -------------------------------------------------------------------------------- Ir -- line 176 ---------------------------------------- . } . fn sess(self) -> Option<&'tcx Session> { . None . } . fn tcx(self) -> Option> { . None . } . 1,407 ( 0.00%) fn decoder(self, pos: usize) -> DecodeContext<'a, 'tcx> { 469 ( 0.00%) let tcx = self.tcx(); 44,958 ( 0.05%) DecodeContext { 4,787 ( 0.01%) opaque: opaque::Decoder::new(self.blob(), pos), 469 ( 0.00%) cdata: self.cdata(), . blob: self.blob(), 1,006 ( 0.00%) sess: self.sess().or(tcx.map(|tcx| tcx.sess)), . tcx, . last_source_file_index: 0, . lazy_state: LazyState::NoNode, . alloc_decoding_session: self . .cdata() 3,719 ( 0.00%) .map(|cdata| cdata.cdata.alloc_decoding_state.new_decoding_session()), . } 1,407 ( 0.00%) } . } . . impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a MetadataBlob { . #[inline] . fn blob(self) -> &'a MetadataBlob { . self . } . } -- line 206 ---------------------------------------- -- line 255 ---------------------------------------- . } . #[inline] . fn tcx(self) -> Option> { . Some(self.1) . } . } . . impl<'a, 'tcx, T: Decodable>> Lazy { 558 ( 0.00%) fn decode>(self, metadata: M) -> T { 3,406 ( 0.00%) let mut dcx = metadata.decoder(self.position.get()); 12,549 ( 0.01%) dcx.lazy_state = LazyState::NodeStart(self.position); 5,666 ( 0.01%) T::decode(&mut dcx) 720 ( 0.00%) } . } . . 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); 3,866 ( 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 { 12,109 ( 0.01%) if cnum == LOCAL_CRATE { self.cdata().cnum } else { self.cdata().cnum_map[cnum] } . } . 4,541 ( 0.00%) fn read_lazy_with_meta(&mut self, meta: T::Meta) -> Lazy { . let distance = self.read_usize(); 4,147 ( 0.00%) let position = match self.lazy_state { . LazyState::NoNode => bug!("read_lazy_with_meta: outside of a metadata node"), 479 ( 0.00%) LazyState::NodeStart(start) => { . let start = start.get(); 958 ( 0.00%) assert!(distance <= start); . start - distance . } 1,626 ( 0.00%) LazyState::Previous(last_pos) => last_pos.get() + distance, . }; 2,042 ( 0.00%) self.lazy_state = LazyState::Previous(NonZeroUsize::new(position).unwrap()); . Lazy::from_position_and_meta(NonZeroUsize::new(position).unwrap(), meta) 4,541 ( 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 326 ---------------------------------------- . . #[inline] . fn tcx(&self) -> TyCtxt<'tcx> { . self.tcx.expect("missing TyCtxt in DecodeContext") . } . . #[inline] . fn peek_byte(&self) -> u8 { 8,935 ( 0.01%) self.opaque.data[self.opaque.position()] . } . . #[inline] . fn position(&self) -> usize { . self.opaque.position() . } . 8,302 ( 0.01%) fn cached_ty_for_shorthand(&mut self, shorthand: usize, or_insert_with: F) -> Ty<'tcx> . where . F: FnOnce(&mut Self) -> Ty<'tcx>, . { 1,186 ( 0.00%) let tcx = self.tcx(); . 1,186 ( 0.00%) let key = ty::CReaderCacheKey { cnum: Some(self.cdata().cnum), pos: shorthand }; . 2,916 ( 0.00%) if let Some(&ty) = tcx.ty_rcache.borrow().get(&key) { . return ty; . } . 457 ( 0.00%) let ty = or_insert_with(self); . tcx.ty_rcache.borrow_mut().insert(key, ty); . ty 10,674 ( 0.01%) } . . fn with_position(&mut self, pos: usize, f: F) -> R . where . F: FnOnce(&mut Self) -> R, . { . let new_opaque = opaque::Decoder::new(self.opaque.data, pos); . let old_opaque = mem::replace(&mut self.opaque, new_opaque); . let old_state = mem::replace(&mut self.lazy_state, LazyState::NoNode); . let r = f(self); 2,315 ( 0.00%) self.opaque = old_opaque; 463 ( 0.00%) self.lazy_state = old_state; . r . } . . fn decode_alloc_id(&mut self) -> rustc_middle::mir::interpret::AllocId { . if let Some(alloc_decoding_session) = self.alloc_decoding_session { . alloc_decoding_session.decode_alloc_id(self) . } else { . bug!("Attempting to decode interpret::AllocId without CrateMetadata") . } . } . } . . impl<'a, 'tcx> Decodable> for CrateNum { . fn decode(d: &mut DecodeContext<'a, 'tcx>) -> CrateNum { 7,123 ( 0.01%) let cnum = CrateNum::from_u32(d.read_u32()); . d.map_encoded_cnum_to_current(cnum) . } . } . . impl<'a, 'tcx> Decodable> for DefIndex { 27 ( 0.00%) fn decode(d: &mut DecodeContext<'a, 'tcx>) -> DefIndex { 14,547 ( 0.02%) DefIndex::from_u32(d.read_u32()) 54 ( 0.00%) } . } . . impl<'a, 'tcx> Decodable> for ExpnIndex { . fn decode(d: &mut DecodeContext<'a, 'tcx>) -> ExpnIndex { . ExpnIndex::from_u32(d.read_u32()) . } . } . . impl<'a, 'tcx> Decodable> for SyntaxContext { 10,228 ( 0.01%) fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> SyntaxContext { 2,557 ( 0.00%) let cdata = decoder.cdata(); 2,557 ( 0.00%) let sess = decoder.sess.unwrap(); 5,114 ( 0.01%) let cname = cdata.root.name; . rustc_span::hygiene::decode_syntax_context(decoder, &cdata.hygiene_context, |_, id| { . debug!("SpecializedDecoder: decoding {}", id); 8 ( 0.00%) cdata . .root . .syntax_contexts . .get(cdata, id) . .unwrap_or_else(|| panic!("Missing SyntaxContext {:?} for crate {:?}", id, cname)) . .decode((cdata, sess)) . }) 12,785 ( 0.01%) } . } . . impl<'a, 'tcx> Decodable> for ExpnId { 1,498 ( 0.00%) fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> ExpnId { 214 ( 0.00%) let local_cdata = decoder.cdata(); 214 ( 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); 10 ( 0.00%) let crate_data = if cnum == local_cdata.cnum { . local_cdata . } else { . local_cdata.cstore.get_crate_data(cnum) . }; 50 ( 0.00%) let expn_data = crate_data . .root . .expn_data . .get(crate_data, index) . .unwrap() . .decode((crate_data, sess)); 50 ( 0.00%) let expn_hash = crate_data . .root . .expn_hashes . .get(crate_data, index) . .unwrap() . .decode((crate_data, sess)); 100 ( 0.00%) (expn_data, expn_hash) . }); . expn_id 1,712 ( 0.00%) } . } . . impl<'a, 'tcx> Decodable> for Span { 20,408 ( 0.02%) fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Span { 2,551 ( 0.00%) let ctxt = SyntaxContext::decode(decoder); . let tag = u8::decode(decoder); . 5,102 ( 0.01%) 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; . 7,641 ( 0.01%) 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. 5,917 ( 0.01%) 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. 7,641 ( 0.01%) let last_source_file = &imported_source_files[decoder.last_source_file_index]; . 10,108 ( 0.01%) 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) 1,646 ( 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 823 ( 0.00%) if tag == TAG_VALID_SPAN_LOCAL { 823 ( 0.00%) decoder.last_source_file_index = index; . } 1,646 ( 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 = 10,188 ( 0.01%) (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) 22,959 ( 0.03%) } . } . . 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 { 594 ( 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(); 3,231 ( 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] . } . 11,605 ( 0.01%) fn opt_item_ident(self, item_index: DefIndex, sess: &Session) -> Option { 8,460 ( 0.01%) let name = self.def_key(item_index).disambiguated_data.data.get_opt_name()?; 2,303 ( 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)) 14,778 ( 0.02%) } . 25 ( 0.00%) fn item_ident(self, item_index: DefIndex, sess: &Session) -> Ident { 93 ( 0.00%) self.opt_item_ident(item_index, sess).expect("no encoded ident for item") 50 ( 0.00%) } . . fn maybe_kind(self, item_id: DefIndex) -> Option { 838 ( 0.00%) self.root.tables.kind.get(self, item_id).map(|k| k.decode(self)) . } . 3,352 ( 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, . ) . }) 2,514 ( 0.00%) } . 3,430 ( 0.00%) fn def_kind(self, item_id: DefIndex) -> DefKind { 2,095 ( 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, . ) . }) 1,960 ( 0.00%) } . 225 ( 0.00%) fn get_span(self, index: DefIndex, sess: &Session) -> Span { 1,499 ( 0.00%) self.root . .tables . .span . .get(self, index) . .unwrap_or_else(|| panic!("Missing span for {:?}", index)) . .decode((self, sess)) 125 ( 0.00%) } . . fn load_proc_macro(self, id: DefIndex, sess: &Session) -> SyntaxExtension { . let (name, kind, helper_attrs) = match *self.raw_proc_macro(id) { . ProcMacro::CustomDerive { trait_name, attributes, client } => { . let helper_attrs = . attributes.iter().cloned().map(Symbol::intern).collect::>(); . ( . trait_name, -- line 778 ---------------------------------------- -- line 795 ---------------------------------------- . self.get_span(id, sess), . helper_attrs, . self.root.edition, . Symbol::intern(name), . &attrs, . ) . } . 91 ( 0.00%) fn get_trait_def(self, item_id: DefIndex, sess: &Session) -> ty::TraitDef { 28 ( 0.00%) match self.kind(item_id) { 7 ( 0.00%) EntryKind::Trait(data) => { 42 ( 0.00%) let data = data.decode((self, sess)); 112 ( 0.00%) ty::TraitDef::new( . self.local_def_id(item_id), 14 ( 0.00%) data.unsafety, 14 ( 0.00%) data.paren_sugar, 14 ( 0.00%) data.has_auto_impl, 14 ( 0.00%) data.is_marker, 7 ( 0.00%) data.skip_array_during_method_dispatch, 7 ( 0.00%) data.specialization_kind, 28 ( 0.00%) self.def_path_hash(item_id), 7 ( 0.00%) data.must_implement_one_of, . ) . } . EntryKind::TraitAlias => ty::TraitDef::new( . self.local_def_id(item_id), . hir::Unsafety::Normal, . false, . false, . false, . false, . ty::trait_def::TraitSpecializationKind::None, . self.def_path_hash(item_id), . None, . ), . _ => bug!("def-index does not refer to trait or trait alias"), . } 63 ( 0.00%) } . 9 ( 0.00%) fn get_variant( . self, . kind: &EntryKind, . index: DefIndex, . parent_did: DefId, . sess: &Session, . ) -> ty::VariantDef { 4 ( 0.00%) let data = match kind { . EntryKind::Variant(data) | EntryKind::Struct(data, _) | EntryKind::Union(data, _) => { 5 ( 0.00%) data.decode(self) . } . _ => bug!(), . }; . 4 ( 0.00%) let adt_kind = match kind { . EntryKind::Variant(_) => ty::AdtKind::Enum, . EntryKind::Struct(..) => ty::AdtKind::Struct, . EntryKind::Union(..) => ty::AdtKind::Union, . _ => bug!(), . }; . . let variant_did = . if adt_kind == ty::AdtKind::Enum { Some(self.local_def_id(index)) } else { None }; 2 ( 0.00%) let ctor_did = data.ctor.map(|index| self.local_def_id(index)); . 22 ( 0.00%) ty::VariantDef::new( . self.item_ident(index, sess).name, . variant_did, . ctor_did, 4 ( 0.00%) data.discr, 6 ( 0.00%) self.root . .tables . .children . .get(self, index) . .unwrap_or_else(Lazy::empty) . .decode(self) . .map(|index| ty::FieldDef { 1 ( 0.00%) did: self.local_def_id(index), 2 ( 0.00%) name: self.item_ident(index, sess).name, 2 ( 0.00%) vis: self.get_visibility(index), . }) . .collect(), . data.ctor_kind, . adt_kind, . parent_did, . false, 1 ( 0.00%) data.is_non_exhaustive, . ) 9 ( 0.00%) } . 15 ( 0.00%) fn get_adt_def(self, item_id: DefIndex, tcx: TyCtxt<'tcx>) -> &'tcx ty::AdtDef { 4 ( 0.00%) let kind = self.kind(item_id); 2 ( 0.00%) let did = self.local_def_id(item_id); . 5 ( 0.00%) let (adt_kind, repr) = match kind { . EntryKind::Enum(repr) => (ty::AdtKind::Enum, repr), . EntryKind::Struct(_, repr) => (ty::AdtKind::Struct, repr), . EntryKind::Union(_, repr) => (ty::AdtKind::Union, repr), . _ => bug!("get_adt_def called on a non-ADT {:?}", did), . }; . . let variants = if let ty::AdtKind::Enum = adt_kind { . self.root -- line 896 ---------------------------------------- -- line 897 ---------------------------------------- . .tables . .children . .get(self, item_id) . .unwrap_or_else(Lazy::empty) . .decode(self) . .map(|index| self.get_variant(&self.kind(index), index, did, tcx.sess)) . .collect() . } else { 8 ( 0.00%) std::iter::once(self.get_variant(&kind, item_id, did, tcx.sess)).collect() . }; . 14 ( 0.00%) tcx.alloc_adt_def(did, adt_kind, variants, repr) 7 ( 0.00%) } . . fn get_explicit_predicates( . self, . item_id: DefIndex, . tcx: TyCtxt<'tcx>, . ) -> ty::GenericPredicates<'tcx> { 100 ( 0.00%) self.root.tables.explicit_predicates.get(self, item_id).unwrap().decode((self, tcx)) . } . . fn get_inferred_outlives( . self, . item_id: DefIndex, . tcx: TyCtxt<'tcx>, . ) -> &'tcx [(ty::Predicate<'tcx>, Span)] { 100 ( 0.00%) self.root . .tables . .inferred_outlives . .get(self, item_id) . .map(|predicates| tcx.arena.alloc_from_iter(predicates.decode((self, tcx)))) . .unwrap_or_default() . } . . fn get_super_predicates( . self, . item_id: DefIndex, . tcx: TyCtxt<'tcx>, . ) -> ty::GenericPredicates<'tcx> { 20 ( 0.00%) self.root.tables.super_predicates.get(self, item_id).unwrap().decode((self, tcx)) . } . . fn get_explicit_item_bounds( . self, . item_id: DefIndex, . tcx: TyCtxt<'tcx>, . ) -> &'tcx [(ty::Predicate<'tcx>, Span)] { . self.root -- line 945 ---------------------------------------- -- line 946 ---------------------------------------- . .tables . .explicit_item_bounds . .get(self, item_id) . .map(|bounds| tcx.arena.alloc_from_iter(bounds.decode((self, tcx)))) . .unwrap_or_default() . } . . fn get_generics(self, item_id: DefIndex, sess: &Session) -> ty::Generics { 144 ( 0.00%) self.root.tables.generics.get(self, item_id).unwrap().decode((self, sess)) . } . . fn get_type(self, id: DefIndex, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { 2,195 ( 0.00%) self.root . .tables . .ty . .get(self, id) . .unwrap_or_else(|| panic!("Not a type: {:?}", id)) . .decode((self, tcx)) . } . . fn get_stability(self, id: DefIndex) -> Option { 70 ( 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 { 60 ( 0.00%) self.root.tables.deprecation.get(self, id).map(|depr| depr.decode(self)) . } . 12 ( 0.00%) fn get_visibility(self, id: DefIndex) -> ty::Visibility { 713 ( 0.00%) self.root.tables.visibility.get(self, id).unwrap().decode(self) 8 ( 0.00%) } . . fn get_impl_data(self, id: DefIndex) -> ImplData { 210 ( 0.00%) match self.kind(id) { 175 ( 0.00%) EntryKind::Impl(data) => data.decode(self), . _ => bug!(), . } . } . . fn get_parent_impl(self, id: DefIndex) -> Option { 84 ( 0.00%) self.get_impl_data(id).parent_impl . } . . fn get_impl_polarity(self, id: DefIndex) -> ty::ImplPolarity { 6 ( 0.00%) self.get_impl_data(id).polarity . } . . fn get_impl_defaultness(self, id: DefIndex) -> hir::Defaultness { 1 ( 0.00%) self.get_impl_data(id).defaultness . } . . fn get_impl_constness(self, id: DefIndex) -> hir::Constness { . self.get_impl_data(id).constness . } . . fn get_trait_item_def_id(self, id: DefIndex) -> Option { 55 ( 0.00%) self.root.tables.trait_item_def_id.get(self, id).map(|d| d.decode(self)) . } . . fn get_coerce_unsized_info(self, id: DefIndex) -> Option { . self.get_impl_data(id).coerce_unsized_info . } . . fn get_impl_trait(self, id: DefIndex, tcx: TyCtxt<'tcx>) -> Option> { 408 ( 0.00%) self.root.tables.impl_trait_ref.get(self, id).map(|tr| tr.decode((self, tcx))) . } . . fn get_expn_that_defined(self, id: DefIndex, sess: &Session) -> ExpnId { 1,010 ( 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(); 6 ( 0.00%) let name_to_id = self . .root . .diagnostic_items . .decode(self) . .map(|(name, def_index)| { 91 ( 0.00%) let id = self.local_def_id(def_index); 91 ( 0.00%) id_to_name.insert(id, name); . (name, id) . }) . .collect(); 27 ( 0.00%) DiagnosticItems { id_to_name, name_to_id } . } . . /// Iterates over all named children of the given module, . /// including both proper items and reexports. . /// Module here is understood in name resolution sense - it can be a `mod` item, . /// or a crate root, or an enum, or a trait. . fn for_each_module_child( . self, . id: DefIndex, . mut callback: impl FnMut(ModChild), . sess: &Session, . ) { 132 ( 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. 264 ( 0.00%) if let Some(children) = self.root.tables.children.get(self, id) { 528 ( 0.00%) for child_index in children.decode((self, sess)) { 6,108 ( 0.01%) if let Some(ident) = self.opt_item_ident(child_index, sess) { 864 ( 0.00%) let kind = self.def_kind(child_index); 576 ( 0.00%) if matches!(kind, DefKind::Macro(..)) { . // FIXME: Macros are currently encoded twice, once as items and once as . // reexports. We ignore the items here and only use the reexports. . continue; . } . let def_id = self.local_def_id(child_index); . let res = Res::Def(kind, def_id); . let vis = self.get_visibility(child_index); . let span = self.get_span(child_index, sess); . . callback(ModChild { ident, res, vis, span }); . . // For non-re-export structs and variants add their constructors to children. . // Re-export lists automatically contain constructors when necessary. 1,128 ( 0.00%) match kind { . DefKind::Struct => { 4 ( 0.00%) if let Some((ctor_def_id, ctor_kind)) = . self.get_ctor_def_id_and_kind(child_index) . { . let ctor_res = . Res::Def(DefKind::Ctor(CtorOf::Struct, ctor_kind), ctor_def_id); . let vis = self.get_visibility(ctor_def_id.index); . callback(ModChild { ident, res: ctor_res, vis, span }); . } . } -- line 1121 ---------------------------------------- -- line 1144 ---------------------------------------- . callback(ModChild { ident, res: ctor_res, vis, span }); . } . _ => {} . } . } . } . } . 345 ( 0.00%) match self.kind(id) { 18 ( 0.00%) EntryKind::Mod(exports) => { 566 ( 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 { 1,400 ( 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 1242 ---------------------------------------- . qualif, . _, . ) => qualif, . _ => bug!("mir_const_qualif: unexpected kind"), . } . } . . fn get_fn_has_self_parameter(self, id: DefIndex) -> bool { 535 ( 0.00%) match self.kind(id) { 428 ( 0.00%) EntryKind::AssocFn(data) => data.decode(self).has_self, . _ => false, . } . } . . fn get_associated_item_def_ids(self, tcx: TyCtxt<'tcx>, id: DefIndex) -> &'tcx [DefId] { 42 ( 0.00%) if let Some(children) = self.root.tables.children.get(self, id) { 18 ( 0.00%) tcx.arena.alloc_from_iter( 6 ( 0.00%) children.decode((self, tcx.sess)).map(|child_index| self.local_def_id(child_index)), . ) . } else { . &[] . } . } . 108 ( 0.00%) fn get_associated_item(self, id: DefIndex, sess: &Session) -> ty::AssocItem { 63 ( 0.00%) let def_key = self.def_key(id); . let parent = self.local_def_id(def_key.parent.unwrap()); . let ident = self.item_ident(id, sess); . 67 ( 0.00%) let (kind, container, has_self) = match self.kind(id) { . EntryKind::AssocConst(container, _, _) => (ty::AssocKind::Const, container, false), 7 ( 0.00%) EntryKind::AssocFn(data) => { . let data = data.decode(self); 49 ( 0.00%) (ty::AssocKind::Fn, data.container, data.has_self) . } 4 ( 0.00%) EntryKind::AssocType(container) => (ty::AssocKind::Type, container, false), . _ => bug!("cannot get associated-item of `{:?}`", def_key), . }; . 162 ( 0.00%) ty::AssocItem { . name: ident.name, . kind, . vis: self.get_visibility(id), . defaultness: container.defaultness(), . def_id: self.local_def_id(id), . trait_item_def_id: self.get_trait_item_def_id(id), . container: container.with_def_id(parent), . fn_has_self_parameter: has_self, . } 81 ( 0.00%) } . . fn get_item_variances(self, id: DefIndex) -> impl Iterator + 'a { 10 ( 0.00%) self.root.tables.variances.get(self, id).unwrap_or_else(Lazy::empty).decode(self) . } . . fn get_ctor_def_id_and_kind(self, node_id: DefIndex) -> Option<(DefId, CtorKind)> { 148 ( 0.00%) match self.kind(node_id) { . EntryKind::Struct(data, _) | EntryKind::Variant(data) => { 64 ( 0.00%) let vdata = data.decode(self); 52 ( 0.00%) vdata.ctor.map(|index| (self.local_def_id(index), vdata.ctor_kind)) . } . _ => None, . } 80 ( 0.00%) } . 84 ( 0.00%) fn get_item_attrs( . self, . id: DefIndex, . sess: &'a Session, . ) -> impl Iterator + 'a { 63 ( 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)) 63 ( 0.00%) } . . fn get_struct_field_names( . self, . id: DefIndex, . sess: &'a Session, . ) -> impl Iterator> + 'a { 95 ( 0.00%) self.root . .tables . .children . .get(self, id) . .unwrap_or_else(Lazy::empty) . .decode(self) 250 ( 0.00%) .map(move |index| respan(self.get_span(index, sess), self.item_ident(index, sess).name)) . } . . fn get_struct_field_visibilities(self, id: DefIndex) -> impl Iterator + 'a { 25 ( 0.00%) self.root . .tables . .children . .get(self, id) . .unwrap_or_else(Lazy::empty) . .decode(self) 4 ( 0.00%) .map(move |field_index| self.get_visibility(field_index)) . } . . fn get_inherent_implementations_for_type( . self, . tcx: TyCtxt<'tcx>, . id: DefIndex, . ) -> &'tcx [DefId] { 4 ( 0.00%) tcx.arena.alloc_from_iter( 5 ( 0.00%) self.root . .tables . .inherent_impls . .get(self, id) . .unwrap_or_else(Lazy::empty) . .decode(self) 11 ( 0.00%) .map(|index| self.local_def_id(index)), . ) . } . . fn get_traits(self) -> impl Iterator + 'a { . self.root.traits.decode(self).map(move |index| self.local_def_id(index)) . } . . fn get_trait_impls(self) -> impl Iterator)> + 'a { -- line 1376 ---------------------------------------- -- line 1380 ---------------------------------------- . index: *trait_index, . }; . impls.decode(self).map(move |(impl_index, simplified_self_ty)| { . (trait_def_id, self.local_def_id(impl_index), simplified_self_ty) . }) . }) . } . 189 ( 0.00%) fn get_implementations_of_trait( . self, . tcx: TyCtxt<'tcx>, . trait_def_id: DefId, . ) -> &'tcx [(DefId, Option)] { 21 ( 0.00%) if self.trait_impls.is_empty() { . return &[]; . } . . // Do a reverse lookup beforehand to avoid touching the crate_num . // hash map in the loop below. 28 ( 0.00%) let key = match self.reverse_translate_def_id(trait_def_id) { . Some(def_id) => (def_id.krate.as_u32(), def_id.index), . None => return &[], . }; . . if let Some(impls) = self.trait_impls.get(&key) { 32 ( 0.00%) tcx.arena.alloc_from_iter( 16 ( 0.00%) impls . .decode(self) 639 ( 0.00%) .map(|(idx, simplified_self_ty)| (self.local_def_id(idx), simplified_self_ty)), . ) . } else { . &[] . } 168 ( 0.00%) } . . fn get_trait_of_item(self, id: DefIndex) -> Option { 20 ( 0.00%) let def_key = self.def_key(id); 25 ( 0.00%) match def_key.disambiguated_data.data { . DefPathData::TypeNs(..) | DefPathData::ValueNs(..) => (), . // Not an associated item . _ => return None, . } 45 ( 0.00%) def_key.parent.and_then(|parent_index| match self.kind(parent_index) { . EntryKind::Trait(_) | EntryKind::TraitAlias => Some(self.local_def_id(parent_index)), . _ => None, . }) . } . . fn get_native_libraries(self, sess: &'a Session) -> impl Iterator + 'a { 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 { 9 ( 0.00%) let constness = match self.kind(id) { 2 ( 0.00%) EntryKind::AssocFn(data) => data.decode(self).fn_data.constness, . EntryKind::Fn(data) => data.decode(self).constness, . EntryKind::ForeignFn(data) => data.decode(self).constness, . EntryKind::Variant(..) | EntryKind::Struct(..) => hir::Constness::Const, . _ => hir::Constness::NotConst, . }; . constness == hir::Constness::Const . } . -- line 1505 ---------------------------------------- -- line 1532 ---------------------------------------- . fn generator_kind(self, id: DefIndex) -> Option { . match self.kind(id) { . EntryKind::Generator(data) => Some(data), . _ => None, . } . } . . fn fn_sig(self, id: DefIndex, tcx: TyCtxt<'tcx>) -> ty::PolyFnSig<'tcx> { 30 ( 0.00%) self.root.tables.fn_sig.get(self, id).unwrap().decode((self, tcx)) . } . . #[inline] 8,897 ( 0.01%) fn def_key(self, index: DefIndex) -> DefKey { 2,542 ( 0.00%) *self . .def_key_cache . .lock() . .entry(index) 5,615 ( 0.01%) .or_insert_with(|| self.root.tables.def_keys.get(self, index).unwrap().decode(self)) 10,168 ( 0.01%) } . . // 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 { 196 ( 0.00%) *def_path_hashes.entry(index).or_insert_with(|| { 125 ( 0.00%) self.root.tables.def_path_hashes.get(self, index).unwrap().decode(self) . }) . } . . #[inline] 686 ( 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) 784 ( 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`. 5,094 ( 0.01%) 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) . }); 5,094 ( 0.01%) 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; . } . } . } . } . } . }; . 5,094 ( 0.01%) 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.52%) *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.00%) 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 { 64 ( 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) { 18 ( 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 { 17 ( 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 { 2,332 ( 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() { 35 ( 0.00%) if global == did.krate { . return Some(DefId { krate: local, index: did.index }); . } . } . . None . } . } . -- line 1964 ---------------------------------------- 62,477 ( 0.07%) -------------------------------------------------------------------------------- -- 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, . } . 14 ( 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() 9 ( 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 { 9,229 ( 0.01%) self.override_span.unwrap_or_else(|| Span::with_root_ctxt(lo, hi)) . } . . /// Returns the next token, and info about preceding whitespace, if any. 53,165 ( 0.06%) fn next_token(&mut self) -> (Spacing, Token) { . let mut spacing = Spacing::Joint; . . // Skip `#!` at the start of the file 15,190 ( 0.02%) let start_src_index = self.src_index(self.pos); 22,785 ( 0.02%) let text: &str = &self.src[start_src_index..self.end_src_index]; . let is_beginning_of_file = self.pos == self.start_pos; 7,595 ( 0.01%) if is_beginning_of_file { 4 ( 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 { 12,517 ( 0.01%) let start_src_index = self.src_index(self.pos); 30,168 ( 0.03%) let text: &str = &self.src[start_src_index..self.end_src_index]; . 10,056 ( 0.01%) if text.is_empty() { . let span = self.mk_sp(self.pos, self.pos); 5 ( 0.00%) return (spacing, Token::new(token::Eof, span)); . } . 30,165 ( 0.03%) let token = rustc_lexer::first_token(text); . 20,110 ( 0.02%) let start = self.pos; 10,055 ( 0.01%) self.pos = self.pos + BytePos::from_usize(token.len); . . debug!("next_token: {:?}({:?})", token.kind, self.str_from(start)); . 81,548 ( 0.09%) match self.cook_lexer_token(token.kind, start) { 60,752 ( 0.07%) Some(kind) => { . let span = self.mk_sp(start, self.pos); 45,564 ( 0.05%) return (spacing, Token::new(kind, span)); . } . None => spacing = Spacing::Alone, . } . } 68,355 ( 0.07%) } . . /// 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. 1,099 ( 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()), . ); . } 1,256 ( 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 { 50,275 ( 0.05%) Some(match token { 434 ( 0.00%) rustc_lexer::TokenKind::LineComment { doc_style } => { . // Skip non-doc comments 1,699 ( 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); 1,385 ( 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 => { 6,532 ( 0.01%) let is_raw_ident = token == rustc_lexer::TokenKind::RawIdent; 8,165 ( 0.01%) let is_unknown_prefix = token == rustc_lexer::TokenKind::UnknownPrefix; . let mut ident_start = start; 3,266 ( 0.00%) if is_raw_ident { . ident_start = ident_start + BytePos(2); . } 4,899 ( 0.01%) if is_unknown_prefix { . self.report_unknown_prefix(start); . } 8,165 ( 0.01%) let sym = nfc_normalize(self.str_from(ident_start)); . let span = self.mk_sp(start, self.pos); 6,532 ( 0.01%) self.sess.symbol_gallery.insert(sym, span); 3,266 ( 0.00%) 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); . } 11,431 ( 0.01%) 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) . } 16 ( 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); 3 ( 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 264 ---------------------------------------- . .emit(); . None . } else { . Some(Symbol::intern(string)) . } . } else { . None . }; 8 ( 0.00%) token::Literal(token::Lit { kind, symbol, suffix }) . } 32 ( 0.00%) 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); 16 ( 0.00%) if starts_with_number { . self.err_span_(start, self.pos, "lifetimes cannot start with a number"); . } 48 ( 0.00%) let ident = Symbol::intern(lifetime_name); 64 ( 0.00%) token::Lifetime(ident) . } . rustc_lexer::TokenKind::Semi => token::Semi, . rustc_lexer::TokenKind::Comma => token::Comma, . rustc_lexer::TokenKind::Dot => token::Dot, . rustc_lexer::TokenKind::OpenParen => token::OpenDelim(token::Paren), . rustc_lexer::TokenKind::CloseParen => token::CloseDelim(token::Paren), . rustc_lexer::TokenKind::OpenBrace => token::OpenDelim(token::Brace), . rustc_lexer::TokenKind::CloseBrace => token::CloseDelim(token::Brace), -- line 291 ---------------------------------------- -- 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? . } . }) . } . 3,324 ( 0.00%) fn cook_doc_comment( . &self, . content_start: BytePos, . content: &str, . comment_kind: CommentKind, . doc_style: DocStyle, . ) -> TokenKind { 277 ( 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, . }; . 831 ( 0.00%) token::DocComment(comment_kind, attr_style, Symbol::intern(content)) 4,155 ( 0.00%) } . . 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 410 ---------------------------------------- . let n = u32::from(n_hashes); . (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##" "## . } 2 ( 0.00%) rustc_lexer::LiteralKind::Int { base, empty_int } => { 1 ( 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); 3 ( 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 465 ---------------------------------------- . #[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 { 13,749 ( 0.02%) 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); 7 ( 0.00%) Symbol::intern(self.str_from_to(start, end)) . } . . /// Slice of the source text spanning from `start` up to but excluding `end`. 2,084 ( 0.00%) fn str_from_to(&self, start: BytePos, end: BytePos) -> &str { . &self.src[self.src_index(start)..self.src_index(end)] 8,336 ( 0.01%) } . . fn report_raw_str_error(&self, start: BytePos, opt_err: Option) { . 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), -- line 493 ---------------------------------------- -- line 633 ---------------------------------------- . range, . err, . ); . } . }); . } . . fn validate_int_literal(&self, base: Base, content_start: BytePos, content_end: BytePos) { 4 ( 0.00%) let base = match base { . Base::Binary => 2, . Base::Octal => 8, . _ => return, . }; . let s = self.str_from_to(content_start + BytePos(2), content_end); . for (idx, c) in s.char_indices() { . let idx = idx as u32; . if c != '_' && c.to_digit(base).is_none() { -- line 649 ---------------------------------------- -- line 650 ---------------------------------------- . 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)); . } . } . } . } . 14,697 ( 0.02%) pub fn nfc_normalize(string: &str) -> Symbol { . use unicode_normalization::{is_nfc_quick, IsNormalized, UnicodeNormalization}; 3,266 ( 0.00%) match is_nfc_quick(string.chars()) { 16,330 ( 0.02%) IsNormalized::Yes => Symbol::intern(string), . _ => { . let normalized_str: String = string.chars().nfc().collect(); . Symbol::intern(&normalized_str) . } . } . } 38,467 ( 0.04%) -------------------------------------------------------------------------------- -- 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 { 3,712 ( 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> { 43 ( 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 237 ---------------------------------------- . /// assert_eq!(last, &2); . /// assert_eq!(elements, &[0, 1]); . /// } . /// ``` . #[stable(feature = "slice_splits", since = "1.5.0")] . #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")] . #[inline] . pub const fn split_last(&self) -> Option<(&T, &[T])> { 115 ( 0.00%) if let [init @ .., last] = self { Some((last, init)) } else { None } . } . . /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty. . /// . /// # Examples . /// . /// ``` . /// let x = &mut [0, 1, 2]; -- line 253 ---------------------------------------- -- line 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> { 14,101 ( 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> { 1,417 ( 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 { 2,291 ( 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 582 ---------------------------------------- . /// v.swap(2, 4); . /// assert!(v == ["a", "b", "e", "d", "c"]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_swap", issue = "83163")] . #[inline] . #[track_caller] . pub const fn swap(&mut self, a: usize, b: usize) { 8 ( 0.00%) let _ = &self[a]; 39 ( 0.00%) let _ = &self[b]; . . // SAFETY: we just checked that both `a` and `b` are in bounds . unsafe { self.swap_unchecked(a, b) } . } . . /// Swaps two elements in the slice, without doing bounds checking. . /// . /// For a safe alternative see [`swap`]. -- line 599 ---------------------------------------- -- line 677 ---------------------------------------- . . // Because this function is first compiled in isolation, . // this check tells LLVM that the indexing below is . // in-bounds. Then after inlining -- once the actual . // lengths of the slices are known -- it's removed. . let (a, b) = (&mut a[..n], &mut b[..n]); . . for i in 0..n { 1,841 ( 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]) { 54 ( 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]) { 294 ( 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. 60 ( 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(); 3,133 ( 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; 76,486 ( 0.08%) while left < right { 132,420 ( 0.14%) 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. 13,900 ( 0.02%) 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. 35,061 ( 0.04%) if cmp == Less { 75,293 ( 0.08%) left = mid + 1; 17,879 ( 0.02%) } else if cmp == Greater { . right = mid; . } else { . // SAFETY: same as the `get_unchecked` above . unsafe { crate::intrinsics::assume(mid < self.len()) }; . return Ok(mid); . } . 102,255 ( 0.11%) 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, . ); . } . 448 ( 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 ---------------------------------------- -- line 3382 ---------------------------------------- . } . let gcd: usize = gcd(mem::size_of::(), mem::size_of::()); . let ts: usize = mem::size_of::() / gcd; . let us: usize = mem::size_of::() / gcd; . . // Armed with this knowledge, we can find how many `U`s we can fit! . let us_len = self.len() / ts * us; . // And how many `T`s will be in the trailing slice! 240 ( 0.00%) let ts_len = self.len() % ts; . (us_len, ts_len) . } . . /// Transmute the slice to a slice of another type, ensuring alignment of the types is . /// maintained. . /// . /// This method splits the slice into three distinct slices: prefix, correctly aligned middle . /// slice of a new type, and the suffix slice. The method may make the middle slice the greatest -- line 3398 ---------------------------------------- -- line 3429 ---------------------------------------- . return (self, &[], &[]); . } . . // First, find at what point do we split between the first and 2nd slice. Easy with . // ptr.align_offset. . let ptr = self.as_ptr(); . // SAFETY: See the `align_to_mut` method for the detailed safety comment. . let offset = unsafe { crate::ptr::align_offset(ptr, mem::align_of::()) }; 240 ( 0.00%) if offset > self.len() { . (self, &[], &[]) . } else { . let (left, rest) = self.split_at(offset); . let (us_len, ts_len) = rest.align_to_offsets::(); . // SAFETY: now `rest` is definitely aligned, so `from_raw_parts` below is okay, . // since the caller guarantees that we can transmute `T` to `U` safely. . unsafe { . ( . left, . from_raw_parts(rest.as_ptr() as *const U, us_len), 240 ( 0.00%) from_raw_parts(rest.as_ptr().add(rest.len() - ts_len), ts_len), . ) . } . } . } . . /// Transmute the slice to a slice of another type, ensuring alignment of the types is . /// maintained. . /// -- line 3456 ---------------------------------------- 56,862 ( 0.06%) -------------------------------------------------------------------------------- -- 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 {} . } . 402 ( 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 { 154 ( 0.00%) Spanned { node: t, span: sp } 141 ( 0.00%) } . . pub fn dummy_spanned(t: T) -> Spanned { . respan(DUMMY_SP, t) . } . . // _____________________________________________________________________________ . // SourceFile, MultiByteChar, FileName, FileLines . // -- line 96 ---------------------------------------- -- 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,570 ( 0.00%) fn new_from_name(name: &FileName, cnum: CrateNum) -> StableSourceFileId { . let mut hasher = StableHasher::new(); 314 ( 0.00%) name.hash(&mut hasher); . StableSourceFileId { file_name_hash: hasher.finish(), cnum } 1,884 ( 0.00%) } . } . . // _____________________________________________________________________________ . // SourceMap . // . . #[derive(Default)] . pub(super) struct SourceMapFiles { -- line 164 ---------------------------------------- -- line 184 ---------------------------------------- . pub fn new(path_mapping: FilePathMapping) -> SourceMap { . Self::with_file_loader_and_hash_kind( . Box::new(RealFileLoader), . path_mapping, . SourceFileHashAlgorithm::Md5, . ) . } . 1 ( 0.00%) pub fn with_file_loader_and_hash_kind( . file_loader: Box, . path_mapping: FilePathMapping, . hash_kind: SourceFileHashAlgorithm, . ) -> SourceMap { 5 ( 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%) } . 4 ( 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() 5 ( 0.00%) } . . fn allocate_address_space(&self, size: usize) -> Result { 314 ( 0.00%) let size = u32::try_from(size).map_err(|_| OffsetOverflowError)?; . . loop { 314 ( 0.00%) let current = self.used_address_space.load(Ordering::Relaxed); 942 ( 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. 8 ( 0.00%) pub fn new_source_file(&self, filename: FileName, src: String) -> Lrc { 12 ( 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() . }) 9 ( 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. 13 ( 0.00%) let (filename, _) = self.path_mapping.map_filename_prefix(&filename); . 2 ( 0.00%) let file_id = StableSourceFileId::new_from_name(&filename, LOCAL_CRATE); . 6 ( 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())?; . 6 ( 0.00%) let source_file = Lrc::new(SourceFile::new( 9 ( 0.00%) filename, 3 ( 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.26%) *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) . } . 341 ( 0.00%) pub fn is_multiline(&self, sp: Span) -> bool { 124 ( 0.00%) let lo = self.lookup_source_file_idx(sp.lo()); 124 ( 0.00%) let hi = self.lookup_source_file_idx(sp.hi()); 62 ( 0.00%) if lo != hi { . return true; . } 62 ( 0.00%) let f = (*self.files.borrow().source_files)[lo].clone(); . f.lookup_line(sp.lo()) != f.lookup_line(sp.hi()) 279 ( 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 533 ---------------------------------------- . . /// Extracts the source surrounding the given `Span` using the `extract_source` function. The . /// extract function takes three arguments: a string slice containing the source, an index in . /// the slice for the beginning of the span and an index in the slice for the end of the span. . fn span_to_source(&self, sp: Span, extract_source: F) -> Result . where . F: Fn(&str, usize, usize) -> Result, . { 35 ( 0.00%) let local_begin = self.lookup_byte_offset(sp.lo()); 35 ( 0.00%) let local_end = self.lookup_byte_offset(sp.hi()); . 10 ( 0.00%) if local_begin.sf.start_pos != local_end.sf.start_pos { . Err(SpanSnippetError::DistinctSources(DistinctSources { . begin: (local_begin.sf.name.clone(), local_begin.sf.start_pos), . end: (local_end.sf.name.clone(), local_end.sf.start_pos), . })) . } else { . self.ensure_source_file_source_present(local_begin.sf.clone()); . . let start_index = local_begin.pos.to_usize(); . let end_index = local_end.pos.to_usize(); 5 ( 0.00%) let source_len = (local_begin.sf.end_pos - local_begin.sf.start_pos).to_usize(); . 20 ( 0.00%) if start_index > end_index || end_index > source_len { . return Err(SpanSnippetError::MalformedForSourcemap(MalformedSourceMapPositions { . name: local_begin.sf.name.clone(), . source_len, . begin_pos: local_begin.pos, . end_pos: local_end.pos, . })); . } . 15 ( 0.00%) if let Some(ref src) = local_begin.sf.src { . extract_source(src, start_index, end_index) . } else if let Some(src) = local_begin.sf.external_src.borrow().get_source() { . extract_source(src, start_index, end_index) . } else { . Err(SpanSnippetError::SourceNotAvailable { filename: local_begin.sf.name.clone() }) . } . } . } -- line 573 ---------------------------------------- -- line 579 ---------------------------------------- . pub fn is_local_span(&self, sp: Span) -> bool { . let local_begin = self.lookup_byte_offset(sp.lo()); . let local_end = self.lookup_byte_offset(sp.hi()); . // This might be a weird span that covers multiple files . local_begin.sf.src.is_some() && local_end.sf.src.is_some() . } . . /// Returns the source snippet as `String` corresponding to the given `Span`. 60 ( 0.00%) pub fn span_to_snippet(&self, sp: Span) -> Result { . self.span_to_source(sp, |src, start_index, end_index| { . src.get(start_index..end_index) . .map(|s| s.to_string()) . .ok_or(SpanSnippetError::IllFormedSpan(sp)) . }) 45 ( 0.00%) } . . pub fn span_to_margin(&self, sp: Span) -> Option { . Some(self.indentation_before(sp)?.len()) . } . . pub fn indentation_before(&self, sp: Span) -> Option { . self.span_to_source(sp, |src, start_index, _| { . let before = &src[..start_index]; -- line 601 ---------------------------------------- -- line 679 ---------------------------------------- . } . } . . sp . } . . /// Given a `Span`, tries to get a shorter span ending before the first occurrence of `char` . /// `c`. 55 ( 0.00%) pub fn span_until_char(&self, sp: Span, c: char) -> Span { 20 ( 0.00%) match self.span_to_snippet(sp) { 20 ( 0.00%) Ok(snippet) => { . let snippet = snippet.split(c).next().unwrap_or("").trim_end(); 10 ( 0.00%) if !snippet.is_empty() && !snippet.contains('\n') { 25 ( 0.00%) sp.with_hi(BytePos(sp.lo().0 + snippet.len() as u32)) . } else { . sp . } . } . _ => sp, . } 45 ( 0.00%) } . . /// Given a `Span`, tries to get a shorter span ending just after the first occurrence of `char` . /// `c`. . pub fn span_through_char(&self, sp: Span, c: char) -> Span { . if let Ok(snippet) = self.span_to_snippet(sp) { . if let Some(offset) = snippet.find(c) { . return sp.with_hi(BytePos(sp.lo().0 + (offset + c.len_utf8()) as u32)); . } -- line 707 ---------------------------------------- -- line 750 ---------------------------------------- . /// Given a `Span`, return a span ending in the closest `{`. This is useful when you have a . /// `Span` enclosing a whole item but we need to point at only the head (usually the first . /// line) of that item. . /// . /// *Only suitable for diagnostics.* . pub fn guess_head_span(&self, sp: Span) -> Span { . // FIXME: extend the AST items to have a head span, or replace callers with pointing at . // the item's ident when appropriate. 10 ( 0.00%) self.span_until_char(sp, '{') . } . . /// Returns a new span representing just the first character of the given span. . pub fn start_point(&self, sp: Span) -> Span { . let width = { . let sp = sp.data(); . let local_begin = self.lookup_byte_offset(sp.lo); . let start_index = local_begin.pos.to_usize(); -- line 766 ---------------------------------------- -- line 782 ---------------------------------------- . }, . } . }; . . sp.with_hi(BytePos(sp.lo().0 + width as u32)) . } . . /// Returns a new span representing just the last character of this span. 192 ( 0.00%) pub fn end_point(&self, sp: Span) -> Span { . let pos = sp.hi().0; . 64 ( 0.00%) let width = self.find_width_of_character_at_span(sp, false); . let corrected_end_position = pos.checked_sub(width).unwrap_or(pos); . . let end_point = BytePos(cmp::max(corrected_end_position, sp.lo().0)); 160 ( 0.00%) sp.with_lo(end_point) . } . . /// Returns a new span representing the next character after the end-point of this span. 22 ( 0.00%) pub fn next_point(&self, sp: Span) -> Span { 2 ( 0.00%) if sp.is_dummy() { . return sp; . } . let start_of_next_point = sp.hi().0; . 8 ( 0.00%) let width = self.find_width_of_character_at_span(sp.shrink_to_hi(), true); . // If the width is 1, then the next span should point to the same `lo` and `hi`. However, . // in the case of a multibyte character, where the width != 1, the next span should . // span multiple bytes to include the whole character. . let end_of_next_point = 4 ( 0.00%) start_of_next_point.checked_add(width - 1).unwrap_or(start_of_next_point); . 4 ( 0.00%) let end_of_next_point = BytePos(cmp::max(sp.lo().0 + 1, end_of_next_point)); . Span::new(BytePos(start_of_next_point), end_of_next_point, sp.ctxt(), None) 18 ( 0.00%) } . . /// Finds the width of the character, either before or after the end of provided span, . /// depending on the `forwards` parameter. 216 ( 0.00%) fn find_width_of_character_at_span(&self, sp: Span, forwards: bool) -> u32 { . let sp = sp.data(); 18 ( 0.00%) if sp.lo == sp.hi { . debug!("find_width_of_character_at_span: early return empty span"); . return 1; . } . 112 ( 0.00%) let local_begin = self.lookup_byte_offset(sp.lo); 144 ( 0.00%) let local_end = self.lookup_byte_offset(sp.hi); . debug!( . "find_width_of_character_at_span: local_begin=`{:?}`, local_end=`{:?}`", . local_begin, local_end . ); . 32 ( 0.00%) if local_begin.sf.start_pos != local_end.sf.start_pos { . debug!("find_width_of_character_at_span: begin and end are in different files"); . return 1; . } . . let start_index = local_begin.pos.to_usize(); . let end_index = local_end.pos.to_usize(); . debug!( . "find_width_of_character_at_span: start_index=`{:?}`, end_index=`{:?}`", . start_index, end_index . ); . . // Disregard indexes that are at the start or end of their spans, they can't fit bigger . // characters. 64 ( 0.00%) if (!forwards && end_index == usize::MIN) || (forwards && start_index == usize::MAX) { . debug!("find_width_of_character_at_span: start or end of span, cannot be multibyte"); . return 1; . } . 16 ( 0.00%) let source_len = (local_begin.sf.end_pos - local_begin.sf.start_pos).to_usize(); . debug!("find_width_of_character_at_span: source_len=`{:?}`", source_len); . // Ensure indexes are also not malformed. 64 ( 0.00%) if start_index > end_index || end_index > source_len { . debug!("find_width_of_character_at_span: source indexes are malformed"); . return 1; . } . . let src = local_begin.sf.external_src.borrow(); . . // We need to extend the snippet to the end of the src rather than to end_index so when . // searching forwards for boundaries we've got somewhere to search. 48 ( 0.00%) let snippet = if let Some(ref src) = local_begin.sf.src { . &src[start_index..] . } else if let Some(src) = src.get_source() { . &src[start_index..] . } else { . return 1; . }; . debug!("find_width_of_character_at_span: snippet=`{:?}`", snippet); . 96 ( 0.00%) let mut target = if forwards { end_index + 1 } else { end_index - 1 }; . debug!("find_width_of_character_at_span: initial target=`{:?}`", target); . 64 ( 0.00%) while !snippet.is_char_boundary(target - start_index) && target < source_len { . target = if forwards { . target + 1 . } else { . match target.checked_sub(1) { . Some(target) => target, . None => { . break; . } . } . }; . debug!("find_width_of_character_at_span: target=`{:?}`", target); . } . debug!("find_width_of_character_at_span: final target=`{:?}`", target); . 64 ( 0.00%) if forwards { (target - end_index) as u32 } else { (end_index - target) as u32 } 162 ( 0.00%) } . . pub fn get_source_file(&self, filename: &FileName) -> Option> { . // Remap filename before lookup . let filename = self.path_mapping().map_filename_prefix(filename).0; . for sf in self.files.borrow().source_files.iter() { . if filename == sf.name { . return Some(sf.clone()); . } . } . None . } . . /// For a global `BytePos`, computes the local offset within the containing `SourceFile`. 210 ( 0.00%) pub fn lookup_byte_offset(&self, bpos: BytePos) -> SourceFileAndBytePos { 42 ( 0.00%) let idx = self.lookup_source_file_idx(bpos); 84 ( 0.00%) let sf = (*self.files.borrow().source_files)[idx].clone(); . let offset = bpos - sf.start_pos; . SourceFileAndBytePos { sf, pos: offset } 210 ( 0.00%) } . . // 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` 315 ( 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) 208 ( 0.00%) .unwrap_or_else(|p| p - 1) 420 ( 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 1010 ---------------------------------------- . . return Some((sugg_span, new_snippet)); . } . } . . None . } . pub fn ensure_source_file_source_present(&self, source_file: Lrc) -> bool { 35 ( 0.00%) source_file.add_external_src(|| { . match source_file.name { . FileName::Real(ref name) if let Some(local_path) = name.local_path() => { . self.file_loader.read_file(local_path).ok() . } . _ => None, . } . }) . } -- line 1026 ---------------------------------------- -- 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 { . pub fn empty() -> FilePathMapping { . FilePathMapping::new(Vec::new()) . } . 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 . }; . 12 ( 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%) } . 8 ( 0.00%) fn map_filename_prefix(&self, file: &FileName) -> (FileName, bool) { 2 ( 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"), . other => (other.clone(), false), . } . } . } 2,359 ( 0.00%) -------------------------------------------------------------------------------- -- 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 }; 112 ( 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. 396 ( 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) { 238 ( 0.00%) self._push(path.as_ref()) . } . 480 ( 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 59 ( 0.00%) } else if need_sep { . self.inner.push(MAIN_SEP_STR); . } . . self.inner.push(path); 360 ( 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 { 10 ( 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, 111 ( 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.01%) 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,385 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs -------------------------------------------------------------------------------- Ir -- line 80 ---------------------------------------- . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_math", since = "1.32.0")] . #[doc(alias = "popcount")] . #[doc(alias = "popcnt")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn count_ones(self) -> u32 { 1,545 ( 0.00%) intrinsics::ctpop(self as $ActualT) as u32 . } . . /// Returns the number of zeros in the binary representation of `self`. . /// . /// # Examples . /// . /// Basic usage: . /// -- line 96 ---------------------------------------- -- line 118 ---------------------------------------- . /// assert_eq!(n.leading_zeros(), 2); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn leading_zeros(self) -> u32 { 8,111 ( 0.01%) intrinsics::ctlz(self as $ActualT) as u32 . } . . /// Returns the number of trailing zeros in the binary representation . /// of `self`. . /// . /// # Examples . /// . /// Basic usage: -- line 134 ---------------------------------------- -- line 139 ---------------------------------------- . /// assert_eq!(n.trailing_zeros(), 3); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn trailing_zeros(self) -> u32 { 12,506 ( 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 { 1,071,500 ( 1.17%) 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`. 32,261 ( 0.04%) 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`. 452 ( 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 16 ( 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 { 1,218 ( 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 { 36 ( 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 { 842,391 ( 0.92%) 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 { 48,786 ( 0.05%) intrinsics::wrapping_sub(self, rhs) . } . . /// Wrapping (modular) multiplication. Computes `self * . /// rhs`, wrapping around at the boundary of the type. . /// . /// # Examples . /// . /// Basic usage: -- line 1233 ---------------------------------------- -- line 1240 ---------------------------------------- . /// assert_eq!(25u8.wrapping_mul(12), 44); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn wrapping_mul(self, rhs: Self) -> Self { 114,278 ( 0.12%) 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) { 22,348 ( 0.02%) let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT); . (a as Self, b) . } . . /// Calculates `self + rhs + carry` without the ability to overflow. . /// . /// Performs "ternary addition" which takes in an extra bit to add, and may return an . /// additional bit of overflow. This allows for chaining together multiple additions . /// to create "big integers" which represent larger values. -- line 1508 ---------------------------------------- -- line 1588 ---------------------------------------- . #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));")] . /// ``` . #[stable(feature = "wrapping", since = "1.7.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) { 4,086 ( 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) { 36,719 ( 0.04%) 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 { 36 ( 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 { 1,146 ( 0.00%) if self <= 1 { return 0; } . 998 ( 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. 2,994 ( 0.00%) let z = unsafe { intrinsics::ctlz_nonzero(p) }; 998 ( 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 { 850 ( 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 ---------------------------------------- 2,031 ( 0.00%) -------------------------------------------------------------------------------- -- 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 { 49,239 ( 0.05%) 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 { 16,390 ( 0.02%) 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 { 850 ( 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 { 47,084 ( 0.05%) 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) { 2,099 ( 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) { 362 ( 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. 936 ( 0.00%) if self.capacity() > self.len { 140 ( 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(); 253 ( 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")] 78,617 ( 0.09%) 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. 47,571 ( 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); 16,523 ( 0.02%) self.len = len; 41 ( 0.00%) ptr::drop_in_place(s); . } 94,338 ( 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. 83,610 ( 0.09%) 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. 329,291 ( 0.36%) 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()); . 47,753 ( 0.05%) self.len = new_len; 38 ( 0.00%) } . . /// Removes an element from the vector and returns it. . /// . /// The removed element is replaced by the last element of the vector. . /// . /// This does not preserve ordering, but is *O*(1). . /// If you need to preserve the element order, use [`remove`] instead. . /// -- line 1276 ---------------------------------------- -- line 1329 ---------------------------------------- . /// let mut vec = vec![1, 2, 3]; . /// vec.insert(1, 4); . /// assert_eq!(vec, [1, 4, 2, 3]); . /// vec.insert(4, 5); . /// assert_eq!(vec, [1, 4, 2, 3, 5]); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] 35 ( 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); . } . 5 ( 0.00%) let len = self.len(); 14 ( 0.00%) if index > len { . assert_failed(index, len); . } . . // space for the new element 54 ( 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.) 81 ( 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); . } 54 ( 0.00%) self.set_len(len + 1); . } 30 ( 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); . } . 16 ( 0.00%) let len = self.len(); 64 ( 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. . ret = ptr::read(ptr); . . // Shift everything down to fill in that spot. 32 ( 0.00%) ptr::copy(ptr.offset(1), ptr, len - index - 1); . } 22 ( 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")] 1,428 ( 0.00%) pub fn retain(&mut self, mut f: F) . where . F: FnMut(&T) -> bool, . { 16 ( 0.00%) self.retain_mut(|elem| f(elem)); 1,416 ( 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, . { 178 ( 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) { 172 ( 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), 94 ( 0.00%) self.v.as_mut_ptr().add(self.processed_len - self.deleted_cnt), . self.original_len - self.processed_len, . ); . } . } . // SAFETY: After filling holes, all items are in contiguous memory. . unsafe { 2 ( 0.00%) self.v.set_len(self.original_len - self.deleted_cnt); . } . } . } . . let mut g = BackshiftOnDrop { v: self, processed_len: 0, deleted_cnt: 0, original_len }; . . fn process_loop( . original_len: usize, . f: &mut F, . g: &mut BackshiftOnDrop<'_, T, A>, . ) where . F: FnMut(&mut T) -> bool, . { 1,785 ( 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) }; 323 ( 0.00%) if !f(cur) { . // Advance early to avoid double drop if `drop_in_place` panicked. 4 ( 0.00%) g.processed_len += 1; . g.deleted_cnt += 1; . // SAFETY: We never touch this element again after dropped. . unsafe { ptr::drop_in_place(cur) }; . // We already advanced the counter. . if DELETED { . continue; . } else { . break; -- line 1546 ---------------------------------------- -- 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, . { 6 ( 0.00%) let len = self.len(); 68 ( 0.00%) if len <= 1 { . return; . } . . /* INVARIANT: vec.len() > read >= write > write-1 >= 0 */ . struct FillGapOnDrop<'a, T, A: core::alloc::Allocator> { . /* Offset of the element we want to check if it is duplicate */ . read: usize, . -- line 1627 ---------------------------------------- -- line 1670 ---------------------------------------- . let ptr = gap.vec.as_mut_ptr(); . . /* Drop items while going through Vec, it should be more efficient than . * doing slice partition_dedup + truncate */ . . /* SAFETY: Because of the invariant, read_ptr, prev_ptr and write_ptr . * are always in-bounds and read_ptr never aliases prev_ptr */ . unsafe { 66 ( 0.00%) while gap.read < len { . let read_ptr = ptr.add(gap.read); . let prev_ptr = ptr.add(gap.write.wrapping_sub(1)); . 30 ( 0.00%) if same_bucket(&mut *read_ptr, &mut *prev_ptr) { . // Increase `gap.read` now since the drop may panic. . gap.read += 1; . /* We have found duplicate, drop it in-place */ . ptr::drop_in_place(read_ptr); . } else { . let write_ptr = ptr.add(gap.write); . . /* Because `read_ptr` can be equal to `write_ptr`, we either . * have to use `copy` or conditional `copy_nonoverlapping`. . * Looks like the first option is faster. */ . ptr::copy(read_ptr, write_ptr, 1); . . /* We have filled that place, so go further */ 30 ( 0.00%) gap.write += 1; . gap.read += 1; . } . } . . /* Technically we could let `gap` clean up with its Drop, but . * when `same_bucket` is guaranteed to not panic, this bloats a little . * the codegen, so we just do it manually */ . gap.vec.set_len(gap.write); . mem::forget(gap); . } 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. 844,616 ( 0.92%) if self.len == self.buf.capacity() { 15,770 ( 0.02%) self.buf.reserve_for_push(self.len); . } . unsafe { 6,661 ( 0.01%) let end = self.as_mut_ptr().add(self.len); . ptr::write(end, value); 888,676 ( 0.97%) 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 { 17,063 ( 0.02%) if self.len == 0 { 3 ( 0.00%) None . } else { . unsafe { 11,506 ( 0.01%) self.len -= 1; 742 ( 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")] 42 ( 0.00%) pub fn append(&mut self, other: &mut Self) { . unsafe { . self.append_elements(other.as_slice() as _); . other.set_len(0); . } 36 ( 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); 500 ( 0.00%) let len = self.len(); . unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) }; 8,907 ( 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. . // 92 ( 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). 21 ( 0.00%) let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start), end - start); 633 ( 0.00%) Drain { . tail_start: end, 20 ( 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) { 131,696 ( 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,300 ( 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 1935 ---------------------------------------- . A: Clone, . { . #[cold] . #[inline(never)] . fn assert_failed(at: usize, len: usize) -> ! { . panic!("`at` split index (is {}) should be <= len (is {})", at, len); . } . 32 ( 0.00%) if at > self.len() { . assert_failed(at, self.len()); . } . 22 ( 0.00%) if at == 0 { . // the new vector can take over the original buffer and avoid the copy . return mem::replace( . self, . Vec::with_capacity_in(self.capacity(), self.allocator().clone()), . ); . } . . let other_len = self.len - at; -- line 1955 ---------------------------------------- -- line 1988 ---------------------------------------- . /// . /// let mut vec = vec![]; . /// let mut p = 1; . /// vec.resize_with(4, || { p *= 2; p }); . /// assert_eq!(vec, [2, 4, 8, 16]); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "vec_resize_with", since = "1.33.0")] 120 ( 0.00%) pub fn resize_with(&mut self, new_len: usize, f: F) . where . F: FnMut() -> T, . { 16 ( 0.00%) let len = self.len(); 32 ( 0.00%) if new_len > len { 302 ( 0.00%) self.extend_with(new_len - len, ExtendFunc(f)); . } else { . self.truncate(new_len); . } 104 ( 0.00%) } . . /// Consumes and leaks the `Vec`, returning a mutable reference to the contents, . /// `&'a mut [T]`. Note that the type `T` must outlive the chosen lifetime . /// `'a`. If the type has only static references, or none at all, then this . /// may be chosen to be `'static`. . /// . /// As of Rust 1.57, this method does not reallocate or shrink the `Vec`, . /// so the leaked allocation may include unused capacity that is not part -- line 2014 ---------------------------------------- -- line 2070 ---------------------------------------- . #[stable(feature = "vec_spare_capacity", since = "1.60.0")] . #[inline] . pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit] { . // Note: . // This method is not implemented in terms of `split_at_spare_mut`, . // to prevent invalidation of pointers to the buffer. . unsafe { . slice::from_raw_parts_mut( 2 ( 0.00%) self.as_mut_ptr().add(self.len) as *mut MaybeUninit, 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 2189 ---------------------------------------- . /// assert_eq!(vec, ["hello", "world", "world"]); . /// . /// let mut vec = vec![1, 2, 3, 4]; . /// vec.resize(2, 0); . /// assert_eq!(vec, [1, 2]); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "vec_resize", since = "1.5.0")] 110 ( 0.00%) pub fn resize(&mut self, new_len: usize, value: T) { 11 ( 0.00%) let len = self.len(); . 33 ( 0.00%) if new_len > len { 138 ( 0.00%) self.extend_with(new_len - len, ExtendElement(value)) . } else { . self.truncate(new_len); . } 19 ( 0.00%) } . . /// Clones and appends all elements in a slice to the `Vec`. . /// . /// Iterates over the slice `other`, clones each element, and then appends . /// it to this `Vec`. The `other` slice is traversed in-order. . /// . /// Note that this function is same as [`extend`] except that it is . /// specialized to work with slices instead. If and when Rust gets -- line 2213 ---------------------------------------- -- line 2291 ---------------------------------------- . fn last(mut self) -> T { . (self.0)() . } . } . . impl Vec { . #[cfg(not(no_global_oom_handling))] . /// Extend the vector by `n` values, using the given generator. 1,984 ( 0.00%) fn extend_with>(&mut self, n: usize, mut value: E) { . self.reserve(n); . . unsafe { 150 ( 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); . } . 3,547 ( 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 . } 1,511 ( 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")] 302 ( 0.00%) pub fn from_elem(elem: T, n: usize) -> Vec { 2,197 ( 0.00%) ::from_elem(elem, n, Global) 322 ( 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] { 57,130 ( 0.06%) 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] { 14,624 ( 0.02%) 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))] 4,189 ( 0.00%) fn clone(&self) -> Self { . let alloc = self.allocator().clone(); 2 ( 0.00%) <[T]>::to_vec_in(&**self, alloc) 4,980 ( 0.01%) } . . // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is . // required for this method definition, is not available. Instead use the . // `slice::to_vec` function which is only available with cfg(test) . // NB see the slice::hack module in slice.rs for more information . #[cfg(test)] . fn clone(&self) -> Self { . let alloc = self.allocator().clone(); -- line 2487 ---------------------------------------- -- line 2518 ---------------------------------------- . message = "vector indices are of type `usize` or ranges of `usize`", . label = "vector indices are of type `usize` or ranges of `usize`" . )] . impl, A: Allocator> Index for Vec { . type Output = I::Output; . . #[inline] . fn index(&self, index: I) -> &Self::Output { 486 ( 0.00%) Index::index(&**self, index) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_on_unimplemented( . message = "vector indices are of type `usize` or ranges of `usize`", . label = "vector indices are of type `usize` or ranges of `usize`" . )] -- line 2534 ---------------------------------------- -- 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 { 13,017 ( 0.01%) >::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,301 ( 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,440 ( 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] 8 ( 0.00%) fn extend>(&mut self, iter: I) { 4,540 ( 0.00%) >::spec_extend(self, iter.into_iter()) 8 ( 0.00%) } . . #[inline] . fn extend_one(&mut self, item: T) { . self.push(item); . } . . #[inline] . fn extend_reserve(&mut self, additional: usize) { -- line 2627 ---------------------------------------- -- line 2636 ---------------------------------------- . fn extend_desugared>(&mut self, mut iterator: I) { . // This is the case for a general iterator. . // . // This function should be the moral equivalent of: . // . // for item in iterator { . // self.push(item); . // } 676 ( 0.00%) while let Some(element) = iterator.next() { 86 ( 0.00%) let len = self.len(); 1,678 ( 0.00%) if len == self.capacity() { 30 ( 0.00%) let (lower, _) = iterator.size_hint(); . self.reserve(lower.saturating_add(1)); . } . unsafe { . ptr::write(self.as_mut_ptr().add(len), element); . // Since next() executes user code which can panic we have to bump the length . // after each step. . // NB can't overflow since we would have had to alloc the address space 1,491 ( 0.00%) self.set_len(len + 1); . } . } 3 ( 0.00%) } . . /// Creates a splicing iterator that replaces the specified range in the vector . /// with the given `replace_with` iterator and yields the removed items. . /// `replace_with` does not need to be the same length as `range`. . /// . /// `range` is removed even if the iterator is not consumed until the end. . /// . /// It is unspecified how many elements are removed from the vector -- line 2666 ---------------------------------------- -- line 2693 ---------------------------------------- . #[cfg(not(no_global_oom_handling))] . #[inline] . #[stable(feature = "vec_splice", since = "1.21.0")] . pub fn splice(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter, A> . where . R: RangeBounds, . I: IntoIterator, . { 11 ( 0.00%) Splice { drain: self.drain(range), replace_with: replace_with.into_iter() } . } . . /// Creates an iterator which uses a closure to determine if an element should be removed. . /// . /// If the closure returns true, then the element is removed and yielded. . /// If the closure returns false, the element will remain in the vector and will not be yielded . /// by the iterator. . /// -- line 2709 ---------------------------------------- -- line 2745 ---------------------------------------- . /// assert_eq!(evens, vec![2, 4, 6, 8, 14]); . /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]); . /// ``` . #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")] . pub fn drain_filter(&mut self, filter: F) -> DrainFilter<'_, T, F, A> . where . F: FnMut(&mut T) -> bool, . { 38 ( 0.00%) let old_len = self.len(); . . // Guard against us getting leaked (leak amplification) . unsafe { . self.set_len(0); . } . 16 ( 0.00%) DrainFilter { vec: self, idx: 0, del: 0, old_len, pred: filter, panic_flag: false } . } . } . . /// Extend implementation that copies elements out of references before pushing them onto the Vec. . /// . /// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to . /// append the entire slice at once. . /// -- line 2768 ---------------------------------------- -- line 2803 ---------------------------------------- . #[inline] . fn cmp(&self, other: &Self) -> Ordering { . Ord::cmp(&**self, &**other) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . unsafe impl<#[may_dangle] T, A: Allocator> Drop for Vec { 22,452 ( 0.02%) fn drop(&mut self) { . unsafe { . // use drop for [T] . // use a raw slice to refer to the elements of the vector as weakest necessary type; . // could avoid questions of validity in certain cases 9,420 ( 0.01%) ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len)) . } . // RawVec handles deallocation 26,708 ( 0.03%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")] . impl const Default for Vec { . /// Creates an empty `Vec`. . fn default() -> Vec { . Vec::new() -- line 2827 ---------------------------------------- -- line 2976 ---------------------------------------- . /// newly-allocated buffer with exactly the right capacity. . /// . /// # Examples . /// . /// ``` . /// assert_eq!(Box::from(vec![1, 2, 3]), vec![1, 2, 3].into_boxed_slice()); . /// ``` . fn from(v: Vec) -> Self { 4 ( 0.00%) v.into_boxed_slice() . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl From<&str> for Vec { . /// Allocate a `Vec` and fill it with a UTF-8 string. . /// -- line 2992 ---------------------------------------- 21,878 ( 0.02%) -------------------------------------------------------------------------------- -- 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) { 19 ( 0.00%) let mut tt_reader = TokenTreesReader { . string_reader: self, 1 ( 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(), . }; 1 ( 0.00%) let res = tt_reader.parse_all_token_trees(); 6 ( 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`. 8 ( 0.00%) fn parse_all_token_trees(&mut self) -> PResult<'a, TokenStream> { . let mut buf = TokenStreamBuilder::default(); . . self.bump(); 620 ( 0.00%) while self.token != token::Eof { 2,472 ( 0.00%) buf.push(self.parse_token_tree()?); . } . . Ok(buf.into_token_stream()) 9 ( 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 { 14,570 ( 0.02%) if let token::CloseDelim(..) = self.token.kind { . return buf.into_token_stream(); . } . 30,260 ( 0.03%) match self.parse_token_tree() { 54,468 ( 0.06%) Ok(tree) => buf.push(tree), . Err(mut e) => { . e.emit(); . return buf.into_token_stream(); . } . } . } . } . 57,249 ( 0.06%) fn parse_token_tree(&mut self) -> PResult<'a, TreeAndSpacing> { 12,722 ( 0.01%) let sm = self.string_reader.sess.source_map(); . 52,317 ( 0.06%) 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,233 ( 0.00%) token::OpenDelim(delim) => { . // The span for beginning of the delimited section 1,233 ( 0.00%) let pre_span = self.token.span; . . // Parse the open delimiter. 8,631 ( 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,233 ( 0.00%) let tts = self.parse_token_trees_until_close_delim(); . . // Expand to cover the entire delimited token tree 6,165 ( 0.01%) let delim_span = DelimSpan::from_pair(pre_span, self.token.span); . 2,466 ( 0.00%) match self.token.kind { . // Correct delimiter. 2,466 ( 0.00%) token::CloseDelim(d) if d == delim => { . let (open_brace, open_brace_span) = self.open_braces.pop().unwrap(); 2,466 ( 0.00%) let close_brace_span = self.token.span; . 3,699 ( 0.00%) if tts.is_empty() { 93 ( 0.00%) let empty_block_span = open_brace_span.to(close_brace_span); 124 ( 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,932 ( 0.01%) if let (DelimToken::Brace, DelimToken::Brace) = (open_brace, delim) { . self.matching_block_spans.push((open_brace_span, close_brace_span)); . } . 1,233 ( 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. . } . _ => {} . } . 8,631 ( 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) . } . _ => { 25,640 ( 0.03%) let tt = TokenTree::Token(self.token.take()); . let mut spacing = self.bump(); 10,256 ( 0.01%) if !self.token.is_op() { . spacing = Alone; . } 30,768 ( 0.03%) Ok((tt, spacing)) . } . } 50,888 ( 0.06%) } . . fn bump(&mut self) -> Spacing { 62,187 ( 0.07%) let (spacing, token) = self.string_reader.next_token(); 31,814 ( 0.03%) self.token = token; . spacing . } . } . 1,233 ( 0.00%) #[derive(Default)] . struct TokenStreamBuilder { . buf: Vec, . } . . impl TokenStreamBuilder { 82,693 ( 0.09%) fn push(&mut self, (tree, joint): TreeAndSpacing) { 34,181 ( 0.04%) if let Some((TokenTree::Token(prev_token), Joint)) = self.buf.last() { 2,042 ( 0.00%) if let TokenTree::Token(token) = &tree { 3,831 ( 0.00%) if let Some(glued) = prev_token.glue(token) { . self.buf.pop(); 2,304 ( 0.00%) self.buf.push((TokenTree::Token(glued), joint)); . return; . } . } . } 30,845 ( 0.03%) self.buf.push((tree, joint)) 50,888 ( 0.06%) } . . fn into_token_stream(self) -> TokenStream { 12,339 ( 0.01%) TokenStream::new(self.buf) . } . } 27,134 ( 0.03%) -------------------------------------------------------------------------------- -- 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 { 591 ( 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 { 148,251 ( 0.16%) write_leb128!(self, v, usize, write_usize_leb128) . } . . #[inline] . fn emit_u128(&mut self, v: u128) -> EncodeResult { 42 ( 0.00%) write_leb128!(self, v, u128, write_u128_leb128) . } . . #[inline] . fn emit_u64(&mut self, v: u64) -> EncodeResult { 105 ( 0.00%) write_leb128!(self, v, u64, write_u64_leb128) . } . . #[inline] . fn emit_u32(&mut self, v: u32) -> EncodeResult { 145,255 ( 0.16%) 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 { 1,648 ( 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 { 374 ( 0.00%) read_leb128!(self, read_u64_leb128) . } . . #[inline] 5,797 ( 0.01%) fn read_u32(&mut self) -> u32 { 23,347 ( 0.03%) read_leb128!(self, read_u32_leb128) 11,594 ( 0.01%) } . . #[inline] . fn read_u16(&mut self) -> u16 { 561,386 ( 0.61%) let bytes = [self.data[self.position], self.data[self.position + 1]]; 80,198 ( 0.09%) let value = u16::from_le_bytes(bytes); 160,396 ( 0.18%) self.position += 2; . value . } . . #[inline] . fn read_u8(&mut self) -> u8 { 1,005,151 ( 1.10%) let value = self.data[self.position]; 186,686 ( 0.20%) self.position += 1; . value . } . . #[inline] 25,503 ( 0.03%) fn read_usize(&mut self) -> usize { 25,521 ( 0.03%) read_leb128!(self, read_usize_leb128) 51,006 ( 0.06%) } . . #[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(); 1,179 ( 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> { 5,646 ( 0.01%) let len = self.read_usize(); 30,514 ( 0.03%) let sentinel = self.data[self.position + len]; 7,642 ( 0.01%) assert!(sentinel == STR_SENTINEL); . let s = unsafe { . std::str::from_utf8_unchecked(&self.data[self.position..self.position + len]) . }; 19,105 ( 0.02%) self.position += len + 1; 5,529 ( 0.01%) Cow::Borrowed(s) . } . . #[inline] . fn read_raw_bytes_into(&mut self, s: &mut [u8]) { 25 ( 0.00%) let start = self.position; 130 ( 0.00%) self.position += s.len(); 25 ( 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 ---------------------------------------- 196,229 ( 0.21%) -------------------------------------------------------------------------------- -- 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 . // . 81,042 ( 0.09%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 60,780 ( 0.07%) libc::malloc(layout.size()) as *mut u8 . } else { . #[cfg(target_os = "macos")] . { . if layout.align() > (1 << 31) { . return ptr::null_mut(); . } . } . aligned_malloc(&layout) . } . } . . #[inline] . unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { . // See the comment above in `alloc` for why this check looks the way it does. 1,348 ( 0.00%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 2,022 ( 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) { 20,587 ( 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 { 7,168 ( 0.01%) if layout.align() <= MIN_ALIGN && layout.align() <= new_size { 14,336 ( 0.02%) libc::realloc(ptr as *mut libc::c_void, new_size) as *mut u8 . } else { . realloc_fallback(self, ptr, layout, new_size) . } . } . } . . cfg_if::cfg_if! { . if #[cfg(any( -- line 56 ---------------------------------------- -- 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/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%) } . 2,282 ( 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 } 23,682 ( 0.03%) } . . /// 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. 6,903 ( 0.01%) pub fn normalize_to_macros_2_0(self) -> Ident { . Ident::new(self.name, self.span.normalize_to_macros_2_0()) 5,369 ( 0.01%) } . . /// "Normalize" ident for use in comparisons using "local variable hygiene". . /// Identifiers with same string value become same if they came from the same non-transparent . /// macro (e.g., `macro` or `macro_rules!` items) and stay different if they came from different . /// non-transparent macros. . /// Technically, this operation strips all transparent marks from ident's syntactic context. 6,165 ( 0.01%) pub fn normalize_to_macro_rules(self) -> Ident { . Ident::new(self.name, self.span.normalize_to_macro_rules()) 4,795 ( 0.01%) } . . /// 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 { 13 ( 0.00%) self.name.as_str() . } . } . . impl PartialEq for Ident { 2,082 ( 0.00%) fn eq(&self, rhs: &Self) -> bool { 5,030 ( 0.01%) self.name == rhs.name && self.span.ctxt() == rhs.span.ctxt() 2,776 ( 0.00%) } . } . . impl Hash for Ident { . fn hash(&self, state: &mut H) { 504 ( 0.00%) self.name.hash(state); 3,502 ( 0.00%) self.span.ctxt().hash(state); . } . } . . impl fmt::Debug for Ident { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . fmt::Display::fmt(self, f)?; . fmt::Debug::fmt(&self.span.ctxt(), f) . } . } . . /// This implementation is supposed to be used in error messages, so it's expected to be identical . /// to printing the original identifier token written in source code (`token_to_string`), . /// except that AST identifiers don't keep the rawness flag, so we have to guess it. . impl fmt::Display for Ident { 32 ( 0.00%) fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 40 ( 0.00%) fmt::Display::fmt(&IdentPrinter::new(self.name, self.is_raw_guess(), None), f) 32 ( 0.00%) } . } . . /// This is the most general way to print identifiers. . /// AST pretty-printer is used as a fallback for turning AST structures into token streams for . /// proc macros. Additionally, proc macros may stringify their input and expect it survive the . /// stringification (especially true for proc macro derives written between Rust 1.15 and 1.30). . /// So we need to somehow pretty-print `$crate` in a way preserving at least some of its . /// hygiene data, most importantly name of the crate it refers to. -- line 1613 ---------------------------------------- -- line 1622 ---------------------------------------- . is_raw: bool, . /// Span used for retrieving the crate name to which `$crate` refers to, . /// if this field is `None` then the `$crate` conversion doesn't happen. . convert_dollar_crate: Option, . } . . impl IdentPrinter { . /// The most general `IdentPrinter` constructor. Do not use this. 23 ( 0.00%) pub fn new(symbol: Symbol, is_raw: bool, convert_dollar_crate: Option) -> IdentPrinter { 192 ( 0.00%) IdentPrinter { symbol, is_raw, convert_dollar_crate } 23 ( 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. 30 ( 0.00%) pub fn for_ast_ident(ident: Ident, is_raw: bool) -> IdentPrinter { 30 ( 0.00%) IdentPrinter::new(ident.name, is_raw, Some(ident.span)) 15 ( 0.00%) } . } . . impl fmt::Display for IdentPrinter { 230 ( 0.00%) fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 92 ( 0.00%) if self.is_raw { . f.write_str("r#")?; 46 ( 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)] 2,754 ( 0.00%) pub struct MacroRulesNormalizedIdent(Ident); . . impl MacroRulesNormalizedIdent { . pub fn new(ident: Ident) -> Self { 680 ( 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)] 2,040 ( 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)) 8 ( 0.00%) } . . /// Maps a string to its interned representation. 49,086 ( 0.05%) pub fn intern(string: &str) -> Self { . with_session_globals(|session_globals| session_globals.symbol_interner.intern(string)) 49,086 ( 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. 17,403 ( 0.02%) pub fn as_str(&self) -> &str { 5,801 ( 0.01%) with_session_globals(|session_globals| unsafe { . std::mem::transmute::<&str, &str>(session_globals.symbol_interner.get(*self)) . }) 23,204 ( 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 { 70 ( 0.00%) fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 624 ( 0.00%) fmt::Display::fmt(self.as_str(), f) . } . } . . impl Encodable for Symbol { . fn encode(&self, s: &mut S) -> Result<(), S::Error> { 11,028 ( 0.01%) s.emit_str(self.as_str()) . } . } . . impl Decodable for Symbol { . #[inline] 2,626 ( 0.00%) fn decode(d: &mut D) -> Symbol { 8,963 ( 0.01%) Symbol::intern(&d.read_str()) . } . } . . impl HashStable for Symbol { . #[inline] 6 ( 0.00%) fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) { 6,411 ( 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(); 8,584 ( 0.01%) if let Some(&name) = inner.names.get(string) { . return name; . } . 1,162 ( 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 { 17,403 ( 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 1863 ---------------------------------------- . . // Used from a macro in `librustc_feature/accepted.rs` . pub use super::kw::MacroRules as macro_rules; . . /// Get the symbol for an integer. . /// . /// The first few non-negative integers each have a static symbol and therefore . /// are fast. 12 ( 0.00%) pub fn integer + Copy + ToString>(n: N) -> Symbol { . if let Result::Ok(idx) = n.try_into() { 8 ( 0.00%) if idx < 10 { 16 ( 0.00%) return Symbol::new(super::SYMBOL_DIGITS_BASE + idx as u32); . } . } . Symbol::intern(&n.to_string()) . } . } . . impl Symbol { . fn is_special(self) -> bool { . self <= kw::Underscore . } . . fn is_used_keyword_always(self) -> bool { 69 ( 0.00%) self >= kw::As && self <= kw::While . } . . fn is_used_keyword_conditional(self, edition: impl FnOnce() -> Edition) -> bool { 594 ( 0.00%) (self >= kw::Async && self <= kw::Dyn) && edition() >= Edition::Edition2018 . } . . fn is_unused_keyword_always(self) -> bool { 69 ( 0.00%) self >= kw::Abstract && self <= kw::Yield . } . . fn is_unused_keyword_conditional(self, edition: impl FnOnce() -> Edition) -> bool { 23 ( 0.00%) self == kw::Try && edition() >= Edition::Edition2018 . } . . pub fn is_reserved(self, edition: impl Copy + FnOnce() -> Edition) -> bool { 895 ( 0.00%) self.is_special() . || self.is_used_keyword_always() . || self.is_unused_keyword_always() . || self.is_used_keyword_conditional(edition) . || self.is_unused_keyword_conditional(edition) . } . . /// A keyword or reserved identifier that can be used as a path segment. . pub fn is_path_segment_keyword(self) -> bool { 2,233 ( 0.00%) self == kw::Super . || self == kw::SelfLower . || self == kw::SelfUpper . || self == kw::Crate . || self == kw::PathRoot . || self == kw::DollarCrate . } . . /// Returns `true` if the symbol is `true` or `false`. . pub fn is_bool_lit(self) -> bool { 1,121 ( 0.00%) self == kw::True || self == kw::False 1,121 ( 0.00%) } . . /// Returns `true` if this symbol can be a raw identifier. . pub fn can_be_raw(self) -> bool { 46 ( 0.00%) 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() 23 ( 0.00%) } . . /// Returns `true` if the token is a keyword used in the language. 23 ( 0.00%) pub fn is_used_keyword(self) -> bool { . // Note: `span.edition()` is relatively expensive, don't call it unless necessary. 23 ( 0.00%) self.name.is_used_keyword_always() . || self.name.is_used_keyword_conditional(|| self.span.edition()) 46 ( 0.00%) } . . /// Returns `true` if the token is a keyword reserved for possible future use. 23 ( 0.00%) pub fn is_unused_keyword(self) -> bool { . // Note: `span.edition()` is relatively expensive, don't call it unless necessary. 23 ( 0.00%) self.name.is_unused_keyword_always() . || self.name.is_unused_keyword_conditional(|| self.span.edition()) 46 ( 0.00%) } . . /// Returns `true` if the token is either a special identifier or a keyword. 156 ( 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()) 312 ( 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() 319 ( 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. 15 ( 0.00%) pub fn is_raw_guess(self) -> bool { . self.name.can_be_raw() && self.is_reserved() 30 ( 0.00%) } . } 10,552 ( 0.01%) -------------------------------------------------------------------------------- -- 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 { 86,884 ( 0.09%) ((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 { 82,824 ( 0.09%) ((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 { 40,600 ( 0.04%) (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 { 51,968 ( 0.06%) (y ^ (x | !z)) . .wrapping_add(w) . .wrapping_add(m) . .wrapping_add(c) . .rotate_left(s) . .wrapping_add(x) . } . . #[inline] 7,308 ( 0.01%) pub fn compress(state: &mut [u32; 4], input: &[u8; 64]) { 1,624 ( 0.00%) let mut a = state[0]; 812 ( 0.00%) let mut b = state[1]; 812 ( 0.00%) let mut c = state[2]; 812 ( 0.00%) let mut d = state[3]; . . let mut data = [0u32; 16]; . for (o, chunk) in data.iter_mut().zip(input.chunks_exact(4)) { 20,300 ( 0.02%) *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,624 ( 0.00%) state[0] = state[0].wrapping_add(a); 812 ( 0.00%) state[1] = state[1].wrapping_add(b); 812 ( 0.00%) state[2] = state[2].wrapping_add(c); 812 ( 0.00%) state[3] = state[3].wrapping_add(d); 6,496 ( 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,147 ( 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 328 ---------------------------------------- . /// assert_eq!(Ordering::Less, result); . /// . /// let result = 1.cmp(&1); . /// assert_eq!(Ordering::Equal, result); . /// . /// let result = 2.cmp(&1); . /// assert_eq!(Ordering::Greater, result); . /// ``` 71 ( 0.00%) #[derive(Clone, Copy, PartialEq, Debug, Hash)] . #[stable(feature = "rust1", since = "1.0.0")] . #[repr(i8)] . pub enum Ordering { . /// An ordering where a compared value is less than another. . #[stable(feature = "rust1", since = "1.0.0")] . Less = -1, . /// An ordering where a compared value is equal to another. . #[stable(feature = "rust1", since = "1.0.0")] -- line 344 ---------------------------------------- -- line 569 ---------------------------------------- . /// let result = x.0.cmp(&y.0).then_with(|| x.1.cmp(&y.1)).then_with(|| x.2.cmp(&y.2)); . /// . /// assert_eq!(result, Ordering::Less); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "ordering_chaining", since = "1.17.0")] . pub fn then_with Ordering>(self, f: F) -> Ordering { 132 ( 0.00%) match self { . Equal => f(), . _ => self, . } . } . } . . /// A helper struct for reverse ordering. . /// -- line 585 ---------------------------------------- -- line 792 ---------------------------------------- . /// ``` . #[stable(feature = "ord_max_min", since = "1.21.0")] . #[inline] . #[must_use] . fn max(self, other: Self) -> Self . where . Self: Sized, . { 312 ( 0.00%) max_by(self, other, Ord::cmp) . } . . /// Compares and returns the minimum of two values. . /// . /// Returns the first argument if the comparison determines them to be equal. . /// . /// # Examples . /// -- line 808 ---------------------------------------- -- 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 { 6,014 ( 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. 71,766 ( 0.08%) !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 { 27,144 ( 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 { 3,595 ( 0.00%) 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,536 ( 0.01%) match compare(&v1, &v2) { 30 ( 0.00%) 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 1290 ---------------------------------------- -- 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] 154 ( 0.00%) fn eq(&self, other: &$t) -> bool { (*self) == (*other) } . #[inline] 79 ( 0.00%) fn ne(&self, other: &$t) -> bool { (*self) != (*other) } . } . )*) . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl PartialEq for () { . #[inline] . fn eq(&self, _other: &()) -> bool { -- line 1326 ---------------------------------------- -- line 1392 ---------------------------------------- . ($($t:ty)*) => ($( . #[stable(feature = "rust1", since = "1.0.0")] . impl PartialOrd for $t { . #[inline] . fn partial_cmp(&self, other: &$t) -> Option { . Some(self.cmp(other)) . } . #[inline] 427,593 ( 0.47%) fn lt(&self, other: &$t) -> bool { (*self) < (*other) } . #[inline] 300 ( 0.00%) fn le(&self, other: &$t) -> bool { (*self) <= (*other) } . #[inline] . fn ge(&self, other: &$t) -> bool { (*self) >= (*other) } . #[inline] . fn gt(&self, other: &$t) -> bool { (*self) > (*other) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Ord for $t { . #[inline] . fn cmp(&self, other: &$t) -> Ordering { . // The order here is important to generate more optimal assembly. . // See for more info. 74,561 ( 0.08%) 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. 58 ( 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 { 1,125 ( 0.00%) PartialEq::eq(*self, *other) 134 ( 0.00%) } . #[inline] . fn ne(&self, other: &&B) -> bool { 9 ( 0.00%) PartialEq::ne(*self, *other) 23 ( 0.00%) } . } . #[stable(feature = "rust1", since = "1.0.0")] . impl PartialOrd<&B> for &A . where . A: PartialOrd, . { . #[inline] . fn partial_cmp(&self, other: &&B) -> Option { -- line 1496 ---------------------------------------- 49,116 ( 0.05%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_index/src/bit_set.rs -------------------------------------------------------------------------------- Ir -- line 44 ---------------------------------------- . } . Some((start, end)) . } . . macro_rules! bit_relations_inherent_impls { . () => { . /// Sets `self = self | other` and returns `true` if `self` changed . /// (i.e., if new bits were added). 392 ( 0.00%) pub fn union(&mut self, other: &Rhs) -> bool . where . Self: BitRelations, . { . >::union(self, other) 294 ( 0.00%) } . . /// Sets `self = self - other` and returns `true` if `self` changed. . /// (i.e., if any bits were removed). . pub fn subtract(&mut self, other: &Rhs) -> bool . where . Self: BitRelations, . { . >::subtract(self, other) -- line 65 ---------------------------------------- -- line 92 ---------------------------------------- . domain_size: usize, . words: Vec, . marker: PhantomData, . } . . impl BitSet { . /// Gets the domain size. . pub fn domain_size(&self) -> usize { 4 ( 0.00%) self.domain_size . } . } . . impl BitSet { . /// Creates a new, empty bitset with a given `domain_size`. . #[inline] . pub fn new_empty(domain_size: usize) -> BitSet { . let num_words = num_words(domain_size); 858 ( 0.00%) BitSet { domain_size, words: vec![0; num_words], marker: PhantomData } . } . . /// Creates a new, filled bitset with a given `domain_size`. . #[inline] . pub fn new_filled(domain_size: usize) -> BitSet { . let num_words = num_words(domain_size); 40 ( 0.00%) let mut result = BitSet { domain_size, words: vec![!0; num_words], marker: PhantomData }; . result.clear_excess_bits(); . result . } . . /// Clear all elements. . #[inline] . pub fn clear(&mut self) { . for word in &mut self.words { 2 ( 0.00%) *word = 0; . } . } . . /// Clear excess bits in the final word. . fn clear_excess_bits(&mut self) { 8 ( 0.00%) let num_bits_in_final_word = self.domain_size % WORD_BITS; 32 ( 0.00%) if num_bits_in_final_word > 0 { 24 ( 0.00%) let mask = (1 << num_bits_in_final_word) - 1; 56 ( 0.00%) let final_word_idx = self.words.len() - 1; 16 ( 0.00%) self.words[final_word_idx] &= mask; . } . } . . /// Count the number of set bits in the set. . pub fn count(&self) -> usize { . self.words.iter().map(|e| e.count_ones() as usize).sum() . } . . /// Returns `true` if `self` contains `elem`. . #[inline] . pub fn contains(&self, elem: T) -> bool { 448 ( 0.00%) assert!(elem.index() < self.domain_size); . let (word_index, mask) = word_index_and_mask(elem); 646 ( 0.00%) (self.words[word_index] & mask) != 0 . } . . /// Is `self` is a (non-strict) superset of `other`? . #[inline] . pub fn superset(&self, other: &BitSet) -> bool { . assert_eq!(self.domain_size, other.domain_size); . self.words.iter().zip(&other.words).all(|(a, b)| (a & b) == *b) . } -- line 157 ---------------------------------------- -- line 160 ---------------------------------------- . #[inline] . pub fn is_empty(&self) -> bool { . self.words.iter().all(|a| *a == 0) . } . . /// Insert `elem`. Returns whether the set has changed. . #[inline] . pub fn insert(&mut self, elem: T) -> bool { 16,809 ( 0.02%) assert!(elem.index() < self.domain_size); . let (word_index, mask) = word_index_and_mask(elem); . let word_ref = &mut self.words[word_index]; 692 ( 0.00%) let word = *word_ref; 1,384 ( 0.00%) let new_word = word | mask; 8,395 ( 0.01%) *word_ref = new_word; 738 ( 0.00%) new_word != word . } . . #[inline] . pub fn insert_range(&mut self, elems: impl RangeBounds) { . let Some((start, end)) = inclusive_start_end(elems, self.domain_size) else { . return; . }; . -- line 182 ---------------------------------------- -- line 199 ---------------------------------------- . } else { . self.words[start_word_index] |= end_mask | (end_mask - start_mask); . } . } . . /// Sets all bits to true. . pub fn insert_all(&mut self) { . for word in &mut self.words { 16 ( 0.00%) *word = !0; . } . self.clear_excess_bits(); . } . . /// Returns `true` if the set has changed. . #[inline] . pub fn remove(&mut self, elem: T) -> bool { 814 ( 0.00%) assert!(elem.index() < self.domain_size); . let (word_index, mask) = word_index_and_mask(elem); . let word_ref = &mut self.words[word_index]; . let word = *word_ref; 855 ( 0.00%) let new_word = word & !mask; 444 ( 0.00%) *word_ref = new_word; . new_word != word . } . . /// Gets a slice of the underlying words. . pub fn words(&self) -> &[Word] { . &self.words . } . -- line 228 ---------------------------------------- -- line 308 ---------------------------------------- . } . . bit_relations_inherent_impls! {} . } . . // dense REL dense . impl BitRelations> for BitSet { . fn union(&mut self, other: &BitSet) -> bool { 294 ( 0.00%) assert_eq!(self.domain_size, other.domain_size); 90 ( 0.00%) bitwise(&mut self.words, &other.words, |a, b| a | b) . } . . fn subtract(&mut self, other: &BitSet) -> bool { . assert_eq!(self.domain_size, other.domain_size); . bitwise(&mut self.words, &other.words, |a, b| a & !b) . } . . fn intersect(&mut self, other: &BitSet) -> bool { -- line 325 ---------------------------------------- -- line 455 ---------------------------------------- . HybridBitSet::Dense(dense) => self.intersect(dense), . } . } . } . . // hybrid REL hybrid . impl BitRelations> for HybridBitSet { . fn union(&mut self, other: &HybridBitSet) -> bool { 36 ( 0.00%) assert_eq!(self.domain_size(), other.domain_size()); 12 ( 0.00%) match self { . HybridBitSet::Sparse(_) => { 12 ( 0.00%) match other { . HybridBitSet::Sparse(other_sparse) => { . // Both sets are sparse. Add the elements in . // `other_sparse` to `self` one at a time. This . // may or may not cause `self` to be densified. . let mut changed = false; . for elem in other_sparse.iter() { 36 ( 0.00%) changed |= self.insert(*elem); . } . changed . } . . HybridBitSet::Dense(other_dense) => self.union(other_dense), . } . } . -- line 481 ---------------------------------------- -- line 511 ---------------------------------------- . } . } . . impl Clone for BitSet { . fn clone(&self) -> Self { . BitSet { domain_size: self.domain_size, words: self.words.clone(), marker: PhantomData } . } . 924 ( 0.00%) fn clone_from(&mut self, from: &Self) { 583 ( 0.00%) if self.domain_size != from.domain_size { . self.words.resize(from.domain_size, 0); . self.domain_size = from.domain_size; . } . . self.words.copy_from_slice(&from.words); . } . } . -- line 528 ---------------------------------------- -- line 599 ---------------------------------------- . } . } . } . . impl<'a, T: Idx> Iterator for BitIter<'a, T> { . type Item = T; . fn next(&mut self) -> Option { . loop { 324 ( 0.00%) if self.word != 0 { . // Get the position of the next set bit in the current word, . // then clear the bit. . let bit_pos = self.word.trailing_zeros() as usize; . let bit = 1 << bit_pos; . self.word ^= bit; 120 ( 0.00%) return Some(T::new(bit_pos + self.offset)); . } . . // Move onto the next word. `wrapping_add()` is needed to handle . // the degenerate initial value given to `offset` in `new()`. . let word = self.iter.next()?; 39 ( 0.00%) self.word = *word; . self.offset = self.offset.wrapping_add(WORD_BITS); . } . } . } . . #[inline] . fn bitwise(out_vec: &mut [Word], in_vec: &[Word], op: Op) -> bool . where . Op: Fn(Word, Word) -> Word, . { 392 ( 0.00%) assert_eq!(out_vec.len(), in_vec.len()); . let mut changed = 0; 180 ( 0.00%) for (out_elem, in_elem) in iter::zip(out_vec, in_vec) { 180 ( 0.00%) let old_val = *out_elem; . let new_val = op(old_val, *in_elem); 90 ( 0.00%) *out_elem = new_val; . // This is essentially equivalent to a != with changed being a bool, but . // in practice this code gets auto-vectorized by the compiler for most . // operators. Using != here causes us to generate quite poor code as the . // compiler tries to go back to a boolean on each loop iteration. 360 ( 0.00%) changed |= old_val ^ new_val; . } . changed != 0 . } . . const SPARSE_MAX: usize = 8; . . /// A fixed-size bitset type with a sparse representation and a maximum of . /// `SPARSE_MAX` elements. The elements are stored as a sorted `ArrayVec` with -- line 648 ---------------------------------------- -- line 656 ---------------------------------------- . } . . impl SparseBitSet { . fn new_empty(domain_size: usize) -> Self { . SparseBitSet { domain_size, elems: ArrayVec::new() } . } . . fn len(&self) -> usize { 62 ( 0.00%) self.elems.len() . } . . fn is_empty(&self) -> bool { . self.elems.len() == 0 . } . . fn contains(&self, elem: T) -> bool { . assert!(elem.index() < self.domain_size); . self.elems.contains(&elem) . } . . fn insert(&mut self, elem: T) -> bool { 62 ( 0.00%) assert!(elem.index() < self.domain_size); 18 ( 0.00%) let changed = if let Some(i) = self.elems.iter().position(|&e| e.index() >= elem.index()) { 10 ( 0.00%) if self.elems[i] == elem { . // `elem` is already in the set. . false . } else { . // `elem` is smaller than one or more existing elements. . self.elems.insert(i, elem); . true . } . } else { . // `elem` is larger than all existing elements. . self.elems.push(elem); . true . }; 62 ( 0.00%) assert!(self.len() <= SPARSE_MAX); . changed . } . . fn remove(&mut self, elem: T) -> bool { . assert!(elem.index() < self.domain_size); . if let Some(i) = self.elems.iter().position(|&e| e == elem) { . self.elems.remove(i); . true -- line 700 ---------------------------------------- -- line 707 ---------------------------------------- . let mut dense = BitSet::new_empty(self.domain_size); . for elem in self.elems.iter() { . dense.insert(*elem); . } . dense . } . . fn iter(&self) -> slice::Iter<'_, T> { 8 ( 0.00%) self.elems.iter() . } . . bit_relations_inherent_impls! {} . } . . impl SparseBitSet { . fn last_set_in(&self, range: impl RangeBounds) -> Option { . let mut last_leq = None; -- line 723 ---------------------------------------- -- line 755 ---------------------------------------- . Self::Sparse(b) => b.fmt(w), . Self::Dense(b) => b.fmt(w), . } . } . } . . impl HybridBitSet { . pub fn new_empty(domain_size: usize) -> Self { 8 ( 0.00%) HybridBitSet::Sparse(SparseBitSet::new_empty(domain_size)) . } . . pub fn domain_size(&self) -> usize { . match self { . HybridBitSet::Sparse(sparse) => sparse.domain_size, . HybridBitSet::Dense(dense) => dense.domain_size, . } . } . . pub fn clear(&mut self) { . let domain_size = self.domain_size(); 6 ( 0.00%) *self = HybridBitSet::new_empty(domain_size); . } . . pub fn contains(&self, elem: T) -> bool { . match self { . HybridBitSet::Sparse(sparse) => sparse.contains(elem), . HybridBitSet::Dense(dense) => dense.contains(elem), . } . } -- line 783 ---------------------------------------- -- line 799 ---------------------------------------- . HybridBitSet::Sparse(sparse) => sparse.is_empty(), . HybridBitSet::Dense(dense) => dense.is_empty(), . } . } . . /// Returns the previous element present in the bitset from `elem`, . /// inclusively of elem. That is, will return `Some(elem)` if elem is in the . /// bitset. 8 ( 0.00%) pub fn last_set_in(&self, range: impl RangeBounds) -> Option . where . T: Ord, . { 8 ( 0.00%) match self { . HybridBitSet::Sparse(sparse) => sparse.last_set_in(range), . HybridBitSet::Dense(dense) => dense.last_set_in(range), . } 12 ( 0.00%) } . 279 ( 0.00%) pub fn insert(&mut self, elem: T) -> bool { . // No need to check `elem` against `self.domain_size` here because all . // the match cases check it, one way or another. 62 ( 0.00%) match self { 62 ( 0.00%) HybridBitSet::Sparse(sparse) if sparse.len() < SPARSE_MAX => { . // The set is sparse and has space for `elem`. . sparse.insert(elem) . } . HybridBitSet::Sparse(sparse) if sparse.contains(elem) => { . // The set is sparse and does not have space for `elem`, but . // that doesn't matter because `elem` is already present. . false . } -- line 829 ---------------------------------------- -- line 832 ---------------------------------------- . let mut dense = sparse.to_dense(); . let changed = dense.insert(elem); . assert!(changed); . *self = HybridBitSet::Dense(dense); . changed . } . HybridBitSet::Dense(dense) => dense.insert(elem), . } 248 ( 0.00%) } . . pub fn insert_range(&mut self, elems: impl RangeBounds) { . // No need to check `elem` against `self.domain_size` here because all . // the match cases check it, one way or another. . let start = match elems.start_bound().cloned() { . Bound::Included(start) => start.index(), . Bound::Excluded(start) => start.index() + 1, . Bound::Unbounded => 0, -- line 848 ---------------------------------------- -- line 896 ---------------------------------------- . pub fn to_dense(self) -> BitSet { . match self { . HybridBitSet::Sparse(sparse) => sparse.to_dense(), . HybridBitSet::Dense(dense) => dense, . } . } . . pub fn iter(&self) -> HybridIter<'_, T> { 20 ( 0.00%) match self { 50 ( 0.00%) HybridBitSet::Sparse(sparse) => HybridIter::Sparse(sparse.iter()), . HybridBitSet::Dense(dense) => HybridIter::Dense(dense.iter()), . } . } . . bit_relations_inherent_impls! {} . } . . pub enum HybridIter<'a, T: Idx> { -- line 913 ---------------------------------------- -- line 935 ---------------------------------------- . /// to or greater than the domain size. . #[derive(Clone, Debug, PartialEq)] . pub struct GrowableBitSet { . bit_set: BitSet, . } . . impl GrowableBitSet { . /// Ensure that the set can hold at least `min_domain_size` elements. 51,632 ( 0.06%) pub fn ensure(&mut self, min_domain_size: usize) { 14,752 ( 0.02%) if self.bit_set.domain_size < min_domain_size { . self.bit_set.domain_size = min_domain_size; . } . . let min_num_words = num_words(min_domain_size); 29,504 ( 0.03%) if self.bit_set.words.len() < min_num_words { . self.bit_set.words.resize(min_num_words, 0) . } 44,256 ( 0.05%) } . . pub fn new_empty() -> GrowableBitSet { . GrowableBitSet { bit_set: BitSet::new_empty(0) } . } . . pub fn with_capacity(capacity: usize) -> GrowableBitSet { 8 ( 0.00%) GrowableBitSet { bit_set: BitSet::new_empty(capacity) } . } . . /// Returns `true` if the set has changed. . #[inline] . pub fn insert(&mut self, elem: T) -> bool { 36,880 ( 0.04%) self.ensure(elem.index() + 1); . self.bit_set.insert(elem) . } . . /// Returns `true` if the set has changed. . #[inline] . pub fn remove(&mut self, elem: T) -> bool { . self.ensure(elem.index() + 1); . self.bit_set.remove(elem) -- line 973 ---------------------------------------- -- line 976 ---------------------------------------- . #[inline] . pub fn is_empty(&self) -> bool { . self.bit_set.is_empty() . } . . #[inline] . pub fn contains(&self, elem: T) -> bool { . let (word_index, mask) = word_index_and_mask(elem); 314 ( 0.00%) self.bit_set.words.get(word_index).map_or(false, |word| (word & mask) != 0) . } . } . . /// A fixed-size 2D bit matrix type with a dense representation. . /// . /// `R` and `C` are index types used to identify rows and columns respectively; . /// typically newtyped `usize` wrappers, but they can also just be `usize`. . /// -- line 992 ---------------------------------------- -- line 1001 ---------------------------------------- . } . . impl BitMatrix { . /// Creates a new `rows x columns` matrix, initially empty. . pub fn new(num_rows: usize, num_columns: usize) -> BitMatrix { . // For every element, we need one bit for every other . // element. Round up to an even number of words. . let words_per_row = num_words(num_columns); 32 ( 0.00%) BitMatrix { . num_rows, . num_columns, 24 ( 0.00%) words: vec![0; num_rows * words_per_row], . marker: PhantomData, . } . } . . /// Creates a new matrix, with `row` used as the value for every row. . pub fn from_row_n(row: &BitSet, num_rows: usize) -> BitMatrix { . let num_columns = row.domain_size(); . let words_per_row = num_words(num_columns); -- line 1020 ---------------------------------------- -- line 1029 ---------------------------------------- . . pub fn rows(&self) -> impl Iterator { . (0..self.num_rows).map(R::new) . } . . /// The range of bits for a given row. . fn range(&self, row: R) -> (usize, usize) { . let words_per_row = num_words(self.num_columns); 336 ( 0.00%) let start = row.index() * words_per_row; 284 ( 0.00%) (start, start + words_per_row) . } . . /// Sets the cell at `(row, column)` to true. Put another way, insert . /// `column` to the bitset for `row`. . /// . /// Returns `true` if this changed the matrix. . pub fn insert(&mut self, row: R, column: C) -> bool { 180 ( 0.00%) assert!(row.index() < self.num_rows && column.index() < self.num_columns); . let (start, _) = self.range(row); . let (word_index, mask) = word_index_and_mask(column); . let words = &mut self.words[..]; 180 ( 0.00%) let word = words[start + word_index]; 72 ( 0.00%) let new_word = word | mask; 36 ( 0.00%) words[start + word_index] = new_word; 72 ( 0.00%) word != new_word . } . . /// Do the bits from `row` contain `column`? Put another way, is . /// the matrix cell at `(row, column)` true? Put yet another way, . /// if the matrix represents (transitive) reachability, can . /// `row` reach `column`? 16 ( 0.00%) pub fn contains(&self, row: R, column: C) -> bool { 80 ( 0.00%) assert!(row.index() < self.num_rows && column.index() < self.num_columns); . let (start, _) = self.range(row); . let (word_index, mask) = word_index_and_mask(column); 80 ( 0.00%) (self.words[start + word_index] & mask) != 0 32 ( 0.00%) } . . /// Returns those indices that are true in rows `a` and `b`. This . /// is an *O*(*n*) operation where *n* is the number of elements . /// (somewhat independent from the actual size of the . /// intersection, in particular). . pub fn intersect_rows(&self, row1: R, row2: R) -> Vec { . assert!(row1.index() < self.num_rows && row2.index() < self.num_rows); . let (row1_start, row1_end) = self.range(row1); -- line 1073 ---------------------------------------- -- line 1090 ---------------------------------------- . . /// Adds the bits from row `read` to the bits from row `write`, and . /// returns `true` if anything changed. . /// . /// This is used when computing transitive reachability because if . /// you have an edge `write -> read`, because in that case . /// `write` can reach everything that `read` can (and . /// potentially more). 36 ( 0.00%) pub fn union_rows(&mut self, read: R, write: R) -> bool { 180 ( 0.00%) assert!(read.index() < self.num_rows && write.index() < self.num_rows); 36 ( 0.00%) let (read_start, read_end) = self.range(read); . let (write_start, write_end) = self.range(write); . let words = &mut self.words[..]; . let mut changed = false; . for (read_index, write_index) in iter::zip(read_start..read_end, write_start..write_end) { 180 ( 0.00%) let word = words[write_index]; 108 ( 0.00%) let new_word = word | words[read_index]; 36 ( 0.00%) words[write_index] = new_word; 180 ( 0.00%) changed |= word != new_word; . } . changed 108 ( 0.00%) } . . /// Adds the bits from `with` to the bits from row `write`, and . /// returns `true` if anything changed. . pub fn union_row_with(&mut self, with: &BitSet, write: R) -> bool { . assert!(write.index() < self.num_rows); . assert_eq!(with.domain_size(), self.num_columns); . let (write_start, write_end) = self.range(write); . let mut changed = false; -- line 1119 ---------------------------------------- -- line 1209 ---------------------------------------- . /// Creates a new empty sparse bit matrix with no rows or columns. . pub fn new(num_columns: usize) -> Self { . Self { num_columns, rows: IndexVec::new() } . } . . fn ensure_row(&mut self, row: R) -> &mut HybridBitSet { . // Instantiate any missing rows up to and including row `row` with an empty HybridBitSet. . // Then replace row `row` with a full HybridBitSet if necessary. 16 ( 0.00%) self.rows.get_or_insert_with(row, || HybridBitSet::new_empty(self.num_columns)) . } . . /// Sets the cell at `(row, column)` to true. Put another way, insert . /// `column` to the bitset for `row`. . /// . /// Returns `true` if this changed the matrix. . pub fn insert(&mut self, row: R, column: C) -> bool { 20 ( 0.00%) self.ensure_row(row).insert(column) . } . . /// Sets the cell at `(row, column)` to false. Put another way, delete . /// `column` from the bitset for `row`. Has no effect if `row` does not . /// exist. . /// . /// Returns `true` if this changed the matrix. . pub fn remove(&mut self, row: R, column: C) -> bool { -- line 1233 ---------------------------------------- -- line 1255 ---------------------------------------- . . /// Adds the bits from row `read` to the bits from row `write`, and . /// returns `true` if anything changed. . /// . /// This is used when computing transitive reachability because if . /// you have an edge `write -> read`, because in that case . /// `write` can reach everything that `read` can (and . /// potentially more). 308 ( 0.00%) pub fn union_rows(&mut self, read: R, write: R) -> bool { 44 ( 0.00%) if read == write || self.row(read).is_none() { . return false; . } . . self.ensure_row(write); 66 ( 0.00%) if let (Some(read_row), Some(write_row)) = self.rows.pick2_mut(read, write) { . write_row.union(read_row) . } else { . unreachable!() . } 396 ( 0.00%) } . . /// Insert all bits in the given row. . pub fn insert_all_into_row(&mut self, row: R) { . self.ensure_row(row).insert_all(); . } . . pub fn rows(&self) -> impl Iterator { . self.rows.indices() -- line 1282 ---------------------------------------- -- line 1284 ---------------------------------------- . . /// Iterates through all the columns set to true in a given row of . /// the matrix. . pub fn iter<'a>(&'a self, row: R) -> impl Iterator + 'a { . self.row(row).into_iter().flat_map(|r| r.iter()) . } . . pub fn row(&self, row: R) -> Option<&HybridBitSet> { 146 ( 0.00%) if let Some(Some(row)) = self.rows.get(row) { Some(row) } else { None } . } . . /// Interescts `row` with `set`. `set` can be either `BitSet` or . /// `HybridBitSet`. Has no effect if `row` does not exist. . /// . /// Returns true if the row was changed. . pub fn intersect_row(&mut self, row: R, set: &Set) -> bool . where -- line 1300 ---------------------------------------- -- line 1329 ---------------------------------------- . HybridBitSet: BitRelations, . { . self.ensure_row(row).union(set) . } . } . . #[inline] . fn num_words(domain_size: T) -> usize { 32,050 ( 0.03%) (domain_size.index() + WORD_BITS - 1) / WORD_BITS . } . . #[inline] . fn word_index_and_mask(elem: T) -> (usize, Word) { . let elem = elem.index(); 18,602 ( 0.02%) let word_index = elem / WORD_BITS; 15,446 ( 0.02%) let mask = 1 << (elem % WORD_BITS); . (word_index, mask) . } . . #[inline] . fn max_bit(word: Word) -> usize { . WORD_BITS - 1 - word.leading_zeros() as usize . } . -- line 1352 ---------------------------------------- 2,668 ( 0.00%) -------------------------------------------------------------------------------- -- 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 35,995 ( 0.04%) ('a' <= self && self <= 'z') . || ('A' <= self && self <= 'Z') 11,370 ( 0.01%) || (self > '\x7f' && derived_property::XID_Start(self)) . } . . #[inline] . fn is_xid_continue(self) -> bool { . // Fast-path for ascii idents 84,542 ( 0.09%) ('a' <= self && self <= 'z') . || ('A' <= self && self <= 'Z') . || ('0' <= self && self <= '9') . || self == '_' 3,298 ( 0.00%) || (self > '\x7f' && derived_property::XID_Continue(self)) . } . } 15,197 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/iter/traits/iterator.rs -------------------------------------------------------------------------------- Ir -- line 193 ---------------------------------------- . /// assert_eq!(a.iter().count(), 5); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . fn count(self) -> usize . where . Self: Sized, . { 89 ( 0.00%) self.fold( . 0, . #[rustc_inherit_overflow_checks] 246 ( 0.00%) |count, _| count + 1, . ) . } . . /// Consumes the iterator, returning the last element. . /// . /// This method will evaluate the iterator until it returns [`None`]. While . /// doing so, it keeps track of the current element. After [`None`] is . /// returned, `last()` will then return the last element it saw. -- line 212 ---------------------------------------- -- line 267 ---------------------------------------- . /// assert_eq!(iter.next(), Some(&3)); . /// assert_eq!(iter.advance_by(0), Ok(())); . /// assert_eq!(iter.advance_by(100), Err(1)); // only `&4` was skipped . /// ``` . #[inline] . #[unstable(feature = "iter_advance_by", reason = "recently added", issue = "77404")] . fn advance_by(&mut self, n: usize) -> Result<(), usize> { . for i in 0..n { 10 ( 0.00%) self.next().ok_or(i)?; . } . Ok(()) . } . . /// Returns the `n`th element of the iterator. . /// . /// Like most indexing operations, the count starts from zero, so `nth(0)` . /// returns the first value, `nth(1)` the second, and so on. -- line 283 ---------------------------------------- -- line 315 ---------------------------------------- . /// ``` . /// let a = [1, 2, 3]; . /// assert_eq!(a.iter().nth(10), None); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . fn nth(&mut self, n: usize) -> Option { . self.advance_by(n).ok()?; 14 ( 0.00%) self.next() . } . . /// Creates an iterator starting at the same point, but stepping by . /// the given amount at each iteration. . /// . /// Note 1: The first element of the iterator will always be returned, . /// regardless of the step given. . /// -- line 331 ---------------------------------------- -- line 441 ---------------------------------------- . /// [`OsStr`]: ../../std/ffi/struct.OsStr.html . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . fn chain(self, other: U) -> Chain . where . Self: Sized, . U: IntoIterator, . { 160 ( 0.00%) Chain::new(self, other.into_iter()) . } . . /// 'Zips up' two iterators into a single iterator of pairs. . /// . /// `zip()` returns a new iterator that will iterate over two other . /// iterators, returning a tuple where the first element comes from the . /// first iterator, and the second element comes from the second iterator. . /// -- line 457 ---------------------------------------- -- line 714 ---------------------------------------- . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . fn map(self, f: F) -> Map . where . Self: Sized, . F: FnMut(Self::Item) -> B, . { 1,167 ( 0.00%) Map::new(self, f) . } . . /// Calls a closure on each element of an iterator. . /// . /// This is equivalent to using a [`for`] loop on the iterator, although . /// `break` and `continue` are not possible from a closure. It's generally . /// more idiomatic to use a `for` loop, but `for_each` may be more legible . /// when processing items at the end of longer iterator chains. In some -- line 730 ---------------------------------------- -- line 761 ---------------------------------------- . #[stable(feature = "iterator_for_each", since = "1.21.0")] . fn for_each(self, f: F) . where . Self: Sized, . F: FnMut(Self::Item), . { . #[inline] . fn call(mut f: impl FnMut(T)) -> impl FnMut((), T) { 20 ( 0.00%) move |(), item| f(item) . } . 11,758 ( 0.01%) self.fold((), call(f)); . } . . /// Creates an iterator which uses a closure to determine if an element . /// should be yielded. . /// . /// Given an element the closure must return `true` or `false`. The returned . /// iterator will yield only the elements for which the closure returns . /// true. -- line 780 ---------------------------------------- -- line 834 ---------------------------------------- . /// Note that `iter.filter(f).next()` is equivalent to `iter.find(f)`. . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . fn filter

(self, predicate: P) -> Filter . where . Self: Sized, . P: FnMut(&Self::Item) -> bool, . { 24 ( 0.00%) Filter::new(self, predicate) . } . . /// Creates an iterator that both filters and maps. . /// . /// The returned iterator yields only the `value`s for which the supplied . /// closure returns `Some(value)`. . /// . /// `filter_map` can be used to make chains of [`filter`] and [`map`] more -- line 850 ---------------------------------------- -- line 879 ---------------------------------------- . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . fn filter_map(self, f: F) -> FilterMap . where . Self: Sized, . F: FnMut(Self::Item) -> Option, . { 16 ( 0.00%) FilterMap::new(self, f) . } . . /// Creates an iterator which gives the current iteration count as well as . /// the next value. . /// . /// The iterator returned yields pairs `(i, val)`, where `i` is the . /// current index of iteration and `val` is the value returned by the . /// iterator. -- line 895 ---------------------------------------- -- line 995 ---------------------------------------- . /// [`peek_mut`]: Peekable::peek_mut . /// [`next`]: Iterator::next . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . fn peekable(self) -> Peekable . where . Self: Sized, . { 13 ( 0.00%) Peekable::new(self) . } . . /// Creates an iterator that [`skip`]s elements based on a predicate. . /// . /// [`skip`]: Iterator::skip . /// . /// `skip_while()` takes a closure as an argument. It will call this . /// closure on each element of the iterator, and ignore elements -- line 1011 ---------------------------------------- -- line 1537 ---------------------------------------- . /// assert_eq!(iter.next(), None); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . fn fuse(self) -> Fuse . where . Self: Sized, . { 20 ( 0.00%) Fuse::new(self) . } . . /// Does something with each element of an iterator, passing the value on. . /// . /// When using iterators, you'll often chain several of them together. . /// While working on such code, you might want to check out what's . /// happening at various parts in the pipeline. To do that, insert . /// a call to `inspect()`. -- line 1553 ---------------------------------------- -- line 1769 ---------------------------------------- . /// [`char`]: type@char . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[must_use = "if you really need to exhaust the iterator, consider `.for_each(drop)` instead"] . fn collect>(self) -> B . where . Self: Sized, . { 349 ( 0.00%) FromIterator::from_iter(self) . } . . /// Consumes an iterator, creating two collections from it. . /// . /// The predicate passed to `partition()` can return `true`, or `false`. . /// `partition()` returns a pair, all of the elements for which it returned . /// `true`, and all of the elements for which it returned `false`. . /// -- line 1785 ---------------------------------------- -- line 1798 ---------------------------------------- . /// let (even, odd): (Vec, Vec) = a . /// .iter() . /// .partition(|&n| n % 2 == 0); . /// . /// assert_eq!(even, vec![2]); . /// assert_eq!(odd, vec![1, 3]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 8 ( 0.00%) fn partition(self, f: F) -> (B, B) . where . Self: Sized, . B: Default + Extend, . F: FnMut(&Self::Item) -> bool, . { . #[inline] . fn extend<'a, T, B: Extend>( . mut f: impl FnMut(&T) -> bool + 'a, -- line 1814 ---------------------------------------- -- line 1822 ---------------------------------------- . right.extend_one(x); . } . } . } . . let mut left: B = Default::default(); . let mut right: B = Default::default(); . 4 ( 0.00%) self.fold((), extend(f, &mut left, &mut right)); . 8 ( 0.00%) (left, right) 9 ( 0.00%) } . . /// Reorders the elements of this iterator *in-place* according to the given predicate, . /// such that all those that return `true` precede all those that return `false`. . /// Returns the number of `true` elements found. . /// . /// The relative order of partitioned items is not maintained. . /// . /// # Current implementation -- line 1841 ---------------------------------------- -- line 2011 ---------------------------------------- . /// } else { . /// ControlFlow::Break(prev) . /// } . /// }); . /// assert_eq!(triangular, ControlFlow::Continue(435)); . /// ``` . #[inline] . #[stable(feature = "iterator_try_fold", since = "1.27.0")] 10,728 ( 0.01%) fn try_fold(&mut self, init: B, mut f: F) -> R . where . Self: Sized, . F: FnMut(B, Self::Item) -> R, . R: Try, . { 8 ( 0.00%) let mut accum = init; 52,053 ( 0.06%) while let Some(x) = self.next() { 14,364 ( 0.02%) accum = f(accum, x)?; . } 12 ( 0.00%) try { accum } 9,536 ( 0.01%) } . . /// An iterator method that applies a fallible function to each item in the . /// iterator, stopping at the first error and returning that error. . /// . /// This can also be thought of as the fallible form of [`for_each()`] . /// or as the stateless version of [`try_fold()`]. . /// . /// [`for_each()`]: Iterator::for_each -- line 2038 ---------------------------------------- -- line 2188 ---------------------------------------- . /// // they're the same . /// assert_eq!(result, result2); . /// ``` . /// . /// [`reduce()`]: Iterator::reduce . #[doc(alias = "inject", alias = "foldl")] . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 42 ( 0.00%) fn fold(mut self, init: B, mut f: F) -> B . where . Self: Sized, . F: FnMut(B, Self::Item) -> B, . { 30 ( 0.00%) let mut accum = init; 1,986 ( 0.00%) while let Some(x) = self.next() { 7,320 ( 0.01%) accum = f(accum, x); . } . accum 48 ( 0.00%) } . . /// Reduces the elements to a single one, by repeatedly applying a reducing . /// operation. . /// . /// If the iterator is empty, returns [`None`]; otherwise, returns the . /// result of the reduction. . /// . /// The reducing function is a closure with two arguments: an 'accumulator', and an element. -- line 2214 ---------------------------------------- -- line 2240 ---------------------------------------- . #[inline] . #[stable(feature = "iterator_fold_self", since = "1.51.0")] . fn reduce(mut self, f: F) -> Option . where . Self: Sized, . F: FnMut(Self::Item, Self::Item) -> Self::Item, . { . let first = self.next()?; 60 ( 0.00%) Some(self.fold(first, f)) . } . . /// Reduces the elements to a single one by repeatedly applying a reducing operation. If the . /// closure returns a failure, the failure is propagated back to the caller immediately. . /// . /// The return type of this method depends on the return type of the closure. If the closure . /// returns `Result`, then this function will return `Result, . /// E>`. If the closure returns `Option`, then this function will return -- line 2256 ---------------------------------------- -- line 2370 ---------------------------------------- . fn all(&mut self, f: F) -> bool . where . Self: Sized, . F: FnMut(Self::Item) -> bool, . { . #[inline] . fn check(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> ControlFlow<()> { . move |(), x| { 22,384 ( 0.02%) if f(x) { ControlFlow::CONTINUE } else { ControlFlow::BREAK } . } . } 2,386 ( 0.00%) self.try_fold((), check(f)) == ControlFlow::CONTINUE . } . . /// Tests if any element of the iterator matches a predicate. . /// . /// `any()` takes a closure that returns `true` or `false`. It applies . /// this closure to each element of the iterator, and if any of them return . /// `true`, then so does `any()`. If they all return `false`, it . /// returns `false`. -- line 2389 ---------------------------------------- -- line 2423 ---------------------------------------- . fn any(&mut self, f: F) -> bool . where . Self: Sized, . F: FnMut(Self::Item) -> bool, . { . #[inline] . fn check(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> ControlFlow<()> { . move |(), x| { 10 ( 0.00%) if f(x) { ControlFlow::BREAK } else { ControlFlow::CONTINUE } . } . } . 9 ( 0.00%) self.try_fold((), check(f)) == ControlFlow::BREAK . } . . /// Searches for an element of an iterator that satisfies a predicate. . /// . /// `find()` takes a closure that returns `true` or `false`. It applies . /// this closure to each element of the iterator, and if any of them return . /// `true`, then `find()` returns [`Some(element)`]. If they all return . /// `false`, it returns [`None`]. -- line 2443 ---------------------------------------- -- line 2483 ---------------------------------------- . fn find

(&mut self, predicate: P) -> Option . where . Self: Sized, . P: FnMut(&Self::Item) -> bool, . { . #[inline] . fn check(mut predicate: impl FnMut(&T) -> bool) -> impl FnMut((), T) -> ControlFlow { . move |(), x| { 255 ( 0.00%) if predicate(&x) { ControlFlow::Break(x) } else { ControlFlow::CONTINUE } . } . } . 184 ( 0.00%) self.try_fold((), check(predicate)).break_value() . } . . /// Applies function to the elements of iterator and returns . /// the first non-none result. . /// . /// `iter.find_map(f)` is equivalent to `iter.filter_map(f).next()`. . /// . /// # Examples -- line 2503 ---------------------------------------- -- line 2513 ---------------------------------------- . #[stable(feature = "iterator_find_map", since = "1.30.0")] . fn find_map(&mut self, f: F) -> Option . where . Self: Sized, . F: FnMut(Self::Item) -> Option, . { . #[inline] . fn check(mut f: impl FnMut(T) -> Option) -> impl FnMut((), T) -> ControlFlow { 549 ( 0.00%) move |(), x| match f(x) { 248 ( 0.00%) Some(x) => ControlFlow::Break(x), . None => ControlFlow::CONTINUE, . } . } . 9 ( 0.00%) self.try_fold((), check(f)).break_value() . } . . /// Applies function to the elements of iterator and returns . /// the first true result or the first error. . /// . /// The return type of this method depends on the return type of the closure. . /// If you return `Result` from the closure, you'll get a `Result; E>`. . /// If you return `Option` from the closure, you'll get an `Option>`. -- line 2535 ---------------------------------------- -- line 2855 ---------------------------------------- . Self: Sized, . F: FnMut(&Self::Item, &Self::Item) -> Ordering, . { . #[inline] . fn fold(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T { . move |x, y| cmp::max_by(x, y, &mut compare) . } . 186 ( 0.00%) self.reduce(fold(compare)) . } . . /// Returns the element that gives the minimum value from the . /// specified function. . /// . /// If several elements are equally minimum, the first element is . /// returned. If the iterator is empty, [`None`] is returned. . /// -- line 2871 ---------------------------------------- -- line 2946 ---------------------------------------- . /// ``` . #[inline] . #[doc(alias = "reverse")] . #[stable(feature = "rust1", since = "1.0.0")] . fn rev(self) -> Rev . where . Self: Sized + DoubleEndedIterator, . { 13 ( 0.00%) Rev::new(self) . } . . /// Converts an iterator of pairs into a pair of containers. . /// . /// `unzip()` consumes an entire iterator of pairs, producing two . /// collections: one from the left elements of the pairs, and one . /// from the right elements. . /// -- line 2962 ---------------------------------------- -- line 3017 ---------------------------------------- . /// assert_eq!(v_map, vec![1, 2, 3]); . /// ``` . #[stable(feature = "iter_copied", since = "1.36.0")] . fn copied<'a, T: 'a>(self) -> Copied . where . Self: Sized + Iterator, . T: Copy, . { 12 ( 0.00%) Copied::new(self) . } . . /// Creates an iterator which [`clone`]s all of its elements. . /// . /// This is useful when you have an iterator over `&T`, but you need an . /// iterator over `T`. . /// . /// [`clone`]: Clone::clone -- line 3033 ---------------------------------------- -- line 3048 ---------------------------------------- . /// assert_eq!(v_map, vec![1, 2, 3]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . fn cloned<'a, T: 'a>(self) -> Cloned . where . Self: Sized + Iterator, . T: Clone, . { 280 ( 0.00%) Cloned::new(self) . } . . /// Repeats an iterator endlessly. . /// . /// Instead of stopping at [`None`], the iterator will instead start again, . /// from the beginning. After iterating again, it will start at the . /// beginning again. And again. And again. Forever. Note that in case the . /// original iterator is empty, the resulting iterator will also be empty. -- line 3064 ---------------------------------------- -- line 3313 ---------------------------------------- . /// . /// # Examples . /// . /// ``` . /// assert_eq!([1].iter().eq([1].iter()), true); . /// assert_eq!([1].iter().eq([1, 2].iter()), false); . /// ``` . #[stable(feature = "iter_order", since = "1.5.0")] 7 ( 0.00%) fn eq(self, other: I) -> bool . where . I: IntoIterator, . Self::Item: PartialEq, . Self: Sized, . { 8 ( 0.00%) self.eq_by(other, |x, y| x == y) 8 ( 0.00%) } . . /// Determines if the elements of this [`Iterator`] are equal to those of . /// another with respect to the specified equality function. . /// . /// # Examples . /// . /// Basic usage: . /// -- line 3336 ---------------------------------------- -- line 3344 ---------------------------------------- . /// ``` . #[unstable(feature = "iter_order_by", issue = "64295")] . fn eq_by(mut self, other: I, mut eq: F) -> bool . where . Self: Sized, . I: IntoIterator, . F: FnMut(Self::Item, I::Item) -> bool, . { 10 ( 0.00%) let mut other = other.into_iter(); . . loop { 3 ( 0.00%) let x = match self.next() { . None => return other.next().is_none(), 11 ( 0.00%) Some(val) => val, . }; . 3 ( 0.00%) let y = match other.next() { . None => return false, . Some(val) => val, . }; . . if !eq(x, y) { . return false; . } . } -- line 3368 ---------------------------------------- -- line 3589 ---------------------------------------- . unreachable!("Always specialized"); . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Iterator for &mut I { . type Item = I::Item; . #[inline] 1,184 ( 0.00%) fn next(&mut self) -> Option { 1,567 ( 0.00%) (**self).next() 1,776 ( 0.00%) } . fn size_hint(&self) -> (usize, Option) { . (**self).size_hint() . } . fn advance_by(&mut self, n: usize) -> Result<(), usize> { . (**self).advance_by(n) . } . fn nth(&mut self, n: usize) -> Option { . (**self).nth(n) -- line 3607 ---------------------------------------- 18,736 ( 0.02%) -------------------------------------------------------------------------------- -- 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 { 90,495 ( 0.10%) Token { kind, len } . } . } . . /// Enum representing common lexeme types. . // perf note: Changing all `usize` to `u32` doesn't change performance. See #77629 16,330 ( 0.02%) #[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. 7 ( 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 8 ( 0.00%) } . . /// Parses the first token from the provided input string. 30,165 ( 0.03%) pub fn first_token(input: &str) -> Token { . debug_assert!(!input.is_empty()); 10,055 ( 0.01%) Cursor::new(input).advance_token() 40,220 ( 0.04%) } . . /// 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,030 ( 0.04%) 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). 34 ( 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. 80,440 ( 0.09%) fn advance_token(&mut self) -> Token { . let first_char = self.bump().unwrap(); 40,493 ( 0.04%) let token_kind = match first_char { . // Slash, comment or block comment. 1,736 ( 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. 68 ( 0.00%) 'r' => match (self.first(), self.second()) { . ('#', c1) if is_id_start(c1) => self.raw_ident(), . ('#', _) | ('"', _) => { . let (n_hashes, err) = self.raw_double_quoted_string(1); . let suffix_start = self.len_consumed(); . if err.is_none() { . self.eat_literal_suffix(); . } . let kind = RawStr { n_hashes, err }; . Literal { kind, suffix_start } . } . _ => self.ident_or_unknown_prefix(), . }, . . // Byte literal, byte string literal, raw byte string literal or identifier. 108 ( 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. 17,052 ( 0.02%) c @ '0'..='9' => { . let literal_kind = self.number(c); . let suffix_start = self.len_consumed(); . self.eat_literal_suffix(); 5 ( 0.00%) TokenKind::Literal { kind: literal_kind, suffix_start } . } . . // One-symbol tokens. 284 ( 0.00%) ';' => Semi, 256 ( 0.00%) ',' => Comma, 16 ( 0.00%) '.' => Dot, 1,314 ( 0.00%) '(' => OpenParen, 1,314 ( 0.00%) ')' => CloseParen, 374 ( 0.00%) '{' => OpenBrace, 374 ( 0.00%) '}' => CloseBrace, 778 ( 0.00%) '[' => OpenBracket, 778 ( 0.00%) ']' => CloseBracket, 150 ( 0.00%) '@' => At, 192 ( 0.00%) '#' => Pound, . '~' => Tilde, 496 ( 0.00%) '?' => Question, 1,232 ( 0.00%) ':' => Colon, 2,510 ( 0.00%) '$' => Dollar, 160 ( 0.00%) '=' => Eq, 96 ( 0.00%) '!' => Bang, 108 ( 0.00%) '<' => Lt, 248 ( 0.00%) '>' => Gt, 12 ( 0.00%) '-' => Minus, 40 ( 0.00%) '&' => And, . '|' => Or, 120 ( 0.00%) '+' => Plus, 482 ( 0.00%) '*' => Star, . '^' => Caret, . '%' => Percent, . . // Lifetime or character literal. 48 ( 0.00%) '\'' => self.lifetime_or_char(), . . // String literal. . '"' => { . let terminated = self.double_quoted_string(); . let suffix_start = self.len_consumed(); . if terminated { . self.eat_literal_suffix(); . } -- line 413 ---------------------------------------- -- line 416 ---------------------------------------- . } . // 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()) 90,495 ( 0.10%) } . . fn line_comment(&mut self) -> TokenKind { . debug_assert!(self.prev() == '/' && self.first() == '/'); . self.bump(); . 1,372 ( 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. 546 ( 0.00%) '/' if self.second() != '/' => Some(DocStyle::Outer), . _ => None, . }; . 15,579 ( 0.02%) self.eat_while(|c| c != '\n'); 1,302 ( 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); 2,304 ( 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 . } . 8,165 ( 0.01%) fn ident_or_unknown_prefix(&mut self) -> TokenKind { . debug_assert!(is_id_start(self.prev())); . // Start is already eaten, eat the rest of identifier. 3,266 ( 0.00%) 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. 3,266 ( 0.00%) match self.first() { . '#' | '"' | '\'' => UnknownPrefix, 1,633 ( 0.00%) c if !c.is_ascii() && unic_emoji_char::is_emoji(c) => { . self.fake_ident_or_unknown_prefix() . } 1,633 ( 0.00%) _ => Ident, . } 6,532 ( 0.01%) } . . 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; 2 ( 0.00%) if first_digit == '0' { . // Attempt to parse encoding base. 5 ( 0.00%) let has_digits = match self.first() { . 'b' => { . base = Base::Binary; . self.bump(); . self.eat_decimal_digits() . } . 'o' => { . base = Base::Octal; . self.bump(); -- line 537 ---------------------------------------- -- line 538 ---------------------------------------- . self.eat_decimal_digits() . } . 'x' => { . base = Base::Hexadecimal; . self.bump(); . self.eat_hexadecimal_digits() . } . // Not a base prefix. 3 ( 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". -- line 554 ---------------------------------------- -- line 585 ---------------------------------------- . self.bump(); . let empty_exponent = !self.eat_float_exponent(); . Float { base, empty_exponent } . } . _ => Int { base, empty_int: false }, . } . } . 112 ( 0.00%) fn lifetime_or_char(&mut self) -> TokenKind { . debug_assert!(self.prev() == '\''); . 32 ( 0.00%) let can_be_a_lifetime = if self.second() == '\'' { . // It's surely not a lifetime. . false . } else { . // If the first symbol is valid for identifier, it can be a lifetime. . // Also check if it's a number for a better error reporting (so '0 will . // be reported as invalid lifetime and not as unterminated char literal). . is_id_start(self.first()) || self.first().is_digit(10) . }; -- line 604 ---------------------------------------- -- line 617 ---------------------------------------- . // length greater than 1. . . let starts_with_number = self.first().is_digit(10); . . // Skip the literal contents. . // First symbol can be a number (which isn't a valid identifier start), . // so skip it without any checks. . self.bump(); 32 ( 0.00%) self.eat_while(is_id_continue); . . // Check if after skipping literal contents we've met a closing . // single quote (which means that user attempted to create a . // string with single quotes). 32 ( 0.00%) if self.first() == '\'' { . self.bump(); . let kind = Char { terminated: true }; . Literal { kind, suffix_start: self.len_consumed() } . } else { 32 ( 0.00%) Lifetime { starts_with_number } . } 96 ( 0.00%) } . . fn single_quoted_string(&mut self) -> bool { . debug_assert!(self.prev() == '\''); . // Check if it's a one-symbol literal. . if self.second() == '\'' && self.first() != '\\' { . self.bump(); . self.bump(); . return true; -- line 645 ---------------------------------------- -- line 816 ---------------------------------------- . 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) { 2 ( 0.00%) self.eat_identifier(); . } . . // Eats the identifier. 3 ( 0.00%) fn eat_identifier(&mut self) { . if !is_id_start(self.first()) { . return; . } . self.bump(); . . self.eat_while(is_id_continue); 4 ( 0.00%) } . } 163,133 ( 0.18%) -------------------------------------------------------------------------------- -- 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 { 100,144 ( 0.11%) if value < 0x80 { . unsafe { 48,359 ( 0.05%) *out.get_unchecked_mut(i).as_mut_ptr() = value as u8; . } . 59,937 ( 0.07%) i += 1; . break; . } else { . unsafe { 53,568 ( 0.06%) *out.get_unchecked_mut(i).as_mut_ptr() = ((value & 0x7f) | 0x80) as u8; . } . 28,223 ( 0.03%) 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. 198,220 ( 0.22%) let byte = slice[*position]; 99,110 ( 0.11%) *position += 1; 99,110 ( 0.11%) 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 { 98,250 ( 0.11%) let byte = slice[*position]; 62,267 ( 0.07%) *position += 1; 65,500 ( 0.07%) if (byte & 0x80) == 0 { 43,933 ( 0.05%) result |= (byte as $int_ty) << shift; . return result; . } else { . result |= ((byte & 0x7F) as $int_ty) << shift; . } . shift += 7; . } . } . }; -- line 80 ---------------------------------------- 120,195 ( 0.13%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/intrinsics.rs -------------------------------------------------------------------------------- Ir -- line 2075 ---------------------------------------- . // SAFETY: As per our safety precondition, we may assume that the `abort` above is never reached. . // Therefore, compiletime_check and runtime_check are observably equivalent. . unsafe { . const_eval_select((src, dst, count), compiletime_check, runtime_check); . } . . // SAFETY: the safety contract for `copy_nonoverlapping` must be . // upheld by the caller. 423,471 ( 0.46%) unsafe { copy_nonoverlapping(src, dst, count) } . } . . /// Copies `count * size_of::()` bytes from `src` to `dst`. The source . /// and destination may overlap. . /// . /// If the source and destination will *never* overlap, . /// [`copy_nonoverlapping`] can be used instead. . /// -- line 2091 ---------------------------------------- -- line 2165 ---------------------------------------- . #[cfg(debug_assertions)] . // SAFETY: As per our safety precondition, we may assume that the `abort` above is never reached. . // Therefore, compiletime_check and runtime_check are observably equivalent. . unsafe { . const_eval_select((src, dst), compiletime_check, runtime_check); . } . . // SAFETY: the safety contract for `copy` must be upheld by the caller. 3,308 ( 0.00%) unsafe { copy(src, dst, count) } . } . . /// Sets `count * size_of::()` bytes of memory starting at `dst` to . /// `val`. . /// . /// `write_bytes` is similar to C's [`memset`], but sets `count * . /// size_of::()` bytes to `val`. . /// -- line 2181 ---------------------------------------- -- line 2266 ---------------------------------------- . #[cfg(debug_assertions)] . // SAFETY: runtime debug-assertions are a best-effort basis; it's fine to . // not do them during compile time . unsafe { . const_eval_select((dst,), compiletime_check, runtime_check); . } . . // SAFETY: the safety contract for `write_bytes` must be upheld by the caller. 9,140 ( 0.01%) unsafe { write_bytes(dst, val, count) } . } . . /// Selects which function to call depending on the context. . /// . /// If this function is evaluated at compile-time, then a call to this . /// intrinsic will be replaced with a call to `called_in_const`. It gets . /// replaced with a call to `called_at_rt` otherwise. . /// -- line 2282 ---------------------------------------- 2,254 ( 0.00%) -------------------------------------------------------------------------------- -- 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. 10,056 ( 0.01%) unsafe { from_raw_parts(self.ptr.as_ptr(), len!(self)) } . } . . // Helper function for moving the start of the iterator forwards by `offset` elements, . // returning the old start. . // Unsafe because the offset must not exceed `self.len()`. . #[inline(always)] . unsafe fn post_inc_start(&mut self, offset: isize) -> * $raw_mut T { . if mem::size_of::() == 0 { . zst_shrink!(self, offset); . self.ptr.as_ptr() . } else { . let old = self.ptr.as_ptr(); . // SAFETY: the caller guarantees that `offset` doesn't exceed `self.len()`, . // so this new pointer is inside `self` and thus guaranteed to be non-null. 53,873 ( 0.06%) 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 { 691 ( 0.00%) len!(self) . } . . #[inline(always)] . fn is_empty(&self) -> bool { . is_empty!(self) . } . } . -- line 128 ---------------------------------------- -- line 134 ---------------------------------------- . fn next(&mut self) -> Option<$elem> { . // could be implemented with slices, but this avoids bounds checks . . // SAFETY: `assume` calls are safe since a slice's start pointer . // must be non-null, and slices over non-ZSTs must also have a . // non-null end pointer. The call to `next_unchecked!` is safe . // since we check if the iterator is empty first. . unsafe { 1,429 ( 0.00%) assume(!self.ptr.as_ptr().is_null()); . if mem::size_of::() != 0 { 10,083 ( 0.01%) assume(!self.end.is_null()); . } 1,991,764 ( 2.17%) if is_empty!(self) { . None . } else { . Some(next_unchecked!(self)) . } . } . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 6,238 ( 0.01%) let exact = len!(self); . (exact, Some(exact)) . } . . #[inline] . fn count(self) -> usize { . len!(self) . } . . #[inline] . fn nth(&mut self, n: usize) -> Option<$elem> { 54 ( 0.00%) if n >= len!(self) { . // This iterator is now empty. . if mem::size_of::() == 0 { . // We have to do it this way as `ptr` may never be 0, but `end` . // could be (due to wrapping). . self.end = self.ptr.as_ptr(); . } else { . // SAFETY: end can't be 0 if T isn't ZST because ptr isn't 0 and end >= ptr . unsafe { -- line 175 ---------------------------------------- -- line 203 ---------------------------------------- . // faster to compile. . #[inline] . fn for_each(mut self, mut f: F) . where . Self: Sized, . F: FnMut(Self::Item), . { . while let Some(x) = self.next() { 15 ( 0.00%) f(x); . } . } . . // We override the default implementation, which uses `try_fold`, . // because this simple implementation generates less LLVM IR and is . // faster to compile. . #[inline] . fn all(&mut self, mut f: F) -> bool . where . Self: Sized, . F: FnMut(Self::Item) -> bool, . { . while let Some(x) = self.next() { 1,034 ( 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, . { 3,056 ( 0.00%) while let Some(x) = self.next() { 7,691 ( 0.01%) 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, . { 106 ( 0.00%) while let Some(x) = self.next() { 1,763 ( 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, . { 279 ( 0.00%) while let Some(x) = self.next() { 2,406 ( 0.00%) if let Some(y) = f(x) { 168 ( 0.00%) return Some(y); . } . } . None 135 ( 0.00%) } . . // We override the default implementation, which uses `try_fold`, . // because this simple implementation generates less LLVM IR and is . // faster to compile. Also, the `assume` avoids a bounds check. . #[inline] . #[rustc_inherit_overflow_checks] . fn position

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

(&mut self, mut predicate: P) -> Option where . P: FnMut(Self::Item) -> bool, . Self: Sized + ExactSizeIterator + DoubleEndedIterator . { . let n = len!(self); . let mut i = n; 640 ( 0.00%) while let Some(x) = self.next_back() { 10,782 ( 0.01%) i -= 1; 9,578 ( 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 332 ---------------------------------------- . // the returned references is guaranteed to refer to an element . // of the slice and thus guaranteed to be valid. . // . // Also note that the caller also guarantees that we're never . // called with the same index again, and that no other methods . // that will access this subslice are called, so it is valid . // for the returned reference to be mutable in the case of . // `IterMut` 182 ( 0.00%) unsafe { & $( $mut_ )? * self.ptr.as_ptr().add(idx) } . } . . $($extra)* . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl<'a, T> DoubleEndedIterator for $name<'a, T> { . #[inline] -- line 348 ---------------------------------------- -- line 351 ---------------------------------------- . . // SAFETY: `assume` calls are safe since a slice's start pointer must be non-null, . // and slices over non-ZSTs must also have a non-null end pointer. . // The call to `next_back_unchecked!` is safe since we check if the iterator is . // empty first. . unsafe { . assume(!self.ptr.as_ptr().is_null()); . if mem::size_of::() != 0 { 4 ( 0.00%) assume(!self.end.is_null()); . } 13,424 ( 0.01%) if is_empty!(self) { . None . } else { . Some(next_back_unchecked!(self)) . } . } . } . . #[inline] -- line 369 ---------------------------------------- 176,044 ( 0.19%) -------------------------------------------------------------------------------- -- 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 { 45,258 ( 0.05%) 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)); 3,605 ( 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::()); 285,146 ( 0.31%) 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" . ); . 3,424 ( 0.00%) self.stride += Group::WIDTH; 3,424 ( 0.00%) self.pos += self.stride; 2,882 ( 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. 3,106 ( 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. 6,235 ( 0.01%) return Some(if cap < 4 { 4 } else { 8 }); . } . . // Otherwise require 1/8 buckets to be empty (87.5% load) . // . // Be careful when modifying this, calculate_layout relies on the . // overflow check here. 1,836 ( 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 { 7,183 ( 0.01%) if bucket_mask < 8 { . // For tables with 1/2/4/8 buckets, we always reserve one empty slot. . // Keep in mind that the bucket mask is one less than the bucket count. . bucket_mask . } else { . // For larger tables we reserve 12.5% of the slots as empty. 2,388 ( 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 = 7,109 ( 0.01%) size.checked_mul(buckets)?.checked_add(ctrl_align - 1)? & !(ctrl_align - 1); 8,921 ( 0.01%) let len = ctrl_offset.checked_add(buckets + Group::WIDTH)?; . . Some(( . unsafe { Layout::from_size_align_unchecked(len, ctrl_align) }, . ctrl_offset, . )) . } . } . -- line 263 ---------------------------------------- -- line 337 ---------------------------------------- . } . } . #[cfg_attr(feature = "inline-more", inline)] . pub unsafe fn drop(&self) { . self.as_ptr().drop_in_place(); . } . #[inline] . pub unsafe fn read(&self) -> T { 10 ( 0.00%) self.as_ptr().read() . } . #[inline] . pub unsafe fn write(&self, val: T) { . self.as_ptr().write(val); . } . #[inline] . pub unsafe fn as_ref<'a>(&self) -> &'a T { . &*self.as_ptr() -- line 353 ---------------------------------------- -- line 422 ---------------------------------------- . /// Creates a new empty hash table without allocating any memory, using the . /// given allocator. . /// . /// In effect this returns a table with exactly 1 bucket. However we can . /// leave the data pointer dangling since that bucket is never written to . /// due to our load factor forcing us to always have at least 1 free bucket. . #[inline] . pub fn new_in(alloc: A) -> Self { 9 ( 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 458 ---------------------------------------- . /// Attempts to allocate a new hash table with at least enough capacity . /// for inserting the given number of elements without reallocating. . fn fallible_with_capacity( . alloc: A, . capacity: usize, . fallibility: Fallibility, . ) -> Result { . Ok(Self { 136 ( 0.00%) table: RawTableInner::fallible_with_capacity( . alloc, . TableLayout::new::(), . capacity, . fallibility, . )?, . marker: PhantomData, . }) . } -- line 474 ---------------------------------------- -- line 527 ---------------------------------------- . debug_assert_ne!(self.table.bucket_mask, 0); . debug_assert!(index < self.buckets()); . Bucket::from_base_index(self.data_end(), index) . } . . /// Erases an element from the table without dropping it. . #[cfg_attr(feature = "inline-more", inline)] . #[deprecated(since = "0.8.1", note = "use erase or remove instead")] 87 ( 0.00%) pub unsafe fn erase_no_drop(&mut self, item: &Bucket) { 87 ( 0.00%) let index = self.bucket_index(item); . self.table.erase(index); 174 ( 0.00%) } . . /// Erases an element from the table, dropping it in place. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::needless_pass_by_value)] . #[allow(deprecated)] . pub unsafe fn erase(&mut self, item: Bucket) { . // Erase the element from the table first since drop might panic. 28 ( 0.00%) self.erase_no_drop(&item); . item.drop(); . } . . /// Finds and erases an element from the table, dropping it in place. . /// Returns true if an element was found. . #[cfg(feature = "raw")] . #[cfg_attr(feature = "inline-more", inline)] . pub fn erase_entry(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> bool { -- line 554 ---------------------------------------- -- line 563 ---------------------------------------- . } . } . . /// Removes an element from the table, returning it. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::needless_pass_by_value)] . #[allow(deprecated)] . pub unsafe fn remove(&mut self, item: Bucket) -> T { 146 ( 0.00%) self.erase_no_drop(&item); . item.read() . } . . /// Finds and removes an element from the table, returning it. . #[cfg_attr(feature = "inline-more", inline)] 7,685 ( 0.01%) pub fn remove_entry(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option { . // Avoid `Option::map` because it bloats LLVM IR. 32 ( 0.00%) match self.find(hash, eq) { 28 ( 0.00%) Some(bucket) => Some(unsafe { self.remove(bucket) }), 1,076 ( 0.00%) None => None, . } 12,283 ( 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) { 372 ( 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) { 7,780 ( 0.01%) if additional > self.table.growth_left { . // Avoid `Result::unwrap_or_else` because it bloats LLVM IR. 5,492 ( 0.01%) if self . .reserve_rehash(additional, hasher, Fallibility::Infallible) . .is_err() . { . unsafe { hint::unreachable_unchecked() } . } . } . } . -- line 660 ---------------------------------------- -- line 671 ---------------------------------------- . } else { . Ok(()) . } . } . . /// Out-of-line slow path for `reserve` and `try_reserve`. . #[cold] . #[inline(never)] 12,521 ( 0.01%) fn reserve_rehash( . &mut self, . additional: usize, . hasher: impl Fn(&T) -> u64, . fallibility: Fallibility, . ) -> Result<(), TryReserveError> { . unsafe { . self.table.reserve_rehash_inner( . additional, -- line 687 ---------------------------------------- -- line 690 ---------------------------------------- . TableLayout::new::(), . if mem::needs_drop::() { . Some(mem::transmute(ptr::drop_in_place:: as unsafe fn(*mut T))) . } else { . None . }, . ) . } 7,896 ( 0.01%) } . . /// Allocates a new table of a different size and moves the contents of the . /// current table into it. . fn resize( . &mut self, . capacity: usize, . hasher: impl Fn(&T) -> u64, . fallibility: Fallibility, -- line 706 ---------------------------------------- -- line 714 ---------------------------------------- . ) . } . } . . /// Inserts a new element into the table, and returns its raw bucket. . /// . /// This does not check if the given element already exists in the table. . #[cfg_attr(feature = "inline-more", inline)] 90,020 ( 0.10%) 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. 136 ( 0.00%) let old_ctrl = *self.table.ctrl(index); 48,432 ( 0.05%) if unlikely(self.table.growth_left == 0 && special_is_empty(old_ctrl)) { . self.reserve(1, hasher); . index = self.table.find_insert_slot(hash); . } . . self.table.record_item_insert_at(index, old_ctrl, hash); . . let bucket = self.bucket(index); 4 ( 0.00%) bucket.write(value); . bucket . } 66,420 ( 0.07%) } . . /// Attempts to insert a new element without growing the table and return its raw bucket. . /// . /// Returns an `Err` containing the given element if inserting it would require growing the . /// table. . /// . /// This does not check if the given element already exists in the table. . #[cfg(feature = "raw")] -- line 749 ---------------------------------------- -- line 760 ---------------------------------------- . } . } . } . . /// Inserts a new element into the table, and returns a mutable reference to it. . /// . /// This does not check if the given element already exists in the table. . #[cfg_attr(feature = "inline-more", inline)] 9,368 ( 0.01%) 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() } 7,026 ( 0.01%) } . . /// Inserts a new element into the table, without growing the table. . /// . /// There must be enough space in the table to insert the new element. . /// . /// This does not check if the given element already exists in the table. . #[cfg_attr(feature = "inline-more", inline)] . #[cfg(any(feature = "raw", feature = "rustc-internal-api"))] 19 ( 0.00%) pub unsafe fn insert_no_grow(&mut self, hash: u64, value: T) -> Bucket { 10,625 ( 0.01%) let (index, old_ctrl) = self.table.prepare_insert_slot(hash); 447 ( 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. 21,352 ( 0.02%) self.table.growth_left -= special_is_empty(old_ctrl) as usize; . . bucket.write(value); 17,796 ( 0.02%) self.table.items += 1; . bucket 24 ( 0.00%) } . . /// Temporary removes a bucket, applying the given function to the removed . /// element and optionally put back the returned value in the same bucket. . /// . /// Returns `true` if the bucket still contains an element . /// . /// This does not check if the given bucket is actually occupied. . #[cfg_attr(feature = "inline-more", inline)] -- line 798 ---------------------------------------- -- line 813 ---------------------------------------- . true . } else { . false . } . } . . /// Searches for an element in the table. . #[inline] 16 ( 0.00%) pub fn find(&self, hash: u64, mut eq: impl FnMut(&T) -> bool) -> Option> { 26 ( 0.00%) let result = self.table.find_inner(hash, &mut |index| unsafe { 292 ( 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, . } 16 ( 0.00%) } . . /// Gets a reference to an element in the table. . #[inline] . pub fn get(&self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option<&T> { . // Avoid `Option::map` because it bloats LLVM IR. 925 ( 0.00%) match self.find(hash, eq) { . Some(bucket) => Some(unsafe { bucket.as_ref() }), . None => None, . } . } . . /// Gets a mutable reference to an element in the table. . #[inline] . pub fn get_mut(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option<&mut T> { . // Avoid `Option::map` because it bloats LLVM IR. 10 ( 0.00%) match self.find(hash, eq) { . Some(bucket) => Some(unsafe { bucket.as_mut() }), . None => None, . } . } . . /// Attempts to get mutable references to `N` entries in the table at once. . /// . /// Returns an array of length `N` with the results of each query. -- line 855 ---------------------------------------- -- line 920 ---------------------------------------- . #[inline] . pub fn len(&self) -> usize { . self.table.items . } . . /// Returns `true` if the table contains no elements. . #[inline] . pub fn is_empty(&self) -> bool { 19,606 ( 0.02%) 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,084 ( 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(); 208 ( 0.00%) let allocation = self.into_allocation(); 156 ( 0.00%) RawIntoIter { 260 ( 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)> { 74 ( 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(( 23 ( 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 { 9,008 ( 0.01%) Self { . // Be careful to cast the entire slice to a raw pointer. . ctrl: unsafe { NonNull::new_unchecked(Group::static_empty() as *const _ as *mut u8) }, . bucket_mask: 0, . items: 0, . growth_left: 0, . alloc, . } . } . } . . impl RawTableInner { . #[cfg_attr(feature = "inline-more", inline)] 11,623 ( 0.01%) unsafe fn new_uninitialized( . alloc: A, . table_layout: TableLayout, . buckets: usize, . fallibility: Fallibility, . ) -> Result { . debug_assert!(buckets.is_power_of_two()); . . // Avoid `Option::ok_or_else` because it bloats LLVM IR. -- line 1071 ---------------------------------------- -- line 1078 ---------------------------------------- . // exceed `isize::MAX`. We can skip this check on 64-bit systems since . // such allocations will never succeed anyways. . // . // This mirrors what Vec does in the standard library. . if mem::size_of::() < 8 && layout.size() > isize::MAX as usize { . return Err(fallibility.capacity_overflow()); . } . 2,912 ( 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)); 7,428 ( 0.01%) Ok(Self { . ctrl, 2,793 ( 0.00%) bucket_mask: buckets - 1, . items: 0, . growth_left: bucket_mask_to_capacity(buckets - 1), . alloc, . }) 8,574 ( 0.01%) } . . #[inline] 932 ( 0.00%) fn fallible_with_capacity( . alloc: A, . table_layout: TableLayout, . capacity: usize, . fallibility: Fallibility, . ) -> Result { 236 ( 0.00%) if capacity == 0 { 36 ( 0.00%) Ok(Self::new_in(alloc)) . } else { . unsafe { . let buckets = . capacity_to_buckets(capacity).ok_or_else(|| fallibility.capacity_overflow())?; . 5,511 ( 0.01%) let result = Self::new_uninitialized(alloc, table_layout, buckets, fallibility)?; . result.ctrl(0).write_bytes(EMPTY, result.num_ctrl_bytes()); . 660 ( 0.00%) Ok(result) . } . } 932 ( 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] 3,599 ( 0.00%) unsafe fn prepare_insert_slot(&self, hash: u64) -> (usize, u8) { . let index = self.find_insert_slot(hash); 3,599 ( 0.00%) let old_ctrl = *self.ctrl(index); . self.set_ctrl_h2(index, hash); . (index, old_ctrl) 7,198 ( 0.01%) } . . /// Searches for an empty or deleted bucket which is suitable for inserting . /// a new element. . /// . /// There must be at least 1 empty bucket in the table. . #[inline] . fn find_insert_slot(&self, hash: u64) -> usize { . let mut probe_seq = self.probe_seq(hash); . loop { . unsafe { . let group = Group::load(self.ctrl(probe_seq.pos)); 30,093 ( 0.03%) if let Some(bit) = group.match_empty_or_deleted().lowest_set_bit() { 88,654 ( 0.10%) 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). 41,657 ( 0.05%) if unlikely(is_full(*self.ctrl(result))) { . debug_assert!(self.bucket_mask < Group::WIDTH); . debug_assert_ne!(probe_seq.pos, 0); . return Group::load_aligned(self.ctrl(0)) . .match_empty_or_deleted() . .lowest_set_bit_nonzero(); . } . . return result; -- line 1165 ---------------------------------------- -- line 1171 ---------------------------------------- . . /// Searches for an element in the table. This uses dynamic dispatch to reduce the amount of . /// code generated, but it is eliminated by LLVM optimizations. . #[inline] . fn find_inner(&self, hash: u64, eq: &mut dyn FnMut(usize) -> bool) -> Option { . let h2_hash = h2(hash); . let mut probe_seq = self.probe_seq(hash); . 704 ( 0.00%) loop { . let group = unsafe { Group::load(self.ctrl(probe_seq.pos)) }; . 60,530 ( 0.07%) for bit in group.match_byte(h2_hash) { 87,415 ( 0.10%) let index = (probe_seq.pos + bit) & self.bucket_mask; . 56,396 ( 0.06%) if likely(eq(index)) { . return Some(index); . } . } . 22,845 ( 0.02%) 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(); 102,064 ( 0.11%) 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 { 448,544 ( 0.49%) 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) { 60,530 ( 0.07%) self.growth_left -= special_is_empty(old_ctrl) as usize; . self.set_ctrl_h2(index, hash); 48,424 ( 0.05%) self.items += 1; . } . . #[inline] . fn is_in_same_group(&self, i: usize, new_i: usize, hash: u64) -> bool { . let probe_seq_pos = self.probe_seq(hash).pos; . let probe_index = . |pos: usize| (pos.wrapping_sub(probe_seq_pos) & self.bucket_mask) / Group::WIDTH; . probe_index(i) == probe_index(new_i) -- line 1281 ---------------------------------------- -- line 1312 ---------------------------------------- . // replicate the buckets at the end of the trailing group. For example . // with 2 buckets and a group size of 4, the control bytes will look . // like this: . // . // Real | Replicated . // --------------------------------------------- . // | [A] | [B] | [EMPTY] | [EMPTY] | [A] | [B] | . // --------------------------------------------- 85,407 ( 0.09%) let index2 = ((index.wrapping_sub(Group::WIDTH)) & self.bucket_mask) + Group::WIDTH; . 28,469 ( 0.03%) *self.ctrl(index) = ctrl; 28,721 ( 0.03%) *self.ctrl(index2) = ctrl; . } . . /// Returns a pointer to a control byte. . #[inline] . unsafe fn ctrl(&self, index: usize) -> *mut u8 { . debug_assert!(index < self.num_ctrl_bytes()); . self.ctrl.as_ptr().add(index) . } . . #[inline] . fn buckets(&self) -> usize { 5,221 ( 0.01%) self.bucket_mask + 1 . } . . #[inline] . fn num_ctrl_bytes(&self) -> usize { 6,275 ( 0.01%) self.bucket_mask + 1 + Group::WIDTH . } . . #[inline] . fn is_empty_singleton(&self) -> bool { 19,064 ( 0.02%) self.bucket_mask == 0 . } . . #[allow(clippy::mut_mut)] . #[inline] . unsafe fn prepare_resize( . &self, . table_layout: TableLayout, . capacity: usize, . fallibility: Fallibility, . ) -> Result, TryReserveError> { . debug_assert!(self.items <= capacity); . . // Allocate and initialize the new table. 249 ( 0.00%) let mut new_table = RawTableInner::fallible_with_capacity( . self.alloc.clone(), . table_layout, . capacity, . fallibility, . )?; 3,349 ( 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_| { 1,526 ( 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. 3,053 ( 0.00%) let new_items = match self.items.checked_add(additional) { . Some(new_items) => new_items, . None => return Err(fallibility.capacity_overflow()), . }; 3,052 ( 0.00%) let full_capacity = bucket_mask_to_capacity(self.bucket_mask); 6,516 ( 0.01%) if new_items <= full_capacity / 2 { . // Rehash in-place without re-allocating if we have plenty of spare . // capacity that is locked up due to DELETED entries. . self.rehash_in_place(hasher, layout.size, drop); . Ok(()) . } else { . // Otherwise, conservatively resize to at least the next size up . // to avoid churning deletes into frequent rehashes. . self.resize_inner( 1,526 ( 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> { 622 ( 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() { 15,707 ( 0.02%) if !is_full(*self.ctrl(i)) { . continue; . } . . // This may panic. . let hash = hasher(self, i); . . // We can use a simpler version of insert() here since: . // - there are no DELETED entries. -- line 1444 ---------------------------------------- -- line 1454 ---------------------------------------- . } . . // We successfully copied all elements without panicking. Now replace . // self with the new table. The old table will have its memory freed but . // the items will not be dropped (since they have been moved into the . // new table). . mem::swap(self, &mut new_table); . 1,526 ( 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( 935 ( 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) { 33 ( 0.00%) if !self.is_empty_singleton() { . unsafe { . self.ctrl(0).write_bytes(EMPTY, self.num_ctrl_bytes()); . } . } 58 ( 0.00%) self.items = 0; 33 ( 0.00%) self.growth_left = bucket_mask_to_capacity(self.bucket_mask); . } . . #[inline] . unsafe fn erase(&mut self, index: usize) { . debug_assert!(is_full(*self.ctrl(index))); 1,990 ( 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. 7,960 ( 0.01%) let ctrl = if empty_before.leading_zeros() + empty_after.trailing_zeros() >= Group::WIDTH { . DELETED . } else { 9,950 ( 0.01%) self.growth_left += 1; . EMPTY . }; . self.set_ctrl(index, ctrl); 7,960 ( 0.01%) self.items -= 1; . } . } . . impl Clone for RawTable { 40 ( 0.00%) fn clone(&self) -> Self { 5 ( 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) . } . } 45 ( 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)] 14,502 ( 0.02%) fn drop(&mut self) { 7,902 ( 0.01%) if !self.table.is_empty_singleton() { . unsafe { . self.drop_elements(); . self.free_buckets(); . } . } 15,210 ( 0.02%) } . } . #[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)] 208 ( 0.00%) fn into_iter(self) -> RawIntoIter { . unsafe { . let iter = self.iter(); . self.into_iter_from(iter) . } 260 ( 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 { 5,113 ( 0.01%) if let Some(index) = self.current_group.lowest_set_bit() { 294 ( 0.00%) self.current_group = self.current_group.remove_lowest_bit(); 539 ( 0.00%) return Some(self.data.next_n(index)); . } . 2,825 ( 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). 46 ( 0.00%) self.current_group = Group::load_aligned(self.next_ctrl).match_full(); 16 ( 0.00%) self.data = self.data.next_n(Group::WIDTH); 86 ( 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) { 72 ( 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)] 451 ( 0.00%) fn next(&mut self) -> Option> { 3,556 ( 0.00%) if let Some(b) = self.iter.next() { 7,552 ( 0.01%) self.items -= 1; . Some(b) . } else { . // We don't check against items == 0 here to allow the . // compiler to optimize away the item count entirely if the . // iterator length is never queried. . debug_assert_eq!(self.items, 0); . None . } 902 ( 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)] 156 ( 0.00%) fn drop(&mut self) { . unsafe { . // Drop all remaining elements . self.iter.drop_elements(); . . // Free the table 333 ( 0.00%) if let Some((ptr, layout)) = self.allocation { . self.alloc.deallocate(ptr, layout); . } . } 34 ( 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)] 16 ( 0.00%) fn next(&mut self) -> Option { 6 ( 0.00%) unsafe { Some(self.iter.next()?.read()) } 33 ( 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 ---------------------------------------- 210,865 ( 0.23%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs -------------------------------------------------------------------------------- Ir -- line 357 ---------------------------------------- . /// . /// ``` . /// use std::rc::Rc; . /// . /// let five = Rc::new(5); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] 48 ( 0.00%) pub fn new(value: T) -> Rc { . // There is an implicit weak pointer owned by all the strong . // pointers, which ensures that the weak destructor never frees . // the allocation while the strong destructor is running, even . // if the weak pointer is stored inside the strong one. . unsafe { . Self::from_inner( 36,948 ( 0.04%) Box::leak(box RcBox { strong: Cell::new(1), weak: Cell::new(1), value }).into(), . ) . } 48 ( 0.00%) } . . /// Constructs a new `Rc` using a closure `data_fn` that has access to a . /// weak reference to the constructing `Rc`. . /// . /// Generally, a structure circularly referencing itself, either directly or . /// indirectly, should not hold a strong reference to prevent a memory leak. . /// In `data_fn`, initialization of `T` can make use of the weak reference . /// by cloning and storing it inside `T` for use at a later time. -- line 383 ---------------------------------------- -- line 637 ---------------------------------------- . /// . /// let x = Rc::new(4); . /// let _y = Rc::clone(&x); . /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4); . /// ``` . #[inline] . #[stable(feature = "rc_unique", since = "1.4.0")] . pub fn try_unwrap(this: Self) -> Result { 2 ( 0.00%) if Rc::strong_count(&this) == 1 { . unsafe { . let val = ptr::read(&*this); // copy the contained object . . // Indicate to Weaks that they can't be promoted by decrementing . // the strong count, and then remove the implicit "strong weak" . // pointer while also handling drop logic by just crafting a . // fake Weak. . this.inner().dec_strong(); -- line 653 ---------------------------------------- -- line 931 ---------------------------------------- . /// let five = Rc::new(5); . /// let _weak_five = Rc::downgrade(&five); . /// . /// assert_eq!(1, Rc::weak_count(&five)); . /// ``` . #[inline] . #[stable(feature = "rc_counts", since = "1.15.0")] . pub fn weak_count(this: &Self) -> usize { 315 ( 0.00%) this.inner().weak() - 1 . } . . /// Gets the number of strong (`Rc`) pointers to this allocation. . /// . /// # Examples . /// . /// ``` . /// use std::rc::Rc; -- line 947 ---------------------------------------- -- line 1023 ---------------------------------------- . pub unsafe fn decrement_strong_count(ptr: *const T) { . unsafe { mem::drop(Rc::from_raw(ptr)) }; . } . . /// Returns `true` if there are no other `Rc` or [`Weak`] pointers to . /// this allocation. . #[inline] . fn is_unique(this: &Self) -> bool { 3 ( 0.00%) Rc::weak_count(this) == 0 && Rc::strong_count(this) == 1 . } . . /// Returns a mutable reference into the given `Rc`, if there are . /// no other `Rc` or [`Weak`] pointers to the same allocation. . /// . /// Returns [`None`] otherwise, because it is not safe to . /// mutate a shared value. . /// -- line 1039 ---------------------------------------- -- line 1053 ---------------------------------------- . /// assert_eq!(*x, 4); . /// . /// let _y = Rc::clone(&x); . /// assert!(Rc::get_mut(&mut x).is_none()); . /// ``` . #[inline] . #[stable(feature = "rc_unique", since = "1.4.0")] . pub fn get_mut(this: &mut Self) -> Option<&mut T> { 1 ( 0.00%) if Rc::is_unique(this) { unsafe { Some(Rc::get_mut_unchecked(this)) } } else { None } . } . . /// Returns a mutable reference into the given `Rc`, . /// without any check. . /// . /// See also [`get_mut`], which is safe and does appropriate checks. . /// . /// [`get_mut`]: Rc::get_mut -- line 1069 ---------------------------------------- -- line 1088 ---------------------------------------- . /// } . /// assert_eq!(*x, "foo"); . /// ``` . #[inline] . #[unstable(feature = "get_mut_unchecked", issue = "63292")] . pub unsafe fn get_mut_unchecked(this: &mut Self) -> &mut T { . // We are careful to *not* create a reference covering the "count" fields, as . // this would conflict with accesses to the reference counts (e.g. by `Weak`). 1,958 ( 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")] 1,010 ( 0.00%) pub fn make_mut(this: &mut Self) -> &mut T { 606 ( 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. 101 ( 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()); 202 ( 0.00%) *this = rc.assume_init(); . } 208 ( 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. 205 ( 0.00%) unsafe { &mut this.ptr.as_mut().value } 1,212 ( 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))] 92 ( 0.00%) unsafe fn copy_from_slice(v: &[T]) -> Rc<[T]> { . unsafe { . let ptr = Self::allocate_for_slice(v.len()); 18 ( 0.00%) ptr::copy_nonoverlapping(v.as_ptr(), &mut (*ptr).value as *mut [T] as *mut T, v.len()); . Self::from_ptr(ptr) . } 120 ( 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 { 24,971 ( 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!" . /// ``` 140,814 ( 0.15%) fn drop(&mut self) { . unsafe { 33,381 ( 0.04%) self.inner().dec_strong(); 67,720 ( 0.07%) if self.inner().strong() == 0 { . // destroy the contained object 609 ( 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(); . 6,828 ( 0.01%) if self.inner().weak() == 0 { 15 ( 0.00%) Global.deallocate(self.ptr.cast(), Layout::for_value(self.ptr.as_ref())); . } . } . } 156,868 ( 0.17%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Clone for Rc { . /// Makes a clone of the `Rc` pointer. . /// . /// This creates another pointer to the same allocation, increasing the . /// strong reference count. -- line 1495 ---------------------------------------- -- line 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 { 20 ( 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) { 30,078 ( 0.03%) 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. 90,544 ( 0.10%) if strong == 0 || strong == usize::MAX { . abort(); . } 88 ( 0.00%) self.strong_ref().set(strong + 1); . } . . #[inline] . fn dec_strong(&self) { 102,401 ( 0.11%) 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) { 10,257 ( 0.01%) self.weak_ref().set(self.weak() - 1); . } . } . . impl RcInnerPtr for RcBox { . #[inline(always)] . fn weak_ref(&self) -> &Cell { . &self.weak . } -- line 2523 ---------------------------------------- 2,907 ( 0.00%) -------------------------------------------------------------------------------- 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/strcmp.S -------------------------------------------------------------------------------- Ir -------------------------------------------------------------------------------- 36,683,557 (40.04%) events annotated