-------------------------------------------------------------------------------- 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 web_sys --edition=2018 src/lib.rs --error-format=json --json=diagnostic-rendered-ansi,artifacts,future-incompat --crate-type lib --emit=dep-info,metadata,link -C embed-bitcode=no -C debuginfo=2 -C metadata=624730c0734639ae -C extra-filename=-624730c0734639ae --out-dir /usr/home/liquid/tmp/.tmpEbjOya/target/debug/deps -L dependency=/usr/home/liquid/tmp/.tmpEbjOya/target/debug/deps --extern js_sys=/usr/home/liquid/tmp/.tmpEbjOya/target/debug/deps/libjs_sys-18ed9659890a73d6.rmeta --extern wasm_bindgen=/usr/home/liquid/tmp/.tmpEbjOya/target/debug/deps/libwasm_bindgen-257a3b187db57b05.rmeta -Adeprecated -Aunknown-lints -Zincremental-verify-ich Data file: results/cgout-w-profiling-web-sys-0.3.56-Debug-Full Events recorded: Ir Events shown: Ir Event sort order: Ir Thresholds: 0.1 Include dirs: User annotated: Auto-annotation: on -------------------------------------------------------------------------------- Ir -------------------------------------------------------------------------------- 175,699,982 (100.0%) PROGRAM TOTALS -------------------------------------------------------------------------------- Ir file:function -------------------------------------------------------------------------------- 10,308,016 ( 5.87%) ./elf/dl-lookup.c:_dl_lookup_symbol_x 7,892,384 ( 4.49%) ./malloc/malloc.c:_int_free 7,888,737 ( 4.49%) ./malloc/malloc.c:_int_malloc 5,415,008 ( 3.08%) ./malloc/malloc.c:malloc 4,842,276 ( 2.76%) ./elf/dl-lookup.c:do_lookup_x 4,482,124 ( 2.55%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/mod.rs:::next_token 4,141,271 ( 2.36%) ./elf/../sysdeps/x86_64/dl-machine.h:_dl_relocate_object 3,435,327 ( 1.96%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::next 3,248,421 ( 1.85%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::bump 3,017,586 ( 1.72%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/tokentrees.rs:::parse_token_tree 2,924,879 ( 1.66%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lexer/src/lib.rs:::advance_token 2,793,830 ( 1.59%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_serialize/src/opaque.rs:>::decode 2,475,668 ( 1.41%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:>::decode 2,370,039 ( 1.35%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/tokenstream.rs:::next_with_spacing 2,328,030 ( 1.33%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:>::decode 2,280,674 ( 1.30%) ./malloc/malloc.c:free 2,139,033 ( 1.22%) ./elf/do-rel.h:_dl_relocate_object 1,822,605 ( 1.04%) ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:__memcpy_avx_unaligned_erms 1,774,350 ( 1.01%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lexer/src/unescape.rs:rustc_lexer::unescape::unescape_literal::<::validate_literal_escape::{closure#0}> 1,485,810 ( 0.85%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lexer/src/unescape.rs:rustc_lexer::unescape::scan_escape 1,485,550 ( 0.85%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::bump_with 1,412,595 ( 0.80%) ???:SetImpliedBits(llvm::FeatureBitset&, llvm::FeatureBitset const&, llvm::ArrayRef) 1,373,250 ( 0.78%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/md-5-0.9.1/src/utils.rs:md5::utils::compress 1,353,418 ( 0.77%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::check 1,341,401 ( 0.76%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/tokentrees.rs:::push 1,206,057 ( 0.69%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::eq 1,201,136 ( 0.68%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs:md5::utils::compress 1,109,366 ( 0.63%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::is_keyword 1,071,721 ( 0.61%) /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}> 1,067,761 ( 0.61%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:::new_imported_source_file 1,064,836 ( 0.61%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:::new_imported_source_file 1,025,076 ( 0.58%) ./malloc/malloc.c:malloc_consolidate 994,627 ( 0.57%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/str/mod.rs:::next_token 978,810 ( 0.56%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/unicode-xid-0.2.2/src/lib.rs:::eat_while:: 950,752 ( 0.54%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:>::truncate 941,013 ( 0.54%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/mod.rs:::validate_literal_escape::{closure#0} 910,059 ( 0.52%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::clone 865,936 ( 0.49%) ./elf/dl-lookup.c:check_match 864,466 ( 0.49%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:::next_token 837,567 ( 0.48%) ./malloc/malloc.c:unlink_chunk.constprop.0 828,239 ( 0.47%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/span_encoding.rs:::to 817,093 ( 0.47%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::clone 778,908 ( 0.44%) /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}> 756,668 ( 0.43%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:::eat_while:: 745,614 ( 0.42%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/str/traits.rs:::next_token 725,556 ( 0.41%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/str/validations.rs:::eat_while:: 720,861 ( 0.41%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs:> as core::ops::drop::Drop>::drop 710,656 ( 0.40%) /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}> 670,258 ( 0.38%) /usr/home/liquid/rust/worktree-benchmarking/library/std/src/sys/unix/alloc.rs:__rdl_alloc 641,521 ( 0.37%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/rustc-hash-1.1.0/src/lib.rs:<&str as core::hash::Hash>::hash:: 637,123 ( 0.36%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:::to 636,021 ( 0.36%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:>::truncate 628,088 ( 0.36%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:::advance_token 616,742 ( 0.35%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/span_encoding.rs:::next_token 589,883 ( 0.34%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/option.rs:::next_token 586,748 ( 0.33%) ./malloc/malloc.c:realloc 581,937 ( 0.33%) ./string/../sysdeps/x86_64/multiarch/memcmp-avx2-movbe.S:__memcmp_avx2_movbe 570,339 ( 0.32%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::ident 534,798 ( 0.30%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:::bump_with 533,373 ( 0.30%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/item.rs:::parse_item_common 531,992 ( 0.30%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lexer/src/lib.rs:rustc_lexer::first_token 530,737 ( 0.30%) ./string/../sysdeps/x86_64/strcmp.S:strcmp 509,412 ( 0.29%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/path.rs:::parse_path_segment 500,202 ( 0.28%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/attr_wrapper.rs:::parse_attribute 495,240 ( 0.28%) ???:llvm::StringMapImpl::LookupBucketFor(llvm::StringRef) 476,053 ( 0.27%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/raw_vec.rs:alloc::raw_vec::finish_grow:: 462,699 ( 0.26%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:rustc_lexer::unescape::unescape_literal::<::validate_literal_escape::{closure#0}> 458,499 ( 0.26%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:::from_lit_token 397,412 ( 0.23%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lexer/src/cursor.rs:::eat_while:: 386,112 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/str/validations.rs:rustc_parse::lexer::nfc_normalize 386,112 ( 0.22%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/unicode-normalization-0.1.13/src/quick_check.rs:rustc_parse::lexer::nfc_normalize 384,397 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/symbol.rs:::intern 380,760 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:> as core::ops::drop::Drop>::drop 376,381 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/source_map.rs:::new_imported_source_file 373,296 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/path.rs:::parse_path_inner 372,170 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:::push 366,300 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/const_ptr.rs:rustc_parse::lexer::nfc_normalize 364,947 ( 0.21%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:::intern 357,788 ( 0.20%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/rustc_entry.rs:>>::rustc_entry 356,532 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/span_encoding.rs:::bump 356,532 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:::bump_with 353,216 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:>::decode 353,216 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cmp.rs:>::decode 353,216 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/iter/range.rs:>::decode 337,963 ( 0.19%) ./malloc/malloc.c:_int_realloc 330,880 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:::cmp 326,766 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::parse_ident_common 326,676 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/mod.rs:rustc_parse::lexer::nfc_normalize 322,428 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/path.rs:::parse_path_segments 318,555 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/option.rs:::to 317,941 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/attr.rs:::parse_attribute 315,353 ( 0.18%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/unicode-xid-0.2.2/src/lib.rs:::advance_token 312,747 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/attr.rs:::parse_outer_attributes 311,564 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:::check 311,422 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/memchr.rs:core::slice::memchr::memchr_general_case 311,306 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:::push 309,592 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::expect 291,411 ( 0.17%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::rustc_entry 289,904 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::is_import_coupler 288,520 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:rustc_parse::lexer::nfc_normalize 283,808 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/fmt/mod.rs:core::fmt::Formatter::pad 283,256 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/raw_vec.rs:>::reserve_for_push 282,762 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/expand.rs:::flat_map_item 281,249 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/str/validations.rs:::advance_token 280,861 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lint/src/levels.rs:::push 271,598 ( 0.15%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>::insert::>::{closure#0}> 265,996 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lexer/src/cursor.rs:rustc_lexer::first_token 265,613 ( 0.15%) ???:llvm::PassRegistry::enumerateWith(llvm::PassRegistrationListener*) 263,335 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/fmt/mod.rs:core::fmt::write 261,770 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::new 261,612 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lexer/src/lib.rs:::ident_or_unknown_prefix 250,299 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:::next_token 247,635 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/str/validations.rs:rustc_lexer::unescape::unescape_literal::<::validate_literal_escape::{closure#0}> 247,635 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/char/methods.rs:rustc_lexer::unescape::unescape_literal::<::validate_literal_escape::{closure#0}> 240,640 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/span_encoding.rs:::cmp 237,688 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/mem/mod.rs:::bump_with 237,354 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/util/literal.rs:::from_token 233,263 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::parse_token_tree 232,030 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/index.rs:::next_token 230,780 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs:<&str as core::hash::Hash>::hash:: 227,231 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lexer/src/cursor.rs:::advance_token 226,486 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/tokentrees.rs:::parse_all_token_trees 221,269 ( 0.13%) ./stdlib/cxa_finalize.c:__cxa_finalize 217,910 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::new 217,890 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lexer/src/lib.rs:::double_quoted_string 216,090 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/fmt/mod.rs:<&mut W as core::fmt::Write>::write_str 212,797 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/raw_vec.rs:>::reserve_for_push 211,982 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/expr.rs:::parse_opt_lit 210,958 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::glue 209,412 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/str/validations.rs:::double_quoted_string 207,855 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:::parse_token_tree 199,984 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/str/iter.rs:::from_lit_token 199,984 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/str/validations.rs:::from_lit_token 198,108 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/str/validations.rs:rustc_lexer::unescape::scan_escape 194,906 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/analyze_source_file.rs:rustc_span::analyze_source_file::analyze_source_file 191,504 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/std/src/alloc.rs:__rdl_alloc 189,321 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/lint.rs:::get_lint_level 186,672 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lexer/src/lib.rs:::eq 186,516 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/attr.rs:::parse_attr_item 183,176 ( 0.10%) ./malloc/malloc.c:alloc_perturb 181,122 ( 0.10%) ???:llvm::StringMapImpl::RehashTable(unsigned int) 178,694 ( 0.10%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs:>>::insert 178,308 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs: as core::clone::Clone>::clone 178,206 ( 0.10%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:rustc_feature::builtin_attrs::is_builtin_attr_name 178,104 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/attr.rs:::parse_meta_item 178,038 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::parse_mac_args_common -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/mem/mod.rs -------------------------------------------------------------------------------- Ir -- line 326 ---------------------------------------- . /// ``` . #[inline] . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_size_of_val", issue = "46571")] . #[cfg_attr(not(test), rustc_diagnostic_item = "mem_size_of_val")] . pub const fn size_of_val(val: &T) -> usize { . // SAFETY: `val` is a reference, so it's a valid raw pointer 14 ( 0.00%) unsafe { intrinsics::size_of_val(val) } . } . . /// Returns the size of the pointed-to value in bytes. . /// . /// This is usually the same as `size_of::()`. However, when `T` *has* no . /// statically-known size, e.g., a slice [`[T]`][slice] or a [trait object], . /// then `size_of_val_raw` can be used to get the dynamically-known size. . /// -- line 342 ---------------------------------------- -- line 375 ---------------------------------------- . /// assert_eq!(13, unsafe { mem::size_of_val_raw(y) }); . /// ``` . #[inline] . #[must_use] . #[unstable(feature = "layout_for_ptr", issue = "69835")] . #[rustc_const_unstable(feature = "const_size_of_val_raw", issue = "46571")] . pub const unsafe fn size_of_val_raw(val: *const T) -> usize { . // SAFETY: the caller must provide a valid raw pointer 28 ( 0.00%) unsafe { intrinsics::size_of_val(val) } . } . . /// Returns the [ABI]-required minimum alignment of a type. . /// . /// Every reference to a value of the type `T` must be a multiple of this number. . /// . /// This is the alignment used for struct fields. It may be smaller than the preferred alignment. . /// -- line 391 ---------------------------------------- -- line 831 ---------------------------------------- . #[must_use = "if you don't need the old value, you can just assign the new value directly"] . #[rustc_const_unstable(feature = "const_replace", issue = "83164")] . #[cfg_attr(not(test), rustc_diagnostic_item = "mem_replace")] . pub const fn replace(dest: &mut T, src: T) -> T { . // SAFETY: We read from `dest` but directly write `src` into it afterwards, . // such that the old value is not duplicated. Nothing is dropped and . // nothing here can panic. . unsafe { 9,937 ( 0.01%) let result = ptr::read(dest); 411,250 ( 0.23%) ptr::write(dest, src); . result . } . } . . /// Disposes of a value. . /// . /// This does so by calling the argument's implementation of [`Drop`][drop]. . /// -- line 848 ---------------------------------------- -- line 901 ---------------------------------------- . /// . /// println!("x: {}, y: {}", x, y.0); // still available . /// ``` . /// . /// [`RefCell`]: crate::cell::RefCell . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[cfg_attr(not(test), rustc_diagnostic_item = "mem_drop")] 3 ( 0.00%) pub fn drop(_x: T) {} . . /// Interprets `src` as having type `&U`, and then reads `src` without moving . /// the contained value. . /// . /// This function will unsafely assume the pointer `src` is valid for [`size_of::`][size_of] . /// bytes by transmuting `&T` to `&U` and then reading the `&U` (except that this is done in a way . /// that is correct even when `&U` makes stricter alignment requirements than `&T`). It will also . /// unsafely create a copy of the contained value instead of moving out of `src`. -- line 917 ---------------------------------------- -- line 1031 ---------------------------------------- . /// assert_eq!(mem::discriminant(&Foo::A("bar")), mem::discriminant(&Foo::A("baz"))); . /// assert_eq!(mem::discriminant(&Foo::B(1)), mem::discriminant(&Foo::B(2))); . /// assert_ne!(mem::discriminant(&Foo::B(3)), mem::discriminant(&Foo::C(3))); . /// ``` . #[stable(feature = "discriminant_value", since = "1.21.0")] . #[rustc_const_unstable(feature = "const_discriminant", issue = "69821")] . #[cfg_attr(not(test), rustc_diagnostic_item = "mem_discriminant")] . pub const fn discriminant(v: &T) -> Discriminant { 5 ( 0.00%) Discriminant(intrinsics::discriminant_value(v)) . } . . /// Returns the number of variants in the enum type `T`. . /// . /// If `T` is not an enum, calling this function will not result in undefined behavior, but the . /// return value is unspecified. Equally, if `T` is an enum with more variants than `usize::MAX` . /// the return value is unspecified. Uninhabited variants will be counted. . /// -- line 1047 ---------------------------------------- 5,743 ( 0.00%) -------------------------------------------------------------------------------- -- 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 { 598,491 ( 0.34%) Token { kind, len } . } . } . . /// Enum representing common lexeme types. . // perf note: Changing all `usize` to `u32` doesn't change performance. See #77629 155,560 ( 0.09%) #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] . pub enum TokenKind { . // Multi-char tokens: . /// "// comment" . LineComment { doc_style: Option }, . /// `/* block comment */` . /// . /// Block comments can be recursive, so the sequence like `/* /* */` . /// will not be considered terminated and will result in a parsing error. -- line 60 ---------------------------------------- -- line 192 ---------------------------------------- . /// Literal starts with "0x". . Hexadecimal, . /// Literal doesn't contain a prefix. . Decimal, . } . . /// `rustc` allows files to have a shebang, e.g. "#!/usr/bin/rustrun", . /// but shebang isn't a part of rust syntax. 14 ( 0.00%) pub fn strip_shebang(input: &str) -> Option { . // Shebang must start with `#!` literally, without any preceding whitespace. . // For simplicity we consider any line starting with `#!` a shebang, . // regardless of restrictions put on shebangs by specific platforms. . if let Some(input_tail) = input.strip_prefix("#!") { . // Ok, this is a shebang but if the next non-whitespace token is `[`, . // then it may be valid Rust code, so consider it Rust code. . let next_non_whitespace_token = tokenize(input_tail).map(|tok| tok.kind).find(|tok| { . !matches!( -- line 208 ---------------------------------------- -- line 213 ---------------------------------------- . ) . }); . if next_non_whitespace_token != Some(TokenKind::OpenBracket) { . // No other choice than to consider this a shebang. . return Some(2 + input_tail.lines().next().unwrap_or_default().len()); . } . } . None 16 ( 0.00%) } . . /// Parses the first token from the provided input string. 199,497 ( 0.11%) pub fn first_token(input: &str) -> Token { . debug_assert!(!input.is_empty()); 66,499 ( 0.04%) Cursor::new(input).advance_token() 265,996 ( 0.15%) } . . /// 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. . 70,778 ( 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). 5,652 ( 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. 531,992 ( 0.30%) fn advance_token(&mut self) -> Token { . let first_char = self.bump().unwrap(); 240,487 ( 0.14%) let token_kind = match first_char { . // Slash, comment or block comment. 76 ( 0.00%) '/' => match self.first() { . '/' => self.line_comment(), . '*' => self.block_comment(), . _ => Slash, . }, . . // Whitespace sequence. . c if is_whitespace(c) => self.whitespace(), . -- line 313 ---------------------------------------- -- 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. 101,817 ( 0.06%) c @ '0'..='9' => { . let literal_kind = self.number(c); . let suffix_start = self.len_consumed(); . self.eat_literal_suffix(); . TokenKind::Literal { kind: literal_kind, suffix_start } . } . . // One-symbol tokens. 5,654 ( 0.00%) ';' => Semi, . ',' => Comma, 4 ( 0.00%) '.' => Dot, 8,486 ( 0.00%) '(' => OpenParen, 8,486 ( 0.00%) ')' => CloseParen, 2 ( 0.00%) '{' => OpenBrace, 2 ( 0.00%) '}' => CloseBrace, 8,478 ( 0.00%) '[' => OpenBracket, 8,478 ( 0.00%) ']' => CloseBracket, . '@' => At, 8,478 ( 0.00%) '#' => Pound, . '~' => Tilde, . '?' => Question, 5,664 ( 0.00%) ':' => Colon, . '$' => Dollar, 5,652 ( 0.00%) '=' => Eq, 4 ( 0.00%) '!' => Bang, 4 ( 0.00%) '<' => Lt, 6 ( 0.00%) '>' => Gt, 2 ( 0.00%) '-' => Minus, . '&' => And, . '|' => Or, . '+' => Plus, 2,826 ( 0.00%) '*' => Star, . '^' => Caret, . '%' => Percent, . . // Lifetime or character literal. . '\'' => self.lifetime_or_char(), . . // String literal. . '"' => { 8,478 ( 0.00%) let terminated = self.double_quoted_string(); . let suffix_start = self.len_consumed(); 5,652 ( 0.00%) if terminated { . self.eat_literal_suffix(); . } . let kind = Str { terminated }; 5,652 ( 0.00%) Literal { kind, suffix_start } . } . // Identifier starting with an emoji. Only lexed for graceful error recovery. . c if !c.is_ascii() && unic_emoji_char::is_emoji(c) => { . self.fake_ident_or_unknown_prefix() . } . _ => Unknown, . }; . Token::new(token_kind, self.len_consumed()) 598,491 ( 0.34%) } . . fn line_comment(&mut self) -> TokenKind { . debug_assert!(self.prev() == '/' && self.first() == '/'); . self.bump(); . 62 ( 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. 21 ( 0.00%) '/' if self.second() != '/' => Some(DocStyle::Outer), . _ => None, . }; . 850 ( 0.00%) self.eat_while(|c| c != '\n'); 57 ( 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); 16,985 ( 0.01%) 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 . } . 77,780 ( 0.04%) fn ident_or_unknown_prefix(&mut self) -> TokenKind { . debug_assert!(is_id_start(self.prev())); . // Start is already eaten, eat the rest of identifier. 31,112 ( 0.02%) 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. 31,112 ( 0.02%) match self.first() { . '#' | '"' | '\'' => UnknownPrefix, 15,556 ( 0.01%) c if !c.is_ascii() && unic_emoji_char::is_emoji(c) => { . self.fake_ident_or_unknown_prefix() . } 15,556 ( 0.01%) _ => Ident, . } 62,224 ( 0.04%) } . . 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 677 ---------------------------------------- . false . } . . /// Eats double-quoted string and returns true . /// if string is terminated. . fn double_quoted_string(&mut self) -> bool { . debug_assert!(self.prev() == '"'); . while let Some(c) = self.bump() { 209,412 ( 0.12%) match c { . '"' => { . return true; . } . '\\' if self.first() == '\\' || self.first() == '"' => { . // Bump again to skip escaped character. . self.bump(); . } . _ => (), . } . } . // End of file reached. . false 2,826 ( 0.00%) } . . /// Eats the double-quoted string and returns `n_hashes` and an error if encountered. . fn raw_double_quoted_string(&mut self, prefix_len: usize) -> (u16, Option) { . // Wrap the actual function to handle the error with too many hashes. . // This way, it eats the whole raw string. . let (n_hashes, err) = self.raw_string_unvalidated(prefix_len); . // Only up to 65535 `#`s are allowed in raw strings . match u16::try_from(n_hashes) { -- line 706 ---------------------------------------- -- 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) { 5,652 ( 0.00%) self.eat_identifier(); . } . . // Eats the identifier. 8,478 ( 0.00%) fn eat_identifier(&mut self) { . if !is_id_start(self.first()) { . return; . } . self.bump(); . . self.eat_while(is_id_continue); 11,304 ( 0.01%) } . } 742,150 ( 0.42%) -------------------------------------------------------------------------------- -- 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. . /// 66,761 ( 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. . // -- line 71 ---------------------------------------- -- line 86 ---------------------------------------- . impl Span { . #[inline] . pub fn new( . mut lo: BytePos, . mut hi: BytePos, . ctxt: SyntaxContext, . parent: Option, . ) -> Self { 91,866 ( 0.05%) if lo > hi { . std::mem::swap(&mut lo, &mut hi); . } . 183,732 ( 0.10%) let (base, len, ctxt2) = (lo.0, hi.0 - lo.0, ctxt.as_u32()); . 520,368 ( 0.30%) if len <= MAX_LEN && ctxt2 <= MAX_CTXT && parent.is_none() { . // Inline format. . Span { base_or_index: base, len_or_tag: len as u16, ctxt_or_zero: ctxt2 as u16 } . } else { . // Interned format. . let index = 15 ( 0.00%) with_span_interner(|interner| interner.intern(&SpanData { lo, hi, ctxt, parent })); . Span { base_or_index: index, len_or_tag: LEN_TAG, ctxt_or_zero: 0 } . } 219,071 ( 0.12%) } . . #[inline] . pub fn data(self) -> SpanData { . let data = self.data_untracked(); . if let Some(parent) = data.parent { . (*SPAN_TRACK)(parent); . } . data . } . . /// Internal function to translate between an encoded span and the expanded representation. . /// This function must not be used outside the incremental engine. . #[inline] . pub fn data_untracked(self) -> SpanData { 475,387 ( 0.27%) 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), 454,076 ( 0.26%) 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); 2 ( 0.00%) let index = self.base_or_index; 10 ( 0.00%) with_span_interner(|interner| interner.spans[index as usize]) . } 600 ( 0.00%) } . } . 4 ( 0.00%) #[derive(Default)] . pub struct SpanInterner { . spans: FxIndexSet, . } . . impl SpanInterner { 3 ( 0.00%) fn intern(&mut self, span_data: &SpanData) -> u32 { 4 ( 0.00%) let (index, _) = self.spans.insert_full(*span_data); . index as u32 4 ( 0.00%) } . } . . // If an interner exists, return it. Otherwise, prepare a fresh one. . #[inline] . fn with_span_interner T>(f: F) -> T { . crate::with_session_globals(|session_globals| f(&mut *session_globals.span_interner.lock())) . } 395,072 ( 0.22%) -------------------------------------------------------------------------------- -- 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. 267,433 ( 0.15%) 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. 232,211 ( 0.13%) self.ptr = unsafe { NonNull::new_unchecked(self.ptr.as_ptr().offset(offset)) }; . old . } . } . . // Helper function for moving the end of the iterator backwards by `offset` elements, . // returning the new end. . // Unsafe because the offset must not exceed `self.len()`. . #[inline(always)] -- line 101 ---------------------------------------- -- line 102 ---------------------------------------- . unsafe fn pre_dec_end(&mut self, offset: isize) -> * $raw_mut T { . if mem::size_of::() == 0 { . zst_shrink!(self, offset); . self.ptr.as_ptr() . } else { . // SAFETY: the caller guarantees that `offset` doesn't exceed `self.len()`, . // which is guaranteed to not overflow an `isize`. Also, the resulting pointer . // is in bounds of `slice`, which fulfills the other requirements for `offset`. 19 ( 0.00%) self.end = unsafe { self.end.offset(-offset) }; . self.end . } . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl ExactSizeIterator for $name<'_, T> { . #[inline(always)] . fn len(&self) -> usize { 100,362 ( 0.06%) 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 { 2,944 ( 0.00%) assume(!self.ptr.as_ptr().is_null()); . if mem::size_of::() != 0 { 118,859 ( 0.07%) assume(!self.end.is_null()); . } 3,916,448 ( 2.23%) if is_empty!(self) { . None . } else { . Some(next_unchecked!(self)) . } . } . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 392 ( 0.00%) let exact = len!(self); . (exact, Some(exact)) . } . . #[inline] . fn count(self) -> usize { . len!(self) . } . -- line 164 ---------------------------------------- -- line 217 ---------------------------------------- . // faster to compile. . #[inline] . fn all(&mut self, mut f: F) -> bool . where . Self: Sized, . F: FnMut(Self::Item) -> bool, . { . while let Some(x) = self.next() { 2,186 ( 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, . { 24,511 ( 0.01%) while let Some(x) = self.next() { 252,532 ( 0.14%) 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, . { 3 ( 0.00%) while let Some(x) = self.next() { 57,325 ( 0.03%) if predicate(&x) { . return Some(x); . } . } . None 2,320 ( 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, . { 15 ( 0.00%) while let Some(x) = self.next() { 122 ( 0.00%) if let Some(y) = f(x) { . return Some(y); . } . } . None 20 ( 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() { 1,882 ( 0.00%) if predicate(x) { . // SAFETY: we are guaranteed to be in bounds by the loop invariant: . // when `i >= n`, `self.next()` returns `None` and the loop breaks. . unsafe { assume(i < n) }; . return Some(i); . } . i += 1; . } . None -- line 303 ---------------------------------------- -- line 308 ---------------------------------------- . // faster to compile. Also, the `assume` avoids a bounds check. . #[inline] . fn rposition

(&mut self, mut predicate: P) -> Option where . P: FnMut(Self::Item) -> bool, . Self: Sized + ExactSizeIterator + DoubleEndedIterator . { . let n = len!(self); . let mut i = n; 505 ( 0.00%) while let Some(x) = self.next_back() { 9,693 ( 0.01%) i -= 1; 9,405 ( 0.01%) if predicate(x) { . // SAFETY: `i` must be lower than `n` since it starts at `n` . // and is only decreasing. . unsafe { assume(i < n) }; . return Some(i); . } . } . None . } -- line 326 ---------------------------------------- -- line 351 ---------------------------------------- . . // SAFETY: `assume` calls are safe since a slice's start pointer must be non-null, . // and slices over non-ZSTs must also have a non-null end pointer. . // The call to `next_back_unchecked!` is safe since we check if the iterator is . // empty first. . unsafe { . assume(!self.ptr.as_ptr().is_null()); . if mem::size_of::() != 0 { 20 ( 0.00%) assume(!self.end.is_null()); . } 6,957 ( 0.00%) if is_empty!(self) { . None . } else { . Some(next_back_unchecked!(self)) . } . } . } . . #[inline] -- line 369 ---------------------------------------- 502,506 ( 0.29%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/path.rs -------------------------------------------------------------------------------- Ir -- line 11 ---------------------------------------- . use rustc_errors::{pluralize, Applicability, PResult}; . use rustc_span::source_map::{BytePos, Span}; . use rustc_span::symbol::{kw, sym, Ident}; . . use std::mem; . use tracing::debug; . . /// Specifies how to parse a path. 1 ( 0.00%) #[derive(Copy, Clone, PartialEq)] . pub enum PathStyle { . /// In some contexts, notably in expressions, paths with generic arguments are ambiguous . /// with something else. For example, in expressions `segment < ....` can be interpreted . /// as a comparison and `segment ( ....` can be interpreted as a function call. . /// In all such contexts the non-path interpretation is preferred by default for practical . /// reasons, but the path interpretation can be forced by the disambiguator `::`, e.g. . /// `x` - comparisons, `x::` - unambiguously a path. . Expr, -- line 27 ---------------------------------------- -- line 116 ---------------------------------------- . Applicability::MachineApplicable, . ) . .emit(); . . true . } . . pub(super) fn parse_path(&mut self, style: PathStyle) -> PResult<'a, Path> { 29,684 ( 0.02%) self.parse_path_inner(style, None) . } . . /// Parses simple paths. . /// . /// `path = [::] segment+` . /// `segment = ident | ident[::] | ident[::](args) [-> type]` . /// . /// # Examples . /// `a::b::C` (without disambiguator) . /// `a::b::C::` (with disambiguator) . /// `Fn(Args)` (without disambiguator) . /// `Fn::(Args)` (with disambiguator) 84,840 ( 0.05%) pub(super) fn parse_path_inner( . &mut self, . style: PathStyle, . ty_generics: Option<&Generics>, . ) -> PResult<'a, Path> { . let reject_generics_if_mod_style = |parser: &Parser<'_>, path: &Path| { . // Ensure generic arguments don't end up in attribute paths, such as: . // . // macro_rules! m { -- line 145 ---------------------------------------- -- line 158 ---------------------------------------- . .map(|arg| arg.span()) . .collect::>(), . "unexpected generic arguments in path", . ) . .emit(); . } . }; . 16,968 ( 0.01%) maybe_whole!(self, NtPath, |path| { . reject_generics_if_mod_style(self, &path); . path . }); . . if let token::Interpolated(nt) = &self.token.kind { . if let token::NtTy(ty) = &**nt { . if let ast::TyKind::Path(None, path) = &ty.kind { . let path = path.clone(); . self.bump(); . reject_generics_if_mod_style(self, &path); . return Ok(path); . } . } . } . 8,484 ( 0.00%) let lo = self.token.span; . let mut segments = Vec::new(); . let mod_sep_ctxt = self.token.span.ctxt(); . if self.eat(&token::ModSep) { . segments.push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt))); . } 59,388 ( 0.03%) self.parse_path_segments(&mut segments, style, ty_generics)?; . 118,776 ( 0.07%) Ok(Path { segments, span: lo.to(self.prev_token.span), tokens: None }) 67,872 ( 0.04%) } . 93,324 ( 0.05%) pub(super) fn parse_path_segments( . &mut self, . segments: &mut Vec, . style: PathStyle, . ty_generics: Option<&Generics>, . ) -> PResult<'a, ()> { . loop { 59,398 ( 0.03%) let segment = self.parse_path_segment(style, ty_generics)?; 8,484 ( 0.00%) if style == PathStyle::Expr { . // In order to check for trailing angle brackets, we must have finished . // recursing (`parse_path_segment` can indirectly call this function), . // that is, the next token must be the highlighted part of the below example: . // . // `Foo::>::Qux` . // ^ here . // . // As opposed to the below highlight (if we had only finished the first -- line 209 ---------------------------------------- -- line 210 ---------------------------------------- . // recursion): . // . // `Foo::>::Qux` . // ^ here . // . // `PathStyle::Expr` is only provided at the root invocation and never in . // `parse_path_segment` to recurse and therefore can be checked to maintain . // this invariant. 10 ( 0.00%) self.check_trailing_angle_brackets(&segment, &[&token::ModSep]); . } 50,912 ( 0.03%) segments.push(segment); . 33,944 ( 0.02%) if self.is_import_coupler() || !self.eat(&token::ModSep) { . return Ok(()); . } . } 76,356 ( 0.04%) } . 93,368 ( 0.05%) pub(super) fn parse_path_segment( . &mut self, . style: PathStyle, . ty_generics: Option<&Generics>, . ) -> PResult<'a, PathSegment> { . let ident = self.parse_path_segment_ident()?; . let is_args_start = |token: &Token| { 15 ( 0.00%) matches!( . token.kind, . token::Lt . | token::BinOp(token::Shl) . | token::OpenDelim(token::Paren) . | token::LArrow . ) . }; . let check_args_start = |this: &mut Self| { . this.expected_tokens.extend_from_slice(&[ . TokenType::Token(token::Lt), . TokenType::Token(token::OpenDelim(token::Paren)), . ]); 3 ( 0.00%) is_args_start(&this.token) . }; . 76,392 ( 0.04%) Ok( 42,434 ( 0.02%) if style == PathStyle::Type && check_args_start(self) 12 ( 0.00%) || style != PathStyle::Mod 18 ( 0.00%) && self.check(&token::ModSep) . && self.look_ahead(1, |t| is_args_start(t)) . { . // We use `style == PathStyle::Expr` to check if this is in a recursion or not. If . // it isn't, then we reset the unmatched angle bracket count as we're about to start . // parsing a new path. 1 ( 0.00%) if style == PathStyle::Expr { 2 ( 0.00%) self.unmatched_angle_bracket_count = 0; . self.max_angle_bracket_count = 0; . } . . // Generic arguments are found - `<`, `(`, `::<` or `::(`. . self.eat(&token::ModSep); 4 ( 0.00%) let lo = self.token.span; . let args = if self.eat_lt() { . // `<'a, T, A = U>` 2 ( 0.00%) let args = self.parse_angle_args_with_leading_angle_bracket_recovery( . style, . lo, . ty_generics, . )?; . self.expect_gt()?; 6 ( 0.00%) let span = lo.to(self.prev_token.span); 16 ( 0.00%) AngleBracketedArgs { args, span }.into() . } else { . // `(T, U) -> R` . let (inputs, _) = self.parse_paren_comma_seq(|p| p.parse_ty())?; . let inputs_span = lo.to(self.prev_token.span); . let output = . self.parse_ret_ty(AllowPlus::No, RecoverQPath::No, RecoverReturnSign::No)?; . let span = ident.span.to(self.prev_token.span); . ParenthesizedArgs { span, inputs, inputs_span, output }.into() . }; . 12 ( 0.00%) PathSegment { ident, args, id: ast::DUMMY_NODE_ID } . } else { . // Generic arguments are not found. 59,402 ( 0.03%) PathSegment::from_ident(ident) . }, . ) 67,904 ( 0.04%) } . . pub(super) fn parse_path_segment_ident(&mut self) -> PResult<'a, Ident> { 59,416 ( 0.03%) match self.token.ident() { 42,440 ( 0.02%) Some((ident, false)) if ident.is_path_segment_keyword() => { . self.bump(); . Ok(ident) . } . _ => self.parse_ident(), . } . } . . /// Parses generic args (within a path segment) with recovery for extra leading angle brackets. -- line 306 ---------------------------------------- -- line 384 ---------------------------------------- . // recover by attempting to parse again. . // . // In practice, the recursion of this function is indirect and there will be other . // locations that consume some `<` characters - as long as we update the count when . // this happens, it isn't an issue. . . let is_first_invocation = style == PathStyle::Expr; . // Take a snapshot before attempting to parse - we can restore this later. 8 ( 0.00%) let snapshot = if is_first_invocation { Some(self.clone()) } else { None }; . . debug!("parse_generic_args_with_leading_angle_bracket_recovery: (snapshotting)"); 10 ( 0.00%) match self.parse_angle_args(ty_generics) { 10 ( 0.00%) Ok(args) => Ok(args), . Err(mut e) if is_first_invocation && self.unmatched_angle_bracket_count > 0 => { . // Swap `self` with our backup of the parser state before attempting to parse . // generic arguments. . let snapshot = mem::replace(self, snapshot.unwrap()); . . // Eat the unmatched angle brackets. . let all_angle_brackets = (0..snapshot.unmatched_angle_bracket_count) . .fold(true, |a, _| a && self.eat_lt()); -- line 404 ---------------------------------------- -- line 449 ---------------------------------------- . } . } . Err(e) => Err(e), . } . } . . /// Parses (possibly empty) list of generic arguments / associated item constraints, . /// possibly including trailing comma. 20 ( 0.00%) pub(super) fn parse_angle_args( . &mut self, . ty_generics: Option<&Generics>, . ) -> PResult<'a, Vec> { . let mut args = Vec::new(); 4 ( 0.00%) while let Some(arg) = self.parse_angle_arg(ty_generics)? { 48 ( 0.00%) args.push(arg); . if !self.eat(&token::Comma) { 8 ( 0.00%) if !self.token.kind.should_end_const_arg() { . if self.handle_ambiguous_unbraced_const_arg(&mut args)? { . // We've managed to (partially) recover, so continue trying to parse . // arguments. . continue; . } . } . break; . } . } 14 ( 0.00%) Ok(args) 16 ( 0.00%) } . . /// Parses a single argument in the angle arguments `<...>` of a path segment. . fn parse_angle_arg( . &mut self, . ty_generics: Option<&Generics>, . ) -> PResult<'a, Option> { 2 ( 0.00%) let lo = self.token.span; 8 ( 0.00%) let arg = self.parse_generic_arg(ty_generics)?; 4 ( 0.00%) match arg { 8 ( 0.00%) Some(arg) => { 4 ( 0.00%) if self.check(&token::Colon) | self.check(&token::Eq) { . let (ident, gen_args) = match self.get_ident_from_generic_arg(arg) { . Ok(ident_gen_args) => ident_gen_args, . Err(arg) => return Ok(Some(AngleBracketedArg::Arg(arg))), . }; . let kind = if self.eat(&token::Colon) { . // Parse associated type constraint bound. . . let bounds = self.parse_generic_bounds(Some(self.prev_token.span))?; -- line 495 ---------------------------------------- -- line 505 ---------------------------------------- . // Gate associated type bounds, e.g., `Iterator`. . if let AssocConstraintKind::Bound { .. } = kind { . self.sess.gated_spans.gate(sym::associated_type_bounds, span); . } . let constraint = . AssocConstraint { id: ast::DUMMY_NODE_ID, ident, gen_args, kind, span }; . Ok(Some(AngleBracketedArg::Constraint(constraint))) . } else { 16 ( 0.00%) Ok(Some(AngleBracketedArg::Arg(arg))) . } . } . _ => Ok(None), . } . } . . /// Parse the term to the right of an associated item equality constraint. . /// That is, parse `` in `Item = `. -- line 521 ---------------------------------------- -- line 606 ---------------------------------------- . } else { . self.handle_unambiguous_unbraced_const_arg()? . }; . Ok(AnonConst { id: ast::DUMMY_NODE_ID, value }) . } . . /// Parse a generic argument in a path segment. . /// This does not include constraints, e.g., `Item = u8`, which is handled in `parse_angle_arg`. 20 ( 0.00%) pub(super) fn parse_generic_arg( . &mut self, . ty_generics: Option<&Generics>, . ) -> PResult<'a, Option> { 2 ( 0.00%) let start = self.token.span; 4 ( 0.00%) let arg = if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) { . // Parse lifetime argument. . GenericArg::Lifetime(self.expect_lifetime()) 4 ( 0.00%) } else if self.check_const_arg() { . // Parse const argument. . GenericArg::Const(self.parse_const_arg()?) 4 ( 0.00%) } else if self.check_type() { . // Parse type argument. 4 ( 0.00%) match self.parse_ty() { . Ok(ty) => GenericArg::Type(ty), . Err(err) => { . // Try to recover from possible `const` arg without braces. . return self.recover_const_arg(start, err).map(Some); . } . } . } else if self.token.is_keyword(kw::Const) { . return self.recover_const_param_declaration(ty_generics); . } else { . return Ok(None); . }; 12 ( 0.00%) Ok(Some(arg)) 16 ( 0.00%) } . . fn get_ident_from_generic_arg( . &self, . gen_arg: GenericArg, . ) -> Result<(Ident, Option), GenericArg> { . if let GenericArg::Type(ty) = &gen_arg { . if let ast::TyKind::Path(qself, path) = &ty.kind { . if qself.is_none() && path.segments.len() == 1 { -- line 648 ---------------------------------------- 86,325 ( 0.05%) -------------------------------------------------------------------------------- -- 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 . // . 383,002 ( 0.22%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 287,250 ( 0.16%) 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. 96 ( 0.00%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 144 ( 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) { 95,764 ( 0.05%) libc::free(ptr as *mut libc::c_void) . } . . #[inline] . unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { 24,512 ( 0.01%) if layout.align() <= MIN_ALIGN && layout.align() <= new_size { 49,024 ( 0.03%) libc::realloc(ptr as *mut libc::c_void, new_size) as *mut u8 . } else { . realloc_fallback(self, ptr, layout, new_size) . } . } . } . . cfg_if::cfg_if! { . if #[cfg(any( -- line 56 ---------------------------------------- -- line 84 ---------------------------------------- . } else if #[cfg(target_os = "wasi")] { . #[inline] . unsafe fn aligned_malloc(layout: &Layout) -> *mut u8 { . libc::aligned_alloc(layout.align(), layout.size()) as *mut u8 . } . } else { . #[inline] . unsafe fn aligned_malloc(layout: &Layout) -> *mut u8 { 1 ( 0.00%) let mut out = ptr::null_mut(); . // posix_memalign requires that the alignment be a multiple of `sizeof(void*)`. . // Since these are all powers of 2, we can just use max. . let align = layout.align().max(crate::mem::size_of::()); 2 ( 0.00%) let ret = libc::posix_memalign(&mut out, align, layout.size()); 2 ( 0.00%) if ret != 0 { ptr::null_mut() } else { out as *mut u8 } . } . } . } 1 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/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 { 73,720 ( 0.04%) 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 335 ( 0.00%) if text.len() < 2 * USIZE_BYTES { 389 ( 0.00%) return text.iter().position(|elt| *elt == x); . } . 219 ( 0.00%) memchr_general_case(x, text) . } . 244 ( 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); . 122 ( 0.00%) if offset > 0 { . offset = cmp::min(offset, len); 156 ( 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); 29,602 ( 0.02%) 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); 44,232 ( 0.03%) let v = *(ptr.add(offset + USIZE_BYTES) as *const usize); . . // break if there is a matching byte 44,232 ( 0.03%) let zu = contains_zero_byte(u ^ repeated_x); 44,232 ( 0.03%) let zv = contains_zero_byte(v ^ repeated_x); 29,488 ( 0.02%) if zu || zv { . break; . } . } 29,434 ( 0.02%) offset += USIZE_BYTES * 2; . } . . // Find the byte after the point the body loop stopped. 498 ( 0.00%) text[offset..].iter().position(|elt| *elt == x).map(|i| offset + i) 305 ( 0.00%) } . . /// Returns the last index matching the byte `x` in `text`. . #[must_use] . pub fn memrchr(x: u8, text: &[u8]) -> Option { . // Scan for a single byte value by reading two `usize` words at a time. . // . // Split `text` in three parts: . // - unaligned tail, after the last word aligned address in text, -- line 100 ---------------------------------------- 15,180 ( 0.01%) -------------------------------------------------------------------------------- -- 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 { 14 ( 0.00%) HashMap { . hash_builder: self.hash_builder.clone(), 3 ( 0.00%) table: self.table.clone(), . } . } . . fn clone_from(&mut self, source: &Self) { . self.table.clone_from(&source.table); . . // Update hash_builder only if we successfully cloned all elements. . self.hash_builder.clone_from(&source.hash_builder); -- line 205 ---------------------------------------- -- line 210 ---------------------------------------- . /// instances of any functions like RawTable::reserve from being generated . #[cfg_attr(feature = "inline-more", inline)] . pub(crate) fn make_hasher(hash_builder: &S) -> impl Fn(&(Q, V)) -> u64 + '_ . where . K: Borrow, . Q: Hash, . S: BuildHasher, . { 1,615 ( 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, . { 17,791 ( 0.01%) 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, . { 12 ( 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)] 2 ( 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) 4 ( 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 { 8,583 ( 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 { 61 ( 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 { 58 ( 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 { 2,901 ( 0.00%) self.len() == 0 . } . . /// Clears the map, returning all key-value pairs as an iterator. Keeps the . /// allocated memory for reuse. . /// . /// # Examples . /// . /// ``` -- line 696 ---------------------------------------- -- line 790 ---------------------------------------- . /// use hashbrown::HashMap; . /// . /// let mut a = HashMap::new(); . /// a.insert(1, "a"); . /// a.clear(); . /// assert!(a.is_empty()); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 6 ( 0.00%) pub fn clear(&mut self) { . self.table.clear(); 6 ( 0.00%) } . . /// Creates a consuming iterator visiting all the keys in arbitrary order. . /// The map cannot be used after calling this. . /// The iterator element type is `K`. . /// . /// # Examples . /// . /// ``` -- line 808 ---------------------------------------- -- line 1047 ---------------------------------------- . /// ``` . #[inline] . pub fn get(&self, k: &Q) -> Option<&V> . where . K: Borrow, . Q: Hash + Eq, . { . // Avoid `Option::map` because it bloats LLVM IR. 21,549 ( 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, . { 39,623 ( 0.02%) if self.table.is_empty() { . None . } else { 1 ( 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,792 ( 0.01%) pub fn contains_key(&self, k: &Q) -> bool . where . K: Borrow, . Q: Hash + Eq, . { . self.get_inner(k).is_some() 11,776 ( 0.01%) } . . /// Returns a mutable reference to the value corresponding to the key. . /// . /// The key may be any borrowed form of the map's key type, but . /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for . /// the key type. . /// . /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html -- line 1177 ---------------------------------------- -- line 1185 ---------------------------------------- . /// let mut map = HashMap::new(); . /// map.insert(1, "a"); . /// if let Some(x) = map.get_mut(&1) { . /// *x = "b"; . /// } . /// assert_eq!(map[&1], "b"); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 1 ( 0.00%) pub fn get_mut(&mut self, k: &Q) -> Option<&mut V> . where . K: Borrow, . Q: Hash + Eq, . { . // Avoid `Option::map` because it bloats LLVM IR. 3 ( 0.00%) match self.get_inner_mut(k) { . Some(&mut (_, ref mut v)) => Some(v), . None => None, . } 2 ( 0.00%) } . . #[inline] . fn get_inner_mut(&mut self, k: &Q) -> Option<&mut (K, V)> . where . K: Borrow, . Q: Hash + Eq, . { 1 ( 0.00%) if self.table.is_empty() { . None . } else { . let hash = make_hash::(&self.hash_builder, k); . self.table.get_mut(hash, equivalent_key(k)) . } . } . . /// Attempts to get mutable references to `N` values in the map at once. -- line 1219 ---------------------------------------- -- line 1495 ---------------------------------------- . /// assert_eq!(map.insert(37, "a"), None); . /// assert_eq!(map.is_empty(), false); . /// . /// map.insert(37, "b"); . /// assert_eq!(map.insert(37, "c"), Some("b")); . /// assert_eq!(map[&37], "c"); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 99,108 ( 0.06%) pub fn insert(&mut self, k: K, v: V) -> Option { . let hash = make_insert_hash::(&self.hash_builder, &k); . if let Some((_, item)) = self.table.get_mut(hash, equivalent_key(&k)) { . Some(mem::replace(item, v)) . } else { 50,807 ( 0.03%) self.table 62,782 ( 0.04%) .insert(hash, (k, v), make_hasher::(&self.hash_builder)); 2,339 ( 0.00%) None . } 78,697 ( 0.04%) } . . /// Insert a key-value pair into the map without checking . /// if the key already exists in the map. . /// . /// Returns a reference to the key and value just inserted. . /// . /// This operation is safe if a key does not exist in the map. . /// -- line 1520 ---------------------------------------- -- line 1592 ---------------------------------------- . /// use hashbrown::HashMap; . /// . /// let mut map = HashMap::new(); . /// map.insert(1, "a"); . /// assert_eq!(map.remove(&1), Some("a")); . /// assert_eq!(map.remove(&1), None); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 2 ( 0.00%) pub fn remove(&mut self, k: &Q) -> Option . where . K: Borrow, . Q: Hash + Eq, . { . // Avoid `Option::map` because it bloats LLVM IR. 10,834 ( 0.01%) match self.remove_entry(k) { 3 ( 0.00%) Some((_, v)) => Some(v), 9 ( 0.00%) None => None, . } 4 ( 0.00%) } . . /// Removes a key from the map, returning the stored key and value if the . /// key was previously in the map. . /// . /// The key may be any borrowed form of the map's key type, but . /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for . /// the key type. . /// -- line 1618 ---------------------------------------- -- line 1631 ---------------------------------------- . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn remove_entry(&mut self, k: &Q) -> Option<(K, V)> . where . K: Borrow, . Q: Hash + Eq, . { . let hash = make_hash::(&self.hash_builder, k); 4,745 ( 0.00%) self.table.remove_entry(hash, equivalent_key(k)) . } . } . . impl HashMap { . /// Creates a raw entry builder for the HashMap. . /// . /// Raw entries provide the lowest level of control for searching and . /// manipulating a map. They must be manually initialized with a hash and -- line 1647 ---------------------------------------- -- line 2209 ---------------------------------------- . /// Creates a `RawEntryMut` from the given key and its hash. . #[inline] . #[allow(clippy::wrong_self_convention)] . pub fn from_key_hashed_nocheck(self, hash: u64, k: &Q) -> RawEntryMut<'a, K, V, S, A> . where . K: Borrow, . Q: Eq, . { 52 ( 0.00%) self.from_hash(hash, equivalent(k)) . } . } . . impl<'a, K, V, S, A: Allocator + Clone> RawEntryBuilderMut<'a, K, V, S, A> { . /// Creates a `RawEntryMut` from the given hash. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::wrong_self_convention)] 212 ( 0.00%) pub fn from_hash(self, hash: u64, is_match: F) -> RawEntryMut<'a, K, V, S, A> . where . for<'b> F: FnMut(&'b K) -> bool, . { . self.search(hash, is_match) 208 ( 0.00%) } . . #[cfg_attr(feature = "inline-more", inline)] . fn search(self, hash: u64, mut is_match: F) -> RawEntryMut<'a, K, V, S, A> . where . for<'b> F: FnMut(&'b K) -> bool, . { . match self.map.table.find(hash, |(k, _)| is_match(k)) { . Some(elem) => RawEntryMut::Occupied(RawOccupiedEntryMut { . elem, . table: &mut self.map.table, . hash_builder: &self.map.hash_builder, . }), 103 ( 0.00%) None => RawEntryMut::Vacant(RawVacantEntryMut { . table: &mut self.map.table, . hash_builder: &self.map.hash_builder, . }), . } . } . } . . impl<'a, K, V, S, A: Allocator + Clone> RawEntryBuilder<'a, K, V, S, A> { -- line 2251 ---------------------------------------- -- line 2260 ---------------------------------------- . { . let hash = make_hash::(&self.map.hash_builder, k); . self.from_key_hashed_nocheck(hash, k) . } . . /// Access an entry by a key and its hash. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::wrong_self_convention)] 643 ( 0.00%) pub fn from_key_hashed_nocheck(self, hash: u64, k: &Q) -> Option<(&'a K, &'a V)> . where . K: Borrow, . Q: Eq, . { 741 ( 0.00%) self.from_hash(hash, equivalent(k)) 1,286 ( 0.00%) } . . #[cfg_attr(feature = "inline-more", inline)] . fn search(self, hash: u64, mut is_match: F) -> Option<(&'a K, &'a V)> . where . F: FnMut(&K) -> bool, . { 1,608 ( 0.00%) match self.map.table.get(hash, |(k, _)| is_match(k)) { . Some(&(ref key, ref value)) => Some((key, value)), . None => None, . } . } . . /// Access an entry by hash. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::wrong_self_convention)] -- line 2289 ---------------------------------------- -- line 2624 ---------------------------------------- . /// and returns a mutable reference to it. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::shadow_unrelated)] . pub fn insert_hashed_nocheck(self, hash: u64, key: K, value: V) -> (&'a mut K, &'a mut V) . where . K: Hash, . S: BuildHasher, . { 156 ( 0.00%) let &mut (ref mut k, ref mut v) = self.table.insert_entry( . hash, . (key, value), . make_hasher::(self.hash_builder), . ); . (k, v) . } . . /// Set the value of an entry with a custom hasher function. -- line 2640 ---------------------------------------- -- line 2975 ---------------------------------------- . /// map.insert("b", 2); . /// map.insert("c", 3); . /// . /// // Not possible with .iter() . /// let vec: Vec<(&str, i32)> = map.into_iter().collect(); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . fn into_iter(self) -> IntoIter { 697 ( 0.00%) IntoIter { 763 ( 0.00%) inner: self.table.into_iter(), . } . } . } . . impl<'a, K, V> Iterator for Iter<'a, K, V> { . type Item = (&'a K, &'a V); . . #[cfg_attr(feature = "inline-more", inline)] . fn next(&mut self) -> Option<(&'a K, &'a V)> { . // Avoid `Option::map` because it bloats LLVM IR. 119 ( 0.00%) match self.inner.next() { . Some(x) => unsafe { . let r = x.as_ref(); . Some((&r.0, &r.1)) . }, . None => None, . } . } . #[cfg_attr(feature = "inline-more", inline)] . fn size_hint(&self) -> (usize, Option) { 1 ( 0.00%) self.inner.size_hint() . } . } . impl ExactSizeIterator for Iter<'_, K, V> { . #[cfg_attr(feature = "inline-more", inline)] . fn len(&self) -> usize { . self.inner.len() . } . } -- line 3013 ---------------------------------------- -- line 3051 ---------------------------------------- . } . } . . impl Iterator for IntoIter { . type Item = (K, V); . . #[cfg_attr(feature = "inline-more", inline)] . fn next(&mut self) -> Option<(K, V)> { 17 ( 0.00%) self.inner.next() . } . #[cfg_attr(feature = "inline-more", inline)] . fn size_hint(&self) -> (usize, Option) { . self.inner.size_hint() . } . } . impl ExactSizeIterator for IntoIter { . #[cfg_attr(feature = "inline-more", inline)] -- line 3067 ---------------------------------------- -- line 4557 ---------------------------------------- . /// keys with new values returned from the iterator. . impl Extend<(K, V)> for HashMap . where . K: Eq + Hash, . S: BuildHasher, . A: Allocator + Clone, . { . #[cfg_attr(feature = "inline-more", inline)] 116 ( 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. 100 ( 0.00%) let iter = iter.into_iter(); 26 ( 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,803 ( 0.01%) self.insert(k, v); . }); 70 ( 0.00%) } . . #[inline] . #[cfg(feature = "nightly")] . fn extend_one(&mut self, (k, v): (K, V)) { . self.insert(k, v); . } . . #[inline] -- line 4588 ---------------------------------------- 17,684 ( 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) { 33,023 ( 0.02%) self.hash = self.hash.rotate_left(5).bitxor(i).wrapping_mul(K); . } . } . . impl Hasher for FxHasher { . #[inline] 504 ( 0.00%) fn write(&mut self, mut bytes: &[u8]) { . #[cfg(target_pointer_width = "32")] . let read_usize = |bytes: &[u8]| u32::from_ne_bytes(bytes[..4].try_into().unwrap()); . #[cfg(target_pointer_width = "64")] . let read_usize = |bytes: &[u8]| u64::from_ne_bytes(bytes[..8].try_into().unwrap()); . 34,023 ( 0.02%) let mut hash = FxHasher { hash: self.hash }; . assert!(size_of::() <= 8); 414,000 ( 0.24%) while bytes.len() >= size_of::() { . hash.add_to_hash(read_usize(bytes) as usize); . bytes = &bytes[size_of::()..]; . } 66,902 ( 0.04%) 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..]; . } 66,902 ( 0.04%) 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..]; . } 74,044 ( 0.04%) if (size_of::() > 1) && bytes.len() >= 1 { 21,579 ( 0.01%) hash.add_to_hash(bytes[0] as usize); . } 1,076 ( 0.00%) self.hash = hash.hash; 504 ( 0.00%) } . . #[inline] . fn write_u8(&mut self, i: u8) { . self.add_to_hash(i as usize); . } . . #[inline] . fn write_u16(&mut self, i: u16) { 1 ( 0.00%) self.add_to_hash(i as usize); . } . . #[inline] . fn write_u32(&mut self, i: u32) { 62,807 ( 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/.cargo/registry/src/github.com-1ecc6299db9ec823/unicode-normalization-0.1.13/src/quick_check.rs -------------------------------------------------------------------------------- Ir -- line 23 ---------------------------------------- . I: Iterator, . F: Fn(char) -> IsNormalized, . { . let mut last_cc = 0u8; . let mut nonstarter_count = 0; . let mut result = IsNormalized::Yes; . for ch in s { . // For ASCII we know it's always allowed and a starter 257,408 ( 0.15%) if ch <= '\x7f' { . last_cc = 0; . nonstarter_count = 0; . continue; . } . . // Otherwise, lookup the combining class and QC property . let cc = canonical_combining_class(ch); . if last_cc > cc && cc != 0 { -- line 39 ---------------------------------------- 128,704 ( 0.07%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs -------------------------------------------------------------------------------- Ir -- 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 { 1,555 ( 0.00%) intrinsics::ctlz(self as $ActualT) as u32 . } . . /// Returns the number of trailing zeros in the binary representation . /// of `self`. . /// . /// # Examples . /// . /// Basic usage: -- line 134 ---------------------------------------- -- line 139 ---------------------------------------- . /// assert_eq!(n.trailing_zeros(), 3); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn trailing_zeros(self) -> u32 { 34,710 ( 0.02%) 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 { 464,513 ( 0.26%) 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`. 36,440 ( 0.02%) unsafe { intrinsics::unchecked_add(self, rhs) } . } . . /// Checked addition with a signed integer. Computes `self + rhs`, . /// returning `None` if overflow occurred. . /// . /// # Examples . /// . /// Basic usage: -- line 472 ---------------------------------------- -- line 525 ---------------------------------------- . )] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")] . #[inline(always)] . pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self { . // SAFETY: the caller must uphold the safety contract for . // `unchecked_sub`. 11 ( 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 { 47 ( 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 { 6 ( 0.00%) intrinsics::saturating_sub(self, rhs) . } . . /// Saturating integer multiplication. Computes `self * rhs`, . /// saturating at the numeric bounds instead of overflowing. . /// . /// # Examples . /// . /// Basic usage: -- line 1100 ---------------------------------------- -- line 1175 ---------------------------------------- . #[doc = concat!("assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::MAX), 199);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn wrapping_add(self, rhs: Self) -> Self { 1,027,307 ( 0.58%) 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 { 81,205 ( 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 { 186,837 ( 0.11%) 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) { 50,900 ( 0.03%) let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT); . (a as Self, b) . } . . /// Calculates `self + rhs + carry` without the ability to overflow. . /// . /// Performs "ternary addition" which takes in an extra bit to add, and may return an . /// additional bit of overflow. This allows for chaining together multiple additions . /// to create "big integers" which represent larger values. -- line 1508 ---------------------------------------- -- line 1588 ---------------------------------------- . #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));")] . /// ``` . #[stable(feature = "wrapping", since = "1.7.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) { 3,729 ( 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) { 122,877 ( 0.07%) let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT); . (a as Self, b) . } . . /// Calculates the divisor when `self` is divided by `rhs`. . /// . /// Returns a tuple of the divisor along with a boolean indicating . /// whether an arithmetic overflow would occur. Note that for unsigned . /// integers overflow never occurs, so the second value is always -- line 1690 ---------------------------------------- -- line 2132 ---------------------------------------- . #[doc = concat!("assert!(16", stringify!($SelfT), ".is_power_of_two());")] . #[doc = concat!("assert!(!10", stringify!($SelfT), ".is_power_of_two());")] . /// ``` . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")] . #[inline(always)] . pub const fn is_power_of_two(self) -> bool { 120 ( 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 { 12 ( 0.00%) if self <= 1 { return 0; } . 4,364 ( 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. 13,092 ( 0.01%) let z = unsafe { intrinsics::ctlz_nonzero(p) }; 4,364 ( 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 { 8,716 ( 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 ---------------------------------------- 4,669 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_metadata/src/rmeta/decoder.rs -------------------------------------------------------------------------------- Ir -- line 178 ---------------------------------------- . None . } . fn tcx(self) -> Option> { . None . } . . fn decoder(self, pos: usize) -> DecodeContext<'a, 'tcx> { . let tcx = self.tcx(); 16,316 ( 0.01%) DecodeContext { 1,628 ( 0.00%) opaque: opaque::Decoder::new(self.blob(), pos), . cdata: self.cdata(), . blob: self.blob(), . sess: self.sess().or(tcx.map(|tcx| tcx.sess)), . tcx, . last_source_file_index: 0, . lazy_state: LazyState::NoNode, . alloc_decoding_session: self . .cdata() 1,329 ( 0.00%) .map(|cdata| cdata.cdata.alloc_decoding_state.new_decoding_session()), . } . } . } . . impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a MetadataBlob { . #[inline] . fn blob(self) -> &'a MetadataBlob { . self -- line 204 ---------------------------------------- -- line 255 ---------------------------------------- . } . #[inline] . fn tcx(self) -> Option> { . Some(self.1) . } . } . . impl<'a, 'tcx, T: Decodable>> Lazy { 18 ( 0.00%) fn decode>(self, metadata: M) -> T { . let mut dcx = metadata.decoder(self.position.get()); 4,708 ( 0.00%) dcx.lazy_state = LazyState::NodeStart(self.position); 2,115 ( 0.00%) T::decode(&mut dcx) 24 ( 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); 2,029 ( 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 { 2,637 ( 0.00%) if cnum == LOCAL_CRATE { self.cdata().cnum } else { self.cdata().cnum_map[cnum] } . } . 14,909 ( 0.01%) fn read_lazy_with_meta(&mut self, meta: T::Meta) -> Lazy { . let distance = self.read_usize(); 14,729 ( 0.01%) let position = match self.lazy_state { . LazyState::NoNode => bug!("read_lazy_with_meta: outside of a metadata node"), 178 ( 0.00%) LazyState::NodeStart(start) => { . let start = start.get(); 356 ( 0.00%) assert!(distance <= start); . start - distance . } 8,517 ( 0.00%) LazyState::Previous(last_pos) => last_pos.get() + distance, . }; 6,034 ( 0.00%) self.lazy_state = LazyState::Previous(NonZeroUsize::new(position).unwrap()); . Lazy::from_position_and_meta(NonZeroUsize::new(position).unwrap(), meta) 14,909 ( 0.01%) } . . #[inline] . pub fn read_raw_bytes(&mut self, len: usize) -> &'a [u8] { . self.opaque.read_raw_bytes(len) . } . } . . impl<'a, 'tcx> TyDecoder<'tcx> for DecodeContext<'a, 'tcx> { -- line 324 ---------------------------------------- -- line 375 ---------------------------------------- . } else { . bug!("Attempting to decode interpret::AllocId without CrateMetadata") . } . } . } . . impl<'a, 'tcx> Decodable> for CrateNum { . fn decode(d: &mut DecodeContext<'a, 'tcx>) -> CrateNum { 2,497 ( 0.00%) let cnum = CrateNum::from_u32(d.read_u32()); . d.map_encoded_cnum_to_current(cnum) . } . } . . impl<'a, 'tcx> Decodable> for DefIndex { 7 ( 0.00%) fn decode(d: &mut DecodeContext<'a, 'tcx>) -> DefIndex { 3,128 ( 0.00%) DefIndex::from_u32(d.read_u32()) 14 ( 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 { 3,616 ( 0.00%) fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> SyntaxContext { 904 ( 0.00%) let cdata = decoder.cdata(); 904 ( 0.00%) let sess = decoder.sess.unwrap(); 1,808 ( 0.00%) let cname = cdata.root.name; . rustc_span::hygiene::decode_syntax_context(decoder, &cdata.hygiene_context, |_, id| { . debug!("SpecializedDecoder: decoding {}", id); . cdata . .root . .syntax_contexts . .get(cdata, id) . .unwrap_or_else(|| panic!("Missing SyntaxContext {:?} for crate {:?}", id, cname)) . .decode((cdata, sess)) . }) 4,520 ( 0.00%) } . } . . impl<'a, 'tcx> Decodable> for ExpnId { 1,330 ( 0.00%) fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> ExpnId { 190 ( 0.00%) let local_cdata = decoder.cdata(); 190 ( 0.00%) let sess = decoder.sess.unwrap(); . . let cnum = CrateNum::decode(decoder); . let index = u32::decode(decoder); . . let expn_id = rustc_span::hygiene::decode_expn_id(cnum, index, |expn_id| { . let ExpnId { krate: cnum, local_id: index } = expn_id; . // Lookup local `ExpnData`s in our own crate data. Foreign `ExpnData`s . // are stored in the owning crate, to avoid duplication. . debug_assert_ne!(cnum, LOCAL_CRATE); 4 ( 0.00%) let crate_data = if cnum == local_cdata.cnum { . local_cdata . } else { . local_cdata.cstore.get_crate_data(cnum) . }; 20 ( 0.00%) let expn_data = crate_data . .root . .expn_data . .get(crate_data, index) . .unwrap() . .decode((crate_data, sess)); 20 ( 0.00%) let expn_hash = crate_data . .root . .expn_hashes . .get(crate_data, index) . .unwrap() . .decode((crate_data, sess)); 40 ( 0.00%) (expn_data, expn_hash) . }); . expn_id 1,520 ( 0.00%) } . } . . impl<'a, 'tcx> Decodable> for Span { 7,232 ( 0.00%) fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Span { 904 ( 0.00%) let ctxt = SyntaxContext::decode(decoder); . let tag = u8::decode(decoder); . 1,808 ( 0.00%) if tag == TAG_PARTIAL_SPAN { . return DUMMY_SP.with_ctxt(ctxt); . } . . debug_assert!(tag == TAG_VALID_SPAN_LOCAL || tag == TAG_VALID_SPAN_FOREIGN); . . let lo = BytePos::decode(decoder); . let len = BytePos::decode(decoder); . let hi = lo + len; . 2,712 ( 0.00%) let Some(sess) = decoder.sess else { . bug!("Cannot decode Span without Session.") . }; . . // There are two possibilities here: . // 1. This is a 'local span', which is located inside a `SourceFile` . // that came from this crate. In this case, we use the source map data . // encoded in this crate. This branch should be taken nearly all of the time. . // 2. This is a 'foreign span', which is located inside a `SourceFile` -- line 476 ---------------------------------------- -- line 492 ---------------------------------------- . // a transitive dependency. . // . // When we encode a foreign span, we adjust its 'lo' and 'high' values . // to be based on the *foreign* crate (e.g. crate C), not the crate . // we are writing metadata for (e.g. crate B). This allows us to . // treat the 'local' and 'foreign' cases almost identically during deserialization: . // we can call `imported_source_files` for the proper crate, and binary search . // through the returned slice using our span. 2,228 ( 0.00%) let imported_source_files = if tag == TAG_VALID_SPAN_LOCAL { . decoder.cdata().imported_source_files(sess) . } else { . // When we encode a proc-macro crate, all `Span`s should be encoded . // with `TAG_VALID_SPAN_LOCAL` 3 ( 0.00%) if decoder.cdata().root.is_proc_macro_crate() { . // Decode `CrateNum` as u32 - using `CrateNum::decode` will ICE . // since we don't have `cnum_map` populated. . let cnum = u32::decode(decoder); . panic!( . "Decoding of crate {:?} tried to access proc-macro dep {:?}", . decoder.cdata().root.name, . cnum . ); -- line 513 ---------------------------------------- -- line 518 ---------------------------------------- . "SpecializedDecoder::specialized_decode: loading source files from cnum {:?}", . cnum . ); . . // Decoding 'foreign' spans should be rare enough that it's . // not worth it to maintain a per-CrateNum cache for `last_source_file_index`. . // We just set it to 0, to ensure that we don't try to access something out . // of bounds for our initial 'guess' 6 ( 0.00%) decoder.last_source_file_index = 0; . 3 ( 0.00%) let foreign_data = decoder.cdata().cstore.get_crate_data(cnum); . foreign_data.imported_source_files(sess) . }; . . let source_file = { . // Optimize for the case that most spans within a translated item . // originate from the same source_file. 2,712 ( 0.00%) let last_source_file = &imported_source_files[decoder.last_source_file_index]; . 3,534 ( 0.00%) if lo >= last_source_file.original_start_pos && lo <= last_source_file.original_end_pos . { . last_source_file . } else { . let index = imported_source_files . .binary_search_by_key(&lo, |source_file| source_file.original_start_pos) 840 ( 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 420 ( 0.00%) if tag == TAG_VALID_SPAN_LOCAL { 418 ( 0.00%) decoder.last_source_file_index = index; . } 840 ( 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 = 3,616 ( 0.00%) (lo + source_file.translated_source_file.start_pos) - source_file.original_start_pos; . let hi = . (hi + source_file.translated_source_file.start_pos) - source_file.original_start_pos; . . // Do not try to decode parent for foreign spans. . Span::new(lo, hi, ctxt, None) 8,136 ( 0.00%) } . } . . impl<'a, 'tcx> Decodable> for &'tcx [thir::abstract_const::Node<'tcx>] { . fn decode(d: &mut DecodeContext<'a, 'tcx>) -> Self { . ty::codec::RefDecodable::decode(d) . } . } . -- line 587 ---------------------------------------- -- line 590 ---------------------------------------- . ty::codec::RefDecodable::decode(d) . } . } . . impl<'a, 'tcx, T: Decodable>> Decodable> . for Lazy . { . fn decode(decoder: &mut DecodeContext<'a, 'tcx>) -> Self { 237 ( 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(); 7,879 ( 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(); 9,802 ( 0.01%) 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) . } . 174 ( 0.00%) crate fn get_root(&self) -> CrateRoot<'tcx> { 58 ( 0.00%) let slice = &self.blob()[..]; . let offset = METADATA_HEADER.len(); 290 ( 0.00%) let pos = (((slice[offset + 0] as u32) << 24) 116 ( 0.00%) | ((slice[offset + 1] as u32) << 16) 232 ( 0.00%) | ((slice[offset + 2] as u32) << 8) 174 ( 0.00%) | ((slice[offset + 3] as u32) << 0)) as usize; . Lazy::>::from_position(NonZeroUsize::new(pos).unwrap()).decode(self) 290 ( 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 { 38 ( 0.00%) self.proc_macro_data.is_some() . } . . crate fn name(&self) -> Symbol { 2 ( 0.00%) self.name . } . . crate fn hash(&self) -> Svh { 19 ( 0.00%) self.hash . } . . crate fn stable_crate_id(&self) -> StableCrateId { 38 ( 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> { 38 ( 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] . } . 2,255 ( 0.00%) fn opt_item_ident(self, item_index: DefIndex, sess: &Session) -> Option { 1,640 ( 0.00%) let name = self.def_key(item_index).disambiguated_data.data.get_opt_name()?; 770 ( 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. 45 ( 0.00%) assert_eq!(self.def_kind(item_index), DefKind::ExternCrate); . return None; . } . }; . Some(Ident::new(name, span)) 2,870 ( 0.00%) } . 5 ( 0.00%) fn item_ident(self, item_index: DefIndex, sess: &Session) -> Ident { 12 ( 0.00%) self.opt_item_ident(item_index, sess).expect("no encoded ident for item") 10 ( 0.00%) } . . fn maybe_kind(self, item_id: DefIndex) -> Option { 386 ( 0.00%) self.root.tables.kind.get(self, item_id).map(|k| k.decode(self)) . } . 1,544 ( 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, . ) . }) 1,158 ( 0.00%) } . 2,030 ( 0.00%) fn def_kind(self, item_id: DefIndex) -> DefKind { 1,165 ( 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,160 ( 0.00%) } . 45 ( 0.00%) fn get_span(self, index: DefIndex, sess: &Session) -> Span { 967 ( 0.00%) self.root . .tables . .span . .get(self, index) . .unwrap_or_else(|| panic!("Missing span for {:?}", index)) . .decode((self, sess)) 25 ( 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 959 ---------------------------------------- . .tables . .ty . .get(self, id) . .unwrap_or_else(|| panic!("Not a type: {:?}", id)) . .decode((self, tcx)) . } . . fn get_stability(self, id: DefIndex) -> Option { 5 ( 0.00%) self.root.tables.stability.get(self, id).map(|stab| stab.decode(self)) . } . . fn get_const_stability(self, id: DefIndex) -> Option { . self.root.tables.const_stability.get(self, id).map(|stab| stab.decode(self)) . } . . fn get_deprecation(self, id: DefIndex) -> Option { 5 ( 0.00%) self.root.tables.deprecation.get(self, id).map(|depr| depr.decode(self)) . } . 12 ( 0.00%) fn get_visibility(self, id: DefIndex) -> ty::Visibility { 215 ( 0.00%) self.root.tables.visibility.get(self, id).unwrap().decode(self) 8 ( 0.00%) } . . fn get_impl_data(self, id: DefIndex) -> ImplData { . match self.kind(id) { . EntryKind::Impl(data) => data.decode(self), . _ => bug!(), . } . } . -- line 988 ---------------------------------------- -- line 1010 ---------------------------------------- . self.get_impl_data(id).coerce_unsized_info . } . . fn get_impl_trait(self, id: DefIndex, tcx: TyCtxt<'tcx>) -> Option> { . self.root.tables.impl_trait_ref.get(self, id).map(|tr| tr.decode((self, tcx))) . } . . fn get_expn_that_defined(self, id: DefIndex, sess: &Session) -> ExpnId { 930 ( 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)] { 57 ( 0.00%) tcx.arena.alloc_from_iter( 38 ( 0.00%) self.root . .lang_items . .decode(self) 564 ( 0.00%) .map(|(def_index, index)| (self.local_def_id(def_index), index)), . ) . } . . /// Iterates over the diagnostic items in the given crate. . fn get_diagnostic_items(self) -> DiagnosticItems { . let mut id_to_name = FxHashMap::default(); . let name_to_id = self . .root -- line 1048 ---------------------------------------- -- line 1062 ---------------------------------------- . /// Module here is understood in name resolution sense - it can be a `mod` item, . /// or a crate root, or an enum, or a trait. . fn for_each_module_child( . self, . id: DefIndex, . mut callback: impl FnMut(ModChild), . sess: &Session, . ) { 12 ( 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. 24 ( 0.00%) if let Some(children) = self.root.tables.children.get(self, id) { 48 ( 0.00%) for child_index in children.decode((self, sess)) { 1,194 ( 0.00%) if let Some(ident) = self.opt_item_ident(child_index, sess) { 297 ( 0.00%) let kind = self.def_kind(child_index); 198 ( 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. 396 ( 0.00%) match kind { . DefKind::Struct => { . if let Some((ctor_def_id, ctor_kind)) = . self.get_ctor_def_id_and_kind(child_index) . { . let ctor_res = . Res::Def(DefKind::Ctor(CtorOf::Struct, ctor_kind), ctor_def_id); . let vis = self.get_visibility(ctor_def_id.index); . callback(ModChild { ident, res: ctor_res, vis, span }); -- line 1119 ---------------------------------------- -- line 1144 ---------------------------------------- . callback(ModChild { ident, res: ctor_res, vis, span }); . } . _ => {} . } . } . } . } . 27 ( 0.00%) match self.kind(id) { 6 ( 0.00%) EntryKind::Mod(exports) => { 398 ( 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,302 ( 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 1290 ---------------------------------------- . } . } . . fn get_item_variances(self, id: DefIndex) -> impl Iterator + 'a { . 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)> { 21 ( 0.00%) match self.kind(node_id) { . EntryKind::Struct(data, _) | EntryKind::Variant(data) => { 9 ( 0.00%) let vdata = data.decode(self); 7 ( 0.00%) vdata.ctor.map(|index| (self.local_def_id(index), vdata.ctor_kind)) . } . _ => None, . } 15 ( 0.00%) } . 12 ( 0.00%) fn get_item_attrs( . self, . id: DefIndex, . sess: &'a Session, . ) -> impl Iterator + 'a { 3 ( 0.00%) self.root . .tables . .attributes . .get(self, id) . .unwrap_or_else(|| { . // Structure and variant constructors don't have any attributes encoded for them, . // but we assume that someone passing a constructor ID actually wants to look at . // the attributes on the corresponding struct or variant. . let def_key = self.def_key(id); -- line 1320 ---------------------------------------- -- line 1322 ---------------------------------------- . let parent_id = def_key.parent.expect("no parent for a constructor"); . self.root . .tables . .attributes . .get(self, parent_id) . .expect("no encoded attributes for a structure or variant") . }) . .decode((self, sess)) 9 ( 0.00%) } . . fn get_struct_field_names( . self, . id: DefIndex, . sess: &'a Session, . ) -> impl Iterator> + 'a { 15 ( 0.00%) self.root . .tables . .children . .get(self, id) . .unwrap_or_else(Lazy::empty) . .decode(self) 50 ( 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 { 5 ( 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] { . tcx.arena.alloc_from_iter( -- line 1361 ---------------------------------------- -- line 1421 ---------------------------------------- . } . def_key.parent.and_then(|parent_index| match self.kind(parent_index) { . EntryKind::Trait(_) | EntryKind::TraitAlias => Some(self.local_def_id(parent_index)), . _ => None, . }) . } . . fn get_native_libraries(self, sess: &'a Session) -> impl Iterator + 'a { 38 ( 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] { 95 ( 0.00%) tcx.arena.alloc_from_iter(self.root.lang_items_missing.decode(self)) . } . . fn get_fn_param_names(self, tcx: TyCtxt<'tcx>, id: DefIndex) -> &'tcx [Ident] { . let param_names = match self.kind(id) { . EntryKind::Fn(data) | EntryKind::ForeignFn(data) => data.decode(self).param_names, . EntryKind::AssocFn(data) => data.decode(self).fn_data.param_names, . _ => Lazy::empty(), . }; -- line 1466 ---------------------------------------- -- line 1479 ---------------------------------------- . EntryKind::AnonConst(_, data) . | EntryKind::Const(_, data) . | EntryKind::AssocConst(_, _, data) => data.decode(self).0, . _ => bug!(), . } . } . . fn get_macro(self, id: DefIndex, sess: &Session) -> MacroDef { 6 ( 0.00%) match self.kind(id) { 1 ( 0.00%) EntryKind::MacroDef(macro_def) => macro_def.decode((self, sess)), . _ => bug!(), . } . } . . // This replicates some of the logic of the crate-local `is_const_fn_raw` query, because we . // don't serialize constness for tuple variant and tuple struct constructors. . fn is_const_fn_raw(self, id: DefIndex) -> bool { . let constness = match self.kind(id) { -- line 1496 ---------------------------------------- -- line 1536 ---------------------------------------- . } . } . . fn fn_sig(self, id: DefIndex, tcx: TyCtxt<'tcx>) -> ty::PolyFnSig<'tcx> { . self.root.tables.fn_sig.get(self, id).unwrap().decode((self, tcx)) . } . . #[inline] 2,737 ( 0.00%) fn def_key(self, index: DefIndex) -> DefKey { 782 ( 0.00%) *self . .def_key_cache . .lock() . .entry(index) 1,460 ( 0.00%) .or_insert_with(|| self.root.tables.def_keys.get(self, index).unwrap().decode(self)) 3,128 ( 0.00%) } . . // Returns the path leading to the thing with this `id`. . fn def_path(self, id: DefIndex) -> DefPath { . debug!("def_path(cnum={:?}, id={:?})", self.cnum, id); . DefPath::make(self.cnum, id, |parent| self.def_key(parent)) . } . . fn def_path_hash_unlocked( . self, . index: DefIndex, . def_path_hashes: &mut FxHashMap, . ) -> DefPathHash { 12 ( 0.00%) *def_path_hashes.entry(index).or_insert_with(|| { 15 ( 0.00%) self.root.tables.def_path_hashes.get(self, index).unwrap().decode(self) . }) . } . . #[inline] 42 ( 0.00%) fn def_path_hash(self, index: DefIndex) -> DefPathHash { . let mut def_path_hashes = self.def_path_hash_cache.lock(); . self.def_path_hash_unlocked(index, &mut def_path_hashes) 48 ( 0.00%) } . . #[inline] . fn def_path_hash_to_def_index(self, hash: DefPathHash) -> DefIndex { . self.def_path_hash_map.def_path_hash_to_def_index(&hash) . } . . fn expn_hash_to_expn_id(self, sess: &Session, index_guess: u32, hash: ExpnHash) -> ExpnId { . debug_assert_eq!(ExpnId::from_hash(hash), None); -- line 1580 ---------------------------------------- -- line 1635 ---------------------------------------- . /// Proc macro crates don't currently export spans, so this function does not have . /// to work for them. . fn imported_source_files(self, sess: &Session) -> &'a [ImportedSourceFile] { . // Translate the virtual `/rustc/$hash` prefix back to a real directory . // that should hold actual sources, where possible. . // . // NOTE: if you update this, you might need to also update bootstrap's code for generating . // the `rust-src` component in `Src::run` in `src/bootstrap/dist.rs`. 1,808 ( 0.00%) let virtual_rust_source_base_dir = option_env!("CFG_VIRTUAL_RUST_SOURCE_BASE_DIR") . .map(Path::new) . .filter(|_| { . // Only spend time on further checks if we have what to translate *to*. . sess.opts.real_rust_source_base_dir.is_some() . }) . .filter(|virtual_dir| { . // Don't translate away `/rustc/$hash` if we're still remapping to it, . // since that means we're still building `std`/`rustc` that need it, . // and we don't want the real path to leak into codegen/debuginfo. . !sess.opts.remap_path_prefix.iter().any(|(_from, to)| to == virtual_dir) . }); 1,808 ( 0.00%) let try_to_translate_virtual_to_real = |name: &mut rustc_span::FileName| { . debug!( . "try_to_translate_virtual_to_real(name={:?}): \ . virtual_rust_source_base_dir={:?}, real_rust_source_base_dir={:?}", . name, virtual_rust_source_base_dir, sess.opts.real_rust_source_base_dir, . ); . 2,630 ( 0.00%) if let Some(virtual_dir) = virtual_rust_source_base_dir { . if let Some(real_dir) = &sess.opts.real_rust_source_base_dir { . if let rustc_span::FileName::Real(old_name) = name { . if let rustc_span::RealFileName::Remapped { local_path: _, virtual_name } = . old_name . { . if let Ok(rest) = virtual_name.strip_prefix(virtual_dir) { . let virtual_name = virtual_name.clone(); . -- line 1670 ---------------------------------------- -- line 1709 ---------------------------------------- . *old_name = new_name; . } . } . } . } . } . }; . 1,805 ( 0.00%) self.cdata.source_map_import_info.get_or_init(|| { 18 ( 0.00%) let external_source_map = self.root.source_map.decode(self); . . external_source_map . .map(|source_file_to_import| { . // We can't reuse an existing SourceFile, so allocate a new one . // containing the information we need. . let rustc_span::SourceFile { 11,046 ( 0.01%) mut name, 3,156 ( 0.00%) src_hash, 526 ( 0.00%) start_pos, 1,052 ( 0.00%) end_pos, 2,630 ( 0.00%) mut lines, 2,630 ( 0.00%) mut multibyte_chars, 3,156 ( 0.00%) mut non_narrow_chars, 2,630 ( 0.00%) mut normalized_pos, 3,156 ( 0.00%) name_hash, . .. . } = source_file_to_import; . . // If this file is under $sysroot/lib/rustlib/src/ but has not been remapped . // during rust bootstrapping by `remap-debuginfo = true`, and the user . // wish to simulate that behaviour by -Z simulate-remapped-rust-src-base, . // then we change `name` to a similar state as if the rust was bootstrapped . // with `remap-debuginfo = true`. . // This is useful for testing so that tests about the effects of . // `try_to_translate_virtual_to_real` don't have to worry about how the . // compiler is bootstrapped. 1,052 ( 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 { 706,432 ( 0.40%) *pos = *pos - start_pos; . } . for mbc in &mut multibyte_chars { 1,594 ( 0.00%) mbc.pos = mbc.pos - start_pos; . } . for swc in &mut non_narrow_chars { 924 ( 0.00%) *swc = *swc - start_pos; . } . for np in &mut normalized_pos { . np.pos = np.pos - start_pos; . } . 9,468 ( 0.01%) let local_version = sess.source_map().new_imported_source_file( 6,838 ( 0.00%) name, 3,682 ( 0.00%) src_hash, . name_hash, . source_length, 1,052 ( 0.00%) self.cnum, 2,630 ( 0.00%) lines, 3,156 ( 0.00%) multibyte_chars, 2,630 ( 0.00%) non_narrow_chars, 2,104 ( 0.00%) normalized_pos, . start_pos, . end_pos, . ); . debug!( . "CrateMetaData::imported_source_files alloc \ . source_file {:?} original (start_pos {:?} end_pos {:?}) \ . translated (start_pos {:?} end_pos {:?})", . local_version.name, -- line 1804 ---------------------------------------- -- line 1808 ---------------------------------------- . local_version.end_pos . ); . . ImportedSourceFile { . original_start_pos: start_pos, . original_end_pos: end_pos, . translated_source_file: local_version, . } 1,578 ( 0.00%) }) . .collect() . }) . } . } . . impl CrateMetadata { 228 ( 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 { 57 ( 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 = 57 ( 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. 19 ( 0.00%) let def_path_hash_map = root.def_path_hash_map.decode(&blob); . 437 ( 0.00%) CrateMetadata { 19 ( 0.00%) blob, 57 ( 0.00%) root, 76 ( 0.00%) trait_impls, . raw_proc_macros, . source_map_import_info: OnceCell::new(), 76 ( 0.00%) def_path_hash_map, . expn_hash_map: Default::default(), 133 ( 0.00%) alloc_decoding_state, . cnum, 76 ( 0.00%) cnum_map, 95 ( 0.00%) dependencies, . dep_kind: Lock::new(dep_kind), 228 ( 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(), . } 171 ( 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 { 95 ( 0.00%) *extern_crate = Some(new_extern_crate); . } . update . } . . crate fn source(&self) -> &CrateSource { . &self.source . } . . crate fn dep_kind(&self) -> CrateDepKind { . *self.dep_kind.lock() . } . . crate fn update_dep_kind(&self, f: impl FnOnce(CrateDepKind) -> CrateDepKind) { 68 ( 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 { 5 ( 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 -- line 1925 ---------------------------------------- -- line 1941 ---------------------------------------- . self.root.hash . } . . fn num_def_ids(&self) -> usize { . self.root.tables.def_keys.size() . } . . fn local_def_id(&self, index: DefIndex) -> DefId { 637 ( 0.00%) DefId { krate: self.cnum, index } . } . . // Translate a DefId from the current compilation environment to a DefId . // for an external crate. . fn reverse_translate_def_id(&self, did: DefId) -> Option { . for (local, &global) in self.cnum_map.iter_enumerated() { . if global == did.krate { . return Some(DefId { krate: local, index: did.index }); -- line 1957 ---------------------------------------- 22,938 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/tokenstream.rs -------------------------------------------------------------------------------- Ir -- line 32 ---------------------------------------- . /// . /// If the syntax extension is an MBE macro, it will attempt to match its . /// LHS token tree against the provided token tree, and if it finds a . /// match, will transcribe the RHS token tree, splicing in any captured . /// `macro_parser::matched_nonterminals` into the `SubstNt`s it finds. . /// . /// The RHS of an MBE macro is the only place `SubstNt`s are substituted. . /// Nothing special happens to misnamed or misplaced `SubstNt`s. 465,362 ( 0.26%) #[derive(Debug, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)] . pub enum TokenTree { . /// A single token. 175,748 ( 0.10%) Token(Token), . /// A delimited sequence of token trees. 16,984 ( 0.01%) Delimited(DelimSpan, DelimToken, TokenStream), . } . . #[derive(Copy, Clone)] . pub enum CanSynthesizeMissingTokens { . Yes, . No, . } . -- line 53 ---------------------------------------- -- line 72 ---------------------------------------- . } . _ => false, . } . } . . /// Retrieves the `TokenTree`'s span. . pub fn span(&self) -> Span { . match self { 19 ( 0.00%) TokenTree::Token(token) => token.span, . TokenTree::Delimited(sp, ..) => sp.entire(), . } . } . . /// Modify the `TokenTree`'s span in-place. . pub fn set_span(&mut self, span: Span) { . match self { . TokenTree::Token(token) => token.span = span, . TokenTree::Delimited(dspan, ..) => *dspan = DelimSpan::from_single(span), . } . } . . pub fn token(kind: TokenKind, span: Span) -> TokenTree { 67,892 ( 0.04%) TokenTree::Token(Token::new(kind, span)) . } . . /// Returns the opening delimiter as a token tree. 8,487 ( 0.00%) pub fn open_tt(span: DelimSpan, delim: DelimToken) -> TokenTree { 25,461 ( 0.01%) TokenTree::token(token::OpenDelim(delim), span.open) 8,487 ( 0.00%) } . . /// Returns the closing delimiter as a token tree. 8,486 ( 0.00%) pub fn close_tt(span: DelimSpan, delim: DelimToken) -> TokenTree { 25,458 ( 0.01%) TokenTree::token(token::CloseDelim(delim), span.close) 8,486 ( 0.00%) } . 4,305 ( 0.00%) pub fn uninterpolate(self) -> TokenTree { 2,870 ( 0.00%) match self { 12,915 ( 0.01%) TokenTree::Token(token) => TokenTree::Token(token.uninterpolate().into_owned()), . tt => tt, . } 5,740 ( 0.00%) } . } . . impl HashStable for TokenStream . where . CTX: crate::HashStableContext, . { 18 ( 0.00%) fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) { 62 ( 0.00%) for sub_tt in self.trees() { . sub_tt.hash_stable(hcx, hasher); . } 16 ( 0.00%) } . } . . pub trait CreateTokenStream: sync::Send + sync::Sync { . fn create_token_stream(&self) -> AttrAnnotatedTokenStream; . } . . impl CreateTokenStream for AttrAnnotatedTokenStream { . fn create_token_stream(&self) -> AttrAnnotatedTokenStream { -- line 131 ---------------------------------------- -- line 188 ---------------------------------------- . Delimited(DelimSpan, DelimToken, AttrAnnotatedTokenStream), . /// Stores the attributes for an attribute target, . /// along with the tokens for that attribute target. . /// See `AttributesData` for more information . Attributes(AttributesData), . } . . impl AttrAnnotatedTokenStream { 16,970 ( 0.01%) pub fn new(tokens: Vec<(AttrAnnotatedTokenTree, Spacing)>) -> AttrAnnotatedTokenStream { . AttrAnnotatedTokenStream(Lrc::new(tokens)) 16,970 ( 0.01%) } . . /// 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); . 52,460 ( 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 { 10 ( 0.00%) TokenStream::new(vec![(tree, Spacing::Alone)]) . } . } . . impl From for TreeAndSpacing { . fn from(tree: TokenTree) -> TreeAndSpacing { 25,456 ( 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 { 8,483 ( 0.00%) self.0.is_empty() 8,483 ( 0.00%) } . . pub fn len(&self) -> usize { 75,110 ( 0.04%) self.0.len() . } . . pub fn from_streams(mut streams: SmallVec<[TokenStream; 2]>) -> TokenStream { . match streams.len() { . 0 => TokenStream::default(), . 1 => streams.pop().unwrap(), . _ => { . // We are going to extend the first stream in `streams` with -- line 421 ---------------------------------------- -- line 448 ---------------------------------------- . . // Create the final `TokenStream`. . TokenStream(first_stream_lrc) . } . } . } . . pub fn trees(&self) -> Cursor { 9 ( 0.00%) self.clone().into_trees() 18 ( 0.00%) } . 11,317 ( 0.01%) pub fn into_trees(self) -> Cursor { . Cursor::new(self) 22,634 ( 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; . 78 ( 0.00%) fn next(&mut self) -> Option { 17,570 ( 0.01%) self.next_with_spacing().map(|(tree, _)| tree) 104 ( 0.00%) } . } . . impl Cursor { . fn new(stream: TokenStream) -> Self { . Cursor { stream, index: 0 } . } . 375,420 ( 0.21%) pub fn next_with_spacing(&mut self) -> Option { 225,330 ( 0.13%) if self.index < self.stream.len() { 104,854 ( 0.06%) self.index += 1; 366,870 ( 0.21%) Some(self.stream.0[self.index - 1].clone()) . } else { 45,348 ( 0.03%) None . } 450,504 ( 0.26%) } . . 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; . } . 14 ( 0.00%) pub fn look_ahead(&self, n: usize) -> Option<&TokenTree> { 28 ( 0.00%) self.stream.0[self.index..].get(n).map(|(tree, _)| tree) 28 ( 0.00%) } . } . 26,926 ( 0.02%) #[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 } . } . 16,966 ( 0.01%) pub fn from_pair(open: Span, close: Span) -> Self { . DelimSpan { open, close } 8,483 ( 0.00%) } . . pub fn dummy() -> Self { . Self::from_single(DUMMY_SP) 8,496 ( 0.00%) } . 16 ( 0.00%) pub fn entire(self) -> Span { . self.open.with_hi(self.close.hi()) 12 ( 0.00%) } . } 70 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/analyze_source_file.rs -------------------------------------------------------------------------------- Ir -- line 4 ---------------------------------------- . #[cfg(test)] . mod tests; . . /// Finds all newlines, multi-byte characters, and non-narrow characters in a . /// SourceFile. . /// . /// This function will use an SSE2 enhanced implementation if hardware support . /// is detected at runtime. 22 ( 0.00%) pub fn analyze_source_file( . src: &str, . source_file_start_pos: BytePos, . ) -> (Vec, Vec, Vec) { 2 ( 0.00%) let mut lines = vec![source_file_start_pos]; . let mut multi_byte_chars = vec![]; . let mut non_narrow_chars = vec![]; . . // Calls the right implementation, depending on hardware support available. . analyze_source_file_dispatch( . src, . source_file_start_pos, . &mut lines, . &mut multi_byte_chars, . &mut non_narrow_chars, . ); . . // The code above optimistically registers a new line *after* each \n . // it encounters. If that point is already outside the source_file, remove . // it again. 2 ( 0.00%) if let Some(&last_line_start) = lines.last() { . let source_file_end = source_file_start_pos + BytePos::from_usize(src.len()); 2 ( 0.00%) assert!(source_file_end >= last_line_start); 2 ( 0.00%) if last_line_start == source_file_end { . lines.pop(); . } . } . 26 ( 0.00%) (lines, multi_byte_chars, non_narrow_chars) 16 ( 0.00%) } . . cfg_if::cfg_if! { . if #[cfg(all(any(target_arch = "x86", target_arch = "x86_64")))] { . fn analyze_source_file_dispatch(src: &str, . source_file_start_pos: BytePos, . lines: &mut Vec, . multi_byte_chars: &mut Vec, . non_narrow_chars: &mut Vec) { -- line 49 ---------------------------------------- -- line 101 ---------------------------------------- . . // For character in the chunk, see if its byte value is < 0, which . // indicates that it's part of a UTF-8 char. . let multibyte_test = _mm_cmplt_epi8(chunk, _mm_set1_epi8(0)); . // Create a bit mask from the comparison results. . let multibyte_mask = _mm_movemask_epi8(multibyte_test); . . // If the bit mask is all zero, we only have ASCII chars here: 29,282 ( 0.02%) if multibyte_mask == 0 { 4 ( 0.00%) assert!(intra_chunk_offset == 0); . . // Check if there are any control characters in the chunk. All . // control characters that we can encounter at this point have a . // byte value less than 32 or ... . let control_char_test0 = _mm_cmplt_epi8(chunk, _mm_set1_epi8(32)); . let control_char_mask0 = _mm_movemask_epi8(control_char_test0); . . // ... it's the ASCII 'DEL' character with a value of 127. . let control_char_test1 = _mm_cmpeq_epi8(chunk, _mm_set1_epi8(127)); . let control_char_mask1 = _mm_movemask_epi8(control_char_test1); . 29,282 ( 0.02%) let control_char_mask = control_char_mask0 | control_char_mask1; . 29,282 ( 0.02%) if control_char_mask != 0 { . // Check for newlines in the chunk . let newlines_test = _mm_cmpeq_epi8(chunk, _mm_set1_epi8(b'\n' as i8)); . let newlines_mask = _mm_movemask_epi8(newlines_test); . 14,320 ( 0.01%) if control_char_mask == newlines_mask { . // All control characters are newlines, record them . let mut newlines_mask = 0xFFFF0000 | newlines_mask as u32; . let output_offset = output_offset + 21,480 ( 0.01%) BytePos::from_usize(chunk_index * CHUNK_SIZE + 1); . . loop { . let index = newlines_mask.trailing_zeros(); . 31,320 ( 0.02%) if index >= CHUNK_SIZE as u32 { . // We have arrived at the end of the chunk. . break . } . . lines.push(BytePos(index) + output_offset); . . // Clear the bit, so we can find the next one. 25,500 ( 0.01%) newlines_mask &= (!1) << index; . } . . // We are done for this chunk. All control characters were . // newlines and we took care of those. . continue . } else { . // Some of the control characters are not newlines, . // fall through to the slow path below. -- line 154 ---------------------------------------- -- line 168 ---------------------------------------- . BytePos::from_usize(scan_start) + output_offset, . lines, . multi_byte_chars, . non_narrow_chars . ); . } . . // There might still be a tail left to analyze 8 ( 0.00%) let tail_start = chunk_count * CHUNK_SIZE + intra_chunk_offset; 6 ( 0.00%) if tail_start < src.len() { 10 ( 0.00%) analyze_source_file_generic(&src[tail_start as usize ..], . src.len() - tail_start, . output_offset + BytePos::from_usize(tail_start), . lines, . multi_byte_chars, . non_narrow_chars); . } . } . } else { -- line 186 ---------------------------------------- -- line 199 ---------------------------------------- . non_narrow_chars); . } . } . } . . // `scan_len` determines the number of bytes in `src` to scan. Note that the . // function can read past `scan_len` if a multi-byte character start within the . // range but extends past it. The overflow is returned by the function. 16 ( 0.00%) fn analyze_source_file_generic( . src: &str, . scan_len: usize, . output_offset: BytePos, . lines: &mut Vec, . multi_byte_chars: &mut Vec, . non_narrow_chars: &mut Vec, . ) -> usize { 4 ( 0.00%) assert!(src.len() >= scan_len); . let mut i = 0; . let src_bytes = src.as_bytes(); . 40 ( 0.00%) while i < scan_len { . let byte = unsafe { . // We verified that i < scan_len <= src.len() 34 ( 0.00%) *src_bytes.get_unchecked(i as usize) . }; . . // How much to advance in order to get to the next UTF-8 char in the . // string. . let mut char_len = 1; . 17 ( 0.00%) if byte < 32 { . // This is an ASCII control character, it could be one of the cases . // that are interesting to us. . . let pos = BytePos::from_usize(i) + output_offset; . 12 ( 0.00%) match byte { . b'\n' => { . lines.push(pos + BytePos(1)); . } . b'\t' => { . non_narrow_chars.push(NonNarrowChar::Tab(pos)); . } . _ => { . non_narrow_chars.push(NonNarrowChar::ZeroWidth(pos)); . } . } 28 ( 0.00%) } else if byte >= 127 { . // The slow path: . // This is either ASCII control character "DEL" or the beginning of . // a multibyte char. Just decode to `char`. . let c = (&src[i..]).chars().next().unwrap(); . char_len = c.len_utf8(); . . let pos = BytePos::from_usize(i) + output_offset; . -- line 254 ---------------------------------------- -- line 262 ---------------------------------------- . // FIXME: How can we decide between `width` and `width_cjk`? . let char_width = UnicodeWidthChar::width(c).unwrap_or(0); . . if char_width != 1 { . non_narrow_chars.push(NonNarrowChar::new(pos, char_width)); . } . } . 34 ( 0.00%) i += char_len; . } . 2 ( 0.00%) i - scan_len 18 ( 0.00%) } 14,381 ( 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)] 2,706,988 ( 1.54%) 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 { 13 ( 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 { 13,866 ( 0.01%) copy_nonoverlapping(src, tmp.as_mut_ptr(), 1); 507,307 ( 0.29%) 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 { 1,509,757 ( 0.86%) copy_nonoverlapping(&src as *const T, dst, 1); . intrinsics::forget(src); . } . } . . /// Overwrites a memory location with the given value without reading or . /// dropping the old value. . /// . /// Unlike [`write()`], the pointer may be unaligned. -- line 900 ---------------------------------------- -- line 1207 ---------------------------------------- . // `stride == 1` case can be computed more simply through `-p (mod a)`, but doing so . // inhibits LLVM's ability to select instructions like `lea`. Instead we compute . // . // round_up_to_next_alignment(p, a) - p . // . // which distributes operations around the load-bearing, but pessimizing `and` sufficiently . // for LLVM to be able to utilize the various optimizations it knows about. . return wrapping_sub( 122 ( 0.00%) wrapping_add(p as usize, a_minus_one) & wrapping_sub(0, a), . p as usize, . ); . } . . let pmoda = p as usize & a_minus_one; . if pmoda == 0 { . // Already aligned. Yay! . return 0; -- line 1223 ---------------------------------------- -- line 1348 ---------------------------------------- . /// assert!(std::ptr::eq( . /// &wrapper as &dyn Trait as *const dyn Trait as *const u8, . /// &wrapper.member as &dyn Trait as *const dyn Trait as *const u8, . /// )); . /// ``` . #[stable(feature = "ptr_eq", since = "1.17.0")] . #[inline] . pub fn eq(a: *const T, b: *const T) -> bool { 2,889 ( 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 ---------------------------------------- 383,651 ( 0.22%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/const_ptr.rs -------------------------------------------------------------------------------- Ir -- line 287 ---------------------------------------- . #[must_use = "returns a new pointer rather than modifying its argument"] . #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")] . #[inline(always)] . pub const unsafe fn offset(self, count: isize) -> *const T . where . T: Sized, . { . // SAFETY: the caller must uphold the safety contract for `offset`. 412,804 ( 0.23%) unsafe { intrinsics::offset(self, count) } . } . . /// Calculates the offset from a pointer using wrapping arithmetic. . /// . /// `count` is in units of T; e.g., a `count` of 3 represents a pointer . /// offset of `3 * size_of::()` bytes. . /// . /// # Safety -- line 303 ---------------------------------------- -- line 443 ---------------------------------------- . #[inline] . pub const unsafe fn offset_from(self, origin: *const T) -> isize . where . T: Sized, . { . let pointee_size = mem::size_of::(); . assert!(0 < pointee_size && pointee_size <= isize::MAX as usize); . // SAFETY: the caller must uphold the safety contract for `ptr_offset_from`. 13,735 ( 0.01%) unsafe { intrinsics::ptr_offset_from(self, origin) } . } . . /// Returns whether two pointers are guaranteed to be equal. . /// . /// At runtime this function behaves like `self == other`. . /// However, in some contexts (e.g., compile-time evaluation), . /// it is not always possible to determine equality of two pointers, so this function may . /// spuriously return `false` for pointers that later actually turn out to be equal. -- line 459 ---------------------------------------- -- line 474 ---------------------------------------- . /// of this issue. . #[unstable(feature = "const_raw_ptr_comparison", issue = "53020")] . #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")] . #[inline] . pub const fn guaranteed_eq(self, other: *const T) -> bool . where . T: Sized, . { 24 ( 0.00%) intrinsics::ptr_guaranteed_eq(self, other) . } . . /// Returns whether two pointers are guaranteed to be unequal. . /// . /// At runtime this function behaves like `self != other`. . /// However, in some contexts (e.g., compile-time evaluation), . /// it is not always possible to determine the inequality of two pointers, so this function may . /// spuriously return `false` for pointers that later actually turn out to be unequal. -- line 490 ---------------------------------------- 288,571 ( 0.16%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/index.rs -------------------------------------------------------------------------------- Ir -- line 154 ---------------------------------------- . . #[stable(feature = "slice_get_slice_impls", since = "1.15.0")] . unsafe impl SliceIndex<[T]> for usize { . type Output = T; . . #[inline] . fn get(self, slice: &[T]) -> Option<&T> { . // SAFETY: `self` is checked to be in bounds. 314,375 ( 0.18%) if self < slice.len() { unsafe { Some(&*self.get_unchecked(slice)) } } else { None } . } . . #[inline] . fn get_mut(self, slice: &mut [T]) -> Option<&mut T> { . // SAFETY: `self` is checked to be in bounds. 8 ( 0.00%) if self < slice.len() { unsafe { Some(&mut *self.get_unchecked_mut(slice)) } } else { None } . } . . #[inline] . unsafe fn get_unchecked(self, slice: *const [T]) -> *const T { . // SAFETY: the caller guarantees that `slice` is not dangling, so it . // cannot be longer than `isize::MAX`. They also guarantee that . // `self` is in bounds of `slice` so `self` cannot overflow an `isize`, . // so the call to `add` is safe. -- line 176 ---------------------------------------- -- line 181 ---------------------------------------- . unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut T { . // SAFETY: see comments for `get_unchecked` above. . unsafe { slice.as_mut_ptr().add(self) } . } . . #[inline] . fn index(self, slice: &[T]) -> &T { . // N.B., use intrinsic indexing 32,536 ( 0.02%) &(*slice)[self] . } . . #[inline] . fn index_mut(self, slice: &mut [T]) -> &mut T { . // N.B., use intrinsic indexing 1,540 ( 0.00%) &mut (*slice)[self] . } . } . . #[stable(feature = "slice_get_slice_impls", since = "1.15.0")] . unsafe impl SliceIndex<[T]> for ops::Range { . type Output = [T]; . . #[inline] . fn get(self, slice: &[T]) -> Option<&[T]> { 1,144 ( 0.00%) if self.start > self.end || self.end > slice.len() { . None . } else { . // SAFETY: `self` is checked to be valid and in bounds above. . unsafe { Some(&*self.get_unchecked(slice)) } . } . } . . #[inline] -- line 213 ---------------------------------------- -- line 221 ---------------------------------------- . } . . #[inline] . unsafe fn get_unchecked(self, slice: *const [T]) -> *const [T] { . // SAFETY: the caller guarantees that `slice` is not dangling, so it . // cannot be longer than `isize::MAX`. They also guarantee that . // `self` is in bounds of `slice` so `self` cannot overflow an `isize`, . // so the call to `add` is safe. 51,273 ( 0.03%) unsafe { ptr::slice_from_raw_parts(slice.as_ptr().add(self.start), self.end - self.start) } . } . . #[inline] . unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T] { . // SAFETY: see comments for `get_unchecked` above. . unsafe { 23,249 ( 0.01%) ptr::slice_from_raw_parts_mut(slice.as_mut_ptr().add(self.start), self.end - self.start) . } . } . . #[inline] . fn index(self, slice: &[T]) -> &[T] { 3 ( 0.00%) if self.start > self.end { . slice_index_order_fail(self.start, self.end); 6,364 ( 0.00%) } else if self.end > slice.len() { . slice_end_index_len_fail(self.end, slice.len()); . } . // SAFETY: `self` is checked to be valid and in bounds above. . unsafe { &*self.get_unchecked(slice) } . } . . #[inline] . fn index_mut(self, slice: &mut [T]) -> &mut [T] { 3,636 ( 0.00%) if self.start > self.end { . slice_index_order_fail(self.start, self.end); 23,255 ( 0.01%) } else if self.end > slice.len() { . slice_end_index_len_fail(self.end, slice.len()); . } . // SAFETY: `self` is checked to be valid and in bounds above. . unsafe { &mut *self.get_unchecked_mut(slice) } . } . } . . #[stable(feature = "slice_get_slice_impls", since = "1.15.0")] -- line 263 ---------------------------------------- -- line 320 ---------------------------------------- . #[inline] . unsafe fn get_unchecked_mut(self, slice: *mut [T]) -> *mut [T] { . // SAFETY: the caller has to uphold the safety contract for `get_unchecked_mut`. . unsafe { (self.start..slice.len()).get_unchecked_mut(slice) } . } . . #[inline] . fn index(self, slice: &[T]) -> &[T] { 686 ( 0.00%) if self.start > slice.len() { . slice_start_index_len_fail(self.start, slice.len()); . } . // SAFETY: `self` is checked to be valid and in bounds above. . unsafe { &*self.get_unchecked(slice) } . } . . #[inline] . fn index_mut(self, slice: &mut [T]) -> &mut [T] { 27 ( 0.00%) if self.start > slice.len() { . slice_start_index_len_fail(self.start, slice.len()); . } . // SAFETY: `self` is checked to be valid and in bounds above. . unsafe { &mut *self.get_unchecked_mut(slice) } . } . } . . #[stable(feature = "slice_get_slice_impls", since = "1.15.0")] -- line 345 ---------------------------------------- -- line 542 ---------------------------------------- . } . ops::Bound::Excluded(&end) => end, . ops::Bound::Unbounded => len, . }; . . if start > end { . slice_index_order_fail(start, end); . } 26 ( 0.00%) if end > len { . slice_end_index_len_fail(end, len); . } . . ops::Range { start, end } . } . . /// Convert pair of `ops::Bound`s into `ops::Range` without performing any bounds checking and (in debug) overflow checking . fn into_range_unchecked( -- line 558 ---------------------------------------- 12,375 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/mod.rs -------------------------------------------------------------------------------- Ir -- line 26 ---------------------------------------- . pub struct UnmatchedBrace { . pub expected_delim: token::DelimToken, . pub found_delim: Option, . pub found_span: Span, . pub unclosed_span: Option, . pub candidate_span: Option, . } . 28 ( 0.00%) crate fn parse_token_trees<'a>( . sess: &'a ParseSess, . src: &'a str, . start_pos: BytePos, . override_span: Option, . ) -> (PResult<'a, TokenStream>, Vec) { . StringReader { sess, start_pos, pos: start_pos, end_src_index: src.len(), src, override_span } . .into_token_trees() 18 ( 0.00%) } . . struct StringReader<'a> { . sess: &'a ParseSess, . /// Initial position, read-only. . start_pos: BytePos, . /// The absolute offset within the source_map of the current character. . pos: BytePos, . /// Stop reading src at this index. -- line 50 ---------------------------------------- -- line 51 ---------------------------------------- . end_src_index: usize, . /// Source text to tokenize. . src: &'a str, . override_span: Option, . } . . impl<'a> StringReader<'a> { . fn mk_sp(&self, lo: BytePos, hi: BytePos) -> Span { 65,074 ( 0.04%) self.override_span.unwrap_or_else(|| Span::with_root_ctxt(lo, hi)) . } . . /// Returns the next token, and info about preceding whitespace, if any. 346,612 ( 0.20%) fn next_token(&mut self) -> (Spacing, Token) { . let mut spacing = Spacing::Joint; . . // Skip `#!` at the start of the file 99,032 ( 0.06%) let start_src_index = self.src_index(self.pos); 148,548 ( 0.08%) let text: &str = &self.src[start_src_index..self.end_src_index]; . let is_beginning_of_file = self.pos == self.start_pos; 49,516 ( 0.03%) if is_beginning_of_file { 8 ( 0.00%) if let Some(shebang_len) = rustc_lexer::strip_shebang(text) { . self.pos = self.pos + BytePos::from_usize(shebang_len); . spacing = Spacing::Alone; . } . } . . // Skip trivial (whitespace & comments) tokens . loop { 83,486 ( 0.05%) let start_src_index = self.src_index(self.pos); 199,503 ( 0.11%) let text: &str = &self.src[start_src_index..self.end_src_index]; . 66,501 ( 0.04%) if text.is_empty() { . let span = self.mk_sp(self.pos, self.pos); 10 ( 0.00%) return (spacing, Token::new(token::Eof, span)); . } . 199,497 ( 0.11%) let token = rustc_lexer::first_token(text); . 132,998 ( 0.08%) let start = self.pos; 66,499 ( 0.04%) self.pos = self.pos + BytePos::from_usize(token.len); . . debug!("next_token: {:?}({:?})", token.kind, self.str_from(start)); . 532,068 ( 0.30%) match self.cook_lexer_token(token.kind, start) { 396,112 ( 0.23%) Some(kind) => { . let span = self.mk_sp(start, self.pos); 297,084 ( 0.17%) return (spacing, Token::new(kind, span)); . } . None => spacing = Spacing::Alone, . } . } 445,644 ( 0.25%) } . . /// 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 150 ---------------------------------------- . ); . } . } . . /// 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 { 332,495 ( 0.19%) Some(match token { 19 ( 0.00%) rustc_lexer::TokenKind::LineComment { doc_style } => { . // Skip non-doc comments 95 ( 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); 95 ( 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 => { 62,224 ( 0.04%) let is_raw_ident = token == rustc_lexer::TokenKind::RawIdent; 77,780 ( 0.04%) let is_unknown_prefix = token == rustc_lexer::TokenKind::UnknownPrefix; . let mut ident_start = start; 31,112 ( 0.02%) if is_raw_ident { . ident_start = ident_start + BytePos(2); . } 46,668 ( 0.03%) if is_unknown_prefix { . self.report_unknown_prefix(start); . } 77,780 ( 0.04%) let sym = nfc_normalize(self.str_from(ident_start)); . let span = self.mk_sp(start, self.pos); 62,224 ( 0.04%) self.sess.symbol_gallery.insert(sym, span); 31,112 ( 0.02%) 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); . } 108,892 ( 0.06%) 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) . } 45,216 ( 0.03%) 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); 8,478 ( 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 . }; 22,608 ( 0.01%) token::Literal(token::Lit { kind, symbol, suffix }) . } . rustc_lexer::TokenKind::Lifetime { starts_with_number } => { . // Include the leading `'` in the real identifier, for macro . // expansion purposes. See #12512 for the gory details of why . // this is necessary. . let lifetime_name = self.str_from(start); . if starts_with_number { . self.err_span_(start, self.pos, "lifetimes cannot start with a number"); -- line 280 ---------------------------------------- -- line 324 ---------------------------------------- . err.help("source files must contain UTF-8 encoded text, unexpected null bytes might occur when a different encoding is used"); . } . err.emit(); . token? . } . }) . } . 228 ( 0.00%) fn cook_doc_comment( . &self, . content_start: BytePos, . content: &str, . comment_kind: CommentKind, . doc_style: DocStyle, . ) -> TokenKind { 19 ( 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, . }; . 57 ( 0.00%) token::DocComment(comment_kind, attr_style, Symbol::intern(content)) 285 ( 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 380 ---------------------------------------- . self.sess.span_diagnostic.span_fatal_with_code( . self.mk_sp(start + BytePos(1), suffix_start), . "unterminated byte constant", . error_code!(E0763), . ) . } . (token::Byte, Mode::Byte, 2, 1) // b' ' . } 2,826 ( 0.00%) rustc_lexer::LiteralKind::Str { terminated } => { 2,826 ( 0.00%) if !terminated { . self.sess.span_diagnostic.span_fatal_with_code( . self.mk_sp(start, suffix_start), . "unterminated double quote string", . error_code!(E0765), . ) . } . (token::Str, Mode::Str, 1, 1) // " " . } -- line 397 ---------------------------------------- -- line 452 ---------------------------------------- . } . . let id = self.symbol_from_to(start, suffix_start); . return (token::Float, id); . } . }; . let content_start = start + BytePos(prefix_len); . let content_end = suffix_start - BytePos(postfix_len); 8,478 ( 0.00%) let id = self.symbol_from_to(content_start, content_end); . self.validate_literal_escape(mode, content_start, content_end, prefix_len, postfix_len); . (lit_kind, id) . } . . #[inline] . fn src_index(&self, pos: BytePos) -> usize { . (pos - self.start_pos).to_usize() . } . . /// Slice of the source text from `start` up to but excluding `self.pos`, . /// meaning the slice does not include the character `self.ch`. . fn str_from(&self, start: BytePos) -> &str { 93,469 ( 0.05%) 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); 33,912 ( 0.02%) Symbol::intern(self.str_from_to(start, end)) . } . . /// Slice of the source text spanning from `start` up to but excluding `end`. 21,227 ( 0.01%) fn str_from_to(&self, start: BytePos, end: BytePos) -> &str { . &self.src[self.src_index(start)..self.src_index(end)] 84,908 ( 0.05%) } . . 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 609 ---------------------------------------- . fn validate_literal_escape( . &self, . mode: Mode, . content_start: BytePos, . content_end: BytePos, . prefix_len: u32, . postfix_len: u32, . ) { 16,956 ( 0.01%) let lit_content = self.str_from_to(content_start, content_end); 458,388 ( 0.26%) unescape::unescape_literal(lit_content, mode, &mut |range, result| { . // Here we only check for errors. The actual unescaping is done later. 99,054 ( 0.06%) if let Err(err) = result { . let span_with_quotes = self . .mk_sp(content_start - BytePos(prefix_len), content_end + BytePos(postfix_len)); . let (start, end) = (range.start as u32, range.end as u32); . let lo = content_start + BytePos(start); . let hi = lo + BytePos(end - start); . let span = self.mk_sp(lo, hi); . emit_unescape_error( . &self.sess.span_diagnostic, -- line 628 ---------------------------------------- -- line 629 ---------------------------------------- . lit_content, . span_with_quotes, . span, . mode, . range, . err, . ); . } 445,743 ( 0.25%) }); . } . . fn validate_int_literal(&self, base: Base, content_start: BytePos, content_end: BytePos) { . let base = match base { . Base::Binary => 2, . Base::Octal => 8, . _ => return, . }; -- line 645 ---------------------------------------- -- 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)); . } . } . } . } . 140,004 ( 0.08%) pub fn nfc_normalize(string: &str) -> Symbol { . use unicode_normalization::{is_nfc_quick, IsNormalized, UnicodeNormalization}; 31,112 ( 0.02%) match is_nfc_quick(string.chars()) { 155,560 ( 0.09%) IsNormalized::Yes => Symbol::intern(string), . _ => { . let normalized_str: String = string.chars().nfc().collect(); . Symbol::intern(&normalized_str) . } . } . } 226,533 ( 0.13%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/rustc_entry.rs -------------------------------------------------------------------------------- Ir -- line 26 ---------------------------------------- . /// } . /// . /// assert_eq!(letters[&'s'], 2); . /// assert_eq!(letters[&'t'], 3); . /// assert_eq!(letters[&'u'], 1); . /// assert_eq!(letters.get(&'y'), None); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 147,720 ( 0.08%) pub fn rustc_entry(&mut self, key: K) -> RustcEntry<'_, K, V, A> { . let hash = make_insert_hash(&self.hash_builder, &key); 130 ( 0.00%) if let Some(elem) = self.table.find(hash, |q| q.0.eq(&key)) { 28,674 ( 0.02%) RustcEntry::Occupied(RustcOccupiedEntry { 17 ( 0.00%) key: Some(key), . elem, . table: &mut self.table, . }) . } else { . // Ideally we would put this in VacantEntry::insert, but Entry is not . // generic over the BuildHasher and adding a generic parameter would be . // a breaking change. . self.reserve(1); . 6,526 ( 0.00%) RustcEntry::Vacant(RustcVacantEntry { . hash, 41 ( 0.00%) key, . table: &mut self.table, . }) . } 131,144 ( 0.07%) } . } . . /// A view into a single entry in a map, which may either be vacant or occupied. . /// . /// This `enum` is constructed from the [`entry`] method on [`HashMap`]. . /// . /// [`HashMap`]: struct.HashMap.html . /// [`entry`]: struct.HashMap.html#method.rustc_entry -- line 62 ---------------------------------------- -- line 405 ---------------------------------------- . /// if let RustcEntry::Occupied(o) = map.rustc_entry("poneyland") { . /// *o.into_mut() += 10; . /// } . /// . /// assert_eq!(map["poneyland"], 22); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn into_mut(self) -> &'a mut V { 145 ( 0.00%) unsafe { &mut self.elem.as_mut().1 } . } . . /// Sets the value of the entry, and returns the entry's old value. . /// . /// # Examples . /// . /// ``` . /// use hashbrown::HashMap; -- line 421 ---------------------------------------- -- line 568 ---------------------------------------- . /// let mut map: HashMap<&str, u32> = HashMap::new(); . /// . /// if let RustcEntry::Vacant(o) = map.rustc_entry("poneyland") { . /// o.insert(37); . /// } . /// assert_eq!(map["poneyland"], 37); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 84 ( 0.00%) pub fn insert(self, value: V) -> &'a mut V { . unsafe { 7,622 ( 0.00%) let bucket = self.table.insert_no_grow(self.hash, (self.key, value)); 23 ( 0.00%) &mut bucket.as_mut().1 . } 104 ( 0.00%) } . . /// Sets the value of the entry with the RustcVacantEntry's key, . /// and returns a RustcOccupiedEntry. . /// . /// # Examples . /// . /// ``` . /// use hashbrown::HashMap; -- line 589 ---------------------------------------- 63,316 ( 0.04%) -------------------------------------------------------------------------------- -- 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 { 257,429 ( 0.15%) 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 { 77,628 ( 0.04%) 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 { 340 ( 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 { 874 ( 0.00%) 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) { 23,089 ( 0.01%) self.buf.reserve(self.len, additional); . } . . /// Reserves the minimum capacity for exactly `additional` more elements to . /// be inserted in the given `Vec`. After calling `reserve_exact`, . /// capacity will be greater than or equal to `self.len() + additional`. . /// Does nothing if the capacity is already sufficient. . /// . /// Note that the allocator may give the collection more space than it -- line 817 ---------------------------------------- -- line 829 ---------------------------------------- . /// ``` . /// let mut vec = vec![1]; . /// vec.reserve_exact(10); . /// assert!(vec.capacity() >= 11); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn reserve_exact(&mut self, additional: usize) { 47 ( 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. 426 ( 0.00%) if self.capacity() > self.len { 2 ( 0.00%) self.buf.shrink_to_fit(self.len); . } . } . . /// Shrinks the capacity of the vector with a lower bound. . /// . /// The capacity will remain at least as large as both the length . /// and the supplied value. . /// -- line 947 ---------------------------------------- -- line 990 ---------------------------------------- . /// let slice = vec.into_boxed_slice(); . /// assert_eq!(slice.into_vec().capacity(), 3); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn into_boxed_slice(mut self) -> Box<[T], A> { . unsafe { . self.shrink_to_fit(); 25 ( 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")] 318,343 ( 0.18%) 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. 191,041 ( 0.11%) 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); 63,707 ( 0.04%) self.len = len; . ptr::drop_in_place(s); . } 382,010 ( 0.22%) } . . /// 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. 198,230 ( 0.11%) 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. 614,377 ( 0.35%) 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()); . 26,963 ( 0.02%) self.len = new_len; . } . . /// Removes an element from the vector and returns it. . /// . /// The removed element is replaced by the last element of the vector. . /// . /// This does not preserve ordering, but is *O*(1). . /// If you need to preserve the element order, use [`remove`] instead. -- line 1275 ---------------------------------------- -- line 1329 ---------------------------------------- . /// let mut vec = vec![1, 2, 3]; . /// vec.insert(1, 4); . /// assert_eq!(vec, [1, 4, 2, 3]); . /// vec.insert(4, 5); . /// assert_eq!(vec, [1, 4, 2, 3, 5]); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] 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(); 10 ( 0.00%) if index > len { . assert_failed(index, len); . } . . // space for the new element 16 ( 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.) 24 ( 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); . } 16 ( 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); . } . 2,968 ( 0.00%) let len = self.len(); 9,047 ( 0.01%) 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. 45,200 ( 0.03%) ret = ptr::read(ptr); . . // Shift everything down to fill in that spot. 5,936 ( 0.00%) ptr::copy(ptr.offset(1), ptr, len - index - 1); . } 2,968 ( 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")] 48 ( 0.00%) pub fn retain(&mut self, mut f: F) . where . F: FnMut(&T) -> bool, . { . self.retain_mut(|elem| f(elem)); 48 ( 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, . { 7 ( 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) { 8 ( 0.00%) if self.deleted_cnt > 0 { . // SAFETY: Trailing unchecked items must be valid since we never touch them. . unsafe { . ptr::copy( . self.v.as_ptr().add(self.processed_len), . self.v.as_mut_ptr().add(self.processed_len - self.deleted_cnt), . self.original_len - self.processed_len, . ); . } . } . // SAFETY: After filling holes, all items are in contiguous memory. . unsafe { 2 ( 0.00%) self.v.set_len(self.original_len - self.deleted_cnt); . } . } . } . . let mut g = BackshiftOnDrop { v: self, processed_len: 0, deleted_cnt: 0, original_len }; . . fn process_loop( . original_len: usize, . f: &mut F, . g: &mut BackshiftOnDrop<'_, T, A>, . ) where . F: FnMut(&mut T) -> bool, . { 34 ( 0.00%) while g.processed_len != original_len { . // SAFETY: Unchecked element must be valid. . let cur = unsafe { &mut *g.v.as_mut_ptr().add(g.processed_len) }; . if !f(cur) { . // Advance early to avoid double drop if `drop_in_place` panicked. . g.processed_len += 1; . g.deleted_cnt += 1; . // SAFETY: We never touch this element again after dropped. . unsafe { ptr::drop_in_place(cur) }; -- line 1541 ---------------------------------------- -- line 1606 ---------------------------------------- . /// ``` . /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"]; . /// . /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b)); . /// . /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]); . /// ``` . #[stable(feature = "dedup_by", since = "1.16.0")] 7 ( 0.00%) pub fn dedup_by(&mut self, mut same_bucket: F) . where . F: FnMut(&mut T, &mut T) -> bool, . { 1 ( 0.00%) let len = self.len(); 12 ( 0.00%) if len <= 1 { . return; . } . . /* INVARIANT: vec.len() > read >= write > write-1 >= 0 */ . struct FillGapOnDrop<'a, T, A: core::alloc::Allocator> { . /* Offset of the element we want to check if it is duplicate */ . read: usize, . -- line 1627 ---------------------------------------- -- line 1699 ---------------------------------------- . } . . /* Technically we could let `gap` clean up with its Drop, but . * when `same_bucket` is guaranteed to not panic, this bloats a little . * the codegen, so we just do it manually */ . gap.vec.set_len(gap.write); . mem::forget(gap); . } 8 ( 0.00%) } . . /// Appends an element to the back of a collection. . /// . /// # Panics . /// . /// Panics if the new capacity exceeds `isize::MAX` bytes. . /// . /// # Examples -- line 1715 ---------------------------------------- -- line 1720 ---------------------------------------- . /// assert_eq!(vec, [1, 2, 3]); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn push(&mut self, value: T) { . // This will panic or abort if we would allocate > isize::MAX bytes . // or if the length increment would overflow for zero-sized types. 1,558,750 ( 0.89%) if self.len == self.buf.capacity() { 54,274 ( 0.03%) self.buf.reserve_for_push(self.len); . } . unsafe { 24,354 ( 0.01%) let end = self.as_mut_ptr().add(self.len); . ptr::write(end, value); 1,770,102 ( 1.01%) 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 { 59,872 ( 0.03%) if self.len == 0 { 3 ( 0.00%) None . } else { . unsafe { 35,466 ( 0.02%) self.len -= 1; 15 ( 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 1789 ---------------------------------------- . } . . /// 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); 21,803 ( 0.01%) let len = self.len(); . unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) }; 84,516 ( 0.05%) 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. . // 20 ( 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). 14 ( 0.00%) let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start), end - start); 47 ( 0.00%) Drain { . tail_start: end, 14 ( 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) { 547,520 ( 0.31%) 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 { 38,470 ( 0.02%) self.len() == 0 . } . . /// Splits the collection into two at the given index. . /// . /// Returns a newly allocated vector containing the elements in the range . /// `[at, len)`. After the call, the original vector will be left containing . /// the elements `[0, at)` with its previous capacity unchanged. . /// -- line 1916 ---------------------------------------- -- line 1994 ---------------------------------------- . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "vec_resize_with", since = "1.33.0")] . pub fn resize_with(&mut self, new_len: usize, f: F) . where . F: FnMut() -> T, . { . let len = self.len(); . if new_len > len { 36 ( 0.00%) self.extend_with(new_len - len, ExtendFunc(f)); . } else { . self.truncate(new_len); . } . } . . /// Consumes and leaks the `Vec`, returning a mutable reference to the contents, . /// `&'a mut [T]`. Note that the type `T` must outlive the chosen lifetime . /// `'a`. If the type has only static references, or none at all, then this -- line 2010 ---------------------------------------- -- line 2070 ---------------------------------------- . #[stable(feature = "vec_spare_capacity", since = "1.60.0")] . #[inline] . pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit] { . // Note: . // This method is not implemented in terms of `split_at_spare_mut`, . // to prevent invalidation of pointers to the buffer. . unsafe { . slice::from_raw_parts_mut( 2 ( 0.00%) self.as_mut_ptr().add(self.len) as *mut MaybeUninit, 23 ( 0.00%) self.buf.capacity() - self.len, . ) . } . } . . /// Returns vector content as a slice of `T`, along with the remaining spare . /// capacity of the vector as a slice of `MaybeUninit`. . /// . /// The returned spare capacity slice can be used to fill the vector with data -- line 2087 ---------------------------------------- -- line 2193 ---------------------------------------- . /// assert_eq!(vec, [1, 2]); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "vec_resize", since = "1.5.0")] . pub fn resize(&mut self, new_len: usize, value: T) { . let len = self.len(); . . if new_len > len { 15 ( 0.00%) self.extend_with(new_len - len, ExtendElement(value)) . } else { . self.truncate(new_len); . } . } . . /// Clones and appends all elements in a slice to the `Vec`. . /// . /// Iterates over the slice `other`, clones each element, and then appends -- line 2209 ---------------------------------------- -- line 2291 ---------------------------------------- . fn last(mut self) -> T { . (self.0)() . } . } . . impl Vec { . #[cfg(not(no_global_oom_handling))] . /// Extend the vector by `n` values, using the given generator. 258 ( 0.00%) fn extend_with>(&mut self, n: usize, mut value: E) { . self.reserve(n); . . unsafe { 35 ( 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); . } . 307 ( 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 . } 199 ( 0.00%) } . } . . impl Vec { . /// Removes consecutive repeated elements in the vector according to the . /// [`PartialEq`] trait implementation. . /// . /// If the vector is sorted, this removes all duplicates. . /// -- line 2333 ---------------------------------------- -- line 2338 ---------------------------------------- . /// . /// vec.dedup(); . /// . /// assert_eq!(vec, [1, 2, 3, 2]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . pub fn dedup(&mut self) { 2 ( 0.00%) self.dedup_by(|a, b| a == b) . } . } . . //////////////////////////////////////////////////////////////////////////////// . // Internal methods and functions . //////////////////////////////////////////////////////////////////////////////// . . #[doc(hidden)] . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] 40 ( 0.00%) pub fn from_elem(elem: T, n: usize) -> Vec { 162 ( 0.00%) ::from_elem(elem, n, Global) 35 ( 0.00%) } . . #[doc(hidden)] . #[cfg(not(no_global_oom_handling))] . #[unstable(feature = "allocator_api", issue = "32838")] . pub fn from_elem_in(elem: T, n: usize, alloc: A) -> Vec { . ::from_elem(elem, n, alloc) . } . -- line 2367 ---------------------------------------- -- line 2424 ---------------------------------------- . // Common trait implementations for Vec . //////////////////////////////////////////////////////////////////////////////// . . #[stable(feature = "rust1", since = "1.0.0")] . impl ops::Deref for Vec { . type Target = [T]; . . fn deref(&self) -> &[T] { 137,853 ( 0.08%) 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] { 3,681 ( 0.00%) 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))] 70,170 ( 0.04%) fn clone(&self) -> Self { . let alloc = self.allocator().clone(); 2 ( 0.00%) <[T]>::to_vec_in(&**self, alloc) 92,948 ( 0.05%) } . . // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is . // required for this method definition, is not available. Instead use the . // `slice::to_vec` function which is only available with cfg(test) . // NB see the slice::hack module in slice.rs for more information . #[cfg(test)] . fn clone(&self) -> Self { . let alloc = self.allocator().clone(); -- line 2487 ---------------------------------------- -- line 2539 ---------------------------------------- . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl FromIterator for Vec { . #[inline] . fn from_iter>(iter: I) -> Vec { 1,893 ( 0.00%) >::from_iter(iter.into_iter()) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl IntoIterator for Vec { . type Item = T; . type IntoIter = IntoIter; . -- line 2555 ---------------------------------------- -- line 2564 ---------------------------------------- . /// for s in v.into_iter() { . /// // s has type String, not &String . /// println!("{}", s); . /// } . /// ``` . #[inline] . fn into_iter(self) -> IntoIter { . unsafe { 14,799 ( 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(); 272 ( 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> { 1,052 ( 0.00%) self.iter_mut() . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl Extend for Vec { . #[inline] . fn extend>(&mut self, iter: I) { 375 ( 0.00%) >::spec_extend(self, iter.into_iter()) . } . . #[inline] . fn extend_one(&mut self, item: T) { . self.push(item); . } . . #[inline] -- line 2626 ---------------------------------------- -- line 2636 ---------------------------------------- . fn extend_desugared>(&mut self, mut iterator: I) { . // This is the case for a general iterator. . // . // This function should be the moral equivalent of: . // . // for item in iterator { . // self.push(item); . // } 421 ( 0.00%) while let Some(element) = iterator.next() { 3 ( 0.00%) let len = self.len(); 3,261 ( 0.00%) if len == self.capacity() { . let (lower, _) = iterator.size_hint(); . self.reserve(lower.saturating_add(1)); . } . unsafe { . ptr::write(self.as_mut_ptr().add(len), element); . // Since next() executes user code which can panic we have to bump the length . // after each step. . // NB can't overflow since we would have had to alloc the address space 3,323 ( 0.00%) self.set_len(len + 1); . } . } . } . . /// 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`. . /// -- line 2663 ---------------------------------------- -- 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, . { 4 ( 0.00%) let old_len = self.len(); . . // Guard against us getting leaked (leak amplification) . unsafe { . self.set_len(0); . } . . DrainFilter { vec: self, idx: 0, del: 0, old_len, pred: filter, panic_flag: false } . } -- line 2761 ---------------------------------------- -- line 2803 ---------------------------------------- . #[inline] . fn cmp(&self, other: &Self) -> Ordering { . Ord::cmp(&**self, &**other) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . unsafe impl<#[may_dangle] T, A: Allocator> Drop for Vec { 109,769 ( 0.06%) 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 65,817 ( 0.04%) ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len)) . } . // RawVec handles deallocation 128,302 ( 0.07%) } . } . . #[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 ---------------------------------------- 84,023 ( 0.05%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/fmt/mod.rs -------------------------------------------------------------------------------- Ir -- line 177 ---------------------------------------- . /// f.write_fmt(format_args!("{}", s)) . /// } . /// . /// let mut buf = String::new(); . /// writer(&mut buf, "world").unwrap(); . /// assert_eq!(&buf, "world"); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 30 ( 0.00%) fn write_fmt(mut self: &mut Self, args: Arguments<'_>) -> Result { 57,713 ( 0.03%) write(&mut self, args) 30 ( 0.00%) } . } . . #[stable(feature = "fmt_write_blanket_impl", since = "1.4.0")] . impl Write for &mut W { 100,912 ( 0.06%) fn write_str(&mut self, s: &str) -> Result { 14,446 ( 0.01%) (**self).write_str(s) 100,912 ( 0.06%) } . 1 ( 0.00%) fn write_char(&mut self, c: char) -> Result { 1 ( 0.00%) (**self).write_char(c) 3 ( 0.00%) } . . fn write_fmt(&mut self, args: Arguments<'_>) -> Result { . (**self).write_fmt(args) . } . } . . /// Configuration for formatting. . /// -- line 206 ---------------------------------------- -- line 228 ---------------------------------------- . /// . /// This can be used as a micro-optimization in cases where a full `Arguments` . /// structure (as created by `format_args!`) is not necessary; `Arguments` . /// is a little more expensive to use in simple formatting scenarios. . /// . /// Currently not intended for use outside of the standard library. . #[unstable(feature = "fmt_internals", reason = "internal to standard library", issue = "none")] . #[doc(hidden)] 8,544 ( 0.00%) pub fn new(buf: &'a mut (dyn Write + 'a)) -> Formatter<'a> { 60,318 ( 0.03%) Formatter { . flags: 0, . fill: ' ', . align: rt::v1::Alignment::Unknown, . width: None, . precision: None, . buf, . } 4,272 ( 0.00%) } . } . . // NB. Argument is essentially an optimized partially applied formatting function, . // equivalent to `exists T.(&T, fn(&T, &mut Formatter<'_>) -> Result`. . . extern "C" { . type Opaque; . } -- line 253 ---------------------------------------- -- line 357 ---------------------------------------- . #[doc(hidden)] . #[inline] . #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")] . #[rustc_const_unstable(feature = "const_fmt_arguments_new", issue = "none")] . pub const fn new_v1(pieces: &'a [&'static str], args: &'a [ArgumentV1<'a>]) -> Arguments<'a> { . if pieces.len() < args.len() || pieces.len() > args.len() + 1 { . panic!("invalid args"); . } 51,718 ( 0.03%) Arguments { pieces, fmt: None, args } . } . . /// This function is used to specify nonstandard formatting parameters. . /// . /// An `UnsafeArg` is required because the following invariants must be held . /// in order for this function to be safe: . /// 1. The `pieces` slice must be at least as long as `fmt`. . /// 2. Every [`rt::v1::Argument::position`] value within `fmt` must be a -- line 373 ---------------------------------------- -- line 379 ---------------------------------------- . #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")] . #[rustc_const_unstable(feature = "const_fmt_arguments_new", issue = "none")] . pub const fn new_v1_formatted( . pieces: &'a [&'static str], . args: &'a [ArgumentV1<'a>], . fmt: &'a [rt::v1::Argument], . _unsafe_arg: UnsafeArg, . ) -> Arguments<'a> { 32 ( 0.00%) Arguments { pieces, fmt: Some(fmt), args } . } . . /// Estimates the length of the formatted text. . /// . /// This is intended to be used for setting initial `String` capacity . /// when using `format!`. Note: this is neither the lower nor upper bound. . #[doc(hidden)] . #[inline] . #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")] . pub fn estimated_capacity(&self) -> usize { . let pieces_length: usize = self.pieces.iter().map(|x| x.len()).sum(); . 5,750 ( 0.00%) if self.args.is_empty() { . pieces_length 23,000 ( 0.01%) } else if !self.pieces.is_empty() && self.pieces[0].is_empty() && pieces_length < 16 { . // If the format string starts with an argument, . // don't preallocate anything, unless length . // of pieces is significant. . 0 . } else { . // There are some arguments, so any additional push . // will reallocate the string. To avoid that, . // we're "pre-doubling" the capacity here. -- line 410 ---------------------------------------- -- line 1146 ---------------------------------------- . /// let mut output = String::new(); . /// write!(&mut output, "Hello {}!", "world") . /// .expect("Error occurred while trying to write in String"); . /// assert_eq!(output, "Hello world!"); . /// ``` . /// . /// [`write!`]: crate::write! . #[stable(feature = "rust1", since = "1.0.0")] 52,029 ( 0.03%) pub fn write(output: &mut dyn Write, args: Arguments<'_>) -> Result { . let mut formatter = Formatter::new(output); . let mut idx = 0; . 17,343 ( 0.01%) match args.fmt { . None => { . // We can use default formatting parameters for all arguments. 5,778 ( 0.00%) for (i, arg) in args.args.iter().enumerate() { . // SAFETY: args.args and args.pieces come from the same Arguments, . // which guarantees the indexes are always within bounds. . let piece = unsafe { args.pieces.get_unchecked(i) }; 11,744 ( 0.01%) if !piece.is_empty() { 34,284 ( 0.02%) formatter.buf.write_str(*piece)?; . } 29,360 ( 0.02%) (arg.formatter)(arg.value, &mut formatter)?; . idx += 1; . } . } . Some(fmt) => { . // Every spec has a corresponding argument that is preceded by . // a string piece. . for (i, arg) in fmt.iter().enumerate() { . // SAFETY: fmt and args.pieces come from the same Arguments, . // which guarantees the indexes are always within bounds. . let piece = unsafe { args.pieces.get_unchecked(i) }; 16 ( 0.00%) if !piece.is_empty() { 24 ( 0.00%) formatter.buf.write_str(*piece)?; . } . // SAFETY: arg and args.args come from the same Arguments, . // which guarantees the indexes are always within bounds. 24 ( 0.00%) unsafe { run(&mut formatter, arg, args.args) }?; . idx += 1; . } . } . } . . // There can be only one trailing string piece left. 5,781 ( 0.00%) if let Some(piece) = args.pieces.get(idx) { 20,006 ( 0.01%) formatter.buf.write_str(*piece)?; . } . . Ok(()) 46,248 ( 0.03%) } . . unsafe fn run(fmt: &mut Formatter<'_>, arg: &rt::v1::Argument, args: &[ArgumentV1<'_>]) -> Result { 16 ( 0.00%) fmt.fill = arg.format.fill; 16 ( 0.00%) fmt.align = arg.format.align; 16 ( 0.00%) fmt.flags = arg.format.flags; . // SAFETY: arg and args come from the same Arguments, . // which guarantees the indexes are always within bounds. . unsafe { 32 ( 0.00%) fmt.width = getcount(args, &arg.format.width); 32 ( 0.00%) fmt.precision = getcount(args, &arg.format.precision); . } . . // Extract the correct argument . debug_assert!(arg.position < args.len()); . // SAFETY: arg and args come from the same Arguments, . // which guarantees its index is always within bounds. 8 ( 0.00%) let value = unsafe { args.get_unchecked(arg.position) }; . . // Then actually do some printing 24 ( 0.00%) (value.formatter)(value.value, fmt) . } . . unsafe fn getcount(args: &[ArgumentV1<'_>], cnt: &rt::v1::Count) -> Option { 58 ( 0.00%) match *cnt { . rt::v1::Count::Is(n) => Some(n), . rt::v1::Count::Implied => None, . rt::v1::Count::Param(i) => { . debug_assert!(i < args.len()); . // SAFETY: cnt and args come from the same Arguments, . // which guarantees this index is always within bounds. . unsafe { args.get_unchecked(i).as_usize() } . } -- line 1228 ---------------------------------------- -- line 1312 ---------------------------------------- . /// . /// assert_eq!(&format!("{}", Foo::new(2)), "2"); . /// assert_eq!(&format!("{}", Foo::new(-1)), "-1"); . /// assert_eq!(&format!("{}", Foo::new(0)), "0"); . /// assert_eq!(&format!("{:#}", Foo::new(-1)), "-Foo 1"); . /// assert_eq!(&format!("{:0>#8}", Foo::new(-1)), "00-Foo 1"); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 120 ( 0.00%) pub fn pad_integral(&mut self, is_nonnegative: bool, prefix: &str, buf: &str) -> Result { . let mut width = buf.len(); . . let mut sign = None; 20 ( 0.00%) if !is_nonnegative { . sign = Some('-'); . width += 1; 10 ( 0.00%) } else if self.sign_plus() { . sign = Some('+'); 10 ( 0.00%) width += 1; . } . 10 ( 0.00%) let prefix = if self.alternate() { . width += prefix.chars().count(); . Some(prefix) . } else { . None . }; . . // Writes the sign if it exists, and then the prefix if it was requested . #[inline(never)] 60 ( 0.00%) fn write_prefix(f: &mut Formatter<'_>, sign: Option, prefix: Option<&str>) -> Result { 20 ( 0.00%) if let Some(c) = sign { . f.buf.write_char(c)?; . } 20 ( 0.00%) if let Some(prefix) = prefix { f.buf.write_str(prefix) } else { Ok(()) } 40 ( 0.00%) } . . // The `width` field is more of a `min-width` parameter at this point. 20 ( 0.00%) match self.width { . // If there's no minimum length requirements then we can just . // write the bytes. . None => { 49 ( 0.00%) write_prefix(self, sign, prefix)?; 35 ( 0.00%) self.buf.write_str(buf) . } . // Check if we're over the minimum width, if so then we can also . // just write the bytes. 9 ( 0.00%) Some(min) if width >= min => { 24 ( 0.00%) write_prefix(self, sign, prefix)?; 9 ( 0.00%) self.buf.write_str(buf) . } . // The sign and prefix goes before the padding if the fill character . // is zero . Some(min) if self.sign_aware_zero_pad() => { . let old_fill = crate::mem::replace(&mut self.fill, '0'); . let old_align = crate::mem::replace(&mut self.align, rt::v1::Alignment::Right); . write_prefix(self, sign, prefix)?; . let post_padding = self.padding(min - width, rt::v1::Alignment::Right)?; -- line 1368 ---------------------------------------- -- line 1406 ---------------------------------------- . /// formatter.pad("Foo") . /// } . /// } . /// . /// assert_eq!(&format!("{:<4}", Foo), "Foo "); . /// assert_eq!(&format!("{:0>4}", Foo), "0Foo"); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 91,224 ( 0.05%) pub fn pad(&mut self, s: &str) -> Result { . // Make sure there's a fast path up front 30,408 ( 0.02%) if self.width.is_none() && self.precision.is_none() { . return self.buf.write_str(s); . } . // The `precision` field can be interpreted as a `max-width` for the . // string being formatted. . let s = if let Some(max) = self.precision { . // If our string is longer that the precision, then we must have . // truncation. However other flags like `fill`, `width` and `align` . // must act as always. -- line 1424 ---------------------------------------- -- line 1591 ---------------------------------------- . /// } . /// } . /// . /// assert_eq!(&format!("{}", Foo), "Foo"); . /// assert_eq!(&format!("{:0>8}", Foo), "Foo"); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn write_str(&mut self, data: &str) -> Result { 255 ( 0.00%) self.buf.write_str(data) . } . . /// Writes some formatted information into this instance. . /// . /// # Examples . /// . /// ``` . /// use std::fmt; -- line 1607 ---------------------------------------- -- line 1613 ---------------------------------------- . /// formatter.write_fmt(format_args!("Foo {}", self.0)) . /// } . /// } . /// . /// assert_eq!(&format!("{}", Foo(-1)), "Foo -1"); . /// assert_eq!(&format!("{:0>8}", Foo(2)), "Foo 2"); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 2 ( 0.00%) pub fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result { 24 ( 0.00%) write(self.buf, fmt) 4 ( 0.00%) } . . /// Flags for formatting . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_deprecated( . since = "1.24.0", . reason = "use the `sign_plus`, `sign_minus`, `alternate`, \ . or `sign_aware_zero_pad` methods instead" -- line 1631 ---------------------------------------- -- line 1793 ---------------------------------------- . /// } . /// . /// assert_eq!(&format!("{:+}", Foo(23)), "Foo(+23)"); . /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)"); . /// ``` . #[must_use] . #[stable(feature = "fmt_flags", since = "1.5.0")] . pub fn sign_plus(&self) -> bool { 30 ( 0.00%) self.flags & (1 << FlagV1::SignPlus as u32) != 0 . } . . /// Determines if the `-` flag was specified. . /// . /// # Examples . /// . /// ``` . /// use std::fmt; -- line 1809 ---------------------------------------- -- line 1850 ---------------------------------------- . /// } . /// . /// assert_eq!(&format!("{:#}", Foo(23)), "Foo(23)"); . /// assert_eq!(&format!("{}", Foo(23)), "23"); . /// ``` . #[must_use] . #[stable(feature = "fmt_flags", since = "1.5.0")] . pub fn alternate(&self) -> bool { 10 ( 0.00%) self.flags & (1 << FlagV1::Alternate as u32) != 0 . } . . /// Determines if the `0` flag was specified. . /// . /// # Examples . /// . /// ``` . /// use std::fmt; -- line 1866 ---------------------------------------- -- line 2076 ---------------------------------------- . . #[stable(since = "1.2.0", feature = "formatter_write")] . impl Write for Formatter<'_> { . fn write_str(&mut self, s: &str) -> Result { . self.buf.write_str(s) . } . . fn write_char(&mut self, c: char) -> Result { 6 ( 0.00%) self.buf.write_char(c) . } . . fn write_fmt(&mut self, args: Arguments<'_>) -> Result { . write(self.buf, args) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] -- line 2092 ---------------------------------------- -- line 2098 ---------------------------------------- . . // Implementations of the core formatting traits . . macro_rules! fmt_refs { . ($($tr:ident),*) => { . $( . #[stable(feature = "rust1", since = "1.0.0")] . impl $tr for &T { 458 ( 0.00%) fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) } . } . #[stable(feature = "rust1", since = "1.0.0")] . impl $tr for &mut T { 4 ( 0.00%) fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) } . } . )* . } . } . . fmt_refs! { Debug, Display, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp } . . #[unstable(feature = "never_type", issue = "35121")] -- line 2118 ---------------------------------------- -- line 2166 ---------------------------------------- . } . f.write_str(&self[from..])?; . f.write_char('"') . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Display for str { 30,399 ( 0.02%) fn fmt(&self, f: &mut Formatter<'_>) -> Result { 20,278 ( 0.01%) f.pad(self) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Debug for char { . fn fmt(&self, f: &mut Formatter<'_>) -> Result { . f.write_char('\'')?; . for c in self.escape_debug_ext(EscapeDebugExtArgs { -- line 2183 ---------------------------------------- -- line 2188 ---------------------------------------- . f.write_char(c)? . } . f.write_char('\'') . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Display for char { 1 ( 0.00%) fn fmt(&self, f: &mut Formatter<'_>) -> Result { 2 ( 0.00%) if f.width.is_none() && f.precision.is_none() { 1 ( 0.00%) f.write_char(*self) . } else { . f.pad(self.encode_utf8(&mut [0; 4])) . } . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Pointer for *const T { -- line 2206 ---------------------------------------- 179,666 ( 0.10%) -------------------------------------------------------------------------------- -- 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}; . 3 ( 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); . } . } . } . }; . } . 129 ( 0.00%) #[derive(Clone)] . pub struct Parser<'a> { 3 ( 0.00%) pub sess: &'a ParseSess, . /// The current token. 2 ( 0.00%) pub token: Token, . /// The spacing for the current token 2 ( 0.00%) pub token_spacing: Spacing, . /// The previous token. 3 ( 0.00%) pub prev_token: Token, 3 ( 0.00%) pub capture_cfg: bool, 7 ( 0.00%) restrictions: Restrictions, 4 ( 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, 4 ( 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. 4 ( 0.00%) unmatched_angle_bracket_count: u32, 6 ( 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. 2 ( 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` 2 ( 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, . } . 8 ( 0.00%) #[derive(Clone)] . struct CaptureState { 8 ( 0.00%) capturing: Capturing, 2 ( 0.00%) replace_ranges: Vec, . inner_attr_ranges: FxHashMap, . } . . impl<'a> Drop for Parser<'a> { . fn drop(&mut self) { 11,325 ( 0.01%) emit_unclosed_delims(&mut self.unclosed_delims, &self.sess); . } . } . 134,442 ( 0.08%) #[derive(Clone)] . struct TokenCursor { . frame: TokenCursorFrame, 29,719 ( 0.02%) stack: Vec, . desugar_doc_comments: bool, . // Counts the number of calls to `next` or `next_desugared`, . // depending on whether `desugar_doc_comments` is set. 9,906 ( 0.01%) 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, . } . 62,269 ( 0.04%) #[derive(Clone)] . struct TokenCursorFrame { 9,910 ( 0.01%) delim: token::DelimToken, . span: DelimSpan, . open_delim: bool, 19,820 ( 0.01%) tree_cursor: tokenstream::Cursor, . close_delim: bool, . } . . impl TokenCursorFrame { . fn new(span: DelimSpan, delim: DelimToken, tts: TokenStream) -> Self { 14,150 ( 0.01%) TokenCursorFrame { . delim, . span, . open_delim: false, 14,147 ( 0.01%) tree_cursor: tts.into_trees(), . close_delim: false, . } . } . } . . impl TokenCursor { 747,072 ( 0.43%) fn next(&mut self) -> (Token, Spacing) { . loop { 370,687 ( 0.21%) let (tree, spacing) = if !self.frame.open_delim { 8,487 ( 0.00%) self.frame.open_delim = true; 42,435 ( 0.02%) TokenTree::open_tt(self.frame.span, self.frame.delim).into() 710,262 ( 0.40%) } else if let Some(tree) = self.frame.tree_cursor.next_with_spacing() { . tree 39,612 ( 0.02%) } else if !self.frame.close_delim { 8,486 ( 0.00%) self.frame.close_delim = true; 42,430 ( 0.02%) TokenTree::close_tt(self.frame.span, self.frame.delim).into() 16,972 ( 0.01%) } else if let Some(frame) = self.stack.pop() { 110,318 ( 0.06%) self.frame = frame; . continue; . } else { 51,012 ( 0.03%) (TokenTree::Token(Token::new(token::Eof, DUMMY_SP)), Spacing::Alone) . }; . 141,486 ( 0.08%) match tree { . TokenTree::Token(token) => { 498,048 ( 0.28%) return (token, spacing); . } . TokenTree::Delimited(sp, delim, tts) => { . let frame = TokenCursorFrame::new(sp, delim, tts); . self.stack.push(mem::replace(&mut self.frame, frame)); . } . } . } 498,048 ( 0.28%) } . 150 ( 0.00%) fn next_desugared(&mut self) -> (Token, Spacing) { 45 ( 0.00%) let (data, attr_style, sp) = match self.next() { . (Token { kind: token::DocComment(_, attr_style, data), span }, _) => { . (data, attr_style, span) . } 75 ( 0.00%) 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() 135 ( 0.00%) } . } . 30 ( 0.00%) #[derive(Debug, Clone, PartialEq)] . enum TokenType { 24 ( 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> { 5,654 ( 0.00%) Some(match token.kind { 11,308 ( 0.01%) _ if token.is_special_ident() => "reserved identifier", 11,308 ( 0.01%) _ if token.is_used_keyword() => "keyword", 11,308 ( 0.01%) _ if token.is_unused_keyword() => "reserved keyword", . token::DocComment(..) => "doc comment", . _ => return None, . }) . } . 19,789 ( 0.01%) pub(super) fn token_descr(token: &Token) -> String { 5,654 ( 0.00%) let token_str = pprust::token_to_string(token); . match token_descr_opt(token) { . Some(prefix) => format!("{} `{}`", prefix, token_str), 19,789 ( 0.01%) _ => format!("`{}`", token_str), . } 14,135 ( 0.01%) } . . impl<'a> Parser<'a> { 39,620 ( 0.02%) pub fn new( . sess: &'a ParseSess, . tokens: TokenStream, . desugar_doc_comments: bool, . subparser_name: Option<&'static str>, . ) -> Self { 2,830 ( 0.00%) let mut start_frame = TokenCursorFrame::new(DelimSpan::dummy(), token::NoDelim, tokens); 5,660 ( 0.00%) start_frame.open_delim = true; . start_frame.close_delim = true; . 87,730 ( 0.05%) let mut parser = Parser { . sess, 2,830 ( 0.00%) token: Token::dummy(), . token_spacing: Spacing::Alone, 2,830 ( 0.00%) prev_token: Token::dummy(), . capture_cfg: false, . restrictions: Restrictions::empty(), . expected_tokens: Vec::new(), . token_cursor: TokenCursor { 16,980 ( 0.01%) 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. 5,660 ( 0.00%) parser.bump(); . . parser 25,470 ( 0.01%) } . . fn next_tok(&mut self, fallback_span: Span) -> (Token, Spacing) { . loop { 356,532 ( 0.20%) let (mut next, spacing) = if self.desugar_doc_comments { 60 ( 0.00%) self.token_cursor.next_desugared() . } else { 178,221 ( 0.10%) self.token_cursor.next() . }; 237,688 ( 0.14%) 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 59,422 ( 0.03%) self.token_cursor.break_last_token = false; 237,688 ( 0.14%) if next.span.is_dummy() { . // Tweak the location for better diagnostics, but keep syntactic context intact. 11,328 ( 0.01%) next.span = fallback_span.with_ctxt(next.span.ctxt()); . } 203,724 ( 0.12%) if matches!( 118,844 ( 0.07%) next.kind, . token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) . ) { . continue; . } 237,688 ( 0.14%) 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`. 76,338 ( 0.04%) pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> { 8,482 ( 0.00%) if self.expected_tokens.is_empty() { 25,452 ( 0.01%) if self.token == *t { 21,210 ( 0.01%) self.bump(); . Ok(false) . } else { . self.unexpected_try_recover(t) . } . } else { 50,880 ( 0.03%) self.expect_one_of(slice::from_ref(t), &[]) . } 127,230 ( 0.07%) } . . /// 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. 50,892 ( 0.03%) pub fn expect_one_of( . &mut self, . edible: &[TokenKind], . inedible: &[TokenKind], . ) -> PResult<'a, bool /* recovered */> { 8,482 ( 0.00%) if edible.contains(&self.token.kind) { 12,720 ( 0.01%) 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) . } 63,615 ( 0.04%) } . . // Public for rustfmt usage. . pub fn parse_ident(&mut self) -> PResult<'a, Ident> { 39,607 ( 0.02%) self.parse_ident_common(true) . } . . fn ident_or_err(&mut self) -> PResult<'a, (Ident, /* is_raw */ bool)> { 29,706 ( 0.02%) 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(), . }) . } . 69,314 ( 0.04%) fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> { 9,902 ( 0.01%) let (ident, is_raw) = self.ident_or_err()?; 59,412 ( 0.03%) if !is_raw && ident.is_reserved() { . let mut err = self.expected_ident_found(); . if recover { . err.emit(); . } else { . return Err(err); . } . } 39,608 ( 0.02%) self.bump(); . Ok(ident) 99,020 ( 0.06%) } . . /// 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. 426,104 ( 0.24%) fn check(&mut self, tok: &TokenKind) -> bool { 182,635 ( 0.10%) let is_present = self.token == *tok; 121,762 ( 0.07%) if !is_present { 191,220 ( 0.11%) self.expected_tokens.push(TokenType::Token(tok.clone())); . } . is_present 426,104 ( 0.24%) } . . /// Consumes a token 'tok' if it exists. Returns whether the given token was present. . pub fn eat(&mut self, tok: &TokenKind) -> bool { 107,553 ( 0.06%) let is_present = self.check(tok); 70,759 ( 0.04%) if is_present { 26,885 ( 0.02%) 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. 28,325 ( 0.02%) fn check_keyword(&mut self, kw: Symbol) -> bool { 5,667 ( 0.00%) self.expected_tokens.push(TokenType::Keyword(kw)); 130,388 ( 0.07%) 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. 70 ( 0.00%) pub fn eat_keyword(&mut self, kw: Symbol) -> bool { 22,678 ( 0.01%) if self.check_keyword(kw) { 8,484 ( 0.00%) self.bump(); . true . } else { . false . } 70 ( 0.00%) } . . fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool { 12 ( 0.00%) if self.token.is_keyword(kw) { 3 ( 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. 7,065 ( 0.00%) fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> { . if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) } 5,652 ( 0.00%) } . . /// Is the given keyword `kw` followed by a non-reserved identifier? 72 ( 0.00%) fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool { 36 ( 0.00%) self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()) 81 ( 0.00%) } . 72 ( 0.00%) fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool { 28 ( 0.00%) if ok { . true . } else { 28 ( 0.00%) self.expected_tokens.push(typ); . false . } 72 ( 0.00%) } . . fn check_ident(&mut self) -> bool { . self.check_or_expected(self.token.is_ident(), TokenType::Ident) . } . 20 ( 0.00%) fn check_path(&mut self) -> bool { 42 ( 0.00%) self.check_or_expected(self.token.is_path_start(), TokenType::Path) 25 ( 0.00%) } . . fn check_type(&mut self) -> bool { 16 ( 0.00%) self.check_or_expected(self.token.can_begin_type(), TokenType::Type) . } . . fn check_const_arg(&mut self) -> bool { 16 ( 0.00%) self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const) . } . . fn check_inline_const(&self, dist: usize) -> bool { . 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, . }) . } . . /// Checks to see if the next token is either `+` or `+=`. . /// Otherwise returns `false`. . fn check_plus(&mut self) -> bool { 12 ( 0.00%) self.check_or_expected( 6 ( 0.00%) self.token.is_like_plus(), 6 ( 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. 96 ( 0.00%) fn break_and_eat(&mut self, expected: TokenKind) -> bool { 56 ( 0.00%) if self.token.kind == expected { 8 ( 0.00%) self.bump(); . return true; . } 20 ( 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 . } . _ => { 12 ( 0.00%) self.expected_tokens.push(TokenType::Token(expected)); . false . } . } 88 ( 0.00%) } . . /// Eats `+` possibly breaking tokens like `+=` in process. . fn eat_plus(&mut self) -> bool { . self.break_and_eat(token::BinOp(token::Plus)) . } . . /// Eats `&` possibly breaking tokens like `&&` in process. . /// Signals an error if `&` is not eaten. -- line 704 ---------------------------------------- -- line 708 ---------------------------------------- . . /// 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. 6 ( 0.00%) fn eat_lt(&mut self) -> bool { 21 ( 0.00%) let ate = self.break_and_eat(token::Lt); 14 ( 0.00%) if ate { . // See doc comment for `unmatched_angle_bracket_count`. 8 ( 0.00%) self.unmatched_angle_bracket_count += 1; 8 ( 0.00%) self.max_angle_bracket_count += 1; . debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count); . } . ate 6 ( 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, ()> { 12 ( 0.00%) if self.break_and_eat(token::Gt) { . // See doc comment for `unmatched_angle_bracket_count`. 6 ( 0.00%) if self.unmatched_angle_bracket_count > 0 { 4 ( 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 { 3 ( 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 765 ---------------------------------------- . let mut v = vec![]; . let unclosed_delims = !self.unclosed_delims.is_empty(); . . while !self.expect_any_with_type(kets, expect) { . if let token::CloseDelim(..) | token::Eof = self.token.kind { . break; . } . if let Some(ref t) = sep.sep { 9 ( 0.00%) if first { . first = false; . } else { . match self.expect(t) { . Ok(false) => { . self.current_closure.take(); . } . Ok(true) => { . self.current_closure.take(); -- line 781 ---------------------------------------- -- line 866 ---------------------------------------- . trailing = true; . break; . } . . let t = f(self)?; . v.push(t); . } . 16 ( 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)> { 19 ( 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. 30 ( 0.00%) fn parse_seq_to_end( . &mut self, . ket: &TokenKind, . sep: SeqSep, . f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, . ) -> PResult<'a, (Vec, bool /* trailing */)> { 11 ( 0.00%) let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?; 5 ( 0.00%) if !recovered { . self.eat(ket); . } 31 ( 0.00%) Ok((val, trailing)) 24 ( 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)> { 10 ( 0.00%) self.expect(bra)?; 24 ( 0.00%) self.parse_seq_to_end(ket, sep, f) . } . . fn parse_delim_comma_seq( . &mut self, . delim: DelimToken, . f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, . ) -> PResult<'a, (Vec, bool)> { . self.parse_unspanned_seq( 4 ( 0.00%) &token::OpenDelim(delim), 5 ( 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. 772,486 ( 0.44%) fn bump_with(&mut self, (next_token, next_spacing): (Token, Spacing)) { . // Bumping after EOF is a bad sign, usually an infinite loop. 356,532 ( 0.20%) 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. 237,688 ( 0.14%) self.prev_token = mem::replace(&mut self.token, next_token); 59,422 ( 0.03%) self.token_spacing = next_spacing; . . // Diagnostics. 59,422 ( 0.03%) self.expected_tokens.clear(); . } . . /// Advance the parser by one token. 475,376 ( 0.27%) pub fn bump(&mut self) { 237,688 ( 0.14%) let next_token = self.next_tok(self.token.span); 356,532 ( 0.20%) self.bump_with(next_token); 475,376 ( 0.27%) } . . /// 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 { 2 ( 0.00%) if dist == 0 { . return looker(&self.token); . } . 2,837 ( 0.00%) let frame = &self.token_cursor.frame; 2,841 ( 0.00%) if frame.delim != DelimToken::NoDelim { . let all_normal = (0..dist).all(|i| { 20 ( 0.00%) let token = frame.tree_cursor.look_ahead(i); 26 ( 0.00%) !matches!(token, Some(TokenTree::Delimited(_, DelimToken::NoDelim, _))) . }); . if all_normal { 34 ( 0.00%) return match frame.tree_cursor.look_ahead(dist - 1) { 12 ( 0.00%) Some(tree) => match tree { 6 ( 0.00%) TokenTree::Token(token) => looker(token), . TokenTree::Delimited(dspan, delim, _) => { . looker(&Token::new(token::OpenDelim(*delim), dspan.open)) . } . }, 7 ( 0.00%) None => looker(&Token::new(token::CloseDelim(frame.delim), frame.span.close)), . }; . } . } . . let mut cursor = self.token_cursor.clone(); . let mut i = 0; 2,843 ( 0.00%) let mut token = Token::dummy(); . while i < dist { 19,838 ( 0.01%) token = cursor.next().0; 8,504 ( 0.00%) if matches!( 5,668 ( 0.00%) token.kind, . token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) . ) { . continue; . } . i += 1; . } . return looker(&token); . } -- line 1060 ---------------------------------------- -- line 1070 ---------------------------------------- . 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. 2,828 ( 0.00%) fn parse_unsafety(&mut self) -> Unsafe { . if self.eat_keyword(kw::Unsafe) { . Unsafe::Yes(self.prev_token.uninterpolated_span()) . } else { . Unsafe::No . } 11,312 ( 0.01%) } . . /// Parses constness: `const` or nothing. 11,328 ( 0.01%) fn parse_constness(&mut self) -> Const { . // Avoid const blocks to be parsed as const items 4,248 ( 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 . } 19,824 ( 0.01%) } . . /// 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 1139 ---------------------------------------- . } . } . . fn parse_mac_args(&mut self) -> PResult<'a, P> { . self.parse_mac_args_common(true).map(P) . } . . fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> { 12,717 ( 0.01%) self.parse_mac_args_common(false) . } . 38,151 ( 0.02%) fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> { 33,912 ( 0.02%) Ok( 21,195 ( 0.01%) if self.check(&token::OpenDelim(DelimToken::Paren)) . || self.check(&token::OpenDelim(DelimToken::Bracket)) . || self.check(&token::OpenDelim(DelimToken::Brace)) . { 16,956 ( 0.01%) match self.parse_token_tree() { 21,195 ( 0.01%) TokenTree::Delimited(dspan, delim, tokens) => . // We've confirmed above that there is a delimiter so unwrapping is OK. . { 8,478 ( 0.00%) MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens) . } . _ => unreachable!(), . } . } 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. -- line 1168 ---------------------------------------- -- line 1173 ---------------------------------------- . MacArgs::Eq(eq_span, Token::new(token_kind, span)) . } else { . MacArgs::Empty . } . } else { . return self.unexpected(); . }, . ) 29,673 ( 0.02%) } . . fn parse_or_use_outer_attributes( . &mut self, . already_parsed_attrs: Option, . ) -> PResult<'a, AttrWrapper> { . if let Some(attrs) = already_parsed_attrs { . Ok(attrs) . } else { . self.parse_outer_attributes() . } . } . . /// Parses a single token tree from the input. 33,928 ( 0.02%) pub(crate) fn parse_token_tree(&mut self) -> TokenTree { 12,723 ( 0.01%) 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. 65,030 ( 0.04%) 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. 28,280 ( 0.02%) self.bump(); . } . // We are still inside the frame corresponding . // to the delimited stream we captured, so grab . // the tokens from this frame. . let frame = &self.token_cursor.frame; 8,482 ( 0.00%) let stream = frame.tree_cursor.stream.clone(); 8,482 ( 0.00%) let span = frame.span; 4,241 ( 0.00%) let delim = frame.delim; . // Consume close delimiter 8,482 ( 0.00%) self.bump(); 21,205 ( 0.01%) TokenTree::Delimited(span, delim, stream) . } . token::CloseDelim(_) | token::Eof => unreachable!(), . _ => { . self.bump(); . TokenTree::Token(self.prev_token.clone()) . } . } 29,687 ( 0.02%) } . . /// 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 { 2 ( 0.00%) let old = self.restrictions; 3 ( 0.00%) self.restrictions = res; . let res = f(self); 2 ( 0.00%) self.restrictions = old; . res . } . 22,648 ( 0.01%) fn is_crate_vis(&self) -> bool { 14,155 ( 0.01%) self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep) 25,479 ( 0.01%) } . . /// 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. 28,300 ( 0.02%) pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> { 5,660 ( 0.00%) maybe_whole!(self, NtVis, |x| x); . 2,830 ( 0.00%) self.expected_tokens.push(TokenType::Keyword(kw::Crate)); 11,320 ( 0.01%) 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". 1,416 ( 0.00%) return Ok(Visibility { 4,248 ( 0.00%) span: self.token.span.shrink_to_lo(), . kind: VisibilityKind::Inherited, . tokens: None, . }); . } 1,414 ( 0.00%) let lo = self.prev_token.span; . 7,070 ( 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. . } . } . 4,242 ( 0.00%) Ok(Visibility { span: lo, kind: VisibilityKind::Public, tokens: None }) 25,470 ( 0.01%) } . . /// 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 { 1 ( 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 `::*` 79,200 ( 0.05%) fn is_import_coupler(&mut self) -> bool { 39,600 ( 0.02%) self.check(&token::ModSep) . && self.look_ahead(1, |t| { 11,336 ( 0.01%) *t == token::OpenDelim(token::Brace) || *t == token::BinOp(token::Star) . }) 89,082 ( 0.05%) } . . 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) . } . 22,656 ( 0.01%) pub fn emit_unclosed_delims(unclosed_delims: &mut Vec, sess: &ParseSess) { 11,328 ( 0.01%) *sess.reached_eof.borrow_mut() |= . unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none()); 11,328 ( 0.01%) for unmatched in unclosed_delims.drain(..) { . if let Some(mut e) = make_unclosed_delims_error(unmatched, sess) { . e.emit(); . } . } 22,656 ( 0.01%) } . . /// A helper struct used when building an `AttrAnnotatedTokenStream` from . /// a `LazyTokenStream`. Both delimiter and non-delimited tokens . /// are stored as `FlatToken::Token`. A vector of `FlatToken`s . /// is then 'parsed' to build up an `AttrAnnotatedTokenStream` with nested . /// `AttrAnnotatedTokenTree::Delimited` tokens . #[derive(Debug, Clone)] . pub enum FlatToken { -- line 1474 ---------------------------------------- 329,695 ( 0.19%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/attr_wrapper.rs -------------------------------------------------------------------------------- Ir -- line 200 ---------------------------------------- . &mut self, . attrs: AttrWrapper, . force_collect: ForceCollect, . f: impl FnOnce(&mut Self, Vec) -> PResult<'a, (R, TrailingToken)>, . ) -> PResult<'a, R> { . // We only bail out when nothing could possibly observe the collected tokens: . // 1. We cannot be force collecting tokens (since force-collecting requires tokens . // by definition 11,320 ( 0.01%) if matches!(force_collect, ForceCollect::No) . // None of our outer attributes can require tokens (e.g. a proc-macro) . && !attrs.maybe_needs_tokens() . // If our target supports custom inner attributes, then we cannot bail . // out early, since we may need to capture tokens for a custom inner attribute . // invocation. . && !R::SUPPORTS_CUSTOM_INNER_ATTRS . // Never bail out early in `capture_cfg` mode, since there might be `#[cfg]` . // or `#[cfg_attr]` attributes. . && !self.capture_cfg . { . return Ok(f(self, attrs.attrs.into())?.0); . } . 59,388 ( 0.03%) let start_token = (self.token.clone(), self.token_spacing); . let cursor_snapshot = self.token_cursor.clone(); . . let has_outer_attrs = !attrs.attrs.is_empty(); . let prev_capturing = std::mem::replace(&mut self.capture_state.capturing, Capturing::Yes); 16,969 ( 0.01%) let replace_ranges_start = self.capture_state.replace_ranges.len(); . 8,483 ( 0.00%) let ret = f(self, attrs.attrs.into()); . 7,075 ( 0.00%) self.capture_state.capturing = prev_capturing; . 77,741 ( 0.04%) let (mut ret, trailing) = ret?; . . // When we're not in `capture-cfg` mode, then bail out early if: . // 1. Our target doesn't support tokens at all (e.g we're parsing an `NtIdent`) . // so there's nothing for us to do. . // 2. Our target already has tokens set (e.g. we've parsed something . // like `#[my_attr] $item`. The actual parsing code takes care of prepending . // any attributes to the nonterminal, so we don't need to modify the . // already captured tokens. . // Note that this check is independent of `force_collect`- if we already . // have tokens, or can't even store them, then there's never a need to . // force collection of new tokens. 49,480 ( 0.03%) if !self.capture_cfg && matches!(ret.tokens_mut(), None | Some(Some(_))) { . return Ok(ret); . } . . // This is very similar to the bail out check at the start of this function. . // Now that we've parsed an AST node, we have more information available. 5,656 ( 0.00%) if matches!(force_collect, ForceCollect::No) . // We now have inner attributes available, so this check is more precise . // than `attrs.maybe_needs_tokens()` at the start of the function. . // As a result, we don't need to check `R::SUPPORTS_CUSTOM_INNER_ATTRS` 1 ( 0.00%) && !crate::parser::attr::maybe_needs_tokens(ret.attrs()) . // Subtle: We call `has_cfg_or_cfg_attr` with the attrs from `ret`. . // This ensures that we consider inner attributes (e.g. `#![cfg]`), . // which require us to have tokens available . // We also call `has_cfg_or_cfg_attr` at the beginning of this function, . // but we only bail out if there's no possibility of inner attributes . // (!R::SUPPORTS_CUSTOM_INNER_ATTRS) . // We only catpure about `#[cfg]` or `#[cfg_attr]` in `capture_cfg` . // mode - during normal parsing, we don't need any special capturing . // for those attributes, since they're builtin. 5,658 ( 0.00%) && !(self.capture_cfg && has_cfg_or_cfg_attr(ret.attrs())) . { . return Ok(ret); . } . . let mut inner_attr_replace_ranges = Vec::new(); . // Take the captured ranges for any inner attributes that we parsed. 4,239 ( 0.00%) for inner_attr in ret.attrs().iter().filter(|a| a.style == ast::AttrStyle::Inner) { . if let Some(attr_range) = self.capture_state.inner_attr_ranges.remove(&inner_attr.id) { . inner_attr_replace_ranges.push(attr_range); . } else { . self.sess . .span_diagnostic . .delay_span_bug(inner_attr.span, "Missing token range for attribute"); . } . } . 4,239 ( 0.00%) let replace_ranges_end = self.capture_state.replace_ranges.len(); . . let cursor_snapshot_next_calls = cursor_snapshot.num_next_calls; 4,239 ( 0.00%) let mut end_pos = self.token_cursor.num_next_calls; . . // Capture a trailing token if requested by the callback 'f' . match trailing { . TrailingToken::None => {} . TrailingToken::Semi => { . assert_eq!(self.token.kind, token::Semi); . end_pos += 1; . } -- line 293 ---------------------------------------- -- line 297 ---------------------------------------- . } . } . } . . // If we 'broke' the last token (e.g. breaking a '>>' token to two '>' tokens), . // then extend the range of captured tokens to include it, since the parser . // was not actually bumped past it. When the `LazyTokenStream` gets converted . // into an `AttrAnnotatedTokenStream`, we will create the proper token. 12,717 ( 0.01%) if self.token_cursor.break_last_token { . assert_eq!( . trailing, . TrailingToken::None, . "Cannot set `break_last_token` and have trailing token" . ); 8,478 ( 0.00%) end_pos += 1; . } . 12,717 ( 0.01%) let num_calls = end_pos - cursor_snapshot_next_calls; . . // If we have no attributes, then we will never need to . // use any replace ranges. 16,956 ( 0.01%) let replace_ranges: Box<[ReplaceRange]> = if ret.attrs().is_empty() && !self.capture_cfg { . Box::new([]) . } else { . // Grab any replace ranges that occur *inside* the current AST node. . // We will perform the actual replacement when we convert the `LazyTokenStream` . // to an `AttrAnnotatedTokenStream` . let start_calls: u32 = cursor_snapshot_next_calls.try_into().unwrap(); . self.capture_state.replace_ranges[replace_ranges_start..replace_ranges_end] . .iter() -- line 326 ---------------------------------------- -- line 327 ---------------------------------------- . .cloned() . .chain(inner_attr_replace_ranges.clone().into_iter()) . .map(|(range, tokens)| { . ((range.start - start_calls)..(range.end - start_calls), tokens) . }) . .collect() . }; . 8,478 ( 0.00%) let tokens = LazyTokenStream::new(LazyTokenStreamImpl { 16,956 ( 0.01%) start_token, . num_calls, 42,390 ( 0.02%) cursor_snapshot, 4,239 ( 0.00%) break_last_token: self.token_cursor.break_last_token, . replace_ranges, . }); . . // If we support tokens at all 12,717 ( 0.01%) if let Some(target_tokens) = ret.tokens_mut() { 4,239 ( 0.00%) if target_tokens.is_none() { . // Store se our newly captured tokens into the AST node 4,239 ( 0.00%) *target_tokens = Some(tokens.clone()); . } . } . 4,239 ( 0.00%) let final_attrs = ret.attrs(); . . // If `capture_cfg` is set and we're inside a recursive call to . // `collect_tokens_trailing_token`, then we need to register a replace range . // if we have `#[cfg]` or `#[cfg_attr]`. This allows us to run eager cfg-expansion . // on the captured token stream. 25,434 ( 0.01%) if self.capture_cfg . && matches!(self.capture_state.capturing, Capturing::Yes) . && has_cfg_or_cfg_attr(&final_attrs) . { . let attr_data = AttributesData { attrs: final_attrs.to_vec().into(), tokens }; . . // Replace the entire AST node that we just parsed, including attributes, . // with a `FlatToken::AttrTarget`. If this AST node is inside an item . // that has `#[derive]`, then this will allow us to cfg-expand this -- line 365 ---------------------------------------- -- line 373 ---------------------------------------- . "Should not have unglued last token with cfg attr" . ); . let range: Range = (start_pos.try_into().unwrap())..(end_pos.try_into().unwrap()); . self.capture_state.replace_ranges.push((range, new_tokens)); . self.capture_state.replace_ranges.extend(inner_attr_replace_ranges); . } . . // Only clear our `replace_ranges` when we're finished capturing entirely. 8,478 ( 0.00%) if matches!(self.capture_state.capturing, Capturing::No) { . self.capture_state.replace_ranges.clear(); . // We don't clear `inner_attr_ranges`, as doing so repeatedly . // had a measureable performance impact. Most inner attributes that . // we insert will get removed - when we drop the parser, we'll free . // up the memory used by any attributes that we didn't remove from the map. . } 76,302 ( 0.04%) Ok(ret) 8,478 ( 0.00%) } . } . . /// Converts a flattened iterator of tokens (including open and close delimiter tokens) . /// into a `TokenStream`, creating a `TokenTree::Delimited` for each matching pair . /// of open and close delims. . // FIXME(#67062): Currently, we don't parse `None`-delimited groups correctly, . // which can cause us to end up with mismatched `None` delimiters in our . // captured tokens. This function contains several hacks to work around this - -- line 397 ---------------------------------------- 77,732 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lexer/src/cursor.rs -------------------------------------------------------------------------------- Ir -- line 11 ---------------------------------------- . #[cfg(debug_assertions)] . prev: char, . } . . pub(crate) const EOF_CHAR: char = '\0'; . . impl<'a> Cursor<'a> { . pub(crate) fn new(input: &'a str) -> Cursor<'a> { 265,996 ( 0.15%) Cursor { . initial_len: input.len(), . chars: input.chars(), . #[cfg(debug_assertions)] . prev: EOF_CHAR, . } . } . . /// Returns the last eaten symbol (or `'\0'` in release builds). -- line 27 ---------------------------------------- -- line 57 ---------------------------------------- . . /// Checks if there is nothing more to consume. . pub(crate) fn is_eof(&self) -> bool { . self.chars.as_str().is_empty() . } . . /// Returns amount of already consumed symbols. . pub(crate) fn len_consumed(&self) -> usize { 207,975 ( 0.12%) self.initial_len - self.chars.as_str().len() . } . . /// Resets the number of bytes consumed to 0. . pub(crate) fn reset_len_consumed(&mut self) { . self.initial_len = self.chars.as_str().len(); . } . . /// Moves to the next character. -- line 73 ---------------------------------------- -- line 78 ---------------------------------------- . { . self.prev = c; . } . . Some(c) . } . . /// Eats symbols while predicate returns true or until the end of file is reached. 77,780 ( 0.04%) pub(crate) fn eat_while(&mut self, mut predicate: impl FnMut(char) -> bool) { . // It was tried making optimized version of this for eg. line comments, but . // LLVM can inline all of this and compile it down to fast iteration over bytes. 132,404 ( 0.08%) while predicate(self.first()) && !self.is_eof() { . self.bump(); . } 93,336 ( 0.05%) } . } 113,148 ( 0.06%) -------------------------------------------------------------------------------- -- 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 { 80,669 ( 0.05%) !self.eq(other) . } . } . . /// Derive macro generating an impl of the trait `PartialEq`. . #[rustc_builtin_macro] . #[stable(feature = "builtin_macro_prelude", since = "1.38.0")] . #[allow_internal_unstable(core_intrinsics, structural_match)] . pub macro PartialEq($item:item) { -- line 239 ---------------------------------------- -- line 569 ---------------------------------------- . /// let result = x.0.cmp(&y.0).then_with(|| x.1.cmp(&y.1)).then_with(|| x.2.cmp(&y.2)); . /// . /// assert_eq!(result, Ordering::Less); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "ordering_chaining", since = "1.17.0")] . pub fn then_with Ordering>(self, f: F) -> Ordering { 1 ( 0.00%) match self { . Equal => f(), . _ => self, . } . } . } . . /// A helper struct for reverse ordering. . /// -- line 585 ---------------------------------------- -- line 1097 ---------------------------------------- . /// let result = 2.0 < 1.0; . /// assert_eq!(result, false); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[default_method_body_is_const] . fn lt(&self, other: &Rhs) -> bool { 76,504 ( 0.04%) 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. 75,181 ( 0.04%) !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 { 141,380 ( 0.08%) 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 { 23,967 ( 0.01%) match compare(&v1, &v2) { . Ordering::Less | Ordering::Equal => v1, . Ordering::Greater => v2, . } . } . . /// Returns the element that gives the minimum value from the specified function. . /// . /// Returns the first argument if the comparison determines them to be equal. -- line 1226 ---------------------------------------- -- line 1273 ---------------------------------------- . /// . /// assert_eq!(cmp::max_by(-2, 1, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), -2); . /// assert_eq!(cmp::max_by(-2, 2, |x: &i32, y: &i32| x.abs().cmp(&y.abs())), 2); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "cmp_min_max_by", since = "1.53.0")] . pub fn max_by Ordering>(v1: T, v2: T, compare: F) -> T { 59,391 ( 0.03%) match compare(&v1, &v2) { . Ordering::Less | Ordering::Equal => v2, . Ordering::Greater => v1, . } . } . . /// Returns the element that gives the maximum value from the specified function. . /// . /// Returns the second argument if the comparison determines them to be equal. -- line 1289 ---------------------------------------- -- line 1308 ---------------------------------------- . use crate::cmp::Ordering::{self, Equal, Greater, Less}; . use crate::hint::unreachable_unchecked; . . macro_rules! partial_eq_impl { . ($($t:ty)*) => ($( . #[stable(feature = "rust1", since = "1.0.0")] . impl PartialEq for $t { . #[inline] 154 ( 0.00%) fn eq(&self, other: &$t) -> bool { (*self) == (*other) } . #[inline] . fn ne(&self, other: &$t) -> bool { (*self) != (*other) } . } . )*) . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl PartialEq for () { -- line 1324 ---------------------------------------- -- line 1392 ---------------------------------------- . ($($t:ty)*) => ($( . #[stable(feature = "rust1", since = "1.0.0")] . impl PartialOrd for $t { . #[inline] . fn partial_cmp(&self, other: &$t) -> Option { . Some(self.cmp(other)) . } . #[inline] 564,424 ( 0.32%) fn lt(&self, other: &$t) -> bool { (*self) < (*other) } . #[inline] . fn le(&self, other: &$t) -> bool { (*self) <= (*other) } . #[inline] . fn ge(&self, other: &$t) -> bool { (*self) >= (*other) } . #[inline] . fn gt(&self, other: &$t) -> bool { (*self) > (*other) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Ord for $t { . #[inline] . fn cmp(&self, other: &$t) -> Ordering { . // The order here is important to generate more optimal assembly. . // See for more info. 82,520 ( 0.05%) 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. 520 ( 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 { 21 ( 0.00%) PartialEq::eq(*self, *other) . } . #[inline] . fn ne(&self, other: &&B) -> bool { 57 ( 0.00%) PartialEq::ne(*self, *other) . } . } . #[stable(feature = "rust1", since = "1.0.0")] . impl PartialOrd<&B> for &A . where . A: PartialOrd, . { . #[inline] -- line 1495 ---------------------------------------- 223,671 ( 0.13%) -------------------------------------------------------------------------------- -- 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%) } . 5,806 ( 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 } 65,689 ( 0.04%) } . . /// 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. 4 ( 0.00%) pub fn from_str(string: &str) -> Ident { 4 ( 0.00%) Ident::with_dummy_span(Symbol::intern(string)) 16 ( 0.00%) } . . /// Maps a string and a span to an identifier. . pub fn from_str_and_span(string: &str, span: Span) -> Ident { . Ident::new(Symbol::intern(string), span) . } . . /// Replaces `lo` and `hi` with those from `span`, but keep hygiene context. 24 ( 0.00%) pub fn with_span_pos(self, span: Span) -> Ident { . Ident::new(self.name, span.with_ctxt(self.span.ctxt())) 15 ( 0.00%) } . . pub fn without_first_quote(self) -> Ident { . Ident::new(Symbol::intern(self.as_str().trim_start_matches('\'')), self.span) . } . . /// "Normalize" ident for use in comparisons using "item hygiene". . /// Identifiers with same string value become same if they came from the same macro 2.0 macro . /// (e.g., `macro` item, but not `macro_rules` item) and stay different if they came from . /// different macro 2.0 macros. . /// Technically, this operation strips all non-opaque marks from ident's syntactic context. 2,799 ( 0.00%) pub fn normalize_to_macros_2_0(self) -> Ident { . Ident::new(self.name, self.span.normalize_to_macros_2_0()) 2,177 ( 0.00%) } . . /// "Normalize" ident for use in comparisons using "local variable hygiene". . /// Identifiers with same string value become same if they came from the same non-transparent . /// macro (e.g., `macro` or `macro_rules!` items) and stay different if they came from different . /// non-transparent macros. . /// Technically, this operation strips all transparent marks from ident's syntactic context. 45 ( 0.00%) pub fn normalize_to_macro_rules(self) -> Ident { . Ident::new(self.name, self.span.normalize_to_macro_rules()) 35 ( 0.00%) } . . /// Access the underlying string. This is a slowish operation because it . /// requires locking the symbol interner. . /// . /// Note that the lifetime of the return value is a lie. See . /// `Symbol::as_str()` for details. . pub fn as_str(&self) -> &str { 2 ( 0.00%) self.name.as_str() . } . } . . impl PartialEq for Ident { 117 ( 0.00%) fn eq(&self, rhs: &Self) -> bool { 180 ( 0.00%) self.name == rhs.name && self.span.ctxt() == rhs.span.ctxt() 156 ( 0.00%) } . } . . impl Hash for Ident { . fn hash(&self, state: &mut H) { 3 ( 0.00%) self.name.hash(state); 53 ( 0.00%) self.span.ctxt().hash(state); . } . } . . impl fmt::Debug for Ident { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . fmt::Display::fmt(self, f)?; . fmt::Debug::fmt(&self.span.ctxt(), f) . } -- line 1596 ---------------------------------------- -- line 1622 ---------------------------------------- . is_raw: bool, . /// Span used for retrieving the crate name to which `$crate` refers to, . /// if this field is `None` then the `$crate` conversion doesn't happen. . convert_dollar_crate: Option, . } . . impl IdentPrinter { . /// The most general `IdentPrinter` constructor. Do not use this. 2,827 ( 0.00%) pub fn new(symbol: Symbol, is_raw: bool, convert_dollar_crate: Option) -> IdentPrinter { 16,968 ( 0.01%) IdentPrinter { symbol, is_raw, convert_dollar_crate } 2,827 ( 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. 2,830 ( 0.00%) pub fn for_ast_ident(ident: Ident, is_raw: bool) -> IdentPrinter { 2,830 ( 0.00%) IdentPrinter::new(ident.name, is_raw, Some(ident.span)) 1,415 ( 0.00%) } . } . . impl fmt::Display for IdentPrinter { 21,210 ( 0.01%) fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 8,484 ( 0.00%) if self.is_raw { . f.write_str("r#")?; 4,242 ( 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)] 10 ( 0.00%) pub struct MacroRulesNormalizedIdent(Ident); . . impl MacroRulesNormalizedIdent { . pub fn new(ident: Ident) -> Self { 5 ( 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)] 4,978 ( 0.00%) pub struct Symbol(SymbolIndex); . . rustc_index::newtype_index! { . struct SymbolIndex { .. } . } . . impl Symbol { . const fn new(n: u32) -> Self { . Symbol(SymbolIndex::from_u32(n)) . } . . /// Maps a string to its interned representation. 171,612 ( 0.10%) pub fn intern(string: &str) -> Self { . with_session_globals(|session_globals| session_globals.symbol_interner.intern(string)) 171,612 ( 0.10%) } . . /// 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. 26,421 ( 0.02%) pub fn as_str(&self) -> &str { 8,807 ( 0.01%) with_session_globals(|session_globals| unsafe { . std::mem::transmute::<&str, &str>(session_globals.symbol_interner.get(*self)) . }) 35,228 ( 0.02%) } . . 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 { 170 ( 0.00%) fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 38,688 ( 0.02%) fmt::Display::fmt(self.as_str(), f) . } . } . . impl Encodable for Symbol { . fn encode(&self, s: &mut S) -> Result<(), S::Error> { 282 ( 0.00%) s.emit_str(self.as_str()) . } . } . . impl Decodable for Symbol { . #[inline] 560 ( 0.00%) fn decode(d: &mut D) -> Symbol { 1,246 ( 0.00%) Symbol::intern(&d.read_str()) . } . } . . impl HashStable for Symbol { . #[inline] 6 ( 0.00%) fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) { 34 ( 0.00%) 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(); 32,066 ( 0.02%) if let Some(&name) = inner.names.get(string) { . return name; . } . 3,035 ( 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 { 26,421 ( 0.02%) self.0.lock().strings[symbol.0.as_usize()] . } . } . . // This module has a very short name because it's used a lot. . /// This module contains all the defined keyword `Symbol`s. . /// . /// Given that `kw` is imported, use them like `kw::keyword_name`. . /// For example `kw::Loop` or `kw::Break`. -- line 1847 ---------------------------------------- -- line 1879 ---------------------------------------- . } . . impl Symbol { . fn is_special(self) -> bool { . self <= kw::Underscore . } . . fn is_used_keyword_always(self) -> bool { 8,481 ( 0.00%) self >= kw::As && self <= kw::While . } . . fn is_used_keyword_conditional(self, edition: impl FnOnce() -> Edition) -> bool { 42,450 ( 0.02%) (self >= kw::Async && self <= kw::Dyn) && edition() >= Edition::Edition2018 . } . . fn is_unused_keyword_always(self) -> bool { 8,481 ( 0.00%) self >= kw::Abstract && self <= kw::Yield . } . . fn is_unused_keyword_conditional(self, edition: impl FnOnce() -> Edition) -> bool { 2,827 ( 0.00%) self == kw::Try && edition() >= Edition::Edition2018 . } . . pub fn is_reserved(self, edition: impl Copy + FnOnce() -> Edition) -> bool { 56,620 ( 0.03%) 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 { 59,633 ( 0.03%) 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 { 4,264 ( 0.00%) self == kw::True || self == kw::False 4,264 ( 0.00%) } . . /// Returns `true` if this symbol can be a raw identifier. . pub fn can_be_raw(self) -> bool { 2,830 ( 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() 2,827 ( 0.00%) } . . /// Returns `true` if the token is a keyword used in the language. 2,827 ( 0.00%) pub fn is_used_keyword(self) -> bool { . // Note: `span.edition()` is relatively expensive, don't call it unless necessary. 2,827 ( 0.00%) self.name.is_used_keyword_always() . || self.name.is_used_keyword_conditional(|| self.span.edition()) 5,654 ( 0.00%) } . . /// Returns `true` if the token is a keyword reserved for possible future use. 2,827 ( 0.00%) pub fn is_unused_keyword(self) -> bool { . // Note: `span.edition()` is relatively expensive, don't call it unless necessary. 2,827 ( 0.00%) self.name.is_unused_keyword_always() . || self.name.is_unused_keyword_conditional(|| self.span.edition()) 5,654 ( 0.00%) } . . /// Returns `true` if the token is either a special identifier or a keyword. 9,909 ( 0.01%) 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()) 19,818 ( 0.01%) } . . /// 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() 8,519 ( 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. 1,415 ( 0.00%) pub fn is_raw_guess(self) -> bool { . self.name.can_be_raw() && self.is_reserved() 2,830 ( 0.00%) } . } 15,105 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/item.rs -------------------------------------------------------------------------------- Ir -- line 21 ---------------------------------------- . . use std::convert::TryFrom; . use std::mem; . use tracing::debug; . . impl<'a> Parser<'a> { . /// Parses a source module as a crate. This is the main entry point for the parser. . pub fn parse_crate_mod(&mut self) -> PResult<'a, ast::Crate> { 9 ( 0.00%) let (attrs, items, span) = self.parse_mod(&token::Eof)?; 5 ( 0.00%) Ok(ast::Crate { attrs, items, span, id: DUMMY_NODE_ID, is_placeholder: false }) . } . . /// Parses a `mod { ... }` or `mod ;` item. 14,130 ( 0.01%) fn parse_item_mod(&mut self, attrs: &mut Vec) -> PResult<'a, ItemInfo> { 5,652 ( 0.00%) let unsafety = self.parse_unsafety(); 7,065 ( 0.00%) self.expect_keyword(kw::Mod)?; . let id = self.parse_ident()?; . let mod_kind = if self.eat(&token::Semi) { . ModKind::Unloaded . } else { . self.expect(&token::OpenDelim(token::Brace))?; . let (mut inner_attrs, items, inner_span) = . self.parse_mod(&token::CloseDelim(token::Brace))?; . attrs.append(&mut inner_attrs); . ModKind::Loaded(items, Inline::Yes, inner_span) . }; 21,195 ( 0.01%) Ok((id, ItemKind::Mod(unsafety, mod_kind))) 11,304 ( 0.01%) } . . /// Parses the contents of a module (inner attributes followed by module items). 20 ( 0.00%) pub fn parse_mod( . &mut self, . term: &TokenKind, . ) -> PResult<'a, (Vec, Vec>, Span)> { 4 ( 0.00%) let lo = self.token.span; 4 ( 0.00%) let attrs = self.parse_inner_attributes()?; . . let mut items = vec![]; . while let Some(item) = self.parse_item(ForceCollect::No)? { . items.push(item); 8,481 ( 0.00%) self.maybe_consume_incorrect_semicolon(&items); . } . . if !self.eat(term) { . let token_str = super::token_descr(&self.token); . if !self.maybe_consume_incorrect_semicolon(&items) { . let msg = &format!("expected item, found {}", token_str); . let mut err = self.struct_span_err(self.token.span, msg); . err.span_label(self.token.span, "expected item"); . return Err(err); . } . } . 60 ( 0.00%) Ok((attrs, items, lo.to(self.prev_token.span))) 18 ( 0.00%) } . } . . pub(super) type ItemInfo = (Ident, ItemKind); . . impl<'a> Parser<'a> { . pub fn parse_item(&mut self, force_collect: ForceCollect) -> PResult<'a, Option>> { . let fn_parse_mode = FnParseMode { req_name: |_| true, req_body: true }; . self.parse_item_(fn_parse_mode, force_collect).map(|i| i.map(P)) . } . . fn parse_item_( . &mut self, . fn_parse_mode: FnParseMode, . force_collect: ForceCollect, . ) -> PResult<'a, Option> { 8,487 ( 0.00%) let attrs = self.parse_outer_attributes()?; 31,119 ( 0.02%) self.parse_item_common(attrs, true, false, fn_parse_mode, force_collect) . } . 45,280 ( 0.03%) pub(super) fn parse_item_common( . &mut self, . attrs: AttrWrapper, . mac_allowed: bool, . attrs_allowed: bool, . fn_parse_mode: FnParseMode, . force_collect: ForceCollect, . ) -> PResult<'a, Option> { . // Don't use `maybe_whole` so that we have precise control . // over when we bump the parser 5,660 ( 0.00%) if let token::Interpolated(nt) = &self.token.kind { . if let token::NtItem(item) = &**nt { . let mut item = item.clone(); . self.bump(); . . attrs.prepend_to_nt_inner(&mut item.attrs); . return Ok(Some(item.into_inner())); . } . }; . . let mut unclosed_delims = vec![]; . let item = 11,320 ( 0.01%) self.collect_tokens_trailing_token(attrs, force_collect, |this: &mut Self, attrs| { . let item = 11,320 ( 0.01%) this.parse_item_common_(attrs, mac_allowed, attrs_allowed, fn_parse_mode); . unclosed_delims.append(&mut this.unclosed_delims); 25,470 ( 0.01%) Ok((item?, TrailingToken::None)) . })?; . . self.unclosed_delims.append(&mut unclosed_delims); 14,150 ( 0.01%) Ok(item) 22,640 ( 0.01%) } . . fn parse_item_common_( . &mut self, . mut attrs: Vec, . mac_allowed: bool, . attrs_allowed: bool, . fn_parse_mode: FnParseMode, . ) -> PResult<'a, Option> { 8,490 ( 0.00%) let lo = self.token.span; 11,320 ( 0.01%) let vis = self.parse_visibility(FollowedByType::No)?; . let mut def = self.parse_defaultness(); . let kind = 31,130 ( 0.02%) self.parse_item_kind(&mut attrs, mac_allowed, lo, &vis, &mut def, fn_parse_mode)?; 56,564 ( 0.03%) if let Some((ident, kind)) = kind { . self.error_on_unconsumed_default(def, &kind); 8,484 ( 0.00%) let span = lo.to(self.prev_token.span); . let id = DUMMY_NODE_ID; 62,216 ( 0.04%) let item = Item { ident, attrs, id, kind, vis, span, tokens: None }; 36,764 ( 0.02%) return Ok(Some(item)); . } . . // At this point, we have failed to parse an item. . self.error_on_unmatched_vis(&vis); . self.error_on_unmatched_defaultness(def); 4 ( 0.00%) if !attrs_allowed { . self.recover_attrs_no_item(&attrs)?; . } 4 ( 0.00%) Ok(None) . } . . /// Error in-case a non-inherited visibility was parsed but no item followed. . fn error_on_unmatched_vis(&self, vis: &Visibility) { 4 ( 0.00%) if let VisibilityKind::Inherited = vis.kind { . return; . } . let vs = pprust::vis_to_string(&vis); . let vs = vs.trim_end(); . self.struct_span_err(vis.span, &format!("visibility `{}` is not followed by an item", vs)) . .span_label(vis.span, "the visibility") . .help(&format!("you likely meant to define an item, e.g., `{} fn foo() {{}}`", vs)) . .emit(); . } . . /// Error in-case a `default` was parsed but no item followed. . fn error_on_unmatched_defaultness(&self, def: Defaultness) { 4 ( 0.00%) if let Defaultness::Default(sp) = def { . self.struct_span_err(sp, "`default` is not followed by an item") . .span_label(sp, "the `default` qualifier") . .note("only `fn`, `const`, `type`, or `impl` items may be prefixed by `default`") . .emit(); . } . } . . /// Error in-case `default` was parsed in an in-appropriate context. . fn error_on_unconsumed_default(&self, def: Defaultness, kind: &ItemKind) { 5,656 ( 0.00%) if let Defaultness::Default(span) = def { . let msg = format!("{} {} cannot be `default`", kind.article(), kind.descr()); . self.struct_span_err(span, &msg) . .span_label(span, "`default` because of this") . .note("only associated `fn`, `const`, and `type` items can be `default`") . .emit(); . } . } . -- line 190 ---------------------------------------- -- line 198 ---------------------------------------- . def: &mut Defaultness, . fn_parse_mode: FnParseMode, . ) -> PResult<'a, Option> { . let def_final = def == &Defaultness::Final; . let mut def = || mem::replace(def, Defaultness::Final); . . let info = if self.eat_keyword(kw::Use) { . // USE ITEM 2,828 ( 0.00%) let tree = self.parse_use_tree()?; . . // If wildcard or glob-like brace syntax doesn't have `;`, . // the user may not know `*` or `{}` should be the last. . if let Err(mut e) = self.expect_semi() { . match tree.kind { . UseTreeKind::Glob => { . e.note("the wildcard token must be last on the path").emit(); . } -- line 214 ---------------------------------------- -- line 215 ---------------------------------------- . UseTreeKind::Nested(..) => { . e.note("glob-like brace syntax must be last on the path").emit(); . } . _ => (), . } . return Err(e); . } . 19,796 ( 0.01%) (Ident::empty(), ItemKind::Use(tree)) 7,080 ( 0.00%) } else if self.check_fn_front_matter(def_final) { . // FUNCTION ITEM 27 ( 0.00%) let (ident, sig, generics, body) = self.parse_fn(attrs, fn_parse_mode, lo, vis)?; . (ident, ItemKind::Fn(Box::new(Fn { defaultness: def(), sig, generics, body }))) . } else if self.eat_keyword(kw::Extern) { . if self.eat_keyword(kw::Crate) { . // EXTERN CRATE . self.parse_item_extern_crate()? . } else { . // EXTERN BLOCK . self.parse_item_foreign_mod(attrs, Unsafe::No)? . } 4,245 ( 0.00%) } else if self.is_unsafe_foreign_mod() { . // EXTERN BLOCK . let unsafety = self.parse_unsafety(); . self.expect_keyword(kw::Extern)?; . self.parse_item_foreign_mod(attrs, unsafety)? . } else if self.is_static_global() { . // STATIC ITEM . self.bump(); // `static` . let m = self.parse_mutability(); . let (ident, ty, expr) = self.parse_item_global(Some(m))?; . (ident, ItemKind::Static(ty, m, expr)) 4,245 ( 0.00%) } else if let Const::Yes(const_span) = self.parse_constness() { . // CONST ITEM . if self.token.is_keyword(kw::Impl) { . // recover from `const impl`, suggest `impl const` . self.recover_const_impl(const_span, attrs, def())? . } else { . self.recover_const_mut(const_span); . let (ident, ty, expr) = self.parse_item_global(None)?; . (ident, ItemKind::Const(def(), ty, expr)) . } 9,905 ( 0.01%) } else if self.check_keyword(kw::Trait) || self.check_auto_or_unsafe_trait_item() { . // TRAIT ITEM . self.parse_item_trait(attrs, lo)? 5,660 ( 0.00%) } else if self.check_keyword(kw::Impl) 5,660 ( 0.00%) || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Impl]) . { . // IMPL ITEM . self.parse_item_impl(attrs, def())? 5,660 ( 0.00%) } else if self.check_keyword(kw::Mod) 8 ( 0.00%) || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Mod]) . { . // MODULE ITEM 2,826 ( 0.00%) self.parse_item_mod(attrs)? 8 ( 0.00%) } else if self.eat_keyword(kw::Type) { . // TYPE ITEM . self.parse_type_alias(def())? 8 ( 0.00%) } else if self.eat_keyword(kw::Enum) { . // ENUM ITEM . self.parse_item_enum()? 8 ( 0.00%) } else if self.eat_keyword(kw::Struct) { . // STRUCT ITEM . self.parse_item_struct()? 8 ( 0.00%) } else if self.is_kw_followed_by_ident(kw::Union) { . // UNION ITEM . self.bump(); // `union` . self.parse_item_union()? 8 ( 0.00%) } else if self.eat_keyword(kw::Macro) { . // MACROS 2.0 ITEM . self.parse_item_decl_macro(lo)? 6 ( 0.00%) } else if let IsMacroRulesItem::Yes { has_bang } = self.is_macro_rules_item() { . // MACRO_RULES ITEM . self.parse_item_macro_rules(vis, has_bang)? 6 ( 0.00%) } else if vis.kind.is_pub() && self.isnt_macro_invocation() { . self.recover_missing_kw_before_item()?; . return Ok(None); 10 ( 0.00%) } else if macros_allowed && self.check_path() { . // MACRO INVOCATION ITEM . (Ident::empty(), ItemKind::MacCall(self.parse_item_macro(vis)?)) . } else { . return Ok(None); . }; 36,764 ( 0.02%) Ok(Some(info)) . } . . /// When parsing a statement, would the start of a path be an item? . pub(super) fn is_path_start_item(&mut self) -> bool { 6 ( 0.00%) self.is_crate_vis() // no: `crate::b`, yes: `crate $item` 3 ( 0.00%) || self.is_kw_followed_by_ident(kw::Union) // no: `union::b`, yes: `union U { .. }` . || self.check_auto_or_unsafe_trait_item() // no: `auto::b`, yes: `auto trait X { .. }` . || self.is_async_fn() // no(2015): `async::b`, yes: `async fn` 3 ( 0.00%) || matches!(self.is_macro_rules_item(), IsMacroRulesItem::Yes{..}) // no: `macro_rules::b`, yes: `macro_rules! mac` . } . . /// Are we sure this could not possibly be a macro invocation? . fn isnt_macro_invocation(&mut self) -> bool { . self.check_ident() && self.look_ahead(1, |t| *t != token::Not && *t != token::ModSep) . } . . /// Recover on encountering a struct or method definition where the user -- line 315 ---------------------------------------- -- line 435 ---------------------------------------- . Err(err) . } . } . } . . /// Recover if we parsed attributes and expected an item but there was none. . fn recover_attrs_no_item(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> { . let (start, end) = match attrs { 4 ( 0.00%) [] => return Ok(()), . [x0 @ xn] | [x0, .., xn] => (x0, xn), . }; . let msg = if end.is_doc_comment() { . "expected item after doc comment" . } else { . "expected item after attributes" . }; . let mut err = self.struct_span_err(end.span, msg); -- line 451 ---------------------------------------- -- line 454 ---------------------------------------- . } . if let [.., penultimate, _] = attrs { . err.span_label(start.span.to(penultimate.span), "other attributes here"); . } . Err(err) . } . . fn is_async_fn(&self) -> bool { 4 ( 0.00%) self.token.is_keyword(kw::Async) && self.is_keyword_ahead(1, &[kw::Fn]) . } . . fn parse_polarity(&mut self) -> ast::ImplPolarity { . // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type. . if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) { . self.bump(); // `!` . ast::ImplPolarity::Negative(self.prev_token.span) . } else { -- line 470 ---------------------------------------- -- line 675 ---------------------------------------- . false . } . . /// Parses defaultness (i.e., `default` or nothing). . fn parse_defaultness(&mut self) -> Defaultness { . // We are interested in `default` followed by another identifier. . // However, we must avoid keywords that occur as binary operators. . // Currently, the only applicable keyword is `as` (`default as Ty`). 5,660 ( 0.00%) if self.check_keyword(kw::Default) . && self.look_ahead(1, |t| t.is_non_raw_ident_where(|i| i.name != kw::As)) . { . self.bump(); // `default` . Defaultness::Default(self.prev_token.uninterpolated_span()) . } else { . Defaultness::Final . } . } . . /// Is this an `(unsafe auto? | auto) trait` item? 5,660 ( 0.00%) fn check_auto_or_unsafe_trait_item(&mut self) -> bool { . // auto trait 2,832 ( 0.00%) self.check_keyword(kw::Auto) && self.is_keyword_ahead(1, &[kw::Trait]) . // unsafe auto trait 2,832 ( 0.00%) || self.check_keyword(kw::Unsafe) && self.is_keyword_ahead(1, &[kw::Trait, kw::Auto]) 5,660 ( 0.00%) } . . /// Parses `unsafe? auto? trait Foo { ... }` or `trait Foo = Bar;`. . fn parse_item_trait(&mut self, attrs: &mut Vec, lo: Span) -> PResult<'a, ItemInfo> { . let unsafety = self.parse_unsafety(); . // Parse optional `auto` prefix. . let is_auto = if self.eat_keyword(kw::Auto) { IsAuto::Yes } else { IsAuto::No }; . . self.expect_keyword(kw::Trait)?; -- line 707 ---------------------------------------- -- line 871 ---------------------------------------- . /// . /// ```text . /// USE_TREE = [`::`] `*` | . /// [`::`] `{` USE_TREE_LIST `}` | . /// PATH `::` `*` | . /// PATH `::` `{` USE_TREE_LIST `}` | . /// PATH [`as` IDENT] . /// ``` 12,726 ( 0.01%) fn parse_use_tree(&mut self) -> PResult<'a, UseTree> { 1,414 ( 0.00%) let lo = self.token.span; . 8,484 ( 0.00%) let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo(), tokens: None }; 12,726 ( 0.01%) let kind = if self.check(&token::OpenDelim(token::Brace)) 4,242 ( 0.00%) || self.check(&token::BinOp(token::Star)) 2,828 ( 0.00%) || self.is_import_coupler() . { . // `use *;` or `use ::*;` or `use {...};` or `use ::{...};` . let mod_sep_ctxt = self.token.span.ctxt(); . if self.eat(&token::ModSep) { . prefix . .segments . .push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt))); . } . . self.parse_use_tree_glob_or_nested()? . } else { . // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;` 7,070 ( 0.00%) prefix = self.parse_path(PathStyle::Mod)?; . . if self.eat(&token::ModSep) { . self.parse_use_tree_glob_or_nested()? . } else { 7 ( 0.00%) UseTreeKind::Simple(self.parse_rename()?, DUMMY_NODE_ID, DUMMY_NODE_ID) . } . }; . 53,732 ( 0.03%) Ok(UseTree { prefix, kind, span: lo.to(self.prev_token.span) }) 11,312 ( 0.01%) } . . /// Parses `*` or `{...}`. . fn parse_use_tree_glob_or_nested(&mut self) -> PResult<'a, UseTreeKind> { . Ok(if self.eat(&token::BinOp(token::Star)) { . UseTreeKind::Glob . } else { . UseTreeKind::Nested(self.parse_use_tree_list()?) . }) -- line 916 ---------------------------------------- -- line 921 ---------------------------------------- . /// ```text . /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`] . /// ``` . fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> { . self.parse_delim_comma_seq(token::Brace, |p| Ok((p.parse_use_tree()?, DUMMY_NODE_ID))) . .map(|(r, _)| r) . } . 6 ( 0.00%) fn parse_rename(&mut self) -> PResult<'a, Option> { . if self.eat_keyword(kw::As) { self.parse_ident_or_underscore().map(Some) } else { Ok(None) } 12 ( 0.00%) } . . fn parse_ident_or_underscore(&mut self) -> PResult<'a, Ident> { . match self.token.ident() { . Some((ident @ Ident { name: kw::Underscore, .. }, false)) => { . self.bump(); . Ok(ident) . } . _ => self.parse_ident(), -- line 939 ---------------------------------------- -- line 1058 ---------------------------------------- . "try using a static value", . "static ".to_string(), . Applicability::MachineApplicable, . ) . .note("for more information, visit https://doc.rust-lang.org/std/keyword.extern.html") . .emit(); . } . 11,320 ( 0.01%) fn is_unsafe_foreign_mod(&self) -> bool { 7,075 ( 0.00%) self.token.is_keyword(kw::Unsafe) . && self.is_keyword_ahead(1, &[kw::Extern]) . && self.look_ahead( . 2 + self.look_ahead(2, |t| t.can_begin_literal_maybe_minus() as usize), . |t| t.kind == token::OpenDelim(token::Brace), . ) 12,735 ( 0.01%) } . . fn is_static_global(&mut self) -> bool { 2,830 ( 0.00%) if self.check_keyword(kw::Static) { . // Check if this could be a closure. . !self.look_ahead(1, |token| { . if token.is_keyword(kw::Move) { . return true; . } . matches!(token.kind, token::BinOp(token::Or) | token::OrOr) . }) . } else { -- line 1084 ---------------------------------------- -- line 1621 ---------------------------------------- . }; . . self.sess.gated_spans.gate(sym::decl_macro, lo.to(self.prev_token.span)); . Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: false }))) . } . . /// Is this a possibly malformed start of a `macro_rules! foo` item definition? . 24 ( 0.00%) fn is_macro_rules_item(&mut self) -> IsMacroRulesItem { 6 ( 0.00%) if self.check_keyword(kw::MacroRules) { . let macro_rules_span = self.token.span; . . if self.look_ahead(1, |t| *t == token::Not) && self.look_ahead(2, |t| t.is_ident()) { . return IsMacroRulesItem::Yes { has_bang: true }; . } else if self.look_ahead(1, |t| (t.is_ident())) { . // macro_rules foo . self.struct_span_err(macro_rules_span, "expected `!` after `macro_rules`") . .span_suggestion( -- line 1638 ---------------------------------------- -- line 1643 ---------------------------------------- . ) . .emit(); . . return IsMacroRulesItem::Yes { has_bang: false }; . } . } . . IsMacroRulesItem::No 24 ( 0.00%) } . . /// Parses a `macro_rules! foo { ... }` declarative macro. . fn parse_item_macro_rules( . &mut self, . vis: &Visibility, . has_bang: bool, . ) -> PResult<'a, ItemInfo> { . self.expect_keyword(kw::MacroRules)?; // `macro_rules` -- line 1659 ---------------------------------------- -- line 1843 ---------------------------------------- . /// definition or extern block. Within an impl block or a module, it should . /// always be set to true. . pub req_body: bool, . } . . /// Parsing of functions and methods. . impl<'a> Parser<'a> { . /// Parse a function starting from the front matter (`const ...`) to the body `{ ... }` or `;`. 15 ( 0.00%) fn parse_fn( . &mut self, . attrs: &mut Vec, . fn_parse_mode: FnParseMode, . sig_lo: Span, . vis: &Visibility, . ) -> PResult<'a, (Ident, FnSig, Generics, Option>)> { 5 ( 0.00%) let header = self.parse_fn_front_matter(vis)?; // `const ... fn` 4 ( 0.00%) let ident = self.parse_ident()?; // `foo` 3 ( 0.00%) let mut generics = self.parse_generics()?; // `<'a, T, ...>` . let decl = 8 ( 0.00%) self.parse_fn_decl(fn_parse_mode.req_name, AllowPlus::Yes, RecoverReturnSign::Yes)?; // `(p: u8, ...)` 9 ( 0.00%) generics.where_clause = self.parse_where_clause()?; // `where T: Ord` . 2 ( 0.00%) let mut sig_hi = self.prev_token.span; 7 ( 0.00%) let body = self.parse_fn_body(attrs, &ident, &mut sig_hi, fn_parse_mode.req_body)?; // `;` or `{ ... }`. 3 ( 0.00%) let fn_sig_span = sig_lo.to(sig_hi); 29 ( 0.00%) Ok((ident, FnSig { header, decl, span: fn_sig_span }, generics, body)) 8 ( 0.00%) } . . /// Parse the "body" of a function. . /// This can either be `;` when there's no body, . /// or e.g. a block when the function is a provided one. 12 ( 0.00%) fn parse_fn_body( . &mut self, . attrs: &mut Vec, . ident: &Ident, . sig_hi: &mut Span, . req_body: bool, . ) -> PResult<'a, Option>> { 2 ( 0.00%) let has_semi = if req_body { 3 ( 0.00%) self.token.kind == TokenKind::Semi . } else { . // Only include `;` in list of expected tokens if body is not required . self.check(&TokenKind::Semi) . }; 3 ( 0.00%) let (inner_attrs, body) = if has_semi { . // Include the trailing semicolon in the span of the signature . self.expect_semi()?; . *sig_hi = self.prev_token.span; . (Vec::new(), None) 6 ( 0.00%) } else if self.check(&token::OpenDelim(token::Brace)) || self.token.is_whole_block() { . self.parse_inner_attrs_and_block().map(|(attrs, body)| (attrs, Some(body)))? . } else if self.token.kind == token::Eq { . // Recover `fn foo() = $expr;`. . self.bump(); // `=` . let eq_sp = self.prev_token.span; . let _ = self.parse_expr()?; . self.expect_semi()?; // `;` . let span = eq_sp.to(self.prev_token.span); -- line 1900 ---------------------------------------- -- line 1921 ---------------------------------------- . } else { . return Err(err); . } . } . (Vec::new(), None) . }; . attrs.extend(inner_attrs); . Ok(body) 10 ( 0.00%) } . . /// Is the current token the start of an `FnHeader` / not a valid parse? . /// . /// `check_pub` adds additional `pub` to the checks in case users place it . /// wrongly, can be used to ensure `pub` never comes after `default`. 12,771 ( 0.01%) pub(super) fn check_fn_front_matter(&mut self, check_pub: bool) -> bool { . // We use an over-approximation here. . // `const const`, `fn const` won't parse, but we're not stepping over other syntax either. . // `pub` is added in case users got confused with the ordering like `async pub fn`, . // only if it wasn't preceeded by `default` as `default pub` is invalid. 7,095 ( 0.00%) let quals: &[Symbol] = if check_pub { . &[kw::Pub, kw::Const, kw::Async, kw::Unsafe, kw::Extern] . } else { . &[kw::Const, kw::Async, kw::Unsafe, kw::Extern] . }; 2,838 ( 0.00%) self.check_keyword(kw::Fn) // Definitely an `fn`. . // `$qual fn` or `$qual $qual`: . || quals.iter().any(|&kw| self.check_keyword(kw)) . && self.look_ahead(1, |t| { . // `$qual fn`, e.g. `const fn` or `async fn`. . t.is_keyword(kw::Fn) . // Two qualifiers `$qual $qual` is enough, e.g. `async unsafe`. . || t.is_non_raw_ident_where(|i| quals.contains(&i.name) . // Rule out 2015 `const async: T = val`. . && i.is_reserved() . // Rule out unsafe extern block. . && !self.is_unsafe_foreign_mod()) . }) . // `extern ABI fn` 2,836 ( 0.00%) || self.check_keyword(kw::Extern) . && self.look_ahead(1, |t| t.can_begin_literal_maybe_minus()) . && self.look_ahead(2, |t| t.is_keyword(kw::Fn)) 11,352 ( 0.01%) } . . /// Parses all the "front matter" (or "qualifiers") for a `fn` declaration, . /// up to and including the `fn` keyword. The formal grammar is: . /// . /// ```text . /// Extern = "extern" StringLit? ; . /// FnQual = "const"? "async"? "unsafe"? Extern? ; . /// FnFrontMatter = FnQual "fn" ; . /// ``` . /// . /// `vis` represents the visibility that was already parsed, if any. Use . /// `Visibility::Inherited` when no visibility is known. 10 ( 0.00%) pub(super) fn parse_fn_front_matter(&mut self, orig_vis: &Visibility) -> PResult<'a, FnHeader> { 2 ( 0.00%) let sp_start = self.token.span; 4 ( 0.00%) let constness = self.parse_constness(); . 1 ( 0.00%) let async_start_sp = self.token.span; . let asyncness = self.parse_asyncness(); . 2 ( 0.00%) let unsafe_start_sp = self.token.span; 4 ( 0.00%) let unsafety = self.parse_unsafety(); . 2 ( 0.00%) let ext_start_sp = self.token.span; . let ext = self.parse_extern(); . 2 ( 0.00%) if let Async::Yes { span, .. } = asyncness { . self.ban_async_in_2015(span); . } . . if !self.eat_keyword(kw::Fn) { . // It is possible for `expect_one_of` to recover given the contents of . // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't . // account for this. . match self.expect_one_of(&[], &[]) { -- line 1996 ---------------------------------------- -- line 2088 ---------------------------------------- . } . } . } . return Err(err); . } . } . } . 18 ( 0.00%) Ok(FnHeader { constness, unsafety, asyncness, ext }) 8 ( 0.00%) } . . /// We are parsing `async fn`. If we are on Rust 2015, emit an error. . fn ban_async_in_2015(&self, span: Span) { . if span.rust_2015() { . let diag = self.diagnostic(); . struct_span_err!(diag, span, E0670, "`async fn` is not permitted in Rust 2015") . .span_label(span, "to use `async fn`, switch to Rust 2018 or later") . .help(&format!("set `edition = \"{}\"` in `Cargo.toml`", LATEST_STABLE_EDITION)) . .note("for more on editions, read https://doc.rust-lang.org/edition-guide") . .emit(); . } . } . . /// Parses the parameter list and result type of a function declaration. 11 ( 0.00%) pub(super) fn parse_fn_decl( . &mut self, . req_name: ReqName, . ret_allow_plus: AllowPlus, . recover_return_sign: RecoverReturnSign, . ) -> PResult<'a, P> { 4 ( 0.00%) Ok(P(FnDecl { 1 ( 0.00%) inputs: self.parse_fn_params(req_name)?, 6 ( 0.00%) output: self.parse_ret_ty(ret_allow_plus, RecoverQPath::Yes, recover_return_sign)?, . })) 10 ( 0.00%) } . . /// Parses the parameter list of a function, including the `(` and `)` delimiters. . fn parse_fn_params(&mut self, req_name: ReqName) -> PResult<'a, Vec> { 1 ( 0.00%) let mut first_param = true; . // Parse the arguments, starting out with `self` being allowed... 2 ( 0.00%) let (mut params, _) = self.parse_paren_comma_seq(|p| { . let param = p.parse_param_general(req_name, first_param).or_else(|mut e| { . e.emit(); . let lo = p.prev_token.span; . // Skip every token until next possible arg or end. . p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]); . // Create a placeholder argument for proper arg count (issue #34264). . Ok(dummy_arg(Ident::new(kw::Empty, lo.to(p.prev_token.span)))) . }); . // ...now that we've parsed the first argument, `self` is no longer allowed. . first_param = false; . param . })?; . // Replace duplicated recovered params with `_` pattern to avoid unnecessary errors. . self.deduplicate_recovered_params_names(&mut params); 2 ( 0.00%) Ok(params) . } . . /// Parses a single function parameter. . /// . /// - `self` is syntactically allowed when `first_param` holds. . fn parse_param_general(&mut self, req_name: ReqName, first_param: bool) -> PResult<'a, Param> { . let lo = self.token.span; . let attrs = self.parse_outer_attributes()?; -- line 2151 ---------------------------------------- 80,634 ( 0.05%) -------------------------------------------------------------------------------- -- 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> { 549,075 ( 0.31%) 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) }; 274,894 ( 0.16%) 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> { 17 ( 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) }; 62 ( 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 ---------------------------------------- 49,620 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/util/literal.rs -------------------------------------------------------------------------------- Ir -- line 19 ---------------------------------------- . InvalidFloatSuffix, . NonDecimalFloat(u32), . IntTooLarge, . } . . impl LitKind { . /// Converts literal token into a semantic literal. . fn from_lit_token(lit: token::Lit) -> Result { 2,845 ( 0.00%) let token::Lit { kind, symbol, suffix } = lit; 2,845 ( 0.00%) if suffix.is_some() && !kind.may_have_suffix() { . return Err(LitError::InvalidSuffix); . } . 36,985 ( 0.02%) Ok(match kind { . token::Bool => { . assert!(symbol.is_bool_lit()); . LitKind::Bool(symbol == kw::True) . } . token::Byte => { . return unescape_byte(symbol.as_str()) . .map(LitKind::Byte) . .map_err(|_| LitError::LexerError); -- line 40 ---------------------------------------- -- line 50 ---------------------------------------- . token::Integer => return integer_lit(symbol, suffix), . token::Float => return float_lit(symbol, suffix), . . token::Str => { . // If there are no characters requiring special treatment we can . // reuse the symbol from the token. Otherwise, we must generate a . // new symbol because the string in the LitKind is different to the . // string in the token. 8,535 ( 0.00%) let s = symbol.as_str(); . let symbol = . if s.contains(&['\\', '\r']) { . let mut buf = String::with_capacity(s.len()); . let mut error = Ok(()); . unescape_literal(&s, Mode::Str, &mut |_, unescaped_char| { . match unescaped_char { . Ok(c) => buf.push(c), . Err(err) => { -- line 66 ---------------------------------------- -- line 68 ---------------------------------------- . error = Err(LitError::LexerError); . } . } . } . }); . error?; . Symbol::intern(&buf) . } else { 5,690 ( 0.00%) symbol . }; 14,225 ( 0.01%) LitKind::Str(symbol, ast::StrStyle::Cooked) . } . token::StrRaw(n) => { . // Ditto. . let s = symbol.as_str(); . let symbol = . if s.contains('\r') { . let mut buf = String::with_capacity(s.len()); . let mut error = Ok(()); -- line 86 ---------------------------------------- -- line 198 ---------------------------------------- . }; . . token::Lit::new(kind, symbol, suffix) . } . } . . impl Lit { . /// Converts literal token into an AST literal. 39,830 ( 0.02%) pub fn from_lit_token(token: token::Lit, span: Span) -> Result { 17,070 ( 0.01%) Ok(Lit { token, kind: LitKind::from_lit_token(token)?, span }) 25,605 ( 0.01%) } . . /// Converts arbitrary token into an AST literal. . /// . /// Keep this in sync with `Token::can_begin_literal_or_bool` excluding unary negation. 63,963 ( 0.04%) pub fn from_token(token: &Token) -> Result { 51,155 ( 0.03%) let lit = match token.uninterpolate().kind { 25,572 ( 0.01%) token::Ident(name, false) if name.is_bool_lit() => { . token::Lit::new(token::Bool, name, None) . } 11,380 ( 0.01%) token::Literal(lit) => lit, . token::Interpolated(ref nt) => { . if let token::NtExpr(expr) | token::NtLiteral(expr) = &**nt { . if let ast::ExprKind::Lit(lit) = &expr.kind { . return Ok(lit.clone()); . } . } . return Err(LitError::NotLiteral); . } . _ => return Err(LitError::NotLiteral), . }; . 8,535 ( 0.00%) Lit::from_lit_token(lit, token.span) 63,963 ( 0.04%) } . . /// Attempts to recover an AST literal from semantic literal. . /// This function is used when the original token doesn't exist (e.g. the literal is created . /// by an AST-based macro) or unavailable (e.g. from HIR pretty-printing). . pub fn from_lit_kind(kind: LitKind, span: Span) -> Lit { . Lit { token: kind.to_lit_token(), kind, span } . } . -- line 239 ---------------------------------------- 24,166 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/option.rs -------------------------------------------------------------------------------- Ir -- line 504 ---------------------------------------- . use crate::panicking::{panic, panic_str}; . use crate::pin::Pin; . use crate::{ . convert, hint, mem, . ops::{self, ControlFlow, Deref, DerefMut}, . }; . . /// The `Option` type. See [the module level documentation](self) for more. 350,865 ( 0.20%) #[derive(Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)] . #[rustc_diagnostic_item = "Option"] . #[stable(feature = "rust1", since = "1.0.0")] . pub enum Option { . /// No value. . #[lang = "None"] . #[stable(feature = "rust1", since = "1.0.0")] . None, . /// Some value of type `T`. -- line 520 ---------------------------------------- -- line 543 ---------------------------------------- . /// let x: Option = None; . /// assert_eq!(x.is_some(), false); . /// ``` . #[must_use = "if you intended to assert that this has a value, consider `.unwrap()` instead"] . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_option", since = "1.48.0")] . pub const fn is_some(&self) -> bool { 20,699 ( 0.01%) matches!(*self, Some(_)) . } . . /// Returns `true` if the option is a [`Some`] wrapping a value matching the predicate. . /// . /// # Examples . /// . /// ``` . /// #![feature(is_some_with)] -- line 559 ---------------------------------------- -- line 616 ---------------------------------------- . /// // then consume *that* with `map`, leaving `text` on the stack. . /// let text_length: Option = text.as_ref().map(|s| s.len()); . /// println!("still can print text: {:?}", text); . /// ``` . #[inline] . #[rustc_const_stable(feature = "const_option", since = "1.48.0")] . #[stable(feature = "rust1", since = "1.0.0")] . pub const fn as_ref(&self) -> Option<&T> { 90,618 ( 0.05%) match *self { . Some(ref x) => Some(x), . None => None, . } . } . . /// Converts from `&mut Option` to `Option<&mut T>`. . /// . /// # Examples -- line 632 ---------------------------------------- -- line 638 ---------------------------------------- . /// None => {}, . /// } . /// assert_eq!(x, Some(42)); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] . pub const fn as_mut(&mut self) -> Option<&mut T> { 4,420 ( 0.00%) match *self { . Some(ref mut x) => Some(x), . None => None, . } . } . . /// Converts from [Pin]<[&]Option\> to Option<[Pin]<[&]T>>. . /// . /// [&]: reference "shared reference" -- line 654 ---------------------------------------- -- line 705 ---------------------------------------- . /// let x: Option<&str> = None; . /// x.expect("fruits are healthy"); // panics with `fruits are healthy` . /// ``` . #[inline] . #[track_caller] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] . pub const fn expect(self, msg: &str) -> T { 8,683 ( 0.00%) match self { 80 ( 0.00%) Some(val) => val, . None => expect_failed(msg), . } . } . . /// Returns the contained [`Some`] value, consuming the `self` value. . /// . /// Because this function may panic, its use is generally discouraged. . /// Instead, prefer to use pattern matching and handle the [`None`] -- line 722 ---------------------------------------- -- line 742 ---------------------------------------- . /// let x: Option<&str> = None; . /// assert_eq!(x.unwrap(), "air"); // fails . /// ``` . #[inline] . #[track_caller] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] . pub const fn unwrap(self) -> T { 42,734 ( 0.02%) match self { 1,315 ( 0.00%) Some(val) => val, . None => panic("called `Option::unwrap()` on a `None` value"), . } . } . . /// Returns the contained [`Some`] value or a provided default. . /// . /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing . /// the result of a function call, it is recommended to use [`unwrap_or_else`], -- line 759 ---------------------------------------- -- line 769 ---------------------------------------- . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn unwrap_or(self, default: T) -> T . where . T: ~const Drop, . { 30,553 ( 0.02%) match self { . Some(x) => x, 4 ( 0.00%) None => default, . } 103 ( 0.00%) } . . /// Returns the contained [`Some`] value or computes it from a closure. . /// . /// # Examples . /// . /// ``` . /// let k = 10; . /// assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4); -- line 789 ---------------------------------------- -- line 792 ---------------------------------------- . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn unwrap_or_else(self, f: F) -> T . where . F: ~const FnOnce() -> T, . F: ~const Drop, . { 143,104 ( 0.08%) match self { 966 ( 0.00%) Some(x) => x, . None => f(), . } 5 ( 0.00%) } . . /// Returns the contained [`Some`] value or a default. . /// . /// Consumes the `self` argument then, if [`Some`], returns the contained . /// value, otherwise if [`None`], returns the [default value] for that . /// type. . /// . /// # Examples -- line 812 ---------------------------------------- -- line 831 ---------------------------------------- . /// [`FromStr`]: crate::str::FromStr . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn unwrap_or_default(self) -> T . where . T: ~const Default, . { 20 ( 0.00%) match self { 12 ( 0.00%) Some(x) => x, . None => Default::default(), . } . } . . /// Returns the contained [`Some`] value, consuming the `self` value, . /// without checking that the value is not [`None`]. . /// . /// # Safety -- line 848 ---------------------------------------- -- line 897 ---------------------------------------- . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn map(self, f: F) -> Option . where . F: ~const FnOnce(T) -> U, . F: ~const Drop, . { 49,964 ( 0.03%) match self { 27,591 ( 0.02%) Some(x) => Some(f(x)), 1,518 ( 0.00%) None => None, . } 21,213 ( 0.01%) } . . /// Calls the provided closure with a reference to the contained value (if [`Some`]). . /// . /// # Examples . /// . /// ``` . /// #![feature(result_option_inspect)] . /// -- line 917 ---------------------------------------- -- line 960 ---------------------------------------- . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn map_or(self, default: U, f: F) -> U . where . F: ~const FnOnce(T) -> U, . F: ~const Drop, . U: ~const Drop, . { 43,873 ( 0.02%) match self { 552 ( 0.00%) Some(t) => f(t), . None => default, . } . } . . /// Computes a default function result (if none), or . /// applies a different function to the contained value (if any). . /// . /// # Examples -- line 977 ---------------------------------------- -- line 990 ---------------------------------------- . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn map_or_else(self, default: D, f: F) -> U . where . D: ~const FnOnce() -> U, . D: ~const Drop, . F: ~const FnOnce(T) -> U, . F: ~const Drop, . { 10 ( 0.00%) match self { . Some(t) => f(t), . None => default(), . } . } . . /// Transforms the `Option` into a [`Result`], mapping [`Some(v)`] to . /// [`Ok(v)`] and [`None`] to [`Err(err)`]. . /// -- line 1006 ---------------------------------------- -- line 1024 ---------------------------------------- . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn ok_or(self, err: E) -> Result . where . E: ~const Drop, . { 37,328 ( 0.02%) match self { . Some(v) => Ok(v), . None => Err(err), . } . } . . /// Transforms the `Option` into a [`Result`], mapping [`Some(v)`] to . /// [`Ok(v)`] and [`None`] to [`Err(err())`]. . /// -- line 1040 ---------------------------------------- -- line 1054 ---------------------------------------- . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn ok_or_else(self, err: F) -> Result . where . F: ~const FnOnce() -> E, . F: ~const Drop, . { 31,252 ( 0.02%) match self { 22,737 ( 0.01%) Some(v) => Ok(v), 5,674 ( 0.00%) None => Err(err()), . } . } . . /// Converts from `Option` (or `&Option`) to `Option<&T::Target>`. . /// . /// Leaves the original Option in-place, creating a new one with a reference . /// to the original one, additionally coercing the contents via [`Deref`]. . /// -- line 1072 ---------------------------------------- -- line 1080 ---------------------------------------- . /// assert_eq!(x.as_deref(), None); . /// ``` . #[stable(feature = "option_deref", since = "1.40.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn as_deref(&self) -> Option<&T::Target> . where . T: ~const Deref, . { 6 ( 0.00%) match self.as_ref() { . Some(t) => Some(t.deref()), . None => None, . } . } . . /// Converts from `Option` (or `&mut Option`) to `Option<&mut T::Target>`. . /// . /// Leaves the original `Option` in-place, creating a new one containing a mutable reference to -- line 1096 ---------------------------------------- -- line 1218 ---------------------------------------- . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn and_then(self, f: F) -> Option . where . F: ~const FnOnce(T) -> Option, . F: ~const Drop, . { 6,434 ( 0.00%) match self { 106 ( 0.00%) Some(x) => f(x), . None => None, . } . } . . /// Returns [`None`] if the option is [`None`], otherwise calls `predicate` . /// with the wrapped value and returns: . /// . /// - [`Some(t)`] if `predicate` returns `true` (where `t` is the wrapped -- line 1235 ---------------------------------------- -- line 1257 ---------------------------------------- . #[stable(feature = "option_filter", since = "1.27.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn filter

(self, predicate: P) -> Self . where . T: ~const Drop, . P: ~const FnOnce(&T) -> bool, . P: ~const Drop, . { 1,430 ( 0.00%) if let Some(x) = self { . if predicate(&x) { . return Some(x); . } . } . None . } . . /// Returns the option if it contains a value, otherwise returns `optb`. -- line 1273 ---------------------------------------- -- line 1299 ---------------------------------------- . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn or(self, optb: Option) -> Option . where . T: ~const Drop, . { 25 ( 0.00%) match self { . Some(x) => Some(x), . None => optb, . } . } . . /// Returns the option if it contains a value, otherwise calls `f` and . /// returns the result. . /// -- line 1315 ---------------------------------------- -- line 1326 ---------------------------------------- . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn or_else(self, f: F) -> Option . where . F: ~const FnOnce() -> Option, . F: ~const Drop, . { 52 ( 0.00%) match self { 80 ( 0.00%) Some(x) => Some(x), . None => f(), . } . } . . /// Returns [`Some`] if exactly one of `self`, `optb` is [`Some`], otherwise returns [`None`]. . /// . /// # Examples . /// -- line 1343 ---------------------------------------- -- line 1499 ---------------------------------------- . #[inline] . #[stable(feature = "option_entry", since = "1.20.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn get_or_insert_with(&mut self, f: F) -> &mut T . where . F: ~const FnOnce() -> T, . F: ~const Drop, . { 27,720 ( 0.02%) if let None = *self { . // the compiler isn't smart enough to know that we are not dropping a `T` . // here and wants us to ensure `T` can be dropped at compile time. 24 ( 0.00%) mem::forget(mem::replace(self, Some(f()))) . } . . // SAFETY: a `None` variant for `self` would have been replaced by a `Some` . // variant in the code above. . unsafe { self.as_mut().unwrap_unchecked() } . } . . ///////////////////////////////////////////////////////////////////////// -- line 1518 ---------------------------------------- -- line 1712 ---------------------------------------- . #[stable(feature = "copied", since = "1.35.0")] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] . pub const fn copied(self) -> Option . where . T: Copy, . { . // FIXME: this implementation, which sidesteps using `Option::map` since it's not const . // ready yet, should be reverted when possible to avoid code repetition 52 ( 0.00%) match self { 851 ( 0.00%) Some(&v) => Some(v), . None => None, . } . } . . /// Maps an `Option<&T>` to an `Option` by cloning the contents of the . /// option. . /// . /// # Examples -- line 1729 ---------------------------------------- -- line 1737 ---------------------------------------- . /// ``` . #[must_use = "`self` will be dropped if the result is not used"] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_cloned", issue = "91582")] . pub const fn cloned(self) -> Option . where . T: ~const Clone, . { 2,858 ( 0.00%) match self { 3 ( 0.00%) Some(t) => Some(t.clone()), 6 ( 0.00%) None => None, . } 14,135 ( 0.01%) } . } . . impl Option<&mut T> { . /// Maps an `Option<&mut T>` to an `Option` by copying the contents of the . /// option. . /// . /// # Examples . /// -- line 1757 ---------------------------------------- -- line 1843 ---------------------------------------- . ///////////////////////////////////////////////////////////////////////////// . // Trait implementations . ///////////////////////////////////////////////////////////////////////////// . . #[stable(feature = "rust1", since = "1.0.0")] . impl Clone for Option { . #[inline] . fn clone(&self) -> Self { 15,851 ( 0.01%) match self { 525 ( 0.00%) Some(x) => Some(x.clone()), 12 ( 0.00%) None => None, . } 193 ( 0.00%) } . . #[inline] . fn clone_from(&mut self, source: &Self) { . match (self, source) { . (Some(to), Some(from)) => to.clone_from(from), . (to, from) => *to = from.clone(), . } . } -- line 1863 ---------------------------------------- -- line 2006 ---------------------------------------- . . #[inline] . fn next(&mut self) -> Option { . self.opt.take() . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 16 ( 0.00%) match self.opt { . Some(_) => (1, Some(1)), . None => (0, Some(0)), . } . } . } . . impl DoubleEndedIterator for Item { . #[inline] -- line 2022 ---------------------------------------- -- line 2245 ---------------------------------------- . . #[inline] . fn from_output(output: Self::Output) -> Self { . Some(output) . } . . #[inline] . fn branch(self) -> ControlFlow { 14,767 ( 0.01%) match self { 38,792 ( 0.02%) Some(v) => ControlFlow::Continue(v), . None => ControlFlow::Break(None), . } . } . } . . #[unstable(feature = "try_trait_v2", issue = "84277")] . #[rustc_const_unstable(feature = "const_convert", issue = "88674")] . impl const ops::FromResidual for Option { . #[inline] . fn from_residual(residual: Option) -> Self { . match residual { 11 ( 0.00%) None => None, . } . } . } . . #[unstable(feature = "try_trait_v2_residual", issue = "91285")] . impl ops::Residual for Option { . type TryType = Option; . } -- line 2274 ---------------------------------------- 572,404 ( 0.33%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/str/iter.rs -------------------------------------------------------------------------------- Ir -- line 138 ---------------------------------------- . #[inline] . fn next(&mut self) -> Option<(usize, char)> { . let pre_len = self.iter.iter.len(); . match self.iter.next() { . None => None, . Some(ch) => { . let index = self.front_offset; . let len = self.iter.iter.len(); 200,709 ( 0.11%) self.front_offset += pre_len - len; . Some((index, ch)) . } . } . } . . #[inline] . fn count(self) -> usize { . self.iter.count() -- line 154 ---------------------------------------- -- line 166 ---------------------------------------- . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl<'a> DoubleEndedIterator for CharIndices<'a> { . #[inline] . fn next_back(&mut self) -> Option<(usize, char)> { . self.iter.next_back().map(|ch| { 15 ( 0.00%) let index = self.front_offset + self.iter.iter.len(); . (index, ch) . }) . } . } . . #[stable(feature = "fused", since = "1.26.0")] . impl FusedIterator for CharIndices<'_> {} . -- line 182 ---------------------------------------- -- line 450 ---------------------------------------- . } . } . . $(#[$common_stability_attribute])* . impl<'a, P: Pattern<'a>> Iterator for $forward_iterator<'a, P> { . type Item = $iterty; . . #[inline] 752 ( 0.00%) fn next(&mut self) -> Option<$iterty> { . self.0.next() 1,080 ( 0.00%) } . } . . $(#[$common_stability_attribute])* . impl<'a, P> Clone for $forward_iterator<'a, P> . where . P: Pattern<'a, Searcher: Clone>, . { . fn clone(&self) -> Self { 44 ( 0.00%) $forward_iterator(self.0.clone()) . } . } . . $(#[$reverse_iterator_attribute])* . $(#[$common_stability_attribute])* . pub struct $reverse_iterator<'a, P: Pattern<'a>>(pub(super) $internal_iterator<'a, P>); . . $(#[$common_stability_attribute])* -- line 477 ---------------------------------------- -- line 582 ---------------------------------------- . .field("finished", &self.finished) . .finish() . } . } . . impl<'a, P: Pattern<'a>> SplitInternal<'a, P> { . #[inline] . fn get_end(&mut self) -> Option<&'a str> { 67 ( 0.00%) if !self.finished && (self.allow_trailing_empty || self.end - self.start > 0) { 32 ( 0.00%) self.finished = true; . // SAFETY: `self.start` and `self.end` always lie on unicode boundaries. . unsafe { 60 ( 0.00%) let string = self.matcher.haystack().get_unchecked(self.start..self.end); . Some(string) . } . } else { . None . } . } . . #[inline] . fn next(&mut self) -> Option<&'a str> { 275 ( 0.00%) if self.finished { . return None; . } . 78 ( 0.00%) let haystack = self.matcher.haystack(); 24 ( 0.00%) match self.matcher.next_match() { . // SAFETY: `Searcher` guarantees that `a` and `b` lie on unicode boundaries. 16 ( 0.00%) Some((a, b)) => unsafe { 55 ( 0.00%) let elt = haystack.get_unchecked(self.start..a); 126 ( 0.00%) self.start = b; . Some(elt) . }, . None => self.get_end(), . } . } . . #[inline] . fn next_inclusive(&mut self) -> Option<&'a str> { -- line 621 ---------------------------------------- -- line 870 ---------------------------------------- . .field("count", &self.count) . .finish() . } . } . . impl<'a, P: Pattern<'a>> SplitNInternal<'a, P> { . #[inline] . fn next(&mut self) -> Option<&'a str> { 140 ( 0.00%) match self.count { . 0 => None, . 1 => { 10 ( 0.00%) self.count = 0; . self.iter.get_end() . } . _ => { 36 ( 0.00%) self.count -= 1; . self.iter.next() . } . } . } . . #[inline] . fn next_back(&mut self) -> Option<&'a str> . where -- line 893 ---------------------------------------- -- line 986 ---------------------------------------- . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . f.debug_tuple("MatchIndicesInternal").field(&self.0).finish() . } . } . . impl<'a, P: Pattern<'a>> MatchIndicesInternal<'a, P> { . #[inline] . fn next(&mut self) -> Option<(usize, &'a str)> { 35 ( 0.00%) self.0 . .next_match() . // SAFETY: `Searcher` guarantees that `start` and `end` lie on unicode boundaries. . .map(|(start, end)| unsafe { (start, self.0.haystack().get_unchecked(start..end)) }) . } . . #[inline] . fn next_back(&mut self) -> Option<(usize, &'a str)> . where -- line 1002 ---------------------------------------- -- line 1204 ---------------------------------------- . #[stable(feature = "split_inclusive", since = "1.51.0")] . pub struct SplitInclusive<'a, P: Pattern<'a>>(pub(super) SplitInternal<'a, P>); . . #[stable(feature = "split_whitespace", since = "1.1.0")] . impl<'a> Iterator for SplitWhitespace<'a> { . type Item = &'a str; . . #[inline] 30 ( 0.00%) fn next(&mut self) -> Option<&'a str> { . self.inner.next() 18 ( 0.00%) } . . #[inline] . fn size_hint(&self) -> (usize, Option) { . self.inner.size_hint() . } . . #[inline] . fn last(mut self) -> Option<&'a str> { -- line 1222 ---------------------------------------- 677 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/rc.rs -------------------------------------------------------------------------------- Ir -- line 364 ---------------------------------------- . #[stable(feature = "rust1", since = "1.0.0")] . pub fn new(value: T) -> Rc { . // There is an implicit weak pointer owned by all the strong . // pointers, which ensures that the weak destructor never frees . // the allocation while the strong destructor is running, even . // if the weak pointer is stored inside the strong one. . unsafe { . Self::from_inner( 97,924 ( 0.06%) Box::leak(box RcBox { strong: Cell::new(1), weak: Cell::new(1), value }).into(), . ) . } . } . . /// Constructs a new `Rc` using a closure `data_fn` that has access to a . /// weak reference to the constructing `Rc`. . /// . /// Generally, a structure circularly referencing itself, either directly or -- line 380 ---------------------------------------- -- line 637 ---------------------------------------- . /// . /// let x = Rc::new(4); . /// let _y = Rc::clone(&x); . /// assert_eq!(*Rc::try_unwrap(x).unwrap_err(), 4); . /// ``` . #[inline] . #[stable(feature = "rc_unique", since = "1.4.0")] . pub fn try_unwrap(this: Self) -> Result { 2 ( 0.00%) if Rc::strong_count(&this) == 1 { . unsafe { . let val = ptr::read(&*this); // copy the contained object . . // Indicate to Weaks that they can't be promoted by decrementing . // the strong count, and then remove the implicit "strong weak" . // pointer while also handling drop logic by just crafting a . // fake Weak. . this.inner().dec_strong(); -- line 653 ---------------------------------------- -- line 931 ---------------------------------------- . /// let five = Rc::new(5); . /// let _weak_five = Rc::downgrade(&five); . /// . /// assert_eq!(1, Rc::weak_count(&five)); . /// ``` . #[inline] . #[stable(feature = "rc_counts", since = "1.15.0")] . pub fn weak_count(this: &Self) -> usize { 9 ( 0.00%) this.inner().weak() - 1 . } . . /// Gets the number of strong (`Rc`) pointers to this allocation. . /// . /// # Examples . /// . /// ``` . /// use std::rc::Rc; -- line 947 ---------------------------------------- -- line 1088 ---------------------------------------- . /// } . /// assert_eq!(*x, "foo"); . /// ``` . #[inline] . #[unstable(feature = "get_mut_unchecked", issue = "63292")] . pub unsafe fn get_mut_unchecked(this: &mut Self) -> &mut T { . // We are careful to *not* create a reference covering the "count" fields, as . // this would conflict with accesses to the reference counts (e.g. by `Weak`). 575 ( 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")] 30 ( 0.00%) pub fn make_mut(this: &mut Self) -> &mut T { 18 ( 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. 3 ( 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()); 6 ( 0.00%) *this = rc.assume_init(); . } 6 ( 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. 6 ( 0.00%) unsafe { &mut this.ptr.as_mut().value } 36 ( 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))] 24 ( 0.00%) unsafe fn copy_from_slice(v: &[T]) -> Rc<[T]> { . unsafe { . let ptr = Self::allocate_for_slice(v.len()); 4 ( 0.00%) ptr::copy_nonoverlapping(v.as_ptr(), &mut (*ptr).value as *mut [T] as *mut T, v.len()); . Self::from_ptr(ptr) . } 32 ( 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 { 86,084 ( 0.05%) &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!" . /// ``` 272,464 ( 0.16%) fn drop(&mut self) { . unsafe { 45,670 ( 0.03%) self.inner().dec_strong(); 91,482 ( 0.05%) if self.inner().strong() == 0 { . // destroy the contained object 540 ( 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(); . 26,752 ( 0.02%) if self.inner().weak() == 0 { 5 ( 0.00%) Global.deallocate(self.ptr.cast(), Layout::for_value(self.ptr.as_ref())); . } . } . } 231,856 ( 0.13%) } . } . . #[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 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; 38 ( 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) { 31,825 ( 0.02%) let strong = self.strong(); . . // We want to abort on overflow instead of dropping the value. . // The reference count will never be zero when this is called; . // nevertheless, we insert an abort here to hint LLVM at . // an otherwise missed optimization. 95,497 ( 0.05%) if strong == 0 || strong == usize::MAX { . abort(); . } 8 ( 0.00%) self.strong_ref().set(strong + 1); . } . . #[inline] . fn dec_strong(&self) { 137,253 ( 0.08%) 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) { 40,131 ( 0.02%) self.weak_ref().set(self.weak() - 1); . } . } . . impl RcInnerPtr for RcBox { . #[inline(always)] . fn weak_ref(&self) -> &Cell { . &self.weak . } -- line 2523 ---------------------------------------- 14,288 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs -------------------------------------------------------------------------------- Ir -- line 111 ---------------------------------------- . const EMPTY: u8 = 0b1111_1111; . . /// Control byte value for a deleted bucket. . const DELETED: u8 = 0b1000_0000; . . /// Checks whether a control byte represents a full bucket (top bit is clear). . #[inline] . fn is_full(ctrl: u8) -> bool { 37,873 ( 0.02%) ctrl & 0x80 == 0 . } . . /// Checks whether a control byte represents a special value (top bit is set). . #[inline] . fn is_special(ctrl: u8) -> bool { . ctrl & 0x80 != 0 . } . . /// Checks whether a special control value is EMPTY (just check 1 bit). . #[inline] . fn special_is_empty(ctrl: u8) -> bool { . debug_assert!(is_special(ctrl)); 2,146 ( 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::()); 353,551 ( 0.20%) 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" . ); . 5,622 ( 0.00%) self.stride += Group::WIDTH; 5,622 ( 0.00%) self.pos += self.stride; 4,861 ( 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,814 ( 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. 9,000 ( 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. 642 ( 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 { 12,470 ( 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. 624 ( 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 = 9,380 ( 0.01%) size.checked_mul(buckets)?.checked_add(ctrl_align - 1)? & !(ctrl_align - 1); 11,336 ( 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 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 { 6 ( 0.00%) Self { . table: RawTableInner::new_in(alloc), . marker: PhantomData, . } . } . . /// Allocates a new hash table with the given number of buckets. . /// . /// The control bytes are left uninitialized. -- line 438 ---------------------------------------- -- line 440 ---------------------------------------- . unsafe fn new_uninitialized( . alloc: A, . buckets: usize, . fallibility: Fallibility, . ) -> Result { . debug_assert!(buckets.is_power_of_two()); . . Ok(Self { 10 ( 0.00%) table: RawTableInner::new_uninitialized( . alloc, . TableLayout::new::(), . buckets, . fallibility, . )?, . marker: PhantomData, . }) . } -- line 456 ---------------------------------------- -- line 569 ---------------------------------------- . #[allow(deprecated)] . pub unsafe fn remove(&mut self, item: Bucket) -> T { . self.erase_no_drop(&item); . item.read() . } . . /// Finds and removes an element from the table, returning it. . #[cfg_attr(feature = "inline-more", inline)] 13,336 ( 0.01%) pub fn remove_entry(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option { . // Avoid `Option::map` because it bloats LLVM IR. . match self.find(hash, eq) { . Some(bucket) => Some(unsafe { self.remove(bucket) }), 8,552 ( 0.00%) None => None, . } 22,653 ( 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) { 96 ( 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) { 4,426 ( 0.00%) if additional > self.table.growth_left { . // Avoid `Result::unwrap_or_else` because it bloats LLVM IR. 6,021 ( 0.00%) if self . .reserve_rehash(additional, hasher, Fallibility::Infallible) . .is_err() . { . unsafe { hint::unreachable_unchecked() } . } . } . } . -- line 660 ---------------------------------------- -- line 671 ---------------------------------------- . } else { . Ok(()) . } . } . . /// Out-of-line slow path for `reserve` and `try_reserve`. . #[cold] . #[inline(never)] 15,399 ( 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 . }, . ) . } 14,152 ( 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)] 86,594 ( 0.05%) 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. 3 ( 0.00%) let old_ctrl = *self.table.ctrl(index); 42,396 ( 0.02%) if unlikely(self.table.growth_left == 0 && special_is_empty(old_ctrl)) { . self.reserve(1, hasher); . index = self.table.find_insert_slot(hash); . } . . self.table.record_item_insert_at(index, old_ctrl, hash); . . let bucket = self.bucket(index); 2 ( 0.00%) bucket.write(value); . bucket . } 64,421 ( 0.04%) } . . /// Attempts to insert a new element without growing the table and return its raw bucket. . /// . /// Returns an `Err` containing the given element if inserting it would require growing the . /// table. . /// . /// This does not check if the given element already exists in the table. . #[cfg(feature = "raw")] -- line 749 ---------------------------------------- -- line 760 ---------------------------------------- . } . } . } . . /// Inserts a new element into the table, and returns a mutable reference to it. . /// . /// This does not check if the given element already exists in the table. . #[cfg_attr(feature = "inline-more", inline)] 208 ( 0.00%) pub fn insert_entry(&mut self, hash: u64, value: T, hasher: impl Fn(&T) -> u64) -> &mut T { . unsafe { self.insert(hash, value, hasher).as_mut() } 156 ( 0.00%) } . . /// Inserts a new element into the table, without growing the table. . /// . /// There must be enough space in the table to insert the new element. . /// . /// This does not check if the given element already exists in the table. . #[cfg_attr(feature = "inline-more", inline)] . #[cfg(any(feature = "raw", feature = "rustc-internal-api"))] 11 ( 0.00%) pub unsafe fn insert_no_grow(&mut self, hash: u64, value: T) -> Bucket { 5,111 ( 0.00%) let (index, old_ctrl) = self.table.prepare_insert_slot(hash); 1,466 ( 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. 11,453 ( 0.01%) self.table.growth_left -= special_is_empty(old_ctrl) as usize; . . bucket.write(value); 9,193 ( 0.01%) self.table.items += 1; . bucket 13 ( 0.00%) } . . /// Temporary removes a bucket, applying the given function to the removed . /// element and optionally put back the returned value in the same bucket. . /// . /// Returns `true` if the bucket still contains an element . /// . /// This does not check if the given bucket is actually occupied. . #[cfg_attr(feature = "inline-more", inline)] -- line 798 ---------------------------------------- -- line 815 ---------------------------------------- . false . } . } . . /// Searches for an element in the table. . #[inline] . pub fn find(&self, hash: u64, mut eq: impl FnMut(&T) -> bool) -> Option> { . let result = self.table.find_inner(hash, &mut |index| unsafe { 22 ( 0.00%) eq(self.bucket(index).as_ref()) . }); . . // Avoid `Option::map` because it bloats LLVM IR. . match result { . Some(index) => Some(unsafe { self.bucket(index) }), . None => None, . } . } . . /// Gets a reference to an element in the table. . #[inline] . pub fn get(&self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option<&T> { . // Avoid `Option::map` because it bloats LLVM IR. 12 ( 0.00%) match self.find(hash, eq) { . Some(bucket) => Some(unsafe { bucket.as_ref() }), . None => None, . } . } . . /// Gets a mutable reference to an element in the table. . #[inline] . pub fn get_mut(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option<&mut T> { -- line 845 ---------------------------------------- -- line 920 ---------------------------------------- . #[inline] . pub fn len(&self) -> usize { . self.table.items . } . . /// Returns `true` if the table contains no elements. . #[inline] . pub fn is_empty(&self) -> bool { 39,674 ( 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()), 5,852 ( 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(); 364 ( 0.00%) let allocation = self.into_allocation(); 273 ( 0.00%) RawIntoIter { 455 ( 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)> { 91 ( 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(( 62 ( 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,466 ( 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)] 2,611 ( 0.00%) unsafe fn new_uninitialized( . alloc: A, . table_layout: TableLayout, . buckets: usize, . fallibility: Fallibility, . ) -> Result { . debug_assert!(buckets.is_power_of_two()); . . // Avoid `Option::ok_or_else` because it bloats LLVM IR. -- line 1071 ---------------------------------------- -- line 1078 ---------------------------------------- . // exceed `isize::MAX`. We can skip this check on 64-bit systems since . // such allocations will never succeed anyways. . // . // This mirrors what Vec does in the standard library. . if mem::size_of::() < 8 && layout.size() > isize::MAX as usize { . return Err(fallibility.capacity_overflow()); . } . 3,816 ( 0.00%) let ptr: NonNull = match do_alloc(&alloc, layout) { . Ok(block) => block.cast(), . Err(_) => return Err(fallibility.alloc_err(layout)), . }; . . let ctrl = NonNull::new_unchecked(ptr.as_ptr().add(ctrl_offset)); 1,794 ( 0.00%) Ok(Self { . ctrl, 2,208 ( 0.00%) bucket_mask: buckets - 1, . items: 0, . growth_left: bucket_mask_to_capacity(buckets - 1), . alloc, . }) 1,940 ( 0.00%) } . . #[inline] 12,416 ( 0.01%) fn fallible_with_capacity( . alloc: A, . table_layout: TableLayout, . capacity: usize, . fallibility: Fallibility, . ) -> Result { 3,104 ( 0.00%) if capacity == 0 { . Ok(Self::new_in(alloc)) . } else { . unsafe { . let buckets = . capacity_to_buckets(capacity).ok_or_else(|| fallibility.capacity_overflow())?; . 1,259 ( 0.00%) let result = Self::new_uninitialized(alloc, table_layout, buckets, fallibility)?; . result.ctrl(0).write_bytes(EMPTY, result.num_ctrl_bytes()); . 9,312 ( 0.01%) Ok(result) . } . } 12,416 ( 0.01%) } . . /// 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] 2,143 ( 0.00%) unsafe fn prepare_insert_slot(&self, hash: u64) -> (usize, u8) { . let index = self.find_insert_slot(hash); 2,143 ( 0.00%) let old_ctrl = *self.ctrl(index); . self.set_ctrl_h2(index, hash); . (index, old_ctrl) 4,286 ( 0.00%) } . . /// Searches for an empty or deleted bucket which is suitable for inserting . /// a new element. . /// . /// There must be at least 1 empty bucket in the table. . #[inline] . fn find_insert_slot(&self, hash: u64) -> usize { . let mut probe_seq = self.probe_seq(hash); . loop { . unsafe { . let group = Group::load(self.ctrl(probe_seq.pos)); 25,313 ( 0.01%) if let Some(bit) = group.match_empty_or_deleted().lowest_set_bit() { 73,656 ( 0.04%) let result = (probe_seq.pos + bit) & self.bucket_mask; . . // In tables smaller than the group width, trailing control . // bytes outside the range of the table are filled with . // EMPTY entries. These will unfortunately trigger a . // match, but once masked may point to a full bucket that . // is already occupied. We detect this situation here and . // perform a second scan starting at the beginning of the . // table. This second scan is guaranteed to find an empty . // slot (due to the load factor) before hitting the trailing . // control bytes (containing EMPTY). 35,151 ( 0.02%) if unlikely(is_full(*self.ctrl(result))) { . debug_assert!(self.bucket_mask < Group::WIDTH); . debug_assert_ne!(probe_seq.pos, 0); . return Group::load_aligned(self.ctrl(0)) . .match_empty_or_deleted() . .lowest_set_bit_nonzero(); . } . . return result; -- line 1165 ---------------------------------------- -- line 1174 ---------------------------------------- . #[inline] . fn find_inner(&self, hash: u64, eq: &mut dyn FnMut(usize) -> bool) -> Option { . let h2_hash = h2(hash); . let mut probe_seq = self.probe_seq(hash); . . loop { . let group = unsafe { Group::load(self.ctrl(probe_seq.pos)) }; . 71,303 ( 0.04%) for bit in group.match_byte(h2_hash) { 128,221 ( 0.07%) let index = (probe_seq.pos + bit) & self.bucket_mask; . 51,503 ( 0.03%) if likely(eq(index)) { . return Some(index); . } . } . 28,426 ( 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(); 80,648 ( 0.05%) base.sub((index + 1) * size_of) . } . . #[inline] . unsafe fn data_end(&self) -> NonNull { . NonNull::new_unchecked(self.ctrl.as_ptr().cast()) . } . . /// Returns an iterator-like object for a probe sequence on the table. . /// . /// This iterator never terminates, but is guaranteed to visit each bucket . /// group exactly once. The loop using `probe_seq` must terminate upon . /// reaching a group containing an empty bucket. . #[inline] . fn probe_seq(&self, hash: u64) -> ProbeSeq { . ProbeSeq { 549,104 ( 0.31%) 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) { 52,995 ( 0.03%) self.growth_left -= special_is_empty(old_ctrl) as usize; . self.set_ctrl_h2(index, hash); 42,396 ( 0.02%) self.items += 1; . } . . #[inline] . fn is_in_same_group(&self, i: usize, new_i: usize, hash: u64) -> bool { . let probe_seq_pos = self.probe_seq(hash).pos; . let probe_index = . |pos: usize| (pos.wrapping_sub(probe_seq_pos) & self.bucket_mask) / Group::WIDTH; . 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] | . // --------------------------------------------- 68,478 ( 0.04%) let index2 = ((index.wrapping_sub(Group::WIDTH)) & self.bucket_mask) + Group::WIDTH; . 22,826 ( 0.01%) *self.ctrl(index) = ctrl; 22,829 ( 0.01%) *self.ctrl(index2) = ctrl; . } . . /// Returns a pointer to a control byte. . #[inline] . unsafe fn ctrl(&self, index: usize) -> *mut u8 { . debug_assert!(index < self.num_ctrl_bytes()); . self.ctrl.as_ptr().add(index) . } . . #[inline] . fn buckets(&self) -> usize { 12,807 ( 0.01%) self.bucket_mask + 1 . } . . #[inline] . fn num_ctrl_bytes(&self) -> usize { 1,501 ( 0.00%) self.bucket_mask + 1 + Group::WIDTH . } . . #[inline] . fn is_empty_singleton(&self) -> bool { 19,820 ( 0.01%) self.bucket_mask == 0 . } . . #[allow(clippy::mut_mut)] . #[inline] . unsafe fn prepare_resize( . &self, . table_layout: TableLayout, . capacity: usize, . fallibility: Fallibility, . ) -> Result, TryReserveError> { . debug_assert!(self.items <= capacity); . . // Allocate and initialize the new table. 4,656 ( 0.00%) let mut new_table = RawTableInner::fallible_with_capacity( . self.alloc.clone(), . table_layout, . capacity, . fallibility, . )?; 3,874 ( 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,907 ( 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,815 ( 0.00%) let new_items = match self.items.checked_add(additional) { . Some(new_items) => new_items, . None => return Err(fallibility.capacity_overflow()), . }; 3,814 ( 0.00%) let full_capacity = bucket_mask_to_capacity(self.bucket_mask); 7,733 ( 0.00%) if new_items <= full_capacity / 2 { . // Rehash in-place without re-allocating if we have plenty of spare . // capacity that is locked up due to DELETED entries. . self.rehash_in_place(hasher, layout.size, drop); . Ok(()) . } else { . // Otherwise, conservatively resize to at least the next size up . // to avoid churning deletes into frequent rehashes. . self.resize_inner( 1,907 ( 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> { 10,931 ( 0.01%) let mut new_table = self.prepare_resize(layout, capacity, fallibility)?; . . // Copy all elements to the new table. . for i in 0..self.buckets() { 13,321 ( 0.01%) if !is_full(*self.ctrl(i)) { . continue; . } . . // This may panic. . let hash = hasher(self, i); . . // We can use a simpler version of insert() here since: . // - there are no DELETED entries. -- line 1444 ---------------------------------------- -- line 1454 ---------------------------------------- . } . . // We successfully copied all elements without panicking. Now replace . // self with the new table. The old table will have its memory freed but . // the items will not be dropped (since they have been moved into the . // new table). . mem::swap(self, &mut new_table); . 1,907 ( 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( 1,704 ( 0.00%) NonNull::new_unchecked(self.ctrl.as_ptr().sub(ctrl_offset)), . layout, . ); . } . . /// Marks all table buckets as empty without dropping their contents. . #[inline] . fn clear_no_drop(&mut self) { 2 ( 0.00%) if !self.is_empty_singleton() { . unsafe { . self.ctrl(0).write_bytes(EMPTY, self.num_ctrl_bytes()); . } . } 4 ( 0.00%) self.items = 0; 2 ( 0.00%) self.growth_left = bucket_mask_to_capacity(self.bucket_mask); . } . . #[inline] . unsafe fn erase(&mut self, index: usize) { . debug_assert!(is_full(*self.ctrl(index))); 381 ( 0.00%) let index_before = index.wrapping_sub(Group::WIDTH) & self.bucket_mask; . let empty_before = Group::load(self.ctrl(index_before)).match_empty(); . let empty_after = Group::load(self.ctrl(index)).match_empty(); . . // If we are inside a continuous block of Group::WIDTH full or deleted . // cells then a probe window may have seen a full block when trying to . // insert. We therefore need to keep that block non-empty so that . // lookups will continue searching to the next probe window. . // . // Note that in this context `leading_zeros` refers to the bytes at the . // end of a group, while `trailing_zeros` refers to the bytes at the . // beginning of a group. 1,524 ( 0.00%) let ctrl = if empty_before.leading_zeros() + empty_after.trailing_zeros() >= Group::WIDTH { . DELETED . } else { 1,905 ( 0.00%) self.growth_left += 1; . EMPTY . }; . self.set_ctrl(index, ctrl); 1,524 ( 0.00%) self.items -= 1; . } . } . . impl Clone for RawTable { 32 ( 0.00%) fn clone(&self) -> Self { 4 ( 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) . } . } 36 ( 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)] 20,973 ( 0.01%) fn drop(&mut self) { 7,277 ( 0.00%) if !self.table.is_empty_singleton() { . unsafe { . self.drop_elements(); . self.free_buckets(); . } . } 23,594 ( 0.01%) } . } . #[cfg(not(feature = "nightly"))] . impl Drop for RawTable { . #[cfg_attr(feature = "inline-more", inline)] . fn drop(&mut self) { . if !self.table.is_empty_singleton() { . unsafe { . self.drop_elements(); -- line 1813 ---------------------------------------- -- line 1817 ---------------------------------------- . } . } . . impl IntoIterator for RawTable { . type Item = T; . type IntoIter = RawIntoIter; . . #[cfg_attr(feature = "inline-more", inline)] 364 ( 0.00%) fn into_iter(self) -> RawIntoIter { . unsafe { . let iter = self.iter(); . self.into_iter_from(iter) . } 455 ( 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 { 7,598 ( 0.00%) if let Some(index) = self.current_group.lowest_set_bit() { 56 ( 0.00%) self.current_group = self.current_group.remove_lowest_bit(); 131 ( 0.00%) return Some(self.data.next_n(index)); . } . 6,726 ( 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). 67 ( 0.00%) self.current_group = Group::load_aligned(self.next_ctrl).match_full(); . self.data = self.data.next_n(Group::WIDTH); 108 ( 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) { 239 ( 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)] 45 ( 0.00%) fn next(&mut self) -> Option> { 3,054 ( 0.00%) if let Some(b) = self.iter.next() { 8,107 ( 0.00%) self.items -= 1; . Some(b) . } else { . // We don't check against items == 0 here to allow the . // compiler to optimize away the item count entirely if the . // iterator length is never queried. . debug_assert_eq!(self.items, 0); . None . } 90 ( 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)] 446 ( 0.00%) fn drop(&mut self) { . unsafe { . // Drop all remaining elements . self.iter.drop_elements(); . . // Free the table 399 ( 0.00%) if let Some((ptr, layout)) = self.allocation { . self.alloc.deallocate(ptr, layout); . } . } 158 ( 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)] 9 ( 0.00%) fn next(&mut self) -> Option { 6 ( 0.00%) unsafe { Some(self.iter.next()?.read()) } 19 ( 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 ---------------------------------------- 212,506 ( 0.12%) -------------------------------------------------------------------------------- -- 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 { 79 ( 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 { 2,221 ( 0.00%) write_leb128!(self, v, usize, write_usize_leb128) . } . . #[inline] . fn emit_u128(&mut self, v: u128) -> EncodeResult { 7 ( 0.00%) write_leb128!(self, v, u128, write_u128_leb128) . } . . #[inline] . fn emit_u64(&mut self, v: u64) -> EncodeResult { 147 ( 0.00%) write_leb128!(self, v, u64, write_u64_leb128) . } . . #[inline] . fn emit_u32(&mut self, v: u32) -> EncodeResult { 1,025 ( 0.00%) 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 { 15 ( 0.00%) self.emit_u8(if v { 1 } else { 0 }) . } . . #[inline] . fn emit_f64(&mut self, v: f64) -> EncodeResult { . let as_u64: u64 = v.to_bits(); . self.emit_u64(as_u64) . } . -- line 147 ---------------------------------------- -- line 549 ---------------------------------------- . #[inline] . pub fn advance(&mut self, bytes: usize) { . self.position += bytes; . } . . #[inline] . pub fn read_raw_bytes(&mut self, bytes: usize) -> &'a [u8] { . let start = self.position; 19 ( 0.00%) self.position += bytes; 19 ( 0.00%) &self.data[start..self.position] . } . } . . macro_rules! read_leb128 { . ($dec:expr, $fun:ident) => {{ leb128::$fun($dec.data, &mut $dec.position) }}; . } . . impl<'a> serialize::Decoder for Decoder<'a> { . #[inline] . fn read_unit(&mut self) -> () { . () . } . . #[inline] . fn read_u128(&mut self) -> u128 { 526 ( 0.00%) read_leb128!(self, read_u128_leb128) . } . . #[inline] . fn read_u64(&mut self) -> u64 { 213 ( 0.00%) read_leb128!(self, read_u64_leb128) . } . . #[inline] 2,480 ( 0.00%) fn read_u32(&mut self) -> u32 { 9,265 ( 0.01%) read_leb128!(self, read_u32_leb128) 4,960 ( 0.00%) } . . #[inline] . fn read_u16(&mut self) -> u16 { 561,386 ( 0.32%) let bytes = [self.data[self.position], self.data[self.position + 1]]; 80,198 ( 0.05%) let value = u16::from_le_bytes(bytes); 160,396 ( 0.09%) self.position += 2; . value . } . . #[inline] . fn read_u8(&mut self) -> u8 { 1,702,582 ( 0.97%) let value = self.data[self.position]; 311,706 ( 0.18%) self.position += 1; . value . } . . #[inline] 14,618 ( 0.01%) fn read_usize(&mut self) -> usize { 14,618 ( 0.01%) read_leb128!(self, read_usize_leb128) 29,236 ( 0.02%) } . . #[inline] . fn read_i128(&mut self) -> i128 { . read_leb128!(self, read_i128_leb128) . } . . #[inline] . fn read_i64(&mut self) -> i64 { -- line 613 ---------------------------------------- -- line 637 ---------------------------------------- . #[inline] . fn read_isize(&mut self) -> isize { . read_leb128!(self, read_isize_leb128) . } . . #[inline] . fn read_bool(&mut self) -> bool { . let value = self.read_u8(); 571 ( 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> { 2,107 ( 0.00%) let len = self.read_usize(); 10,904 ( 0.01%) let sentinel = self.data[self.position + len]; 2,726 ( 0.00%) assert!(sentinel == STR_SENTINEL); . let s = unsafe { . std::str::from_utf8_unchecked(&self.data[self.position..self.position + len]) . }; 6,815 ( 0.00%) self.position += len + 1; 2,232 ( 0.00%) Cow::Borrowed(s) . } . . #[inline] . fn read_raw_bytes_into(&mut self, s: &mut [u8]) { 3 ( 0.00%) let start = self.position; 24 ( 0.00%) self.position += s.len(); 3 ( 0.00%) s.copy_from_slice(&self.data[start..self.position]); . } . } . . // Specializations for contiguous byte sequences follow. The default implementations for slices . // encode and decode each element individually. This isn't necessary for `u8` slices when using . // opaque encoders and decoders, because each `u8` is unchanged by encoding and decoding. . // Therefore, we can use more efficient implementations that process the entire sequence at once. . -- line 690 ---------------------------------------- 105,950 ( 0.06%) -------------------------------------------------------------------------------- -- 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 { 391,834 ( 0.22%) ((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 { 373,524 ( 0.21%) ((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 { 183,100 ( 0.10%) (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 { 234,368 ( 0.13%) (y ^ (x | !z)) . .wrapping_add(w) . .wrapping_add(m) . .wrapping_add(c) . .rotate_left(s) . .wrapping_add(x) . } . . #[inline] 32,958 ( 0.02%) pub fn compress(state: &mut [u32; 4], input: &[u8; 64]) { 7,324 ( 0.00%) let mut a = state[0]; 3,662 ( 0.00%) let mut b = state[1]; 3,662 ( 0.00%) let mut c = state[2]; 3,662 ( 0.00%) let mut d = state[3]; . . let mut data = [0u32; 16]; . for (o, chunk) in data.iter_mut().zip(input.chunks_exact(4)) { 91,550 ( 0.05%) *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); . 7,324 ( 0.00%) state[0] = state[0].wrapping_add(a); 3,662 ( 0.00%) state[1] = state[1].wrapping_add(b); 3,662 ( 0.00%) state[2] = state[2].wrapping_add(c); 3,662 ( 0.00%) state[3] = state[3].wrapping_add(d); 29,296 ( 0.02%) } -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/iter/range.rs -------------------------------------------------------------------------------- Ir -- line 198 ---------------------------------------- . } . . #[inline] . #[allow(arithmetic_overflow)] . #[rustc_inherit_overflow_checks] . fn forward(start: Self, n: usize) -> Self { . // In debug builds, trigger a panic on overflow. . // This should optimize completely out in release builds. 2,912 ( 0.00%) if Self::forward_checked(start, n).is_none() { . let _ = Self::MAX + 1; . } . // Do wrapping math to allow e.g. `Step::forward(-128i8, 255)`. . start.wrapping_add(n as Self) . } . . #[inline] . #[allow(arithmetic_overflow)] -- line 214 ---------------------------------------- -- line 613 ---------------------------------------- . . if taken < n { Err(taken) } else { Ok(()) } . } . } . . impl RangeIteratorImpl for ops::Range { . #[inline] . fn spec_next(&mut self) -> Option { 457,559 ( 0.26%) 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 { 125 ( 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) { 249 ( 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 ---------------------------------------- 68,425 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/lint.rs -------------------------------------------------------------------------------- Ir -- line 70 ---------------------------------------- . // -A,-W,-D flags, a `Symbol` for the flag itself and `Level` for which . // flag. . pub specs: FxHashMap, . . pub parent: LintStackIndex, . } . . impl LintLevelSets { 4 ( 0.00%) pub fn new() -> Self { 8 ( 0.00%) LintLevelSets { list: IndexVec::new(), lint_cap: Level::Forbid } 4 ( 0.00%) } . 18,525 ( 0.01%) pub fn get_lint_level( . &self, . lint: &'static Lint, . idx: LintStackIndex, . aux: Option<&FxHashMap>, . sess: &Session, . ) -> LevelAndSource { 9,975 ( 0.01%) let (level, mut src) = self.get_lint_id_level(LintId::of(lint), idx, aux); . . // If `level` is none then we actually assume the default level for this . // lint. 8,532 ( 0.00%) let mut level = level.unwrap_or_else(|| lint.default_level(sess.edition())); . . // If we're about to issue a warning, check at the last minute for any . // directives against the warnings "lint". If, for example, there's an . // `allow(warnings)` in scope then we want to respect that instead. . // . // We exempt `FORBIDDEN_LINT_GROUPS` from this because it specifically . // triggers in cases (like #80988) where you have `forbid(warnings)`, . // and so if we turned that into an error, it'd defeat the purpose of the . // future compatibility warning. 18,453 ( 0.01%) if level == Level::Warn && LintId::of(lint) != LintId::of(FORBIDDEN_LINT_GROUPS) { . let (warnings_level, warnings_src) = 7,095 ( 0.00%) self.get_lint_id_level(LintId::of(builtin::WARNINGS), idx, aux); . if let Some(configured_warning_level) = warnings_level { . if configured_warning_level != Level::Warn { . level = configured_warning_level; . src = warnings_src; . } . } . } . . // Ensure that we never exceed the `--cap-lints` argument . // unless the source is a --force-warn 15,675 ( 0.01%) level = if let LintLevelSource::CommandLine(_, Level::ForceWarn) = src { . level . } else { . cmp::min(level, self.lint_cap) . }; . 4,275 ( 0.00%) if let Some(driver_level) = sess.driver_lint_caps.get(&LintId::of(lint)) { . // Ensure that we never exceed driver level. . level = cmp::min(*driver_level, level); . } . 9,975 ( 0.01%) (level, src) 11,400 ( 0.01%) } . . pub fn get_lint_id_level( . &self, . id: LintId, . mut idx: LintStackIndex, . aux: Option<&FxHashMap>, . ) -> (Option, LintLevelSource) { 7,113 ( 0.00%) if let Some(specs) = aux { 9,896 ( 0.01%) if let Some(&(level, src)) = specs.get(&id) { . return (Some(level), src); . } . } . loop { 11,444 ( 0.01%) let LintSet { ref specs, parent } = self.list[idx]; 11,444 ( 0.01%) if let Some(&(level, src)) = specs.get(&id) { . return (Some(level), src); . } 2,858 ( 0.00%) if idx == COMMAND_LINE { . return (None, LintLevelSource::Default); . } . idx = parent; . } . } . } . . #[derive(Debug)] -- line 154 ---------------------------------------- -- line 160 ---------------------------------------- . impl LintLevelMap { . /// If the `id` was previously registered with `register_id` when building . /// this `LintLevelMap` this returns the corresponding lint level and source . /// of the lint level for the lint provided. . /// . /// If the `id` was not previously registered, returns `None`. If `None` is . /// returned then the parent of `id` should be acquired and this function . /// should be called again. 48 ( 0.00%) pub fn level_and_source( . &self, . lint: &'static Lint, . id: HirId, . session: &Session, . ) -> Option { 8 ( 0.00%) self.id_to_set.get(&id).map(|idx| self.sets.get_lint_level(lint, *idx, None, session)) 56 ( 0.00%) } . } . . impl<'a> HashStable> for LintLevelMap { . #[inline] . fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) { . let LintLevelMap { ref sets, ref id_to_set } = *self; . . id_to_set.hash_stable(hcx, hasher); -- line 183 ---------------------------------------- -- line 207 ---------------------------------------- . lint: &'static Lint, . level: Level, . src: LintLevelSource, . span: Option, . decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>) + 'd, . ) { . // Avoid codegen bloat from monomorphization by immediately doing dyn dispatch of `decorate` to . // the "real" work. 32 ( 0.00%) fn struct_lint_level_impl<'s, 'd>( . sess: &'s Session, . lint: &'static Lint, . level: Level, . src: LintLevelSource, . span: Option, . decorate: Box FnOnce(LintDiagnosticBuilder<'b>) + 'd>, . ) { . // Check for future incompatibility lints and issue a stronger warning. 6 ( 0.00%) let lint_id = LintId::of(lint); 20 ( 0.00%) let future_incompatible = lint.future_incompatible; . . let has_future_breakage = future_incompatible.map_or( . // Default allow lints trigger too often for testing. 20 ( 0.00%) sess.opts.debugging_opts.future_incompat_test && lint.default_level != Level::Allow, . |incompat| { . matches!(incompat.reason, FutureIncompatibilityReason::FutureReleaseErrorReportNow) . }, . ); . 10 ( 0.00%) let mut err = match (level, span) { 14 ( 0.00%) (Level::Allow, span) => { 4 ( 0.00%) if has_future_breakage { . if let Some(span) = span { . sess.struct_span_allow(span, "") . } else { . sess.struct_allow("") . } . } else { . return; . } 4 ( 0.00%) } . (Level::Warn, Some(span)) => sess.struct_span_warn(span, ""), . (Level::Warn, None) => sess.struct_warn(""), . (Level::ForceWarn, Some(span)) => sess.struct_span_force_warn(span, ""), . (Level::ForceWarn, None) => sess.struct_force_warn(""), . (Level::Deny | Level::Forbid, Some(span)) => { . let mut builder = sess.diagnostic().struct_err_lint(""); . builder.set_span(span); . builder -- line 254 ---------------------------------------- -- line 377 ---------------------------------------- . let citation = . format!("for more information, see {}", future_incompatible.reference); . err.note(&citation); . } . } . . // Finally, run `decorate`. This function is also responsible for emitting the diagnostic. . decorate(LintDiagnosticBuilder::new(err)); 16 ( 0.00%) } 34 ( 0.00%) struct_lint_level_impl(sess, lint, level, src, span, Box::new(decorate)) . } . . /// Returns whether `span` originates in a foreign crate's external macro. . /// . /// This is used to test whether a lint should not even begin to figure out whether it should . /// be reported on the current node. . pub fn in_external_macro(sess: &Session, span: Span) -> bool { . let expn_data = span.ctxt().outer_expn_data(); -- line 394 ---------------------------------------- 42,682 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/std/src/alloc.rs -------------------------------------------------------------------------------- Ir -- line 342 ---------------------------------------- . . // for symbol names src/librustc_ast/expand/allocator.rs . // for signatures src/librustc_allocator/lib.rs . . // linkage directives are provided as part of the current compiler allocator . // ABI . . #[rustc_std_internal_symbol] 191,502 ( 0.11%) pub unsafe extern "C" fn __rdl_alloc(size: usize, align: usize) -> *mut u8 { . // SAFETY: see the guarantees expected by `Layout::from_size_align` and . // `GlobalAlloc::alloc`. . unsafe { . let layout = Layout::from_size_align_unchecked(size, align); . System.alloc(layout) . } 2 ( 0.00%) } . . #[rustc_std_internal_symbol] . pub unsafe extern "C" fn __rdl_dealloc(ptr: *mut u8, size: usize, align: usize) { . // SAFETY: see the guarantees expected by `Layout::from_size_align` and . // `GlobalAlloc::dealloc`. . unsafe { System.dealloc(ptr, Layout::from_size_align_unchecked(size, align)) } . } . . #[rustc_std_internal_symbol] 49,024 ( 0.03%) pub unsafe extern "C" fn __rdl_realloc( . ptr: *mut u8, . old_size: usize, . align: usize, . new_size: usize, . ) -> *mut u8 { . // SAFETY: see the guarantees expected by `Layout::from_size_align` and . // `GlobalAlloc::realloc`. . unsafe { . let old_layout = Layout::from_size_align_unchecked(old_size, align); . System.realloc(ptr, old_layout, new_size) . } . } . . #[rustc_std_internal_symbol] 96 ( 0.00%) pub unsafe extern "C" fn __rdl_alloc_zeroed(size: usize, align: usize) -> *mut u8 { . // SAFETY: see the guarantees expected by `Layout::from_size_align` and . // `GlobalAlloc::alloc_zeroed`. . unsafe { . let layout = Layout::from_size_align_unchecked(size, align); . System.alloc_zeroed(layout) . } . } . } -- line 390 ---------------------------------------- -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/char/methods.rs -------------------------------------------------------------------------------- Ir -- line 345 ---------------------------------------- . if radix > 10 { . if digit < 10 { . return Some(digit); . } . // Force the 6th bit to be set to ensure ascii is lower case. . digit = (self as u32 | 0b10_0000).wrapping_sub('a' as u32).saturating_add(10); . } . // FIXME: once then_some is const fn, use it here 368 ( 0.00%) if digit < radix { Some(digit) } else { None } . } . . /// Returns an iterator that yields the hexadecimal Unicode escape of a . /// character as `char`s. . /// . /// This will escape characters with the Rust syntax of the form . /// `\u{NNNNNN}` where `NNNNNN` is a hexadecimal representation. . /// -- line 361 ---------------------------------------- -- line 708 ---------------------------------------- . /// // love is many things, but it is not alphabetic . /// assert!(!c.is_alphabetic()); . /// ``` . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . pub fn is_alphabetic(self) -> bool { . match self { 35 ( 0.00%) 'a'..='z' | 'A'..='Z' => true, 2 ( 0.00%) c => c > '\x7f' && unicode::Alphabetic(c), . } . } . . /// Returns `true` if this `char` has the `Lowercase` property. . /// . /// `Lowercase` is described in Chapter 4 (Character Properties) of the [Unicode Standard] and . /// specified in the [Unicode Character Database][ucd] [`DerivedCoreProperties.txt`]. . /// -- line 725 ---------------------------------------- -- line 774 ---------------------------------------- . /// assert!(!'中'.is_uppercase()); . /// assert!(!' '.is_uppercase()); . /// ``` . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . pub fn is_uppercase(self) -> bool { . match self { 42 ( 0.00%) 'A'..='Z' => true, 28 ( 0.00%) c => c > '\x7f' && unicode::Uppercase(c), . } . } . . /// Returns `true` if this `char` has the `White_Space` property. . /// . /// `White_Space` is specified in the [Unicode Character Database][ucd] [`PropList.txt`]. . /// . /// [ucd]: https://www.unicode.org/reports/tr44/ -- line 791 ---------------------------------------- -- line 802 ---------------------------------------- . /// assert!('\u{A0}'.is_whitespace()); . /// . /// assert!(!'越'.is_whitespace()); . /// ``` . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . pub fn is_whitespace(self) -> bool { 25 ( 0.00%) match self { . ' ' | '\x09'..='\x0d' => true, 306 ( 0.00%) c => c > '\x7f' && unicode::White_Space(c), . } . } . . /// Returns `true` if this `char` satisfies either [`is_alphabetic()`] or [`is_numeric()`]. . /// . /// [`is_alphabetic()`]: #method.is_alphabetic . /// [`is_numeric()`]: #method.is_numeric . /// -- line 820 ---------------------------------------- -- line 904 ---------------------------------------- . /// assert!(!'و'.is_numeric()); . /// assert!(!'藏'.is_numeric()); . /// ``` . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . pub fn is_numeric(self) -> bool { . match self { 3 ( 0.00%) '0'..='9' => true, . c => c > '\x7f' && unicode::N(c), . } . } . . /// Returns an iterator that yields the lowercase mapping of this `char` as one or more . /// `char`s. . /// . /// If this `char` does not have a lowercase mapping, the iterator yields the same `char`. -- line 920 ---------------------------------------- -- line 1084 ---------------------------------------- . /// assert!(ascii.is_ascii()); . /// assert!(!non_ascii.is_ascii()); . /// ``` . #[must_use] . #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")] . #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.32.0")] . #[inline] . pub const fn is_ascii(&self) -> bool { 65,083 ( 0.04%) *self as u32 <= 0x7F . } . . /// Makes a copy of the value in its ASCII upper case equivalent. . /// . /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z', . /// but non-ASCII letters are unchanged. . /// . /// To uppercase the value in-place, use [`make_ascii_uppercase()`]. -- line 1100 ---------------------------------------- -- line 1622 ---------------------------------------- . escape_grapheme_extended: true, . escape_single_quote: true, . escape_double_quote: true, . }; . } . . #[inline] . const fn len_utf8(code: u32) -> usize { 99,072 ( 0.06%) if code < MAX_ONE_B { . 1 99,070 ( 0.06%) } else if code < MAX_TWO_B { . 2 . } else if code < MAX_THREE_B { . 3 . } else { . 4 . } . } . -- line 1640 ---------------------------------------- 49,535 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/raw_vec.rs -------------------------------------------------------------------------------- Ir -- line 124 ---------------------------------------- . Self { ptr: Unique::dangling(), cap: 0, alloc } . } . . /// Like `with_capacity`, but parameterized over the choice of . /// allocator for the returned `RawVec`. . #[cfg(not(no_global_oom_handling))] . #[inline] . pub fn with_capacity_in(capacity: usize, alloc: A) -> Self { 38 ( 0.00%) Self::allocate_in(capacity, AllocInit::Uninitialized, alloc) . } . . /// Like `with_capacity_zeroed`, but parameterized over the choice . /// of allocator for the returned `RawVec`. . #[cfg(not(no_global_oom_handling))] . #[inline] . pub fn with_capacity_zeroed_in(capacity: usize, alloc: A) -> Self { . Self::allocate_in(capacity, AllocInit::Zeroed, alloc) -- line 140 ---------------------------------------- -- line 147 ---------------------------------------- . /// . /// # Safety . /// . /// * `len` must be greater than or equal to the most recently requested capacity, and . /// * `len` must be less than or equal to `self.capacity()`. . /// . /// Note, that the requested capacity and `self.capacity()` could differ, as . /// an allocator could overallocate and return a greater memory block than requested. 9 ( 0.00%) pub unsafe fn into_box(self, len: usize) -> Box<[MaybeUninit], A> { . // Sanity-check one half of the safety requirement (we cannot check the other half). . debug_assert!( . len <= self.capacity(), . "`len` must be smaller than or equal to `self.capacity()`" . ); . . let me = ManuallyDrop::new(self); . unsafe { . let slice = slice::from_raw_parts_mut(me.ptr() as *mut MaybeUninit, len); . Box::from_raw_in(slice, ptr::read(&me.alloc)) . } 9 ( 0.00%) } . . #[cfg(not(no_global_oom_handling))] 76 ( 0.00%) fn allocate_in(capacity: usize, init: AllocInit, alloc: A) -> Self { . if mem::size_of::() == 0 { . Self::new_in(alloc) . } else { . // We avoid `unwrap_or_else` here because it bloats the amount of . // LLVM IR generated. . let layout = match Layout::array::(capacity) { . Ok(layout) => layout, . Err(_) => capacity_overflow(), . }; . match alloc_guard(layout.size()) { . Ok(_) => {} . Err(_) => capacity_overflow(), . } 38 ( 0.00%) let result = match init { . AllocInit::Uninitialized => alloc.allocate(layout), . AllocInit::Zeroed => alloc.allocate_zeroed(layout), . }; . let ptr = match result { . Ok(ptr) => ptr, . Err(_) => handle_alloc_error(layout), . }; . -- line 192 ---------------------------------------- -- line 194 ---------------------------------------- . // matches the size requested. If that ever changes, the capacity . // here should change to `ptr.len() / mem::size_of::()`. . Self { . ptr: unsafe { Unique::new_unchecked(ptr.cast().as_ptr()) }, . cap: capacity, . alloc, . } . } 95 ( 0.00%) } . . /// Reconstitutes a `RawVec` from a pointer, capacity, and allocator. . /// . /// # Safety . /// . /// The `ptr` must be allocated (via the given allocator `alloc`), and with the given . /// `capacity`. . /// The `capacity` cannot exceed `isize::MAX` for sized types. (only a concern on 32-bit -- line 210 ---------------------------------------- -- line 233 ---------------------------------------- . } . . /// Returns a shared reference to the allocator backing this `RawVec`. . pub fn allocator(&self) -> &A { . &self.alloc . } . . fn current_memory(&self) -> Option<(NonNull, Layout)> { 341,738 ( 0.19%) if mem::size_of::() == 0 || self.cap == 0 { 29,972 ( 0.02%) None . } else { . // We have an allocated chunk of memory, so we can bypass runtime . // checks to get our current layout. . unsafe { . let align = mem::align_of::(); 99,276 ( 0.06%) let size = mem::size_of::() * self.cap; . let layout = Layout::from_size_align_unchecked(size, align); 24,460 ( 0.01%) Some((self.ptr.cast().into(), layout)) . } . } . } . . /// Ensures that the buffer contains at least enough space to hold `len + . /// additional` elements. If it doesn't already have enough capacity, will . /// reallocate enough space plus comfortable slack space to get amortized . /// *O*(1) behavior. Will limit this behavior if it would needlessly cause -- line 258 ---------------------------------------- -- line 274 ---------------------------------------- . #[cfg(not(no_global_oom_handling))] . #[inline] . pub fn reserve(&mut self, len: usize, additional: usize) { . // Callers expect this function to be very cheap when there is already sufficient capacity. . // Therefore, we move all the resizing and error-handling logic from grow_amortized and . // handle_reserve behind a call, while making sure that this function is likely to be . // inlined as just a comparison and a call if the comparison fails. . #[cold] 35,247 ( 0.02%) fn do_reserve_and_handle( . slf: &mut RawVec, . len: usize, . additional: usize, . ) { 4 ( 0.00%) handle_reserve(slf.grow_amortized(len, additional)); 46,979 ( 0.03%) } . 29,238 ( 0.02%) if self.needs_to_grow(len, additional) { 46,908 ( 0.03%) do_reserve_and_handle(self, len, additional); . } . } . . /// A specialized version of `reserve()` used only by the hot and . /// oft-instantiated `Vec::push()`, which does its own capacity check. . #[cfg(not(no_global_oom_handling))] . #[inline(never)] 97,305 ( 0.06%) pub fn reserve_for_push(&mut self, len: usize) { . handle_reserve(self.grow_amortized(len, 1)); 121,603 ( 0.07%) } . . /// The same as `reserve`, but returns on errors instead of panicking or aborting. . pub fn try_reserve(&mut self, len: usize, additional: usize) -> Result<(), TryReserveError> { . if self.needs_to_grow(len, additional) { . self.grow_amortized(len, additional) . } else { . Ok(()) . } -- line 309 ---------------------------------------- -- line 322 ---------------------------------------- . /// # Panics . /// . /// Panics if the new capacity exceeds `isize::MAX` bytes. . /// . /// # Aborts . /// . /// Aborts on OOM. . #[cfg(not(no_global_oom_handling))] 100 ( 0.00%) pub fn reserve_exact(&mut self, len: usize, additional: usize) { . handle_reserve(self.try_reserve_exact(len, additional)); 100 ( 0.00%) } . . /// The same as `reserve_exact`, but returns on errors instead of panicking or aborting. . pub fn try_reserve_exact( . &mut self, . len: usize, . additional: usize, . ) -> Result<(), TryReserveError> { 238 ( 0.00%) if self.needs_to_grow(len, additional) { self.grow_exact(len, additional) } else { Ok(()) } . } . . /// Shrinks the buffer down to the specified capacity. If the given amount . /// is 0, actually completely deallocates. . /// . /// # Panics . /// . /// Panics if the given amount is *larger* than the current capacity. . /// . /// # Aborts . /// . /// Aborts on OOM. . #[cfg(not(no_global_oom_handling))] 5 ( 0.00%) pub fn shrink_to_fit(&mut self, cap: usize) { . handle_reserve(self.shrink(cap)); 6 ( 0.00%) } . } . . impl RawVec { . /// Returns if the buffer needs to grow to fulfill the needed extra capacity. . /// Mainly used to make inlining reserve-calls possible without inlining `grow`. . fn needs_to_grow(&self, len: usize, additional: usize) -> bool { 53,101 ( 0.03%) additional > self.capacity().wrapping_sub(len) . } . . fn set_ptr_and_cap(&mut self, ptr: NonNull<[u8]>, cap: usize) { . // Allocators currently return a `NonNull<[u8]>` whose length matches . // the size requested. If that ever changes, the capacity here should . // change to `ptr.len() / mem::size_of::()`. 36,105 ( 0.02%) self.ptr = unsafe { Unique::new_unchecked(ptr.cast().as_ptr()) }; 36,106 ( 0.02%) self.cap = cap; . } . . // This method is usually instantiated many times. So we want it to be as . // small as possible, to improve compile times. But we also want as much of . // its contents to be statically computable as possible, to make the . // generated code run faster. Therefore, this method is carefully written . // so that all of the code that depends on `T` is within it, while as much . // of the code that doesn't depend on `T` as possible is in functions that . // are non-generic over `T`. 6 ( 0.00%) fn grow_amortized(&mut self, len: usize, additional: usize) -> Result<(), TryReserveError> { . // This is ensured by the calling contexts. . debug_assert!(additional > 0); . . if mem::size_of::() == 0 { . // Since we return a capacity of `usize::MAX` when `elem_size` is . // 0, getting to here necessarily means the `RawVec` is overfull. . return Err(CapacityOverflow.into()); . } . . // Nothing we can really do about these checks, sadly. . let required_cap = len.checked_add(additional).ok_or(CapacityOverflow)?; . . // This guarantees exponential growth. The doubling cannot overflow . // because `cap <= isize::MAX` and the type of `cap` is `usize`. 144,260 ( 0.08%) let cap = cmp::max(self.cap * 2, required_cap); . let cap = cmp::max(Self::MIN_NON_ZERO_CAP, cap); . . let new_layout = Layout::array::(cap); . . // `finish_grow` is non-generic over `T`. 114,141 ( 0.06%) let ptr = finish_grow(new_layout, self.current_memory(), &mut self.alloc)?; . self.set_ptr_and_cap(ptr, cap); . Ok(()) 5 ( 0.00%) } . . // The constraints on this method are much the same as those on . // `grow_amortized`, but this method is usually instantiated less often so . // it's less critical. . fn grow_exact(&mut self, len: usize, additional: usize) -> Result<(), TryReserveError> { . if mem::size_of::() == 0 { . // Since we return a capacity of `usize::MAX` when the type size is . // 0, getting to here necessarily means the `RawVec` is overfull. . return Err(CapacityOverflow.into()); . } . . let cap = len.checked_add(additional).ok_or(CapacityOverflow)?; . let new_layout = Layout::array::(cap); . . // `finish_grow` is non-generic over `T`. 109 ( 0.00%) let ptr = finish_grow(new_layout, self.current_memory(), &mut self.alloc)?; . self.set_ptr_and_cap(ptr, cap); . Ok(()) . } . . fn shrink(&mut self, cap: usize) -> Result<(), TryReserveError> { 3 ( 0.00%) assert!(cap <= self.capacity(), "Tried to shrink to a larger capacity"); . . let (ptr, layout) = if let Some(mem) = self.current_memory() { mem } else { return Ok(()) }; 3 ( 0.00%) let new_size = cap * mem::size_of::(); . . let ptr = unsafe { . let new_layout = Layout::from_size_align_unchecked(new_size, layout.align()); . self.alloc . .shrink(ptr, layout, new_layout) . .map_err(|_| AllocError { layout: new_layout, non_exhaustive: () })? . }; . self.set_ptr_and_cap(ptr, cap); -- line 438 ---------------------------------------- -- line 440 ---------------------------------------- . } . } . . // This function is outside `RawVec` to minimize compile times. See the comment . // above `RawVec::grow_amortized` for details. (The `A` parameter isn't . // significant, because the number of different `A` types seen in practice is . // much smaller than the number of `T` types.) . #[inline(never)] 180,500 ( 0.10%) fn finish_grow( . new_layout: Result, . current_memory: Option<(NonNull, Layout)>, . alloc: &mut A, . ) -> Result, TryReserveError> . where . A: Allocator, . { . // Check for the error here to minimize the size of `RawVec::grow_*`. . let new_layout = new_layout.map_err(|_| CapacityOverflow)?; . . alloc_guard(new_layout.size())?; . 114,402 ( 0.07%) let memory = if let Some((ptr, old_layout)) = current_memory { . debug_assert_eq!(old_layout.align(), new_layout.align()); . unsafe { . // The allocator checks for alignment equality . intrinsics::assume(old_layout.align() == new_layout.align()); . alloc.grow(ptr, old_layout, new_layout) . } . } else { . alloc.allocate(new_layout) . }; . . memory.map_err(|_| AllocError { layout: new_layout, non_exhaustive: () }.into()) 144,400 ( 0.08%) } . . unsafe impl<#[may_dangle] T, A: Allocator> Drop for RawVec { . /// Frees the memory owned by the `RawVec` *without* trying to drop its contents. 2 ( 0.00%) fn drop(&mut self) { 143,898 ( 0.08%) if let Some((ptr, layout)) = self.current_memory() { . unsafe { self.alloc.deallocate(ptr, layout) } . } 2 ( 0.00%) } . } . . // Central function for reserve error handling. . #[cfg(not(no_global_oom_handling))] . #[inline] . fn handle_reserve(result: Result<(), TryReserveError>) { . match result.map_err(|e| e.kind()) { . Err(CapacityOverflow) => capacity_overflow(), -- line 489 ---------------------------------------- 532,810 ( 0.30%) -------------------------------------------------------------------------------- -- 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 261,605 ( 0.15%) ('a' <= self && self <= 'z') . || ('A' <= self && self <= 'Z') 73,530 ( 0.04%) || (self > '\x7f' && derived_property::XID_Start(self)) . } . . #[inline] . fn is_xid_continue(self) -> bool { . // Fast-path for ascii idents 803,404 ( 0.46%) ('a' <= self && self <= 'z') . || ('A' <= self && self <= 'Z') . || ('0' <= self && self <= '9') . || self == '_' 31,112 ( 0.02%) || (self > '\x7f' && derived_property::XID_Continue(self)) . } . } 144,294 ( 0.08%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/expr.rs -------------------------------------------------------------------------------- Ir -- line 122 ---------------------------------------- . } . _ => Err(err), . }, . } . } . . /// Parses a sequence of expressions delimited by parentheses. . fn parse_paren_expr_seq(&mut self) -> PResult<'a, Vec>> { 12 ( 0.00%) self.parse_paren_comma_seq(|p| p.parse_expr_catch_underscore()).map(|(r, _)| r) . } . . /// Parses an expression, subject to the given restrictions. . #[inline] . pub(super) fn parse_expr_res( . &mut self, . r: Restrictions, . already_parsed_attrs: Option, -- line 138 ---------------------------------------- -- line 148 ---------------------------------------- . fn parse_assoc_expr( . &mut self, . already_parsed_attrs: Option, . ) -> PResult<'a, P> { . self.parse_assoc_expr_with(0, already_parsed_attrs.into()) . } . . /// Parses an associative expression with operators of at least `min_prec` precedence. 9 ( 0.00%) pub(super) fn parse_assoc_expr_with( . &mut self, . min_prec: usize, . lhs: LhsExpr, . ) -> PResult<'a, P> { 6 ( 0.00%) let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs { 4 ( 0.00%) expr . } else { . let attrs = match lhs { . LhsExpr::AttributesParsed(attrs) => Some(attrs), . _ => None, . }; . if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind) { . return self.parse_prefix_range_expr(attrs); . } else { . self.parse_prefix_expr(attrs)? . } . }; 2 ( 0.00%) let last_type_ascription_set = self.last_type_ascription.is_some(); . . if !self.should_continue_as_assoc_expr(&lhs) { . self.last_type_ascription = None; . return Ok(lhs); . } . . self.expected_tokens.push(TokenType::Operator); . while let Some(op) = self.check_assoc_op() { -- line 182 ---------------------------------------- -- line 341 ---------------------------------------- . self.span_bug(span, "AssocOp should have been handled by special case") . } . }; . . if let Fixity::None = fixity { . break; . } . } 1 ( 0.00%) if last_type_ascription_set { . self.last_type_ascription = None; . } 2 ( 0.00%) Ok(lhs) 17 ( 0.00%) } . . fn should_continue_as_assoc_expr(&mut self, lhs: &Expr) -> bool { 7 ( 0.00%) match (self.expr_is_complete(lhs), AssocOp::from_token(&self.token)) { . // Semi-statement forms are odd: . // See https://github.com/rust-lang/rust/issues/29071 . (true, None) => false, . (false, _) => true, // Continue parsing the expression. . // An exhaustive check is done in the following block, but these are checked first . // because they *are* ambiguous but also reasonable looking incorrect syntax, so we . // want to keep their span info to improve diagnostics in these cases in a later stage. . (true, Some(AssocOp::Multiply)) | // `{ 42 } *foo = bar;` or `{ 42 } * 3` -- line 364 ---------------------------------------- -- line 401 ---------------------------------------- . err.emit(); . } . . /// Possibly translate the current token to an associative operator. . /// The method does not advance the current token. . /// . /// Also performs recovery for `and` / `or` which are mistaken for `&&` and `||` respectively. . fn check_assoc_op(&self) -> Option> { 11 ( 0.00%) let (op, span) = match (AssocOp::from_token(&self.token), self.token.ident()) { . // When parsing const expressions, stop parsing when encountering `>`. . ( . Some( . AssocOp::ShiftRight . | AssocOp::Greater . | AssocOp::GreaterEqual . | AssocOp::AssignOp(token::BinOpToken::Shr), . ), -- line 417 ---------------------------------------- -- line 443 ---------------------------------------- . Applicability::MachineApplicable, . ) . .note("unlike in e.g., python and PHP, `&&` and `||` are used for logical operators") . .emit(); . } . . /// Checks if this expression is a successfully parsed statement. . fn expr_is_complete(&self, e: &Expr) -> bool { 3 ( 0.00%) self.restrictions.contains(Restrictions::STMT_EXPR) 7 ( 0.00%) && !classify::expr_requires_semi_to_be_stmt(e) . } . . /// Parses `x..y`, `x..=y`, and `x..`/`x..=`. . /// The other two variants are handled in `parse_prefix_range_expr` below. . fn parse_range_expr( . &mut self, . prec: usize, . lhs: P, -- line 460 ---------------------------------------- -- line 902 ---------------------------------------- . &mut self, . e0: P, . lo: Span, . mut attrs: Vec, . ) -> PResult<'a, P> { . // Stitch the list of outer attributes onto the return value. . // A little bit ugly, but the best way given the current code . // structure 7 ( 0.00%) self.parse_dot_or_call_expr_with_(e0, lo).map(|expr| { 7 ( 0.00%) expr.map(|mut expr| { 1 ( 0.00%) attrs.extend::>(expr.attrs.into()); 2 ( 0.00%) expr.attrs = attrs.into(); 14 ( 0.00%) expr . }) . }) . } . 31 ( 0.00%) fn parse_dot_or_call_expr_with_(&mut self, mut e: P, lo: Span) -> PResult<'a, P> { . loop { . if self.eat(&token::Question) { . // `expr?` . e = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Try(e), AttrVec::new()); . continue; . } . if self.eat(&token::Dot) { . // expr.f 8 ( 0.00%) e = self.parse_dot_suffix_expr(lo, e)?; . continue; . } 4 ( 0.00%) if self.expr_is_complete(&e) { . return Ok(e); . } 11 ( 0.00%) e = match self.token.kind { 3 ( 0.00%) token::OpenDelim(token::Paren) => self.parse_fn_call_expr(lo, e), . token::OpenDelim(token::Bracket) => self.parse_index_expr(lo, e)?, 1 ( 0.00%) _ => return Ok(e), . } . } 9 ( 0.00%) } . . fn look_ahead_type_ascription_as_field(&mut self) -> bool { 5 ( 0.00%) self.look_ahead(1, |t| t.is_ident()) . && self.look_ahead(2, |t| t == &token::Colon) . && self.look_ahead(3, |t| t.can_begin_expr()) . } . . fn parse_dot_suffix_expr(&mut self, lo: Span, base: P) -> PResult<'a, P> { 22 ( 0.00%) match self.token.uninterpolate().kind { . token::Ident(..) => self.parse_dot_suffix(base, lo), . token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) => { . Ok(self.parse_tuple_field_access_expr(lo, base, symbol, suffix, None)) . } . token::Literal(token::Lit { kind: token::Float, symbol, suffix }) => { . Ok(self.parse_tuple_field_access_expr_float(lo, base, symbol, suffix)) . } . _ => { -- line 957 ---------------------------------------- -- line 1091 ---------------------------------------- . let span = self.prev_token.span; . let field = ExprKind::Field(base, Ident::new(field, span)); . self.expect_no_suffix(span, "a tuple index", suffix); . self.mk_expr(lo.to(span), field, AttrVec::new()) . } . . /// Parse a function call expression, `expr(...)`. . fn parse_fn_call_expr(&mut self, lo: Span, fun: P) -> P { 5 ( 0.00%) let snapshot = if self.token.kind == token::OpenDelim(token::Paren) . && self.look_ahead_type_ascription_as_field() . { . Some((self.clone(), fun.kind.clone())) . } else { 3 ( 0.00%) None . }; 1 ( 0.00%) let open_paren = self.token.span; . 2 ( 0.00%) let mut seq = self.parse_paren_expr_seq().map(|args| { 3 ( 0.00%) self.mk_expr(lo.to(self.prev_token.span), self.mk_call(fun, args), AttrVec::new()) . }); . if let Some(expr) = . self.maybe_recover_struct_lit_bad_delims(lo, open_paren, &mut seq, snapshot) . { . return expr; . } 5 ( 0.00%) self.recover_seq_parse_error(token::Paren, lo, seq) . } . . /// If we encounter a parser state that looks like the user has written a `struct` literal with . /// parentheses instead of braces, recover the parser state and provide suggestions. . #[instrument(skip(self, seq, snapshot), level = "trace")] . fn maybe_recover_struct_lit_bad_delims( . &mut self, . lo: Span, . open_paren: Span, . seq: &mut PResult<'a, P>, . snapshot: Option<(Self, ExprKind)>, . ) -> Option> { 10 ( 0.00%) match (seq.as_mut(), snapshot) { . (Err(ref mut err), Some((mut snapshot, ExprKind::Path(None, path)))) => { . let name = pprust::path_to_string(&path); . snapshot.bump(); // `(` . match snapshot.parse_struct_fields(path, false, token::Paren) { . Ok((fields, ..)) if snapshot.eat(&token::CloseDelim(token::Paren)) => { . // We are certain we have `Enum::Foo(a: 3, b: 4)`, suggest . // `Enum::Foo { a: 3, b: 4 }` or `Enum::Foo(3, 4)`. . *self = snapshot; -- line 1137 ---------------------------------------- -- line 1165 ---------------------------------------- . } . return Some(self.mk_expr_err(span)); . } . Ok(_) => {} . Err(mut err) => err.emit(), . } . } . _ => {} 3 ( 0.00%) } . None . } . . /// Parse an indexing expression `expr[...]`. . fn parse_index_expr(&mut self, lo: Span, base: P) -> PResult<'a, P> { . self.bump(); // `[` . let index = self.parse_expr()?; . self.expect(&token::CloseDelim(token::Bracket))?; . Ok(self.mk_expr(lo.to(self.prev_token.span), self.mk_index(base, index), AttrVec::new())) . } . . /// Assuming we have just parsed `.`, continue parsing into an expression. . fn parse_dot_suffix(&mut self, self_arg: P, lo: Span) -> PResult<'a, P> { 4 ( 0.00%) if self.token.uninterpolated_span().rust_2018() && self.eat_keyword(kw::Await) { . return Ok(self.mk_await_expr(self_arg, lo)); . } . 2 ( 0.00%) let fn_span_lo = self.token.span; 12 ( 0.00%) let mut segment = self.parse_path_segment(PathStyle::Expr, None)?; 10 ( 0.00%) self.check_trailing_angle_brackets(&segment, &[&token::OpenDelim(token::Paren)]); . self.check_turbofish_missing_angle_brackets(&mut segment); . 10 ( 0.00%) if self.check(&token::OpenDelim(token::Paren)) { . // Method call `expr.f()` 2 ( 0.00%) let mut args = self.parse_paren_expr_seq()?; 8 ( 0.00%) args.insert(0, self_arg); . 6 ( 0.00%) let fn_span = fn_span_lo.to(self.prev_token.span); 6 ( 0.00%) let span = lo.to(self.prev_token.span); 10 ( 0.00%) Ok(self.mk_expr(span, ExprKind::MethodCall(segment, args, fn_span), AttrVec::new())) . } else { . // Field access `expr.f` . if let Some(args) = segment.args { . self.struct_span_err( . args.span(), . "field expressions cannot have generic arguments", . ) . .emit(); -- line 1211 ---------------------------------------- -- line 1607 ---------------------------------------- . symbol_unescaped, . }), . _ => Err(Some(lit)), . }, . None => Err(None), . } . } . 50,877 ( 0.03%) pub(super) fn parse_lit(&mut self) -> PResult<'a, Lit> { 5,653 ( 0.00%) self.parse_opt_lit().ok_or_else(|| { 5,654 ( 0.00%) if let token::Interpolated(inner) = &self.token.kind { . let expr = match inner.as_ref() { . token::NtExpr(expr) => Some(expr), . token::NtLiteral(expr) => Some(expr), . _ => None, . }; . if let Some(expr) = expr { . if matches!(expr.kind, ExprKind::Err) { . self.diagnostic() . .delay_span_bug(self.token.span, &"invalid interpolated expression"); . return self.diagnostic().struct_dummy(); . } . } . } 31,097 ( 0.02%) let msg = format!("unexpected token: {}", super::token_descr(&self.token)); 2,827 ( 0.00%) self.struct_span_err(self.token.span, &msg) . }) 39,571 ( 0.02%) } . . /// Matches `lit = true | false | token_lit`. . /// Returns `None` if the next token is not a literal. 50,877 ( 0.03%) pub(super) fn parse_opt_lit(&mut self) -> Option { 5,653 ( 0.00%) let mut recovered = None; 33,918 ( 0.02%) if self.token == token::Dot { . // Attempt to recover `.4` as `0.4`. We don't currently have any syntax where . // dot would follow an optional literal, so we do this unconditionally. . recovered = self.look_ahead(1, |next_token| { . if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = . next_token.kind . { . if self.token.span.hi() == next_token.span.lo() { . let s = String::from("0.") + symbol.as_str(); -- line 1648 ---------------------------------------- -- line 1654 ---------------------------------------- . }); . if let Some(token) = &recovered { . self.bump(); . self.error_float_lits_must_have_int_part(&token); . } . } . . let token = recovered.as_ref().unwrap_or(&self.token); 25,440 ( 0.01%) match Lit::from_token(token) { 16,956 ( 0.01%) Ok(lit) => { 5,652 ( 0.00%) self.bump(); 16,956 ( 0.01%) Some(lit) . } 2,827 ( 0.00%) Err(LitError::NotLiteral) => None, . Err(err) => { . let span = token.span; . let lit = match token.kind { . token::Literal(lit) => lit, . _ => unreachable!(), . }; . self.bump(); . self.report_lit_error(err, lit, span); -- line 1675 ---------------------------------------- -- line 1676 ---------------------------------------- . // Pack possible quotes and prefixes from the original literal into . // the error literal's symbol so they can be pretty-printed faithfully. . let suffixless_lit = token::Lit::new(lit.kind, lit.symbol, None); . let symbol = Symbol::intern(&suffixless_lit.to_string()); . let lit = token::Lit::new(token::Err, symbol, lit.suffix); . Some(Lit::from_lit_token(lit, span).unwrap_or_else(|_| unreachable!())) . } . } 45,224 ( 0.03%) } . . fn error_float_lits_must_have_int_part(&self, token: &Token) { . self.struct_span_err(token.span, "float literals must have an integer part") . .span_suggestion( . token.span, . "must have an integer part", . pprust::token_to_string(token).into(), . Applicability::MachineApplicable, -- line 1692 ---------------------------------------- 14,170 ( 0.01%) -------------------------------------------------------------------------------- -- 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 { 96,579 ( 0.05%) 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. 549,108 ( 0.31%) if index == 0 { . return true; . } . 274,538 ( 0.16%) 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. 116,017 ( 0.07%) None => index == self.len(), . . // This is bit magic equivalent to: b < 128 || b >= 192 158,525 ( 0.09%) Some(&b) => (b as i8) >= -0x40, . } . } . . /// Converts a string slice to a byte slice. To convert the byte slice back . /// into a string slice, use the [`from_utf8`] function. . /// . /// # Examples . /// -- line 226 ---------------------------------------- -- line 808 ---------------------------------------- . /// . /// assert_eq!(None, iter.next()); . /// ``` . #[must_use = "this returns the split string as an iterator, \ . without modifying the original"] . #[stable(feature = "split_whitespace", since = "1.1.0")] . #[inline] . pub fn split_whitespace(&self) -> SplitWhitespace<'_> { 9 ( 0.00%) SplitWhitespace { inner: self.split(IsWhitespace).filter(IsNotEmpty) } . } . . /// Splits a string slice by ASCII whitespace. . /// . /// The iterator returned will return string slices that are sub-slices of . /// the original string slice, separated by any amount of ASCII whitespace. . /// . /// To split by Unicode `Whitespace` instead, use [`split_whitespace`]. -- line 824 ---------------------------------------- -- line 1056 ---------------------------------------- . /// ``` . /// let s = "Löwe 老虎 Léopard"; . /// let x: &[_] = &['1', '2']; . /// . /// assert_eq!(s.find(x), None); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] 6 ( 0.00%) pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option { 1 ( 0.00%) pat.into_searcher(self).next_match().map(|(i, _)| i) 2 ( 0.00%) } . . /// Returns the byte index for the first character of the rightmost match of the pattern in . /// this string slice. . /// . /// Returns [`None`] if the pattern doesn't match. . /// . /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a . /// function or closure that determines if a character matches. -- line 1074 ---------------------------------------- -- line 1472 ---------------------------------------- . /// . /// ``` . /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect(); . /// assert_eq!(v, ["abc", "defXghi"]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . pub fn splitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> SplitN<'a, P> { 199 ( 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)> { 40 ( 0.00%) let (start, end) = delimiter.into_searcher(self).next_match()?; . // SAFETY: `Searcher` is known to return valid indices. . unsafe { Some((self.get_unchecked(..start), self.get_unchecked(end..))) } . } . . /// Splits the string on the last occurrence of the specified delimiter and . /// returns prefix before delimiter and suffix after delimiter. . /// . /// # Examples -- line 1556 ---------------------------------------- -- line 1749 ---------------------------------------- . /// . /// assert_eq!("Hello\tworld", s.trim()); . /// ``` . #[inline] . #[must_use = "this returns the trimmed string as a slice, \ . without modifying the original"] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn trim(&self) -> &str { 11 ( 0.00%) self.trim_matches(|c: char| c.is_whitespace()) . } . . /// Returns a string slice with leading whitespace removed. . /// . /// 'Whitespace' is defined according to the terms of the Unicode Derived . /// Core Property `White_Space`. . /// . /// # Text directionality -- line 1765 ---------------------------------------- -- line 1945 ---------------------------------------- . /// A more complex pattern, using a closure: . /// . /// ``` . /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar"); . /// ``` . #[must_use = "this returns the trimmed string as a new slice, \ . without modifying the original"] . #[stable(feature = "rust1", since = "1.0.0")] 56 ( 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) } 56 ( 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")] 12 ( 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()) } 12 ( 0.00%) } . . /// Returns a string slice with the prefix removed. . /// . /// If the string starts with the pattern `prefix`, returns substring after the prefix, wrapped . /// in `Some`. Unlike `trim_start_matches`, this method removes the prefix exactly once. . /// . /// If the string does not start with `prefix`, returns `None`. . /// -- line 2018 ---------------------------------------- -- line 2240 ---------------------------------------- . /// ``` . /// let nope = "j".parse::(); . /// . /// assert!(nope.is_err()); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn parse(&self) -> Result { 18 ( 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 ---------------------------------------- 57 ( 0.00%) -------------------------------------------------------------------------------- -- 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 646,083 ( 0.37%) let x = *bytes.next()?; 1,258,176 ( 0.72%) if x < 128 { . return Some(x as u32); . } . . // Multibyte case follows . // Decode from a byte combination out of: [[[x y] z] w] . // NOTE: Performance is sensitive to the exact formulation here . let init = utf8_first_byte(x, 2); . // SAFETY: `bytes` produces an UTF-8-like string, -- line 47 ---------------------------------------- -- 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()? { 21 ( 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 { 14,826 ( 0.01%) (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; 438 ( 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); . 1,122 ( 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] . }}; . } . 546 ( 0.00%) let first = v[index]; 1,092 ( 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. 1,780 ( 0.00%) if align != usize::MAX && align.wrapping_sub(index) % usize_bytes == 0 { . let ptr = v.as_ptr(); 29,936 ( 0.02%) 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 14,826 ( 0.01%) let zu = contains_nonascii(*block); . let zv = contains_nonascii(*block.offset(1)); 29,652 ( 0.02%) if zu || zv { . break; . } . } 29,652 ( 0.02%) index += ascii_block_size; . } . // step from the point where the wordwise loop stopped 5,045 ( 0.00%) while index < len && v[index] < 128 { 1,092 ( 0.00%) index += 1; . } . } else { 404 ( 0.00%) index += 1; . } . } . } . . Ok(()) . } . . // https://tools.ietf.org/html/rfc3629 -- line 245 ---------------------------------------- 401,552 ( 0.23%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/attr.rs -------------------------------------------------------------------------------- Ir -- line 28 ---------------------------------------- . enum OuterAttributeType { . DocComment, . DocBlockComment, . Attribute, . } . . impl<'a> Parser<'a> { . /// Parses attributes that appear before an item. 25,479 ( 0.01%) pub(super) fn parse_outer_attributes(&mut self) -> PResult<'a, AttrWrapper> { . let mut attrs: Vec = Vec::new(); . let mut just_parsed_doc_comment = false; 14,155 ( 0.01%) let start_pos = self.token_cursor.num_next_calls; . loop { 35,375 ( 0.02%) let attr = if self.check(&token::Pound) { 59,318 ( 0.03%) let inner_error_reason = if just_parsed_doc_comment { . "an inner attribute is not permitted following an outer doc comment" . } else if !attrs.is_empty() { . "an inner attribute is not permitted following an outer attribute" . } else { . DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG . }; . let inner_parse_policy = InnerAttrPolicy::Forbidden { . reason: inner_error_reason, . saw_doc_comment: just_parsed_doc_comment, 4,239 ( 0.00%) prev_attr_sp: attrs.last().map(|a| a.span), . }; . just_parsed_doc_comment = false; 33,896 ( 0.02%) Some(self.parse_attribute(inner_parse_policy)?) 5,683 ( 0.00%) } else if let token::DocComment(comment_kind, attr_style, data) = self.token.kind { 7 ( 0.00%) if attr_style != ast::AttrStyle::Outer { . let span = self.token.span; . let mut err = self.sess.span_diagnostic.struct_span_err_with_code( . span, . "expected outer doc comment", . error_code!(E0753), . ); . if let Some(replacement_span) = self.annotate_following_item_if_applicable( . &mut err, -- line 65 ---------------------------------------- -- line 77 ---------------------------------------- . replacement_span, . "you might have meant to write a regular comment", . String::new(), . rustc_errors::Applicability::MachineApplicable, . ); . } . err.emit(); . } 14 ( 0.00%) self.bump(); . just_parsed_doc_comment = true; . // Always make an outer attribute - this allows us to recover from a misplaced . // inner attribute. 168 ( 0.00%) Some(attr::mk_doc_comment( . comment_kind, . ast::AttrStyle::Outer, . data, 7 ( 0.00%) self.prev_token.span, . )) . } else { . None . }; . 8,488 ( 0.00%) if let Some(attr) = attr { 76,392 ( 0.04%) attrs.push(attr); . } else { . break; . } . } 19,817 ( 0.01%) Ok(AttrWrapper::new(attrs.into(), start_pos)) 22,648 ( 0.01%) } . . /// Matches `attribute = # ! [ meta_item ]`. . /// `inner_parse_policy` prescribes how to handle inner attributes. . // Public for rustfmt usage. 42,390 ( 0.02%) pub fn parse_attribute( . &mut self, . inner_parse_policy: InnerAttrPolicy<'_>, . ) -> PResult<'a, ast::Attribute> { . debug!( . "parse_attribute: inner_parse_policy={:?} self.token={:?}", . inner_parse_policy, self.token . ); 21,195 ( 0.01%) let lo = self.token.span; . // Attributes can't have attributes of their own [Editor's note: not with that attitude] . self.collect_tokens_no_attrs(|this| { . if this.eat(&token::Pound) { . let style = if this.eat(&token::Not) { . ast::AttrStyle::Inner . } else { . ast::AttrStyle::Outer . }; . 12,717 ( 0.01%) this.expect(&token::OpenDelim(token::Bracket))?; 16,956 ( 0.01%) let item = this.parse_attr_item(false)?; 12,717 ( 0.01%) this.expect(&token::CloseDelim(token::Bracket))?; 12,717 ( 0.01%) let attr_sp = lo.to(this.prev_token.span); . . // Emit error if inner attribute is encountered and forbidden. 8,478 ( 0.00%) if style == ast::AttrStyle::Inner { 16 ( 0.00%) this.error_on_forbidden_inner_attr(attr_sp, inner_parse_policy); . } . 139,887 ( 0.08%) Ok(attr::mk_attr_from_item(item, None, style, attr_sp)) . } else { . let token_str = pprust::token_to_string(&this.token); . let msg = &format!("expected `#`, found `{}`", token_str); . Err(this.struct_span_err(this.token.span, msg)) . } . }) 38,151 ( 0.02%) } . . fn annotate_following_item_if_applicable( . &self, . err: &mut DiagnosticBuilder<'_>, . span: Span, . attr_type: OuterAttributeType, . ) -> Option { . let mut snapshot = self.clone(); -- line 154 ---------------------------------------- -- line 209 ---------------------------------------- . Err(mut item_err) => { . item_err.cancel(); . } . Ok(None) => {} . } . Some(replacement_span) . } . 14 ( 0.00%) pub(super) fn error_on_forbidden_inner_attr(&self, attr_sp: Span, policy: InnerAttrPolicy<'_>) { 6 ( 0.00%) if let InnerAttrPolicy::Forbidden { reason, saw_doc_comment, prev_attr_sp } = policy { . let prev_attr_note = . if saw_doc_comment { "previous doc comment" } else { "previous outer attribute" }; . . let mut diag = self.struct_span_err(attr_sp, reason); . . if let Some(prev_attr_sp) = prev_attr_sp { . diag.span_label(attr_sp, "not permitted following an outer attribute") . .span_label(prev_attr_sp, prev_attr_note); -- line 226 ---------------------------------------- -- line 237 ---------------------------------------- . OuterAttributeType::Attribute, . ) . .is_some() . { . diag.note("outer attributes, like `#[test]`, annotate the item following them"); . }; . diag.emit(); . } 16 ( 0.00%) } . . /// Parses an inner part of an attribute (the path and following tokens). . /// The tokens must be either a delimited token stream, or empty token stream, . /// or the "legacy" key-value form. . /// PATH `(` TOKEN_STREAM `)` . /// PATH `[` TOKEN_STREAM `]` . /// PATH `{` TOKEN_STREAM `}` . /// PATH . /// PATH `=` UNSUFFIXED_LIT . /// The delimiters or `=` are still put into the resulting token stream. 42,390 ( 0.02%) pub fn parse_attr_item(&mut self, capture_tokens: bool) -> PResult<'a, ast::AttrItem> { 8,478 ( 0.00%) let item = match self.token.kind { . token::Interpolated(ref nt) => match **nt { . Nonterminal::NtMeta(ref item) => Some(item.clone().into_inner()), . _ => None, . }, . _ => None, . }; 50,868 ( 0.03%) Ok(if let Some(item) = item { . self.bump(); . item . } else { 25,434 ( 0.01%) let do_parse = |this: &mut Self| { 8,478 ( 0.00%) let path = this.parse_path(PathStyle::Mod)?; . let args = this.parse_attr_args()?; 38,151 ( 0.02%) Ok(ast::AttrItem { path, args, tokens: None }) 16,956 ( 0.01%) }; . // Attr items don't have attributes 16,956 ( 0.01%) if capture_tokens { self.collect_tokens_no_attrs(do_parse) } else { do_parse(self) }? . }) 63,585 ( 0.04%) } . . /// Parses attributes that appear after the opening of an item. These should . /// be preceded by an exclamation mark, but we accept and warn about one . /// terminated by a semicolon. . /// . /// Matches `inner_attrs*`. 24 ( 0.00%) crate fn parse_inner_attributes(&mut self) -> PResult<'a, Vec> { . let mut attrs: Vec = vec![]; . loop { 17 ( 0.00%) let start_pos: u32 = self.token_cursor.num_next_calls.try_into().unwrap(); . // Only try to parse if it is an inner attribute (has `!`). 91 ( 0.00%) let attr = if self.check(&token::Pound) && self.look_ahead(1, |t| t == &token::Not) { 10 ( 0.00%) Some(self.parse_attribute(InnerAttrPolicy::Permitted)?) 30 ( 0.00%) } else if let token::DocComment(comment_kind, attr_style, data) = self.token.kind { 12 ( 0.00%) if attr_style == ast::AttrStyle::Inner { 24 ( 0.00%) self.bump(); 300 ( 0.00%) Some(attr::mk_doc_comment(comment_kind, attr_style, data, self.prev_token.span)) . } else { . None . } . } else { . None . }; 294 ( 0.00%) if let Some(attr) = attr { 14 ( 0.00%) let end_pos: u32 = self.token_cursor.num_next_calls.try_into().unwrap(); . // If we are currently capturing tokens, mark the location of this inner attribute. . // If capturing ends up creating a `LazyTokenStream`, we will include . // this replace range with it, removing the inner attribute from the final . // `AttrAnnotatedTokenStream`. Inner attributes are stored in the parsed AST note. . // During macro expansion, they are selectively inserted back into the . // token stream (the first inner attribute is remoevd each time we invoke the . // corresponding macro). . let range = start_pos..end_pos; 42 ( 0.00%) if let Capturing::Yes = self.capture_state.capturing { . self.capture_state.inner_attr_ranges.insert(attr.id, (range, vec![])); . } 224 ( 0.00%) attrs.push(attr); . } else { . break; . } . } 18 ( 0.00%) Ok(attrs) 27 ( 0.00%) } . 39,571 ( 0.02%) crate fn parse_unsuffixed_lit(&mut self) -> PResult<'a, ast::Lit> { 11,305 ( 0.01%) let lit = self.parse_lit()?; . debug!("checking if {:?} is unusuffixed", lit); . 8,478 ( 0.00%) if !lit.kind.is_unsuffixed() { . self.struct_span_err(lit.span, "suffixed literals are not allowed in attributes") . .help( . "instead of using a suffixed literal (`1u8`, `1.0f32`, etc.), \ . use an unsuffixed version (`1`, `1.0`, etc.)", . ) . .emit(); . } . 19,782 ( 0.01%) Ok(lit) 33,918 ( 0.02%) } . . /// Parses `cfg_attr(pred, attr_item_list)` where `attr_item_list` is comma-delimited. . pub fn parse_cfg_attr(&mut self) -> PResult<'a, (ast::MetaItem, Vec<(ast::AttrItem, Span)>)> { . let cfg_predicate = self.parse_meta_item()?; . self.expect(&token::Comma)?; . . // Presumably, the majority of the time there will only be one attr. . let mut expanded_attrs = Vec::with_capacity(1); -- line 343 ---------------------------------------- -- line 349 ---------------------------------------- . break; . } . } . . Ok((cfg_predicate, expanded_attrs)) . } . . /// Matches `COMMASEP(meta_item_inner)`. 25,443 ( 0.01%) crate fn parse_meta_seq_top(&mut self) -> PResult<'a, Vec> { . // Presumably, the majority of the time there will only be one attr. . let mut nmis = Vec::with_capacity(1); 14,135 ( 0.01%) while self.token.kind != token::Eof { 11,308 ( 0.01%) nmis.push(self.parse_meta_item_inner()?); . if !self.eat(&token::Comma) { . break; . } . } 22,616 ( 0.01%) Ok(nmis) 22,616 ( 0.01%) } . . /// Matches the following grammar (per RFC 1559). . /// . /// meta_item : PATH ( '=' UNSUFFIXED_LIT | '(' meta_item_inner? ')' )? ; . /// meta_item_inner : (meta_item | UNSUFFIXED_LIT) (',' meta_item_inner)? ; 25,443 ( 0.01%) pub fn parse_meta_item(&mut self) -> PResult<'a, ast::MetaItem> { 5,654 ( 0.00%) let nt_meta = match self.token.kind { . token::Interpolated(ref nt) => match **nt { . token::NtMeta(ref e) => Some(e.clone()), . _ => None, . }, . _ => None, . }; . . if let Some(item) = nt_meta { -- line 382 ---------------------------------------- -- line 384 ---------------------------------------- . Some(meta) => { . self.bump(); . Ok(meta) . } . None => self.unexpected(), . }; . } . 5,654 ( 0.00%) let lo = self.token.span; 2,827 ( 0.00%) let path = self.parse_path(PathStyle::Mod)?; 5,654 ( 0.00%) let kind = self.parse_meta_item_kind()?; 5,654 ( 0.00%) let span = lo.to(self.prev_token.span); 79,156 ( 0.05%) Ok(ast::MetaItem { path, kind, span }) 25,443 ( 0.01%) } . . crate fn parse_meta_item_kind(&mut self) -> PResult<'a, ast::MetaItemKind> { 16,962 ( 0.01%) Ok(if self.eat(&token::Eq) { 5,652 ( 0.00%) ast::MetaItemKind::NameValue(self.parse_unsuffixed_lit()?) 5 ( 0.00%) } else if self.check(&token::OpenDelim(token::Paren)) { . // Matches `meta_seq = ( COMMASEP(meta_item_inner) )`. . let (list, _) = self.parse_paren_comma_seq(|p| p.parse_meta_item_inner())?; . ast::MetaItemKind::List(list) . } else { . ast::MetaItemKind::Word . }) . } . . /// Matches `meta_item_inner : (meta_item | UNSUFFIXED_LIT) ;`. 25,443 ( 0.01%) fn parse_meta_item_inner(&mut self) -> PResult<'a, ast::NestedMetaItem> { 8,481 ( 0.00%) match self.parse_unsuffixed_lit() { . Ok(lit) => return Ok(ast::NestedMetaItem::Literal(lit)), 11,308 ( 0.01%) Err(ref mut err) => err.cancel(), 5,654 ( 0.00%) } . 11,308 ( 0.01%) match self.parse_meta_item() { 42,405 ( 0.02%) Ok(mi) => return Ok(ast::NestedMetaItem::MetaItem(mi)), . Err(ref mut err) => err.cancel(), . } . . let found = pprust::token_to_string(&self.token); . let msg = format!("expected unsuffixed literal or identifier, found `{}`", found); . Err(self.struct_span_err(self.token.span, &msg)) 19,789 ( 0.01%) } . } . . pub fn maybe_needs_tokens(attrs: &[ast::Attribute]) -> bool { . // One of the attributes may either itself be a macro, . // or expand to macro attributes (`cfg_attr`). . attrs.iter().any(|attr| { 65,027 ( 0.04%) if attr.is_doc_comment() { . return false; . } 16,948 ( 0.01%) attr.ident().map_or(true, |ident| { 16,948 ( 0.01%) ident.name == sym::cfg_attr || !rustc_feature::is_builtin_attr_name(ident.name) . }) . }) . } 29,709 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/expand.rs -------------------------------------------------------------------------------- Ir -- line 72 ---------------------------------------- . AstFragmentKind::OptExpr => . result.make_expr().map(Some).map(AstFragment::OptExpr), . $(AstFragmentKind::$Kind => result.$make_ast().map(AstFragment::$Kind),)* . } . } . } . . impl AstFragment { 1 ( 0.00%) pub fn add_placeholders(&mut self, placeholders: &[NodeId]) { 1 ( 0.00%) if placeholders.is_empty() { . return; . } . match self { . $($(AstFragment::$Kind(ast) => ast.extend(placeholders.iter().flat_map(|id| { . // We are repeating through arguments with `many`, to do that we have to . // mention some macro variable from those arguments even if it's not used. . macro _repeating($flat_map_ast_elt) {} . placeholder(AstFragmentKind::$Kind, *id, None).$make_ast() . })),)?)* . _ => panic!("unexpected AST fragment kind") . } 2 ( 0.00%) } . . pub fn make_opt_expr(self) -> Option> { . match self { . AstFragment::OptExpr(expr) => expr, . _ => panic!("AstFragment::make_* called on the wrong kind of fragment"), . } . } . . $(pub fn $make_ast(self) -> $AstTy { 2 ( 0.00%) match self { 9 ( 0.00%) AstFragment::$Kind(ast) => ast, . _ => panic!("AstFragment::make_* called on the wrong kind of fragment"), . } . })* . . fn make_ast(self) -> T::OutputTy { . T::fragment_to_output(self) . } . 2 ( 0.00%) pub fn mut_visit_with(&mut self, vis: &mut F) { 11 ( 0.00%) match self { . AstFragment::OptExpr(opt_expr) => { . visit_clobber(opt_expr, |opt_expr| { . if let Some(expr) = opt_expr { . vis.filter_map_expr(expr) . } else { . None . } . }); . } 9 ( 0.00%) $($(AstFragment::$Kind(ast) => vis.$mut_visit_ast(ast),)?)* . $($(AstFragment::$Kind(ast) => . ast.flat_map_in_place(|ast| vis.$flat_map_ast_elt(ast)),)?)* . } . } . 18 ( 0.00%) pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) { 10 ( 0.00%) match *self { . AstFragment::OptExpr(Some(ref expr)) => visitor.visit_expr(expr), . AstFragment::OptExpr(None) => {} 11 ( 0.00%) $($(AstFragment::$Kind(ref ast) => visitor.$visit_ast(ast),)?)* . $($(AstFragment::$Kind(ref ast) => for ast_elt in &ast[..] { . visitor.$visit_ast_elt(ast_elt, $($args)*); . })?)* . } . } . } . . impl<'a> MacResult for crate::mbe::macro_rules::ParserAnyMacro<'a> { -- line 142 ---------------------------------------- -- line 358 ---------------------------------------- . monotonic: bool, // cf. `cx.monotonic_expander()` . } . . impl<'a, 'b> MacroExpander<'a, 'b> { . pub fn new(cx: &'a mut ExtCtxt<'b>, monotonic: bool) -> Self { . MacroExpander { cx, monotonic } . } . 10 ( 0.00%) pub fn expand_crate(&mut self, krate: ast::Crate) -> ast::Crate { 6 ( 0.00%) let file_path = match self.cx.source_map().span_to_filename(krate.span) { 11 ( 0.00%) FileName::Real(name) => name . .into_local_path() . .expect("attempting to resolve a file path in an external file"), . other => PathBuf::from(other.prefer_local().to_string()), . }; 4 ( 0.00%) let dir_path = file_path.parent().unwrap_or(&file_path).to_owned(); 3 ( 0.00%) self.cx.root_path = dir_path.clone(); 1 ( 0.00%) self.cx.current_expansion.module = Rc::new(ModuleData { 3 ( 0.00%) mod_path: vec![Ident::from_str(&self.cx.ecfg.crate_name)], 4 ( 0.00%) file_path_stack: vec![file_path], . dir_path, . }); 13 ( 0.00%) let krate = self.fully_expand_fragment(AstFragment::Crate(krate)).make_crate(); 1 ( 0.00%) assert_eq!(krate.id, ast::CRATE_NODE_ID); 2 ( 0.00%) self.cx.trace_macros_diag(); . krate 9 ( 0.00%) } . . // Recursively expand all macro invocations in this AST fragment. 9 ( 0.00%) pub fn fully_expand_fragment(&mut self, input_fragment: AstFragment) -> AstFragment { 1 ( 0.00%) let orig_expansion_data = self.cx.current_expansion.clone(); 3 ( 0.00%) let orig_force_mode = self.cx.force_mode; . . // Collect all macro invocations and replace them with placeholders. 8 ( 0.00%) let (mut fragment_with_placeholders, mut invocations) = 10 ( 0.00%) self.collect_invocations(input_fragment, &[]); . . // Optimization: if we resolve all imports now, . // we'll be able to immediately resolve most of imported macros. . self.resolve_imports(); . . // Resolve paths in all invocations and produce output expanded fragments for them, but . // do not insert them into our input AST fragment yet, only store in `expanded_fragments`. . // The output fragments also go through expansion recursively until no invocations are left. . // Unresolved macros produce dummy outputs as a recovery measure. . invocations.reverse(); . let mut expanded_fragments = Vec::new(); . let mut undetermined_invocations = Vec::new(); 6 ( 0.00%) let (mut progress, mut force) = (false, !self.monotonic); . loop { . let Some((invoc, ext)) = invocations.pop() else { . self.resolve_imports(); 1 ( 0.00%) if undetermined_invocations.is_empty() { . break; . } . invocations = mem::take(&mut undetermined_invocations); . force = !mem::replace(&mut progress, false); . if force && self.monotonic { . self.cx.sess.delay_span_bug( . invocations.last().unwrap().0.span(), . "expansion entered force mode without producing any errors", -- line 418 ---------------------------------------- -- line 506 ---------------------------------------- . progress = true; . if expanded_fragments.len() < depth { . expanded_fragments.push(Vec::new()); . } . expanded_fragments[depth - 1].push((expn_id, expanded_fragment)); . invocations.extend(new_invocations.into_iter().rev()); . } . 23 ( 0.00%) self.cx.current_expansion = orig_expansion_data; 1 ( 0.00%) self.cx.force_mode = orig_force_mode; . . // Finally incorporate all the expanded macros into the input AST fragment. . let mut placeholder_expander = PlaceholderExpander::default(); . while let Some(expanded_fragments) = expanded_fragments.pop() { . for (expn_id, expanded_fragment) in expanded_fragments.into_iter().rev() { . placeholder_expander . .add(NodeId::placeholder_from_expn_id(expn_id), expanded_fragment); . } . } 1 ( 0.00%) fragment_with_placeholders.mut_visit_with(&mut placeholder_expander); . fragment_with_placeholders 8 ( 0.00%) } . . fn resolve_imports(&mut self) { 7 ( 0.00%) if self.monotonic { 8 ( 0.00%) self.cx.resolver.resolve_imports(); . } . } . . /// Collects all macro invocations reachable at this time in this AST fragment, and replace . /// them with "placeholders" - dummy macro invocations with specially crafted `NodeId`s. . /// Then call into resolver that builds a skeleton ("reduced graph") of the fragment and . /// prepares data for resolving paths of macro invocations. 12 ( 0.00%) fn collect_invocations( . &mut self, . mut fragment: AstFragment, . extra_placeholders: &[NodeId], . ) -> (AstFragment, Vec<(Invocation, Option>)>) { . // Resolve `$crate`s in the fragment for pretty-printing. 4 ( 0.00%) self.cx.resolver.resolve_dollar_crates(); . . let mut invocations = { 6 ( 0.00%) let mut collector = InvocationCollector { . // Non-derive macro invocations cannot see the results of cfg expansion - they . // will either be removed along with the item, or invoked before the cfg/cfg_attr . // attribute is expanded. Therefore, we don't need to configure the tokens . // Derive macros *can* see the results of cfg-expansion - they are handled . // specially in `fully_expand_fragment` . cfg: StripUnconfigured { 1 ( 0.00%) sess: &self.cx.sess, 1 ( 0.00%) features: self.cx.ecfg.features, . config_tokens: false, . }, . cx: self.cx, . invocations: Vec::new(), 1 ( 0.00%) monotonic: self.monotonic, . }; . fragment.mut_visit_with(&mut collector); 4 ( 0.00%) fragment.add_placeholders(extra_placeholders); 4 ( 0.00%) collector.invocations . }; . 2 ( 0.00%) if self.monotonic { 3 ( 0.00%) self.cx . .resolver 2 ( 0.00%) .visit_ast_fragment_with_placeholders(self.cx.current_expansion.id, &fragment); . 3 ( 0.00%) if self.cx.sess.opts.debugging_opts.incremental_relative_spans { . for (invoc, _) in invocations.iter_mut() { . let expn_id = invoc.expansion_data.id; . let parent_def = self.cx.resolver.invocation_parent(expn_id); . let span = match &mut invoc.kind { . InvocationKind::Bang { ref mut span, .. } => span, . InvocationKind::Attr { attr, .. } => &mut attr.span, . InvocationKind::Derive { path, .. } => &mut path.span, . }; . *span = span.with_parent(Some(parent_def)); . } . } . } . 9 ( 0.00%) (fragment, invocations) 8 ( 0.00%) } . . fn error_recursion_limit_reached(&mut self) { . let expn_data = self.cx.current_expansion.id.expn_data(); . let suggested_limit = match self.cx.ecfg.recursion_limit { . Limit(0) => Limit(2), . limit => limit * 2, . }; . self.cx -- line 596 ---------------------------------------- -- line 1047 ---------------------------------------- . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { . fragment.make_items() . } . fn id(&mut self) -> &mut NodeId { . &mut self.id . } . fn noop_flat_map(self, visitor: &mut V) -> Self::OutputTy { 12 ( 0.00%) noop_flat_map_item(self, visitor) . } . fn is_mac_call(&self) -> bool { 4 ( 0.00%) matches!(self.kind, ItemKind::MacCall(..)) . } . fn take_mac_call(self) -> (ast::MacCall, Self::AttrsTy, AddSemicolon) { . let node = self.into_inner(); . match node.kind { . ItemKind::MacCall(mac) => (mac, node.attrs, AddSemicolon::No), . _ => unreachable!(), . } . } 44 ( 0.00%) fn wrap_flat_map_node_noop_flat_map( . mut node: Self, . collector: &mut InvocationCollector<'_, '_>, . noop_flat_map: impl FnOnce(Self, &mut InvocationCollector<'_, '_>) -> Self::OutputTy, . ) -> Result { 8 ( 0.00%) if !matches!(node.kind, ItemKind::Mod(..)) { 18 ( 0.00%) return Ok(noop_flat_map(node, collector)); . } . . // Work around borrow checker not seeing through `P`'s deref. 11 ( 0.00%) let (ident, span, mut attrs) = (node.ident, node.span, mem::take(&mut node.attrs)); . let ItemKind::Mod(_, mod_kind) = &mut node.kind else { . unreachable!() . }; . . let ecx = &mut collector.cx; 2 ( 0.00%) let (file_path, dir_path, dir_ownership) = match mod_kind { . ModKind::Loaded(_, inline, _) => { . // Inline `mod foo { ... }`, but we still need to push directories. . let (dir_path, dir_ownership) = mod_dir_path( . &ecx.sess, . ident, . &attrs, . &ecx.current_expansion.module, . ecx.current_expansion.dir_ownership, . *inline, . ); . node.attrs = attrs; . (None, dir_path, dir_ownership) . } . ModKind::Unloaded => { . // We have an outline `mod foo;` so we need to parse the file. 2 ( 0.00%) let old_attrs_len = attrs.len(); 19 ( 0.00%) let ParsedExternalMod { items, inner_span, file_path, dir_path, dir_ownership } = 8 ( 0.00%) parse_external_mod( 2 ( 0.00%) &ecx.sess, 2 ( 0.00%) ident, . span, 1 ( 0.00%) &ecx.current_expansion.module, 1 ( 0.00%) ecx.current_expansion.dir_ownership, . &mut attrs, . ); . 5 ( 0.00%) if let Some(lint_store) = ecx.lint_store { 13 ( 0.00%) lint_store.pre_expansion_lint( 2 ( 0.00%) ecx.sess, 4 ( 0.00%) ecx.resolver.registered_tools(), 2 ( 0.00%) ecx.current_expansion.lint_node_id, . &attrs, . &items, 1 ( 0.00%) ident.name.as_str(), . ); . } . 12 ( 0.00%) *mod_kind = ModKind::Loaded(items, Inline::No, inner_span); 9 ( 0.00%) node.attrs = attrs; 2 ( 0.00%) if node.attrs.len() > old_attrs_len { . // If we loaded an out-of-line module and added some inner attributes, . // then we need to re-configure it and re-collect attributes for . // resolution and expansion. . return Err(node); . } . (Some(file_path), dir_path, dir_ownership) . } . }; . . // Set the module info before we flat map. 7 ( 0.00%) let mut module = ecx.current_expansion.module.with_dir_path(dir_path); 2 ( 0.00%) module.mod_path.push(ident); 2 ( 0.00%) if let Some(file_path) = file_path { . module.file_path_stack.push(file_path); . } . 2 ( 0.00%) let orig_module = mem::replace(&mut ecx.current_expansion.module, Rc::new(module)); . let orig_dir_ownership = 1 ( 0.00%) mem::replace(&mut ecx.current_expansion.dir_ownership, dir_ownership); . 5 ( 0.00%) let res = Ok(noop_flat_map(node, collector)); . 3 ( 0.00%) collector.cx.current_expansion.dir_ownership = orig_dir_ownership; 4 ( 0.00%) collector.cx.current_expansion.module = orig_module; 4 ( 0.00%) res 36 ( 0.00%) } . } . . struct TraitItemTag; . impl InvocationCollectorNode for AstLikeWrapper, TraitItemTag> { . type OutputTy = SmallVec<[P; 1]>; . const KIND: AstFragmentKind = AstFragmentKind::TraitItems; . fn to_annotatable(self) -> Annotatable { . Annotatable::TraitItem(self.wrapped) -- line 1157 ---------------------------------------- -- line 1410 ---------------------------------------- . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { . fragment.make_crate() . } . fn id(&mut self) -> &mut NodeId { . &mut self.id . } . fn noop_visit(&mut self, visitor: &mut V) { 3 ( 0.00%) noop_visit_crate(self, visitor) . } . } . . impl InvocationCollectorNode for P { . type OutputTy = P; . const KIND: AstFragmentKind = AstFragmentKind::Ty; . fn to_annotatable(self) -> Annotatable { . unreachable!() -- line 1426 ---------------------------------------- -- line 1581 ---------------------------------------- . . /// If `item` is an attribute invocation, remove the attribute and return it together with . /// its position and derives following it. We have to collect the derives in order to resolve . /// legacy derive helpers (helpers written before derives that introduce them). . fn take_first_attr( . &self, . item: &mut impl AstLike, . ) -> Option<(ast::Attribute, usize, Vec)> { 2,830 ( 0.00%) let mut attr = None; . 2,830 ( 0.00%) let mut cfg_pos = None; 5,659 ( 0.00%) let mut attr_pos = None; 2 ( 0.00%) for (pos, attr) in item.attrs().iter().enumerate() { 25,537 ( 0.01%) if !attr.is_doc_comment() && !self.cx.expanded_inert_attrs.is_marked(attr) { 5,658 ( 0.00%) let name = attr.ident().map(|ident| ident.name); 11,316 ( 0.01%) if name == Some(sym::cfg) || name == Some(sym::cfg_attr) { 5,650 ( 0.00%) cfg_pos = Some(pos); // a cfg attr found, no need to search anymore . break; 12 ( 0.00%) } else if attr_pos.is_none() . && !name.map_or(false, rustc_feature::is_builtin_attr_name) . { . attr_pos = Some(pos); // a non-cfg attr found, still may find a cfg attr . } . } . } . . item.visit_attrs(|attrs| { 121,495 ( 0.07%) attr = Some(match (cfg_pos, attr_pos) { 48,025 ( 0.03%) (Some(pos), _) => (attrs.remove(pos), pos, Vec::new()), . (_, Some(pos)) => { . let attr = attrs.remove(pos); . let following_derives = attrs[pos..] . .iter() . .filter(|a| a.has_name(sym::derive)) . .flat_map(|a| a.meta_item_list().unwrap_or_default()) . .filter_map(|nested_meta| match nested_meta { . NestedMetaItem::MetaItem(ast::MetaItem { -- line 1617 ---------------------------------------- -- line 1679 ---------------------------------------- . } . . fn expand_cfg_true( . &mut self, . node: &mut impl AstLike, . attr: ast::Attribute, . pos: usize, . ) -> bool { 5,650 ( 0.00%) let res = self.cfg.cfg_true(&attr); 5,650 ( 0.00%) if res { . // FIXME: `cfg(TRUE)` attributes do not currently remove themselves during expansion, . // and some tools like rustdoc and clippy rely on that. Find a way to remove them . // while keeping the tools working. . self.cx.expanded_inert_attrs.mark(&attr); . node.visit_attrs(|attrs| attrs.insert(pos, attr)); . } . res . } -- line 1696 ---------------------------------------- -- line 1701 ---------------------------------------- . }); . } . . fn flat_map_node>( . &mut self, . mut node: Node, . ) -> Node::OutputTy { . loop { 8,487 ( 0.00%) return match self.take_first_attr(&mut node) { 79,100 ( 0.05%) Some((attr, pos, derives)) => match attr.name_or_empty() { . sym::cfg => { 48,025 ( 0.03%) if self.expand_cfg_true(&mut node, attr, pos) { . continue; . } . Default::default() . } . sym::cfg_attr => { . self.expand_cfg_attr(&mut node, attr, pos); . continue; . } . _ => { . Node::pre_flat_map_node_collect_attr(&self.cfg, &attr); . self.collect_attr((attr, pos, derives), node.to_annotatable(), Node::KIND) . .make_ast::() . } . }, 4 ( 0.00%) None if node.is_mac_call() => { . let (mac, attrs, add_semicolon) = node.take_mac_call(); . self.check_attributes(&attrs, &mac); . let mut res = self.collect_bang(mac, Node::KIND).make_ast::(); . Node::post_flat_map_node_collect_bang(&mut res, add_semicolon); . res . } . None => { 24 ( 0.00%) match Node::wrap_flat_map_node_noop_flat_map(node, self, |mut node, this| { 44 ( 0.00%) assign_id!(this, node.id(), || node.noop_flat_map(this)) . }) { 20 ( 0.00%) Ok(output) => output, . Err(returned_node) => { 2,833 ( 0.00%) node = returned_node; . continue; . } . } . } . }; . } 2,825 ( 0.00%) } . . fn visit_node + DummyAstNode>( . &mut self, . node: &mut Node, . ) { . loop { 3 ( 0.00%) return match self.take_first_attr(node) { . Some((attr, pos, derives)) => match attr.name_or_empty() { . sym::cfg => { . let span = attr.span; . if self.expand_cfg_true(node, attr, pos) { . continue; . } . let msg = . format!("removing {} is not supported in this position", Node::descr()); -- line 1762 ---------------------------------------- -- line 1776 ---------------------------------------- . visit_clobber(node, |node| { . // Do not clobber unless it's actually a macro (uncommon case). . let (mac, attrs, _) = node.take_mac_call(); . self.check_attributes(&attrs, &mac); . self.collect_bang(mac, Node::KIND).make_ast::() . }) . } . None => { 13 ( 0.00%) assign_id!(self, node.id(), || node.noop_visit(self)) . } . }; . } . } . } . . impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> { 39,606 ( 0.02%) fn flat_map_item(&mut self, node: P) -> SmallVec<[P; 1]> { . self.flat_map_node(node) 25,461 ( 0.01%) } . . fn flat_map_trait_item(&mut self, node: P) -> SmallVec<[P; 1]> { . self.flat_map_node(AstLikeWrapper::new(node, TraitItemTag)) . } . . fn flat_map_impl_item(&mut self, node: P) -> SmallVec<[P; 1]> { . self.flat_map_node(AstLikeWrapper::new(node, ImplItemTag)) . } -- line 1802 ---------------------------------------- -- line 1863 ---------------------------------------- . } . _ => assign_id!(self, &mut node.id, || noop_flat_map_stmt(node, self)), . }; . } . . self.flat_map_node(node) . } . 13 ( 0.00%) fn visit_crate(&mut self, node: &mut ast::Crate) { . self.visit_node(node) 8 ( 0.00%) } . . fn visit_ty(&mut self, node: &mut P) { . self.visit_node(node) . } . . fn visit_pat(&mut self, node: &mut P) { . self.visit_node(node) . } -- line 1881 ---------------------------------------- -- line 1899 ---------------------------------------- . ); . noop_visit_block(node, self); . self.cx.current_expansion.dir_ownership = orig_dir_ownership; . } . . fn visit_id(&mut self, id: &mut NodeId) { . // We may have already assigned a `NodeId` . // by calling `assign_id` 65 ( 0.00%) if self.monotonic && *id == ast::DUMMY_NODE_ID { 40 ( 0.00%) *id = self.cx.resolver.next_node_id(); . } . } . } . . pub struct ExpansionConfig<'feat> { . pub crate_name: String, . pub features: Option<&'feat Features>, . pub recursion_limit: Limit, . pub trace_mac: bool, . pub should_test: bool, // If false, strip `#[test]` nodes . pub span_debug: bool, // If true, use verbose debugging for `proc_macro::Span` . pub proc_macro_backtrace: bool, // If true, show backtraces for proc-macro panics . } . . impl<'feat> ExpansionConfig<'feat> { 12 ( 0.00%) pub fn default(crate_name: String) -> ExpansionConfig<'static> { 18 ( 0.00%) ExpansionConfig { 9 ( 0.00%) crate_name, . features: None, 6 ( 0.00%) recursion_limit: Limit::new(1024), . trace_mac: false, . should_test: false, . span_debug: false, . proc_macro_backtrace: false, . } 15 ( 0.00%) } . . fn proc_macro_hygiene(&self) -> bool { . self.features.map_or(false, |features| features.proc_macro_hygiene) . } . } 8,518 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs -------------------------------------------------------------------------------- Ir -- line 84 ---------------------------------------- . pub struct SessionGlobals { . symbol_interner: symbol::Interner, . span_interner: Lock, . hygiene_data: Lock, . source_map: Lock>>, . } . . impl SessionGlobals { 12 ( 0.00%) pub fn new(edition: Edition) -> SessionGlobals { 50 ( 0.00%) SessionGlobals { 2 ( 0.00%) symbol_interner: symbol::Interner::fresh(), . span_interner: Lock::new(span_encoding::SpanInterner::default()), 6 ( 0.00%) hygiene_data: Lock::new(hygiene::HygieneData::new(edition)), . source_map: Lock::new(None), . } 10 ( 0.00%) } . } . . #[inline] . pub fn create_session_globals_then(edition: Edition, f: impl FnOnce() -> R) -> R { 1 ( 0.00%) assert!( . !SESSION_GLOBALS.is_set(), . "SESSION_GLOBALS should never be overwritten! \ . Use another thread if you need another SessionGlobals" . ); 3 ( 0.00%) let session_globals = SessionGlobals::new(edition); 7 ( 0.00%) SESSION_GLOBALS.set(&session_globals, f) 1 ( 0.00%) } . . #[inline] . pub fn set_session_globals_then(session_globals: &SessionGlobals, f: impl FnOnce() -> R) -> R { . assert!( . !SESSION_GLOBALS.is_set(), . "SESSION_GLOBALS should never be overwritten! \ . Use another thread if you need another SessionGlobals" . ); -- line 119 ---------------------------------------- -- line 120 ---------------------------------------- . SESSION_GLOBALS.set(session_globals, f) . } . . #[inline] . pub fn create_default_session_if_not_set_then(f: F) -> R . where . F: FnOnce(&SessionGlobals) -> R, . { 4 ( 0.00%) create_session_if_not_set_then(edition::DEFAULT_EDITION, f) . } . . #[inline] . pub fn create_session_if_not_set_then(edition: Edition, f: F) -> R . where . F: FnOnce(&SessionGlobals) -> R, . { 1 ( 0.00%) if !SESSION_GLOBALS.is_set() { 3 ( 0.00%) let session_globals = SessionGlobals::new(edition); 11 ( 0.00%) SESSION_GLOBALS.set(&session_globals, || SESSION_GLOBALS.with(f)) 1 ( 0.00%) } else { . SESSION_GLOBALS.with(f) . } . } . . #[inline] . pub fn with_session_globals(f: F) -> R . where . F: FnOnce(&SessionGlobals) -> R, . { 3,016 ( 0.00%) 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)] 1,040 ( 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 2,635 ( 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 { 2,106 ( 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 { 2 ( 0.00%) match self { . RealFileName::LocalPath(path) . | RealFileName::Remapped { local_path: None, virtual_name: path } . | RealFileName::Remapped { local_path: Some(path), virtual_name: _ } => path, . } . } . 2 ( 0.00%) pub fn to_string_lossy(&self, display_pref: FileNameDisplayPreference) -> Cow<'_, str> { 4 ( 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() . } . } 3 ( 0.00%) } . } . . /// Differentiates between real files and common virtual files. 5,377 ( 0.00%) #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash)] 6,283 ( 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 { 14 ( 0.00%) fn from(p: PathBuf) -> Self { 4 ( 0.00%) assert!(!p.to_string_lossy().ends_with('>')); 12 ( 0.00%) FileName::Real(RealFileName::LocalPath(p)) 14 ( 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<'_> { 8 ( 0.00%) fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { . use FileName::*; 12 ( 0.00%) match *self.inner { . Real(ref name) => { 12 ( 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, ""), . } 10 ( 0.00%) } . } . . impl FileNameDisplay<'_> { . pub fn to_string_lossy(&self) -> Cow<'_, str> { . match self.inner { . FileName::Real(ref inner) => inner.to_string_lossy(self.display_pref), . _ => Cow::from(format!("{}", self)), . } . } . } . . impl FileName { . pub fn is_real(&self) -> bool { . use FileName::*; 1,056 ( 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. 2 ( 0.00%) pub fn prefer_local(&self) -> FileNameDisplay<'_> { . FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Local } 4 ( 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 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 { 59,559 ( 0.03%) self.lo.0 == 0 && self.hi.0 == 0 . } . /// Returns `true` if `self` fully encloses `other`. . pub fn contains(self, other: Self) -> bool { . self.lo <= other.lo && other.hi <= self.hi . } . } . . // The interner is pointed to by a thread local value which is only set on the main thread -- line 501 ---------------------------------------- -- line 502 ---------------------------------------- . // with parallelization is disabled. So we don't allow `Span` to transfer between threads . // to avoid panics and other errors, even though it would be memory safe to do so. . #[cfg(not(parallel_compiler))] . impl !Send for Span {} . #[cfg(not(parallel_compiler))] . impl !Sync for Span {} . . impl PartialOrd for Span { 120,320 ( 0.07%) fn partial_cmp(&self, rhs: &Self) -> Option { 90,240 ( 0.05%) PartialOrd::partial_cmp(&self.data(), &rhs.data()) 120,320 ( 0.07%) } . } . 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] 18 ( 0.00%) pub fn with_lo(self, lo: BytePos) -> Span { . self.data().with_lo(lo) 12 ( 0.00%) } . #[inline] 5,740 ( 0.00%) pub fn hi(self) -> BytePos { . self.data().hi 5,740 ( 0.00%) } . #[inline] 12,915 ( 0.01%) pub fn with_hi(self, hi: BytePos) -> Span { . self.data().with_hi(hi) 8,610 ( 0.00%) } . #[inline] . pub fn ctxt(self) -> SyntaxContext { . self.data_untracked().ctxt . } . #[inline] 14,160 ( 0.01%) pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span { . self.data_untracked().with_ctxt(ctxt) 8,496 ( 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. 33 ( 0.00%) pub fn edition(self) -> edition::Edition { . self.ctxt().edition() 22 ( 0.00%) } . . #[inline] . pub fn rust_2015(self) -> bool { 11 ( 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 { . self.edition() >= edition::Edition::Edition2021 . } . . /// Returns the source callee. -- line 698 ---------------------------------------- -- line 707 ---------------------------------------- . } . let expn_data = self.ctxt().outer_expn_data(); . if !expn_data.is_root() { Some(source_callee(expn_data)) } else { None } . } . . /// Checks if a span is "internal" to a macro in which `#[unstable]` . /// items can be used (that is, a macro marked with . /// `#[allow_internal_unstable]`). 5 ( 0.00%) pub fn allows_unstable(self, feature: Symbol) -> bool { 1 ( 0.00%) self.ctxt() . .outer_expn_data() . .allow_internal_unstable . .map_or(false, |features| features.iter().any(|&f| f == feature)) 4 ( 0.00%) } . . /// Checks if this span arises from a compiler desugaring of kind `kind`. . pub fn is_desugaring(self, kind: DesugaringKind) -> bool { . match self.ctxt().outer_expn_data().kind { . ExpnKind::Desugaring(k) => k == kind, . _ => false, . } . } -- line 728 ---------------------------------------- -- line 767 ---------------------------------------- . . /// Returns a `Span` that would enclose both `self` and `end`. . /// . /// ```text . /// ____ ___ . /// self lorem ipsum end . /// ^^^^^^^^^^^^^^^^^^^^ . /// ``` 233,607 ( 0.13%) 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. 42,474 ( 0.02%) 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 }, 148,659 ( 0.08%) if span_data.parent == end_data.parent { span_data.parent } else { None }, . ) 191,133 ( 0.11%) } . . /// Returns a `Span` between the end of `self` to the beginning of `end`. . /// . /// ```text . /// ____ ___ . /// self lorem ipsum end . /// ^^^^^^^^^^^^^ . /// ``` -- line 804 ---------------------------------------- -- line 856 ---------------------------------------- . span.ctxt, . span.parent, . ) . } . . /// Equivalent of `Span::def_site` from the proc macro API, . /// except that the location is taken from the `self` span. . pub fn with_def_site_ctxt(self, expn_id: ExpnId) -> Span { 2 ( 0.00%) self.with_ctxt_from_mark(expn_id, Transparency::Opaque) . } . . /// Equivalent of `Span::call_site` from the proc macro API, . /// except that the location is taken from the `self` span. . pub fn with_call_site_ctxt(self, expn_id: ExpnId) -> Span { 2 ( 0.00%) self.with_ctxt_from_mark(expn_id, Transparency::Transparent) . } . . /// Equivalent of `Span::mixed_site` from the proc macro API, . /// except that the location is taken from the `self` span. . pub fn with_mixed_site_ctxt(self, expn_id: ExpnId) -> Span { . self.with_ctxt_from_mark(expn_id, Transparency::SemiTransparent) . } . . /// Produces a span with the same location as `self` and context produced by a macro with the . /// given ID and transparency, assuming that macro was defined directly and not produced by . /// some other macro (which is the case for built-in and procedural macros). 24 ( 0.00%) pub fn with_ctxt_from_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span { . self.with_ctxt(SyntaxContext::root().apply_mark(expn_id, transparency)) 14 ( 0.00%) } . . #[inline] . pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span { . let span = self.data(); . span.with_ctxt(span.ctxt.apply_mark(expn_id, transparency)) . } . . #[inline] -- line 892 ---------------------------------------- -- line 901 ---------------------------------------- . pub fn adjust(&mut self, expn_id: ExpnId) -> Option { . let mut span = self.data(); . let mark = span.ctxt.adjust(expn_id); . *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark . } . . #[inline] 45 ( 0.00%) pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option { 30 ( 0.00%) let mut span = self.data(); 25 ( 0.00%) let mark = span.ctxt.normalize_to_macros_2_0_and_adjust(expn_id); 45 ( 0.00%) *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark 50 ( 0.00%) } . . #[inline] . pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option> { . let mut span = self.data(); . let mark = span.ctxt.glob_adjust(expn_id, glob_span); . *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark . } -- line 922 ---------------------------------------- -- line 929 ---------------------------------------- . ) -> Option> { . let mut span = self.data(); . let mark = span.ctxt.reverse_glob_adjust(expn_id, glob_span); . *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark . } . . #[inline] 32 ( 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()) 28 ( 0.00%) } . . #[inline] . pub fn normalize_to_macro_rules(self) -> Span { . let span = self.data(); . span.with_ctxt(span.ctxt.normalize_to_macro_rules()) . } . } . -- line 948 ---------------------------------------- -- line 958 ---------------------------------------- . . /// What label should we attach to this span (if any)? . pub label: Option, . } . . impl Default for Span { . fn default() -> Self { . DUMMY_SP 2 ( 0.00%) } . } . . impl Encodable for Span { . default fn encode(&self, s: &mut E) -> Result<(), E::Error> { . let span = self.data(); . s.emit_struct(false, |s| { . s.emit_struct_field("lo", true, |s| span.lo.encode(s))?; . s.emit_struct_field("hi", false, |s| span.hi.encode(s)) -- line 974 ---------------------------------------- -- line 990 ---------------------------------------- . /// any spans that are debug-printed during the closure's execution. . /// . /// Normally, the global `TyCtxt` is used to retrieve the `SourceMap` . /// (see `rustc_interface::callbacks::span_debug1`). However, some parts . /// of the compiler (e.g. `rustc_parse`) may debug-print `Span`s before . /// a `TyCtxt` is available. In this case, we fall back to . /// the `SourceMap` provided to this function. If that is not available, . /// we fall back to printing the raw `Span` field values. 9 ( 0.00%) pub fn with_source_map T>(source_map: Lrc, f: F) -> T { . with_session_globals(|session_globals| { 2 ( 0.00%) *session_globals.source_map.borrow_mut() = Some(source_map); . }); . struct ClearSourceMap; . impl Drop for ClearSourceMap { . fn drop(&mut self) { . with_session_globals(|session_globals| { 1 ( 0.00%) session_globals.source_map.borrow_mut().take(); . }); . } . } . . let _guard = ClearSourceMap; 4 ( 0.00%) f() 8 ( 0.00%) } . . pub fn debug_with_source_map( . span: Span, . f: &mut fmt::Formatter<'_>, . source_map: &SourceMap, . ) -> fmt::Result { . write!(f, "{} ({:?})", source_map.span_to_diagnostic_string(span), span.ctxt()) . } -- line 1021 ---------------------------------------- -- line 1048 ---------------------------------------- . . impl MultiSpan { . #[inline] . pub fn new() -> MultiSpan { . MultiSpan { primary_spans: vec![], span_labels: vec![] } . } . . pub fn from_span(primary_span: Span) -> MultiSpan { 14,145 ( 0.01%) MultiSpan { primary_spans: vec![primary_span], span_labels: vec![] } . } . . pub fn from_spans(mut vec: Vec) -> MultiSpan { . vec.sort(); . MultiSpan { primary_spans: vec, span_labels: vec![] } . } . . pub fn push_span_label(&mut self, span: Span, label: String) { . self.span_labels.push((span, label)); . } . . /// Selects the first primary span (if any). . pub fn primary_span(&self) -> Option { . self.primary_spans.first().cloned() 2,827 ( 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 { 14,145 ( 0.01%) fn from(span: Span) -> MultiSpan { . MultiSpan::from_span(span) 14,145 ( 0.01%) } . } . . 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`. 308 ( 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 { 532 ( 0.00%) match self { . NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs), . NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs), . NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs), . } . } . } . . impl Sub for NonNarrowChar { . type Output = Self; . 154 ( 0.00%) fn sub(self, rhs: BytePos) -> Self { 532 ( 0.00%) match self { . NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs), . NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs), . NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs), . } 462 ( 0.00%) } . } . . /// Identifies an offset of a character that was normalized away from `SourceFile`. . #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)] . pub struct NormalizedPos { . /// The absolute offset of the character in the `SourceMap`. . pub pos: BytePos, . /// The difference between original and normalized string at position. . pub diff: u32, . } . 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; . 1,052 ( 0.00%) #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Encodable, Decodable)] . pub enum SourceFileHashAlgorithm { . Md5, . Sha1, . Sha256, . } . . impl FromStr for SourceFileHashAlgorithm { . type Err = (); -- line 1283 ---------------------------------------- -- line 1290 ---------------------------------------- . _ => Err(()), . } . } . } . . rustc_data_structures::impl_stable_hash_via_hash!(SourceFileHashAlgorithm); . . /// The hash of the on-disk source file used for debug info. 6 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, Debug)] 2,104 ( 0.00%) #[derive(HashStable_Generic, Encodable, Decodable)] . pub struct SourceFileHash { . pub kind: SourceFileHashAlgorithm, . value: [u8; 32], . } . . impl SourceFileHash { . pub fn new(kind: SourceFileHashAlgorithm, src: &str) -> SourceFileHash { . let mut hash = SourceFileHash { kind, value: Default::default() }; . let len = hash.hash_len(); . let value = &mut hash.value[..len]; . let data = src.as_bytes(); . match kind { . SourceFileHashAlgorithm::Md5 => { 6 ( 0.00%) value.copy_from_slice(&Md5::digest(data)); . } . SourceFileHashAlgorithm::Sha1 => { . value.copy_from_slice(&Sha1::digest(data)); . } . SourceFileHashAlgorithm::Sha256 => { . value.copy_from_slice(&Sha256::digest(data)); . } . } -- line 1321 ---------------------------------------- -- line 1329 ---------------------------------------- . . /// The bytes of the hash. . pub fn hash_bytes(&self) -> &[u8] { . let len = self.hash_len(); . &self.value[..len] . } . . fn hash_len(&self) -> usize { 6 ( 0.00%) match self.kind { . SourceFileHashAlgorithm::Md5 => 16, . SourceFileHashAlgorithm::Sha1 => 20, . SourceFileHashAlgorithm::Sha256 => 32, . } . } . } . . /// A single source in the [`SourceMap`]. 58 ( 0.00%) #[derive(Clone)] . pub struct SourceFile { . /// The name of the file that the source came from. Source that doesn't . /// originate from files has names between angle brackets by convention . /// (e.g., ``). . pub name: FileName, . /// The complete source code. 1 ( 0.00%) pub src: Option>, . /// The source code's hash. . pub src_hash: SourceFileHash, . /// The external source code (used for external crates, which will have a `None` . /// value as `self.src`. . pub external_src: Lock, . /// The start position of this source in the `SourceMap`. . pub start_pos: BytePos, . /// The end position of this source in the `SourceMap`. -- line 1361 ---------------------------------------- -- line 1364 ---------------------------------------- . pub lines: Vec, . /// Locations of multi-byte characters in the source code. . pub multibyte_chars: Vec, . /// Width of characters that are not narrow in the source code. . pub non_narrow_chars: Vec, . /// Locations of characters removed during normalization. . pub normalized_pos: Vec, . /// A hash of the filename, used for speeding up hashing in incremental compilation. 1 ( 0.00%) pub name_hash: u128, . /// Indicates which crate this `SourceFile` was imported from. 1 ( 0.00%) pub cnum: CrateNum, . } . . impl Encodable for SourceFile { . fn encode(&self, s: &mut S) -> Result<(), S::Error> { . s.emit_struct(false, |s| { . s.emit_struct_field("name", true, |s| self.name.encode(s))?; . s.emit_struct_field("src_hash", false, |s| self.src_hash.encode(s))?; . s.emit_struct_field("start_pos", false, |s| self.start_pos.encode(s))?; . s.emit_struct_field("end_pos", false, |s| self.end_pos.encode(s))?; . s.emit_struct_field("lines", false, |s| { . let lines = &self.lines[..]; . // Store the length. . s.emit_u32(lines.len() as u32)?; . 4 ( 0.00%) if !lines.is_empty() { . // In order to preserve some space, we exploit the fact that . // the lines list is sorted and individual lines are . // probably not that long. Because of that we can store lines . // as a difference list, using as little space as possible . // for the differences. . let max_line_length = if lines.len() == 1 { . 0 . } else { -- line 1397 ---------------------------------------- -- line 1399 ---------------------------------------- . .array_windows() . .map(|&[fst, snd]| snd - fst) . .map(|bp| bp.to_usize()) . .max() . .unwrap() . }; . . let bytes_per_diff: u8 = match max_line_length { 2 ( 0.00%) 0..=0xFF => 1, . 0x100..=0xFFFF => 2, . _ => 4, . }; . . // Encode the number of bytes used per diff. . bytes_per_diff.encode(s)?; . . // Encode the first element. . lines[0].encode(s)?; . . let diff_iter = lines.array_windows().map(|&[fst, snd]| snd - fst); . 2 ( 0.00%) match bytes_per_diff { . 1 => { . for diff in diff_iter { . (diff.0 as u8).encode(s)? . } . } . 2 => { . for diff in diff_iter { . (diff.0 as u16).encode(s)? -- line 1428 ---------------------------------------- -- line 1436 ---------------------------------------- . _ => unreachable!(), . } . } . . Ok(()) . })?; . s.emit_struct_field("multibyte_chars", false, |s| self.multibyte_chars.encode(s))?; . s.emit_struct_field("non_narrow_chars", false, |s| self.non_narrow_chars.encode(s))?; 3 ( 0.00%) s.emit_struct_field("name_hash", false, |s| self.name_hash.encode(s))?; . s.emit_struct_field("normalized_pos", false, |s| self.normalized_pos.encode(s))?; 11 ( 0.00%) s.emit_struct_field("cnum", false, |s| self.cnum.encode(s)) . }) . } . } . . impl Decodable for SourceFile { 4,734 ( 0.00%) fn decode(d: &mut D) -> SourceFile { . d.read_struct(|d| { . let name: FileName = d.read_struct_field("name", |d| Decodable::decode(d)); . let src_hash: SourceFileHash = . d.read_struct_field("src_hash", |d| Decodable::decode(d)); . let start_pos: BytePos = d.read_struct_field("start_pos", |d| Decodable::decode(d)); . let end_pos: BytePos = d.read_struct_field("end_pos", |d| Decodable::decode(d)); . let lines: Vec = d.read_struct_field("lines", |d| { . let num_lines: u32 = Decodable::decode(d); 526 ( 0.00%) let mut lines = Vec::with_capacity(num_lines as usize); . . if num_lines > 0 { . // Read the number of bytes used per diff. . let bytes_per_diff: u8 = Decodable::decode(d); . . // Read the first element. . let mut line_start: BytePos = Decodable::decode(d); . lines.push(line_start); . . for _ in 1..num_lines { 865,776 ( 0.49%) let diff = match bytes_per_diff { . 1 => d.read_u8() as u32, . 2 => d.read_u16() as u32, . 4 => d.read_u32(), . _ => unreachable!(), . }; . . line_start = line_start + BytePos(diff); . -- line 1480 ---------------------------------------- -- line 1483 ---------------------------------------- . } . . lines . }); . let multibyte_chars: Vec = . d.read_struct_field("multibyte_chars", |d| Decodable::decode(d)); . let non_narrow_chars: Vec = . d.read_struct_field("non_narrow_chars", |d| Decodable::decode(d)); 1,052 ( 0.00%) let name_hash: u128 = d.read_struct_field("name_hash", |d| Decodable::decode(d)); . let normalized_pos: Vec = . d.read_struct_field("normalized_pos", |d| Decodable::decode(d)); . let cnum: CrateNum = d.read_struct_field("cnum", |d| Decodable::decode(d)); 5,786 ( 0.00%) SourceFile { 4,208 ( 0.00%) name, . start_pos, . end_pos, . src: None, 2,104 ( 0.00%) src_hash, . // Unused - the metadata decoder will construct . // a new SourceFile, filling in `external_src` properly . external_src: Lock::new(ExternalSource::Unneeded), 2,104 ( 0.00%) lines, 2,104 ( 0.00%) multibyte_chars, 2,104 ( 0.00%) non_narrow_chars, 2,104 ( 0.00%) normalized_pos, . name_hash, . cnum, . } . }) 4,734 ( 0.00%) } . } . . impl fmt::Debug for SourceFile { . fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { . write!(fmt, "SourceFile({:?})", self.name) . } . } . . impl SourceFile { 22 ( 0.00%) pub fn new( . name: FileName, . mut src: String, . start_pos: BytePos, . hash_kind: SourceFileHashAlgorithm, . ) -> Self { . // Compute the file hash before any normalization. . let src_hash = SourceFileHash::new(hash_kind, &src); 6 ( 0.00%) let normalized_pos = normalize_src(&mut src, start_pos); . . let name_hash = { . let mut hasher: StableHasher = StableHasher::new(); 4 ( 0.00%) name.hash(&mut hasher); . hasher.finish::() . }; 4 ( 0.00%) let end_pos = start_pos.to_usize() + src.len(); 6 ( 0.00%) assert!(end_pos <= u32::MAX as usize); . 24 ( 0.00%) let (lines, multibyte_chars, non_narrow_chars) = 4 ( 0.00%) analyze_source_file::analyze_source_file(&src, start_pos); . 34 ( 0.00%) SourceFile { . name, . src: Some(Lrc::new(src)), 22 ( 0.00%) src_hash, . external_src: Lock::new(ExternalSource::Unneeded), . start_pos, . end_pos: Pos::from_usize(end_pos), 8 ( 0.00%) lines, 8 ( 0.00%) multibyte_chars, 8 ( 0.00%) non_narrow_chars, 8 ( 0.00%) normalized_pos, . name_hash, . cnum: LOCAL_CRATE, . } 18 ( 0.00%) } . . /// Returns the `BytePos` of the beginning of the current line. . pub fn line_begin_pos(&self, pos: BytePos) -> BytePos { . let line_index = self.lookup_line(pos).unwrap(); . self.lines[line_index] . } . . /// Add externally loaded source. -- line 1565 ---------------------------------------- -- line 1627 ---------------------------------------- . Some(Cow::Owned(String::from(get_until_newline(src, begin)))) . } else { . None . } . } . . pub fn is_real_file(&self) -> bool { . self.name.is_real() 528 ( 0.00%) } . . pub fn is_imported(&self) -> bool { . self.src.is_none() 553 ( 0.00%) } . . pub fn count_lines(&self) -> usize { . self.lines.len() . } . . /// Finds the line containing the given position. The return value is the . /// index into the `lines` array of this `SourceFile`, not the 1-based line . /// number. If the source_file is empty or the position is located before the . /// first line, `None` is returned. . pub fn lookup_line(&self, pos: BytePos) -> Option { 33 ( 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 { 26 ( 0.00%) if self.is_empty() { . return self.start_pos..self.end_pos; . } . 16 ( 0.00%) assert!(line_index < self.lines.len()); 24 ( 0.00%) if line_index == (self.lines.len() - 1) { 6 ( 0.00%) self.lines[line_index]..self.end_pos . } else { 12 ( 0.00%) self.lines[line_index]..self.lines[line_index + 1] . } . } . . /// Returns whether or not the file contains the given `SourceMap` byte . /// position. The position one past the end of the file is considered to be . /// contained by the file. This implies that files for which `is_empty` . /// returns true still contain one byte position according to this function. . #[inline] -- line 1674 ---------------------------------------- -- line 1692 ---------------------------------------- . Err(i) if i == 0 => 0, . Err(i) => self.normalized_pos[i - 1].diff, . }; . . BytePos::from_u32(pos.0 - self.start_pos.0 + diff) . } . . /// Converts an absolute `BytePos` to a `CharPos` relative to the `SourceFile`. 2 ( 0.00%) pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos { . // The number of extra bytes due to multibyte chars in the `SourceFile`. . let mut total_extra_bytes = 0; . 6 ( 0.00%) for mbc in self.multibyte_chars.iter() { . debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos); . if mbc.pos < bpos { . // Every character is at least one byte, so we only . // count the actual extra bytes. . total_extra_bytes += mbc.bytes as u32 - 1; . // We should never see a byte position in the middle of a . // character. . assert!(bpos.to_u32() >= mbc.pos.to_u32() + mbc.bytes as u32); . } else { . break; . } . } . 12 ( 0.00%) assert!(self.start_pos.to_u32() + total_extra_bytes <= bpos.to_u32()); 10 ( 0.00%) CharPos(bpos.to_usize() - self.start_pos.to_usize() - total_extra_bytes as usize) 4 ( 0.00%) } . . /// Looks up the file's (1-based) line number and (0-based `CharPos`) column offset, for a . /// given `BytePos`. 7 ( 0.00%) pub fn lookup_file_pos(&self, pos: BytePos) -> (usize, CharPos) { 2 ( 0.00%) let chpos = self.bytepos_to_file_charpos(pos); . match self.lookup_line(pos) { . Some(a) => { . let line = a + 1; // Line numbers start at 1 1 ( 0.00%) let linebpos = self.lines[a]; 2 ( 0.00%) let linechpos = self.bytepos_to_file_charpos(linebpos); . let col = chpos - linechpos; . debug!("byte pos {:?} is on the line at byte pos {:?}", pos, linebpos); . debug!("char pos {:?} is on the line at char pos {:?}", chpos, linechpos); . debug!("byte is on line: {}", line); 1 ( 0.00%) assert!(chpos >= linechpos); . (line, col) . } . None => (0, chpos), . } 8 ( 0.00%) } . . /// Looks up the file's (1-based) line number, (0-based `CharPos`) column offset, and (0-based) . /// column offset when displayed, for a given `BytePos`. 8 ( 0.00%) pub fn lookup_file_pos_with_col_display(&self, pos: BytePos) -> (usize, CharPos, usize) { 3 ( 0.00%) let (line, col_or_chpos) = self.lookup_file_pos(pos); 2 ( 0.00%) if line > 0 { . let col = col_or_chpos; 1 ( 0.00%) let linebpos = self.lines[line - 1]; . let col_display = { . let start_width_idx = self . .non_narrow_chars . .binary_search_by_key(&linebpos, |x| x.pos()) . .unwrap_or_else(|x| x); . let end_width_idx = self . .non_narrow_chars . .binary_search_by_key(&pos, |x| x.pos()) . .unwrap_or_else(|x| x); . let special_chars = end_width_idx - start_width_idx; . let non_narrow: usize = self.non_narrow_chars[start_width_idx..end_width_idx] . .iter() . .map(|x| x.width()) . .sum(); 5 ( 0.00%) col.0 - special_chars + non_narrow . }; . (line, col, col_display) . } else { . let chpos = col_or_chpos; . let col_display = { . let end_width_idx = self . .non_narrow_chars . .binary_search_by_key(&pos, |x| x.pos()) . .unwrap_or_else(|x| x); . let non_narrow: usize = . self.non_narrow_chars[0..end_width_idx].iter().map(|x| x.width()).sum(); . chpos.0 - end_width_idx + non_narrow . }; . (0, chpos, col_display) . } 7 ( 0.00%) } . } . . /// Normalizes the source code and records the normalizations. 20 ( 0.00%) fn normalize_src(src: &mut String, start_pos: BytePos) -> Vec { . let mut normalized_pos = vec![]; . remove_bom(src, &mut normalized_pos); . normalize_newlines(src, &mut normalized_pos); . . // Offset all the positions by start_pos to match the final file positions. . for np in &mut normalized_pos { . np.pos.0 += start_pos.0; . } . . normalized_pos 18 ( 0.00%) } . . /// Removes UTF-8 BOM, if any. . fn remove_bom(src: &mut String, normalized_pos: &mut Vec) { 2 ( 0.00%) if src.starts_with('\u{feff}') { . src.drain(..3); . normalized_pos.push(NormalizedPos { pos: BytePos(0), diff: 3 }); . } . } . . /// Replaces `\r\n` with `\n` in-place in `src`. . /// . /// Returns error if there's a lone `\r` in the string. . fn normalize_newlines(src: &mut String, normalized_pos: &mut Vec) { 2 ( 0.00%) if !src.as_bytes().contains(&b'\r') { . return; . } . . // We replace `\r\n` with `\n` in-place, which doesn't break utf-8 encoding. . // While we *can* call `as_mut_vec` and do surgery on the live string . // directly, let's rather steal the contents of `src`. This makes the code . // safe even if a panic occurs. . -- line 1816 ---------------------------------------- -- line 1877 ---------------------------------------- . ( . $( . $(#[$attr:meta])* . $vis:vis struct $ident:ident($inner_vis:vis $inner_ty:ty); . )* . ) => { . $( . $(#[$attr])* 49,530 ( 0.03%) $vis struct $ident($inner_vis $inner_ty); . . impl Pos for $ident { . #[inline(always)] . fn from_usize(n: usize) -> $ident { 7,160 ( 0.00%) $ident(n as $inner_ty) . } . . #[inline(always)] . fn to_usize(&self) -> usize { 137,278 ( 0.08%) self.0 as usize . } . . #[inline(always)] . fn from_u32(n: u32) -> $ident { . $ident(n as $inner_ty) . } . . #[inline(always)] -- line 1903 ---------------------------------------- -- line 1906 ---------------------------------------- . } . } . . impl Add for $ident { . type Output = $ident; . . #[inline(always)] . fn add(self, rhs: $ident) -> $ident { 1,607,994 ( 0.92%) $ident(self.0 + rhs.0) . } . } . . impl Sub for $ident { . type Output = $ident; . . #[inline(always)] . fn sub(self, rhs: $ident) -> $ident { 1,153,256 ( 0.66%) $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 { 10,174 ( 0.01%) BytePos(d.read_u32()) . } . } . . // _____________________________________________________________________________ . // Loc, SourceFileAndLine, SourceFileAndBytePos . // . . /// A source code location used for error reporting. -- line 1962 ---------------------------------------- -- line 2079 ---------------------------------------- . /// offsets into the `SourceMap`). Instead, we hash the (file name, line, column) . /// triple, which stays the same even if the containing `SourceFile` has moved . /// within the `SourceMap`. . /// . /// Also note that we are hashing byte offsets for the column, not unicode . /// codepoint offsets. For the purpose of the hash that's sufficient. . /// Also, hashing filenames is expensive so we avoid doing it twice when the . /// span starts and ends in the same file, which is almost always the case. 322 ( 0.00%) 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; . 78 ( 0.00%) if !ctx.hash_spans() { . return; . } . 244 ( 0.00%) let span = self.data_untracked(); 46 ( 0.00%) span.ctxt.hash_stable(ctx, hasher); 138 ( 0.00%) span.parent.hash_stable(ctx, hasher); . 112 ( 0.00%) if span.is_dummy() { . Hash::hash(&TAG_INVALID_SPAN, hasher); . return; . } . 52 ( 0.00%) if let Some(parent) = span.parent { . let def_span = ctx.def_span(parent).data_untracked(); . if def_span.contains(span) { . // This span is enclosed in a definition: only hash the relative position. . Hash::hash(&TAG_RELATIVE_SPAN, hasher); . (span.lo - def_span.lo).to_u32().hash_stable(ctx, hasher); . (span.hi - def_span.lo).to_u32().hash_stable(ctx, hasher); . return; . } . } . . // If this is not an empty or invalid span, we want to hash the last . // position that belongs to it, as opposed to hashing the first . // position past it. 104 ( 0.00%) let (file, line_lo, col_lo, line_hi, col_hi) = match ctx.span_data_to_lines_and_cols(&span) . { 52 ( 0.00%) Some(pos) => pos, . None => { . Hash::hash(&TAG_INVALID_SPAN, hasher); . return; . } . }; . . Hash::hash(&TAG_VALID_SPAN, hasher); . // We truncate the stable ID hash and line and column numbers. The chances -- line 2129 ---------------------------------------- -- line 2134 ---------------------------------------- . // hash only the length, for example, then two otherwise equal spans with . // different end locations will have the same hash. This can cause a problem . // during incremental compilation wherein a previous result for a query that . // depends on the end location of a span will be incorrectly reused when the . // end location of the span it depends on has changed (see issue #74890). A . // similar analysis applies if some query depends specifically on the length . // of the span, but we only hash the end location. So hash both. . 26 ( 0.00%) let col_lo_trunc = (col_lo.0 as u64) & 0xFF; . let line_lo_trunc = ((line_lo as u64) & 0xFF_FF_FF) << 8; . let col_hi_trunc = (col_hi.0 as u64) & 0xFF << 32; . let line_hi_trunc = ((line_hi as u64) & 0xFF_FF_FF) << 40; . let col_line = col_lo_trunc | line_lo_trunc | col_hi_trunc | line_hi_trunc; 26 ( 0.00%) let len = (span.hi - span.lo).0; . Hash::hash(&col_line, hasher); . Hash::hash(&len, hasher); 368 ( 0.00%) } . } 1,328,604 ( 0.76%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/tokentrees.rs -------------------------------------------------------------------------------- Ir -- line 8 ---------------------------------------- . }; . use rustc_ast_pretty::pprust::token_to_string; . use rustc_data_structures::fx::FxHashMap; . use rustc_errors::PResult; . use rustc_span::Span; . . impl<'a> StringReader<'a> { . pub(super) fn into_token_trees(self) -> (PResult<'a, TokenStream>, Vec) { 38 ( 0.00%) let mut tt_reader = TokenTreesReader { . string_reader: self, 2 ( 0.00%) token: Token::dummy(), . open_braces: Vec::new(), . unmatched_braces: Vec::new(), . matching_delim_spans: Vec::new(), . last_unclosed_found_span: None, . last_delim_empty_block_spans: FxHashMap::default(), . matching_block_spans: Vec::new(), . }; 2 ( 0.00%) let res = tt_reader.parse_all_token_trees(); 12 ( 0.00%) (res, tt_reader.unmatched_braces) . } . } . . struct TokenTreesReader<'a> { . string_reader: StringReader<'a>, . token: Token, . /// Stack of open delimiters and their spans. Used for error message. . open_braces: Vec<(token::DelimToken, Span)>, -- line 35 ---------------------------------------- -- line 43 ---------------------------------------- . last_delim_empty_block_spans: FxHashMap, . /// Collect the spans of braces (Open, Close). Used only . /// for detecting if blocks are empty and only braces. . matching_block_spans: Vec<(Span, Span)>, . } . . impl<'a> TokenTreesReader<'a> { . // Parse a stream of tokens into a list of `TokenTree`s, up to an `Eof`. 16 ( 0.00%) fn parse_all_token_trees(&mut self) -> PResult<'a, TokenStream> { . let mut buf = TokenStreamBuilder::default(); . . self.bump(); 45,284 ( 0.03%) while self.token != token::Eof { 181,120 ( 0.10%) buf.push(self.parse_token_tree()?); . } . . Ok(buf.into_token_stream()) 18 ( 0.00%) } . . // Parse a stream of tokens into a list of `TokenTree`s, up to a `CloseDelim`. . fn parse_token_trees_until_close_delim(&mut self) -> TokenStream { . let mut buf = TokenStreamBuilder::default(); . loop { 53,748 ( 0.03%) if let token::CloseDelim(..) = self.token.kind { . return buf.into_token_stream(); . } . 91,955 ( 0.05%) match self.parse_token_tree() { 165,519 ( 0.09%) Ok(tree) => buf.push(tree), . Err(mut e) => { . e.emit(); . return buf.into_token_stream(); . } . } . } . } . 369,279 ( 0.21%) fn parse_token_tree(&mut self) -> PResult<'a, TreeAndSpacing> { 82,062 ( 0.05%) let sm = self.string_reader.sess.source_map(); . 335,347 ( 0.19%) 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) . } 8,483 ( 0.00%) token::OpenDelim(delim) => { . // The span for beginning of the delimited section 8,483 ( 0.00%) let pre_span = self.token.span; . . // Parse the open delimiter. 59,381 ( 0.03%) 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. 8,483 ( 0.00%) let tts = self.parse_token_trees_until_close_delim(); . . // Expand to cover the entire delimited token tree 42,415 ( 0.02%) let delim_span = DelimSpan::from_pair(pre_span, self.token.span); . 16,966 ( 0.01%) match self.token.kind { . // Correct delimiter. 16,966 ( 0.01%) token::CloseDelim(d) if d == delim => { . let (open_brace, open_brace_span) = self.open_braces.pop().unwrap(); 16,966 ( 0.01%) let close_brace_span = self.token.span; . 25,449 ( 0.01%) if tts.is_empty() { 12 ( 0.00%) let empty_block_span = open_brace_span.to(close_brace_span); 16 ( 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 33,932 ( 0.02%) if let (DelimToken::Brace, DelimToken::Brace) = (open_brace, delim) { . self.matching_block_spans.push((open_brace_span, close_brace_span)); . } . 8,483 ( 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. . } . _ => {} . } . 59,381 ( 0.03%) 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) . } . _ => { 162,740 ( 0.09%) let tt = TokenTree::Token(self.token.take()); . let mut spacing = self.bump(); 65,096 ( 0.04%) if !self.token.is_op() { . spacing = Alone; . } 195,288 ( 0.11%) Ok((tt, spacing)) . } . } 328,248 ( 0.19%) } . . fn bump(&mut self) -> Spacing { 403,223 ( 0.23%) let (spacing, token) = self.string_reader.next_token(); 205,173 ( 0.12%) self.token = token; . spacing . } . } . 8,483 ( 0.00%) #[derive(Default)] . struct TokenStreamBuilder { . buf: Vec, . } . . impl TokenStreamBuilder { 533,403 ( 0.30%) fn push(&mut self, (tree, joint): TreeAndSpacing) { 223,613 ( 0.13%) if let Some((TokenTree::Token(prev_token), Joint)) = self.buf.last() { 14,158 ( 0.01%) if let TokenTree::Token(token) = &tree { 26,905 ( 0.02%) if let Some(glued) = prev_token.glue(token) { . self.buf.pop(); 17,004 ( 0.01%) self.buf.push((TokenTree::Token(glued), joint)); . return; . } . } . } 198,070 ( 0.11%) self.buf.push((tree, joint)) 328,248 ( 0.19%) } . . fn into_token_stream(self) -> TokenStream { 84,848 ( 0.05%) TokenStream::new(self.buf) . } . } 161,211 ( 0.09%) -------------------------------------------------------------------------------- -- 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 {} . } . 56 ( 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 { 28 ( 0.00%) Spanned { node: t, span: sp } 25 ( 0.00%) } . . pub fn dummy_spanned(t: T) -> Spanned { . respan(DUMMY_SP, t) . } . . // _____________________________________________________________________________ . // SourceFile, MultiByteChar, FileName, FileLines . // -- line 96 ---------------------------------------- -- line 103 ---------------------------------------- . /// Read the contents of a UTF-8 file into memory. . fn read_file(&self, path: &Path) -> io::Result; . } . . /// A FileLoader that uses std::fs to load real files. . pub struct RealFileLoader; . . impl FileLoader for RealFileLoader { 8 ( 0.00%) fn file_exists(&self, path: &Path) -> bool { . path.exists() 8 ( 0.00%) } . 4 ( 0.00%) fn read_file(&self, path: &Path) -> io::Result { . fs::read_to_string(path) 6 ( 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. 46 ( 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 { 1,052 ( 0.00%) StableSourceFileId::new_from_name(&source_file.name, source_file.cnum) . } . 2,640 ( 0.00%) fn new_from_name(name: &FileName, cnum: CrateNum) -> StableSourceFileId { . let mut hasher = StableHasher::new(); 528 ( 0.00%) name.hash(&mut hasher); . StableSourceFileId { file_name_hash: hasher.finish(), cnum } 3,168 ( 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 { 10 ( 0.00%) self.file_loader.file_exists(path) . } . 22 ( 0.00%) pub fn load_file(&self, path: &Path) -> io::Result> { 8 ( 0.00%) let src = self.file_loader.read_file(path)?; . let filename = path.to_owned().into(); 36 ( 0.00%) Ok(self.new_source_file(filename, src)) 18 ( 0.00%) } . . /// Loads source file as a binary blob. . /// . /// Unlike `load_file`, guarantees that no normalization like BOM-removal . /// takes place. . pub fn load_binary_file(&self, path: &Path) -> io::Result> { . // Ideally, this should use `self.file_loader`, but it can't . // deal with binary files yet. -- line 226 ---------------------------------------- -- line 233 ---------------------------------------- . // empty string. . let text = std::str::from_utf8(&bytes).unwrap_or("").to_string(); . self.new_source_file(path.to_owned().into(), text); . Ok(bytes) . } . . // By returning a `MonotonicVec`, we ensure that consumers cannot invalidate . // any existing indices pointing into `files`. 4 ( 0.00%) pub fn files(&self) -> MappedReadGuard<'_, monotonic::MonotonicVec>> { . ReadGuard::map(self.files.borrow(), |files| &files.source_files) 12 ( 0.00%) } . 8 ( 0.00%) pub fn source_file_by_stable_id( . &self, . stable_id: StableSourceFileId, . ) -> Option> { . self.files.borrow().stable_id_to_source_file.get(&stable_id).cloned() 10 ( 0.00%) } . . fn allocate_address_space(&self, size: usize) -> Result { 528 ( 0.00%) let size = u32::try_from(size).map_err(|_| OffsetOverflowError)?; . . loop { 528 ( 0.00%) let current = self.used_address_space.load(Ordering::Relaxed); 1,584 ( 0.00%) let next = current . .checked_add(size) . // Add one so there is some space between files. This lets us distinguish . // positions in the `SourceMap`, even in the presence of zero-length files. . .and_then(|next| next.checked_add(1)) . .ok_or(OffsetOverflowError)?; . . if self . .used_address_space -- line 265 ---------------------------------------- -- line 269 ---------------------------------------- . return Ok(usize::try_from(current).unwrap()); . } . } . } . . /// Creates a new `SourceFile`. . /// If a file already exists in the `SourceMap` with the same ID, that file is returned . /// unmodified. 16 ( 0.00%) pub fn new_source_file(&self, filename: FileName, src: String) -> Lrc { 24 ( 0.00%) self.try_new_source_file(filename, src).unwrap_or_else(|OffsetOverflowError| { . eprintln!("fatal error: rustc does not support files larger than 4GB"); . crate::fatal_error::FatalError.raise() . }) 18 ( 0.00%) } . . fn try_new_source_file( . &self, . filename: FileName, . src: String, . ) -> Result, OffsetOverflowError> { . // Note that filename may not be a valid path, eg it may be `` etc, . // but this is okay because the directory determined by `path.pop()` will . // be empty, so the working directory will be used. 26 ( 0.00%) let (filename, _) = self.path_mapping.map_filename_prefix(&filename); . 4 ( 0.00%) let file_id = StableSourceFileId::new_from_name(&filename, LOCAL_CRATE); . 12 ( 0.00%) let lrc_sf = match self.source_file_by_stable_id(file_id) { . Some(lrc_sf) => lrc_sf, . None => { . let start_pos = self.allocate_address_space(src.len())?; . 12 ( 0.00%) let source_file = Lrc::new(SourceFile::new( 18 ( 0.00%) filename, 6 ( 0.00%) src, . Pos::from_usize(start_pos), . self.hash_kind, . )); . . // Let's make sure the file_id we generated above actually matches . // the ID we generate for the SourceFile we just created. . debug_assert_eq!(StableSourceFileId::new(&source_file), file_id); . -- line 311 ---------------------------------------- -- line 319 ---------------------------------------- . }; . Ok(lrc_sf) . } . . /// Allocates a new `SourceFile` representing a source file from an external . /// crate. The source code of such an "imported `SourceFile`" is not available, . /// but we still know enough to generate accurate debuginfo location . /// information for things inlined from other crates. 4,208 ( 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 { 353,216 ( 0.20%) *pos = *pos + start_pos; . } . . for mbc in &mut file_local_multibyte_chars { 797 ( 0.00%) mbc.pos = mbc.pos + start_pos; . } . . for swc in &mut file_local_non_narrow_chars { 616 ( 0.00%) *swc = *swc + start_pos; . } . . for nc in &mut file_local_normalized_pos { . nc.pos = nc.pos + start_pos; . } . 1,578 ( 0.00%) let source_file = Lrc::new(SourceFile { 4,208 ( 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 4,734 ( 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) . } . 44 ( 0.00%) pub fn is_multiline(&self, sp: Span) -> bool { 16 ( 0.00%) let lo = self.lookup_source_file_idx(sp.lo()); 16 ( 0.00%) let hi = self.lookup_source_file_idx(sp.hi()); 8 ( 0.00%) if lo != hi { . return true; . } 8 ( 0.00%) let f = (*self.files.borrow().source_files)[lo].clone(); . f.lookup_line(sp.lo()) != f.lookup_line(sp.hi()) 36 ( 0.00%) } . . #[instrument(skip(self), level = "trace")] . pub fn is_valid_span(&self, sp: Span) -> Result<(Loc, Loc), SpanLinesError> { . let lo = self.lookup_char_pos(sp.lo()); . trace!(?lo); . let hi = self.lookup_char_pos(sp.hi()); . trace!(?hi); . if lo.file.start_pos != hi.file.start_pos { -- line 483 ---------------------------------------- -- line 909 ---------------------------------------- . let sf = (*self.files.borrow().source_files)[idx].clone(); . let offset = bpos - sf.start_pos; . SourceFileAndBytePos { sf, pos: offset } . } . . // Returns the index of the `SourceFile` (in `self.files`) that contains `pos`. . // This index is guaranteed to be valid for the lifetime of this `SourceMap`, . // since `source_files` is a `MonotonicVec` 30 ( 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) 16 ( 0.00%) .unwrap_or_else(|p| p - 1) 40 ( 0.00%) } . . pub fn count_lines(&self) -> usize { . self.files().iter().fold(0, |a, f| a + f.count_lines()) . } . . pub fn generate_fn_name_span(&self, span: Span) -> Option { . let prev_span = self.span_extend_to_prev_str(span, "fn", true); . if let Ok(snippet) = self.span_to_snippet(prev_span) { -- line 931 ---------------------------------------- -- line 1053 ---------------------------------------- . let span = span.shrink_to_hi().with_hi(BytePos(span.hi().0.checked_add(1)?)); . if self.span_to_snippet(span).as_deref() != Ok(";") { . return None; . } . Some(span) . } . } . 16 ( 0.00%) #[derive(Clone)] . pub struct FilePathMapping { 8 ( 0.00%) mapping: Vec<(PathBuf, PathBuf)>, 4 ( 0.00%) filename_display_for_diagnostics: FileNameDisplayPreference, . } . . impl FilePathMapping { . 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%) } . 16 ( 0.00%) fn map_filename_prefix(&self, file: &FileName) -> (FileName, bool) { 4 ( 0.00%) match file { 4 ( 0.00%) FileName::Real(realfile) if let RealFileName::LocalPath(local_path) = realfile => { 28 ( 0.00%) let (mapped_path, mapped) = self.map_prefix(local_path.to_path_buf()); 2 ( 0.00%) let realfile = if mapped { . RealFileName::Remapped { . local_path: Some(local_path.clone()), . virtual_name: mapped_path, . } . } else { . realfile.clone() . }; 20 ( 0.00%) (FileName::Real(realfile), mapped) 8 ( 0.00%) } . FileName::Real(_) => unreachable!("attempted to remap an already remapped filename"), . other => (other.clone(), false), . } . } . } 3,433 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lexer/src/unescape.rs -------------------------------------------------------------------------------- Ir -- line 73 ---------------------------------------- . EscapeError::UnskippedWhitespaceWarning | EscapeError::MultipleSkippedLinesWarning . ) . } . } . . /// Takes a contents of a literal (without quotes) and produces a . /// sequence of escaped characters or errors. . /// Values are returned through invoking of the provided callback. 50,868 ( 0.03%) pub fn unescape_literal(literal_text: &str, mode: Mode, callback: &mut F) . where . F: FnMut(Range, Result), . { . match mode { . Mode::Char | Mode::Byte => { . let mut chars = literal_text.chars(); . let result = unescape_char_or_byte(&mut chars, mode); . // The Chars iterator moved forward. -- line 89 ---------------------------------------- -- line 91 ---------------------------------------- . } . Mode::Str | Mode::ByteStr => unescape_str_or_byte_str(literal_text, mode, callback), . // NOTE: Raw strings do not perform any explicit character escaping, here we . // only translate CRLF to LF and produce errors on bare CR. . Mode::RawStr | Mode::RawByteStr => { . unescape_raw_str_or_byte_str(literal_text, mode, callback) . } . } 22,608 ( 0.01%) } . . /// Takes a contents of a byte, byte string or raw byte string (without quotes) . /// and produces a sequence of bytes or errors. . /// Values are returned through invoking of the provided callback. . pub fn unescape_byte_literal(literal_text: &str, mode: Mode, callback: &mut F) . where . F: FnMut(Range, Result), . { -- line 107 ---------------------------------------- -- line 136 ---------------------------------------- . Byte, . ByteStr, . RawStr, . RawByteStr, . } . . impl Mode { . pub fn in_single_quotes(self) -> bool { 5,652 ( 0.00%) match self { . Mode::Char | Mode::Byte => true, . Mode::Str | Mode::ByteStr | Mode::RawStr | Mode::RawByteStr => false, . } . } . 5,652 ( 0.00%) pub fn in_double_quotes(self) -> bool { . !self.in_single_quotes() 2,826 ( 0.00%) } . . pub fn is_bytes(self) -> bool { . match self { . Mode::Byte | Mode::ByteStr | Mode::RawByteStr => true, . Mode::Char | Mode::Str | Mode::RawStr => false, . } . } . } . 495,270 ( 0.28%) fn scan_escape(first_char: char, chars: &mut Chars<'_>, mode: Mode) -> Result { 247,635 ( 0.14%) if first_char != '\\' { . // Previous character was not a slash, and we don't expect it to be . // an escape-only character. . return match first_char { . '\t' | '\n' => Err(EscapeError::EscapeOnlyChar), . '\r' => Err(EscapeError::BareCarriageReturn), . '\'' if mode.in_single_quotes() => Err(EscapeError::EscapeOnlyChar), . '"' if mode.in_double_quotes() => Err(EscapeError::EscapeOnlyChar), . _ => { 49,527 ( 0.03%) if mode.is_bytes() && !first_char.is_ascii() { . // Byte literal can't be a non-ascii character. . return Err(EscapeError::NonAsciiCharInByte); . } . Ok(first_char) . } . }; . } . -- line 180 ---------------------------------------- -- line 263 ---------------------------------------- . value = value * 16 + digit; . } . }; . } . } . _ => return Err(EscapeError::InvalidEscape), . }; . Ok(res) 594,324 ( 0.34%) } . . fn unescape_char_or_byte(chars: &mut Chars<'_>, mode: Mode) -> Result { . let first_char = chars.next().ok_or(EscapeError::ZeroChars)?; . let res = scan_escape(first_char, chars, mode)?; . if chars.next().is_some() { . return Err(EscapeError::MoreThanOneChar); . } . Ok(res) -- line 279 ---------------------------------------- -- line 280 ---------------------------------------- . } . . /// Takes a contents of a string literal (without quotes) and produces a . /// sequence of escaped characters or errors. . fn unescape_str_or_byte_str(src: &str, mode: Mode, callback: &mut F) . where . F: FnMut(Range, Result), . { 8,478 ( 0.00%) assert!(mode.in_double_quotes()); . let initial_len = src.len(); 2,826 ( 0.00%) let mut chars = src.chars(); . while let Some(first_char) = chars.next() { 247,635 ( 0.14%) let start = initial_len - chars.as_str().len() - first_char.len_utf8(); . 297,162 ( 0.17%) let unescaped_char = match first_char { . '\\' => { . let second_char = chars.clone().next(); . match second_char { . Some('\n') => { . // Rust language specification requires us to skip whitespaces . // if unescaped '\' character is followed by '\n'. . // For details see [Rust language reference] . // (https://doc.rust-lang.org/reference/tokens.html#string-literals). -- line 302 ---------------------------------------- -- line 305 ---------------------------------------- . } . _ => scan_escape(first_char, &mut chars, mode), . } . } . '\n' => Ok('\n'), . '\t' => Ok('\t'), . _ => scan_escape(first_char, &mut chars, mode), . }; 148,581 ( 0.08%) let end = initial_len - chars.as_str().len(); 643,851 ( 0.37%) callback(start..end, unescaped_char); . } . . fn skip_ascii_whitespace(chars: &mut Chars<'_>, start: usize, callback: &mut F) . where . F: FnMut(Range, Result), . { . let tail = chars.as_str(); . let first_non_space = tail -- line 322 ---------------------------------------- -- line 344 ---------------------------------------- . /// Takes a contents of a string literal (without quotes) and produces a . /// sequence of characters or errors. . /// NOTE: Raw strings do not perform any explicit character escaping, here we . /// only translate CRLF to LF and produce errors on bare CR. . fn unescape_raw_str_or_byte_str(literal_text: &str, mode: Mode, callback: &mut F) . where . F: FnMut(Range, Result), . { 5,652 ( 0.00%) assert!(mode.in_double_quotes()); . let initial_len = literal_text.len(); . . let mut chars = literal_text.chars(); . while let Some(curr) = chars.next() { . let start = initial_len - chars.as_str().len() - curr.len_utf8(); . . let result = match curr { . '\r' => Err(EscapeError::BareCarriageReturnInRawString), -- line 360 ---------------------------------------- 445,743 ( 0.25%) -------------------------------------------------------------------------------- -- 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}; . 134 ( 0.00%) #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub enum CommentKind { . Line, . Block, . } . 3 ( 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. 11,345 ( 0.01%) #[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, . } . 45 ( 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. 11,528 ( 0.01%) #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub struct Lit { . pub kind: LitKind, . pub symbol: Symbol, . pub suffix: Option, . } . . impl fmt::Display for Lit { . 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 { 12 ( 0.00%) let ident_token = Token::new(Ident(name, is_raw), span); . 4 ( 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) . } . 2,364,356 ( 1.35%) #[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, 12,744 ( 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., `{`). 8,520 ( 0.00%) OpenDelim(DelimToken), . /// A closing delimiter (e.g., `}`). 6 ( 0.00%) CloseDelim(DelimToken), . . /* Literals */ 17,031 ( 0.01%) Literal(Lit), . . /// Identifier token. . /// Do not forget about `NtIdent` when you want to match on identifiers. . /// It's recommended to use `Token::(ident,uninterpolate,uninterpolated_span)` to . /// treat regular and interpolated identifiers in the same way. 25,505 ( 0.01%) Ident(Symbol, /* is_raw */ bool), . /// Lifetime identifier token. . /// Do not forget about `NtLifetime` when you want to match on lifetime identifiers. . /// It's recommended to use `Token::(lifetime,uninterpolate,uninterpolated_span)` to . /// treat regular and interpolated lifetime identifiers in the same way. . Lifetime(Symbol), . . Interpolated(Lrc), . . /// A doc comment token. . /// `Symbol` is the doc comment's data excluding its "quotes" (`///`, `/**`, etc) . /// similarly to symbols in string literal tokens. 57 ( 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); . 180,451 ( 0.10%) #[derive(Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub struct Token { 14,176 ( 0.01%) pub kind: TokenKind, . 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`. 4 ( 0.00%) pub fn break_two_token_op(&self) -> Option<(TokenKind, TokenKind)> { 16 ( 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), 4 ( 0.00%) _ => return None, . }) 4 ( 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 { 8 ( 0.00%) matches!(self, Gt | Ge | BinOp(Shr) | BinOpEq(Shr)) 2 ( 0.00%) } . } . . impl Token { 52,354 ( 0.03%) pub fn new(kind: TokenKind, span: Span) -> Self { 182,558 ( 0.10%) Token { kind, span } 52,354 ( 0.03%) } . . /// Some token that will be thrown away later. 8,496 ( 0.00%) pub fn dummy() -> Self { . Token::new(TokenKind::Question, DUMMY_SP) 8,496 ( 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. 32,548 ( 0.02%) pub fn take(&mut self) -> Self { . mem::replace(self, Token::dummy()) 32,548 ( 0.02%) } . . /// 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 { 4 ( 0.00%) match &self.kind { . Interpolated(nt) => nt.span(), 2 ( 0.00%) _ => self.span, . } 2 ( 0.00%) } . . pub fn is_op(&self) -> bool { 97,644 ( 0.06%) !matches!( 32,548 ( 0.02%) self.kind, . OpenDelim(..) . | CloseDelim(..) . | Literal(..) . | DocComment(..) . | Ident(..) . | Lifetime(..) . | Interpolated(..) . | Eof . ) 32,548 ( 0.02%) } . . pub fn is_like_plus(&self) -> bool { 30 ( 0.00%) matches!(self.kind, BinOp(Plus) | BinOpEq(Plus)) 6 ( 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. 8 ( 0.00%) pub fn can_begin_type(&self) -> bool { 10 ( 0.00%) match self.uninterpolate().kind { 18 ( 0.00%) Ident(name, is_raw) => 2 ( 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, . } 12 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of a const param. . pub fn can_begin_const_arg(&self) -> bool { 10 ( 0.00%) match self.kind { . OpenDelim(Brace) => true, . Interpolated(ref nt) => matches!(**nt, NtExpr(..) | NtBlock(..) | NtLiteral(..)), 2 ( 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. 2 ( 0.00%) pub fn can_begin_literal_maybe_minus(&self) -> bool { 20 ( 0.00%) match self.uninterpolate().kind { . Literal(..) | BinOp(Minus) => true, 8 ( 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, . } 4 ( 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. 2 ( 0.00%) pub fn uninterpolate(&self) -> Cow<'_, Token> { 194,228 ( 0.11%) 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), . } 2 ( 0.00%) } . . /// Returns an identifier if this token is an identifier. 18,403 ( 0.01%) pub fn ident(&self) -> Option<(Ident, /* is_raw */ bool)> { . let token = self.uninterpolate(); 130,351 ( 0.07%) match token.kind { 789,635 ( 0.45%) Ident(name, is_raw) => Some((Ident::new(name, token.span), is_raw)), . _ => None, . } 152,883 ( 0.09%) } . . /// Returns a lifetime identifier if this token is a lifetime. 8 ( 0.00%) pub fn lifetime(&self) -> Option { . let token = self.uninterpolate(); 20 ( 0.00%) match token.kind { . Lifetime(name) => Some(Ident::new(name, token.span)), . _ => None, . } 56 ( 0.00%) } . . /// Returns `true` if the token is an identifier. . pub fn is_ident(&self) -> bool { . self.ident().is_some() 3 ( 0.00%) } . . /// Returns `true` if the token is a lifetime. 2 ( 0.00%) pub fn is_lifetime(&self) -> bool { . self.lifetime().is_some() 4 ( 0.00%) } . . /// Returns `true` if the token is an identifier whose name is the given . /// string slice. . pub fn is_ident_named(&self, name: Symbol) -> bool { . self.ident().map_or(false, |(ident, _)| ident.name == name) . } . . /// Returns `true` if the token is an interpolated path. . fn is_path(&self) -> bool { 28 ( 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 535 ---------------------------------------- . false . } . . /// Returns `true` if the token is either the `mut` or `const` keyword. . pub fn is_mutability(&self) -> bool { . self.is_keyword(kw::Mut) || self.is_keyword(kw::Const) . } . 2 ( 0.00%) pub fn is_qpath_start(&self) -> bool { 16 ( 0.00%) self == &Lt || self == &BinOp(Shl) . } . 28 ( 0.00%) pub fn is_path_start(&self) -> bool { 38 ( 0.00%) self == &ModSep . || self.is_qpath_start() . || self.is_path() . || self.is_path_segment_keyword() 7 ( 0.00%) || self.is_ident() && !self.is_reserved_ident() 35 ( 0.00%) } . . /// Returns `true` if the token is a given keyword, `kw`. 38,272 ( 0.02%) pub fn is_keyword(&self, kw: Symbol) -> bool { . self.is_non_raw_ident_where(|id| id.name == kw) 76,544 ( 0.04%) } . . pub fn is_path_segment_keyword(&self) -> bool { . self.is_non_raw_ident_where(Ident::is_path_segment_keyword) . } . . // Returns true for reserved identifiers used internally for elided lifetimes, . // unnamed method parameters, crate root module, error recovery etc. 2,827 ( 0.00%) pub fn is_special_ident(&self) -> bool { . self.is_non_raw_ident_where(Ident::is_special) . } . . /// Returns `true` if the token is a keyword used in the language. 2,827 ( 0.00%) pub fn is_used_keyword(&self) -> bool { . self.is_non_raw_ident_where(Ident::is_used_keyword) . } . . /// Returns `true` if the token is a keyword reserved for possible future use. 2,827 ( 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) . } . -- line 584 ---------------------------------------- -- line 591 ---------------------------------------- . matches!( . self.kind, . Literal(Lit { kind: LitKind::Integer, .. }) | Literal(Lit { kind: LitKind::Float, .. }) . ) . } . . /// Returns `true` if the token is a non-raw identifier for which `pred` holds. . pub fn is_non_raw_ident_where(&self, pred: impl FnOnce(Ident) -> bool) -> bool { 246,632 ( 0.14%) match self.ident() { 5 ( 0.00%) Some((id, false)) => pred(id), . _ => false, . } . } . 70,790 ( 0.04%) pub fn glue(&self, joint: &Token) -> Option { 35,395 ( 0.02%) let kind = match self.kind { . Eq => match joint.kind { . Eq => EqEq, . Gt => FatArrow, . _ => return None, . }, . Lt => match joint.kind { . Eq => Le, . Lt => BinOp(Shl), -- line 614 ---------------------------------------- -- line 621 ---------------------------------------- . Gt => BinOp(Shr), . Ge => BinOpEq(Shr), . _ => return None, . }, . Not => match joint.kind { . Eq => Ne, . _ => return None, . }, 11,310 ( 0.01%) BinOp(op) => match joint.kind { . Eq => BinOpEq(op), . BinOp(And) if op == And => AndAnd, . BinOp(Or) if op == Or => OrOr, 1 ( 0.00%) Gt if op == Minus => RArrow, . _ => return None, . }, . Dot => match joint.kind { . Dot => DotDot, . DotDot => DotDotDot, . _ => return None, . }, . DotDot => match joint.kind { . Dot => DotDotDot, . Eq => DotDotEq, . _ => return None, . }, 2,832 ( 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, . }; . 18,421 ( 0.01%) Some(Token::new(kind, self.span.to(joint.span))) 63,711 ( 0.04%) } . } . . impl PartialEq for Token { . fn eq(&self, rhs: &TokenKind) -> bool { 100,585 ( 0.06%) 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. 4 ( 0.00%) pub fn from_symbol( . symbol: Symbol, . edition: impl FnOnce() -> Edition, . ) -> Option { 10 ( 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, . }) 4 ( 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 ---------------------------------------- 812,060 ( 0.46%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lint/src/levels.rs -------------------------------------------------------------------------------- Ir -- line 20 ---------------------------------------- . Level, Lint, LintId, . }; . use rustc_session::parse::feature_err; . use rustc_session::Session; . use rustc_span::symbol::{sym, Symbol}; . use rustc_span::{source_map::MultiSpan, Span, DUMMY_SP}; . use tracing::debug; . 9 ( 0.00%) fn lint_levels(tcx: TyCtxt<'_>, (): ()) -> LintLevelMap { . let store = unerased_lint_store(tcx); . let levels = 6 ( 0.00%) LintLevelsBuilder::new(tcx.sess, false, &store, &tcx.resolutions(()).registered_tools); 13 ( 0.00%) let mut builder = LintLevelMapBuilder { levels, tcx }; 3 ( 0.00%) let krate = tcx.hir().krate(); . 2 ( 0.00%) builder.levels.id_to_set.reserve(krate.owners.len() + 1); . 8 ( 0.00%) let push = builder.levels.push(tcx.hir().attrs(hir::CRATE_HIR_ID), true); . builder.levels.register_id(hir::CRATE_HIR_ID); . tcx.hir().walk_toplevel_module(&mut builder); . builder.levels.pop(push); . 16 ( 0.00%) builder.levels.build_map() 9 ( 0.00%) } . . pub struct LintLevelsBuilder<'s> { . sess: &'s Session, . sets: LintLevelSets, . id_to_set: FxHashMap, . cur: LintStackIndex, . warn_about_weird_lints: bool, . store: &'s LintStore, -- line 51 ---------------------------------------- -- line 53 ---------------------------------------- . } . . pub struct BuilderPush { . prev: LintStackIndex, . pub changed: bool, . } . . impl<'s> LintLevelsBuilder<'s> { 52 ( 0.00%) pub fn new( . sess: &'s Session, . warn_about_weird_lints: bool, . store: &'s LintStore, . registered_tools: &'s RegisteredTools, . ) -> Self { 44 ( 0.00%) let mut builder = LintLevelsBuilder { . sess, 4 ( 0.00%) sets: LintLevelSets::new(), . cur: COMMAND_LINE, . id_to_set: Default::default(), . warn_about_weird_lints, . store, . registered_tools, . }; . builder.process_command_line(sess, store); 12 ( 0.00%) assert_eq!(builder.sets.list.len(), 1); . builder 36 ( 0.00%) } . . pub(crate) fn sess(&self) -> &Session { 4,254 ( 0.00%) self.sess . } . . pub(crate) fn lint_store(&self) -> &LintStore { . self.store . } . . fn process_command_line(&mut self, sess: &Session, store: &LintStore) { . let mut specs = FxHashMap::default(); 8 ( 0.00%) self.sets.lint_cap = sess.opts.lint_cap.unwrap_or(Level::Forbid); . 8 ( 0.00%) for &(ref lint_name, level) in &sess.opts.lint_opts { 40 ( 0.00%) store.check_lint_name_cmdline(sess, &lint_name, level, self.registered_tools); . let orig_level = level; 16 ( 0.00%) let lint_flag_val = Symbol::intern(lint_name); . 40 ( 0.00%) let ids = match store.find_lints(&lint_name) { 32 ( 0.00%) Ok(ids) => ids, . Err(_) => continue, // errors handled in check_lint_name_cmdline above . }; 24 ( 0.00%) for id in ids { . // ForceWarn and Forbid cannot be overriden . if let Some((Level::ForceWarn | Level::Forbid, _)) = specs.get(&id) { . continue; . } . 32 ( 0.00%) self.check_gated_lint(id, DUMMY_SP); . let src = LintLevelSource::CommandLine(lint_flag_val, orig_level); 16 ( 0.00%) specs.insert(id, (level, src)); . } . } . 32 ( 0.00%) self.cur = self.sets.list.push(LintSet { specs, parent: COMMAND_LINE }); . } . . /// Attempts to insert the `id` to `level_src` map entry. If unsuccessful . /// (e.g. if a forbid was already inserted on the same scope), then emits a . /// diagnostic with no change to `specs`. 15,565 ( 0.01%) fn insert_spec( . &mut self, . specs: &mut FxHashMap, . id: LintId, 8,490 ( 0.00%) (level, src): LevelAndSource, . ) { 7,075 ( 0.00%) let (old_level, old_src) = 9,905 ( 0.01%) self.sets.get_lint_level(id.lint, self.cur, Some(&specs), &self.sess); . // Setting to a non-forbid level is an error if the lint previously had . // a forbid level. Note that this is not necessarily true even with a . // `#[forbid(..)]` attribute present, as that is overriden by `--cap-lints`. . // . // This means that this only errors if we're truly lowering the lint . // level from forbid. 1,415 ( 0.00%) if level != Level::Forbid { 5,660 ( 0.00%) if let Level::Forbid = old_level { . // Backwards compatibility check: . // . // We used to not consider `forbid(lint_group)` . // as preventing `allow(lint)` for some lint `lint` in . // `lint_group`. For now, issue a future-compatibility . // warning for this case. . let id_name = id.lint.name_lower(); . let fcw_warning = match old_src { -- line 143 ---------------------------------------- -- line 202 ---------------------------------------- . if !fcw_warning { . return; . } . } . } . if let Level::ForceWarn = old_level { . specs.insert(id, (old_level, old_src)); . } else { 5,660 ( 0.00%) specs.insert(id, (level, src)); . } 11,320 ( 0.01%) } . . /// Pushes a list of AST lint attributes onto this context. . /// . /// This function will return a `BuilderPush` object which should be passed . /// to `pop` when this scope for the attributes provided is exited. . /// . /// This function will perform a number of tasks: . /// . /// * It'll validate all lint-related attributes in `attrs` . /// * It'll mark all lint-related attributes as used . /// * Lint levels will be updated based on the attributes provided . /// * Lint attributes are validated, e.g., a `#[forbid]` can't be switched to . /// `#[allow]` . /// . /// Don't forget to call `pop`! 22,768 ( 0.01%) pub(crate) fn push(&mut self, attrs: &[ast::Attribute], is_crate_node: bool) -> BuilderPush { . let mut specs = FxHashMap::default(); 5,692 ( 0.00%) let sess = self.sess; 2,846 ( 0.00%) let bad_attr = |span| struct_span_err!(sess, span, E0452, "malformed lint attribute input"); . for attr in attrs { 30,030 ( 0.02%) let Some(level) = Level::from_symbol(attr.name_or_empty()) else { . continue . }; . 12,735 ( 0.01%) let Some(mut metas) = attr.meta_item_list() else { . continue . }; . 1,415 ( 0.00%) if metas.is_empty() { . // FIXME (#55112): issue unused-attributes lint for `#[level()]` . continue; . } . . // Before processing the lint names, look for a reason (RFC 2383) . // at the end. . let mut reason = None; 1,415 ( 0.00%) let tail_li = &metas[metas.len() - 1]; 4,245 ( 0.00%) if let Some(item) = tail_li.meta_item() { 7,075 ( 0.00%) match item.kind { . ast::MetaItemKind::Word => {} // actual lint names handled later . ast::MetaItemKind::NameValue(ref name_value) => { . if item.path == sym::reason { . // FIXME (#55112): issue unused-attributes lint if we thereby . // don't have any lint names (`#[level(reason = "foo")]`) . if let ast::LitKind::Str(rationale, _) = name_value.kind { . if !self.sess.features_untracked().lint_reasons { . feature_err( -- line 259 ---------------------------------------- -- line 279 ---------------------------------------- . } . } . ast::MetaItemKind::List(_) => { . bad_attr(item.span).span_label(item.span, "bad attribute argument").emit(); . } . } . } . 31,130 ( 0.02%) for li in metas { 5,660 ( 0.00%) let sp = li.span(); 2,830 ( 0.00%) let mut meta_item = match li { 25,470 ( 0.01%) ast::NestedMetaItem::MetaItem(meta_item) if meta_item.is_word() => meta_item, . _ => { . let mut err = bad_attr(sp); . let mut add_label = true; . if let Some(item) = li.meta_item() { . if let ast::MetaItemKind::NameValue(_) = item.kind { . if item.path == sym::reason { . err.span_label(sp, "reason in lint attribute must come last"); . add_label = false; -- line 298 ---------------------------------------- -- line 301 ---------------------------------------- . } . if add_label { . err.span_label(sp, "bad attribute argument"); . } . err.emit(); . continue; . } . }; 4,245 ( 0.00%) let tool_ident = if meta_item.path.segments.len() > 1 { . Some(meta_item.path.segments.remove(0).ident) . } else { 1,415 ( 0.00%) None . }; 1,415 ( 0.00%) let tool_name = tool_ident.map(|ident| ident.name); 4,245 ( 0.00%) let name = pprust::path_to_string(&meta_item.path); . let lint_result = 7,075 ( 0.00%) self.store.check_lint_name(&name, tool_name, self.registered_tools); 4,245 ( 0.00%) match &lint_result { . CheckLintNameResult::Ok(ids) => { . let src = LintLevelSource::Node( . meta_item.path.segments.last().expect("empty lint name").ident.name, . sp, . reason, . ); 4,245 ( 0.00%) for &id in *ids { 7,075 ( 0.00%) self.check_gated_lint(id, attr.span); 16,980 ( 0.01%) self.insert_spec(&mut specs, id, (level, src)); . } . } . . CheckLintNameResult::Tool(result) => { . match *result { . Ok(ids) => { . let complete_name = . &format!("{}::{}", tool_ident.unwrap().name, name); -- line 335 ---------------------------------------- -- line 454 ---------------------------------------- . } . db.emit(); . }); . } . } . // If this lint was renamed, apply the new lint instead of ignoring the attribute. . // This happens outside of the match because the new lint should be applied even if . // we don't warn about the name change. 7,075 ( 0.00%) if let CheckLintNameResult::Warning(_, Some(new_name)) = lint_result { . // Ignore any errors or warnings that happen because the new name is inaccurate . // NOTE: `new_name` already includes the tool name, so we don't have to add it again. . if let CheckLintNameResult::Ok(ids) = . self.store.check_lint_name(&new_name, None, self.registered_tools) . { . let src = LintLevelSource::Node(Symbol::intern(&new_name), sp, reason); . for &id in ids { . self.check_gated_lint(id, attr.span); . self.insert_spec(&mut specs, id, (level, src)); . } . } else { . panic!("renamed lint does not exist: {}", new_name); . } . } 5,660 ( 0.00%) } . } . 5,692 ( 0.00%) if !is_crate_node { 2,824 ( 0.00%) for (id, &(level, ref src)) in specs.iter() { 4,236 ( 0.00%) if !id.lint.crate_level_only { . continue; . } . . let LintLevelSource::Node(lint_attr_name, lint_attr_span, _) = *src else { . continue . }; . . let lint = builtin::UNUSED_ATTRIBUTES; -- line 490 ---------------------------------------- -- line 505 ---------------------------------------- . db.emit(); . }, . ); . // don't set a separate error for every lint in the group . break; . } . } . 2,846 ( 0.00%) let prev = self.cur; 2,846 ( 0.00%) if !specs.is_empty() { 8,490 ( 0.00%) self.cur = self.sets.list.push(LintSet { specs, parent: prev }); . } . . BuilderPush { prev, changed: prev != self.cur } 25,614 ( 0.01%) } . . /// Checks if the lint is gated on a feature that is not enabled. 9,961 ( 0.01%) fn check_gated_lint(&self, lint_id: LintId, span: Span) { 4,269 ( 0.00%) if let Some(feature) = lint_id.lint.feature_gate { . if !self.sess.features_untracked().enabled(feature) { . feature_err( . &self.sess.parse_sess, . feature, . span, . &format!("the `{}` lint is unstable", lint_id.lint.name_lower()), . ) . .emit(); . } . } 11,384 ( 0.01%) } . . /// Called after `push` when the scope of a set of attributes are exited. . pub fn pop(&mut self, push: BuilderPush) { 2,846 ( 0.00%) self.cur = push.prev; 2,841 ( 0.00%) } . . /// Find the lint level for a lint. 4 ( 0.00%) pub fn lint_level(&self, lint: &'static Lint) -> (Level, LintLevelSource) { 44 ( 0.00%) self.sets.get_lint_level(lint, self.cur, None, self.sess) 6 ( 0.00%) } . . /// Used to emit a lint-related diagnostic based on the current state of . /// this lint context. 22 ( 0.00%) pub fn struct_lint( . &self, . lint: &'static Lint, . span: Option, . decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>), . ) { 16 ( 0.00%) let (level, src) = self.lint_level(lint); 2 ( 0.00%) struct_lint_level(self.sess, lint, level, src, span, decorate) 14 ( 0.00%) } . . /// Registers the ID provided with the current set of lints stored in . /// this context. . pub fn register_id(&mut self, id: HirId) { 1 ( 0.00%) self.id_to_set.insert(id, self.cur); . } . . pub fn build_map(self) -> LintLevelMap { 8 ( 0.00%) LintLevelMap { sets: self.sets, id_to_set: self.id_to_set } . } . } . . struct LintLevelMapBuilder<'tcx> { . levels: LintLevelsBuilder<'tcx>, . tcx: TyCtxt<'tcx>, . } . . impl LintLevelMapBuilder<'_> { . fn with_lint_attrs(&mut self, id: hir::HirId, f: F) . where . F: FnOnce(&mut Self), . { . let is_crate_hir = id == hir::CRATE_HIR_ID; 20 ( 0.00%) let attrs = self.tcx.hir().attrs(id); 24 ( 0.00%) let push = self.levels.push(attrs, is_crate_hir); 7 ( 0.00%) if push.changed { . self.levels.register_id(id); . } . f(self); . self.levels.pop(push); . } . } . . impl<'tcx> intravisit::Visitor<'tcx> for LintLevelMapBuilder<'tcx> { . type NestedFilter = nested_filter::All; . . fn nested_visit_map(&mut self) -> Self::Map { 4 ( 0.00%) self.tcx.hir() . } . . fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) { . self.with_lint_attrs(param.hir_id, |builder| { . intravisit::walk_param(builder, param); . }); . } . . fn visit_item(&mut self, it: &'tcx hir::Item<'tcx>) { 4 ( 0.00%) self.with_lint_attrs(it.hir_id(), |builder| { 12 ( 0.00%) intravisit::walk_item(builder, it); . }); . } . . fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>) { . self.with_lint_attrs(it.hir_id(), |builder| { . intravisit::walk_foreign_item(builder, it); . }) . } -- line 613 ---------------------------------------- -- line 663 ---------------------------------------- . fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) { . self.with_lint_attrs(impl_item.hir_id(), |builder| { . intravisit::walk_impl_item(builder, impl_item); . }); . } . } . . pub fn provide(providers: &mut Providers) { 2 ( 0.00%) providers.lint_levels = lint_levels; . } 24,085 ( 0.01%) -------------------------------------------------------------------------------- The following files chosen for auto-annotation could not be found: -------------------------------------------------------------------------------- ./elf/../sysdeps/x86_64/dl-machine.h ./elf/dl-lookup.c ./elf/do-rel.h ./malloc/malloc.c ./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/strcmp.S -------------------------------------------------------------------------------- Ir -------------------------------------------------------------------------------- 94,127,190 (53.57%) events annotated