-------------------------------------------------------------------------------- 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 unic_ucd_segment --edition=2018 src/lib.rs --error-format=json --json=diagnostic-rendered-ansi,artifacts,future-incompat --crate-type lib --emit=dep-info,metadata -C embed-bitcode=no -C debuginfo=2 -C metadata=08cd80d7f0f8428a -C extra-filename=-08cd80d7f0f8428a --out-dir /usr/home/liquid/tmp/.tmp2fSd7H/target/debug/deps -L dependency=/usr/home/liquid/tmp/.tmp2fSd7H/target/debug/deps --extern unic_char_property=/usr/home/liquid/tmp/.tmp2fSd7H/target/debug/deps/libunic_char_property-39f6b98a6bd1e93e.rmeta --extern unic_char_range=/usr/home/liquid/tmp/.tmp2fSd7H/target/debug/deps/libunic_char_range-b27602c142e9712a.rmeta --extern unic_ucd_version=/usr/home/liquid/tmp/.tmp2fSd7H/target/debug/deps/libunic_ucd_version-3b0948a0b985ea33.rmeta -Adeprecated -Aunknown-lints -Zincremental-verify-ich Data file: results/cgout-w-profiling-unic-ucd-segment-0.9.0-Check-Full Events recorded: Ir Events shown: Ir Event sort order: Ir Thresholds: 0.1 Include dirs: User annotated: Auto-annotation: on -------------------------------------------------------------------------------- Ir -------------------------------------------------------------------------------- 2,124,594,230 (100.0%) PROGRAM TOTALS -------------------------------------------------------------------------------- Ir file:function -------------------------------------------------------------------------------- 63,331,523 ( 2.98%) ./malloc/malloc.c:_int_free 56,006,439 ( 2.64%) ./malloc/malloc.c:_int_malloc 49,965,948 ( 2.35%) ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:__memcpy_avx_unaligned_erms 40,885,493 ( 1.92%) ./malloc/malloc.c:malloc 19,602,705 ( 0.92%) ./malloc/malloc.c:free 14,695,152 ( 0.69%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/mod.rs:::lookup_source_file_idx 12,273,513 ( 0.58%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs:::short_write_process_buffer:: 11,979,031 ( 0.56%) ./malloc/malloc.c:malloc_consolidate 10,304,970 ( 0.49%) ./elf/dl-lookup.c:_dl_lookup_symbol_x 9,962,023 ( 0.47%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::next 9,830,759 ( 0.46%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/caching_source_map_view.rs:::span_data_to_lines_and_cols 9,400,988 ( 0.44%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::bump 8,233,164 ( 0.39%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs:::short_write_process_buffer:: 8,195,311 ( 0.39%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::check 7,786,940 ( 0.37%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_target/src/abi/mod.rs:::checked_add 7,552,779 ( 0.36%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::from_key_hashed_nocheck:: 7,030,496 ( 0.33%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/mod.rs:::next_token 6,887,172 ( 0.32%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/tokenstream.rs:::next_with_spacing 6,345,978 ( 0.30%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::get:: 6,163,198 ( 0.29%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast_pretty/src/pp.rs:::advance_left 5,835,781 ( 0.27%) /usr/home/liquid/rust/worktree-benchmarking/library/std/src/sys/unix/alloc.rs:__rdl_alloc 5,790,278 ( 0.27%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/tokentrees.rs:::parse_token_tree 5,704,258 ( 0.27%) ./malloc/malloc.c:unlink_chunk.constprop.0 5,703,992 ( 0.27%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::clone 5,607,429 ( 0.26%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:>::hash_stable 5,481,121 ( 0.26%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::eq 5,450,858 ( 0.26%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/util.rs:::checked_add 5,322,145 ( 0.25%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/operand.rs:>::try_read_immediate 5,301,153 ( 0.25%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast_pretty/src/pp/ring.rs:>::pop_first 5,091,097 ( 0.24%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/string.rs:alloc::string::String::push 5,085,907 ( 0.24%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/mod.rs:::span_data_to_lines_and_cols 4,908,589 ( 0.23%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/vec_deque/mod.rs:>::push_back 4,835,295 ( 0.23%) ./elf/dl-lookup.c:do_lookup_x 4,795,676 ( 0.23%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/layout.rs:<&rustc_middle::ty::TyS as rustc_target::abi::TyAbiInterface<_>>::ty_and_layout_field::field_ty_or_layout::> 4,789,175 ( 0.23%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, (), core::hash::BuildHasherDefault>>::from_hash::>::{closure#0}> 4,586,368 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::clone 4,578,269 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_metadata/src/rmeta/encoder.rs:>::encode 4,558,656 ( 0.21%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/rustc_entry.rs:>>::rustc_entry 4,413,929 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lexer/src/lib.rs:::advance_token 4,350,205 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_dataflow/src/drop_flag_effects.rs:rustc_mir_dataflow::drop_flag_effects::on_all_children_bits::is_terminal_path 4,282,850 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::bump_with 4,232,935 ( 0.20%) ./malloc/malloc.c:realloc 4,189,947 ( 0.20%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::from_key_hashed_nocheck:: 4,165,443 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:alloc::string::String::push 4,141,271 ( 0.19%) ./elf/../sysdeps/x86_64/dl-machine.h:_dl_relocate_object 4,121,675 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe/macro_parser.rs:rustc_expand::mbe::macro_parser::parse_tt 4,019,524 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::ident 3,942,214 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs:>::hash_stable 3,894,283 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/option.rs:::advance_left 3,860,208 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/hir/map/mod.rs:::attrs 3,751,756 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/middle/region.rs:::temporary_scope 3,729,560 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/coercion.rs:::coerce 3,650,944 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_target/src/abi/mod.rs:, (), core::hash::BuildHasherDefault>>::from_hash::>::{closure#0}> 3,588,783 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_resolve/src/lib.rs:::early_resolve_ident_in_lexical_scope 3,549,440 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe/transcribe.rs:rustc_expand::mbe::transcribe::transcribe 3,517,557 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_resolve/src/imports.rs:::resolve_ident_in_module_unadjusted_ext 3,361,698 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_resolve/src/macros.rs:::early_resolve_ident_in_lexical_scope 3,341,522 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/interpret/allocation.rs:::read_scalar:: 3,324,664 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_target/src/abi/mod.rs:::scalar::> 3,302,743 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast_pretty/src/pp.rs:::scan_string 3,279,625 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/hir/map/mod.rs:::find_parent_node 3,216,449 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/layout.rs:<&rustc_middle::ty::TyS as rustc_target::abi::TyAbiInterface>>::ty_and_layout_field 3,214,542 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/span_encoding.rs:::to 3,171,378 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/library/std/src/thread/local.rs:rustc_span::SESSION_GLOBALS::FOO::__getit 3,056,125 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/mod.rs:::shallow_resolve_ty 3,033,706 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/hygiene.rs:::apply_mark 3,022,939 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_resolve/src/lib.rs:::resolve_path_with_ribs 3,003,648 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/context.rs:::lang_items 2,977,633 ( 0.14%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, (core::result::Result, rustc_middle::ty::layout::LayoutError>, rustc_query_system::dep_graph::graph::DepNodeIndex), core::hash::BuildHasherDefault>>::from_key_hashed_nocheck::> 2,926,148 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/middle/region.rs:>>::get:: 2,925,629 ( 0.14%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, (), core::hash::BuildHasherDefault>>::from_hash::, rustc_middle::ty::context::Interned>::{closure#0}> 2,903,240 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/freshen.rs:::fold_ty 2,891,736 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/context.rs:::maybe_lint_level_root_bounded 2,889,468 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:>::truncate 2,803,146 ( 0.13%) ./malloc/malloc.c:_int_realloc 2,782,327 ( 0.13%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs:>>::from_key_hashed_nocheck:: 2,765,814 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/hygiene.rs:>::hash_stable 2,753,157 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/interpret/allocation.rs:::get_bytes_internal:: 2,746,700 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_trait_selection/src/traits/query/type_op/mod.rs:> as rustc_trait_selection::traits::query::type_op::TypeOp>::fully_perform 2,741,024 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:>::truncate 2,706,714 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_build/src/thir/cx/expr.rs:::mirror_expr_inner 2,684,493 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/tokentrees.rs:::push 2,648,623 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/validity.rs: as rustc_const_eval::interpret::visitor::ValueVisitor>::visit_value 2,623,137 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/expr.rs:::collect_tokens_for_expr::<::parse_dot_or_call_expr::{closure#0}>::{closure#0} 2,610,608 ( 0.12%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>::insert::>::{closure#0}> 2,599,410 ( 0.12%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>::reserve_rehash::>::{closure#0}> 2,587,421 ( 0.12%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs:rustc_expand::mbe::macro_parser::parse_tt 2,528,000 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/vec_deque/mod.rs:::advance_left 2,527,002 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:::to 2,514,144 ( 0.12%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:::node_type_opt 2,513,545 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/hygiene.rs:::apply_mark_internal 2,511,678 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/span_encoding.rs:::early_resolve_ident_in_lexical_scope 2,510,118 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/validity.rs:>::try_visit_primitive 2,498,488 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/expr.rs:::parse_assoc_expr_with 2,441,652 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/memory.rs:>::get 2,421,698 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/undo_log.rs:::rollback_to 2,406,231 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/place.rs:>::force_allocation_maybe_sized 2,399,500 ( 0.11%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs:>, (), core::hash::BuildHasherDefault>>::from_hash::>>::{closure#0}> 2,367,758 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_serialize/src/leb128.rs:>::encode 2,364,016 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:::check 2,358,801 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lexer/src/unescape.rs:rustc_lexer::unescape::scan_escape 2,347,545 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/mod.rs:::commit_from 2,338,760 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/interpret/allocation.rs:::get_relocations:: 2,324,302 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/undo_log.rs:>::reverse 2,305,284 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_build/src/thir/cx/expr.rs:::make_mirror_unadjusted 2,269,746 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/sty.rs:::eq 2,231,310 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/mod.rs:::start_snapshot 2,228,359 ( 0.10%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, rustc_query_system::dep_graph::graph::DepNodeIndex), core::hash::BuildHasherDefault>>::from_key_hashed_nocheck:: 2,214,926 ( 0.10%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::rustc_entry 2,209,870 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/visitor.rs: as rustc_const_eval::interpret::visitor::ValueVisitor>::walk_value 2,192,072 ( 0.10%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>::reserve_rehash::>::{closure#0}> 2,189,794 ( 0.10%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs:, (), core::hash::BuildHasherDefault>>::from_hash::>::{closure#0}> 2,186,748 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/context.rs:::_intern_substs 2,176,445 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/validity.rs:>::aggregate_field_path_elem 2,172,919 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/memory.rs:>::get_global_alloc 2,171,367 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cell.rs:::attrs 2,139,033 ( 0.10%) ./elf/do-rel.h:_dl_relocate_object 2,135,566 ( 0.10%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::insert -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/string.rs -------------------------------------------------------------------------------- Ir -- line 375 ---------------------------------------- . /// ``` . /// let s = String::new(); . /// ``` . #[inline] . #[rustc_const_stable(feature = "const_string_new", since = "1.39.0")] . #[stable(feature = "rust1", since = "1.0.0")] . #[must_use] . pub const fn new() -> String { 47,118 ( 0.00%) String { vec: Vec::new() } . } . . /// Creates a new empty `String` with a particular capacity. . /// . /// `String`s have an internal buffer to hold their data. The capacity is . /// the length of that buffer, and can be queried with the [`capacity`] . /// method. This method creates an empty `String`, but one with an initial . /// buffer that can hold `capacity` bytes. This is useful when you may be -- line 391 ---------------------------------------- -- line 420 ---------------------------------------- . /// // ...but this may make the string reallocate . /// s.push('a'); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[must_use] . pub fn with_capacity(capacity: usize) -> String { 1,754 ( 0.00%) String { vec: Vec::with_capacity(capacity) } . } . . // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is . // required for this method definition, is not available. Since we don't . // require this method for testing purposes, I'll just stub it . // NB see the slice::hack module in slice.rs for more information . #[inline] . #[cfg(test)] -- line 436 ---------------------------------------- -- line 492 ---------------------------------------- . /// . /// [`from_utf8_unchecked`]: String::from_utf8_unchecked . /// [`Vec`]: crate::vec::Vec "Vec" . /// [`&str`]: prim@str "&str" . /// [`into_bytes`]: String::into_bytes . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn from_utf8(vec: Vec) -> Result { 180 ( 0.00%) match str::from_utf8(&vec) { . Ok(..) => Ok(String { vec }), . Err(e) => Err(FromUtf8Error { bytes: vec, error: e }), . } . } . . /// Converts a slice of bytes to a string, including invalid characters. . /// . /// Strings are made of bytes ([`u8`]), and a slice of bytes -- line 508 ---------------------------------------- -- line 550 ---------------------------------------- . /// let input = b"Hello \xF0\x90\x80World"; . /// let output = String::from_utf8_lossy(input); . /// . /// assert_eq!("Hello �World", output); . /// ``` . #[must_use] . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] 171 ( 0.00%) pub fn from_utf8_lossy(v: &[u8]) -> Cow<'_, str> { 190 ( 0.00%) let mut iter = lossy::Utf8Lossy::from_bytes(v).chunks(); . 95 ( 0.00%) let first_valid = if let Some(chunk) = iter.next() { . let lossy::Utf8LossyChunk { valid, broken } = chunk; 19 ( 0.00%) if broken.is_empty() { . debug_assert_eq!(valid.len(), v.len()); 19 ( 0.00%) return Cow::Borrowed(valid); . } . valid . } else { . return Cow::Borrowed(""); . }; . . const REPLACEMENT: &str = "\u{FFFD}"; . -- line 573 ---------------------------------------- -- line 578 ---------------------------------------- . for lossy::Utf8LossyChunk { valid, broken } in iter { . res.push_str(valid); . if !broken.is_empty() { . res.push_str(REPLACEMENT); . } . } . . Cow::Owned(res) 152 ( 0.00%) } . . /// Decode a UTF-16–encoded vector `v` into a `String`, returning [`Err`] . /// if `v` contains any invalid data. . /// . /// # Examples . /// . /// Basic usage: . /// -- line 594 ---------------------------------------- -- line 762 ---------------------------------------- . /// }; . /// . /// assert_eq!("💖", sparkle_heart); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . pub unsafe fn from_utf8_unchecked(bytes: Vec) -> String { 800 ( 0.00%) String { vec: bytes } . } . . /// Converts a `String` into a byte vector. . /// . /// This consumes the `String`, so we do not need to copy its contents. . /// . /// # Examples . /// -- line 778 ---------------------------------------- -- line 1138 ---------------------------------------- . /// s.push('2'); . /// s.push('3'); . /// . /// assert_eq!("abc123", s); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 3,207,798 ( 0.15%) pub fn push(&mut self, ch: char) { . match ch.len_utf8() { . 1 => self.vec.push(ch as u8), 2 ( 0.00%) _ => self.vec.extend_from_slice(ch.encode_utf8(&mut [0; 4]).as_bytes()), . } 2,673,165 ( 0.13%) } . . /// Returns a byte slice of this `String`'s contents. . /// . /// The inverse of this method is [`from_utf8`]. . /// . /// [`from_utf8`]: String::from_utf8 . /// . /// # Examples -- line 1159 ---------------------------------------- -- line 1543 ---------------------------------------- . /// let fancy_f = String::from("ƒoo"); . /// assert_eq!(fancy_f.len(), 4); . /// assert_eq!(fancy_f.chars().count(), 3); . /// ``` . #[inline] . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn len(&self) -> usize { 31 ( 0.00%) self.vec.len() . } . . /// Returns `true` if this `String` has a length of zero, and `false` otherwise. . /// . /// # Examples . /// . /// Basic usage: . /// -- line 1559 ---------------------------------------- -- line 1845 ---------------------------------------- . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . fmt::Display::fmt("invalid utf-16: lone surrogate found", f) . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl Clone for String { 1,572 ( 0.00%) fn clone(&self) -> Self { 786 ( 0.00%) String { vec: self.vec.clone() } 1,834 ( 0.00%) } . . fn clone_from(&mut self, source: &Self) { . self.vec.clone_from(&source.vec); . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl FromIterator for String { 45,540 ( 0.00%) fn from_iter>(iter: I) -> String { . let mut buf = String::new(); . buf.extend(iter); . buf 54,648 ( 0.00%) } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "string_from_iter_by_ref", since = "1.17.0")] . impl<'a> FromIterator<&'a char> for String { . fn from_iter>(iter: I) -> String { . let mut buf = String::new(); . buf.extend(iter); -- line 1877 ---------------------------------------- -- line 1937 ---------------------------------------- . } . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl Extend for String { . fn extend>(&mut self, iter: I) { 45,540 ( 0.00%) let iterator = iter.into_iter(); . let (lower_bound, _) = iterator.size_hint(); . self.reserve(lower_bound); 1,603,479 ( 0.08%) iterator.for_each(move |c| self.push(c)); . } . . #[inline] . fn extend_one(&mut self, c: char) { . self.push(c); . } . . #[inline] -- line 1956 ---------------------------------------- -- line 2128 ---------------------------------------- . fn default() -> String { . String::new() . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl fmt::Display for String { . #[inline] 103 ( 0.00%) fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 218 ( 0.00%) fmt::Display::fmt(&**self, f) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl fmt::Debug for String { . #[inline] . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . fmt::Debug::fmt(&**self, f) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl hash::Hash for String { . #[inline] . fn hash(&self, hasher: &mut H) { 1,243 ( 0.00%) (**self).hash(hasher) . } . } . . /// Implements the `+` operator for concatenating two strings. . /// . /// This consumes the `String` on the left-hand side and re-uses its buffer (growing it if . /// necessary). This is done to avoid allocating a new `String` and copying the entire contents on . /// every operation, which would lead to *O*(*n*^2) running time when building an *n*-byte string by -- line 2161 ---------------------------------------- -- line 2194 ---------------------------------------- . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl Add<&str> for String { . type Output = String; . . #[inline] . fn add(mut self, other: &str) -> String { . self.push_str(other); 2 ( 0.00%) self . } . } . . /// Implements the `+=` operator for appending to a `String`. . /// . /// This has the same behavior as the [`push_str`][String::push_str] method. . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "stringaddassign", since = "1.12.0")] -- line 2210 ---------------------------------------- -- line 2233 ---------------------------------------- . &self[..][index] . } . } . #[stable(feature = "rust1", since = "1.0.0")] . impl ops::Index> for String { . type Output = str; . . #[inline] 3,891 ( 0.00%) fn index(&self, index: ops::RangeFrom) -> &str { . &self[..][index] 3,891 ( 0.00%) } . } . #[stable(feature = "rust1", since = "1.0.0")] . impl ops::Index for String { . type Output = str; . . #[inline] . fn index(&self, _index: ops::RangeFull) -> &str { . unsafe { str::from_utf8_unchecked(&self.vec) } -- line 2251 ---------------------------------------- -- line 2388 ---------------------------------------- . impl ToString for T { . // A common guideline is to not inline generic functions. However, . // removing `#[inline]` from this method causes non-negligible regressions. . // See , the last attempt . // to try to remove it. . #[inline] . default fn to_string(&self) -> String { . let mut buf = String::new(); 150,044 ( 0.01%) let mut formatter = core::fmt::Formatter::new(&mut buf); . // Bypass format_args!() to avoid write_str with zero-length strs 37,515 ( 0.00%) fmt::Display::fmt(self, &mut formatter) . .expect("a Display implementation returned an error unexpectedly"); . buf . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "char_to_string_specialization", since = "1.46.0")] . impl ToString for char { -- line 2406 ---------------------------------------- -- line 2620 ---------------------------------------- . /// ``` . /// # use std::borrow::Cow; . /// assert_eq!(Cow::from("eggplant"), Cow::Borrowed("eggplant")); . /// ``` . /// . /// [`Borrowed`]: crate::borrow::Cow::Borrowed "borrow::Cow::Borrowed" . #[inline] . fn from(s: &'a str) -> Cow<'a, str> { 662 ( 0.00%) Cow::Borrowed(s) . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl<'a> From for Cow<'a, str> { . /// Converts a [`String`] into an [`Owned`] variant. . /// No heap allocation is performed, and the string -- line 2636 ---------------------------------------- -- line 2643 ---------------------------------------- . /// let s = "eggplant".to_string(); . /// let s2 = "eggplant".to_string(); . /// assert_eq!(Cow::from(s), Cow::<'static, str>::Owned(s2)); . /// ``` . /// . /// [`Owned`]: crate::borrow::Cow::Owned "borrow::Cow::Owned" . #[inline] . fn from(s: String) -> Cow<'a, str> { 355 ( 0.00%) Cow::Owned(s) . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "cow_from_string_ref", since = "1.28.0")] . impl<'a> From<&'a String> for Cow<'a, str> { . /// Converts a [`String`] reference into a [`Borrowed`] variant. . /// No heap allocation is performed, and the string -- line 2659 ---------------------------------------- -- line 2709 ---------------------------------------- . /// ``` . /// let s1 = String::from("hello world"); . /// let v1 = Vec::from(s1); . /// . /// for b in v1 { . /// println!("{}", b); . /// } . /// ``` 3 ( 0.00%) fn from(string: String) -> Vec { 12 ( 0.00%) string.into_bytes() 3 ( 0.00%) } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl fmt::Write for String { . #[inline] 479,040 ( 0.02%) fn write_str(&mut self, s: &str) -> fmt::Result { . self.push_str(s); . Ok(()) 419,160 ( 0.02%) } . . #[inline] 12,030 ( 0.00%) fn write_char(&mut self, c: char) -> fmt::Result { 8 ( 0.00%) self.push(c); . Ok(()) 12,030 ( 0.00%) } . } . . /// A draining iterator for `String`. . /// . /// This struct is created by the [`drain`] method on [`String`]. See its . /// documentation for more. . /// . /// [`drain`]: String::drain -- line 2743 ---------------------------------------- 75,067 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/mod.rs -------------------------------------------------------------------------------- Ir -- line 108 ---------------------------------------- . suppress_errors: bool, . }, . } . . impl RegionckMode { . /// Indicates that the MIR borrowck will repeat these region . /// checks, so we should ignore errors if NLL is (unconditionally) . /// enabled. 61 ( 0.00%) pub fn for_item_body(tcx: TyCtxt<'_>) -> Self { . // FIXME(Centril): Once we actually remove `::Migrate` also make . // this always `true` and then proceed to eliminate the dead code. 61 ( 0.00%) match tcx.borrowck_mode() { . // If we're on Migrate mode, report AST region errors . BorrowckMode::Migrate => RegionckMode::Erase { suppress_errors: false }, . . // If we're on MIR, don't report AST region errors as they should be reported by NLL . BorrowckMode::Mir => RegionckMode::Erase { suppress_errors: true }, . } 122 ( 0.00%) } . } . . /// This type contains all the things within `InferCtxt` that sit within a . /// `RefCell` and are involved with taking/rolling back snapshots. Snapshot . /// operations are hot enough that we want only one call to `borrow_mut` per . /// call to `start_snapshot` and `rollback_to`. . pub struct InferCtxtInner<'tcx> { . /// Cache for projections. This cache is snapshotted along with the infcx. -- line 134 ---------------------------------------- -- line 202 ---------------------------------------- . /// type instantiations (`ty::Infer`) to the actual opaque . /// type (`ty::Opaque`). Used during fallback to map unconstrained . /// opaque type inference variables to their corresponding . /// opaque type. . pub opaque_types_vars: FxHashMap, Ty<'tcx>>, . } . . impl<'tcx> InferCtxtInner<'tcx> { 9,285 ( 0.00%) fn new() -> InferCtxtInner<'tcx> { 63,138 ( 0.00%) InferCtxtInner { . projection_cache: Default::default(), . type_variable_storage: type_variable::TypeVariableStorage::new(), . undo_log: InferCtxtUndoLogs::default(), . const_unification_storage: ut::UnificationTableStorage::new(), . int_unification_storage: ut::UnificationTableStorage::new(), . float_unification_storage: ut::UnificationTableStorage::new(), 5,571 ( 0.00%) region_constraint_storage: Some(RegionConstraintStorage::new()), . region_obligations: vec![], . opaque_types: Default::default(), . opaque_types_vars: Default::default(), . } 11,142 ( 0.00%) } . . #[inline] . pub fn region_obligations(&self) -> &[(hir::HirId, RegionObligation<'tcx>)] { . &self.region_obligations . } . . #[inline] . pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> { 96 ( 0.00%) self.projection_cache.with_log(&mut self.undo_log) . } . . #[inline] . fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> { 312,644 ( 0.01%) self.type_variable_storage.with_log(&mut self.undo_log) . } . . #[inline] . fn int_unification_table( . &mut self, . ) -> ut::UnificationTable< . ut::InPlace< . ty::IntVid, -- line 245 ---------------------------------------- -- line 268 ---------------------------------------- . &mut self, . ) -> ut::UnificationTable< . ut::InPlace< . ty::ConstVid<'tcx>, . &mut ut::UnificationStorage>, . &mut InferCtxtUndoLogs<'tcx>, . >, . > { 4,967 ( 0.00%) self.const_unification_storage.with_log(&mut self.undo_log) . } . . #[inline] . pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> { 13,707 ( 0.00%) self.region_constraint_storage . .as_mut() . .expect("region constraints already solved") 10,361 ( 0.00%) .with_log(&mut self.undo_log) . } . } . . pub struct InferCtxt<'a, 'tcx> { . pub tcx: TyCtxt<'tcx>, . . /// The `DefId` of the item in whose context we are performing inference or typeck. . /// It is used to check whether an opaque type use is a defining use. -- line 292 ---------------------------------------- -- line 361 ---------------------------------------- . /// item we are type-checking, and just consider those names as . /// part of the root universe. So this would only get incremented . /// when we enter into a higher-ranked (`for<..>`) type or trait . /// bound. . universe: Cell, . } . . /// See the `error_reporting` module for more details. 16,648 ( 0.00%) #[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable)] . pub enum ValuePairs<'tcx> { . Types(ExpectedFound>), . Regions(ExpectedFound>), . Consts(ExpectedFound<&'tcx ty::Const<'tcx>>), . TraitRefs(ExpectedFound>), . PolyTraitRefs(ExpectedFound>), . } . -- line 377 ---------------------------------------- -- line 383 ---------------------------------------- . pub struct TypeTrace<'tcx> { . cause: ObligationCause<'tcx>, . values: ValuePairs<'tcx>, . } . . /// The origin of a `r1 <= r2` constraint. . /// . /// See `error_reporting` module for more details 14,083 ( 0.00%) #[derive(Clone, Debug)] . pub enum SubregionOrigin<'tcx> { . /// Arose from a subtyping relation 858 ( 0.00%) Subtype(Box>), . . /// When casting `&'a T` to an `&'b Trait` object, . /// relating `'a` to `'b` . RelateObjectBound(Span), . . /// Some type parameter was instantiated with the given type, . /// and that type must outlive some region. 61 ( 0.00%) RelateParamBound(Span, Ty<'tcx>, Option), . . /// The given region parameter was instantiated with a region . /// that must outlive some other region. . RelateRegionParamBound(Span), . . /// Creating a pointer `b` to contents of another reference . Reborrow(Span), . . /// Creating a pointer `b` to contents of an upvar . ReborrowUpvar(Span, ty::UpvarId), . . /// Data with type `Ty<'tcx>` was borrowed 61 ( 0.00%) DataBorrowed(Ty<'tcx>, Span), . . /// (&'a &'b T) where a >= b 70 ( 0.00%) ReferenceOutlivesReferent(Ty<'tcx>, Span), . . /// Comparing the signature and requirements of an impl method against . /// the containing trait. . CompareImplMethodObligation { span: Span, impl_item_def_id: DefId, trait_item_def_id: DefId }, . . /// Comparing the signature and requirements of an impl associated type . /// against the containing trait . CompareImplTypeObligation { span: Span, impl_item_def_id: DefId, trait_item_def_id: DefId }, -- line 426 ---------------------------------------- -- line 554 ---------------------------------------- . defining_use_anchor: Option, . } . . pub trait TyCtxtInferExt<'tcx> { . fn infer_ctxt(self) -> InferCtxtBuilder<'tcx>; . } . . impl<'tcx> TyCtxtInferExt<'tcx> for TyCtxt<'tcx> { 1,857 ( 0.00%) fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> { 5,571 ( 0.00%) InferCtxtBuilder { tcx: self, defining_use_anchor: None, fresh_typeck_results: None } 1,857 ( 0.00%) } . } . . impl<'tcx> InferCtxtBuilder<'tcx> { . /// Used only by `rustc_typeck` during body type-checking/inference, . /// will initialize `in_progress_typeck_results` with fresh `TypeckResults`. . /// Will also change the scope for opaque type defining use checks to the given owner. 1,557 ( 0.00%) pub fn with_fresh_in_progress_typeck_results(mut self, table_owner: LocalDefId) -> Self { 1,903 ( 0.00%) self.fresh_typeck_results = Some(RefCell::new(ty::TypeckResults::new(table_owner))); 865 ( 0.00%) self.with_opaque_type_inference(table_owner) 1,211 ( 0.00%) } . . /// Whenever the `InferCtxt` should be able to handle defining uses of opaque types, . /// you need to call this function. Otherwise the opaque type will be treated opaquely. . /// . /// It is only meant to be called in two places, for typeck . /// (via `with_fresh_in_progress_typeck_results`) and for the inference context used . /// in mir borrowck. 122 ( 0.00%) pub fn with_opaque_type_inference(mut self, defining_use_anchor: LocalDefId) -> Self { 61 ( 0.00%) self.defining_use_anchor = Some(defining_use_anchor); 468 ( 0.00%) self 183 ( 0.00%) } . . /// Given a canonical value `C` as a starting point, create an . /// inference context that contains each of the bound values . /// within instantiated as a fresh variable. The `f` closure is . /// invoked with the new infcx, along with the instantiated value . /// `V` and a substitution `S`. This substitution `S` maps from . /// the bound values in `C` to their instantiated values in `V` . /// (in other words, `S(C) = V`). 1,480 ( 0.00%) pub fn enter_with_canonical( . &mut self, . span: Span, . canonical: &Canonical<'tcx, T>, . f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>, T, CanonicalVarValues<'tcx>) -> R, . ) -> R . where . T: TypeFoldable<'tcx>, . { . self.enter(|infcx| { 1,828 ( 0.00%) let (value, subst) = 123 ( 0.00%) infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical); 2,704 ( 0.00%) f(infcx, value, subst) . }) 1,615 ( 0.00%) } . 13,529 ( 0.00%) pub fn enter(&mut self, f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>) -> R) -> R { 4,970 ( 0.00%) let InferCtxtBuilder { tcx, defining_use_anchor, ref fresh_typeck_results } = *self; . let in_progress_typeck_results = fresh_typeck_results.as_ref(); 80,164 ( 0.00%) f(InferCtxt { . tcx, . defining_use_anchor, . in_progress_typeck_results, 1,857 ( 0.00%) inner: RefCell::new(InferCtxtInner::new()), . lexical_region_resolutions: RefCell::new(None), . selection_cache: Default::default(), . evaluation_cache: Default::default(), . reported_trait_errors: Default::default(), . reported_closure_mismatch: Default::default(), . tainted_by_errors_flag: Cell::new(false), 1,857 ( 0.00%) err_count_on_creation: tcx.sess.err_count(), . in_snapshot: Cell::new(false), . skip_leak_check: Cell::new(false), . universe: Cell::new(ty::UniverseIndex::ROOT), . }) 14,231 ( 0.00%) } . } . . impl<'tcx, T> InferOk<'tcx, T> { . pub fn unit(self) -> InferOk<'tcx, ()> { . InferOk { value: (), obligations: self.obligations } . } . . /// Extracts `value`, registering any obligations into `fulfill_cx`. . pub fn into_value_registering_obligations( . self, . infcx: &InferCtxt<'_, 'tcx>, . fulfill_cx: &mut dyn TraitEngine<'tcx>, . ) -> T { 15 ( 0.00%) let InferOk { value, obligations } = self; 64 ( 0.00%) for obligation in obligations { . fulfill_cx.register_predicate_obligation(infcx, obligation); . } . value . } . } . . impl<'tcx> InferOk<'tcx, ()> { 15,432 ( 0.00%) pub fn into_obligations(self) -> PredicateObligations<'tcx> { 61,728 ( 0.00%) self.obligations 15,432 ( 0.00%) } . } . . #[must_use = "once you start a snapshot, you should always consume it"] . pub struct CombinedSnapshot<'a, 'tcx> { . undo_snapshot: Snapshot<'tcx>, . region_constraints_snapshot: RegionSnapshot, . universe: ty::UniverseIndex, . was_in_snapshot: bool, -- line 662 ---------------------------------------- -- line 674 ---------------------------------------- . let canonical = self.canonicalize_query((a, b), &mut OriginalQueryValues::default()); . debug!("canonical consts: {:?}", &canonical.value); . . self.tcx.try_unify_abstract_consts(canonical.value) . } . . pub fn is_in_snapshot(&self) -> bool { . self.in_snapshot.get() 12,335 ( 0.00%) } . 163,584 ( 0.01%) pub fn freshen>(&self, t: T) -> T { 184,032 ( 0.01%) t.fold_with(&mut self.freshener()) 184,032 ( 0.01%) } . . /// Returns the origin of the type variable identified by `vid`, or `None` . /// if this is not a type variable. . /// . /// No attempt is made to resolve `ty`. . pub fn type_var_origin(&'a self, ty: Ty<'tcx>) -> Option { . match *ty.kind() { . ty::Infer(ty::TyVar(vid)) => { . Some(*self.inner.borrow_mut().type_variables().var_origin(vid)) . } . _ => None, . } . } . 20,448 ( 0.00%) pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> { . freshen::TypeFreshener::new(self, false) 20,448 ( 0.00%) } . . /// Like `freshener`, but does not replace `'static` regions. 62,089 ( 0.00%) pub fn freshener_keep_static<'b>(&'b self) -> TypeFreshener<'b, 'tcx> { . freshen::TypeFreshener::new(self, true) 62,089 ( 0.00%) } . 244 ( 0.00%) pub fn unsolved_variables(&self) -> Vec> { 122 ( 0.00%) let mut inner = self.inner.borrow_mut(); 122 ( 0.00%) let mut vars: Vec> = inner . .type_variables() . .unsolved_variables() . .into_iter() . .map(|t| self.tcx.mk_ty_var(t)) . .collect(); . vars.extend( . (0..inner.int_unification_table().len()) . .map(|i| ty::IntVid { index: i as u32 }) -- line 720 ---------------------------------------- -- line 723 ---------------------------------------- . ); . vars.extend( . (0..inner.float_unification_table().len()) . .map(|i| ty::FloatVid { index: i as u32 }) . .filter(|&vid| inner.float_unification_table().probe_value(vid).is_none()) . .map(|v| self.tcx.mk_float_var(v)), . ); . vars 427 ( 0.00%) } . 50,511 ( 0.00%) fn combine_fields( . &'a self, . trace: TypeTrace<'tcx>, . param_env: ty::ParamEnv<'tcx>, . ) -> CombineFields<'a, 'tcx> { 202,044 ( 0.01%) CombineFields { . infcx: self, 505,110 ( 0.02%) trace, . cause: None, . param_env, . obligations: PredicateObligations::new(), . } 50,511 ( 0.00%) } . . /// Clear the "currently in a snapshot" flag, invoke the closure, . /// then restore the flag to its original value. This flag is a . /// debugging measure designed to detect cases where we start a . /// snapshot, create type variables, and register obligations . /// which may involve those type variables in the fulfillment cx, . /// potentially leaving "dangling type variables" behind. . /// In such cases, an assertion will fail when attempting to -- line 753 ---------------------------------------- -- line 760 ---------------------------------------- . /// before we return, this is not a problem, as there won't be any . /// escaping obligations in the main cx. In those cases, you can . /// use this function. . pub fn save_and_restore_in_snapshot_flag(&self, func: F) -> R . where . F: FnOnce(&Self) -> R, . { . let flag = self.in_snapshot.replace(false); 29,802 ( 0.00%) let result = func(self); . self.in_snapshot.set(flag); . result . } . 297,508 ( 0.01%) fn start_snapshot(&self) -> CombinedSnapshot<'a, 'tcx> { . debug!("start_snapshot()"); . . let in_snapshot = self.in_snapshot.replace(true); . . let mut inner = self.inner.borrow_mut(); . 892,524 ( 0.04%) CombinedSnapshot { . undo_snapshot: inner.undo_log.start_snapshot(), . region_constraints_snapshot: inner.unwrap_region_constraints().start_snapshot(), . universe: self.universe(), . was_in_snapshot: in_snapshot, . // Borrow typeck results "in progress" (i.e., during typeck) . // to ban writes from within a snapshot to them. 148,754 ( 0.01%) _in_progress_typeck_results: self . .in_progress_typeck_results . .map(|typeck_results| typeck_results.borrow()), . } 595,016 ( 0.03%) } . 277,189 ( 0.01%) #[instrument(skip(self, snapshot), level = "debug")] . fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) { . let CombinedSnapshot { 25,199 ( 0.00%) undo_snapshot, 25,199 ( 0.00%) region_constraints_snapshot, 25,199 ( 0.00%) universe, 25,199 ( 0.00%) was_in_snapshot, 50,398 ( 0.00%) _in_progress_typeck_results, . } = snapshot; . . self.in_snapshot.set(was_in_snapshot); . self.universe.set(universe); . . let mut inner = self.inner.borrow_mut(); 25,199 ( 0.00%) inner.rollback_to(undo_snapshot); . inner.unwrap_region_constraints().rollback_to(region_constraints_snapshot); . } . 1,853,325 ( 0.09%) #[instrument(skip(self, snapshot), level = "debug")] . fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) { . let CombinedSnapshot { 123,555 ( 0.01%) undo_snapshot, . region_constraints_snapshot: _, . universe: _, 123,555 ( 0.01%) was_in_snapshot, 247,110 ( 0.01%) _in_progress_typeck_results, . } = snapshot; . . self.in_snapshot.set(was_in_snapshot); . . self.inner.borrow_mut().commit(undo_snapshot); . } . . /// Executes `f` and commit the bindings. 4,096 ( 0.00%) #[instrument(skip(self, f), level = "debug")] 5,049 ( 0.00%) pub fn commit_unconditionally(&self, f: F) -> R . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R, . { 459 ( 0.00%) let snapshot = self.start_snapshot(); 1,590 ( 0.00%) let r = f(&snapshot); 3,213 ( 0.00%) self.commit_from(snapshot); 2,681 ( 0.00%) r . } . . /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`. 570,465 ( 0.03%) #[instrument(skip(self, f), level = "debug")] 710,041 ( 0.03%) pub fn commit_if_ok(&self, f: F) -> Result . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result, . { 161,480 ( 0.01%) let snapshot = self.start_snapshot(); 329,813 ( 0.02%) let r = f(&snapshot); . debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok()); 204,545 ( 0.01%) match r { . Ok(_) => { 861,979 ( 0.04%) self.commit_from(snapshot); . } . Err(_) => { 192,074 ( 0.01%) self.rollback_to("commit_if_ok -- error", snapshot); . } . } 999,321 ( 0.05%) r . } . . /// Execute `f` then unroll any bindings it creates. 8,129 ( 0.00%) #[instrument(skip(self, f), level = "debug")] 9,447 ( 0.00%) pub fn probe(&self, f: F) -> R . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R, . { 11,703 ( 0.00%) let snapshot = self.start_snapshot(); 4,115 ( 0.00%) let r = f(&snapshot); 53,937 ( 0.00%) self.rollback_to("probe", snapshot); 75,703 ( 0.00%) r . } . . /// If `should_skip` is true, then execute `f` then unroll any bindings it creates. . #[instrument(skip(self, f), level = "debug")] . pub fn probe_maybe_skip_leak_check(&self, should_skip: bool, f: F) -> R . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R, . { -- line 875 ---------------------------------------- -- line 884 ---------------------------------------- . r . } . . /// Scan the constraints produced since `snapshot` began and returns: . /// . /// - `None` -- if none of them involve "region outlives" constraints . /// - `Some(true)` -- if there are `'a: 'b` constraints where `'a` or `'b` is a placeholder . /// - `Some(false)` -- if there are `'a: 'b` constraints but none involve placeholders 570 ( 0.00%) pub fn region_constraints_added_in_snapshot( . &self, . snapshot: &CombinedSnapshot<'a, 'tcx>, . ) -> Option { 1,140 ( 0.00%) self.inner . .borrow_mut() . .unwrap_region_constraints() . .region_constraints_added_in_snapshot(&snapshot.undo_snapshot) 855 ( 0.00%) } . . pub fn add_given(&self, sub: ty::Region<'tcx>, sup: ty::RegionVid) { . self.inner.borrow_mut().unwrap_region_constraints().add_given(sub, sup); . } . . pub fn can_sub(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx> . where . T: at::ToTrace<'tcx>, -- line 908 ---------------------------------------- -- line 911 ---------------------------------------- . self.probe(|_| { . self.at(origin, param_env).sub(a, b).map(|InferOk { obligations: _, .. }| { . // Ignore obligations, since we are unrolling . // everything anyway. . }) . }) . } . 648 ( 0.00%) pub fn can_eq(&self, param_env: ty::ParamEnv<'tcx>, a: T, b: T) -> UnitResult<'tcx> . where . T: at::ToTrace<'tcx>, . { . let origin = &ObligationCause::dummy(); . self.probe(|_| { . self.at(origin, param_env).eq(a, b).map(|InferOk { obligations: _, .. }| { . // Ignore obligations, since we are unrolling . // everything anyway. . }) . }) 486 ( 0.00%) } . 6,330 ( 0.00%) #[instrument(skip(self), level = "debug")] . pub fn sub_regions( . &self, . origin: SubregionOrigin<'tcx>, . a: ty::Region<'tcx>, . b: ty::Region<'tcx>, . ) { 5,697 ( 0.00%) self.inner.borrow_mut().unwrap_region_constraints().make_subregion(origin, a, b); . } . . /// Require that the region `r` be equal to one of the regions in . /// the set `regions`. . #[instrument(skip(self), level = "debug")] . pub fn member_constraint( . &self, . opaque_type_def_id: DefId, -- line 947 ---------------------------------------- -- line 983 ---------------------------------------- . let subtype_predicate = predicate.map_bound(|p| ty::SubtypePredicate { . a_is_expected: false, // when coercing from `a` to `b`, `b` is expected . a: p.a, . b: p.b, . }); . self.subtype_predicate(cause, param_env, subtype_predicate) . } . 108 ( 0.00%) pub fn subtype_predicate( . &self, . cause: &ObligationCause<'tcx>, . param_env: ty::ParamEnv<'tcx>, . predicate: ty::PolySubtypePredicate<'tcx>, . ) -> Option> { . // Check for two unresolved inference variables, in which case we can . // make no progress. This is partly a micro-optimization, but it's . // also an opportunity to "sub-unify" the variables. This isn't -- line 999 ---------------------------------------- -- line 1002 ---------------------------------------- . // earlier that they are sub-unified). . // . // Note that we can just skip the binders here because . // type variables can't (at present, at . // least) capture any of the things bound by this binder. . // . // Note that this sub here is not just for diagnostics - it has semantic . // effects as well. 9 ( 0.00%) let r_a = self.shallow_resolve(predicate.skip_binder().a); 9 ( 0.00%) let r_b = self.shallow_resolve(predicate.skip_binder().b); 72 ( 0.00%) match (r_a.kind(), r_b.kind()) { 18 ( 0.00%) (&ty::Infer(ty::TyVar(a_vid)), &ty::Infer(ty::TyVar(b_vid))) => { . self.inner.borrow_mut().type_variables().sub(a_vid, b_vid); 18 ( 0.00%) return None; . } . _ => {} . } . . Some(self.commit_if_ok(|_snapshot| { . let ty::SubtypePredicate { a_is_expected, a, b } = . self.replace_bound_vars_with_placeholders(predicate); . . let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?; . . Ok(ok.unit()) . })) 81 ( 0.00%) } . 1,596 ( 0.00%) pub fn region_outlives_predicate( . &self, . cause: &traits::ObligationCause<'tcx>, . predicate: ty::PolyRegionOutlivesPredicate<'tcx>, . ) -> UnitResult<'tcx> { . self.commit_if_ok(|_snapshot| { . let ty::OutlivesPredicate(r_a, r_b) = . self.replace_bound_vars_with_placeholders(predicate); . let origin = SubregionOrigin::from_obligation_cause(cause, || { . RelateRegionParamBound(cause.span) . }); 1,330 ( 0.00%) self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b` . Ok(()) . }) 1,064 ( 0.00%) } . . /// Number of type variables created so far. . pub fn num_ty_vars(&self) -> usize { . self.inner.borrow_mut().type_variables().num_vars() . } . 39,686 ( 0.00%) pub fn next_ty_var_id(&self, origin: TypeVariableOrigin) -> TyVid { 198,430 ( 0.01%) self.inner.borrow_mut().type_variables().new_var(self.universe(), origin) 59,529 ( 0.00%) } . 38,788 ( 0.00%) pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> { 138,452 ( 0.01%) self.tcx.mk_ty_var(self.next_ty_var_id(origin)) 58,182 ( 0.00%) } . 2 ( 0.00%) pub fn next_ty_var_in_universe( . &self, . origin: TypeVariableOrigin, . universe: ty::UniverseIndex, . ) -> Ty<'tcx> { 11 ( 0.00%) let vid = self.inner.borrow_mut().type_variables().new_var(universe, origin); 1 ( 0.00%) self.tcx.mk_ty_var(vid) 3 ( 0.00%) } . . pub fn next_const_var( . &self, . ty: Ty<'tcx>, . origin: ConstVariableOrigin, . ) -> &'tcx ty::Const<'tcx> { . self.tcx.mk_const_var(self.next_const_var_id(origin), ty) . } -- line 1074 ---------------------------------------- -- line 1108 ---------------------------------------- . . pub fn next_float_var(&self) -> Ty<'tcx> { . self.tcx.mk_float_var(self.next_float_var_id()) . } . . /// Creates a fresh region variable with the next available index. . /// The variable will be created in the maximum universe created . /// thus far, allowing it to name any region created thus far. 1,646 ( 0.00%) pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> { 29,704 ( 0.00%) self.next_region_var_in_universe(origin, self.universe()) 3,292 ( 0.00%) } . . /// Creates a fresh region variable with the next available index . /// in the given universe; typically, you can use . /// `next_region_var` and just use the maximal universe. 10,638 ( 0.00%) pub fn next_region_var_in_universe( . &self, . origin: RegionVariableOrigin, . universe: ty::UniverseIndex, . ) -> ty::Region<'tcx> { . let region_var = 69,147 ( 0.00%) self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin); 26,595 ( 0.00%) self.tcx.mk_region(ty::ReVar(region_var)) 15,957 ( 0.00%) } . . /// Return the universe that the region `r` was created in. For . /// most regions (e.g., `'static`, named regions from the user, . /// etc) this is the root universe U0. For inference variables or . /// placeholders, however, it will return the universe which which . /// they are associated. 778 ( 0.00%) pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex { . self.inner.borrow_mut().unwrap_region_constraints().universe(r) 1,167 ( 0.00%) } . . /// Number of region variables created so far. 488 ( 0.00%) pub fn num_region_vars(&self) -> usize { . self.inner.borrow_mut().unwrap_region_constraints().num_region_vars() 732 ( 0.00%) } . . /// Just a convenient wrapper of `next_region_var` for using during NLL. 2,517 ( 0.00%) pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin) -> ty::Region<'tcx> { . self.next_region_var(RegionVariableOrigin::Nll(origin)) 5,034 ( 0.00%) } . . /// Just a convenient wrapper of `next_region_var` for using during NLL. . pub fn next_nll_region_var_in_universe( . &self, . origin: NllRegionVariableOrigin, . universe: ty::UniverseIndex, . ) -> ty::Region<'tcx> { . self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe) . } . 14,240 ( 0.00%) pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> { 7,668 ( 0.00%) match param.kind { . GenericParamDefKind::Lifetime => { . // Create a region inference variable for the given . // region parameter definition. 616 ( 0.00%) self.next_region_var(EarlyBoundRegion(span, param.name)).into() . } . GenericParamDefKind::Type { .. } => { . // Create a type inference variable for the given . // type parameter definition. The substitutions are . // for actual parameters that may be referred to by . // the default of this type parameter, if it exists. . // e.g., `struct Foo(...);` when . // used in a path such as `Foo::::new()` will . // use an inference variable for `C` with `[T, U]` . // as the substitutions for the default, `(T, U)`. 4,656 ( 0.00%) let ty_var_id = self.inner.borrow_mut().type_variables().new_var( . self.universe(), 5,820 ( 0.00%) TypeVariableOrigin { . kind: TypeVariableOriginKind::TypeParameterDefinition( 1,164 ( 0.00%) param.name, 1,164 ( 0.00%) Some(param.def_id), . ), . span, . }, . ); . 1,164 ( 0.00%) self.tcx.mk_ty_var(ty_var_id).into() . } . GenericParamDefKind::Const { .. } => { . let origin = ConstVariableOrigin { . kind: ConstVariableOriginKind::ConstParameterDefinition( . param.name, . param.def_id, . ), . span, -- line 1196 ---------------------------------------- -- line 1202 ---------------------------------------- . }); . self.tcx.mk_const_var(const_var_id, self.tcx.type_of(param.def_id)).into() . } . } . } . . /// Given a set of generics defined on a type or impl, returns a substitution mapping each . /// type/region parameter to a fresh inference variable. 1,848 ( 0.00%) pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> { 10,261 ( 0.00%) InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param)) 1,232 ( 0.00%) } . . /// Returns `true` if errors have been reported since this infcx was . /// created. This is sometimes used as a heuristic to skip . /// reporting errors that often occur as a result of earlier . /// errors, but where it's hard to be 100% sure (e.g., unresolved . /// inference variables, regionck errors). 122 ( 0.00%) pub fn is_tainted_by_errors(&self) -> bool { . debug!( . "is_tainted_by_errors(err_count={}, err_count_on_creation={}, \ . tainted_by_errors_flag={})", . self.tcx.sess.err_count(), . self.err_count_on_creation, . self.tainted_by_errors_flag.get() . ); . 6,787 ( 0.00%) if self.tcx.sess.err_count() > self.err_count_on_creation { . return true; // errors reported since this infcx was made . } . self.tainted_by_errors_flag.get() 183 ( 0.00%) } . . /// Set the "tainted by errors" flag to true. We call this when we . /// observe an error from a prior pass. . pub fn set_tainted_by_errors(&self) { . debug!("set_tainted_by_errors()"); . self.tainted_by_errors_flag.set(true) . } . . /// Process the region constraints and return any any errors that . /// result. After this, no more unification operations should be . /// done -- or the compiler will panic -- but it is legal to use . /// `resolve_vars_if_possible` as well as `fully_resolve`. 7,420 ( 0.00%) pub fn resolve_regions( . &self, . region_context: DefId, . outlives_env: &OutlivesEnvironment<'tcx>, . mode: RegionckMode, . ) -> Vec> { 20,140 ( 0.00%) let (var_infos, data) = { . let mut inner = self.inner.borrow_mut(); . let inner = &mut *inner; 1,060 ( 0.00%) assert!( 3,180 ( 0.00%) self.is_tainted_by_errors() || inner.region_obligations.is_empty(), . "region_obligations not empty: {:#?}", . inner.region_obligations . ); . inner . .region_constraint_storage . .take() . .expect("regions already resolved") . .with_log(&mut inner.undo_log) . .into_infos_and_data() 1,060 ( 0.00%) }; . . let region_rels = 1,060 ( 0.00%) &RegionRelations::new(self.tcx, region_context, outlives_env.free_region_map()); . 9,540 ( 0.00%) let (lexical_region_resolutions, errors) = 25,440 ( 0.00%) lexical_region_resolve::resolve(region_rels, var_infos, data, mode); . 4,240 ( 0.00%) let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions)); 1,060 ( 0.00%) assert!(old_value.is_none()); . . errors 9,540 ( 0.00%) } . . /// Process the region constraints and report any errors that . /// result. After this, no more unification operations should be . /// done -- or the compiler will panic -- but it is legal to use . /// `resolve_vars_if_possible` as well as `fully_resolve`. 10,600 ( 0.00%) pub fn resolve_regions_and_report_errors( . &self, . region_context: DefId, . outlives_env: &OutlivesEnvironment<'tcx>, . mode: RegionckMode, . ) { 2,120 ( 0.00%) let errors = self.resolve_regions(region_context, outlives_env, mode); . 3,180 ( 0.00%) if !self.is_tainted_by_errors() { . // As a heuristic, just skip reporting region errors . // altogether if other errors have been reported while . // this infcx was in use. This is totally hokey but . // otherwise we have a hard time separating legit region . // errors from silly ones. 2,120 ( 0.00%) self.report_region_errors(&errors); . } 5,300 ( 0.00%) } . . /// Obtains (and clears) the current set of region . /// constraints. The inference context is still usable: further . /// unifications will simply add new constraints. . /// . /// This method is not meant to be used with normal lexical region . /// resolution. Rather, it is used in the NLL mode as a kind of . /// interim hack: basically we run normal type-check and generate -- line 1307 ---------------------------------------- -- line 1319 ---------------------------------------- . } . . /// Gives temporary access to the region constraint data. . pub fn with_region_constraints( . &self, . op: impl FnOnce(&RegionConstraintData<'tcx>) -> R, . ) -> R { . let mut inner = self.inner.borrow_mut(); 512 ( 0.00%) op(inner.unwrap_region_constraints().data()) . } . . pub fn region_var_origin(&self, vid: ty::RegionVid) -> RegionVariableOrigin { . let mut inner = self.inner.borrow_mut(); . let inner = &mut *inner; . inner . .region_constraint_storage . .as_mut() -- line 1335 ---------------------------------------- -- line 1338 ---------------------------------------- . .var_origin(vid) . } . . /// Takes ownership of the list of variable regions. This implies . /// that all the region constraints have already been taken, and . /// hence that `resolve_regions_and_report_errors` can never be . /// called. This is used only during NLL processing to "hand off" ownership . /// of the set of region variables into the NLL region context. 305 ( 0.00%) pub fn take_region_var_origins(&self) -> VarInfos { . let mut inner = self.inner.borrow_mut(); 1,159 ( 0.00%) let (var_infos, data) = inner . .region_constraint_storage . .take() . .expect("regions already resolved") . .with_log(&mut inner.undo_log) 61 ( 0.00%) .into_infos_and_data(); 61 ( 0.00%) assert!(data.is_empty()); . var_infos 488 ( 0.00%) } . . pub fn ty_to_string(&self, t: Ty<'tcx>) -> String { . self.resolve_vars_if_possible(t).to_string() . } . . /// If `TyVar(vid)` resolves to a type, return that type. Else, return the . /// universe index of `TyVar(vid)`. 946 ( 0.00%) pub fn probe_ty_var(&self, vid: TyVid) -> Result, ty::UniverseIndex> { . use self::type_variable::TypeVariableValue; . 2,838 ( 0.00%) match self.inner.borrow_mut().type_variables().probe(vid) { . TypeVariableValue::Known { value } => Ok(value), . TypeVariableValue::Unknown { universe } => Err(universe), . } 3,311 ( 0.00%) } . . /// Resolve any type variables found in `value` -- but only one . /// level. So, if the variable `?X` is bound to some type . /// `Foo`, then this would return `Foo` (but `?Y` may . /// itself be bound to a type). . /// . /// Useful when you only need to inspect the outermost level of . /// the type and don't care about nested types (or perhaps you . /// will be resolving them as well, e.g. in a loop). . pub fn shallow_resolve(&self, value: T) -> T . where . T: TypeFoldable<'tcx>, . { 298,846 ( 0.01%) value.fold_with(&mut ShallowResolver { infcx: self }) . } . 1,280 ( 0.00%) pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid { . self.inner.borrow_mut().type_variables().root_var(var) 1,920 ( 0.00%) } . . /// Where possible, replaces type/const variables in . /// `value` with their final value. Note that region variables . /// are unaffected. If a type/const variable has not been unified, it . /// is left as is. This is an idempotent operation that does . /// not affect inference state in any way and so you can do it . /// at will. . pub fn resolve_vars_if_possible(&self, value: T) -> T . where . T: TypeFoldable<'tcx>, . { 115,071 ( 0.01%) if !value.needs_infer() { 173,943 ( 0.01%) return value; // Avoid duplicated subst-folding. . } 22,153 ( 0.00%) let mut r = resolve::OpportunisticVarResolver::new(self); 29,652 ( 0.00%) value.fold_with(&mut r) . } . . /// Returns the first unresolved variable contained in `T`. In the . /// process of visiting `T`, this will resolve (where possible) . /// type variables in `T`, but it never constructs the final, . /// resolved type, so it's more efficient than . /// `resolve_vars_if_possible()`. . pub fn unresolved_type_vars(&self, value: &T) -> Option<(Ty<'tcx>, Option)> -- line 1414 ---------------------------------------- -- line 1490 ---------------------------------------- . expected: &'tcx ty::Const<'tcx>, . actual: &'tcx ty::Const<'tcx>, . err: TypeError<'tcx>, . ) -> DiagnosticBuilder<'tcx> { . let trace = TypeTrace::consts(cause, true, expected, actual); . self.report_and_explain_type_error(trace, &err) . } . 2,718 ( 0.00%) pub fn replace_bound_vars_with_fresh_vars( . &self, . span: Span, . lbrct: LateBoundRegionConversionTime, . value: ty::Binder<'tcx, T>, . ) -> (T, BTreeMap>) . where . T: TypeFoldable<'tcx>, . { . let fld_r = 18,564 ( 0.00%) |br: ty::BoundRegion| self.next_region_var(LateBoundRegion(span, br.kind, lbrct)); . let fld_t = |_| { . self.next_ty_var(TypeVariableOrigin { . kind: TypeVariableOriginKind::MiscVariable, . span, . }) . }; . let fld_c = |_, ty| { . self.next_const_var( . ty, . ConstVariableOrigin { kind: ConstVariableOriginKind::MiscVariable, span }, . ) . }; 13,152 ( 0.00%) self.tcx.replace_bound_vars(value, fld_r, fld_t, fld_c) 1,812 ( 0.00%) } . . /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method. 72 ( 0.00%) pub fn verify_generic_bound( . &self, . origin: SubregionOrigin<'tcx>, . kind: GenericKind<'tcx>, . a: ty::Region<'tcx>, . bound: VerifyBound<'tcx>, . ) { . debug!("verify_generic_bound({:?}, {:?} <: {:?})", kind, a, bound); . 27 ( 0.00%) self.inner . .borrow_mut() . .unwrap_region_constraints() 153 ( 0.00%) .verify_generic_bound(origin, kind, a, bound); 63 ( 0.00%) } . . /// Obtains the latest type of the given closure; this may be a . /// closure in the current function, in which case its . /// `ClosureKind` may not yet be known. . pub fn closure_kind(&self, closure_substs: SubstsRef<'tcx>) -> Option { . let closure_kind_ty = closure_substs.as_closure().kind_ty(); . let closure_kind_ty = self.shallow_resolve(closure_kind_ty); . closure_kind_ty.to_opt_closure_kind() -- line 1546 ---------------------------------------- -- line 1551 ---------------------------------------- . /// its `ParamEnv`, since `FulfillmentContext` doesn't use probing. . pub fn clear_caches(&self) { . self.selection_cache.clear(); . self.evaluation_cache.clear(); . self.inner.borrow_mut().projection_cache().clear(); . } . . pub fn universe(&self) -> ty::UniverseIndex { 325,902 ( 0.02%) self.universe.get() 146,135 ( 0.01%) } . . /// Creates and return a fresh universe that extends all previous . /// universes. Updates `self.universe` to that new universe. . pub fn create_next_universe(&self) -> ty::UniverseIndex { . let u = self.universe.get().next_universe(); . self.universe.set(u); . u . } -- line 1568 ---------------------------------------- -- line 1606 ---------------------------------------- . // variables, thus we don't need to substitute back the original values. . self.tcx.const_eval_resolve(param_env_erased, unevaluated, span) . } . . /// If `typ` is a type variable of some kind, resolve it one level . /// (but do not resolve types found in the result). If `typ` is . /// not a type variable, just return it unmodified. . // FIXME(eddyb) inline into `ShallowResolver::visit_ty`. 1,154,360 ( 0.05%) fn shallow_resolve_ty(&self, typ: Ty<'tcx>) -> Ty<'tcx> { 364,856 ( 0.02%) match *typ.kind() { . ty::Infer(ty::TyVar(v)) => { . // Not entirely obvious: if `typ` is a type variable, . // it can be resolved to an int/float variable, which . // can then be recursively resolved, hence the . // recursion. Note though that we prevent type . // variables from unifying to other type variables . // directly (though they may be embedded . // structurally), and we prevent cycles in any case, . // so this recursion should always be of very limited . // depth. . // . // Note: if these two lines are combined into one we get . // dynamic borrow errors on `self.inner`. 74,964 ( 0.00%) let known = self.inner.borrow_mut().type_variables().probe(v).known(); . known.map_or(typ, |t| self.shallow_resolve_ty(t)) . } . . ty::Infer(ty::IntVar(v)) => self . .inner . .borrow_mut() . .int_unification_table() . .probe_value(v) -- line 1637 ---------------------------------------- -- line 1643 ---------------------------------------- . .borrow_mut() . .float_unification_table() . .probe_value(v) . .map(|v| v.to_type(self.tcx)) . .unwrap_or(typ), . . _ => typ, . } 1,298,655 ( 0.06%) } . . /// `ty_or_const_infer_var_changed` is equivalent to one of these two: . /// * `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`) . /// * `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`) . /// . /// However, `ty_or_const_infer_var_changed` is more efficient. It's always . /// inlined, despite being large, because it has only two call sites that . /// are extremely hot (both in `traits::fulfill`'s checking of `stalled_on` -- line 1659 ---------------------------------------- -- line 1662 ---------------------------------------- . #[inline(always)] . pub fn ty_or_const_infer_var_changed(&self, infer_var: TyOrConstInferVar<'tcx>) -> bool { . match infer_var { . TyOrConstInferVar::Ty(v) => { . use self::type_variable::TypeVariableValue; . . // If `inlined_probe` returns a `Known` value, it never equals . // `ty::Infer(ty::TyVar(v))`. 28,548 ( 0.00%) match self.inner.borrow_mut().type_variables().inlined_probe(v) { . TypeVariableValue::Unknown { .. } => false, . TypeVariableValue::Known { .. } => true, . } . } . . TyOrConstInferVar::TyInt(v) => { . // If `inlined_probe_value` returns a value it's always a . // `ty::Int(_)` or `ty::UInt(_)`, which never matches a -- line 1678 ---------------------------------------- -- line 1716 ---------------------------------------- . /// Equivalent to `ty::ConstKind::Infer(ty::InferConst::Var(_))`. . Const(ConstVid<'tcx>), . } . . impl<'tcx> TyOrConstInferVar<'tcx> { . /// Tries to extract an inference variable from a type or a constant, returns `None` . /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`) and . /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`). 958 ( 0.00%) pub fn maybe_from_generic_arg(arg: GenericArg<'tcx>) -> Option { . match arg.unpack() { . GenericArgKind::Type(ty) => Self::maybe_from_ty(ty), . GenericArgKind::Const(ct) => Self::maybe_from_const(ct), . GenericArgKind::Lifetime(_) => None, . } 958 ( 0.00%) } . . /// Tries to extract an inference variable from a type, returns `None` . /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`). 18 ( 0.00%) pub fn maybe_from_ty(ty: Ty<'tcx>) -> Option { 8,784 ( 0.00%) match *ty.kind() { 1,952 ( 0.00%) ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)), . ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)), . ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)), . _ => None, . } 18 ( 0.00%) } . . /// Tries to extract an inference variable from a constant, returns `None` . /// for constants other than `ty::ConstKind::Infer(_)` (or `InferConst::Fresh`). . pub fn maybe_from_const(ct: &'tcx ty::Const<'tcx>) -> Option { . match ct.val { . ty::ConstKind::Infer(InferConst::Var(v)) => Some(TyOrConstInferVar::Const(v)), . _ => None, . } -- line 1749 ---------------------------------------- -- line 1755 ---------------------------------------- . } . . impl<'a, 'tcx> TypeFolder<'tcx> for ShallowResolver<'a, 'tcx> { . fn tcx<'b>(&'b self) -> TyCtxt<'tcx> { . self.infcx.tcx . } . . fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> { 273,758 ( 0.01%) self.infcx.shallow_resolve_ty(ty) . } . . fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> { . if let ty::Const { val: ty::ConstKind::Infer(InferConst::Var(vid)), .. } = ct { . self.infcx . .inner . .borrow_mut() . .const_unification_table() -- line 1771 ---------------------------------------- -- line 1818 ---------------------------------------- . CompareImplTypeObligation { span, .. } => span, . } . } . . pub fn from_obligation_cause(cause: &traits::ObligationCause<'tcx>, default: F) -> Self . where . F: FnOnce() -> Self, . { 2,443 ( 0.00%) match *cause.code() { 455 ( 0.00%) traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => { 2,275 ( 0.00%) SubregionOrigin::ReferenceOutlivesReferent(ref_type, cause.span) . } . . traits::ObligationCauseCode::CompareImplMethodObligation { . impl_item_def_id, . trait_item_def_id, . } => SubregionOrigin::CompareImplMethodObligation { . span: cause.span, . impl_item_def_id, -- line 1836 ---------------------------------------- 420,637 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/context.rs -------------------------------------------------------------------------------- Ir -- line 118 ---------------------------------------- . stability: InternedSet<'tcx, attr::Stability>, . . /// `#[rustc_const_stable]` and `#[rustc_const_unstable]` attributes . const_stability: InternedSet<'tcx, attr::ConstStability>, . } . . impl<'tcx> CtxtInterners<'tcx> { . fn new(arena: &'tcx WorkerLocal>) -> CtxtInterners<'tcx> { 17 ( 0.00%) CtxtInterners { . arena, . type_: Default::default(), . type_list: Default::default(), . substs: Default::default(), . region: Default::default(), . poly_existential_predicates: Default::default(), . canonical_var_infos: Default::default(), . predicate: Default::default(), -- line 134 ---------------------------------------- -- line 143 ---------------------------------------- . stability: Default::default(), . const_stability: Default::default(), . } . } . . /// Interns a type. . #[allow(rustc::usage_of_ty_tykind)] . #[inline(never)] 749,728 ( 0.04%) fn intern_ty(&self, kind: TyKind<'tcx>) -> Ty<'tcx> { . self.type_ 468,580 ( 0.02%) .intern(kind, |kind| { 9,504 ( 0.00%) let flags = super::flags::FlagComputation::for_kind(&kind); . . let ty_struct = TyS { 19,008 ( 0.00%) kind, . flags: flags.flags, . outer_exclusive_binder: flags.outer_exclusive_binder, . }; . . Interned(self.arena.alloc(ty_struct)) . }) . .0 843,444 ( 0.04%) } . . #[inline(never)] 426,288 ( 0.02%) fn intern_predicate( . &self, . kind: Binder<'tcx, PredicateKind<'tcx>>, . ) -> &'tcx PredicateInner<'tcx> { . self.predicate 373,002 ( 0.02%) .intern(kind, |kind| { 23,070 ( 0.00%) let flags = super::flags::FlagComputation::for_predicate(kind); . . let predicate_struct = PredicateInner { . kind, . flags: flags.flags, . outer_exclusive_binder: flags.outer_exclusive_binder, . }; . . Interned(self.arena.alloc(predicate_struct)) . }) . .0 479,574 ( 0.02%) } . } . . pub struct CommonTypes<'tcx> { . pub unit: Ty<'tcx>, . pub bool: Ty<'tcx>, . pub char: Ty<'tcx>, . pub isize: Ty<'tcx>, . pub i8: Ty<'tcx>, -- line 193 ---------------------------------------- -- line 237 ---------------------------------------- . /// safely used as a key in the maps of a TypeckResults. For that to be . /// the case, the HirId must have the same `owner` as all the other IDs in . /// this table (signified by `hir_owner`). Otherwise the HirId . /// would be in a different frame of reference and using its `local_id` . /// would result in lookup errors, or worse, in silently wrong data being . /// stored/returned. . #[inline] . fn validate_hir_id_for_typeck_results(hir_owner: LocalDefId, hir_id: hir::HirId) { 453,369 ( 0.02%) if hir_id.owner != hir_owner { . invalid_hir_id_for_typeck_results(hir_owner, hir_id); . } . } . . #[cold] . #[inline(never)] . fn invalid_hir_id_for_typeck_results(hir_owner: LocalDefId, hir_id: hir::HirId) { . ty::tls::with(|tcx| { -- line 253 ---------------------------------------- -- line 261 ---------------------------------------- . } . . impl<'a, V> LocalTableInContext<'a, V> { . pub fn contains_key(&self, id: hir::HirId) -> bool { . validate_hir_id_for_typeck_results(self.hir_owner, id); . self.data.contains_key(&id.local_id) . } . 311,476 ( 0.01%) pub fn get(&self, id: hir::HirId) -> Option<&V> { 62,323 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, id); 62,323 ( 0.00%) self.data.get(&id.local_id) 249,204 ( 0.01%) } . . pub fn iter(&self) -> hash_map::Iter<'_, hir::ItemLocalId, V> { . self.data.iter() . } . } . . impl<'a, V> ::std::ops::Index for LocalTableInContext<'a, V> { . type Output = V; . 306 ( 0.00%) fn index(&self, key: hir::HirId) -> &V { . self.get(key).expect("LocalTableInContext: key not found") 204 ( 0.00%) } . } . . pub struct LocalTableInContextMut<'a, V> { . hir_owner: LocalDefId, . data: &'a mut ItemLocalMap, . } . . impl<'a, V> LocalTableInContextMut<'a, V> { -- line 292 ---------------------------------------- -- line 507 ---------------------------------------- . pub treat_byte_string_as_slice: ItemLocalSet, . . /// Contains the data for evaluating the effect of feature `capture_disjoint_fields` . /// on closure size. . pub closure_size_eval: FxHashMap>, . } . . impl<'tcx> TypeckResults<'tcx> { 1,404 ( 0.00%) pub fn new(hir_owner: LocalDefId) -> TypeckResults<'tcx> { 16,614 ( 0.00%) TypeckResults { . hir_owner, . type_dependent_defs: Default::default(), . field_indices: Default::default(), . user_provided_types: Default::default(), . user_provided_sigs: Default::default(), . node_types: Default::default(), . node_substs: Default::default(), . adjustments: Default::default(), -- line 524 ---------------------------------------- -- line 532 ---------------------------------------- . tainted_by_errors: None, . concrete_opaque_types: Default::default(), . closure_min_captures: Default::default(), . closure_fake_reads: Default::default(), . generator_interior_types: ty::Binder::dummy(Default::default()), . treat_byte_string_as_slice: Default::default(), . closure_size_eval: Default::default(), . } 1,404 ( 0.00%) } . . /// Returns the final resolution of a `QPath` in an `Expr` or `Pat` node. 76,887 ( 0.00%) pub fn qpath_res(&self, qpath: &hir::QPath<'_>, id: hir::HirId) -> Res { 51,258 ( 0.00%) match *qpath { 152,712 ( 0.01%) hir::QPath::Resolved(_, ref path) => path.res, . hir::QPath::TypeRelative(..) | hir::QPath::LangItem(..) => self . .type_dependent_def(id) 1,062 ( 0.00%) .map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)), . } 128,145 ( 0.01%) } . 58 ( 0.00%) pub fn type_dependent_defs( . &self, . ) -> LocalTableInContext<'_, Result<(DefKind, DefId), ErrorReported>> { 450 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.type_dependent_defs } 58 ( 0.00%) } . 522 ( 0.00%) pub fn type_dependent_def(&self, id: HirId) -> Option<(DefKind, DefId)> { 1,047 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, id); . self.type_dependent_defs.get(&id.local_id).cloned().and_then(|r| r.ok()) 1,044 ( 0.00%) } . 1,392 ( 0.00%) pub fn type_dependent_def_id(&self, id: HirId) -> Option { . self.type_dependent_def(id).map(|(_, def_id)| def_id) 1,392 ( 0.00%) } . 25,839 ( 0.00%) pub fn type_dependent_defs_mut( . &mut self, . ) -> LocalTableInContextMut<'_, Result<(DefKind, DefId), ErrorReported>> { 25,839 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.type_dependent_defs } 25,839 ( 0.00%) } . . pub fn field_indices(&self) -> LocalTableInContext<'_, usize> { 18,222 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.field_indices } . } . . pub fn field_indices_mut(&mut self) -> LocalTableInContextMut<'_, usize> { 54,666 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.field_indices } 27,333 ( 0.00%) } . . pub fn user_provided_types(&self) -> LocalTableInContext<'_, CanonicalUserType<'tcx>> { 20,618 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.user_provided_types } 10,309 ( 0.00%) } . . pub fn user_provided_types_mut( . &mut self, . ) -> LocalTableInContextMut<'_, CanonicalUserType<'tcx>> { 220 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.user_provided_types } 110 ( 0.00%) } . . pub fn node_types(&self) -> LocalTableInContext<'_, Ty<'tcx>> { 51,840 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.node_types } 25,920 ( 0.00%) } . . pub fn node_types_mut(&mut self) -> LocalTableInContextMut<'_, Ty<'tcx>> { 102,628 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.node_types } 51,314 ( 0.00%) } . 604,884 ( 0.03%) pub fn node_type(&self, id: hir::HirId) -> Ty<'tcx> { 100,814 ( 0.00%) self.node_type_opt(id).unwrap_or_else(|| { . bug!("node_type: no type for node `{}`", tls::with(|tcx| tcx.hir().node_to_string(id))) . }) 504,070 ( 0.02%) } . 125,706 ( 0.01%) pub fn node_type_opt(&self, id: hir::HirId) -> Option> { 125,706 ( 0.01%) validate_hir_id_for_typeck_results(self.hir_owner, id); . self.node_types.get(&id.local_id).cloned() 251,412 ( 0.01%) } . . pub fn node_substs_mut(&mut self) -> LocalTableInContextMut<'_, SubstsRef<'tcx>> { 1,226 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.node_substs } 613 ( 0.00%) } . 36,161 ( 0.00%) pub fn node_substs(&self, id: hir::HirId) -> SubstsRef<'tcx> { 36,161 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, id); . self.node_substs.get(&id.local_id).cloned().unwrap_or_else(|| InternalSubsts::empty()) 72,322 ( 0.00%) } . 25,482 ( 0.00%) pub fn node_substs_opt(&self, id: hir::HirId) -> Option> { 25,482 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, id); . self.node_substs.get(&id.local_id).cloned() 50,964 ( 0.00%) } . . // Returns the type of a pattern as a monotype. Like @expr_ty, this function . // doesn't provide type parameter substitutions. . pub fn pat_ty(&self, pat: &hir::Pat<'_>) -> Ty<'tcx> { 656 ( 0.00%) self.node_type(pat.hir_id) . } . . // Returns the type of an expression as a monotype. . // . // NB (1): This is the PRE-ADJUSTMENT TYPE for the expression. That is, in . // some cases, we insert `Adjustment` annotations such as auto-deref or . // auto-ref. The type returned by this function does not consider such . // adjustments. See `expr_ty_adjusted()` instead. . // . // NB (2): This type doesn't provide type parameter substitutions; e.g., if you . // ask for the type of "id" in "id(3)", it will return "fn(&isize) -> isize" . // instead of "fn(ty) -> T with T = isize". . pub fn expr_ty(&self, expr: &hir::Expr<'_>) -> Ty<'tcx> { 137,227 ( 0.01%) self.node_type(expr.hir_id) . } . . pub fn expr_ty_opt(&self, expr: &hir::Expr<'_>) -> Option> { 99,192 ( 0.00%) self.node_type_opt(expr.hir_id) . } . . pub fn adjustments(&self) -> LocalTableInContext<'_, Vec>> { 51,094 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.adjustments } 25,547 ( 0.00%) } . . pub fn adjustments_mut( . &mut self, . ) -> LocalTableInContextMut<'_, Vec>> { 52,690 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.adjustments } 26,345 ( 0.00%) } . 49,170 ( 0.00%) pub fn expr_adjustments(&self, expr: &hir::Expr<'_>) -> &[ty::adjustment::Adjustment<'tcx>] { 98,340 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, expr.hir_id); . self.adjustments.get(&expr.hir_id.local_id).map_or(&[], |a| &a[..]) 98,340 ( 0.00%) } . . /// Returns the type of `expr`, considering any `Adjustment` . /// entry recorded for that expression. 105 ( 0.00%) pub fn expr_ty_adjusted(&self, expr: &hir::Expr<'_>) -> Ty<'tcx> { 21 ( 0.00%) self.expr_adjustments(expr).last().map_or_else(|| self.expr_ty(expr), |adj| adj.target) . } . . pub fn expr_ty_adjusted_opt(&self, expr: &hir::Expr<'_>) -> Option> { . self.expr_adjustments(expr).last().map(|adj| adj.target).or_else(|| self.expr_ty_opt(expr)) . } . 392 ( 0.00%) pub fn is_method_call(&self, expr: &hir::Expr<'_>) -> bool { . // Only paths and method calls/overloaded operators have . // entries in type_dependent_defs, ignore the former here. 784 ( 0.00%) if let hir::ExprKind::Path(_) = expr.kind { . return false; . } . 784 ( 0.00%) matches!(self.type_dependent_defs().get(expr.hir_id), Some(Ok((DefKind::AssocFn, _)))) 784 ( 0.00%) } . 1,476 ( 0.00%) pub fn extract_binding_mode(&self, s: &Session, id: HirId, sp: Span) -> Option { . self.pat_binding_modes().get(id).copied().or_else(|| { . s.delay_span_bug(sp, "missing binding mode"); . None . }) 1,968 ( 0.00%) } . . pub fn pat_binding_modes(&self) -> LocalTableInContext<'_, BindingMode> { 1,148 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.pat_binding_modes } 328 ( 0.00%) } . . pub fn pat_binding_modes_mut(&mut self) -> LocalTableInContextMut<'_, BindingMode> { 656 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.pat_binding_modes } 328 ( 0.00%) } . . pub fn pat_adjustments(&self) -> LocalTableInContext<'_, Vec>> { 3,788 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.pat_adjustments } 1,894 ( 0.00%) } . . pub fn pat_adjustments_mut(&mut self) -> LocalTableInContextMut<'_, Vec>> { 1,226 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.pat_adjustments } 613 ( 0.00%) } . . /// For a given closure, returns the iterator of `ty::CapturedPlace`s that are captured . /// by the closure. 244 ( 0.00%) pub fn closure_min_captures_flattened( . &self, . closure_def_id: DefId, . ) -> impl Iterator> { . self.closure_min_captures . .get(&closure_def_id) . .map(|closure_min_captures| closure_min_captures.values().flat_map(|v| v.iter())) . .into_iter() . .flatten() 305 ( 0.00%) } . . pub fn closure_kind_origins(&self) -> LocalTableInContext<'_, (Span, HirPlace<'tcx>)> { 122 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.closure_kind_origins } 61 ( 0.00%) } . . pub fn closure_kind_origins_mut( . &mut self, . ) -> LocalTableInContextMut<'_, (Span, HirPlace<'tcx>)> { . LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.closure_kind_origins } . } . . pub fn liberated_fn_sigs(&self) -> LocalTableInContext<'_, ty::FnSig<'tcx>> { 326 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.liberated_fn_sigs } 163 ( 0.00%) } . . pub fn liberated_fn_sigs_mut(&mut self) -> LocalTableInContextMut<'_, ty::FnSig<'tcx>> { 204 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.liberated_fn_sigs } 102 ( 0.00%) } . . pub fn fru_field_types(&self) -> LocalTableInContext<'_, Vec>> { 122 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.fru_field_types } 61 ( 0.00%) } . . pub fn fru_field_types_mut(&mut self) -> LocalTableInContextMut<'_, Vec>> { . LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.fru_field_types } . } . . pub fn is_coercion_cast(&self, hir_id: hir::HirId) -> bool { . validate_hir_id_for_typeck_results(self.hir_owner, hir_id); . self.coercion_casts.contains(&hir_id.local_id) . } . . pub fn set_coercion_cast(&mut self, id: ItemLocalId) { . self.coercion_casts.insert(id); . } . . pub fn coercion_casts(&self) -> &ItemLocalSet { 61 ( 0.00%) &self.coercion_casts 61 ( 0.00%) } . } . . impl<'a, 'tcx> HashStable> for TypeckResults<'tcx> { . fn hash_stable(&self, hcx: &mut StableHashingContext<'a>, hasher: &mut StableHasher) { . let ty::TypeckResults { . hir_owner, . ref type_dependent_defs, . ref field_indices, -- line 764 ---------------------------------------- -- line 819 ---------------------------------------- . const START_INDEX = 0, . } . } . . /// Mapping of type annotation indices to canonical user type annotations. . pub type CanonicalUserTypeAnnotations<'tcx> = . IndexVec>; . 110 ( 0.00%) #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)] . pub struct CanonicalUserTypeAnnotation<'tcx> { . pub user_ty: CanonicalUserType<'tcx>, . pub span: Span, 55 ( 0.00%) pub inferred_ty: Ty<'tcx>, . } . . /// Canonicalized user type annotation. . pub type CanonicalUserType<'tcx> = Canonical<'tcx, UserType<'tcx>>; . . impl<'tcx> CanonicalUserType<'tcx> { . /// Returns `true` if this represents a substitution of the form `[?0, ?1, ?2]`, . /// i.e., each thing is mapped to a canonical variable with the same index. 296 ( 0.00%) pub fn is_identity(&self) -> bool { 592 ( 0.00%) match self.value { . UserType::Ty(_) => false, . UserType::TypeOf(_, user_substs) => { 296 ( 0.00%) if user_substs.user_self_ty.is_some() { . return false; . } . . iter::zip(user_substs.substs, BoundVar::new(0)..).all(|(kind, cvar)| { . match kind.unpack() { 934 ( 0.00%) GenericArgKind::Type(ty) => match ty.kind() { . ty::Bound(debruijn, b) => { . // We only allow a `ty::INNERMOST` index in substitutions. 467 ( 0.00%) assert_eq!(*debruijn, ty::INNERMOST); . cvar == b.var . } . _ => false, . }, . . GenericArgKind::Lifetime(r) => match r { . ty::ReLateBound(debruijn, br) => { . // We only allow a `ty::INNERMOST` index in substitutions. -- line 861 ---------------------------------------- -- line 872 ---------------------------------------- . cvar == b . } . _ => false, . }, . } . }) . } . } 592 ( 0.00%) } . } . . /// A user-given type annotation attached to a constant. These arise . /// from constants that are named via paths, like `Foo::::new` and . /// so forth. 330 ( 0.00%) #[derive(Copy, Clone, Debug, PartialEq, TyEncodable, TyDecodable)] 3,324 ( 0.00%) #[derive(HashStable, TypeFoldable, Lift)] . pub enum UserType<'tcx> { . Ty(Ty<'tcx>), . . /// The canonical type is the result of `type_of(def_id)` with the . /// given substitutions applied. . TypeOf(DefId, UserSubsts<'tcx>), . } . . impl<'tcx> CommonTypes<'tcx> { . fn new(interners: &CtxtInterners<'tcx>) -> CommonTypes<'tcx> { 111 ( 0.00%) let mk = |ty| interners.intern_ty(ty); . . CommonTypes { . unit: mk(Tuple(List::empty())), . bool: mk(Bool), . char: mk(Char), . never: mk(Never), . isize: mk(Int(ty::IntTy::Isize)), . i8: mk(Int(ty::IntTy::I8)), -- line 906 ---------------------------------------- -- line 921 ---------------------------------------- . . trait_object_dummy_self: mk(Infer(ty::FreshTy(0))), . } . } . } . . impl<'tcx> CommonLifetimes<'tcx> { . fn new(interners: &CtxtInterners<'tcx>) -> CommonLifetimes<'tcx> { 67 ( 0.00%) let mk = |r| interners.region.intern(r, |r| Interned(interners.arena.alloc(r))).0; . . CommonLifetimes { 5 ( 0.00%) re_root_empty: mk(RegionKind::ReEmpty(ty::UniverseIndex::ROOT)), 5 ( 0.00%) re_static: mk(RegionKind::ReStatic), 5 ( 0.00%) re_erased: mk(RegionKind::ReErased), . } . } . } . . impl<'tcx> CommonConsts<'tcx> { . fn new(interners: &CtxtInterners<'tcx>, types: &CommonTypes<'tcx>) -> CommonConsts<'tcx> { 6 ( 0.00%) let mk_const = |c| interners.const_.intern(c, |c| Interned(interners.arena.alloc(c))).0; . . CommonConsts { . unit: mk_const(ty::Const { . val: ty::ConstKind::Value(ConstValue::Scalar(Scalar::ZST)), . ty: types.unit, . }), . } . } -- line 949 ---------------------------------------- -- line 1045 ---------------------------------------- . . /// Stores memory for globals (statics/consts). . pub(crate) alloc_map: Lock>, . . output_filenames: Arc, . } . . impl<'tcx> TyCtxt<'tcx> { 2,760 ( 0.00%) pub fn typeck_opt_const_arg( . self, . def: ty::WithOptConstParam, . ) -> &'tcx TypeckResults<'tcx> { 1,104 ( 0.00%) if let Some(param_did) = def.const_param_did { . self.typeck_const_arg((def.did, param_did)) . } else { . self.typeck(def.did) . } 2,208 ( 0.00%) } . 183 ( 0.00%) pub fn alloc_steal_thir(self, thir: Thir<'tcx>) -> &'tcx Steal> { 61 ( 0.00%) self.arena.alloc(Steal::new(thir)) 244 ( 0.00%) } . 965 ( 0.00%) pub fn alloc_steal_mir(self, mir: Body<'tcx>) -> &'tcx Steal> { 193 ( 0.00%) self.arena.alloc(Steal::new(mir)) 1,351 ( 0.00%) } . 244 ( 0.00%) pub fn alloc_steal_promoted( . self, . promoted: IndexVec>, . ) -> &'tcx Steal>> { 61 ( 0.00%) self.arena.alloc(Steal::new(promoted)) 305 ( 0.00%) } . 72 ( 0.00%) pub fn alloc_adt_def( . self, . did: DefId, . kind: AdtKind, . variants: IndexVec, . repr: ReprOptions, . ) -> &'tcx ty::AdtDef { 128 ( 0.00%) self.intern_adt_def(ty::AdtDef::new(self, did, kind, variants, repr)) 32 ( 0.00%) } . . /// Allocates a read-only byte or string literal for `mir::interpret`. . pub fn allocate_bytes(self, bytes: &[u8]) -> interpret::AllocId { . // Create an allocation that just contains these bytes. . let alloc = interpret::Allocation::from_bytes_byte_aligned_immutable(bytes); . let alloc = self.intern_const_alloc(alloc); . self.create_memory_alloc(alloc) . } . . /// Returns a range of the start/end indices specified with the . /// `rustc_layout_scalar_valid_range` attribute. . // FIXME(eddyb) this is an awkward spot for this method, maybe move it? 76,928 ( 0.00%) pub fn layout_scalar_valid_range(self, def_id: DefId) -> (Bound, Bound) { 38,464 ( 0.00%) let attrs = self.get_attrs(def_id); 163,472 ( 0.01%) let get = |name| { 38,464 ( 0.00%) let attr = match attrs.iter().find(|a| a.has_name(name)) { . Some(attr) => attr, . None => return Bound::Unbounded, . }; . debug!("layout_scalar_valid_range: attr={:?}", attr); . if let Some( . &[ . ast::NestedMetaItem::Literal(ast::Lit { . kind: ast::LitKind::Int(a, _), .. -- line 1111 ---------------------------------------- -- line 1114 ---------------------------------------- . ) = attr.meta_item_list().as_deref() . { . Bound::Included(a) . } else { . self.sess . .delay_span_bug(attr.span, "invalid rustc_layout_scalar_valid_range attribute"); . Bound::Unbounded . } 192,320 ( 0.01%) }; 57,696 ( 0.00%) ( 57,696 ( 0.00%) get(sym::rustc_layout_scalar_valid_range_start), 28,848 ( 0.00%) get(sym::rustc_layout_scalar_valid_range_end), . ) 76,928 ( 0.00%) } . . pub fn lift>(self, value: T) -> Option { . value.lift_to_tcx(self) . } . . /// Creates a type context and call the closure with a `TyCtxt` reference . /// to the context. The closure enforces that the type context and any interned . /// value (types, substs, etc.) can only be used while `ty::tls` has a valid . /// reference to the context, to allow formatting values that need it. 23 ( 0.00%) pub fn create_global_ctxt( . s: &'tcx Session, . lint_store: Lrc, . arena: &'tcx WorkerLocal>, . resolutions: ty::ResolverOutputs, . krate: &'tcx hir::Crate<'tcx>, . dep_graph: DepGraph, . on_disk_cache: Option<&'tcx dyn OnDiskCache<'tcx>>, . queries: &'tcx dyn query::QueryEngine<'tcx>, . query_kinds: &'tcx [DepKindStruct], . crate_name: &str, . output_filenames: OutputFilenames, . ) -> GlobalCtxt<'tcx> { 1 ( 0.00%) let data_layout = TargetDataLayout::parse(&s.target).unwrap_or_else(|err| { . s.fatal(&err); . }); . let interners = CtxtInterners::new(arena); . let common_types = CommonTypes::new(&interners); . let common_lifetimes = CommonLifetimes::new(&interners); . let common_consts = CommonConsts::new(&interners, &common_types); . 127 ( 0.00%) GlobalCtxt { . sess: s, 6 ( 0.00%) lint_store, . arena, 2 ( 0.00%) interners, 5 ( 0.00%) dep_graph, 4 ( 0.00%) untracked_resolutions: resolutions, 2 ( 0.00%) prof: s.prof.clone(), . types: common_types, . lifetimes: common_lifetimes, . consts: common_consts, . untracked_crate: krate, . on_disk_cache, . queries, . query_caches: query::QueryCaches::default(), . query_kinds, . ty_rcache: Default::default(), . pred_rcache: Default::default(), . selection_cache: Default::default(), . evaluation_cache: Default::default(), 1 ( 0.00%) crate_name: Symbol::intern(crate_name), . data_layout, . alloc_map: Lock::new(interpret::AllocMap::new()), . output_filenames: Arc::new(output_filenames), . } 9 ( 0.00%) } . . crate fn query_kind(self, k: DepKind) -> &'tcx DepKindStruct { . &self.query_kinds[k as usize] . } . . /// Constructs a `TyKind::Error` type and registers a `delay_span_bug` to ensure it gets used. . #[track_caller] . pub fn ty_error(self) -> Ty<'tcx> { -- line 1191 ---------------------------------------- -- line 1217 ---------------------------------------- . ty: Ty<'tcx>, . span: S, . msg: &str, . ) -> &'tcx Const<'tcx> { . self.sess.delay_span_bug(span, msg); . self.mk_const(ty::Const { val: ty::ConstKind::Error(DelaySpanBugEmitted(())), ty }) . } . 21 ( 0.00%) pub fn consider_optimizing String>(self, msg: T) -> bool { 3 ( 0.00%) let cname = self.crate_name(LOCAL_CRATE); 24 ( 0.00%) self.sess.consider_optimizing(cname.as_str(), msg) 24 ( 0.00%) } . . /// Obtain all lang items of this crate and all dependencies (recursively) 1,314,096 ( 0.06%) pub fn lang_items(self) -> &'tcx rustc_hir::lang_items::LanguageItems { . self.get_lang_items(()) 1,689,552 ( 0.08%) } . . /// Obtain the given diagnostic item's `DefId`. Use `is_diagnostic_item` if you just want to . /// compare against another `DefId`, since `is_diagnostic_item` is cheaper. 21 ( 0.00%) pub fn get_diagnostic_item(self, name: Symbol) -> Option { . self.all_diagnostic_items(()).name_to_id.get(&name).copied() 24 ( 0.00%) } . . /// Obtain the diagnostic item's name 6,300 ( 0.00%) pub fn get_diagnostic_name(self, id: DefId) -> Option { . self.diagnostic_items(id.krate).id_to_name.get(&id).copied() 7,200 ( 0.00%) } . . /// Check whether the diagnostic item with the given `name` has the given `DefId`. 2,884 ( 0.00%) pub fn is_diagnostic_item(self, name: Symbol, did: DefId) -> bool { . self.diagnostic_items(did.krate).name_to_id.get(&name) == Some(&did) 3,296 ( 0.00%) } . 1,687 ( 0.00%) pub fn stability(self) -> &'tcx stability::Index<'tcx> { . self.stability_index(()) 2,169 ( 0.00%) } . 413,154 ( 0.02%) pub fn features(self) -> &'tcx rustc_feature::Features { . self.features_query(()) 472,176 ( 0.02%) } . . pub fn def_key(self, id: DefId) -> rustc_hir::definitions::DefKey { . // Accessing the DefKey is ok, since it is part of DefPathHash. 34,667 ( 0.00%) if let Some(id) = id.as_local() { . self.untracked_resolutions.definitions.def_key(id) . } else { 2,350 ( 0.00%) self.untracked_resolutions.cstore.def_key(id) . } . } . . /// Converts a `DefId` into its fully expanded `DefPath` (every . /// `DefId` is really just an interned `DefPath`). . /// . /// Note that if `id` is not local to this crate, the result will . /// be a non-local `DefPath`. -- line 1272 ---------------------------------------- -- line 1277 ---------------------------------------- . } else { . self.untracked_resolutions.cstore.def_path(id) . } . } . . #[inline] . pub fn def_path_hash(self, def_id: DefId) -> rustc_hir::definitions::DefPathHash { . // Accessing the DefPathHash is ok, it is incr. comp. stable. 756 ( 0.00%) if let Some(def_id) = def_id.as_local() { . self.untracked_resolutions.definitions.def_path_hash(def_id) . } else { 176 ( 0.00%) self.untracked_resolutions.cstore.def_path_hash(def_id) . } . } . . #[inline] . pub fn stable_crate_id(self, crate_num: CrateNum) -> StableCrateId { . if crate_num == LOCAL_CRATE { . self.sess.local_stable_crate_id() . } else { -- line 1296 ---------------------------------------- -- line 1353 ---------------------------------------- . &(format!("{:08x}", stable_crate_id.to_u64()))[..4], . self.def_path(def_id).to_string_no_crate_verbose() . ) . } . . /// Note that this is *untracked* and should only be used within the query . /// system if the result is otherwise tracked through queries . pub fn cstore_untracked(self) -> &'tcx ty::CrateStoreDyn { 10,562 ( 0.00%) &*self.untracked_resolutions.cstore 5,281 ( 0.00%) } . . /// Note that this is *untracked* and should only be used within the query . /// system if the result is otherwise tracked through queries . pub fn definitions_untracked(self) -> &'tcx hir::definitions::Definitions { . &self.untracked_resolutions.definitions . } . . #[inline(always)] . pub fn create_stable_hashing_context(self) -> StableHashingContext<'tcx> { 11 ( 0.00%) let resolutions = &self.gcx.untracked_resolutions; 54 ( 0.00%) StableHashingContext::new(self.sess, &resolutions.definitions, &*resolutions.cstore) . } . . #[inline(always)] . pub fn create_no_span_stable_hashing_context(self) -> StableHashingContext<'tcx> { . let resolutions = &self.gcx.untracked_resolutions; . StableHashingContext::ignore_spans( . self.sess, . &resolutions.definitions, -- line 1381 ---------------------------------------- -- line 1390 ---------------------------------------- . /// If `true`, we should use the MIR-based borrowck, but also . /// fall back on the AST borrowck if the MIR-based one errors. . pub fn migrate_borrowck(self) -> bool { . self.borrowck_mode().migrate() . } . . /// What mode(s) of borrowck should we run? AST? MIR? both? . /// (Also considers the `#![feature(nll)]` setting.) 122 ( 0.00%) pub fn borrowck_mode(self) -> BorrowckMode { . // Here are the main constraints we need to deal with: . // . // 1. An opts.borrowck_mode of `BorrowckMode::Migrate` is . // synonymous with no `-Z borrowck=...` flag at all. . // . // 2. We want to allow developers on the Nightly channel . // to opt back into the "hard error" mode for NLL, . // (which they can do via specifying `#![feature(nll)]` -- line 1406 ---------------------------------------- -- line 1413 ---------------------------------------- . // errors. (To simplify the code here, it now even overrides . // a user's attempt to specify `-Z borrowck=compare`, which . // we arguably do not need anymore and should remove.) . // . // * Otherwise, if no `-Z borrowck=...` then use migrate mode . // . // * Otherwise, use the behavior requested via `-Z borrowck=...` . 183 ( 0.00%) if self.features().nll { . return BorrowckMode::Mir; . } . 61 ( 0.00%) self.sess.opts.borrowck_mode 244 ( 0.00%) } . . /// If `true`, we should use lazy normalization for constants, otherwise . /// we still evaluate them eagerly. . #[inline] . pub fn lazy_normalization(self) -> bool { . let features = self.features(); . // Note: We only use lazy normalization for generic const expressions. . features.generic_const_exprs -- line 1434 ---------------------------------------- -- line 1554 ---------------------------------------- . self.mk_imm_ref( . self.lifetimes.re_static, . self.type_of(self.require_lang_item(LangItem::PanicLocation, None)) . .subst(self, self.mk_substs([self.lifetimes.re_static.into()].iter())), . ) . } . . /// Returns a displayable description and article for the given `def_id` (e.g. `("a", "struct")`). 319 ( 0.00%) pub fn article_and_description(self, def_id: DefId) -> (&'static str, &'static str) { 232 ( 0.00%) match self.def_kind(def_id) { . DefKind::Generator => match self.generator_kind(def_id).unwrap() { . rustc_hir::GeneratorKind::Async(..) => ("an", "async closure"), . rustc_hir::GeneratorKind::Gen => ("a", "generator"), . }, 522 ( 0.00%) def_kind => (def_kind.article(), def_kind.descr(def_id)), . } 261 ( 0.00%) } . . pub fn type_length_limit(self) -> Limit { . self.limits(()).type_length_limit . } . 152,684 ( 0.01%) pub fn recursion_limit(self) -> Limit { . self.limits(()).recursion_limit 174,496 ( 0.01%) } . . pub fn move_size_limit(self) -> Limit { . self.limits(()).move_size_limit . } . 224 ( 0.00%) pub fn const_eval_limit(self) -> Limit { . self.limits(()).const_eval_limit 256 ( 0.00%) } . . pub fn all_traits(self) -> impl Iterator + 'tcx { . iter::once(LOCAL_CRATE) . .chain(self.crates(()).iter().copied()) . .flat_map(move |cnum| self.traits_in_crate(cnum).iter().copied()) . } . } . -- line 1594 ---------------------------------------- -- line 1684 ---------------------------------------- . /// This is the implicit state of rustc. It contains the current . /// `TyCtxt` and query. It is updated when creating a local interner or . /// executing a new query. Whenever there's a `TyCtxt` value available . /// you should also have access to an `ImplicitCtxt` through the functions . /// in this module. . #[derive(Clone)] . pub struct ImplicitCtxt<'a, 'tcx> { . /// The current `TyCtxt`. 1 ( 0.00%) pub tcx: TyCtxt<'tcx>, . . /// The current query job, if any. This is updated by `JobOwner::start` in . /// `ty::query::plumbing` when executing a query. . pub query: Option>, . . /// Where to store diagnostics for the current query job, if any. . /// This is updated by `JobOwner::start` in `ty::query::plumbing` when executing a query. . pub diagnostics: Option<&'a Lock>>, -- line 1700 ---------------------------------------- -- line 1703 ---------------------------------------- . pub layout_depth: usize, . . /// The current dep graph task. This is used to add dependencies to queries . /// when executing them. . pub task_deps: TaskDepsRef<'a>, . } . . impl<'a, 'tcx> ImplicitCtxt<'a, 'tcx> { 5 ( 0.00%) pub fn new(gcx: &'tcx GlobalCtxt<'tcx>) -> Self { . let tcx = TyCtxt { gcx }; 25 ( 0.00%) ImplicitCtxt { . tcx, . query: None, . diagnostics: None, . layout_depth: 0, . task_deps: TaskDepsRef::Ignore, . } 5 ( 0.00%) } . } . . /// Sets Rayon's thread-local variable, which is preserved for Rayon jobs . /// to `value` during the call to `f`. It is restored to its previous value after. . /// This is used to set the pointer to the new `ImplicitCtxt`. . #[cfg(parallel_compiler)] . #[inline] . fn set_tlv R, R>(value: usize, f: F) -> R { -- line 1728 ---------------------------------------- -- line 1745 ---------------------------------------- . . /// Sets TLV to `value` during the call to `f`. . /// It is restored to its previous value after. . /// This is used to set the pointer to the new `ImplicitCtxt`. . #[cfg(not(parallel_compiler))] . #[inline] . fn set_tlv R, R>(value: usize, f: F) -> R { . let old = get_tlv(); 17,123 ( 0.00%) let _reset = rustc_data_structures::OnDrop(move || TLV.with(|tlv| tlv.set(old))); . TLV.with(|tlv| tlv.set(value)); . f() . } . . /// Gets the pointer to the current `ImplicitCtxt`. . #[cfg(not(parallel_compiler))] . #[inline] . fn get_tlv() -> usize { -- line 1761 ---------------------------------------- -- line 1763 ---------------------------------------- . } . . /// Sets `context` as the new current `ImplicitCtxt` for the duration of the function `f`. . #[inline] . pub fn enter_context<'a, 'tcx, F, R>(context: &ImplicitCtxt<'a, 'tcx>, f: F) -> R . where . F: FnOnce(&ImplicitCtxt<'a, 'tcx>) -> R, . { 1 ( 0.00%) set_tlv(context as *const _ as usize, || f(&context)) . } . . /// Allows access to the current `ImplicitCtxt` in a closure if one is available. . #[inline] . pub fn with_context_opt(f: F) -> R . where . F: for<'a, 'tcx> FnOnce(Option<&ImplicitCtxt<'a, 'tcx>>) -> R, . { . let context = get_tlv(); 86,014 ( 0.00%) if context == 0 { . f(None) . } else { . // We could get an `ImplicitCtxt` pointer from another thread. . // Ensure that `ImplicitCtxt` is `Sync`. . sync::assert_sync::>(); . . unsafe { f(Some(&*(context as *const ImplicitCtxt<'_, '_>))) } . } -- line 1789 ---------------------------------------- -- line 1805 ---------------------------------------- . /// This will panic if you pass it a `TyCtxt` which is different from the current . /// `ImplicitCtxt`'s `tcx` field. . #[inline] . pub fn with_related_context<'tcx, F, R>(tcx: TyCtxt<'tcx>, f: F) -> R . where . F: FnOnce(&ImplicitCtxt<'_, 'tcx>) -> R, . { . with_context(|context| unsafe { 42,602 ( 0.00%) assert!(ptr_eq(context.tcx.gcx, tcx.gcx)); . let context: &ImplicitCtxt<'_, '_> = mem::transmute(context); 42,534 ( 0.00%) f(context) . }) . } . . /// Allows access to the `TyCtxt` in the current `ImplicitCtxt`. . /// Panics if there is no `ImplicitCtxt` available. . #[inline] . pub fn with(f: F) -> R . where -- line 1823 ---------------------------------------- -- line 1981 ---------------------------------------- . fn into_pointer(&self) -> *const () { . self.0 as *const _ as *const () . } . } . . #[allow(rustc::usage_of_ty_tykind)] . impl<'tcx> Borrow> for Interned<'tcx, TyS<'tcx>> { . fn borrow<'a>(&'a self) -> &'a TyKind<'tcx> { 89,903 ( 0.00%) &self.0.kind() . } . } . . impl<'tcx> PartialEq for Interned<'tcx, TyS<'tcx>> { . fn eq(&self, other: &Interned<'tcx, TyS<'tcx>>) -> bool { . // The `Borrow` trait requires that `x.borrow() == y.borrow()` equals . // `x == y`. . self.0.kind() == other.0.kind() -- line 1997 ---------------------------------------- -- line 1998 ---------------------------------------- . } . } . . impl<'tcx> Eq for Interned<'tcx, TyS<'tcx>> {} . . impl<'tcx> Hash for Interned<'tcx, TyS<'tcx>> { . fn hash(&self, s: &mut H) { . // The `Borrow` trait requires that `x.borrow().hash(s) == x.hash(s)`. 21,492 ( 0.00%) self.0.kind().hash(s) . } . } . . impl<'tcx> Borrow>> for Interned<'tcx, PredicateInner<'tcx>> { . fn borrow<'a>(&'a self) -> &'a Binder<'tcx, PredicateKind<'tcx>> { 49,895 ( 0.00%) &self.0.kind . } . } . . impl<'tcx> PartialEq for Interned<'tcx, PredicateInner<'tcx>> { . fn eq(&self, other: &Interned<'tcx, PredicateInner<'tcx>>) -> bool { . // The `Borrow` trait requires that `x.borrow() == y.borrow()` equals . // `x == y`. . self.0.kind == other.0.kind -- line 2020 ---------------------------------------- -- line 2021 ---------------------------------------- . } . } . . impl<'tcx> Eq for Interned<'tcx, PredicateInner<'tcx>> {} . . impl<'tcx> Hash for Interned<'tcx, PredicateInner<'tcx>> { . fn hash(&self, s: &mut H) { . // The `Borrow` trait requires that `x.borrow().hash(s) == x.hash(s)`. 7,164 ( 0.00%) self.0.kind.hash(s) . } . } . . impl<'tcx, T> Borrow<[T]> for Interned<'tcx, List> { . fn borrow<'a>(&'a self) -> &'a [T] { 141,065 ( 0.01%) &self.0[..] . } . } . . impl<'tcx, T: PartialEq> PartialEq for Interned<'tcx, List> { . fn eq(&self, other: &Interned<'tcx, List>) -> bool { . // The `Borrow` trait requires that `x.borrow() == y.borrow()` equals . // `x == y`. . self.0[..] == other.0[..] -- line 2043 ---------------------------------------- -- line 2044 ---------------------------------------- . } . } . . impl<'tcx, T: Eq> Eq for Interned<'tcx, List> {} . . impl<'tcx, T: Hash> Hash for Interned<'tcx, List> { . fn hash(&self, s: &mut H) { . // The `Borrow` trait requires that `x.borrow().hash(s) == x.hash(s)`. 8,173 ( 0.00%) self.0[..].hash(s) . } . } . . macro_rules! direct_interners { . ($($name:ident: $method:ident($ty:ty),)+) => { . $(impl<'tcx> Borrow<$ty> for Interned<'tcx, $ty> { . fn borrow<'a>(&'a self) -> &'a $ty { 54,952 ( 0.00%) &self.0 . } . } . . impl<'tcx> PartialEq for Interned<'tcx, $ty> { . fn eq(&self, other: &Self) -> bool { . // The `Borrow` trait requires that `x.borrow() == y.borrow()` . // equals `x == y`. . self.0 == other.0 -- line 2068 ---------------------------------------- -- line 2070 ---------------------------------------- . } . . impl<'tcx> Eq for Interned<'tcx, $ty> {} . . impl<'tcx> Hash for Interned<'tcx, $ty> { . fn hash(&self, s: &mut H) { . // The `Borrow` trait requires that `x.borrow().hash(s) == . // x.hash(s)`. 27,611 ( 0.00%) self.0.hash(s) . } . } . . impl<'tcx> TyCtxt<'tcx> { 520,834 ( 0.02%) pub fn $method(self, v: $ty) -> &'tcx $ty { 251,715 ( 0.01%) self.interners.$name.intern(v, |v| { 6,558 ( 0.00%) Interned(self.interners.arena.alloc(v)) . }).0 549,432 ( 0.03%) } . })+ . } . } . . direct_interners! { . region: mk_region(RegionKind), . const_: mk_const(Const<'tcx>), . const_allocation: intern_const_alloc(Allocation), -- line 2095 ---------------------------------------- -- line 2097 ---------------------------------------- . adt_def: intern_adt_def(AdtDef), . stability: intern_stability(attr::Stability), . const_stability: intern_const_stability(attr::ConstStability), . } . . macro_rules! slice_interners { . ($($field:ident: $method:ident($ty:ty)),+ $(,)?) => ( . impl<'tcx> TyCtxt<'tcx> { 1,450,341 ( 0.07%) $(pub fn $method(self, v: &[$ty]) -> &'tcx List<$ty> { . self.interners.$field.intern_ref(v, || { . Interned(List::from_arena(&*self.arena, v)) . }).0 1,282,653 ( 0.06%) })+ . } . ); . } . . slice_interners!( . type_list: _intern_type_list(Ty<'tcx>), . substs: _intern_substs(GenericArg<'tcx>), . canonical_var_infos: _intern_canonical_var_infos(CanonicalVarInfo<'tcx>), -- line 2117 ---------------------------------------- -- line 2188 ---------------------------------------- . self.mk_fn_sig(params_iter, s.output(), s.c_variadic, unsafety, abi::Abi::Rust) . }) . } . . /// Same a `self.mk_region(kind)`, but avoids accessing the interners if . /// `*r == kind`. . #[inline] . pub fn reuse_or_mk_region(self, r: Region<'tcx>, kind: RegionKind) -> Region<'tcx> { 6,844 ( 0.00%) if *r == kind { r } else { self.mk_region(kind) } . } . . #[allow(rustc::usage_of_ty_tykind)] . #[inline] . pub fn mk_ty(self, st: TyKind<'tcx>) -> Ty<'tcx> { 611,275 ( 0.03%) self.interners.intern_ty(st) . } . . #[inline] . pub fn mk_predicate(self, binder: Binder<'tcx, PredicateKind<'tcx>>) -> Predicate<'tcx> { 627,415 ( 0.03%) let inner = self.interners.intern_predicate(binder); . Predicate { inner } . } . . #[inline] 82,856 ( 0.00%) pub fn reuse_or_mk_predicate( . self, . pred: Predicate<'tcx>, . binder: Binder<'tcx, PredicateKind<'tcx>>, . ) -> Predicate<'tcx> { 5,300 ( 0.00%) if pred.kind() != binder { self.mk_predicate(binder) } else { pred } 82,856 ( 0.00%) } . . pub fn mk_mach_int(self, tm: IntTy) -> Ty<'tcx> { . match tm { . IntTy::Isize => self.types.isize, . IntTy::I8 => self.types.i8, . IntTy::I16 => self.types.i16, . IntTy::I32 => self.types.i32, . IntTy::I64 => self.types.i64, -- line 2226 ---------------------------------------- -- line 2243 ---------------------------------------- . match tm { . FloatTy::F32 => self.types.f32, . FloatTy::F64 => self.types.f64, . } . } . . #[inline] . pub fn mk_static_str(self) -> Ty<'tcx> { 904 ( 0.00%) self.mk_imm_ref(self.lifetimes.re_static, self.types.str_) . } . . #[inline] . pub fn mk_adt(self, def: &'tcx AdtDef, substs: SubstsRef<'tcx>) -> Ty<'tcx> { . // Take a copy of substs so that we own the vectors inside. . self.mk_ty(Adt(def, substs)) . } . -- line 2259 ---------------------------------------- -- line 2329 ---------------------------------------- . } . . #[inline] . pub fn mk_imm_ptr(self, ty: Ty<'tcx>) -> Ty<'tcx> { . self.mk_ptr(TypeAndMut { ty, mutbl: hir::Mutability::Not }) . } . . #[inline] 138 ( 0.00%) pub fn mk_array(self, ty: Ty<'tcx>, n: u64) -> Ty<'tcx> { . self.mk_ty(Array(ty, ty::Const::from_usize(self, n))) 144 ( 0.00%) } . . #[inline] . pub fn mk_slice(self, ty: Ty<'tcx>) -> Ty<'tcx> { . self.mk_ty(Slice(ty)) . } . . #[inline] . pub fn intern_tup(self, ts: &[Ty<'tcx>]) -> Ty<'tcx> { . let kinds: Vec<_> = ts.iter().map(|&t| GenericArg::from(t)).collect(); . self.mk_ty(Tuple(self.intern_substs(&kinds))) . } . . pub fn mk_tup], Ty<'tcx>>>(self, iter: I) -> I::Output { 1,120 ( 0.00%) iter.intern_with(|ts| { 50,350 ( 0.00%) let kinds: Vec<_> = ts.iter().map(|&t| GenericArg::from(t)).collect(); 75,200 ( 0.00%) self.mk_ty(Tuple(self.intern_substs(&kinds))) 1,008 ( 0.00%) }) . } . . #[inline] . pub fn mk_unit(self) -> Ty<'tcx> { 3 ( 0.00%) self.types.unit . } . . #[inline] . pub fn mk_diverging_default(self) -> Ty<'tcx> { . if self.features().never_type_fallback { self.types.never } else { self.types.unit } . } . . #[inline] . pub fn mk_fn_def(self, def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> { . self.mk_ty(FnDef(def_id, substs)) . } . . #[inline] . pub fn mk_fn_ptr(self, fty: PolyFnSig<'tcx>) -> Ty<'tcx> { 60 ( 0.00%) self.mk_ty(FnPtr(fty)) . } . . #[inline] . pub fn mk_dynamic( . self, . obj: &'tcx List>>, . reg: ty::Region<'tcx>, . ) -> Ty<'tcx> { -- line 2384 ---------------------------------------- -- line 2445 ---------------------------------------- . self.mk_ty(Param(ParamTy { index, name })) . } . . #[inline] . pub fn mk_const_param(self, index: u32, name: Symbol, ty: Ty<'tcx>) -> &'tcx Const<'tcx> { . self.mk_const(ty::Const { val: ty::ConstKind::Param(ParamConst { index, name }), ty }) . } . 210 ( 0.00%) pub fn mk_param_from_def(self, param: &ty::GenericParamDef) -> GenericArg<'tcx> { 150 ( 0.00%) match param.kind { . GenericParamDefKind::Lifetime => { . self.mk_region(ty::ReEarlyBound(param.to_early_bound_region_data())).into() . } 60 ( 0.00%) GenericParamDefKind::Type { .. } => self.mk_ty_param(param.index, param.name).into(), . GenericParamDefKind::Const { .. } => { . self.mk_const_param(param.index, param.name, self.type_of(param.def_id)).into() . } . } 210 ( 0.00%) } . . #[inline] . pub fn mk_opaque(self, def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> { . self.mk_ty(Opaque(def_id, substs)) . } . 18,222 ( 0.00%) pub fn mk_place_field(self, place: Place<'tcx>, f: Field, ty: Ty<'tcx>) -> Place<'tcx> { 18,222 ( 0.00%) self.mk_place_elem(place, PlaceElem::Field(f, ty)) 36,444 ( 0.00%) } . . pub fn mk_place_deref(self, place: Place<'tcx>) -> Place<'tcx> { . self.mk_place_elem(place, PlaceElem::Deref) . } . 4,612 ( 0.00%) pub fn mk_place_downcast( . self, . place: Place<'tcx>, . adt_def: &'tcx AdtDef, . variant_index: VariantIdx, . ) -> Place<'tcx> { 4,612 ( 0.00%) self.mk_place_elem( . place, 9,224 ( 0.00%) PlaceElem::Downcast(Some(adt_def.variants[variant_index].name), variant_index), . ) 9,224 ( 0.00%) } . . pub fn mk_place_downcast_unnamed( . self, . place: Place<'tcx>, . variant_index: VariantIdx, . ) -> Place<'tcx> { . self.mk_place_elem(place, PlaceElem::Downcast(None, variant_index)) . } -- line 2496 ---------------------------------------- -- line 2497 ---------------------------------------- . . pub fn mk_place_index(self, place: Place<'tcx>, index: Local) -> Place<'tcx> { . self.mk_place_elem(place, PlaceElem::Index(index)) . } . . /// This method copies `Place`'s projection, add an element and reintern it. Should not be used . /// to build a full `Place` it's just a convenient way to grab a projection and modify it in . /// flight. 205,506 ( 0.01%) pub fn mk_place_elem(self, place: Place<'tcx>, elem: PlaceElem<'tcx>) -> Place<'tcx> { . let mut projection = place.projection.to_vec(); . projection.push(elem); . . Place { local: place.local, projection: self.intern_place_elems(&projection) } 228,340 ( 0.01%) } . 49 ( 0.00%) pub fn intern_poly_existential_predicates( . self, . eps: &[ty::Binder<'tcx, ExistentialPredicate<'tcx>>], . ) -> &'tcx List>> { 7 ( 0.00%) assert!(!eps.is_empty()); . assert!( . eps.array_windows() 30 ( 0.00%) .all(|[a, b]| a.skip_binder().stable_cmp(self, &b.skip_binder()) . != Ordering::Greater) . ); 28 ( 0.00%) self._intern_poly_existential_predicates(eps) 56 ( 0.00%) } . . pub fn intern_predicates(self, preds: &[Predicate<'tcx>]) -> &'tcx List> { . // FIXME consider asking the input slice to be sorted to avoid . // re-interning permutations, in which case that would be asserted . // here. 1,675 ( 0.00%) if preds.is_empty() { . // The macro-generated method below asserts we don't intern an empty slice. . List::empty() . } else { 31 ( 0.00%) self._intern_predicates(preds) . } 3,288 ( 0.00%) } . . pub fn intern_type_list(self, ts: &[Ty<'tcx>]) -> &'tcx List> { 4,366 ( 0.00%) if ts.is_empty() { List::empty() } else { self._intern_type_list(ts) } 16 ( 0.00%) } . . pub fn intern_substs(self, ts: &[GenericArg<'tcx>]) -> &'tcx List> { 225,629 ( 0.01%) if ts.is_empty() { List::empty() } else { self._intern_substs(ts) } 44,844 ( 0.00%) } . . pub fn intern_projs(self, ps: &[ProjectionKind]) -> &'tcx List { . if ps.is_empty() { List::empty() } else { self._intern_projs(ps) } . } . . pub fn intern_place_elems(self, ts: &[PlaceElem<'tcx>]) -> &'tcx List> { 47,467 ( 0.00%) if ts.is_empty() { List::empty() } else { self._intern_place_elems(ts) } 1,246 ( 0.00%) } . . pub fn intern_canonical_var_infos( . self, . ts: &[CanonicalVarInfo<'tcx>], . ) -> CanonicalVarInfos<'tcx> { 3,532 ( 0.00%) if ts.is_empty() { List::empty() } else { self._intern_canonical_var_infos(ts) } 96 ( 0.00%) } . . pub fn intern_bound_variable_kinds( . self, . ts: &[ty::BoundVariableKind], . ) -> &'tcx List { 549 ( 0.00%) if ts.is_empty() { List::empty() } else { self._intern_bound_variable_kinds(ts) } 784 ( 0.00%) } . . pub fn mk_fn_sig( . self, . inputs: I, . output: I::Item, . c_variadic: bool, . unsafety: hir::Unsafety, . abi: abi::Abi, . ) -> , ty::FnSig<'tcx>>>::Output . where . I: Iterator, ty::FnSig<'tcx>>>, . { . inputs.chain(iter::once(output)).intern_with(|xs| ty::FnSig { 354 ( 0.00%) inputs_and_output: self.intern_type_list(xs), 48 ( 0.00%) c_variadic, 72 ( 0.00%) unsafety, 48 ( 0.00%) abi, . }) . } . . pub fn mk_poly_existential_predicates< . I: InternAs< . [ty::Binder<'tcx, ExistentialPredicate<'tcx>>], . &'tcx List>>, . >, . >( . self, . iter: I, . ) -> I::Output { 21 ( 0.00%) iter.intern_with(|xs| self.intern_poly_existential_predicates(xs)) . } . . pub fn mk_predicates], &'tcx List>>>( . self, . iter: I, . ) -> I::Output { . iter.intern_with(|xs| self.intern_predicates(xs)) . } . . pub fn mk_type_list], &'tcx List>>>(self, iter: I) -> I::Output { 521 ( 0.00%) iter.intern_with(|xs| self.intern_type_list(xs)) . } . . pub fn mk_substs], &'tcx List>>>( . self, . iter: I, . ) -> I::Output { 165,229 ( 0.01%) iter.intern_with(|xs| self.intern_substs(xs)) . } . . pub fn mk_place_elems], &'tcx List>>>( . self, . iter: I, . ) -> I::Output { . iter.intern_with(|xs| self.intern_place_elems(xs)) . } . 44,937 ( 0.00%) pub fn mk_substs_trait(self, self_ty: Ty<'tcx>, rest: &[GenericArg<'tcx>]) -> SubstsRef<'tcx> { . self.mk_substs(iter::once(self_ty.into()).chain(rest.iter().cloned())) 89,874 ( 0.00%) } . . pub fn mk_bound_variable_kinds< . I: InternAs<[ty::BoundVariableKind], &'tcx List>, . >( . self, . iter: I, . ) -> I::Output { 3,138 ( 0.00%) iter.intern_with(|xs| self.intern_bound_variable_kinds(xs)) . } . . /// Walks upwards from `id` to find a node which might change lint levels with attributes. . /// It stops at `bound` and just returns it if reached. 347,956 ( 0.02%) pub fn maybe_lint_level_root_bounded(self, mut id: HirId, bound: HirId) -> HirId { 347,956 ( 0.02%) let hir = self.hir(); . loop { 536,529 ( 0.03%) if id == bound { . return bound; . } . 645,675 ( 0.03%) if hir.attrs(id).iter().any(|attr| Level::from_symbol(attr.name_or_empty()).is_some()) { . return id; . } . let next = hir.get_parent_node(id); 387,405 ( 0.02%) if next == id { . bug!("lint traversal reached the root of the crate"); . } . id = next; . } 497,080 ( 0.02%) } . 2,720 ( 0.00%) pub fn lint_level_at_node( . self, . lint: &'static Lint, . mut id: hir::HirId, . ) -> (Level, LintLevelSource) { . let sets = self.lint_levels(()); . loop { 9,062 ( 0.00%) if let Some(pair) = sets.level_and_source(lint, id, self.sess) { . return pair; . } 478 ( 0.00%) let next = self.hir().get_parent_node(id); 1,434 ( 0.00%) if next == id { . bug!("lint traversal reached the root of the crate"); . } . id = next; . } 2,720 ( 0.00%) } . 84 ( 0.00%) pub fn struct_span_lint_hir( . self, . lint: &'static Lint, . hir_id: HirId, . span: impl Into, . decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>), . ) { 237 ( 0.00%) let (level, src) = self.lint_level_at_node(lint, hir_id); 63 ( 0.00%) struct_lint_level(self.sess, lint, level, src, Some(span.into()), decorate); 48 ( 0.00%) } . . pub fn struct_lint_node( . self, . lint: &'static Lint, . id: HirId, . decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>), . ) { . let (level, src) = self.lint_level_at_node(lint, id); . struct_lint_level(self.sess, lint, level, src, None, decorate); . } . 1,218 ( 0.00%) pub fn in_scope_traits(self, id: HirId) -> Option<&'tcx [TraitCandidate]> { 348 ( 0.00%) let map = self.in_scope_traits_map(id.owner)?; . let candidates = map.get(&id.local_id)?; 348 ( 0.00%) Some(&*candidates) 1,392 ( 0.00%) } . 1,771 ( 0.00%) pub fn named_region(self, id: HirId) -> Option { . debug!(?id, "named_region"); . self.named_region_map(id.owner).and_then(|map| map.get(&id.local_id).cloned()) 2,277 ( 0.00%) } . . pub fn is_late_bound(self, id: HirId) -> bool { . self.is_late_bound_map(id.owner) . .map_or(false, |(owner, set)| owner == id.owner && set.contains(&id.local_id)) . } . 3,360 ( 0.00%) pub fn object_lifetime_defaults(self, id: HirId) -> Option> { . self.object_lifetime_defaults_map(id.owner) 4,320 ( 0.00%) } . 891 ( 0.00%) pub fn late_bound_vars(self, id: HirId) -> &'tcx List { . self.mk_bound_variable_kinds( . self.late_bound_vars_map(id.owner) . .and_then(|map| map.get(&id.local_id).cloned()) . .unwrap_or_else(|| { . bug!("No bound vars found for {:?} ({:?})", self.hir().node_to_string(id), id) . }) . .iter(), . ) 891 ( 0.00%) } . . pub fn lifetime_scope(self, id: HirId) -> Option { . self.lifetime_scope_map(id.owner).and_then(|mut map| map.remove(&id.local_id)) . } . . /// Whether the `def_id` counts as const fn in the current crate, considering all active . /// feature gates 20 ( 0.00%) pub fn is_const_fn(self, def_id: DefId) -> bool { 2 ( 0.00%) if self.is_const_fn_raw(def_id) { 2 ( 0.00%) match self.lookup_const_stability(def_id) { 4 ( 0.00%) Some(stability) if stability.level.is_unstable() => { . // has a `rustc_const_unstable` attribute, check whether the user enabled the . // corresponding feature gate. 2 ( 0.00%) self.features() . .declared_lib_features . .iter() . .any(|&(sym, _)| sym == stability.feature) . } . // functions without const stability are either stable user written . // const fn or the user is using feature gates and we thus don't . // care what they do . _ => true, . } . } else { . false . } 18 ( 0.00%) } . } . . impl<'tcx> TyCtxtAt<'tcx> { . /// Constructs a `TyKind::Error` type and registers a `delay_span_bug` to ensure it gets used. . #[track_caller] . pub fn ty_error(self) -> Ty<'tcx> { . self.tcx.ty_error_with_message(self.span, "TyKind::Error constructed but no error reported") . } -- line 2759 ---------------------------------------- -- line 2774 ---------------------------------------- . } . . impl InternAs<[T], R> for I . where . E: InternIteratorElement, . I: Iterator, . { . type Output = E::Output; 20,696 ( 0.00%) fn intern_with(self, f: F) -> Self::Output . where . F: FnOnce(&[T]) -> R, . { 625,385 ( 0.03%) E::intern_with(self, f) 21,222 ( 0.00%) } . } . . pub trait InternIteratorElement: Sized { . type Output; . fn intern_with, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output; . } . . impl InternIteratorElement for T { . type Output = R; 264,861 ( 0.01%) fn intern_with, F: FnOnce(&[T]) -> R>( . mut iter: I, . f: F, . ) -> Self::Output { . // This code is hot enough that it's worth specializing for the most . // common length lists, to avoid the overhead of `SmallVec` creation. . // Lengths 0, 1, and 2 typically account for ~95% of cases. If . // `size_hint` is incorrect a panic will occur via an `unwrap` or an . // `assert`. 323,559 ( 0.02%) match iter.size_hint() { . (0, Some(0)) => { . assert!(iter.next().is_none()); . f(&[]) . } . (1, Some(1)) => { . let t0 = iter.next().unwrap(); 15 ( 0.00%) assert!(iter.next().is_none()); 27,990 ( 0.00%) f(&[t0]) . } . (2, Some(2)) => { . let t0 = iter.next().unwrap(); . let t1 = iter.next().unwrap(); 24 ( 0.00%) assert!(iter.next().is_none()); 39,799 ( 0.00%) f(&[t0, t1]) . } 96 ( 0.00%) _ => f(&iter.collect::>()), . } 307,575 ( 0.01%) } . } . . impl<'a, T, R> InternIteratorElement for &'a T . where . T: Clone + 'a, . { . type Output = R; 555 ( 0.00%) fn intern_with, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output { . // This code isn't hot. . f(&iter.cloned().collect::>()) 444 ( 0.00%) } . } . . impl InternIteratorElement for Result { . type Output = Result; 110,994 ( 0.01%) fn intern_with, F: FnOnce(&[T]) -> R>( . mut iter: I, . f: F, . ) -> Self::Output { . // This code is hot enough that it's worth specializing for the most . // common length lists, to avoid the overhead of `SmallVec` creation. . // Lengths 0, 1, and 2 typically account for ~95% of cases. If . // `size_hint` is incorrect a panic will occur via an `unwrap` or an . // `assert`, unless a failure happens first, in which case the result . // will be an error anyway. 63,424 ( 0.00%) Ok(match iter.size_hint() { . (0, Some(0)) => { . assert!(iter.next().is_none()); . f(&[]) . } . (1, Some(1)) => { . let t0 = iter.next().unwrap()?; . assert!(iter.next().is_none()); 1,021 ( 0.00%) f(&[t0]) . } . (2, Some(2)) => { 36 ( 0.00%) let t0 = iter.next().unwrap()?; 36 ( 0.00%) let t1 = iter.next().unwrap()?; 54 ( 0.00%) assert!(iter.next().is_none()); 2,826 ( 0.00%) f(&[t0, t1]) . } 60 ( 0.00%) _ => f(&iter.collect::, _>>()?), . }) 126,294 ( 0.01%) } . } . . // We are comparing types with different invariant lifetimes, so `ptr::eq` . // won't work for us. . fn ptr_eq(t: *const T, u: *const U) -> bool { 42,602 ( 0.00%) t as *const () == u as *const () . } . . pub fn provide(providers: &mut ty::query::Providers) { 2 ( 0.00%) providers.in_scope_traits_map = . |tcx, id| tcx.hir_crate(()).owners[id].as_ref().map(|owner_info| &owner_info.trait_map); 3 ( 0.00%) providers.resolutions = |tcx, ()| &tcx.untracked_resolutions; 2 ( 0.00%) providers.module_reexports = . |tcx, id| tcx.resolutions(()).reexport_map.get(&id).map(|v| &v[..]); 2 ( 0.00%) providers.crate_name = |tcx, id| { 1 ( 0.00%) assert_eq!(id, LOCAL_CRATE); 1 ( 0.00%) tcx.crate_name . }; 2 ( 0.00%) providers.maybe_unused_trait_import = . |tcx, id| tcx.resolutions(()).maybe_unused_trait_imports.contains(&id); 2 ( 0.00%) providers.maybe_unused_extern_crates = . |tcx, ()| &tcx.resolutions(()).maybe_unused_extern_crates[..]; 2 ( 0.00%) providers.names_imported_by_glob_use = |tcx, id| { . tcx.arena.alloc(tcx.resolutions(()).glob_map.get(&id).cloned().unwrap_or_default()) . }; . 11 ( 0.00%) providers.lookup_stability = |tcx, id| tcx.stability().local_stability(id.expect_local()); 2 ( 0.00%) providers.lookup_const_stability = . |tcx, id| tcx.stability().local_const_stability(id.expect_local()); 2 ( 0.00%) providers.lookup_deprecation_entry = 1,912 ( 0.00%) |tcx, id| tcx.stability().local_deprecation_entry(id.expect_local()); 2 ( 0.00%) providers.extern_mod_stmt_cnum = . |tcx, id| tcx.resolutions(()).extern_crate_map.get(&id).cloned(); 3 ( 0.00%) providers.output_filenames = |tcx, ()| tcx.output_filenames.clone(); 3 ( 0.00%) providers.features_query = |tcx, ()| tcx.sess.features_untracked(); 2 ( 0.00%) providers.is_panic_runtime = |tcx, cnum| { . assert_eq!(cnum, LOCAL_CRATE); . tcx.sess.contains_name(tcx.hir().krate_attrs(), sym::panic_runtime) . }; 2 ( 0.00%) providers.is_compiler_builtins = |tcx, cnum| { . assert_eq!(cnum, LOCAL_CRATE); . tcx.sess.contains_name(tcx.hir().krate_attrs(), sym::compiler_builtins) . }; 2 ( 0.00%) providers.has_panic_handler = |tcx, cnum| { 1 ( 0.00%) assert_eq!(cnum, LOCAL_CRATE); . // We want to check if the panic handler was defined in this crate 3 ( 0.00%) tcx.lang_items().panic_impl().map_or(false, |did| did.is_local()) . }; . } 1,048,219 ( 0.05%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/undo_log.rs -------------------------------------------------------------------------------- Ir -- line 28 ---------------------------------------- . PushRegionObligation, . } . . macro_rules! impl_from { . ($($ctor: ident ($ty: ty),)*) => { . $( . impl<'tcx> From<$ty> for UndoLog<'tcx> { . fn from(x: $ty) -> Self { 12 ( 0.00%) UndoLog::$ctor(x.into()) . } . } . )* . } . } . . // Upcast from a single kind of "undoable action" to the general enum . impl_from! { -- line 44 ---------------------------------------- -- line 57 ---------------------------------------- . ConstUnificationTable(sv::UndoLog>>), . . RegionUnificationTable(sv::UndoLog>>), . ProjectionCache(traits::UndoLog<'tcx>), . } . . /// The Rollback trait defines how to rollback a particular action. . impl<'tcx> Rollback> for InferCtxtInner<'tcx> { 320,313 ( 0.02%) fn reverse(&mut self, undo: UndoLog<'tcx>) { 533,855 ( 0.03%) match undo { 1,011,360 ( 0.05%) UndoLog::TypeVariables(undo) => self.type_variable_storage.reverse(undo), . UndoLog::ConstUnificationTable(undo) => self.const_unification_storage.reverse(undo), . UndoLog::IntUnificationTable(undo) => self.int_unification_storage.reverse(undo), . UndoLog::FloatUnificationTable(undo) => self.float_unification_storage.reverse(undo), . UndoLog::RegionConstraintCollector(undo) => { 21,350 ( 0.00%) self.region_constraint_storage.as_mut().unwrap().reverse(undo) . } . UndoLog::RegionUnificationTable(undo) => { 5,170 ( 0.00%) self.region_constraint_storage.as_mut().unwrap().unification_table.reverse(undo) . } . UndoLog::ProjectionCache(undo) => self.projection_cache.reverse(undo), . UndoLog::PushRegionObligation => { . self.region_obligations.pop(); . } . } 427,084 ( 0.02%) } . } . . /// The combined undo log for all the various unification tables. For each change to the storage . /// for any kind of inference variable, we record an UndoLog entry in the vector here. . pub(crate) struct InferCtxtUndoLogs<'tcx> { . logs: Vec>, . num_open_snapshots: usize, . } . . impl Default for InferCtxtUndoLogs<'_> { . fn default() -> Self { 3,714 ( 0.00%) Self { logs: Default::default(), num_open_snapshots: Default::default() } . } . } . . /// The UndoLogs trait defines how we undo a particular kind of action (of type T). We can undo any . /// action that is convertable into an UndoLog (per the From impls above). . impl<'tcx, T> UndoLogs for InferCtxtUndoLogs<'tcx> . where . UndoLog<'tcx>: From, -- line 102 ---------------------------------------- -- line 103 ---------------------------------------- . { . #[inline] . fn num_open_snapshots(&self) -> usize { . self.num_open_snapshots . } . . #[inline] . fn push(&mut self, undo: T) { 30,530 ( 0.00%) if self.in_snapshot() { 96 ( 0.00%) self.logs.push(undo.into()) . } . } . . fn clear(&mut self) { . self.logs.clear(); . self.num_open_snapshots = 0; . } . -- line 120 ---------------------------------------- -- line 125 ---------------------------------------- . { . if self.in_snapshot() { . self.logs.extend(undos.into_iter().map(UndoLog::from)) . } . } . } . . impl<'tcx> InferCtxtInner<'tcx> { 151,194 ( 0.01%) pub fn rollback_to(&mut self, snapshot: Snapshot<'tcx>) { . debug!("rollback_to({})", snapshot.undo_len); . self.undo_log.assert_open_snapshot(&snapshot); . 370,711 ( 0.02%) while self.undo_log.logs.len() > snapshot.undo_len { . let undo = self.undo_log.logs.pop().unwrap(); 1,281,252 ( 0.06%) self.reverse(undo); . } . 70,051 ( 0.00%) if self.undo_log.num_open_snapshots == 1 { . // The root snapshot. It's safe to clear the undo log because . // there's no snapshot further out that we might need to roll back . // to. 10,864 ( 0.00%) assert!(snapshot.undo_len == 0); . self.undo_log.logs.clear(); . } . 81,029 ( 0.00%) self.undo_log.num_open_snapshots -= 1; 176,393 ( 0.01%) } . . pub fn commit(&mut self, snapshot: Snapshot<'tcx>) { . debug!("commit({})", snapshot.undo_len); . 370,665 ( 0.02%) if self.undo_log.num_open_snapshots == 1 { . // The root snapshot. It's safe to clear the undo log because . // there's no snapshot further out that we might need to roll back . // to. 80,414 ( 0.00%) assert!(snapshot.undo_len == 0); . self.undo_log.logs.clear(); . } . 410,872 ( 0.02%) self.undo_log.num_open_snapshots -= 1; . } . } . . impl<'tcx> InferCtxtUndoLogs<'tcx> { . pub fn start_snapshot(&mut self) -> Snapshot<'tcx> { 595,016 ( 0.03%) self.num_open_snapshots += 1; . Snapshot { undo_len: self.logs.len(), _marker: PhantomData } . } . . pub(crate) fn region_constraints_in_snapshot( . &self, . s: &Snapshot<'tcx>, . ) -> impl Iterator> + Clone { 505 ( 0.00%) self.logs[s.undo_len..].iter().filter_map(|log| match log { . UndoLog::RegionConstraintCollector(log) => Some(log), . _ => None, . }) . } . . pub(crate) fn region_constraints( . &self, . ) -> impl Iterator> + Clone { -- line 186 ---------------------------------------- -- line 187 ---------------------------------------- . self.logs.iter().filter_map(|log| match log { . UndoLog::RegionConstraintCollector(log) => Some(log), . _ => None, . }) . } . . fn assert_open_snapshot(&self, snapshot: &Snapshot<'tcx>) { . // Failures here may indicate a failure to follow a stack discipline. 75,597 ( 0.00%) assert!(self.logs.len() >= snapshot.undo_len); 75,597 ( 0.00%) assert!(self.num_open_snapshots > 0); . } . } . . impl<'tcx> std::ops::Index for InferCtxtUndoLogs<'tcx> { . type Output = UndoLog<'tcx>; . . fn index(&self, key: usize) -> &Self::Output { . &self.logs[key] -- line 204 ---------------------------------------- 134,180 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_dataflow/src/drop_flag_effects.rs -------------------------------------------------------------------------------- Ir -- line 48 ---------------------------------------- . // . // FIXME: we have to do something for moving slice patterns. . fn place_contents_drop_state_cannot_differ<'tcx>( . tcx: TyCtxt<'tcx>, . body: &Body<'tcx>, . place: mir::Place<'tcx>, . ) -> bool { . let ty = place.ty(body, tcx).ty; 721,512 ( 0.03%) match ty.kind() { . ty::Array(..) => { . debug!( . "place_contents_drop_state_cannot_differ place: {:?} ty: {:?} => false", . place, ty . ); . false . } . ty::Slice(..) | ty::Ref(..) | ty::RawPtr(..) => { . debug!( . "place_contents_drop_state_cannot_differ place: {:?} ty: {:?} refd => true", . place, ty . ); . true . } 685,143 ( 0.03%) ty::Adt(def, _) if (def.has_dtor(tcx) && !def.is_box()) || def.is_union() => { . debug!( . "place_contents_drop_state_cannot_differ place: {:?} ty: {:?} Drop => true", . place, ty . ); . true . } . _ => false, . } -- line 79 ---------------------------------------- -- line 83 ---------------------------------------- . tcx: TyCtxt<'tcx>, . body: &Body<'tcx>, . move_data: &MoveData<'tcx>, . lookup_result: LookupResult, . each_child: F, . ) where . F: FnMut(MovePathIndex), . { 1,328 ( 0.00%) match lookup_result { . LookupResult::Parent(..) => { . // access to untracked value - do not touch children . } . LookupResult::Exact(e) => on_all_children_bits(tcx, body, move_data, e, each_child), . } . } . . pub fn on_all_children_bits<'tcx, F>( -- line 99 ---------------------------------------- -- line 100 ---------------------------------------- . tcx: TyCtxt<'tcx>, . body: &Body<'tcx>, . move_data: &MoveData<'tcx>, . move_path_index: MovePathIndex, . mut each_child: F, . ) where . F: FnMut(MovePathIndex), . { 984,296 ( 0.05%) fn is_terminal_path<'tcx>( . tcx: TyCtxt<'tcx>, . body: &Body<'tcx>, . move_data: &MoveData<'tcx>, . path: MovePathIndex, . ) -> bool { 246,074 ( 0.01%) place_contents_drop_state_cannot_differ(tcx, body, move_data.move_paths[path].place) 984,296 ( 0.05%) } . 1,134,362 ( 0.05%) fn on_all_children_bits<'tcx, F>( . tcx: TyCtxt<'tcx>, . body: &Body<'tcx>, . move_data: &MoveData<'tcx>, . move_path_index: MovePathIndex, . each_child: &mut F, . ) where . F: FnMut(MovePathIndex), . { 59,801 ( 0.00%) each_child(move_path_index); . 861,259 ( 0.04%) if is_terminal_path(tcx, body, move_data, move_path_index) { . return; . } . 114,682 ( 0.01%) let mut next_child_index = move_data.move_paths[move_path_index].first_child; 229,364 ( 0.01%) while let Some(child_index) = next_child_index { . on_all_children_bits(tcx, body, move_data, child_index, each_child); . next_child_index = move_data.move_paths[child_index].next_sibling; . } 929,294 ( 0.04%) } 739,001 ( 0.03%) on_all_children_bits(tcx, body, move_data, move_path_index, &mut each_child); . } . . pub fn on_all_drop_children_bits<'tcx, F>( . tcx: TyCtxt<'tcx>, . body: &Body<'tcx>, . ctxt: &MoveDataParamEnv<'tcx>, . path: MovePathIndex, . mut each_child: F, -- line 146 ---------------------------------------- -- line 156 ---------------------------------------- . if erased_ty.needs_drop(tcx, ctxt.param_env) { . each_child(child); . } else { . debug!("on_all_drop_children_bits - skipping") . } . }) . } . 2,062 ( 0.00%) pub fn drop_flag_effects_for_function_entry<'tcx, F>( . tcx: TyCtxt<'tcx>, . body: &Body<'tcx>, . ctxt: &MoveDataParamEnv<'tcx>, . mut callback: F, . ) where . F: FnMut(MovePathIndex, DropFlagState), . { . let move_data = &ctxt.move_data; 186 ( 0.00%) for arg in body.args_iter() { 192 ( 0.00%) let place = mir::Place::from(arg); 288 ( 0.00%) let lookup_result = move_data.rev_lookup.find(place.as_ref()); . on_lookup_result_bits(tcx, body, move_data, lookup_result, |mpi| { 96 ( 0.00%) callback(mpi, DropFlagState::Present) . }); . } 1,488 ( 0.00%) } . 723,024 ( 0.03%) pub fn drop_flag_effects_for_location<'tcx, F>( . tcx: TyCtxt<'tcx>, . body: &Body<'tcx>, . ctxt: &MoveDataParamEnv<'tcx>, . loc: Location, . mut callback: F, . ) where . F: FnMut(MovePathIndex, DropFlagState), . { . let move_data = &ctxt.move_data; . debug!("drop_flag_effects_for_location({:?})", loc); . . // first, move out of the RHS 18,834 ( 0.00%) for mi in &move_data.loc_map[loc] { 236,547 ( 0.01%) let path = mi.move_path_index(move_data); . debug!("moving out of path {:?}", move_data.move_paths[path]); . 62,572 ( 0.00%) on_all_children_bits(tcx, body, move_data, path, |mpi| callback(mpi, DropFlagState::Absent)) . } . . debug!("drop_flag_effects: assignment for location({:?})", loc); . 59,801 ( 0.00%) for_location_inits(tcx, body, move_data, loc, |mpi| callback(mpi, DropFlagState::Present)); 592,464 ( 0.03%) } . . pub fn for_location_inits<'tcx, F>( . tcx: TyCtxt<'tcx>, . body: &Body<'tcx>, . move_data: &MoveData<'tcx>, . loc: Location, . mut callback: F, . ) where . F: FnMut(MovePathIndex), . { 18,834 ( 0.00%) for ii in &move_data.init_loc_map[loc] { 242,612 ( 0.01%) let init = move_data.inits[*ii]; 123,010 ( 0.01%) match init.kind { . InitKind::Deep => { . let path = init.path; . . on_all_children_bits(tcx, body, move_data, path, &mut callback) . } . InitKind::Shallow => { . let mpi = init.path; . callback(mpi); -- line 226 ---------------------------------------- -- line 230 ---------------------------------------- . } . } . . /// Calls `handle_inactive_variant` for each descendant move path of `enum_place` that contains a . /// `Downcast` to a variant besides the `active_variant`. . /// . /// NOTE: If there are no move paths corresponding to an inactive variant, . /// `handle_inactive_variant` will not be called for that variant. 2,640 ( 0.00%) pub(crate) fn on_all_inactive_variants<'tcx>( . tcx: TyCtxt<'tcx>, . body: &mir::Body<'tcx>, . move_data: &MoveData<'tcx>, . enum_place: mir::Place<'tcx>, . active_variant: VariantIdx, . mut handle_inactive_variant: impl FnMut(MovePathIndex), . ) { 1,100 ( 0.00%) let enum_mpi = match move_data.rev_lookup.find(enum_place.as_ref()) { . LookupResult::Exact(mpi) => mpi, . LookupResult::Parent(_) => return, . }; . . let enum_path = &move_data.move_paths[enum_mpi]; . for (variant_mpi, variant_path) in enum_path.children(&move_data.move_paths) { . // Because of the way we build the `MoveData` tree, each child should have exactly one more . // projection than `enum_place`. This additional projection must be a downcast since the -- line 254 ---------------------------------------- -- line 262 ---------------------------------------- . }; . . if variant_idx != active_variant { . on_all_children_bits(tcx, body, move_data, variant_mpi, |mpi| { . handle_inactive_variant(mpi) . }); . } . } 1,760 ( 0.00%) } 907,663 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/expr.rs -------------------------------------------------------------------------------- Ir -- line 71 ---------------------------------------- . AlreadyParsed(P), . } . . impl From> for LhsExpr { . /// Converts `Some(attrs)` into `LhsExpr::AttributesParsed(attrs)` . /// and `None` into `LhsExpr::NotYetParsed`. . /// . /// This conversion does not allocate. 4,565 ( 0.00%) fn from(o: Option) -> Self { 67,566 ( 0.00%) if let Some(attrs) = o { LhsExpr::AttributesParsed(attrs) } else { LhsExpr::NotYetParsed } 4,565 ( 0.00%) } . } . . impl From> for LhsExpr { . /// Converts the `expr: P` into `LhsExpr::AlreadyParsed(expr)`. . /// . /// This conversion does not allocate. . fn from(expr: P) -> Self { . LhsExpr::AlreadyParsed(expr) -- line 89 ---------------------------------------- -- line 96 ---------------------------------------- . pub fn parse_expr(&mut self) -> PResult<'a, P> { . self.current_closure.take(); . . self.parse_expr_res(Restrictions::empty(), None) . } . . /// Parses an expression, forcing tokens to be collected . pub fn parse_expr_force_collect(&mut self) -> PResult<'a, P> { 1,500 ( 0.00%) self.collect_tokens_no_attrs(|this| this.parse_expr()) . } . . pub fn parse_anon_const_expr(&mut self) -> PResult<'a, AnonConst> { . self.parse_expr().map(|value| AnonConst { id: DUMMY_NODE_ID, value }) . } . 75,648 ( 0.00%) fn parse_expr_catch_underscore(&mut self) -> PResult<'a, P> { 18,912 ( 0.00%) match self.parse_expr() { . Ok(expr) => Ok(expr), . Err(mut err) => match self.token.ident() { . Some((Ident { name: kw::Underscore, .. }, false)) . if self.look_ahead(1, |t| t == &token::Comma) => . { . // Special-case handling of `foo(_, _, _)` . err.emit(); . self.bump(); . Ok(self.mk_expr(self.prev_token.span, ExprKind::Err, AttrVec::new())) . } . _ => Err(err), . }, . } 94,560 ( 0.00%) } . . /// Parses a sequence of expressions delimited by parentheses. . fn parse_paren_expr_seq(&mut self) -> PResult<'a, Vec>> { 2,088 ( 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 144 ---------------------------------------- . /// . /// This parses an expression accounting for associativity and precedence of the operators in . /// the expression. . #[inline] . fn parse_assoc_expr( . &mut self, . already_parsed_attrs: Option, . ) -> PResult<'a, P> { 97,129 ( 0.00%) self.parse_assoc_expr_with(0, already_parsed_attrs.into()) . } . . /// Parses an associative expression with operators of at least `min_prec` precedence. 261,423 ( 0.01%) pub(super) fn parse_assoc_expr_with( . &mut self, . min_prec: usize, . lhs: LhsExpr, . ) -> PResult<'a, P> { 145,229 ( 0.01%) let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs { 60 ( 0.00%) expr . } else { 58,064 ( 0.00%) let attrs = match lhs { 58,169 ( 0.00%) LhsExpr::AttributesParsed(attrs) => Some(attrs), . _ => None, . }; 29,032 ( 0.00%) if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token.kind) { . return self.parse_prefix_range_expr(attrs); . } else { 348,384 ( 0.02%) self.parse_prefix_expr(attrs)? . } . }; 58,094 ( 0.00%) let last_type_ascription_set = self.last_type_ascription.is_some(); . . if !self.should_continue_as_assoc_expr(&lhs) { 36 ( 0.00%) self.last_type_ascription = None; . return Ok(lhs); . } . . self.expected_tokens.push(TokenType::Operator); . while let Some(op) = self.check_assoc_op() { . // Adjust the span for interpolated LHS to point to the `$lhs` token . // and not to what it refers to. . let lhs_span = match self.prev_token.kind { -- line 185 ---------------------------------------- -- line 341 ---------------------------------------- . self.span_bug(span, "AssocOp should have been handled by special case") . } . }; . . if let Fixity::None = fixity { . break; . } . } 29,035 ( 0.00%) if last_type_ascription_set { . self.last_type_ascription = None; . } 58,070 ( 0.00%) Ok(lhs) 493,766 ( 0.02%) } . . fn should_continue_as_assoc_expr(&mut self, lhs: &Expr) -> bool { 203,353 ( 0.01%) 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> { 319,385 ( 0.02%) 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 { 58,326 ( 0.00%) self.restrictions.contains(Restrictions::STMT_EXPR) 2,578 ( 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 520 ---------------------------------------- . (lo, None) . }; . let range = this.mk_range(None, opt_end, limits); . Ok(this.mk_expr(span, range, attrs.into())) . }) . } . . /// Parses a prefix-unary-operator expr. 203,329 ( 0.01%) fn parse_prefix_expr(&mut self, attrs: Option) -> PResult<'a, P> { 232,376 ( 0.01%) let attrs = self.parse_or_use_outer_attributes(attrs)?; 145,235 ( 0.01%) let lo = self.token.span; . . macro_rules! make_it { . ($this:ident, $attrs:expr, |this, _| $body:expr) => { 126 ( 0.00%) $this.collect_tokens_for_expr($attrs, |$this, attrs| { 120 ( 0.00%) let (hi, ex) = $body?; 240 ( 0.00%) Ok($this.mk_expr(lo.to(hi), ex, attrs.into())) 141 ( 0.00%) }) . }; . } . . let this = self; . . // Note: when adding new unary operators, don't forget to adjust TokenKind::can_begin_expr() 174,342 ( 0.01%) match this.token.uninterpolate().kind { . token::Not => make_it!(this, attrs, |this, _| this.parse_unary_expr(lo, UnOp::Not)), // `!expr` . token::Tilde => make_it!(this, attrs, |this, _| this.recover_tilde_expr(lo)), // `~expr` . token::BinOp(token::Minus) => { . make_it!(this, attrs, |this, _| this.parse_unary_expr(lo, UnOp::Neg)) . } // `-expr` . token::BinOp(token::Star) => { 9 ( 0.00%) make_it!(this, attrs, |this, _| this.parse_unary_expr(lo, UnOp::Deref)) . } // `*expr` . token::BinOp(token::And) | token::AndAnd => { 12 ( 0.00%) make_it!(this, attrs, |this, _| this.parse_borrow_expr(lo)) . } . token::BinOp(token::Plus) if this.look_ahead(1, |tok| tok.is_numeric_lit()) => { . let mut err = this.struct_span_err(lo, "leading `+` is not supported"); . err.span_label(lo, "unexpected `+`"); . . // a block on the LHS might have been intended to be an expression instead . if let Some(sp) = this.sess.ambiguous_block_expr_parse.borrow().get(&lo) { . this.sess.expr_parentheses_needed(&mut err, *sp); -- line 562 ---------------------------------------- -- line 568 ---------------------------------------- . Applicability::MachineApplicable, . ); . } . err.emit(); . . this.bump(); . this.parse_prefix_expr(None) . } // `+expr` 57,708 ( 0.00%) token::Ident(..) if this.token.is_keyword(kw::Box) => { . make_it!(this, attrs, |this, _| this.parse_box_expr(lo)) . } . token::Ident(..) if this.is_mistaken_not_ident_negation() => { . make_it!(this, attrs, |this, _| this.recover_not_expr(lo)) . } . _ => return this.parse_dot_or_call_expr(Some(attrs)), . } 290,470 ( 0.01%) } . . fn parse_prefix_expr_common(&mut self, lo: Span) -> PResult<'a, (Span, P)> { 18 ( 0.00%) self.bump(); 36 ( 0.00%) let expr = self.parse_prefix_expr(None); 9 ( 0.00%) let (span, expr) = self.interpolated_or_expr_span(expr)?; 18 ( 0.00%) Ok((lo.to(span), expr)) . } . . fn parse_unary_expr(&mut self, lo: Span, op: UnOp) -> PResult<'a, (Span, ExprKind)> { . let (span, expr) = self.parse_prefix_expr_common(lo)?; . Ok((span, self.mk_unary(op, expr))) . } . . // Recover on `!` suggesting for bitwise negation instead. -- line 598 ---------------------------------------- -- line 619 ---------------------------------------- . fn is_mistaken_not_ident_negation(&self) -> bool { . let token_cannot_continue_expr = |t: &Token| match t.uninterpolate().kind { . // These tokens can start an expression after `!`, but . // can't continue an expression after an ident . token::Ident(name, is_raw) => token::ident_can_begin_expr(name, t.span, is_raw), . token::Literal(..) | token::Pound => true, . _ => t.is_whole_expr(), . }; 57,708 ( 0.00%) self.token.is_ident_named(sym::not) && self.look_ahead(1, token_cannot_continue_expr) . } . . /// Recover on `not expr` in favor of `!expr`. . fn recover_not_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> { . // Emit the error... . let not_token = self.look_ahead(1, |t| t.clone()); . self.struct_span_err( . not_token.span, -- line 635 ---------------------------------------- -- line 651 ---------------------------------------- . . /// Returns the span of expr, if it was not interpolated or the span of the interpolated token. . fn interpolated_or_expr_span( . &self, . expr: PResult<'a, P>, . ) -> PResult<'a, (Span, P)> { . expr.map(|e| { . ( 116,203 ( 0.01%) match self.prev_token.kind { . TokenKind::Interpolated(..) => self.prev_token.span, . _ => e.span, . }, . e, . ) . }) . } . -- line 667 ---------------------------------------- -- line 844 ---------------------------------------- . let lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type)?; . self.sess.gated_spans.gate(sym::type_ascription, lhs.span); . Ok(lhs) . } . . /// Parse `& mut? ` or `& raw [ const | mut ] `. . fn parse_borrow_expr(&mut self, lo: Span) -> PResult<'a, (Span, ExprKind)> { . self.expect_and()?; 30 ( 0.00%) let has_lifetime = self.token.is_lifetime() && self.look_ahead(1, |t| t != &token::Colon); . let lifetime = has_lifetime.then(|| self.expect_lifetime()); // For recovery, see below. . let (borrow_kind, mutbl) = self.parse_borrow_modifiers(lo); 24 ( 0.00%) let expr = self.parse_prefix_expr(None); 12 ( 0.00%) let (hi, expr) = self.interpolated_or_expr_span(expr)?; 6 ( 0.00%) let span = lo.to(hi); 12 ( 0.00%) if let Some(lt) = lifetime { . self.error_remove_borrow_lifetime(span, lt.ident.span); . } . Ok((span, ExprKind::AddrOf(borrow_kind, mutbl, expr))) . } . . fn error_remove_borrow_lifetime(&self, span: Span, lt_span: Span) { . self.struct_span_err(span, "borrow expressions cannot be annotated with lifetimes") . .span_label(lt_span, "annotated with lifetime here") -- line 866 ---------------------------------------- -- line 870 ---------------------------------------- . String::new(), . Applicability::MachineApplicable, . ) . .emit(); . } . . /// Parse `mut?` or `raw [ const | mut ]`. . fn parse_borrow_modifiers(&mut self, lo: Span) -> (ast::BorrowKind, ast::Mutability) { 12 ( 0.00%) if self.check_keyword(kw::Raw) && self.look_ahead(1, Token::is_mutability) { . // `raw [ const | mut ]`. . let found_raw = self.eat_keyword(kw::Raw); . assert!(found_raw); . let mutability = self.parse_const_or_mut().unwrap(); . self.sess.gated_spans.gate(sym::raw_ref_op, lo.to(self.prev_token.span)); . (ast::BorrowKind::Raw, mutability) . } else { . // `mut?` -- line 886 ---------------------------------------- -- line 889 ---------------------------------------- . } . . /// Parses `a.b` or `a(13)` or `a[4]` or just `a`. . fn parse_dot_or_call_expr(&mut self, attrs: Option) -> PResult<'a, P> { . let attrs = self.parse_or_use_outer_attributes(attrs)?; . self.collect_tokens_for_expr(attrs, |this, attrs| { . let base = this.parse_bottom_expr(); . let (span, base) = this.interpolated_or_expr_span(base)?; 116,128 ( 0.01%) this.parse_dot_or_call_expr_with(base, span, attrs) . }) . } . . pub(super) fn parse_dot_or_call_expr_with( . &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 203,329 ( 0.01%) self.parse_dot_or_call_expr_with_(e0, lo).map(|expr| { 203,329 ( 0.01%) expr.map(|mut expr| { 29,047 ( 0.00%) attrs.extend::>(expr.attrs.into()); 58,094 ( 0.00%) expr.attrs = attrs.into(); 406,658 ( 0.02%) expr . }) . }) . } . 900,457 ( 0.04%) 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 464 ( 0.00%) e = self.parse_dot_suffix_expr(lo, e)?; . continue; . } 1,306 ( 0.00%) if self.expr_is_complete(&e) { . return Ok(e); . } 60,218 ( 0.00%) e = match self.token.kind { 696 ( 0.00%) token::OpenDelim(token::Paren) => self.parse_fn_call_expr(lo, e), . token::OpenDelim(token::Bracket) => self.parse_index_expr(lo, e)?, 29,035 ( 0.00%) _ => return Ok(e), . } . } 261,423 ( 0.01%) } . . fn look_ahead_type_ascription_as_field(&mut self) -> bool { 949 ( 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> { 1,276 ( 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 { 1,160 ( 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 { 696 ( 0.00%) None . }; 232 ( 0.00%) let open_paren = self.token.span; . 464 ( 0.00%) let mut seq = self.parse_paren_expr_seq().map(|args| { 696 ( 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; . } 1,160 ( 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> { 2,320 ( 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(), . } . } . _ => {} 696 ( 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> { 232 ( 0.00%) if self.token.uninterpolated_span().rust_2018() && self.eat_keyword(kw::Await) { . return Ok(self.mk_await_expr(self_arg, lo)); . } . 116 ( 0.00%) let fn_span_lo = self.token.span; 696 ( 0.00%) let mut segment = self.parse_path_segment(PathStyle::Expr, None)?; 580 ( 0.00%) self.check_trailing_angle_brackets(&segment, &[&token::OpenDelim(token::Paren)]); . self.check_turbofish_missing_angle_brackets(&mut segment); . 580 ( 0.00%) if self.check(&token::OpenDelim(token::Paren)) { . // Method call `expr.f()` 116 ( 0.00%) let mut args = self.parse_paren_expr_seq()?; 464 ( 0.00%) args.insert(0, self_arg); . 348 ( 0.00%) let fn_span = fn_span_lo.to(self.prev_token.span); 348 ( 0.00%) let span = lo.to(self.prev_token.span); 580 ( 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 1217 ---------------------------------------- . } . . /// At the bottom (top?) of the precedence hierarchy, . /// Parses things like parenthesized exprs, macros, `return`, etc. . /// . /// N.B., this does not parse outer attributes, and is private because it only works . /// correctly if called from `parse_dot_or_call_expr()`. . fn parse_bottom_expr(&mut self) -> PResult<'a, P> { 82,828 ( 0.00%) maybe_recover_from_interpolated_ty_qpath!(self, true); 93,728 ( 0.00%) maybe_whole_expr!(self); . . // Outer attributes are already parsed and will be . // added to the return value after the fact. . // . // Therefore, prevent sub-parser from parsing . // attributes by giving them an empty "already-parsed" list. 28,629 ( 0.00%) let attrs = AttrVec::new(); . . // Note: when adding new syntax here, don't forget to adjust `TokenKind::can_begin_expr()`. 18,990 ( 0.00%) let lo = self.token.span; 85,392 ( 0.00%) if let token::Literal(_) = self.token.kind { . // This match arm is a special-case of the `_` match arm below and . // could be removed without changing functionality, but it's faster . // to have it here, especially for programs with large constants. 38,556 ( 0.00%) self.parse_lit_expr(attrs) 94,950 ( 0.00%) } else if self.check(&token::OpenDelim(token::Paren)) { 13,671 ( 0.00%) self.parse_tuple_parens_expr(attrs) 72,165 ( 0.00%) } else if self.check(&token::OpenDelim(token::Brace)) { . self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs) 144,330 ( 0.01%) } else if self.check(&token::BinOp(token::Or)) || self.check(&token::OrOr) { . self.parse_closure_expr(attrs) 72,165 ( 0.00%) } else if self.check(&token::OpenDelim(token::Bracket)) { 30 ( 0.00%) self.parse_array_or_repeat_expr(attrs, token::Bracket) 57,708 ( 0.00%) } else if self.check_path() { 57,660 ( 0.00%) self.parse_path_start_expr(attrs) 120 ( 0.00%) } else if self.check_keyword(kw::Move) || self.check_keyword(kw::Static) { . self.parse_closure_expr(attrs) 60 ( 0.00%) } else if self.eat_keyword(kw::If) { . self.parse_if_expr(attrs) 60 ( 0.00%) } else if self.check_keyword(kw::For) { . if self.choose_generics_over_qpath(1) { . // NOTE(Centril, eddyb): DO NOT REMOVE! Beyond providing parser recovery, . // this is an insurance policy in case we allow qpaths in (tuple-)struct patterns. . // When `for ::Proj in $expr $block` is wanted, . // you can disambiguate in favor of a pattern with `(...)`. . self.recover_quantified_closure_expr(attrs) . } else { . assert!(self.eat_keyword(kw::For)); . self.parse_for_expr(None, self.prev_token.span, attrs) . } 60 ( 0.00%) } else if self.eat_keyword(kw::While) { . self.parse_while_expr(None, self.prev_token.span, attrs) 48 ( 0.00%) } else if let Some(label) = self.eat_label() { . self.parse_labeled_expr(label, attrs, true) 60 ( 0.00%) } else if self.eat_keyword(kw::Loop) { . self.parse_loop_expr(None, self.prev_token.span, attrs) 60 ( 0.00%) } else if self.eat_keyword(kw::Continue) { . let kind = ExprKind::Continue(self.eat_label()); . Ok(self.mk_expr(lo.to(self.prev_token.span), kind, attrs)) 48 ( 0.00%) } else if self.eat_keyword(kw::Match) { 24 ( 0.00%) let match_sp = self.prev_token.span; 96 ( 0.00%) self.parse_match_expr(attrs).map_err(|mut err| { . err.span_label(match_sp, "while parsing this match expression"); . err . }) . } else if self.eat_keyword(kw::Unsafe) { . self.parse_block_expr(None, lo, BlockCheckMode::Unsafe(ast::UserProvided), attrs) . } else if self.check_inline_const(0) { . self.parse_const_block(lo.to(self.token.span), false) . } else if self.is_do_catch_block() { -- line 1286 ---------------------------------------- -- line 1325 ---------------------------------------- . } else { . self.parse_lit_expr(attrs) . } . } else { . self.parse_lit_expr(attrs) . } . } . 96,390 ( 0.00%) fn parse_lit_expr(&mut self, attrs: AttrVec) -> PResult<'a, P> { 19,278 ( 0.00%) let lo = self.token.span; 38,556 ( 0.00%) match self.parse_opt_lit() { 57,834 ( 0.00%) Some(literal) => { 86,751 ( 0.00%) let expr = self.mk_expr(lo.to(self.prev_token.span), ExprKind::Lit(literal), attrs); 96,390 ( 0.00%) self.maybe_recover_from_bad_qpath(expr, true) . } . None => self.try_macro_suggestion(), . } . } . . fn parse_tuple_parens_expr(&mut self, attrs: AttrVec) -> PResult<'a, P> { 9,114 ( 0.00%) let lo = self.token.span; 13,671 ( 0.00%) self.expect(&token::OpenDelim(token::Paren))?; . let (es, trailing_comma) = match self.parse_seq_to_end( . &token::CloseDelim(token::Paren), . SeqSep::trailing_allowed(token::Comma), 18,216 ( 0.00%) |p| p.parse_expr_catch_underscore(), . ) { . Ok(x) => x, . Err(err) => return Ok(self.recover_seq_parse_error(token::Paren, lo, Err(err))), . }; 22,785 ( 0.00%) let kind = if es.len() == 1 && !trailing_comma { . // `(e)` is parenthesized `e`. . ExprKind::Paren(es.into_iter().next().unwrap()) . } else { . // `(e,)` is a tuple with only one field, `e`. 22,785 ( 0.00%) ExprKind::Tup(es) . }; 13,671 ( 0.00%) let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs); 13,671 ( 0.00%) self.maybe_recover_from_bad_qpath(expr, true) . } . 66 ( 0.00%) fn parse_array_or_repeat_expr( . &mut self, . attrs: AttrVec, . close_delim: token::DelimToken, . ) -> PResult<'a, P> { 18 ( 0.00%) let lo = self.token.span; 6 ( 0.00%) self.bump(); // `[` or other open delim . 18 ( 0.00%) let close = &token::CloseDelim(close_delim); . let kind = if self.eat(close) { . // Empty vector . ExprKind::Array(Vec::new()) . } else { . // Non-empty vector 12 ( 0.00%) let first_expr = self.parse_expr()?; . if self.eat(&token::Semi) { . // Repeating array syntax: `[ 0; 512 ]` . let count = self.parse_anon_const_expr()?; . self.expect(close)?; . ExprKind::Repeat(first_expr, count) . } else if self.eat(&token::Comma) { . // Vector with two or more elements. . let sep = SeqSep::trailing_allowed(token::Comma); . let (remaining_exprs, _) = self.parse_seq_to_end(close, sep, |p| p.parse_expr())?; 6 ( 0.00%) let mut exprs = vec![first_expr]; . exprs.extend(remaining_exprs); 30 ( 0.00%) ExprKind::Array(exprs) . } else { . // Vector with one element . self.expect(close)?; . ExprKind::Array(vec![first_expr]) . } . }; 18 ( 0.00%) let expr = self.mk_expr(lo.to(self.prev_token.span), kind, attrs); 18 ( 0.00%) self.maybe_recover_from_bad_qpath(expr, true) 60 ( 0.00%) } . 144,150 ( 0.01%) fn parse_path_start_expr(&mut self, attrs: AttrVec) -> PResult<'a, P> { 115,320 ( 0.01%) let (qself, path) = if self.eat_lt() { . let (qself, path) = self.parse_qpath(PathStyle::Expr)?; . (Some(qself), path) . } else { 28,830 ( 0.00%) (None, self.parse_path(PathStyle::Expr)?) . }; 14,415 ( 0.00%) let lo = path.span; . . // `!`, as an operator, is prefix, so we know this isn't that. 147,900 ( 0.01%) let (hi, kind) = if self.eat(&token::Not) { . // MACRO INVOCATION expression 4,781 ( 0.00%) if qself.is_some() { . self.struct_span_err(path.span, "macros cannot use qualified paths").emit(); . } 28,686 ( 0.00%) let mac = MacCall { 33,467 ( 0.00%) path, . args: self.parse_mac_args()?, . prior_type_ascription: self.last_type_ascription, . }; 105,182 ( 0.00%) (self.prev_token.span, ExprKind::MacCall(mac)) 48,170 ( 0.00%) } else if self.check(&token::OpenDelim(token::Brace)) { 9,110 ( 0.00%) if let Some(expr) = self.maybe_parse_struct_expr(qself.as_ref(), &path, &attrs) { 4,555 ( 0.00%) if qself.is_some() { . self.sess.gated_spans.gate(sym::more_qualified_paths, path.span); . } . return expr; . } else { . (path.span, ExprKind::Path(qself, path)) . } . } else { . (path.span, ExprKind::Path(qself, path)) . }; . 19,720 ( 0.00%) let expr = self.mk_expr(lo.to(hi), kind, attrs); 29,580 ( 0.00%) self.maybe_recover_from_bad_qpath(expr, true) 163,870 ( 0.01%) } . . /// Parse `'label: $expr`. The label is already parsed. . fn parse_labeled_expr( . &mut self, . label: Label, . attrs: AttrVec, . mut consume_colon: bool, . ) -> PResult<'a, P> { -- line 1447 ---------------------------------------- -- line 1607 ---------------------------------------- . symbol_unescaped, . }), . _ => Err(Some(lit)), . }, . None => Err(None), . } . } . 4,617 ( 0.00%) pub(super) fn parse_lit(&mut self) -> PResult<'a, Lit> { 513 ( 0.00%) self.parse_opt_lit().ok_or_else(|| { 112 ( 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(); . } . } . } 616 ( 0.00%) let msg = format!("unexpected token: {}", super::token_descr(&self.token)); 56 ( 0.00%) self.struct_span_err(self.token.span, &msg) . }) 3,591 ( 0.00%) } . . /// Matches `lit = true | false | token_lit`. . /// Returns `None` if the next token is not a literal. 91,368 ( 0.00%) pub(super) fn parse_opt_lit(&mut self) -> Option { 10,152 ( 0.00%) let mut recovered = None; 60,912 ( 0.00%) 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); 30,624 ( 0.00%) match Lit::from_token(token) { 60,576 ( 0.00%) Ok(lit) => { 20,192 ( 0.00%) self.bump(); 60,576 ( 0.00%) Some(lit) . } 56 ( 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!())) . } . } 81,216 ( 0.00%) } . . 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 ---------------------------------------- -- line 1795 ---------------------------------------- . }; . err.span_label(sp, format!("invalid suffix `{}`", suf)); . err.emit(); . } . } . . /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`). . /// Keep this in sync with `Token::can_begin_literal_maybe_minus`. 880 ( 0.00%) pub fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P> { 1,650 ( 0.00%) maybe_whole_expr!(self); . . let lo = self.token.span; . let minus_present = self.eat(&token::BinOp(token::Minus)); . let lit = self.parse_lit()?; . let expr = self.mk_expr(lit.span, ExprKind::Lit(lit), AttrVec::new()); . . if minus_present { . Ok(self.mk_expr( . lo.to(self.prev_token.span), . self.mk_unary(UnOp::Neg, expr), . AttrVec::new(), . )) . } else { . Ok(expr) . } 990 ( 0.00%) } . . fn is_array_like_block(&mut self) -> bool { . self.look_ahead(1, |t| matches!(t.kind, TokenKind::Ident(..) | TokenKind::Literal(_))) . && self.look_ahead(2, |t| t == &token::Comma) . && self.look_ahead(3, |t| t.can_begin_expr()) . } . . /// Emits a suggestion if it looks like the user meant an array but -- line 1828 ---------------------------------------- -- line 2235 ---------------------------------------- . lo: Span, . mut attrs: AttrVec, . ) -> PResult<'a, P> { . let (iattrs, body) = self.parse_inner_attrs_and_block()?; . attrs.extend(iattrs); . Ok(self.mk_expr(lo.to(self.prev_token.span), ExprKind::Loop(body, opt_label), attrs)) . } . 48 ( 0.00%) fn eat_label(&mut self) -> Option RawTableInner { . #[inline] . const fn new_in(alloc: A) -> Self { 695,648 ( 0.03%) 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)] 273,234 ( 0.01%) unsafe fn new_uninitialized( . alloc: A, . table_layout: TableLayout, . buckets: usize, . fallibility: Fallibility, . ) -> Result { . debug_assert!(buckets.is_power_of_two()); . . // Avoid `Option::ok_or_else` because it bloats LLVM IR. -- line 1071 ---------------------------------------- -- line 1078 ---------------------------------------- . // exceed `isize::MAX`. We can skip this check on 64-bit systems since . // such allocations will never succeed anyways. . // . // This mirrors what Vec does in the standard library. . if mem::size_of::() < 8 && layout.size() > isize::MAX as usize { . return Err(fallibility.capacity_overflow()); . } . 65,768 ( 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)); 158,004 ( 0.01%) Ok(Self { . ctrl, 60,100 ( 0.00%) bucket_mask: buckets - 1, . items: 0, . growth_left: bucket_mask_to_capacity(buckets - 1), . alloc, . }) 199,712 ( 0.01%) } . . #[inline] 40,401 ( 0.00%) fn fallible_with_capacity( . alloc: A, . table_layout: TableLayout, . capacity: usize, . fallibility: Fallibility, . ) -> Result { 10,146 ( 0.00%) if capacity == 0 { 23,244 ( 0.00%) Ok(Self::new_in(alloc)) . } else { . unsafe { . let buckets = . capacity_to_buckets(capacity).ok_or_else(|| fallibility.capacity_overflow())?; . 126,170 ( 0.01%) let result = Self::new_uninitialized(alloc, table_layout, buckets, fallibility)?; . result.ctrl(0).write_bytes(EMPTY, result.num_ctrl_bytes()); . 2,472 ( 0.00%) Ok(result) . } . } 40,401 ( 0.00%) } . . /// Searches for an empty or deleted bucket which is suitable for inserting . /// a new element and sets the hash for that slot. . /// . /// There must be at least 1 empty bucket in the table. . #[inline] 42,587 ( 0.00%) unsafe fn prepare_insert_slot(&self, hash: u64) -> (usize, u8) { . let index = self.find_insert_slot(hash); 42,587 ( 0.00%) let old_ctrl = *self.ctrl(index); . self.set_ctrl_h2(index, hash); . (index, old_ctrl) 85,174 ( 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)); 904,066 ( 0.04%) if let Some(bit) = group.match_empty_or_deleted().lowest_set_bit() { 2,511,207 ( 0.12%) 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). 1,174,013 ( 0.06%) if unlikely(is_full(*self.ctrl(result))) { . debug_assert!(self.bucket_mask < Group::WIDTH); . debug_assert_ne!(probe_seq.pos, 0); . return Group::load_aligned(self.ctrl(0)) . .match_empty_or_deleted() . .lowest_set_bit_nonzero(); . } . . return result; -- line 1165 ---------------------------------------- -- line 1171 ---------------------------------------- . . /// Searches for an element in the table. This uses dynamic dispatch to reduce the amount of . /// code generated, but it is eliminated by LLVM optimizations. . #[inline] . fn find_inner(&self, hash: u64, eq: &mut dyn FnMut(usize) -> bool) -> Option { . let h2_hash = h2(hash); . let mut probe_seq = self.probe_seq(hash); . 8,840 ( 0.00%) loop { . let group = unsafe { Group::load(self.ctrl(probe_seq.pos)) }; . 4,413,467 ( 0.21%) for bit in group.match_byte(h2_hash) { 8,597,064 ( 0.40%) let index = (probe_seq.pos + bit) & self.bucket_mask; . 5,590,339 ( 0.26%) if likely(eq(index)) { . return Some(index); . } . } . 1,233,335 ( 0.06%) 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(); 3,522,672 ( 0.17%) 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 { 22,260,487 ( 1.05%) 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) { 1,685,090 ( 0.08%) self.growth_left -= special_is_empty(old_ctrl) as usize; . self.set_ctrl_h2(index, hash); 1,348,072 ( 0.06%) 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] | . // --------------------------------------------- 2,476,251 ( 0.12%) let index2 = ((index.wrapping_sub(Group::WIDTH)) & self.bucket_mask) + Group::WIDTH; . 825,417 ( 0.04%) *self.ctrl(index) = ctrl; 825,452 ( 0.04%) *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 { 330,484 ( 0.02%) self.bucket_mask + 1 . } . . #[inline] . fn num_ctrl_bytes(&self) -> usize { 146,688 ( 0.01%) self.bucket_mask + 1 + Group::WIDTH . } . . #[inline] . fn is_empty_singleton(&self) -> bool { 1,156,296 ( 0.05%) 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. 804 ( 0.00%) let mut new_table = RawTableInner::fallible_with_capacity( . self.alloc.clone(), . table_layout, . capacity, . fallibility, . )?; 83,090 ( 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_| { 33,620 ( 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. 67,241 ( 0.00%) let new_items = match self.items.checked_add(additional) { . Some(new_items) => new_items, . None => return Err(fallibility.capacity_overflow()), . }; 67,240 ( 0.00%) let full_capacity = bucket_mask_to_capacity(self.bucket_mask); 141,306 ( 0.01%) if new_items <= full_capacity / 2 { . // Rehash in-place without re-allocating if we have plenty of spare . // capacity that is locked up due to DELETED entries. . self.rehash_in_place(hasher, layout.size, drop); . Ok(()) . } else { . // Otherwise, conservatively resize to at least the next size up . // to avoid churning deletes into frequent rehashes. . self.resize_inner( 33,620 ( 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> { 1,934 ( 0.00%) let mut new_table = self.prepare_resize(layout, capacity, fallibility)?; . . // Copy all elements to the new table. . for i in 0..self.buckets() { 534,312 ( 0.03%) 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); . 33,620 ( 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( 25,203 ( 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) { 7,143 ( 0.00%) if !self.is_empty_singleton() { . unsafe { . self.ctrl(0).write_bytes(EMPTY, self.num_ctrl_bytes()); . } . } 12,025 ( 0.00%) self.items = 0; 7,143 ( 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))); 48,602 ( 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. 194,408 ( 0.01%) let ctrl = if empty_before.leading_zeros() + empty_after.trailing_zeros() >= Group::WIDTH { . DELETED . } else { 242,310 ( 0.01%) self.growth_left += 1; . EMPTY . }; . self.set_ctrl(index, ctrl); 194,408 ( 0.01%) self.items -= 1; . } . } . . impl Clone for RawTable { 109,680 ( 0.01%) fn clone(&self) -> Self { 13,710 ( 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) . } . } 123,390 ( 0.01%) } . . fn clone_from(&mut self, source: &Self) { . if source.table.is_empty_singleton() { . *self = Self::new_in(self.table.alloc.clone()); . } else { . unsafe { . // First, drop all our elements without clearing the control bytes. . self.drop_elements(); -- line 1640 ---------------------------------------- -- line 1687 ---------------------------------------- . .table . .ctrl(0) . .copy_to_nonoverlapping(self.table.ctrl(0), self.table.num_ctrl_bytes()); . source . .data_start() . .copy_to_nonoverlapping(self.data_start(), self.table.buckets()); . . self.table.items = source.table.items; 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)] 664,590 ( 0.03%) fn drop(&mut self) { 485,744 ( 0.02%) if !self.table.is_empty_singleton() { . unsafe { . self.drop_elements(); . self.free_buckets(); . } . } 712,218 ( 0.03%) } . } . #[cfg(not(feature = "nightly"))] . impl Drop for RawTable { . #[cfg_attr(feature = "inline-more", inline)] . fn drop(&mut self) { . if !self.table.is_empty_singleton() { . unsafe { . self.drop_elements(); -- line 1813 ---------------------------------------- -- line 1817 ---------------------------------------- . } . } . . impl IntoIterator for RawTable { . type Item = T; . type IntoIter = RawIntoIter; . . #[cfg_attr(feature = "inline-more", inline)] 1,288 ( 0.00%) fn into_iter(self) -> RawIntoIter { . unsafe { . let iter = self.iter(); . self.into_iter_from(iter) . } 1,610 ( 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 { 307,502 ( 0.01%) if let Some(index) = self.current_group.lowest_set_bit() { 66,476 ( 0.00%) self.current_group = self.current_group.remove_lowest_bit(); 119,346 ( 0.01%) return Some(self.data.next_n(index)); . } . 310,732 ( 0.01%) if self.next_ctrl >= self.end { . return None; . } . . // We might read past self.end up to the next group boundary, . // but this is fine because it only occurs on tables smaller . // than the group size where the trailing control bytes are all . // EMPTY. On larger tables self.end is guaranteed to be aligned . // to the group size (since tables are power-of-two sized). 11,444 ( 0.00%) self.current_group = Group::load_aligned(self.next_ctrl).match_full(); 13,292 ( 0.00%) self.data = self.data.next_n(Group::WIDTH); 11,762 ( 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) { 13,945 ( 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)] 79,082 ( 0.00%) fn next(&mut self) -> Option> { 137,402 ( 0.01%) if let Some(b) = self.iter.next() { 403,763 ( 0.02%) 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 . } 158,164 ( 0.01%) } . . #[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)] 604 ( 0.00%) fn drop(&mut self) { . unsafe { . // Drop all remaining elements . self.iter.drop_elements(); . . // Free the table 2,726 ( 0.00%) if let Some((ptr, layout)) = self.allocation { . self.alloc.deallocate(ptr, layout); . } . } 146 ( 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,251 ( 0.00%) fn next(&mut self) -> Option { 13,767 ( 0.00%) unsafe { Some(self.iter.next()?.read()) } 18,502 ( 0.00%) } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 3 ( 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)] 36,536 ( 0.00%) fn drop(&mut self) { . unsafe { . // Drop all remaining elements. Note that this may panic. . self.iter.drop_elements(); . . // Reset the contents of the table now that all elements have been . // dropped. . self.table.clear_no_drop(); . . // Move the now empty table back to its original location. 4,567 ( 0.00%) self.orig_table . .as_ptr() . .copy_from_nonoverlapping(&*self.table, 1); . } 36,536 ( 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 ---------------------------------------- 11,149,145 ( 0.52%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/operand.rs -------------------------------------------------------------------------------- Ir -- line 55 ---------------------------------------- . Immediate::Scalar(ScalarMaybeUninit::from_pointer(p, cx)) . } . . pub fn from_maybe_pointer(p: Pointer>, cx: &impl HasDataLayout) -> Self { . Immediate::Scalar(ScalarMaybeUninit::from_maybe_pointer(p, cx)) . } . . pub fn new_slice(val: Scalar, len: u64, cx: &impl HasDataLayout) -> Self { 54 ( 0.00%) Immediate::ScalarPair(val.into(), Scalar::from_machine_usize(len, cx).into()) . } . . pub fn new_dyn_trait( . val: Scalar, . vtable: Pointer>, . cx: &impl HasDataLayout, . ) -> Self { . Immediate::ScalarPair(val.into(), ScalarMaybeUninit::from_maybe_pointer(vtable, cx)) . } . . #[inline] . pub fn to_scalar_or_uninit(self) -> ScalarMaybeUninit { 100,994 ( 0.00%) match self { 146,632 ( 0.01%) Immediate::Scalar(val) => val, . Immediate::ScalarPair(..) => bug!("Got a scalar pair where a scalar was expected"), . } . } . . #[inline] . pub fn to_scalar(self) -> InterpResult<'tcx, Scalar> { . self.to_scalar_or_uninit().check_init() . } -- line 85 ---------------------------------------- -- line 159 ---------------------------------------- . fn deref(&self) -> &Immediate { . &self.imm . } . } . . /// An `Operand` is the result of computing a `mir::Operand`. It can be immediate, . /// or still in memory. The latter is an optimization, to delay reading that chunk of . /// memory and to avoid having to store arbitrary-sized data here. 12 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, HashStable, Hash, Debug)] . pub enum Operand { . Immediate(Immediate), . Indirect(MemPlace), . } . . #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] . pub struct OpTy<'tcx, Tag: Provenance = AllocId> { . op: Operand, // Keep this private; it helps enforce invariants. -- line 175 ---------------------------------------- -- line 185 ---------------------------------------- . fn deref(&self) -> &Operand { . &self.op . } . } . . impl<'tcx, Tag: Provenance> From> for OpTy<'tcx, Tag> { . #[inline(always)] . fn from(mplace: MPlaceTy<'tcx, Tag>) -> Self { 248 ( 0.00%) OpTy { op: Operand::Indirect(*mplace), layout: mplace.layout } . } . } . . impl<'tcx, Tag: Provenance> From<&'_ MPlaceTy<'tcx, Tag>> for OpTy<'tcx, Tag> { . #[inline(always)] . fn from(mplace: &MPlaceTy<'tcx, Tag>) -> Self { . OpTy { op: Operand::Indirect(**mplace), layout: mplace.layout } . } -- line 201 ---------------------------------------- -- line 248 ---------------------------------------- . . impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { . /// Try reading an immediate in memory; this is interesting particularly for `ScalarPair`. . /// Returns `None` if the layout does not permit loading this as a value. . fn try_read_immediate_from_mplace( . &self, . mplace: &MPlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, Option>> { 73,367 ( 0.00%) if mplace.layout.is_unsized() { . // Don't touch unsized . return Ok(None); . } . 192,753 ( 0.01%) let alloc = match self.get_alloc(mplace)? { 321,255 ( 0.02%) Some(ptr) => ptr, . None => { . return Ok(Some(ImmTy { . // zero-sized type . imm: Scalar::ZST.into(), . layout: mplace.layout, . })); . } . }; . 504,858 ( 0.02%) match mplace.layout.abi { . Abi::Scalar(..) => { 55,118 ( 0.00%) let scalar = alloc.read_scalar(alloc_range(Size::ZERO, mplace.layout.size))?; . Ok(Some(ImmTy { imm: scalar.into(), layout: mplace.layout })) . } 13,725 ( 0.00%) Abi::ScalarPair(a, b) => { . // We checked `ptr_align` above, so all fields will have the alignment they need. . // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`, . // which `ptr.offset(b_offset)` cannot possibly fail to satisfy. . let (a, b) = (a.value, b.value); . let (a_size, b_size) = (a.size(self), b.size(self)); . let b_offset = a_size.align_to(b.align(self).abi); 9,150 ( 0.00%) assert!(b_offset.bytes() > 0); // we later use the offset to tell apart the fields . let a_val = alloc.read_scalar(alloc_range(Size::ZERO, a_size))?; 13,725 ( 0.00%) let b_val = alloc.read_scalar(alloc_range(b_offset, b_size))?; 22,875 ( 0.00%) Ok(Some(ImmTy { imm: Immediate::ScalarPair(a_val, b_val), layout: mplace.layout })) . } . _ => Ok(None), . } . } . . /// Try returning an immediate for the operand. . /// If the layout does not permit loading this as an immediate, return where in memory . /// we can find the data. . /// Note that for a given layout, this operation will either always fail or always . /// succeed! Whether it succeeds depends on whether the layout can be represented . /// in an `Immediate`, not on which data is stored there currently. 660,636 ( 0.03%) pub fn try_read_immediate( . &self, . src: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, Result, MPlaceTy<'tcx, M::PointerTag>>> { 1,321,272 ( 0.06%) Ok(match src.try_as_mplace() { . Ok(ref mplace) => { 128,502 ( 0.01%) if let Some(val) = self.try_read_immediate_from_mplace(mplace)? { . Ok(val) . } else { . Err(*mplace) . } . } 91,530 ( 0.00%) Err(val) => Ok(val), . }) 660,636 ( 0.03%) } . . /// Read an immediate from a place, asserting that that is possible with the given layout. . #[inline(always)] . pub fn read_immediate( . &self, . op: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, ImmTy<'tcx, M::PointerTag>> { 165,567 ( 0.01%) if let Ok(imm) = self.try_read_immediate(op)? { 293,684 ( 0.01%) Ok(imm) . } else { . span_bug!(self.cur_span(), "primitive read failed for type: {:?}", op.layout.ty); . } . } . . /// Read a scalar from a place 403,238 ( 0.02%) pub fn read_scalar( . &self, . op: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, ScalarMaybeUninit> { 36,658 ( 0.00%) Ok(self.read_immediate(op)?.to_scalar_or_uninit()) 329,922 ( 0.02%) } . . /// Read a pointer from a place. . pub fn read_pointer( . &self, . op: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, Pointer>> { . Ok(self.scalar_to_ptr(self.read_scalar(op)?.check_init()?)) . } -- line 342 ---------------------------------------- -- line 345 ---------------------------------------- . pub fn read_str(&self, mplace: &MPlaceTy<'tcx, M::PointerTag>) -> InterpResult<'tcx, &str> { . let len = mplace.len(self)?; . let bytes = self.memory.read_bytes(mplace.ptr, Size::from_bytes(len))?; . let str = std::str::from_utf8(bytes).map_err(|err| err_ub!(InvalidStr(err)))?; . Ok(str) . } . . /// Projection functions 594,920 ( 0.03%) pub fn operand_field( . &self, . op: &OpTy<'tcx, M::PointerTag>, . field: usize, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { . let base = match op.try_as_mplace() { . Ok(ref mplace) => { . // We can reuse the mplace field computation logic for indirect operands. . let field = self.mplace_field(mplace, field)?; 654,412 ( 0.03%) return Ok(field.into()); . } . Err(value) => value, . }; . . let field_layout = op.layout.field(self, field); . if field_layout.is_zst() { . let immediate = Scalar::ZST.into(); . return Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout }); -- line 370 ---------------------------------------- -- line 381 ---------------------------------------- . Immediate::Scalar(val) => span_bug!( . self.cur_span(), . "field access on non aggregate {:#?}, {:#?}", . val, . op.layout . ), . }; . Ok(OpTy { op: Operand::Immediate(immediate), layout: field_layout }) 535,428 ( 0.03%) } . . pub fn operand_index( . &self, . op: &OpTy<'tcx, M::PointerTag>, . index: u64, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { . if let Ok(index) = usize::try_from(index) { . // We can just treat this as a field. -- line 397 ---------------------------------------- -- line 398 ---------------------------------------- . self.operand_field(op, index) . } else { . // Indexing into a big array. This must be an mplace. . let mplace = op.assert_mem_place(); . Ok(self.mplace_index(&mplace, index)?.into()) . } . } . 101,431 ( 0.00%) pub fn operand_downcast( . &self, . op: &OpTy<'tcx, M::PointerTag>, . variant: VariantIdx, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { . // Downcasts only change the layout 156,757 ( 0.01%) Ok(match op.try_as_mplace() { 92,210 ( 0.00%) Ok(ref mplace) => self.mplace_downcast(mplace, variant)?.into(), . Err(..) => { . let layout = op.layout.for_variant(self, variant); . OpTy { layout, ..*op } . } . }) 82,989 ( 0.00%) } . . pub fn operand_projection( . &self, . base: &OpTy<'tcx, M::PointerTag>, . proj_elem: mir::PlaceElem<'tcx>, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { . use rustc_middle::mir::ProjectionElem::*; . Ok(match proj_elem { -- line 427 ---------------------------------------- -- line 449 ---------------------------------------- . self.mplace_to_simd(&base.assert_mem_place()) . } . . /// Read from a local. Will not actually access the local if reading from a ZST. . /// Will not access memory, instead an indirect `Operand` is returned. . /// . /// This is public because it is used by [priroda](https://github.com/oli-obk/priroda) to get an . /// OpTy from a local 123,786 ( 0.01%) pub fn access_local( . &self, . frame: &super::Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>, . local: mir::Local, . layout: Option>, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { . let layout = self.layout_of_local(frame, local, layout)?; 4,558 ( 0.00%) let op = if layout.is_zst() { . // Do not read from ZST, they might not be initialized . Operand::Immediate(Scalar::ZST.into()) . } else { . M::access_local(&self, frame, local)? . }; 178,802 ( 0.01%) Ok(OpTy { op, layout }) 110,032 ( 0.01%) } . . /// Every place can be read from, so we can turn them into an operand. . /// This will definitely return `Indirect` if the place is a `Ptr`, i.e., this . /// will never actually read from memory. . #[inline(always)] . pub fn place_to_op( . &self, . place: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { 24 ( 0.00%) let op = match **place { . Place::Ptr(mplace) => Operand::Indirect(mplace), . Place::Local { frame, local } => { 108 ( 0.00%) *self.access_local(&self.stack()[frame], local, None)? . } . }; 84 ( 0.00%) Ok(OpTy { op, layout: place.layout }) . } . . // Evaluate a place with the goal of reading from it. This lets us sometimes . // avoid allocations. 109,808 ( 0.01%) pub fn eval_place_to_op( . &self, . place: mir::Place<'tcx>, . layout: Option>, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { . // Do not use the layout passed in as argument if the base we are looking at . // here is not the entire place. 13,726 ( 0.00%) let layout = if place.projection.is_empty() { layout } else { None }; . 41,178 ( 0.00%) let base_op = self.access_local(self.frame(), place.local, layout)?; . . let op = place . .projection . .iter() . .try_fold(base_op, |op, elem| self.operand_projection(&op, elem))?; . . trace!("eval_place_to_op: got {:?}", *op); . // Sanity-check the type we ended up with. -- line 509 ---------------------------------------- -- line 510 ---------------------------------------- . debug_assert!(mir_assign_valid_types( . *self.tcx, . self.param_env, . self.layout_of(self.subst_from_current_frame_and_normalize_erasing_regions( . place.ty(&self.frame().body.local_decls, *self.tcx).ty . )?)?, . op.layout, . )); 41,178 ( 0.00%) Ok(op) 123,534 ( 0.01%) } . . /// Evaluate the operand, returning a place where you can then find the data. . /// If you already know the layout, you can save two table lookups . /// by passing it in here. . #[inline] 205,614 ( 0.01%) pub fn eval_operand( . &self, . mir_op: &mir::Operand<'tcx>, . layout: Option>, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { . use rustc_middle::mir::Operand::*; 45,692 ( 0.00%) let op = match *mir_op { . // FIXME: do some more logic on `move` to invalidate the old location 68,630 ( 0.00%) Copy(place) | Move(place) => self.eval_place_to_op(place, layout)?, . . Constant(ref constant) => { . let val = 136,800 ( 0.01%) self.subst_from_current_frame_and_normalize_erasing_regions(constant.literal)?; . // This can still fail: . // * During ConstProp, with `TooGeneric` or since the `requried_consts` were not all . // checked yet. . // * During CTFE, since promoteds in `const`/`static` initializer bodies can fail. . . self.mir_const_to_op(&val, layout)? . } . }; . trace!("{:?}: {:?}", mir_op, *op); 296,998 ( 0.01%) Ok(op) 137,076 ( 0.01%) } . . /// Evaluate a bunch of operands at once . pub(super) fn eval_operands( . &self, . ops: &[mir::Operand<'tcx>], . ) -> InterpResult<'tcx, Vec>> { . ops.iter().map(|op| self.eval_operand(op, None)).collect() . } . . // Used when the miri-engine runs into a constant and for extracting information from constants . // in patterns via the `const_eval` module . /// The `val` and `layout` are assumed to already be in our interpreter . /// "universe" (param_env). 109,440 ( 0.01%) pub fn const_to_op( . &self, . val: &ty::Const<'tcx>, . layout: Option>, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { 45,600 ( 0.00%) match val.val { . ty::ConstKind::Param(_) | ty::ConstKind::Bound(..) => throw_inval!(TooGeneric), . ty::ConstKind::Error(_) => throw_inval!(AlreadyReported(ErrorReported)), . ty::ConstKind::Unevaluated(uv) => { . let instance = self.resolve(uv.def, uv.substs)?; . Ok(self.eval_to_allocation(GlobalId { instance, promoted: uv.promoted })?.into()) . } . ty::ConstKind::Infer(..) | ty::ConstKind::Placeholder(..) => { . span_bug!(self.cur_span(), "const_to_op: Unexpected ConstKind {:?}", val) . } 91,200 ( 0.00%) ty::ConstKind::Value(val_val) => self.const_val_to_op(val_val, val.ty, layout), . } 82,080 ( 0.00%) } . . pub fn mir_const_to_op( . &self, . val: &mir::ConstantKind<'tcx>, . layout: Option>, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { 18,240 ( 0.00%) match val { 36,480 ( 0.00%) mir::ConstantKind::Ty(ct) => self.const_to_op(ct, layout), . mir::ConstantKind::Val(val, ty) => self.const_val_to_op(*val, ty, layout), . } . } . 91,200 ( 0.00%) crate fn const_val_to_op( . &self, . val_val: ConstValue<'tcx>, . ty: Ty<'tcx>, . layout: Option>, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { . // Other cases need layout. . let tag_scalar = |scalar| -> InterpResult<'tcx, _> { 54,702 ( 0.00%) Ok(match scalar { . Scalar::Ptr(ptr, size) => Scalar::Ptr(self.global_base_pointer(ptr)?, size), 27,333 ( 0.00%) Scalar::Int(int) => Scalar::Int(int), . }) . }; . let layout = from_known_layout(self.tcx, self.param_env, layout, || self.layout_of(ty))?; 27,366 ( 0.00%) let op = match val_val { . ConstValue::ByRef { alloc, offset } => { . let id = self.tcx.create_memory_alloc(alloc); . // We rely on mutability being set correctly in that allocation to prevent writes . // where none should happen. . let ptr = self.global_base_pointer(Pointer::new(id, offset))?; . Operand::Indirect(MemPlace::from_ptr(ptr.into(), layout.align.abi)) . } 82,053 ( 0.00%) ConstValue::Scalar(x) => Operand::Immediate(tag_scalar(x)?.into()), 9 ( 0.00%) ConstValue::Slice { data, start, end } => { . // We rely on mutability being set correctly in `data` to prevent writes . // where none should happen. . let ptr = Pointer::new( 9 ( 0.00%) self.tcx.create_memory_alloc(data), . Size::from_bytes(start), // offset: `start` . ); . Operand::Immediate(Immediate::new_slice( . Scalar::from_pointer(self.global_base_pointer(ptr)?, &*self.tcx), . u64::try_from(end.checked_sub(start).unwrap()).unwrap(), // len: `end - start` . self, . )) . } . }; 191,520 ( 0.01%) Ok(OpTy { op, layout }) 72,960 ( 0.00%) } . . /// Read discriminant, return the runtime value as well as the variant index. . /// Can also legally be called on non-enums (e.g. through the discriminant_value intrinsic)! 138,330 ( 0.01%) pub fn read_discriminant( . &self, . op: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, (Scalar, VariantIdx)> { . trace!("read_discriminant_value {:#?}", op.layout); . // Get type and layout of the discriminant. 165,996 ( 0.01%) let discr_layout = self.layout_of(op.layout.ty.discriminant_ty(*self.tcx))?; . trace!("discriminant type: {:?}", discr_layout.ty); . . // We use "discriminant" to refer to the value associated with a particular enum variant. . // This is not to be confused with its "variant index", which is just determining its position in the . // declared list of variants -- they can differ with explicitly assigned discriminants. . // We use "tag" to refer to how the discriminant is encoded in memory, which can be either . // straight-forward (`TagEncoding::Direct`) or with a niche (`TagEncoding::Niche`). 41,499 ( 0.00%) let (tag_scalar_layout, tag_encoding, tag_field) = match op.layout.variants { . Variants::Single { index } => { . let discr = match op.layout.ty.discriminant_for_variant(*self.tcx, index) { . Some(discr) => { . // This type actually has discriminants. . assert_eq!(discr.ty, discr_layout.ty); . Scalar::from_uint(discr.val, discr_layout.size) . } . None => { . // On a type without actual discriminants, variant is 0. . assert_eq!(index.as_u32(), 0); . Scalar::from_uint(index.as_u32(), discr_layout.size) . } . }; . return Ok((discr, index)); . } 27,666 ( 0.00%) Variants::Multiple { tag, ref tag_encoding, tag_field, .. } => { . (tag, tag_encoding, tag_field) . } . }; . . // There are *three* layouts that come into play here: . // - The discriminant has a type for typechecking. This is `discr_layout`, and is used for . // the `Scalar` we return. . // - The tag (encoded discriminant) has layout `tag_layout`. This is always an integer type, . // and used to interpret the value we read from the tag field. . // For the return value, a cast to `discr_layout` is performed. . // - The field storing the tag has a layout, which is very similar to `tag_layout` but . // may be a pointer. This is `tag_val.layout`; we just use it for sanity checks. . . // Get layout for tag. 82,998 ( 0.00%) let tag_layout = self.layout_of(tag_scalar_layout.value.to_int_ty(*self.tcx))?; . . // Read tag and sanity-check `tag_layout`. 96,831 ( 0.00%) let tag_val = self.read_immediate(&self.operand_field(op, tag_field)?)?; 27,666 ( 0.00%) assert_eq!(tag_layout.size, tag_val.layout.size); 110,664 ( 0.01%) assert_eq!(tag_layout.abi.is_signed(), tag_val.layout.abi.is_signed()); . let tag_val = tag_val.to_scalar()?; . trace!("tag value: {:?}", tag_val); . . // Figure out which discriminant and variant this corresponds to. 124,497 ( 0.01%) Ok(match *tag_encoding { . TagEncoding::Direct => { 276,660 ( 0.01%) let tag_bits = tag_val . .try_to_int() . .map_err(|dbg_val| err_ub!(InvalidTag(dbg_val)))? . .assert_bits(tag_layout.size); . // Cast bits from tag layout to discriminant layout. 110,664 ( 0.01%) let discr_val = self.cast_from_scalar(tag_bits, tag_layout, discr_layout.ty); 27,666 ( 0.00%) let discr_bits = discr_val.assert_bits(discr_layout.size); . // Convert discriminant to variant index, and catch invalid discriminants. 69,165 ( 0.00%) let index = match *op.layout.ty.kind() { 13,833 ( 0.00%) ty::Adt(adt, _) => { 562,134 ( 0.03%) adt.discriminants(*self.tcx).find(|(_, var)| var.val == discr_bits) . } . ty::Generator(def_id, substs, _) => { . let substs = substs.as_generator(); . substs . .discriminants(def_id, *self.tcx) . .find(|(_, var)| var.val == discr_bits) . } . _ => span_bug!(self.cur_span(), "tagged layout for non-adt non-generator"), . } . .ok_or_else(|| err_ub!(InvalidTag(Scalar::from_uint(tag_bits, tag_layout.size))))?; . // Return the cast value, and the index. 55,332 ( 0.00%) (discr_val, index.0) . } . TagEncoding::Niche { dataful_variant, ref niche_variants, niche_start } => { . // Compute the variant this niche value/"tag" corresponds to. With niche layout, . // discriminant (encoded in niche/tag) and variant index are the same. . let variants_start = niche_variants.start().as_u32(); . let variants_end = niche_variants.end().as_u32(); . let variant = match tag_val.try_to_int() { . Err(dbg_val) => { -- line 721 ---------------------------------------- -- line 766 ---------------------------------------- . } . }; . // Compute the size of the scalar we need to return. . // No need to cast, because the variant index directly serves as discriminant and is . // encoded in the tag. . (Scalar::from_uint(variant.as_u32(), discr_layout.size), variant) . } . }) 124,497 ( 0.01%) } . } 1,940,667 ( 0.09%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_resolve/src/imports.rs -------------------------------------------------------------------------------- Ir -- line 109 ---------------------------------------- . /// The resolution of `module_path`. . pub imported_module: Cell>>, . pub vis: Cell, . pub used: Cell, . } . . impl<'a> Import<'a> { . pub fn is_glob(&self) -> bool { 14,721 ( 0.00%) matches!(self.kind, ImportKind::Glob { .. }) . } . . pub fn is_nested(&self) -> bool { . match self.kind { . ImportKind::Single { nested, .. } => nested, . _ => false, . } . } . . crate fn crate_lint(&self) -> CrateLint { 388 ( 0.00%) CrateLint::UsePath { root_id: self.root_id, root_span: self.root_span } 656 ( 0.00%) } . } . 5,547 ( 0.00%) #[derive(Clone, Default, Debug)] . /// Records information about the resolution of a name in a namespace of a module. . pub struct NameResolution<'a> { . /// Single imports that may define the name in the namespace. . /// Imports are arena-allocated, so it's ok to use pointers as keys. . single_imports: FxHashSet>>, . /// The least shadowable known binding for this name, or None if there are no known bindings. . pub binding: Option<&'a NameBinding<'a>>, . shadowed_glob: Option<&'a NameBinding<'a>>, . } . . impl<'a> NameResolution<'a> { . // Returns the binding for the name if it is known or None if it not known. . pub(crate) fn binding(&self) -> Option<&'a NameBinding<'a>> { 2,054 ( 0.00%) self.binding.and_then(|binding| { 686 ( 0.00%) if !binding.is_glob_import() || self.single_imports.is_empty() { . Some(binding) . } else { . None . } . }) . } . . crate fn add_single_import(&mut self, import: &'a Import<'a>) { -- line 155 ---------------------------------------- -- line 177 ---------------------------------------- . &mut self, . module: ModuleOrUniformRoot<'a>, . ident: Ident, . ns: Namespace, . parent_scope: &ParentScope<'a>, . record_used: bool, . path_span: Span, . ) -> Result<&'a NameBinding<'a>, Determinacy> { 99,367 ( 0.00%) self.resolve_ident_in_module_unadjusted_ext( . module, . ident, . ns, . parent_scope, . false, . record_used, . path_span, . ) . .map_err(|(determinacy, _)| determinacy) . } . . /// Attempts to resolve `ident` in namespaces `ns` of `module`. . /// Invariant: if `record_used` is `Some`, expansion and import resolution must be complete. 903,000 ( 0.04%) crate fn resolve_ident_in_module_unadjusted_ext( . &mut self, . module: ModuleOrUniformRoot<'a>, . ident: Ident, . ns: Namespace, . parent_scope: &ParentScope<'a>, . restricted_shadowing: bool, . record_used: bool, . path_span: Span, -- line 207 ---------------------------------------- -- line 259 ---------------------------------------- . path_span, . ); . return binding.map_err(|determinacy| (determinacy, Weak::No)); . } . }; . . let key = self.new_key(ident, ns); . let resolution = 344,000 ( 0.02%) self.resolution(module, key).try_borrow_mut().map_err(|_| (Determined, Weak::No))?; // This happens when there is a cycle of imports. . 161,840 ( 0.01%) if let Some(binding) = resolution.binding { 16,418 ( 0.00%) if !restricted_shadowing && binding.expansion != LocalExpnId::ROOT { 14,458 ( 0.00%) if let NameBindingKind::Res(_, true) = binding.kind { . self.macro_expanded_macro_export_errors.insert((path_span, binding.span)); . } . } . } . 172,000 ( 0.01%) let check_usable = |this: &mut Self, binding: &'a NameBinding<'a>| { 6,768 ( 0.00%) if let Some(unusable_binding) = this.unusable_binding { . if ptr::eq(binding, unusable_binding) { . return Err((Determined, Weak::No)); . } . } 3,735 ( 0.00%) let usable = this.is_accessible_from(binding.vis, parent_scope.module); 4,036 ( 0.00%) if usable { Ok(binding) } else { Err((Determined, Weak::No)) } . }; . 86,000 ( 0.00%) if record_used { 42,868 ( 0.00%) return resolution . .binding . .and_then(|binding| { . // If the primary binding is unusable, search further and return the shadowed glob . // binding if it exists. What we really want here is having two separate scopes in . // a module - one for non-globs and one for globs, but until that's done use this . // hack to avoid inconsistent resolution ICEs during import validation. 77,286 ( 0.00%) if let Some(unusable_binding) = self.unusable_binding { . if ptr::eq(binding, unusable_binding) { . return resolution.shadowed_glob; . } . } . Some(binding) . }) . .ok_or((Determined, Weak::No)) . .and_then(|binding| { 31,292 ( 0.00%) if self.last_import_segment && check_usable(self, binding).is_err() { . Err((Determined, Weak::No)) . } else { 92,460 ( 0.00%) self.record_use(ident, binding, restricted_shadowing); . 46,230 ( 0.00%) if let Some(shadowed_glob) = resolution.shadowed_glob { . // Forbid expanded shadowing to avoid time travel. . if restricted_shadowing . && binding.expansion != LocalExpnId::ROOT . && binding.res() != shadowed_glob.res() . { . self.ambiguity_errors.push(AmbiguityError { . kind: AmbiguityKind::GlobVsExpanded, . ident, -- line 317 ---------------------------------------- -- line 318 ---------------------------------------- . b1: binding, . b2: shadowed_glob, . misc1: AmbiguityErrorMisc::None, . misc2: AmbiguityErrorMisc::None, . }); . } . } . 77,050 ( 0.00%) if !self.is_accessible_from(binding.vis, parent_scope.module) { . self.privacy_errors.push(PrivacyError { . ident, . binding, . dedup_span: path_span, . }); . } . . Ok(binding) . } . }); . } . . // Items and single imports are not shadowable, if we have one, then it's determined. 64,698 ( 0.00%) if let Some(binding) = resolution.binding { 3 ( 0.00%) if !binding.is_glob_import() { . return check_usable(self, binding); . } . } . . // --- From now on we either have a glob resolution or no resolution. --- . . // Check if one of single imports can still define the name, . // if it can then our result is not determined and can be invalidated. 205,560 ( 0.01%) for single_import in &resolution.single_imports { . if !self.is_accessible_from(single_import.vis.get(), parent_scope.module) { . continue; . } . let module = match single_import.imported_module.get() { . Some(x) => x, . None => return Err((Undetermined, Weak::No)), . }; . let ident = match single_import.kind { -- line 358 ---------------------------------------- -- line 385 ---------------------------------------- . // Additionally, any macro in any module can plant names in the root module if it creates . // `macro_export` macros, so the root module effectively has unresolved invocations if any . // module has unresolved invocations. . // However, it causes resolution/expansion to stuck too often (#53144), so, to make . // progress, we have to ignore those potential unresolved invocations from other modules . // and prohibit access to macro-expanded `macro_export` macros instead (unless restricted . // shadowing is enabled, see `macro_expanded_macro_export_errors`). . let unexpanded_macros = !module.unexpanded_invocations.borrow().is_empty(); 102,780 ( 0.00%) if let Some(binding) = resolution.binding { . if !unexpanded_macros || ns == MacroNS || restricted_shadowing { . return check_usable(self, binding); . } else { . return Err((Undetermined, Weak::No)); . } . } . . // --- From now on we have no resolution. --- -- line 401 ---------------------------------------- -- line 403 ---------------------------------------- . // Now we are in situation when new item/import can appear only from a glob or a macro . // expansion. With restricted shadowing names from globs and macro expansions cannot . // shadow names from outer scopes, so we can freely fallback from module search to search . // in outer scopes. For `early_resolve_ident_in_lexical_scope` to continue search in outer . // scopes we return `Undetermined` with `Weak::Yes`. . . // Check if one of unexpanded macros can still define the name, . // if it can then our "no resolution" result is not determined and can be invalidated. 20,556 ( 0.00%) if unexpanded_macros { . return Err((Undetermined, Weak::Yes)); . } . . // Check if one of glob imports can still define the name, . // if it can then our "no resolution" result is not determined and can be invalidated. 80,984 ( 0.00%) for glob_import in module.globs.borrow().iter() { . if !self.is_accessible_from(glob_import.vis.get(), parent_scope.module) { . continue; . } . let module = match glob_import.imported_module.get() { . Some(ModuleOrUniformRoot::Module(module)) => module, . Some(_) => continue, . None => return Err((Undetermined, Weak::Yes)), . }; -- line 425 ---------------------------------------- -- line 452 ---------------------------------------- . continue; . } . Ok(_) | Err(Undetermined) => return Err((Undetermined, Weak::Yes)), . } . } . . // No resolution and no one else can define the name - determinate error. . Err((Determined, Weak::No)) 774,000 ( 0.04%) } . . // Given a binding and an import that resolves to it, . // return the corresponding binding defined by the import. 2,760 ( 0.00%) crate fn import( . &self, . binding: &'a NameBinding<'a>, . import: &'a Import<'a>, . ) -> &'a NameBinding<'a> { 2,760 ( 0.00%) let vis = if binding.vis.is_at_least(import.vis.get(), self) . || pub_use_of_private_extern_crate_hack(import, binding) . { . import.vis.get() . } else { . binding.vis . }; . 828 ( 0.00%) if let ImportKind::Glob { ref max_vis, .. } = import.kind { . if vis == import.vis.get() || vis.is_at_least(max_vis.get(), self) { . max_vis.set(vis) . } . } . 276 ( 0.00%) self.arenas.alloc_name_binding(NameBinding { . kind: NameBindingKind::Import { binding, import, used: Cell::new(false) }, . ambiguity: None, 276 ( 0.00%) span: import.span, . vis, 276 ( 0.00%) expansion: import.parent_scope.expansion, . }) 2,208 ( 0.00%) } . . // Define the name or return the existing binding if there is a collision. 14,184 ( 0.00%) crate fn try_define( . &mut self, . module: Module<'a>, . key: BindingKey, . binding: &'a NameBinding<'a>, . ) -> Result<(), &'a NameBinding<'a>> { . let res = binding.res(); 21,276 ( 0.00%) self.check_reserved_macro_name(key.ident, res); . self.set_binding_parent_module(binding, module); 7,092 ( 0.00%) self.update_resolution(module, key, |this, resolution| { . if let Some(old_binding) = resolution.binding { . if res == Res::Err { . // Do not override real bindings with `Res::Err`s from error recovery. . return Ok(()); . } . match (old_binding.is_glob_import(), binding.is_glob_import()) { . (true, true) => { . if res != old_binding.res() { -- line 510 ---------------------------------------- -- line 535 ---------------------------------------- . } . resolution.shadowed_glob = Some(glob_binding); . } . (false, false) => { . return Err(old_binding); . } . } . } else { 3,546 ( 0.00%) resolution.binding = Some(binding); . } . . Ok(()) . }) 10,638 ( 0.00%) } . . fn ambiguity( . &self, . kind: AmbiguityKind, . primary_binding: &'a NameBinding<'a>, . secondary_binding: &'a NameBinding<'a>, . ) -> &'a NameBinding<'a> { . self.arenas.alloc_name_binding(NameBinding { -- line 556 ---------------------------------------- -- line 563 ---------------------------------------- . // If the resolution becomes a success, define it in the module's glob importers. . fn update_resolution(&mut self, module: Module<'a>, key: BindingKey, f: F) -> T . where . F: FnOnce(&mut Resolver<'a>, &mut NameResolution<'a>) -> T, . { . // Ensure that `resolution` isn't borrowed when defining in the module's glob importers, . // during which the resolution might end up getting re-defined via a glob cycle. . let (binding, t) = { 20,048 ( 0.00%) let resolution = &mut *self.resolution(module, key).borrow_mut(); . let old_binding = resolution.binding(); . . let t = f(self, resolution); . . match resolution.binding() { . _ if old_binding.is_some() => return t, . None => return t, . Some(binding) => match old_binding { -- line 579 ---------------------------------------- -- line 643 ---------------------------------------- . // This is a fixed-point algorithm. We resolve imports until our efforts . // are stymied by an unresolved import; then we bail out of the current . // module and continue. We terminate successfully once no more imports . // remain or unsuccessfully when no forward progress in resolving imports . // is made. . . /// Resolves all imports for the crate. This method performs the fixed- . /// point iteration. 16 ( 0.00%) pub fn resolve_imports(&mut self) { 10 ( 0.00%) let mut prev_num_indeterminates = self.r.indeterminate_imports.len() + 1; 29 ( 0.00%) while self.r.indeterminate_imports.len() < prev_num_indeterminates { . prev_num_indeterminates = self.r.indeterminate_imports.len(); 278 ( 0.00%) for import in mem::take(&mut self.r.indeterminate_imports) { . match self.resolve_import(&import) { 128 ( 0.00%) true => self.r.determined_imports.push(import), 12 ( 0.00%) false => self.r.indeterminate_imports.push(import), . } . } . } 16 ( 0.00%) } . 7 ( 0.00%) pub fn finalize_imports(&mut self) { 2 ( 0.00%) for module in self.r.arenas.local_modules().iter() { 21 ( 0.00%) self.finalize_resolutions_in(module); . } . . let mut seen_spans = FxHashSet::default(); . let mut errors = vec![]; . let mut prev_root_id: NodeId = NodeId::from_u32(0); 1 ( 0.00%) let determined_imports = mem::take(&mut self.r.determined_imports); 1 ( 0.00%) let indeterminate_imports = mem::take(&mut self.r.indeterminate_imports); . 12 ( 0.00%) for (is_indeterminate, import) in determined_imports . .into_iter() . .map(|i| (false, i)) . .chain(indeterminate_imports.into_iter().map(|i| (true, i))) . { 762 ( 0.00%) if let Some(err) = self.finalize_import(import) { . if let ImportKind::Single { source, ref source_bindings, .. } = import.kind { . if source.name == kw::SelfLower { . // Silence `unresolved import` error if E0429 is already emitted . if let Err(Determined) = source_bindings.value_ns.get() { . continue; . } . } . } -- line 688 ---------------------------------------- -- line 703 ---------------------------------------- . let path = import_path_to_string( . &import.module_path.iter().map(|seg| seg.ident).collect::>(), . &import.kind, . err.span, . ); . errors.push((path, err)); . prev_root_id = import.root_id; . } 254 ( 0.00%) } else if is_indeterminate { . // Consider erroneous imports used to avoid duplicate diagnostics. . self.r.used_imports.insert(import.id); . let path = import_path_to_string( . &import.module_path.iter().map(|seg| seg.ident).collect::>(), . &import.kind, . import.span, . ); . let err = UnresolvedImportError { -- line 719 ---------------------------------------- -- line 721 ---------------------------------------- . label: None, . note: Vec::new(), . suggestion: None, . }; . errors.push((path, err)); . } . } . 1 ( 0.00%) if !errors.is_empty() { . self.throw_unresolved_import_error(errors, None); . } 8 ( 0.00%) } . . fn throw_unresolved_import_error( . &self, . errors: Vec<(String, UnresolvedImportError)>, . span: Option, . ) { . /// Upper limit on the number of `span_label` messages. . const MAX_LABEL_COUNT: usize = 10; -- line 740 ---------------------------------------- -- line 776 ---------------------------------------- . /// If successful, the resolved bindings are written into the module. . fn resolve_import(&mut self, import: &'b Import<'b>) -> bool { . debug!( . "(resolving import for module) resolving import `{}::...` in `{}`", . Segment::names_to_string(&import.module_path), . module_to_string(import.parent_scope.module).unwrap_or_else(|| "???".to_string()), . ); . 429 ( 0.00%) let module = if let Some(module) = import.imported_module.get() { 24 ( 0.00%) module . } else { . // For better failure detection, pretend that the import will . // not define any names while resolving its module path. . let orig_vis = import.vis.replace(ty::Visibility::Invisible); . let path_res = self.r.resolve_path( . &import.module_path, . None, 127 ( 0.00%) &import.parent_scope, . false, . import.span, . import.crate_lint(), . ); . import.vis.set(orig_vis); . 889 ( 0.00%) match path_res { 635 ( 0.00%) PathResult::Module(module) => module, . PathResult::Indeterminate => return false, . PathResult::NonModule(..) | PathResult::Failed { .. } => return true, . } . }; . . import.imported_module.set(Some(module)); 1,661 ( 0.00%) let (source, target, source_bindings, target_bindings, type_ns_only) = match import.kind { . ImportKind::Single { . source, . target, 138 ( 0.00%) ref source_bindings, 138 ( 0.00%) ref target_bindings, 138 ( 0.00%) type_ns_only, . .. . } => (source, target, source_bindings, target_bindings, type_ns_only), . ImportKind::Glob { .. } => { . self.resolve_glob_import(import); . return true; . } . _ => unreachable!(), . }; . 138 ( 0.00%) let mut indeterminate = false; 5,934 ( 0.00%) self.r.per_ns(|this, ns| { 1,242 ( 0.00%) if !type_ns_only || ns == TypeNS { 1,656 ( 0.00%) if let Err(Undetermined) = source_bindings[ns].get() { . // For better failure detection, pretend that the import will . // not define any names while resolving its module path. 414 ( 0.00%) let orig_vis = import.vis.replace(ty::Visibility::Invisible); . let binding = this.resolve_ident_in_module( 1,242 ( 0.00%) module, 1,242 ( 0.00%) source, . ns, 414 ( 0.00%) &import.parent_scope, . false, 414 ( 0.00%) import.span, . ); . import.vis.set(orig_vis); . source_bindings[ns].set(binding); . } else { . return; . }; . 414 ( 0.00%) let parent = import.parent_scope.module; 770 ( 0.00%) match source_bindings[ns].get() { 108 ( 0.00%) Err(Undetermined) => indeterminate = true, . // Don't update the resolution, because it was never added. 284 ( 0.00%) Err(Determined) if target.name == kw::Underscore => {} . Err(Determined) => { 284 ( 0.00%) let key = this.new_key(target, ns); . this.update_resolution(parent, key, |_, resolution| { 284 ( 0.00%) resolution.single_imports.remove(&PtrKey(import)); . }); . } . Ok(binding) if !binding.is_importable() => { . let msg = format!("`{}` is not directly importable", target); . struct_span_err!(this.session, import.span, E0253, "{}", &msg) . .span_label(import.span, "cannot be imported directly") . .emit(); . // Do not import this illegal binding. Import a dummy binding and pretend . // everything is fine . this.import_dummy_binding(import); . } . Ok(binding) => { 944 ( 0.00%) let imported_binding = this.import(binding, import); 236 ( 0.00%) target_bindings[ns].set(Some(imported_binding)); 708 ( 0.00%) this.define(parent, target, ns, imported_binding); . } . } . } 3,312 ( 0.00%) }); . 402 ( 0.00%) !indeterminate . } . . /// Performs final import resolution, consistency checks and error reporting. . /// . /// Optionally returns an unresolved import error. This error is buffered and used to . /// consolidate multiple unresolved import errors into a single diagnostic. 1,270 ( 0.00%) fn finalize_import(&mut self, import: &'b Import<'b>) -> Option { . let orig_vis = import.vis.replace(ty::Visibility::Invisible); 508 ( 0.00%) let orig_unusable_binding = match &import.kind { . ImportKind::Single { target_bindings, .. } => { 252 ( 0.00%) Some(mem::replace(&mut self.r.unusable_binding, target_bindings[TypeNS].get())) . } . _ => None, . }; 254 ( 0.00%) let prev_ambiguity_errors_len = self.r.ambiguity_errors.len(); . let path_res = self.r.resolve_path( . &import.module_path, . None, 127 ( 0.00%) &import.parent_scope, . true, 127 ( 0.00%) import.span, . import.crate_lint(), . ); 127 ( 0.00%) let no_ambiguity = self.r.ambiguity_errors.len() == prev_ambiguity_errors_len; 127 ( 0.00%) if let Some(orig_unusable_binding) = orig_unusable_binding { 126 ( 0.00%) self.r.unusable_binding = orig_unusable_binding; . } . import.vis.set(orig_vis); 635 ( 0.00%) if let PathResult::Failed { .. } | PathResult::NonModule(..) = path_res { . // Consider erroneous imports used to avoid duplicate diagnostics. . self.r.used_imports.insert(import.id); . } . let module = match path_res { 381 ( 0.00%) PathResult::Module(module) => { . // Consistency checks, analogous to `finalize_macro_resolutions`. 381 ( 0.00%) if let Some(initial_module) = import.imported_module.get() { 381 ( 0.00%) if !ModuleOrUniformRoot::same_def(module, initial_module) && no_ambiguity { . span_bug!(import.span, "inconsistent resolution for an import"); . } . } else if self.r.privacy_errors.is_empty() { . let msg = "cannot determine resolution for the import"; . let msg_note = "import resolution is stuck, try simplifying other imports"; . self.r.session.struct_span_err(import.span, msg).note(msg_note).emit(); . } . 381 ( 0.00%) module . } . PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => { . if no_ambiguity { . assert!(import.imported_module.get().is_none()); . self.r . .report_error(span, ResolutionError::FailedToResolve { label, suggestion }); . } . return None; -- line 928 ---------------------------------------- -- line 961 ---------------------------------------- . assert!(import.imported_module.get().is_none()); . } . // The error was already reported earlier. . return None; . } . PathResult::Indeterminate => unreachable!(), . }; . 1,517 ( 0.00%) let (ident, target, source_bindings, target_bindings, type_ns_only) = match import.kind { . ImportKind::Single { . source, . target, 126 ( 0.00%) ref source_bindings, 126 ( 0.00%) ref target_bindings, 126 ( 0.00%) type_ns_only, . .. . } => (source, target, source_bindings, target_bindings, type_ns_only), 2 ( 0.00%) ImportKind::Glob { is_prelude, ref max_vis } => { 3 ( 0.00%) if import.module_path.len() <= 1 { . // HACK(eddyb) `lint_if_path_starts_with_module` needs at least . // 2 segments, so the `resolve_path` above won't trigger it. . let mut full_path = import.module_path.clone(); . full_path.push(Segment::from_ident(Ident::empty())); . self.r.lint_if_path_starts_with_module( . import.crate_lint(), . &full_path, . import.span, . None, . ); . } . 4 ( 0.00%) if let ModuleOrUniformRoot::Module(module) = module { 1 ( 0.00%) if ptr::eq(module, import.parent_scope.module) { . // Importing a module into itself is not allowed. . return Some(UnresolvedImportError { . span: import.span, . label: Some(String::from("cannot glob-import a module into itself")), . note: Vec::new(), . suggestion: None, . }); . } . } 1 ( 0.00%) if !is_prelude && . max_vis.get() != ty::Visibility::Invisible && // Allow empty globs. . !max_vis.get().is_at_least(import.vis.get(), &*self) . { . let msg = "glob import doesn't reexport anything because no candidate is public enough"; . self.r.lint_buffer.buffer_lint(UNUSED_IMPORTS, import.id, import.span, msg); . } . return None; . } . _ => unreachable!(), . }; . 252 ( 0.00%) let mut all_ns_err = true; 5,796 ( 0.00%) self.r.per_ns(|this, ns| { 1,134 ( 0.00%) if !type_ns_only || ns == TypeNS { 378 ( 0.00%) let orig_vis = import.vis.replace(ty::Visibility::Invisible); . let orig_unusable_binding = 756 ( 0.00%) mem::replace(&mut this.unusable_binding, target_bindings[ns].get()); . let orig_last_import_segment = mem::replace(&mut this.last_import_segment, true); . let binding = this.resolve_ident_in_module( 1,134 ( 0.00%) module, 1,512 ( 0.00%) ident, . ns, 378 ( 0.00%) &import.parent_scope, . true, . import.span, . ); 756 ( 0.00%) this.last_import_segment = orig_last_import_segment; 756 ( 0.00%) this.unusable_binding = orig_unusable_binding; . import.vis.set(orig_vis); . . match binding { . Ok(binding) => { . // Consistency checks, analogous to `finalize_macro_resolutions`. 708 ( 0.00%) let initial_res = source_bindings[ns].get().map(|initial_binding| { 236 ( 0.00%) all_ns_err = false; 708 ( 0.00%) if let Some(target_binding) = target_bindings[ns].get() { 236 ( 0.00%) if target.name == kw::Underscore . && initial_binding.is_extern_crate() . && !initial_binding.is_import() . { . this.record_use( . ident, . target_binding, . import.module_path.is_empty(), . ); . } . } . initial_binding.res() . }); . let res = binding.res(); 3,304 ( 0.00%) if let Ok(initial_res) = initial_res { 708 ( 0.00%) if res != initial_res && this.ambiguity_errors.is_empty() { . span_bug!(import.span, "inconsistent resolution for an import"); . } . } else if res != Res::Err . && this.ambiguity_errors.is_empty() . && this.privacy_errors.is_empty() . { . let msg = "cannot determine resolution for the import"; . let msg_note = -- line 1063 ---------------------------------------- -- line 1070 ---------------------------------------- . // single import (see test `issue-55884-2.rs`). In theory single imports should . // always block globs, even if they are not yet resolved, so that this kind of . // self-inconsistent resolution never happens. . // Re-enable the assert when the issue is fixed. . // assert!(result[ns].get().is_err()); . } . } . } 3,024 ( 0.00%) }); . 252 ( 0.00%) if all_ns_err { . let mut all_ns_failed = true; . self.r.per_ns(|this, ns| { . if !type_ns_only || ns == TypeNS { . let binding = this.resolve_ident_in_module( . module, . ident, . ns, . &import.parent_scope, -- line 1088 ---------------------------------------- -- line 1175 ---------------------------------------- . }) . } else { . // `resolve_ident_in_module` reported a privacy error. . self.r.import_dummy_binding(import); . None . }; . } . 126 ( 0.00%) let mut reexport_error = None; 126 ( 0.00%) let mut any_successful_reexport = false; 252 ( 0.00%) let mut crate_private_reexport = false; 1,512 ( 0.00%) self.r.per_ns(|this, ns| { 882 ( 0.00%) if let Ok(binding) = source_bindings[ns].get() { 708 ( 0.00%) let vis = import.vis.get(); 1,416 ( 0.00%) if !binding.vis.is_at_least(vis, &*this) { . reexport_error = Some((ns, binding)); . if let ty::Visibility::Restricted(binding_def_id) = binding.vis { . if binding_def_id.is_top_level_module() { . crate_private_reexport = true; . } . } . } else { 472 ( 0.00%) any_successful_reexport = true; . } . } . }); . . // All namespaces must be re-exported with extra visibility for an error to occur. 252 ( 0.00%) if !any_successful_reexport { . let (ns, binding) = reexport_error.unwrap(); . if pub_use_of_private_extern_crate_hack(import, binding) { . let msg = format!( . "extern crate `{}` is private, and cannot be \ . re-exported (error E0365), consider declaring with \ . `pub`", . ident . ); -- line 1211 ---------------------------------------- -- line 1241 ---------------------------------------- . format!("consider marking `{}` as `pub` in the imported module", ident); . struct_span_err!(self.r.session, import.span, E0364, "{}", error_msg) . .span_note(import.span, ¬e_msg) . .emit(); . } . } . } . 378 ( 0.00%) if import.module_path.len() <= 1 { . // HACK(eddyb) `lint_if_path_starts_with_module` needs at least . // 2 segments, so the `resolve_path` above won't trigger it. . let mut full_path = import.module_path.clone(); 21 ( 0.00%) full_path.push(Segment::from_ident(ident)); 49 ( 0.00%) self.r.per_ns(|this, ns| { 42 ( 0.00%) if let Ok(binding) = source_bindings[ns].get() { 21 ( 0.00%) this.lint_if_path_starts_with_module( . import.crate_lint(), . &full_path, 7 ( 0.00%) import.span, . Some(binding), . ); . } . }); . } . . // Record what this import resolves to for later uses in documentation, . // this may resolve to either a value or a type, but for documentation . // purposes it's good enough to just favor one over the other. 3,528 ( 0.00%) self.r.per_ns(|this, ns| { 1,396 ( 0.00%) if let Ok(binding) = source_bindings[ns].get() { 3,776 ( 0.00%) this.import_res_map.entry(import.id).or_default()[ns] = Some(binding.res()); . } 3,024 ( 0.00%) }); . 1,134 ( 0.00%) self.check_for_redundant_imports(ident, import, source_bindings, target_bindings, target); . . debug!("(resolving single import) successfully resolved import"); . None 1,016 ( 0.00%) } . . fn check_for_redundant_imports( . &mut self, . ident: Ident, . import: &'b Import<'b>, . source_bindings: &PerNS, Determinacy>>>, . target_bindings: &PerNS>>>, . target: Ident, . ) { . // Skip if the import was produced by a macro. 126 ( 0.00%) if import.parent_scope.expansion != LocalExpnId::ROOT { . return; . } . . // Skip if we are inside a named module (in contrast to an anonymous . // module defined by a block). 48 ( 0.00%) if let ModuleKind::Def(..) = import.parent_scope.module.kind { . return; . } . . let mut is_redundant = PerNS { value_ns: None, type_ns: None, macro_ns: None }; . . let mut redundant_span = PerNS { value_ns: None, type_ns: None, macro_ns: None }; . . self.r.per_ns(|this, ns| { -- line 1304 ---------------------------------------- -- line 1350 ---------------------------------------- . let module = match import.imported_module.get().unwrap() { . ModuleOrUniformRoot::Module(module) => module, . _ => { . self.r.session.span_err(import.span, "cannot glob-import all possible crates"); . return; . } . }; . 3 ( 0.00%) if module.is_trait() { . self.r.session.span_err(import.span, "items in traits are not importable"); . return; 1 ( 0.00%) } else if ptr::eq(module, import.parent_scope.module) { . return; 4 ( 0.00%) } else if let ImportKind::Glob { is_prelude: true, .. } = import.kind { 2 ( 0.00%) self.r.prelude = Some(module); . return; . } . . // Add to module's glob_importers . module.glob_importers.borrow_mut().push(import); . . // Ensure that `resolutions` isn't borrowed during `try_define`, . // since it might get updated via a glob cycle. -- line 1372 ---------------------------------------- -- line 1394 ---------------------------------------- . // Record the destination of this import . self.r.record_partial_res(import.id, PartialRes::new(module.res().unwrap())); . } . . // Miscellaneous post-processing, including recording re-exports, . // reporting conflicts, and reporting unresolved imports. . fn finalize_resolutions_in(&mut self, module: Module<'b>) { . // Since import resolution is finished, globs will not define any more names. 84 ( 0.00%) *module.globs.borrow_mut() = Vec::new(); . . let mut reexports = Vec::new(); . 105 ( 0.00%) module.for_each_child(self.r, |_, ident, _, binding| { . // Filter away ambiguous imports and anything that has def-site hygiene. . // FIXME: Implement actual cross-crate hygiene. . let is_good_import = 616 ( 0.00%) binding.is_import() && !binding.is_ambiguity() && !ident.span.from_expansion(); 862 ( 0.00%) if is_good_import || binding.is_macro_def() { . let res = binding.res().expect_non_local(); . if res != def::Res::Err { 952 ( 0.00%) reexports.push(ModChild { ident, res, vis: binding.vis, span: binding.span }); . } . } . }); . 21 ( 0.00%) if !reexports.is_empty() { 39 ( 0.00%) if let Some(def_id) = module.opt_def_id() { . // Call to `expect_local` should be fine because current . // code is only called for local modules. . self.r.reexport_map.insert(def_id.expect_local(), reexports); . } . } . } . } . -- line 1428 ---------------------------------------- 203,095 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/validity.rs -------------------------------------------------------------------------------- Ir -- line 132 ---------------------------------------- . /// State for tracking recursive validation of references . pub struct RefTracking { . pub seen: FxHashSet, . pub todo: Vec<(T, PATH)>, . } . . impl RefTracking { . pub fn empty() -> Self { 64 ( 0.00%) RefTracking { seen: FxHashSet::default(), todo: vec![] } . } 80 ( 0.00%) pub fn new(op: T) -> Self { . let mut ref_tracking_for_consts = 256 ( 0.00%) RefTracking { seen: FxHashSet::default(), todo: vec![(op, PATH::default())] }; . ref_tracking_for_consts.seen.insert(op); . ref_tracking_for_consts 80 ( 0.00%) } . . pub fn track(&mut self, op: T, path: impl FnOnce() -> PATH) { 74 ( 0.00%) if self.seen.insert(op) { . trace!("Recursing below ptr {:#?}", op); . let path = path(); . // Remember to come back to this later. 165 ( 0.00%) self.todo.push((op, path)); . } . } . } . . /// Format a path . fn write_path(out: &mut String, path: &[PathElem]) { . use self::PathElem::*; . -- line 162 ---------------------------------------- -- line 208 ---------------------------------------- . path: Vec, . ref_tracking: Option<&'rt mut RefTracking, Vec>>, . /// `None` indicates this is not validating for CTFE (but for runtime). . ctfe_mode: Option, . ecx: &'rt InterpCx<'mir, 'tcx, M>, . } . . impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, 'tcx, M> { 658,524 ( 0.03%) fn aggregate_field_path_elem(&mut self, layout: TyAndLayout<'tcx>, field: usize) -> PathElem { . // First, check if we are projecting to a variant. 164,634 ( 0.01%) match layout.variants { . Variants::Multiple { tag_field, .. } => { 18,442 ( 0.00%) if tag_field == field { 27,663 ( 0.00%) return match layout.ty.kind() { 18,442 ( 0.00%) ty::Adt(def, ..) if def.is_enum() => PathElem::EnumTag, . ty::Generator(..) => PathElem::GeneratorTag, . _ => bug!("non-variant type {:?}", layout.ty), . }; . } . } . Variants::Single { .. } => {} . } . . // Now we know we are projecting to a field, so figure out which one. 182,624 ( 0.01%) match layout.ty.kind() { . // generators and closures. . ty::Closure(def_id, _) | ty::Generator(def_id, _, _) => { . let mut name = None; . // FIXME this should be more descriptive i.e. CapturePlace instead of CapturedVar . // https://github.com/rust-lang/project-rfc-2229/issues/46 . if let Some(local_def_id) = def_id.as_local() { . let tables = self.ecx.tcx.typeck(local_def_id); . if let Some(captured_place) = -- line 240 ---------------------------------------- -- line 257 ---------------------------------------- . sym::integer(field) . })) . } . . // tuples . ty::Tuple(_) => PathElem::TupleElem(field), . . // enums 36,444 ( 0.00%) ty::Adt(def, ..) if def.is_enum() => { . // we might be projecting *to* a variant, or to a field *in* a variant. 3 ( 0.00%) match layout.variants { 3 ( 0.00%) Variants::Single { index } => { . // Inside a variant . PathElem::Field(def.variants[index].fields[field].name) . } . Variants::Multiple { .. } => bug!("we handled variants above"), . } . } . . // other ADTs 18,219 ( 0.00%) ty::Adt(def, _) => PathElem::Field(def.non_enum_variant().fields[field].name), . . // arrays/slices . ty::Array(..) | ty::Slice(..) => PathElem::ArrayElem(field), . . // dyn traits . ty::Dynamic(..) => PathElem::DynDowncast, . . // nothing else has an aggregate layout . _ => bug!("aggregate_field_path_elem: got non-aggregate type {:?}", layout.ty), . } 713,401 ( 0.03%) } . . fn with_elem( . &mut self, . elem: PathElem, . f: impl FnOnce(&mut Self) -> InterpResult<'tcx, R>, . ) -> InterpResult<'tcx, R> { . // Remember the old state 146,638 ( 0.01%) let path_len = self.path.len(); . // Record new element . self.path.push(elem); . // Perform operation 146,638 ( 0.01%) let r = f(self)?; . // Undo changes . self.path.truncate(path_len); . // Done . Ok(r) . } . 81 ( 0.00%) fn check_wide_ptr_meta( . &mut self, . meta: MemPlaceMeta, . pointee: TyAndLayout<'tcx>, . ) -> InterpResult<'tcx> { 63 ( 0.00%) let tail = self.ecx.tcx.struct_tail_erasing_lifetimes(pointee.ty, self.ecx.param_env); 36 ( 0.00%) match tail.kind() { . ty::Dynamic(..) => { . let vtable = self.ecx.scalar_to_ptr(meta.unwrap_meta()); . // Direct call to `check_ptr_access_align` checks alignment even on CTFE machines. . try_validation!( . self.ecx.memory.check_ptr_access_align( . vtable, . 3 * self.ecx.tcx.data_layout.pointer_size, // drop, size, align . self.ecx.tcx.data_layout.pointer_align.abi, -- line 321 ---------------------------------------- -- line 347 ---------------------------------------- . err_ub!(InvalidVtableAlignment(msg)) => . { "invalid vtable: alignment {}", msg }, . err_unsup!(ReadPointerAsBytes) => { "invalid size or align in vtable" }, . ); . // FIXME: More checks for the vtable. . } . ty::Slice(..) | ty::Str => { . let _len = try_validation!( 9 ( 0.00%) meta.unwrap_meta().to_machine_usize(self.ecx), . self.path, . err_unsup!(ReadPointerAsBytes) => { "non-integer slice length in wide pointer" }, . ); . // We do not check that `len * elem_size <= isize::MAX`: . // that is only required for references, and there it falls out of the . // "dereferenceable" check performed by Stacked Borrows. . } . ty::Foreign(..) => { . // Unsized, but not wide. . } . _ => bug!("Unexpected unsized type tail: {:?}", tail), . } . . Ok(()) 81 ( 0.00%) } . . /// Check a reference or `Box`. 165 ( 0.00%) fn check_safe_pointer( . &mut self, . value: &OpTy<'tcx, M::PointerTag>, . kind: &str, . ) -> InterpResult<'tcx> { 45 ( 0.00%) let value = try_validation!( 30 ( 0.00%) self.ecx.read_immediate(value), . self.path, . err_unsup!(ReadPointerAsBytes) => { "part of a pointer" } expected { "a proper pointer or integer value" }, . ); . // Handle wide pointers. . // Check metadata early, for better diagnostics 150 ( 0.00%) let place = try_validation!( 45 ( 0.00%) self.ecx.ref_to_mplace(&value), . self.path, . err_ub!(InvalidUninitBytes(None)) => { "uninitialized {}", kind }, . ); 45 ( 0.00%) if place.layout.is_unsized() { 99 ( 0.00%) self.check_wide_ptr_meta(place.meta, place.layout)?; . } . // Make sure this is dereferenceable and all. 30 ( 0.00%) let size_and_align = try_validation!( 15 ( 0.00%) self.ecx.size_and_align_of_mplace(&place), . self.path, . err_ub!(InvalidMeta(msg)) => { "invalid {} metadata: {}", kind, msg }, . ); . let (size, align) = size_and_align . // for the purpose of validity, consider foreign types to have . // alignment and size determined by the layout (size will be 0, . // alignment should take attributes into account). . .unwrap_or_else(|| (place.layout.size, place.layout.align.abi)); . // Direct call to `check_ptr_access_align` checks alignment even on CTFE machines. . try_validation!( 30 ( 0.00%) self.ecx.memory.check_ptr_access_align( 45 ( 0.00%) place.ptr, . size, . align, . CheckInAllocMsg::InboundsTest, // will anyway be replaced by validity message . ), . self.path, . err_ub!(AlignmentCheckFailed { required, has }) => . { . "an unaligned {} (required {} byte alignment but found {})", -- line 415 ---------------------------------------- -- line 424 ---------------------------------------- . err_ub!(PointerOutOfBounds { .. }) => . { "a dangling {} (going beyond the bounds of its allocation)", kind }, . // This cannot happen during const-eval (because interning already detects . // dangling pointers), but it can happen in Miri. . err_ub!(PointerUseAfterFree(..)) => . { "a dangling {} (use-after-free)", kind }, . ); . // Recursive checking 45 ( 0.00%) if let Some(ref mut ref_tracking) = self.ref_tracking { . // Proceed recursively even for ZST, no reason to skip them! . // `!` is a ZST and we want to validate it. . // Skip validation entirely for some external statics 30 ( 0.00%) if let Ok((alloc_id, _offset, _ptr)) = self.ecx.memory.ptr_try_get_alloc(place.ptr) { . // not a ZST 45 ( 0.00%) let alloc_kind = self.ecx.tcx.get_global_alloc(alloc_id); 30 ( 0.00%) if let Some(GlobalAlloc::Static(did)) = alloc_kind { . assert!(!self.ecx.tcx.is_thread_local_static(did)); . assert!(self.ecx.tcx.is_static(did)); . if matches!( . self.ctfe_mode, . Some(CtfeValidationMode::Const { allow_static_ptrs: false, .. }) . ) { . // See const_eval::machine::MemoryExtra::can_access_statics for why . // this check is so important. -- line 447 ---------------------------------------- -- line 460 ---------------------------------------- . // and that static refers back to us. . // We might miss const-invalid data, . // but things are still sound otherwise (in particular re: consts . // referring to statics). . return Ok(()); . } . } . let path = &self.path; 135 ( 0.00%) ref_tracking.track(place, || { . // We need to clone the path anyway, make sure it gets created . // with enough space for the additional `Deref`. 60 ( 0.00%) let mut new_path = Vec::with_capacity(path.len() + 1); . new_path.clone_from(path); . new_path.push(PathElem::Deref); . new_path . }); . } . Ok(()) 135 ( 0.00%) } . 256,606 ( 0.01%) fn read_scalar( . &self, . op: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, ScalarMaybeUninit> { 293,264 ( 0.01%) Ok(try_validation!( 109,974 ( 0.01%) self.ecx.read_scalar(op), . self.path, . err_unsup!(ReadPointerAsBytes) => { "(potentially part of) a pointer" } expected { "plain (non-pointer) bytes" }, . )) 219,948 ( 0.01%) } . . /// Check if this is a value of primitive type, and if yes check the validity of the value . /// at that type. Return `true` if the type is indeed primitive. 577,161 ( 0.03%) fn try_visit_primitive( . &mut self, . value: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, bool> { . // Go over all the primitive types 192,387 ( 0.01%) let ty = value.layout.ty; 384,774 ( 0.02%) match ty.kind() { . ty::Bool => { . let value = self.read_scalar(value)?; . try_validation!( . value.to_bool(), . self.path, . err_ub!(InvalidBool(..)) | err_ub!(InvalidUninitBytes(None)) => . { "{}", value } expected { "a boolean" }, . ); . Ok(true) . } . ty::Char => { 72,864 ( 0.00%) let value = self.read_scalar(value)?; 36,432 ( 0.00%) try_validation!( . value.to_char(), . self.path, . err_ub!(InvalidChar(..)) | err_ub!(InvalidUninitBytes(None)) => . { "{}", value } expected { "a valid unicode scalar value (in `0..=0x10FFFF` but not in `0xD800..=0xDFFF`)" }, . ); . Ok(true) . } . ty::Float(_) | ty::Int(_) | ty::Uint(_) => { 36,896 ( 0.00%) let value = self.read_scalar(value)?; . // NOTE: Keep this in sync with the array optimization for int/float . // types below! . if M::enforce_number_validity(self.ecx) { . // Integers/floats in CTFE: Must be scalar bits, pointers are dangerous . let is_bits = value.check_init().map_or(false, |v| v.try_to_int().is_ok()); . if !is_bits { . throw_validation_failure!(self.path, . { "{}", value } expected { "initialized plain (non-pointer) bytes" } -- line 529 ---------------------------------------- -- line 543 ---------------------------------------- . err_unsup!(ReadPointerAsBytes) => { "part of a pointer" } expected { "a proper pointer or integer value" }, . ); . if place.layout.is_unsized() { . self.check_wide_ptr_meta(place.meta, place.layout)?; . } . Ok(true) . } . ty::Ref(_, ty, mutbl) => { 45 ( 0.00%) if matches!(self.ctfe_mode, Some(CtfeValidationMode::Const { .. })) . && *mutbl == hir::Mutability::Mut . { . // A mutable reference inside a const? That does not seem right (except if it is . // a ZST). . let layout = self.ecx.layout_of(ty)?; . if !layout.is_zst() { . throw_validation_failure!(self.path, { "mutable reference in a `const`" }); . } . } 45 ( 0.00%) self.check_safe_pointer(value, "reference")?; . Ok(true) . } 55,102 ( 0.00%) ty::Adt(def, ..) if def.is_box() => { . self.check_safe_pointer(value, "box")?; . Ok(true) . } . ty::FnPtr(_sig) => { . let value = try_validation!( . self.ecx.read_immediate(value), . self.path, . err_unsup!(ReadPointerAsBytes) => { "part of a pointer" } expected { "a proper pointer or integer value" }, -- line 572 ---------------------------------------- -- line 606 ---------------------------------------- . | ty::Infer(..) . | ty::Placeholder(..) . | ty::Bound(..) . | ty::Param(..) . | ty::Opaque(..) . | ty::Projection(..) . | ty::GeneratorWitness(..) => bug!("Encountered invalid type {:?}", ty), . } 961,935 ( 0.05%) } . 73,744 ( 0.00%) fn visit_scalar( . &mut self, . op: &OpTy<'tcx, M::PointerTag>, . scalar_layout: ScalarAbi, . ) -> InterpResult<'tcx> { 27,654 ( 0.00%) if scalar_layout.valid_range.is_full_for(op.layout.size) { . // Nothing to check . return Ok(()); . } . // At least one value is excluded. . let valid_range = scalar_layout.valid_range; . let WrappingRange { start, end } = valid_range; . let max_value = op.layout.size.unsigned_int_max(); 36,872 ( 0.00%) assert!(end <= max_value); . // Determine the allowed range 27,654 ( 0.00%) let value = self.read_scalar(op)?; . let value = try_validation!( . value.check_init(), . self.path, . err_ub!(InvalidUninitBytes(None)) => { "{}", value } . expected { "something {}", wrapping_range_format(valid_range, max_value) }, . ); 18,436 ( 0.00%) let bits = match value.try_to_int() { . Err(_) => { . // So this is a pointer then, and casting to an int failed. . // Can only happen during CTFE. . let ptr = self.ecx.scalar_to_ptr(value); . if start == 1 && end == max_value { . // Only null is the niche. So make sure the ptr is NOT null. . if self.ecx.memory.ptr_may_be_null(ptr) { . throw_validation_failure!(self.path, -- line 646 ---------------------------------------- -- line 659 ---------------------------------------- . { "a pointer" } . expected { . "something that cannot possibly fail to be {}", . wrapping_range_format(valid_range, max_value) . } . ) . } . } 147,488 ( 0.01%) Ok(int) => int.assert_bits(op.layout.size), . }; . // Now compare. This is slightly subtle because this is a special "wrap-around" range. 46,090 ( 0.00%) if valid_range.contains(bits) { . Ok(()) . } else { . throw_validation_failure!(self.path, . { "{}", bits } . expected { "something {}", wrapping_range_format(valid_range, max_value) } . ) . } 82,962 ( 0.00%) } . } . . impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValueVisitor<'mir, 'tcx, M> . for ValidityVisitor<'rt, 'mir, 'tcx, M> . { . type V = OpTy<'tcx, M::PointerTag>; . . #[inline(always)] -- line 686 ---------------------------------------- -- line 688 ---------------------------------------- . &self.ecx . } . . fn read_discriminant( . &mut self, . op: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, VariantIdx> { . self.with_elem(PathElem::EnumTag, move |this| { 27,663 ( 0.00%) Ok(try_validation!( 36,884 ( 0.00%) this.ecx.read_discriminant(op), . this.path, . err_ub!(InvalidTag(val)) => . { "{}", val } expected { "a valid enum tag" }, . err_ub!(InvalidUninitBytes(None)) => . { "uninitialized bytes" } expected { "a valid enum tag" }, . err_unsup!(ReadPointerAsBytes) => . { "a pointer" } expected { "a valid enum tag" }, . ) -- line 705 ---------------------------------------- -- line 709 ---------------------------------------- . . #[inline] . fn visit_field( . &mut self, . old_op: &OpTy<'tcx, M::PointerTag>, . field: usize, . new_op: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx> { 247,162 ( 0.01%) let elem = self.aggregate_field_path_elem(old_op.layout, field); 164,631 ( 0.01%) self.with_elem(elem, move |this| this.visit_value(new_op)) . } . . #[inline] . fn visit_variant( . &mut self, . old_op: &OpTy<'tcx, M::PointerTag>, . variant_id: VariantIdx, . new_op: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx> { 36,884 ( 0.00%) let name = match old_op.layout.ty.kind() { 36,884 ( 0.00%) ty::Adt(adt, _) => PathElem::Variant(adt.variants[variant_id].name), . // Generators also have variants . ty::Generator(..) => PathElem::GeneratorState(variant_id), . _ => bug!("Unexpected type with variant: {:?}", old_op.layout.ty), . }; 64,547 ( 0.00%) self.with_elem(name, move |this| this.visit_value(new_op)) . } . . #[inline(always)] . fn visit_union( . &mut self, . op: &OpTy<'tcx, M::PointerTag>, . _fields: NonZeroUsize, . ) -> InterpResult<'tcx> { -- line 742 ---------------------------------------- -- line 745 ---------------------------------------- . if !op.layout.ty.is_freeze(self.ecx.tcx.at(DUMMY_SP), self.ecx.param_env) { . throw_validation_failure!(self.path, { "`UnsafeCell` in a `const`" }); . } . } . Ok(()) . } . . #[inline] 576,882 ( 0.03%) fn visit_value(&mut self, op: &OpTy<'tcx, M::PointerTag>) -> InterpResult<'tcx> { . trace!("visit_value: {:?}, {:?}", *op, op.layout); . . // Check primitive types -- the leafs of our recursive descend. 256,485 ( 0.01%) if self.try_visit_primitive(op)? { . return Ok(()); . } . // Sanity check: `builtin_deref` does not know any pointers that are not primitive. 146,696 ( 0.01%) assert!(op.layout.ty.builtin_deref(true).is_none()); . . // Special check preventing `UnsafeCell` in the inner part of constants 128,450 ( 0.01%) if let Some(def) = op.layout.ty.ty_adt_def() { 137,748 ( 0.01%) if matches!(self.ctfe_mode, Some(CtfeValidationMode::Const { inner: true, .. })) 192,808 ( 0.01%) && Some(def.did) == self.ecx.tcx.lang_items().unsafe_cell_type() . { . throw_validation_failure!(self.path, { "`UnsafeCell` in a `const`" }); . } . } . . // Recursively walk the value at its type. 183,370 ( 0.01%) self.walk_value(op)?; . . // *After* all of this, check the ABI. We need to check the ABI to handle . // types like `NonNull` where the `Scalar` info is more restrictive than what . // the fields say (`rustc_layout_scalar_valid_range_start`). . // But in most cases, this will just propagate what the fields say, . // and then we want the error to point at the field -- so, first recurse, . // then check ABI. . // . // FIXME: We could avoid some redundant checks here. For newtypes wrapping . // scalars, we do the same check on every "level" (e.g., first we check . // MyNewtype and then the scalar in there). 201,806 ( 0.01%) match op.layout.abi { . Abi::Uninhabited => { . throw_validation_failure!(self.path, . { "a value of uninhabited type {:?}", op.layout.ty } . ); . } . Abi::Scalar(scalar_layout) => { 101,398 ( 0.00%) self.visit_scalar(op, scalar_layout)?; . } . Abi::ScalarPair { .. } | Abi::Vector { .. } => { . // These have fields that we already visited above, so we already checked . // all their scalar-level restrictions. . // There is also no equivalent to `rustc_layout_scalar_valid_range_start` . // that would make skipping them here an issue. . } . Abi::Aggregate { .. } => { . // Nothing to do. . } . } . . Ok(()) 512,784 ( 0.02%) } . . fn visit_aggregate( . &mut self, . op: &OpTy<'tcx, M::PointerTag>, . fields: impl Iterator>, . ) -> InterpResult<'tcx> { 330,054 ( 0.02%) match op.layout.ty.kind() { . ty::Str => { . let mplace = op.assert_mem_place(); // strings are never immediate 6 ( 0.00%) let len = mplace.len(self.ecx)?; 6 ( 0.00%) try_validation!( 18 ( 0.00%) self.ecx.memory.read_bytes(mplace.ptr, Size::from_bytes(len)), . self.path, . err_ub!(InvalidUninitBytes(..)) => { "uninitialized data in `str`" }, . err_unsup!(ReadPointerAsBytes) => { "a pointer in `str`" }, . ); . } . ty::Array(tys, ..) | ty::Slice(tys) . // This optimization applies for types that can hold arbitrary bytes (such as . // integer and floating point types) or for structs or tuples with no fields. . // FIXME(wesleywiser) This logic could be extended further to arbitrary structs . // or tuples made up of integer/floating point types or inhabited ZSTs with no . // padding. 60 ( 0.00%) if matches!(tys.kind(), ty::Int(..) | ty::Uint(..) | ty::Float(..)) . => . { . // Optimized handling for arrays of integer/float type. . . // Arrays cannot be immediate, slices are never immediate. . let mplace = op.assert_mem_place(); . // This is the length of the array/slice. . let len = mplace.len(self.ecx)?; -- line 838 ---------------------------------------- -- line 891 ---------------------------------------- . _ => return Err(err), . } . } . } . } . // Fast path for arrays and slices of ZSTs. We only need to check a single ZST element . // of an array and not all of them, because there's only a single value of a specific . // ZST type, so either validation fails for all elements or none. 108 ( 0.00%) ty::Array(tys, ..) | ty::Slice(tys) if self.ecx.layout_of(tys)?.is_zst() => { . // Validate just the first element (if any). . self.walk_aggregate(op, fields.take(1))? . } . _ => { . self.walk_aggregate(op, fields)? // default handler . } . } . Ok(()) . } . } . . impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { 186 ( 0.00%) fn validate_operand_internal( . &self, . op: &OpTy<'tcx, M::PointerTag>, . path: Vec, . ref_tracking: Option<&mut RefTracking, Vec>>, . ctfe_mode: Option, . ) -> InterpResult<'tcx> { . trace!("validate_operand_internal: {:?}, {:?}", *op, op.layout.ty); . . // Construct a visitor 279 ( 0.00%) let mut visitor = ValidityVisitor { path, ref_tracking, ctfe_mode, ecx: self }; . . // Run it. 93 ( 0.00%) match visitor.visit_value(&op) { . Ok(()) => Ok(()), . // Pass through validation failures. . Err(err) if matches!(err.kind(), err_ub!(ValidationFailure { .. })) => Err(err), . // Also pass through InvalidProgram, those just indicate that we could not . // validate and each caller will know best what to do with them. . Err(err) if matches!(err.kind(), InterpError::InvalidProgram(_)) => Err(err), . // Avoid other errors as those do not show *where* in the value the issue lies. . Err(err) => { . err.print_backtrace(); . bug!("Unexpected error during validation: {}", err); . } . } 217 ( 0.00%) } . . /// This function checks the data at `op` to be const-valid. . /// `op` is assumed to cover valid memory if it is an indirect operand. . /// It will error if the bits at the destination do not match the ones described by the layout. . /// . /// `ref_tracking` is used to record references that we encounter so that they . /// can be checked recursively by an outside driving loop. . /// -- line 946 ---------------------------------------- -- line 950 ---------------------------------------- . #[inline(always)] . pub fn const_validate_operand( . &self, . op: &OpTy<'tcx, M::PointerTag>, . path: Vec, . ref_tracking: &mut RefTracking, Vec>, . ctfe_mode: CtfeValidationMode, . ) -> InterpResult<'tcx> { 310 ( 0.00%) self.validate_operand_internal(op, path, Some(ref_tracking), Some(ctfe_mode)) . } . . /// This function checks the data at `op` to be runtime-valid. . /// `op` is assumed to cover valid memory if it is an indirect operand. . /// It will error if the bits at the destination do not match the ones described by the layout. . #[inline(always)] . pub fn validate_operand(&self, op: &OpTy<'tcx, M::PointerTag>) -> InterpResult<'tcx> { . self.validate_operand_internal(op, vec![], None, None) -- line 966 ---------------------------------------- 1,034,551 ( 0.05%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/sty.rs -------------------------------------------------------------------------------- Ir -- line 32 ---------------------------------------- . pub mutbl: hir::Mutability, . } . . #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, TyEncodable, TyDecodable, Copy)] . #[derive(HashStable)] . /// A "free" region `fr` can be interpreted as "some region . /// at least as big as the scope `fr.scope`". . pub struct FreeRegion { 5,494 ( 0.00%) pub scope: DefId, 7,087 ( 0.00%) pub bound_region: BoundRegionKind, . } . 30,718 ( 0.00%) #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, TyEncodable, TyDecodable, Copy)] . #[derive(HashStable)] . pub enum BoundRegionKind { . /// An anonymous region parameter for a given fn (&T) 338 ( 0.00%) BrAnon(u32), . . /// Named region parameters for functions (a in &'a T) . /// . /// The `DefId` is needed to distinguish free regions in . /// the event of shadowing. . BrNamed(DefId, Symbol), . . /// Anonymous region for the implicit env pointer parameter . /// to a closure . BrEnv, . } . 60 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, Debug, PartialOrd, Ord)] . #[derive(HashStable)] . pub struct BoundRegion { 6,146 ( 0.00%) pub var: BoundVar, 4,716 ( 0.00%) pub kind: BoundRegionKind, . } . . impl BoundRegionKind { . pub fn is_named(&self) -> bool { . match *self { . BoundRegionKind::BrNamed(_, name) => name != kw::UnderscoreLifetime, . _ => false, . } . } . } . . /// Defines the kinds of types. . /// . /// N.B., if you change this, you'll probably want to change the corresponding . /// AST structure in `rustc_ast/src/ast.rs` as well. 3,008,618 ( 0.14%) #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable, Debug)] . #[derive(HashStable)] . #[rustc_diagnostic_item = "TyKind"] . pub enum TyKind<'tcx> { . /// The primitive boolean type. Written as `bool`. . Bool, . . /// The primitive character type; holds a Unicode scalar value . /// (a non-surrogate code point). Written as `char`. -- line 89 ---------------------------------------- -- line 99 ---------------------------------------- . Float(ty::FloatTy), . . /// Algebraic data types (ADT). For example: structures, enumerations and unions. . /// . /// InternalSubsts here, possibly against intuition, *may* contain `Param`s. . /// That is, even after substitution it is possible that there are type . /// variables. This happens when the `Adt` corresponds to an ADT . /// definition and not a concrete use of it. 537,591 ( 0.03%) Adt(&'tcx AdtDef, SubstsRef<'tcx>), . . /// An unsized FFI type that is opaque to Rust. Written as `extern type T`. . Foreign(DefId), . . /// The pointee of a string slice. Written as `str`. . Str, . . /// An array with the given length. Written as `[T; n]`. 792 ( 0.00%) Array(Ty<'tcx>, &'tcx ty::Const<'tcx>), . . /// The pointee of an array slice. Written as `[T]`. . Slice(Ty<'tcx>), . . /// A raw pointer. Written as `*mut T` or `*const T` . RawPtr(TypeAndMut<'tcx>), . . /// A reference; a pointer with an associated lifetime. Written as . /// `&'a mut T` or `&'a T`. 140,940 ( 0.01%) Ref(Region<'tcx>, Ty<'tcx>, hir::Mutability), . . /// The anonymous type of a function declaration/definition. Each . /// function has a unique type, which is output (for a function . /// named `foo` returning an `i32`) as `fn() -> i32 {foo}`. . /// . /// For example the type of `bar` here: . /// . /// ```rust -- line 134 ---------------------------------------- -- line 143 ---------------------------------------- . /// . /// ```rust . /// fn foo() -> i32 { 1 } . /// let bar: fn() -> i32 = foo; . /// ``` . FnPtr(PolyFnSig<'tcx>), . . /// A trait object. Written as `dyn for<'b> Trait<'b, Assoc = u32> + Send + 'a`. 24 ( 0.00%) Dynamic(&'tcx List>>, ty::Region<'tcx>), . . /// The anonymous type of a closure. Used to represent the type of . /// `|a| a`. . Closure(DefId, SubstsRef<'tcx>), . . /// The anonymous type of a generator. Used to represent the type of . /// `|a| yield a`. . Generator(DefId, SubstsRef<'tcx>, hir::Movability), -- line 159 ---------------------------------------- -- line 180 ---------------------------------------- . /// The substitutions are for the generics of the function in question. . /// After typeck, the concrete type can be found in the `types` map. . Opaque(DefId, SubstsRef<'tcx>), . . /// A type parameter; for example, `T` in `fn f(x: T) {}`. . Param(ParamTy), . . /// Bound type variable, used only when preparing a trait query. 467 ( 0.00%) Bound(ty::DebruijnIndex, BoundTy), . . /// A placeholder type - universally quantified higher-ranked type. . Placeholder(ty::PlaceholderType), . . /// A type variable used during type checking. . Infer(InferTy), . . /// A placeholder for a type which could not be computed; this is -- line 196 ---------------------------------------- -- line 760 ---------------------------------------- . } . . /// Returns the type of this inline const. . pub fn ty(self) -> Ty<'tcx> { . self.split().ty.expect_ty() . } . } . 200 ( 0.00%) #[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Ord, Eq, Hash, TyEncodable, TyDecodable)] . #[derive(HashStable, TypeFoldable)] . pub enum ExistentialPredicate<'tcx> { . /// E.g., `Iterator`. . Trait(ExistentialTraitRef<'tcx>), . /// E.g., `Iterator::Item = T`. . Projection(ExistentialProjection<'tcx>), . /// E.g., `Send`. 6 ( 0.00%) AutoTrait(DefId), . } . . impl<'tcx> ExistentialPredicate<'tcx> { . /// Compares via an ordering that will not change if modules are reordered or other changes are . /// made to the tree. In particular, this ordering is preserved across incremental compilations. 30 ( 0.00%) pub fn stable_cmp(&self, tcx: TyCtxt<'tcx>, other: &Self) -> Ordering { . use self::ExistentialPredicate::*; 32 ( 0.00%) match (*self, *other) { . (Trait(_), Trait(_)) => Ordering::Equal, . (Projection(ref a), Projection(ref b)) => { . tcx.def_path_hash(a.item_def_id).cmp(&tcx.def_path_hash(b.item_def_id)) . } . (AutoTrait(ref a), AutoTrait(ref b)) => { . tcx.def_path_hash(*a).cmp(&tcx.def_path_hash(*b)) . } . (Trait(_), _) => Ordering::Less, . (Projection(_), Trait(_)) => Ordering::Greater, . (Projection(_), _) => Ordering::Less, . (AutoTrait(_), _) => Ordering::Greater, . } 36 ( 0.00%) } . } . . impl<'tcx> Binder<'tcx, ExistentialPredicate<'tcx>> { . pub fn with_self_ty(&self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ty::Predicate<'tcx> { . use crate::ty::ToPredicate; . match self.skip_binder() { . ExistentialPredicate::Trait(tr) => { . self.rebind(tr).with_self_ty(tcx, self_ty).without_const().to_predicate(tcx) -- line 805 ---------------------------------------- -- line 840 ---------------------------------------- . /// . /// It is also possible to have a "trivial" trait object that . /// consists only of auto traits, with no principal - for example, . /// `dyn Send + Sync`. In that case, the set of auto-trait bounds . /// is `{Send, Sync}`, while there is no principal. These trait objects . /// have a "trivial" vtable consisting of just the size, alignment, . /// and destructor. . pub fn principal(&self) -> Option>> { 6 ( 0.00%) self[0] 6 ( 0.00%) .map_bound(|this| match this { . ExistentialPredicate::Trait(tr) => Some(tr), . _ => None, . }) . .transpose() . } . . pub fn principal_def_id(&self) -> Option { . self.principal().map(|trait_ref| trait_ref.skip_binder().def_id) -- line 857 ---------------------------------------- -- line 886 ---------------------------------------- . /// T: Foo . /// . /// This would be represented by a trait-reference where the `DefId` is the . /// `DefId` for the trait `Foo` and the substs define `T` as parameter 0, . /// and `U` as parameter 1. . /// . /// Trait references also appear in object types like `Foo`, but in . /// that case the `Self` parameter is absent from the substitutions. 5,907 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] 128,885 ( 0.01%) #[derive(HashStable, TypeFoldable)] . pub struct TraitRef<'tcx> { 4 ( 0.00%) pub def_id: DefId, 259,395 ( 0.01%) pub substs: SubstsRef<'tcx>, . } . . impl<'tcx> TraitRef<'tcx> { 99 ( 0.00%) pub fn new(def_id: DefId, substs: SubstsRef<'tcx>) -> TraitRef<'tcx> { . TraitRef { def_id, substs } 396 ( 0.00%) } . . /// Returns a `TraitRef` of the form `P0: Foo` where `Pi` . /// are the parameters defined on trait. 153 ( 0.00%) pub fn identity(tcx: TyCtxt<'tcx>, def_id: DefId) -> Binder<'tcx, TraitRef<'tcx>> { 68 ( 0.00%) ty::Binder::dummy(TraitRef { . def_id, 102 ( 0.00%) substs: InternalSubsts::identity_for_item(tcx, def_id), . }) 136 ( 0.00%) } . . #[inline] . pub fn self_ty(&self) -> Ty<'tcx> { . self.substs.type_at(0) . } . 48 ( 0.00%) pub fn from_method( . tcx: TyCtxt<'tcx>, . trait_id: DefId, . substs: SubstsRef<'tcx>, . ) -> ty::TraitRef<'tcx> { . let defs = tcx.generics_of(trait_id); . 6 ( 0.00%) ty::TraitRef { def_id: trait_id, substs: tcx.intern_substs(&substs[..defs.params.len()]) } 66 ( 0.00%) } . } . . pub type PolyTraitRef<'tcx> = Binder<'tcx, TraitRef<'tcx>>; . . impl<'tcx> PolyTraitRef<'tcx> { . pub fn self_ty(&self) -> Binder<'tcx, Ty<'tcx>> { . self.map_bound_ref(|tr| tr.self_ty()) . } . . pub fn def_id(&self) -> DefId { 81 ( 0.00%) self.skip_binder().def_id 27 ( 0.00%) } . 42 ( 0.00%) pub fn to_poly_trait_predicate(&self) -> ty::PolyTraitPredicate<'tcx> { 84 ( 0.00%) self.map_bound(|trait_ref| ty::TraitPredicate { . trait_ref, . constness: ty::BoundConstness::NotConst, . polarity: ty::ImplPolarity::Positive, . }) 42 ( 0.00%) } . } . . /// An existential reference to a trait, where `Self` is erased. . /// For example, the trait object `Trait<'a, 'b, X, Y>` is: . /// . /// exists T. T: Trait<'a, 'b, X, Y> . /// . /// The substitutions don't include the erased `Self`, only trait . /// type and lifetime parameters (`[X, Y]` and `['a, 'b]` above). 28 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] . #[derive(HashStable, TypeFoldable)] . pub struct ExistentialTraitRef<'tcx> { 6 ( 0.00%) pub def_id: DefId, 12 ( 0.00%) pub substs: SubstsRef<'tcx>, . } . . impl<'tcx> ExistentialTraitRef<'tcx> { . pub fn erase_self_ty( . tcx: TyCtxt<'tcx>, . trait_ref: ty::TraitRef<'tcx>, . ) -> ty::ExistentialTraitRef<'tcx> { . // Assert there is a Self. -- line 970 ---------------------------------------- -- line 999 ---------------------------------------- . /// we convert the principal trait-ref into a normal trait-ref, . /// you must give *some* self type. A common choice is `mk_err()` . /// or some placeholder type. . pub fn with_self_ty(&self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ty::PolyTraitRef<'tcx> { . self.map_bound(|trait_ref| trait_ref.with_self_ty(tcx, self_ty)) . } . } . 2,264 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] . #[derive(HashStable)] . pub enum BoundVariableKind { . Ty(BoundTyKind), . Region(BoundRegionKind), . Const, . } . . /// Binder is a binder for higher-ranked lifetimes or types. It is part of the -- line 1015 ---------------------------------------- -- line 1016 ---------------------------------------- . /// compiler's representation for things like `for<'a> Fn(&'a isize)` . /// (which would be represented by the type `PolyTraitRef == . /// Binder<'tcx, TraitRef>`). Note that when we instantiate, . /// erase, or otherwise "discharge" these bound vars, we change the . /// type from `Binder<'tcx, T>` to just `T` (see . /// e.g., `liberate_late_bound_regions`). . /// . /// `Decodable` and `Encodable` are implemented for `Binder` using the `impl_binder_encode_decode!` macro. 244 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] 126,945 ( 0.01%) pub struct Binder<'tcx, T>(T, &'tcx List); . . impl<'tcx, T> Binder<'tcx, T> . where . T: TypeFoldable<'tcx>, . { . /// Wraps `value` in a binder, asserting that `value` does not . /// contain any bound vars that would be bound by the . /// binder. This is commonly used to 'inject' a value T into a . /// different binding level. 4,165 ( 0.00%) pub fn dummy(value: T) -> Binder<'tcx, T> { 74,089 ( 0.00%) assert!(!value.has_escaping_bound_vars()); 150,053 ( 0.01%) Binder(value, ty::List::empty()) 4,165 ( 0.00%) } . . pub fn bind_with_vars(value: T, vars: &'tcx List) -> Binder<'tcx, T> { . if cfg!(debug_assertions) { . let mut validator = ValidateBoundVars::new(vars); . value.visit_with(&mut validator); . } 1,256 ( 0.00%) Binder(value, vars) . } . } . . impl<'tcx, T> Binder<'tcx, T> { . /// Skips the binder and returns the "bound" value. This is a . /// risky thing to do because it's easy to get confused about . /// De Bruijn indices and the like. It is usually better to . /// discharge the binder using `no_bound_vars` or -- line 1053 ---------------------------------------- -- line 1059 ---------------------------------------- . /// accounting. . /// . /// Some examples where `skip_binder` is reasonable: . /// . /// - extracting the `DefId` from a PolyTraitRef; . /// - comparing the self type of a PolyTraitRef to see if it is equal to . /// a type parameter `X`, since the type `X` does not reference any regions . pub fn skip_binder(self) -> T { 200,325 ( 0.01%) self.0 . } . . pub fn bound_vars(&self) -> &'tcx List { 111 ( 0.00%) self.1 . } . . pub fn as_ref(&self) -> Binder<'tcx, &T> { 106 ( 0.00%) Binder(&self.0, self.1) . } . . pub fn map_bound_ref_unchecked(&self, f: F) -> Binder<'tcx, U> . where . F: FnOnce(&T) -> U, . { . let value = f(&self.0); . Binder(value, self.1) -- line 1083 ---------------------------------------- -- line 1089 ---------------------------------------- . { . self.as_ref().map_bound(f) . } . . pub fn map_bound>(self, f: F) -> Binder<'tcx, U> . where . F: FnOnce(T) -> U, . { 1,423 ( 0.00%) let value = f(self.0); . if cfg!(debug_assertions) { . let mut validator = ValidateBoundVars::new(self.1); . value.visit_with(&mut validator); . } 371,650 ( 0.02%) Binder(value, self.1) . } . . pub fn try_map_bound, E>(self, f: F) -> Result, E> . where . F: FnOnce(T) -> Result, . { . let value = f(self.0)?; . if cfg!(debug_assertions) { . let mut validator = ValidateBoundVars::new(self.1); . value.visit_with(&mut validator); . } 48 ( 0.00%) Ok(Binder(value, self.1)) . } . . /// Wraps a `value` in a binder, using the same bound variables as the . /// current `Binder`. This should not be used if the new value *changes* . /// the bound variables. Note: the (old or new) value itself does not . /// necessarily need to *name* all the bound variables. . /// . /// This currently doesn't do anything different than `bind`, because we -- line 1122 ---------------------------------------- -- line 1126 ---------------------------------------- . pub fn rebind(&self, value: U) -> Binder<'tcx, U> . where . U: TypeFoldable<'tcx>, . { . if cfg!(debug_assertions) { . let mut validator = ValidateBoundVars::new(self.bound_vars()); . value.visit_with(&mut validator); . } 517 ( 0.00%) Binder(value, self.1) . } . . /// Unwraps and returns the value within, but only if it contains . /// no bound vars at all. (In other words, if this binder -- . /// and indeed any enclosing binder -- doesn't bind anything at . /// all.) Otherwise, returns `None`. . /// . /// (One could imagine having a method that just unwraps a single -- line 1142 ---------------------------------------- -- line 1143 ---------------------------------------- . /// binder, but permits late-bound vars bound by enclosing . /// binders, but that would require adjusting the debruijn . /// indices, and given the shallow binding structure we often use, . /// would not be that useful.) . pub fn no_bound_vars(self) -> Option . where . T: TypeFoldable<'tcx>, . { 15,756 ( 0.00%) if self.0.has_escaping_bound_vars() { None } else { Some(self.skip_binder()) } . } . . /// Splits the contents into two things that share the same binder . /// level as the original, returning two distinct binders. . /// . /// `f` should consider bound regions at depth 1 to be free, and . /// anything it produces with bound regions at depth 1 will be . /// bound in the resulting return values. -- line 1159 ---------------------------------------- -- line 1170 ---------------------------------------- . pub fn transpose(self) -> Option> { . let bound_vars = self.1; . self.0.map(|v| Binder(v, bound_vars)) . } . } . . /// Represents the projection of an associated type. In explicit UFCS . /// form this would be written `>::N`. 57 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] 478 ( 0.00%) #[derive(HashStable, TypeFoldable)] . pub struct ProjectionTy<'tcx> { . /// The parameters of the associated item. 294 ( 0.00%) pub substs: SubstsRef<'tcx>, . . /// The `DefId` of the `TraitItem` for the associated type `N`. . /// . /// Note that this is not the `DefId` of the `TraitRef` containing this . /// associated type, which is in `tcx.associated_item(item_def_id).container`. 321 ( 0.00%) pub item_def_id: DefId, . } . . impl<'tcx> ProjectionTy<'tcx> { 252 ( 0.00%) pub fn trait_def_id(&self, tcx: TyCtxt<'tcx>) -> DefId { 72 ( 0.00%) tcx.associated_item(self.item_def_id).container.id() 288 ( 0.00%) } . . /// Extracts the underlying trait reference and own substs from this projection. . /// For example, if this is a projection of `::Item<'a>`, . /// then this function would return a `T: Iterator` trait reference and `['a]` as the own substs 168 ( 0.00%) pub fn trait_ref_and_own_substs( . &self, . tcx: TyCtxt<'tcx>, . ) -> (ty::TraitRef<'tcx>, &'tcx [ty::GenericArg<'tcx>]) { 72 ( 0.00%) let def_id = tcx.associated_item(self.item_def_id).container.id(); . let trait_generics = tcx.generics_of(def_id); 120 ( 0.00%) ( . ty::TraitRef { def_id, substs: self.substs.truncate_to(tcx, trait_generics) }, . &self.substs[trait_generics.count()..], . ) 216 ( 0.00%) } . . /// Extracts the underlying trait reference from this projection. . /// For example, if this is a projection of `::Item`, . /// then this function would return a `T: Iterator` trait reference. . /// . /// WARNING: This will drop the substs for generic associated types . /// consider calling [Self::trait_ref_and_own_substs] to get those . /// as well. 324 ( 0.00%) pub fn trait_ref(&self, tcx: TyCtxt<'tcx>) -> ty::TraitRef<'tcx> { 36 ( 0.00%) let def_id = self.trait_def_id(tcx); 36 ( 0.00%) ty::TraitRef { def_id, substs: self.substs.truncate_to(tcx, tcx.generics_of(def_id)) } 396 ( 0.00%) } . 96 ( 0.00%) pub fn self_ty(&self) -> Ty<'tcx> { 288 ( 0.00%) self.substs.type_at(0) 192 ( 0.00%) } . } . . #[derive(Copy, Clone, Debug, TypeFoldable)] . pub struct GenSig<'tcx> { . pub resume_ty: Ty<'tcx>, . pub yield_ty: Ty<'tcx>, . pub return_ty: Ty<'tcx>, . } -- line 1233 ---------------------------------------- -- line 1235 ---------------------------------------- . pub type PolyGenSig<'tcx> = Binder<'tcx, GenSig<'tcx>>; . . /// Signature of a function type, which we have arbitrarily . /// decided to use to refer to the input/output types. . /// . /// - `inputs`: is the list of arguments and their modes. . /// - `output`: is the return type. . /// - `c_variadic`: indicates whether this is a C-variadic function. 5,727 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] 2,580 ( 0.00%) #[derive(HashStable, TypeFoldable)] . pub struct FnSig<'tcx> { 9 ( 0.00%) pub inputs_and_output: &'tcx List>, 1,383 ( 0.00%) pub c_variadic: bool, 155 ( 0.00%) pub unsafety: hir::Unsafety, 2,423 ( 0.00%) pub abi: abi::Abi, . } . . impl<'tcx> FnSig<'tcx> { 3,301 ( 0.00%) pub fn inputs(&self) -> &'tcx [Ty<'tcx>] { 14,680 ( 0.00%) &self.inputs_and_output[..self.inputs_and_output.len() - 1] 6,602 ( 0.00%) } . 2,071 ( 0.00%) pub fn output(&self) -> Ty<'tcx> { 15,061 ( 0.00%) self.inputs_and_output[self.inputs_and_output.len() - 1] 4,142 ( 0.00%) } . . // Creates a minimal `FnSig` to be used when encountering a `TyKind::Error` in a fallible . // method. . fn fake() -> FnSig<'tcx> { . FnSig { . inputs_and_output: List::empty(), . c_variadic: false, . unsafety: hir::Unsafety::Normal, -- line 1267 ---------------------------------------- -- line 1270 ---------------------------------------- . } . } . . pub type PolyFnSig<'tcx> = Binder<'tcx, FnSig<'tcx>>; . . impl<'tcx> PolyFnSig<'tcx> { . #[inline] . pub fn inputs(&self) -> Binder<'tcx, &'tcx [Ty<'tcx>]> { 841 ( 0.00%) self.map_bound_ref_unchecked(|fn_sig| fn_sig.inputs()) . } . #[inline] . pub fn input(&self, index: usize) -> ty::Binder<'tcx, Ty<'tcx>> { 2,499 ( 0.00%) self.map_bound_ref(|fn_sig| fn_sig.inputs()[index]) . } . pub fn inputs_and_output(&self) -> ty::Binder<'tcx, &'tcx List>> { . self.map_bound_ref(|fn_sig| fn_sig.inputs_and_output) 51 ( 0.00%) } . #[inline] . pub fn output(&self) -> ty::Binder<'tcx, Ty<'tcx>> { 1,597 ( 0.00%) self.map_bound_ref(|fn_sig| fn_sig.output()) . } . pub fn c_variadic(&self) -> bool { 102 ( 0.00%) self.skip_binder().c_variadic 51 ( 0.00%) } . pub fn unsafety(&self) -> hir::Unsafety { 568 ( 0.00%) self.skip_binder().unsafety 284 ( 0.00%) } . pub fn abi(&self) -> abi::Abi { 348 ( 0.00%) self.skip_binder().abi 87 ( 0.00%) } . } . . pub type CanonicalPolyFnSig<'tcx> = Canonical<'tcx, Binder<'tcx, FnSig<'tcx>>>; . 4 ( 0.00%) #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] . #[derive(HashStable)] . pub struct ParamTy { . pub index: u32, . pub name: Symbol, . } . . impl<'tcx> ParamTy { 6 ( 0.00%) pub fn new(index: u32, name: Symbol) -> ParamTy { . ParamTy { index, name } 3 ( 0.00%) } . . pub fn for_def(def: &ty::GenericParamDef) -> ParamTy { . ParamTy::new(def.index, def.name) . } . . #[inline] . pub fn to_ty(self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { . tcx.mk_ty_param(self.index, self.name) . } . } . . #[derive(Copy, Clone, Hash, TyEncodable, TyDecodable, Eq, PartialEq, Ord, PartialOrd)] . #[derive(HashStable)] . pub struct ParamConst { 44 ( 0.00%) pub index: u32, 44 ( 0.00%) pub name: Symbol, . } . . impl ParamConst { . pub fn new(index: u32, name: Symbol) -> ParamConst { . ParamConst { index, name } . } . . pub fn for_def(def: &ty::GenericParamDef) -> ParamConst { -- line 1338 ---------------------------------------- -- line 1440 ---------------------------------------- . /// the inference variable is supposed to satisfy the relation . /// *for every value of the placeholder region*. To ensure that doesn't . /// happen, you can use `leak_check`. This is more clearly explained . /// by the [rustc dev guide]. . /// . /// [1]: https://smallcultfollowing.com/babysteps/blog/2013/10/29/intermingled-parameter-lists/ . /// [2]: https://smallcultfollowing.com/babysteps/blog/2013/11/04/intermingled-parameter-lists/ . /// [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/hrtb.html 404,272 ( 0.02%) #[derive(Clone, PartialEq, Eq, Hash, Copy, TyEncodable, TyDecodable, PartialOrd, Ord)] 24 ( 0.00%) pub enum RegionKind { . /// Region bound in a type or fn declaration which will be . /// substituted 'early' -- that is, at the same time when type . /// parameters are substituted. . ReEarlyBound(EarlyBoundRegion), . . /// Region bound in a function scope, which will be substituted when the . /// function is called. 9,432 ( 0.00%) ReLateBound(ty::DebruijnIndex, BoundRegion), . . /// When checking a function body, the types of all arguments and so forth . /// that refer to bound region parameters are modified to refer to free . /// region parameters. . ReFree(FreeRegion), . . /// Static data that has an "infinite" lifetime. Top in the region lattice. . ReStatic, -- line 1465 ---------------------------------------- -- line 1478 ---------------------------------------- . /// regions visible from `U`, but not less than regions not visible . /// from `U`. . ReEmpty(ty::UniverseIndex), . . /// Erased region, used by trait selection, in MIR and during codegen. . ReErased, . } . 1,926 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, Debug, PartialOrd, Ord)] . pub struct EarlyBoundRegion { . pub def_id: DefId, 1,353 ( 0.00%) pub index: u32, 520 ( 0.00%) pub name: Symbol, . } . . /// A **`const`** **v**ariable **ID**. . #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] . pub struct ConstVid<'tcx> { 4,967 ( 0.00%) pub index: u32, . pub phantom: PhantomData<&'tcx ()>, . } . . rustc_index::newtype_index! { . /// A **region** (lifetime) **v**ariable **ID**. . pub struct RegionVid { . DEBUG_FORMAT = custom, . } -- line 1504 ---------------------------------------- -- line 1513 ---------------------------------------- . rustc_index::newtype_index! { . pub struct BoundVar { .. } . } . . #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] . #[derive(HashStable)] . pub struct BoundTy { . pub var: BoundVar, 467 ( 0.00%) pub kind: BoundTyKind, . } . 7,966 ( 0.00%) #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] . #[derive(HashStable)] . pub enum BoundTyKind { . Anon, . Param(Symbol), . } . . impl From for BoundTy { . fn from(var: BoundVar) -> Self { -- line 1532 ---------------------------------------- -- line 1616 ---------------------------------------- . RegionKind::RePlaceholder(placeholder) => placeholder.name.is_named(), . RegionKind::ReEmpty(_) => false, . RegionKind::ReErased => false, . } . } . . #[inline] . pub fn is_late_bound(&self) -> bool { 181 ( 0.00%) matches!(*self, ty::ReLateBound(..)) . } . . #[inline] . pub fn is_placeholder(&self) -> bool { . matches!(*self, ty::RePlaceholder(..)) . } . . #[inline] . pub fn bound_at_or_above_binder(&self, index: ty::DebruijnIndex) -> bool { 10,695 ( 0.00%) match *self { . ty::ReLateBound(debruijn, _) => debruijn >= index, . _ => false, . } . } . . pub fn type_flags(&self) -> TypeFlags { . let mut flags = TypeFlags::empty(); . 16,926 ( 0.00%) match *self { . ty::ReVar(..) => { . flags = flags | TypeFlags::HAS_FREE_REGIONS; . flags = flags | TypeFlags::HAS_FREE_LOCAL_REGIONS; . flags = flags | TypeFlags::HAS_RE_INFER; . } . ty::RePlaceholder(..) => { . flags = flags | TypeFlags::HAS_FREE_REGIONS; . flags = flags | TypeFlags::HAS_FREE_LOCAL_REGIONS; -- line 1651 ---------------------------------------- -- line 1669 ---------------------------------------- . ty::ReErased => { . flags = flags | TypeFlags::HAS_RE_ERASED; . } . } . . debug!("type_flags({:?}) = {:?}", self, flags); . . flags 494 ( 0.00%) } . . /// Given an early-bound or free region, returns the `DefId` where it was bound. . /// For example, consider the regions in this snippet of code: . /// . /// ``` . /// impl<'a> Foo { . /// ^^ -- early bound, declared on an impl . /// -- line 1685 ---------------------------------------- -- line 1713 ---------------------------------------- . . #[inline(always)] . pub fn flags(&self) -> TypeFlags { . self.flags . } . . #[inline] . pub fn is_unit(&self) -> bool { 254 ( 0.00%) match self.kind() { 15 ( 0.00%) Tuple(ref tys) => tys.is_empty(), . _ => false, . } . } . . #[inline] . pub fn is_never(&self) -> bool { 101,617 ( 0.00%) matches!(self.kind(), Never) . } . . #[inline] . pub fn is_primitive(&self) -> bool { . self.kind().is_primitive() . } . . #[inline] -- line 1737 ---------------------------------------- -- line 1741 ---------------------------------------- . . #[inline] . pub fn is_ref(&self) -> bool { . matches!(self.kind(), Ref(..)) . } . . #[inline] . pub fn is_ty_var(&self) -> bool { 89,274 ( 0.00%) matches!(self.kind(), Infer(TyVar(_))) . } . . #[inline] . pub fn ty_vid(&self) -> Option { 22,688 ( 0.00%) match self.kind() { 658 ( 0.00%) &Infer(TyVar(vid)) => Some(vid), . _ => None, . } . } . . #[inline] . pub fn is_ty_infer(&self) -> bool { . matches!(self.kind(), Infer(_)) . } -- line 1763 ---------------------------------------- -- line 1791 ---------------------------------------- . match self.kind() { . RawPtr(TypeAndMut { ty, .. }) | Ref(_, ty, _) => matches!(ty.kind(), Slice(_) | Str), . _ => false, . } . } . . #[inline] . pub fn is_array(&self) -> bool { 3 ( 0.00%) matches!(self.kind(), Array(..)) . } . . #[inline] . pub fn is_simd(&self) -> bool { . match self.kind() { . Adt(def, _) => def.repr.simd(), . _ => false, . } . } . 12 ( 0.00%) pub fn sequence_element_type(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { 24 ( 0.00%) match self.kind() { . Array(ty, _) | Slice(ty) => ty, . Str => tcx.mk_mach_uint(ty::UintTy::U8), . _ => bug!("`sequence_element_type` called on non-sequence value: {}", self), . } 12 ( 0.00%) } . . pub fn simd_size_and_type(&self, tcx: TyCtxt<'tcx>) -> (u64, Ty<'tcx>) { . match self.kind() { . Adt(def, substs) => { . assert!(def.repr.simd(), "`simd_size_and_type` called on non-SIMD type"); . let variant = def.non_enum_variant(); . let f0_ty = variant.fields[0].ty(tcx, substs); . -- line 1824 ---------------------------------------- -- line 1861 ---------------------------------------- . match self.kind() { . Ref(_, _, mutability) => Some(*mutability), . _ => None, . } . } . . #[inline] . pub fn is_unsafe_ptr(&self) -> bool { 569 ( 0.00%) matches!(self.kind(), RawPtr(_)) . } . . /// Tests if this is any kind of primitive pointer type (reference, raw pointer, fn pointer). . #[inline] . pub fn is_any_ptr(&self) -> bool { . self.is_region_ptr() || self.is_unsafe_ptr() || self.is_fn_ptr() . } . . #[inline] . pub fn is_box(&self) -> bool { 71,516 ( 0.00%) match self.kind() { 19,646 ( 0.00%) Adt(def, _) => def.is_box(), . _ => false, . } . } . . /// Panics if called on any type other than `Box`. . pub fn boxed_ty(&self) -> Ty<'tcx> { . match self.kind() { . Adt(def, substs) if def.is_box() => substs.type_at(0), -- line 1889 ---------------------------------------- -- line 1891 ---------------------------------------- . } . } . . /// A scalar type is one that denotes an atomic datum, with no sub-components. . /// (A RawPtr is scalar because it represents a non-managed pointer, so its . /// contents are abstract to rustc.) . #[inline] . pub fn is_scalar(&self) -> bool { 113 ( 0.00%) matches!( 327 ( 0.00%) self.kind(), . Bool | Char . | Int(_) . | Float(_) . | Uint(_) . | FnDef(..) . | FnPtr(_) . | RawPtr(_) . | Infer(IntVar(_) | FloatVar(_)) -- line 1908 ---------------------------------------- -- line 1922 ---------------------------------------- . . #[inline] . pub fn is_enum(&self) -> bool { . matches!(self.kind(), Adt(adt_def, _) if adt_def.is_enum()) . } . . #[inline] . pub fn is_union(&self) -> bool { 128 ( 0.00%) matches!(self.kind(), Adt(adt_def, _) if adt_def.is_union()) . } . . #[inline] . pub fn is_closure(&self) -> bool { . matches!(self.kind(), Closure(..)) . } . . #[inline] . pub fn is_generator(&self) -> bool { . matches!(self.kind(), Generator(..)) . } . . #[inline] . pub fn is_integral(&self) -> bool { 3,634 ( 0.00%) matches!(self.kind(), Infer(IntVar(_)) | Int(_) | Uint(_)) . } . . #[inline] . pub fn is_fresh_ty(&self) -> bool { . matches!(self.kind(), Infer(FreshTy(_))) . } . . #[inline] . pub fn is_fresh(&self) -> bool { 165 ( 0.00%) matches!(self.kind(), Infer(FreshTy(_) | FreshIntTy(_) | FreshFloatTy(_))) . } . . #[inline] . pub fn is_char(&self) -> bool { . matches!(self.kind(), Char) . } . . #[inline] -- line 1963 ---------------------------------------- -- line 1967 ---------------------------------------- . . #[inline] . pub fn is_signed(&self) -> bool { . matches!(self.kind(), Int(_)) . } . . #[inline] . pub fn is_ptr_sized_integral(&self) -> bool { 36 ( 0.00%) matches!(self.kind(), Int(ty::IntTy::Isize) | Uint(ty::UintTy::Usize)) . } . . #[inline] . pub fn has_concrete_skeleton(&self) -> bool { . !matches!(self.kind(), Param(_) | Infer(_) | Error(_)) . } . . /// Returns the type and mutability of `*ty`. . /// . /// The parameter `explicit` indicates if this is an *explicit* dereference. . /// Some types -- notably unsafe ptrs -- can only be dereferenced explicitly. 38,179 ( 0.00%) pub fn builtin_deref(&self, explicit: bool) -> Option> { 265,071 ( 0.01%) match self.kind() { 55,108 ( 0.00%) Adt(def, _) if def.is_box() => { . Some(TypeAndMut { ty: self.boxed_ty(), mutbl: hir::Mutability::Not }) . } 5,550 ( 0.00%) Ref(_, ty, mutbl) => Some(TypeAndMut { ty, mutbl: *mutbl }), . RawPtr(mt) if explicit => Some(*mt), . _ => None, . } 76,358 ( 0.00%) } . . /// Returns the type of `ty[i]`. . pub fn builtin_index(&self) -> Option> { . match self.kind() { . Array(ty, _) | Slice(ty) => Some(ty), . _ => None, . } . } . 7,032 ( 0.00%) pub fn fn_sig(&self, tcx: TyCtxt<'tcx>) -> PolyFnSig<'tcx> { 3,516 ( 0.00%) match self.kind() { 2,637 ( 0.00%) FnDef(def_id, substs) => tcx.fn_sig(*def_id).subst(tcx, substs), . FnPtr(f) => *f, . Error(_) => { . // ignore errors (#54954) . ty::Binder::dummy(FnSig::fake()) . } . Closure(..) => bug!( . "to get the signature of a closure, use `substs.as_closure().sig()` not `fn_sig()`", . ), . _ => bug!("Ty::fn_sig() called on non-fn type: {:?}", self), . } 7,911 ( 0.00%) } . . #[inline] . pub fn is_fn(&self) -> bool { . matches!(self.kind(), FnDef(..) | FnPtr(_)) . } . . #[inline] . pub fn is_fn_ptr(&self) -> bool { -- line 2027 ---------------------------------------- -- line 2030 ---------------------------------------- . . #[inline] . pub fn is_impl_trait(&self) -> bool { . matches!(self.kind(), Opaque(..)) . } . . #[inline] . pub fn ty_adt_def(&self) -> Option<&'tcx AdtDef> { 65,042 ( 0.00%) match self.kind() { . Adt(adt, _) => Some(adt), . _ => None, . } . } . . /// Iterates over tuple fields. . /// Panics when called on anything but a tuple. 3 ( 0.00%) pub fn tuple_fields(&self) -> impl DoubleEndedIterator> { 9,174 ( 0.00%) match self.kind() { 4,599 ( 0.00%) Tuple(substs) => substs.iter().map(|field| field.expect_ty()), . _ => bug!("tuple_fields called on non-tuple"), . } 6 ( 0.00%) } . . /// Get the `i`-th element of a tuple. . /// Panics when called on anything but a tuple. . pub fn tuple_element_ty(&self, i: usize) -> Option> { . match self.kind() { . Tuple(substs) => substs.iter().nth(i).map(|field| field.expect_ty()), . _ => bug!("tuple_fields called on non-tuple"), . } -- line 2059 ---------------------------------------- -- line 2073 ---------------------------------------- . } . } . . /// If the type contains variants, returns the variant for `variant_index`. . /// Panics if `variant_index` is out of range. . // . // FIXME: This requires the optimized MIR in the case of generators. . #[inline] 46,120 ( 0.00%) pub fn discriminant_for_variant( . &self, . tcx: TyCtxt<'tcx>, . variant_index: VariantIdx, . ) -> Option> { 23,060 ( 0.00%) match self.kind() { 9,224 ( 0.00%) TyKind::Adt(adt, _) if adt.variants.is_empty() => { . // This can actually happen during CTFE, see . // https://github.com/rust-lang/rust/issues/89765. . None . } 4,612 ( 0.00%) TyKind::Adt(adt, _) if adt.is_enum() => { . Some(adt.discriminant_for_variant(tcx, variant_index)) . } . TyKind::Generator(def_id, substs, _) => { . Some(substs.as_generator().discriminant_for_variant(*def_id, tcx, variant_index)) . } . _ => None, . } 36,896 ( 0.00%) } . . /// Returns the type of the discriminant of this type. 138,690 ( 0.01%) pub fn discriminant_ty(&'tcx self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { 69,345 ( 0.00%) match self.kind() { 110,952 ( 0.01%) ty::Adt(adt, _) if adt.is_enum() => adt.repr.discr_type().to_ty(tcx), . ty::Generator(_, substs, _) => substs.as_generator().discr_ty(tcx), . . ty::Param(_) | ty::Projection(_) | ty::Opaque(..) | ty::Infer(ty::TyVar(_)) => { . let assoc_items = tcx.associated_item_def_ids( . tcx.require_lang_item(hir::LangItem::DiscriminantKind, None), . ); . tcx.mk_projection(assoc_items[0], tcx.intern_substs(&[self.into()])) . } -- line 2113 ---------------------------------------- -- line 2135 ---------------------------------------- . | ty::Infer(IntVar(_) | FloatVar(_)) => tcx.types.u8, . . ty::Bound(..) . | ty::Placeholder(_) . | ty::Infer(FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => { . bug!("`discriminant_ty` applied to unexpected type: {:?}", self) . } . } 110,952 ( 0.01%) } . . /// Returns the type of metadata for (potentially fat) pointers to this type. . pub fn ptr_metadata_ty( . &'tcx self, . tcx: TyCtxt<'tcx>, . normalize: impl FnMut(Ty<'tcx>) -> Ty<'tcx>, . ) -> Ty<'tcx> { . let tail = tcx.struct_tail_with_normalize(self, normalize); -- line 2151 ---------------------------------------- -- line 2229 ---------------------------------------- . /// Returning true means the type is known to be sized. Returning . /// `false` means nothing -- could be sized, might not be. . /// . /// Note that we could never rely on the fact that a type such as `[_]` is . /// trivially `!Sized` because we could be in a type environment with a . /// bound such as `[_]: Copy`. A function with such a bound obviously never . /// can be called, but that doesn't mean it shouldn't typecheck. This is why . /// this method doesn't return `Option`. 646,920 ( 0.03%) pub fn is_trivially_sized(&self, tcx: TyCtxt<'tcx>) -> bool { 431,280 ( 0.02%) match self.kind() { . ty::Infer(ty::IntVar(_) | ty::FloatVar(_)) . | ty::Uint(_) . | ty::Int(_) . | ty::Bool . | ty::Float(_) . | ty::FnDef(..) . | ty::FnPtr(_) . | ty::RawPtr(..) -- line 2246 ---------------------------------------- -- line 2250 ---------------------------------------- . | ty::GeneratorWitness(..) . | ty::Array(..) . | ty::Closure(..) . | ty::Never . | ty::Error(_) => true, . . ty::Str | ty::Slice(_) | ty::Dynamic(..) | ty::Foreign(..) => false, . 68,608 ( 0.00%) ty::Tuple(tys) => tys.iter().all(|ty| ty.expect_ty().is_trivially_sized(tcx)), . 167,208 ( 0.01%) ty::Adt(def, _substs) => def.sized_constraint(tcx).is_empty(), . . ty::Projection(_) | ty::Param(_) | ty::Opaque(..) => false, . . ty::Infer(ty::TyVar(_)) => false, . . ty::Bound(..) . | ty::Placeholder(..) . | ty::Infer(ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_)) => { . bug!("`is_trivially_sized` applied to unexpected type: {:?}", self) . } . } 646,920 ( 0.03%) } . } . . /// Extra information about why we ended up with a particular variance. . /// This is only used to add more information to error messages, and . /// has no effect on soundness. While choosing the 'wrong' `VarianceDiagInfo` . /// may lead to confusing notes in error messages, it will never cause . /// a miscompilation or unsoundness. . /// -- line 2280 ---------------------------------------- -- line 2295 ---------------------------------------- . /// (e.g. `0` for `*mut T`, `1` for `MyStruct<'CovariantParam, 'InvariantParam>`) . param_index: u32, . }, . } . . impl<'tcx> VarianceDiagInfo<'tcx> { . /// Mirrors `Variance::xform` - used to 'combine' the existing . /// and new `VarianceDiagInfo`s when our variance changes. 8,174 ( 0.00%) pub fn xform(self, other: VarianceDiagInfo<'tcx>) -> VarianceDiagInfo<'tcx> { . // For now, just use the first `VarianceDiagInfo::Invariant` that we see 12,261 ( 0.00%) match self { . VarianceDiagInfo::None => other, . VarianceDiagInfo::Invariant { .. } => self, . } 4,087 ( 0.00%) } . } 3,312,092 ( 0.16%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cell.rs -------------------------------------------------------------------------------- Ir -- line 346 ---------------------------------------- . /// . /// let c = Cell::new(5); . /// . /// c.set(10); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn set(&self, val: T) { 27 ( 0.00%) let old = self.replace(val); 252 ( 0.00%) drop(old); . } . . /// Swaps the values of two `Cell`s. . /// Difference with `std::mem::swap` is that this function doesn't require `&mut` reference. . /// . /// # Examples . /// . /// ``` -- line 363 ---------------------------------------- -- line 434 ---------------------------------------- . /// . /// let five = c.get(); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn get(&self) -> T { . // SAFETY: This can cause data races if called from a separate thread, . // but `Cell` is `!Sync` so this won't happen. 137,027 ( 0.01%) unsafe { *self.value.get() } . } . . /// Updates the contained value using a function and returns the new value. . /// . /// # Examples . /// . /// ``` . /// #![feature(cell_update)] -- line 450 ---------------------------------------- -- line 689 ---------------------------------------- . . #[inline(always)] . fn is_writing(x: BorrowFlag) -> bool { . x < UNUSED . } . . #[inline(always)] . fn is_reading(x: BorrowFlag) -> bool { 574,570 ( 0.03%) x > UNUSED . } . . impl RefCell { . /// Creates a new `RefCell` containing `value`. . /// . /// # Examples . /// . /// ``` -- line 705 ---------------------------------------- -- line 706 ---------------------------------------- . /// use std::cell::RefCell; . /// . /// let c = RefCell::new(5); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_refcell_new", since = "1.24.0")] . #[inline] . pub const fn new(value: T) -> RefCell { 11,640 ( 0.00%) RefCell { 11,104 ( 0.00%) value: UnsafeCell::new(value), . borrow: Cell::new(UNUSED), . #[cfg(feature = "debug_refcell")] . borrowed_at: Cell::new(None), . } . } . . /// Consumes the `RefCell`, returning the wrapped value. . /// -- line 723 ---------------------------------------- -- line 731 ---------------------------------------- . /// let five = c.into_inner(); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_cell_into_inner", issue = "78729")] . #[inline] . pub const fn into_inner(self) -> T { . // Since this function takes `self` (the `RefCell`) by value, the . // compiler statically verifies that it is not currently borrowed. 412 ( 0.00%) self.value.into_inner() . } . . /// Replaces the wrapped value with a new one, returning the old value, . /// without deinitializing either one. . /// . /// This function corresponds to [`std::mem::replace`](../mem/fn.replace.html). . /// . /// # Panics -- line 747 ---------------------------------------- -- line 845 ---------------------------------------- . /// let c = RefCell::new(5); . /// . /// let m = c.borrow_mut(); . /// let b = c.borrow(); // this causes a panic . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . #[track_caller] 20,246 ( 0.00%) pub fn borrow(&self) -> Ref<'_, T> { . self.try_borrow().expect("already mutably borrowed") 60,738 ( 0.00%) } . . /// Immutably borrows the wrapped value, returning an error if the value is currently mutably . /// borrowed. . /// . /// The borrow lasts until the returned `Ref` exits scope. Multiple immutable borrows can be . /// taken out at the same time. . /// . /// This is the non-panicking variant of [`borrow`](#method.borrow). -- line 863 ---------------------------------------- -- line 937 ---------------------------------------- . /// let c = RefCell::new(5); . /// let m = c.borrow(); . /// . /// let b = c.borrow_mut(); // this causes a panic . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . #[track_caller] 39,813 ( 0.00%) pub fn borrow_mut(&self) -> RefMut<'_, T> { . self.try_borrow_mut().expect("already borrowed") 119,439 ( 0.01%) } . . /// Mutably borrows the wrapped value, returning an error if the value is currently borrowed. . /// . /// The borrow lasts until the returned `RefMut` or all `RefMut`s derived . /// from it exit scope. The value cannot be borrowed while this borrow is . /// active. . /// . /// This is the non-panicking variant of [`borrow_mut`](#method.borrow_mut). -- line 955 ---------------------------------------- -- line 975 ---------------------------------------- . match BorrowRefMut::new(&self.borrow) { . Some(b) => { . #[cfg(feature = "debug_refcell")] . { . self.borrowed_at.set(Some(crate::panic::Location::caller())); . } . . // SAFETY: `BorrowRef` guarantees unique access. 22 ( 0.00%) Ok(RefMut { value: unsafe { &mut *self.value.get() }, borrow: b }) . } . None => Err(BorrowMutError { . // If a borrow occurred, then we must already have an outstanding borrow, . // so `borrowed_at` will be `Some` . #[cfg(feature = "debug_refcell")] . location: self.borrowed_at.get().unwrap(), . }), . } -- line 991 ---------------------------------------- -- line 1254 ---------------------------------------- . . struct BorrowRef<'b> { . borrow: &'b Cell, . } . . impl<'b> BorrowRef<'b> { . #[inline] . fn new(borrow: &'b Cell) -> Option> { 910,630 ( 0.04%) let b = borrow.get().wrapping_add(1); 542,754 ( 0.03%) if !is_reading(b) { . // Incrementing borrow can result in a non-reading value (<= 0) in these cases: . // 1. It was < 0, i.e. there are writing borrows, so we can't allow a read borrow . // due to Rust's reference aliasing rules . // 2. It was isize::MAX (the max amount of reading borrows) and it overflowed . // into isize::MIN (the max amount of writing borrows) so we can't allow . // an additional read borrow because isize can't represent so many read borrows . // (this can only happen if you mem::forget more than a small constant amount of . // `Ref`s, which is not good practice) -- line 1271 ---------------------------------------- -- line 1279 ---------------------------------------- . Some(BorrowRef { borrow }) . } . } . } . . impl Drop for BorrowRef<'_> { . #[inline] . fn drop(&mut self) { 387,304 ( 0.02%) let borrow = self.borrow.get(); . debug_assert!(is_reading(borrow)); 774,277 ( 0.04%) self.borrow.set(borrow - 1); . } . } . . impl Clone for BorrowRef<'_> { . #[inline] . fn clone(&self) -> Self { . // Since this Ref exists, we know the borrow flag . // is a reading borrow. -- line 1297 ---------------------------------------- -- line 1645 ---------------------------------------- . . struct BorrowRefMut<'b> { . borrow: &'b Cell, . } . . impl Drop for BorrowRefMut<'_> { . #[inline] . fn drop(&mut self) { 3,384,937 ( 0.16%) let borrow = self.borrow.get(); . debug_assert!(is_writing(borrow)); 6,509,790 ( 0.31%) self.borrow.set(borrow + 1); . } . } . . impl<'b> BorrowRefMut<'b> { . #[inline] . fn new(borrow: &'b Cell) -> Option> { . // NOTE: Unlike BorrowRefMut::clone, new is called to create the initial . // mutable reference, and so there must currently be no existing . // references. Thus, while clone increments the mutable refcount, here . // we explicitly only allow going from UNUSED to UNUSED - 1. 7,257,137 ( 0.34%) match borrow.get() { . UNUSED => { . borrow.set(UNUSED - 1); . Some(BorrowRefMut { borrow }) . } . _ => None, . } . } . -- line 1674 ---------------------------------------- -- line 1711 ---------------------------------------- . self.value . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl DerefMut for RefMut<'_, T> { . #[inline] . fn deref_mut(&mut self) -> &mut T { 61 ( 0.00%) self.value . } . } . . #[unstable(feature = "coerce_unsized", issue = "27732")] . impl<'b, T: ?Sized + Unsize, U: ?Sized> CoerceUnsized> for RefMut<'b, T> {} . . #[stable(feature = "std_guard_impls", since = "1.20.0")] . impl fmt::Display for RefMut<'_, T> { -- line 1727 ---------------------------------------- -- line 1909 ---------------------------------------- . /// ``` . #[inline(always)] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_unsafecell_get", since = "1.32.0")] . pub const fn get(&self) -> *mut T { . // We can just cast the pointer from `UnsafeCell` to `T` because of . // #[repr(transparent)]. This exploits libstd's special status, there is . // no guarantee for user code that this will work in future versions of the compiler! 3,049,801 ( 0.14%) self as *const UnsafeCell as *const T as *mut T . } . . /// Returns a mutable reference to the underlying data. . /// . /// This call borrows the `UnsafeCell` mutably (at compile-time) which . /// guarantees that we possess the only reference. . /// . /// # Examples -- line 1925 ---------------------------------------- 4,944,945 ( 0.23%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs -------------------------------------------------------------------------------- Ir -- line 57 ---------------------------------------- . /// # Examples . /// . /// Basic usage: . /// . /// ``` . #[doc = concat!("assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 6 ( 0.00%) pub fn from_str_radix(src: &str, radix: u32) -> Result { 3 ( 0.00%) from_str_radix(src, radix) 9 ( 0.00%) } . . /// Returns the number of ones in the binary representation of `self`. . /// . /// # Examples . /// . /// Basic usage: . /// . /// ``` -- line 75 ---------------------------------------- -- line 80 ---------------------------------------- . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_math", since = "1.32.0")] . #[doc(alias = "popcount")] . #[doc(alias = "popcnt")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn count_ones(self) -> u32 { 17,475 ( 0.00%) intrinsics::ctpop(self as $ActualT) as u32 . } . . /// Returns the number of zeros in the binary representation of `self`. . /// . /// # Examples . /// . /// Basic usage: . /// -- line 96 ---------------------------------------- -- line 118 ---------------------------------------- . /// assert_eq!(n.leading_zeros(), 2); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn leading_zeros(self) -> u32 { 214,028 ( 0.01%) intrinsics::ctlz(self as $ActualT) as u32 . } . . /// Returns the number of trailing zeros in the binary representation . /// of `self`. . /// . /// # Examples . /// . /// Basic usage: -- line 134 ---------------------------------------- -- line 139 ---------------------------------------- . /// assert_eq!(n.trailing_zeros(), 3); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn trailing_zeros(self) -> u32 { 625,985 ( 0.03%) 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 { 13,045,036 ( 0.61%) 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`. 827,441 ( 0.04%) unsafe { intrinsics::unchecked_add(self, rhs) } . } . . /// Checked addition with a signed integer. Computes `self + rhs`, . /// returning `None` if overflow occurred. . /// . /// # Examples . /// . /// Basic usage: -- line 472 ---------------------------------------- -- line 525 ---------------------------------------- . )] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")] . #[inline(always)] . pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self { . // SAFETY: the caller must uphold the safety contract for . // `unchecked_sub`. 73,759 ( 0.00%) unsafe { intrinsics::unchecked_sub(self, rhs) } . } . . /// Checked integer multiplication. Computes `self * rhs`, returning . /// `None` if overflow occurred. . /// . /// # Examples . /// . /// Basic usage: -- line 541 ---------------------------------------- -- line 1035 ---------------------------------------- . #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_add(127), ", stringify!($SelfT), "::MAX);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")] . #[inline(always)] . pub const fn saturating_add(self, rhs: Self) -> Self { 235,439 ( 0.01%) 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 { 477,362 ( 0.02%) 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 { 8,224,112 ( 0.39%) 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 { 2,993,360 ( 0.14%) 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 { 6,923,654 ( 0.33%) 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) { 2,418,681 ( 0.11%) 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) { 238,217 ( 0.01%) let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT); . (a as Self, b) . } . . /// Calculates `self - rhs - borrow` without the ability to overflow. . /// . /// Performs "ternary subtraction" which takes in an extra bit to subtract, and may return . /// an additional bit of overflow. This allows for chaining together multiple subtractions . /// to create "big integers" which represent larger values. -- line 1604 ---------------------------------------- -- line 1674 ---------------------------------------- . /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true)); . /// ``` . #[stable(feature = "wrapping", since = "1.7.0")] . #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline(always)] . pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) { 1,398,246 ( 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 { 84 ( 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 { 21,912 ( 0.00%) if self <= 1 { return 0; } . 14,085 ( 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. 42,229 ( 0.00%) let z = unsafe { intrinsics::ctlz_nonzero(p) }; 14,095 ( 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 { 6,250 ( 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 ---------------------------------------- 43,126 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast_pretty/src/pp.rs -------------------------------------------------------------------------------- Ir -- line 166 ---------------------------------------- . String(Cow<'static, str>), . Break(BreakToken), . Begin(BeginToken), . End, . } . . impl Token { . pub fn is_hardbreak_tok(&self) -> bool { 27,426 ( 0.00%) matches!(self, Token::Break(BreakToken { offset: 0, blank_space: SIZE_INFINITY })) . } . } . . #[derive(Copy, Clone)] . enum PrintFrame { . Fits, . Broken { offset: isize, breaks: Breaks }, . } -- line 182 ---------------------------------------- -- line 213 ---------------------------------------- . . #[derive(Clone)] . struct BufEntry { . token: Token, . size: isize, . } . . impl Printer { 40 ( 0.00%) pub fn new() -> Self { . let linewidth = 78; 10,045 ( 0.00%) Printer { . out: String::new(), . margin: linewidth as isize, . space: linewidth as isize, . buf: RingBuffer::new(), . left_total: 0, . right_total: 0, . scan_stack: VecDeque::new(), . print_stack: Vec::new(), . pending_indentation: 0, . last_printed: None, . } 50 ( 0.00%) } . . pub fn last_token(&self) -> Option<&Token> { . self.last_token_still_buffered().or_else(|| self.last_printed.as_ref()) . } . . pub fn last_token_still_buffered(&self) -> Option<&Token> { . self.buf.last().map(|last| &last.token) . } . . /// Be very careful with this! . pub fn replace_last_token_still_buffered(&mut self, token: Token) { . self.buf.last_mut().unwrap().token = token; . } . . fn scan_eof(&mut self) { 463 ( 0.00%) if !self.scan_stack.is_empty() { 20 ( 0.00%) self.check_stack(0); 20 ( 0.00%) self.advance_left(); . } . } . . fn scan_begin(&mut self, token: BeginToken) { 41,085 ( 0.00%) if self.scan_stack.is_empty() { 20 ( 0.00%) self.left_total = 1; . self.right_total = 1; . self.buf.clear(); . } 164,340 ( 0.01%) let right = self.buf.push(BufEntry { token: Token::Begin(token), size: -self.right_total }); . self.scan_stack.push_back(right); . } . . fn scan_end(&mut self) { 41,085 ( 0.00%) if self.scan_stack.is_empty() { . self.print_end(); . } else { . let right = self.buf.push(BufEntry { token: Token::End, size: -1 }); . self.scan_stack.push_back(right); . } . } . . fn scan_break(&mut self, token: BreakToken) { 22,824 ( 0.00%) if self.scan_stack.is_empty() { . self.left_total = 1; . self.right_total = 1; . self.buf.clear(); . } else { 45,648 ( 0.00%) self.check_stack(0); . } 91,296 ( 0.00%) let right = self.buf.push(BufEntry { token: Token::Break(token), size: -self.right_total }); . self.scan_stack.push_back(right); 68,472 ( 0.00%) self.right_total += token.blank_space; . } . 826,182 ( 0.04%) fn scan_string(&mut self, string: Cow<'static, str>) { 91,798 ( 0.00%) if self.scan_stack.is_empty() { . self.print_string(&string); . } else { . let len = string.len() as isize; 91,345 ( 0.00%) self.buf.push(BufEntry { token: Token::String(string), size: len }); 274,035 ( 0.01%) self.right_total += len; . self.check_stream(); . } 730,760 ( 0.03%) } . . fn check_stream(&mut self) { 569,975 ( 0.03%) while self.right_total - self.left_total > self.space { 122,757 ( 0.01%) if *self.scan_stack.front().unwrap() == self.buf.index_of_first() { . self.scan_stack.pop_front().unwrap(); 31,832 ( 0.00%) self.buf.first_mut().unwrap().size = SIZE_INFINITY; . } 81,838 ( 0.00%) self.advance_left(); 40,919 ( 0.00%) if self.buf.is_empty() { . break; . } . } . } . 892,132 ( 0.04%) fn advance_left(&mut self) { 474,516 ( 0.02%) while self.buf.first().unwrap().size >= 0 { 589,017 ( 0.03%) let left = self.buf.pop_first().unwrap(); . . match &left.token { . Token::String(string) => { 274,035 ( 0.01%) self.left_total += string.len() as isize; . self.print_string(string); . } . Token::Break(token) => { 68,472 ( 0.00%) self.left_total += token.blank_space; . self.print_break(*token, left.size); . } 54,555 ( 0.00%) Token::Begin(token) => self.print_begin(*token, left.size), . Token::End => self.print_end(), . } . 1,570,712 ( 0.07%) self.last_printed = Some(left.token); . 196,339 ( 0.01%) if self.buf.is_empty() { . break; . } . } 327,432 ( 0.02%) } . 205,506 ( 0.01%) fn check_stack(&mut self, mut depth: usize) { 182,826 ( 0.01%) while let Some(&index) = self.scan_stack.back() { . let mut entry = &mut self.buf[index]; 361,113 ( 0.02%) match entry.token { . Token::Begin(_) => { 73,202 ( 0.00%) if depth == 0 { . break; . } . self.scan_stack.pop_back().unwrap(); 68,700 ( 0.00%) entry.size += self.right_total; 22,900 ( 0.00%) depth -= 1; . } . Token::End => { . // paper says + not =, but that makes no sense. . self.scan_stack.pop_back().unwrap(); 41,082 ( 0.00%) entry.size = 1; 82,164 ( 0.00%) depth += 1; . } . _ => { . self.scan_stack.pop_back().unwrap(); 27,540 ( 0.00%) entry.size += self.right_total; 18,393 ( 0.00%) if depth == 0 { . break; . } . } . } . } 182,672 ( 0.01%) } . . fn get_top(&self) -> PrintFrame { 68,472 ( 0.00%) *self . .print_stack . .last() . .unwrap_or(&PrintFrame::Broken { offset: 0, breaks: Breaks::Inconsistent }) . } . . fn print_begin(&mut self, token: BeginToken, size: isize) { 123,255 ( 0.01%) if size > self.space { 90,925 ( 0.00%) let col = self.margin - self.space + token.offset; . self.print_stack.push(PrintFrame::Broken { offset: col, breaks: token.breaks }); . } else { . self.print_stack.push(PrintFrame::Fits); . } . } . . fn print_end(&mut self) { . self.print_stack.pop().unwrap(); . } . . fn print_break(&mut self, token: BreakToken, size: isize) { . let break_offset = 91,320 ( 0.00%) match self.get_top() { . PrintFrame::Fits => None, . PrintFrame::Broken { offset, breaks: Breaks::Consistent } => Some(offset), . PrintFrame::Broken { offset, breaks: Breaks::Inconsistent } => { . if size > self.space { Some(offset) } else { None } . } . }; . if let Some(offset) = break_offset { . self.out.push('\n'); 40,932 ( 0.00%) self.pending_indentation = offset + token.offset; 54,576 ( 0.00%) self.space = self.margin - (offset + token.offset); . } else { 27,540 ( 0.00%) self.pending_indentation += token.blank_space; 36,720 ( 0.00%) self.space -= token.blank_space; . } . } . . fn print_string(&mut self, string: &str) { . // Write the pending indent. A more concise way of doing this would be: . // . // write!(self.out, "{: >n$}", "", n = self.pending_indentation as usize)?; . // . // But that is significantly slower. This code is sufficiently hot, and indents can get . // sufficiently large, that the difference is significant on some workloads. 91,798 ( 0.00%) self.out.reserve(self.pending_indentation as usize); 25 ( 0.00%) self.out.extend(iter::repeat(' ').take(self.pending_indentation as usize)); 91,798 ( 0.00%) self.pending_indentation = 0; . . self.out.push_str(string); 458,537 ( 0.02%) self.space -= string.len() as isize; . } . . // Convenience functions to talk to the printer. . . /// "raw box" 72,944 ( 0.00%) pub fn rbox(&mut self, indent: usize, breaks: Breaks) { . self.scan_begin(BeginToken { offset: indent as isize, breaks }) 54,708 ( 0.00%) } . . /// Inconsistent breaking box 191,802 ( 0.01%) pub fn ibox(&mut self, indent: usize) { . self.rbox(indent, Breaks::Inconsistent) 159,835 ( 0.01%) } . . /// Consistent breaking box . pub fn cbox(&mut self, indent: usize) { . self.rbox(indent, Breaks::Consistent) . } . 182,592 ( 0.01%) pub fn break_offset(&mut self, n: usize, off: isize) { . self.scan_break(BreakToken { offset: off, blank_space: n as isize }) 136,944 ( 0.01%) } . 164,340 ( 0.01%) pub fn end(&mut self) { . self.scan_end() 164,340 ( 0.01%) } . 2,315 ( 0.00%) pub fn eof(mut self) -> String { . self.scan_eof(); 1,852 ( 0.00%) self.out 2,315 ( 0.00%) } . . pub fn word>>(&mut self, wrd: S) { . let string = wrd.into(); 651,985 ( 0.03%) self.scan_string(string) . } . . fn spaces(&mut self, n: usize) { 82,185 ( 0.00%) self.break_offset(n, 0) . } . . crate fn zerobreak(&mut self) { . self.spaces(0) . } . . pub fn space(&mut self) { . self.spaces(1) . } . . pub fn hardbreak(&mut self) { . self.spaces(SIZE_INFINITY as usize) . } . . pub fn is_beginning_of_line(&self) -> bool { 27,426 ( 0.00%) match self.last_token() { . Some(last_token) => last_token.is_hardbreak_tok(), . None => true, . } . } . . pub fn hardbreak_tok_offset(off: isize) -> Token { . Token::Break(BreakToken { offset: off, blank_space: SIZE_INFINITY }) . } -- line 481 ---------------------------------------- 1,443,871 ( 0.07%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/interpret/allocation.rs -------------------------------------------------------------------------------- Ir -- line 18 ---------------------------------------- . }; . use crate::ty; . . /// This type represents an Allocation in the Miri/CTFE core engine. . /// . /// Its public API is rather low-level, working directly with allocation offsets and a custom error . /// type to account for the lack of an AllocId on this level. The Miri/CTFE core engine `memory` . /// module provides higher-level access. 14,194 ( 0.00%) #[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] . #[derive(HashStable)] . pub struct Allocation { . /// The actual bytes of the allocation. . /// Note that the bytes of a pointer represent the offset of the pointer. 5,033 ( 0.00%) bytes: Box<[u8]>, . /// Maps from byte addresses to extra data for each pointer. . /// Only the first byte of a pointer is inserted into the map; i.e., . /// every entry in this map applies to `pointer_size` consecutive bytes starting . /// at the given offset. 688 ( 0.00%) relocations: Relocations, . /// Denotes which part of this allocation is initialized. . init_mask: InitMask, . /// The alignment of the allocation to detect unaligned reads. . /// (`Align` guarantees that this is a power of two.) 800 ( 0.00%) pub align: Align, . /// `true` if the allocation is mutable. . /// Also used by codegen to determine if a static should be put into mutable memory, . /// which happens for `static mut` and `static` with interior mutability. 400 ( 0.00%) pub mutability: Mutability, . /// Extra state for the machine. . pub extra: Extra, . } . . /// We have our own error type that does not know about the `AllocId`; that information . /// is added when converting to `InterpError`. . #[derive(Debug)] . pub enum AllocError { -- line 53 ---------------------------------------- -- line 91 ---------------------------------------- . impl AllocRange { . #[inline(always)] . pub fn end(self) -> Size { . self.start + self.size // This does overflow checking. . } . . /// Returns the `subrange` within this range; panics if it is not a subrange. . #[inline] 91,732 ( 0.00%) pub fn subrange(self, subrange: AllocRange) -> AllocRange { . let sub_start = self.start + subrange.start; . let range = alloc_range(sub_start, subrange.size); 91,732 ( 0.00%) assert!(range.end() <= self.end(), "access outside the bounds for given AllocRange"); . range 275,196 ( 0.01%) } . } . . // The constructors are all without extra; the extra gets added by a machine hook later. . impl Allocation { . /// Creates an allocation initialized by the given bytes . pub fn from_bytes<'a>( . slice: impl Into>, . align: Align, . mutability: Mutability, . ) -> Self { . let bytes = Box::<[u8]>::from(slice.into()); . let size = Size::from_bytes(bytes.len()); 936 ( 0.00%) Self { . bytes, . relocations: Relocations::new(), 351 ( 0.00%) init_mask: InitMask::new(size, true), . align, . mutability, . extra: (), . } . } . . pub fn from_bytes_byte_aligned_immutable<'a>(slice: impl Into>) -> Self { . Allocation::from_bytes(slice, Align::ONE, Mutability::Not) . } . . /// Try to create an Allocation of `size` bytes, failing if there is not enough memory . /// available to the compiler to do so. 151,173 ( 0.01%) pub fn uninit(size: Size, align: Align, panic_on_fail: bool) -> InterpResult<'static, Self> { . let bytes = Box::<[u8]>::try_new_zeroed_slice(size.bytes_usize()).map_err(|_| { . // This results in an error that can happen non-deterministically, since the memory . // available to the compiler can change between runs. Normally queries are always . // deterministic. However, we can be non-determinstic here because all uses of const . // evaluation (including ConstProp!) will make compilation fail (via hard error . // or ICE) upon encountering a `MemoryExhausted` error. . if panic_on_fail { . panic!("Allocation::uninit called with panic_on_fail had allocation failure") -- line 141 ---------------------------------------- -- line 142 ---------------------------------------- . } . ty::tls::with(|tcx| { . tcx.sess.delay_span_bug(DUMMY_SP, "exhausted memory during interpreation") . }); . InterpError::ResourceExhaustion(ResourceExhaustionInfo::MemoryExhausted) . })?; . // SAFETY: the box was zero-allocated, which is a valid initial value for Box<[u8]> . let bytes = unsafe { bytes.assume_init() }; 192,402 ( 0.01%) Ok(Allocation { . bytes, . relocations: Relocations::new(), 41,229 ( 0.00%) init_mask: InitMask::new(size, false), . align, . mutability: Mutability::Mut, . extra: (), . }) 123,687 ( 0.01%) } . } . . impl Allocation { . /// Convert Tag and add Extra fields . pub fn convert_tag_add_extra( . self, . cx: &impl HasDataLayout, . extra: Extra, -- line 166 ---------------------------------------- -- line 194 ---------------------------------------- . . /// Raw accessors. Provide access to otherwise private bytes. . impl Allocation { . pub fn len(&self) -> usize { . self.bytes.len() . } . . pub fn size(&self) -> Size { 96,298 ( 0.00%) Size::from_bytes(self.len()) . } . . /// Looks at a slice which may describe uninitialized bytes or describe a relocation. This differs . /// from `get_bytes_with_uninit_and_ptr` in that it does no relocation checks (even on the . /// edges) at all. . /// This must not be used for reads affecting the interpreter execution. . pub fn inspect_with_uninit_and_ptr_outside_interpreter(&self, range: Range) -> &[u8] { . &self.bytes[range] -- line 210 ---------------------------------------- -- line 227 ---------------------------------------- . /// or pointer bytes. You should never call this, call `get_bytes` or . /// `get_bytes_with_uninit_and_ptr` instead, . /// . /// This function also guarantees that the resulting pointer will remain stable . /// even when new allocations are pushed to the `HashMap`. `copy_repeatedly` relies . /// on that. . /// . /// It is the caller's responsibility to check bounds and alignment beforehand. 825,948 ( 0.04%) fn get_bytes_internal( . &self, . cx: &impl HasDataLayout, . range: AllocRange, . check_init_and_ptr: bool, . ) -> AllocResult<&[u8]> { 137,658 ( 0.01%) if check_init_and_ptr { 12 ( 0.00%) self.check_init(range)?; . self.check_relocations(cx, range)?; . } else { . // We still don't want relocations on the *edges*. . self.check_relocation_edges(cx, range)?; . } . 275,316 ( 0.01%) Ok(&self.bytes[range.start.bytes_usize()..range.end().bytes_usize()]) 619,461 ( 0.03%) } . . /// Checks that these bytes are initialized and not pointer bytes, and then return them . /// as a slice. . /// . /// It is the caller's responsibility to check bounds and alignment beforehand. . /// Most likely, you want to use the `PlaceTy` and `OperandTy`-based methods . /// on `InterpCx` instead. . #[inline] . pub fn get_bytes(&self, cx: &impl HasDataLayout, range: AllocRange) -> AllocResult<&[u8]> { 6 ( 0.00%) self.get_bytes_internal(cx, range, true) . } . . /// It is the caller's responsibility to handle uninitialized and pointer bytes. . /// However, this still checks that there are no relocations on the *edges*. . /// . /// It is the caller's responsibility to check bounds and alignment beforehand. . #[inline] . pub fn get_bytes_with_uninit_and_ptr( . &self, . cx: &impl HasDataLayout, . range: AllocRange, . ) -> AllocResult<&[u8]> { 160,442 ( 0.01%) self.get_bytes_internal(cx, range, false) . } . . /// Just calling this already marks everything as defined and removes relocations, . /// so be sure to actually put data there! . /// . /// It is the caller's responsibility to check bounds and alignment beforehand. . /// Most likely, you want to use the `PlaceTy` and `OperandTy`-based methods . /// on `InterpCx` instead. 302,104 ( 0.01%) pub fn get_bytes_mut( . &mut self, . cx: &impl HasDataLayout, . range: AllocRange, . ) -> AllocResult<&mut [u8]> { . self.mark_init(range, true); 137,320 ( 0.01%) self.clear_relocations(cx, range)?; . 109,856 ( 0.01%) Ok(&mut self.bytes[range.start.bytes_usize()..range.end().bytes_usize()]) 219,712 ( 0.01%) } . . /// A raw pointer variant of `get_bytes_mut` that avoids invalidating existing aliases into this memory. 50,138 ( 0.00%) pub fn get_bytes_mut_ptr( . &mut self, . cx: &impl HasDataLayout, . range: AllocRange, . ) -> AllocResult<*mut [u8]> { . self.mark_init(range, true); 22,790 ( 0.00%) self.clear_relocations(cx, range)?; . 9,116 ( 0.00%) assert!(range.end().bytes_usize() <= self.bytes.len()); // need to do our own bounds-check . let begin_ptr = self.bytes.as_mut_ptr().wrapping_add(range.start.bytes_usize()); 9,116 ( 0.00%) let len = range.end().bytes_usize() - range.start.bytes_usize(); 18,232 ( 0.00%) Ok(ptr::slice_from_raw_parts_mut(begin_ptr, len)) 36,464 ( 0.00%) } . } . . /// Reading and writing. . impl Allocation { . /// Validates that `ptr.offset` and `ptr.offset + size` do not point to the middle of a . /// relocation. If `allow_uninit_and_ptr` is `false`, also enforces that the memory in the . /// given range contains neither relocations nor uninitialized bytes. . pub fn check_bytes( -- line 314 ---------------------------------------- -- line 329 ---------------------------------------- . . /// Reads a *non-ZST* scalar. . /// . /// ZSTs can't be read because in order to obtain a `Pointer`, we need to check . /// for ZSTness anyway due to integer pointers being valid for ZSTs. . /// . /// It is the caller's responsibility to check bounds and alignment beforehand. . /// Most likely, you want to call `InterpCx::read_scalar` instead of this method. 835,484 ( 0.04%) pub fn read_scalar( . &self, . cx: &impl HasDataLayout, . range: AllocRange, . ) -> AllocResult> { . // `get_bytes_with_uninit_and_ptr` tests relocation edges. . // We deliberately error when loading data that partially has provenance, or partially . // initialized data (that's the check below), into a scalar. The LLVM semantics of this are . // unclear so we are conservative. See for -- line 345 ---------------------------------------- -- line 348 ---------------------------------------- . // Uninit check happens *after* we established that the alignment is correct. . // We must not return `Ok()` for unaligned pointers! . if self.is_init(range).is_err() { . // This inflates uninitialized bytes to the entire scalar, even if only a few . // bytes are uninitialized. . return Ok(ScalarMaybeUninit::Uninit); . } . // Now we do the actual reading. 64,268 ( 0.00%) let bits = read_target_uint(cx.data_layout().endian, bytes).unwrap(); . // See if we got a pointer. 64,268 ( 0.00%) if range.size != cx.data_layout().pointer_size { . // Not a pointer. . // *Now*, we better make sure that the inside is free of relocations too. . self.check_relocations(cx, range)?; . } else { . // Maybe a pointer. . if let Some(&prov) = self.relocations.get(&range.start) { . let ptr = Pointer::new(prov, Size::from_bytes(bits)); 195 ( 0.00%) return Ok(ScalarMaybeUninit::from_pointer(ptr, cx)); . } . } . // We don't. Just return the bits. 385,374 ( 0.02%) Ok(ScalarMaybeUninit::Scalar(Scalar::from_uint(bits, range.size))) 578,412 ( 0.03%) } . . /// Writes a *non-ZST* scalar. . /// . /// ZSTs can't be read because in order to obtain a `Pointer`, we need to check . /// for ZSTness anyway due to integer pointers being valid for ZSTs. . /// . /// It is the caller's responsibility to check bounds and alignment beforehand. . /// Most likely, you want to call `InterpCx::write_scalar` instead of this method. 192,248 ( 0.01%) pub fn write_scalar( . &mut self, . cx: &impl HasDataLayout, . range: AllocRange, . val: ScalarMaybeUninit, . ) -> AllocResult { 27,464 ( 0.00%) assert!(self.mutability == Mutability::Mut); . 82,392 ( 0.00%) let val = match val { . ScalarMaybeUninit::Scalar(scalar) => scalar, . ScalarMaybeUninit::Uninit => { . self.mark_init(range, false); . return Ok(()); . } . }; . . // `to_bits_or_ptr_internal` is the right method because we just want to store this data . // as-is into memory. 109,856 ( 0.01%) let (bytes, provenance) = match val.to_bits_or_ptr_internal(range.size) { . Err(val) => { . let (provenance, offset) = val.into_parts(); . (u128::from(offset.bytes()), Some(provenance)) . } . Ok(data) => (data, None), . }; . 82,392 ( 0.00%) let endian = cx.data_layout().endian; 82,392 ( 0.00%) let dst = self.get_bytes_mut(cx, range)?; . write_target_uint(endian, dst, bytes).unwrap(); . . // See if we have to also write a relocation. 82,377 ( 0.00%) if let Some(provenance) = provenance { 60 ( 0.00%) self.relocations.0.insert(range.start, provenance); . } . . Ok(()) 247,176 ( 0.01%) } . } . . /// Relocations. . impl Allocation { . /// Returns all relocations overlapping with the given pointer-offset pair. 701,628 ( 0.03%) pub fn get_relocations(&self, cx: &impl HasDataLayout, range: AllocRange) -> &[(Size, Tag)] { . // We have to go back `pointer_size - 1` bytes, as that one would still overlap with . // the beginning of this range. 715,302 ( 0.03%) let start = range.start.bytes().saturating_sub(cx.data_layout().pointer_size.bytes() - 1); . self.relocations.range(Size::from_bytes(start)..range.end()) 935,504 ( 0.04%) } . . /// Checks that there are no relocations overlapping with the given range. . #[inline(always)] . fn check_relocations(&self, cx: &impl HasDataLayout, range: AllocRange) -> AllocResult { 1,211,124 ( 0.06%) if self.get_relocations(cx, range).is_empty() { . Ok(()) . } else { . Err(AllocError::ReadPointerAsBytes) . } . } . . /// Removes all relocations inside the given range. . /// If there are relocations overlapping with the edges, they . /// are removed as well *and* the bytes they cover are marked as . /// uninitialized. This is a somewhat odd "spooky action at a distance", . /// but it allows strictly more code to run than if we would just error . /// immediately in that case. 352,242 ( 0.02%) fn clear_relocations(&mut self, cx: &impl HasDataLayout, range: AllocRange) -> AllocResult . where . Tag: Provenance, . { . // Find the start and end of the given range and its outermost relocations. . let (first, last) = { . // Find all relocations overlapping the given range. 160,110 ( 0.01%) let relocations = self.get_relocations(cx, range); 32,022 ( 0.00%) if relocations.is_empty() { . return Ok(()); . } . . ( . relocations.first().unwrap().0, . relocations.last().unwrap().0 + cx.data_layout().pointer_size, . ) . }; -- line 461 ---------------------------------------- -- line 478 ---------------------------------------- . } . self.init_mask.set_range(end, last, false); . } . . // Forget all the relocations. . self.relocations.0.remove_range(first..last); . . Ok(()) 224,154 ( 0.01%) } . . /// Errors if there are relocations overlapping with the edges of the . /// given memory range. . #[inline] . fn check_relocation_edges(&self, cx: &impl HasDataLayout, range: AllocRange) -> AllocResult { . self.check_relocations(cx, alloc_range(range.start, Size::ZERO))?; . self.check_relocations(cx, alloc_range(range.end(), Size::ZERO))?; . Ok(()) -- line 494 ---------------------------------------- -- line 496 ---------------------------------------- . } . . /// "Relocations" stores the provenance information of pointers stored in memory. . #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] . pub struct Relocations(SortedMap); . . impl Relocations { . pub fn new() -> Self { 27,720 ( 0.00%) Relocations(SortedMap::new()) . } . . // The caller must guarantee that the given relocations are already sorted . // by address and contain no duplicates. . pub fn from_presorted(r: Vec<(Size, Tag)>) -> Self { . Relocations(SortedMap::from_presorted_elements(r)) . } . } -- line 512 ---------------------------------------- -- line 520 ---------------------------------------- . } . . /// A partial, owned list of relocations to transfer into another allocation. . pub struct AllocationRelocations { . relative_relocations: Vec<(Size, Tag)>, . } . . impl Allocation { 45,580 ( 0.00%) pub fn prepare_relocation_copy( . &self, . cx: &impl HasDataLayout, . src: AllocRange, . dest: Size, . count: u64, . ) -> AllocationRelocations { . let relocations = self.get_relocations(cx, src); 4,558 ( 0.00%) if relocations.is_empty() { 9,110 ( 0.00%) return AllocationRelocations { relative_relocations: Vec::new() }; . } . 3 ( 0.00%) let size = src.size; 9 ( 0.00%) let mut new_relocations = Vec::with_capacity(relocations.len() * (count as usize)); . 3 ( 0.00%) for i in 0..count { . new_relocations.extend(relocations.iter().map(|&(offset, reloc)| { . // compute offset for current repetition 12 ( 0.00%) let dest_offset = dest + size * i; // `Size` operations . ( . // shift offsets from source allocation to destination allocation 3 ( 0.00%) (offset + dest_offset) - src.start, // `Size` operations . reloc, . ) . })); . } . 21 ( 0.00%) AllocationRelocations { relative_relocations: new_relocations } 41,022 ( 0.00%) } . . /// Applies a relocation copy. . /// The affected range, as defined in the parameters to `prepare_relocation_copy` is expected . /// to be clear of relocations. 31,906 ( 0.00%) pub fn mark_relocation_range(&mut self, relocations: AllocationRelocations) { 18,232 ( 0.00%) self.relocations.0.insert_presorted(relocations.relative_relocations); 36,464 ( 0.00%) } . } . . //////////////////////////////////////////////////////////////////////////////// . // Uninitialized byte tracking . //////////////////////////////////////////////////////////////////////////////// . . type Block = u64; . -- line 571 ---------------------------------------- -- line 582 ---------------------------------------- . pub const BLOCK_SIZE: u64 = 64; . . #[inline] . fn bit_index(bits: Size) -> (usize, usize) { . // BLOCK_SIZE is the number of bits that can fit in a `Block`. . // Each bit in a `Block` represents the initialization state of one byte of an allocation, . // so we use `.bytes()` here. . let bits = bits.bytes(); 375,858 ( 0.02%) let a = bits / InitMask::BLOCK_SIZE; 109,988 ( 0.01%) let b = bits % InitMask::BLOCK_SIZE; . (usize::try_from(a).unwrap(), usize::try_from(b).unwrap()) . } . . #[inline] . fn size_from_bit_index(block: impl TryInto, bit: impl TryInto) -> Size { . let block = block.try_into().ok().unwrap(); . let bit = bit.try_into().ok().unwrap(); 67,123 ( 0.00%) Size::from_bytes(block * InitMask::BLOCK_SIZE + bit) . } . 55,440 ( 0.00%) pub fn new(size: Size, state: bool) -> Self { 27,720 ( 0.00%) let mut m = InitMask { blocks: vec![], len: Size::ZERO }; 13,860 ( 0.00%) m.grow(size, state); . m 69,300 ( 0.00%) } . 256,176 ( 0.01%) pub fn set_range(&mut self, start: Size, end: Size, new_state: bool) { 64,044 ( 0.00%) let len = self.len; 32,022 ( 0.00%) if end > len { . self.grow(end - len, new_state); . } 320,220 ( 0.02%) self.set_range_inbounds(start, end, new_state); . } . 219,976 ( 0.01%) pub fn set_range_inbounds(&mut self, start: Size, end: Size, new_state: bool) { . let (blocka, bita) = Self::bit_index(start); . let (blockb, bitb) = Self::bit_index(end); 109,988 ( 0.01%) if blocka == blockb { . // First set all bits except the first `bita`, . // then unset the last `64 - bitb` bits. 106,570 ( 0.01%) let range = if bitb == 0 { . u64::MAX << bita . } else { 372,995 ( 0.02%) (u64::MAX << bita) & (u64::MAX >> (64 - bitb)) . }; 106,570 ( 0.01%) if new_state { 35,275 ( 0.00%) self.blocks[blocka] |= range; . } else { 36,020 ( 0.00%) self.blocks[blocka] &= !range; . } . return; . } . // across block boundaries 3,418 ( 0.00%) if new_state { . // Set `bita..64` to `1`. 4,266 ( 0.00%) self.blocks[blocka] |= u64::MAX << bita; . // Set `0..bitb` to `1`. 2,844 ( 0.00%) if bitb != 0 { 5,690 ( 0.00%) self.blocks[blockb] |= u64::MAX >> (64 - bitb); . } . // Fill in all the other blocks (much faster than one bit at a time). . for block in (blocka + 1)..blockb { . self.blocks[block] = u64::MAX; . } . } else { . // Set `bita..64` to `0`. 1,148 ( 0.00%) self.blocks[blocka] &= !(u64::MAX << bita); . // Set `0..bitb` to `0`. 574 ( 0.00%) if bitb != 0 { 12 ( 0.00%) self.blocks[blockb] &= !(u64::MAX >> (64 - bitb)); . } . // Fill in all the other blocks (much faster than one bit at a time). . for block in (blocka + 1)..blockb { 850 ( 0.00%) self.blocks[block] = 0; . } . } 109,988 ( 0.01%) } . . #[inline] . pub fn get(&self, i: Size) -> bool { . let (block, bit) = Self::bit_index(i); 31,906 ( 0.00%) (self.blocks[block] & (1 << bit)) != 0 . } . . #[inline] . pub fn set(&mut self, i: Size, new_state: bool) { . let (block, bit) = Self::bit_index(i); . self.set_bit(block, bit, new_state); . } . -- line 671 ---------------------------------------- -- line 673 ---------------------------------------- . fn set_bit(&mut self, block: usize, bit: usize, new_state: bool) { . if new_state { . self.blocks[block] |= 1 << bit; . } else { . self.blocks[block] &= !(1 << bit); . } . } . 83,160 ( 0.00%) pub fn grow(&mut self, amount: Size, new_state: bool) { 27,720 ( 0.00%) if amount.bytes() == 0 { . return; . } . let unused_trailing_bits = 110,880 ( 0.01%) u64::try_from(self.blocks.len()).unwrap() * Self::BLOCK_SIZE - self.len.bytes(); 27,720 ( 0.00%) if amount.bytes() > unused_trailing_bits { 41,580 ( 0.00%) let additional_blocks = amount.bytes() / Self::BLOCK_SIZE + 1; . self.blocks.extend( . // FIXME(oli-obk): optimize this by repeating `new_state as Block`. . iter::repeat(0).take(usize::try_from(additional_blocks).unwrap()), . ); . } 13,860 ( 0.00%) let start = self.len; . self.len += amount; 124,740 ( 0.01%) self.set_range_inbounds(start, start + amount, new_state); // `Size` operation . } . . /// Returns the index of the first bit in `start..end` (end-exclusive) that is equal to is_init. 146,766 ( 0.01%) fn find_bit(&self, start: Size, end: Size, is_init: bool) -> Option { . /// A fast implementation of `find_bit`, . /// which skips over an entire block at a time if it's all 0s (resp. 1s), . /// and finds the first 1 (resp. 0) bit inside a block using `trailing_zeros` instead of a loop. . /// . /// Note that all examples below are written with 8 (instead of 64) bit blocks for simplicity, . /// and with the least significant bit (and lowest block) first: . /// . /// 00000000|00000000 -- line 708 ---------------------------------------- -- line 728 ---------------------------------------- . // start_bit = 3 . // is_init = false . // Note that, for the examples in this function, the most significant bit is written first, . // which is backwards compared to the comments in `find_bit`/`find_bit_fast`. . . // Invert bits so we're always looking for the first set bit. . // ! 0b00111011 . // bits = 0b11000100 293,532 ( 0.01%) let bits = if is_init { bits } else { !bits }; . // Mask off unused start bits. . // 0b11000100 . // & 0b11111000 . // bits = 0b11000000 220,149 ( 0.01%) let bits = bits & (!0 << start_bit); . // Find set bit, if any. . // bit = trailing_zeros(0b11000000) . // bit = 6 146,766 ( 0.01%) if bits == 0 { . None . } else { . let bit = bits.trailing_zeros(); . Some(InitMask::size_from_bit_index(block, bit)) . } . } . 73,383 ( 0.00%) if start >= end { . return None; . } . . // Convert `start` and `end` to block indexes and bit indexes within each block. . // We must convert `end` to an inclusive bound to handle block boundaries correctly. . // . // For example: . // -- line 761 ---------------------------------------- -- line 819 ---------------------------------------- . // The block marked (3) in this example is the first block that will be handled by this loop, . // and it will be skipped for that reason: . // . // (3) . // -------- . // (e) 01000000|00000000|00000001 . // ^~~~~~~~~~~~~~~~~~^ . // start end 12,520 ( 0.00%) if start_block < end_block_inclusive { . // This loop is written in a specific way for performance. . // Notably: `..end_block_inclusive + 1` is used for an inclusive range instead of `..=end_block_inclusive`, . // and `.zip(start_block + 1..)` is used to track the index instead of `.enumerate().skip().take()`, . // because both alternatives result in significantly worse codegen. . // `end_block_inclusive + 1` is guaranteed not to wrap, because `end_block_inclusive <= end / BLOCK_SIZE`, . // and `BLOCK_SIZE` (the number of bits per block) will always be at least 8 (1 byte). . for (&bits, block) in init_mask.blocks[start_block + 1..end_block_inclusive + 1] . .iter() -- line 835 ---------------------------------------- -- line 879 ---------------------------------------- . "optimized implementation of find_bit is wrong for start={:?} end={:?} is_init={} init_mask={:#?}", . start, . end, . is_init, . self . ); . . result 146,766 ( 0.01%) } . } . . /// A contiguous chunk of initialized or uninitialized memory. . pub enum InitChunk { . Init(Range), . Uninit(Range), . } . -- line 895 ---------------------------------------- -- line 913 ---------------------------------------- . . impl InitMask { . /// Checks whether the range `start..end` (end-exclusive) is entirely initialized. . /// . /// Returns `Ok(())` if it's initialized. Otherwise returns a range of byte . /// indexes for the first contiguous span of the uninitialized access. . #[inline] . pub fn is_range_initialized(&self, start: Size, end: Size) -> Result<(), Range> { 64,274 ( 0.00%) if end > self.len { . return Err(self.len..end); . } . 321,355 ( 0.02%) let uninit_start = self.find_bit(start, end, false); . 128,542 ( 0.01%) match uninit_start { . Some(uninit_start) => { . let uninit_end = self.find_bit(uninit_start, end, true).unwrap_or(end); . Err(uninit_start..uninit_end) . } . None => Ok(()), . } . } . -- line 935 ---------------------------------------- -- line 938 ---------------------------------------- . /// . /// The iterator guarantees the following: . /// - Chunks are nonempty. . /// - Chunks are adjacent (each range's start is equal to the previous range's end). . /// - Chunks span exactly `start..end` (the first starts at `start`, the last ends at `end`). . /// - Chunks alternate between [`InitChunk::Init`] and [`InitChunk::Uninit`]. . #[inline] . pub fn range_as_init_chunks(&self, start: Size, end: Size) -> InitChunkIter<'_> { 4,558 ( 0.00%) assert!(end <= self.len); . 4,558 ( 0.00%) let is_init = if start < end { . self.get(start) . } else { . // `start..end` is empty: there are no chunks, so use some arbitrary value . false . }; . . InitChunkIter { init_mask: self, is_init, start, end } . } -- line 956 ---------------------------------------- -- line 968 ---------------------------------------- . end: Size, . } . . impl<'a> Iterator for InitChunkIter<'a> { . type Item = InitChunk; . . #[inline] . fn next(&mut self) -> Option { 9,112 ( 0.00%) if self.start >= self.end { . return None; . } . . let end_of_chunk = 54,668 ( 0.00%) self.init_mask.find_bit(self.start, self.end, !self.is_init).unwrap_or(self.end); . let range = self.start..end_of_chunk; . . let ret = 31,894 ( 0.00%) Some(if self.is_init { InitChunk::Init(range) } else { InitChunk::Uninit(range) }); . . self.is_init = !self.is_init; . self.start = end_of_chunk; . . ret . } . } . -- line 993 ---------------------------------------- -- line 998 ---------------------------------------- . /// Returns `Ok(())` if it's initialized. Otherwise returns the range of byte . /// indexes of the first contiguous uninitialized access. . fn is_init(&self, range: AllocRange) -> Result<(), Range> { . self.init_mask.is_range_initialized(range.start, range.end()) // `Size` addition . } . . /// Checks that a range of bytes is initialized. If not, returns the `InvalidUninitBytes` . /// error which will report the first range of bytes which is uninitialized. 27 ( 0.00%) fn check_init(&self, range: AllocRange) -> AllocResult { . self.is_init(range).map_err(|idx_range| { . AllocError::InvalidUninitBytes(Some(UninitBytesAccess { . access_offset: range.start, . access_size: range.size, . uninit_offset: idx_range.start, . uninit_size: idx_range.end - idx_range.start, // `Size` subtraction . })) . }) 24 ( 0.00%) } . . pub fn mark_init(&mut self, range: AllocRange, is_init: bool) { 64,044 ( 0.00%) if range.size.bytes() == 0 { . return; . } 32,022 ( 0.00%) assert!(self.mutability == Mutability::Mut); 128,088 ( 0.01%) self.init_mask.set_range(range.start, range.end(), is_init); . } . } . . /// Run-length encoding of the uninit mask. . /// Used to copy parts of a mask multiple times to another allocation. . pub struct InitMaskCompressed { . /// Whether the first range is initialized. . initial: bool, -- line 1030 ---------------------------------------- -- line 1032 ---------------------------------------- . /// The initialization state of the ranges alternate starting with `initial`. . ranges: smallvec::SmallVec<[u64; 1]>, . } . . impl InitMaskCompressed { . pub fn no_bytes_init(&self) -> bool { . // The `ranges` are run-length encoded and of alternating initialization state. . // So if `ranges.len() > 1` then the second block is an initialized range. 9,116 ( 0.00%) !self.initial && self.ranges.len() == 1 4,558 ( 0.00%) } . } . . /// Transferring the initialization mask to other allocations. . impl Allocation { . /// Creates a run-length encoding of the initialization mask; panics if range is empty. . /// . /// This is essentially a more space-efficient version of . /// `InitMask::range_as_init_chunks(...).collect::>()`. 31,906 ( 0.00%) pub fn compress_uninit_range(&self, range: AllocRange) -> InitMaskCompressed { . // Since we are copying `size` bytes from `src` to `dest + i * size` (`for i in 0..repeat`), . // a naive initialization mask copying algorithm would repeatedly have to read the initialization mask from . // the source and write it to the destination. Even if we optimized the memory accesses, . // we'd be doing all of this `repeat` times. . // Therefore we precompute a compressed version of the initialization mask of the source value and . // then write it back `repeat` times without computing any more information from the source. . . // A precomputed cache for ranges of initialized / uninitialized bits -- line 1058 ---------------------------------------- -- line 1062 ---------------------------------------- . . let mut ranges = smallvec::SmallVec::<[u64; 1]>::new(); . . let mut chunks = self.init_mask.range_as_init_chunks(range.start, range.end()).peekable(); . . let initial = chunks.peek().expect("range should be nonempty").is_init(); . . // Here we rely on `range_as_init_chunks` to yield alternating init/uninit chunks. 9,108 ( 0.00%) for chunk in chunks { 18,224 ( 0.00%) let len = chunk.range().end.bytes() - chunk.range().start.bytes(); . ranges.push(len); . } . 31,906 ( 0.00%) InitMaskCompressed { ranges, initial } 36,464 ( 0.00%) } . . /// Applies multiple instances of the run-length encoding to the initialization mask. 50,138 ( 0.00%) pub fn mark_compressed_init_range( . &mut self, . defined: &InitMaskCompressed, . range: AllocRange, . repeat: u64, . ) { . // An optimization where we can just overwrite an entire range of initialization . // bits if they are going to be uniformly `1` or `0`. 9,116 ( 0.00%) if defined.ranges.len() <= 1 { 40 ( 0.00%) self.init_mask.set_range_inbounds( . range.start, . range.start + range.size * repeat, // `Size` operations 4 ( 0.00%) defined.initial, . ); . return; . } . . for mut j in 0..repeat { 13,662 ( 0.00%) j *= range.size.bytes(); 9,108 ( 0.00%) j += range.start.bytes(); . let mut cur = defined.initial; . for range in &defined.ranges { . let old_j = j; . j += range; 27,324 ( 0.00%) self.init_mask.set_range_inbounds( . Size::from_bytes(old_j), . Size::from_bytes(j), 36,432 ( 0.00%) cur, . ); . cur = !cur; . } . } 36,432 ( 0.00%) } . } 1,368,963 ( 0.06%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/std/src/sys/unix/alloc.rs -------------------------------------------------------------------------------- Ir -- line 5 ---------------------------------------- . #[stable(feature = "alloc_system_type", since = "1.28.0")] . unsafe impl GlobalAlloc for System { . #[inline] . unsafe fn alloc(&self, layout: Layout) -> *mut u8 { . // jemalloc provides alignment less than MIN_ALIGN for small allocations. . // So only rely on MIN_ALIGN if size >= align. . // Also see and . // . 3,334,732 ( 0.16%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 2,501,049 ( 0.12%) 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. 65,796 ( 0.00%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 98,694 ( 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) { 850,121 ( 0.04%) libc::free(ptr as *mut libc::c_void) . } . . #[inline] . unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { 180,144 ( 0.01%) if layout.align() <= MIN_ALIGN && layout.align() <= new_size { 360,288 ( 0.02%) libc::realloc(ptr as *mut libc::c_void, new_size) as *mut u8 . } else { . realloc_fallback(self, ptr, layout, new_size) . } . } . } . . cfg_if::cfg_if! { . if #[cfg(any( -- line 56 ---------------------------------------- -------------------------------------------------------------------------------- -- 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, . { 2,043,667 ( 0.10%) 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. 37 ( 0.00%) #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd)] 660 ( 0.00%) #[derive(Decodable)] . pub enum RealFileName { . LocalPath(PathBuf), . /// For remapped paths (namely paths into libstd that have been mapped . /// to the appropriate spot on the local host's file system, and local file . /// system paths that have been remapped with `FilePathMapping`), . Remapped { . /// `local_path` is the (host-dependent) local path to the file. This is . /// None if the file was imported from another crate -- line 173 ---------------------------------------- -- line 179 ---------------------------------------- . } . . impl Hash for RealFileName { . fn hash(&self, state: &mut H) { . // To prevent #70924 from happening again we should only hash the . // remapped (virtualized) path if that exists. This is because . // virtualized paths to sysroot crates (/rust/$hash or /rust/$version) . // remain stable even if the corresponding local_path changes 1,827 ( 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> { 18 ( 0.00%) encoder.emit_enum(|encoder| match *self { . RealFileName::LocalPath(ref local_path) => { 72 ( 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 213 ---------------------------------------- . } . } . . impl RealFileName { . /// 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. . pub fn local_path(&self) -> Option<&Path> { 2 ( 0.00%) match self { . RealFileName::LocalPath(p) => Some(p), . RealFileName::Remapped { local_path: p, virtual_name: _ } => { . 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. 10 ( 0.00%) pub fn into_local_path(self) -> Option { 10 ( 0.00%) match self { . RealFileName::LocalPath(p) => Some(p), . RealFileName::Remapped { local_path: p, virtual_name: _ } => p, . } 15 ( 0.00%) } . . /// Returns the path suitable for embedding into build artifacts. This would still . /// be a local path if it has not been remapped. A remapped path will not correspond . /// to a valid file system path: see `local_path_if_available()` for something that . /// is more likely to return paths into the local host file system. . pub fn remapped_path_if_available(&self) -> &Path { 1,432 ( 0.00%) match self { . RealFileName::LocalPath(p) . | RealFileName::Remapped { local_path: _, virtual_name: p } => &p, . } 10 ( 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 { 9 ( 0.00%) match self { . RealFileName::LocalPath(path) . | RealFileName::Remapped { local_path: None, virtual_name: path } . | RealFileName::Remapped { local_path: Some(path), virtual_name: _ } => path, . } . } . . pub fn to_string_lossy(&self, display_pref: FileNameDisplayPreference) -> Cow<'_, str> { 9 ( 0.00%) match display_pref { . FileNameDisplayPreference::Local => self.local_path_if_available().to_string_lossy(), . FileNameDisplayPreference::Remapped => { . self.remapped_path_if_available().to_string_lossy() . } . } . } . } . . /// Differentiates between real files and common virtual files. 3,879 ( 0.00%) #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash)] 4,092 ( 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 { 63 ( 0.00%) fn from(p: PathBuf) -> Self { 18 ( 0.00%) assert!(!p.to_string_lossy().ends_with('>')); 54 ( 0.00%) FileName::Real(RealFileName::LocalPath(p)) 63 ( 0.00%) } . } . 2 ( 0.00%) #[derive(Clone, Copy, Eq, PartialEq, Hash, Debug)] . pub enum FileNameDisplayPreference { . Remapped, . Local, . } . . pub struct FileNameDisplay<'a> { . inner: &'a FileName, . display_pref: FileNameDisplayPreference, . } . . impl fmt::Display for FileNameDisplay<'_> { 36 ( 0.00%) fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { . use FileName::*; 54 ( 0.00%) match *self.inner { . Real(ref name) => { 54 ( 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, ""), . } 45 ( 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::*; 684 ( 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. 9 ( 0.00%) pub fn prefer_local(&self) -> FileNameDisplay<'_> { . FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Local } 18 ( 0.00%) } . . pub fn display(&self, display_pref: FileNameDisplayPreference) -> FileNameDisplay<'_> { . FileNameDisplay { inner: self, display_pref } . } . . pub fn macro_expansion_source_code(src: &str) -> FileName { . let mut hasher = StableHasher::new(); . src.hash(&mut hasher); -- line 375 ---------------------------------------- -- line 423 ---------------------------------------- . /// that the length of the span is equal to `span.hi - span.lo`; there may be space in the . /// [`BytePos`] range between files. . /// . /// `SpanData` is public because `Span` uses a thread-local interner and can't be . /// sent to other threads, but some pieces of performance infra run in a separate thread. . /// Using `Span` is generally preferred. . #[derive(Clone, Copy, Hash, PartialEq, Eq)] . pub struct SpanData { 10 ( 0.00%) pub lo: BytePos, 10 ( 0.00%) pub hi: BytePos, . /// Information about where the macro came from, if this piece of . /// code was created by a macro expansion. 15 ( 0.00%) pub ctxt: SyntaxContext, 5 ( 0.00%) pub parent: Option, . } . . // Order spans by position in the file. . impl Ord for SpanData { . fn cmp(&self, other: &Self) -> Ordering { . let SpanData { . lo: s_lo, . hi: s_hi, -- line 444 ---------------------------------------- -- line 485 ---------------------------------------- . } . #[inline] . pub fn with_parent(&self, parent: Option) -> Span { . Span::new(self.lo, self.hi, self.ctxt, parent) . } . /// Returns `true` if this is a dummy span with any hygienic context. . #[inline] . pub fn is_dummy(self) -> bool { 504,617 ( 0.02%) self.lo.0 == 0 && self.hi.0 == 0 . } . /// Returns `true` if `self` fully encloses `other`. . pub fn contains(self, other: Self) -> bool { 183 ( 0.00%) self.lo <= other.lo && other.hi <= self.hi . } . } . . // The interner is pointed to by a thread local value which is only set on the main thread . // with parallelization is disabled. So we don't allow `Span` to transfer between threads . // to avoid panics and other errors, even though it would be memory safe to do so. . #[cfg(not(parallel_compiler))] . impl !Send for Span {} . #[cfg(not(parallel_compiler))] . impl !Sync for Span {} . . impl PartialOrd for Span { 8,552 ( 0.00%) fn partial_cmp(&self, rhs: &Self) -> Option { 6,414 ( 0.00%) PartialOrd::partial_cmp(&self.data(), &rhs.data()) 8,552 ( 0.00%) } . } . 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] 136,665 ( 0.01%) pub fn with_lo(self, lo: BytePos) -> Span { . self.data().with_lo(lo) 91,110 ( 0.00%) } . #[inline] 1,008 ( 0.00%) pub fn hi(self) -> BytePos { . self.data().hi 1,008 ( 0.00%) } . #[inline] 7,119 ( 0.00%) pub fn with_hi(self, hi: BytePos) -> Span { . self.data().with_hi(hi) 4,746 ( 0.00%) } . #[inline] . pub fn ctxt(self) -> SyntaxContext { . self.data_untracked().ctxt . } . #[inline] 49,145 ( 0.00%) pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span { . self.data_untracked().with_ctxt(ctxt) 29,487 ( 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 568 ---------------------------------------- . /// Returns `true` if this is a dummy span with any hygienic context. . #[inline] . pub fn is_dummy(self) -> bool { . self.data_untracked().is_dummy() . } . . /// Returns `true` if this span comes from a macro or desugaring. . #[inline] 9 ( 0.00%) pub fn from_expansion(self) -> bool { . self.ctxt() != SyntaxContext::root() 6 ( 0.00%) } . . /// Returns `true` if `span` originates in a derive-macro's expansion. . pub fn in_derive_expansion(self) -> bool { . matches!(self.ctxt().outer_expn_data().kind, ExpnKind::Macro(MacroKind::Derive, _)) . } . . /// Gate suggestions that would not be appropriate in a context the user didn't write. . pub fn can_be_used_for_suggestions(self) -> bool { -- line 586 ---------------------------------------- -- line 618 ---------------------------------------- . } . . /// Returns `self` if `self` is not the dummy span, and `other` otherwise. . pub fn substitute_dummy(self, other: Span) -> Span { . if self.is_dummy() { other } else { self } . } . . /// Returns `true` if `self` fully encloses `other`. 549 ( 0.00%) pub fn contains(self, other: Span) -> bool { . let span = self.data(); . let other = other.data(); . span.contains(other) 366 ( 0.00%) } . . /// Returns `true` if `self` touches `other`. . pub fn overlaps(self, other: Span) -> bool { . let span = self.data(); . let other = other.data(); . span.lo < other.hi && other.lo < span.hi . } . -- line 638 ---------------------------------------- -- line 650 ---------------------------------------- . pub fn trim_start(self, other: Span) -> Option { . let span = self.data(); . let other = other.data(); . if span.hi > other.hi { Some(span.with_lo(cmp::max(span.lo, other.hi))) } else { None } . } . . /// Returns the source span -- this is either the supplied span, or the span for . /// the macro callsite that expanded to it. 40 ( 0.00%) pub fn source_callsite(self) -> Span { . let expn_data = self.ctxt().outer_expn_data(); 16 ( 0.00%) if !expn_data.is_root() { expn_data.call_site.source_callsite() } else { self } 32 ( 0.00%) } . . /// The `Span` for the tokens in the previous macro expansion from which `self` was generated, . /// if any. . pub fn parent_callsite(self) -> Option { . let expn_data = self.ctxt().outer_expn_data(); . if !expn_data.is_root() { Some(expn_data.call_site) } else { None } . } . . /// Walk down the expansion ancestors to find a span that's contained within `outer`. 610 ( 0.00%) pub fn find_ancestor_inside(mut self, outer: Span) -> Option { 305 ( 0.00%) while !outer.contains(self) { . self = self.parent_callsite()?; . } . Some(self) 671 ( 0.00%) } . . /// Edition of the crate from which this span came. 32,070 ( 0.00%) pub fn edition(self) -> edition::Edition { . self.ctxt().edition() 21,380 ( 0.00%) } . . #[inline] . pub fn rust_2015(self) -> bool { 10,396 ( 0.00%) self.edition() == edition::Edition::Edition2015 . } . . #[inline] . pub fn rust_2018(self) -> bool { 232 ( 0.00%) self.edition() >= edition::Edition::Edition2018 . } . . #[inline] . pub fn rust_2021(self) -> bool { 464 ( 0.00%) self.edition() >= edition::Edition::Edition2021 . } . . /// Returns the source callee. . /// . /// Returns `None` if the supplied span has no expansion trace, . /// else returns the `ExpnData` for the macro definition . /// corresponding to the source callsite. . pub fn source_callee(self) -> Option { -- line 703 ---------------------------------------- -- line 707 ---------------------------------------- . } . let expn_data = self.ctxt().outer_expn_data(); . if !expn_data.is_root() { Some(source_callee(expn_data)) } else { None } . } . . /// Checks if a span is "internal" to a macro in which `#[unstable]` . /// items can be used (that is, a macro marked with . /// `#[allow_internal_unstable]`). 110 ( 0.00%) pub fn allows_unstable(self, feature: Symbol) -> bool { 22 ( 0.00%) self.ctxt() . .outer_expn_data() . .allow_internal_unstable . .map_or(false, |features| features.iter().any(|&f| f == feature)) 88 ( 0.00%) } . . /// Checks if this span arises from a compiler desugaring of kind `kind`. 4,186 ( 0.00%) pub fn is_desugaring(self, kind: DesugaringKind) -> bool { 3,588 ( 0.00%) match self.ctxt().outer_expn_data().kind { . ExpnKind::Desugaring(k) => k == kind, . _ => false, . } 2,990 ( 0.00%) } . . /// Returns the compiler desugaring that created this span, or `None` . /// if this span is not from a desugaring. 15 ( 0.00%) pub fn desugaring_kind(self) -> Option { 18 ( 0.00%) match self.ctxt().outer_expn_data().kind { . ExpnKind::Desugaring(k) => Some(k), . _ => None, . } 12 ( 0.00%) } . . /// Checks if a span is "internal" to a macro in which `unsafe` . /// can be used without triggering the `unsafe_code` lint. . // (that is, a macro marked with `#[allow_internal_unsafe]`). . pub fn allows_unsafe(self) -> bool { . self.ctxt().outer_expn_data().allow_internal_unsafe . } . -- line 745 ---------------------------------------- -- line 767 ---------------------------------------- . . /// Returns a `Span` that would enclose both `self` and `end`. . /// . /// ```text . /// ____ ___ . /// self lorem ipsum end . /// ^^^^^^^^^^^^^^^^^^^^ . /// ``` 947,958 ( 0.04%) pub fn to(self, end: Span) -> Span { . let span_data = self.data(); . let end_data = end.data(); . // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480). . // Return the macro span on its own to avoid weird diagnostic output. It is preferable to . // have an incomplete span than a completely nonsensical one. 162,566 ( 0.01%) if span_data.ctxt != end_data.ctxt { 9,784 ( 0.00%) if span_data.ctxt == SyntaxContext::root() { . return end; 9,784 ( 0.00%) } else if end_data.ctxt == SyntaxContext::root() { . return self; . } . // Both spans fall within a macro. . // FIXME(estebank): check if it is the *same* macro. . } . Span::new( . cmp::min(span_data.lo, end_data.lo), . cmp::max(span_data.hi, end_data.hi), . if span_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt }, 534,926 ( 0.03%) if span_data.parent == end_data.parent { span_data.parent } else { None }, . ) 775,602 ( 0.04%) } . . /// Returns a `Span` between the end of `self` to the beginning of `end`. . /// . /// ```text . /// ____ ___ . /// self lorem ipsum end . /// ^^^^^^^^^^^^^ . /// ``` 231 ( 0.00%) pub fn between(self, end: Span) -> Span { . let span = self.data(); . let end = end.data(); . Span::new( . span.hi, . end.lo, . if end.ctxt == SyntaxContext::root() { end.ctxt } else { span.ctxt }, 147 ( 0.00%) if span.parent == end.parent { span.parent } else { None }, . ) 168 ( 0.00%) } . . /// Returns a `Span` from the beginning of `self` until the beginning of `end`. . /// . /// ```text . /// ____ ___ . /// self lorem ipsum end . /// ^^^^^^^^^^^^^^^^^ . /// ``` 132 ( 0.00%) pub fn until(self, end: Span) -> Span { . // Most of this function's body is copied from `to`. . // We can't just do `self.to(end.shrink_to_lo())`, . // because to also does some magic where it uses min/max so . // it can handle overlapping spans. Some advanced mis-use of . // `until` with different ctxts makes this visible. . let span_data = self.data(); . let end_data = end.data(); . // FIXME(jseyfried): `self.ctxt` should always equal `end.ctxt` here (cf. issue #23480). . // Return the macro span on its own to avoid weird diagnostic output. It is preferable to . // have an incomplete span than a completely nonsensical one. 24 ( 0.00%) if span_data.ctxt != end_data.ctxt { . if span_data.ctxt == SyntaxContext::root() { . return end; . } else if end_data.ctxt == SyntaxContext::root() { . return self; . } . // Both spans fall within a macro. . // FIXME(estebank): check if it is the *same* macro. . } . Span::new( . span_data.lo, . end_data.lo, . if end_data.ctxt == SyntaxContext::root() { end_data.ctxt } else { span_data.ctxt }, 84 ( 0.00%) if span_data.parent == end_data.parent { span_data.parent } else { None }, . ) 108 ( 0.00%) } . . pub fn from_inner(self, inner: InnerSpan) -> Span { . let span = self.data(); . Span::new( . span.lo + BytePos::from_usize(inner.start), . span.lo + BytePos::from_usize(inner.end), . span.ctxt, . span.parent, . ) . } . . /// Equivalent of `Span::def_site` from the proc macro API, . /// except that the location is taken from the `self` span. . pub fn with_def_site_ctxt(self, expn_id: ExpnId) -> Span { 1,046 ( 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). 6,288 ( 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)) 3,668 ( 0.00%) } . . #[inline] . pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span { . let span = self.data(); 532,179 ( 0.03%) span.with_ctxt(span.ctxt.apply_mark(expn_id, transparency)) . } . . #[inline] . pub fn remove_mark(&mut self) -> ExpnId { . let mut span = self.data(); . let mark = span.ctxt.remove_mark(); . *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark -- line 897 ---------------------------------------- -- line 901 ---------------------------------------- . pub fn adjust(&mut self, expn_id: ExpnId) -> Option { . let mut span = self.data(); . let mark = span.ctxt.adjust(expn_id); . *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark . } . . #[inline] 264,726 ( 0.01%) pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option { 176,484 ( 0.01%) let mut span = self.data(); 146,968 ( 0.01%) let mark = span.ctxt.normalize_to_macros_2_0_and_adjust(expn_id); 264,726 ( 0.01%) *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark 294,038 ( 0.01%) } . . #[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] 86,952 ( 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()) 76,083 ( 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 { 380 ( 0.00%) MultiSpan { primary_spans: vec![primary_span], span_labels: vec![] } . } . . pub fn from_spans(mut vec: Vec) -> MultiSpan { . vec.sort(); 30 ( 0.00%) 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() 56 ( 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 { 380 ( 0.00%) fn from(span: Span) -> MultiSpan { . MultiSpan::from_span(span) 380 ( 0.00%) } . } . . impl From> for MultiSpan { 30 ( 0.00%) fn from(spans: Vec) -> MultiSpan { 24 ( 0.00%) MultiSpan::from_spans(spans) 30 ( 0.00%) } . } . . /// Identifies an offset of a multi-byte character in a `SourceFile`. 1,408 ( 0.00%) #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)] . pub struct MultiByteChar { . /// The absolute offset of the character in the `SourceMap`. . pub pos: BytePos, . /// The number of bytes, `>= 2`. . pub bytes: u8, . } . . /// Identifies an offset of a non-narrow character in a `SourceFile`. 839 ( 0.00%) #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)] . pub enum NonNarrowChar { . /// Represents a zero-width character. . ZeroWidth(BytePos), . /// Represents a wide (full-width) character. . Wide(BytePos), . /// Represents a tab character, represented visually with a width of 4 characters. . Tab(BytePos), . } . . impl NonNarrowChar { . fn new(pos: BytePos, width: usize) -> Self { 200 ( 0.00%) match width { . 0 => NonNarrowChar::ZeroWidth(pos), . 2 => NonNarrowChar::Wide(pos), . 4 => NonNarrowChar::Tab(pos), . _ => panic!("width {} given for non-narrow character", width), . } . } . . /// Returns the absolute offset of the character in the `SourceMap`. -- line 1188 ---------------------------------------- -- line 1201 ---------------------------------------- . } . } . } . . impl Add for NonNarrowChar { . type Output = Self; . . fn add(self, rhs: BytePos) -> Self { 466 ( 0.00%) match self { . NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos + rhs), . NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos + rhs), . NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos + rhs), . } . } . } . . impl Sub for NonNarrowChar { . type Output = Self; . 134 ( 0.00%) fn sub(self, rhs: BytePos) -> Self { 466 ( 0.00%) match self { . NonNarrowChar::ZeroWidth(pos) => NonNarrowChar::ZeroWidth(pos - rhs), . NonNarrowChar::Wide(pos) => NonNarrowChar::Wide(pos - rhs), . NonNarrowChar::Tab(pos) => NonNarrowChar::Tab(pos - rhs), . } 402 ( 0.00%) } . } . . /// Identifies an offset of a character that was normalized away from `SourceFile`. . #[derive(Copy, Clone, Encodable, Decodable, Eq, PartialEq, Debug)] . pub struct NormalizedPos { . /// The absolute offset of the character in the `SourceMap`. . pub pos: BytePos, . /// The difference between original and normalized string at position. . pub diff: u32, . } . 27 ( 0.00%) #[derive(PartialEq, Eq, Clone, Debug)] . pub enum ExternalSource { . /// No external source has to be loaded, since the `SourceFile` represents a local crate. . Unneeded, . Foreign { . kind: ExternalSourceKind, . /// This SourceFile's byte-offset within the source_map of its original crate. . original_start_pos: BytePos, . /// The end of this SourceFile within the source_map of its original crate. -- line 1246 ---------------------------------------- -- line 1257 ---------------------------------------- . AbsentOk, . /// A failed attempt has been made to load the external source. . AbsentErr, . Unneeded, . } . . impl ExternalSource { . pub fn get_source(&self) -> Option<&Lrc> { 1,529 ( 0.00%) match self { . ExternalSource::Foreign { kind: ExternalSourceKind::Present(ref src), .. } => Some(src), . _ => None, . } . } . } . . #[derive(Debug)] . pub struct OffsetOverflowError; . 666 ( 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. 54 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, Debug)] 1,332 ( 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 { 1 ( 0.00%) 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 => { 30 ( 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)); . } . } . hash . } . . /// Check if the stored hash matches the hash of the string. . pub fn matches(&self, src: &str) -> bool { 1 ( 0.00%) Self::new(self.kind, src) == *self . } . . /// The bytes of the hash. . pub fn hash_bytes(&self) -> &[u8] { . let len = self.hash_len(); . &self.value[..len] . } . . fn hash_len(&self) -> usize { 29 ( 0.00%) match self.kind { . SourceFileHashAlgorithm::Md5 => 16, . SourceFileHashAlgorithm::Sha1 => 20, . SourceFileHashAlgorithm::Sha256 => 32, . } . } . } . . /// A single source in the [`SourceMap`]. 522 ( 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. 9 ( 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. 9 ( 0.00%) pub name_hash: u128, . /// Indicates which crate this `SourceFile` was imported from. 9 ( 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)?; . 36 ( 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 { 18 ( 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); . 18 ( 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))?; 27 ( 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))?; 99 ( 0.00%) s.emit_struct_field("cnum", false, |s| self.cnum.encode(s)) . }) . } . } . . impl Decodable for SourceFile { 2,997 ( 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); 333 ( 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 { 639,524 ( 0.03%) 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)); 666 ( 0.00%) let name_hash: u128 = d.read_struct_field("name_hash", |d| Decodable::decode(d)); . let normalized_pos: Vec = . d.read_struct_field("normalized_pos", |d| Decodable::decode(d)); . let cnum: CrateNum = d.read_struct_field("cnum", |d| Decodable::decode(d)); 3,663 ( 0.00%) SourceFile { 2,664 ( 0.00%) name, . start_pos, . end_pos, . src: None, 1,332 ( 0.00%) src_hash, . // Unused - the metadata decoder will construct . // a new SourceFile, filling in `external_src` properly . external_src: Lock::new(ExternalSource::Unneeded), 1,332 ( 0.00%) lines, 1,332 ( 0.00%) multibyte_chars, 1,332 ( 0.00%) non_narrow_chars, 1,332 ( 0.00%) normalized_pos, . name_hash, . cnum, . } . }) 2,997 ( 0.00%) } . } . . impl fmt::Debug for SourceFile { . fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { . write!(fmt, "SourceFile({:?})", self.name) . } . } . . impl SourceFile { 99 ( 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); 27 ( 0.00%) let normalized_pos = normalize_src(&mut src, start_pos); . . let name_hash = { . let mut hasher: StableHasher = StableHasher::new(); 18 ( 0.00%) name.hash(&mut hasher); . hasher.finish::() . }; 18 ( 0.00%) let end_pos = start_pos.to_usize() + src.len(); 27 ( 0.00%) assert!(end_pos <= u32::MAX as usize); . 108 ( 0.00%) let (lines, multibyte_chars, non_narrow_chars) = 18 ( 0.00%) analyze_source_file::analyze_source_file(&src, start_pos); . 153 ( 0.00%) SourceFile { . name, . src: Some(Lrc::new(src)), 99 ( 0.00%) src_hash, . external_src: Lock::new(ExternalSource::Unneeded), . start_pos, . end_pos: Pos::from_usize(end_pos), 36 ( 0.00%) lines, 36 ( 0.00%) multibyte_chars, 36 ( 0.00%) non_narrow_chars, 36 ( 0.00%) normalized_pos, . name_hash, . cnum: LOCAL_CRATE, . } 81 ( 0.00%) } . . /// Returns the `BytePos` of the beginning of the current line. . pub fn line_begin_pos(&self, pos: BytePos) -> BytePos { . let line_index = self.lookup_line(pos).unwrap(); . self.lines[line_index] . } . . /// Add externally loaded source. . /// If the hash of the input doesn't match or no input is supplied via None, . /// it is interpreted as an error and the corresponding enum variant is set. . /// The return value signifies whether some kind of source is present. 651 ( 0.00%) pub fn add_external_src(&self, get_src: F) -> bool . where . F: FnOnce() -> Option, . { 249 ( 0.00%) if matches!( 186 ( 0.00%) *self.external_src.borrow(), . ExternalSource::Foreign { kind: ExternalSourceKind::AbsentOk, .. } . ) { 1 ( 0.00%) let src = get_src(); . let mut external_src = self.external_src.borrow_mut(); . // Check that no-one else have provided the source while we were getting it 3 ( 0.00%) if let ExternalSource::Foreign { . kind: src_kind @ ExternalSourceKind::AbsentOk, .. . } = &mut *external_src . { 5 ( 0.00%) if let Some(mut src) = src { . // The src_hash needs to be computed on the pre-normalized src. 1 ( 0.00%) if self.src_hash.matches(&src) { 3 ( 0.00%) normalize_src(&mut src, BytePos::from_usize(0)); 8 ( 0.00%) *src_kind = ExternalSourceKind::Present(Lrc::new(src)); . return true; . } . } else { . *src_kind = ExternalSourceKind::AbsentErr; . } . . false . } else { . self.src.is_some() || external_src.get_source().is_some() . } . } else { 92 ( 0.00%) self.src.is_some() || self.external_src.borrow().get_source().is_some() . } 837 ( 0.00%) } . . /// Gets a line from the list of pre-computed line-beginnings. . /// The line number here is 0-based. . pub fn get_line(&self, line_number: usize) -> Option> { . fn get_until_newline(src: &str, begin: usize) -> &str { . // We can't use `lines.get(line_number+1)` because we might . // be parsing when we call this function and thus the current . // line is the last one we have line info for. -- line 1610 ---------------------------------------- -- line 1627 ---------------------------------------- . Some(Cow::Owned(String::from(get_until_newline(src, begin)))) . } else { . None . } . } . . pub fn is_real_file(&self) -> bool { . self.name.is_real() 342 ( 0.00%) } . . pub fn is_imported(&self) -> bool { . self.src.is_none() 74,987 ( 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 { 41,298 ( 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 { 146,413 ( 0.01%) if self.is_empty() { . return self.start_pos..self.end_pos; . } . 91,388 ( 0.00%) assert!(line_index < self.lines.len()); 136,875 ( 0.01%) if line_index == (self.lines.len() - 1) { 13,732 ( 0.00%) self.lines[line_index]..self.end_pos . } else { 82,092 ( 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`. 10 ( 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; . 30 ( 0.00%) for mbc in self.multibyte_chars.iter() { . debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos); 516 ( 0.00%) if mbc.pos < bpos { . // Every character is at least one byte, so we only . // count the actual extra bytes. 1,536 ( 0.00%) total_extra_bytes += mbc.bytes as u32 - 1; . // We should never see a byte position in the middle of a . // character. 1,280 ( 0.00%) assert!(bpos.to_u32() >= mbc.pos.to_u32() + mbc.bytes as u32); . } else { . break; . } . } . 60 ( 0.00%) assert!(self.start_pos.to_u32() + total_extra_bytes <= bpos.to_u32()); 50 ( 0.00%) CharPos(bpos.to_usize() - self.start_pos.to_usize() - total_extra_bytes as usize) 20 ( 0.00%) } . . /// Looks up the file's (1-based) line number and (0-based `CharPos`) column offset, for a . /// given `BytePos`. 35 ( 0.00%) pub fn lookup_file_pos(&self, pos: BytePos) -> (usize, CharPos) { 10 ( 0.00%) let chpos = self.bytepos_to_file_charpos(pos); 4 ( 0.00%) match self.lookup_line(pos) { . Some(a) => { . let line = a + 1; // Line numbers start at 1 5 ( 0.00%) let linebpos = self.lines[a]; 10 ( 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); 5 ( 0.00%) assert!(chpos >= linechpos); . (line, col) . } . None => (0, chpos), . } 40 ( 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`. 40 ( 0.00%) pub fn lookup_file_pos_with_col_display(&self, pos: BytePos) -> (usize, CharPos, usize) { 15 ( 0.00%) let (line, col_or_chpos) = self.lookup_file_pos(pos); 10 ( 0.00%) if line > 0 { . let col = col_or_chpos; 5 ( 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); 9 ( 0.00%) let special_chars = end_width_idx - start_width_idx; . let non_narrow: usize = self.non_narrow_chars[start_width_idx..end_width_idx] . .iter() . .map(|x| x.width()) . .sum(); 25 ( 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) . } 35 ( 0.00%) } . } . . /// Normalizes the source code and records the normalizations. 100 ( 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 90 ( 0.00%) } . . /// Removes UTF-8 BOM, if any. . fn remove_bom(src: &mut String, normalized_pos: &mut Vec) { 10 ( 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) { 10 ( 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])* 179,503 ( 0.01%) $vis struct $ident($inner_vis $inner_ty); . . impl Pos for $ident { . #[inline(always)] . fn from_usize(n: usize) -> $ident { 5,668 ( 0.00%) $ident(n as $inner_ty) . } . . #[inline(always)] . fn to_usize(&self) -> usize { 216,985 ( 0.01%) 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,361,508 ( 0.06%) $ident(self.0 + rhs.0) . } . } . . impl Sub for $ident { . type Output = $ident; . . #[inline(always)] . fn sub(self, rhs: $ident) -> $ident { 2,183,347 ( 0.10%) $ident(self.0 - rhs.0) . } . } . )* . }; . } . . impl_pos! { . /// A byte offset. -- line 1931 ---------------------------------------- -- line 1939 ---------------------------------------- . /// Because of multibyte UTF-8 characters, a byte offset . /// is not equivalent to a character offset. The [`SourceMap`] will convert [`BytePos`] . /// values to `CharPos` values as necessary. . #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] . pub struct CharPos(pub usize); . } . . impl Encodable for BytePos { 265 ( 0.00%) fn encode(&self, s: &mut S) -> Result<(), S::Error> { . s.emit_u32(self.0) 318 ( 0.00%) } . } . . impl Decodable for BytePos { . fn decode(d: &mut D) -> BytePos { 36,910 ( 0.00%) 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. 726,292 ( 0.03%) 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; . 108,626 ( 0.01%) if !ctx.hash_spans() { . return; . } . 617,666 ( 0.03%) let span = self.data_untracked(); 296,658 ( 0.01%) span.ctxt.hash_stable(ctx, hasher); 311,268 ( 0.01%) span.parent.hash_stable(ctx, hasher); . 207,594 ( 0.01%) if span.is_dummy() { . Hash::hash(&TAG_INVALID_SPAN, hasher); . return; . } . 207,348 ( 0.01%) 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. 414,696 ( 0.02%) let (file, line_lo, col_lo, line_hi, col_hi) = match ctx.span_data_to_lines_and_cols(&span) . { 207,348 ( 0.01%) 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. . 103,674 ( 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; 103,674 ( 0.00%) let len = (span.hi - span.lo).0; . Hash::hash(&col_line, hasher); . Hash::hash(&len, hasher); 830,048 ( 0.04%) } . } 2,602,831 ( 0.12%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_build/src/thir/cx/expr.rs -------------------------------------------------------------------------------- Ir -- line 18 ---------------------------------------- . use rustc_middle::ty::{self, AdtKind, Ty, UpvarSubsts, UserType}; . use rustc_span::def_id::DefId; . use rustc_span::Span; . use rustc_target::abi::VariantIdx; . . impl<'tcx> Cx<'tcx> { . crate fn mirror_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) -> ExprId { . // `mirror_expr` is recursing very deep. Make sure the stack doesn't overflow. 41,001 ( 0.00%) ensure_sufficient_stack(|| self.mirror_expr_inner(expr)) . } . 146 ( 0.00%) crate fn mirror_exprs(&mut self, exprs: &'tcx [hir::Expr<'tcx>]) -> Box<[ExprId]> { 42,276 ( 0.00%) exprs.iter().map(|expr| self.mirror_expr_inner(expr)).collect() 292 ( 0.00%) } . 219,159 ( 0.01%) pub(super) fn mirror_expr_inner(&mut self, hir_expr: &'tcx hir::Expr<'tcx>) -> ExprId { 170,457 ( 0.01%) let temp_lifetime = self.region_scope_tree.temporary_scope(hir_expr.hir_id.local_id); . let expr_scope = . region::Scope { id: hir_expr.hir_id.local_id, data: region::ScopeData::Node }; . . debug!("Expr::make_mirror(): id={}, span={:?}", hir_expr.hir_id, hir_expr.span); . 97,404 ( 0.00%) let mut expr = self.make_mirror_unadjusted(hir_expr); . 146,106 ( 0.01%) let adjustment_span = match self.adjustment_span { 1,300 ( 0.00%) Some((hir_id, span)) if hir_id == hir_expr.hir_id => Some(span), . _ => None, . }; . . // Now apply adjustments, if any. 97,404 ( 0.00%) for adjustment in self.typeck_results.expr_adjustments(hir_expr) { . debug!("make_mirror: expr={:?} applying adjustment={:?}", expr, adjustment); 1,452 ( 0.00%) let span = expr.span; 5,103 ( 0.00%) expr = 13,122 ( 0.00%) self.apply_adjustment(hir_expr, expr, adjustment, adjustment_span.unwrap_or(span)); . } . . // Next, wrap this up in the expr's scope. 316,563 ( 0.01%) expr = Expr { . temp_lifetime, 23,988 ( 0.00%) ty: expr.ty, 24,351 ( 0.00%) span: hir_expr.span, . kind: ExprKind::Scope { . region_scope: expr_scope, 438,318 ( 0.02%) value: self.thir.exprs.push(expr), 48,702 ( 0.00%) lint_level: LintLevel::Explicit(hir_expr.hir_id), . }, . }; . . // Finally, create a destruction scope, if any. 73,053 ( 0.00%) if let Some(region_scope) = 48,702 ( 0.00%) self.region_scope_tree.opt_destruction_scope(hir_expr.hir_id.local_id) . { 7,584 ( 0.00%) expr = Expr { . temp_lifetime, . ty: expr.ty, 632 ( 0.00%) span: hir_expr.span, . kind: ExprKind::Scope { . region_scope, 8,848 ( 0.00%) value: self.thir.exprs.push(expr), . lint_level: LintLevel::Inherited, . }, . }; . } . . // OK, all done! 535,722 ( 0.03%) self.thir.exprs.push(expr) 219,159 ( 0.01%) } . . fn apply_adjustment( . &mut self, . hir_expr: &'tcx hir::Expr<'tcx>, . mut expr: Expr<'tcx>, . adjustment: &Adjustment<'tcx>, . mut span: Span, . ) -> Expr<'tcx> { 1,458 ( 0.00%) let Expr { temp_lifetime, .. } = expr; . . // Adjust the span from the block, to the last expression of the . // block. This is a better span when returning a mutable reference . // with too short a lifetime. The error message will use the span . // from the assignment to the return place, which should only point . // at the returned value, not the entire function body. . // . // fn return_short_lived<'a>(x: &'a mut i32) -> &'static mut i32 { . // x . // // ^ error message points at this expression. . // } . let mut adjust_span = |expr: &mut Expr<'tcx>| { 732 ( 0.00%) if let ExprKind::Block { body } = &expr.kind { . if let Some(last_expr) = body.expr { . span = self.thir[last_expr].span; . expr.span = span; . } . } . }; . 6,567 ( 0.00%) let kind = match adjustment.kind { . Adjust::Pointer(PointerCast::Unsize) => { . adjust_span(&mut expr); 102 ( 0.00%) ExprKind::Pointer { cast: PointerCast::Unsize, source: self.thir.exprs.push(expr) } . } . Adjust::Pointer(cast) => ExprKind::Pointer { cast, source: self.thir.exprs.push(expr) }, . Adjust::NeverToAny => ExprKind::NeverToAny { source: self.thir.exprs.push(expr) }, . Adjust::Deref(None) => { . adjust_span(&mut expr); 6,120 ( 0.00%) ExprKind::Deref { arg: self.thir.exprs.push(expr) } . } . Adjust::Deref(Some(deref)) => { . // We don't need to do call adjust_span here since . // deref coercions always start with a built-in deref. . let call = deref.method_call(self.tcx(), expr.ty); . . expr = Expr { . temp_lifetime, -- line 132 ---------------------------------------- -- line 139 ---------------------------------------- . arg: self.thir.exprs.push(expr), . }, . }; . . let expr = Box::new([self.thir.exprs.push(expr)]); . . self.overloaded_place(hir_expr, adjustment.target, Some(call), expr, deref.span) . } 1,452 ( 0.00%) Adjust::Borrow(AutoBorrow::Ref(_, m)) => ExprKind::Borrow { . borrow_kind: m.to_borrow_kind(), 5,082 ( 0.00%) arg: self.thir.exprs.push(expr), . }, . Adjust::Borrow(AutoBorrow::RawPtr(mutability)) => { . ExprKind::AddressOf { mutability, arg: self.thir.exprs.push(expr) } . } . }; . 13,851 ( 0.00%) Expr { temp_lifetime, ty: adjustment.target, span, kind } . } . 243,510 ( 0.01%) fn make_mirror_unadjusted(&mut self, expr: &'tcx hir::Expr<'tcx>) -> Expr<'tcx> { 97,404 ( 0.00%) let expr_ty = self.typeck_results().expr_ty(expr); 24,351 ( 0.00%) let expr_span = expr.span; 121,755 ( 0.01%) let temp_lifetime = self.region_scope_tree.temporary_scope(expr.hir_id.local_id); . 146,250 ( 0.01%) let kind = match expr.kind { . // Here comes the interesting stuff: 348 ( 0.00%) hir::ExprKind::MethodCall(segment, ref args, fn_span) => { . // Rewrite a.b(c) into UFCS form like Trait::b(a, c) 812 ( 0.00%) let expr = self.method_callee(expr, segment.ident.span, None); . // When we apply adjustments to the receiver, use the span of . // the overall method call for better diagnostics. args[0] . // is guaranteed to exist, since a method call always has a receiver. 464 ( 0.00%) let old_adjustment_span = self.adjustment_span.replace((args[0].hir_id, expr_span)); . tracing::info!("Using method span: {:?}", expr.span); 116 ( 0.00%) let args = self.mirror_exprs(args); 232 ( 0.00%) self.adjustment_span = old_adjustment_span; 812 ( 0.00%) ExprKind::Call { 116 ( 0.00%) ty: expr.ty, 1,624 ( 0.00%) fun: self.thir.exprs.push(expr), . args, . from_hir_call: true, . fn_span, . } . } . . hir::ExprKind::Call(ref fun, ref args) => { 1,196 ( 0.00%) if self.typeck_results().is_method_call(expr) { . // The callee is something implementing Fn, FnMut, or FnOnce. . // Find the actual method implementation being called and . // build the appropriate UFCS call expression with the . // callee-object as expr parameter. . . // rewrite f(u, v) into FnOnce::call_once(f, (u, v)) . . let method = self.method_callee(expr, fun.span, None); -- line 194 ---------------------------------------- -- line 206 ---------------------------------------- . ty: method.ty, . fun: self.thir.exprs.push(method), . args: Box::new([self.mirror_expr(fun), tupled_args]), . from_hir_call: true, . fn_span: expr.span, . } . } else { . let adt_data = 1,495 ( 0.00%) if let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = fun.kind { . // Tuple-like ADTs are represented as ExprKind::Call. We convert them here. 2,516 ( 0.00%) expr_ty.ty_adt_def().and_then(|adt_def| match path.res { 452 ( 0.00%) Res::Def(DefKind::Ctor(_, CtorKind::Fn), ctor_id) => { 904 ( 0.00%) Some((adt_def, adt_def.variant_index_with_ctor_id(ctor_id))) . } . Res::SelfCtor(..) => Some((adt_def, VariantIdx::new(0))), . _ => None, . }) . } else { . None . }; 482 ( 0.00%) if let Some((adt_def, index)) = adt_data { 1,130 ( 0.00%) let substs = self.typeck_results().node_substs(fun.hir_id); 678 ( 0.00%) let user_provided_types = self.typeck_results().user_provided_types(); . let user_ty = 1,130 ( 0.00%) user_provided_types.get(fun.hir_id).copied().map(|mut u_ty| { . if let UserType::TypeOf(ref mut did, _) = &mut u_ty.value { . *did = adt_def.did; . } . u_ty . }); . debug!("make_mirror_unadjusted: (call) user_ty={:?}", user_ty); . 226 ( 0.00%) let field_refs = args . .iter() . .enumerate() . .map(|(idx, e)| FieldExpr { . name: Field::new(idx), . expr: self.mirror_expr(e), . }) . .collect(); . ExprKind::Adt(Box::new(Adt { -- line 246 ---------------------------------------- -- line 247 ---------------------------------------- . adt_def, . substs, . variant_index: index, . fields: field_refs, . user_ty, . base: None, . })) . } else { 292 ( 0.00%) ExprKind::Call { 380 ( 0.00%) ty: self.typeck_results().node_type(fun.hir_id), 73 ( 0.00%) fun: self.mirror_expr(fun), 292 ( 0.00%) args: self.mirror_exprs(args), . from_hir_call: true, 73 ( 0.00%) fn_span: expr.span, . } . } . } . } . . hir::ExprKind::AddrOf(hir::BorrowKind::Ref, mutbl, ref arg) => { 135 ( 0.00%) ExprKind::Borrow { borrow_kind: mutbl.to_borrow_kind(), arg: self.mirror_expr(arg) } . } . . hir::ExprKind::AddrOf(hir::BorrowKind::Raw, mutability, ref arg) => { . ExprKind::AddressOf { mutability, arg: self.mirror_expr(arg) } . } . 1,736 ( 0.00%) hir::ExprKind::Block(ref blk, _) => ExprKind::Block { body: self.mirror_block(blk) }, . . hir::ExprKind::Assign(ref lhs, ref rhs, _) => { . ExprKind::Assign { lhs: self.mirror_expr(lhs), rhs: self.mirror_expr(rhs) } . } . . hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => { . if self.typeck_results().is_method_call(expr) { . let lhs = self.mirror_expr(lhs); -- line 282 ---------------------------------------- -- line 286 ---------------------------------------- . ExprKind::AssignOp { . op: bin_op(op.node), . lhs: self.mirror_expr(lhs), . rhs: self.mirror_expr(rhs), . } . } . } . 9,462 ( 0.00%) hir::ExprKind::Lit(ref lit) => ExprKind::Literal { 37,848 ( 0.00%) literal: self.const_eval_literal(&lit.node, expr_ty, lit.span, false), . user_ty: None, . const_id: None, . }, . 6 ( 0.00%) hir::ExprKind::Binary(op, ref lhs, ref rhs) => { 24 ( 0.00%) if self.typeck_results().is_method_call(expr) { . let lhs = self.mirror_expr(lhs); . let rhs = self.mirror_expr(rhs); . self.overloaded_operator(expr, Box::new([lhs, rhs])) . } else { . // FIXME overflow 18 ( 0.00%) match op.node { 12 ( 0.00%) hir::BinOpKind::And => ExprKind::LogicalOp { . op: LogicalOp::And, 3 ( 0.00%) lhs: self.mirror_expr(lhs), 3 ( 0.00%) rhs: self.mirror_expr(rhs), . }, . hir::BinOpKind::Or => ExprKind::LogicalOp { . op: LogicalOp::Or, . lhs: self.mirror_expr(lhs), . rhs: self.mirror_expr(rhs), . }, . _ => { 12 ( 0.00%) let op = bin_op(op.node); 15 ( 0.00%) ExprKind::Binary { . op, 3 ( 0.00%) lhs: self.mirror_expr(lhs), 3 ( 0.00%) rhs: self.mirror_expr(rhs), . } . } . } . } . } . . hir::ExprKind::Index(ref lhs, ref index) => { . if self.typeck_results().is_method_call(expr) { -- line 331 ---------------------------------------- -- line 333 ---------------------------------------- . let index = self.mirror_expr(index); . self.overloaded_place(expr, expr_ty, None, Box::new([lhs, index]), expr.span) . } else { . ExprKind::Index { lhs: self.mirror_expr(lhs), index: self.mirror_expr(index) } . } . } . . hir::ExprKind::Unary(hir::UnOp::Deref, ref arg) => { 150 ( 0.00%) if self.typeck_results().is_method_call(expr) { . let arg = self.mirror_expr(arg); . self.overloaded_place(expr, expr_ty, None, Box::new([arg]), expr.span) . } else { 90 ( 0.00%) ExprKind::Deref { arg: self.mirror_expr(arg) } . } . } . . hir::ExprKind::Unary(hir::UnOp::Not, ref arg) => { . if self.typeck_results().is_method_call(expr) { . let arg = self.mirror_expr(arg); . self.overloaded_operator(expr, Box::new([arg])) . } else { -- line 353 ---------------------------------------- -- line 365 ---------------------------------------- . user_ty: None, . const_id: None, . } . } else { . ExprKind::Unary { op: UnOp::Neg, arg: self.mirror_expr(arg) } . } . } . 9,110 ( 0.00%) hir::ExprKind::Struct(ref qpath, ref fields, ref base) => match expr_ty.kind() { 9,110 ( 0.00%) ty::Adt(adt, substs) => match adt.adt_kind() { . AdtKind::Struct | AdtKind::Union => { 13,665 ( 0.00%) let user_provided_types = self.typeck_results().user_provided_types(); 18,220 ( 0.00%) let user_ty = user_provided_types.get(expr.hir_id).copied(); . debug!("make_mirror_unadjusted: (struct/union) user_ty={:?}", user_ty); 18,220 ( 0.00%) ExprKind::Adt(Box::new(Adt { 9,110 ( 0.00%) adt_def: adt, . variant_index: VariantIdx::new(0), 9,110 ( 0.00%) substs, . user_ty, 9,110 ( 0.00%) fields: self.field_refs(fields), 18,220 ( 0.00%) base: base.as_ref().map(|base| FruInfo { . base: self.mirror_expr(base), . field_types: self.typeck_results().fru_field_types()[expr.hir_id] . .iter() . .copied() . .collect(), . }), . })) . } -- line 393 ---------------------------------------- -- line 454 ---------------------------------------- . }) . .collect(), . None => Vec::new(), . }; . . ExprKind::Closure { closure_id: def_id, substs, upvars, movability, fake_reads } . } . 5,133 ( 0.00%) hir::ExprKind::Path(ref qpath) => { 20,532 ( 0.00%) let res = self.typeck_results().qpath_res(qpath, expr.hir_id); 20,532 ( 0.00%) self.convert_path_expr(expr, res) . } . . hir::ExprKind::InlineAsm(ref asm) => ExprKind::InlineAsm { . template: asm.template, . operands: asm . .operands . .iter() . .map(|(op, _op_sp)| { -- line 472 ---------------------------------------- -- line 600 ---------------------------------------- . label: region::Scope { id: loop_id.local_id, data: region::ScopeData::Node }, . }, . Err(err) => bug!("invalid loop id for continue: {}", err), . }, . hir::ExprKind::Let(let_expr) => ExprKind::Let { . expr: self.mirror_expr(let_expr.init), . pat: self.pattern_from_hir(let_expr.pat), . }, 33 ( 0.00%) hir::ExprKind::If(cond, then, else_opt) => ExprKind::If { . if_then_scope: region::Scope { 3 ( 0.00%) id: then.hir_id.local_id, . data: region::ScopeData::IfThen, . }, . cond: self.mirror_expr(cond), . then: self.mirror_expr(then), . else_opt: else_opt.map(|el| self.mirror_expr(el)), . }, 105 ( 0.00%) hir::ExprKind::Match(ref discr, ref arms, _) => ExprKind::Match { 21 ( 0.00%) scrutinee: self.mirror_expr(discr), 1,368 ( 0.00%) arms: arms.iter().map(|a| self.convert_arm(a)).collect(), . }, . hir::ExprKind::Loop(ref body, ..) => { . let block_ty = self.typeck_results().node_type(body.hir_id); . let temp_lifetime = self.region_scope_tree.temporary_scope(body.hir_id.local_id); . let block = self.mirror_block(body); . let body = self.thir.exprs.push(Expr { . ty: block_ty, . temp_lifetime, -- line 627 ---------------------------------------- -- line 757 ---------------------------------------- . let mirrored = self.mirror_expr(source); . if source.is_syntactic_place_expr() { . ExprKind::PlaceTypeAscription { source: mirrored, user_ty } . } else { . ExprKind::ValueTypeAscription { source: mirrored, user_ty } . } . } . hir::ExprKind::DropTemps(ref source) => { 12 ( 0.00%) ExprKind::Use { source: self.mirror_expr(source) } . } . hir::ExprKind::Box(ref value) => ExprKind::Box { value: self.mirror_expr(value) }, . hir::ExprKind::Array(ref fields) => { 30 ( 0.00%) ExprKind::Array { fields: self.mirror_exprs(fields) } . } 22,830 ( 0.00%) hir::ExprKind::Tup(ref fields) => ExprKind::Tuple { fields: self.mirror_exprs(fields) }, . . hir::ExprKind::Yield(ref v, _) => ExprKind::Yield { value: self.mirror_expr(v) }, . hir::ExprKind::Err => unreachable!(), . }; . 827,934 ( 0.04%) Expr { temp_lifetime, ty: expr_ty, span: expr.span, kind } 194,808 ( 0.01%) } . 1,755 ( 0.00%) fn user_substs_applied_to_res( . &mut self, . hir_id: hir::HirId, . res: Res, . ) -> Option> { . debug!("user_substs_applied_to_res: res={:?}", res); 1,170 ( 0.00%) let user_provided_type = match res { . // A reference to something callable -- e.g., a fn, method, or . // a tuple-struct or tuple-variant. This has the type of a . // `Fn` but with the user-given substitutions. . Res::Def(DefKind::Fn, _) . | Res::Def(DefKind::AssocFn, _) . | Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) . | Res::Def(DefKind::Const, _) . | Res::Def(DefKind::AssocConst, _) => { 1,365 ( 0.00%) self.typeck_results().user_provided_types().get(hir_id).copied() . } . . // A unit struct/variant which is used as a value (e.g., . // `None`). This has the type of the enum/struct that defines . // this variant -- but with the substitutions given by the . // user. . Res::Def(DefKind::Ctor(_, CtorKind::Const), _) => { . self.user_substs_applied_to_ty_of_hir_id(hir_id) -- line 803 ---------------------------------------- -- line 805 ---------------------------------------- . . // `Self` is used in expression as a tuple struct constructor or a unit struct constructor . Res::SelfCtor(_) => self.user_substs_applied_to_ty_of_hir_id(hir_id), . . _ => bug!("user_substs_applied_to_res: unexpected res {:?} at {:?}", res, hir_id), . }; . debug!("user_substs_applied_to_res: user_provided_type={:?}", user_provided_type); . user_provided_type 1,170 ( 0.00%) } . 1,508 ( 0.00%) fn method_callee( . &mut self, . expr: &hir::Expr<'_>, . span: Span, . overloaded_callee: Option<(DefId, SubstsRef<'tcx>)>, . ) -> Expr<'tcx> { 696 ( 0.00%) let temp_lifetime = self.region_scope_tree.temporary_scope(expr.hir_id.local_id); 928 ( 0.00%) let (def_id, substs, user_ty) = match overloaded_callee { . Some((def_id, substs)) => (def_id, substs, None), . None => { . let (kind, def_id) = 1,044 ( 0.00%) self.typeck_results().type_dependent_def(expr.hir_id).unwrap_or_else(|| { . span_bug!(expr.span, "no type-dependent def for method callee") . }); 1,740 ( 0.00%) let user_ty = self.user_substs_applied_to_res(expr.hir_id, Res::Def(kind, def_id)); . debug!("method_callee: user_ty={:?}", user_ty); 1,740 ( 0.00%) (def_id, self.typeck_results().node_substs(expr.hir_id), user_ty) . } . }; . let ty = self.tcx().mk_fn_def(def_id, substs); 1,508 ( 0.00%) Expr { . temp_lifetime, . ty, . span, . kind: ExprKind::Literal { . literal: ty::Const::zero_sized(self.tcx(), ty), 696 ( 0.00%) user_ty, . const_id: None, . }, . } 928 ( 0.00%) } . 4,041 ( 0.00%) fn convert_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) -> ArmId { 3,592 ( 0.00%) let arm = Arm { 1,347 ( 0.00%) pattern: self.pattern_from_hir(&arm.pat), 220 ( 0.00%) guard: arm.guard.as_ref().map(|g| match g { 110 ( 0.00%) hir::Guard::If(ref e) => Guard::If(self.mirror_expr(e)), . hir::Guard::IfLet(ref pat, ref e) => { . Guard::IfLet(self.pattern_from_hir(pat), self.mirror_expr(e)) . } . }), 449 ( 0.00%) body: self.mirror_expr(arm.body), 898 ( 0.00%) lint_level: LintLevel::Explicit(arm.hir_id), . scope: region::Scope { id: arm.hir_id.local_id, data: region::ScopeData::Node }, 449 ( 0.00%) span: arm.span, . }; 6,735 ( 0.00%) self.thir.arms.push(arm) 4,041 ( 0.00%) } . . fn convert_path_expr(&mut self, expr: &'tcx hir::Expr<'tcx>, res: Res) -> ExprKind<'tcx> { 35,931 ( 0.00%) let substs = self.typeck_results().node_substs(expr.hir_id); 60,091 ( 0.00%) match res { . // A regular function, constructor function or a constant. . Res::Def(DefKind::Fn, _) . | Res::Def(DefKind::AssocFn, _) . | Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) . | Res::SelfCtor(..) => { 730 ( 0.00%) let user_ty = self.user_substs_applied_to_res(expr.hir_id, res); . debug!("convert_path_expr: user_ty={:?}", user_ty); 73 ( 0.00%) ExprKind::Literal { . literal: ty::Const::zero_sized( 146 ( 0.00%) self.tcx, 219 ( 0.00%) self.typeck_results().node_type(expr.hir_id), . ), 584 ( 0.00%) user_ty, . const_id: None, . } . } . . Res::Def(DefKind::ConstParam, def_id) => { . let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id.expect_local()); . let item_id = self.tcx.hir().get_parent_node(hir_id); . let item_def_id = self.tcx.hir().local_def_id(item_id); -- line 887 ---------------------------------------- -- line 895 ---------------------------------------- . ty: self.typeck_results().node_type(expr.hir_id), . }), . user_ty: None, . const_id: Some(def_id), . } . } . . Res::Def(DefKind::Const, def_id) | Res::Def(DefKind::AssocConst, def_id) => { 54 ( 0.00%) let user_ty = self.user_substs_applied_to_res(expr.hir_id, res); . debug!("convert_path_expr: (const) user_ty={:?}", user_ty); 30 ( 0.00%) ExprKind::Literal { 72 ( 0.00%) literal: self.tcx.mk_const(ty::Const { . val: ty::ConstKind::Unevaluated(ty::Unevaluated::new( . ty::WithOptConstParam::unknown(def_id), . substs, . )), 18 ( 0.00%) ty: self.typeck_results().node_type(expr.hir_id), . }), 48 ( 0.00%) user_ty, . const_id: Some(def_id), . } . } . 24,160 ( 0.00%) Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id) => { 24,160 ( 0.00%) let user_provided_types = self.typeck_results.user_provided_types(); 19,328 ( 0.00%) let user_provided_type = user_provided_types.get(expr.hir_id).copied(); . debug!("convert_path_expr: user_provided_type={:?}", user_provided_type); 19,328 ( 0.00%) let ty = self.typeck_results().node_type(expr.hir_id); 9,664 ( 0.00%) match ty.kind() { . // A unit struct/variant which is used as a value. . // We return a completely different ExprKind here to account for this special case. . ty::Adt(adt_def, substs) => ExprKind::Adt(Box::new(Adt { 4,832 ( 0.00%) adt_def, 24,160 ( 0.00%) variant_index: adt_def.variant_index_with_ctor_id(def_id), 4,832 ( 0.00%) substs, . user_ty: user_provided_type, . fields: Box::new([]), . base: None, . })), . _ => bug!("unexpected ty: {:?}", ty), . } . } . -- line 937 ---------------------------------------- -- line 953 ---------------------------------------- . def_id: id, . } . }; . ExprKind::Deref { . arg: self.thir.exprs.push(Expr { ty, temp_lifetime, span: expr.span, kind }), . } . } . 1,776 ( 0.00%) Res::Local(var_hir_id) => self.convert_var(var_hir_id), . . _ => span_bug!(expr.span, "res `{:?}` not yet implemented", res), . } . } . 2,220 ( 0.00%) fn convert_var(&mut self, var_hir_id: hir::HirId) -> ExprKind<'tcx> { . // We want upvars here not captures. . // Captures will be handled in MIR. . let is_upvar = self . .tcx . .upvars_mentioned(self.body_owner) . .map_or(false, |upvars| upvars.contains_key(&var_hir_id)); . . debug!( . "convert_var({:?}): is_upvar={}, body_owner={:?}", . var_hir_id, is_upvar, self.body_owner . ); . . if is_upvar { . ExprKind::UpvarRef { closure_def_id: self.body_owner, var_hir_id } . } else { 666 ( 0.00%) ExprKind::VarRef { id: var_hir_id } . } 1,776 ( 0.00%) } . . fn overloaded_operator( . &mut self, . expr: &'tcx hir::Expr<'tcx>, . args: Box<[ExprId]>, . ) -> ExprKind<'tcx> { . let fun = self.method_callee(expr, expr.span, None); . let fun = self.thir.exprs.push(fun); -- line 993 ---------------------------------------- -- line 1121 ---------------------------------------- . } . } . . /// Converts a list of named fields (i.e., for struct-like struct/enum ADTs) into FieldExpr. . fn field_refs(&mut self, fields: &'tcx [hir::ExprField<'tcx>]) -> Box<[FieldExpr]> { . fields . .iter() . .map(|field| FieldExpr { 27,333 ( 0.00%) name: Field::new(self.tcx.field_index(field.hir_id, self.typeck_results)), . expr: self.mirror_expr(field.expr), . }) . .collect() . } . } . . trait ToBorrowKind { . fn to_borrow_kind(&self) -> BorrowKind; . } . . impl ToBorrowKind for AutoBorrowMutability { . fn to_borrow_kind(&self) -> BorrowKind { . use rustc_middle::ty::adjustment::AllowTwoPhase; 2,541 ( 0.00%) match *self { . AutoBorrowMutability::Mut { allow_two_phase_borrow } => BorrowKind::Mut { . allow_two_phase_borrow: match allow_two_phase_borrow { . AllowTwoPhase::Yes => true, . AllowTwoPhase::No => false, . }, . }, . AutoBorrowMutability::Not => BorrowKind::Shared, . } -- line 1151 ---------------------------------------- -- line 1156 ---------------------------------------- . fn to_borrow_kind(&self) -> BorrowKind { . match *self { . hir::Mutability::Mut => BorrowKind::Mut { allow_two_phase_borrow: false }, . hir::Mutability::Not => BorrowKind::Shared, . } . } . } . 6 ( 0.00%) fn bin_op(op: hir::BinOpKind) -> BinOp { 27 ( 0.00%) match op { . hir::BinOpKind::Add => BinOp::Add, . hir::BinOpKind::Sub => BinOp::Sub, . hir::BinOpKind::Mul => BinOp::Mul, . hir::BinOpKind::Div => BinOp::Div, . hir::BinOpKind::Rem => BinOp::Rem, . hir::BinOpKind::BitXor => BinOp::BitXor, . hir::BinOpKind::BitAnd => BinOp::BitAnd, . hir::BinOpKind::BitOr => BinOp::BitOr, -- line 1173 ---------------------------------------- -- line 1176 ---------------------------------------- . hir::BinOpKind::Eq => BinOp::Eq, . hir::BinOpKind::Lt => BinOp::Lt, . hir::BinOpKind::Le => BinOp::Le, . hir::BinOpKind::Ne => BinOp::Ne, . hir::BinOpKind::Ge => BinOp::Ge, . hir::BinOpKind::Gt => BinOp::Gt, . _ => bug!("no equivalent for ast binop {:?}", op), . } 6 ( 0.00%) } 365,088 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/smallvec-1.7.0/src/lib.rs -------------------------------------------------------------------------------- Ir -- line 294 ---------------------------------------- . #[allow(deprecated)] . impl From for CollectionAllocErr { . fn from(_: LayoutErr) -> Self { . CollectionAllocErr::CapacityOverflow . } . } . . fn infallible(result: Result) -> T { 289,140 ( 0.01%) match result { . Ok(x) => x, . Err(CollectionAllocErr::CapacityOverflow) => panic!("capacity overflow"), . Err(CollectionAllocErr::AllocErr { layout }) => alloc::alloc::handle_alloc_error(layout), . } . } . . /// FIXME: use `Layout::array` when we require a Rust version where it’s stable . /// https://github.com/rust-lang/rust/issues/55724 -- line 310 ---------------------------------------- -- line 422 ---------------------------------------- . #[cfg(feature = "union")] . impl SmallVecData { . #[inline] . unsafe fn inline(&self) -> *const A::Item { . self.inline.as_ptr() as *const A::Item . } . #[inline] . unsafe fn inline_mut(&mut self) -> *mut A::Item { 11,984 ( 0.00%) self.inline.as_mut_ptr() as *mut A::Item . } . #[inline] . fn from_inline(inline: MaybeUninit) -> SmallVecData { . SmallVecData { . inline: core::mem::ManuallyDrop::new(inline), . } . } . #[inline] . unsafe fn into_inline(self) -> MaybeUninit { . core::mem::ManuallyDrop::into_inner(self.inline) . } . #[inline] . unsafe fn heap(&self) -> (*mut A::Item, usize) { 21,529 ( 0.00%) self.heap . } . #[inline] . unsafe fn heap_mut(&mut self) -> &mut (*mut A::Item, usize) { . &mut self.heap . } . #[inline] . fn from_heap(ptr: *mut A::Item, len: usize) -> SmallVecData { . SmallVecData { heap: (ptr, len) } -- line 452 ---------------------------------------- -- line 557 ---------------------------------------- . #[inline] . pub fn new() -> SmallVec { . // Try to detect invalid custom implementations of `Array`. Hopefully, . // this check should be optimized away entirely for valid ones. . assert!( . mem::size_of::() == A::size() * mem::size_of::() . && mem::align_of::() >= mem::align_of::() . ); 331,924 ( 0.02%) SmallVec { . capacity: 0, . data: SmallVecData::from_inline(MaybeUninit::uninit()), . } . } . . /// Construct an empty vector with enough capacity pre-allocated to store at least `n` . /// elements. . /// -- line 573 ---------------------------------------- -- line 635 ---------------------------------------- . /// let small_vec: SmallVec<_> = SmallVec::from_buf(buf); . /// . /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]); . /// ``` . #[inline] . pub fn from_buf(buf: A) -> SmallVec { . SmallVec { . capacity: A::size(), 1,239 ( 0.00%) data: SmallVecData::from_inline(MaybeUninit::new(buf)), . } . } . . /// Constructs a new `SmallVec` on the stack from an `A` without . /// copying elements. Also sets the length, which must be less or . /// equal to the size of `buf`. . /// . /// ```rust -- line 651 ---------------------------------------- -- line 653 ---------------------------------------- . /// . /// let buf = [1, 2, 3, 4, 5, 0, 0, 0]; . /// let small_vec: SmallVec<_> = SmallVec::from_buf_and_len(buf, 5); . /// . /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]); . /// ``` . #[inline] . pub fn from_buf_and_len(buf: A, len: usize) -> SmallVec { 12 ( 0.00%) assert!(len <= A::size()); 36 ( 0.00%) unsafe { SmallVec::from_buf_and_len_unchecked(MaybeUninit::new(buf), len) } . } . . /// Constructs a new `SmallVec` on the stack from an `A` without . /// copying elements. Also sets the length. The user is responsible . /// for ensuring that `len <= A::size()`. . /// . /// ```rust . /// use smallvec::SmallVec; -- line 670 ---------------------------------------- -- line 674 ---------------------------------------- . /// let small_vec: SmallVec<_> = unsafe { . /// SmallVec::from_buf_and_len_unchecked(MaybeUninit::new(buf), 5) . /// }; . /// . /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]); . /// ``` . #[inline] . pub unsafe fn from_buf_and_len_unchecked(buf: MaybeUninit, len: usize) -> SmallVec { 6 ( 0.00%) SmallVec { . capacity: len, . data: SmallVecData::from_inline(buf), . } . } . . /// Sets the length of a vector. . /// . /// This will explicitly set the size of the vector, without actually . /// modifying its buffers, so it is up to the caller to ensure that the . /// vector is actually the specified size. . pub unsafe fn set_len(&mut self, new_len: usize) { . let (_, len_ptr, _) = self.triple_mut(); 56,281 ( 0.00%) *len_ptr = new_len; . } . . /// The maximum number of elements this vector can hold inline . #[inline] . fn inline_capacity() -> usize { . if mem::size_of::() > 0 { . A::size() . } else { -- line 703 ---------------------------------------- -- line 725 ---------------------------------------- . #[inline] . pub fn len(&self) -> usize { . self.triple().1 . } . . /// Returns `true` if the vector is empty . #[inline] . pub fn is_empty(&self) -> bool { 147,465 ( 0.01%) self.len() == 0 . } . . /// The number of items the vector can hold without reallocating . #[inline] . pub fn capacity(&self) -> usize { . self.triple().2 . } . . /// Returns a tuple with (data ptr, len, capacity) . /// Useful to get all SmallVec properties with a single check of the current storage variant. . #[inline] . fn triple(&self) -> (*const A::Item, usize, usize) { . unsafe { 1,915,090 ( 0.09%) if self.spilled() { . let (ptr, len) = self.data.heap(); . (ptr, len, self.capacity) . } else { . (self.data.inline(), self.capacity, Self::inline_capacity()) . } . } . } . . /// Returns a tuple with (data ptr, len ptr, capacity) . #[inline] . fn triple_mut(&mut self) -> (*mut A::Item, &mut usize, usize) { . unsafe { 4,497,473 ( 0.21%) if self.spilled() { 31,855 ( 0.00%) let &mut (ptr, ref mut len_ptr) = self.data.heap_mut(); . (ptr, len_ptr, self.capacity) . } else { . ( . self.data.inline_mut(), . &mut self.capacity, . Self::inline_capacity(), . ) . } . } . } . . /// Returns `true` if the data has spilled into a separate heap-allocated buffer. . #[inline] . pub fn spilled(&self) -> bool { 4,094,196 ( 0.19%) self.capacity > Self::inline_capacity() . } . . /// Creates a draining iterator that removes the specified range in the vector . /// and yields the removed items. . /// . /// Note 1: The element range is removed even if the iterator is only . /// partially consumed or not consumed at all. . /// -- line 784 ---------------------------------------- -- line 821 ---------------------------------------- . iter: range_slice.iter(), . vec: NonNull::from(self), . } . } . } . . /// Append an item to the vector. . #[inline] 14,920 ( 0.00%) pub fn push(&mut self, value: A::Item) { . unsafe { . let (mut ptr, mut len, cap) = self.triple_mut(); 607,064 ( 0.03%) if *len == cap { 213 ( 0.00%) self.reserve(1); 10,315 ( 0.00%) let &mut (heap_ptr, ref mut heap_len) = self.data.heap_mut(); . ptr = heap_ptr; . len = heap_len; . } 19,488 ( 0.00%) ptr::write(ptr.add(*len), value); 987,351 ( 0.05%) *len += 1; . } 11,936 ( 0.00%) } . . /// Remove an item from the end of the vector and return it, or None if empty. . #[inline] . pub fn pop(&mut self) -> Option { . unsafe { . let (ptr, len_ptr, _) = self.triple_mut(); 325,120 ( 0.02%) if *len_ptr == 0 { . return None; . } 94,251 ( 0.00%) let last_index = *len_ptr - 1; 108,889 ( 0.01%) *len_ptr = last_index; 41,279 ( 0.00%) Some(ptr::read(ptr.add(last_index))) . } . } . . /// Moves all the elements of `other` into `self`, leaving `other` empty. . /// . /// # Example . /// . /// ``` -- line 861 ---------------------------------------- -- line 879 ---------------------------------------- . /// or if the capacity computation overflows `usize`. . pub fn grow(&mut self, new_cap: usize) { . infallible(self.try_grow(new_cap)) . } . . /// Re-allocate to set the capacity to `max(new_cap, inline_size())`. . /// . /// Panics if `new_cap` is less than the vector's length 632 ( 0.00%) pub fn try_grow(&mut self, new_cap: usize) -> Result<(), CollectionAllocErr> { . unsafe { 56 ( 0.00%) let (ptr, &mut len, cap) = self.triple_mut(); . let unspilled = !self.spilled(); 21,882 ( 0.00%) assert!(new_cap >= len); 21,882 ( 0.00%) if new_cap <= self.inline_size() { . if unspilled { . return Ok(()); . } . self.data = SmallVecData::from_inline(MaybeUninit::uninit()); . ptr::copy_nonoverlapping(ptr, self.data.inline_mut(), len); . self.capacity = len; . deallocate(ptr, cap); 21,882 ( 0.00%) } else if new_cap != cap { 21,731 ( 0.00%) let layout = layout_array::(new_cap)?; . debug_assert!(layout.size() > 0); . let new_alloc; 10,941 ( 0.00%) if unspilled { . new_alloc = NonNull::new(alloc::alloc::alloc(layout)) . .ok_or(CollectionAllocErr::AllocErr { layout })? . .cast() . .as_ptr(); . ptr::copy_nonoverlapping(ptr, new_alloc, len); . } else { . // This should never fail since the same succeeded . // when previously allocating `ptr`. 1,634 ( 0.00%) let old_layout = layout_array::(cap)?; . . let new_ptr = alloc::alloc::realloc(ptr as *mut u8, old_layout, layout.size()); . new_alloc = NonNull::new(new_ptr) . .ok_or(CollectionAllocErr::AllocErr { layout })? . .cast() . .as_ptr(); . } 21,882 ( 0.00%) self.data = SmallVecData::from_heap(new_alloc, len); 32,563 ( 0.00%) self.capacity = new_cap; . } . Ok(()) . } 688 ( 0.00%) } . . /// Reserve capacity for `additional` more elements to be inserted. . /// . /// May reserve more space to avoid frequent reallocations. . /// . /// Panics if the capacity computation overflows `usize`. . #[inline] 52,037 ( 0.00%) pub fn reserve(&mut self, additional: usize) { 332,081 ( 0.02%) infallible(self.try_reserve(additional)) 59,216 ( 0.00%) } . . /// Reserve capacity for `additional` more elements to be inserted. . /// . /// May reserve more space to avoid frequent reallocations. 1,188,114 ( 0.06%) pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> { . // prefer triple_mut() even if triple() would work . // so that the optimizer removes duplicated calls to it . // from callers like insert() 1,050 ( 0.00%) let (_, &mut len, cap) = self.triple_mut(); 883,101 ( 0.04%) if cap - len >= additional { . return Ok(()); . } . let new_cap = len . .checked_add(additional) . .and_then(usize::checked_next_power_of_two) . .ok_or(CollectionAllocErr::CapacityOverflow)?; 172 ( 0.00%) self.try_grow(new_cap) 1,300,829 ( 0.06%) } . . /// Reserve the minimum capacity for `additional` more elements to be inserted. . /// . /// Panics if the new capacity overflows `usize`. . pub fn reserve_exact(&mut self, additional: usize) { . infallible(self.try_reserve_exact(additional)) . } . . /// Reserve the minimum capacity for `additional` more elements to be inserted. . pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), CollectionAllocErr> { . let (_, &mut len, cap) = self.triple_mut(); 22,773 ( 0.00%) if cap - len >= additional { . return Ok(()); . } . let new_cap = len . .checked_add(additional) . .ok_or(CollectionAllocErr::CapacityOverflow)?; . self.try_grow(new_cap) . } . -- line 974 ---------------------------------------- -- line 999 ---------------------------------------- . /// If `len` is greater than or equal to the vector's current length, this has no . /// effect. . /// . /// This does not re-allocate. If you want the vector's capacity to shrink, call . /// `shrink_to_fit` after truncating. . pub fn truncate(&mut self, len: usize) { . unsafe { . let (ptr, len_ptr, _) = self.triple_mut(); 6,726 ( 0.00%) while len < *len_ptr { . let last_index = *len_ptr - 1; . *len_ptr = last_index; . ptr::drop_in_place(ptr.add(last_index)); . } . } . } . . /// Extracts a slice containing the entire vector. -- line 1015 ---------------------------------------- -- line 1044 ---------------------------------------- . pub fn clear(&mut self) { . self.truncate(0); . } . . /// Remove and return the element at position `index`, shifting all elements after it to the . /// left. . /// . /// Panics if `index` is out of bounds. 440 ( 0.00%) pub fn remove(&mut self, index: usize) -> A::Item { . unsafe { . let (mut ptr, len_ptr, _) = self.triple_mut(); 498 ( 0.00%) let len = *len_ptr; 2,484 ( 0.00%) assert!(index < len); 41,218 ( 0.00%) *len_ptr = len - 1; . ptr = ptr.add(index); . let item = ptr::read(ptr); 1,656 ( 0.00%) ptr::copy(ptr.add(1), ptr, len - index - 1); . item . } 550 ( 0.00%) } . . /// Insert an element at position `index`, shifting all elements after it to the right. . /// . /// Panics if `index` is out of bounds. 57,803 ( 0.00%) pub fn insert(&mut self, index: usize, element: A::Item) { . self.reserve(1); . . unsafe { . let (mut ptr, len_ptr, _) = self.triple_mut(); 5,315 ( 0.00%) let len = *len_ptr; 10,570 ( 0.00%) assert!(index <= len); 21,140 ( 0.00%) *len_ptr = len + 1; . ptr = ptr.add(index); 10,570 ( 0.00%) ptr::copy(ptr, ptr.add(1), len - index); . ptr::write(ptr, element); . } 36,786 ( 0.00%) } . . /// Insert multiple elements at position `index`, shifting all following elements toward the . /// back. . pub fn insert_many>(&mut self, index: usize, iterable: I) { . let mut iter = iterable.into_iter(); . if index == self.len() { . return self.extend(iter); . } -- line 1088 ---------------------------------------- -- line 1201 ---------------------------------------- . } . } . . /// Retains only the elements specified by the predicate. . /// . /// In other words, remove all elements `e` such that `f(&e)` returns `false`. . /// This method operates in place and preserves the order of the retained . /// elements. 13,149 ( 0.00%) pub fn retain bool>(&mut self, mut f: F) { . let mut del = 0; . let len = self.len(); . for i in 0..len { 1,772 ( 0.00%) if !f(&mut self[i]) { . del += 1; 452 ( 0.00%) } else if del > 0 { . self.swap(i - del, i); . } . } 2,922 ( 0.00%) self.truncate(len - del); 11,688 ( 0.00%) } . . /// Removes consecutive duplicate elements. . pub fn dedup(&mut self) . where . A::Item: PartialEq, . { . self.dedup_by(|a, b| a == b); . } -- line 1228 ---------------------------------------- -- line 1418 ---------------------------------------- . capacity: len, . data: SmallVecData::from_inline(unsafe { . let mut data: MaybeUninit = MaybeUninit::uninit(); . ptr::copy_nonoverlapping( . slice.as_ptr(), . data.as_mut_ptr() as *mut A::Item, . len, . ); 11 ( 0.00%) data . }), . } . } else { . let mut b = slice.to_vec(); . let (ptr, cap) = (b.as_mut_ptr(), b.capacity()); . mem::forget(b); . SmallVec { . capacity: cap, -- line 1434 ---------------------------------------- -- line 1436 ---------------------------------------- . } . } . } . . /// Copy elements from a slice into the vector at position `index`, shifting any following . /// elements toward the back. . /// . /// For slices of `Copy` types, this is more efficient than `insert`. 124,182 ( 0.01%) pub fn insert_from_slice(&mut self, index: usize, slice: &[A::Item]) { . self.reserve(slice.len()); . . let len = self.len(); 32,541 ( 0.00%) assert!(index <= len); . . unsafe { . let slice_ptr = slice.as_ptr(); . let ptr = self.as_mut_ptr().add(index); . ptr::copy(ptr, ptr.add(slice.len()), len - index); . ptr::copy_nonoverlapping(slice_ptr, ptr, slice.len()); 21,694 ( 0.00%) self.set_len(len + slice.len()); . } 86,776 ( 0.00%) } . . /// Copy elements from a slice and append them to the vector. . /// . /// For slices of `Copy` types, this is more efficient than `extend`. . #[inline] . pub fn extend_from_slice(&mut self, slice: &[A::Item]) { . let len = self.len(); 24,049 ( 0.00%) self.insert_from_slice(len, slice); . } . } . . impl SmallVec . where . A::Item: Clone, . { . /// Resizes the vector so that its length is equal to `len`. -- line 1473 ---------------------------------------- -- line 1522 ---------------------------------------- . } . } . } . . impl ops::DerefMut for SmallVec { . #[inline] . fn deref_mut(&mut self) -> &mut [A::Item] { . unsafe { 48,482 ( 0.00%) let (ptr, &mut len, _) = self.triple_mut(); . slice::from_raw_parts_mut(ptr, len) . } . } . } . . impl AsRef<[A::Item]> for SmallVec { . #[inline] . fn as_ref(&self) -> &[A::Item] { -- line 1538 ---------------------------------------- -- line 1716 ---------------------------------------- . SmallVec::extend_from_slice(self, other) . } . } . . impl FromIterator for SmallVec { . #[inline] . fn from_iter>(iterable: I) -> SmallVec { . let mut v = SmallVec::new(); 249,236 ( 0.01%) v.extend(iterable); . v . } . } . . impl Extend for SmallVec { 1,444,138 ( 0.07%) fn extend>(&mut self, iterable: I) { 121,454 ( 0.01%) let mut iter = iterable.into_iter(); . let (lower_size_bound, _) = iter.size_hint(); 8,654 ( 0.00%) self.reserve(lower_size_bound); . . unsafe { . let (ptr, len_ptr, cap) = self.triple_mut(); . let mut len = SetLenOnDrop::new(len_ptr); 624,827 ( 0.03%) while len.get() < cap { 148,530 ( 0.01%) if let Some(out) = iter.next() { . ptr::write(ptr.add(len.get()), out); . len.increment_len(1); . } else { . return; . } . } . } . 69,785 ( 0.00%) for elem in iter { 1,760 ( 0.00%) self.push(elem); . } 1,236,340 ( 0.06%) } . } . . impl fmt::Debug for SmallVec . where . A::Item: fmt::Debug, . { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . f.debug_list().entries(self.iter()).finish() -- line 1759 ---------------------------------------- -- line 1764 ---------------------------------------- . #[inline] . fn default() -> SmallVec { . SmallVec::new() . } . } . . #[cfg(feature = "may_dangle")] . unsafe impl<#[may_dangle] A: Array> Drop for SmallVec { 1,068,227 ( 0.05%) fn drop(&mut self) { . unsafe { 1,014,778 ( 0.05%) if self.spilled() { . let (ptr, len) = self.data.heap(); . Vec::from_raw_parts(ptr, len, self.capacity); . } else { . ptr::drop_in_place(&mut self[..]); . } . } 1,089,651 ( 0.05%) } . } . . #[cfg(not(feature = "may_dangle"))] . impl Drop for SmallVec { . fn drop(&mut self) { . unsafe { . if self.spilled() { . let (ptr, len) = self.data.heap(); -- line 1789 ---------------------------------------- -- line 1888 ---------------------------------------- . A::Item: Clone, . { . fn clone(&self) -> IntoIter { . SmallVec::from(self.as_slice()).into_iter() . } . } . . impl Drop for IntoIter { 135 ( 0.00%) fn drop(&mut self) { 8,044 ( 0.00%) for _ in self {} 120 ( 0.00%) } . } . . impl Iterator for IntoIter { . type Item = A::Item; . . #[inline] . fn next(&mut self) -> Option { 278,113 ( 0.01%) if self.current == self.end { 1,371 ( 0.00%) None . } else { . unsafe { . let current = self.current; 117,270 ( 0.01%) self.current += 1; 539 ( 0.00%) Some(ptr::read(self.data.as_ptr().add(current))) . } . } . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 1,856 ( 0.00%) let size = self.end - self.current; . (size, Some(size)) . } . } . . impl DoubleEndedIterator for IntoIter { . #[inline] . fn next_back(&mut self) -> Option { . if self.current == self.end { -- line 1927 ---------------------------------------- -- line 1955 ---------------------------------------- . impl IntoIterator for SmallVec { . type IntoIter = IntoIter; . type Item = A::Item; . fn into_iter(mut self) -> Self::IntoIter { . unsafe { . // Set SmallVec len to zero as `IntoIter` drop handles dropping of the elements . let len = self.len(); . self.set_len(0); 32,293 ( 0.00%) IntoIter { 246,002 ( 0.01%) data: self, . current: 0, . end: len, . } . } . } . } . . impl<'a, A: Array> IntoIterator for &'a SmallVec { -- line 1972 ---------------------------------------- -- line 2000 ---------------------------------------- . len: &'a mut usize, . local_len: usize, . } . . impl<'a> SetLenOnDrop<'a> { . #[inline] . fn new(len: &'a mut usize) -> Self { . SetLenOnDrop { 156,239 ( 0.01%) local_len: *len, . len, . } . } . . #[inline] . fn get(&self) -> usize { . self.local_len . } . . #[inline] . fn increment_len(&mut self, increment: usize) { 62,608 ( 0.00%) self.local_len += increment; . } . } . . impl<'a> Drop for SetLenOnDrop<'a> { . #[inline] . fn drop(&mut self) { 176,497 ( 0.01%) *self.len = self.local_len; . } . } . . #[cfg(feature = "const_new")] . impl SmallVec<[T; N]> { . /// Construct an empty vector. . /// . /// This is a `const` version of [`SmallVec::new`] that is enabled by the feature `const_new`, with the limitation that it only works for arrays. -- line 2035 ---------------------------------------- 2,578,880 ( 0.12%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/place.rs -------------------------------------------------------------------------------- Ir -- line 14 ---------------------------------------- . use rustc_target::abi::{HasDataLayout, Size, VariantIdx, Variants}; . . use super::{ . alloc_range, mir_assign_valid_types, AllocId, AllocRef, AllocRefMut, CheckInAllocMsg, . ConstAlloc, ImmTy, Immediate, InterpCx, InterpResult, LocalValue, Machine, MemoryKind, OpTy, . Operand, Pointer, PointerArithmetic, Provenance, Scalar, ScalarMaybeUninit, . }; . 82,433 ( 0.00%) #[derive(Copy, Clone, Hash, PartialEq, Eq, HashStable, Debug)] . /// Information required for the sound usage of a `MemPlace`. . pub enum MemPlaceMeta { . /// The unsized payload (e.g. length for slices or vtable pointer for trait objects). . Meta(Scalar), . /// `Sized` types or unsized `extern type` . None, . /// The address of this place may not be taken. This protects the `MemPlace` from coming from . /// a ZST Operand without a backing allocation and being converted to an integer address. This -- line 30 ---------------------------------------- -- line 33 ---------------------------------------- . Poison, . } . . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . rustc_data_structures::static_assert_size!(MemPlaceMeta, 24); . . impl MemPlaceMeta { . pub fn unwrap_meta(self) -> Scalar { 60 ( 0.00%) match self { 18 ( 0.00%) Self::Meta(s) => s, . Self::None | Self::Poison => { . bug!("expected wide pointer extra data (e.g. slice length or trait object vtable)") . } . } . } . fn has_meta(self) -> bool { 100,985 ( 0.00%) match self { . Self::Meta(_) => true, . Self::None | Self::Poison => false, . } . } . } . . #[derive(Copy, Clone, Hash, PartialEq, Eq, HashStable, Debug)] . pub struct MemPlace { -- line 57 ---------------------------------------- -- line 113 ---------------------------------------- . fn deref(&self) -> &MemPlace { . &self.mplace . } . } . . impl<'tcx, Tag: Provenance> From> for PlaceTy<'tcx, Tag> { . #[inline(always)] . fn from(mplace: MPlaceTy<'tcx, Tag>) -> Self { 576 ( 0.00%) PlaceTy { place: Place::Ptr(mplace.mplace), layout: mplace.layout } . } . } . . impl MemPlace { . #[inline(always)] . pub fn from_ptr(ptr: Pointer>, align: Align) -> Self { . MemPlace { ptr, align, meta: MemPlaceMeta::None } . } -- line 129 ---------------------------------------- -- line 132 ---------------------------------------- . pub fn map_provenance(self, f: impl FnOnce(Option) -> Option) -> Self { . MemPlace { ptr: self.ptr.map_provenance(f), ..self } . } . . /// Turn a mplace into a (thin or wide) pointer, as a reference, pointing to the same space. . /// This is the inverse of `ref_to_mplace`. . #[inline(always)] . pub fn to_ref(self, cx: &impl HasDataLayout) -> Immediate { 180 ( 0.00%) match self.meta { 126 ( 0.00%) MemPlaceMeta::None => Immediate::from(Scalar::from_maybe_pointer(self.ptr, cx)), . MemPlaceMeta::Meta(meta) => { . Immediate::ScalarPair(Scalar::from_maybe_pointer(self.ptr, cx).into(), meta.into()) . } . MemPlaceMeta::Poison => bug!( . "MPlaceTy::dangling may never be used to produce a \ . place that will have the address of its pointee taken" . ), . } -- line 149 ---------------------------------------- -- line 177 ---------------------------------------- . #[inline] . pub fn offset( . &self, . offset: Size, . meta: MemPlaceMeta, . layout: TyAndLayout<'tcx>, . cx: &impl HasDataLayout, . ) -> InterpResult<'tcx, Self> { 558,699 ( 0.03%) Ok(MPlaceTy { mplace: self.mplace.offset(offset, meta, cx)?, layout }) . } . . #[inline] . pub fn from_aligned_ptr(ptr: Pointer>, layout: TyAndLayout<'tcx>) -> Self { 32 ( 0.00%) MPlaceTy { mplace: MemPlace::from_ptr(ptr, layout.align.abi), layout } . } . . #[inline] 21 ( 0.00%) pub(super) fn len(&self, cx: &impl HasDataLayout) -> InterpResult<'tcx, u64> { 93 ( 0.00%) if self.layout.is_unsized() { . // We need to consult `meta` metadata 69 ( 0.00%) match self.layout.ty.kind() { 18 ( 0.00%) ty::Slice(..) | ty::Str => self.mplace.meta.unwrap_meta().to_machine_usize(cx), . _ => bug!("len not supported on unsized type {:?}", self.layout.ty), . } . } else { . // Go through the layout. There are lots of types that support a length, . // e.g., SIMD types. (But not all repr(simd) types even have FieldsShape::Array!) 24 ( 0.00%) match self.layout.fields { 24 ( 0.00%) FieldsShape::Array { count, .. } => Ok(count), . _ => bug!("len not supported on sized type {:?}", self.layout.ty), . } . } 42 ( 0.00%) } . . #[inline] . pub(super) fn vtable(&self) -> Scalar { . match self.layout.ty.kind() { . ty::Dynamic(..) => self.mplace.meta.unwrap_meta(), . _ => bug!("vtable not supported on type {:?}", self.layout.ty), . } . } -- line 217 ---------------------------------------- -- line 218 ---------------------------------------- . } . . // These are defined here because they produce a place. . impl<'tcx, Tag: Provenance> OpTy<'tcx, Tag> { . #[inline(always)] . /// Note: do not call `as_ref` on the resulting place. This function should only be used to . /// read from the resulting mplace, not to get its address back. . pub fn try_as_mplace(&self) -> Result, ImmTy<'tcx, Tag>> { 284,284 ( 0.01%) match **self { 1,495,589 ( 0.07%) Operand::Indirect(mplace) => Ok(MPlaceTy { mplace, layout: self.layout }), . Operand::Immediate(_) if self.layout.is_zst() => Ok(MPlaceTy::dangling(self.layout)), 64,071 ( 0.00%) Operand::Immediate(imm) => Err(ImmTy::from_immediate(imm, self.layout)), . } . } . . #[inline(always)] . /// Note: do not call `as_ref` on the resulting place. This function should only be used to . /// read from the resulting mplace, not to get its address back. . pub fn assert_mem_place(&self) -> MPlaceTy<'tcx, Tag> { . self.try_as_mplace().unwrap() -- line 237 ---------------------------------------- -- line 263 ---------------------------------------- . M: Machine<'mir, 'tcx, PointerTag = Tag>, . { . /// Take a value, which represents a (thin or wide) reference, and make it a place. . /// Alignment is just based on the type. This is the inverse of `MemPlace::to_ref()`. . /// . /// Only call this if you are sure the place is "valid" (aligned and inbounds), or do not . /// want to ever use the place for memory access! . /// Generally prefer `deref_operand`. 420 ( 0.00%) pub fn ref_to_mplace( . &self, . val: &ImmTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> { . let pointee_type = 126 ( 0.00%) val.layout.ty.builtin_deref(true).expect("`ref_to_mplace` called on non-ptr type").ty; 126 ( 0.00%) let layout = self.layout_of(pointee_type)?; 210 ( 0.00%) let (ptr, meta) = match **val { 48 ( 0.00%) Immediate::Scalar(ptr) => (ptr, MemPlaceMeta::None), 126 ( 0.00%) Immediate::ScalarPair(ptr, meta) => (ptr, MemPlaceMeta::Meta(meta.check_init()?)), . }; . . let mplace = MemPlace { . ptr: self.scalar_to_ptr(ptr.check_init()?), . // We could use the run-time alignment here. For now, we do not, because . // the point of tracking the alignment here is to make sure that the *static* . // alignment information emitted with the loads is correct. The run-time . // alignment can only be more restrictive. 42 ( 0.00%) align: layout.align.abi, . meta, . }; 714 ( 0.00%) Ok(MPlaceTy { mplace, layout }) 378 ( 0.00%) } . . /// Take an operand, representing a pointer, and dereference it to a place -- that . /// will always be a MemPlace. Lives in `place.rs` because it creates a place. 132 ( 0.00%) pub fn deref_operand( . &self, . src: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> { 36 ( 0.00%) let val = self.read_immediate(src)?; . trace!("deref to {} on {:?}", val.layout.ty, *val); 24 ( 0.00%) let mplace = self.ref_to_mplace(&val)?; 60 ( 0.00%) self.check_mplace_access(mplace, CheckInAllocMsg::DerefTest)?; 132 ( 0.00%) Ok(mplace) 108 ( 0.00%) } . . #[inline] . pub(super) fn get_alloc( . &self, . place: &MPlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, Option>> { . assert!(!place.layout.is_unsized()); 64,251 ( 0.00%) assert!(!place.meta.has_meta()); 64,251 ( 0.00%) let size = place.layout.size; 578,259 ( 0.03%) self.memory.get(place.ptr, size, place.align) . } . . #[inline] . pub(super) fn get_alloc_mut( . &mut self, . place: &MPlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, Option>> { 22,901 ( 0.00%) assert!(!place.layout.is_unsized()); 22,901 ( 0.00%) assert!(!place.meta.has_meta()); 22,901 ( 0.00%) let size = place.layout.size; 137,406 ( 0.01%) self.memory.get_mut(place.ptr, size, place.align) . } . . /// Check if this mplace is dereferenceable and sufficiently aligned. . fn check_mplace_access( . &self, . mplace: MPlaceTy<'tcx, M::PointerTag>, . msg: CheckInAllocMsg, . ) -> InterpResult<'tcx> { . let (size, align) = self . .size_and_align_of_mplace(&mplace)? 12 ( 0.00%) .unwrap_or((mplace.layout.size, mplace.layout.align.abi)); 12 ( 0.00%) assert!(mplace.mplace.align <= align, "dynamic alignment less strict than static one?"); 12 ( 0.00%) let align = M::enforce_alignment(&self.memory.extra).then_some(align); 36 ( 0.00%) self.memory.check_ptr_access_align(mplace.ptr, size, align.unwrap_or(Align::ONE), msg)?; . Ok(()) . } . . /// Offset a pointer to project to a field of a struct/union. Unlike `place_field`, this is . /// always possible without allocating, so it can take `&self`. Also return the field's layout. . /// This supports both struct and array fields. . /// . /// This also works for arrays, but then the `usize` index type is restricting. . /// For indexing into arrays, use `mplace_index`. . #[inline(always)] . pub fn mplace_field( . &self, . base: &MPlaceTy<'tcx, M::PointerTag>, . field: usize, . ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> { 393,408 ( 0.02%) let offset = base.layout.fields.offset(field); 269,815 ( 0.01%) let field_layout = base.layout.field(self, field); . . // Offset may need adjustment for unsized fields. 557,953 ( 0.03%) let (meta, offset) = if field_layout.is_unsized() { . // Re-use parent metadata to determine dynamic field layout. . // With custom DSTS, this *will* execute user-defined code, but the same . // happens at run-time so that's okay. . match self.size_and_align_of(&base.meta, &field_layout)? { . Some((_, align)) => (base.meta, offset.align_to(align)), . None => { . // For unsized types with an extern type tail we perform no adjustments. . // NOTE: keep this in sync with `PlaceRef::project_field` in the codegen backend. -- line 369 ---------------------------------------- -- line 374 ---------------------------------------- . } else { . // base.meta could be present; we might be accessing a sized field of an unsized . // struct. . (MemPlaceMeta::None, offset) . }; . . // We do not look at `base.layout.align` nor `field_layout.align`, unlike . // codegen -- mostly to see if we can get away with that 91,336 ( 0.00%) base.offset(offset, meta, field_layout, self) . } . . /// Index into an array. . #[inline(always)] . pub fn mplace_index( . &self, . base: &MPlaceTy<'tcx, M::PointerTag>, . index: u64, -- line 390 ---------------------------------------- -- line 409 ---------------------------------------- . "`mplace_index` called on non-array type {:?}", . base.layout.ty . ), . } . } . . // Iterates over all fields of an array. Much more efficient than doing the . // same by repeatedly calling `mplace_array`. 210 ( 0.00%) pub(super) fn mplace_array_fields<'a>( . &self, . base: &'a MPlaceTy<'tcx, Tag>, . ) -> InterpResult<'tcx, impl Iterator>> + 'a> . { 84 ( 0.00%) let len = base.len(self)?; // also asserts that we have a type where this makes sense 63 ( 0.00%) let stride = match base.layout.fields { 21 ( 0.00%) FieldsShape::Array { stride, .. } => stride, . _ => span_bug!(self.cur_span(), "mplace_array_fields: expected an array layout"), . }; 42 ( 0.00%) let layout = base.layout.field(self, 0); 21 ( 0.00%) let dl = &self.tcx.data_layout; . // `Size` multiplication 83,109 ( 0.00%) Ok((0..len).map(move |i| base.offset(stride * i, MemPlaceMeta::None, layout, dl))) 189 ( 0.00%) } . . fn mplace_subslice( . &self, . base: &MPlaceTy<'tcx, M::PointerTag>, . from: u64, . to: u64, . from_end: bool, . ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> { -- line 439 ---------------------------------------- -- line 476 ---------------------------------------- . } . . pub(crate) fn mplace_downcast( . &self, . base: &MPlaceTy<'tcx, M::PointerTag>, . variant: VariantIdx, . ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> { . // Downcasts only change the layout 13,833 ( 0.00%) assert!(!base.meta.has_meta()); 41,508 ( 0.00%) Ok(MPlaceTy { layout: base.layout.for_variant(self, variant), ..*base }) . } . . /// Project into an mplace . pub(super) fn mplace_projection( . &self, . base: &MPlaceTy<'tcx, M::PointerTag>, . proj_elem: mir::PlaceElem<'tcx>, . ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> { -- line 493 ---------------------------------------- -- line 542 ---------------------------------------- . assert_eq!(layout.size, base.layout.size); . Ok((MPlaceTy { layout, ..*base }, len)) . } . . /// Gets the place of a field inside the place, and also the field's type. . /// Just a convenience function, but used quite a bit. . /// This is the only projection that might have a side-effect: We cannot project . /// into the field of a local `ScalarPair`, we have to first allocate it. 274,430 ( 0.01%) pub fn place_field( . &mut self, . base: &PlaceTy<'tcx, M::PointerTag>, . field: usize, . ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> { . // FIXME: We could try to be smarter and avoid allocation for fields that span the . // entire place. 27,443 ( 0.00%) let mplace = self.force_allocation(base)?; 329,316 ( 0.02%) Ok(self.mplace_field(&mplace, field)?.into()) 219,544 ( 0.01%) } . . pub fn place_index( . &mut self, . base: &PlaceTy<'tcx, M::PointerTag>, . index: u64, . ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> { . let mplace = self.force_allocation(base)?; . Ok(self.mplace_index(&mplace, index)?.into()) -- line 567 ---------------------------------------- -- line 568 ---------------------------------------- . } . . pub fn place_downcast( . &self, . base: &PlaceTy<'tcx, M::PointerTag>, . variant: VariantIdx, . ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> { . // Downcast just changes the layout 24 ( 0.00%) Ok(match base.place { . Place::Ptr(mplace) => { . self.mplace_downcast(&MPlaceTy { mplace, layout: base.layout }, variant)?.into() . } . Place::Local { .. } => { . let layout = base.layout.for_variant(self, variant); 3 ( 0.00%) PlaceTy { layout, ..*base } . } . }) . } . . /// Projects into a place. . pub fn place_projection( . &mut self, . base: &PlaceTy<'tcx, M::PointerTag>, . &proj_elem: &mir::ProjectionElem>, . ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> { . use rustc_middle::mir::ProjectionElem::*; 273,555 ( 0.01%) Ok(match proj_elem { 91,110 ( 0.00%) Field(field, _) => self.place_field(base, field.index())?, . Downcast(_, variant) => self.place_downcast(base, variant)?, 96 ( 0.00%) Deref => self.deref_operand(&self.place_to_op(base)?)?.into(), . // For the other variants, we have to force an allocation. . // This matches `operand_projection`. . Subslice { .. } | ConstantIndex { .. } | Index(_) => { . let mplace = self.force_allocation(base)?; . self.mplace_projection(&mplace, proj_elem)?.into() . } . }) . } -- line 605 ---------------------------------------- -- line 611 ---------------------------------------- . base: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::PointerTag>, u64)> { . let mplace = self.force_allocation(base)?; . self.mplace_to_simd(&mplace) . } . . /// Computes a place. You should only use this if you intend to write into this . /// place; for reading, a more efficient alternative is `eval_place_for_read`. 183,128 ( 0.01%) pub fn eval_place( . &mut self, . place: mir::Place<'tcx>, . ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> { 114,455 ( 0.01%) let mut place_ty = PlaceTy { . // This works even for dead/uninitialized locals; we check further when writing . place: Place::Local { frame: self.frame_idx(), local: place.local }, . layout: self.layout_of_local(self.frame(), place.local, None)?, . }; . 36,474 ( 0.00%) for elem in place.projection.iter() { 18,237 ( 0.00%) place_ty = self.place_projection(&place_ty, &elem)? . } . . trace!("{:?}", self.dump_place(place_ty.place)); . // Sanity-check the type we ended up with. . debug_assert!(mir_assign_valid_types( . *self.tcx, . self.param_env, . self.layout_of(self.subst_from_current_frame_and_normalize_erasing_regions( . place.ty(&self.frame().body.local_decls, *self.tcx).ty . )?)?, . place_ty.layout, . )); 412,038 ( 0.02%) Ok(place_ty) 183,128 ( 0.01%) } . . /// Write an immediate to a place . #[inline(always)] . pub fn write_immediate( . &mut self, . src: Immediate, . dest: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx> { 23,318 ( 0.00%) self.write_immediate_no_validate(src, dest)?; . . if M::enforce_validity(self) { . // Data got changed, better make sure it matches the type! . self.validate_operand(&self.place_to_op(dest)?)?; . } . . Ok(()) . } -- line 661 ---------------------------------------- -- line 678 ---------------------------------------- . dest: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx> { . self.write_scalar(Scalar::from_maybe_pointer(ptr.into(), self), dest) . } . . /// Write an immediate to a place. . /// If you use this you are responsible for validating that things got copied at the . /// right type. 22,934 ( 0.00%) fn write_immediate_no_validate( . &mut self, . src: Immediate, . dest: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx> { . if cfg!(debug_assertions) { . // This is a very common path, avoid some checks in release mode . assert!(!dest.layout.is_unsized(), "Cannot write unsized data"); . match src { -- line 694 ---------------------------------------- -- line 705 ---------------------------------------- . // FIXME: Can we check anything here? . } . } . } . trace!("write_immediate: {:?} <- {:?}: {}", *dest, src, dest.layout.ty); . . // See if we can avoid an allocation. This is the counterpart to `try_read_immediate`, . // but not factored as a separate function. 45,868 ( 0.00%) let mplace = match dest.place { 66 ( 0.00%) Place::Local { frame, local } => { . match M::access_local_mut(self, frame, local)? { . Ok(local) => { . // Local can be updated in-place. 330 ( 0.00%) *local = LocalValue::Live(Operand::Immediate(src)); . return Ok(()); . } . Err(mplace) => { . // The local is in memory, go on below. . mplace . } . } . } 137,406 ( 0.01%) Place::Ptr(mplace) => mplace, // already referring to memory . }; 206,109 ( 0.01%) let dest = MPlaceTy { mplace, layout: dest.layout }; . . // This is already in memory, write there. 251,911 ( 0.01%) self.write_immediate_to_mplace_no_validate(src, &dest) 45,868 ( 0.00%) } . . /// Write an immediate to memory. . /// If you use this you are responsible for validating that things got copied at the . /// right type. 229,010 ( 0.01%) fn write_immediate_to_mplace_no_validate( . &mut self, . value: Immediate, . dest: &MPlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx> { . // Note that it is really important that the type here is the right one, and matches the . // type things are read at. In case `src_val` is a `ScalarPair`, we don't do any magic here . // to handle padding properly, which is only correct if we never look at this data with the . // wrong type. . . // Invalid places are a thing: the return place of a diverging function 22,901 ( 0.00%) let tcx = *self.tcx; 45,802 ( 0.00%) let mut alloc = match self.get_alloc_mut(dest)? { 114,505 ( 0.01%) Some(a) => a, . None => return Ok(()), // zero-sized access . }; . . // FIXME: We should check that there are dest.layout.size many bytes available in . // memory. The code below is not sufficient, with enough padding it might not . // cover all the bytes! 45,802 ( 0.00%) match value { . Immediate::Scalar(scalar) => { 36,676 ( 0.00%) match dest.layout.abi { . Abi::Scalar(_) => {} // fine . _ => span_bug!( . self.cur_span(), . "write_immediate_to_mplace: invalid Scalar layout: {:#?}", . dest.layout . ), . } 165,042 ( 0.01%) alloc.write_scalar(alloc_range(Size::ZERO, dest.layout.size), scalar) . } . Immediate::ScalarPair(a_val, b_val) => { . // We checked `ptr_align` above, so all fields will have the alignment they need. . // We would anyway check against `ptr_align.restrict_for_offset(b_offset)`, . // which `ptr.offset(b_offset)` cannot possibly fail to satisfy. 9,126 ( 0.00%) let (a, b) = match dest.layout.abi { 41,013 ( 0.00%) Abi::ScalarPair(a, b) => (a.value, b.value), . _ => span_bug!( . self.cur_span(), . "write_immediate_to_mplace: invalid ScalarPair layout: {:#?}", . dest.layout . ), . }; . let (a_size, b_size) = (a.size(&tcx), b.size(&tcx)); . let b_offset = a_size.align_to(b.align(&tcx).abi); . . // It is tempting to verify `b_offset` against `layout.fields.offset(1)`, . // but that does not work: We could be a newtype around a pair, then the . // fields do not match the `ScalarPair` components. . 45,630 ( 0.00%) alloc.write_scalar(alloc_range(Size::ZERO, a_size), a_val)?; 36,504 ( 0.00%) alloc.write_scalar(alloc_range(b_offset, b_size), b_val) . } . } 183,208 ( 0.01%) } . . /// Copies the data from an operand to a place. This does not support transmuting! . /// Use `copy_op_transmute` if the layouts could disagree. . #[inline(always)] . pub fn copy_op( . &mut self, . src: &OpTy<'tcx, M::PointerTag>, . dest: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx> { 118,953 ( 0.01%) self.copy_op_no_validate(src, dest)?; . . if M::enforce_validity(self) { . // Data got changed, better make sure it matches the type! . self.validate_operand(&self.place_to_op(dest)?)?; . } . . Ok(()) . } . . /// Copies the data from an operand to a place. This does not support transmuting! . /// Use `copy_op_transmute` if the layouts could disagree. . /// Also, if you use this you are responsible for validating that things get copied at the . /// right type. 182,848 ( 0.01%) fn copy_op_no_validate( . &mut self, . src: &OpTy<'tcx, M::PointerTag>, . dest: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx> { . // We do NOT compare the types for equality, because well-typed code can . // actually "transmute" `&mut T` to `&T` in an assignment without a cast. 411,408 ( 0.02%) if !mir_assign_valid_types(*self.tcx, self.param_env, src.layout, dest.layout) { . span_bug!( . self.cur_span(), . "type mismatch when copying!\nsrc: {:?},\ndest: {:?}", . src.layout.ty, . dest.layout.ty, . ); . } . . // Let us see if the layout is simple so we take a shortcut, avoid force_allocation. 114,280 ( 0.01%) let src = match self.try_read_immediate(src)? { . Ok(src_val) => { 18,298 ( 0.00%) assert!(!src.layout.is_unsized(), "cannot have unsized immediates"); . // Yay, we got a value that we can write directly. . // FIXME: Add a check to make sure that if `src` is indirect, . // it does not overlap with `dest`. 237,874 ( 0.01%) return self.write_immediate_no_validate(*src_val, dest); . } 36,464 ( 0.00%) Err(mplace) => mplace, . }; . // Slow path, this does not fit into an immediate. Just memcpy. . trace!("copy_op: {:?} <- {:?}: {}", *dest, src, dest.layout.ty); . . // This interprets `src.meta` with the `dest` local's layout, if an unsized local . // is being initialized! 59,254 ( 0.00%) let (dest, size) = self.force_allocation_maybe_sized(dest, src.meta)?; . let size = size.unwrap_or_else(|| { 13,674 ( 0.00%) assert!( . !dest.layout.is_unsized(), . "Cannot copy into already initialized unsized place" . ); 4,558 ( 0.00%) dest.layout.size . }); 4,558 ( 0.00%) assert_eq!(src.meta, dest.meta, "Can only copy between equally-sized instances"); . 4,558 ( 0.00%) self.memory 13,674 ( 0.00%) .copy(src.ptr, src.align, dest.ptr, dest.align, size, /*nonoverlapping*/ true) 182,848 ( 0.01%) } . . /// Copies the data from an operand to a place. The layouts may disagree, but they must . /// have the same size. 128 ( 0.00%) pub fn copy_op_transmute( . &mut self, . src: &OpTy<'tcx, M::PointerTag>, . dest: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx> { 288 ( 0.00%) if mir_assign_valid_types(*self.tcx, self.param_env, src.layout, dest.layout) { . // Fast path: Just use normal `copy_op` . return self.copy_op(src, dest); . } . // We still require the sizes to match. . if src.layout.size != dest.layout.size { . // FIXME: This should be an assert instead of an error, but if we transmute within an . // array length computation, `typeck` may not have yet been run and errored out. In fact . // most likey we *are* running `typeck` right now. Investigate whether we can bail out -- line 878 ---------------------------------------- -- line 916 ---------------------------------------- . /// Ensures that a place is in memory, and returns where it is. . /// If the place currently refers to a local that doesn't yet have a matching allocation, . /// create such an allocation. . /// This is essentially `force_to_memplace`. . /// . /// This supports unsized types and returns the computed size to avoid some . /// redundant computation when copying; use `force_allocation` for a simpler, sized-only . /// version. 288,171 ( 0.01%) pub fn force_allocation_maybe_sized( . &mut self, . place: &PlaceTy<'tcx, M::PointerTag>, . meta: MemPlaceMeta, . ) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::PointerTag>, Option)> { 320,190 ( 0.02%) let (mplace, size) = match place.place { 27,449 ( 0.00%) Place::Local { frame, local } => { 54,898 ( 0.00%) match M::access_local_mut(self, frame, local)? { 123,543 ( 0.01%) Ok(&mut local_val) => { . // We need to make an allocation. . . // We need the layout of the local. We can NOT use the layout we got, . // that might e.g., be an inner field of a struct with `Scalar` layout, . // that has different alignment than the outer field. . let local_layout = 68,635 ( 0.00%) self.layout_of_local(&self.stack()[frame], local, None)?; . // We also need to support unsized types, and hence cannot use `allocate`. 54,908 ( 0.00%) let (size, align) = self . .size_and_align_of(&meta, &local_layout)? . .expect("Cannot allocate for non-dyn-sized type"); 96,089 ( 0.00%) let ptr = self.memory.allocate(size, align, MemoryKind::Stack)?; . let mplace = MemPlace { ptr: ptr.into(), align, meta }; 68,635 ( 0.00%) if let LocalValue::Live(Operand::Immediate(value)) = local_val { . // Preserve old value. . // We don't have to validate as we can assume the local . // was already valid for its type. . let mplace = MPlaceTy { mplace, layout: local_layout }; . self.write_immediate_to_mplace_no_validate(value, &mplace)?; . } . // Now we can call `access_mut` again, asserting it goes well, . // and actually overwrite things. 260,813 ( 0.01%) *M::access_local_mut(self, frame, local).unwrap().unwrap() = . LocalValue::Live(Operand::Indirect(mplace)); 96,089 ( 0.00%) (mplace, Some(size)) . } 137,220 ( 0.01%) Err(mplace) => (mplace, None), // this already was an indirect local . } . } 59,410 ( 0.00%) Place::Ptr(mplace) => (mplace, None), . }; . // Return with the original layout, so that the caller can go on 384,228 ( 0.02%) Ok((MPlaceTy { mplace, layout: place.layout }, size)) 256,152 ( 0.01%) } . . #[inline(always)] . pub fn force_allocation( . &mut self, . place: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> { 247,095 ( 0.01%) Ok(self.force_allocation_maybe_sized(place, MemPlaceMeta::None)?.0) . } . . pub fn allocate( . &mut self, . layout: TyAndLayout<'tcx>, . kind: MemoryKind, . ) -> InterpResult<'static, MPlaceTy<'tcx, M::PointerTag>> { 112 ( 0.00%) let ptr = self.memory.allocate(layout.size, layout.align.abi, kind)?; . Ok(MPlaceTy::from_aligned_ptr(ptr.into(), layout)) . } . . /// Returns a wide MPlace of type `&'static [mut] str` to a new 1-aligned allocation. . pub fn allocate_str( . &mut self, . str: &str, . kind: MemoryKind, -- line 989 ---------------------------------------- -- line 998 ---------------------------------------- . self.tcx.lifetimes.re_static, . ty::TypeAndMut { ty: self.tcx.types.str_, mutbl }, . ); . let layout = self.layout_of(ty).unwrap(); . MPlaceTy { mplace, layout } . } . . /// Writes the discriminant of the given variant. 50,732 ( 0.00%) pub fn write_discriminant( . &mut self, . variant_index: VariantIdx, . dest: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx> { . // This must be an enum or generator. 18,448 ( 0.00%) match dest.layout.ty.kind() { 9,224 ( 0.00%) ty::Adt(adt, _) => assert!(adt.is_enum()), . ty::Generator(..) => {} . _ => span_bug!( . self.cur_span(), . "write_discriminant called on non-variant-type (neither enum nor generator)" . ), . } . // Layout computation excludes uninhabited variants from consideration . // therefore there's no way to represent those variants in the given layout. . // Essentially, uninhabited variants do not have a tag that corresponds to their . // discriminant, so we cannot do anything here. . // When evaluating we will always error before even getting here, but ConstProp 'executes' . // dead code, so we cannot ICE here. 9,224 ( 0.00%) if dest.layout.for_variant(self, variant_index).abi.is_uninhabited() { . throw_ub!(UninhabitedEnumVariantWritten) . } . 23,060 ( 0.00%) match dest.layout.variants { . Variants::Single { index } => { . assert_eq!(index, variant_index); . } . Variants::Multiple { . tag_encoding: TagEncoding::Direct, 13,836 ( 0.00%) tag: tag_layout, 9,224 ( 0.00%) tag_field, . .. . } => { . // No need to validate that the discriminant here because the . // `TyAndLayout::for_variant()` call earlier already checks the variant is valid. . . let discr_val = 18,448 ( 0.00%) dest.layout.ty.discriminant_for_variant(*self.tcx, variant_index).unwrap().val; . . // raw discriminants for enums are isize or bigger during . // their computation, but the in-memory tag is the smallest possible . // representation . let size = tag_layout.value.size(self); . let tag_val = size.truncate(discr_val); . 23,060 ( 0.00%) let tag_dest = self.place_field(dest, tag_field)?; . self.write_scalar(Scalar::from_uint(tag_val, size), &tag_dest)?; . } . Variants::Multiple { . tag_encoding: . TagEncoding::Niche { dataful_variant, ref niche_variants, niche_start }, . tag: tag_layout, . tag_field, . .. -- line 1060 ---------------------------------------- -- line 1082 ---------------------------------------- . // Write result. . let niche_dest = self.place_field(dest, tag_field)?; . self.write_immediate(*tag_val, &niche_dest)?; . } . } . } . . Ok(()) 36,896 ( 0.00%) } . 144 ( 0.00%) pub fn raw_const_to_mplace( . &self, . raw: ConstAlloc<'tcx>, . ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> { . // This must be an allocation in `tcx` 48 ( 0.00%) let _ = self.tcx.global_alloc(raw.alloc_id); . let ptr = self.global_base_pointer(Pointer::from(raw.alloc_id))?; 48 ( 0.00%) let layout = self.layout_of(raw.ty)?; 96 ( 0.00%) Ok(MPlaceTy::from_aligned_ptr(ptr.into(), layout)) 112 ( 0.00%) } . . /// Turn a place with a `dyn Trait` type into a place with the actual dynamic type. . /// Also return some more information so drop doesn't have to run the same code twice. . pub(super) fn unpack_dyn_trait( . &self, . mplace: &MPlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, (ty::Instance<'tcx>, MPlaceTy<'tcx, M::PointerTag>)> { . let vtable = self.scalar_to_ptr(mplace.vtable()); // also sanity checks the type -- line 1109 ---------------------------------------- 591,361 ( 0.03%) -------------------------------------------------------------------------------- -- 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. . /// 539,513 ( 0.03%) #[derive(Clone, Copy, Eq, PartialEq, Hash)] . // FIXME(@lcnr): Enable this attribute once the bootstrap . // compiler knows of `rustc_pass_by_value`. . // . // Right now, this lint would only trigger when compiling the . // stage 2 compiler, which is fairly annoying as there are . // a lot of places using `&Span` right now. After the next bootstrap bump, . // the lint will already trigger when using stage 1, which is a lot less annoying. . // . // #[cfg_attr(not(bootstrap), rustc_pass_by_value)] . pub struct Span { 528 ( 0.00%) base_or_index: u32, 12 ( 0.00%) len_or_tag: u16, 81 ( 0.00%) ctxt_or_zero: u16, . } . . const LEN_TAG: u16 = 0b1000_0000_0000_0000; . const MAX_LEN: u32 = 0b0111_1111_1111_1111; . const MAX_CTXT: u32 = 0b1111_1111_1111_1111; . . /// Dummy span, both position and length are zero, syntax context is zero as well. . pub const DUMMY_SP: Span = Span { base_or_index: 0, len_or_tag: 0, ctxt_or_zero: 0 }; -- line 84 ---------------------------------------- -- line 86 ---------------------------------------- . impl Span { . #[inline] . pub fn new( . mut lo: BytePos, . mut hi: BytePos, . ctxt: SyntaxContext, . parent: Option, . ) -> Self { 519,500 ( 0.02%) if lo > hi { . std::mem::swap(&mut lo, &mut hi); . } . 1,039,000 ( 0.05%) let (base, len, ctxt2) = (lo.0, hi.0 - lo.0, ctxt.as_u32()); . 4,324,329 ( 0.20%) 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 = 650 ( 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 } . } 1,638,842 ( 0.08%) } . . #[inline] . pub fn data(self) -> SpanData { . let data = self.data_untracked(); 36,690 ( 0.00%) if let Some(parent) = data.parent { . (*SPAN_TRACK)(parent); . } . data . } . . /// Internal function to translate between an encoded span and the expanded representation. . /// This function must not be used outside the incremental engine. . #[inline] . pub fn data_untracked(self) -> SpanData { 5,202,487 ( 0.24%) 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), 4,773,306 ( 0.22%) 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); 23,058 ( 0.00%) let index = self.base_or_index; 88,002 ( 0.00%) with_span_interner(|interner| interner.spans[index as usize]) . } 1,321,870 ( 0.06%) } . } . 4 ( 0.00%) #[derive(Default)] . pub struct SpanInterner { . spans: FxIndexSet, . } . . impl SpanInterner { 177 ( 0.00%) fn intern(&mut self, span_data: &SpanData) -> u32 { 236 ( 0.00%) let (index, _) = self.spans.insert_full(*span_data); . index as u32 236 ( 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())) . } 5,078,028 ( 0.24%) -------------------------------------------------------------------------------- -- 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, . } . 126 ( 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() 81 ( 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 { 97,912 ( 0.00%) self.override_span.unwrap_or_else(|| Span::with_root_ctxt(lo, hi)) . } . . /// Returns the next token, and info about preceding whitespace, if any. 578,802 ( 0.03%) fn next_token(&mut self) -> (Spacing, Token) { . let mut spacing = Spacing::Joint; . . // Skip `#!` at the start of the file 165,372 ( 0.01%) let start_src_index = self.src_index(self.pos); 248,058 ( 0.01%) let text: &str = &self.src[start_src_index..self.end_src_index]; . let is_beginning_of_file = self.pos == self.start_pos; 82,686 ( 0.00%) if is_beginning_of_file { 36 ( 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 { 105,134 ( 0.00%) let start_src_index = self.src_index(self.pos); 281,730 ( 0.01%) let text: &str = &self.src[start_src_index..self.end_src_index]; . 93,910 ( 0.00%) if text.is_empty() { . let span = self.mk_sp(self.pos, self.pos); 45 ( 0.00%) return (spacing, Token::new(token::Eof, span)); . } . 281,703 ( 0.01%) let token = rustc_lexer::first_token(text); . 187,802 ( 0.01%) let start = self.pos; 93,901 ( 0.00%) self.pos = self.pos + BytePos::from_usize(token.len); . . debug!("next_token: {:?}({:?})", token.kind, self.str_from(start)); . 753,172 ( 0.04%) match self.cook_lexer_token(token.kind, start) { 661,416 ( 0.03%) Some(kind) => { . let span = self.mk_sp(start, self.pos); 496,062 ( 0.02%) return (spacing, Token::new(kind, span)); . } . None => spacing = Spacing::Alone, . } . } 744,174 ( 0.04%) } . . /// Report a fatal lexical error with a given span. . fn fatal_span(&self, sp: Span, m: &str) -> FatalError { . self.sess.span_diagnostic.span_fatal(sp, m) . } . . /// Report a lexical error with a given span. . fn err_span(&self, sp: Span, m: &str) { -- line 110 ---------------------------------------- -- line 130 ---------------------------------------- . ) -> DiagnosticBuilder<'a> { . self.sess . .span_diagnostic . .struct_span_fatal(self.mk_sp(from_pos, to_pos), &format!("{}: {}", m, escaped_char(c))) . } . . /// Detect usages of Unicode codepoints changing the direction of the text on screen and loudly . /// complain about it. 539 ( 0.00%) fn lint_unicode_text_flow(&self, start: BytePos) { . // Opening delimiter of the length 2 is not included into the comment text. . let content_start = start + BytePos(2); . let content = self.str_from(content_start); . if contains_text_flow_control_chars(content) { . let span = self.mk_sp(start, self.pos); . self.sess.buffer_lint_with_diagnostic( . &TEXT_DIRECTION_CODEPOINT_IN_COMMENT, . span, . ast::CRATE_NODE_ID, . "unicode codepoint changing visible direction of text present in comment", . BuiltinLintDiagnostics::UnicodeTextFlow(span, content.to_string()), . ); . } 616 ( 0.00%) } . . /// Turns simple `rustc_lexer::TokenKind` enum into a rich . /// `rustc_ast::TokenKind`. This turns strings into interned . /// symbols and runs additional validation. . fn cook_lexer_token(&self, token: rustc_lexer::TokenKind, start: BytePos) -> Option { 469,505 ( 0.02%) Some(match token { 568 ( 0.00%) rustc_lexer::TokenKind::LineComment { doc_style } => { . // Skip non-doc comments 2,609 ( 0.00%) let doc_style = if let Some(doc_style) = doc_style { . doc_style . } else { . self.lint_unicode_text_flow(start); . return None; . }; . . // Opening delimiter of the length 3 is not included into the symbol. . let content_start = start + BytePos(3); . let content = self.str_from(content_start); 2,455 ( 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 => { 60,868 ( 0.00%) let is_raw_ident = token == rustc_lexer::TokenKind::RawIdent; 76,085 ( 0.00%) let is_unknown_prefix = token == rustc_lexer::TokenKind::UnknownPrefix; . let mut ident_start = start; 30,434 ( 0.00%) if is_raw_ident { . ident_start = ident_start + BytePos(2); . } 45,651 ( 0.00%) if is_unknown_prefix { . self.report_unknown_prefix(start); . } 76,085 ( 0.00%) let sym = nfc_normalize(self.str_from(ident_start)); . let span = self.mk_sp(start, self.pos); 60,868 ( 0.00%) self.sess.symbol_gallery.insert(sym, span); 30,434 ( 0.00%) if is_raw_ident { . if !sym.can_be_raw() { . self.err_span(span, &format!("`{}` cannot be a raw identifier", sym)); . } . self.sess.raw_identifier_spans.borrow_mut().push(span); . } 106,519 ( 0.01%) token::Ident(sym, is_raw_ident) . } . rustc_lexer::TokenKind::InvalidIdent . // Do not recover an identifier with emoji if the codepoint is a confusable . // with a recoverable substitution token, like `➖`. . if UNICODE_ARRAY . .iter() . .find(|&&(c, _, _)| { . let sym = self.str_from(start); -- line 232 ---------------------------------------- -- line 234 ---------------------------------------- . }) . .is_none() => . { . let sym = nfc_normalize(self.str_from(start)); . let span = self.mk_sp(start, self.pos); . self.sess.bad_unicode_identifiers.borrow_mut().entry(sym).or_default().push(span); . token::Ident(sym, false) . } 149,600 ( 0.01%) 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); 28,050 ( 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 . }; 74,800 ( 0.00%) token::Literal(token::Lit { kind, symbol, suffix }) . } . rustc_lexer::TokenKind::Lifetime { starts_with_number } => { . // Include the leading `'` in the real identifier, for macro . // expansion purposes. See #12512 for the gory details of why . // this is necessary. . let lifetime_name = self.str_from(start); . if starts_with_number { . self.err_span_(start, self.pos, "lifetimes cannot start with a number"); -- line 280 ---------------------------------------- -- line 324 ---------------------------------------- . err.help("source files must contain UTF-8 encoded text, unexpected null bytes might occur when a different encoding is used"); . } . err.emit(); . token? . } . }) . } . 5,892 ( 0.00%) fn cook_doc_comment( . &self, . content_start: BytePos, . content: &str, . comment_kind: CommentKind, . doc_style: DocStyle, . ) -> TokenKind { 491 ( 0.00%) if content.contains('\r') { . for (idx, _) in content.char_indices().filter(|&(_, c)| c == '\r') { . self.err_span_( . content_start + BytePos(idx as u32), . content_start + BytePos(idx as u32 + 1), . match comment_kind { . CommentKind::Line => "bare CR not allowed in doc-comment", . CommentKind::Block => "bare CR not allowed in block doc-comment", . }, -- line 347 ---------------------------------------- -- line 349 ---------------------------------------- . } . } . . let attr_style = match doc_style { . DocStyle::Outer => AttrStyle::Outer, . DocStyle::Inner => AttrStyle::Inner, . }; . 1,473 ( 0.00%) token::DocComment(comment_kind, attr_style, Symbol::intern(content)) 7,365 ( 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###"`, ... . let (lit_kind, mode, prefix_len, postfix_len) = match kind { 9,267 ( 0.00%) rustc_lexer::LiteralKind::Char { terminated } => { 9,267 ( 0.00%) if !terminated { . self.sess.span_diagnostic.span_fatal_with_code( . self.mk_sp(start, suffix_start), . "unterminated character literal", . error_code!(E0762), . ) . } . (token::Char, Mode::Char, 1, 1) // ' ' . } -- line 377 ---------------------------------------- -- 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' ' . } 80 ( 0.00%) rustc_lexer::LiteralKind::Str { terminated } => { 80 ( 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 410 ---------------------------------------- . let n = u32::from(n_hashes); . (token::StrRaw(n_hashes), Mode::RawStr, 2 + n, 1 + n) // r##" "## . } . rustc_lexer::LiteralKind::RawByteStr { n_hashes, err } => { . self.report_raw_str_error(start, err); . let n = u32::from(n_hashes); . (token::ByteStrRaw(n_hashes), Mode::RawByteStr, 3 + n, 1 + n) // br##" "## . } 6 ( 0.00%) rustc_lexer::LiteralKind::Int { base, empty_int } => { 3 ( 0.00%) return if empty_int { . self.sess . .span_diagnostic . .struct_span_err_with_code( . self.mk_sp(start, suffix_start), . "no valid digits found for number", . error_code!(E0768), . ) . .emit(); . (token::Integer, sym::integer(0)) . } else { . self.validate_int_literal(base, start, suffix_start); 9 ( 0.00%) (token::Integer, self.symbol_from_to(start, suffix_start)) . }; . } . rustc_lexer::LiteralKind::Float { base, empty_exponent } => { . if empty_exponent { . self.err_span_(start, self.pos, "expected at least one digit in exponent"); . } . . match base { -- line 439 ---------------------------------------- -- line 452 ---------------------------------------- . } . . let id = self.symbol_from_to(start, suffix_start); . return (token::Float, id); . } . }; . let content_start = start + BytePos(prefix_len); . let content_end = suffix_start - BytePos(postfix_len); 28,041 ( 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 { 95,663 ( 0.00%) 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); 112,185 ( 0.01%) Symbol::intern(self.str_from_to(start, end)) . } . . /// Slice of the source text spanning from `start` up to but excluding `end`. 34,482 ( 0.00%) fn str_from_to(&self, start: BytePos, end: BytePos) -> &str { . &self.src[self.src_index(start)..self.src_index(end)] 137,928 ( 0.01%) } . . fn report_raw_str_error(&self, start: BytePos, opt_err: Option) { . match opt_err { . Some(RawStrError::InvalidStarter { bad_char }) => { . self.report_non_started_raw_string(start, bad_char) . } . Some(RawStrError::NoTerminator { expected, found, possible_terminator_offset }) => self . .report_unterminated_raw_string(start, expected, possible_terminator_offset, found), -- line 493 ---------------------------------------- -- line 609 ---------------------------------------- . fn validate_literal_escape( . &self, . mode: Mode, . content_start: BytePos, . content_end: BytePos, . prefix_len: u32, . postfix_len: u32, . ) { 56,082 ( 0.00%) let lit_content = self.str_from_to(content_start, content_end); 288,138 ( 0.01%) unescape::unescape_literal(lit_content, mode, &mut |range, result| { . // Here we only check for errors. The actual unescaping is done later. 20,626 ( 0.00%) if let Err(err) = result { . let span_with_quotes = self . .mk_sp(content_start - BytePos(prefix_len), content_end + BytePos(postfix_len)); . let (start, end) = (range.start as u32, range.end as u32); . let lo = content_start + BytePos(start); . let hi = lo + BytePos(end - start); . let span = self.mk_sp(lo, hi); . emit_unescape_error( . &self.sess.span_diagnostic, -- line 628 ---------------------------------------- -- line 629 ---------------------------------------- . lit_content, . span_with_quotes, . span, . mode, . range, . err, . ); . } 92,817 ( 0.00%) }); . } . . fn validate_int_literal(&self, base: Base, content_start: BytePos, content_end: BytePos) { 12 ( 0.00%) let base = match base { . Base::Binary => 2, . Base::Octal => 8, . _ => return, . }; . let s = self.str_from_to(content_start + BytePos(2), content_end); . for (idx, c) in s.char_indices() { . let idx = idx as u32; . if c != '_' && c.to_digit(base).is_none() { -- line 649 ---------------------------------------- -- line 650 ---------------------------------------- . let lo = content_start + BytePos(2 + idx); . let hi = content_start + BytePos(2 + idx + c.len_utf8() as u32); . self.err_span_(lo, hi, &format!("invalid digit for a base {} literal", base)); . } . } . } . } . 136,953 ( 0.01%) pub fn nfc_normalize(string: &str) -> Symbol { . use unicode_normalization::{is_nfc_quick, IsNormalized, UnicodeNormalization}; 30,434 ( 0.00%) match is_nfc_quick(string.chars()) { 152,170 ( 0.01%) IsNormalized::Yes => Symbol::intern(string), . _ => { . let normalized_str: String = string.chars().nfc().collect(); . Symbol::intern(&normalized_str) . } . } . } 429,627 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_metadata/src/rmeta/encoder.rs -------------------------------------------------------------------------------- Ir -- line 83 ---------------------------------------- . if $self.is_proc_macro { . return Lazy::empty(); . } . }; . } . . macro_rules! encoder_methods { . ($($name:ident($ty:ty);)*) => { 58,119 ( 0.00%) $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> { . self.opaque.$name(value) 69,744 ( 0.00%) })* . } . } . . impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> { . type Error = ::Error; . . #[inline] . fn emit_unit(&mut self) -> Result<(), Self::Error> { -- line 101 ---------------------------------------- -- line 125 ---------------------------------------- . emit_raw_bytes(&[u8]); . } . } . . impl<'a, 'tcx, T: Encodable>> Encodable> . for Lazy . { . fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { 1,524 ( 0.00%) e.emit_lazy_distance(*self) . } . } . . impl<'a, 'tcx, T: Encodable>> Encodable> . for Lazy<[T]> . { 70 ( 0.00%) fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { . e.emit_usize(self.meta)?; 184 ( 0.00%) if self.meta == 0 { . return Ok(()); . } 403 ( 0.00%) e.emit_lazy_distance(*self) 6 ( 0.00%) } . } . . impl<'a, 'tcx, I: Idx, T: Encodable>> Encodable> . for Lazy> . where . Option: FixedSizeEncoding, . { . fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { . e.emit_usize(self.meta)?; 144 ( 0.00%) e.emit_lazy_distance(*self) . } . } . . impl<'a, 'tcx> Encodable> for CrateNum { 243,593 ( 0.01%) fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { 159,003 ( 0.01%) if *self != LOCAL_CRATE && s.is_proc_macro { . panic!("Attempted to encode non-local CrateNum {:?} for proc-macro crate", self); . } . s.emit_u32(self.as_u32()) 208,794 ( 0.01%) } . } . . impl<'a, 'tcx> Encodable> for DefIndex { 3,660 ( 0.00%) fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { . s.emit_u32(self.as_u32()) 4,392 ( 0.00%) } . } . . impl<'a, 'tcx> Encodable> for ExpnIndex { . fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { . s.emit_u32(self.as_u32()) . } . } . . impl<'a, 'tcx> Encodable> for SyntaxContext { 442,295 ( 0.02%) fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { 265,377 ( 0.01%) rustc_span::hygiene::raw_encode_syntax_context(*self, &s.hygiene_ctxt, s) 530,754 ( 0.02%) } . } . . impl<'a, 'tcx> Encodable> for ExpnId { . fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { 5,071 ( 0.00%) if self.krate == LOCAL_CRATE { . // We will only write details for local expansions. Non-local expansions will fetch . // data from the corresponding crate's metadata. . // FIXME(#43047) FIXME(#74731) We may eventually want to avoid relying on external . // metadata from proc-macro crates. 38,179 ( 0.00%) s.hygiene_ctxt.schedule_expn_data_for_encoding(*self); . } 28,514 ( 0.00%) self.krate.encode(s)?; . self.local_id.encode(s) . } . } . . impl<'a, 'tcx> Encodable> for Span { 597,536 ( 0.03%) fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { 448,152 ( 0.02%) let span = self.data(); . . // Don't serialize any `SyntaxContext`s from a proc-macro crate, . // since we don't load proc-macro dependencies during serialization. . // This means that any hygiene information from macros used *within* . // a proc-macro crate (e.g. invoking a macro that expands to a proc-macro . // definition) will be lost. . // . // This can show up in two ways: -- line 211 ---------------------------------------- -- line 228 ---------------------------------------- . // None of these user-visible effects should result in any . // cross-crate inconsistencies (getting one behavior in the same . // crate, and a different behavior in another crate) due to the . // limited surface that proc-macros can expose. . // . // IMPORTANT: If this is ever changed, be sure to update . // `rustc_span::hygiene::raw_encode_expn_id` to handle . // encoding `ExpnData` for proc-macro crates. 149,384 ( 0.01%) if s.is_proc_macro { . SyntaxContext::root().encode(s)?; . } else { 74,692 ( 0.00%) span.ctxt.encode(s)?; . } . 74,692 ( 0.00%) if self.is_dummy() { . return TAG_PARTIAL_SPAN.encode(s); . } . . // The Span infrastructure should make sure that this invariant holds: . debug_assert!(span.lo <= span.hi); . 325,327 ( 0.02%) if !s.source_file_cache.0.contains(span.lo) { 95,572 ( 0.00%) let source_map = s.tcx.sess.source_map(); 191,144 ( 0.01%) let source_file_index = source_map.lookup_source_file_idx(span.lo); 95,572 ( 0.00%) s.source_file_cache = 191,144 ( 0.01%) (source_map.files()[source_file_index].clone(), source_file_index); . } . 415,037 ( 0.02%) if !s.source_file_cache.0.contains(span.hi) { . // Unfortunately, macro expansion still sometimes generates Spans . // that malformed in this way. . return TAG_PARTIAL_SPAN.encode(s); . } . . let source_files = s.required_source_files.as_mut().expect("Already encoded SourceMap!"); . // Record the fact that we need to encode the data for this `SourceFile` 74,631 ( 0.00%) source_files.insert(s.source_file_cache.1); . . // There are two possible cases here: . // 1. This span comes from a 'foreign' crate - e.g. some crate upstream of the . // crate we are writing metadata for. When the metadata for *this* crate gets . // deserialized, the deserializer will need to know which crate it originally came . // from. We use `TAG_VALID_SPAN_FOREIGN` to indicate that a `CrateNum` should . // be deserialized after the rest of the span data, which tells the deserializer . // which crate contains the source map information. -- line 272 ---------------------------------------- -- line 274 ---------------------------------------- . // write `TAG_VALID_SPAN_LOCAL` to let the deserializer know that it should use . // our own source map information. . // . // If we're a proc-macro crate, we always treat this as a local `Span`. . // In `encode_source_map`, we serialize foreign `SourceFile`s into our metadata . // if we're a proc-macro crate. . // This allows us to avoid loading the dependencies of proc-macro crates: all of . // the information we need to decode `Span`s is stored in the proc-macro crate. 447,786 ( 0.02%) let (tag, lo, hi) = if s.source_file_cache.0.is_imported() && !s.is_proc_macro { . // To simplify deserialization, we 'rebase' this span onto the crate it originally came from . // (the crate that 'owns' the file it references. These rebased 'lo' and 'hi' values . // are relative to the source map information for the 'foreign' crate whose CrateNum . // we write into the metadata. This allows `imported_source_files` to binary . // search through the 'foreign' crate's source map information, using the . // deserialized 'lo' and 'hi' values directly. . // . // All of this logic ensures that the final result of deserialization is a 'normal' . // Span that can be used without any additional trouble. . let external_start_pos = { . // Introduce a new scope so that we drop the 'lock()' temporary 75,375 ( 0.00%) match &*s.source_file_cache.0.external_src.lock() { 25,125 ( 0.00%) ExternalSource::Foreign { original_start_pos, .. } => *original_start_pos, . src => panic!("Unexpected external source {:?}", src), . } . }; 75,375 ( 0.00%) let lo = (span.lo - s.source_file_cache.0.start_pos) + external_start_pos; 25,125 ( 0.00%) let hi = (span.hi - s.source_file_cache.0.start_pos) + external_start_pos; . . (TAG_VALID_SPAN_FOREIGN, lo, hi) . } else { 148,518 ( 0.01%) (TAG_VALID_SPAN_LOCAL, span.lo, span.hi) . }; . . tag.encode(s)?; . lo.encode(s)?; . . // Encode length which is usually less than span.hi and profits more . // from the variable-length integer encoding that we use. . let len = hi - lo; . len.encode(s)?; . 149,262 ( 0.01%) if tag == TAG_VALID_SPAN_FOREIGN { . // This needs to be two lines to avoid holding the `s.source_file_cache` . // while calling `cnum.encode(s)` 100,500 ( 0.00%) let cnum = s.source_file_cache.0.cnum; 75,375 ( 0.00%) cnum.encode(s)?; . } . . Ok(()) 597,536 ( 0.03%) } . } . . impl<'a, 'tcx> TyEncoder<'tcx> for EncodeContext<'a, 'tcx> { . const CLEAR_CROSS_CRATE: bool = true; . . fn position(&self) -> usize { . self.opaque.position() . } -- line 331 ---------------------------------------- -- line 361 ---------------------------------------- . } . . /// Helper trait to allow overloading `EncodeContext::lazy` for iterators. . trait EncodeContentsForLazy<'a, 'tcx, T: ?Sized + LazyMeta> { . fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> T::Meta; . } . . impl<'a, 'tcx, T: Encodable>> EncodeContentsForLazy<'a, 'tcx, T> for &T { 79,982 ( 0.00%) fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) { 1,902 ( 0.00%) self.encode(ecx).unwrap() 6 ( 0.00%) } . } . . impl<'a, 'tcx, T: Encodable>> EncodeContentsForLazy<'a, 'tcx, T> for T { 8,392 ( 0.00%) fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) { 4,153 ( 0.00%) self.encode(ecx).unwrap() 5,755 ( 0.00%) } . } . . impl<'a, 'tcx, I, T: Encodable>> EncodeContentsForLazy<'a, 'tcx, [T]> for I . where . I: IntoIterator, . I::Item: EncodeContentsForLazy<'a, 'tcx, T>, . { 364 ( 0.00%) fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> usize { 4,107 ( 0.00%) self.into_iter().map(|value| value.encode_contents_for_lazy(ecx)).count() 468 ( 0.00%) } . } . . // Shorthand for `$self.$tables.$table.set($def_id.index, $self.lazy($value))`, which would . // normally need extra variables to avoid errors about multiple mutable borrows. . macro_rules! record { . ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{ . { . let value = $value; . let lazy = $self.lazy(value); . $self.$tables.$table.set($def_id.index, lazy); . } . }}; . } . . impl<'a, 'tcx> EncodeContext<'a, 'tcx> { 1,590 ( 0.00%) fn emit_lazy_distance( . &mut self, . lazy: Lazy, . ) -> Result<(), ::Error> { . let pos = lazy.position.get(); 1,056 ( 0.00%) let distance = match self.lazy_state { . LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"), 267 ( 0.00%) LazyState::NodeStart(start) => { . let start = start.get(); 534 ( 0.00%) assert!(pos <= start); . start - pos . } 51 ( 0.00%) LazyState::Previous(last_pos) => { 51 ( 0.00%) assert!( . last_pos <= lazy.position, . "make sure that the calls to `lazy*` \ . are in the same order as the metadata fields", . ); 153 ( 0.00%) lazy.position.get() - last_pos.get() . } . }; 636 ( 0.00%) self.lazy_state = LazyState::Previous(NonZeroUsize::new(pos).unwrap()); . self.emit_usize(distance) 1,590 ( 0.00%) } . 4,095 ( 0.00%) fn lazy( . &mut self, . value: impl EncodeContentsForLazy<'a, 'tcx, T>, . ) -> Lazy { . let pos = NonZeroUsize::new(self.position()).unwrap(); . 18,512 ( 0.00%) assert_eq!(self.lazy_state, LazyState::NoNode); 42,501 ( 0.00%) self.lazy_state = LazyState::NodeStart(pos); 36,807 ( 0.00%) let meta = value.encode_contents_for_lazy(self); 19,830 ( 0.00%) self.lazy_state = LazyState::NoNode; . 37,821 ( 0.00%) assert!(pos.get() <= self.position()); . . Lazy::from_position_and_meta(pos, meta) 6,030 ( 0.00%) } . . fn encode_info_for_items(&mut self) { 9 ( 0.00%) self.encode_info_for_mod(CRATE_DEF_ID, self.tcx.hir().root_module()); . . // Proc-macro crates only export proc-macro items, which are looked . // up using `proc_macro_data` 2 ( 0.00%) if self.is_proc_macro { . return; . } . 6 ( 0.00%) self.tcx.hir().visit_all_item_likes(&mut self.as_deep_visitor()); . } . . fn encode_def_path_table(&mut self) { 4 ( 0.00%) let table = self.tcx.resolutions(()).definitions.def_path_table(); 2 ( 0.00%) if self.is_proc_macro { . for def_index in std::iter::once(CRATE_DEF_INDEX) . .chain(self.tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index)) . { . let def_key = self.lazy(table.def_key(def_index)); . let def_path_hash = self.lazy(table.def_path_hash(def_index)); . self.tables.def_keys.set(def_index, def_key); . self.tables.def_path_hashes.set(def_index, def_path_hash); . } . } else { 5 ( 0.00%) for (def_index, def_key, def_path_hash) in table.enumerated_keys_and_path_hashes() { . let def_key = self.lazy(def_key); . let def_path_hash = self.lazy(def_path_hash); 2,492 ( 0.00%) self.tables.def_keys.set(def_index, def_key); 2,492 ( 0.00%) self.tables.def_path_hashes.set(def_index, def_path_hash); . } . } . } . . fn encode_def_path_hash_map(&mut self) -> Lazy> { . self.lazy(DefPathHashMapRef::BorrowedFromTcx( 2 ( 0.00%) self.tcx.resolutions(()).definitions.def_path_hash_to_def_index_map(), . )) . } . . fn encode_source_map(&mut self) -> Lazy<[rustc_span::SourceFile]> { 2 ( 0.00%) let source_map = self.tcx.sess.source_map(); 3 ( 0.00%) let all_source_files = source_map.files(); . . // By replacing the `Option` with `None`, we ensure that we can't . // accidentally serialize any more `Span`s after the source map encoding . // is done. . let required_source_files = self.required_source_files.take().unwrap(); . . let adapted = all_source_files . .iter() . .enumerate() . .filter(|(idx, source_file)| { . // Only serialize `SourceFile`s that were used . // during the encoding of a `Span` 683 ( 0.00%) required_source_files.contains(*idx) && . // Don't serialize imported `SourceFile`s, unless . // we're in a proc-macro crate. 93 ( 0.00%) (!source_file.is_imported() || self.is_proc_macro) . }) . .map(|(_, source_file)| { 27 ( 0.00%) let mut adapted = match source_file.name { . FileName::Real(ref realname) => { 18 ( 0.00%) let mut adapted = (**source_file).clone(); 144 ( 0.00%) adapted.name = FileName::Real(match realname { . RealFileName::LocalPath(path_to_file) => { . // Prepend path of working directory onto potentially . // relative paths, because they could become relative . // to a wrong directory. . // We include `working_dir` as part of the crate hash, . // so it's okay for us to use it as part of the encoded . // metadata. 18 ( 0.00%) let working_dir = &self.tcx.sess.opts.working_dir; 18 ( 0.00%) match working_dir { . RealFileName::LocalPath(absolute) => { . // Although neither working_dir or the file name were subject . // to path remapping, the concatenation between the two may . // be. Hence we need to do a remapping here. . let joined = Path::new(absolute).join(path_to_file); 63 ( 0.00%) let (joined, remapped) = 99 ( 0.00%) source_map.path_mapping().map_prefix(joined); 18 ( 0.00%) if remapped { . RealFileName::Remapped { . local_path: None, . virtual_name: joined, . } . } else { . RealFileName::LocalPath(joined) . } . } -- line 532 ---------------------------------------- -- line 544 ---------------------------------------- . RealFileName::Remapped { local_path: _, virtual_name } => { . RealFileName::Remapped { . // We do not want any local path to be exported into metadata . local_path: None, . virtual_name: virtual_name.clone(), . } . } . }); 18 ( 0.00%) adapted.name_hash = { . let mut hasher: StableHasher = StableHasher::new(); 9 ( 0.00%) adapted.name.hash(&mut hasher); . hasher.finish::() . }; 9 ( 0.00%) Lrc::new(adapted) . } . . // expanded code, not from a file . _ => source_file.clone(), . }; . . // We're serializing this `SourceFile` into our crate metadata, . // so mark it as coming from this crate. . // This also ensures that we don't try to deserialize the . // `CrateNum` for a proc-macro dependency - since proc macro . // dependencies aren't loaded when we deserialize a proc-macro, . // trying to remap the `CrateNum` would fail. 18 ( 0.00%) if self.is_proc_macro { . Lrc::make_mut(&mut adapted).cnum = LOCAL_CRATE; . } . adapted . }) . .collect::>(); . . self.lazy(adapted.iter().map(|rc| &**rc)) . } . 8 ( 0.00%) fn encode_crate_root(&mut self) -> Lazy> { . let mut i = self.position(); . . // Encode the crate deps . let crate_deps = self.encode_crate_deps(); . let dylib_dependency_formats = self.encode_dylib_dependency_formats(); 5 ( 0.00%) let dep_bytes = self.position() - i; . . // Encode the lib features. . i = self.position(); . let lib_features = self.encode_lib_features(); 7 ( 0.00%) let lib_feature_bytes = self.position() - i; . . // Encode the language items. . i = self.position(); . let lang_items = self.encode_lang_items(); . let lang_items_missing = self.encode_lang_items_missing(); 5 ( 0.00%) let lang_item_bytes = self.position() - i; . . // Encode the diagnostic items. . i = self.position(); . let diagnostic_items = self.encode_diagnostic_items(); 5 ( 0.00%) let diagnostic_item_bytes = self.position() - i; . . // Encode the native libraries used . i = self.position(); . let native_libraries = self.encode_native_libraries(); 4 ( 0.00%) let native_lib_bytes = self.position() - i; . . let foreign_modules = self.encode_foreign_modules(); . . // Encode DefPathTable . i = self.position(); . self.encode_def_path_table(); 5 ( 0.00%) let def_path_table_bytes = self.position() - i; . . // Encode the def IDs of traits, for rustdoc and diagnostics. . i = self.position(); . let traits = self.encode_traits(); 5 ( 0.00%) let traits_bytes = self.position() - i; . . // Encode the def IDs of impls, for coherence checking. . i = self.position(); . let impls = self.encode_impls(); 5 ( 0.00%) let impls_bytes = self.position() - i; . 3 ( 0.00%) let tcx = self.tcx; . . // Encode MIR. . i = self.position(); . self.encode_mir(); 5 ( 0.00%) let mir_bytes = self.position() - i; . . // Encode the items. . i = self.position(); . self.encode_def_ids(); . self.encode_info_for_items(); 4 ( 0.00%) let item_bytes = self.position() - i; . . // Encode the allocation index . let interpret_alloc_index = { . let mut interpret_alloc_index = Vec::new(); . let mut n = 0; . trace!("beginning to encode alloc ids"); . loop { . let new_n = self.interpret_allocs.len(); . // if we have found new ids, serialize those, too 2 ( 0.00%) if n == new_n { . // otherwise, abort . break; . } . trace!("encoding {} further alloc ids", new_n - n); . for idx in n..new_n { . let id = self.interpret_allocs[idx]; . let pos = self.position() as u32; . interpret_alloc_index.push(pos); . interpret::specialized_encode_alloc_id(self, tcx, id).unwrap(); . } . n = new_n; . } 6 ( 0.00%) self.lazy(interpret_alloc_index) . }; . . // Encode the proc macro data. This affects 'tables', . // so we need to do this before we encode the tables . i = self.position(); . let proc_macro_data = self.encode_proc_macros(); 4 ( 0.00%) let proc_macro_data_bytes = self.position() - i; . . i = self.position(); 4 ( 0.00%) let tables = self.tables.encode(&mut self.opaque); 4 ( 0.00%) let tables_bytes = self.position() - i; . . // Encode exported symbols info. This is prefetched in `encode_metadata` so we encode . // this as late as possible to give the prefetching as much time as possible to complete. . i = self.position(); . let exported_symbols = tcx.exported_symbols(LOCAL_CRATE); . let exported_symbols = self.encode_exported_symbols(&exported_symbols); 4 ( 0.00%) let exported_symbols_bytes = self.position() - i; . . // Encode the hygiene data, . // IMPORTANT: this *must* be the last thing that we encode (other than `SourceMap`). The process . // of encoding other items (e.g. `optimized_mir`) may cause us to load . // data from the incremental cache. If this causes us to deserialize a `Span`, . // then we may load additional `SyntaxContext`s into the global `HygieneData`. . // Therefore, we need to encode the hygiene data last to ensure that we encode . // any `SyntaxContext`s that might be used. . i = self.position(); . let (syntax_contexts, expn_data, expn_hashes) = self.encode_hygiene(); 5 ( 0.00%) let hygiene_bytes = self.position() - i; . . i = self.position(); . let def_path_hash_map = self.encode_def_path_hash_map(); 1 ( 0.00%) let def_path_hash_map_bytes = self.position() - i; . . // Encode source_map. This needs to be done last, . // since encoding `Span`s tells us which `SourceFiles` we actually . // need to encode. . i = self.position(); . let source_map = self.encode_source_map(); 4 ( 0.00%) let source_map_bytes = self.position() - i; . 3 ( 0.00%) let attrs = tcx.hir().krate_attrs(); 7 ( 0.00%) let has_default_lib_allocator = tcx.sess.contains_name(&attrs, sym::default_lib_allocator); . 118 ( 0.00%) let root = self.lazy(CrateRoot { . name: tcx.crate_name(LOCAL_CRATE), 3 ( 0.00%) extra_filename: tcx.sess.opts.cg.extra_filename.clone(), 1 ( 0.00%) triple: tcx.sess.opts.target_triple.clone(), . hash: tcx.crate_hash(LOCAL_CRATE), . stable_crate_id: tcx.def_path_hash(LOCAL_CRATE.as_def_id()).stable_crate_id(), 3 ( 0.00%) panic_strategy: tcx.sess.panic_strategy(), 3 ( 0.00%) panic_in_drop_strategy: tcx.sess.opts.debugging_opts.panic_in_drop, 2 ( 0.00%) edition: tcx.sess.edition(), . has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE), . has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE), . has_default_lib_allocator, . proc_macro_data, 6 ( 0.00%) compiler_builtins: tcx.sess.contains_name(&attrs, sym::compiler_builtins), 6 ( 0.00%) needs_allocator: tcx.sess.contains_name(&attrs, sym::needs_allocator), 6 ( 0.00%) needs_panic_runtime: tcx.sess.contains_name(&attrs, sym::needs_panic_runtime), 6 ( 0.00%) no_builtins: tcx.sess.contains_name(&attrs, sym::no_builtins), 5 ( 0.00%) panic_runtime: tcx.sess.contains_name(&attrs, sym::panic_runtime), 5 ( 0.00%) profiler_runtime: tcx.sess.contains_name(&attrs, sym::profiler_runtime), 2 ( 0.00%) symbol_mangling_version: tcx.sess.opts.get_symbol_mangling_version(), . . crate_deps, . dylib_dependency_formats, . lib_features, . lang_items, . diagnostic_items, . lang_items_missing, . native_libraries, . foreign_modules, . source_map, . traits, . impls, . exported_symbols, . interpret_alloc_index, 2 ( 0.00%) tables, . syntax_contexts, . expn_data, . expn_hashes, . def_path_hash_map, . }); . 1 ( 0.00%) let total_bytes = self.position(); . 4 ( 0.00%) if tcx.sess.meta_stats() { . let mut zero_bytes = 0; . for e in self.opaque.data.iter() { . if *e == 0 { . zero_bytes += 1; . } . } . . eprintln!("metadata stats:"); -- line 756 ---------------------------------------- -- line 770 ---------------------------------------- . eprintln!(" item bytes: {}", item_bytes); . eprintln!(" table bytes: {}", tables_bytes); . eprintln!(" hygiene bytes: {}", hygiene_bytes); . eprintln!(" zero bytes: {}", zero_bytes); . eprintln!(" total bytes: {}", total_bytes); . } . . root 9 ( 0.00%) } . } . . fn should_encode_visibility(def_kind: DefKind) -> bool { . match def_kind { . DefKind::Mod . | DefKind::Struct . | DefKind::Union . | DefKind::Enum -- line 786 ---------------------------------------- -- line 853 ---------------------------------------- . /// Whether we should encode MIR. . /// . /// Computing, optimizing and encoding the MIR is a relatively expensive operation. . /// We want to avoid this work when not required. Therefore: . /// - we only compute `mir_for_ctfe` on items with const-eval semantics; . /// - we skip `optimized_mir` for check runs. . /// . /// Return a pair, resp. for CTFE and for LLVM. 549 ( 0.00%) fn should_encode_mir(tcx: TyCtxt<'_>, def_id: LocalDefId) -> (bool, bool) { 305 ( 0.00%) match tcx.def_kind(def_id) { . // Constructors . DefKind::Ctor(_, _) => { . let mir_opt_base = tcx.sess.opts.output_types.should_codegen() . || tcx.sess.opts.debugging_opts.always_encode_mir; . (true, mir_opt_base) . } . // Constants . DefKind::AnonConst . | DefKind::InlineConst . | DefKind::AssocConst . | DefKind::Static . | DefKind::Const => (true, false), . // Full-fledged functions . DefKind::AssocFn | DefKind::Fn => { . let generics = tcx.generics_of(def_id); 300 ( 0.00%) let needs_inline = (generics.requires_monomorphization(tcx) 96 ( 0.00%) || tcx.codegen_fn_attrs(def_id).requests_inline()) 36 ( 0.00%) && tcx.sess.opts.output_types.should_codegen(); . // The function has a `const` modifier or is annotated with `default_method_body_is_const`. 51 ( 0.00%) let is_const_fn = tcx.is_const_fn_raw(def_id.to_def_id()) 255 ( 0.00%) || tcx.has_attr(def_id.to_def_id(), sym::default_method_body_is_const); . let always_encode_mir = tcx.sess.opts.debugging_opts.always_encode_mir; 102 ( 0.00%) (is_const_fn, needs_inline || always_encode_mir) . } . // Closures can't be const fn. . DefKind::Closure => { . let generics = tcx.generics_of(def_id); . let needs_inline = (generics.requires_monomorphization(tcx) . || tcx.codegen_fn_attrs(def_id).requests_inline()) . && tcx.sess.opts.output_types.should_codegen(); . let always_encode_mir = tcx.sess.opts.debugging_opts.always_encode_mir; . (false, needs_inline || always_encode_mir) . } . // Generators require optimized MIR to compute layout. . DefKind::Generator => (false, true), . // The others don't have MIR. . _ => (false, false), . } 549 ( 0.00%) } . . fn should_encode_variances(def_kind: DefKind) -> bool { . match def_kind { . DefKind::Struct . | DefKind::Union . | DefKind::Enum . | DefKind::Variant . | DefKind::Fn -- line 909 ---------------------------------------- -- line 969 ---------------------------------------- . | DefKind::LifetimeParam . | DefKind::GlobalAsm . | DefKind::ExternCrate => false, . } . } . . impl<'a, 'tcx> EncodeContext<'a, 'tcx> { . fn encode_def_ids(&mut self) { 2 ( 0.00%) if self.is_proc_macro { . return; . } 1 ( 0.00%) let tcx = self.tcx; 3 ( 0.00%) let hir = tcx.hir(); 45 ( 0.00%) for local_id in hir.iter_local_def_id() { . let def_id = local_id.to_def_id(); . let def_kind = tcx.opt_def_kind(local_id); 3,738 ( 0.00%) let def_kind = if let Some(def_kind) = def_kind { def_kind } else { continue }; 7,696 ( 0.00%) record!(self.tables.def_kind[def_id] <- match def_kind { . // Replace Ctor by the enclosing object to avoid leaking details in children crates. . DefKind::Ctor(CtorOf::Struct, _) => DefKind::Struct, . DefKind::Ctor(CtorOf::Variant, _) => DefKind::Variant, . def_kind => def_kind, . }); 1,443 ( 0.00%) record!(self.tables.span[def_id] <- tcx.def_span(def_id)); 5,772 ( 0.00%) record!(self.tables.attributes[def_id] <- tcx.get_attrs(def_id)); 3,848 ( 0.00%) record!(self.tables.expn_that_defined[def_id] <- self.tcx.expn_that_defined(def_id)); . if should_encode_visibility(def_kind) { 2,844 ( 0.00%) record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id)); . } . if should_encode_stability(def_kind) { . self.encode_stability(def_id); . self.encode_const_stability(def_id); 1,434 ( 0.00%) self.encode_deprecation(def_id); . } . if should_encode_variances(def_kind) { 328 ( 0.00%) let v = self.tcx.variances_of(def_id); 1,148 ( 0.00%) record!(self.tables.variances[def_id] <- v); . } . if should_encode_generics(def_kind) { . let g = tcx.generics_of(def_id); 900 ( 0.00%) record!(self.tables.generics[def_id] <- g); 2,700 ( 0.00%) record!(self.tables.explicit_predicates[def_id] <- self.tcx.explicit_predicates_of(def_id)); 225 ( 0.00%) let inferred_outlives = self.tcx.inferred_outlives_of(def_id); 283 ( 0.00%) if !inferred_outlives.is_empty() { . record!(self.tables.inferred_outlives[def_id] <- inferred_outlives); . } . } 3,367 ( 0.00%) if let DefKind::Trait | DefKind::TraitAlias = def_kind { . record!(self.tables.super_predicates[def_id] <- self.tcx.super_predicates_of(def_id)); . } . } . let inherent_impls = tcx.crate_inherent_impls(()); . for (def_id, implementations) in inherent_impls.inherent_impls.iter() { 3 ( 0.00%) if implementations.is_empty() { . continue; . } 27 ( 0.00%) record!(self.tables.inherent_impls[def_id.to_def_id()] <- implementations.iter().map(|&def_id| { 3 ( 0.00%) assert!(def_id.is_local()); . def_id.index . })); . } . } . 1,554 ( 0.00%) fn encode_item_type(&mut self, def_id: DefId) { . debug!("EncodeContext::encode_item_type({:?})", def_id); 1,332 ( 0.00%) record!(self.tables.ty[def_id] <- self.tcx.type_of(def_id)); 1,776 ( 0.00%) } . . fn encode_enum_variant_info(&mut self, def: &ty::AdtDef, index: VariantIdx) { . let tcx = self.tcx; . let variant = &def.variants[index]; 220 ( 0.00%) let def_id = variant.def_id; . debug!("EncodeContext::encode_enum_variant_info({:?})", def_id); . 330 ( 0.00%) let data = VariantData { 55 ( 0.00%) ctor_kind: variant.ctor_kind, . discr: variant.discr, 55 ( 0.00%) ctor: variant.ctor_def_id.map(|did| did.index), 55 ( 0.00%) is_non_exhaustive: variant.is_field_list_non_exhaustive(), . }; . . record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data))); . record!(self.tables.children[def_id] <- variant.fields.iter().map(|f| { . assert!(f.did.is_local()); . f.did.index . })); 55 ( 0.00%) self.encode_ident_span(def_id, variant.ident(tcx)); 55 ( 0.00%) self.encode_item_type(def_id); 55 ( 0.00%) if variant.ctor_kind == CtorKind::Fn { . // FIXME(eddyb) encode signature only in `encode_enum_variant_ctor`. . if let Some(ctor_def_id) = variant.ctor_def_id { . record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(ctor_def_id)); . } . } . } . . fn encode_enum_variant_ctor(&mut self, def: &ty::AdtDef, index: VariantIdx) { . let tcx = self.tcx; . let variant = &def.variants[index]; 275 ( 0.00%) let def_id = variant.ctor_def_id.unwrap(); . debug!("EncodeContext::encode_enum_variant_ctor({:?})", def_id); . . // FIXME(eddyb) encode only the `CtorKind` for constructors. . let data = VariantData { 55 ( 0.00%) ctor_kind: variant.ctor_kind, . discr: variant.discr, . ctor: Some(def_id.index), 55 ( 0.00%) is_non_exhaustive: variant.is_field_list_non_exhaustive(), . }; . 220 ( 0.00%) record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data))); 165 ( 0.00%) self.encode_item_type(def_id); 55 ( 0.00%) if variant.ctor_kind == CtorKind::Fn { . record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); . } . } . 140 ( 0.00%) fn encode_info_for_mod(&mut self, local_def_id: LocalDefId, md: &hir::Mod<'_>) { 28 ( 0.00%) let tcx = self.tcx; . let def_id = local_def_id.to_def_id(); . debug!("EncodeContext::encode_info_for_mod({:?})", def_id); . . // If we are encoding a proc-macro crates, `encode_info_for_mod` will . // only ever get called for the crate root. We still want to encode . // the crate root for consistency with other crates (some of the resolver . // code uses it). However, we skip encoding anything relating to child . // items - we encode information about proc-macros later on. 42 ( 0.00%) let reexports = if !self.is_proc_macro { 28 ( 0.00%) match tcx.module_reexports(local_def_id) { . Some(exports) => self.lazy(exports), . _ => Lazy::empty(), . } . } else { . Lazy::empty() . }; . 56 ( 0.00%) record!(self.tables.kind[def_id] <- EntryKind::Mod(reexports)); 28 ( 0.00%) if self.is_proc_macro { . // Encode this here because we don't do it in encode_def_ids. . record!(self.tables.expn_that_defined[def_id] <- tcx.expn_that_defined(local_def_id)); . } else { . let direct_children = md.item_ids.iter().map(|item_id| item_id.def_id.local_def_index); . // Foreign items are planted into their parent modules from name resolution point of view. 28 ( 0.00%) let tcx = self.tcx; . let foreign_item_children = md . .item_ids . .iter() 1,550 ( 0.00%) .filter_map(|item_id| match tcx.hir().item(*item_id).kind { . hir::ItemKind::ForeignMod { items, .. } => { . Some(items.iter().map(|fi_ref| fi_ref.id.def_id.local_def_index)) . } . _ => None, . }) . .flatten(); . 98 ( 0.00%) record!(self.tables.children[def_id] <- direct_children.chain(foreign_item_children)); . } 112 ( 0.00%) } . . fn encode_field( . &mut self, . adt_def: &ty::AdtDef, . variant_index: VariantIdx, . field_index: usize, . ) { . let variant = &adt_def.variants[variant_index]; -- line 1134 ---------------------------------------- -- line 1234 ---------------------------------------- . } . if trait_item.kind == ty::AssocKind::Fn { . record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); . } . } . . fn encode_info_for_impl_item(&mut self, def_id: DefId) { . debug!("EncodeContext::encode_info_for_impl_item({:?})", def_id); 108 ( 0.00%) let tcx = self.tcx; . 324 ( 0.00%) let ast_item = self.tcx.hir().expect_impl_item(def_id.expect_local()); 54 ( 0.00%) let impl_item = self.tcx.associated_item(def_id); . 216 ( 0.00%) let container = match impl_item.defaultness { . hir::Defaultness::Default { has_value: true } => AssocContainer::ImplDefault, . hir::Defaultness::Final => AssocContainer::ImplFinal, . hir::Defaultness::Default { has_value: false } => { . span_bug!(ast_item.span, "impl items always have values (currently)") . } . }; . 324 ( 0.00%) match impl_item.kind { . ty::AssocKind::Const => { . if let hir::ImplItemKind::Const(_, body_id) = ast_item.kind { . let qualifs = self.tcx.at(ast_item.span).mir_const_qualif(def_id); . . record!(self.tables.kind[def_id] <- EntryKind::AssocConst( . container, . qualifs, . self.encode_rendered_const_for_body(body_id)) . ); . } else { . bug!() . } . } . ty::AssocKind::Fn => { 102 ( 0.00%) let fn_data = if let hir::ImplItemKind::Fn(ref sig, body) = ast_item.kind { . FnData { . asyncness: sig.header.asyncness, . // Can be inside `impl const Trait`, so using sig.header.constness is not reliable 51 ( 0.00%) constness: if self.tcx.is_const_fn_raw(def_id) { . hir::Constness::Const . } else { . hir::Constness::NotConst . }, . param_names: self.encode_fn_param_names_for_body(body), . } . } else { . bug!() -- line 1282 ---------------------------------------- -- line 1286 ---------------------------------------- . container, . has_self: impl_item.fn_has_self_parameter, . }))); . } . ty::AssocKind::Type => { . record!(self.tables.kind[def_id] <- EntryKind::AssocType(container)); . } . } 162 ( 0.00%) self.encode_ident_span(def_id, impl_item.ident(self.tcx)); 270 ( 0.00%) self.encode_item_type(def_id); 216 ( 0.00%) if let Some(trait_item_def_id) = impl_item.trait_item_def_id { . record!(self.tables.trait_item_def_id[def_id] <- trait_item_def_id); . } 54 ( 0.00%) if impl_item.kind == ty::AssocKind::Fn { . record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); . } . } . . fn encode_fn_param_names_for_body(&mut self, body_id: hir::BodyId) -> Lazy<[Ident]> { 357 ( 0.00%) self.lazy(self.tcx.hir().body_param_names(body_id)) . } . . fn encode_fn_param_names(&mut self, param_names: &[Ident]) -> Lazy<[Ident]> { . self.lazy(param_names.iter()) . } . . fn encode_mir(&mut self) { 3 ( 0.00%) if self.is_proc_macro { . return; . } . . let keys_and_jobs = self . .tcx . .mir_keys(()) . .iter() . .filter_map(|&def_id| { 305 ( 0.00%) let (encode_const, encode_opt) = should_encode_mir(self.tcx, def_id); 213 ( 0.00%) if encode_const || encode_opt { 20 ( 0.00%) Some((def_id, encode_const, encode_opt)) . } else { . None . } 122 ( 0.00%) }) . .collect::>(); 55 ( 0.00%) for (def_id, encode_const, encode_opt) in keys_and_jobs.into_iter() { . debug_assert!(encode_const || encode_opt); . . debug!("EntryBuilder::encode_mir({:?})", def_id); 10 ( 0.00%) if encode_opt { . record!(self.tables.mir[def_id.to_def_id()] <- self.tcx.optimized_mir(def_id)); . } 10 ( 0.00%) if encode_const { 40 ( 0.00%) record!(self.tables.mir_for_ctfe[def_id.to_def_id()] <- self.tcx.mir_for_ctfe(def_id)); . . // FIXME(generic_const_exprs): this feels wrong to have in `encode_mir` 10 ( 0.00%) let abstract_const = self.tcx.thir_abstract_const(def_id); 40 ( 0.00%) if let Ok(Some(abstract_const)) = abstract_const { . record!(self.tables.thir_abstract_consts[def_id.to_def_id()] <- abstract_const); . } . } 40 ( 0.00%) record!(self.tables.promoted_mir[def_id.to_def_id()] <- self.tcx.promoted_mir(def_id)); . . let instance = . ty::InstanceDef::Item(ty::WithOptConstParam::unknown(def_id.to_def_id())); 10 ( 0.00%) let unused = self.tcx.unused_generic_params(instance); 10 ( 0.00%) if !unused.is_empty() { . record!(self.tables.unused_generic_params[def_id.to_def_id()] <- unused); . } . } . } . . fn encode_stability(&mut self, def_id: DefId) { . debug!("EncodeContext::encode_stability({:?})", def_id); . . // The query lookup can take a measurable amount of time in crates with many items. Check if . // the stability attributes are even enabled before using their queries. 1,912 ( 0.00%) if self.feat.staged_api || self.tcx.sess.opts.debugging_opts.force_unstable_if_unmarked { . if let Some(stab) = self.tcx.lookup_stability(def_id) { . record!(self.tables.stability[def_id] <- stab) . } . } . } . . fn encode_const_stability(&mut self, def_id: DefId) { . debug!("EncodeContext::encode_const_stability({:?})", def_id); . . // The query lookup can take a measurable amount of time in crates with many items. Check if . // the stability attributes are even enabled before using their queries. 1,673 ( 0.00%) if self.feat.staged_api || self.tcx.sess.opts.debugging_opts.force_unstable_if_unmarked { . if let Some(stab) = self.tcx.lookup_const_stability(def_id) { . record!(self.tables.const_stability[def_id] <- stab) . } . } . } . 1,434 ( 0.00%) fn encode_deprecation(&mut self, def_id: DefId) { . debug!("EncodeContext::encode_deprecation({:?})", def_id); 1,195 ( 0.00%) if let Some(depr) = self.tcx.lookup_deprecation(def_id) { . record!(self.tables.deprecation[def_id] <- depr); . } 1,195 ( 0.00%) } . 60 ( 0.00%) fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> Lazy { 30 ( 0.00%) let hir = self.tcx.hir(); 20 ( 0.00%) let body = hir.body(body_id); 80 ( 0.00%) let rendered = rustc_hir_pretty::to_string(&(&hir as &dyn intravisit::Map<'_>), |s| { 30 ( 0.00%) s.print_expr(&body.value) . }); 20 ( 0.00%) let rendered_const = &RenderedConst(rendered); . self.lazy(rendered_const) 70 ( 0.00%) } . 639 ( 0.00%) fn encode_info_for_item(&mut self, def_id: DefId, item: &'tcx hir::Item<'tcx>) { . let tcx = self.tcx; . . debug!("EncodeContext::encode_info_for_item({:?})", def_id); . . self.encode_ident_span(def_id, item.ident); . 426 ( 0.00%) let entry_kind = match item.kind { . hir::ItemKind::Static(_, hir::Mutability::Mut, _) => EntryKind::MutStatic, . hir::ItemKind::Static(_, hir::Mutability::Not, _) => EntryKind::ImmStatic, 30 ( 0.00%) hir::ItemKind::Const(_, body_id) => { 30 ( 0.00%) let qualifs = self.tcx.at(item.span).mir_const_qualif(def_id); 70 ( 0.00%) EntryKind::Const(qualifs, self.encode_rendered_const_for_body(body_id)) . } . hir::ItemKind::Fn(ref sig, .., body) => { . let data = FnData { . asyncness: sig.header.asyncness, . constness: sig.header.constness, . param_names: self.encode_fn_param_names_for_body(body), . }; . . EntryKind::Fn(self.lazy(data)) . } . hir::ItemKind::Macro(ref macro_def) => { . EntryKind::MacroDef(self.lazy(macro_def.clone())) . } . hir::ItemKind::Mod(ref m) => { 156 ( 0.00%) return self.encode_info_for_mod(item.def_id, m); . } . hir::ItemKind::ForeignMod { .. } => EntryKind::ForeignMod, . hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm, . hir::ItemKind::TyAlias(..) => EntryKind::Type, . hir::ItemKind::OpaqueTy(..) => { . self.encode_explicit_item_bounds(def_id); . EntryKind::OpaqueTy . } 18 ( 0.00%) hir::ItemKind::Enum(..) => EntryKind::Enum(self.tcx.adt_def(def_id).repr), . hir::ItemKind::Struct(ref struct_def, _) => { . let adt_def = self.tcx.adt_def(def_id); . let variant = adt_def.non_enum_variant(); . . // Encode def_ids for each field and method . // for methods, write all the stuff get_trait_method . // needs to know . let ctor = struct_def -- line 1442 ---------------------------------------- -- line 1462 ---------------------------------------- . ctor_kind: variant.ctor_kind, . discr: variant.discr, . ctor: None, . is_non_exhaustive: variant.is_field_list_non_exhaustive(), . }), . adt_def.repr, . ) . } 180 ( 0.00%) hir::ItemKind::Impl(hir::Impl { defaultness, constness, .. }) => { 174 ( 0.00%) let trait_ref = self.tcx.impl_trait_ref(def_id); 90 ( 0.00%) let polarity = self.tcx.impl_polarity(def_id); 90 ( 0.00%) let parent = if let Some(trait_ref) = trait_ref { 42 ( 0.00%) let trait_def = self.tcx.trait_def(trait_ref.def_id); 252 ( 0.00%) trait_def.ancestors(self.tcx, def_id).ok().and_then(|mut an| { 252 ( 0.00%) an.nth(1).and_then(|node| match node { . specialization_graph::Node::Impl(parent) => Some(parent), . _ => None, . }) . }) . } else { . None . }; . . // if this is an impl of `CoerceUnsized`, create its . // "unsized info", else just store None . let coerce_unsized_info = trait_ref.and_then(|t| { 252 ( 0.00%) if Some(t.def_id) == self.tcx.lang_items().coerce_unsized_trait() { . Some(self.tcx.at(item.span).coerce_unsized_info(def_id)) . } else { . None . } . }); . . let data = ImplData { . polarity, -- line 1496 ---------------------------------------- -- line 1518 ---------------------------------------- . } . hir::ItemKind::TraitAlias(..) => EntryKind::TraitAlias, . hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => { . bug!("cannot encode info for item {:?}", item) . } . }; . record!(self.tables.kind[def_id] <- entry_kind); . // FIXME(eddyb) there should be a nicer way to do this. 290 ( 0.00%) match item.kind { . hir::ItemKind::Enum(..) => record!(self.tables.children[def_id] <- 6 ( 0.00%) self.tcx.adt_def(def_id).variants.iter().map(|v| { 55 ( 0.00%) assert!(v.def_id.is_local()); . v.def_id.index . }) . ), . hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => { . record!(self.tables.children[def_id] <- . self.tcx.adt_def(def_id).non_enum_variant().fields.iter().map(|f| { . assert!(f.did.is_local()); . f.did.index . }) . ) . } . hir::ItemKind::Impl { .. } | hir::ItemKind::Trait(..) => { 90 ( 0.00%) let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id); . record!(self.tables.children[def_id] <- . associated_item_def_ids.iter().map(|&def_id| { 54 ( 0.00%) assert!(def_id.is_local()); . def_id.index . }) . ); . } . _ => {} . } 164 ( 0.00%) match item.kind { . hir::ItemKind::Static(..) . | hir::ItemKind::Const(..) . | hir::ItemKind::Fn(..) . | hir::ItemKind::TyAlias(..) . | hir::ItemKind::OpaqueTy(..) . | hir::ItemKind::Enum(..) . | hir::ItemKind::Struct(..) . | hir::ItemKind::Union(..) 232 ( 0.00%) | hir::ItemKind::Impl { .. } => self.encode_item_type(def_id), . _ => {} . } 174 ( 0.00%) if let hir::ItemKind::Fn(..) = item.kind { . record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); . } 116 ( 0.00%) if let hir::ItemKind::Impl { .. } = item.kind { 225 ( 0.00%) if let Some(trait_ref) = self.tcx.impl_trait_ref(def_id) { 210 ( 0.00%) record!(self.tables.impl_trait_ref[def_id] <- trait_ref); . } . } 464 ( 0.00%) } . . fn encode_info_for_generic_param(&mut self, def_id: DefId, kind: EntryKind, encode_type: bool) { 9 ( 0.00%) record!(self.tables.kind[def_id] <- kind); 3 ( 0.00%) if encode_type { . self.encode_item_type(def_id); . } . } . . fn encode_info_for_closure(&mut self, hir_id: hir::HirId) { . let def_id = self.tcx.hir().local_def_id(hir_id); . debug!("EncodeContext::encode_info_for_closure({:?})", def_id); . -- line 1584 ---------------------------------------- -- line 1611 ---------------------------------------- . let const_data = self.encode_rendered_const_for_body(body_id); . let qualifs = self.tcx.mir_const_qualif(def_id); . . record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::AnonConst(qualifs, const_data)); . self.encode_item_type(def_id.to_def_id()); . } . . fn encode_native_libraries(&mut self) -> Lazy<[NativeLib]> { 2 ( 0.00%) empty_proc_macro!(self); 2 ( 0.00%) let used_libraries = self.tcx.native_libraries(LOCAL_CRATE); . self.lazy(used_libraries.iter()) . } . . fn encode_foreign_modules(&mut self) -> Lazy<[ForeignModule]> { 5 ( 0.00%) empty_proc_macro!(self); 2 ( 0.00%) let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE); . self.lazy(foreign_modules.iter().map(|(_, m)| m).cloned()) . } . . fn encode_hygiene(&mut self) -> (SyntaxContextTable, ExpnDataTable, ExpnHashTable) { . let mut syntax_contexts: TableBuilder<_, _> = Default::default(); . let mut expn_data_table: TableBuilder<_, _> = Default::default(); . let mut expn_hash_table: TableBuilder<_, _> = Default::default(); . 2 ( 0.00%) let _: Result<(), !> = self.hygiene_ctxt.encode( 8 ( 0.00%) &mut (&mut *self, &mut syntax_contexts, &mut expn_data_table, &mut expn_hash_table), . |(this, syntax_contexts, _, _), index, ctxt_data| { . syntax_contexts.set(index, this.lazy(ctxt_data)); . Ok(()) . }, . |(this, _, expn_data_table, expn_hash_table), index, expn_data, hash| { . if let Some(index) = index.as_local() { 9,190 ( 0.00%) expn_data_table.set(index.as_raw(), this.lazy(expn_data)); 9,190 ( 0.00%) expn_hash_table.set(index.as_raw(), this.lazy(hash)); . } . Ok(()) . }, . ); . . ( . syntax_contexts.encode(&mut self.opaque), . expn_data_table.encode(&mut self.opaque), . expn_hash_table.encode(&mut self.opaque), . ) . } . . fn encode_proc_macros(&mut self) -> Option { 6 ( 0.00%) let is_proc_macro = self.tcx.sess.crate_types().contains(&CrateType::ProcMacro); . if is_proc_macro { . let tcx = self.tcx; . let hir = tcx.hir(); . . let proc_macro_decls_static = tcx.proc_macro_decls_static(()).unwrap().local_def_index; . let stability = tcx.lookup_stability(DefId::local(CRATE_DEF_INDEX)).copied(); . let macros = . self.lazy(tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index)); -- line 1666 ---------------------------------------- -- line 1725 ---------------------------------------- . . Some(ProcMacroData { proc_macro_decls_static, stability, macros }) . } else { . None . } . } . . fn encode_crate_deps(&mut self) -> Lazy<[CrateDep]> { 7 ( 0.00%) empty_proc_macro!(self); . 1 ( 0.00%) let deps = self . .tcx . .crates(()) . .iter() . .map(|&cnum| { . let dep = CrateDep { 7 ( 0.00%) name: self.tcx.crate_name(cnum), 7 ( 0.00%) hash: self.tcx.crate_hash(cnum), 7 ( 0.00%) host_hash: self.tcx.crate_host_hash(cnum), 7 ( 0.00%) kind: self.tcx.dep_kind(cnum), 7 ( 0.00%) extra_filename: self.tcx.extra_filename(cnum), . }; 35 ( 0.00%) (cnum, dep) . }) . .collect::>(); . . { . // Sanity-check the crate numbers . let mut expected_cnum = 1; 14 ( 0.00%) for &(n, _) in &deps { 18 ( 0.00%) assert_eq!(n, CrateNum::new(expected_cnum)); . expected_cnum += 1; . } . } . . // We're just going to write a list of crate 'name-hash-version's, with . // the assumption that they are numbered 1 to n. . // FIXME (#2166): This is not nearly enough to support correct versioning . // but is enough to get transitive crate dependencies working. . self.lazy(deps.iter().map(|&(_, ref dep)| dep)) . } . . fn encode_lib_features(&mut self) -> Lazy<[(Symbol, Option)]> { 2 ( 0.00%) empty_proc_macro!(self); 1 ( 0.00%) let tcx = self.tcx; . let lib_features = tcx.lib_features(()); 2 ( 0.00%) self.lazy(lib_features.to_vec()) . } . . fn encode_diagnostic_items(&mut self) -> Lazy<[(Symbol, DefIndex)]> { 3 ( 0.00%) empty_proc_macro!(self); 1 ( 0.00%) let tcx = self.tcx; . let diagnostic_items = &tcx.diagnostic_items(LOCAL_CRATE).name_to_id; . self.lazy(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index))) . } . . fn encode_lang_items(&mut self) -> Lazy<[(DefIndex, usize)]> { 4 ( 0.00%) empty_proc_macro!(self); 1 ( 0.00%) let tcx = self.tcx; 1 ( 0.00%) let lang_items = tcx.lang_items(); 2 ( 0.00%) let lang_items = lang_items.items().iter(); . self.lazy(lang_items.enumerate().filter_map(|(i, &opt_def_id)| { 568 ( 0.00%) if let Some(def_id) = opt_def_id { . if def_id.is_local() { . return Some((def_id.index, i)); . } . } . None . })) . } . . fn encode_lang_items_missing(&mut self) -> Lazy<[lang_items::LangItem]> { 2 ( 0.00%) empty_proc_macro!(self); 1 ( 0.00%) let tcx = self.tcx; 1 ( 0.00%) self.lazy(&tcx.lang_items().missing) . } . . fn encode_traits(&mut self) -> Lazy<[DefIndex]> { 3 ( 0.00%) empty_proc_macro!(self); 1 ( 0.00%) self.lazy(self.tcx.traits_in_crate(LOCAL_CRATE).iter().map(|def_id| def_id.index)) . } . . /// Encodes an index, mapping each trait to its (local) implementations. . fn encode_impls(&mut self) -> Lazy<[TraitImpls]> { . debug!("EncodeContext::encode_traits_and_impls()"); 2 ( 0.00%) empty_proc_macro!(self); 2 ( 0.00%) let tcx = self.tcx; 5 ( 0.00%) let mut visitor = ImplsVisitor { tcx, impls: FxHashMap::default() }; 4 ( 0.00%) tcx.hir().visit_all_item_likes(&mut visitor); . . let mut all_impls: Vec<_> = visitor.impls.into_iter().collect(); . . // Bring everything into deterministic order for hashing 14 ( 0.00%) all_impls.sort_by_cached_key(|&(trait_def_id, _)| tcx.def_path_hash(trait_def_id)); . . let all_impls: Vec<_> = all_impls . .into_iter() 210 ( 0.00%) .map(|(trait_def_id, mut impls)| { . // Bring everything into deterministic order for hashing 14 ( 0.00%) impls.sort_by_cached_key(|&(index, _)| { 42 ( 0.00%) tcx.hir().def_path_hash(LocalDefId { local_def_index: index }) . }); . 56 ( 0.00%) TraitImpls { . trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index), 42 ( 0.00%) impls: self.lazy(&impls), . } 112 ( 0.00%) }) . .collect(); . . self.lazy(&all_impls) . } . . // Encodes all symbols exported from this crate into the metadata. . // . // This pass is seeded off the reachability list calculated in the . // middle::reachable module but filters out items that either don't have a . // symbol associated with them (they weren't translated) or if they're an FFI . // definition (as that's not defined in this crate). . fn encode_exported_symbols( . &mut self, . exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportLevel)], . ) -> Lazy<[(ExportedSymbol<'tcx>, SymbolExportLevel)]> { 2 ( 0.00%) empty_proc_macro!(self); . // The metadata symbol name is special. It should not show up in . // downstream crates. 9 ( 0.00%) let metadata_symbol_name = SymbolName::new(self.tcx, &metadata_symbol_name(self.tcx)); . . self.lazy( . exported_symbols . .iter() . .filter(|&&(ref exported_symbol, _)| match *exported_symbol { . ExportedSymbol::NoDefId(symbol_name) => symbol_name != metadata_symbol_name, . _ => true, . }) . .cloned(), . ) . } . . fn encode_dylib_dependency_formats(&mut self) -> Lazy<[Option]> { 2 ( 0.00%) empty_proc_macro!(self); 2 ( 0.00%) let formats = self.tcx.dependency_formats(()); 4 ( 0.00%) for (ty, arr) in formats.iter() { 2 ( 0.00%) if *ty != CrateType::Dylib { . continue; . } . return self.lazy(arr.iter().map(|slot| match *slot { . Linkage::NotLinked | Linkage::IncludedFromDylib => None, . . Linkage::Dynamic => Some(LinkagePreference::RequireDynamic), . Linkage::Static => Some(LinkagePreference::RequireStatic), . })); -- line 1876 ---------------------------------------- -- line 1914 ---------------------------------------- . } . } . . // FIXME(eddyb) make metadata encoding walk over all definitions, instead of HIR. . impl<'a, 'tcx> Visitor<'tcx> for EncodeContext<'a, 'tcx> { . type NestedFilter = nested_filter::OnlyBodies; . . fn nested_visit_map(&mut self) -> Self::Map { 61 ( 0.00%) self.tcx.hir() . } 222,183 ( 0.01%) fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) { 24,687 ( 0.00%) intravisit::walk_expr(self, ex); . self.encode_info_for_expr(ex); 197,496 ( 0.01%) } . fn visit_anon_const(&mut self, c: &'tcx AnonConst) { . intravisit::walk_anon_const(self, c); . self.encode_info_for_anon_const(c.hir_id); . } . fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { 939 ( 0.00%) intravisit::walk_item(self, item); 626 ( 0.00%) match item.kind { . hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {} // ignore these 284 ( 0.00%) _ => self.encode_info_for_item(item.def_id.to_def_id(), item), . } 1,252 ( 0.00%) self.encode_addl_info_for_item(item); . } . fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem<'tcx>) { . intravisit::walk_foreign_item(self, ni); . self.encode_info_for_foreign_item(ni.def_id.to_def_id(), ni); . } 918 ( 0.00%) fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) { . intravisit::walk_generics(self, generics); . self.encode_info_for_generics(generics); 816 ( 0.00%) } . } . . impl<'a, 'tcx> EncodeContext<'a, 'tcx> { 21 ( 0.00%) fn encode_fields(&mut self, adt_def: &ty::AdtDef) { . for (variant_index, variant) in adt_def.variants.iter_enumerated() { . for (field_index, _field) in variant.fields.iter().enumerate() { . self.encode_field(adt_def, variant_index, field_index); . } . } 24 ( 0.00%) } . . fn encode_info_for_generics(&mut self, generics: &hir::Generics<'tcx>) { . for param in generics.params { 18 ( 0.00%) let def_id = self.tcx.hir().local_def_id(param.hir_id); 27 ( 0.00%) match param.kind { . GenericParamKind::Lifetime { .. } => continue, . GenericParamKind::Type { default, .. } => { . self.encode_info_for_generic_param( . def_id.to_def_id(), . EntryKind::TypeParam, . default.is_some(), . ); . } -- line 1970 ---------------------------------------- -- line 1975 ---------------------------------------- . record!(self.tables.const_defaults[def_id] <- self.tcx.const_param_default(def_id)) . } . } . } . } . } . . fn encode_info_for_expr(&mut self, expr: &hir::Expr<'_>) { 49,374 ( 0.00%) if let hir::ExprKind::Closure(..) = expr.kind { . self.encode_info_for_closure(expr.hir_id); . } . } . . fn encode_ident_span(&mut self, def_id: DefId, ident: Ident) { . record!(self.tables.ident_span[def_id] <- ident.span); . } . . /// In some cases, along with the item itself, we also . /// encode some sub-items. Usually we want some info from the item . /// so it's easier to do that here then to wait until we would encounter . /// normally in the visitor walk. 2,817 ( 0.00%) fn encode_addl_info_for_item(&mut self, item: &hir::Item<'_>) { 1,565 ( 0.00%) match item.kind { . hir::ItemKind::Static(..) . | hir::ItemKind::Const(..) . | hir::ItemKind::Fn(..) . | hir::ItemKind::Macro(..) . | hir::ItemKind::Mod(..) . | hir::ItemKind::ForeignMod { .. } . | hir::ItemKind::GlobalAsm(..) . | hir::ItemKind::ExternCrate(..) . | hir::ItemKind::Use(..) . | hir::ItemKind::TyAlias(..) . | hir::ItemKind::OpaqueTy(..) . | hir::ItemKind::TraitAlias(..) => { . // no sub-item recording needed in these cases . } . hir::ItemKind::Enum(..) => { 3 ( 0.00%) let def = self.tcx.adt_def(item.def_id.to_def_id()); 6 ( 0.00%) self.encode_fields(def); . . for (i, variant) in def.variants.iter_enumerated() { . self.encode_enum_variant_info(def, i); . 165 ( 0.00%) if let Some(_ctor_def_id) = variant.ctor_def_id { . self.encode_enum_variant_ctor(def, i); . } . } . } . hir::ItemKind::Struct(ref struct_def, _) => { . let def = self.tcx.adt_def(item.def_id.to_def_id()); . self.encode_fields(def); . -- line 2027 ---------------------------------------- -- line 2031 ---------------------------------------- . self.encode_struct_ctor(def, ctor_def_id.to_def_id()); . } . } . hir::ItemKind::Union(..) => { . let def = self.tcx.adt_def(item.def_id.to_def_id()); . self.encode_fields(def); . } . hir::ItemKind::Impl { .. } => { 216 ( 0.00%) for &trait_item_def_id in 45 ( 0.00%) self.tcx.associated_item_def_ids(item.def_id.to_def_id()).iter() . { . self.encode_info_for_impl_item(trait_item_def_id); . } . } . hir::ItemKind::Trait(..) => { . for &item_def_id in self.tcx.associated_item_def_ids(item.def_id.to_def_id()).iter() . { . self.encode_info_for_trait_item(item_def_id); . } . } . } 2,504 ( 0.00%) } . } . . struct ImplsVisitor<'tcx> { . tcx: TyCtxt<'tcx>, . impls: FxHashMap)>>, . } . . impl<'tcx, 'v> ItemLikeVisitor<'v> for ImplsVisitor<'tcx> { 2,191 ( 0.00%) fn visit_item(&mut self, item: &hir::Item<'_>) { 626 ( 0.00%) match item.kind { . hir::ItemKind::Impl(..) => { 174 ( 0.00%) if let Some(trait_ref) = self.tcx.impl_trait_ref(item.def_id.to_def_id()) { 252 ( 0.00%) let simplified_self_ty = fast_reject::simplify_type( . self.tcx, . trait_ref.self_ty(), . SimplifyParams::No, . StripReferences::No, . ); . . self.impls . .entry(trait_ref.def_id) . .or_default() . .push((item.def_id.local_def_index, simplified_self_ty)); . } . } . _ => {} . } 2,504 ( 0.00%) } . . fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem<'v>) {} . . fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem<'v>) { . // handled in `visit_item` above . } . . fn visit_foreign_item(&mut self, _foreign_item: &'v hir::ForeignItem<'v>) {} -- line 2088 ---------------------------------------- -- line 2146 ---------------------------------------- . } . . #[inline] . pub fn raw_data(&self) -> &[u8] { . &self.raw_data . } . } . 10 ( 0.00%) pub fn encode_metadata(tcx: TyCtxt<'_>) -> EncodedMetadata { 5 ( 0.00%) let _prof_timer = tcx.prof.verbose_generic_activity("generate_crate_metadata"); . . // Since encoding metadata is not in a query, and nothing is cached, . // there's no need to do dep-graph tracking for any of it. . tcx.dep_graph.assert_ignored(); . 7 ( 0.00%) join( 3 ( 0.00%) || encode_metadata_impl(tcx), . || { 5 ( 0.00%) if tcx.sess.threads() == 1 { . return; . } . // Prefetch some queries used by metadata encoding. . // This is not necessary for correctness, but is only done for performance reasons. . // It can be removed if it turns out to cause trouble or be detrimental to performance. . join(|| prefetch_mir(tcx), || tcx.exported_symbols(LOCAL_CRATE)); . }, . ) . .0 9 ( 0.00%) } . 9 ( 0.00%) fn encode_metadata_impl(tcx: TyCtxt<'_>) -> EncodedMetadata { 1 ( 0.00%) let mut encoder = opaque::Encoder::new(vec![]); . encoder.emit_raw_bytes(METADATA_HEADER).unwrap(); . . // Will be filled with the root position after encoding everything. . encoder.emit_raw_bytes(&[0, 0, 0, 0]).unwrap(); . 2 ( 0.00%) let source_map_files = tcx.sess.source_map().files(); 3 ( 0.00%) let source_file_cache = (source_map_files[0].clone(), 0); 2 ( 0.00%) let required_source_files = Some(GrowableBitSet::with_capacity(source_map_files.len())); . drop(source_map_files); . . let hygiene_ctxt = HygieneEncodeContext::default(); . 35 ( 0.00%) let mut ecx = EncodeContext { 4 ( 0.00%) opaque: encoder, . tcx, 2 ( 0.00%) feat: tcx.features(), . tables: Default::default(), . lazy_state: LazyState::NoNode, . type_shorthands: Default::default(), . predicate_shorthands: Default::default(), 4 ( 0.00%) source_file_cache, . interpret_allocs: Default::default(), 4 ( 0.00%) required_source_files, 2 ( 0.00%) is_proc_macro: tcx.sess.crate_types().contains(&CrateType::ProcMacro), . hygiene_ctxt: &hygiene_ctxt, . }; . . // Encode the rustc version string in a predictable location. . rustc_version().encode(&mut ecx).unwrap(); . . // Encode all the entries and extra information in the crate, . // culminating in the `CrateRoot` which points to all of it. 1 ( 0.00%) let root = ecx.encode_crate_root(); . 7 ( 0.00%) let mut result = ecx.opaque.into_inner(); . . // Encode the root position. . let header = METADATA_HEADER.len(); . let pos = root.position.get(); 3 ( 0.00%) result[header + 0] = (pos >> 24) as u8; 3 ( 0.00%) result[header + 1] = (pos >> 16) as u8; 1 ( 0.00%) result[header + 2] = (pos >> 8) as u8; 5 ( 0.00%) result[header + 3] = (pos >> 0) as u8; . . // Record metadata size for self-profiling . tcx.prof.artifact_size("crate_metadata", "crate_metadata", result.len() as u64); . 5 ( 0.00%) EncodedMetadata { raw_data: result } 12 ( 0.00%) } . . pub fn provide(providers: &mut Providers) { 2 ( 0.00%) *providers = Providers { . traits_in_crate: |tcx, cnum| { 1 ( 0.00%) assert_eq!(cnum, LOCAL_CRATE); . 1 ( 0.00%) #[derive(Default)] . struct TraitsVisitor { . traits: Vec, . } . impl ItemLikeVisitor<'_> for TraitsVisitor { . fn visit_item(&mut self, item: &hir::Item<'_>) { 1,252 ( 0.00%) if let hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) = item.kind { . self.traits.push(item.def_id.to_def_id()); . } . } . fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem<'_>) {} . fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem<'_>) {} . fn visit_foreign_item(&mut self, _foreign_item: &hir::ForeignItem<'_>) {} . } . . let mut visitor = TraitsVisitor::default(); 4 ( 0.00%) tcx.hir().visit_all_item_likes(&mut visitor); . // Bring everything into deterministic order. . visitor.traits.sort_by_cached_key(|&def_id| tcx.def_path_hash(def_id)); . tcx.arena.alloc_slice(&visitor.traits) . }, . . ..*providers . }; . } -- line 2257 ---------------------------------------- 159,907 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/util.rs -------------------------------------------------------------------------------- Ir -- line 41 ---------------------------------------- . write!(fmt, "{}", x) . } . _ => write!(fmt, "{}", self.val), . } . } . } . . fn int_size_and_signed<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> (Size, bool) { 333,726 ( 0.02%) let (int, signed) = match *ty.kind() { 778,694 ( 0.04%) Int(ity) => (Integer::from_int_ty(&tcx, ity), true), . Uint(uty) => (Integer::from_uint_ty(&tcx, uty), false), . _ => bug!("non integer discriminant"), . }; . (int.size(), signed) . } . . impl<'tcx> Discr<'tcx> { . /// Adds `1` to the value and wraps around if the maximum for the type is reached. 532,355 ( 0.03%) pub fn wrap_incr(self, tcx: TyCtxt<'tcx>) -> Self { 746,260 ( 0.04%) self.checked_add(tcx, 1).0 212,942 ( 0.01%) } 1,001,178 ( 0.05%) pub fn checked_add(self, tcx: TyCtxt<'tcx>, n: u128) -> (Self, bool) { . let (size, signed) = int_size_and_signed(tcx, self.ty); . let (val, oflo) = if signed { . let min = size.signed_int_min(); . let max = size.signed_int_max(); . let val = size.sign_extend(self.val) as i128; 444,968 ( 0.02%) assert!(n < (i128::MAX as u128)); . let n = n as i128; 778,694 ( 0.04%) let oflo = val > max - n; 444,968 ( 0.02%) let val = if oflo { min + (n - (max - val) - 1) } else { val + n }; . // zero the upper bits . let val = val as u128; . let val = size.truncate(val); . (val, oflo) . } else { . let max = size.unsigned_int_max(); . let val = self.val; . let oflo = val > max - n; . let val = if oflo { n - (max - val) - 1 } else { val + n }; . (val, oflo) . }; 444,968 ( 0.02%) (Self { val, ty: self.ty }, oflo) 1,001,178 ( 0.05%) } . } . . pub trait IntTypeExt { . fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx>; . fn disr_incr<'tcx>(&self, tcx: TyCtxt<'tcx>, val: Option>) -> Option>; . fn initial_discriminant<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Discr<'tcx>; . } . . impl IntTypeExt for attr::IntType { . fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { 162,115 ( 0.01%) match *self { . SignedInt(ast::IntTy::I8) => tcx.types.i8, . SignedInt(ast::IntTy::I16) => tcx.types.i16, . SignedInt(ast::IntTy::I32) => tcx.types.i32, . SignedInt(ast::IntTy::I64) => tcx.types.i64, . SignedInt(ast::IntTy::I128) => tcx.types.i128, . SignedInt(ast::IntTy::Isize) => tcx.types.isize, . UnsignedInt(ast::UintTy::U8) => tcx.types.u8, . UnsignedInt(ast::UintTy::U16) => tcx.types.u16, . UnsignedInt(ast::UintTy::U32) => tcx.types.u32, . UnsignedInt(ast::UintTy::U64) => tcx.types.u64, . UnsignedInt(ast::UintTy::U128) => tcx.types.u128, . UnsignedInt(ast::UintTy::Usize) => tcx.types.usize, . } 13,884 ( 0.00%) } . . fn initial_discriminant<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Discr<'tcx> { . Discr { val: 0, ty: self.to_ty(tcx) } 55,425 ( 0.00%) } . 110 ( 0.00%) fn disr_incr<'tcx>(&self, tcx: TyCtxt<'tcx>, val: Option>) -> Option> { 266 ( 0.00%) if let Some(val) = val { 104 ( 0.00%) assert_eq!(self.to_ty(tcx), val.ty); 468 ( 0.00%) let (new, oflo) = val.checked_add(tcx, 1); 52 ( 0.00%) if oflo { None } else { Some(new) } . } else { . Some(self.initial_discriminant(tcx)) . } 110 ( 0.00%) } . } . . impl<'tcx> TyCtxt<'tcx> { . /// Creates a hash of the type `Ty` which will be the same no matter what crate . /// context it's calculated within. This is used by the `type_id` intrinsic. . pub fn type_id_hash(self, ty: Ty<'tcx>) -> u64 { . let mut hasher = StableHasher::new(); . let mut hcx = self.create_stable_hashing_context(); -- line 131 ---------------------------------------- -- line 138 ---------------------------------------- . hcx.while_hashing_spans(false, |hcx| { . hcx.with_node_id_hashing_mode(NodeIdHashingMode::HashDefPath, |hcx| { . ty.hash_stable(hcx, &mut hasher); . }); . }); . hasher.finish() . } . 21 ( 0.00%) pub fn has_error_field(self, ty: Ty<'tcx>) -> bool { 12 ( 0.00%) if let ty::Adt(def, substs) = *ty.kind() { . for field in def.all_fields() { . let field_ty = field.ty(self, substs); . if let Error(_) = field_ty.kind() { . return true; . } . } . } . false 24 ( 0.00%) } . . /// Attempts to returns the deeply last field of nested structures, but . /// does not apply any normalization in its search. Returns the same type . /// if input `ty` is not a structure at all. 4,338 ( 0.00%) pub fn struct_tail_without_normalization(self, ty: Ty<'tcx>) -> Ty<'tcx> { . let tcx = self; . tcx.struct_tail_with_normalize(ty, |ty| ty) 3,856 ( 0.00%) } . . /// Returns the deeply last field of nested structures, or the same type if . /// not a structure at all. Corresponds to the only possible unsized field, . /// and its type can be used to determine unsizing strategy. . /// . /// Should only be called if `ty` has no inference variables and does not . /// need its lifetimes preserved (e.g. as part of codegen); otherwise . /// normalization attempt may cause compiler bugs. 407 ( 0.00%) pub fn struct_tail_erasing_lifetimes( . self, . ty: Ty<'tcx>, . param_env: ty::ParamEnv<'tcx>, . ) -> Ty<'tcx> { . let tcx = self; . tcx.struct_tail_with_normalize(ty, |ty| tcx.normalize_erasing_regions(param_env, ty)) 333 ( 0.00%) } . . /// Returns the deeply last field of nested structures, or the same type if . /// not a structure at all. Corresponds to the only possible unsized field, . /// and its type can be used to determine unsizing strategy. . /// . /// This is parameterized over the normalization strategy (i.e. how to . /// handle `::Assoc` and `impl Trait`); pass the identity . /// function to indicate no normalization should take place. -- line 188 ---------------------------------------- -- line 189 ---------------------------------------- . /// . /// See also `struct_tail_erasing_lifetimes`, which is suitable for use . /// during codegen. . pub fn struct_tail_with_normalize( . self, . mut ty: Ty<'tcx>, . mut normalize: impl FnMut(Ty<'tcx>) -> Ty<'tcx>, . ) -> Ty<'tcx> { 2,595 ( 0.00%) let recursion_limit = self.recursion_limit(); . for iteration in 0.. { 519 ( 0.00%) if !recursion_limit.value_within_limit(iteration) { . return self.ty_error_with_message( . DUMMY_SP, . &format!("reached the recursion limit finding the struct tail for {}", ty), . ); . } 2,266 ( 0.00%) match *ty.kind() { 220 ( 0.00%) ty::Adt(def, substs) => { 440 ( 0.00%) if !def.is_struct() { . break; . } . match def.non_enum_variant().fields.last() { . Some(f) => ty = f.ty(self, substs), . None => break, . } . } . 3 ( 0.00%) ty::Tuple(tys) if let Some((&last_ty, _)) = tys.split_last() => { . ty = last_ty.expect_ty(); . } . . ty::Tuple(_) => break, . . ty::Projection(_) | ty::Opaque(..) => { . let normalized = normalize(ty); . if ty == normalized { -- line 224 ---------------------------------------- -- line 240 ---------------------------------------- . /// keeps going as long as the two types are instances of the same . /// structure definitions. . /// For `(Foo>, Foo)`, the result will be `(Foo, Trait)`, . /// whereas struct_tail produces `T`, and `Trait`, respectively. . /// . /// Should only be called if the types have no inference variables and do . /// not need their lifetimes preserved (e.g., as part of codegen); otherwise, . /// normalization attempt may cause compiler bugs. 90 ( 0.00%) pub fn struct_lockstep_tails_erasing_lifetimes( . self, . source: Ty<'tcx>, . target: Ty<'tcx>, . param_env: ty::ParamEnv<'tcx>, . ) -> (Ty<'tcx>, Ty<'tcx>) { . let tcx = self; . tcx.struct_lockstep_tails_with_normalize(source, target, |ty| { . tcx.normalize_erasing_regions(param_env, ty) . }) 60 ( 0.00%) } . . /// Same as applying `struct_tail` on `source` and `target`, but only . /// keeps going as long as the two types are instances of the same . /// structure definitions. . /// For `(Foo>, Foo)`, the result will be `(Foo, Trait)`, . /// whereas struct_tail produces `T`, and `Trait`, respectively. . /// . /// See also `struct_lockstep_tails_erasing_lifetimes`, which is suitable for use -- line 266 ---------------------------------------- -- line 268 ---------------------------------------- . pub fn struct_lockstep_tails_with_normalize( . self, . source: Ty<'tcx>, . target: Ty<'tcx>, . normalize: impl Fn(Ty<'tcx>) -> Ty<'tcx>, . ) -> (Ty<'tcx>, Ty<'tcx>) { . let (mut a, mut b) = (source, target); . loop { 72 ( 0.00%) match (&a.kind(), &b.kind()) { . (&Adt(a_def, a_substs), &Adt(b_def, b_substs)) . if a_def == b_def && a_def.is_struct() => . { . if let Some(f) = a_def.non_enum_variant().fields.last() { . a = f.ty(self, a_substs); . b = f.ty(self, b_substs); . } else { . break; -- line 284 ---------------------------------------- -- line 310 ---------------------------------------- . . _ => break, . } . } . (a, b) . } . . /// Calculate the destructor of a given type. 96 ( 0.00%) pub fn calculate_dtor( . self, . adt_did: DefId, . validate: impl Fn(Self, DefId) -> Result<(), ErrorReported>, . ) -> Option { 40 ( 0.00%) let drop_trait = self.lang_items().drop_trait()?; . self.ensure().coherent_trait(drop_trait); . 8 ( 0.00%) let ty = self.type_of(adt_did); 72 ( 0.00%) let (did, constness) = self.find_map_relevant_impl(drop_trait, ty, |impl_did| { . if let Some(item_id) = self.associated_item_def_ids(impl_did).first() { . if validate(self, impl_did).is_ok() { . return Some((*item_id, self.impl_constness(impl_did))); . } . } . None . })?; . . Some(ty::Destructor { did, constness }) 80 ( 0.00%) } . . /// Returns the set of types that are required to be alive in . /// order to run the destructor of `def` (see RFCs 769 and . /// 1238). . /// . /// Note that this returns only the constraints for the . /// destructor of `def` itself. For the destructors of the . /// contents, you need `adt_dtorck_constraint`. 88 ( 0.00%) pub fn destructor_constraints(self, def: &'tcx ty::AdtDef) -> Vec> { 40 ( 0.00%) let dtor = match def.destructor(self) { . None => { . debug!("destructor_constraints({:?}) - no dtor", def.did); . return vec![]; . } . Some(dtor) => dtor.did, . }; . . let impl_def_id = self.associated_item(dtor).container.id(); -- line 355 ---------------------------------------- -- line 406 ---------------------------------------- . false . } . } . }) . .map(|(item_param, _)| item_param) . .collect(); . debug!("destructor_constraint({:?}) = {:?}", def.did, result); . result 80 ( 0.00%) } . . /// Returns `true` if `def_id` refers to a closure (e.g., `|x| x * 2`). Note . /// that closures have a `DefId`, but the closure *expression* also . /// has a `HirId` that is located within the context where the . /// closure appears (and, sadly, a corresponding `NodeId`, since . /// those are not yet phased out). The parent of the closure's . /// `DefId` will also be the context where it appears. 199 ( 0.00%) pub fn is_closure(self, def_id: DefId) -> bool { 995 ( 0.00%) matches!(self.def_kind(def_id), DefKind::Closure | DefKind::Generator) 398 ( 0.00%) } . . /// Returns `true` if `def_id` refers to a definition that does not have its own . /// type-checking context, i.e. closure, generator or inline const. 122 ( 0.00%) pub fn is_typeck_child(self, def_id: DefId) -> bool { 1,952 ( 0.00%) matches!( 2,074 ( 0.00%) self.def_kind(def_id), . DefKind::Closure | DefKind::Generator | DefKind::InlineConst . ) 244 ( 0.00%) } . . /// Returns `true` if `def_id` refers to a trait (i.e., `trait Foo { ... }`). 492 ( 0.00%) pub fn is_trait(self, def_id: DefId) -> bool { 492 ( 0.00%) self.def_kind(def_id) == DefKind::Trait 984 ( 0.00%) } . . /// Returns `true` if `def_id` refers to a trait alias (i.e., `trait Foo = ...;`), . /// and `false` otherwise. 252 ( 0.00%) pub fn is_trait_alias(self, def_id: DefId) -> bool { 252 ( 0.00%) self.def_kind(def_id) == DefKind::TraitAlias 504 ( 0.00%) } . . /// Returns `true` if this `DefId` refers to the implicit constructor for . /// a tuple struct like `struct Foo(u32)`, and `false` otherwise. 20 ( 0.00%) pub fn is_constructor(self, def_id: DefId) -> bool { 1,080 ( 0.00%) matches!(self.def_kind(def_id), DefKind::Ctor(..)) 40 ( 0.00%) } . . /// Given the `DefId`, returns the `DefId` of the innermost item that . /// has its own type-checking context or "inference enviornment". . /// . /// For example, a closure has its own `DefId`, but it is type-checked . /// with the containing item. Similarly, an inline const block has its . /// own `DefId` but it is type-checked together with the containing item. . /// . /// Therefore, when we fetch the . /// `typeck` the closure, for example, we really wind up . /// fetching the `typeck` the enclosing fn item. 4,880 ( 0.00%) pub fn typeck_root_def_id(self, def_id: DefId) -> DefId { . let mut def_id = def_id; . while self.is_typeck_child(def_id) { . def_id = self.parent(def_id).unwrap_or_else(|| { . bug!("closure {:?} has no parent", def_id); . }); . } . def_id 3,904 ( 0.00%) } . . /// Given the `DefId` and substs a closure, creates the type of . /// `self` argument that the closure expects. For example, for a . /// `Fn` closure, this would return a reference type `&T` where . /// `T = closure_ty`. . /// . /// Returns `None` if this closure's kind has not yet been inferred. . /// This should only be possible during type checking. -- line 478 ---------------------------------------- -- line 492 ---------------------------------------- . ty::ClosureKind::Fn => self.mk_imm_ref(self.mk_region(env_region), closure_ty), . ty::ClosureKind::FnMut => self.mk_mut_ref(self.mk_region(env_region), closure_ty), . ty::ClosureKind::FnOnce => closure_ty, . }; . Some(env_ty) . } . . /// Returns `true` if the node pointed to by `def_id` is a `static` item. 336 ( 0.00%) pub fn is_static(self, def_id: DefId) -> bool { . self.static_mutability(def_id).is_some() 384 ( 0.00%) } . . /// Returns `true` if this is a `static` item with the `#[thread_local]` attribute. . pub fn is_thread_local_static(self, def_id: DefId) -> bool { . self.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::THREAD_LOCAL) . } . . /// Returns `true` if the node pointed to by `def_id` is a mutable `static` item. . pub fn is_mutable_static(self, def_id: DefId) -> bool { -- line 510 ---------------------------------------- -- line 597 ---------------------------------------- . self.found_recursion = def_id == *self.primary_def_id.as_ref().unwrap(); . None . } . } . } . . impl<'tcx> TypeFolder<'tcx> for OpaqueTypeExpander<'tcx> { . fn tcx(&self) -> TyCtxt<'tcx> { 2 ( 0.00%) self.tcx . } . . fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { 4 ( 0.00%) if let ty::Opaque(def_id, substs) = t.kind { . self.expand_opaque_ty(def_id, substs).unwrap_or(t) 2 ( 0.00%) } else if t.has_opaque_types() { . t.super_fold_with(self) . } else { . t . } . } . } . . impl<'tcx> ty::TyS<'tcx> { -- line 619 ---------------------------------------- -- line 658 ---------------------------------------- . . /// Checks whether values of this type `T` are *moved* or *copied* . /// when referenced -- this amounts to a check for whether `T: . /// Copy`, but note that we **don't** consider lifetimes when . /// doing this check. This means that we may generate MIR which . /// does copies even when the type actually doesn't satisfy the . /// full requirements for the `Copy` trait (cc #29149) -- this . /// winds up being reported as an error during NLL borrow check. 740 ( 0.00%) pub fn is_copy_modulo_regions( . &'tcx self, . tcx_at: TyCtxtAt<'tcx>, . param_env: ty::ParamEnv<'tcx>, . ) -> bool { . tcx_at.is_copy_raw(param_env.and(self)) 592 ( 0.00%) } . . /// Checks whether values of this type `T` have a size known at . /// compile time (i.e., whether `T: Sized`). Lifetimes are ignored . /// for the purposes of this check, so it can be an . /// over-approximation in generic contexts, where one can have . /// strange rules like `>::Bar: Sized` that . /// actually carry lifetime requirements. 258,687 ( 0.01%) pub fn is_sized(&'tcx self, tcx_at: TyCtxtAt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool { 143,715 ( 0.01%) self.is_trivially_sized(tcx_at.tcx) || tcx_at.is_sized_raw(param_env.and(self)) 172,458 ( 0.01%) } . . /// Checks whether values of this type `T` implement the `Freeze` . /// trait -- frozen types are those that do not contain an . /// `UnsafeCell` anywhere. This is a language concept used to . /// distinguish "true immutability", which is relevant to . /// optimization as well as the rules around static values. Note . /// that the `Freeze` trait is not exposed to end users and is . /// effectively an implementation detail. 247,599 ( 0.01%) pub fn is_freeze(&'tcx self, tcx_at: TyCtxtAt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool { 137,555 ( 0.01%) self.is_trivially_freeze() || tcx_at.is_freeze_raw(param_env.and(self)) 165,066 ( 0.01%) } . . /// Fast path helper for testing if a type is `Freeze`. . /// . /// Returning true means the type is known to be `Freeze`. Returning . /// `false` means nothing -- could be `Freeze`, might not be. . fn is_trivially_freeze(&self) -> bool { . match self.kind() { . ty::Int(_) -- line 701 ---------------------------------------- -- line 731 ---------------------------------------- . pub fn is_unpin(&'tcx self, tcx_at: TyCtxtAt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool { . self.is_trivially_unpin() || tcx_at.is_unpin_raw(param_env.and(self)) . } . . /// Fast path helper for testing if a type is `Unpin`. . /// . /// Returning true means the type is known to be `Unpin`. Returning . /// `false` means nothing -- could be `Unpin`, might not be. 137,600 ( 0.01%) fn is_trivially_unpin(&self) -> bool { 137,660 ( 0.01%) match self.kind() { . ty::Int(_) . | ty::Uint(_) . | ty::Float(_) . | ty::Bool . | ty::Char . | ty::Str . | ty::Never . | ty::Ref(..) . | ty::RawPtr(_) . | ty::FnDef(..) . | ty::Error(_) . | ty::FnPtr(_) => true, . ty::Tuple(_) => self.tuple_fields().all(Self::is_trivially_unpin), 24 ( 0.00%) ty::Slice(elem_ty) | ty::Array(elem_ty, _) => elem_ty.is_trivially_unpin(), . ty::Adt(..) . | ty::Bound(..) . | ty::Closure(..) . | ty::Dynamic(..) . | ty::Foreign(_) . | ty::Generator(..) . | ty::GeneratorWitness(_) . | ty::Infer(_) . | ty::Opaque(..) . | ty::Param(_) . | ty::Placeholder(_) . | ty::Projection(_) => false, . } 192,640 ( 0.01%) } . . /// If `ty.needs_drop(...)` returns `true`, then `ty` is definitely . /// non-copy and *might* have a destructor attached; if it returns . /// `false`, then `ty` definitely has no destructor (i.e., no drop glue). . /// . /// (Note that this implies that if `ty` has a destructor attached, . /// then `needs_drop` will definitely return `true` for `ty`.) . /// . /// Note that this method is used to check eligible types in unions. . #[inline] 148,110 ( 0.01%) pub fn needs_drop(&'tcx self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool { . // Avoid querying in simple cases. 158,385 ( 0.01%) match needs_drop_components(self, &tcx.data_layout) { . Err(AlwaysRequiresDrop) => true, 95,716 ( 0.00%) Ok(components) => { . let query_ty = match *components { 75,752 ( 0.00%) [] => return false, . // If we've got a single component, call the query with that . // to increase the chance that we hit the query cache. 9,390 ( 0.00%) [component_ty] => component_ty, . _ => self, . }; . . // This doesn't depend on regions, so try to minimize distinct . // query keys used. . // If normalization fails, we just use `query_ty`. . let query_ty = . tcx.try_normalize_erasing_regions(param_env, query_ty).unwrap_or(query_ty); . . tcx.needs_drop_raw(param_env.and(query_ty)) . } . } 133,299 ( 0.01%) } . . /// Checks if `ty` has has a significant drop. . /// . /// Note that this method can return false even if `ty` has a destructor . /// attached; even if that is the case then the adt has been marked with . /// the attribute `rustc_insignificant_dtor`. . /// . /// Note that this method is used to check for change in drop order for -- line 809 ---------------------------------------- -- line 854 ---------------------------------------- . /// . /// This function is "shallow" because it may return `true` for a composite type whose fields . /// are not `StructuralEq`. For example, `[T; 4]` has structural equality regardless of `T` . /// because equality for arrays is determined by the equality of each array element. If you . /// want to know whether a given call to `PartialEq::eq` will proceed structurally all the way . /// down, you will need to use a type visitor. . #[inline] . pub fn is_structural_eq_shallow(&'tcx self, tcx: TyCtxt<'tcx>) -> bool { 109,360 ( 0.01%) match self.kind() { . // Look for an impl of both `PartialStructuralEq` and `StructuralEq`. . Adt(..) => tcx.has_structural_eq_impls(self), . . // Primitive types that satisfy `Eq`. . Bool | Char | Int(_) | Uint(_) | Str | Never => true, . . // Composite types that satisfy `Eq` when all of their fields do. . // -- line 870 ---------------------------------------- -- line 911 ---------------------------------------- . /// This method is idempotent, i.e. `ty.peel_refs().peel_refs() == ty.peel_refs()`. . /// . /// # Examples . /// . /// - `u8` -> `u8` . /// - `&'a mut u8` -> `u8` . /// - `&'a &'b u8` -> `u8` . /// - `&'a *const &'b u8 -> *const &'b u8` 164 ( 0.00%) pub fn peel_refs(&'tcx self) -> Ty<'tcx> { . let mut ty = self; 784 ( 0.00%) while let Ref(_, inner_ty, _) = ty.kind() { 152 ( 0.00%) ty = inner_ty; . } . ty 164 ( 0.00%) } . . pub fn outer_exclusive_binder(&'tcx self) -> DebruijnIndex { 7 ( 0.00%) self.outer_exclusive_binder 7 ( 0.00%) } . } . . pub enum ExplicitSelf<'tcx> { . ByValue, . ByReference(ty::Region<'tcx>, hir::Mutability), . ByRawPointer(hir::Mutability), . ByBox, . Other, -- line 937 ---------------------------------------- -- line 976 ---------------------------------------- . _ => Other, . } . } . } . . /// Returns a list of types such that the given type needs drop if and only if . /// *any* of the returned types need drop. Returns `Err(AlwaysRequiresDrop)` if . /// this type always needs drop. 231,609 ( 0.01%) pub fn needs_drop_components<'tcx>( . ty: Ty<'tcx>, . target_layout: &TargetDataLayout, . ) -> Result; 2]>, AlwaysRequiresDrop> { 198,522 ( 0.01%) match ty.kind() { . ty::Infer(ty::FreshIntTy(_)) . | ty::Infer(ty::FreshFloatTy(_)) . | ty::Bool . | ty::Int(_) . | ty::Uint(_) . | ty::Float(_) . | ty::Never . | ty::FnDef(..) -- line 996 ---------------------------------------- -- line 1003 ---------------------------------------- . . // Foreign types can never have destructors. . ty::Foreign(..) => Ok(SmallVec::new()), . . ty::Dynamic(..) | ty::Error(_) => Err(AlwaysRequiresDrop), . . ty::Slice(ty) => needs_drop_components(ty, target_layout), . ty::Array(elem_ty, size) => { 36 ( 0.00%) match needs_drop_components(elem_ty, target_layout) { 12 ( 0.00%) Ok(v) if v.is_empty() => Ok(v), 48 ( 0.00%) res => match size.val.try_to_bits(target_layout.pointer_size) { . // Arrays of size zero don't need drop, even if their element . // type does. . Some(0) => Ok(SmallVec::new()), 24 ( 0.00%) Some(_) => res, . // We don't know which of the cases above we are in, so . // return the whole type and let the caller decide what to . // do. . None => Ok(smallvec![ty]), . }, . } . } . // If any field needs drop, then the whole tuple does. 9,150 ( 0.00%) ty::Tuple(..) => ty.tuple_fields().try_fold(SmallVec::new(), move |mut acc, elem| { 54,828 ( 0.00%) acc.extend(needs_drop_components(elem, target_layout)?); 36,552 ( 0.00%) Ok(acc) . }), . . // These require checking for `Copy` bounds or `Adt` destructors. . ty::Adt(..) . | ty::Projection(..) . | ty::Param(_) . | ty::Bound(..) . | ty::Placeholder(..) . | ty::Opaque(..) . | ty::Infer(_) . | ty::Closure(..) 37,048 ( 0.00%) | ty::Generator(..) => Ok(smallvec![ty]), . } 198,522 ( 0.01%) } . 60 ( 0.00%) pub fn is_trivially_const_drop<'tcx>(ty: Ty<'tcx>) -> bool { 40 ( 0.00%) match *ty.kind() { . ty::Bool . | ty::Char . | ty::Int(_) . | ty::Uint(_) . | ty::Float(_) . | ty::Infer(ty::IntVar(_)) . | ty::Infer(ty::FloatVar(_)) . | ty::Str -- line 1053 ---------------------------------------- -- line 1070 ---------------------------------------- . // Not trivial because they have components, and instead of looking inside, . // we'll just perform trait selection. . ty::Closure(..) | ty::Generator(..) | ty::GeneratorWitness(_) | ty::Adt(..) => false, . . ty::Array(ty, _) | ty::Slice(ty) => is_trivially_const_drop(ty), . . ty::Tuple(tys) => tys.iter().all(|ty| is_trivially_const_drop(ty.expect_ty())), . } 80 ( 0.00%) } . . // Does the equivalent of . // ``` . // let v = self.iter().map(|p| p.fold_with(folder)).collect::>(); . // folder.tcx().intern_*(&v) . // ``` 53,960 ( 0.00%) pub fn fold_list<'tcx, F, T>( . list: &'tcx ty::List, . folder: &mut F, . intern: impl FnOnce(TyCtxt<'tcx>, &[T]) -> &'tcx ty::List, . ) -> Result<&'tcx ty::List, F::Error> . where . F: FallibleTypeFolder<'tcx>, . T: TypeFoldable<'tcx> + PartialEq + Copy, . { . let mut iter = list.iter(); . // Look for the first element that changed 512 ( 0.00%) match iter.by_ref().enumerate().find_map(|(i, t)| match t.try_fold_with(folder) { 960 ( 0.00%) Ok(new_t) if new_t == t => None, . new_t => Some((i, new_t)), . }) { . Some((i, Ok(new_t))) => { . // An element changed, prepare to intern the resulting list . let mut new_list = SmallVec::<[_; 8]>::with_capacity(list.len()); . new_list.extend_from_slice(&list[..i]); . new_list.push(new_t); . for t in iter { . new_list.push(t.try_fold_with(folder)?) . } 1,194 ( 0.00%) Ok(intern(folder.tcx(), &new_list)) . } . Some((_, Err(err))) => { . return Err(err); . } . None => Ok(list), . } 54,919 ( 0.00%) } . . #[derive(Copy, Clone, Debug, HashStable, TyEncodable, TyDecodable)] . pub struct AlwaysRequiresDrop; . . /// Normalizes all opaque types in the given value, replacing them . /// with their underlying types. 8 ( 0.00%) pub fn normalize_opaque_types<'tcx>( . tcx: TyCtxt<'tcx>, . val: &'tcx List>, . ) -> &'tcx List> { 14 ( 0.00%) let mut visitor = OpaqueTypeExpander { . seen_opaque_tys: FxHashSet::default(), . expanded_cache: FxHashMap::default(), . primary_def_id: None, . found_recursion: false, . found_any_recursion: false, . check_recursion: false, . tcx, . }; . val.fold_with(&mut visitor) 10 ( 0.00%) } . . pub fn provide(providers: &mut ty::query::Providers) { 2 ( 0.00%) *providers = ty::query::Providers { normalize_opaque_types, ..*providers } . } 423,773 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs -------------------------------------------------------------------------------- Ir -- line 180 ---------------------------------------- . /// assert_eq!(v, &[0.into()]); . /// . /// // Ensure that the last item was dropped. . /// assert!(weak.upgrade().is_none()); . /// ``` . #[stable(feature = "drop_in_place", since = "1.8.0")] . #[lang = "drop_in_place"] . #[allow(unconditional_recursion)] 26,828,381 ( 1.26%) 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 { 3 ( 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 { 597,247 ( 0.03%) copy_nonoverlapping(src, tmp.as_mut_ptr(), 1); 3,769,390 ( 0.18%) 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 { 28,900,589 ( 1.36%) copy_nonoverlapping(&src as *const T, dst, 1); . intrinsics::forget(src); . } . } . . /// Overwrites a memory location with the given value without reading or . /// dropping the old value. . /// . /// Unlike [`write()`], the pointer may be unaligned. -- line 900 ---------------------------------------- -- line 1206 ---------------------------------------- . if stride == 1 { . // `stride == 1` case can be computed more simply through `-p (mod a)`, but doing so . // inhibits LLVM's ability to select instructions like `lea`. Instead we compute . // . // round_up_to_next_alignment(p, a) - p . // . // which distributes operations around the load-bearing, but pessimizing `and` sufficiently . // for LLVM to be able to utilize the various optimizations it knows about. 453 ( 0.00%) return wrapping_sub( 18,674 ( 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 { 573,618 ( 0.03%) 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 ---------------------------------------- 4,948,933 ( 0.23%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/caching_source_map_view.rs -------------------------------------------------------------------------------- Ir -- line 27 ---------------------------------------- . impl CacheEntry { . #[inline] . fn update( . &mut self, . new_file_and_idx: Option<(Lrc, usize)>, . pos: BytePos, . time_stamp: usize, . ) { 36,363 ( 0.00%) if let Some((file, file_idx)) = new_file_and_idx { 44,182 ( 0.00%) self.file = file; 59,750 ( 0.00%) self.file_index = file_idx; . } . 10,981 ( 0.00%) let line_index = self.file.lookup_line(pos).unwrap(); . let line_bounds = self.file.line_bounds(line_index); 91,250 ( 0.00%) self.line_number = line_index + 1; 146,275 ( 0.01%) self.line = line_bounds; . self.touch(time_stamp); . } . . #[inline] . fn touch(&mut self, time_stamp: usize) { 171,261 ( 0.01%) self.time_stamp = time_stamp; . } . } . . #[derive(Clone)] . pub struct CachingSourceMapView<'sm> { . source_map: &'sm SourceMap, . line_cache: [CacheEntry; 3], . time_stamp: usize, . } . . impl<'sm> CachingSourceMapView<'sm> { 10,680 ( 0.00%) pub fn new(source_map: &'sm SourceMap) -> CachingSourceMapView<'sm> { . let files = source_map.files(); 5,340 ( 0.00%) let first_file = files[0].clone(); . let entry = CacheEntry { . time_stamp: 0, . line_number: 0, . line: BytePos(0)..BytePos(0), . file: first_file, . file_index: 0, . }; . 26,700 ( 0.00%) CachingSourceMapView { . source_map, 37,380 ( 0.00%) line_cache: [entry.clone(), entry.clone(), entry], . time_stamp: 0, . } 21,360 ( 0.00%) } . . pub fn byte_pos_to_line_and_col( . &mut self, . pos: BytePos, . ) -> Option<(Lrc, usize, BytePos)> { . self.time_stamp += 1; . . // Check if the position is in one of the cached lines -- line 85 ---------------------------------------- -- line 106 ---------------------------------------- . }; . . let cache_entry = &mut self.line_cache[oldest]; . cache_entry.update(new_file_and_idx, pos, self.time_stamp); . . Some((cache_entry.file.clone(), cache_entry.line_number, pos - cache_entry.line.start)) . } . 725,718 ( 0.03%) pub fn span_data_to_lines_and_cols( . &mut self, . span_data: &SpanData, . ) -> Option<(Lrc, usize, BytePos, usize, BytePos)> { 414,696 ( 0.02%) self.time_stamp += 1; . . // Check if lo and hi are in the cached lines. 103,674 ( 0.00%) let lo_cache_idx = self.cache_entry_index(span_data.lo); 103,674 ( 0.00%) let hi_cache_idx = self.cache_entry_index(span_data.hi); . 135,180 ( 0.01%) if lo_cache_idx != -1 && hi_cache_idx != -1 { . // Cache hit for span lo and hi. Check if they belong to the same file. . let result = { 135,174 ( 0.01%) let lo = &self.line_cache[lo_cache_idx as usize]; . let hi = &self.line_cache[hi_cache_idx as usize]; . 405,522 ( 0.02%) if lo.file_index != hi.file_index { . return None; . } . . ( 135,174 ( 0.01%) lo.file.clone(), . lo.line_number, . span_data.lo - lo.line.start, 67,587 ( 0.00%) hi.line_number, . span_data.hi - hi.line.start, . ) . }; . 67,587 ( 0.00%) self.line_cache[lo_cache_idx as usize].touch(self.time_stamp); 67,587 ( 0.00%) self.line_cache[hi_cache_idx as usize].touch(self.time_stamp); . 270,348 ( 0.01%) return Some(result); . } . . // No cache hit or cache hit for only one of span lo and hi. 72,168 ( 0.00%) let oldest = if lo_cache_idx != -1 || hi_cache_idx != -1 { . let avoid_idx = if lo_cache_idx != -1 { lo_cache_idx } else { hi_cache_idx }; . self.oldest_cache_entry_index_avoid(avoid_idx as usize) . } else { . self.oldest_cache_entry_index() . }; . . // If the entry doesn't point to the correct file, get the new file and index. . // Return early if the file containing beginning of span doesn't contain end of span. 269,360 ( 0.01%) let new_file_and_idx = if !file_contains(&self.line_cache[oldest].file, span_data.lo) { 125,530 ( 0.01%) let new_file_and_idx = self.file_for_position(span_data.lo)?; 150,636 ( 0.01%) if !file_contains(&new_file_and_idx.0, span_data.hi) { . return None; . } . 100,424 ( 0.00%) Some(new_file_and_idx) . } else { . let file = &self.line_cache[oldest].file; 32,943 ( 0.00%) if !file_contains(&file, span_data.hi) { . return None; . } . 32,943 ( 0.00%) None . }; . . // Update the cache entries. 180,435 ( 0.01%) let (lo_idx, hi_idx) = match (lo_cache_idx, hi_cache_idx) { . // Oldest cache entry is for span_data.lo line. . (-1, -1) => { . let lo = &mut self.line_cache[oldest]; . lo.update(new_file_and_idx, span_data.lo, self.time_stamp); . 107,838 ( 0.01%) if !lo.line.contains(&span_data.hi) { . let new_file_and_idx = Some((lo.file.clone(), lo.file_index)); . let next_oldest = self.oldest_cache_entry_index_avoid(oldest); . let hi = &mut self.line_cache[next_oldest]; . hi.update(new_file_and_idx, span_data.hi, self.time_stamp); . (oldest, next_oldest) . } else { . (oldest, oldest) . } . } . // Oldest cache entry is for span_data.lo line. . (-1, _) => { . let lo = &mut self.line_cache[oldest]; . lo.update(new_file_and_idx, span_data.lo, self.time_stamp); 6 ( 0.00%) let hi = &mut self.line_cache[hi_cache_idx as usize]; 9 ( 0.00%) hi.touch(self.time_stamp); . (oldest, hi_cache_idx as usize) . } . // Oldest cache entry is for span_data.hi line. . (_, -1) => { . let hi = &mut self.line_cache[oldest]; 138 ( 0.00%) hi.update(new_file_and_idx, span_data.hi, self.time_stamp); 276 ( 0.00%) let lo = &mut self.line_cache[lo_cache_idx as usize]; 552 ( 0.00%) lo.touch(self.time_stamp); . (lo_cache_idx as usize, oldest) . } . _ => { . panic!(); . } . }; . . let lo = &self.line_cache[lo_idx]; . let hi = &self.line_cache[hi_idx]; . . // Span lo and hi may equal line end when last line doesn't . // end in newline, hence the inclusive upper bounds below. 72,174 ( 0.00%) assert!(span_data.lo >= lo.line.start); 36,087 ( 0.00%) assert!(span_data.lo <= lo.line.end); 72,174 ( 0.00%) assert!(span_data.hi >= hi.line.start); 36,087 ( 0.00%) assert!(span_data.hi <= hi.line.end); 180,435 ( 0.01%) assert!(lo.file.contains(span_data.lo)); 108,261 ( 0.01%) assert!(lo.file.contains(span_data.hi)); 108,261 ( 0.01%) assert_eq!(lo.file_index, hi.file_index); . 108,261 ( 0.01%) Some(( 36,087 ( 0.00%) lo.file.clone(), . lo.line_number, . span_data.lo - lo.line.start, 36,087 ( 0.00%) hi.line_number, . span_data.hi - hi.line.start, . )) 933,066 ( 0.04%) } . . fn cache_entry_index(&self, pos: BytePos) -> isize { . for (idx, cache_entry) in self.line_cache.iter().enumerate() { 1,500,815 ( 0.07%) if cache_entry.line.contains(&pos) { . return idx as isize; . } . } . . -1 . } . . fn oldest_cache_entry_index(&self) -> usize { . let mut oldest = 0; . . for idx in 1..self.line_cache.len() { 215,676 ( 0.01%) if self.line_cache[idx].time_stamp < self.line_cache[oldest].time_stamp { . oldest = idx; . } . } . . oldest . } . . fn oldest_cache_entry_index_avoid(&self, avoid_idx: usize) -> usize { . let mut oldest = if avoid_idx != 0 { 0 } else { 1 }; . . for idx in 0..self.line_cache.len() { 48,621 ( 0.00%) if idx != avoid_idx 38,552 ( 0.00%) && self.line_cache[idx].time_stamp < self.line_cache[oldest].time_stamp . { . oldest = idx; . } . } . . oldest . } . 125,530 ( 0.01%) fn file_for_position(&self, pos: BytePos) -> Option<(Lrc, usize)> { 25,106 ( 0.00%) if !self.source_map.files().is_empty() { 50,212 ( 0.00%) let file_idx = self.source_map.lookup_source_file_idx(pos); . let file = &self.source_map.files()[file_idx]; . 200,848 ( 0.01%) if file_contains(file, pos) { . return Some((file.clone(), file_idx)); . } . } . . None 125,530 ( 0.01%) } . } . . #[inline] . fn file_contains(file: &SourceFile, pos: BytePos) -> bool { . // `SourceMap::lookup_source_file_idx` and `SourceFile::contains` both consider the position . // one past the end of a file to belong to it. Normally, that's what we want. But for the . // purposes of converting a byte position to a line and column number, we can't come up with a . // line and column number if the file is empty, because an empty file doesn't contain any -- line 290 ---------------------------------------- 2,085,086 ( 0.10%) -------------------------------------------------------------------------------- -- 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 { 3,574,099 ( 0.17%) Vec { buf: RawVec::NEW, len: 0 } 46 ( 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 { 1,362,793 ( 0.06%) Vec { buf: RawVec::with_capacity_in(capacity, alloc), len: 0 } . } . . /// Creates a `Vec` directly from the raw components of another vector. . /// . /// # Safety . /// . /// This is highly unsafe, due to the number of invariants that aren't . /// checked: -- line 617 ---------------------------------------- -- line 677 ---------------------------------------- . /// // Put everything back together into a Vec . /// let rebuilt = Vec::from_raw_parts_in(p, len, cap, alloc.clone()); . /// assert_eq!(rebuilt, [4, 5, 6]); . /// } . /// ``` . #[inline] . #[unstable(feature = "allocator_api", issue = "32838")] . pub unsafe fn from_raw_parts_in(ptr: *mut T, length: usize, capacity: usize, alloc: A) -> Self { 43,186 ( 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 { 829,230 ( 0.04%) 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) { 359,681 ( 0.02%) 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) { 1,756 ( 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. 61,004 ( 0.00%) if self.capacity() > self.len { 850 ( 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(); 20,504 ( 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")] 862,157 ( 0.04%) 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. 689,950 ( 0.03%) 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); 378,825 ( 0.02%) self.len = len; 825 ( 0.00%) ptr::drop_in_place(s); . } 1,034,588 ( 0.05%) } . . /// 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. 4,037,017 ( 0.19%) 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. 3,890,947 ( 0.18%) 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()); . 1,168,175 ( 0.05%) self.len = new_len; 30 ( 0.00%) } . . /// Removes an element from the vector and returns it. . /// . /// The removed element is replaced by the last element of the vector. . /// . /// This does not preserve ordering, but is *O*(1). . /// If you need to preserve the element order, use [`remove`] instead. . /// -- line 1276 ---------------------------------------- -- line 1329 ---------------------------------------- . /// let mut vec = vec![1, 2, 3]; . /// vec.insert(1, 4); . /// assert_eq!(vec, [1, 4, 2, 3]); . /// vec.insert(4, 5); . /// assert_eq!(vec, [1, 4, 2, 3, 5]); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] 896 ( 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); . } . 161 ( 0.00%) let len = self.len(); 560 ( 0.00%) if index > len { . assert_failed(index, len); . } . . // space for the new element 780 ( 0.00%) if len == self.buf.capacity() { . self.reserve(1); . } . . unsafe { . // infallible . // The spot to put the new value . { . let p = self.as_mut_ptr().add(index); . // Shift everything over to make space. (Duplicating the . // `index`th element into two consecutive places.) 1,071 ( 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); . } 780 ( 0.00%) self.set_len(len + 1); . } 768 ( 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); . } . 29 ( 0.00%) let len = self.len(); 110 ( 0.00%) if index >= len { . assert_failed(index, len); . } . unsafe { . // infallible . let ret; . { . // the place we are taking from. . let ptr = self.as_mut_ptr().add(index); . // copy it out, unsafely having a copy of the value on . // the stack and in the vector at the same time. 96 ( 0.00%) ret = ptr::read(ptr); . . // Shift everything down to fill in that spot. 72 ( 0.00%) ptr::copy(ptr.offset(1), ptr, len - index - 1); . } 397 ( 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")] 51,047 ( 0.00%) pub fn retain(&mut self, mut f: F) . where . F: FnMut(&T) -> bool, . { 2,784 ( 0.00%) self.retain_mut(|elem| f(elem)); 50,104 ( 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, . { 6,413 ( 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) { 6,772 ( 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), 5,530 ( 0.00%) self.v.as_mut_ptr().add(self.processed_len - self.deleted_cnt), . self.original_len - self.processed_len, . ); . } . } . // SAFETY: After filling holes, all items are in contiguous memory. . unsafe { 2 ( 0.00%) self.v.set_len(self.original_len - self.deleted_cnt); . } . } . } . . let mut g = BackshiftOnDrop { v: self, processed_len: 0, deleted_cnt: 0, original_len }; . . fn process_loop( . original_len: usize, . f: &mut F, . g: &mut BackshiftOnDrop<'_, T, A>, . ) where . F: FnMut(&mut T) -> bool, . { 358,551 ( 0.02%) 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) }; 126,230 ( 0.01%) if !f(cur) { . // Advance early to avoid double drop if `drop_in_place` panicked. 82,494 ( 0.00%) g.processed_len += 1; 82,410 ( 0.00%) g.deleted_cnt += 1; . // SAFETY: We never touch this element again after dropped. 82,338 ( 0.00%) unsafe { ptr::drop_in_place(cur) }; . // We already advanced the counter. . if DELETED { . continue; . } else { . break; . } . } . if DELETED { . // SAFETY: `deleted_cnt` > 0, so the hole slot must not overlap with current element. . // We use copy for move, and never touch this element again. . unsafe { 162 ( 0.00%) let hole_slot = g.v.as_mut_ptr().add(g.processed_len - g.deleted_cnt); . ptr::copy_nonoverlapping(cur, hole_slot, 1); . } . } 108 ( 0.00%) g.processed_len += 1; . } . } . . // Stage 1: Nothing was deleted. . process_loop::(original_len, &mut f, &mut g); . . // Stage 2: Some elements were deleted. . process_loop::(original_len, &mut f, &mut g); -- line 1565 ---------------------------------------- -- line 1606 ---------------------------------------- . /// ``` . /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"]; . /// . /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b)); . /// . /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]); . /// ``` . #[stable(feature = "dedup_by", since = "1.16.0")] 28 ( 0.00%) pub fn dedup_by(&mut self, mut same_bucket: F) . where . F: FnMut(&mut T, &mut T) -> bool, . { 4 ( 0.00%) let len = self.len(); 756 ( 0.00%) if len <= 1 { . return; . } . . /* INVARIANT: vec.len() > read >= write > write-1 >= 0 */ . struct FillGapOnDrop<'a, T, A: core::alloc::Allocator> { . /* Offset of the element we want to check if it is duplicate */ . read: usize, . -- line 1627 ---------------------------------------- -- line 1670 ---------------------------------------- . let ptr = gap.vec.as_mut_ptr(); . . /* Drop items while going through Vec, it should be more efficient than . * doing slice partition_dedup + truncate */ . . /* SAFETY: Because of the invariant, read_ptr, prev_ptr and write_ptr . * are always in-bounds and read_ptr never aliases prev_ptr */ . unsafe { 642 ( 0.00%) while gap.read < len { . let read_ptr = ptr.add(gap.read); . let prev_ptr = ptr.add(gap.write.wrapping_sub(1)); . 232 ( 0.00%) if same_bucket(&mut *read_ptr, &mut *prev_ptr) { . // Increase `gap.read` now since the drop may panic. . gap.read += 1; . /* We have found duplicate, drop it in-place */ . ptr::drop_in_place(read_ptr); . } else { . let write_ptr = ptr.add(gap.write); . . /* Because `read_ptr` can be equal to `write_ptr`, we either . * have to use `copy` or conditional `copy_nonoverlapping`. . * Looks like the first option is faster. */ . ptr::copy(read_ptr, write_ptr, 1); . . /* We have filled that place, so go further */ 214 ( 0.00%) gap.write += 1; . gap.read += 1; . } . } . . /* Technically we could let `gap` clean up with its Drop, but . * when `same_bucket` is guaranteed to not panic, this bloats a little . * the codegen, so we just do it manually */ . gap.vec.set_len(gap.write); . mem::forget(gap); . } 32 ( 0.00%) } . . /// Appends an element to the back of a collection. . /// . /// # Panics . /// . /// Panics if the new capacity exceeds `isize::MAX` bytes. . /// . /// # Examples -- line 1715 ---------------------------------------- -- line 1717 ---------------------------------------- . /// ``` . /// let mut vec = vec![1, 2]; . /// vec.push(3); . /// assert_eq!(vec, [1, 2, 3]); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] 35 ( 0.00%) pub fn push(&mut self, value: T) { . // This will panic or abort if we would allocate > isize::MAX bytes . // or if the length increment would overflow for zero-sized types. 6,959,469 ( 0.33%) if self.len == self.buf.capacity() { 318,986 ( 0.02%) self.buf.reserve_for_push(self.len); . } . unsafe { 152,377 ( 0.01%) let end = self.as_mut_ptr().add(self.len); . ptr::write(end, value); 10,317,786 ( 0.49%) self.len += 1; . } 28 ( 0.00%) } . . /// Removes the last element from a vector and returns it, or [`None`] if it . /// is empty. . /// . /// If you'd like to pop the first element, consider using . /// [`VecDeque::pop_front`] instead. . /// . /// [`VecDeque::pop_front`]: crate::collections::VecDeque::pop_front -- line 1744 ---------------------------------------- -- line 1748 ---------------------------------------- . /// ``` . /// let mut vec = vec![1, 2, 3]; . /// assert_eq!(vec.pop(), Some(3)); . /// assert_eq!(vec, [1, 2]); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn pop(&mut self) -> Option { 949,135 ( 0.04%) if self.len == 0 { 22 ( 0.00%) None . } else { . unsafe { 838,109 ( 0.04%) self.len -= 1; 66,867 ( 0.00%) Some(ptr::read(self.as_ptr().add(self.len()))) . } . } . } . . /// Moves all the elements of `other` into `Self`, leaving `other` empty. . /// . /// # Panics . /// -- line 1769 ---------------------------------------- -- line 1776 ---------------------------------------- . /// let mut vec2 = vec![4, 5, 6]; . /// vec.append(&mut vec2); . /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]); . /// assert_eq!(vec2, []); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[inline] . #[stable(feature = "append", since = "1.4.0")] 231 ( 0.00%) pub fn append(&mut self, other: &mut Self) { . unsafe { . self.append_elements(other.as_slice() as _); . other.set_len(0); . } 198 ( 0.00%) } . . /// Appends elements to `Self` from other buffer. . #[cfg(not(no_global_oom_handling))] . #[inline] . unsafe fn append_elements(&mut self, other: *const [T]) { . let count = unsafe { (*other).len() }; . self.reserve(count); 102,943 ( 0.00%) let len = self.len(); . unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) }; 720,958 ( 0.03%) 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. . // 14,668 ( 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). 27,342 ( 0.00%) let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start), end - start); 41,469 ( 0.00%) Drain { . tail_start: end, 18,230 ( 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) { 1,544,307 ( 0.07%) 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 { 664,784 ( 0.03%) self.len() == 0 . } . . /// Splits the collection into two at the given index. . /// . /// Returns a newly allocated vector containing the elements in the range . /// `[at, len)`. After the call, the original vector will be left containing . /// the elements `[0, at)` with its previous capacity unchanged. . /// -- line 1916 ---------------------------------------- -- line 1935 ---------------------------------------- . A: Clone, . { . #[cold] . #[inline(never)] . fn assert_failed(at: usize, len: usize) -> ! { . panic!("`at` split index (is {}) should be <= len (is {})", at, len); . } . 333 ( 0.00%) if at > self.len() { . assert_failed(at, self.len()); . } . 243 ( 0.00%) if at == 0 { . // the new vector can take over the original buffer and avoid the copy . return mem::replace( . self, . Vec::with_capacity_in(self.capacity(), self.allocator().clone()), . ); . } . . let other_len = self.len - at; -- line 1955 ---------------------------------------- -- line 1988 ---------------------------------------- . /// . /// let mut vec = vec![]; . /// let mut p = 1; . /// vec.resize_with(4, || { p *= 2; p }); . /// assert_eq!(vec, [2, 4, 8, 16]); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "vec_resize_with", since = "1.33.0")] 9,688 ( 0.00%) pub fn resize_with(&mut self, new_len: usize, f: F) . where . F: FnMut() -> T, . { 1,336 ( 0.00%) let len = self.len(); 2,672 ( 0.00%) if new_len > len { 36,428 ( 0.00%) self.extend_with(new_len - len, ExtendFunc(f)); . } else { . self.truncate(new_len); . } 8,352 ( 0.00%) } . . /// Consumes and leaks the `Vec`, returning a mutable reference to the contents, . /// `&'a mut [T]`. Note that the type `T` must outlive the chosen lifetime . /// `'a`. If the type has only static references, or none at all, then this . /// may be chosen to be `'static`. . /// . /// As of Rust 1.57, this method does not reallocate or shrink the `Vec`, . /// so the leaked allocation may include unused capacity that is not part -- line 2014 ---------------------------------------- -- line 2070 ---------------------------------------- . #[stable(feature = "vec_spare_capacity", since = "1.60.0")] . #[inline] . pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit] { . // Note: . // This method is not implemented in terms of `split_at_spare_mut`, . // to prevent invalidation of pointers to the buffer. . unsafe { . slice::from_raw_parts_mut( 2 ( 0.00%) self.as_mut_ptr().add(self.len) as *mut MaybeUninit, 45 ( 0.00%) self.buf.capacity() - self.len, . ) . } . } . . /// Returns vector content as a slice of `T`, along with the remaining spare . /// capacity of the vector as a slice of `MaybeUninit`. . /// . /// The returned spare capacity slice can be used to fill the vector with data -- line 2087 ---------------------------------------- -- line 2189 ---------------------------------------- . /// assert_eq!(vec, ["hello", "world", "world"]); . /// . /// let mut vec = vec![1, 2, 3, 4]; . /// vec.resize(2, 0); . /// assert_eq!(vec, [1, 2]); . /// ``` . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "vec_resize", since = "1.5.0")] 160 ( 0.00%) pub fn resize(&mut self, new_len: usize, value: T) { 16 ( 0.00%) let len = self.len(); . 48 ( 0.00%) if new_len > len { 1,917 ( 0.00%) self.extend_with(new_len - len, ExtendElement(value)) . } else { . self.truncate(new_len); . } 72 ( 0.00%) } . . /// Clones and appends all elements in a slice to the `Vec`. . /// . /// Iterates over the slice `other`, clones each element, and then appends . /// it to this `Vec`. The `other` slice is traversed in-order. . /// . /// Note that this function is same as [`extend`] except that it is . /// specialized to work with slices instead. If and when Rust gets -- line 2213 ---------------------------------------- -- line 2271 ---------------------------------------- . trait ExtendWith { . fn next(&mut self) -> T; . fn last(self) -> T; . } . . struct ExtendElement(T); . impl ExtendWith for ExtendElement { . fn next(&mut self) -> T { 27,346 ( 0.00%) self.0.clone() . } . fn last(self) -> T { . self.0 . } . } . . struct ExtendFunc(F); . impl T> ExtendWith for ExtendFunc { -- line 2287 ---------------------------------------- -- line 2291 ---------------------------------------- . fn last(mut self) -> T { . (self.0)() . } . } . . impl Vec { . #[cfg(not(no_global_oom_handling))] . /// Extend the vector by `n` values, using the given generator. 121,428 ( 0.01%) fn extend_with>(&mut self, n: usize, mut value: E) { . self.reserve(n); . . unsafe { 1,190 ( 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); . } . 133,544 ( 0.01%) if n > 0 { . // We can write the last element directly without cloning needlessly . ptr::write(ptr, value.last()); . local_len.increment_len(1); . } . . // len set by scope guard . } 85,921 ( 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) { 5 ( 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")] 5,240 ( 0.00%) pub fn from_elem(elem: T, n: usize) -> Vec { 105,403 ( 0.00%) ::from_elem(elem, n, Global) 6,571 ( 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] { 6,734,263 ( 0.32%) 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] { 1,178,491 ( 0.06%) 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))] 692,656 ( 0.03%) fn clone(&self) -> Self { . let alloc = self.allocator().clone(); 2 ( 0.00%) <[T]>::to_vec_in(&**self, alloc) 832,369 ( 0.04%) } . . // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is . // required for this method definition, is not available. Instead use the . // `slice::to_vec` function which is only available with cfg(test) . // NB see the slice::hack module in slice.rs for more information . #[cfg(test)] . fn clone(&self) -> Self { . let alloc = self.allocator().clone(); -- line 2487 ---------------------------------------- -- line 2518 ---------------------------------------- . message = "vector indices are of type `usize` or ranges of `usize`", . label = "vector indices are of type `usize` or ranges of `usize`" . )] . impl, A: Allocator> Index for Vec { . type Output = I::Output; . . #[inline] . fn index(&self, index: I) -> &Self::Output { 56,502 ( 0.00%) Index::index(&**self, index) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_on_unimplemented( . message = "vector indices are of type `usize` or ranges of `usize`", . label = "vector indices are of type `usize` or ranges of `usize`" . )] . impl, A: Allocator> IndexMut for Vec { . #[inline] . fn index_mut(&mut self, index: I) -> &mut Self::Output { 12 ( 0.00%) IndexMut::index_mut(&mut **self, index) . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl FromIterator for Vec { . #[inline] . fn from_iter>(iter: I) -> Vec { 1,372,678 ( 0.06%) >::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 { 763,402 ( 0.04%) 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(); 416,640 ( 0.02%) 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> { 666 ( 0.00%) self.iter_mut() . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl Extend for Vec { . #[inline] 72 ( 0.00%) fn extend>(&mut self, iter: I) { 391,429 ( 0.02%) >::spec_extend(self, iter.into_iter()) 72 ( 0.00%) } . . #[inline] . fn extend_one(&mut self, item: T) { . self.push(item); . } . . #[inline] . fn extend_reserve(&mut self, additional: usize) { -- line 2627 ---------------------------------------- -- line 2636 ---------------------------------------- . fn extend_desugared>(&mut self, mut iterator: I) { . // This is the case for a general iterator. . // . // This function should be the moral equivalent of: . // . // for item in iterator { . // self.push(item); . // } 154,225 ( 0.01%) while let Some(element) = iterator.next() { 6,717 ( 0.00%) let len = self.len(); 115,797 ( 0.01%) if len == self.capacity() { 294 ( 0.00%) let (lower, _) = iterator.size_hint(); . self.reserve(lower.saturating_add(1)); . } . unsafe { . ptr::write(self.as_mut_ptr().add(len), element); . // Since next() executes user code which can panic we have to bump the length . // after each step. . // NB can't overflow since we would have had to alloc the address space 102,596 ( 0.00%) self.set_len(len + 1); . } . } 951 ( 0.00%) } . . /// Creates a splicing iterator that replaces the specified range in the vector . /// with the given `replace_with` iterator and yields the removed items. . /// `replace_with` does not need to be the same length as `range`. . /// . /// `range` is removed even if the iterator is not consumed until the end. . /// . /// It is unspecified how many elements are removed from the vector -- line 2666 ---------------------------------------- -- line 2693 ---------------------------------------- . #[cfg(not(no_global_oom_handling))] . #[inline] . #[stable(feature = "vec_splice", since = "1.21.0")] . pub fn splice(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter, A> . where . R: RangeBounds, . I: IntoIterator, . { 100,280 ( 0.00%) Splice { drain: self.drain(range), replace_with: replace_with.into_iter() } . } . . /// Creates an iterator which uses a closure to determine if an element should be removed. . /// . /// If the closure returns true, then the element is removed and yielded. . /// If the closure returns false, the element will remain in the vector and will not be yielded . /// by the iterator. . /// -- line 2709 ---------------------------------------- -- line 2745 ---------------------------------------- . /// assert_eq!(evens, vec![2, 4, 6, 8, 14]); . /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]); . /// ``` . #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")] . pub fn drain_filter(&mut self, filter: F) -> DrainFilter<'_, T, F, A> . where . F: FnMut(&mut T) -> bool, . { 445 ( 0.00%) let old_len = self.len(); . . // Guard against us getting leaked (leak amplification) . unsafe { . self.set_len(0); . } . 216 ( 0.00%) DrainFilter { vec: self, idx: 0, del: 0, old_len, pred: filter, panic_flag: false } . } . } . . /// Extend implementation that copies elements out of references before pushing them onto the Vec. . /// . /// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to . /// append the entire slice at once. . /// -- line 2768 ---------------------------------------- -- line 2803 ---------------------------------------- . #[inline] . fn cmp(&self, other: &Self) -> Ordering { . Ord::cmp(&**self, &**other) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . unsafe impl<#[may_dangle] T, A: Allocator> Drop for Vec { 1,514,101 ( 0.07%) 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 500,798 ( 0.02%) ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len)) . } . // RawVec handles deallocation 1,785,306 ( 0.08%) } . } . . #[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 ---------------------------------------- 2,405,189 ( 0.11%) -------------------------------------------------------------------------------- -- 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 { 845,109 ( 0.04%) Token { kind, len } . } . } . . /// Enum representing common lexeme types. . // perf note: Changing all `usize` to `u32` doesn't change performance. See #77629 152,170 ( 0.01%) #[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. 63 ( 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 72 ( 0.00%) } . . /// Parses the first token from the provided input string. 281,703 ( 0.01%) pub fn first_token(input: &str) -> Token { . debug_assert!(!input.is_empty()); 93,901 ( 0.00%) Cursor::new(input).advance_token() 375,604 ( 0.02%) } . . /// 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. . 98,068 ( 0.00%) 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). 37,234 ( 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. 751,208 ( 0.04%) fn advance_token(&mut self) -> Token { . let first_char = self.bump().unwrap(); 389,972 ( 0.02%) let token_kind = match first_char { . // Slash, comment or block comment. 2,272 ( 0.00%) '/' => match self.first() { . '/' => self.line_comment(), . '*' => self.block_comment(), . _ => Slash, . }, . . // Whitespace sequence. . c if is_whitespace(c) => self.whitespace(), . -- line 313 ---------------------------------------- -- line 322 ---------------------------------------- . } . let kind = RawStr { n_hashes, err }; . Literal { kind, suffix_start } . } . _ => self.ident_or_unknown_prefix(), . }, . . // Byte literal, byte string literal, raw byte string literal or identifier. 9 ( 0.00%) 'b' => match (self.first(), self.second()) { . ('\'', _) => { . self.bump(); . let terminated = self.single_quoted_string(); . let suffix_start = self.len_consumed(); . if terminated { . self.eat_literal_suffix(); . } . let kind = Byte { terminated }; -- line 338 ---------------------------------------- -- line 361 ---------------------------------------- . _ => self.ident_or_unknown_prefix(), . }, . . // Identifier (this should be checked after other variant that can . // start as identifier). . c if is_id_start(c) => self.ident_or_unknown_prefix(), . . // Numeric literal. 200,907 ( 0.01%) c @ '0'..='9' => { . let literal_kind = self.number(c); . let suffix_start = self.len_consumed(); . self.eat_literal_suffix(); 15 ( 0.00%) TokenKind::Literal { kind: literal_kind, suffix_start } . } . . // One-symbol tokens. 432 ( 0.00%) ';' => Semi, 18,896 ( 0.00%) ',' => Comma, 18,240 ( 0.00%) '.' => Dot, 18,990 ( 0.00%) '(' => OpenParen, 18,990 ( 0.00%) ')' => CloseParen, 216 ( 0.00%) '{' => OpenBrace, 216 ( 0.00%) '}' => CloseBrace, 64 ( 0.00%) '[' => OpenBracket, 64 ( 0.00%) ']' => CloseBracket, . '@' => At, 58 ( 0.00%) '#' => Pound, . '~' => Tilde, . '?' => Question, 19,724 ( 0.00%) ':' => Colon, . '$' => Dollar, 9,470 ( 0.00%) '=' => Eq, 9,470 ( 0.00%) '!' => Bang, 6 ( 0.00%) '<' => Lt, 372 ( 0.00%) '>' => Gt, 18 ( 0.00%) '-' => Minus, 12 ( 0.00%) '&' => And, . '|' => Or, . '+' => Plus, . '*' => Star, . '^' => Caret, . '%' => Percent, . . // Lifetime or character literal. 27,801 ( 0.00%) '\'' => self.lifetime_or_char(), . . // String literal. . '"' => { 240 ( 0.00%) let terminated = self.double_quoted_string(); . let suffix_start = self.len_consumed(); 160 ( 0.00%) if terminated { . self.eat_literal_suffix(); . } . let kind = Str { terminated }; 160 ( 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()) 845,109 ( 0.04%) } . . fn line_comment(&mut self) -> TokenKind { . debug_assert!(self.prev() == '/' && self.first() == '/'); . self.bump(); . 1,344 ( 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. 1,392 ( 0.00%) '/' if self.second() != '/' => Some(DocStyle::Outer), . _ => None, . }; . 17,166 ( 0.00%) self.eat_while(|c| c != '\n'); 1,704 ( 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); 11,147 ( 0.00%) Whitespace . } . . fn raw_ident(&mut self) -> TokenKind { . debug_assert!(self.prev() == 'r' && self.first() == '#' && is_id_start(self.second())); . // Eat "#" symbol. . self.bump(); . // Eat the identifier part of RawIdent. . self.eat_identifier(); . RawIdent . } . 76,085 ( 0.00%) fn ident_or_unknown_prefix(&mut self) -> TokenKind { . debug_assert!(is_id_start(self.prev())); . // Start is already eaten, eat the rest of identifier. 30,434 ( 0.00%) self.eat_while(is_id_continue); . // Known prefixes must have been handled earlier. So if . // we see a prefix here, it is definitely an unknown prefix. 30,434 ( 0.00%) match self.first() { . '#' | '"' | '\'' => UnknownPrefix, 15,217 ( 0.00%) c if !c.is_ascii() && unic_emoji_char::is_emoji(c) => { . self.fake_ident_or_unknown_prefix() . } 15,217 ( 0.00%) _ => Ident, . } 60,868 ( 0.00%) } . . fn fake_ident_or_unknown_prefix(&mut self) -> TokenKind { . // Start is already eaten, eat the rest of identifier. . self.eat_while(|c| { . unicode_xid::UnicodeXID::is_xid_continue(c) . || (!c.is_ascii() && unic_emoji_char::is_emoji(c)) . || c == '\u{200d}' . }); -- line 515 ---------------------------------------- -- line 519 ---------------------------------------- . '#' | '"' | '\'' => UnknownPrefix, . _ => InvalidIdent, . } . } . . fn number(&mut self, first_digit: char) -> LiteralKind { . debug_assert!('0' <= self.prev() && self.prev() <= '9'); . let mut base = Base::Decimal; 6 ( 0.00%) if first_digit == '0' { . // Attempt to parse encoding base. 10 ( 0.00%) let has_digits = match self.first() { . 'b' => { . base = Base::Binary; . self.bump(); . self.eat_decimal_digits() . } . 'o' => { . base = Base::Octal; . self.bump(); -- line 537 ---------------------------------------- -- line 538 ---------------------------------------- . self.eat_decimal_digits() . } . 'x' => { . base = Base::Hexadecimal; . self.bump(); . self.eat_hexadecimal_digits() . } . // Not a base prefix. 6 ( 0.00%) '0'..='9' | '_' | '.' | 'e' | 'E' => { . self.eat_decimal_digits(); . true . } . // Just a 0. . _ => return Int { base, empty_int: false }, . }; . // Base prefix was provided, but there were no digits . // after it, e.g. "0x". -- line 554 ---------------------------------------- -- line 555 ---------------------------------------- . if !has_digits { . return Int { base, empty_int: true }; . } . } else { . // No base prefix, parse number in the usual way. . self.eat_decimal_digits(); . }; . 6 ( 0.00%) match self.first() { . // Don't be greedy if this is actually an . // integer literal followed by field/method access or a range pattern . // (`0..2` and `12.foo()`) . '.' if self.second() != '.' && !is_id_start(self.second()) => { . // might have stuff after the ., and if it does, it needs to start . // with a number . self.bump(); . let mut empty_exponent = false; -- line 571 ---------------------------------------- -- line 585 ---------------------------------------- . self.bump(); . let empty_exponent = !self.eat_float_exponent(); . Float { base, empty_exponent } . } . _ => Int { base, empty_int: false }, . } . } . 64,869 ( 0.00%) fn lifetime_or_char(&mut self) -> TokenKind { . debug_assert!(self.prev() == '\''); . 18,534 ( 0.00%) let can_be_a_lifetime = if self.second() == '\'' { . // It's surely not a lifetime. . false . } else { . // If the first symbol is valid for identifier, it can be a lifetime. . // Also check if it's a number for a better error reporting (so '0 will . // be reported as invalid lifetime and not as unterminated char literal). . is_id_start(self.first()) || self.first().is_digit(10) . }; . 9,267 ( 0.00%) if !can_be_a_lifetime { 27,801 ( 0.00%) let terminated = self.single_quoted_string(); . let suffix_start = self.len_consumed(); 18,534 ( 0.00%) if terminated { . self.eat_literal_suffix(); . } . let kind = Char { terminated }; 37,068 ( 0.00%) return Literal { kind, suffix_start }; . } . . // Either a lifetime or a character literal with . // length greater than 1. . . let starts_with_number = self.first().is_digit(10); . . // Skip the literal contents. -- line 621 ---------------------------------------- -- line 629 ---------------------------------------- . // string with single quotes). . if self.first() == '\'' { . self.bump(); . let kind = Char { terminated: true }; . Literal { kind, suffix_start: self.len_consumed() } . } else { . Lifetime { starts_with_number } . } 55,602 ( 0.00%) } . . fn single_quoted_string(&mut self) -> bool { . debug_assert!(self.prev() == '\''); . // Check if it's a one-symbol literal. 18,534 ( 0.00%) if self.second() == '\'' && self.first() != '\\' { . self.bump(); . self.bump(); . return true; . } . . // Literal has more than one symbol. . . // Parse until either quotes are terminated or error is detected. . loop { 430,377 ( 0.02%) match self.first() { . // Quotes are terminated, finish parsing. . '\'' => { . self.bump(); . return true; . } . // Probably beginning of the comment, which we don't want to include . // to the error report. . '/' => break, -- line 660 ---------------------------------------- -- line 670 ---------------------------------------- . // Skip the character. . _ => { . self.bump(); . } . } . } . // String was not terminated. . false 9,267 ( 0.00%) } . . /// Eats double-quoted string and returns true . /// if string is terminated. . fn double_quoted_string(&mut self) -> bool { . debug_assert!(self.prev() == '"'); . while let Some(c) = self.bump() { 4,504 ( 0.00%) match c { . '"' => { . return true; . } . '\\' if self.first() == '\\' || self.first() == '"' => { . // Bump again to skip escaped character. . self.bump(); . } . _ => (), . } . } . // End of file reached. . false 80 ( 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 773 ---------------------------------------- . max_hashes = n_end_hashes; . } . } . } . . fn eat_decimal_digits(&mut self) -> bool { . let mut has_digits = false; . loop { 4 ( 0.00%) match self.first() { . '_' => { . self.bump(); . } 6 ( 0.00%) '0'..='9' => { . has_digits = true; . self.bump(); . } . _ => break, . } . } . has_digits 2 ( 0.00%) } . . fn eat_hexadecimal_digits(&mut self) -> bool { . let mut has_digits = false; . loop { . match self.first() { . '_' => { . self.bump(); . } -- line 801 ---------------------------------------- -- 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) { 18,700 ( 0.00%) self.eat_identifier(); . } . . // Eats the identifier. 28,050 ( 0.00%) fn eat_identifier(&mut self) { . if !is_id_start(self.first()) { . return; . } . self.bump(); . . self.eat_while(is_id_continue); 37,400 ( 0.00%) } . } 1,202,245 ( 0.06%) -------------------------------------------------------------------------------- -- 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)] 3,607,379 ( 0.17%) pub fn rustc_entry(&mut self, key: K) -> RustcEntry<'_, K, V, A> { . let hash = make_insert_hash(&self.hash_builder, &key); 153 ( 0.00%) if let Some(elem) = self.table.find(hash, |q| q.0.eq(&key)) { 501,560 ( 0.02%) RustcEntry::Occupied(RustcOccupiedEntry { 805,600 ( 0.04%) 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); . 158,556 ( 0.01%) RustcEntry::Vacant(RustcVacantEntry { . hash, 133,043 ( 0.01%) key, . table: &mut self.table, . }) . } 2,275,660 ( 0.11%) } . } . . /// 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 { 16,930 ( 0.00%) unsafe { &mut self.elem.as_mut().1 } . } . . /// Sets the value of the entry, and returns the entry's old value. . /// . /// # Examples . /// . /// ``` . /// use hashbrown::HashMap; -- line 421 ---------------------------------------- -- line 568 ---------------------------------------- . /// let mut map: HashMap<&str, u32> = HashMap::new(); . /// . /// if let RustcEntry::Vacant(o) = map.rustc_entry("poneyland") { . /// o.insert(37); . /// } . /// assert_eq!(map["poneyland"], 37); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 3,998 ( 0.00%) pub fn insert(self, value: V) -> &'a mut V { . unsafe { 111,389 ( 0.01%) let bucket = self.table.insert_no_grow(self.hash, (self.key, value)); 904 ( 0.00%) &mut bucket.as_mut().1 . } 5,260 ( 0.00%) } . . /// Sets the value of the entry with the RustcVacantEntry's key, . /// and returns a RustcOccupiedEntry. . /// . /// # Examples . /// . /// ``` . /// use hashbrown::HashMap; -- line 589 ---------------------------------------- 688,354 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/freshen.rs -------------------------------------------------------------------------------- Ir -- line 47 ---------------------------------------- . const_freshen_count: u32, . ty_freshen_map: FxHashMap>, . const_freshen_map: FxHashMap, &'tcx ty::Const<'tcx>>, . keep_static: bool, . } . . impl<'a, 'tcx> TypeFreshener<'a, 'tcx> { . pub fn new(infcx: &'a InferCtxt<'a, 'tcx>, keep_static: bool) -> TypeFreshener<'a, 'tcx> { 412,685 ( 0.02%) TypeFreshener { . infcx, . ty_freshen_count: 0, . const_freshen_count: 0, . ty_freshen_map: Default::default(), . const_freshen_map: Default::default(), . keep_static, . } . } . 318,144 ( 0.01%) fn freshen_ty( . &mut self, . opt_ty: Option>, . key: ty::InferTy, . freshener: F, . ) -> Ty<'tcx> . where . F: FnOnce(u32) -> ty::InferTy, . { 79,536 ( 0.00%) if let Some(ty) = opt_ty { . return ty.fold_with(self); . } . 3,016 ( 0.00%) match self.ty_freshen_map.entry(key) { 9 ( 0.00%) Entry::Occupied(entry) => *entry.get(), . Entry::Vacant(entry) => { 1,499 ( 0.00%) let index = self.ty_freshen_count; 5,996 ( 0.00%) self.ty_freshen_count += 1; 2,998 ( 0.00%) let t = self.infcx.tcx.mk_ty_infer(freshener(index)); . entry.insert(t); . t . } . } 13,572 ( 0.00%) } . . fn freshen_const( . &mut self, . opt_ct: Option<&'tcx ty::Const<'tcx>>, . key: ty::InferConst<'tcx>, . freshener: F, . ty: Ty<'tcx>, . ) -> &'tcx ty::Const<'tcx> -- line 96 ---------------------------------------- -- line 111 ---------------------------------------- . ct . } . } . } . } . . impl<'a, 'tcx> TypeFolder<'tcx> for TypeFreshener<'a, 'tcx> { . fn tcx<'b>(&'b self) -> TyCtxt<'tcx> { 87,988 ( 0.00%) self.infcx.tcx 40,037 ( 0.00%) } . . fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> { 9,824 ( 0.00%) match *r { . ty::ReLateBound(..) => { . // leave bound regions alone . r . } . . ty::ReEarlyBound(..) . | ty::ReFree(_) . | ty::ReVar(_) . | ty::RePlaceholder(..) . | ty::ReEmpty(_) . | ty::ReErased => { . // replace all free regions with 'erased . self.tcx().lifetimes.re_erased . } . ty::ReStatic => { 65 ( 0.00%) if self.keep_static { . r . } else { . self.tcx().lifetimes.re_erased . } . } . } . } . 725,328 ( 0.03%) fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { 362,664 ( 0.02%) if !t.needs_infer() && !t.has_erasable_regions() { . return t; . } . . let tcx = self.infcx.tcx; . 406,440 ( 0.02%) match *t.kind() { 39,768 ( 0.00%) ty::Infer(ty::TyVar(v)) => { 318,144 ( 0.01%) let opt_ty = self.infcx.inner.borrow_mut().type_variables().probe(v).known(); 357,912 ( 0.02%) self.freshen_ty(opt_ty, ty::TyVar(v), ty::FreshTy) . } . . ty::Infer(ty::IntVar(v)) => self.freshen_ty( . self.infcx . .inner . .borrow_mut() . .int_unification_table() . .probe_value(v) -- line 166 ---------------------------------------- -- line 210 ---------------------------------------- . | ty::Dynamic(..) . | ty::Never . | ty::Tuple(..) . | ty::Projection(..) . | ty::Foreign(..) . | ty::Param(..) . | ty::Closure(..) . | ty::GeneratorWitness(..) 23,360 ( 0.00%) | ty::Opaque(..) => t.super_fold_with(self), . . ty::Placeholder(..) | ty::Bound(..) => bug!("unexpected type {:?}", t), . } 547,400 ( 0.03%) } . . fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> { . match ct.val { . ty::ConstKind::Infer(ty::InferConst::Var(v)) => { . let opt_ct = self . .infcx . .inner . .borrow_mut() -- line 230 ---------------------------------------- 134,050 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_resolve/src/lib.rs -------------------------------------------------------------------------------- Ir -- line 91 ---------------------------------------- . mod late; . mod macros; . . enum Weak { . Yes, . No, . } . 15,276 ( 0.00%) #[derive(Copy, Clone, PartialEq, Debug)] . pub enum Determinacy { . Determined, . Undetermined, . } . . impl Determinacy { . fn determined(determined: bool) -> Determinacy { . if determined { Determinacy::Determined } else { Determinacy::Undetermined } 10,184 ( 0.00%) } . } . . /// A specific scope in which a name can be looked up. . /// This enum is currently used only for early resolution (imports and macros), . /// but not for late resolution yet. . #[derive(Clone, Copy)] . enum Scope<'a> { . DeriveHelpers(LocalExpnId), -- line 116 ---------------------------------------- -- line 157 ---------------------------------------- . macro_rules: MacroRulesScopeRef<'a>, . derives: &'a [ast::Path], . } . . impl<'a> ParentScope<'a> { . /// Creates a parent scope with the passed argument used as the module scope component, . /// and other scope components set to default empty values. . pub fn module(module: Module<'a>, resolver: &Resolver<'a>) -> ParentScope<'a> { 8 ( 0.00%) ParentScope { . module, . expansion: LocalExpnId::ROOT, 809 ( 0.00%) macro_rules: resolver.arenas.alloc_macro_rules_scope(MacroRulesScope::Empty), . derives: &[], . } . } . } . . #[derive(Copy, Debug, Clone)] . enum ImplTraitContext { . Existential, -- line 176 ---------------------------------------- -- line 278 ---------------------------------------- . FailedToResolve(Span, String, Option), . ExpectedFound(Span, String, Res), . Indeterminate(Span), . ModuleOnly(Span), . } . . /// A minimal representation of a path segment. We use this in resolve because we synthesize 'path . /// segments' which don't have the rest of an AST or HIR `PathSegment`. 15 ( 0.00%) #[derive(Clone, Copy, Debug)] . pub struct Segment { . ident: Ident, . id: Option, . /// Signals whether this `PathSegment` has generic arguments. Used to avoid providing . /// nonsensical suggestions. . has_generic_args: bool, . } . -- line 294 ---------------------------------------- -- line 303 ---------------------------------------- . . fn names_to_string(segments: &[Segment]) -> String { . names_to_string(&segments.iter().map(|seg| seg.ident.name).collect::>()) . } . } . . impl<'a> From<&'a ast::PathSegment> for Segment { . fn from(seg: &'a ast::PathSegment) -> Segment { 625 ( 0.00%) Segment { ident: seg.ident, id: Some(seg.id), has_generic_args: seg.args.is_some() } . } . } . . struct UsePlacementFinder { . target_module: NodeId, . span: Option, . found_use: bool, . } -- line 319 ---------------------------------------- -- line 391 ---------------------------------------- . #[derive(Debug)] . enum LexicalScopeBinding<'a> { . Item(&'a NameBinding<'a>), . Res(Res), . } . . impl<'a> LexicalScopeBinding<'a> { . fn res(self) -> Res { 108 ( 0.00%) match self { . LexicalScopeBinding::Item(binding) => binding.res(), 162 ( 0.00%) LexicalScopeBinding::Res(res) => res, . } . } . } . . #[derive(Copy, Clone, Debug)] . enum ModuleOrUniformRoot<'a> { . /// Regular module. . Module(Module<'a>), -- line 409 ---------------------------------------- -- line 418 ---------------------------------------- . /// Virtual module that denotes resolution in current scope. . /// Used only for resolving single-segment imports. The reason it exists is that import paths . /// are always split into two parts, the first of which should be some kind of module. . CurrentScope, . } . . impl ModuleOrUniformRoot<'_> { . fn same_def(lhs: Self, rhs: Self) -> bool { 508 ( 0.00%) match (lhs, rhs) { . (ModuleOrUniformRoot::Module(lhs), ModuleOrUniformRoot::Module(rhs)) => { . ptr::eq(lhs, rhs) . } . ( . ModuleOrUniformRoot::CrateRootAndExternPrelude, . ModuleOrUniformRoot::CrateRootAndExternPrelude, . ) . | (ModuleOrUniformRoot::ExternPrelude, ModuleOrUniformRoot::ExternPrelude) -- line 434 ---------------------------------------- -- line 491 ---------------------------------------- . /// A key that identifies a binding in a given `Module`. . /// . /// Multiple bindings in the same module can have the same key (in a valid . /// program) if all but one of them come from glob imports. . #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] . struct BindingKey { . /// The identifier for the binding, aways the `normalize_to_macros_2_0` version of the . /// identifier. 522,552 ( 0.02%) ident: Ident, 173,792 ( 0.01%) ns: Namespace, . /// 0 if ident is not `_`, otherwise a value that's unique to the specific . /// `_` in the expanded AST that introduced this binding. 130,050 ( 0.01%) disambiguator: u32, . } . . type Resolutions<'a> = RefCell>>>; . . /// One node in the tree of modules. . /// . /// Note that a "module" in resolve is broader than a `mod` that you declare in Rust code. It may be one of these: . /// -- line 511 ---------------------------------------- -- line 551 ---------------------------------------- . impl<'a> ModuleData<'a> { . fn new( . parent: Option>, . kind: ModuleKind, . expansion: ExpnId, . span: Span, . no_implicit_prelude: bool, . ) -> Self { 1,631 ( 0.00%) let is_foreign = match kind { . ModuleKind::Def(_, def_id, _) => !def_id.is_local(), . ModuleKind::Block(_) => false, . }; 5,359 ( 0.00%) ModuleData { . parent, . kind, . lazy_resolutions: Default::default(), . populate_on_access: Cell::new(is_foreign), . unexpanded_invocations: Default::default(), . no_implicit_prelude, . glob_importers: RefCell::new(Vec::new()), . globs: RefCell::new(Vec::new()), . traits: RefCell::new(None), . span, . expansion, . } . } . 254 ( 0.00%) fn for_each_child(&'a self, resolver: &mut R, mut f: F) . where . R: AsMut>, . F: FnMut(&mut R, Ident, Namespace, &'a NameBinding<'a>), . { 79 ( 0.00%) for (key, name_resolution) in resolver.as_mut().resolutions(self).borrow().iter() { 4,044 ( 0.00%) if let Some(binding) = name_resolution.borrow().binding { 1,128 ( 0.00%) f(resolver, key.ident, key.ns, binding); . } . } 200 ( 0.00%) } . . /// This modifies `self` in place. The traits will be stored in `self.traits`. . fn ensure_traits(&'a self, resolver: &mut R) . where . R: AsMut>, . { . let mut traits = self.traits.borrow_mut(); 348 ( 0.00%) if traits.is_none() { . let mut collected_traits = Vec::new(); . self.for_each_child(resolver, |_, name, ns, binding| { 88 ( 0.00%) if ns != TypeNS { . return; . } 188 ( 0.00%) if let Res::Def(DefKind::Trait | DefKind::TraitAlias, _) = binding.res() { . collected_traits.push((name, binding)) . } . }); 24 ( 0.00%) *traits = Some(collected_traits.into_boxed_slice()); . } . } . . fn res(&self) -> Option { 22,528 ( 0.00%) match self.kind { 24,035 ( 0.00%) ModuleKind::Def(kind, def_id, _) => Some(Res::Def(kind, def_id)), . _ => None, . } . } . . // Public for rustdoc. . pub fn def_id(&self) -> DefId { . self.opt_def_id().expect("`ModuleData::def_id` is called on a block module") . } . . fn opt_def_id(&self) -> Option { 10,456 ( 0.00%) match self.kind { . ModuleKind::Def(_, def_id, _) => Some(def_id), . _ => None, . } . } . . // `self` resolves to the first module ancestor that `is_normal`. . fn is_normal(&self) -> bool { 25,863 ( 0.00%) matches!(self.kind, ModuleKind::Def(DefKind::Mod, _, _)) . } . . fn is_trait(&self) -> bool { 1 ( 0.00%) matches!(self.kind, ModuleKind::Def(DefKind::Trait, _, _)) . } . . fn nearest_item_scope(&'a self) -> Module<'a> { 74,556 ( 0.00%) match self.kind { . ModuleKind::Def(DefKind::Enum | DefKind::Trait, ..) => { 418 ( 0.00%) self.parent.expect("enum or trait module without a parent") . } . _ => self, . } . } . . /// The [`DefId`] of the nearest `mod` item ancestor (which may be this module). . /// This may be the crate root. 22,216 ( 0.00%) fn nearest_parent_mod(&self) -> DefId { 88,742 ( 0.00%) match self.kind { 44,310 ( 0.00%) ModuleKind::Def(DefKind::Mod, def_id, _) => def_id, 122 ( 0.00%) _ => self.parent.expect("non-root module without parent").nearest_parent_mod(), . } 44,432 ( 0.00%) } . . fn is_ancestor_of(&self, mut other: &Self) -> bool { . while !ptr::eq(self, other) { . if let Some(parent) = other.parent { . other = parent; . } else { . return false; . } -- line 662 ---------------------------------------- -- line 773 ---------------------------------------- . b1: &'a NameBinding<'a>, . b2: &'a NameBinding<'a>, . misc1: AmbiguityErrorMisc, . misc2: AmbiguityErrorMisc, . } . . impl<'a> NameBinding<'a> { . fn module(&self) -> Option> { 137,054 ( 0.01%) match self.kind { 9,970 ( 0.00%) NameBindingKind::Module(module) => Some(module), 9,310 ( 0.00%) NameBindingKind::Import { binding, .. } => binding.module(), . _ => None, . } . } . . fn res(&self) -> Res { 410,120 ( 0.02%) match self.kind { 240,377 ( 0.01%) NameBindingKind::Res(res, _) => res, 11,150 ( 0.00%) NameBindingKind::Module(module) => module.res().unwrap(), 39,067 ( 0.00%) NameBindingKind::Import { binding, .. } => binding.res(), . } . } . . fn is_ambiguity(&self) -> bool { 480 ( 0.00%) self.ambiguity.is_some() 480 ( 0.00%) || match self.kind { 240 ( 0.00%) NameBindingKind::Import { binding, .. } => binding.is_ambiguity(), . _ => false, . } . } . . fn is_possibly_imported_variant(&self) -> bool { . match self.kind { . NameBindingKind::Import { binding, .. } => binding.is_possibly_imported_variant(), . NameBindingKind::Res( -- line 807 ---------------------------------------- -- line 822 ---------------------------------------- . kind: ModuleKind::Def(DefKind::Mod, def_id, _), . .. . }) => def_id.index == CRATE_DEF_INDEX, . _ => false, . } . } . . fn is_import(&self) -> bool { 752 ( 0.00%) matches!(self.kind, NameBindingKind::Import { .. }) . } . . fn is_glob_import(&self) -> bool { 6,218 ( 0.00%) match self.kind { 689 ( 0.00%) NameBindingKind::Import { import, .. } => import.is_glob(), . _ => false, . } . } . . fn is_importable(&self) -> bool { 920 ( 0.00%) !matches!( . self.res(), . Res::Def(DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy, _) . ) . } . . fn is_macro_def(&self) -> bool { 138 ( 0.00%) matches!(self.kind, NameBindingKind::Res(Res::Def(DefKind::Macro(..), _), _)) . } . . fn macro_kind(&self) -> Option { . self.res().macro_kind() . } . . // Suppose that we resolved macro invocation with `invoc_parent_expansion` to binding `binding` . // at some expansion round `max(invoc, binding)` when they both emerged from macros. -- line 856 ---------------------------------------- -- line 1065 ---------------------------------------- . /// they are declared in the static array generated by proc_macro_harness. . proc_macros: Vec, . confused_type_with_std_module: FxHashMap, . . access_levels: AccessLevels, . } . . /// Nothing really interesting here; it just provides memory for the rest of the crate. 7 ( 0.00%) #[derive(Default)] . pub struct ResolverArenas<'a> { . modules: TypedArena>, . local_modules: RefCell>>, . imports: TypedArena>, . name_resolutions: TypedArena>>, . ast_paths: TypedArena, . dropless: DroplessArena, . } . . impl<'a> ResolverArenas<'a> { 3,029 ( 0.00%) fn new_module( . &'a self, . parent: Option>, . kind: ModuleKind, . expn_id: ExpnId, . span: Span, . no_implicit_prelude: bool, . module_map: &mut FxHashMap>, . ) -> Module<'a> { . let module = . self.modules.alloc(ModuleData::new(parent, kind, expn_id, span, no_implicit_prelude)); . let def_id = module.opt_def_id(); 699 ( 0.00%) if def_id.map_or(true, |def_id| def_id.is_local()) { . self.local_modules.borrow_mut().push(module); . } 233 ( 0.00%) if let Some(def_id) = def_id { . module_map.insert(def_id, module); . } . module 2,097 ( 0.00%) } . fn local_modules(&'a self) -> std::cell::Ref<'a, Vec>> { . self.local_modules.borrow() . } . fn alloc_name_binding(&'a self, name_binding: NameBinding<'a>) -> &'a NameBinding<'a> { . self.dropless.alloc(name_binding) . } 56 ( 0.00%) fn alloc_import(&'a self, import: Import<'a>) -> &'a Import<'_> { 3,334 ( 0.00%) self.imports.alloc(import) 56 ( 0.00%) } . fn alloc_name_resolution(&'a self) -> &'a RefCell> { 1,849 ( 0.00%) self.name_resolutions.alloc(Default::default()) . } . fn alloc_macro_rules_scope(&'a self, scope: MacroRulesScope<'a>) -> MacroRulesScopeRef<'a> { . PtrKey(self.dropless.alloc(Cell::new(scope))) . } . fn alloc_macro_rules_binding( . &'a self, . binding: MacroRulesBinding<'a>, . ) -> &'a MacroRulesBinding<'a> { -- line 1122 ---------------------------------------- -- line 1133 ---------------------------------------- . impl<'a> AsMut> for Resolver<'a> { . fn as_mut(&mut self) -> &mut Resolver<'a> { . self . } . } . . impl<'a, 'b> DefIdTree for &'a Resolver<'b> { . fn parent(self, id: DefId) -> Option { 4,583 ( 0.00%) match id.as_local() { . Some(id) => self.definitions.def_key(id).parent, . None => self.cstore().def_key(id).parent, . } . .map(|index| DefId { index, ..id }) . } . } . . /// This interface is used through the AST→HIR step, to embed full paths into the HIR. After that . /// the resolver is no longer needed as all the relevant information is inline. . impl ResolverAstLowering for Resolver<'_> { . fn def_key(&mut self, id: DefId) -> DefKey { . if let Some(id) = id.as_local() { . self.definitions().def_key(id) . } else { 73,695 ( 0.00%) self.cstore().def_key(id) . } . } . . #[inline] . fn def_span(&self, id: LocalDefId) -> Span { . self.definitions.def_span(id) . } . 28,422 ( 0.00%) fn item_generics_num_lifetimes(&self, def_id: DefId) -> usize { 4,863 ( 0.00%) if let Some(def_id) = def_id.as_local() { 63 ( 0.00%) self.item_generics_num_lifetimes[&def_id] . } else { 37,392 ( 0.00%) self.cstore().item_generics_num_lifetimes(def_id, self.session) . } 252 ( 0.00%) } . 598 ( 0.00%) fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option> { 299 ( 0.00%) self.legacy_const_generic_args(expr) 897 ( 0.00%) } . 31,610 ( 0.00%) fn get_partial_res(&self, id: NodeId) -> Option { . self.partial_res_map.get(&id).cloned() 94,830 ( 0.00%) } . 1,012 ( 0.00%) fn get_import_res(&mut self, id: NodeId) -> PerNS> { 253 ( 0.00%) self.import_res_map.get(&id).cloned().unwrap_or_default() 1,265 ( 0.00%) } . . fn get_label_res(&mut self, id: NodeId) -> Option { . self.label_res_map.get(&id).cloned() . } . . fn definitions(&mut self) -> &mut Definitions { 371 ( 0.00%) &mut self.definitions 371 ( 0.00%) } . 2,960 ( 0.00%) fn create_stable_hashing_context(&self) -> StableHashingContext<'_> { 33,989 ( 0.00%) StableHashingContext::new(self.session, &self.definitions, self.crate_loader.cstore()) 3,700 ( 0.00%) } . . fn lint_buffer(&mut self) -> &mut LintBuffer { . &mut self.lint_buffer . } . . fn next_node_id(&mut self) -> NodeId { . self.next_node_id() . } . 228,204 ( 0.01%) fn take_trait_map(&mut self, node: NodeId) -> Option> { . self.trait_map.remove(&node) 228,204 ( 0.01%) } . 249,132 ( 0.01%) fn opt_local_def_id(&self, node: NodeId) -> Option { 6,149 ( 0.00%) self.node_id_to_def_id.get(&node).copied() 249,132 ( 0.01%) } . 2,088 ( 0.00%) fn local_def_id(&self, node: NodeId) -> LocalDefId { . self.opt_local_def_id(node).unwrap_or_else(|| panic!("no entry for node id: `{:?}`", node)) 2,088 ( 0.00%) } . . fn def_path_hash(&self, def_id: DefId) -> DefPathHash { . match def_id.as_local() { . Some(def_id) => self.definitions.def_path_hash(def_id), . None => self.cstore().def_path_hash(def_id), . } . } . . /// Adds a definition with a parent definition. 9,330 ( 0.00%) fn create_def( . &mut self, . parent: LocalDefId, . node_id: ast::NodeId, . data: DefPathData, . expn_id: ExpnId, . span: Span, . ) -> LocalDefId { 1,244 ( 0.00%) assert!( 1,244 ( 0.00%) !self.node_id_to_def_id.contains_key(&node_id), . "adding a def'n for node-id {:?} and data {:?} but a previous def'n exists: {:?}", . node_id, . data, . self.definitions.def_key(self.node_id_to_def_id[&node_id]), . ); . . // Find the next free disambiguator for this key. 622 ( 0.00%) let next_disambiguator = &mut self.next_disambiguator; . let next_disambiguator = |parent, data| { 3,110 ( 0.00%) let next_disamb = next_disambiguator.entry((parent, data)).or_insert(0); 622 ( 0.00%) let disambiguator = *next_disamb; 622 ( 0.00%) *next_disamb = next_disamb.checked_add(1).expect("disambiguator overflow"); . disambiguator . }; . 6,220 ( 0.00%) let def_id = self.definitions.create_def(parent, data, expn_id, next_disambiguator, span); . . // Some things for which we allocate `LocalDefId`s don't correspond to . // anything in the AST, so they don't have a `NodeId`. For these cases . // we don't need a mapping from `NodeId` to `LocalDefId`. 1,866 ( 0.00%) if node_id != ast::DUMMY_NODE_ID { . debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id); . self.node_id_to_def_id.insert(node_id, def_id); . } 1,866 ( 0.00%) assert_eq!(self.def_id_to_node_id.push(node_id), def_id); . . def_id 5,598 ( 0.00%) } . } . . impl<'a> Resolver<'a> { 16 ( 0.00%) pub fn new( . session: &'a Session, . krate: &Crate, . crate_name: &str, . metadata_loader: Box, . arenas: &'a ResolverArenas<'a>, . ) -> Resolver<'a> { . let root_def_id = CRATE_DEF_ID.to_def_id(); . let mut module_map = FxHashMap::default(); 14 ( 0.00%) let graph_root = arenas.new_module( . None, . ModuleKind::Def(DefKind::Mod, root_def_id, kw::Empty), 1 ( 0.00%) ExpnId::root(), 1 ( 0.00%) krate.span, 2 ( 0.00%) session.contains_name(&krate.attrs, sym::no_implicit_prelude), . &mut module_map, . ); 12 ( 0.00%) let empty_module = arenas.new_module( . None, . ModuleKind::Def(DefKind::Mod, root_def_id, kw::Empty), 1 ( 0.00%) ExpnId::root(), . DUMMY_SP, . true, . &mut FxHashMap::default(), . ); . 4 ( 0.00%) let definitions = Definitions::new(session.local_stable_crate_id(), krate.span); 2 ( 0.00%) let root = definitions.get_root_def(); . . let mut visibilities = FxHashMap::default(); . visibilities.insert(CRATE_DEF_ID, ty::Visibility::Public); . . let mut def_id_to_node_id = IndexVec::default(); 2 ( 0.00%) assert_eq!(def_id_to_node_id.push(CRATE_NODE_ID), root); . let mut node_id_to_def_id = FxHashMap::default(); . node_id_to_def_id.insert(CRATE_NODE_ID, root); . . let mut invocation_parents = FxHashMap::default(); . invocation_parents.insert(LocalExpnId::ROOT, (root, ImplTraitContext::Existential)); . 3 ( 0.00%) let mut extern_prelude: FxHashMap> = session . .opts . .externs . .iter() 3 ( 0.00%) .filter(|(_, entry)| entry.add_prelude) 3 ( 0.00%) .map(|(name, _)| (Ident::from_str(name), Default::default())) . .collect(); . 9 ( 0.00%) if !session.contains_name(&krate.attrs, sym::no_core) { . extern_prelude.insert(Ident::with_dummy_span(sym::core), Default::default()); 7 ( 0.00%) if !session.contains_name(&krate.attrs, sym::no_std) { . extern_prelude.insert(Ident::with_dummy_span(sym::std), Default::default()); . } . } . 8 ( 0.00%) let (registered_attrs, registered_tools) = 4 ( 0.00%) macros::registered_attrs_and_tools(session, &krate.attrs); . . let features = session.features_untracked(); . 237 ( 0.00%) let mut resolver = Resolver { . session, . 2 ( 0.00%) definitions, . . // The outermost module has def ID 0; this is not reflected in the . // AST. . graph_root, . prelude: None, 4 ( 0.00%) extern_prelude, . . has_self: FxHashSet::default(), . field_names: FxHashMap::default(), . . determined_imports: Vec::new(), . indeterminate_imports: Vec::new(), . . last_import_segment: false, -- line 1343 ---------------------------------------- -- line 1347 ---------------------------------------- . partial_res_map: Default::default(), . import_res_map: Default::default(), . label_res_map: Default::default(), . extern_crate_map: Default::default(), . reexport_map: FxHashMap::default(), . trait_map: NodeMap::default(), . underscore_disambiguator: 0, . empty_module, 4 ( 0.00%) module_map, . block_map: Default::default(), . binding_parent_modules: FxHashMap::default(), . ast_transform_scopes: FxHashMap::default(), . . glob_map: Default::default(), 4 ( 0.00%) visibilities, . used_imports: FxHashSet::default(), . maybe_unused_trait_imports: Default::default(), . maybe_unused_extern_crates: Vec::new(), . . privacy_errors: Vec::new(), . ambiguity_errors: Vec::new(), . use_injections: Vec::new(), . macro_expanded_macro_export_errors: BTreeSet::new(), -- line 1369 ---------------------------------------- -- line 1372 ---------------------------------------- . dummy_binding: arenas.alloc_name_binding(NameBinding { . kind: NameBindingKind::Res(Res::Err, false), . ambiguity: None, . expansion: LocalExpnId::ROOT, . span: DUMMY_SP, . vis: ty::Visibility::Public, . }), . 6 ( 0.00%) crate_loader: CrateLoader::new(session, metadata_loader, crate_name), . macro_names: FxHashSet::default(), . builtin_macros: Default::default(), 4 ( 0.00%) registered_attrs, 4 ( 0.00%) registered_tools, . macro_use_prelude: FxHashMap::default(), . all_macros: FxHashMap::default(), . macro_map: FxHashMap::default(), 7 ( 0.00%) dummy_ext_bang: Lrc::new(SyntaxExtension::dummy_bang(session.edition())), 6 ( 0.00%) dummy_ext_derive: Lrc::new(SyntaxExtension::dummy_derive(session.edition())), 5 ( 0.00%) non_macro_attr: Lrc::new(SyntaxExtension::non_macro_attr(session.edition())), . invocation_parent_scopes: Default::default(), . output_macro_rules_scopes: Default::default(), . helper_attrs: Default::default(), . derive_data: Default::default(), . local_macro_def_scopes: FxHashMap::default(), . name_already_seen: FxHashMap::default(), . potentially_unused_imports: Vec::new(), . struct_constructors: Default::default(), -- line 1398 ---------------------------------------- -- line 1405 ---------------------------------------- . active_features: features . .declared_lib_features . .iter() . .map(|(feat, ..)| *feat) . .chain(features.declared_lang_features.iter().map(|(feat, ..)| *feat)) . .collect(), . lint_buffer: LintBuffer::default(), . next_node_id: CRATE_NODE_ID, 4 ( 0.00%) node_id_to_def_id, 4 ( 0.00%) def_id_to_node_id, . placeholder_field_indices: Default::default(), 4 ( 0.00%) invocation_parents, . next_disambiguator: Default::default(), . trait_impl_items: Default::default(), . legacy_const_generic_args: Default::default(), . item_generics_num_lifetimes: Default::default(), . main_def: Default::default(), . trait_impls: Default::default(), . proc_macros: Default::default(), . confused_type_with_std_module: Default::default(), . access_levels: Default::default(), . }; . . let root_parent_scope = ParentScope::module(graph_root, &resolver); . resolver.invocation_parent_scopes.insert(LocalExpnId::ROOT, root_parent_scope); . . resolver 9 ( 0.00%) } . . fn new_module( . &mut self, . parent: Option>, . kind: ModuleKind, . expn_id: ExpnId, . span: Span, . no_implicit_prelude: bool, . ) -> Module<'a> { 16 ( 0.00%) let module_map = &mut self.module_map; 2,299 ( 0.00%) self.arenas.new_module(parent, kind, expn_id, span, no_implicit_prelude, module_map) . } . . pub fn next_node_id(&mut self) -> NodeId { . let next = 67,883 ( 0.00%) self.next_node_id.as_u32().checked_add(1).expect("input too large; ran out of NodeIds"); . mem::replace(&mut self.next_node_id, ast::NodeId::from_u32(next)) . } . . pub fn lint_buffer(&mut self) -> &mut LintBuffer { 3 ( 0.00%) &mut self.lint_buffer 3 ( 0.00%) } . 1 ( 0.00%) pub fn arenas() -> ResolverArenas<'a> { . Default::default() 1 ( 0.00%) } . 9 ( 0.00%) pub fn into_outputs(self) -> ResolverOutputs { . let proc_macros = self.proc_macros.iter().map(|id| self.local_def_id(*id)).collect(); 1 ( 0.00%) let definitions = self.definitions; 4 ( 0.00%) let visibilities = self.visibilities; 4 ( 0.00%) let extern_crate_map = self.extern_crate_map; 4 ( 0.00%) let reexport_map = self.reexport_map; 4 ( 0.00%) let maybe_unused_trait_imports = self.maybe_unused_trait_imports; 4 ( 0.00%) let maybe_unused_extern_crates = self.maybe_unused_extern_crates; 4 ( 0.00%) let glob_map = self.glob_map; 6 ( 0.00%) let main_def = self.main_def; 4 ( 0.00%) let confused_type_with_std_module = self.confused_type_with_std_module; 6 ( 0.00%) let access_levels = self.access_levels; 37 ( 0.00%) ResolverOutputs { 2 ( 0.00%) definitions, 11 ( 0.00%) cstore: Box::new(self.crate_loader.into_cstore()), 4 ( 0.00%) visibilities, 4 ( 0.00%) access_levels, 4 ( 0.00%) extern_crate_map, 4 ( 0.00%) reexport_map, 4 ( 0.00%) glob_map, 4 ( 0.00%) maybe_unused_trait_imports, 4 ( 0.00%) maybe_unused_extern_crates, . extern_prelude: self . .extern_prelude . .iter() 6 ( 0.00%) .map(|(ident, entry)| (ident.name, entry.introduced_by_item)) . .collect(), 6 ( 0.00%) main_def, 4 ( 0.00%) trait_impls: self.trait_impls, 4 ( 0.00%) proc_macros, 4 ( 0.00%) confused_type_with_std_module, 5 ( 0.00%) registered_tools: self.registered_tools, . } 19 ( 0.00%) } . . pub fn clone_outputs(&self) -> ResolverOutputs { . let proc_macros = self.proc_macros.iter().map(|id| self.local_def_id(*id)).collect(); . ResolverOutputs { . definitions: self.definitions.clone(), . access_levels: self.access_levels.clone(), . cstore: Box::new(self.cstore().clone()), . visibilities: self.visibilities.clone(), -- line 1501 ---------------------------------------- -- line 1513 ---------------------------------------- . trait_impls: self.trait_impls.clone(), . proc_macros, . confused_type_with_std_module: self.confused_type_with_std_module.clone(), . registered_tools: self.registered_tools.clone(), . } . } . . pub fn cstore(&self) -> &CStore { 86,947 ( 0.00%) self.crate_loader.cstore() . } . . fn dummy_ext(&self, macro_kind: MacroKind) -> Lrc { . match macro_kind { . MacroKind::Bang => self.dummy_ext_bang.clone(), . MacroKind::Derive => self.dummy_ext_derive.clone(), . MacroKind::Attr => self.non_macro_attr.clone(), . } . } . . /// Runs the function on each namespace. 924 ( 0.00%) fn per_ns(&mut self, mut f: F) { 1,833 ( 0.00%) f(self, TypeNS); 1,812 ( 0.00%) f(self, ValueNS); 1,812 ( 0.00%) f(self, MacroNS); 798 ( 0.00%) } . . fn is_builtin_macro(&mut self, res: Res) -> bool { . self.get_macro(res).map_or(false, |ext| ext.builtin_name.is_some()) . } . . fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId { . loop { . match ctxt.outer_expn_data().macro_def_id { . Some(def_id) => return def_id, . None => ctxt.remove_mark(), . }; . } . } . . /// Entry point to crate resolution. 2 ( 0.00%) pub fn resolve_crate(&mut self, krate: &Crate) { 4 ( 0.00%) self.session.time("resolve_crate", || { 3 ( 0.00%) self.session.time("finalize_imports", || ImportResolver { r: self }.finalize_imports()); . self.session.time("resolve_access_levels", || { 3 ( 0.00%) AccessLevelsVisitor::compute_access_levels(self, krate) . }); 2 ( 0.00%) self.session.time("finalize_macro_resolutions", || self.finalize_macro_resolutions()); 3 ( 0.00%) self.session.time("late_resolve_crate", || self.late_resolve_crate(krate)); 2 ( 0.00%) self.session.time("resolve_main", || self.resolve_main()); 3 ( 0.00%) self.session.time("resolve_check_unused", || self.check_unused(krate)); 3 ( 0.00%) self.session.time("resolve_report_errors", || self.report_errors(krate)); 4 ( 0.00%) self.session.time("resolve_postprocess", || self.crate_loader.postprocess(krate)); . }); . } . 2,088 ( 0.00%) pub fn traits_in_scope( . &mut self, . current_trait: Option>, . parent_scope: &ParentScope<'a>, . ctxt: SyntaxContext, . assoc_item: Option<(Symbol, Namespace)>, . ) -> Vec { . let mut found_traits = Vec::new(); . 348 ( 0.00%) if let Some(module) = current_trait { . if self.trait_may_have_item(Some(module), assoc_item) { . let def_id = module.def_id(); 18 ( 0.00%) found_traits.push(TraitCandidate { def_id, import_ids: smallvec![] }); . } . } . . self.visit_scopes(ScopeSet::All(TypeNS, false), parent_scope, ctxt, |this, scope, _, _| { . match scope { . Scope::Module(module, _) => { . this.traits_in_module(module, assoc_item, &mut found_traits); . } . Scope::StdLibPrelude => { 522 ( 0.00%) if let Some(module) = this.prelude { . this.traits_in_module(module, assoc_item, &mut found_traits); . } . } . Scope::ExternPrelude | Scope::ToolPrelude | Scope::BuiltinTypes => {} . _ => unreachable!(), . } . None::<()> . }); . . found_traits 1,392 ( 0.00%) } . . fn traits_in_module( . &mut self, . module: Module<'a>, . assoc_item: Option<(Symbol, Namespace)>, . found_traits: &mut Vec, . ) { . module.ensure_traits(self); . let traits = module.traits.borrow(); 9,048 ( 0.00%) for (trait_name, trait_binding) in traits.as_ref().unwrap().iter() { . if self.trait_may_have_item(trait_binding.module(), assoc_item) { . let def_id = trait_binding.res().def_id(); 9 ( 0.00%) let import_ids = self.find_transitive_imports(&trait_binding.kind, *trait_name); 27 ( 0.00%) found_traits.push(TraitCandidate { def_id, import_ids }); . } . } . } . . // List of traits in scope is pruned on best effort basis. We reject traits not having an . // associated item with the given name and namespace (if specified). This is a conservative . // optimization, proper hygienic type-based resolution of associated items is done in typeck. . // We don't reject trait aliases (`trait_module == None`) because we don't have access to their . // associated items. . fn trait_may_have_item( . &mut self, . trait_module: Option>, . assoc_item: Option<(Symbol, Namespace)>, . ) -> bool { 4,692 ( 0.00%) match (trait_module, assoc_item) { . (Some(trait_module), Some((name, ns))) => { 9,213 ( 0.00%) self.resolutions(trait_module).borrow().iter().any(|resolution| { . let (&BindingKey { ident: assoc_ident, ns: assoc_ns, .. }, _) = resolution; 34,373 ( 0.00%) assoc_ns == ns && assoc_ident.name == name . }) . } . _ => true, . } . } . . fn find_transitive_imports( . &mut self, . mut kind: &NameBindingKind<'_>, . trait_name: Ident, . ) -> SmallVec<[LocalDefId; 1]> { . let mut import_ids = smallvec![]; 21 ( 0.00%) while let NameBindingKind::Import { import, binding, .. } = kind { 9 ( 0.00%) let id = self.local_def_id(import.id); . self.maybe_unused_trait_imports.insert(id); 3 ( 0.00%) self.add_to_glob_map(&import, trait_name); . import_ids.push(id); 3 ( 0.00%) kind = &binding.kind; . } . import_ids . } . . fn new_key(&mut self, ident: Ident, ns: Namespace) -> BindingKey { 137,710 ( 0.01%) let ident = ident.normalize_to_macros_2_0(); 44,753 ( 0.00%) let disambiguator = if ident.name == kw::Underscore { . self.underscore_disambiguator += 1; . self.underscore_disambiguator . } else { . 0 . }; . BindingKey { ident, ns, disambiguator } . } . 397,992 ( 0.02%) fn resolutions(&mut self, module: Module<'a>) -> &'a Resolutions<'a> { 49,749 ( 0.00%) if module.populate_on_access.get() { . module.populate_on_access.set(false); . self.build_reduced_graph_external(module); . } 49,749 ( 0.00%) &module.lazy_resolutions 447,741 ( 0.02%) } . 406,791 ( 0.02%) fn resolution( . &mut self, . module: Module<'a>, . key: BindingKey, . ) -> &'a RefCell> { 135,597 ( 0.01%) *self . .resolutions(module) . .borrow_mut() 271,194 ( 0.01%) .entry(key) 90,398 ( 0.00%) .or_insert_with(|| self.arenas.alloc_name_resolution()) 361,592 ( 0.02%) } . 378,158 ( 0.02%) fn record_use( . &mut self, . ident: Ident, . used_binding: &'a NameBinding<'a>, . is_lexical_scope: bool, . ) { 103,134 ( 0.00%) if let Some((b2, kind)) = used_binding.ambiguity { . self.ambiguity_errors.push(AmbiguityError { . kind, . ident, . b1: used_binding, . b2, . misc1: AmbiguityErrorMisc::None, . misc2: AmbiguityErrorMisc::None, . }); . } 96,808 ( 0.00%) if let NameBindingKind::Import { import, binding, ref used } = used_binding.kind { . // Avoid marking `extern crate` items that refer to a name from extern prelude, . // but not introduce it, as used if they are accessed from lexical scope. 28,052 ( 0.00%) if is_lexical_scope { 11 ( 0.00%) if let Some(entry) = self.extern_prelude.get(&ident.normalize_to_macros_2_0()) { 5 ( 0.00%) if let Some(crate_item) = entry.extern_crate_item { 2 ( 0.00%) if ptr::eq(used_binding, crate_item) && !entry.introduced_by_item { . return; . } . } . } . } . used.set(true); . import.used.set(true); 14,026 ( 0.00%) self.used_imports.insert(import.id); 70,130 ( 0.00%) self.add_to_glob_map(&import, ident); 84,156 ( 0.00%) self.record_use(ident, binding, false); . } 275,024 ( 0.01%) } . . #[inline] 42,078 ( 0.00%) fn add_to_glob_map(&mut self, import: &Import<'_>, ident: Ident) { 14,029 ( 0.00%) if import.is_glob() { . let def_id = self.local_def_id(import.id); . self.glob_map.entry(def_id).or_default().insert(ident.name); . } 56,104 ( 0.00%) } . . /// A generic scope visitor. . /// Visits scopes in order to resolve some identifier in them or perform other actions. . /// If the callback returns `Some` result, we stop visiting scopes and return it. . fn visit_scopes( . &mut self, . scope_set: ScopeSet<'a>, . parent_scope: &ParentScope<'a>, -- line 1738 ---------------------------------------- -- line 1780 ---------------------------------------- . // ambiguities with `macro_rules`. . // 4. `macro_use` prelude (open, the open part is from macro expansions, not controlled). . // 4a. User-defined prelude from macro-use . // (open, the open part is from macro expansions, not controlled). . // 4b. "Standard library prelude" part implemented through `macro-use` (closed, controlled). . // 4c. Standard library prelude (de-facto closed, controlled). . // 6. Language prelude: builtin attributes (closed, controlled). . 189,126 ( 0.01%) let rust_2015 = ctxt.edition() == Edition::Edition2015; . let (ns, macro_kind, is_absolute_path) = match scope_set { . ScopeSet::All(ns, _) => (ns, None, false), . ScopeSet::AbsolutePath(ns) => (ns, None, true), . ScopeSet::Macro(macro_kind) => (MacroNS, Some(macro_kind), false), . ScopeSet::Late(ns, ..) => (ns, None, false), . }; 586,768 ( 0.03%) let module = match scope_set { . // Start with the specified module. . ScopeSet::Late(_, module, _) => module, . // Jump out of trait or enum modules, they do not act as scopes. 10,626 ( 0.00%) _ => parent_scope.module.nearest_item_scope(), . }; 41,912 ( 0.00%) let mut scope = match ns { 104,780 ( 0.00%) _ if is_absolute_path => Scope::CrateRoot, . TypeNS | ValueNS => Scope::Module(module, None), 31,308 ( 0.00%) MacroNS => Scope::DeriveHelpers(parent_scope.expansion), . }; 42,260 ( 0.00%) let mut ctxt = ctxt.normalize_to_macros_2_0(); 85,912 ( 0.00%) let mut use_prelude = !module.no_implicit_prelude; . . loop { 709,565 ( 0.03%) let visit = match scope { . // Derive helpers are not in scope when resolving derives in the same container. . Scope::DeriveHelpers(expn_id) => { 31,762 ( 0.00%) !(expn_id == parent_scope.expansion && macro_kind == Some(MacroKind::Derive)) . } . Scope::DeriveHelpersCompat => true, . Scope::MacroRules(macro_rules_scope) => { . // Use "path compression" on `macro_rules` scope chains. This is an optimization . // used to avoid long scope chains, see the comments on `MacroRulesScopeRef`. . // As another consequence of this optimization visitors never observe invocation . // scopes for macros that were already expanded. 20,938 ( 0.00%) while let MacroRulesScope::Invocation(invoc_id) = macro_rules_scope.get() { . if let Some(next_scope) = self.output_macro_rules_scopes.get(&invoc_id) { . macro_rules_scope.set(next_scope.get()); . } else { . break; . } . } . true . } . Scope::CrateRoot => true, . Scope::Module(..) => true, 10,436 ( 0.00%) Scope::RegisteredAttrs => use_prelude, . Scope::MacroUsePrelude => use_prelude || rust_2015, . Scope::BuiltinAttrs => true, 234 ( 0.00%) Scope::ExternPrelude => use_prelude || is_absolute_path, 57 ( 0.00%) Scope::ToolPrelude => use_prelude, 65,754 ( 0.00%) Scope::StdLibPrelude => use_prelude || ns == MacroNS, . Scope::BuiltinTypes => true, . }; . 31,449 ( 0.00%) if visit { 90,155 ( 0.00%) if let break_result @ Some(..) = visitor(self, scope, use_prelude, ctxt) { . return break_result; . } . } . 192,374 ( 0.01%) scope = match scope { . Scope::DeriveHelpers(LocalExpnId::ROOT) => Scope::DeriveHelpersCompat, . Scope::DeriveHelpers(expn_id) => { . // Derive helpers are not visible to code generated by bang or derive macros. . let expn_data = expn_id.expn_data(); 97,758 ( 0.00%) match expn_data.kind { . ExpnKind::Root . | ExpnKind::Macro(MacroKind::Bang | MacroKind::Derive, _) => { . Scope::DeriveHelpersCompat . } 454 ( 0.00%) _ => Scope::DeriveHelpers(expn_data.parent.expect_local()), . } . } 31,308 ( 0.00%) Scope::DeriveHelpersCompat => Scope::MacroRules(parent_scope.macro_rules), 20,872 ( 0.00%) Scope::MacroRules(macro_rules_scope) => match macro_rules_scope.get() { . MacroRulesScope::Binding(binding) => { . Scope::MacroRules(binding.parent_macro_rules_scope) . } . MacroRulesScope::Invocation(invoc_id) => { . Scope::MacroRules(self.invocation_parent_scopes[&invoc_id].macro_rules) . } . MacroRulesScope::Empty => Scope::Module(module, None), . }, -- line 1869 ---------------------------------------- -- line 1870 ---------------------------------------- . Scope::CrateRoot => match ns { . TypeNS => { . ctxt.adjust(ExpnId::root()); . Scope::ExternPrelude . } . ValueNS | MacroNS => break, . }, . Scope::Module(module, prev_lint_id) => { 63,944 ( 0.00%) use_prelude = !module.no_implicit_prelude; . let derive_fallback_lint_id = match scope_set { . ScopeSet::Late(.., lint_id) => lint_id, . _ => None, . }; 96,612 ( 0.00%) match self.hygienic_lexical_parent(module, &mut ctxt, derive_fallback_lint_id) { . Some((parent_module, lint_id)) => { . Scope::Module(parent_module, lint_id.or(prev_lint_id)) . } . None => { 80,169 ( 0.00%) ctxt.adjust(ExpnId::root()); 63,144 ( 0.00%) match ns { . TypeNS => Scope::ExternPrelude, . ValueNS => Scope::StdLibPrelude, . MacroNS => Scope::RegisteredAttrs, . } . } . } . } . Scope::RegisteredAttrs => Scope::MacroUsePrelude, . Scope::MacroUsePrelude => Scope::StdLibPrelude, . Scope::BuiltinAttrs => break, // nowhere else to search 114 ( 0.00%) Scope::ExternPrelude if is_absolute_path => break, . Scope::ExternPrelude => Scope::ToolPrelude, . Scope::ToolPrelude => Scope::StdLibPrelude, 42,418 ( 0.00%) Scope::StdLibPrelude => match ns { . TypeNS => Scope::BuiltinTypes, . ValueNS => break, // nowhere else to search . MacroNS => Scope::BuiltinAttrs, . }, . Scope::BuiltinTypes => break, // nowhere else to search . }; . } . -- line 1911 ---------------------------------------- -- line 1924 ---------------------------------------- . /// let g = || {}; . /// fn g() {} . /// g(); // This resolves to the local variable `g` since it shadows the item. . /// } . /// ``` . /// . /// Invariant: This must only be called during main resolution, not during . /// import resolution. 109,140 ( 0.01%) fn resolve_ident_in_lexical_scope( . &mut self, . mut ident: Ident, . ns: Namespace, . parent_scope: &ParentScope<'a>, . record_used_id: Option, . path_span: Span, . ribs: &[Rib<'a>], . ) -> Option> { 21,828 ( 0.00%) assert!(ns == TypeNS || ns == ValueNS); . let orig_ident = ident; 76,398 ( 0.00%) if ident.name == kw::Empty { . return Some(LexicalScopeBinding::Res(Res::Err)); . } . let (general_span, normalized_span) = if ident.name == kw::SelfUpper { . // FIXME(jseyfried) improve `Self` hygiene . let empty_span = ident.span.with_ctxt(SyntaxContext::root()); . (empty_span, empty_span) 10,869 ( 0.00%) } else if ns == TypeNS { 25,980 ( 0.00%) let normalized_span = ident.span.normalize_to_macros_2_0(); . (normalized_span, normalized_span) . } else { 28,365 ( 0.00%) (ident.span.normalize_to_macro_rules(), ident.span.normalize_to_macros_2_0()) . }; . ident.span = general_span; . let normalized_ident = Ident { span: normalized_span, ..ident }; . . // Walk backwards up the ribs in scope. . let record_used = record_used_id.is_some(); 32,742 ( 0.00%) let mut module = self.graph_root; . for i in (0..ribs.len()).rev() { . debug!("walk rib\n{:?}", ribs[i].bindings); . // Use the rib kind to determine whether we are resolving parameters . // (macro 2.0 hygiene) or local variables (`macro_rules` hygiene). 36,854 ( 0.00%) let rib_ident = if ribs[i].kind.contains_params() { normalized_ident } else { ident }; . if let Some((original_rib_ident_def, res)) = ribs[i].bindings.get_key_value(&rib_ident) . { . // The ident resolves to a type parameter or local variable. 4,560 ( 0.00%) return Some(LexicalScopeBinding::Res(self.validate_res_from_ribs( . i, 760 ( 0.00%) rib_ident, 1,900 ( 0.00%) *res, . record_used, . path_span, . *original_rib_ident_def, . ribs, . ))); . } . 212,730 ( 0.01%) module = match ribs[i].kind { 10,647 ( 0.00%) ModuleRibKind(module) => module, . MacroDefinition(def) if def == self.macro_def(ident.span.ctxt()) => { . // If an invocation of this macro created `ident`, give up on `ident` . // and switch to `ident`'s source from the macro definition. . ident.span.remove_mark(); . continue; . } . _ => continue, . }; . 31,941 ( 0.00%) match module.kind { . ModuleKind::Block(..) => {} // We can see through blocks . _ => break, . } . . let item = self.resolve_ident_in_module_unadjusted( . ModuleOrUniformRoot::Module(module), . ident, . ns, . parent_scope, . record_used, . path_span, . ); . if let Ok(binding) = item { . // The ident resolves to an item. 9 ( 0.00%) return Some(LexicalScopeBinding::Item(binding)); . } . } 179,027 ( 0.01%) self.early_resolve_ident_in_lexical_scope( . orig_ident, . ScopeSet::Late(ns, module, record_used_id), . parent_scope, . record_used, . record_used, . path_span, . ) . .ok() . .map(LexicalScopeBinding::Item) 98,226 ( 0.00%) } . 176,803 ( 0.01%) fn hygienic_lexical_parent( . &mut self, . module: Module<'a>, . ctxt: &mut SyntaxContext, . derive_fallback_lint_id: Option, . ) -> Option<(Module<'a>, Option)> { 112,511 ( 0.01%) if !module.expansion.outer_expn_is_descendant_of(*ctxt) { 444 ( 0.00%) return Some((self.expn_def_scope(ctxt.remove_mark()), None)); . } . 31,998 ( 0.00%) if let ModuleKind::Block(..) = module.kind { . return Some((module.parent.unwrap().nearest_item_scope(), None)); . } . . // We need to support the next case under a deprecation warning . // ``` . // struct MyStruct; . // ---- begin: this comes from a proc macro derive . // mod implementation_details { . // // Note that `MyStruct` is not in scope here. . // impl SomeTrait for MyStruct { ... } . // } . // ---- end . // ``` . // So we have to fall back to the module's parent during lexical resolution in this case. 15,999 ( 0.00%) if derive_fallback_lint_id.is_some() { 795 ( 0.00%) if let Some(parent) = module.parent { . // Inner module is inside the macro, parent module is outside of the macro. 1,325 ( 0.00%) if module.expansion != parent.expansion . && module.expansion.is_descendant_of(parent.expansion) . { . // The macro is a proc macro derive . if let Some(def_id) = module.expansion.expn_data().macro_def_id { . let ext = self.get_macro_by_def_id(def_id); . if ext.builtin_name.is_none() . && ext.macro_kind() == MacroKind::Derive . && parent.expansion.outer_expn_is_descendant_of(*ctxt) -- line 2058 ---------------------------------------- -- line 2060 ---------------------------------------- . return Some((parent, derive_fallback_lint_id)); . } . } . } . } . } . . None 160,730 ( 0.01%) } . . fn resolve_ident_in_module( . &mut self, . module: ModuleOrUniformRoot<'a>, . ident: Ident, . ns: Namespace, . parent_scope: &ParentScope<'a>, . record_used: bool, . path_span: Span, . ) -> Result<&'a NameBinding<'a>, Determinacy> { 98,208 ( 0.00%) self.resolve_ident_in_module_ext(module, ident, ns, parent_scope, record_used, path_span) . .map_err(|(determinacy, _)| determinacy) . } . 219,080 ( 0.01%) fn resolve_ident_in_module_ext( . &mut self, . module: ModuleOrUniformRoot<'a>, . mut ident: Ident, . ns: Namespace, . parent_scope: &ParentScope<'a>, . record_used: bool, . path_span: Span, . ) -> Result<&'a NameBinding<'a>, (Determinacy, Weak)> { . let tmp_parent_scope; . let mut adjusted_parent_scope = parent_scope; . match module { . ModuleOrUniformRoot::Module(m) => { 65,730 ( 0.00%) if let Some(def) = ident.span.normalize_to_macros_2_0_and_adjust(m.expansion) { 590 ( 0.00%) tmp_parent_scope = 708 ( 0.00%) ParentScope { module: self.expn_def_scope(def), ..*parent_scope }; . adjusted_parent_scope = &tmp_parent_scope; . } . } . ModuleOrUniformRoot::ExternPrelude => { . ident.span.normalize_to_macros_2_0_and_adjust(ExpnId::root()); . } . ModuleOrUniformRoot::CrateRootAndExternPrelude | ModuleOrUniformRoot::CurrentScope => { . // No adjustments . } . } 120,504 ( 0.01%) self.resolve_ident_in_module_unadjusted_ext( . module, 21,910 ( 0.00%) ident, . ns, . adjusted_parent_scope, . false, . record_used, . path_span, . ) 76,678 ( 0.00%) } . 96,480 ( 0.00%) fn resolve_crate_root(&mut self, ident: Ident) -> Module<'a> { . debug!("resolve_crate_root({:?})", ident); 9,648 ( 0.00%) let mut ctxt = ident.span.ctxt(); 9,648 ( 0.00%) let mark = if ident.name == kw::DollarCrate { . // When resolving `$crate` from a `macro_rules!` invoked in a `macro`, . // we don't want to pretend that the `macro_rules!` definition is in the `macro` . // as described in `SyntaxContext::apply_mark`, so we ignore prepended opaque marks. . // FIXME: This is only a guess and it doesn't work correctly for `macro_rules!` . // definitions actually produced by `macro` and `macro` definitions produced by . // `macro_rules!`, but at least such configurations are not stable yet. 19,272 ( 0.00%) ctxt = ctxt.normalize_to_macro_rules(); . debug!( . "resolve_crate_root: marks={:?}", . ctxt.marks().into_iter().map(|(i, t)| (i.expn_data(), t)).collect::>() . ); 19,272 ( 0.00%) let mut iter = ctxt.marks().into_iter().rev().peekable(); . let mut result = None; . // Find the last opaque mark from the end if it exists. 30,351 ( 0.00%) while let Some(&(mark, transparency)) = iter.peek() { . if transparency == Transparency::Opaque { . result = Some(mark); . iter.next(); . } else { . break; . } . } . debug!( . "resolve_crate_root: found opaque mark {:?} {:?}", . result, . result.map(|r| r.expn_data()) . ); . // Then find the last semi-transparent mark from the end if it exists. 28,908 ( 0.00%) for (mark, transparency) in iter { . if transparency == Transparency::SemiTransparent { . result = Some(mark); . } else { . break; . } . } . debug!( . "resolve_crate_root: found semi-transparent mark {:?} {:?}", . result, . result.map(|r| r.expn_data()) . ); . result . } else { . debug!("resolve_crate_root: not DollarCrate"); 12 ( 0.00%) ctxt = ctxt.normalize_to_macros_2_0(); 84 ( 0.00%) ctxt.adjust(ExpnId::root()) . }; 19,296 ( 0.00%) let module = match mark { 48,170 ( 0.00%) Some(def) => self.expn_def_scope(def), . None => { . debug!( . "resolve_crate_root({:?}): found no mark (ident.span = {:?})", . ident, ident.span . ); 28 ( 0.00%) return self.graph_root; . } . }; . let module = self.expect_module( . module.opt_def_id().map_or(LOCAL_CRATE, |def_id| def_id.krate).as_def_id(), . ); . debug!( . "resolve_crate_root({:?}): got module {:?} ({:?}) (ident.span = {:?})", . ident, . module, . module.kind.name(), . ident.span . ); . module 67,536 ( 0.00%) } . 4,122 ( 0.00%) fn resolve_self(&mut self, ctxt: &mut SyntaxContext, module: Module<'a>) -> Module<'a> { 916 ( 0.00%) let mut module = self.expect_module(module.nearest_parent_mod()); 1,832 ( 0.00%) while module.span.ctxt().normalize_to_macros_2_0() != *ctxt { . let parent = module.parent.unwrap_or_else(|| self.expn_def_scope(ctxt.remove_mark())); . module = self.expect_module(parent.nearest_parent_mod()); . } . module 4,122 ( 0.00%) } . . fn resolve_path( . &mut self, . path: &[Segment], . opt_ns: Option, // `None` indicates a module path in import . parent_scope: &ParentScope<'a>, . record_used: bool, . path_span: Span, . crate_lint: CrateLint, . ) -> PathResult<'a> { 2,667 ( 0.00%) self.resolve_path_with_ribs( . path, . opt_ns, . parent_scope, . record_used, . path_span, . crate_lint, . None, . ) . } . 235,080 ( 0.01%) fn resolve_path_with_ribs( . &mut self, . path: &[Segment], . opt_ns: Option, // `None` indicates a module path in import . parent_scope: &ParentScope<'a>, . record_used: bool, . path_span: Span, . crate_lint: CrateLint, . ribs: Option<&PerNS>>>, . ) -> PathResult<'a> { 15,672 ( 0.00%) let mut module = None; . let mut allow_super = true; . let mut second_binding = None; . . debug!( . "resolve_path(path={:?}, opt_ns={:?}, record_used={:?}, \ . path_span={:?}, crate_lint={:?})", . path, opt_ns, record_used, path_span, crate_lint, . ); . 155,004 ( 0.01%) for (i, &Segment { ident, id, has_generic_args: _ }) in path.iter().enumerate() { . debug!("resolve_path ident {} {:?} {:?}", i, ident, id); 146,750 ( 0.01%) let record_segment_res = |this: &mut Self, res| { 17,580 ( 0.00%) if record_used { 28,655 ( 0.00%) if let Some(id) = id { 11,462 ( 0.00%) if !this.partial_res_map.contains_key(&id) { 11,314 ( 0.00%) assert!(id != ast::DUMMY_NODE_ID, "Trying to resolve dummy id"); 22,628 ( 0.00%) this.record_partial_res(id, PartialRes::new(res)); . } . } . } 23,440 ( 0.00%) }; . 71,584 ( 0.00%) let is_last = i == path.len() - 1; 129,170 ( 0.01%) let ns = if is_last { opt_ns.unwrap_or(TypeNS) } else { TypeNS }; 25,834 ( 0.00%) let name = ident.name; . 41,086 ( 0.00%) allow_super &= ns == TypeNS && (name == kw::SelfLower || name == kw::Super); . . if ns == TypeNS { 30,504 ( 0.00%) if allow_super && name == kw::Super { 916 ( 0.00%) let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0(); 458 ( 0.00%) let self_module = match i { 916 ( 0.00%) 0 => Some(self.resolve_self(&mut ctxt, parent_scope.module)), . _ => match module { . Some(ModuleOrUniformRoot::Module(module)) => Some(module), . _ => None, . }, . }; . if let Some(self_module) = self_module { 687 ( 0.00%) if let Some(parent) = self_module.parent { 1,145 ( 0.00%) module = Some(ModuleOrUniformRoot::Module( 458 ( 0.00%) self.resolve_self(&mut ctxt, parent), . )); . continue; . } . } . let msg = "there are too many leading `super` keywords".to_string(); . return PathResult::Failed { . span: ident.span, . label: msg, . suggestion: None, . is_error_from_last_segment: false, . }; . } 30,046 ( 0.00%) if i == 0 { 29,802 ( 0.00%) if name == kw::SelfLower { . let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0(); . module = Some(ModuleOrUniformRoot::Module( . self.resolve_self(&mut ctxt, parent_scope.module), . )); . continue; . } . if name == kw::PathRoot && ident.span.rust_2018() { . module = Some(ModuleOrUniformRoot::ExternPrelude); -- line 2296 ---------------------------------------- -- line 2298 ---------------------------------------- . } . if name == kw::PathRoot && ident.span.rust_2015() && self.session.rust_2018() { . // `::a::b` from 2015 macro on 2018 global edition . module = Some(ModuleOrUniformRoot::CrateRootAndExternPrelude); . continue; . } . if name == kw::PathRoot || name == kw::Crate || name == kw::DollarCrate { . // `::a::b`, `crate::a::b` or `$crate::a::b` 18,892 ( 0.00%) module = Some(ModuleOrUniformRoot::Module(self.resolve_crate_root(ident))); . continue; . } . } . } . . // Report special messages for path segment keywords in wrong positions. 104,500 ( 0.00%) if ident.is_path_segment_keyword() && i != 0 { . let name_str = if name == kw::PathRoot { . "crate root".to_string() . } else { . format!("`{}`", name) . }; . let label = if i == 1 && path[0].ident.name == kw::PathRoot { . format!("global paths cannot start with {}", name_str) . } else { -- line 2321 ---------------------------------------- -- line 2328 ---------------------------------------- . is_error_from_last_segment: false, . }; . } . . enum FindBindingResult<'a> { . Binding(Result<&'a NameBinding<'a>, Determinacy>), . PathResult(PathResult<'a>), . } 668,224 ( 0.03%) let find_binding_in_ns = |this: &mut Self, ns| { 93,690 ( 0.00%) let binding = if let Some(module) = module { . this.resolve_ident_in_module( . module, 30,486 ( 0.00%) ident, . ns, . parent_scope, 20,324 ( 0.00%) record_used, 10,162 ( 0.00%) path_span, . ) 64,256 ( 0.00%) } else if ribs.is_none() || opt_ns.is_none() || opt_ns == Some(MacroNS) { . let scopes = ScopeSet::All(ns, opt_ns.is_none()); 272 ( 0.00%) this.early_resolve_ident_in_lexical_scope( 48 ( 0.00%) ident, . scopes, 16 ( 0.00%) parent_scope, 32 ( 0.00%) record_used, . record_used, 16 ( 0.00%) path_span, . ) . } else { 42,816 ( 0.00%) let record_used_id = if record_used { 5,637 ( 0.00%) crate_lint.node_id().or(Some(CRATE_NODE_ID)) . } else { . None . }; 160,080 ( 0.01%) match this.resolve_ident_in_lexical_scope( 32,112 ( 0.00%) ident, . ns, 10,704 ( 0.00%) parent_scope, . record_used_id, 21,408 ( 0.00%) path_span, . &ribs.unwrap()[ns], . ) { . // we found a locally-imported or available item/module 16,200 ( 0.00%) Some(LexicalScopeBinding::Item(binding)) => Ok(binding), . // we found a local variable or type param . Some(LexicalScopeBinding::Res(res)) 480 ( 0.00%) if opt_ns == Some(TypeNS) || opt_ns == Some(ValueNS) => . { 2,160 ( 0.00%) record_segment_res(this, res); 1,920 ( 0.00%) return FindBindingResult::PathResult(PathResult::NonModule( 1,680 ( 0.00%) PartialRes::with_unresolved_segments(res, path.len() - 1), . )); . } 15,192 ( 0.00%) _ => Err(Determinacy::determined(record_used)), . } . }; 144,494 ( 0.01%) FindBindingResult::Binding(binding) 167,056 ( 0.01%) }; 146,174 ( 0.01%) let binding = match find_binding_in_ns(self, ns) { 3,360 ( 0.00%) FindBindingResult::PathResult(x) => return x, . FindBindingResult::Binding(binding) => binding, . }; 56,476 ( 0.00%) match binding { . Ok(binding) => { 77,890 ( 0.00%) if i == 1 { . second_binding = Some(binding); . } . let res = binding.res(); 155,780 ( 0.01%) let maybe_assoc = opt_ns != Some(MacroNS) && PathSource::Type.is_expected(res); . if let Some(next_module) = binding.module() { 11,240 ( 0.00%) module = Some(ModuleOrUniformRoot::Module(next_module)); 50,580 ( 0.00%) record_segment_res(self, res); 69,706 ( 0.00%) } else if res == Res::ToolMod && i + 1 != path.len() { . if binding.is_import() { . self.session . .struct_span_err( . ident.span, . "cannot use a tool module through an import", . ) . .span_note(binding.span, "the tool module imported here") . .emit(); . } . let res = Res::NonMacroAttr(NonMacroAttrKind::Tool); . return PathResult::NonModule(PartialRes::new(res)); 49,790 ( 0.00%) } else if res == Res::Err { . return PathResult::NonModule(PartialRes::new(Res::Err)); 29,874 ( 0.00%) } else if opt_ns.is_some() && (is_last || maybe_assoc) { 69,706 ( 0.00%) self.lint_if_path_starts_with_module( 19,916 ( 0.00%) crate_lint, . path, 9,958 ( 0.00%) path_span, . second_binding, . ); 29,874 ( 0.00%) return PathResult::NonModule(PartialRes::with_unresolved_segments( 39,832 ( 0.00%) res, 39,832 ( 0.00%) path.len() - i - 1, . )); . } else { . let label = format!( . "`{}` is {} {}, not a module", . ident, . res.article(), . res.descr(), . ); -- line 2431 ---------------------------------------- -- line 2433 ---------------------------------------- . return PathResult::Failed { . span: ident.span, . label, . suggestion: None, . is_error_from_last_segment: is_last, . }; . } . } 10,128 ( 0.00%) Err(Undetermined) => return PathResult::Indeterminate, . Err(Determined) => { . if let Some(ModuleOrUniformRoot::Module(module)) = module { . if opt_ns.is_some() && !module.is_normal() { . return PathResult::NonModule(PartialRes::with_unresolved_segments( . module.res().unwrap(), . path.len() - i, . )); . } -- line 2449 ---------------------------------------- -- line 2612 ---------------------------------------- . label, . suggestion, . is_error_from_last_segment: is_last, . }; . } . } . } . 4,510 ( 0.00%) self.lint_if_path_starts_with_module(crate_lint, path, path_span, second_binding); . 2,460 ( 0.00%) PathResult::Module(match module { 820 ( 0.00%) Some(module) => module, . None if path.is_empty() => ModuleOrUniformRoot::CurrentScope, . _ => span_bug!(path_span, "resolve_path: non-empty path `{:?}` has no module", path), . }) 141,048 ( 0.01%) } . 124,500 ( 0.01%) fn lint_if_path_starts_with_module( . &mut self, . crate_lint: CrateLint, . path: &[Segment], . path_span: Span, . second_binding: Option<&NameBinding<'_>>, . ) { 51,875 ( 0.00%) let (diag_id, diag_span) = match crate_lint { . CrateLint::No => return, . CrateLint::SimplePath(id) => (id, path_span), . CrateLint::UsePath { root_id, root_span } => (root_id, root_span), . CrateLint::QPathTrait { qpath_id, qpath_span } => (qpath_id, qpath_span), . }; . 10,372 ( 0.00%) let first_name = match path.get(0) { . // In the 2018 edition this lint is a hard error, so nothing to do 20,744 ( 0.00%) Some(seg) if seg.ident.span.rust_2015() && self.session.rust_2015() => seg.ident.name, . _ => return, . }; . . // We're only interested in `use` paths which should start with . // `{{root}}` currently. . if first_name != kw::PathRoot { . return; . } -- line 2653 ---------------------------------------- -- line 2679 ---------------------------------------- . self.lint_buffer.buffer_lint_with_diagnostic( . lint::builtin::ABSOLUTE_PATHS_NOT_STARTING_WITH_CRATE, . diag_id, . diag_span, . "absolute paths must start with `self`, `super`, \ . `crate`, or an external crate name in the 2018 edition", . diag, . ); 83,000 ( 0.00%) } . . // Validate a local resolution (from ribs). . fn validate_res_from_ribs( . &mut self, . rib_index: usize, . rib_ident: Ident, . mut res: Res, . record_used: bool, . span: Span, . original_rib_ident_def: Ident, . all_ribs: &[Rib<'a>], . ) -> Res { . const CG_BUG_STR: &str = "min_const_generics resolve check didn't stop compilation"; . debug!("validate_res_from_ribs({:?})", res); 760 ( 0.00%) let ribs = &all_ribs[rib_index + 1..]; . . // An invalid forward use of a generic parameter from a previous default. 1,520 ( 0.00%) if let ForwardGenericParamBanRibKind = all_ribs[rib_index].kind { . if record_used { . let res_error = if rib_ident.name == kw::SelfUpper { . ResolutionError::SelfInGenericParamDefault . } else { . ResolutionError::ForwardDeclaredGenericParam . }; . self.report_error(span, res_error); . } . assert_eq!(res, Res::Err); . return Res::Err; . } . 2,573 ( 0.00%) match res { . Res::Local(_) => { . use ResolutionError::*; 332 ( 0.00%) let mut res_err = None; . . for rib in ribs { 2,372 ( 0.00%) match rib.kind { . NormalRibKind . | ClosureOrAsyncRibKind . | ModuleRibKind(..) . | MacroDefinition(..) . | ForwardGenericParamBanRibKind => { . // Nothing to do. Continue. . } . ItemRibKind(_) | FnItemRibKind | AssocItemRibKind => { . // This was an attempt to access an upvar inside a . // named function item. This is not allowed, so we . // report an error. 222 ( 0.00%) if record_used { . // We don't immediately trigger a resolve error, because . // we want certain other resolution errors (namely those . // emitted for `ConstantItemRibKind` below) to take . // precedence. . res_err = Some(CannotCaptureDynamicEnvironmentInFnItem); . } . } . ConstantItemRibKind(_, item) => { -- line 2744 ---------------------------------------- -- line 2773 ---------------------------------------- . ConstParamTyRibKind => { . if record_used { . self.report_error(span, ParamInTyOfConstParam(rib_ident.name)); . } . return Res::Err; . } . } . } 224 ( 0.00%) if let Some(res_err) = res_err { . self.report_error(span, res_err); . return Res::Err; . } . } . Res::Def(DefKind::TyParam, _) | Res::SelfTy(..) => { . for rib in ribs { 315 ( 0.00%) let has_generic_params: HasGenericParams = match rib.kind { . NormalRibKind . | ClosureOrAsyncRibKind . | AssocItemRibKind . | ModuleRibKind(..) . | MacroDefinition(..) . | ForwardGenericParamBanRibKind => { . // Nothing to do. Continue. . continue; -- line 2796 ---------------------------------------- -- line 2799 ---------------------------------------- . ConstantItemRibKind(trivial, _) => { . let features = self.session.features_untracked(); . // HACK(min_const_generics): We currently only allow `N` or `{ N }`. . if !(trivial || features.generic_const_exprs) { . // HACK(min_const_generics): If we encounter `Self` in an anonymous constant . // we can't easily tell if it's generic at this stage, so we instead remember . // this and then enforce the self type to be concrete later on. . if let Res::SelfTy(trait_def, Some((impl_def, _))) = res { 45 ( 0.00%) res = Res::SelfTy(trait_def, Some((impl_def, true))); . } else { . if record_used { . self.report_error( . span, . ResolutionError::ParamInNonTrivialAnonConst { . name: rib_ident.name, . is_type: true, . }, -- line 2815 ---------------------------------------- -- line 2912 ---------------------------------------- . ), . ); . } . return Res::Err; . } . } . _ => {} . } 1,520 ( 0.00%) res . } . . fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) { . debug!("(recording res) recording {:?} for {}", resolution, node_id); 32,750 ( 0.00%) if let Some(prev_res) = self.partial_res_map.insert(node_id, resolution) { . panic!("path resolved multiple times ({:?} before, {:?} now)", prev_res, resolution); . } . } . . fn record_pat_span(&mut self, node: NodeId, span: Span) { . debug!("(recording pat) recording {:?} for {:?}", node, span); . self.pat_span_map.insert(node, span); . } . . fn is_accessible_from(&self, vis: ty::Visibility, module: Module<'a>) -> bool { 99,930 ( 0.00%) vis.is_accessible_from(module.nearest_parent_mod(), self) . } . . fn set_binding_parent_module(&mut self, binding: &'a NameBinding<'a>, module: Module<'a>) { 4,728 ( 0.00%) if let Some(old_module) = self.binding_parent_modules.insert(PtrKey(binding), module) { . if !ptr::eq(module, old_module) { . span_bug!(binding.span, "parent module is reset for binding"); . } . } . } . . fn disambiguate_macro_rules_vs_modularized( . &self, -- line 2948 ---------------------------------------- -- line 2959 ---------------------------------------- . (Some(macro_rules), Some(modularized)) => { . macro_rules.nearest_parent_mod() == modularized.nearest_parent_mod() . && modularized.is_ancestor_of(macro_rules) . } . _ => false, . } . } . 7 ( 0.00%) fn report_errors(&mut self, krate: &Crate) { . self.report_with_use_injections(krate); . 6 ( 0.00%) for &(span_use, span_def) in &self.macro_expanded_macro_export_errors { . let msg = "macro-expanded `macro_export` macros from the current crate \ . cannot be referred to by absolute paths"; . self.lint_buffer.buffer_lint_with_diagnostic( . lint::builtin::MACRO_EXPANDED_MACRO_EXPORTS_ACCESSED_BY_ABSOLUTE_PATHS, . CRATE_NODE_ID, . span_use, . msg, . BuiltinLintDiagnostics::MacroExpandedMacroExportsAccessedByAbsolutePaths(span_def), -- line 2978 ---------------------------------------- -- line 2984 ---------------------------------------- . } . . let mut reported_spans = FxHashSet::default(); . for error in &self.privacy_errors { . if reported_spans.insert(error.dedup_span) { . self.report_privacy_error(error); . } . } 8 ( 0.00%) } . . fn report_with_use_injections(&mut self, krate: &Crate) { . for UseError { mut err, candidates, def_id, instead, suggestion } in 10 ( 0.00%) self.use_injections.drain(..) . { . let (span, found_use) = if let Some(def_id) = def_id.as_local() { . UsePlacementFinder::check(krate, self.def_id_to_node_id[def_id]) . } else { . (None, false) . }; . if !candidates.is_empty() { . diagnostics::show_candidates( -- line 3004 ---------------------------------------- -- line 3284 ---------------------------------------- . } . . return; . } . . err.span_suggestion(span, message, String::new(), Applicability::MachineApplicable); . } . 760 ( 0.00%) fn extern_prelude_get( . &mut self, . ident: Ident, . speculative: bool, . ) -> Option<&'a NameBinding<'a>> { 380 ( 0.00%) if ident.is_path_segment_keyword() { . // Make sure `self`, `super` etc produce an error when passed to here. . return None; . } 684 ( 0.00%) self.extern_prelude.get(&ident.normalize_to_macros_2_0()).cloned().and_then(|entry| { 56 ( 0.00%) if let Some(binding) = entry.extern_crate_item { 60 ( 0.00%) if !speculative && entry.introduced_by_item { . self.record_use(ident, binding, false); . } . Some(binding) . } else { 8 ( 0.00%) let crate_id = if !speculative { 2 ( 0.00%) let Some(crate_id) = 3 ( 0.00%) self.crate_loader.process_path_extern(ident.name, ident.span) else { return Some(self.dummy_binding); }; . crate_id . } else { 12 ( 0.00%) self.crate_loader.maybe_process_path_extern(ident.name)? . }; . let crate_root = self.expect_module(crate_id.as_def_id()); . Some( . (crate_root, ty::Visibility::Public, DUMMY_SP, LocalExpnId::ROOT) 4 ( 0.00%) .to_name_binding(self.arenas), . ) . } . }) 608 ( 0.00%) } . . /// Rustdoc uses this to resolve things in a recoverable way. `ResolutionError<'a>` . /// isn't something that can be returned because it can't be made to live that long, . /// and also it's a private type. Fortunately rustdoc doesn't need to know the error, . /// just that an error occurred. . // FIXME(Manishearth): intra-doc links won't get warned of epoch changes. . pub fn resolve_str_path_error( . &mut self, -- line 3330 ---------------------------------------- -- line 3422 ---------------------------------------- . #[inline] . pub fn opt_span(&self, def_id: DefId) -> Option { . def_id.as_local().map(|def_id| self.definitions.def_span(def_id)) . } . . /// Checks if an expression refers to a function marked with . /// `#[rustc_legacy_const_generics]` and returns the argument index list . /// from the attribute. 4,784 ( 0.00%) pub fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option> { 2,392 ( 0.00%) if let ExprKind::Path(None, path) = &expr.kind { . // Don't perform legacy const generics rewriting if the path already . // has generic arguments. 598 ( 0.00%) if path.segments.last().unwrap().args.is_some() { . return None; . } . . let partial_res = self.partial_res_map.get(&expr.id)?; 1,196 ( 0.00%) if partial_res.unresolved_segments() != 0 { . return None; . } . 1,928 ( 0.00%) if let Res::Def(def::DefKind::Fn, def_id) = partial_res.base_res() { . // We only support cross-crate argument rewriting. Uses . // within the same crate should be updated to use the new . // const generics style. 18 ( 0.00%) if def_id.is_local() { . return None; . } . . if let Some(v) = self.legacy_const_generic_args.get(&def_id) { . return v.clone(); . } . 108 ( 0.00%) let attr = self . .cstore() 36 ( 0.00%) .item_attrs_untracked(def_id, self.session) . .find(|a| a.has_name(sym::rustc_legacy_const_generics))?; . let mut ret = Vec::new(); . for meta in attr.meta_item_list()? { . match meta.literal()?.kind { . LitKind::Int(a, _) => ret.push(a as usize), . _ => panic!("invalid arg index"), . } . } . // Cache the lookup to avoid parsing attributes for an iterm multiple times. . self.legacy_const_generic_args.insert(def_id, Some(ret.clone())); . return Some(ret); . } . } . None 5,382 ( 0.00%) } . 7 ( 0.00%) fn resolve_main(&mut self) { 2 ( 0.00%) let module = self.graph_root; . let ident = Ident::with_dummy_span(sym::main); . let parent_scope = &ParentScope::module(module, self); . . let name_binding = match self.resolve_ident_in_module( . ModuleOrUniformRoot::Module(module), . ident, . ValueNS, . parent_scope, -- line 3483 ---------------------------------------- -- line 3490 ---------------------------------------- . . let res = name_binding.res(); . let is_import = name_binding.is_import(); . let span = name_binding.span; . if let Res::Def(DefKind::Fn, _) = res { . self.record_use(ident, name_binding, false); . } . self.main_def = Some(MainDefinition { res, is_import, span }); 8 ( 0.00%) } . } . . fn names_to_string(names: &[Symbol]) -> String { . let mut result = String::new(); . for (i, name) in names.iter().filter(|name| **name != kw::PathRoot).enumerate() { . if i > 0 { . result.push_str("::"); . } -- line 3506 ---------------------------------------- -- line 3558 ---------------------------------------- . /// This is the "trait item" from a fully qualified path. For example, . /// we might be resolving `X::Y::Z` from a path like `::Z`. . /// The `path_span` is the span of the to the trait itself (`X::Y`). . QPathTrait { qpath_id: NodeId, qpath_span: Span }, . } . . impl CrateLint { . fn node_id(&self) -> Option { 16,911 ( 0.00%) match *self { . CrateLint::No => None, . CrateLint::SimplePath(id) . | CrateLint::UsePath { root_id: id, .. } . | CrateLint::QPathTrait { qpath_id: id, .. } => Some(id), . } . } . } . . pub fn provide(providers: &mut Providers) { . late::lifetimes::provide(providers); 1 ( 0.00%) } 1,210,852 ( 0.06%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe/transcribe.rs -------------------------------------------------------------------------------- Ir -- line 16 ---------------------------------------- . use std::mem; . . // A Marker adds the given mark to the syntax context. . struct Marker(LocalExpnId, Transparency); . . impl MutVisitor for Marker { . const VISIT_TOKENS: bool = true; . 532,179 ( 0.03%) fn visit_span(&mut self, span: &mut Span) { 354,786 ( 0.02%) *span = span.apply_mark(self.0.to_expn_id(), self.1) 473,048 ( 0.02%) } . } . . /// An iterator over the token trees in a delimited token tree (`{ ... }`) or a sequence (`$(...)`). . enum Frame { . Delimited { forest: Lrc, idx: usize, span: DelimSpan }, . Sequence { forest: Lrc, idx: usize, sep: Option }, . } . . impl Frame { . /// Construct a new frame around the delimited set of tokens. . fn new(tts: Vec) -> Frame { . let forest = Lrc::new(mbe::Delimited { delim: token::NoDelim, tts }); 36,528 ( 0.00%) Frame::Delimited { forest, idx: 0, span: DelimSpan::dummy() } . } . } . . impl Iterator for Frame { . type Item = mbe::TokenTree; . . fn next(&mut self) -> Option { 296,064 ( 0.01%) match *self { 133,520 ( 0.01%) Frame::Delimited { ref forest, ref mut idx, .. } => { 200,280 ( 0.01%) *idx += 1; . forest.tts.get(*idx - 1).cloned() . } 21,768 ( 0.00%) Frame::Sequence { ref forest, ref mut idx, .. } => { 21,768 ( 0.00%) *idx += 1; . forest.tts.get(*idx - 1).cloned() . } . } . } . } . . /// This can do Macro-By-Example transcription. . /// - `interp` is a map of meta-variables to the tokens (non-terminals) they matched in the -- line 61 ---------------------------------------- -- line 72 ---------------------------------------- . /// foo!(bar); . /// ``` . /// . /// `interp` would contain `$id => bar` and `src` would contain `println!("{}", stringify!($id));`. . /// . /// `transcribe` would return a `TokenStream` containing `println!("{}", stringify!(bar));`. . /// . /// Along the way, we do some additional error checking. 45,660 ( 0.00%) pub(super) fn transcribe<'a>( . cx: &ExtCtxt<'a>, . interp: &FxHashMap, . src: Vec, . transparency: Transparency, . ) -> PResult<'a, TokenStream> { . // Nothing for us to transcribe... 4,566 ( 0.00%) if src.is_empty() { . return Ok(TokenStream::default()); . } . . // We descend into the RHS (`src`), expanding things as we go. This stack contains the things . // we have yet to expand/are still expanding. We start the stack off with the whole RHS. 36,528 ( 0.00%) let mut stack: SmallVec<[Frame; 1]> = smallvec![Frame::new(src)]; . . // As we descend in the RHS, we will need to be able to match nested sequences of matchers. . // `repeats` keeps track of where we are in matching at each level, with the last element being . // the most deeply nested sequence. This is used as a stack. . let mut repeats = Vec::new(); . . // `result` contains resulting token stream from the TokenTree we just finished processing. At . // the end, this will contain the full result of transcription, but at arbitrary points during -- line 101 ---------------------------------------- -- line 105 ---------------------------------------- . // `result_stack` and clear `results`. We will then produce the results of transcribing the . // TokenTree into `results`. Then, as we unwind back out of the `TokenTree`, we will pop the . // `result_stack` and append `results` too it to produce the new `results` up to that point. . // . // Thus, if we try to pop the `result_stack` and it is empty, we have reached the top-level . // again, and we are done transcribing. . let mut result: Vec = Vec::new(); . let mut result_stack = Vec::new(); 18,264 ( 0.00%) let mut marker = Marker(cx.current_expansion.id, transparency); . . loop { . // Look at the last frame on the stack. . // If it still has a TokenTree we have not looked at yet, use that tree. 506,593 ( 0.02%) let Some(tree) = stack.last_mut().unwrap().next() else { . // This else-case never produces a value for `tree` (it `continue`s or `return`s). . . // Otherwise, if we have just reached the end of a sequence and we can keep repeating, . // go back to the beginning of the sequence. 45,576 ( 0.00%) if let Frame::Sequence { idx, sep, .. } = stack.last_mut().unwrap() { . let (repeat_idx, repeat_len) = repeats.last_mut().unwrap(); 4,468 ( 0.00%) *repeat_idx += 1; 1,117 ( 0.00%) if repeat_idx < repeat_len { 1,023 ( 0.00%) *idx = 0; 2,046 ( 0.00%) if let Some(sep) = sep { . result.push(TokenTree::Token(sep.clone()).into()); . } . continue; . } . } . . // We are done with the top of the stack. Pop it. Depending on what it was, we do . // different things. Note that the outermost item must be the delimited, wrapped RHS . // that was passed in originally to `transcribe`. 20,742 ( 0.00%) match stack.pop().unwrap() { . // Done with a sequence. Pop from repeats. . Frame::Sequence { .. } => { . repeats.pop(); . } . . // We are done processing a Delimited. If this is the top-level delimited, we are . // done. Otherwise, we unwind the result_stack to append what we have produced to . // any previous results. 41,108 ( 0.00%) Frame::Delimited { forest, span, .. } => { 10,277 ( 0.00%) if result_stack.is_empty() { . // No results left to compute! We are back at the top-level. 27,396 ( 0.00%) return Ok(TokenStream::new(result)); . } . . // Step back into the parent Delimited. 74,243 ( 0.00%) let tree = TokenTree::Delimited(span, forest.delim, TokenStream::new(result)); 17,133 ( 0.00%) result = result_stack.pop().unwrap(); . result.push(tree.into()); . } 20,554 ( 0.00%) } . continue; . }; . . // At this point, we know we are in the middle of a TokenTree (the last one on `stack`). . // `tree` contains the next `TokenTree` to be processed. 375,732 ( 0.02%) match tree { . // We are descending into a sequence. We first make sure that the matchers in the RHS . // and the matches in `interp` have the same shape. Otherwise, either the caller or the . // macro writer has made a mistake. 376 ( 0.00%) seq @ mbe::TokenTree::Sequence(..) => { 658 ( 0.00%) match lockstep_iter_size(&seq, interp, &repeats) { . LockstepIterSize::Unconstrained => { . return Err(cx.struct_span_err( . seq.span(), /* blame macro writer */ . "attempted to repeat an expression containing no syntax variables \ . matched as repeating at this depth", . )); . } . -- line 177 ---------------------------------------- -- line 181 ---------------------------------------- . // sequence, but they come from different sequence matchers and repeat . // different amounts. . return Err(cx.struct_span_err(seq.span(), &msg)); . } . . LockstepIterSize::Constraint(len, _) => { . // We do this to avoid an extra clone above. We know that this is a . // sequence already. 658 ( 0.00%) let mbe::TokenTree::Sequence(sp, seq) = seq else { . unreachable!() . }; . . // Is the repetition empty? 188 ( 0.00%) if len == 0 { . if seq.kleene.op == mbe::KleeneOp::OneOrMore { . // FIXME: this really ought to be caught at macro definition . // time... It happens when the Kleene operator in the matcher and . // the body for the same meta-variable do not match. . return Err(cx.struct_span_err( . sp.entire(), . "this must repeat at least once", . )); -- line 202 ---------------------------------------- -- line 204 ---------------------------------------- . } else { . // 0 is the initial counter (we have done 0 repretitions so far). `len` . // is the total number of repetitions we should generate. . repeats.push((0, len)); . . // The first time we encounter the sequence we push it to the stack. It . // then gets reused (see the beginning of the loop) until we are done . // repeating. 846 ( 0.00%) stack.push(Frame::Sequence { . idx: 0, . sep: seq.separator.clone(), . forest: seq, . }); . } . } . } . } . . // Replace the meta-var with the matched token tree from the invocation. 68,292 ( 0.00%) mbe::TokenTree::MetaVar(mut sp, mut orignal_ident) => { . // Find the matched nonterminal from the macro invocation, and use it to replace . // the meta-var. 45,528 ( 0.00%) let ident = MacroRulesNormalizedIdent::new(orignal_ident); 68,292 ( 0.00%) if let Some(cur_matched) = lookup_cur_matched(ident, interp, &repeats) { 34,146 ( 0.00%) if let MatchedNonterminal(nt) = cur_matched { 34,146 ( 0.00%) let token = if let NtTT(tt) = &**nt { . // `tt`s are emitted into the output stream directly as "raw tokens", . // without wrapping them into groups. . tt.clone() . } else { . // Other variables are emitted into the output stream as groups with . // `Delimiter::None` to maintain parsing priorities. . // `Interpolated` is currenty used for such groups in rustc parser. 6,822 ( 0.00%) marker.visit_span(&mut sp); 13,644 ( 0.00%) TokenTree::token(token::Interpolated(nt.clone()), sp) . }; . result.push(token.into()); . } else { . // We were unable to descend far enough. This is an error. . return Err(cx.struct_span_err( . sp, /* blame the macro writer */ . &format!("variable '{}' is still repeating at this depth", ident), . )); -- line 246 ---------------------------------------- -- line 255 ---------------------------------------- . } . } . . // If we are entering a new delimiter, we push its contents to the `stack` to be . // processed, and we push all of the currently produced results to the `result_stack`. . // We will produce all of the results of the inside of the `Delimited` and then we will . // jump back out of the Delimited, pop the result_stack and add the new results back to . // the previous results (from outside the Delimited). 34,266 ( 0.00%) mbe::TokenTree::Delimited(mut span, delimited) => { . mut_visit::visit_delim_span(&mut span, &mut marker); 34,266 ( 0.00%) stack.push(Frame::Delimited { forest: delimited, idx: 0, span }); . result_stack.push(mem::take(&mut result)); . } . . // Nothing much to do here. Just push the token to the result, being careful to . // preserve syntax context. . mbe::TokenTree::Token(token) => { 272,610 ( 0.01%) let mut tt = TokenTree::Token(token); 136,305 ( 0.01%) mut_visit::visit_tt(&mut tt, &mut marker); . result.push(tt.into()); . } . . // There should be no meta-var declarations in the invocation of a macro. . mbe::TokenTree::MetaVarDecl(..) => panic!("unexpected `TokenTree::MetaVarDecl"), . } . } 54,792 ( 0.00%) } . . /// Lookup the meta-var named `ident` and return the matched token tree from the invocation using . /// the set of matches `interpolations`. . /// . /// See the definition of `repeats` in the `transcribe` function. `repeats` is used to descend . /// into the right place in nested matchers. If we attempt to descend too far, the macro writer has . /// made a mistake, and we return `None`. 103,797 ( 0.00%) fn lookup_cur_matched<'a>( . ident: MacroRulesNormalizedIdent, . interpolations: &'a FxHashMap, . repeats: &[(usize, usize)], . ) -> Option<&'a NamedMatch> { . interpolations.get(&ident).map(|matched| { . let mut matched = matched; . for &(idx, _) in repeats { 14,408 ( 0.00%) match matched { . MatchedNonterminal(_) => break, 2,220 ( 0.00%) MatchedSeq(ref ads) => matched = ads.get(idx).unwrap(), . } . } . . matched . }) 103,797 ( 0.00%) } . . /// An accumulator over a TokenTree to be used with `fold`. During transcription, we need to make . /// sure that the size of each sequence and all of its nested sequences are the same as the sizes . /// of all the matched (nested) sequences in the macro invocation. If they don't match, somebody . /// has made a mistake (either the macro writer or caller). . #[derive(Clone)] . enum LockstepIterSize { . /// No constraints on length of matcher. This is true for any TokenTree variants except a -- line 313 ---------------------------------------- -- line 322 ---------------------------------------- . Contradiction(String), . } . . impl LockstepIterSize { . /// Find incompatibilities in matcher/invocation sizes. . /// - `Unconstrained` is compatible with everything. . /// - `Contradiction` is incompatible with everything. . /// - `Constraint(len)` is only compatible with other constraints of the same length. 4,158 ( 0.00%) fn with(self, other: LockstepIterSize) -> LockstepIterSize { 1,644 ( 0.00%) match self { . LockstepIterSize::Unconstrained => other, . LockstepIterSize::Contradiction(_) => self, 969 ( 0.00%) LockstepIterSize::Constraint(l_len, ref l_id) => match other { . LockstepIterSize::Unconstrained => self, . LockstepIterSize::Contradiction(_) => other, 99 ( 0.00%) LockstepIterSize::Constraint(r_len, _) if l_len == r_len => self, . LockstepIterSize::Constraint(r_len, r_id) => { . let msg = format!( . "meta-variable `{}` repeats {} time{}, but `{}` repeats {} time{}", . l_id, . l_len, . pluralize!(l_len), . r_id, . r_len, . pluralize!(r_len), . ); . LockstepIterSize::Contradiction(msg) . } . }, . } 3,492 ( 0.00%) } . } . . /// Given a `tree`, make sure that all sequences have the same length as the matches for the . /// appropriate meta-vars in `interpolations`. . /// . /// Note that if `repeats` does not match the exact correct depth of a meta-var, . /// `lookup_cur_matched` will return `None`, which is why this still works even in the presence of . /// multiple nested matcher sequences. 5,560 ( 0.00%) fn lockstep_iter_size( . tree: &mbe::TokenTree, . interpolations: &FxHashMap, . repeats: &[(usize, usize)], . ) -> LockstepIterSize { . use mbe::TokenTree; 3,892 ( 0.00%) match *tree { . TokenTree::Delimited(_, ref delimed) => { 88 ( 0.00%) delimed.tts.iter().fold(LockstepIterSize::Unconstrained, |size, tt| { 1,584 ( 0.00%) size.with(lockstep_iter_size(tt, interpolations, repeats)) . }) . } . TokenTree::Sequence(_, ref seq) => { 97 ( 0.00%) seq.tts.iter().fold(LockstepIterSize::Unconstrained, |size, tt| { 5,347 ( 0.00%) size.with(lockstep_iter_size(tt, interpolations, repeats)) . }) . } . TokenTree::MetaVar(_, name) | TokenTree::MetaVarDecl(_, name, _) => { 302 ( 0.00%) let name = MacroRulesNormalizedIdent::new(name); 1,359 ( 0.00%) match lookup_cur_matched(name, interpolations, repeats) { 302 ( 0.00%) Some(matched) => match matched { . MatchedNonterminal(_) => LockstepIterSize::Unconstrained, 762 ( 0.00%) MatchedSeq(ref ads) => LockstepIterSize::Constraint(ads.len(), name), . }, . _ => LockstepIterSize::Unconstrained, . } . } . TokenTree::Token(..) => LockstepIterSize::Unconstrained, . } 4,448 ( 0.00%) } 783,628 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/coercion.rs -------------------------------------------------------------------------------- Ir -- line 73 ---------------------------------------- . /// See #47489 and #48598 . /// See docs on the "AllowTwoPhase" type for a more detailed discussion . allow_two_phase: AllowTwoPhase, . } . . impl<'a, 'tcx> Deref for Coerce<'a, 'tcx> { . type Target = FnCtxt<'a, 'tcx>; . fn deref(&self) -> &Self::Target { 212,417 ( 0.01%) &self.fcx . } . } . . type CoerceResult<'tcx> = InferResult<'tcx, (Vec>, Ty<'tcx>)>; . . /// Coercing a mutable reference to an immutable works, while . /// coercing `&T` to `&mut T` should be forbidden. . fn coerce_mutbls<'tcx>( . from_mutbl: hir::Mutability, . to_mutbl: hir::Mutability, . ) -> RelateResult<'tcx, ()> { 1,788 ( 0.00%) match (from_mutbl, to_mutbl) { . (hir::Mutability::Mut, hir::Mutability::Mut | hir::Mutability::Not) . | (hir::Mutability::Not, hir::Mutability::Not) => Ok(()), . (hir::Mutability::Not, hir::Mutability::Mut) => Err(TypeError::Mutability), . } . } . . /// Do not require any adjustments, i.e. coerce `x -> x`. . fn identity(_: Ty<'_>) -> Vec> { -- line 101 ---------------------------------------- -- line 107 ---------------------------------------- . } . . /// This always returns `Ok(...)`. . fn success<'tcx>( . adj: Vec>, . target: Ty<'tcx>, . obligations: traits::PredicateObligations<'tcx>, . ) -> CoerceResult<'tcx> { 57,462 ( 0.00%) Ok(InferOk { value: (adj, target), obligations }) . } . . impl<'f, 'tcx> Coerce<'f, 'tcx> { . fn new( . fcx: &'f FnCtxt<'f, 'tcx>, . cause: ObligationCause<'tcx>, . allow_two_phase: AllowTwoPhase, . ) -> Self { 152,476 ( 0.01%) Coerce { fcx, cause, allow_two_phase, use_lub: false } . } . 420,926 ( 0.02%) fn unify(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> InferResult<'tcx, Ty<'tcx>> { . debug!("unify(a: {:?}, b: {:?}, use_lub: {})", a, b, self.use_lub); . self.commit_if_ok(|_| { 76,532 ( 0.00%) if self.use_lub { 880 ( 0.00%) self.at(&self.cause, self.fcx.param_env).lub(b, a) . } else { 75,652 ( 0.00%) self.at(&self.cause, self.fcx.param_env) . .sup(b, a) . .map(|InferOk { value: (), obligations }| InferOk { value: a, obligations }) . } . }) 306,128 ( 0.01%) } . . /// Unify two types (using sub or lub) and produce a specific coercion. 75,364 ( 0.00%) fn unify_and(&self, a: Ty<'tcx>, b: Ty<'tcx>, f: F) -> CoerceResult<'tcx> . where . F: FnOnce(Ty<'tcx>) -> Vec>, . { 95,361 ( 0.00%) self.unify(&a, &b) 76,520 ( 0.00%) .and_then(|InferOk { value: ty, obligations }| success(f(ty), ty, obligations)) 56,523 ( 0.00%) } . 401,982 ( 0.02%) #[instrument(skip(self))] . fn coerce(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> { . // First, remove any resolved type variables (at the top level, at least): 19,142 ( 0.00%) let a = self.shallow_resolve(a); 19,142 ( 0.00%) let b = self.shallow_resolve(b); . debug!("Coerce.tys({:?} => {:?})", a, b); . . // Just ignore error types. 38,284 ( 0.00%) if a.references_error() || b.references_error() { . return success(vec![], self.fcx.tcx.ty_error(), vec![]); . } . . // Coercing from `!` to any type is allowed: 19,142 ( 0.00%) if a.is_never() { . return success(simple(Adjust::NeverToAny)(b), b, vec![]); . } . . // Coercing *from* an unresolved inference variable means that . // we have no information about the source type. This will always . // ultimately fall back to some form of subtyping. 19,142 ( 0.00%) if a.is_ty_var() { . return self.coerce_from_inference_variable(a, b, identity); . } . . // Consider coercing the subtype to a DST . // . // NOTE: this is wrapped in a `commit_if_ok` because it creates . // a "spurious" type variable, and we don't want to have that . // type variable in memory if the coercion fails. . let unsize = self.commit_if_ok(|_| self.coerce_unsized(a, b)); 76,556 ( 0.00%) match unsize { . Ok(_) => { . debug!("coerce: unsize successful"); 90 ( 0.00%) return unsize; . } . Err(TypeError::ObjectUnsafeCoercion(did)) => { . debug!("coerce: unsize not object safe"); . return Err(TypeError::ObjectUnsafeCoercion(did)); . } . Err(error) => { . debug!(?error, "coerce: unsize failed"); . } . } . . // Examine the supertype and consider auto-borrowing. 95,090 ( 0.00%) match *b.kind() { . ty::RawPtr(mt_b) => { . return self.coerce_unsafe_ptr(a, b, mt_b.mutbl); . } 590 ( 0.00%) ty::Ref(r_b, _, mutbl_b) => { 1,770 ( 0.00%) return self.coerce_borrowed_pointer(a, b, r_b, mutbl_b); . } . _ => {} . } . 131,887 ( 0.01%) match *a.kind() { . ty::FnDef(..) => { . // Function items are coercible to any closure . // type; function pointers are not (that would . // require double indirection). . // Additionally, we permit coercion of function . // items to drop the unsafe qualifier. . self.coerce_from_fn_item(a, b) . } -- line 212 ---------------------------------------- -- line 218 ---------------------------------------- . ty::Closure(closure_def_id_a, substs_a) => { . // Non-capturing closures are coercible to . // function pointers or unsafe function pointers. . // It cannot convert closures that require unsafe. . self.coerce_closure_to_fn(a, closure_def_id_a, substs_a, b) . } . _ => { . // Otherwise, just use unification rules. 94,205 ( 0.00%) self.unify_and(a, b, identity) . } . } 38,284 ( 0.00%) } . . /// Coercing *from* an inference variable. In this case, we have no information . /// about the source type, so we can't really do a true coercion and we always . /// fall back to subtyping (`unify_and`). . fn coerce_from_inference_variable( . &self, . a: Ty<'tcx>, . b: Ty<'tcx>, -- line 237 ---------------------------------------- -- line 278 ---------------------------------------- . // to do something useful. . self.unify_and(a, b, make_adjustments) . } . } . . /// Reborrows `&mut A` to `&mut B` and `&(mut) A` to `&B`. . /// To match `A` with `B`, autoderef will be performed, . /// calling `deref`/`deref_mut` where necessary. 2,950 ( 0.00%) fn coerce_borrowed_pointer( . &self, . a: Ty<'tcx>, . b: Ty<'tcx>, . r_b: ty::Region<'tcx>, . mutbl_b: hir::Mutability, . ) -> CoerceResult<'tcx> { . debug!("coerce_borrowed_pointer(a={:?}, b={:?})", a, b); . . // If we have a parameter of type `&M T_a` and the value . // provided is `expr`, we will be adding an implicit borrow, . // meaning that we convert `f(expr)` to `f(&M *expr)`. Therefore, . // to type check, we will construct the type that `&M*expr` would . // yield. . 590 ( 0.00%) let (r_a, mt_a) = match *a.kind() { 885 ( 0.00%) ty::Ref(r_a, ty, mutbl) => { . let mt_a = ty::TypeAndMut { ty, mutbl }; . coerce_mutbls(mt_a.mutbl, mutbl_b)?; . (r_a, mt_a) . } . _ => return self.unify_and(a, b, identity), . }; . 590 ( 0.00%) let span = self.cause.span; . . let mut first_error = None; . let mut r_borrow_var = None; . let mut autoderef = self.autoderef(span, a); . let mut found = None; . 1,180 ( 0.00%) for (referent_ty, autoderefs) in autoderef.by_ref() { 1,180 ( 0.00%) if autoderefs == 0 { . // Don't let this pass, otherwise it would cause . // &T to autoref to &&T. . continue; . } . . // At this point, we have deref'd `a` to `referent_ty`. So . // imagine we are coercing from `&'a mut Vec` to `&'b mut [T]`. . // In the autoderef loop for `&'a mut Vec`, we would get -- line 326 ---------------------------------------- -- line 386 ---------------------------------------- . // this extra edge causes the region `'a` to be inferred to something . // too big, which then results in borrowck errors.) . // - We could track the innermost shared reference, but there is already . // code in regionck that has the job of creating links between . // the region of a borrow and the regions in the thing being . // borrowed (here, `'a` and `'x`), and it knows how to handle . // all the various cases. So instead we just make a region variable . // and let regionck figure it out. 590 ( 0.00%) let r = if !self.use_lub { . r_b // [2] above . } else if autoderefs == 1 { . r_a // [3] above . } else { . if r_borrow_var.is_none() { . // create var lazily, at most once . let coercion = Coercion(span); . let r = self.next_region_var(coercion); . r_borrow_var = Some(r); // [4] above . } . r_borrow_var.unwrap() . }; 295 ( 0.00%) let derefd_ty_a = self.tcx.mk_ref( . r, . TypeAndMut { . ty: referent_ty, . mutbl: mutbl_b, // [1] above . }, . ); 2,065 ( 0.00%) match self.unify(derefd_ty_a, b) { . Ok(ok) => { 1,180 ( 0.00%) found = Some(ok); . break; . } . Err(err) => { . if first_error.is_none() { . first_error = Some(err); . } . } . } . } . . // Extract type or return an error. We return the first error . // we got, which should be from relating the "base" type . // (e.g., in example above, the failure from relating `Vec` . // to the target type), since that should be the least . // confusing. 2,360 ( 0.00%) let InferOk { value: ty, mut obligations } = match found { . Some(d) => d, . None => { . let err = first_error.expect("coerce_borrowed_pointer had no error"); . debug!("coerce_borrowed_pointer: failed with err = {:?}", err); . return Err(err); . } . }; . 565 ( 0.00%) if ty == a && mt_a.mutbl == hir::Mutability::Not && autoderef.step_count() == 1 { . // As a special case, if we would produce `&'a *x`, that's . // a total no-op. We end up with the type `&'a T` just as . // we started with. In that case, just skip it . // altogether. This is just an optimization. . // . // Note that for `&mut`, we DO want to reborrow -- . // otherwise, this would be a move, which might be an . // error. For example `foo(self.x)` where `self` and . // `self.x` both have `&mut `type would be a move of . // `self.x`, but we auto-coerce it to `foo(&mut *self.x)`, . // which is a borrow. 108 ( 0.00%) assert_eq!(mutbl_b, hir::Mutability::Not); // can only coerce &T -> &U 216 ( 0.00%) return success(vec![], ty, obligations); . } . 1,687 ( 0.00%) let InferOk { value: mut adjustments, obligations: o } = 241 ( 0.00%) self.adjust_steps_as_infer_ok(&autoderef); . obligations.extend(o); 4,579 ( 0.00%) obligations.extend(autoderef.into_obligations()); . . // Now apply the autoref. We have to extract the region out of . // the final ref type we got. 482 ( 0.00%) let r_borrow = match ty.kind() { . ty::Ref(r_borrow, _, _) => r_borrow, . _ => span_bug!(span, "expected a ref type, got {:?}", ty), . }; 964 ( 0.00%) let mutbl = match mutbl_b { . hir::Mutability::Not => AutoBorrowMutability::Not, . hir::Mutability::Mut => { . AutoBorrowMutability::Mut { allow_two_phase_borrow: self.allow_two_phase } . } . }; . adjustments.push(Adjustment { 241 ( 0.00%) kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mutbl)), . target: ty, . }); . . debug!("coerce_borrowed_pointer: succeeded ty={:?} adjustments={:?}", ty, adjustments); . 1,928 ( 0.00%) success(adjustments, ty, obligations) 2,360 ( 0.00%) } . . // &[T; n] or &mut [T; n] -> &[T] . // or &mut [T; n] -> &mut [T] . // or &Concrete -> &Trait, etc. . #[instrument(skip(self), level = "debug")] . fn coerce_unsized(&self, mut source: Ty<'tcx>, mut target: Ty<'tcx>) -> CoerceResult<'tcx> { . source = self.shallow_resolve(source); . target = self.shallow_resolve(target); -- line 490 ---------------------------------------- -- line 506 ---------------------------------------- . // would need to be generic over the self-type (`impl CoerceUnsized for T`) . // or generic over the `CoerceUnsized` type parameter (`impl CoerceUnsized for . // SomeType`). . // . // However, these are exactly the kinds of impls which are forbidden by . // the compiler! Therefore, we can be sure that coercion will always fail . // when either the source or target type is a type variable. This allows us . // to skip performing any trait selection, and immediately bail out. 19,142 ( 0.00%) if source.is_ty_var() { . debug!("coerce_unsized: source is a TyVar, bailing out"); . return Err(TypeError::Mismatch); . } 19,166 ( 0.00%) if target.is_ty_var() { . debug!("coerce_unsized: target is a TyVar, bailing out"); . return Err(TypeError::Mismatch); . } . . let traits = 229,560 ( 0.01%) (self.tcx.lang_items().unsize_trait(), self.tcx.lang_items().coerce_unsized_trait()); 76,520 ( 0.00%) let (Some(unsize_did), Some(coerce_unsized_did)) = traits else { . debug!("missing Unsize or CoerceUnsized traits"); . return Err(TypeError::Mismatch); . }; . . // Note, we want to avoid unnecessary unsizing. We don't want to coerce to . // a DST unless we have to. This currently comes out in the wash since . // we can't unify [T] with U. But to properly support DST, we need to allow . // that, at which point we will need extra checks on the target here. . . // Handle reborrows before selecting `Source: CoerceUnsized`. 39,163 ( 0.00%) let reborrow = match (source.kind(), target.kind()) { 903 ( 0.00%) (&ty::Ref(_, ty_a, mutbl_a), &ty::Ref(_, _, mutbl_b)) => { . coerce_mutbls(mutbl_a, mutbl_b)?; . 301 ( 0.00%) let coercion = Coercion(self.cause.span); 1,505 ( 0.00%) let r_borrow = self.next_region_var(coercion); . let mutbl = match mutbl_b { . hir::Mutability::Not => AutoBorrowMutability::Not, . hir::Mutability::Mut => AutoBorrowMutability::Mut { . // We don't allow two-phase borrows here, at least for initial . // implementation. If it happens that this coercion is a function argument, . // the reborrow in coerce_borrowed_ptr will pick it up. . allow_two_phase_borrow: AllowTwoPhase::No, . }, . }; . Some(( . Adjustment { kind: Adjust::Deref(None), target: ty_a }, . Adjustment { . kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mutbl)), 301 ( 0.00%) target: self . .tcx . .mk_ref(r_borrow, ty::TypeAndMut { mutbl: mutbl_b, ty: ty_a }), . }, . )) . } . (&ty::Ref(_, ty_a, mt_a), &ty::RawPtr(ty::TypeAndMut { mutbl: mt_b, .. })) => { . coerce_mutbls(mt_a, mt_b)?; . -- line 563 ---------------------------------------- -- line 574 ---------------------------------------- . let coerce_source = reborrow.as_ref().map_or(source, |&(_, ref r)| r.target); . . // Setup either a subtyping or a LUB relationship between . // the `CoerceUnsized` target type and the expected type. . // We only have the latter, so we use an inference variable . // for the former and let type inference do the rest. . let origin = TypeVariableOrigin { . kind: TypeVariableOriginKind::MiscVariable, 19,130 ( 0.00%) span: self.cause.span, . }; 95,650 ( 0.00%) let coerce_target = self.next_ty_var(origin); 76,520 ( 0.00%) let mut coercion = self.unify_and(coerce_target, target, |target| { . let unsize = Adjustment { kind: Adjust::Pointer(PointerCast::Unsize), target }; 38,260 ( 0.00%) match reborrow { 94,145 ( 0.00%) None => vec![unsize], 4,214 ( 0.00%) Some((ref deref, ref autoref)) => vec![deref.clone(), autoref.clone(), unsize], . } . })?; . 19,130 ( 0.00%) let mut selcx = traits::SelectionContext::new(self); . . // Create an obligation for `Source: CoerceUnsized`. . let cause = ObligationCause::new( 38,260 ( 0.00%) self.cause.span, 38,260 ( 0.00%) self.body_id, . ObligationCauseCode::Coercion { source, target }, . ); . . // Use a FIFO queue for this custom fulfillment procedure. . // . // A Vec (or SmallVec) is not a natural choice for a queue. However, . // this code path is hot, and this queue usually has a max length of 1 . // and almost never more than 3. By using a SmallVec we avoid an . // allocation, at the (very small) cost of (occasionally) having to . // shift subsequent elements down when removing the front element. 267,820 ( 0.01%) let mut queue: SmallVec<[_; 4]> = smallvec![traits::predicate_for_trait_def( 38,260 ( 0.00%) self.tcx, 19,130 ( 0.00%) self.fcx.param_env, 95,650 ( 0.00%) cause, . coerce_unsized_did, . 0, . coerce_source, 95,650 ( 0.00%) &[coerce_target.into()] . )]; . . let mut has_unsized_tuple_coercion = false; . let mut has_trait_upcasting_coercion = false; . . // Keep resolving `CoerceUnsized` and `Unsize` predicates to avoid . // emitting a coercion in cases like `Foo<$1>` -> `Foo<$2>`, where . // inference might unify those two inner type variables later. . let traits = [coerce_unsized_did, unsize_did]; 39,354 ( 0.00%) while !queue.is_empty() { . let obligation = queue.remove(0); . debug!("coerce_unsized resolve step: {:?}", obligation); 19,671 ( 0.00%) let bound_predicate = obligation.predicate.kind(); 98,355 ( 0.00%) let trait_pred = match bound_predicate.skip_binder() { 116,586 ( 0.01%) ty::PredicateKind::Trait(trait_pred) if traits.contains(&trait_pred.def_id()) => { 174,879 ( 0.01%) if unsize_did == trait_pred.def_id() { 1,806 ( 0.00%) let self_ty = trait_pred.self_ty(); 1,204 ( 0.00%) let unsize_ty = trait_pred.trait_ref.substs[1].expect_ty(); 1,505 ( 0.00%) if let (ty::Dynamic(ref data_a, ..), ty::Dynamic(ref data_b, ..)) = . (self_ty.kind(), unsize_ty.kind()) . { . if data_a.principal_def_id() != data_b.principal_def_id() { . debug!("coerce_unsized: found trait upcasting coercion"); . has_trait_upcasting_coercion = true; . } . } 1,806 ( 0.00%) if let ty::Tuple(..) = unsize_ty.kind() { . debug!("coerce_unsized: found unsized tuple coercion"); . has_unsized_tuple_coercion = true; . } . } 38,862 ( 0.00%) bound_predicate.rebind(trait_pred) . } . _ => { 1,440 ( 0.00%) coercion.obligations.push(obligation); . continue; . } . }; 213,741 ( 0.01%) match selcx.select(&obligation.with(trait_pred)) { . // Uncertain or unimplemented. . Ok(None) => { 234 ( 0.00%) if trait_pred.def_id() == unsize_did { 108 ( 0.00%) let trait_pred = self.resolve_vars_if_possible(trait_pred); 36 ( 0.00%) let self_ty = trait_pred.skip_binder().self_ty(); 108 ( 0.00%) let unsize_ty = trait_pred.skip_binder().trait_ref.substs[1].expect_ty(); . debug!("coerce_unsized: ambiguous unsize case for {:?}", trait_pred); 36 ( 0.00%) match (&self_ty.kind(), &unsize_ty.kind()) { . (ty::Infer(ty::TyVar(v)), ty::Dynamic(..)) . if self.type_var_is_sized(*v) => . { . debug!("coerce_unsized: have sized infer {:?}", v); . coercion.obligations.push(obligation); . // `$0: Unsize` where we know that `$0: Sized`, try going . // for unsizing. . } -- line 671 ---------------------------------------- -- line 679 ---------------------------------------- . } . } else { . debug!("coerce_unsized: early return - ambiguous"); . return Err(TypeError::Mismatch); . } . } . Err(traits::Unimplemented) => { . debug!("coerce_unsized: early return - can't prove obligation"); 114,636 ( 0.01%) return Err(TypeError::Mismatch); . } . . // Object safety violations or miscellaneous. . Err(err) => { . self.report_selection_error(obligation.clone(), &obligation, &err, false); . // Treat this like an obligation and follow through . // with the unsizing - the lack of a coercion should . // be silent, as it causes a type mismatch later. . } . 5,833 ( 0.00%) Ok(Some(impl_source)) => queue.extend(impl_source.nested_obligations()), . } 38,248 ( 0.00%) } . 12 ( 0.00%) if has_unsized_tuple_coercion && !self.tcx.features().unsized_tuple_coercion { . feature_err( . &self.tcx.sess.parse_sess, . sym::unsized_tuple_coercion, . self.cause.span, . "unsized tuple coercion is not stable enough for use and is subject to change", . ) . .emit(); . } . 12 ( 0.00%) if has_trait_upcasting_coercion && !self.tcx().features().trait_upcasting { . feature_err( . &self.tcx.sess.parse_sess, . sym::trait_upcasting, . self.cause.span, . "trait upcasting coercion is experimental", . ) . .emit(); . } . 66 ( 0.00%) Ok(coercion) . } . . fn coerce_from_safe_fn( . &self, . a: Ty<'tcx>, . fn_ty_a: ty::PolyFnSig<'tcx>, . b: Ty<'tcx>, . to_unsafe: F, -- line 730 ---------------------------------------- -- line 906 ---------------------------------------- . } . } . . impl<'a, 'tcx> FnCtxt<'a, 'tcx> { . /// Attempt to coerce an expression to a type, and return the . /// adjusted type of the expression, if successful. . /// Adjustments are only recorded if the coercion succeeded. . /// The expressions *must not* have any pre-existing adjustments. 264,908 ( 0.01%) pub fn try_coerce( . &self, . expr: &hir::Expr<'_>, . expr_ty: Ty<'tcx>, . target: Ty<'tcx>, . allow_two_phase: AllowTwoPhase, . cause: Option>, . ) -> RelateResult<'tcx, Ty<'tcx>> { 56,766 ( 0.00%) let source = self.resolve_vars_with_obligations(expr_ty); . debug!("coercion::try({:?}: {:?} -> {:?})", expr, source, target); . . let cause = 18,922 ( 0.00%) cause.unwrap_or_else(|| self.cause(expr.span, ObligationCauseCode::ExprAssignable)); . let coerce = Coerce::new(self, cause, allow_two_phase); 227,064 ( 0.01%) let ok = self.commit_if_ok(|_| coerce.coerce(source, target))?; . 75,688 ( 0.00%) let (adjustments, _) = self.register_infer_ok_obligations(ok); 189,220 ( 0.01%) self.apply_adjustments(expr, adjustments); 56,766 ( 0.00%) Ok(if expr_ty.references_error() { self.tcx.ty_error() } else { target }) 170,298 ( 0.01%) } . . /// Same as `try_coerce()`, but without side-effects. . /// . /// Returns false if the coercion creates any obligations that result in . /// errors. . pub fn can_coerce(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> bool { . let source = self.resolve_vars_with_obligations(expr_ty); . debug!("coercion::can_with_predicates({:?} -> {:?})", source, target); -- line 941 ---------------------------------------- -- line 967 ---------------------------------------- . } . . /// Given some expressions, their known unified type and another expression, . /// tries to unify the types, potentially inserting coercions on any of the . /// provided expressions and returns their LUB (aka "common supertype"). . /// . /// This is really an internal helper. From outside the coercion . /// module, you should instantiate a `CoerceMany` instance. 65,442 ( 0.00%) fn try_find_coercion_lub( . &self, . cause: &ObligationCause<'tcx>, . exprs: &[E], . prev_ty: Ty<'tcx>, . new: &hir::Expr<'_>, . new_ty: Ty<'tcx>, . ) -> RelateResult<'tcx, Ty<'tcx>> . where . E: AsCoercionSite, . { 30,204 ( 0.00%) let prev_ty = self.resolve_vars_with_obligations(prev_ty); 15,102 ( 0.00%) let new_ty = self.resolve_vars_with_obligations(new_ty); . debug!( . "coercion::try_find_coercion_lub({:?}, {:?}, exprs={:?} exprs)", . prev_ty, . new_ty, . exprs.len() . ); . . // The following check fixes #88097, where the compiler erroneously . // attempted to coerce a closure type to itself via a function pointer. 5,034 ( 0.00%) if prev_ty == new_ty { 4,811 ( 0.00%) return Ok(prev_ty); . } . . // Special-case that coercion alone cannot handle: . // Function items or non-capturing closures of differing IDs or InternalSubsts. 1,760 ( 0.00%) let (a_sig, b_sig) = { 1,760 ( 0.00%) let is_capturing_closure = |ty| { 880 ( 0.00%) if let &ty::Closure(closure_def_id, _substs) = ty { . self.tcx.upvars_mentioned(closure_def_id.expect_local()).is_some() . } else { . false . } 1,760 ( 0.00%) }; 2,640 ( 0.00%) if is_capturing_closure(prev_ty.kind()) || is_capturing_closure(new_ty.kind()) { . (None, None) . } else { 1,320 ( 0.00%) match (prev_ty.kind(), new_ty.kind()) { . (ty::FnDef(..), ty::FnDef(..)) => { . // Don't reify if the function types have a LUB, i.e., they . // are the same function and their parameters have a LUB. . match self . .commit_if_ok(|_| self.at(cause, self.param_env).lub(prev_ty, new_ty)) . { . // We have a LUB of prev_ty and new_ty, just return it. . Ok(ok) => return Ok(self.register_infer_ok_obligations(ok)), -- line 1022 ---------------------------------------- -- line 1048 ---------------------------------------- . substs_b.as_closure().sig(), . hir::Unsafety::Normal, . )), . ), . _ => (None, None), . } . } . }; 880 ( 0.00%) if let (Some(a_sig), Some(b_sig)) = (a_sig, b_sig) { . // Intrinsics are not coercible to function pointers. . if a_sig.abi() == Abi::RustIntrinsic . || a_sig.abi() == Abi::PlatformIntrinsic . || b_sig.abi() == Abi::RustIntrinsic . || b_sig.abi() == Abi::PlatformIntrinsic . { . return Err(TypeError::IntrinsicCast); . } -- line 1064 ---------------------------------------- -- line 1094 ---------------------------------------- . } . . // Configure a Coerce instance to compute the LUB. . // We don't allow two-phase borrows on any autorefs this creates since we . // probably aren't processing function arguments here and even if we were, . // they're going to get autorefed again anyway and we can apply 2-phase borrows . // at that time. . let mut coerce = Coerce::new(self, cause.clone(), AllowTwoPhase::No); 220 ( 0.00%) coerce.use_lub = true; . . // First try to coerce the new expression to the type of the previous ones, . // but only if the new expression has no coercion already applied to it. . let mut first_error = None; 1,760 ( 0.00%) if !self.typeck_results.borrow().adjustments().contains_key(new.hir_id) { 20,902 ( 0.00%) let result = self.commit_if_ok(|_| coerce.coerce(new_ty, prev_ty)); 440 ( 0.00%) match result { . Ok(ok) => { 1,760 ( 0.00%) let (adjustments, target) = self.register_infer_ok_obligations(ok); 1,760 ( 0.00%) self.apply_adjustments(new, adjustments); . debug!( . "coercion::try_find_coercion_lub: was able to coerce from previous type {:?} to new type {:?}", . prev_ty, new_ty, . ); 440 ( 0.00%) return Ok(target); . } . Err(e) => first_error = Some(e), . } . } . . // Then try to coerce the previous expressions to the type of the new one. . // This requires ensuring there are no coercions applied to *any* of the . // previous expressions, other than noop reborrows (ignoring lifetimes). -- line 1125 ---------------------------------------- -- line 1175 ---------------------------------------- . let (adjustments, target) = self.register_infer_ok_obligations(ok); . for expr in exprs { . let expr = expr.as_coercion_site(); . self.apply_adjustments(expr, adjustments.clone()); . } . Ok(target) . } . } 45,306 ( 0.00%) } . } . . /// CoerceMany encapsulates the pattern you should use when you have . /// many expressions that are all getting coerced to a common . /// type. This arises, for example, when you have a match (the result . /// of each arm is coerced to a common type). It also arises in less . /// obvious places, such as when you have many `break foo` expressions . /// that target the same loop, or the various `return` expressions in -- line 1191 ---------------------------------------- -- line 1253 ---------------------------------------- . /// expected to pass each element in the slice to `coerce(...)` in . /// order. This is used with arrays in particular to avoid . /// needlessly cloning the slice. . pub fn with_coercion_sites(expected_ty: Ty<'tcx>, coercion_sites: &'exprs [E]) -> Self { . Self::make(expected_ty, Expressions::UpFront(coercion_sites)) . } . . fn make(expected_ty: Ty<'tcx>, expressions: Expressions<'tcx, 'exprs, E>) -> Self { 219 ( 0.00%) CoerceMany { expected_ty, final_ty: None, expressions, pushed: 0 } . } . . /// Returns the "expected type" with which this coercion was . /// constructed. This represents the "downward propagated" type . /// that was given to us at the start of typing whatever construct . /// we are typing (e.g., the match expression). . /// . /// Typically, this is used as the expected type when -- line 1269 ---------------------------------------- -- line 1281 ---------------------------------------- . self.final_ty.unwrap_or(self.expected_ty) . } . . /// Indicates that the value generated by `expression`, which is . /// of type `expression_ty`, is one of the possibilities that we . /// could coerce from. This will record `expression`, and later . /// calls to `coerce` may come back and add adjustments and things . /// if necessary. 55,308 ( 0.00%) pub fn coerce<'a>( . &mut self, . fcx: &FnCtxt<'a, 'tcx>, . cause: &ObligationCause<'tcx>, . expression: &'tcx hir::Expr<'tcx>, . expression_ty: Ty<'tcx>, . ) { 1,264 ( 0.00%) self.coerce_inner(fcx, cause, Some(expression), expression_ty, None, false) 36,872 ( 0.00%) } . . /// Indicates that one of the inputs is a "forced unit". This . /// occurs in a case like `if foo { ... };`, where the missing else . /// generates a "forced unit". Another example is a `loop { break; . /// }`, where the `break` has no argument expression. We treat . /// these cases slightly differently for error-reporting . /// purposes. Note that these tend to correspond to cases where . /// the `()` expression is implicit in the source, and hence we do -- line 1305 ---------------------------------------- -- line 1310 ---------------------------------------- . /// removing a `;`). . pub fn coerce_forced_unit<'a>( . &mut self, . fcx: &FnCtxt<'a, 'tcx>, . cause: &ObligationCause<'tcx>, . augment_error: &mut dyn FnMut(&mut DiagnosticBuilder<'_>), . label_unit_as_expected: bool, . ) { 27 ( 0.00%) self.coerce_inner( . fcx, . cause, . None, 3 ( 0.00%) fcx.tcx.mk_unit(), . Some(augment_error), . label_unit_as_expected, . ) . } . . /// The inner coercion "engine". If `expression` is `None`, this . /// is a forced-unit case, and hence `expression_ty` must be . /// `Nil`. 13,230 ( 0.00%) #[instrument(skip(self, fcx, augment_error, label_expression_as_expected), level = "debug")] . crate fn coerce_inner<'a>( . &mut self, . fcx: &FnCtxt<'a, 'tcx>, . cause: &ObligationCause<'tcx>, . expression: Option<&'tcx hir::Expr<'tcx>>, . mut expression_ty: Ty<'tcx>, . augment_error: Option<&mut dyn FnMut(&mut DiagnosticBuilder<'_>)>, . label_expression_as_expected: bool, . ) { . // Incorporate whatever type inference information we have . // until now; in principle we might also want to process . // pending obligations, but doing so should only improve . // compatibility (hopefully that is true) by helping us . // uncover never types better. 5,245 ( 0.00%) if expression_ty.is_ty_var() { . expression_ty = fcx.infcx.shallow_resolve(expression_ty); . } . . // If we see any error types, just propagate that error . // upwards. 20,956 ( 0.00%) if expression_ty.references_error() || self.merged_ty().references_error() { . self.final_ty = Some(fcx.tcx.ty_error()); . return; . } . . // Handle the actual type unification etc. 1,890 ( 0.00%) let result = if let Some(expression) = expression { 15,708 ( 0.00%) if self.pushed == 0 { . // Special-case the first expression we are coercing. . // To be honest, I'm not entirely sure why we do this. . // We don't allow two-phase borrows, see comment in try_find_coercion_lub for why 1,818 ( 0.00%) fcx.try_coerce( . expression, . expression_ty, . self.expected_ty, . AllowTwoPhase::No, 808 ( 0.00%) Some(cause.clone()), . ) . } else { 10,068 ( 0.00%) match self.expressions { 6 ( 0.00%) Expressions::Dynamic(ref exprs) => fcx.try_find_coercion_lub( . cause, . exprs, . self.merged_ty(), . expression, . expression_ty, . ), 30,614 ( 0.00%) Expressions::UpFront(ref coercion_sites) => fcx.try_find_coercion_lub( . cause, 15,093 ( 0.00%) &coercion_sites[0..self.pushed], . self.merged_ty(), . expression, . expression_ty, . ), . } . } . } else { . // this is a hack for cases where we default to `()` because -- line 1389 ---------------------------------------- -- line 1394 ---------------------------------------- . // . // we wind up with a second match arm that is like `_ => . // ()`. That is the case we are considering here. We take . // a different path to get the right "expected, found" . // message and so forth (and because we know that . // `expression_ty` will be unit). . // . // Another example is `break` with no argument expression. 3 ( 0.00%) assert!(expression_ty.is_unit(), "if let hack without unit type"); 6 ( 0.00%) fcx.at(cause, fcx.param_env) . .eq_exp(label_expression_as_expected, expression_ty, self.merged_ty()) . .map(|infer_ok| { . fcx.register_infer_ok_obligations(infer_ok); . expression_ty . }) . }; . 10,906 ( 0.00%) match result { 5,242 ( 0.00%) Ok(v) => { 5,236 ( 0.00%) self.final_ty = Some(v); . if let Some(e) = expression { 10,472 ( 0.00%) match self.expressions { . Expressions::Dynamic(ref mut buffer) => buffer.push(e), 10,358 ( 0.00%) Expressions::UpFront(coercion_sites) => { . // if the user gave us an array to validate, check that we got . // the next expression in the list, as expected 20,146 ( 0.00%) assert_eq!( 15,537 ( 0.00%) coercion_sites[self.pushed].as_coercion_site().hir_id, . e.hir_id . ); . } . } 21,001 ( 0.00%) self.pushed += 1; . } . } . Err(coercion_error) => { . let (expected, found) = if label_expression_as_expected { . // In the case where this is a "forced unit", like . // `break`, we want to call the `()` "expected" . // since it is implied by the syntax. . // (Note: not all force-units work this way.)" -- line 1434 ---------------------------------------- -- line 1707 ---------------------------------------- . if let ty::Dynamic(..) = ty.kind() { . return true; . } . } . } . false . } . 120 ( 0.00%) pub fn complete<'a>(self, fcx: &FnCtxt<'a, 'tcx>) -> Ty<'tcx> { 615 ( 0.00%) if let Some(final_ty) = self.final_ty { . final_ty . } else { . // If we only had inputs that were of type `!` (or no . // inputs at all), then the final type is `!`. . assert_eq!(self.pushed, 0); . fcx.tcx.types.never . } 150 ( 0.00%) } . } . . /// Something that can be converted into an expression to which we can . /// apply a coercion. . pub trait AsCoercionSite { . fn as_coercion_site(&self) -> &hir::Expr<'_>; . } . -- line 1732 ---------------------------------------- -- line 1736 ---------------------------------------- . } . } . . impl<'a, T> AsCoercionSite for &'a T . where . T: AsCoercionSite, . { . fn as_coercion_site(&self) -> &hir::Expr<'_> { 121 ( 0.00%) (**self).as_coercion_site() . } . } . . impl AsCoercionSite for ! { . fn as_coercion_site(&self) -> &hir::Expr<'_> { . unreachable!() . } . } . . impl AsCoercionSite for hir::Arm<'_> { . fn as_coercion_site(&self) -> &hir::Expr<'_> { 898 ( 0.00%) &self.body . } . } 748,059 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_target/src/abi/mod.rs -------------------------------------------------------------------------------- Ir -- line 40 ---------------------------------------- . /// Minimum size of #[repr(C)] enums (default I32 bits) . pub c_enum_min_size: Integer, . } . . impl Default for TargetDataLayout { . /// Creates an instance of `TargetDataLayout`. . fn default() -> TargetDataLayout { . let align = |bits| Align::from_bits(bits).unwrap(); 24 ( 0.00%) TargetDataLayout { . endian: Endian::Big, . i1_align: AbiAndPrefAlign::new(align(8)), . i8_align: AbiAndPrefAlign::new(align(8)), . i16_align: AbiAndPrefAlign::new(align(16)), . i32_align: AbiAndPrefAlign::new(align(32)), . i64_align: AbiAndPrefAlign { abi: align(32), pref: align(64) }, . i128_align: AbiAndPrefAlign { abi: align(32), pref: align(64) }, . f32_align: AbiAndPrefAlign::new(align(32)), . f64_align: AbiAndPrefAlign::new(align(64)), . pointer_size: Size::from_bits(64), . pointer_align: AbiAndPrefAlign::new(align(64)), . aggregate_align: AbiAndPrefAlign { abi: align(0), pref: align(64) }, 8 ( 0.00%) vector_align: vec![ . (Size::from_bits(64), AbiAndPrefAlign::new(align(64))), . (Size::from_bits(128), AbiAndPrefAlign::new(align(128))), . ], . instruction_address_space: AddressSpace::DATA, . c_enum_min_size: Integer::I32, . } . } . } . . impl TargetDataLayout { 18 ( 0.00%) pub fn parse(target: &Target) -> Result { . // Parse an address space index from a string. . let parse_address_space = |s: &str, cause: &str| { . s.parse::().map(AddressSpace).map_err(|err| { . format!("invalid address space `{}` for `{}` in \"data-layout\": {}", s, cause, err) . }) . }; . . // Parse a bit count from a string. -- line 80 ---------------------------------------- -- line 83 ---------------------------------------- . format!("invalid {} `{}` for `{}` in \"data-layout\": {}", kind, s, cause, err) . }) . }; . . // Parse a size string. . let size = |s: &str, cause: &str| parse_bits(s, "size", cause).map(Size::from_bits); . . // Parse an alignment string. 20 ( 0.00%) let align = |s: &[&str], cause: &str| { 2 ( 0.00%) if s.is_empty() { . return Err(format!("missing alignment for `{}` in \"data-layout\"", cause)); . } 12 ( 0.00%) let align_from_bits = |bits| { . Align::from_bits(bits).map_err(|err| { . format!("invalid alignment for `{}` in \"data-layout\": {}", cause, err) . }) 16 ( 0.00%) }; 18 ( 0.00%) let abi = parse_bits(s[0], "alignment", cause)?; . let pref = s.get(1).map_or(Ok(abi), |pref| parse_bits(pref, "alignment", cause))?; 14 ( 0.00%) Ok(AbiAndPrefAlign { abi: align_from_bits(abi)?, pref: align_from_bits(pref)? }) 16 ( 0.00%) }; . . let mut dl = TargetDataLayout::default(); . let mut i128_align_src = 64; 32 ( 0.00%) for spec in target.data_layout.split('-') { . let spec_parts = spec.split(':').collect::>(); . . match &*spec_parts { 78 ( 0.00%) ["e"] => dl.endian = Endian::Little, . ["E"] => dl.endian = Endian::Big, 2 ( 0.00%) [p] if p.starts_with('P') => { . dl.instruction_address_space = parse_address_space(&p[1..], "P")? . } 44 ( 0.00%) ["a", ref a @ ..] => dl.aggregate_align = align(a, "a")?, 4 ( 0.00%) ["f32", ref a @ ..] => dl.f32_align = align(a, "f32")?, 4 ( 0.00%) ["f64", ref a @ ..] => dl.f64_align = align(a, "f64")?, 44 ( 0.00%) [p @ "p", s, ref a @ ..] | [p @ "p0", s, ref a @ ..] => { . dl.pointer_size = size(s, p)?; . dl.pointer_align = align(a, p)?; . } 64 ( 0.00%) [s, ref a @ ..] if s.starts_with('i') => { 4 ( 0.00%) let bits = match s[1..].parse::() { . Ok(bits) => bits, . Err(_) => { . size(&s[1..], "i")?; // For the user error. . continue; . } . }; 14 ( 0.00%) let a = align(a, s)?; 10 ( 0.00%) match bits { . 1 => dl.i1_align = a, . 8 => dl.i8_align = a, . 16 => dl.i16_align = a, . 32 => dl.i32_align = a, 6 ( 0.00%) 64 => dl.i64_align = a, . _ => {} . } 8 ( 0.00%) if bits >= i128_align_src && bits <= 128 { . // Default alignment for i128 is decided by taking the alignment of . // largest-sized i{64..=128}. . i128_align_src = bits; 8 ( 0.00%) dl.i128_align = a; . } . } 14 ( 0.00%) [s, ref a @ ..] if s.starts_with('v') => { . let v_size = size(&s[1..], "v")?; . let a = align(a, s)?; . if let Some(v) = dl.vector_align.iter_mut().find(|v| v.0 == v_size) { . v.1 = a; . continue; . } . // No existing entry, add a new one. . dl.vector_align.push((v_size, a)); . } . _ => {} // Ignore everything else. . } . } . . // Perform consistency checks against the Target information. 8 ( 0.00%) if dl.endian != target.endian { . return Err(format!( . "inconsistent target specification: \"data-layout\" claims \ . architecture is {}-endian, while \"target-endian\" is `{}`", . dl.endian.as_str(), . target.endian.as_str(), . )); . } . 10 ( 0.00%) if dl.pointer_size.bits() != target.pointer_width.into() { . return Err(format!( . "inconsistent target specification: \"data-layout\" claims \ . pointers are {}-bit, while \"target-pointer-width\" is `{}`", . dl.pointer_size.bits(), . target.pointer_width . )); . } . 4 ( 0.00%) dl.c_enum_min_size = Integer::from_size(Size::from_bits(target.c_enum_min_bits))?; . 34 ( 0.00%) Ok(dl) 18 ( 0.00%) } . . /// Returns exclusive upper bound on object size. . /// . /// The theoretical maximum object size is defined as the maximum positive `isize` value. . /// This ensures that the `offset` semantics remain well-defined by allowing it to correctly . /// index every address within an object along with one byte past the end, along with allowing . /// `isize` to store the difference between any two pointers into an object. . /// . /// The upper bound on 64-bit currently needs to be lower because LLVM uses a 64-bit integer . /// to represent object size in bits. It would need to be 1 << 61 to account for this, but is . /// currently conservatively bounded to 1 << 47 as that is enough to cover the current usable . /// address space on 64-bit ARMv8 and x86_64. . #[inline] . pub fn obj_size_bound(&self) -> u64 { 578,082 ( 0.03%) match self.pointer_size.bits() { . 16 => 1 << 15, . 32 => 1 << 31, . 64 => 1 << 47, . bits => panic!("obj_size_bound: unknown pointer bit size {}", bits), . } 9 ( 0.00%) } . . #[inline] . pub fn ptr_sized_integer(&self) -> Integer { 416,922 ( 0.02%) match self.pointer_size.bits() { . 16 => I16, . 32 => I32, . 64 => I64, . bits => panic!("ptr_sized_integer: unknown pointer bit size {}", bits), . } 13 ( 0.00%) } . . #[inline] . pub fn vector_align(&self, vec_size: Size) -> AbiAndPrefAlign { . for &(size, align) in &self.vector_align { . if size == vec_size { . return align; . } . } -- line 222 ---------------------------------------- -- line 233 ---------------------------------------- . impl HasDataLayout for TargetDataLayout { . #[inline] . fn data_layout(&self) -> &TargetDataLayout { . self . } . } . . /// Endianness of the target, which must match cfg(target-endian). 2 ( 0.00%) #[derive(Copy, Clone, PartialEq)] . pub enum Endian { . Little, . Big, . } . . impl Endian { . pub fn as_str(&self) -> &'static str { 3 ( 0.00%) match self { . Self::Little => "little", . Self::Big => "big", . } 1 ( 0.00%) } . } . . impl fmt::Debug for Endian { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . f.write_str(self.as_str()) . } . } . -- line 261 ---------------------------------------- -- line 277 ---------------------------------------- . } . } . . /// Size of a type in bytes. . #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Encodable, Decodable)] . #[derive(HashStable_Generic)] . pub struct Size { . // The top 3 bits are ALWAYS zero. 271,830 ( 0.01%) raw: u64, . } . . impl Size { . pub const ZERO: Size = Size { raw: 0 }; . . /// Rounds `bits` up to the next-higher byte boundary, if `bits` is . /// is not aligned. . pub fn from_bits(bits: impl TryInto) -> Size { -- line 293 ---------------------------------------- -- line 296 ---------------------------------------- . #[cold] . fn overflow(bits: u64) -> ! { . panic!("Size::from_bits({}) has overflowed", bits); . } . . // This is the largest value of `bits` that does not cause overflow . // during rounding, and guarantees that the resulting number of bytes . // cannot cause overflow when multiplied by 8. 12 ( 0.00%) if bits > 0xffff_ffff_ffff_fff8 { . overflow(bits); . } . . // Avoid potential overflow from `bits + 7`. 26 ( 0.00%) Size { raw: bits / 8 + ((bits % 8) + 7) / 8 } . } . . #[inline] . pub fn from_bytes(bytes: impl TryInto) -> Size { . let bytes: u64 = bytes.try_into().ok().unwrap(); . Size { raw: bytes } . } . -- line 317 ---------------------------------------- -- line 322 ---------------------------------------- . . #[inline] . pub fn bytes_usize(self) -> usize { . self.bytes().try_into().unwrap() . } . . #[inline] . pub fn bits(self) -> u64 { 602,255 ( 0.03%) self.raw << 3 . } . . #[inline] . pub fn bits_usize(self) -> usize { . self.bits().try_into().unwrap() . } . . #[inline] 9 ( 0.00%) pub fn align_to(self, align: Align) -> Size { 28,378 ( 0.00%) let mask = align.bytes() - 1; 23,959 ( 0.00%) Size::from_bytes((self.bytes() + mask) & !mask) 27 ( 0.00%) } . . #[inline] . pub fn is_aligned(self, align: Align) -> bool { . let mask = align.bytes() - 1; . self.bytes() & mask == 0 . } . . #[inline] . pub fn checked_add(self, offset: Size, cx: &C) -> Option { . let dl = cx.data_layout(); . 96,323 ( 0.00%) let bytes = self.bytes().checked_add(offset.bytes())?; . 481,540 ( 0.02%) if bytes < dl.obj_size_bound() { Some(Size::from_bytes(bytes)) } else { None } . } . . #[inline] 12 ( 0.00%) pub fn checked_mul(self, count: u64, cx: &C) -> Option { . let dl = cx.data_layout(); . 15 ( 0.00%) let bytes = self.bytes().checked_mul(count)?; 45 ( 0.00%) if bytes < dl.obj_size_bound() { Some(Size::from_bytes(bytes)) } else { None } 6 ( 0.00%) } . . /// Truncates `value` to `self` bits and then sign-extends it to 128 bits . /// (i.e., if it is negative, fill with 1's on the left). . #[inline] . pub fn sign_extend(self, value: u128) -> u128 { . let size = self.bits(); . if size == 0 { . // Truncated until nothing is left. . return 0; . } . // Sign-extend it. 111,242 ( 0.01%) let shift = 128 - size; . // Shift the unsigned value to the left, then shift back to the right as signed . // (essentially fills with sign bit on the left). 3,782,228 ( 0.18%) (((value << shift) as i128) >> shift) as u128 . } . . /// Truncates `value` to `self` bits. . #[inline] . pub fn truncate(self, value: u128) -> u128 { . let size = self.bits(); 179,280 ( 0.01%) if size == 0 { . // Truncated until nothing is left. . return 0; . } 174,668 ( 0.01%) let shift = 128 - size; . // Truncate (shift left to drop out leftover values, shift right to fill with zeroes). 3,175,471 ( 0.15%) (value << shift) >> shift . } . . #[inline] . pub fn signed_int_min(&self) -> i128 { 1,001,178 ( 0.05%) self.sign_extend(1_u128 << (self.bits() - 1)) as i128 . } . . #[inline] . pub fn signed_int_max(&self) -> i128 { 1,001,178 ( 0.05%) i128::MAX >> (128 - self.bits()) . } . . #[inline] 9 ( 0.00%) pub fn unsigned_int_max(&self) -> u128 { 180,893 ( 0.01%) u128::MAX >> (128 - self.bits()) 18 ( 0.00%) } . } . . // Panicking addition, subtraction and multiplication for convenience. . // Avoid during layout computation, return `LayoutError` instead. . . impl Add for Size { . type Output = Size; . #[inline] -- line 417 ---------------------------------------- -- line 438 ---------------------------------------- . fn mul(self, size: Size) -> Size { . size * self . } . } . . impl Mul for Size { . type Output = Size; . #[inline] 18,232 ( 0.00%) fn mul(self, count: u64) -> Size { 32,117 ( 0.00%) match self.bytes().checked_mul(count) { . Some(bytes) => Size::from_bytes(bytes), . None => panic!("Size::mul: {} * {} doesn't fit in u64", self.bytes(), count), . } 18,232 ( 0.00%) } . } . . impl AddAssign for Size { . #[inline] . fn add_assign(&mut self, other: Size) { 13,860 ( 0.00%) *self = *self + other; . } . } . . impl Step for Size { . #[inline] . fn steps_between(start: &Self, end: &Self) -> Option { . u64::steps_between(&start.bytes(), &end.bytes()) . } -- line 465 ---------------------------------------- -- line 494 ---------------------------------------- . Self::from_bytes(u64::backward_unchecked(start.bytes(), count)) . } . } . . /// Alignment of a type in bytes (always a power of two). . #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Encodable, Decodable)] . #[derive(HashStable_Generic)] . pub struct Align { 34,073 ( 0.00%) pow2: u8, . } . . impl Align { . pub const ONE: Align = Align { pow2: 0 }; . . #[inline] . pub fn from_bits(bits: u64) -> Result { . Align::from_bytes(Size::from_bits(bits).bytes()) . } . . #[inline] . pub fn from_bytes(align: u64) -> Result { . // Treat an alignment of 0 bytes like 1-byte alignment. 8 ( 0.00%) if align == 0 { . return Ok(Align::ONE); . } . . #[cold] . fn not_power_of_2(align: u64) -> String { . format!("`{}` is not a power of 2", align) . } . . #[cold] . fn too_large(align: u64) -> String { . format!("`{}` is too large", align) . } . . let mut bytes = align; . let mut pow2: u8 = 0; 56 ( 0.00%) while (bytes & 1) == 0 { 36 ( 0.00%) pow2 += 1; 24 ( 0.00%) bytes >>= 1; . } 8 ( 0.00%) if bytes != 1 { . return Err(not_power_of_2(align)); . } 8 ( 0.00%) if pow2 > 29 { . return Err(too_large(align)); . } . 18 ( 0.00%) Ok(Align { pow2 }) . } . . #[inline] . pub fn bytes(self) -> u64 { 10,061 ( 0.00%) 1 << self.pow2 . } . . #[inline] . pub fn bits(self) -> u64 { 10 ( 0.00%) self.bytes() * 8 . } . . /// Computes the best alignment possible for the given offset . /// (the largest power of two that the offset is a multiple of). . /// . /// N.B., for an offset of `0`, this happens to return `2^64`. . #[inline] . pub fn max_for_offset(offset: Size) -> Align { -- line 561 ---------------------------------------- -- line 591 ---------------------------------------- . . #[inline] . pub fn max(self, other: AbiAndPrefAlign) -> AbiAndPrefAlign { . AbiAndPrefAlign { abi: self.abi.max(other.abi), pref: self.pref.max(other.pref) } . } . } . . /// Integers, also used for enum discriminants. 64,594 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, HashStable_Generic)] . pub enum Integer { . I8, . I16, . I32, . I64, . I128, . } . . impl Integer { . #[inline] . pub fn size(self) -> Size { 414,956 ( 0.02%) match self { . I8 => Size::from_bytes(1), . I16 => Size::from_bytes(2), . I32 => Size::from_bytes(4), . I64 => Size::from_bytes(8), . I128 => Size::from_bytes(16), . } . } . . pub fn align(self, cx: &C) -> AbiAndPrefAlign { . let dl = cx.data_layout(); . 85 ( 0.00%) match self { 129,078 ( 0.01%) I8 => dl.i8_align, 8 ( 0.00%) I16 => dl.i16_align, 13,674 ( 0.00%) I32 => dl.i32_align, 125 ( 0.00%) I64 => dl.i64_align, . I128 => dl.i128_align, . } . } . . /// Finds the smallest Integer type which can represent the signed value. . #[inline] . pub fn fit_signed(x: i128) -> Integer { . match x { 126 ( 0.00%) -0x0000_0000_0000_0080..=0x0000_0000_0000_007f => I8, . -0x0000_0000_0000_8000..=0x0000_0000_0000_7fff => I16, . -0x0000_0000_8000_0000..=0x0000_0000_7fff_ffff => I32, . -0x8000_0000_0000_0000..=0x7fff_ffff_ffff_ffff => I64, . _ => I128, . } . } . . /// Finds the smallest Integer type which can represent the unsigned value. . #[inline] . pub fn fit_unsigned(x: u128) -> Integer { . match x { 36 ( 0.00%) 0..=0x0000_0000_0000_00ff => I8, . 0..=0x0000_0000_0000_ffff => I16, . 0..=0x0000_0000_ffff_ffff => I32, . 0..=0xffff_ffff_ffff_ffff => I64, . _ => I128, . } . } . . /// Finds the smallest integer with the given alignment. 108 ( 0.00%) pub fn for_align(cx: &C, wanted: Align) -> Option { . let dl = cx.data_layout(); . 741 ( 0.00%) for candidate in [I8, I16, I32, I64, I128] { 144 ( 0.00%) if wanted == candidate.align(dl).abi && wanted.bytes() == candidate.size().bytes() { . return Some(candidate); . } . } . None 108 ( 0.00%) } . . /// Find the largest integer with the given alignment or less. . pub fn approximate_align(cx: &C, wanted: Align) -> Integer { . let dl = cx.data_layout(); . . // FIXME(eddyb) maybe include I128 in the future, when it works everywhere. . for candidate in [I64, I32, I16] { . if wanted >= candidate.align(dl).abi && wanted.bytes() >= candidate.size().bytes() { -- line 674 ---------------------------------------- -- line 677 ---------------------------------------- . } . I8 . } . . // FIXME(eddyb) consolidate this and other methods that find the appropriate . // `Integer` given some requirements. . #[inline] . fn from_size(size: Size) -> Result { 8 ( 0.00%) match size.bits() { . 8 => Ok(Integer::I8), . 16 => Ok(Integer::I16), . 32 => Ok(Integer::I32), . 64 => Ok(Integer::I64), . 128 => Ok(Integer::I128), . _ => Err(format!("rust does not support integers with {} bits", size.bits())), . } . } . } . . /// Fundamental unit of memory access and layout. 1,099,388 ( 0.05%) #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable_Generic)] . pub enum Primitive { . /// The `bool` is the signedness of the `Integer` type. . /// . /// One would think we would not care about such details this low down, . /// but some ABIs are described in terms of C types and ISAs where the . /// integer arithmetic is done on {sign,zero}-extended registers, e.g. . /// a negative integer passed by zero-extension will appear positive in . /// the callee, and most operations on it will produce the wrong values. 387,510 ( 0.02%) Int(Integer, bool), . F32, . F64, . Pointer, . } . . impl Primitive { . pub fn size(self, cx: &C) -> Size { . let dl = cx.data_layout(); . 607,826 ( 0.03%) match self { . Int(i, _) => i.size(), . F32 => Size::from_bits(32), . F64 => Size::from_bits(64), 106 ( 0.00%) Pointer => dl.pointer_size, . } 9 ( 0.00%) } . . pub fn align(self, cx: &C) -> AbiAndPrefAlign { . let dl = cx.data_layout(); . 180 ( 0.00%) match self { . Int(i, _) => i.align(dl), . F32 => dl.f32_align, . F64 => dl.f64_align, 12 ( 0.00%) Pointer => dl.pointer_align, . } . } . . // FIXME(eddyb) remove, it's trivial thanks to `matches!`. . #[inline] . pub fn is_float(self) -> bool { . matches!(self, F32 | F64) . } -- line 739 ---------------------------------------- -- line 753 ---------------------------------------- . /// sequence: . /// . /// 254 (-2), 255 (-1), 0, 1, 2 . /// . /// This is intended specifically to mirror LLVM’s `!range` metadata semantics. . #[derive(Clone, Copy, PartialEq, Eq, Hash)] . #[derive(HashStable_Generic)] . pub struct WrappingRange { 193,873 ( 0.01%) pub start: u128, . pub end: u128, . } . . impl WrappingRange { . /// Returns `true` if `v` is contained in the range. . #[inline(always)] . pub fn contains(&self, v: u128) -> bool { 36,872 ( 0.00%) if self.start <= self.end { . self.start <= v && v <= self.end . } else { . self.start <= v || v <= self.end . } . } . . /// Returns `self` with replaced `start` . #[inline(always)] -- line 777 ---------------------------------------- -- line 787 ---------------------------------------- . self . } . . /// Returns `true` if `size` completely fills the range. . #[inline] . pub fn is_full_for(&self, size: Size) -> bool { . let max_value = size.unsigned_int_max(); . debug_assert!(self.start <= max_value && self.end <= max_value); 55,308 ( 0.00%) self.start == (self.end.wrapping_add(1) & max_value) . } . } . . impl fmt::Debug for WrappingRange { . fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { . if self.start > self.end { . write!(fmt, "(..={}) | ({}..)", self.end, self.start)?; . } else { -- line 803 ---------------------------------------- -- line 806 ---------------------------------------- . Ok(()) . } . } . . /// Information about one scalar component of a Rust type. . #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] . #[derive(HashStable_Generic)] . pub struct Scalar { 226,306 ( 0.01%) pub value: Primitive, . . // FIXME(eddyb) always use the shortest range, e.g., by finding . // the largest space between two consecutive valid values and . // taking everything else as the (shortest) valid range. 258,454 ( 0.01%) pub valid_range: WrappingRange, . } . . impl Scalar { . #[inline] . pub fn is_bool(&self) -> bool { . matches!( . self, . Scalar { value: Int(I8, false), valid_range: WrappingRange { start: 0, end: 1 } } -- line 827 ---------------------------------------- -- line 831 ---------------------------------------- . /// Returns `true` if all possible numbers are valid, i.e `valid_range` covers the whole layout . #[inline] . pub fn is_always_valid(&self, cx: &C) -> bool { . self.valid_range.is_full_for(self.value.size(cx)) . } . } . . /// Describes how the fields of a type are located in memory. 519,009 ( 0.02%) #[derive(PartialEq, Eq, Hash, Debug, HashStable_Generic)] . pub enum FieldsShape { . /// Scalar primitives and `!`, which never have fields. . Primitive, . . /// All fields start at no offset. The `usize` is the field count. . Union(NonZeroUsize), . . /// Array/vector-like placement, with all fields of identical types. 16 ( 0.00%) Array { stride: Size, count: u64 }, . . /// Struct-like placement, with precomputed offsets. . /// . /// Fields are guaranteed to not overlap, but note that gaps . /// before, between and after all the fields are NOT always . /// padding, and as such their contents may not be discarded. . /// For example, enum variants leave a gap at the start, . /// where the discriminant field in the enum layout goes. -- line 856 ---------------------------------------- -- line 875 ---------------------------------------- . // FIXME(camlorn) also consider small vector optimization here. . memory_index: Vec, . }, . } . . impl FieldsShape { . #[inline] . pub fn count(&self) -> usize { 580 ( 0.00%) match *self { . FieldsShape::Primitive => 0, . FieldsShape::Union(count) => count.get(), . FieldsShape::Array { count, .. } => count.try_into().unwrap(), 348 ( 0.00%) FieldsShape::Arbitrary { ref offsets, .. } => offsets.len(), . } . } . . #[inline] 173,870 ( 0.01%) pub fn offset(&self, i: usize) -> Size { 548,845 ( 0.03%) match *self { . FieldsShape::Primitive => { . unreachable!("FieldsShape::offset: `Primitive`s have no fields") . } . FieldsShape::Union(count) => { . assert!( . i < count.get(), . "tried to access field {} of union with {} fields", . i, . count . ); . Size::ZERO . } . FieldsShape::Array { stride, count } => { . let i = u64::try_from(i).unwrap(); 9,218 ( 0.00%) assert!(i < count); . stride * i . } 105,160 ( 0.00%) FieldsShape::Arbitrary { ref offsets, .. } => offsets[i], . } 173,870 ( 0.01%) } . . #[inline] . pub fn memory_index(&self, i: usize) -> usize { . match *self { . FieldsShape::Primitive => { . unreachable!("FieldsShape::memory_index: `Primitive`s have no fields") . } . FieldsShape::Union(_) | FieldsShape::Array { .. } => i, . FieldsShape::Arbitrary { ref memory_index, .. } => memory_index[i].try_into().unwrap(), . } . } . . /// Gets source indices of the fields by increasing offsets. . #[inline] . pub fn index_by_increasing_offset<'a>(&'a self) -> impl Iterator + 'a { 464 ( 0.00%) let mut inverse_small = [0u8; 64]; . let mut inverse_big = vec![]; 116 ( 0.00%) let use_small = self.count() <= inverse_small.len(); . . // We have to write this logic twice in order to keep the array small. . if let FieldsShape::Arbitrary { ref memory_index, .. } = *self { 116 ( 0.00%) if use_small { . for i in 0..self.count() { 36 ( 0.00%) inverse_small[memory_index[i] as usize] = i as u8; . } . } else { . inverse_big = vec![0; self.count()]; . for i in 0..self.count() { . inverse_big[memory_index[i] as usize] = i as u32; . } . } . } . 940 ( 0.00%) (0..self.count()).map(move |i| match *self { . FieldsShape::Primitive | FieldsShape::Union(_) | FieldsShape::Array { .. } => i, . FieldsShape::Arbitrary { .. } => { 6 ( 0.00%) if use_small { 18 ( 0.00%) inverse_small[i] as usize . } else { . inverse_big[i] as usize . } . } . }) . } . } . -- line 959 ---------------------------------------- -- line 965 ---------------------------------------- . . impl AddressSpace { . /// The default address space, corresponding to data space. . pub const DATA: Self = AddressSpace(0); . } . . /// Describes how values of the type are passed by target ABIs, . /// in terms of categories of C types there are ABI rules for. 324,456 ( 0.02%) #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable_Generic)] . pub enum Abi { . Uninhabited, . Scalar(Scalar), 65 ( 0.00%) ScalarPair(Scalar, Scalar), . Vector { . element: Scalar, . count: u64, . }, . Aggregate { . /// If true, the size is exact, otherwise it's only a lower bound. 555 ( 0.00%) sized: bool, . }, . } . . impl Abi { . /// Returns `true` if the layout corresponds to an unsized type. . #[inline] . pub fn is_unsized(&self) -> bool { 320,571 ( 0.02%) match *self { . Abi::Uninhabited | Abi::Scalar(_) | Abi::ScalarPair(..) | Abi::Vector { .. } => false, . Abi::Aggregate { sized } => !sized, . } . } . . /// Returns `true` if this is a single signed integer scalar . #[inline] . pub fn is_signed(&self) -> bool { 82,998 ( 0.00%) match self { 193,662 ( 0.01%) Abi::Scalar(scal) => match scal.value { . Primitive::Int(_, signed) => signed, . _ => false, . }, . _ => panic!("`is_signed` on non-scalar ABI {:?}", self), . } . } . . /// Returns `true` if this is an uninhabited type . #[inline] . pub fn is_uninhabited(&self) -> bool { 4,671 ( 0.00%) matches!(*self, Abi::Uninhabited) . } . . /// Returns `true` is this is a scalar type . #[inline] . pub fn is_scalar(&self) -> bool { . matches!(*self, Abi::Scalar(_)) . } . } . . rustc_index::newtype_index! { . pub struct VariantIdx { . derive [HashStable_Generic] . } . } . 337,652 ( 0.02%) #[derive(PartialEq, Eq, Hash, Debug, HashStable_Generic)] . pub enum Variants { . /// Single enum variants, structs/tuples, unions, and all non-ADTs. 50,811 ( 0.00%) Single { index: VariantIdx }, . . /// Enum-likes with more than one inhabited variant: each variant comes with . /// a *discriminant* (usually the same as the variant index but the user can . /// assign explicit discriminant values). That discriminant is encoded . /// as a *tag* on the machine. The layout of each variant is . /// a struct, and they all have space reserved for the tag. . /// For enums, the tag is the sole field of the layout. . Multiple { . tag: Scalar, 25 ( 0.00%) tag_encoding: TagEncoding, 20 ( 0.00%) tag_field: usize, 5 ( 0.00%) variants: IndexVec, . }, . } . 118 ( 0.00%) #[derive(PartialEq, Eq, Hash, Debug, HashStable_Generic)] . pub enum TagEncoding { . /// The tag directly stores the discriminant, but possibly with a smaller layout . /// (so converting the tag to the discriminant can require sign extension). . Direct, . . /// Niche (values invalid for a type) encoding the discriminant: . /// Discriminant and variant index coincide. . /// The variant `dataful_variant` contains a niche at an arbitrary -- line 1056 ---------------------------------------- -- line 1065 ---------------------------------------- . dataful_variant: VariantIdx, . niche_variants: RangeInclusive, . niche_start: u128, . }, . } . . #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, HashStable_Generic)] . pub struct Niche { 32,307 ( 0.00%) pub offset: Size, 32,307 ( 0.00%) pub scalar: Scalar, . } . . impl Niche { 66 ( 0.00%) pub fn from_scalar(cx: &C, offset: Size, scalar: Scalar) -> Option { 66 ( 0.00%) let niche = Niche { offset, scalar }; 517,125 ( 0.02%) if niche.available(cx) > 0 { Some(niche) } else { None } 77 ( 0.00%) } . 4 ( 0.00%) pub fn available(&self, cx: &C) -> u128 { 44 ( 0.00%) let Scalar { value, valid_range: v } = self.scalar; . let size = value.size(cx); 64,754 ( 0.00%) assert!(size.bits() <= 128); . let max_value = size.unsigned_int_max(); . . // Find out how many values are outside the valid range. . let niche = v.end.wrapping_add(1)..v.start; 468 ( 0.00%) niche.end.wrapping_sub(niche.start) & max_value 8 ( 0.00%) } . . pub fn reserve(&self, cx: &C, count: u128) -> Option<(u128, Scalar)> { . assert!(count > 0); . . let Scalar { value, valid_range: v } = self.scalar; . let size = value.size(cx); . assert!(size.bits() <= 128); . let max_value = size.unsigned_int_max(); -- line 1100 ---------------------------------------- -- line 1144 ---------------------------------------- . move_start(v) . } else { . move_end(v) . } . } . } . } . 455,868 ( 0.02%) #[derive(PartialEq, Eq, Hash, Debug, HashStable_Generic)] . pub struct Layout { . /// Says where the fields are located within the layout. . pub fields: FieldsShape, . . /// Encodes information about multi-variant layouts. . /// Even with `Multiple` variants, a layout still has its own fields! Those are then . /// shared between all variants. One of them will be the discriminant, . /// but e.g. generators can have more. . /// . /// To access all fields of this layout, both `fields` and the fields of the active variant . /// must be taken into account. 54 ( 0.00%) pub variants: Variants, . . /// The `abi` defines how this data is passed between functions, and it defines . /// value restrictions via `valid_range`. . /// . /// Note that this is entirely orthogonal to the recursive structure defined by . /// `variants` and `fields`; for example, `ManuallyDrop>` has . /// `Abi::ScalarPair`! So, even with non-`Aggregate` `abi`, `fields` and `variants` . /// have to be taken into account to find all fields of this layout. 32,363 ( 0.00%) pub abi: Abi, . . /// The leaf scalar with the largest number of invalid values . /// (i.e. outside of its `valid_range`), if it exists. 161,630 ( 0.01%) pub largest_niche: Option, . 259,208 ( 0.01%) pub align: AbiAndPrefAlign, 129,472 ( 0.01%) pub size: Size, . } . . impl Layout { 193,758 ( 0.01%) pub fn scalar(cx: &C, scalar: Scalar) -> Self { 193,758 ( 0.01%) let largest_niche = Niche::from_scalar(cx, Size::ZERO, scalar); . let size = scalar.value.size(cx); . let align = scalar.value.align(cx); 678,153 ( 0.03%) Layout { . variants: Variants::Single { index: VariantIdx::new(0) }, . fields: FieldsShape::Primitive, 193,758 ( 0.01%) abi: Abi::Scalar(scalar), 129,172 ( 0.01%) largest_niche, . size, . align, . } 258,344 ( 0.01%) } . } . . /// The layout of a type, alongside the type itself. . /// Provides various type traversal APIs (e.g., recursing into fields). . /// . /// Note that the layout is NOT guaranteed to always be identical . /// to that obtained from `layout_of(ty)`, as we need to produce . /// layouts for which Rust types do not exist, such as enum variants . /// or synthetic fields of enums (i.e., discriminants) and fat pointers. . #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable_Generic)] . pub struct TyAndLayout<'a, Ty> { 119,058 ( 0.01%) pub ty: Ty, 238,171 ( 0.01%) pub layout: &'a Layout, . } . . impl<'a, Ty> Deref for TyAndLayout<'a, Ty> { . type Target = &'a Layout; . fn deref(&self) -> &&'a Layout { 8 ( 0.00%) &self.layout . } . } . . #[derive(Copy, Clone, PartialEq, Eq, Debug)] . pub enum PointerKind { . /// Most general case, we know no restrictions to tell LLVM. . Shared, . -- line 1223 ---------------------------------------- -- line 1255 ---------------------------------------- . ) -> Option; . } . . impl<'a, Ty> TyAndLayout<'a, Ty> { . pub fn for_variant(self, cx: &C, variant_index: VariantIdx) -> Self . where . Ty: TyAbiInterface<'a, C>, . { 46,135 ( 0.00%) Ty::ty_and_layout_for_variant(self, cx, variant_index) . } . . pub fn field(self, cx: &C, i: usize) -> Self . where . Ty: TyAbiInterface<'a, C>, . { 453,038 ( 0.02%) Ty::ty_and_layout_field(self, cx, i) . } . . pub fn pointee_info_at(self, cx: &C, offset: Size) -> Option . where . Ty: TyAbiInterface<'a, C>, . { . Ty::ty_and_layout_pointee_info_at(self, cx, offset) . } . } . . impl<'a, Ty> TyAndLayout<'a, Ty> { . /// Returns `true` if the layout corresponds to an unsized type. . pub fn is_unsized(&self) -> bool { 41,249 ( 0.00%) self.abi.is_unsized() . } . . /// Returns `true` if the type is a ZST and not unsized. . pub fn is_zst(&self) -> bool { 220,454 ( 0.01%) match self.abi { . Abi::Scalar(_) | Abi::ScalarPair(..) | Abi::Vector { .. } => false, . Abi::Uninhabited => self.size.bytes() == 0, 27,480 ( 0.00%) Abi::Aggregate { sized } => sized && self.size.bytes() == 0, . } 12 ( 0.00%) } . . /// Determines if this type permits "raw" initialization by just transmuting some . /// memory into an instance of `T`. . /// `zero` indicates if the memory is zero-initialized, or alternatively . /// left entirely uninitialized. . /// This is conservative: in doubt, it will answer `true`. . /// . /// FIXME: Once we removed all the conservatism, we could alternatively -- line 1302 ---------------------------------------- 2,010,337 ( 0.09%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/std/src/thread/local.rs -------------------------------------------------------------------------------- Ir -- line 173 ---------------------------------------- . #[unstable(feature = "thread_local_internals", reason = "should not be necessary", issue = "none")] . #[macro_export] . #[allow_internal_unstable(thread_local_internals, cfg_target_thread_local, thread_local)] . #[allow_internal_unsafe] . macro_rules! __thread_local_inner { . // used to generate the `LocalKey` value for const-initialized thread locals . (@key $t:ty, const $init:expr) => {{ . #[cfg_attr(not(windows), inline)] // see comments below 4 ( 0.00%) unsafe fn __getit() -> $crate::option::Option<&'static $t> { . const INIT_EXPR: $t = $init; . . // wasm without atomics maps directly to `static mut`, and dtors . // aren't implemented because thread dtors aren't really a thing . // on wasm right now . // . // FIXME(#84224) this should come after the `target_thread_local` . // block. -- line 189 ---------------------------------------- -- line 211 ---------------------------------------- . } . . // 0 == dtor not registered . // 1 == dtor registered, dtor not run . // 2 == dtor registered and is running or has run . #[thread_local] . static mut STATE: u8 = 0; . 8 ( 0.00%) unsafe extern "C" fn destroy(ptr: *mut u8) { . let ptr = ptr as *mut $t; . . unsafe { . debug_assert_eq!(STATE, 1); 12 ( 0.00%) STATE = 2; . $crate::ptr::drop_in_place(ptr); . } 8 ( 0.00%) } . . unsafe { 36 ( 0.00%) match STATE { . // 0 == we haven't registered a destructor, so do . // so now. . 0 => { . $crate::thread::__FastLocalKeyInner::<$t>::register_dtor( . $crate::ptr::addr_of_mut!(VAL) as *mut u8, . destroy, . ); 8 ( 0.00%) STATE = 1; . Some(&VAL) . } . // 1 == the destructor is registered and the value . // is valid, so return the pointer. . 1 => Some(&VAL), . // otherwise the destructor has already run, so we . // can't give access. . _ => None, -- line 246 ---------------------------------------- -- line 257 ---------------------------------------- . { . #[inline] . const fn __init() -> $t { INIT_EXPR } . static __KEY: $crate::thread::__OsLocalKeyInner<$t> = . $crate::thread::__OsLocalKeyInner::new(); . #[allow(unused_unsafe)] . unsafe { __KEY.get(__init) } . } 63,812 ( 0.00%) } . . unsafe { . $crate::thread::LocalKey::new(__getit) . } . }}; . . // used to generate the `LocalKey` value for `thread_local!` . (@key $t:ty, $init:expr) => { -- line 273 ---------------------------------------- -- line 318 ---------------------------------------- . static __KEY: $crate::thread::__OsLocalKeyInner<$t> = . $crate::thread::__OsLocalKeyInner::new(); . . // FIXME: remove the #[allow(...)] marker when macros don't . // raise warning for missing/extraneous unsafe blocks anymore. . // See https://github.com/rust-lang/rust/issues/74838. . #[allow(unused_unsafe)] . unsafe { __KEY.get(__init) } 2,539,913 ( 0.12%) } . . unsafe { . $crate::thread::LocalKey::new(__getit) . } . } . }; . ($(#[$attr:meta])* $vis:vis $name:ident, $t:ty, $($init:tt)*) => { . $(#[$attr])* $vis const $name: $crate::thread::LocalKey<$t> = -- line 334 ---------------------------------------- -- line 377 ---------------------------------------- . /// this key yet. . /// . /// # Panics . /// . /// This function will `panic!()` if the key currently has its . /// destructor running, and it **may** panic if the destructor has . /// previously been run for this thread. . #[stable(feature = "rust1", since = "1.0.0")] 12 ( 0.00%) pub fn with(&'static self, f: F) -> R . where . F: FnOnce(&T) -> R, . { 17 ( 0.00%) self.try_with(f).expect( . "cannot access a Thread Local Storage value \ . during or after destruction", . ) 16 ( 0.00%) } . . /// Acquires a reference to the value in this TLS key. . /// . /// This will lazily initialize the value if this thread has not referenced . /// this key yet. If the key has been destroyed (which may happen if this is called . /// in a destructor), this function will return an [`AccessError`]. . /// . /// # Panics -- line 401 ---------------------------------------- -- line 404 ---------------------------------------- . /// key's initializer panics. . #[stable(feature = "thread_local_try_with", since = "1.26.0")] . #[inline] . pub fn try_with(&'static self, f: F) -> Result . where . F: FnOnce(&T) -> R, . { . unsafe { 1,926,935 ( 0.09%) let thread_local = (self.inner)().ok_or(AccessError)?; 833,911 ( 0.04%) Ok(f(thread_local)) . } . } . } . . mod lazy { . use crate::cell::UnsafeCell; . use crate::hint; . use crate::mem; -- line 421 ---------------------------------------- -- line 434 ---------------------------------------- . // the inner cell nor mutable reference to the Option inside said . // cell. This make it safe to hand a reference, though the lifetime . // of 'static is itself unsafe, making the get method unsafe. . unsafe { (*self.inner.get()).as_ref() } . } . . /// The caller must ensure that no reference is active: this method . /// needs unique access. 9 ( 0.00%) pub unsafe fn initialize T>(&self, init: F) -> &'static T { . // Execute the initialization up front, *then* move it into our slot, . // just in case initialization fails. . let value = init(); . let ptr = self.inner.get(); . . // SAFETY: . // . // note that this can in theory just be `*ptr = Some(value)`, but due to -- line 450 ---------------------------------------- -- line 475 ---------------------------------------- . // always work it empirically doesn't seem to always get optimized away, . // which means that using something like `try_with` can pull in . // panicking code and cause a large size bloat. . match *ptr { . Some(ref x) => x, . None => hint::unreachable_unchecked(), . } . } 10 ( 0.00%) } . . /// The other methods hand out references while taking &self. . /// As such, callers of this method must ensure no `&` and `&mut` are . /// available and used at the same time. . #[allow(unused)] . pub unsafe fn take(&mut self) -> Option { . // SAFETY: See doc comment for this method. . unsafe { (*self.inner.get()).take() } -- line 491 ---------------------------------------- -- line 596 ---------------------------------------- . // SAFETY: See the definitions of `LazyKeyInner::get` and . // `try_initialize` for more information. . // . // The caller must ensure no mutable references are ever active to . // the inner cell or the inner T when this is called. . // The `try_initialize` is dependant on the passed `init` function . // for this. . unsafe { 770,759 ( 0.04%) match self.inner.get() { . Some(val) => Some(val), 18 ( 0.00%) None => self.try_initialize(init), . } . } . } . . // `try_initialize` is only called once per fast thread local variable, . // except in corner cases where thread_local dtors reference other . // thread_local's, or it is being recursively initialized. . // . // Macos: Inlining this function can cause two `tlv_get_addr` calls to . // be performed for every call to `Key::get`. . // LLVM issue: https://bugs.llvm.org/show_bug.cgi?id=41722 . #[inline(never)] 8 ( 0.00%) unsafe fn try_initialize T>(&self, init: F) -> Option<&'static T> { . // SAFETY: See comment above (this function doc). . if !mem::needs_drop::() || unsafe { self.try_register_dtor() } { . // SAFETY: See comment above (his function doc). 6 ( 0.00%) Some(unsafe { self.inner.initialize(init) }) . } else { . None . } 8 ( 0.00%) } . . // `try_register_dtor` is only called once per fast thread local . // variable, except in corner cases where thread_local dtors reference . // other thread_local's, or it is being recursively initialized. . unsafe fn try_register_dtor(&self) -> bool { 6 ( 0.00%) match self.dtor_state.get() { . DtorState::Unregistered => { . // SAFETY: dtor registration happens before initialization. . // Passing `self` as a pointer while using `destroy_value` . // is safe because the function will build a pointer to a . // Key, which is the type of self and so find the correct . // size. 6 ( 0.00%) unsafe { register_dtor(self as *const _ as *mut u8, destroy_value::) }; . self.dtor_state.set(DtorState::Registered); . true . } . DtorState::Registered => { . // recursively initialized . true . } . DtorState::RunningOrHasRun => false, . } . } . } . 4 ( 0.00%) unsafe extern "C" fn destroy_value(ptr: *mut u8) { . let ptr = ptr as *mut Key; . . // SAFETY: . // . // The pointer `ptr` has been built just above and comes from . // `try_register_dtor` where it is originally a Key coming from `self`, . // making it non-NUL and of the correct type. . // -- line 661 ---------------------------------------- 4 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/memory.rs -------------------------------------------------------------------------------- Ir -- line 114 ---------------------------------------- . . /// Lets us implement `HasDataLayout`, which is awfully convenient. . pub tcx: TyCtxt<'tcx>, . } . . impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> HasDataLayout for Memory<'mir, 'tcx, M> { . #[inline] . fn data_layout(&self) -> &TargetDataLayout { 4,603 ( 0.00%) &self.tcx.data_layout . } . } . . /// A reference to some allocation that was already bounds-checked for the given region . /// and had the on-access machine hooks run. . #[derive(Copy, Clone)] . pub struct AllocRef<'a, 'tcx, Tag, Extra> { . alloc: &'a Allocation, -- line 130 ---------------------------------------- -- line 138 ---------------------------------------- . alloc: &'a mut Allocation, . range: AllocRange, . tcx: TyCtxt<'tcx>, . alloc_id: AllocId, . } . . impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> { . pub fn new(tcx: TyCtxt<'tcx>, extra: M::MemoryExtra) -> Self { 208 ( 0.00%) Memory { . alloc_map: M::MemoryMap::default(), . extra_fn_ptr_map: FxHashMap::default(), . dead_alloc_map: FxHashMap::default(), . extra, . tcx, . } . } . -- line 154 ---------------------------------------- -- line 157 ---------------------------------------- . /// for any other pointers, nor for TLS statics. . /// . /// Using the resulting pointer represents a *direct* access to that memory . /// (e.g. by directly using a `static`), . /// as opposed to access through a pointer that was created by the program. . /// . /// This function can fail only if `ptr` points to an `extern static`. . #[inline] 300 ( 0.00%) pub fn global_base_pointer( . &self, . ptr: Pointer, . ) -> InterpResult<'tcx, Pointer> { . // We know `offset` is relative to the allocation, so we can use `into_parts`. . let (alloc_id, offset) = ptr.into_parts(); . // We need to handle `extern static`. 100 ( 0.00%) match self.tcx.get_global_alloc(alloc_id) { . Some(GlobalAlloc::Static(def_id)) if self.tcx.is_thread_local_static(def_id) => { . bug!("global memory cannot point to thread-local static") . } . Some(GlobalAlloc::Static(def_id)) if self.tcx.is_foreign_item(def_id) => { . return M::extern_static_base_pointer(self, def_id); . } . _ => {} . } . // And we need to get the tag. 75 ( 0.00%) Ok(M::tag_alloc_base_pointer(self, Pointer::new(alloc_id, offset))) 200 ( 0.00%) } . . pub fn create_fn_alloc( . &mut self, . fn_val: FnVal<'tcx, M::ExtraFnVal>, . ) -> Pointer { . let id = match fn_val { . FnVal::Instance(instance) => self.tcx.create_fn_alloc(instance), . FnVal::Other(extra) => { -- line 191 ---------------------------------------- -- line 196 ---------------------------------------- . id . } . }; . // Functions are global allocations, so make sure we get the right base pointer. . // We know this is not an `extern static` so this cannot fail. . self.global_base_pointer(Pointer::from(id)).unwrap() . } . 123,687 ( 0.01%) pub fn allocate( . &mut self, . size: Size, . align: Align, . kind: MemoryKind, . ) -> InterpResult<'static, Pointer> { 54,972 ( 0.00%) let alloc = Allocation::uninit(size, align, M::PANIC_ON_ALLOC_FAIL)?; 123,687 ( 0.01%) Ok(self.allocate_with(alloc, kind)) 96,201 ( 0.00%) } . . pub fn allocate_bytes( . &mut self, . bytes: &[u8], . align: Align, . kind: MemoryKind, . mutability: Mutability, . ) -> Pointer { -- line 220 ---------------------------------------- -- line 222 ---------------------------------------- . self.allocate_with(alloc, kind) . } . . pub fn allocate_with( . &mut self, . alloc: Allocation, . kind: MemoryKind, . ) -> Pointer { 27,486 ( 0.00%) let id = self.tcx.reserve_alloc_id(); . debug_assert_ne!( . Some(kind), . M::GLOBAL_KIND.map(MemoryKind::Machine), . "dynamically allocating global memory" . ); . let alloc = M::init_allocation_extra(self, id, Cow::Owned(alloc), Some(kind)); 329,832 ( 0.02%) self.alloc_map.insert(id, (kind, alloc.into_owned())); . M::tag_alloc_base_pointer(self, Pointer::from(id)) . } . . pub fn reallocate( . &mut self, . ptr: Pointer>, . old_size_and_align: Option<(Size, Align)>, . new_size: Size, -- line 245 ---------------------------------------- -- line 361 ---------------------------------------- . let align = M::enforce_alignment(&self.extra).then_some(align); . self.check_and_deref_ptr( . ptr, . size, . align, . CheckInAllocMsg::MemoryAccessTest, . |alloc_id, offset, ptr| { . let (size, align) = 128,068 ( 0.01%) self.get_size_and_align(alloc_id, AllocCheck::Dereferenceable)?; . Ok((size, align, (alloc_id, offset, ptr))) . }, . ) . } . . /// Check if the given pointer points to live memory of given `size` and `align` . /// (ignoring `M::enforce_alignment`). The caller can control the error message for the . /// out-of-bounds case. -- line 377 ---------------------------------------- -- line 378 ---------------------------------------- . #[inline(always)] . pub fn check_ptr_access_align( . &self, . ptr: Pointer>, . size: Size, . align: Align, . msg: CheckInAllocMsg, . ) -> InterpResult<'tcx> { 228 ( 0.00%) self.check_and_deref_ptr(ptr, size, Some(align), msg, |alloc_id, _, _| { 108 ( 0.00%) let check = match msg { . CheckInAllocMsg::DerefTest | CheckInAllocMsg::MemoryAccessTest => { . AllocCheck::Dereferenceable . } . CheckInAllocMsg::PointerArithmeticTest | CheckInAllocMsg::InboundsTest => { . AllocCheck::Live . } . }; 54 ( 0.00%) let (size, align) = self.get_size_and_align(alloc_id, check)?; . Ok((size, align, ())) . })?; . Ok(()) . } . . /// Low-level helper function to check if a ptr is in-bounds and potentially return a reference . /// to the allocation it points to. Supports both shared and mutable references, as the actual . /// checking is offloaded to a helper closure. `align` defines whether and which alignment check . /// is done. Returns `None` for size 0, and otherwise `Some` of what `alloc_size` returned. 378 ( 0.00%) fn check_and_deref_ptr( . &self, . ptr: Pointer>, . size: Size, . align: Option, . msg: CheckInAllocMsg, . alloc_size: impl FnOnce( . AllocId, . Size, . Pointer, . ) -> InterpResult<'tcx, (Size, Align, T)>, . ) -> InterpResult<'tcx, Option> { 54 ( 0.00%) fn check_offset_align(offset: u64, align: Align) -> InterpResult<'static> { 135 ( 0.00%) if offset % align.bytes() == 0 { . Ok(()) . } else { . // The biggest power of two through which `offset` is divisible. . let offset_pow2 = 1 << offset.trailing_zeros(); . throw_ub!(AlignmentCheckFailed { . has: Align::from_bytes(offset_pow2).unwrap(), . required: align, . }) . } 81 ( 0.00%) } . . // Extract from the pointer an `Option` and an offset, which is relative to the . // allocation or (if that is `None`) an absolute address. 192,704 ( 0.01%) let ptr_or_addr = if size.bytes() == 0 { . // Let's see what we can do, but don't throw errors if there's nothing there. . self.ptr_try_get_alloc(ptr) . } else { . // A "real" access, we insist on getting an `AllocId`. . Ok(self.ptr_get_alloc(ptr)?) . }; . Ok(match ptr_or_addr { . Err(addr) => { -- line 440 ---------------------------------------- -- line 460 ---------------------------------------- . alloc_size, . ptr_offset: self.machine_usize_to_isize(offset.bytes()), . ptr_size: size, . msg, . }) . } . // Test align. Check this last; if both bounds and alignment are violated . // we want the error to be about the bounds. 54 ( 0.00%) if let Some(align) = align { . if M::force_int_for_alignment_check(&self.extra) { . let addr = Scalar::from_pointer(ptr, &self.tcx) . .to_machine_usize(&self.tcx) . .expect("ptr-to-int cast for align check should never fail"); . check_offset_align(addr, align)?; . } else { . // Check allocation alignment and offset alignment. 54 ( 0.00%) if alloc_align.bytes() < align.bytes() { . throw_ub!(AlignmentCheckFailed { has: alloc_align, required: align }); . } 135 ( 0.00%) check_offset_align(offset.bytes(), align)?; . } . } . . // We can still be zero-sized in this branch, in which case we have to . // return `None`. . if size.bytes() == 0 { None } else { Some(ret_val) } . } . }) 405 ( 0.00%) } . . /// Test if the pointer might be null. . pub fn ptr_may_be_null(&self, ptr: Pointer>) -> bool { . match self.ptr_try_get_alloc(ptr) { . Ok((alloc_id, offset, _)) => { . let (size, _align) = self . .get_size_and_align(alloc_id, AllocCheck::MaybeDead) . .expect("alloc info with MaybeDead cannot fail"); -- line 496 ---------------------------------------- -- line 505 ---------------------------------------- . . /// Allocation accessors . impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> { . /// Helper function to obtain a global (tcx) allocation. . /// This attempts to return a reference to an existing allocation if . /// one can be found in `tcx`. That, however, is only possible if `tcx` and . /// this machine use the same pointer tag, so it is indirected through . /// `M::tag_allocation`. 555,863 ( 0.03%) fn get_global_alloc( . &self, . id: AllocId, . is_write: bool, . ) -> InterpResult<'tcx, Cow<'tcx, Allocation>> { 454,797 ( 0.02%) let (alloc, def_id) = match self.tcx.get_global_alloc(id) { 50,533 ( 0.00%) Some(GlobalAlloc::Memory(mem)) => { . // Memory of a constant or promoted or anonymous memory referenced by a static. . (mem, None) . } . Some(GlobalAlloc::Function(..)) => throw_ub!(DerefFunctionPointer(id)), . None => throw_ub!(PointerUseAfterFree(id)), . Some(GlobalAlloc::Static(def_id)) => { . assert!(self.tcx.is_static(def_id)); . assert!(!self.tcx.is_thread_local_static(def_id)); -- line 527 ---------------------------------------- -- line 537 ---------------------------------------- . // to another static), those inner references only exist in "resolved" form. . if self.tcx.is_foreign_item(def_id) { . throw_unsup!(ReadExternStatic(def_id)); . } . . (self.tcx.eval_static_initializer(def_id)?, Some(def_id)) . } . }; 404,264 ( 0.02%) M::before_access_global(&self.extra, id, alloc, def_id, is_write)?; . let alloc = Cow::Borrowed(alloc); . // We got tcx memory. Let the machine initialize its "extra" stuff. . let alloc = M::init_allocation_extra( . self, . id, // always use the ID we got as input, not the "hidden" one. . alloc, . M::GLOBAL_KIND.map(MemoryKind::Machine), . ); 202,132 ( 0.01%) Ok(alloc) 404,264 ( 0.02%) } . . /// Gives raw access to the `Allocation`, without bounds or alignment checks. . /// The caller is responsible for calling the access hooks! 275,248 ( 0.01%) fn get_raw( . &self, . id: AllocId, . ) -> InterpResult<'tcx, &Allocation> { . // The error type of the inner closure here is somewhat funny. We have two . // ways of "erroring": An actual error, or because we got a reference from . // `get_global_alloc` that we can actually use directly without inserting anything anywhere. . // So the error type is `InterpResult<'tcx, &Allocation>`. . let a = self.alloc_map.get_or(id, || { 202,132 ( 0.01%) let alloc = self.get_global_alloc(id, /*is_write*/ false).map_err(Err)?; 101,066 ( 0.00%) match alloc { . Cow::Borrowed(alloc) => { . // We got a ref, cheaply return that as an "error" so that the . // map does not get mutated. . Err(Ok(alloc)) . } . Cow::Owned(alloc) => { . // Need to put it into the map and return a ref to that . let kind = M::GLOBAL_KIND.expect( -- line 577 ---------------------------------------- -- line 578 ---------------------------------------- . "I got a global allocation that I have to copy but the machine does \ . not expect that to happen", . ); . Ok((MemoryKind::Machine(kind), alloc)) . } . } . }); . // Now unpack that funny error type 36,558 ( 0.00%) match a { . Ok(a) => Ok(&a.1), . Err(a) => a, . } 206,436 ( 0.01%) } . . /// "Safe" (bounds and align-checked) allocation access. 771,048 ( 0.04%) pub fn get<'a>( . &'a self, . ptr: Pointer>, . size: Size, . align: Align, . ) -> InterpResult<'tcx, Option>> { . let align = M::enforce_alignment(&self.extra).then_some(align); . let ptr_and_alloc = self.check_and_deref_ptr( . ptr, . size, . align, . CheckInAllocMsg::MemoryAccessTest, . |alloc_id, offset, ptr| { 257,016 ( 0.01%) let alloc = self.get_raw(alloc_id)?; . Ok((alloc.size(), alloc.align, (alloc_id, offset, ptr, alloc))) . }, . )?; 128,508 ( 0.01%) if let Some((alloc_id, offset, ptr, alloc)) = ptr_and_alloc { . let range = alloc_range(offset, size); . M::memory_read(&self.extra, &alloc.extra, ptr.provenance, range)?; 449,778 ( 0.02%) Ok(Some(AllocRef { alloc, range, tcx: self.tcx, alloc_id })) . } else { . // Even in this branch we have to be sure that we actually access the allocation, in . // order to ensure that `static FOO: Type = FOO;` causes a cycle error instead of . // magically pulling *any* ZST value from the ether. However, the `get_raw` above is . // always called when `ptr` has an `AllocId`. . Ok(None) . } 578,286 ( 0.03%) } . . /// Return the `extra` field of the given allocation. . pub fn get_alloc_extra<'a>(&'a self, id: AllocId) -> InterpResult<'tcx, &'a M::AllocExtra> { . Ok(&self.get_raw(id)?.extra) . } . . /// Gives raw mutable access to the `Allocation`, without bounds or alignment checks. . /// The caller is responsible for calling the access hooks! . /// . /// Also returns a ptr to `self.extra` so that the caller can use it in parallel with the . /// allocation. 219,672 ( 0.01%) fn get_raw_mut( . &mut self, . id: AllocId, . ) -> InterpResult<'tcx, (&mut Allocation, &mut M::MemoryExtra)> . { . // We have "NLL problem case #3" here, which cannot be worked around without loss of . // efficiency even for the common case where the key is in the map. . // . // (Cannot use `get_mut_or` since `get_global_alloc` needs `&self`.) 27,459 ( 0.00%) if self.alloc_map.get_mut(id).is_none() { . // Slow path. . // Allocation not found locally, go look global. . let alloc = self.get_global_alloc(id, /*is_write*/ true)?; . let kind = M::GLOBAL_KIND.expect( . "I got a global allocation that I have to copy but the machine does \ . not expect that to happen", . ); . self.alloc_map.insert(id, (MemoryKind::Machine(kind), alloc.into_owned())); . } . 27,459 ( 0.00%) let (_kind, alloc) = self.alloc_map.get_mut(id).unwrap(); 27,459 ( 0.00%) if alloc.mutability == Mutability::Not { . throw_ub!(WriteToReadOnly(id)) . } 109,836 ( 0.01%) Ok((alloc, &mut self.extra)) 137,295 ( 0.01%) } . . /// "Safe" (bounds and align-checked) allocation access. 274,812 ( 0.01%) pub fn get_mut<'a>( . &'a mut self, . ptr: Pointer>, . size: Size, . align: Align, . ) -> InterpResult<'tcx, Option>> { . let parts = self.get_ptr_access(ptr, size, align)?; 45,802 ( 0.00%) if let Some((alloc_id, offset, ptr)) = parts { . let tcx = self.tcx; . // FIXME: can we somehow avoid looking up the allocation twice here? . // We cannot call `get_raw_mut` inside `check_and_deref_ptr` as that would duplicate `&mut self`. 68,703 ( 0.00%) let (alloc, extra) = self.get_raw_mut(alloc_id)?; . let range = alloc_range(offset, size); . M::memory_written(extra, &mut alloc.extra, ptr.provenance, range)?; 137,406 ( 0.01%) Ok(Some(AllocRefMut { alloc, range, tcx, alloc_id })) . } else { . Ok(None) . } 206,109 ( 0.01%) } . . /// Return the `extra` field of the given allocation. . pub fn get_alloc_extra_mut<'a>( . &'a mut self, . id: AllocId, . ) -> InterpResult<'tcx, (&'a mut M::AllocExtra, &'a mut M::MemoryExtra)> { . let (alloc, memory_extra) = self.get_raw_mut(id)?; . Ok((&mut alloc.extra, memory_extra)) . } . . /// Obtain the size and alignment of an allocation, even if that allocation has . /// been deallocated. . /// . /// If `liveness` is `AllocCheck::MaybeDead`, this function always returns `Ok`. 352,484 ( 0.02%) pub fn get_size_and_align( . &self, . id: AllocId, . liveness: AllocCheck, . ) -> InterpResult<'static, (Size, Align)> { . // # Regular allocations . // Don't use `self.get_raw` here as that will . // a) cause cycles in case `id` refers to a static . // b) duplicate a global's allocation in miri 160,220 ( 0.01%) if let Some((_, alloc)) = self.alloc_map.get(id) { 32,017 ( 0.00%) return Ok((alloc.size(), alloc.align)); . } . . // # Function pointers . // (both global from `alloc_map` and local from `extra_fn_ptr_map`) 108 ( 0.00%) if self.get_fn_alloc(id).is_some() { . return if let AllocCheck::Dereferenceable = liveness { . // The caller requested no function pointers. . throw_ub!(DerefFunctionPointer(id)) . } else { . Ok((Size::ZERO, Align::ONE)) . }; . } . . // # Statics . // Can't do this in the match argument, we may get cycle errors since the lock would . // be held throughout the match. 297 ( 0.00%) match self.tcx.get_global_alloc(id) { . Some(GlobalAlloc::Static(did)) => { . assert!(!self.tcx.is_thread_local_static(did)); . // Use size and align of the type. . let ty = self.tcx.type_of(did); . let layout = self.tcx.layout_of(ParamEnv::empty().and(ty)).unwrap(); . Ok((layout.size, layout.align.abi)) . } 27 ( 0.00%) Some(GlobalAlloc::Memory(alloc)) => { . // Need to duplicate the logic here, because the global allocations have . // different associated types than the interpreter-local ones. 54 ( 0.00%) Ok((alloc.size(), alloc.align)) . } . Some(GlobalAlloc::Function(_)) => bug!("We already checked function pointers above"), . // The rest must be dead. . None => { . if let AllocCheck::MaybeDead = liveness { . // Deallocated pointers are allowed, we should be able to find . // them in the map. . Ok(*self -- line 740 ---------------------------------------- -- line 741 ---------------------------------------- . .dead_alloc_map . .get(&id) . .expect("deallocated pointers should all be recorded in `dead_alloc_map`")) . } else { . throw_ub!(PointerUseAfterFree(id)) . } . } . } 256,352 ( 0.01%) } . 108 ( 0.00%) fn get_fn_alloc(&self, id: AllocId) -> Option> { . if let Some(extra) = self.extra_fn_ptr_map.get(&id) { . Some(FnVal::Other(*extra)) . } else { 135 ( 0.00%) match self.tcx.get_global_alloc(id) { . Some(GlobalAlloc::Function(instance)) => Some(FnVal::Instance(instance)), 27 ( 0.00%) _ => None, . } . } 108 ( 0.00%) } . . pub fn get_fn( . &self, . ptr: Pointer>, . ) -> InterpResult<'tcx, FnVal<'tcx, M::ExtraFnVal>> { . trace!("get_fn({:?})", ptr); . let (alloc_id, offset, _ptr) = self.ptr_get_alloc(ptr)?; . if offset.bytes() != 0 { -- line 768 ---------------------------------------- -- line 903 ---------------------------------------- . writeln!(fmt)?; . } . Ok(()) . } . } . . /// Reading and writing. . impl<'tcx, 'a, Tag: Provenance, Extra> AllocRefMut<'a, 'tcx, Tag, Extra> { 247,176 ( 0.01%) pub fn write_scalar( . &mut self, . range: AllocRange, . val: ScalarMaybeUninit, . ) -> InterpResult<'tcx> { 137,320 ( 0.01%) Ok(self . .alloc 302,104 ( 0.01%) .write_scalar(&self.tcx, self.range.subrange(range), val) . .map_err(|e| e.to_interp_error(self.alloc_id))?) 164,784 ( 0.01%) } . . pub fn write_ptr_sized( . &mut self, . offset: Size, . val: ScalarMaybeUninit, . ) -> InterpResult<'tcx> { . self.write_scalar(alloc_range(offset, self.tcx.data_layout().pointer_size), val) . } . } . . impl<'tcx, 'a, Tag: Provenance, Extra> AllocRef<'a, 'tcx, Tag, Extra> { 36,600 ( 0.00%) pub fn read_scalar(&self, range: AllocRange) -> InterpResult<'tcx, ScalarMaybeUninit> { 693,223 ( 0.03%) Ok(self . .alloc 390,183 ( 0.02%) .read_scalar(&self.tcx, self.range.subrange(range)) . .map_err(|e| e.to_interp_error(self.alloc_id))?) 36,600 ( 0.00%) } . . pub fn read_ptr_sized(&self, offset: Size) -> InterpResult<'tcx, ScalarMaybeUninit> { . self.read_scalar(alloc_range(offset, self.tcx.data_layout().pointer_size)) . } . . pub fn check_bytes(&self, range: AllocRange, allow_uninit_and_ptr: bool) -> InterpResult<'tcx> { . Ok(self . .alloc -- line 945 ---------------------------------------- -- line 947 ---------------------------------------- . .map_err(|e| e.to_interp_error(self.alloc_id))?) . } . } . . impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> { . /// Reads the given number of bytes from memory. Returns them as a slice. . /// . /// Performs appropriate bounds checks. 12 ( 0.00%) pub fn read_bytes( . &self, . ptr: Pointer>, . size: Size, . ) -> InterpResult<'tcx, &[u8]> { 9 ( 0.00%) let alloc_ref = match self.get(ptr, size, Align::ONE)? { 18 ( 0.00%) Some(a) => a, . None => return Ok(&[]), // zero-sized access . }; . // Side-step AllocRef and directly access the underlying bytes more efficiently. . // (We are staying inside the bounds here so all is good.) 6 ( 0.00%) Ok(alloc_ref . .alloc 9 ( 0.00%) .get_bytes(&alloc_ref.tcx, alloc_ref.range) . .map_err(|e| e.to_interp_error(alloc_ref.alloc_id))?) 12 ( 0.00%) } . . /// Writes the given stream of bytes into memory. . /// . /// Performs appropriate bounds checks. . pub fn write_bytes( . &mut self, . ptr: Pointer>, . src: impl IntoIterator, -- line 978 ---------------------------------------- -- line 1016 ---------------------------------------- . &mut self, . src: Pointer>, . src_align: Align, . dest: Pointer>, . dest_align: Align, . size: Size, . nonoverlapping: bool, . ) -> InterpResult<'tcx> { 22,790 ( 0.00%) self.copy_repeatedly(src, src_align, dest, dest_align, size, 1, nonoverlapping) . } . 59,254 ( 0.00%) pub fn copy_repeatedly( . &mut self, . src: Pointer>, . src_align: Align, . dest: Pointer>, . dest_align: Align, . size: Size, . num_copies: u64, . nonoverlapping: bool, . ) -> InterpResult<'tcx> { 9,116 ( 0.00%) let tcx = self.tcx; . // We need to do our own bounds-checks. . let src_parts = self.get_ptr_access(src, size, src_align)?; . let dest_parts = self.get_ptr_access(dest, size * num_copies, dest_align)?; // `Size` multiplication . . // FIXME: we look up both allocations twice here, once ebfore for the `check_ptr_access` . // and once below to get the underlying `&[mut] Allocation`. . . // Source alloc preparations and access hooks. 9,116 ( 0.00%) let (src_alloc_id, src_offset, src) = match src_parts { . None => return Ok(()), // Zero-sized *source*, that means dst is also zero-sized and we have nothing to do. . Some(src_ptr) => src_ptr, . }; 18,232 ( 0.00%) let src_alloc = self.get_raw(src_alloc_id)?; . let src_range = alloc_range(src_offset, size); . M::memory_read(&self.extra, &src_alloc.extra, src.provenance, src_range)?; . // We need the `dest` ptr for the next operation, so we get it now. . // We already did the source checks and called the hooks so we are good to return early. 9,116 ( 0.00%) let (dest_alloc_id, dest_offset, dest) = match dest_parts { . None => return Ok(()), // Zero-sized *destiantion*. . Some(dest_ptr) => dest_ptr, . }; . . // This checks relocation edges on the src, which needs to happen before . // `prepare_relocation_copy`. . let src_bytes = src_alloc . .get_bytes_with_uninit_and_ptr(&tcx, src_range) . .map_err(|e| e.to_interp_error(src_alloc_id))? . .as_ptr(); // raw ptr, so we can also get a ptr to the destination allocation . // first copy the relocations to a temporary buffer, because . // `get_bytes_mut` will clear the relocations, which is correct, . // since we don't want to keep any relocations at the target. . let relocations = 54,696 ( 0.00%) src_alloc.prepare_relocation_copy(self, src_range, dest_offset, num_copies); . // Prepare a copy of the initialization mask. 18,232 ( 0.00%) let compressed = src_alloc.compress_uninit_range(src_range); . . // Destination alloc preparations and access hooks. 13,674 ( 0.00%) let (dest_alloc, extra) = self.get_raw_mut(dest_alloc_id)?; 13,674 ( 0.00%) let dest_range = alloc_range(dest_offset, size * num_copies); . M::memory_written(extra, &mut dest_alloc.extra, dest.provenance, dest_range)?; 18,232 ( 0.00%) let dest_bytes = dest_alloc . .get_bytes_mut_ptr(&tcx, dest_range) . .map_err(|e| e.to_interp_error(dest_alloc_id))? . .as_mut_ptr(); . 13,674 ( 0.00%) if compressed.no_bytes_init() { . // Fast path: If all bytes are `uninit` then there is nothing to copy. The target range . // is marked as uninitialized but we otherwise omit changing the byte representation which may . // be arbitrary for uninitialized bytes. . // This also avoids writing to the target bytes so that the backing allocation is never . // touched if the bytes stay uninitialized for the whole interpreter execution. On contemporary . // operating system this can avoid physically allocating the page. . dest_alloc.mark_init(dest_range, false); // `Size` multiplication . dest_alloc.mark_relocation_range(relocations); -- line 1091 ---------------------------------------- -- line 1093 ---------------------------------------- . } . . // SAFE: The above indexing would have panicked if there weren't at least `size` bytes . // behind `src` and `dest`. Also, we use the overlapping-safe `ptr::copy` if `src` and . // `dest` could possibly overlap. . // The pointers above remain valid even if the `HashMap` table is moved around because they . // point into the `Vec` storing the bytes. . unsafe { 4,558 ( 0.00%) if src_alloc_id == dest_alloc_id { . if nonoverlapping { . // `Size` additions . if (src_offset <= dest_offset && src_offset + size > dest_offset) . || (dest_offset <= src_offset && dest_offset + size > src_offset) . { . throw_ub_format!("copy_nonoverlapping called on overlapping ranges") . } . } -- line 1109 ---------------------------------------- -- line 1114 ---------------------------------------- . dest_bytes.add((size * i).bytes_usize()), // `Size` multiplication . size.bytes_usize(), . ); . } . } else { . for i in 0..num_copies { . ptr::copy_nonoverlapping( . src_bytes, 13,674 ( 0.00%) dest_bytes.add((size * i).bytes_usize()), // `Size` multiplication . size.bytes_usize(), . ); . } . } . } . . // now fill in all the "init" data 22,790 ( 0.00%) dest_alloc.mark_compressed_init_range( . &compressed, . alloc_range(dest_offset, size), // just a single copy (i.e., not full `dest_range`) . num_copies, . ); . // copy the relocations to the destination 41,022 ( 0.00%) dest_alloc.mark_relocation_range(relocations); . . Ok(()) 41,022 ( 0.00%) } . } . . /// Machine pointer introspection. . impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> { 45 ( 0.00%) pub fn scalar_to_ptr(&self, scalar: Scalar) -> Pointer> { . // We use `to_bits_or_ptr_internal` since we are just implementing the method people need to . // call to force getting out a pointer. 225 ( 0.00%) match scalar.to_bits_or_ptr_internal(self.pointer_size()) { . Err(ptr) => ptr.into(), . Ok(bits) => { . let addr = u64::try_from(bits).unwrap(); . let ptr = M::ptr_from_addr(&self, addr); . if addr == 0 { . assert!(ptr.provenance.is_none(), "null pointer can never have an AllocId"); . } . ptr . } . } 90 ( 0.00%) } . . /// Turning a "maybe pointer" into a proper pointer (and some information . /// about where it points), or an absolute address. . pub fn ptr_try_get_alloc( . &self, . ptr: Pointer>, . ) -> Result<(AllocId, Size, Pointer), u64> { . match ptr.into_pointer_or_addr() { -- line 1166 ---------------------------------------- 660,053 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_resolve/src/macros.rs -------------------------------------------------------------------------------- Ir -- line 84 ---------------------------------------- . } . let sub_ns = |kind| match kind { . MacroKind::Bang => SubNS::Bang, . MacroKind::Attr | MacroKind::Derive => SubNS::AttrLike, . }; . let candidate = candidate.map(sub_ns); . let requirement = requirement.map(sub_ns); . // "No specific sub-namespace" means "matches anything" for both requirements and candidates. 37,714 ( 0.00%) candidate.is_none() || requirement.is_none() || candidate == requirement . } . . // We don't want to format a path using pretty-printing, . // `format!("{}", path)`, because that tries to insert . // line-breaks and is slow. 39,392 ( 0.00%) fn fast_print_path(path: &ast::Path) -> Symbol { 14,772 ( 0.00%) if path.segments.len() == 1 { 9,848 ( 0.00%) path.segments[0].ident.name . } else { . let mut path_str = String::with_capacity(64); . for (i, segment) in path.segments.iter().enumerate() { . if i != 0 { . path_str.push_str("::"); . } . if segment.ident.name != kw::PathRoot { . path_str.push_str(segment.ident.as_str()) . } . } . Symbol::intern(&path_str) . } 44,316 ( 0.00%) } . . /// The code common between processing `#![register_tool]` and `#![register_attr]`. 22 ( 0.00%) fn registered_idents( . sess: &Session, . attrs: &[ast::Attribute], . attr_name: Symbol, . descr: &str, . ) -> FxHashSet { . let mut registered = FxHashSet::default(); 2 ( 0.00%) for attr in sess.filter_by_name(attrs, attr_name) { . for nested_meta in attr.meta_item_list().unwrap_or_default() { . match nested_meta.ident() { . Some(ident) => { . if let Some(old_ident) = registered.replace(ident) { . let msg = format!("{} `{}` was already registered", descr, ident); . sess.struct_span_err(ident.span, &msg) . .span_label(old_ident.span, "already registered here") . .emit(); -- line 131 ---------------------------------------- -- line 135 ---------------------------------------- . let msg = format!("`{}` only accepts identifiers", attr_name); . let span = nested_meta.span(); . sess.struct_span_err(span, &msg).span_label(span, "not an identifier").emit(); . } . } . } . } . registered 16 ( 0.00%) } . 9 ( 0.00%) crate fn registered_attrs_and_tools( . sess: &Session, . attrs: &[ast::Attribute], . ) -> (FxHashSet, FxHashSet) { 5 ( 0.00%) let registered_attrs = registered_idents(sess, attrs, sym::register_attr, "attribute"); 8 ( 0.00%) let mut registered_tools = registered_idents(sess, attrs, sym::register_tool, "tool"); . // We implicitly add `rustfmt` and `clippy` to known tools, . // but it's not an error to register them explicitly. . let predefined_tools = [sym::clippy, sym::rustfmt]; . registered_tools.extend(predefined_tools.iter().cloned().map(Ident::with_dummy_span)); 8 ( 0.00%) (registered_attrs, registered_tools) 7 ( 0.00%) } . . // Some feature gates for inner attributes are reported as lints for backward compatibility. . fn soft_custom_inner_attributes_gate(path: &ast::Path, invoc: &Invocation) -> bool { . match &path.segments[..] { . // `#![test]` 24,620 ( 0.00%) [seg] if seg.ident.name == sym::test => return true, . // `#![rustfmt::skip]` on out-of-line modules . [seg1, seg2] if seg1.ident.name == sym::rustfmt && seg2.ident.name == sym::skip => { . if let InvocationKind::Attr { item, .. } = &invoc.kind { . if let Annotatable::Item(item) = item { . if let ItemKind::Mod(_, ModKind::Loaded(_, Inline::No, _)) = item.kind { . return true; . } . } -- line 170 ---------------------------------------- -- line 171 ---------------------------------------- . } . } . _ => {} . } . false . } . . impl<'a> ResolverExpand for Resolver<'a> { 67,883 ( 0.00%) fn next_node_id(&mut self) -> NodeId { . self.next_node_id() 135,766 ( 0.01%) } . . fn invocation_parent(&self, id: LocalExpnId) -> LocalDefId { . self.invocation_parents[&id].0 . } . . fn resolve_dollar_crates(&mut self) { 4,935 ( 0.00%) hygiene::update_dollar_crate_names(|ctxt| { . let ident = Ident::new(kw::DollarCrate, DUMMY_SP.with_ctxt(ctxt)); 44,325 ( 0.00%) match self.resolve_crate_root(ident).kind { . ModuleKind::Def(.., name) if name != kw::Empty => name, . _ => kw::Crate, . } . }); . } . 39,400 ( 0.00%) fn visit_ast_fragment_with_placeholders( . &mut self, . expansion: LocalExpnId, . fragment: &AstFragment, . ) { . // Integrate the new AST fragment into all the definition and module structures. . // We are inside the `expansion` now, but other parent scope components are still the same. 19,700 ( 0.00%) let parent_scope = ParentScope { expansion, ..self.invocation_parent_scopes[&expansion] }; . let output_macro_rules_scope = self.build_reduced_graph(fragment, parent_scope); . self.output_macro_rules_scopes.insert(expansion, output_macro_rules_scope); . . parent_scope.module.unexpanded_invocations.borrow_mut().remove(&expansion); 39,400 ( 0.00%) } . 308 ( 0.00%) fn register_builtin_macro(&mut self, name: Symbol, ext: SyntaxExtensionKind) { 264 ( 0.00%) if self.builtin_macros.insert(name, BuiltinMacroState::NotYetSeen(ext)).is_some() { . self.session . .diagnostic() . .bug(&format!("built-in macro `{}` was already registered", name)); . } 220 ( 0.00%) } . . // Create a new Expansion with a definition site of the provided module, or . // a fake empty `#[no_implicit_prelude]` module if no module is provided. 9 ( 0.00%) fn expansion_for_ast_pass( . &mut self, . call_site: Span, . pass: AstPass, . features: &[Symbol], . parent_module_id: Option, . ) -> LocalExpnId { . let parent_module = . parent_module_id.map(|module_id| self.local_def_id(module_id).to_def_id()); . let expn_id = LocalExpnId::fresh( 11 ( 0.00%) ExpnData::allow_unstable( . ExpnKind::AstPass(pass), . call_site, 7 ( 0.00%) self.session.edition(), . features.into(), . None, . parent_module, . ), . self.create_stable_hashing_context(), . ); . . let parent_scope = . parent_module.map_or(self.empty_module, |def_id| self.expect_module(def_id)); . self.ast_transform_scopes.insert(expn_id, parent_scope); . . expn_id 9 ( 0.00%) } . 2 ( 0.00%) fn resolve_imports(&mut self) { 6 ( 0.00%) ImportResolver { r: self }.resolve_imports() 4 ( 0.00%) } . 34,468 ( 0.00%) fn resolve_macro_invocation( . &mut self, . invoc: &Invocation, . eager_expansion_root: LocalExpnId, . force: bool, . ) -> Result, Indeterminate> { . let invoc_id = invoc.expansion_data.id; . let parent_scope = match self.invocation_parent_scopes.get(&invoc_id) { 14,772 ( 0.00%) Some(parent_scope) => *parent_scope, . None => { . // If there's no entry in the table, then we are resolving an eagerly expanded . // macro, which should inherit its parent scope from its eager expansion root - . // the macro that requested this eager expansion. . let parent_scope = *self . .invocation_parent_scopes . .get(&eager_expansion_root) . .expect("non-eager expansion without a parent scope"); . self.invocation_parent_scopes.insert(invoc_id, parent_scope); . parent_scope . } . }; . 24,662 ( 0.00%) let (path, kind, inner_attr, derives) = match invoc.kind { 3 ( 0.00%) InvocationKind::Attr { ref attr, ref derives, .. } => ( 6 ( 0.00%) &attr.get_normal_item().path, . MacroKind::Attr, . attr.style == ast::AttrStyle::Inner, 3 ( 0.00%) self.arenas.alloc_ast_paths(derives), . ), 44,127 ( 0.00%) InvocationKind::Bang { ref mac, .. } => (&mac.path, MacroKind::Bang, false, &[][..]), 144 ( 0.00%) InvocationKind::Derive { ref path, .. } => (path, MacroKind::Derive, false, &[][..]), . }; . . // Derives are not included when `invocations` are collected, so we have to add them here. 24,620 ( 0.00%) let parent_scope = &ParentScope { derives, ..parent_scope }; 14,772 ( 0.00%) let supports_macro_expansion = invoc.fragment_kind.supports_macro_expansion(); . let node_id = invoc.expansion_data.lint_node_id; 4,924 ( 0.00%) let (ext, res) = self.smart_resolve_macro_path( . path, . kind, . supports_macro_expansion, . inner_attr, . parent_scope, . node_id, . force, . soft_custom_inner_attributes_gate(path, invoc), . )?; . 9,848 ( 0.00%) let span = invoc.span(); . let def_id = res.opt_def_id(); . invoc_id.set_expn_data( 49,240 ( 0.00%) ext.expn_data( 9,848 ( 0.00%) parent_scope.expansion, . span, 4,924 ( 0.00%) fast_print_path(path), . def_id, 24,620 ( 0.00%) def_id.map(|def_id| self.macro_def_scope(def_id).nearest_parent_mod()), . ), . self.create_stable_hashing_context(), . ); . . Ok(ext) 39,392 ( 0.00%) } . 7 ( 0.00%) fn check_unused_macros(&mut self) { . for (_, &(node_id, ident)) in self.unused_macros.iter() { . self.lint_buffer.buffer_lint( . UNUSED_MACROS, . node_id, . ident.span, . &format!("unused macro definition: `{}`", ident.as_str()), . ); . } 8 ( 0.00%) } . 42 ( 0.00%) fn has_derive_copy(&self, expn_id: LocalExpnId) -> bool { . self.containers_deriving_copy.contains(&expn_id) 42 ( 0.00%) } . 33 ( 0.00%) fn resolve_derives( . &mut self, . expn_id: LocalExpnId, . force: bool, . derive_paths: &dyn Fn() -> DeriveResolutions, . ) -> Result<(), Indeterminate> { . // Block expansion of the container until we resolve all derives in it. . // This is required for two reasons: . // - Derive helper attributes are in scope for the item to which the `#[derive]` . // is applied, so they have to be produced by the container's expansion rather . // than by individual derives. . // - Derives in the container need to know whether one of them is a built-in `Copy`. . // Temporarily take the data to avoid borrow checker conflicts. . let mut derive_data = mem::take(&mut self.derive_data); . let entry = derive_data.entry(expn_id).or_insert_with(|| DeriveData { 6 ( 0.00%) resolutions: derive_paths(), . helper_attrs: Vec::new(), . has_derive_copy: false, . }); 21 ( 0.00%) let parent_scope = self.invocation_parent_scopes[&expn_id]; . for (i, (path, _, opt_ext)) in entry.resolutions.iter_mut().enumerate() { 18 ( 0.00%) if opt_ext.is_none() { 18 ( 0.00%) *opt_ext = Some( 270 ( 0.00%) match self.resolve_macro_path( . &path, . Some(MacroKind::Derive), . &parent_scope, . true, . force, . ) { 36 ( 0.00%) Ok((Some(ext), _)) => { 18 ( 0.00%) if !ext.helper_attrs.is_empty() { . let last_seg = path.segments.last().unwrap(); . let span = last_seg.ident.span.normalize_to_macros_2_0(); . entry.helper_attrs.extend( . ext.helper_attrs . .iter() . .map(|name| (i, Ident::new(*name, span))), . ); . } 108 ( 0.00%) entry.has_derive_copy |= ext.builtin_name == Some(sym::Copy); . ext . } . Ok(_) | Err(Determinacy::Determined) => self.dummy_ext(MacroKind::Derive), . Err(Determinacy::Undetermined) => { . assert!(self.derive_data.is_empty()); . self.derive_data = derive_data; . return Err(Indeterminate); . } . }, 126 ( 0.00%) ); . } . } . // Sort helpers in a stable way independent from the derive resolution order. . entry.helper_attrs.sort_by_key(|(i, _)| *i); . self.helper_attrs . .insert(expn_id, entry.helper_attrs.iter().map(|(_, ident)| *ident).collect()); . // Mark this derive as having `Copy` either if it has `Copy` itself or if its parent derive . // has `Copy`, to support cases like `#[derive(Clone, Copy)] #[derive(Debug)]`. 6 ( 0.00%) if entry.has_derive_copy || self.has_derive_copy(parent_scope.expansion) { . self.containers_deriving_copy.insert(expn_id); . } 3 ( 0.00%) assert!(self.derive_data.is_empty()); 27 ( 0.00%) self.derive_data = derive_data; . Ok(()) 24 ( 0.00%) } . 19,696 ( 0.00%) fn take_derive_resolutions(&mut self, expn_id: LocalExpnId) -> Option { . self.derive_data.remove(&expn_id).map(|data| data.resolutions) 19,696 ( 0.00%) } . . // The function that implements the resolution logic of `#[cfg_accessible(path)]`. . // Returns true if the path can certainly be resolved in one of three namespaces, . // returns false if the path certainly cannot be resolved in any of the three namespaces. . // Returns `Indeterminate` if we cannot give a certain answer yet. . fn cfg_accessible( . &mut self, . expn_id: LocalExpnId, -- line 409 ---------------------------------------- -- line 444 ---------------------------------------- . self.crate_loader.cstore().get_proc_macro_quoted_span_untracked(krate, id, self.session) . } . . fn declare_proc_macro(&mut self, id: NodeId) { . self.proc_macros.push(id) . } . . fn registered_tools(&self) -> &RegisteredTools { 6 ( 0.00%) &self.registered_tools 6 ( 0.00%) } . } . . impl<'a> Resolver<'a> { . /// Resolve macro path with error reporting and recovery. . /// Uses dummy syntax extensions for unresolved macros or macros with unexpected resolutions . /// for better error recovery. . fn smart_resolve_macro_path( . &mut self, -- line 461 ---------------------------------------- -- line 463 ---------------------------------------- . kind: MacroKind, . supports_macro_expansion: SupportsMacroExpansion, . inner_attr: bool, . parent_scope: &ParentScope<'a>, . node_id: NodeId, . force: bool, . soft_custom_inner_attributes_gate: bool, . ) -> Result<(Lrc, Res), Indeterminate> { 118,176 ( 0.01%) let (ext, res) = match self.resolve_macro_path(path, Some(kind), parent_scope, true, force) . { 29,544 ( 0.00%) Ok((Some(ext), res)) => (ext, res), . Ok((None, res)) => (self.dummy_ext(kind), res), . Err(Determinacy::Determined) => (self.dummy_ext(kind), Res::Err), . Err(Determinacy::Undetermined) => return Err(Indeterminate), . }; . . // Report errors for the resolved macro. . for segment in &path.segments { 39,377 ( 0.00%) if let Some(args) = &segment.args { . self.session.span_err(args.span(), "generic arguments in macro path"); . } 9,860 ( 0.00%) if kind == MacroKind::Attr && segment.ident.as_str().starts_with("rustc") { . self.session.span_err( . segment.ident.span, . "attributes starting with `rustc` are reserved for use by the `rustc` compiler", . ); . } . } . 54,164 ( 0.00%) match res { . Res::Def(DefKind::Macro(_), def_id) => { 4,924 ( 0.00%) if let Some(def_id) = def_id.as_local() { . self.unused_macros.remove(&def_id); . if self.proc_macro_stubs.contains(&def_id) { . self.session.span_err( . path.span, . "can't use a procedural macro from the same crate that defines it", . ); . } . } . } . Res::NonMacroAttr(..) | Res::Err => {} . _ => panic!("expected `DefKind::Macro` or `Res::NonMacroAttr`"), . }; . . self.check_stability_and_deprecation(&ext, path, node_id); . 14,772 ( 0.00%) let unexpected_res = if ext.macro_kind() != kind { . Some((kind.article(), kind.descr_expected())) 9,848 ( 0.00%) } else if matches!(res, Res::Def(..)) { 9,848 ( 0.00%) match supports_macro_expansion { . SupportsMacroExpansion::No => Some(("a", "non-macro attribute")), . SupportsMacroExpansion::Yes { supports_inner_attrs } => { 14,772 ( 0.00%) if inner_attr && !supports_inner_attrs { . Some(("a", "non-macro inner attribute")) . } else { . None . } . } . } . } else { . None -- line 524 ---------------------------------------- -- line 529 ---------------------------------------- . self.session . .struct_span_err(path.span, &msg) . .span_label(path.span, format!("not {} {}", article, expected)) . .emit(); . return Ok((self.dummy_ext(kind), Res::Err)); . } . . // We are trying to avoid reporting this error if other related errors were reported. 29,544 ( 0.00%) if res != Res::Err . && inner_attr . && !self.session.features_untracked().custom_inner_attributes . { . let msg = match res { . Res::Def(..) => "inner macro attributes are unstable", . Res::NonMacroAttr(..) => "custom inner attributes are unstable", . _ => unreachable!(), . }; -- line 545 ---------------------------------------- -- line 546 ---------------------------------------- . if soft_custom_inner_attributes_gate { . self.session.parse_sess.buffer_lint(SOFT_UNSTABLE, path.span, node_id, msg); . } else { . feature_err(&self.session.parse_sess, sym::custom_inner_attributes, path.span, msg) . .emit(); . } . } . 19,696 ( 0.00%) Ok((ext, res)) . } . 59,304 ( 0.00%) pub fn resolve_macro_path( . &mut self, . path: &ast::Path, . kind: Option, . parent_scope: &ParentScope<'a>, . trace: bool, . force: bool, . ) -> Result<(Option>, Res), Determinacy> { 4,942 ( 0.00%) let path_span = path.span; . let mut path = Segment::from_path(path); . . // Possibly apply the macro helper hack 19,729 ( 0.00%) if kind == Some(MacroKind::Bang) . && path.len() == 1 24,515 ( 0.00%) && path[0].ident.span.ctxt().outer_expn_data().local_inner_macros . { . let root = Ident::new(kw::DollarCrate, path[0].ident.span); . path.insert(0, Segment::from_ident(root)); . } . 78 ( 0.00%) let res = if path.len() > 1 { . let res = match self.resolve_path( . &path, . Some(MacroNS), . parent_scope, . false, . path_span, . CrateLint::No, . ) { -- line 585 ---------------------------------------- -- line 603 ---------------------------------------- . res.ok(), . )); . } . . self.prohibit_imported_non_macro_attrs(None, res.ok(), path_span); . res . } else { . let scope_set = kind.map_or(ScopeSet::All(MacroNS, false), ScopeSet::Macro); 44,478 ( 0.00%) let binding = self.early_resolve_ident_in_lexical_scope( 19,768 ( 0.00%) path[0].ident, . scope_set, . parent_scope, . false, . force, . path_span, . ); 14,826 ( 0.00%) if let Err(Determinacy::Undetermined) = binding { . return Err(Determinacy::Undetermined); . } . 9,884 ( 0.00%) if trace { . let kind = kind.expect("macro kind must be specified if tracing is enabled"); 49,420 ( 0.00%) self.single_segment_macro_resolutions.push(( . path[0].ident, . kind, . *parent_scope, . binding.ok(), . )); . } . . let res = binding.map(|binding| binding.res()); 19,768 ( 0.00%) self.prohibit_imported_non_macro_attrs(binding.ok(), res.ok(), path_span); 24,710 ( 0.00%) res . }; . 19,768 ( 0.00%) res.map(|res| (self.get_macro(res), res)) 54,362 ( 0.00%) } . . // Resolve an identifier in lexical scope. . // This is a variation of `fn resolve_ident_in_lexical_scope` that can be run during . // expansion and import resolution (perhaps they can be merged in the future). . // The function is used for resolving initial segments of macro paths (e.g., `foo` in . // `foo::bar!(); or `foo!();`) and also for import paths on 2018 edition. 272,779 ( 0.01%) crate fn early_resolve_ident_in_lexical_scope( . &mut self, . orig_ident: Ident, . scope_set: ScopeSet<'a>, . parent_scope: &ParentScope<'a>, . record_used: bool, . force: bool, . path_span: Span, . ) -> Result<&'a NameBinding<'a>, Determinacy> { -- line 654 ---------------------------------------- -- line 657 ---------------------------------------- . const MACRO_RULES = 1 << 0; . const MODULE = 1 << 1; . const MISC_SUGGEST_CRATE = 1 << 2; . const MISC_SUGGEST_SELF = 1 << 3; . const MISC_FROM_PRELUDE = 1 << 4; . } . } . 62,140 ( 0.00%) assert!(force || !record_used); // `record_used` implies `force` . . // Make sure `self`, `super` etc produce an error when passed to here. 104,915 ( 0.00%) if orig_ident.is_path_segment_keyword() { . return Err(Determinacy::Determined); . } . 146,692 ( 0.01%) let (ns, macro_kind, is_import) = match scope_set { . ScopeSet::All(ns, is_import) => (ns, None, is_import), . ScopeSet::AbsolutePath(ns) => (ns, None, false), . ScopeSet::Macro(macro_kind) => (MacroNS, Some(macro_kind), false), . ScopeSet::Late(ns, ..) => (ns, None, false), . }; . . // This is *the* result, resolution from the scope closest to the resolved identifier. . // However, sometimes this result is "weak" because it comes from a glob import or -- line 680 ---------------------------------------- -- line 691 ---------------------------------------- . let mut determinacy = Determinacy::Determined; . . // Go through all the scopes and try to resolve the name. . let break_result = self.visit_scopes( . scope_set, . parent_scope, . orig_ident.span.ctxt(), . |this, scope, use_prelude, ctxt| { 180,310 ( 0.01%) let ident = Ident::new(orig_ident.name, orig_ident.span.with_ctxt(ctxt)); . let ok = |res, span, arenas| { . Ok(( . (res, ty::Visibility::Public, span, LocalExpnId::ROOT) . .to_name_binding(arenas), . Flags::empty(), . )) . }; 450,775 ( 0.02%) let result = match scope { . Scope::DeriveHelpers(expn_id) => { . if let Some(attr) = this . .helper_attrs . .get(&expn_id) . .and_then(|attrs| attrs.iter().rfind(|i| ident == **i)) . { . let binding = ( . Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper), -- line 715 ---------------------------------------- -- line 720 ---------------------------------------- . .to_name_binding(this.arenas); . Ok((binding, Flags::empty())) . } else { . Err(Determinacy::Determined) . } . } . Scope::DeriveHelpersCompat => { . let mut result = Err(Determinacy::Determined); 10,436 ( 0.00%) for derive in parent_scope.derives { . let parent_scope = &ParentScope { derives: &[], ..*parent_scope }; . match this.resolve_macro_path( . derive, . Some(MacroKind::Derive), . parent_scope, . true, . force, . ) { -- line 736 ---------------------------------------- -- line 747 ---------------------------------------- . Ok(_) | Err(Determinacy::Determined) => {} . Err(Determinacy::Undetermined) => { . result = Err(Determinacy::Undetermined) . } . } . } . result . } 41,744 ( 0.00%) Scope::MacroRules(macro_rules_scope) => match macro_rules_scope.get() { . MacroRulesScope::Binding(macro_rules_binding) . if ident == macro_rules_binding.ident => . { . Ok((macro_rules_binding.binding, Flags::MACRO_RULES)) . } . MacroRulesScope::Invocation(_) => Err(Determinacy::Undetermined), . _ => Err(Determinacy::Determined), . }, -- line 763 ---------------------------------------- -- line 779 ---------------------------------------- . } . Err((Determinacy::Undetermined, Weak::Yes)) => { . Err(Determinacy::Undetermined) . } . Err((Determinacy::Determined, _)) => Err(Determinacy::Determined), . } . } . Scope::Module(module, derive_fallback_lint_id) => { 168,240 ( 0.01%) let adjusted_parent_scope = &ParentScope { module, ..*parent_scope }; 273,390 ( 0.01%) let binding = this.resolve_ident_in_module_unadjusted_ext( . ModuleOrUniformRoot::Module(module), . ident, . ns, . adjusted_parent_scope, . !matches!(scope_set, ScopeSet::Late(..)), . record_used, . path_span, . ); 90,576 ( 0.00%) match binding { . Ok(binding) => { 10,264 ( 0.00%) if let Some(lint_id) = derive_fallback_lint_id { . this.lint_buffer.buffer_lint_with_diagnostic( . PROC_MACRO_DERIVE_RESOLUTION_FALLBACK, . lint_id, . orig_ident.span, . &format!( . "cannot find {} `{}` in this scope", . ns.descr(), . ident . ), . BuiltinLintDiagnostics::ProcMacroDeriveResolutionFallback( . orig_ident.span, . ), . ); . } 5,132 ( 0.00%) let misc_flags = if ptr::eq(module, this.graph_root) { . Flags::MISC_SUGGEST_CRATE 5,127 ( 0.00%) } else if module.is_normal() { . Flags::MISC_SUGGEST_SELF . } else { . Flags::empty() . }; . Ok((binding, Flags::MODULE | misc_flags)) . } . Err((Determinacy::Undetermined, Weak::No)) => { . return Some(Err(Determinacy::determined(force))); -- line 824 ---------------------------------------- -- line 833 ---------------------------------------- . Some(ident) => ok( . Res::NonMacroAttr(NonMacroAttrKind::Registered), . ident.span, . this.arenas, . ), . None => Err(Determinacy::Determined), . }, . Scope::MacroUsePrelude => { 19,612 ( 0.00%) match this.macro_use_prelude.get(&ident.name).cloned() { . Some(binding) => Ok((binding, Flags::MISC_FROM_PRELUDE)), . None => Err(Determinacy::determined( 627 ( 0.00%) this.graph_root.unexpanded_invocations.borrow().is_empty(), . )), . } . } . Scope::BuiltinAttrs => { 16,482 ( 0.00%) if is_builtin_attr_name(ident.name) { . ok( 1,104 ( 0.00%) Res::NonMacroAttr(NonMacroAttrKind::Builtin(ident.name)), . DUMMY_SP, 552 ( 0.00%) this.arenas, . ) . } else { . Err(Determinacy::Determined) . } . } 608 ( 0.00%) Scope::ExternPrelude => match this.extern_prelude_get(ident, !record_used) { . Some(binding) => Ok((binding, Flags::empty())), . None => Err(Determinacy::determined( 48 ( 0.00%) this.graph_root.unexpanded_invocations.borrow().is_empty(), . )), . }, . Scope::ToolPrelude => match this.registered_tools.get(&ident).cloned() { . Some(ident) => ok(Res::ToolMod, ident.span, this.arenas), . None => Err(Determinacy::Determined), . }, . Scope::StdLibPrelude => { . let mut result = Err(Determinacy::Determined); 32,697 ( 0.00%) if let Some(prelude) = this.prelude { . if let Ok(binding) = this.resolve_ident_in_module_unadjusted( . ModuleOrUniformRoot::Module(prelude), . ident, . ns, . parent_scope, . false, . path_span, . ) { 1,300 ( 0.00%) if use_prelude || this.is_builtin_macro(binding.res()) { . result = Ok((binding, Flags::MISC_FROM_PRELUDE)); . } . } . } . result . } 135 ( 0.00%) Scope::BuiltinTypes => match PrimTy::from_name(ident.name) { 33 ( 0.00%) Some(prim_ty) => ok(Res::PrimTy(prim_ty), DUMMY_SP, this.arenas), . None => Err(Determinacy::Determined), . }, . }; . 33,420 ( 0.00%) match result { . Ok((binding, flags)) 21,546 ( 0.00%) if sub_namespace_match(binding.macro_kind(), macro_kind) => . { 32,402 ( 0.00%) if !record_used || matches!(scope_set, ScopeSet::Late(..)) { . return Some(Ok(binding)); . } . 11,678 ( 0.00%) if let Some((innermost_binding, innermost_flags)) = innermost_result { . // Found another solution, if the first one was "weak", report an error. 11,121 ( 0.00%) let (res, innermost_res) = (binding.res(), innermost_binding.res()); 1,011 ( 0.00%) if res != innermost_res { . let is_builtin = |res| { . matches!(res, Res::NonMacroAttr(NonMacroAttrKind::Builtin(..))) . }; . let derive_helper = . Res::NonMacroAttr(NonMacroAttrKind::DeriveHelper); . let derive_helper_compat = . Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat); . -- line 912 ---------------------------------------- -- line 977 ---------------------------------------- . }, . ); . . if let Some(break_result) = break_result { . return break_result; . } . . // The first found solution was the only one, return it. 21,188 ( 0.00%) if let Some((binding, _)) = innermost_result { . return Ok(binding); . } . 5,092 ( 0.00%) Err(Determinacy::determined(determinacy == Determinacy::Determined || force)) 272,779 ( 0.01%) } . 8 ( 0.00%) crate fn finalize_macro_resolutions(&mut self) { 39,536 ( 0.00%) let check_consistency = |this: &mut Self, . path: &[Segment], . span, . kind: MacroKind, . initial_res: Option, . res: Res| { 34,594 ( 0.00%) if let Some(initial_res) = initial_res { 14,826 ( 0.00%) if res != initial_res { . // Make sure compilation does not succeed if preferred macro resolution . // has changed after the macro had been expanded. In theory all such . // situations should be reported as errors, so this is a bug. . this.session.delay_span_bug(span, "inconsistent resolution for a macro"); . } . } else { . // It's possible that the macro was unresolved (indeterminate) and silently . // expanded into a dummy fragment for recovery during expansion. -- line 1008 ---------------------------------------- -- line 1016 ---------------------------------------- . "cannot determine resolution for the {} `{}`", . kind.descr(), . Segment::names_to_string(path) . ); . let msg_note = "import resolution is stuck, try simplifying macro imports"; . this.session.struct_span_err(span, &msg).note(msg_note).emit(); . } . } 34,594 ( 0.00%) }; . . let macro_resolutions = mem::take(&mut self.multi_segment_macro_resolutions); 4 ( 0.00%) for (mut path, path_span, kind, parent_scope, initial_res) in macro_resolutions { . // FIXME: Path resolution will ICE if segment IDs present. . for seg in &mut path { . seg.id = None; . } . match self.resolve_path( . &path, . Some(MacroNS), . &parent_scope, -- line 1035 ---------------------------------------- -- line 1059 ---------------------------------------- . ResolutionError::FailedToResolve { label, suggestion: None }, . ); . } . PathResult::Module(..) | PathResult::Indeterminate => unreachable!(), . } . } . . let macro_resolutions = mem::take(&mut self.single_segment_macro_resolutions); 64,246 ( 0.00%) for (ident, kind, parent_scope, initial_binding) in macro_resolutions { 79,072 ( 0.00%) match self.early_resolve_ident_in_lexical_scope( 4,942 ( 0.00%) ident, . ScopeSet::Macro(kind), . &parent_scope, . true, . true, 9,884 ( 0.00%) ident.span, . ) { . Ok(binding) => { . let initial_res = initial_binding.map(|initial_binding| { 34,594 ( 0.00%) self.record_use(ident, initial_binding, false); . initial_binding.res() . }); . let res = binding.res(); 9,884 ( 0.00%) let seg = Segment::from_ident(ident); 232,274 ( 0.01%) check_consistency(self, &[seg], ident.span, kind, initial_res, res); 24,710 ( 0.00%) if res == Res::NonMacroAttr(NonMacroAttrKind::DeriveHelperCompat) { . let node_id = self . .invocation_parents . .get(&parent_scope.expansion) . .map_or(ast::CRATE_NODE_ID, |id| self.def_id_to_node_id[id.0]); . self.lint_buffer.buffer_lint_with_diagnostic( . LEGACY_DERIVE_HELPERS, . node_id, . ident.span, -- line 1092 ---------------------------------------- -- line 1101 ---------------------------------------- . let mut err = self.session.struct_span_err(ident.span, &msg); . self.unresolved_macro_suggestions(&mut err, kind, &parent_scope, ident); . err.emit(); . } . } . } . . let builtin_attrs = mem::take(&mut self.builtin_attrs); 4,423 ( 0.00%) for (ident, parent_scope) in builtin_attrs { 5,520 ( 0.00%) let _ = self.early_resolve_ident_in_lexical_scope( . ident, . ScopeSet::Macro(MacroKind::Attr), . &parent_scope, . true, . true, 1,104 ( 0.00%) ident.span, . ); . } 8 ( 0.00%) } . . fn check_stability_and_deprecation( . &mut self, . ext: &SyntaxExtension, . path: &ast::Path, . node_id: NodeId, . ) { 4,924 ( 0.00%) let span = path.span; 14,772 ( 0.00%) if let Some(stability) = &ext.stability { 716 ( 0.00%) if let StabilityLevel::Unstable { reason, issue, is_soft } = stability.level { . let feature = stability.feature; . if !self.active_features.contains(&feature) && !span.allows_unstable(feature) { . let lint_buffer = &mut self.lint_buffer; . let soft_handler = . |lint, span, msg: &_| lint_buffer.buffer_lint(lint, node_id, span, msg); . stability::report_unstable( . self.session, . feature, -- line 1137 ---------------------------------------- -- line 1140 ---------------------------------------- . None, . is_soft, . span, . soft_handler, . ); . } . } . } 9,848 ( 0.00%) if let Some(depr) = &ext.deprecation { . let path = pprust::path_to_string(&path); . let (message, lint) = stability::deprecation_message_and_lint(depr, "macro", &path); . stability::early_report_deprecation( . &mut self.lint_buffer, . &message, . depr.suggestion, . lint, . span, . node_id, . ); . } . } . 34,594 ( 0.00%) fn prohibit_imported_non_macro_attrs( . &self, . binding: Option<&'a NameBinding<'a>>, . res: Option, . span: Span, . ) { 9,884 ( 0.00%) if let Some(Res::NonMacroAttr(kind)) = res { . if kind != NonMacroAttrKind::Tool && binding.map_or(true, |b| b.is_import()) { . let msg = . format!("cannot use {} {} through an import", kind.article(), kind.descr()); . let mut err = self.session.struct_span_err(span, &msg); . if let Some(binding) = binding { . err.span_note(binding.span, &format!("the {} imported here", kind.descr())); . } . err.emit(); . } . } 39,536 ( 0.00%) } . 13,002 ( 0.00%) crate fn check_reserved_macro_name(&mut self, ident: Ident, res: Res) { . // Reserve some names that are not quite covered by the general check . // performed on `Resolver::builtin_attrs`. 4,728 ( 0.00%) if ident.name == sym::cfg || ident.name == sym::cfg_attr { 6 ( 0.00%) let macro_kind = self.get_macro(res).map(|ext| ext.macro_kind()); 2 ( 0.00%) if macro_kind.is_some() && sub_namespace_match(macro_kind, Some(MacroKind::Attr)) { . self.session.span_err( . ident.span, . &format!("name `{}` is reserved in attribute namespace", ident), . ); . } . } 9,456 ( 0.00%) } . . /// Compile the macro into a `SyntaxExtension` and possibly replace . /// its expander to a pre-defined one for built-in macros. 104 ( 0.00%) crate fn compile_macro(&mut self, item: &ast::Item, edition: Edition) -> SyntaxExtension { 39 ( 0.00%) let mut result = compile_declarative_macro( 13 ( 0.00%) &self.session, . self.session.features_untracked(), . item, . edition, . ); . 50 ( 0.00%) if let Some(builtin_name) = result.builtin_name { . // The macro was marked with `#[rustc_builtin_macro]`. 22 ( 0.00%) if let Some(builtin_macro) = self.builtin_macros.get_mut(&builtin_name) { . // The macro is a built-in, replace its expander function . // while still taking everything else from the source code. . // If we already loaded this builtin macro, give a better error message than 'no such builtin macro'. 33 ( 0.00%) match mem::replace(builtin_macro, BuiltinMacroState::AlreadySeen(item.span)) { 132 ( 0.00%) BuiltinMacroState::NotYetSeen(ext) => result.kind = ext, . BuiltinMacroState::AlreadySeen(span) => { . struct_span_err!( . self.session, . item.span, . E0773, . "attempted to define built-in macro more than once" . ) . .span_note(span, "previously defined here") -- line 1220 ---------------------------------------- -- line 1223 ---------------------------------------- . } . } else { . let msg = format!("cannot find a built-in macro with name `{}`", item.ident); . self.session.span_err(item.span, &msg); . } . } . . result 117 ( 0.00%) } . } 1,245,499 ( 0.06%) -------------------------------------------------------------------------------- -- 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. 131,178 ( 0.01%) pub fn unescape_literal(literal_text: &str, mode: Mode, callback: &mut F) . where . F: FnMut(Range, Result), . { . match mode { . Mode::Char | Mode::Byte => { 27,801 ( 0.00%) let mut chars = literal_text.chars(); 9,267 ( 0.00%) let result = unescape_char_or_byte(&mut chars, mode); . // The Chars iterator moved forward. 64,869 ( 0.00%) callback(0..(literal_text.len() - chars.as_str().len()), result); . } . 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) . } . } 74,776 ( 0.00%) } . . /// 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 108 ---------------------------------------- . assert!(mode.is_bytes()); . unescape_literal(literal_text, mode, &mut |range, result| { . callback(range, result.map(byte_from_char)); . }) . } . . /// Takes a contents of a char literal (without quotes), and returns an . /// unescaped char or an error 54,648 ( 0.00%) pub fn unescape_char(literal_text: &str) -> Result { 36,432 ( 0.00%) let mut chars = literal_text.chars(); 18,216 ( 0.00%) unescape_char_or_byte(&mut chars, Mode::Char) . .map_err(|err| (literal_text.len() - chars.as_str().len(), err)) 54,648 ( 0.00%) } . . /// Takes a contents of a byte literal (without quotes), and returns an . /// unescaped byte or an error. . pub fn unescape_byte(literal_text: &str) -> Result { . let mut chars = literal_text.chars(); . unescape_char_or_byte(&mut chars, Mode::Byte) . .map(byte_from_char) . .map_err(|err| (literal_text.len() - chars.as_str().len(), err)) -- line 128 ---------------------------------------- -- line 136 ---------------------------------------- . Byte, . ByteStr, . RawStr, . RawByteStr, . } . . impl Mode { . pub fn in_single_quotes(self) -> bool { 160 ( 0.00%) match self { . Mode::Char | Mode::Byte => true, . Mode::Str | Mode::ByteStr | Mode::RawStr | Mode::RawByteStr => false, . } . } . 160 ( 0.00%) pub fn in_double_quotes(self) -> bool { . !self.in_single_quotes() 80 ( 0.00%) } . . pub fn is_bytes(self) -> bool { . match self { . Mode::Byte | Mode::ByteStr | Mode::RawByteStr => true, . Mode::Char | Mode::Str | Mode::RawStr => false, . } . } . } . 194,210 ( 0.01%) fn scan_escape(first_char: char, chars: &mut Chars<'_>, mode: Mode) -> Result { 96,967 ( 0.00%) 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), . _ => { 1,046 ( 0.00%) if mode.is_bytes() && !first_char.is_ascii() { . // Byte literal can't be a non-ascii character. . return Err(EscapeError::NonAsciiCharInByte); . } . Ok(first_char) . } . }; . } . . // Previous character is '\\', try to unescape it. . 55,125 ( 0.00%) let second_char = chars.next().ok_or(EscapeError::LoneSlash)?; . . let res = match second_char { . '"' => '"', . 'n' => '\n', . 'r' => '\r', . 't' => '\t', . '\\' => '\\', . '\'' => '\'', -- line 191 ---------------------------------------- -- line 209 ---------------------------------------- . let value = value as u8; . . value as char . } . . 'u' => { . // We've parsed '\u', now we have to parse '{..}'. . 73,500 ( 0.00%) if chars.next() != Some('{') { . return Err(EscapeError::NoBraceInUnicodeEscape); . } . . // First character must be a hexadecimal digit. . let mut n_digits = 1; 147,000 ( 0.01%) let mut value: u32 = match chars.next().ok_or(EscapeError::UnclosedUnicodeEscape)? { . '_' => return Err(EscapeError::LeadingUnderscoreUnicodeEscape), . '}' => return Err(EscapeError::EmptyUnicodeEscape), 7,320 ( 0.00%) c => c.to_digit(16).ok_or(EscapeError::InvalidCharInUnicodeEscape)?, . }; . . // First character is valid, now parse the rest of the number . // and closing brace. . loop { 537,074 ( 0.03%) match chars.next() { . None => return Err(EscapeError::UnclosedUnicodeEscape), . Some('_') => continue, . Some('}') => { 36,750 ( 0.00%) if n_digits > 6 { . return Err(EscapeError::OverlongUnicodeEscape); . } . . // Incorrect syntax has higher priority for error reporting . // than unallowed value for a literal. . if mode.is_bytes() { . return Err(EscapeError::UnicodeEscapeInByte); . } . 55,125 ( 0.00%) break std::char::from_u32(value).ok_or_else(|| { . if value > 0x10FFFF { . EscapeError::OutOfRangeUnicodeEscape . } else { . EscapeError::LoneSurrogateUnicodeEscape . } . })?; . } . Some(c) => { . let digit = 19,937 ( 0.00%) c.to_digit(16).ok_or(EscapeError::InvalidCharInUnicodeEscape)?; 106,706 ( 0.01%) n_digits += 1; 106,706 ( 0.01%) if n_digits > 6 { . // Stop updating value since we're sure that it's is incorrect already. . continue; . } . let digit = digit as u32; 373,471 ( 0.02%) value = value * 16 + digit; . } . }; . } . } . _ => return Err(EscapeError::InvalidEscape), . }; . Ok(res) 233,052 ( 0.01%) } . 18,375 ( 0.00%) fn unescape_char_or_byte(chars: &mut Chars<'_>, mode: Mode) -> Result { . let first_char = chars.next().ok_or(EscapeError::ZeroChars)?; 91,875 ( 0.00%) let res = scan_escape(first_char, chars, mode)?; . if chars.next().is_some() { . return Err(EscapeError::MoreThanOneChar); . } . Ok(res) 91,875 ( 0.00%) } . . /// 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), . { 240 ( 0.00%) assert!(mode.in_double_quotes()); . let initial_len = src.len(); 80 ( 0.00%) let mut chars = src.chars(); . while let Some(first_char) = chars.next() { 5,230 ( 0.00%) let start = initial_len - chars.as_str().len() - first_char.len_utf8(); . 6,276 ( 0.00%) 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), . }; 3,138 ( 0.00%) let end = initial_len - chars.as_str().len(); 13,598 ( 0.00%) 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), . { 160 ( 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 ---------------------------------------- 423,276 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_serialize/src/leb128.rs -------------------------------------------------------------------------------- Ir -- line 17 ---------------------------------------- . #[inline] . pub fn $fn_name( . out: &mut [::std::mem::MaybeUninit; max_leb128_len!($int_ty)], . mut value: $int_ty, . ) -> &[u8] { . let mut i = 0; . . loop { 2,145,790 ( 0.10%) if value < 0x80 { . unsafe { 855,271 ( 0.04%) *out.get_unchecked_mut(i).as_mut_ptr() = value as u8; . } . 1,188,497 ( 0.06%) i += 1; . break; . } else { . unsafe { 1,233,752 ( 0.06%) *out.get_unchecked_mut(i).as_mut_ptr() = ((value & 0x7f) | 0x80) as u8; . } . 512,363 ( 0.02%) value >>= 7; . i += 1; . } . } . . unsafe { ::std::mem::MaybeUninit::slice_assume_init_ref(&out.get_unchecked(..i)) } . } . }; . } -- line 45 ---------------------------------------- -- line 53 ---------------------------------------- . macro_rules! impl_read_unsigned_leb128 { . ($fn_name:ident, $int_ty:ty) => { . #[inline] . pub fn $fn_name(slice: &[u8], position: &mut usize) -> $int_ty { . // The first iteration of this loop is unpeeled. This is a . // performance win because this code is hot and integer values less . // than 128 are very common, typically occurring 50-80% or more of . // the time, even for u64 and u128. 659,780 ( 0.03%) let byte = slice[*position]; 329,890 ( 0.02%) *position += 1; 329,890 ( 0.02%) if (byte & 0x80) == 0 { 2 ( 0.00%) return byte as $int_ty; . } 666 ( 0.00%) let mut result = (byte & 0x7F) as $int_ty; . let mut shift = 7; . loop { 171,339 ( 0.01%) let byte = slice[*position]; 110,627 ( 0.01%) *position += 1; 114,226 ( 0.01%) if (byte & 0x80) == 0 { 80,055 ( 0.00%) result |= (byte as $int_ty) << shift; . return result; . } else { . result |= ((byte & 0x7F) as $int_ty) << shift; . } . shift += 7; . } . } . }; -- line 80 ---------------------------------------- 534,479 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_trait_selection/src/traits/query/type_op/mod.rs -------------------------------------------------------------------------------- Ir -- line 72 ---------------------------------------- . /// it might do things like invoke `sub_regions`, which would be . /// bad, because it would create subregion relationships that are . /// not captured in the return value. . fn perform_query( . tcx: TyCtxt<'tcx>, . canonicalized: Canonicalized<'tcx, ParamEnvAnd<'tcx, Self>>, . ) -> Fallible>; . 693,179 ( 0.03%) fn fully_perform_into( . query_key: ParamEnvAnd<'tcx, Self>, . infcx: &InferCtxt<'_, 'tcx>, . output_query_region_constraints: &mut QueryRegionConstraints<'tcx>, . ) -> Fallible<( . Self::QueryResponse, . Option>>, . PredicateObligations<'tcx>, . Certainty, . )> { 144,173 ( 0.01%) if let Some(result) = QueryTypeOp::try_fast_path(infcx.tcx, &query_key) { 344,029 ( 0.02%) return Ok((result, None, vec![], Certainty::Proven)); . } . . // FIXME(#33684) -- We need to use . // `canonicalize_query_keep_static` here because of things . // like the subtype query, which go awry around . // `'static` otherwise. 2,746 ( 0.00%) let mut canonical_var_values = OriginalQueryValues::default(); 67 ( 0.00%) let old_param_env = query_key.param_env; . let canonical_self = 1,696 ( 0.00%) infcx.canonicalize_query_keep_static(query_key, &mut canonical_var_values); 13,914 ( 0.00%) let canonical_result = Self::perform_query(infcx.tcx, canonical_self)?; . 17,238 ( 0.00%) let InferOk { value, obligations } = infcx . .instantiate_nll_query_response_and_region_obligations( . &ObligationCause::dummy(), . old_param_env, . &canonical_var_values, . canonical_result, . output_query_region_constraints, . )?; . 21,131 ( 0.00%) Ok((value, Some(canonical_self), obligations, canonical_result.value.certainty)) 638,893 ( 0.03%) } . } . . impl<'tcx, Q> TypeOp<'tcx> for ParamEnvAnd<'tcx, Q> . where . Q: QueryTypeOp<'tcx>, . { . type Output = Q::QueryResponse; . 583,608 ( 0.03%) fn fully_perform(self, infcx: &InferCtxt<'_, 'tcx>) -> Fallible> { . let mut region_constraints = QueryRegionConstraints::default(); 440,555 ( 0.02%) let (output, canonicalized_query, mut obligations, _) = 75,893 ( 0.00%) Q::fully_perform_into(self, infcx, &mut region_constraints)?; . . // Typically, instantiating NLL query results does not . // create obligations. However, in some cases there . // are unresolved type variables, and unify them *can* . // create obligations. In that case, we have to go . // fulfill them. We do this via a (recursive) query. 72,951 ( 0.00%) while !obligations.is_empty() { . trace!("{:#?}", obligations); . let mut progress = false; . for obligation in std::mem::take(&mut obligations) { . let obligation = infcx.resolve_vars_if_possible(obligation); . match ProvePredicate::fully_perform_into( . obligation.param_env.and(ProvePredicate::new(obligation.predicate)), . infcx, . &mut region_constraints, -- line 141 ---------------------------------------- -- line 153 ---------------------------------------- . if !progress { . return Err(NoSolution); . } . } . . // Promote the final query-region-constraints into a . // (optional) ref-counted vector: . let region_constraints = 291,804 ( 0.01%) if region_constraints.is_empty() { None } else { Some(Rc::new(region_constraints)) }; . 915,691 ( 0.04%) Ok(TypeOpOutput { output, constraints: region_constraints, canonicalized_query }) 729,510 ( 0.03%) } . } 510,303 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/middle/region.rs -------------------------------------------------------------------------------- Ir -- line 77 ---------------------------------------- . // . // FIXME(pnkfelix): this currently derives `PartialOrd` and `Ord` to . // placate the same deriving in `ty::FreeRegion`, but we may want to . // actually attach a more meaningful ordering to scopes than the one . // generated via deriving here. . #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Copy, TyEncodable, TyDecodable)] . #[derive(HashStable)] . pub struct Scope { 25,679 ( 0.00%) pub id: hir::ItemLocalId, 633,642 ( 0.03%) pub data: ScopeData, . } . . impl fmt::Debug for Scope { . fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { . match self.data { . ScopeData::Node => write!(fmt, "Node({:?})", self.id), . ScopeData::CallSite => write!(fmt, "CallSite({:?})", self.id), . ScopeData::Arguments => write!(fmt, "Arguments({:?})", self.id), -- line 94 ---------------------------------------- -- line 99 ---------------------------------------- . "Remainder {{ block: {:?}, first_statement_index: {}}}", . self.id, . fsi.as_u32(), . ), . } . } . } . 2,827,386 ( 0.13%) #[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Debug, Copy, TyEncodable, TyDecodable)] . #[derive(HashStable)] . pub enum ScopeData { . Node, . . /// Scope of the call-site for a function or closure . /// (outlives the arguments as well as the body). . CallSite, . -- line 115 ---------------------------------------- -- line 159 ---------------------------------------- . /// . /// N.B., likely to be replaced as API is refined; e.g., pnkfelix . /// anticipates `fn entry_node_id` and `fn each_exit_node_id`. . pub fn item_local_id(&self) -> hir::ItemLocalId { . self.id . } . . pub fn hir_id(&self, scope_tree: &ScopeTree) -> Option { 14,879 ( 0.00%) scope_tree . .root_body . .map(|hir_id| hir::HirId { owner: hir_id.owner, local_id: self.item_local_id() }) . } . . /// Returns the span of this `Scope`. Note that in general the . /// returned span may not correspond to the span of any `NodeId` in . /// the AST. 104,153 ( 0.00%) pub fn span(&self, tcx: TyCtxt<'_>, scope_tree: &ScopeTree) -> Span { 29,758 ( 0.00%) let hir_id = match self.hir_id(scope_tree) { . Some(hir_id) => hir_id, . None => return DUMMY_SP, . }; 59,516 ( 0.00%) let span = tcx.hir().span(hir_id); 59,516 ( 0.00%) if let ScopeData::Remainder(first_statement_index) = self.data { 72 ( 0.00%) if let Node::Block(ref blk) = tcx.hir().get(hir_id) { . // Want span for scope starting after the . // indexed statement and ending at end of . // `blk`; reuse span of `blk` and shift `lo` . // forward to end of indexed statement. . // . // (This is the special case alluded to in the . // doc-comment for this method) . 96 ( 0.00%) let stmt_span = blk.stmts[first_statement_index.index()].span; . . // To avoid issues with macro-generated spans, the span . // of the statement must be nested in that of the block. 24 ( 0.00%) if span.lo() <= stmt_span.lo() && stmt_span.lo() <= span.hi() { 48 ( 0.00%) return span.with_lo(stmt_span.lo()); . } . } . } . span 133,911 ( 0.01%) } . } . . pub type ScopeDepth = u32; . . /// The region scope tree encodes information about region relationships. . #[derive(Default, Debug)] . pub struct ScopeTree { . /// If not empty, this body is the root of this region hierarchy. -- line 209 ---------------------------------------- -- line 321 ---------------------------------------- . /// The `Span` of the yield. . pub span: Span, . /// The number of expressions and patterns appearing before the `yield` in the body, plus one. . pub expr_and_pat_count: usize, . pub source: hir::YieldSource, . } . . impl ScopeTree { 159,942 ( 0.01%) pub fn record_scope_parent(&mut self, child: Scope, parent: Option<(Scope, ScopeDepth)>) { . debug!("{:?}.parent = {:?}", child, parent); . 53,314 ( 0.00%) if let Some(p) = parent { . let prev = self.parent_map.insert(child, p); 26,548 ( 0.00%) assert!(prev.is_none()); . } . . // Record the destruction scopes for later so we can query them. 53,314 ( 0.00%) if let ScopeData::Destruction = child.data { . self.destruction_scopes.insert(child.item_local_id(), child); . } 104,064 ( 0.00%) } . 48,968 ( 0.00%) pub fn opt_destruction_scope(&self, n: hir::ItemLocalId) -> Option { . self.destruction_scopes.get(&n).cloned() 48,968 ( 0.00%) } . . pub fn record_var_scope(&mut self, var: hir::ItemLocalId, lifetime: Scope) { . debug!("record_var_scope(sub={:?}, sup={:?})", var, lifetime); 164 ( 0.00%) assert!(var != lifetime.item_local_id()); . self.var_map.insert(var, lifetime); . } . . pub fn record_rvalue_scope(&mut self, var: hir::ItemLocalId, lifetime: Option) { . debug!("record_rvalue_scope(sub={:?}, sup={:?})", var, lifetime); 12 ( 0.00%) if let Some(lifetime) = lifetime { . assert!(var != lifetime.item_local_id()); . } . self.rvalue_scopes.insert(var, lifetime); . } . . /// Returns the narrowest scope that encloses `id`, if any. . pub fn opt_encl_scope(&self, id: Scope) -> Option { . self.parent_map.get(&id).cloned().map(|(p, _)| p) . } . . /// Returns the lifetime of the local variable `var_id` 684 ( 0.00%) pub fn var_scope(&self, var_id: hir::ItemLocalId) -> Scope { . self.var_map . .get(&var_id) . .cloned() . .unwrap_or_else(|| bug!("no enclosing scope for id {:?}", var_id)) 684 ( 0.00%) } . . /// Returns the scope when the temp created by `expr_id` will be cleaned up. 341,726 ( 0.02%) pub fn temporary_scope(&self, expr_id: hir::ItemLocalId) -> Option { . // Check for a designated rvalue scope. 18 ( 0.00%) if let Some(&s) = self.rvalue_scopes.get(&expr_id) { . debug!("temporary_scope({:?}) = {:?} [custom]", expr_id, s); . return s; . } . . // Otherwise, locate the innermost terminating scope . // if there's one. Static items, for instance, won't . // have an enclosing scope, hence no scope will be . // returned. 48,812 ( 0.00%) let mut id = Scope { id: expr_id, data: ScopeData::Node }; . 1,657,998 ( 0.08%) while let Some(&(p, _)) = self.parent_map.get(&id) { 535,098 ( 0.03%) match p.data { . ScopeData::Destruction => { . debug!("temporary_scope({:?}) = {:?} [enclosing]", expr_id, id); . return Some(id); . } 195,018 ( 0.01%) _ => id = p, . } . } . . debug!("temporary_scope({:?}) = None", expr_id); . None 390,544 ( 0.02%) } . . /// Returns `true` if `subscope` is equal to or is lexically nested inside `superscope`, and . /// `false` otherwise. . /// . /// Used by clippy. . pub fn is_subscope_of(&self, subscope: Scope, superscope: Scope) -> bool { . let mut s = subscope; . debug!("is_subscope_of({:?}, {:?})", subscope, superscope); -- line 408 ---------------------------------------- 1,052,765 ( 0.05%) -------------------------------------------------------------------------------- -- 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) { 171 ( 0.00%) let mut tt_reader = TokenTreesReader { . string_reader: self, 9 ( 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(), . }; 9 ( 0.00%) let res = tt_reader.parse_all_token_trees(); 54 ( 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`. 72 ( 0.00%) fn parse_all_token_trees(&mut self) -> PResult<'a, TokenStream> { . let mut buf = TokenStreamBuilder::default(); . . self.bump(); 544 ( 0.00%) while self.token != token::Eof { 2,104 ( 0.00%) buf.push(self.parse_token_tree()?); . } . . Ok(buf.into_token_stream()) 81 ( 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 { 164,828 ( 0.01%) if let token::CloseDelim(..) = self.token.kind { . return buf.into_token_stream(); . } . 363,895 ( 0.02%) match self.parse_token_tree() { 655,011 ( 0.03%) Ok(tree) => buf.push(tree), . Err(mut e) => { . e.emit(); . return buf.into_token_stream(); . } . } . } . } . 657,378 ( 0.03%) fn parse_token_tree(&mut self) -> PResult<'a, TreeAndSpacing> { 146,084 ( 0.01%) let sm = self.string_reader.sess.source_map(); . 618,838 ( 0.03%) 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) . } 9,635 ( 0.00%) token::OpenDelim(delim) => { . // The span for beginning of the delimited section 9,635 ( 0.00%) let pre_span = self.token.span; . . // Parse the open delimiter. 67,445 ( 0.00%) 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. 9,635 ( 0.00%) let tts = self.parse_token_trees_until_close_delim(); . . // Expand to cover the entire delimited token tree 48,175 ( 0.00%) let delim_span = DelimSpan::from_pair(pre_span, self.token.span); . 19,270 ( 0.00%) match self.token.kind { . // Correct delimiter. 19,270 ( 0.00%) token::CloseDelim(d) if d == delim => { . let (open_brace, open_brace_span) = self.open_braces.pop().unwrap(); 19,270 ( 0.00%) let close_brace_span = self.token.span; . 28,905 ( 0.00%) if tts.is_empty() { 99 ( 0.00%) let empty_block_span = open_brace_span.to(close_brace_span); 132 ( 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 38,540 ( 0.00%) if let (DelimToken::Brace, DelimToken::Brace) = (open_brace, delim) { . self.matching_block_spans.push((open_brace_span, close_brace_span)); . } . 9,635 ( 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. . } . _ => {} . } . 67,445 ( 0.00%) 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) . } . _ => { 317,035 ( 0.01%) let tt = TokenTree::Token(self.token.take()); . let mut spacing = self.bump(); 126,814 ( 0.01%) if !self.token.is_op() { . spacing = Alone; . } 380,442 ( 0.02%) Ok((tt, spacing)) . } . } 584,336 ( 0.03%) } . . fn bump(&mut self) -> Spacing { 695,972 ( 0.03%) let (spacing, token) = self.string_reader.next_token(); 365,291 ( 0.02%) self.token = token; . spacing . } . } . 9,635 ( 0.00%) #[derive(Default)] . struct TokenStreamBuilder { . buf: Vec, . } . . impl TokenStreamBuilder { 949,546 ( 0.04%) fn push(&mut self, (tree, joint): TreeAndSpacing) { 485,687 ( 0.02%) if let Some((TokenTree::Token(prev_token), Joint)) = self.buf.last() { 57,344 ( 0.00%) if let TokenTree::Token(token) = &tree { 142,872 ( 0.01%) if let Some(glued) = prev_token.glue(token) { . self.buf.pop(); 170,568 ( 0.01%) self.buf.push((TokenTree::Token(glued), joint)); . return; . } . } . } 294,140 ( 0.01%) self.buf.push((tree, joint)) 584,336 ( 0.03%) } . . fn into_token_stream(self) -> TokenStream { 96,431 ( 0.00%) TokenStream::new(self.buf) . } . } 261,422 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs -------------------------------------------------------------------------------- Ir -- line 36 ---------------------------------------- . use rustc_session::parse::ParseSess; . use rustc_span::source_map::{MultiSpan, Span, DUMMY_SP}; . use rustc_span::symbol::{kw, sym, Ident, Symbol}; . use tracing::debug; . . use std::ops::Range; . use std::{cmp, mem, slice}; . 91,940 ( 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); . } . } . } . }; . } . 772,214 ( 0.04%) #[derive(Clone)] . pub struct Parser<'a> { 31,982 ( 0.00%) pub sess: &'a ParseSess, . /// The current token. 27,416 ( 0.00%) pub token: Token, . /// The spacing for the current token 13,708 ( 0.00%) pub token_spacing: Spacing, . /// The previous token. 41,124 ( 0.00%) pub prev_token: Token, 13,708 ( 0.00%) pub capture_cfg: bool, 27,416 ( 0.00%) restrictions: Restrictions, 27,416 ( 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, 27,416 ( 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. 27,416 ( 0.00%) unmatched_angle_bracket_count: u32, 41,124 ( 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. 13,708 ( 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` 13,708 ( 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, . } . 59,398 ( 0.00%) #[derive(Clone)] . struct CaptureState { 54,832 ( 0.00%) capturing: Capturing, 13,708 ( 0.00%) replace_ranges: Vec, . inner_attr_ranges: FxHashMap, . } . . impl<'a> Drop for Parser<'a> { . fn drop(&mut self) { 70,528 ( 0.00%) emit_unclosed_delims(&mut self.unclosed_delims, &self.sess); . } . } . 414,382 ( 0.02%) #[derive(Clone)] . struct TokenCursor { . frame: TokenCursorFrame, 92,259 ( 0.00%) stack: Vec, . desugar_doc_comments: bool, . // Counts the number of calls to `next` or `next_desugared`, . // depending on whether `desugar_doc_comments` is set. 30,692 ( 0.00%) num_next_calls: usize, . // During parsing, we may sometimes need to 'unglue' a . // glued token into two component tokens . // (e.g. '>>' into '>' and '>), so that the parser . // can consume them one at a time. This process . // bypasses the normal capturing mechanism . // (e.g. `num_next_calls` will not be incremented), . // since the 'unglued' tokens due not exist in . // the original `TokenStream`. -- line 217 ---------------------------------------- -- line 226 ---------------------------------------- . // in `Option>` requires us to unglue . // the trailing `>>` token. The `break_last_token` . // field is used to track this token - it gets . // appended to the captured stream when . // we evaluate a `LazyTokenStream` . break_last_token: bool, . } . 184,460 ( 0.01%) #[derive(Clone)] . struct TokenCursorFrame { 35,753 ( 0.00%) delim: token::DelimToken, . span: DelimSpan, . open_delim: bool, 71,506 ( 0.00%) tree_cursor: tokenstream::Cursor, . close_delim: bool, . } . . impl TokenCursorFrame { . fn new(span: DelimSpan, delim: DelimToken, tts: TokenStream) -> Self { 48,205 ( 0.00%) TokenCursorFrame { . delim, . span, . open_delim: false, 36,388 ( 0.00%) tree_cursor: tts.into_trees(), . close_delim: false, . } . } . } . . impl TokenCursor { 2,244,276 ( 0.11%) fn next(&mut self) -> (Token, Spacing) { . loop { 1,049,295 ( 0.05%) let (tree, spacing) = if !self.frame.open_delim { 16,647 ( 0.00%) self.frame.open_delim = true; 83,235 ( 0.00%) TokenTree::open_tt(self.frame.span, self.frame.delim).into() 2,137,838 ( 0.10%) } else if let Some(tree) = self.frame.tree_cursor.next_with_spacing() { . tree 85,820 ( 0.00%) } else if !self.frame.close_delim { 16,620 ( 0.00%) self.frame.close_delim = true; 83,100 ( 0.00%) TokenTree::close_tt(self.frame.span, self.frame.delim).into() 33,240 ( 0.00%) } else if let Some(frame) = self.stack.pop() { 216,060 ( 0.01%) self.frame = frame; . continue; . } else { 174,060 ( 0.01%) (TokenTree::Token(Token::new(token::Eof, DUMMY_SP)), Spacing::Alone) . }; . 406,422 ( 0.02%) match tree { . TokenTree::Token(token) => { 1,496,184 ( 0.07%) return (token, spacing); . } . TokenTree::Delimited(sp, delim, tts) => { . let frame = TokenCursorFrame::new(sp, delim, tts); . self.stack.push(mem::replace(&mut self.frame, frame)); . } . } . } 1,496,184 ( 0.07%) } . 299,100 ( 0.01%) fn next_desugared(&mut self) -> (Token, Spacing) { 90,648 ( 0.00%) let (data, attr_style, sp) = match self.next() { 1,377 ( 0.00%) (Token { kind: token::DocComment(_, attr_style, data), span }, _) => { . (data, attr_style, span) . } 147,255 ( 0.01%) 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; 73,916 ( 0.00%) for ch in data.as_str().chars() { . count = match ch { . '"' => 1, 84 ( 0.00%) '#' if count > 0 => count + 1, . _ => 0, . }; . num_of_hashes = cmp::max(num_of_hashes, count); . } . 1,836 ( 0.00%) let delim_span = DelimSpan::from_single(sp); 2,295 ( 0.00%) let body = TokenTree::Delimited( . delim_span, . token::Bracket, 5,508 ( 0.00%) [ 3,213 ( 0.00%) TokenTree::token(token::Ident(sym::doc, false), sp), 1,836 ( 0.00%) TokenTree::token(token::Eq, sp), 3,672 ( 0.00%) TokenTree::token(TokenKind::lit(token::StrRaw(num_of_hashes), data, None), sp), . ] . .iter() . .cloned() . .collect::(), 459 ( 0.00%) ); . . self.stack.push(mem::replace( . &mut self.frame, . TokenCursorFrame::new( . delim_span, . token::NoDelim, 459 ( 0.00%) if attr_style == AttrStyle::Inner { . [TokenTree::token(token::Pound, sp), TokenTree::token(token::Not, sp), body] . .iter() . .cloned() . .collect::() . } else { 5,508 ( 0.00%) [TokenTree::token(token::Pound, sp), body] . .iter() . .cloned() . .collect::() . }, . ), . )); . 1,377 ( 0.00%) self.next() 269,190 ( 0.01%) } . } . 1,420 ( 0.00%) #[derive(Debug, Clone, PartialEq)] . enum TokenType { 1,136 ( 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> { 112 ( 0.00%) Some(match token.kind { 224 ( 0.00%) _ if token.is_special_ident() => "reserved identifier", 224 ( 0.00%) _ if token.is_used_keyword() => "keyword", 224 ( 0.00%) _ if token.is_unused_keyword() => "reserved keyword", . token::DocComment(..) => "doc comment", . _ => return None, . }) . } . 392 ( 0.00%) pub(super) fn token_descr(token: &Token) -> String { 112 ( 0.00%) let token_str = pprust::token_to_string(token); . match token_descr_opt(token) { . Some(prefix) => format!("{} `{}`", prefix, token_str), 392 ( 0.00%) _ => format!("`{}`", token_str), . } 280 ( 0.00%) } . . impl<'a> Parser<'a> { 134,974 ( 0.01%) pub fn new( . sess: &'a ParseSess, . tokens: TokenStream, . desugar_doc_comments: bool, . subparser_name: Option<&'static str>, . ) -> Self { 9,641 ( 0.00%) let mut start_frame = TokenCursorFrame::new(DelimSpan::dummy(), token::NoDelim, tokens); 19,282 ( 0.00%) start_frame.open_delim = true; . start_frame.close_delim = true; . 298,871 ( 0.01%) let mut parser = Parser { . sess, 9,641 ( 0.00%) token: Token::dummy(), . token_spacing: Spacing::Alone, 9,641 ( 0.00%) prev_token: Token::dummy(), . capture_cfg: false, . restrictions: Restrictions::empty(), . expected_tokens: Vec::new(), . token_cursor: TokenCursor { 57,846 ( 0.00%) frame: start_frame, . stack: Vec::new(), . num_next_calls: 0, . desugar_doc_comments, . break_last_token: false, . }, . desugar_doc_comments, . unmatched_angle_bracket_count: 0, . max_angle_bracket_count: 0, -- line 445 ---------------------------------------- -- line 451 ---------------------------------------- . capturing: Capturing::No, . replace_ranges: Vec::new(), . inner_attr_ranges: Default::default(), . }, . current_closure: None, . }; . . // Make parser point to the first token. 19,282 ( 0.00%) parser.bump(); . . parser 86,769 ( 0.00%) } . . fn next_tok(&mut self, fallback_span: Span) -> (Token, Spacing) { . loop { 1,033,392 ( 0.05%) let (mut next, spacing) = if self.desugar_doc_comments { 119,640 ( 0.01%) self.token_cursor.next_desugared() . } else { 426,966 ( 0.02%) self.token_cursor.next() . }; 688,928 ( 0.03%) 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 172,232 ( 0.01%) self.token_cursor.break_last_token = false; 688,928 ( 0.03%) if next.span.is_dummy() { . // Tweak the location for better diagnostics, but keep syntactic context intact. 38,584 ( 0.00%) next.span = fallback_span.with_ctxt(next.span.ctxt()); . } 566,556 ( 0.03%) if matches!( 344,464 ( 0.02%) next.kind, . token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) . ) { . continue; . } 685,256 ( 0.03%) 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`. 222,741 ( 0.01%) pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> { 24,749 ( 0.00%) if self.expected_tokens.is_empty() { 30,222 ( 0.00%) if self.token == *t { 25,185 ( 0.00%) self.bump(); . Ok(false) . } else { . self.unexpected_try_recover(t) . } . } else { 236,544 ( 0.01%) self.expect_one_of(slice::from_ref(t), &[]) . } 371,235 ( 0.02%) } . . /// 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. 350,820 ( 0.02%) pub fn expect_one_of( . &mut self, . edible: &[TokenKind], . inedible: &[TokenKind], . ) -> PResult<'a, bool /* recovered */> { 58,470 ( 0.00%) if edible.contains(&self.token.kind) { 87,630 ( 0.00%) self.bump(); . Ok(false) . } else if inedible.contains(&self.token.kind) { . // leave it in the input . Ok(false) . } else if self.last_unexpected_token_span == Some(self.token.span) { . FatalError.raise(); . } else { . self.expected_one_of_not_found(edible, inedible) . } 438,525 ( 0.02%) } . . // Public for rustfmt usage. . pub fn parse_ident(&mut self) -> PResult<'a, Ident> { 84,180 ( 0.00%) self.parse_ident_common(true) . } . . fn ident_or_err(&mut self) -> PResult<'a, (Ident, /* is_raw */ bool)> { 90,585 ( 0.00%) self.token.ident().ok_or_else(|| match self.prev_token.kind { . TokenKind::DocComment(..) => { . self.span_err(self.prev_token.span, Error::UselessDocComment) . } . _ => self.expected_ident_found(), . }) . } . 210,980 ( 0.01%) fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> { 30,140 ( 0.00%) let (ident, is_raw) = self.ident_or_err()?; 180,840 ( 0.01%) if !is_raw && ident.is_reserved() { . let mut err = self.expected_ident_found(); . if recover { . err.emit(); . } else { . return Err(err); . } . } 120,560 ( 0.01%) self.bump(); . Ok(ident) 301,400 ( 0.01%) } . . /// Checks if the next token is `tok`, and returns `true` if so. . /// . /// This method will automatically add `tok` to `expected_tokens` if `tok` is not . /// encountered. 2,472,435 ( 0.12%) fn check(&mut self, tok: &TokenKind) -> bool { 1,060,446 ( 0.05%) let is_present = self.token == *tok; 707,898 ( 0.03%) if !is_present { 1,467,512 ( 0.07%) self.expected_tokens.push(TokenType::Token(tok.clone())); . } . is_present 2,472,435 ( 0.12%) } . . /// Consumes a token 'tok' if it exists. Returns whether the given token was present. 28 ( 0.00%) pub fn eat(&mut self, tok: &TokenKind) -> bool { 395,816 ( 0.02%) let is_present = self.check(tok); 268,463 ( 0.01%) if is_present { 42,858 ( 0.00%) self.bump() . } . is_present 35 ( 0.00%) } . . /// If the next token is the given keyword, returns `true` without eating it. . /// An expectation is also added for diagnostics purposes. 2,940 ( 0.00%) fn check_keyword(&mut self, kw: Symbol) -> bool { 1,019 ( 0.00%) self.expected_tokens.push(TokenType::Keyword(kw)); 29,129 ( 0.00%) self.token.is_keyword(kw) . } . . /// If the next token is the given keyword, eats it and returns `true`. . /// Otherwise, returns `false`. An expectation is also added for diagnostics purposes. . // Public for rustfmt usage. 10,600 ( 0.00%) pub fn eat_keyword(&mut self, kw: Symbol) -> bool { 8,372 ( 0.00%) if self.check_keyword(kw) { 1,244 ( 0.00%) self.bump(); . true . } else { . false . } 10,600 ( 0.00%) } . . fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool { 424 ( 0.00%) if self.token.is_keyword(kw) { 106 ( 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. 185 ( 0.00%) fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> { . if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) } 148 ( 0.00%) } . . /// Is the given keyword `kw` followed by a non-reserved identifier? 6,928 ( 0.00%) fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool { 3,464 ( 0.00%) self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()) 7,794 ( 0.00%) } . 92,058 ( 0.00%) fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool { 31,100 ( 0.00%) if ok { . true . } else { 1,396 ( 0.00%) self.expected_tokens.push(typ); . false . } 92,058 ( 0.00%) } . . fn check_ident(&mut self) -> bool { 3,573 ( 0.00%) self.check_or_expected(self.token.is_ident(), TokenType::Ident) . } . 58,296 ( 0.00%) fn check_path(&mut self) -> bool { 119,549 ( 0.01%) self.check_or_expected(self.token.is_path_start(), TokenType::Path) 72,870 ( 0.00%) } . . fn check_type(&mut self) -> bool { 72 ( 0.00%) self.check_or_expected(self.token.can_begin_type(), TokenType::Type) . } . . fn check_const_arg(&mut self) -> bool { 72 ( 0.00%) self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const) . } . 3,573 ( 0.00%) fn check_inline_const(&self, dist: usize) -> bool { 1,985 ( 0.00%) self.is_keyword_ahead(dist, &[kw::Const]) . && self.look_ahead(dist + 1, |t| match t.kind { . token::Interpolated(ref nt) => matches!(**nt, token::NtBlock(..)), . token::OpenDelim(DelimToken::Brace) => true, . _ => false, . }) 3,573 ( 0.00%) } . . /// Checks to see if the next token is either `+` or `+=`. . /// Otherwise returns `false`. . fn check_plus(&mut self) -> bool { 316 ( 0.00%) self.check_or_expected( 158 ( 0.00%) self.token.is_like_plus(), 158 ( 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. 177,600 ( 0.01%) fn break_and_eat(&mut self, expected: TokenKind) -> bool { 103,600 ( 0.00%) if self.token.kind == expected { 102 ( 0.00%) self.bump(); . return true; . } 73,745 ( 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 . } . _ => { 44,247 ( 0.00%) self.expected_tokens.push(TokenType::Token(expected)); . false . } . } 192,196 ( 0.01%) } . . /// 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. . fn expect_and(&mut self) -> PResult<'a, ()> { 234 ( 0.00%) if self.break_and_eat(token::BinOp(token::And)) { Ok(()) } else { self.unexpected() } . } . . /// Eats `|` possibly breaking tokens like `||` in process. . /// Signals an error if `|` was not eaten. . fn expect_or(&mut self) -> PResult<'a, ()> { . if self.break_and_eat(token::BinOp(token::Or)) { Ok(()) } else { self.unexpected() } . } . . /// Eats `<` possibly breaking tokens like `<<` in process. 542 ( 0.00%) fn eat_lt(&mut self) -> bool { 44,334 ( 0.00%) let ate = self.break_and_eat(token::Lt); 29,516 ( 0.00%) if ate { . // See doc comment for `unmatched_angle_bracket_count`. 24 ( 0.00%) self.unmatched_angle_bracket_count += 1; 24 ( 0.00%) self.max_angle_bracket_count += 1; . debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count); . } . ate 542 ( 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, ()> { 36 ( 0.00%) if self.break_and_eat(token::Gt) { . // See doc comment for `unmatched_angle_bracket_count`. 18 ( 0.00%) if self.unmatched_angle_bracket_count > 0 { 12 ( 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 { 97,710 ( 0.00%) TokenExpectType::Expect => self.check(k), . TokenExpectType::NoExpect => self.token == **k, . }) . } . . fn parse_seq_to_before_tokens( . &mut self, . kets: &[&TokenKind], . sep: SeqSep, -- line 758 ---------------------------------------- -- line 761 ---------------------------------------- . ) -> PResult<'a, (Vec, bool /* trailing */, bool /* recovered */)> { . let mut first = true; . let mut recovered = false; . let mut trailing = false; . let mut v = vec![]; . let unclosed_delims = !self.unclosed_delims.is_empty(); . . while !self.expect_any_with_type(kets, expect) { 75,655 ( 0.00%) if let token::CloseDelim(..) | token::Eof = self.token.kind { . break; . } 47,970 ( 0.00%) if let Some(ref t) = sep.sep { 43,332 ( 0.00%) if first { . first = false; . } else { 69,122 ( 0.00%) match self.expect(t) { . Ok(false) => { . self.current_closure.take(); . } . Ok(true) => { . self.current_closure.take(); . recovered = true; . break; . } -- line 784 ---------------------------------------- -- line 857 ---------------------------------------- . e.cancel(); . break; . } . } . } . } . } . } 28,300 ( 0.00%) if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) { . trailing = true; . break; . } . 14,155 ( 0.00%) let t = f(self)?; 533 ( 0.00%) v.push(t); . } . 19,900 ( 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)> { 15,501 ( 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. 3,480 ( 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 */)> { 10,299 ( 0.00%) let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?; 9,601 ( 0.00%) if !recovered { . self.eat(ket); . } 12,508 ( 0.00%) Ok((val, trailing)) 2,784 ( 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)> { 1,115 ( 0.00%) self.expect(bra)?; 2,784 ( 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( 412 ( 0.00%) &token::OpenDelim(delim), 479 ( 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. 2,227,082 ( 0.10%) fn bump_with(&mut self, (next_token, next_spacing): (Token, Spacing)) { . // Bumping after EOF is a bad sign, usually an infinite loop. 1,027,884 ( 0.05%) 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. 685,256 ( 0.03%) self.prev_token = mem::replace(&mut self.token, next_token); 171,314 ( 0.01%) self.token_spacing = next_spacing; . . // Diagnostics. 171,314 ( 0.01%) self.expected_tokens.clear(); . } . . /// Advance the parser by one token. 1,370,512 ( 0.06%) pub fn bump(&mut self) { 685,256 ( 0.03%) let next_token = self.next_tok(self.token.span); 1,027,884 ( 0.05%) self.bump_with(next_token); 1,370,512 ( 0.06%) } . . /// 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 { 884 ( 0.00%) if dist == 0 { 430 ( 0.00%) return looker(&self.token); . } . 58,915 ( 0.00%) let frame = &self.token_cursor.frame; 68,274 ( 0.00%) if frame.delim != DelimToken::NoDelim { . let all_normal = (0..dist).all(|i| { 152,555 ( 0.01%) let token = frame.tree_cursor.look_ahead(i); 214,451 ( 0.01%) !matches!(token, Some(TokenTree::Delimited(_, DelimToken::NoDelim, _))) . }); . if all_normal { 269,514 ( 0.01%) return match frame.tree_cursor.look_ahead(dist - 1) { 106,158 ( 0.00%) Some(tree) => match tree { 52,918 ( 0.00%) TokenTree::Token(token) => looker(token), . TokenTree::Delimited(dspan, delim, _) => { 1,927 ( 0.00%) looker(&Token::new(token::OpenDelim(*delim), dspan.open)) . } . }, 6,110 ( 0.00%) None => looker(&Token::new(token::CloseDelim(frame.delim), frame.span.close)), . }; . } . } . . let mut cursor = self.token_cursor.clone(); . let mut i = 0; 14,344 ( 0.00%) let mut token = Token::dummy(); . while i < dist { 100,324 ( 0.00%) token = cursor.next().0; 43,050 ( 0.00%) if matches!( 28,664 ( 0.00%) token.kind, . token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) . ) { . continue; . } . i += 1; . } 4,685 ( 0.00%) return looker(&token); . } . . /// Returns whether any of the given keywords are `dist` tokens ahead of the current one. 3,789 ( 0.00%) fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool { 878 ( 0.00%) self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw))) 3,789 ( 0.00%) } . . /// Parses asyncness: `async` or nothing. . fn parse_asyncness(&mut self) -> Async { . if self.eat_keyword(kw::Async) { . let span = self.prev_token.uninterpolated_span(); . Async::Yes { span, closure_id: DUMMY_NODE_ID, return_impl_trait_id: DUMMY_NODE_ID } . } else { . Async::No . } . } . . /// Parses unsafety: `unsafe` or nothing. 188 ( 0.00%) fn parse_unsafety(&mut self) -> Unsafe { . if self.eat_keyword(kw::Unsafe) { . Unsafe::Yes(self.prev_token.uninterpolated_span()) . } else { . Unsafe::No . } 752 ( 0.00%) } . . /// Parses constness: `const` or nothing. 1,544 ( 0.00%) fn parse_constness(&mut self) -> Const { . // Avoid const blocks to be parsed as const items 477 ( 0.00%) if self.look_ahead(1, |t| t != &token::OpenDelim(DelimToken::Brace)) . && self.eat_keyword(kw::Const) . { 50 ( 0.00%) Const::Yes(self.prev_token.uninterpolated_span()) . } else { . Const::No . } 2,702 ( 0.00%) } . . /// Parses inline const expressions. . fn parse_const_block(&mut self, span: Span, pat: bool) -> PResult<'a, P> { . if pat { . self.sess.gated_spans.gate(sym::inline_const_pat, span); . } else { . self.sess.gated_spans.gate(sym::inline_const, span); . } -- line 1104 ---------------------------------------- -- line 1110 ---------------------------------------- . }; . let blk_span = anon_const.value.span; . Ok(self.mk_expr(span.to(blk_span), ExprKind::ConstBlock(anon_const), AttrVec::new())) . } . . /// Parses mutability (`mut` or nothing). . fn parse_mutability(&mut self) -> Mutability { . if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not } 78 ( 0.00%) } . . /// Possibly parses mutability (`const` or `mut`). . fn parse_const_or_mut(&mut self) -> Option { . if self.eat_keyword(kw::Mut) { . Some(Mutability::Mut) . } else if self.eat_keyword(kw::Const) { . Some(Mutability::Not) . } else { . None . } . } . . fn parse_field_name(&mut self) -> PResult<'a, Ident> { 18,222 ( 0.00%) if let token::Literal(token::Lit { kind: token::Integer, symbol, suffix }) = self.token.kind . { . self.expect_no_suffix(self.token.span, "a tuple index", suffix); . self.bump(); . Ok(Ident::new(symbol, self.prev_token.span)) . } else { 27,333 ( 0.00%) self.parse_ident_common(true) . } . } . . fn parse_mac_args(&mut self) -> PResult<'a, P> { 14,715 ( 0.00%) self.parse_mac_args_common(true).map(P) . } . . fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> { 1,503 ( 0.00%) self.parse_mac_args_common(false) . } . 49,158 ( 0.00%) fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> { 43,696 ( 0.00%) Ok( 29,282 ( 0.00%) if self.check(&token::OpenDelim(DelimToken::Paren)) 1,479 ( 0.00%) || self.check(&token::OpenDelim(DelimToken::Bracket)) 1,479 ( 0.00%) || self.check(&token::OpenDelim(DelimToken::Brace)) . { 19,924 ( 0.00%) match self.parse_token_tree() { 24,905 ( 0.00%) TokenTree::Delimited(dspan, delim, tokens) => . // We've confirmed above that there is a delimiter so unwrapping is OK. . { 9,962 ( 0.00%) MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens) . } . _ => unreachable!(), . } 962 ( 0.00%) } else if !delimited_only { . if self.eat(&token::Eq) { 457 ( 0.00%) let eq_span = self.prev_token.span; . . // Collect tokens because they are used during lowering to HIR. 457 ( 0.00%) let expr = self.parse_expr_force_collect()?; 457 ( 0.00%) let span = expr.span; . 2,285 ( 0.00%) let token_kind = token::Interpolated(Lrc::new(token::NtExpr(expr))); 4,113 ( 0.00%) MacArgs::Eq(eq_span, Token::new(token_kind, span)) . } else { . MacArgs::Empty . } . } else { . return self.unexpected(); . }, . ) 38,234 ( 0.00%) } . . fn parse_or_use_outer_attributes( . &mut self, . already_parsed_attrs: Option, . ) -> PResult<'a, AttrWrapper> { 87,204 ( 0.00%) if let Some(attrs) = already_parsed_attrs { . Ok(attrs) . } else { 58,052 ( 0.00%) self.parse_outer_attributes() . } . } . . /// Parses a single token tree from the input. 149,464 ( 0.01%) pub(crate) fn parse_token_tree(&mut self) -> TokenTree { 110,697 ( 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. 101,676 ( 0.00%) 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. 48,854 ( 0.00%) 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; 10,042 ( 0.00%) let stream = frame.tree_cursor.stream.clone(); 10,042 ( 0.00%) let span = frame.span; 5,021 ( 0.00%) let delim = frame.delim; . // Consume close delimiter 10,042 ( 0.00%) self.bump(); 25,105 ( 0.00%) TokenTree::Delimited(span, delim, stream) . } . token::CloseDelim(_) | token::Eof => unreachable!(), . _ => { 27,324 ( 0.00%) self.bump(); 68,310 ( 0.00%) TokenTree::Token(self.prev_token.clone()) . } . } 130,781 ( 0.01%) } . . /// 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 { 29,062 ( 0.00%) let old = self.restrictions; 29,098 ( 0.00%) self.restrictions = res; . let res = f(self); 29,125 ( 0.00%) self.restrictions = old; . res . } . 4,336 ( 0.00%) fn is_crate_vis(&self) -> bool { 2,710 ( 0.00%) self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep) 4,878 ( 0.00%) } . . /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`, . /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`. . /// If the following element can't be a tuple (i.e., it's a function definition), then . /// it's not a tuple struct field), and the contents within the parentheses aren't valid, . /// so emit a proper diagnostic. . // Public for rustfmt usage. 3,590 ( 0.00%) pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> { 910 ( 0.00%) maybe_whole!(self, NtVis, |x| x); . 359 ( 0.00%) self.expected_tokens.push(TokenType::Keyword(kw::Crate)); 1,436 ( 0.00%) if self.is_crate_vis() { . self.bump(); // `crate` . self.sess.gated_spans.gate(sym::crate_visibility_modifier, self.prev_token.span); . return Ok(Visibility { . span: self.prev_token.span, . kind: VisibilityKind::Crate(CrateSugar::JustCrate), . tokens: None, . }); . } . . if !self.eat_keyword(kw::Pub) { . // We need a span for our `Spanned`, but there's inherently no . // keyword to grab a span from for inherited visibility; an empty span at the . // beginning of the current token would seem to be the "Schelling span". 223 ( 0.00%) return Ok(Visibility { 669 ( 0.00%) span: self.token.span.shrink_to_lo(), . kind: VisibilityKind::Inherited, . tokens: None, . }); . } 136 ( 0.00%) let lo = self.prev_token.span; . 680 ( 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. . } . } . 408 ( 0.00%) Ok(Visibility { span: lo, kind: VisibilityKind::Public, tokens: None }) 3,231 ( 0.00%) } . . /// Recovery for e.g. `pub(something) fn ...` or `struct X { pub(something) y: Z }` . fn recover_incorrect_vis_restriction(&mut self) -> PResult<'a, ()> { . self.bump(); // `(` . let path = self.parse_path(PathStyle::Mod)?; . self.expect(&token::CloseDelim(token::Paren))?; // `)` . . let msg = "incorrect visibility restriction"; -- line 1355 ---------------------------------------- -- line 1370 ---------------------------------------- . ) . .emit(); . . Ok(()) . } . . /// Parses `extern string_literal?`. . fn parse_extern(&mut self) -> Extern { 57 ( 0.00%) if self.eat_keyword(kw::Extern) { Extern::from_abi(self.parse_abi()) } else { Extern::None } . } . . /// Parses a string literal as an ABI spec. . fn parse_abi(&mut self) -> Option { . match self.parse_str_lit() { . Ok(str_lit) => Some(str_lit), . Err(Some(lit)) => match lit.kind { . ast::LitKind::Err(_) => None, -- line 1386 ---------------------------------------- -- line 1395 ---------------------------------------- . .emit(); . None . } . }, . Err(None) => None, . } . } . 7,500 ( 0.00%) pub fn collect_tokens_no_attrs( . &mut self, . f: impl FnOnce(&mut Self) -> PResult<'a, R>, . ) -> PResult<'a, R> { . // The only reason to call `collect_tokens_no_attrs` is if you want tokens, so use . // `ForceCollect::Yes` . self.collect_tokens_trailing_token( . AttrWrapper::empty(), . ForceCollect::Yes, 750 ( 0.00%) |this, _attrs| Ok((f(this)?, TrailingToken::None)), . ) 7,500 ( 0.00%) } . . /// `::{` or `::*` 203,536 ( 0.01%) fn is_import_coupler(&mut self) -> bool { 101,768 ( 0.00%) self.check(&token::ModSep) . && self.look_ahead(1, |t| { 118,245 ( 0.01%) *t == token::OpenDelim(token::Brace) || *t == token::BinOp(token::Star) . }) 183,600 ( 0.01%) } . . pub fn clear_expected_tokens(&mut self) { . self.expected_tokens.clear(); . } . } . . crate fn make_unclosed_delims_error( . unmatched: UnmatchedBrace, -- line 1430 ---------------------------------------- -- line 1450 ---------------------------------------- . err.span_label(sp, "closing delimiter possibly meant for this"); . } . if let Some(sp) = unmatched.unclosed_span { . err.span_label(sp, "unclosed delimiter"); . } . Some(err) . } . 186,792 ( 0.01%) pub fn emit_unclosed_delims(unclosed_delims: &mut Vec, sess: &ParseSess) { 93,396 ( 0.00%) *sess.reached_eof.borrow_mut() |= . unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none()); 93,396 ( 0.00%) for unmatched in unclosed_delims.drain(..) { . if let Some(mut e) = make_unclosed_delims_error(unmatched, sess) { . e.emit(); . } . } 186,792 ( 0.01%) } . . /// A helper struct used when building an `AttrAnnotatedTokenStream` from . /// a `LazyTokenStream`. Both delimiter and non-delimited tokens . /// are stored as `FlatToken::Token`. A vector of `FlatToken`s . /// is then 'parsed' to build up an `AttrAnnotatedTokenStream` with nested . /// `AttrAnnotatedTokenTree::Delimited` tokens . #[derive(Debug, Clone)] . pub enum FlatToken { -- line 1474 ---------------------------------------- 1,139,865 ( 0.05%) -------------------------------------------------------------------------------- -- 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. 2,278,514 ( 0.11%) #[derive(Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)] . #[rustc_diagnostic_item = "Option"] . #[stable(feature = "rust1", since = "1.0.0")] . pub enum Option { . /// No value. . #[lang = "None"] . #[stable(feature = "rust1", since = "1.0.0")] . None, . /// Some value of type `T`. . #[lang = "Some"] . #[stable(feature = "rust1", since = "1.0.0")] 54 ( 0.00%) Some(#[stable(feature = "rust1", since = "1.0.0")] T), . } . . ///////////////////////////////////////////////////////////////////////////// . // Type implementation . ///////////////////////////////////////////////////////////////////////////// . . impl Option { . ///////////////////////////////////////////////////////////////////////// -- line 531 ---------------------------------------- -- line 543 ---------------------------------------- . /// let x: Option = None; . /// assert_eq!(x.is_some(), false); . /// ``` . #[must_use = "if you intended to assert that this has a value, consider `.unwrap()` instead"] . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_option", since = "1.48.0")] . pub const fn is_some(&self) -> bool { 2,466,000 ( 0.12%) 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> { 3,951,603 ( 0.19%) 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> { 809,113 ( 0.04%) 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 { 957,132 ( 0.05%) match self { 71,470 ( 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 { 3,103,483 ( 0.15%) match self { 2,995,973 ( 0.14%) Some(val) => val, . None => panic("called `Option::unwrap()` on a `None` value"), . } . } . . /// Returns the contained [`Some`] value or a provided default. . /// . /// Arguments passed to `unwrap_or` are eagerly evaluated; if you are passing . /// the result of a function call, it is recommended to use [`unwrap_or_else`], -- line 759 ---------------------------------------- -- line 769 ---------------------------------------- . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn unwrap_or(self, default: T) -> T . where . T: ~const Drop, . { 1,319,490 ( 0.06%) match self { . Some(x) => x, 59,088 ( 0.00%) None => default, . } 209 ( 0.00%) } . . /// Returns the contained [`Some`] value or computes it from a closure. . /// . /// # Examples . /// . /// ``` . /// let k = 10; . /// assert_eq!(Some(4).unwrap_or_else(|| 2 * k), 4); . /// assert_eq!(None.unwrap_or_else(|| 2 * k), 20); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] 6 ( 0.00%) pub const fn unwrap_or_else(self, f: F) -> T . where . F: ~const FnOnce() -> T, . F: ~const Drop, . { 1,652,094 ( 0.08%) match self { 123,917 ( 0.01%) Some(x) => x, 37,440 ( 0.00%) None => f(), . } 15 ( 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, . { 4,095 ( 0.00%) match self { 2,655 ( 0.00%) Some(x) => x, . None => Default::default(), . } . } . . /// Returns the contained [`Some`] value, consuming the `self` value, . /// without checking that the value is not [`None`]. . /// . /// # Safety -- line 848 ---------------------------------------- -- line 892 ---------------------------------------- . /// // `Option::map` takes self *by value*, consuming `maybe_some_string` . /// let maybe_some_len = maybe_some_string.map(|s| s.len()); . /// . /// assert_eq!(maybe_some_len, Some(13)); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] 32,158 ( 0.00%) pub const fn map(self, f: F) -> Option . where . F: ~const FnOnce(T) -> U, . F: ~const Drop, . { 1,457,194 ( 0.07%) match self { 1,601,586 ( 0.08%) Some(x) => Some(f(x)), 32,850 ( 0.00%) None => None, . } 97,997 ( 0.00%) } . . /// Calls the provided closure with a reference to the contained value (if [`Some`]). . /// . /// # Examples . /// . /// ``` . /// #![feature(result_option_inspect)] . /// -- line 917 ---------------------------------------- -- line 960 ---------------------------------------- . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn map_or(self, default: U, f: F) -> U . where . F: ~const FnOnce(T) -> U, . F: ~const Drop, . U: ~const Drop, . { 755,979 ( 0.04%) match self { 24,475 ( 0.00%) Some(t) => f(t), 451 ( 0.00%) None => default, . } . } . . /// Computes a default function result (if none), or . /// applies a different function to the contained value (if any). . /// . /// # Examples . /// -- line 978 ---------------------------------------- -- line 990 ---------------------------------------- . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn map_or_else(self, default: D, f: F) -> U . where . D: ~const FnOnce() -> U, . D: ~const Drop, . F: ~const FnOnce(T) -> U, . F: ~const Drop, . { 1,416 ( 0.00%) match self { 108 ( 0.00%) Some(t) => f(t), . None => default(), . } . } . . /// Transforms the `Option` into a [`Result`], mapping [`Some(v)`] to . /// [`Ok(v)`] and [`None`] to [`Err(err)`]. . /// . /// Arguments passed to `ok_or` are eagerly evaluated; if you are passing the -- line 1007 ---------------------------------------- -- line 1024 ---------------------------------------- . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn ok_or(self, err: E) -> Result . where . E: ~const Drop, . { 301,745 ( 0.01%) match self { 372 ( 0.00%) Some(v) => Ok(v), 108 ( 0.00%) None => Err(err), . } . } . . /// Transforms the `Option` into a [`Result`], mapping [`Some(v)`] to . /// [`Ok(v)`] and [`None`] to [`Err(err())`]. . /// . /// [`Ok(v)`]: Ok . /// [`Err(err())`]: Err -- line 1042 ---------------------------------------- -- line 1049 ---------------------------------------- . /// assert_eq!(x.ok_or_else(|| 0), Ok("foo")); . /// . /// let x: Option<&str> = None; . /// assert_eq!(x.ok_or_else(|| 0), Err(0)); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] 55,332 ( 0.00%) pub const fn ok_or_else(self, err: F) -> Result . where . F: ~const FnOnce() -> E, . F: ~const Drop, . { 140,692 ( 0.01%) match self { 150,119 ( 0.01%) Some(v) => Ok(v), 39,770 ( 0.00%) None => Err(err()), . } 69,165 ( 0.00%) } . . /// Converts from `Option` (or `&Option`) to `Option<&T::Target>`. . /// . /// Leaves the original Option in-place, creating a new one with a reference . /// to the original one, additionally coercing the contents via [`Deref`]. . /// . /// # Examples . /// -- line 1074 ---------------------------------------- -- line 1080 ---------------------------------------- . /// assert_eq!(x.as_deref(), None); . /// ``` . #[stable(feature = "option_deref", since = "1.40.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn as_deref(&self) -> Option<&T::Target> . where . T: ~const Deref, . { 2,082 ( 0.00%) match self.as_ref() { . Some(t) => Some(t.deref()), . None => None, . } . } . . /// Converts from `Option` (or `&mut Option`) to `Option<&mut T::Target>`. . /// . /// Leaves the original `Option` in-place, creating a new one containing a mutable reference to -- line 1096 ---------------------------------------- -- line 1213 ---------------------------------------- . /// assert_eq!(Some(2).and_then(sq).and_then(sq), Some(16)); . /// assert_eq!(Some(2).and_then(sq).and_then(nope), None); . /// assert_eq!(Some(2).and_then(nope).and_then(sq), None); . /// assert_eq!(None.and_then(sq).and_then(sq), None); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] 482 ( 0.00%) pub const fn and_then(self, f: F) -> Option . where . F: ~const FnOnce(T) -> Option, . F: ~const Drop, . { 209,276 ( 0.01%) match self { 9,658 ( 0.00%) Some(x) => f(x), . None => None, . } 4,171 ( 0.00%) } . . /// Returns [`None`] if the option is [`None`], otherwise calls `predicate` . /// with the wrapped value and returns: . /// . /// - [`Some(t)`] if `predicate` returns `true` (where `t` is the wrapped . /// value), and . /// - [`None`] if `predicate` returns `false`. . /// -- line 1238 ---------------------------------------- -- line 1257 ---------------------------------------- . #[stable(feature = "option_filter", since = "1.27.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn filter

(self, predicate: P) -> Self . where . T: ~const Drop, . P: ~const FnOnce(&T) -> bool, . P: ~const Drop, . { 5,038 ( 0.00%) if let Some(x) = self { 461 ( 0.00%) if predicate(&x) { . return Some(x); . } . } . None 558 ( 0.00%) } . . /// Returns the option if it contains a value, otherwise returns `optb`. . /// . /// Arguments passed to `or` are eagerly evaluated; if you are passing the . /// result of a function call, it is recommended to use [`or_else`], which is . /// lazily evaluated. . /// . /// [`or_else`]: Option::or_else -- line 1279 ---------------------------------------- -- line 1299 ---------------------------------------- . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn or(self, optb: Option) -> Option . where . T: ~const Drop, . { 24,015 ( 0.00%) match self { 63,777 ( 0.00%) Some(x) => Some(x), . None => optb, . } . } . . /// Returns the option if it contains a value, otherwise calls `f` and . /// returns the result. . /// . /// # Examples -- line 1316 ---------------------------------------- -- line 1326 ---------------------------------------- . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn or_else(self, f: F) -> Option . where . F: ~const FnOnce() -> Option, . F: ~const Drop, . { 152,684 ( 0.01%) match self { 2,805 ( 0.00%) Some(x) => Some(x), . None => f(), . } . } . . /// Returns [`Some`] if exactly one of `self`, `optb` is [`Some`], otherwise returns [`None`]. . /// . /// # Examples . /// -- line 1343 ---------------------------------------- -- line 1431 ---------------------------------------- . /// ``` . #[inline] . #[stable(feature = "option_entry", since = "1.20.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn get_or_insert(&mut self, value: T) -> &mut T . where . T: ~const Drop, . { 9,531 ( 0.00%) if let None = *self { 22,239 ( 0.00%) *self = Some(value); . } . . // SAFETY: a `None` variant for `self` would have been replaced by a `Some` . // variant in the code above. . unsafe { self.as_mut().unwrap_unchecked() } . } . . /// Inserts the default value into the option if it is [`None`], then -- line 1448 ---------------------------------------- -- line 1499 ---------------------------------------- . #[inline] . #[stable(feature = "option_entry", since = "1.20.0")] . #[rustc_const_unstable(feature = "const_option_ext", issue = "91930")] . pub const fn get_or_insert_with(&mut self, f: F) -> &mut T . where . F: ~const FnOnce() -> T, . F: ~const Drop, . { 240,346 ( 0.01%) if let None = *self { . // the compiler isn't smart enough to know that we are not dropping a `T` . // here and wants us to ensure `T` can be dropped at compile time. 18 ( 0.00%) mem::forget(mem::replace(self, Some(f()))) . } . . // SAFETY: a `None` variant for `self` would have been replaced by a `Some` . // variant in the code above. . unsafe { self.as_mut().unwrap_unchecked() } . } . . ///////////////////////////////////////////////////////////////////////// -- line 1518 ---------------------------------------- -- line 1558 ---------------------------------------- . /// let old = x.replace(3); . /// assert_eq!(x, Some(3)); . /// assert_eq!(old, None); . /// ``` . #[inline] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] . #[stable(feature = "option_replace", since = "1.31.0")] . pub const fn replace(&mut self, value: T) -> Option { 192 ( 0.00%) mem::replace(self, Some(value)) . } . . /// Returns `true` if the option is a [`Some`] value containing the given value. . /// . /// # Examples . /// . /// ``` . /// #![feature(option_result_contains)] -- line 1574 ---------------------------------------- -- line 1712 ---------------------------------------- . #[stable(feature = "copied", since = "1.35.0")] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] . pub const fn copied(self) -> Option . where . T: Copy, . { . // FIXME: this implementation, which sidesteps using `Option::map` since it's not const . // ready yet, should be reverted when possible to avoid code repetition 27,220 ( 0.00%) match self { 331,654 ( 0.02%) Some(&v) => Some(v), 207 ( 0.00%) None => None, . } . } . . /// Maps an `Option<&T>` to an `Option` by cloning the contents of the . /// option. . /// . /// # Examples . /// -- line 1730 ---------------------------------------- -- line 1733 ---------------------------------------- . /// let opt_x = Some(&x); . /// assert_eq!(opt_x, Some(&12)); . /// let cloned = opt_x.cloned(); . /// assert_eq!(cloned, Some(12)); . /// ``` . #[must_use = "`self` will be dropped if the result is not used"] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_cloned", issue = "91582")] 39,928 ( 0.00%) pub const fn cloned(self) -> Option . where . T: ~const Clone, . { 311,025 ( 0.01%) match self { 1,102,542 ( 0.05%) Some(t) => Some(t.clone()), 32,039 ( 0.00%) None => None, . } 43,622 ( 0.00%) } . } . . impl Option<&mut T> { . /// Maps an `Option<&mut T>` to an `Option` by copying the contents of the . /// option. . /// . /// # Examples . /// -- line 1757 ---------------------------------------- -- line 1843 ---------------------------------------- . ///////////////////////////////////////////////////////////////////////////// . // Trait implementations . ///////////////////////////////////////////////////////////////////////////// . . #[stable(feature = "rust1", since = "1.0.0")] . impl Clone for Option { . #[inline] . fn clone(&self) -> Self { 1,901,959 ( 0.09%) match self { 8,762 ( 0.00%) Some(x) => Some(x.clone()), 1,938 ( 0.00%) None => None, . } 585,217 ( 0.03%) } . . #[inline] . fn clone_from(&mut self, source: &Self) { . match (self, source) { . (Some(to), Some(from)) => to.clone_from(from), . (to, from) => *to = from.clone(), . } . } -- line 1863 ---------------------------------------- -- line 2006 ---------------------------------------- . . #[inline] . fn next(&mut self) -> Option { . self.opt.take() . } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 159,289 ( 0.01%) match self.opt { . Some(_) => (1, Some(1)), . None => (0, Some(0)), . } . } . } . . impl DoubleEndedIterator for Item { . #[inline] -- line 2022 ---------------------------------------- -- line 2241 ---------------------------------------- . #[rustc_const_unstable(feature = "const_convert", issue = "88674")] . impl const ops::Try for Option { . type Output = T; . type Residual = Option; . . #[inline] . fn from_output(output: Self::Output) -> Self { . Some(output) 240 ( 0.00%) } . . #[inline] . fn branch(self) -> ControlFlow { 796,471 ( 0.04%) match self { 120,232 ( 0.01%) Some(v) => ControlFlow::Continue(v), . None => ControlFlow::Break(None), . } . } . } . . #[unstable(feature = "try_trait_v2", issue = "84277")] . #[rustc_const_unstable(feature = "const_convert", issue = "88674")] . impl const ops::FromResidual for Option { . #[inline] . fn from_residual(residual: Option) -> Self { . match residual { 53,936 ( 0.00%) None => None, . } . } . } . . #[unstable(feature = "try_trait_v2_residual", issue = "91285")] . impl ops::Residual for Option { . type TryType = Option; . } -- line 2274 ---------------------------------------- -- line 2297 ---------------------------------------- . /// let x: Option>> = Some(Some(Some(6))); . /// assert_eq!(Some(Some(6)), x.flatten()); . /// assert_eq!(Some(6), x.flatten().flatten()); . /// ``` . #[inline] . #[stable(feature = "option_flattening", since = "1.40.0")] . #[rustc_const_unstable(feature = "const_option", issue = "67441")] . pub const fn flatten(self) -> Option { 8 ( 0.00%) match self { 44 ( 0.00%) Some(inner) => inner, . None => None, . } . } . } 3,899,293 ( 0.18%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast_pretty/src/pp/ring.rs -------------------------------------------------------------------------------- Ir -- line 22 ---------------------------------------- . RingBuffer { data: VecDeque::new(), offset: 0 } . } . . pub fn is_empty(&self) -> bool { . self.data.is_empty() . } . . pub fn push(&mut self, value: T) -> usize { 392,678 ( 0.02%) let index = self.offset + self.data.len(); 1,278,554 ( 0.06%) self.data.push_back(value); . index . } . . pub fn clear(&mut self) { 10 ( 0.00%) self.data.clear(); . } . . pub fn index_of_first(&self) -> usize { . self.offset . } . . pub fn first(&self) -> Option<&T> { . self.data.front() . } . . pub fn first_mut(&mut self) -> Option<&mut T> { . self.data.front_mut() . } . 981,695 ( 0.05%) pub fn pop_first(&mut self) -> Option { . let first = self.data.pop_front()?; 785,356 ( 0.04%) self.offset += 1; 1,178,034 ( 0.06%) Some(first) 1,374,373 ( 0.06%) } . . pub fn last(&self) -> Option<&T> { . self.data.back() . } . . pub fn last_mut(&mut self) -> Option<&mut T> { . self.data.back_mut() . } -- line 63 ---------------------------------------- 981,695 ( 0.05%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/vec_deque/mod.rs -------------------------------------------------------------------------------- Ir -- line 126 ---------------------------------------- . self.extend(remainder.iter().cloned()); . } . } . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . unsafe impl<#[may_dangle] T, A: Allocator> Drop for VecDeque { 6,804 ( 0.00%) fn drop(&mut self) { . /// Runs the destructor for all items in the slice when it gets dropped (normally or . /// during unwinding). . struct Dropper<'a, T>(&'a mut [T]); . . impl<'a, T> Drop for Dropper<'a, T> { . fn drop(&mut self) { . unsafe { . ptr::drop_in_place(self.0); -- line 142 ---------------------------------------- -- line 146 ---------------------------------------- . . let (front, back) = self.as_mut_slices(); . unsafe { . let _back_dropper = Dropper(back); . // use drop for [T] . ptr::drop_in_place(front); . } . // RawVec handles deallocation 7,776 ( 0.00%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Default for VecDeque { . /// Creates an empty `VecDeque`. . #[inline] . fn default() -> VecDeque { . VecDeque::new() . } . } . . impl VecDeque { . /// Marginally more convenient . #[inline] . fn ptr(&self) -> *mut T { 394,484 ( 0.02%) self.buf.ptr() . } . . /// Marginally more convenient . #[inline] . fn cap(&self) -> usize { . if mem::size_of::() == 0 { . // For zero sized types, we are always at maximum capacity . MAXIMUM_ZST_CAPACITY . } else { 481,008 ( 0.02%) self.buf.capacity() . } . } . . /// Turn ptr into a slice . #[inline] . unsafe fn buffer_as_slice(&self) -> &[T] { . unsafe { slice::from_raw_parts(self.ptr(), self.cap()) } . } -- line 188 ---------------------------------------- -- line 191 ---------------------------------------- . #[inline] . unsafe fn buffer_as_mut_slice(&mut self) -> &mut [T] { . unsafe { slice::from_raw_parts_mut(self.ptr(), self.cap()) } . } . . /// Moves an element out of the buffer . #[inline] . unsafe fn buffer_read(&mut self, off: usize) -> T { 19,637 ( 0.00%) unsafe { ptr::read(self.ptr().add(off)) } . } . . /// Writes an element into the buffer, moving it. . #[inline] . unsafe fn buffer_write(&mut self, off: usize, value: T) { . unsafe { . ptr::write(self.ptr().add(off), value); . } . } . . /// Returns `true` if the buffer is at full capacity. . #[inline] . fn is_full(&self) -> bool { 923,310 ( 0.04%) self.cap() - self.len() == 1 . } . . /// Returns the index in the underlying buffer for a given logical element . /// index. . #[inline] . fn wrap_index(&self, idx: usize) -> usize { . wrap_index(idx, self.cap()) . } -- line 221 ---------------------------------------- -- line 452 ---------------------------------------- . // [o o . o o o o o ] . // T H . // B [. . . o o o o o o o . . . . . . ] . // H T . // [o o o o o . o o ] . // H T . // C [o o o o o . . . . . . . . . o o ] . 136 ( 0.00%) if self.tail <= self.head { . // A . // Nop 48 ( 0.00%) } else if self.head < old_capacity - self.tail { . // B . unsafe { . self.copy_nonoverlapping(old_capacity, 0, self.head); . } . self.head += old_capacity; . debug_assert!(self.head > self.tail); . } else { . // C 24 ( 0.00%) let new_tail = new_capacity - (old_capacity - self.tail); . unsafe { 8 ( 0.00%) self.copy_nonoverlapping(new_tail, self.tail, old_capacity - self.tail); . } 8 ( 0.00%) self.tail = new_tail; . debug_assert!(self.head < self.tail); . } . debug_assert!(self.head < self.cap()); . debug_assert!(self.tail < self.cap()); . debug_assert!(self.cap().count_ones() == 1); . } . } . -- line 484 ---------------------------------------- -- line 507 ---------------------------------------- . /// use std::collections::VecDeque; . /// . /// let vector: VecDeque = VecDeque::with_capacity(10); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . #[must_use] . pub fn with_capacity(capacity: usize) -> VecDeque { 514 ( 0.00%) Self::with_capacity_in(capacity, Global) . } . } . . impl VecDeque { . /// Creates an empty `VecDeque`. . /// . /// # Examples . /// -- line 523 ---------------------------------------- -- line 524 ---------------------------------------- . /// ``` . /// use std::collections::VecDeque; . /// . /// let vector: VecDeque = VecDeque::new(); . /// ``` . #[inline] . #[unstable(feature = "allocator_api", issue = "32838")] . pub fn new_in(alloc: A) -> VecDeque { 1,018 ( 0.00%) VecDeque::with_capacity_in(INITIAL_CAPACITY, alloc) . } . . /// Creates an empty `VecDeque` with space for at least `capacity` elements. . /// . /// # Examples . /// . /// ``` . /// use std::collections::VecDeque; . /// . /// let vector: VecDeque = VecDeque::with_capacity(10); . /// ``` . #[unstable(feature = "allocator_api", issue = "32838")] 3,064 ( 0.00%) pub fn with_capacity_in(capacity: usize, alloc: A) -> VecDeque { 1,628 ( 0.00%) assert!(capacity < 1_usize << usize::BITS - 1, "capacity overflow"); . // +1 since the ringbuffer always leaves one space empty . let cap = cmp::max(capacity + 1, MINIMUM_CAPACITY + 1).next_power_of_two(); . 6,688 ( 0.00%) VecDeque { tail: 0, head: 0, buf: RawVec::with_capacity_in(cap, alloc) } 4,596 ( 0.00%) } . . /// Provides a reference to the element at the given index. . /// . /// Element at index 0 is the front of the queue. . /// . /// # Examples . /// . /// ``` -- line 559 ---------------------------------------- -- line 562 ---------------------------------------- . /// let mut buf = VecDeque::new(); . /// buf.push_back(3); . /// buf.push_back(4); . /// buf.push_back(5); . /// assert_eq!(buf.get(1), Some(&4)); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn get(&self, index: usize) -> Option<&T> { 1,573,939 ( 0.07%) if index < self.len() { . let idx = self.wrap_add(self.tail, index); . unsafe { Some(&*self.ptr().add(idx)) } . } else { . None . } . } . . /// Provides a mutable reference to the element at the given index. -- line 578 ---------------------------------------- -- line 591 ---------------------------------------- . /// if let Some(elem) = buf.get_mut(1) { . /// *elem = 7; . /// } . /// . /// assert_eq!(buf[1], 7); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn get_mut(&mut self, index: usize) -> Option<&mut T> { 648,506 ( 0.03%) if index < self.len() { . let idx = self.wrap_add(self.tail, index); . unsafe { Some(&mut *self.ptr().add(idx)) } . } else { . None . } . } . . /// Swaps elements at indices `i` and `j`. -- line 607 ---------------------------------------- -- line 694 ---------------------------------------- . /// . /// let mut buf: VecDeque = [1].into(); . /// buf.reserve(10); . /// assert!(buf.capacity() >= 11); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn reserve(&mut self, additional: usize) { . let old_cap = self.cap(); 8 ( 0.00%) let used_cap = self.len() + 1; . let new_cap = used_cap . .checked_add(additional) . .and_then(|needed_cap| needed_cap.checked_next_power_of_two()) . .expect("capacity overflow"); . 16 ( 0.00%) if new_cap > old_cap { 24 ( 0.00%) self.buf.reserve_exact(used_cap, new_cap - used_cap); . unsafe { . self.handle_capacity_increase(old_cap); . } . } . } . . /// Tries to reserve the minimum capacity for exactly `additional` more elements to . /// be inserted in the given `VecDeque`. After calling `try_reserve_exact`, -- line 717 ---------------------------------------- -- line 924 ---------------------------------------- . /// buf.push_back(5); . /// buf.push_back(10); . /// buf.push_back(15); . /// assert_eq!(buf, [5, 10, 15]); . /// buf.truncate(1); . /// assert_eq!(buf, [5]); . /// ``` . #[stable(feature = "deque_extras", since = "1.16.0")] 80 ( 0.00%) pub fn truncate(&mut self, len: usize) { . /// Runs the destructor for all items in the slice when it gets dropped (normally or . /// during unwinding). . struct Dropper<'a, T>(&'a mut [T]); . . impl<'a, T> Drop for Dropper<'a, T> { . fn drop(&mut self) { . unsafe { . ptr::drop_in_place(self.0); -- line 940 ---------------------------------------- -- line 945 ---------------------------------------- . // Safe because: . // . // * Any slice passed to `drop_in_place` is valid; the second case has . // `len <= front.len()` and returning on `len > self.len()` ensures . // `begin <= back.len()` in the first case . // * The head of the VecDeque is moved before calling `drop_in_place`, . // so no value is dropped twice if `drop_in_place` panics . unsafe { 20 ( 0.00%) if len > self.len() { . return; . } . let num_dropped = self.len() - len; . let (front, back) = self.as_mut_slices(); 20 ( 0.00%) if len > front.len() { . let begin = len - front.len(); . let drop_back = back.get_unchecked_mut(begin..) as *mut _; . self.head = self.wrap_sub(self.head, num_dropped); . ptr::drop_in_place(drop_back); . } else { . let drop_back = back as *mut _; . let drop_front = front.get_unchecked_mut(len..) as *mut _; 10 ( 0.00%) self.head = self.wrap_sub(self.head, num_dropped); . . // Make sure the second half is dropped even when a destructor . // in the first one panics. . let _back_dropper = Dropper(&mut *drop_back); . ptr::drop_in_place(drop_front); . } . } 80 ( 0.00%) } . . /// Returns a reference to the underlying allocator. . #[unstable(feature = "allocator_api", issue = "32838")] . #[inline] . pub fn allocator(&self) -> &A { . self.buf.allocator() . } . -- line 982 ---------------------------------------- -- line 1085 ---------------------------------------- . /// vector.as_mut_slices().0[0] = 42; . /// vector.as_mut_slices().1[0] = 24; . /// assert_eq!(vector.as_slices(), (&[42, 10][..], &[24, 1][..])); . /// ``` . #[inline] . #[stable(feature = "deque_extras_15", since = "1.5.0")] . pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) { . unsafe { 2,249 ( 0.00%) let head = self.head; 2,249 ( 0.00%) let tail = self.tail; 1,545 ( 0.00%) let buf = self.buffer_as_mut_slice(); . RingSlices::ring_slices(buf, head, tail) . } . } . . /// Returns the number of elements in the `VecDeque`. . /// . /// # Examples . /// -- line 1103 ---------------------------------------- -- line 1106 ---------------------------------------- . /// . /// let mut v = VecDeque::new(); . /// assert_eq!(v.len(), 0); . /// v.push_back(1); . /// assert_eq!(v.len(), 1); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn len(&self) -> usize { 761,965 ( 0.04%) count(self.tail, self.head, self.cap()) . } . . /// Returns `true` if the `VecDeque` is empty. . /// . /// # Examples . /// . /// ``` . /// use std::collections::VecDeque; -- line 1122 ---------------------------------------- -- line 1123 ---------------------------------------- . /// . /// let mut v = VecDeque::new(); . /// assert!(v.is_empty()); . /// v.push_front(1); . /// assert!(!v.is_empty()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn is_empty(&self) -> bool { 1,375,731 ( 0.06%) self.tail == self.head . } . . fn range_tail_head(&self, range: R) -> (usize, usize) . where . R: RangeBounds, . { . let Range { start, end } = slice::range(range, ..self.len()); . let tail = self.wrap_add(self.tail, start); -- line 1139 ---------------------------------------- -- line 1307 ---------------------------------------- . /// let mut v = VecDeque::new(); . /// v.push_back(1); . /// v.clear(); . /// assert!(v.is_empty()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . pub fn clear(&mut self) { 20 ( 0.00%) self.truncate(0); . } . . /// Returns `true` if the `VecDeque` contains an element equal to the . /// given value. . /// . /// # Examples . /// . /// ``` -- line 1323 ---------------------------------------- -- line 1396 ---------------------------------------- . /// assert_eq!(d.back(), None); . /// . /// d.push_back(1); . /// d.push_back(2); . /// assert_eq!(d.back(), Some(&2)); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn back(&self) -> Option<&T> { 22,834 ( 0.00%) self.get(self.len().wrapping_sub(1)) . } . . /// Provides a mutable reference to the back element, or `None` if the . /// `VecDeque` is empty. . /// . /// # Examples . /// . /// ``` -- line 1412 ---------------------------------------- -- line 1441 ---------------------------------------- . /// d.push_back(2); . /// . /// assert_eq!(d.pop_front(), Some(1)); . /// assert_eq!(d.pop_front(), Some(2)); . /// assert_eq!(d.pop_front(), None); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn pop_front(&mut self) -> Option { 243,115 ( 0.01%) if self.is_empty() { . None . } else { . let tail = self.tail; 438,020 ( 0.02%) self.tail = self.wrap_add(self.tail, 1); 6,549 ( 0.00%) unsafe { Some(self.buffer_read(tail)) } . } . } . . /// Removes the last element from the `VecDeque` and returns it, or `None` if . /// it is empty. . /// . /// # Examples . /// -- line 1462 ---------------------------------------- -- line 1466 ---------------------------------------- . /// let mut buf = VecDeque::new(); . /// assert_eq!(buf.pop_back(), None); . /// buf.push_back(1); . /// buf.push_back(3); . /// assert_eq!(buf.pop_back(), Some(3)); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn pop_back(&mut self) -> Option { 73,162 ( 0.00%) if self.is_empty() { . None . } else { 105,242 ( 0.00%) self.head = self.wrap_sub(self.head, 1); . let head = self.head; . unsafe { Some(self.buffer_read(head)) } . } . } . . /// Prepends an element to the `VecDeque`. . /// . /// # Examples -- line 1485 ---------------------------------------- -- line 1513 ---------------------------------------- . /// use std::collections::VecDeque; . /// . /// let mut buf = VecDeque::new(); . /// buf.push_back(1); . /// buf.push_back(3); . /// assert_eq!(3, *buf.back().unwrap()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 785,356 ( 0.04%) pub fn push_back(&mut self, value: T) { 923,310 ( 0.04%) if self.is_full() { 45 ( 0.00%) self.grow(); . } . 26 ( 0.00%) let head = self.head; 307,796 ( 0.01%) self.head = self.wrap_add(self.head, 1); 111,431 ( 0.01%) unsafe { self.buffer_write(head, value) } 785,356 ( 0.04%) } . . #[inline] . fn is_contiguous(&self) -> bool { . // FIXME: Should we consider `head == 0` to mean . // that `self` is contiguous? . self.tail <= self.head . } . -- line 1537 ---------------------------------------- -- line 2209 ---------------------------------------- . self.truncate(idx); . } . } . . // Double the buffer size. This method is inline(never), so we expect it to only . // be called in cold paths. . // This may panic or abort . #[inline(never)] 156 ( 0.00%) fn grow(&mut self) { . // Extend or possibly remove this assertion when valid use-cases for growing the . // buffer without it being full emerge . debug_assert!(self.is_full()); . let old_cap = self.cap(); 78 ( 0.00%) self.buf.reserve_exact(old_cap, old_cap); 130 ( 0.00%) assert!(self.cap() == old_cap * 2); . unsafe { . self.handle_capacity_increase(old_cap); . } . debug_assert!(!self.is_full()); 156 ( 0.00%) } . . /// Modifies the `VecDeque` in-place so that `len()` is equal to `new_len`, . /// either by removing excess elements from the back or by appending . /// elements generated by calling `generator` to the back. . /// . /// # Examples . /// . /// ``` -- line 2236 ---------------------------------------- -- line 2751 ---------------------------------------- . } . } . . /// Returns the index in the underlying buffer for a given logical element index. . #[inline] . fn wrap_index(index: usize, size: usize) -> usize { . // size is always a power of 2 . debug_assert!(size.is_power_of_two()); 1,637,970 ( 0.08%) index & (size - 1) . } . . /// Calculate the number of elements left to be read in the buffer . #[inline] . fn count(tail: usize, head: usize, size: usize) -> usize { . // size is always a power of 2 2,858,048 ( 0.13%) (head.wrapping_sub(tail)) & (size - 1) . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl PartialEq for VecDeque { . fn eq(&self, other: &Self) -> bool { . if self.len() != other.len() { . return false; . } -- line 2774 ---------------------------------------- -- line 2902 ---------------------------------------- . . fn into_iter(self) -> IterMut<'a, T> { . self.iter_mut() . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Extend for VecDeque { 784 ( 0.00%) fn extend>(&mut self, iter: I) { . // This function should be the moral equivalent of: . // . // for item in iter.into_iter() { . // self.push_back(item); . // } . let mut iter = iter.into_iter(); . while let Some(element) = iter.next() { 448 ( 0.00%) if self.len() == self.capacity() { . let (lower, _) = iter.size_hint(); . self.reserve(lower.saturating_add(1)); . } . . let head = self.head; 104 ( 0.00%) self.head = self.wrap_add(self.head, 1); . unsafe { 104 ( 0.00%) self.buffer_write(head, element); . } . } 896 ( 0.00%) } . . #[inline] . fn extend_one(&mut self, elem: T) { . self.push_back(elem); . } . . #[inline] . fn extend_reserve(&mut self, additional: usize) { -- line 2937 ---------------------------------------- 402,917 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/layout.rs -------------------------------------------------------------------------------- Ir -- line 23 ---------------------------------------- . use std::iter; . use std::num::NonZeroUsize; . use std::ops::Bound; . . use rand::{seq::SliceRandom, SeedableRng}; . use rand_xoshiro::Xoshiro128StarStar; . . pub fn provide(providers: &mut ty::query::Providers) { 6 ( 0.00%) *providers = . ty::query::Providers { layout_of, fn_abi_of_fn_ptr, fn_abi_of_instance, ..*providers }; . } . . pub trait IntegerExt { . fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>, signed: bool) -> Ty<'tcx>; . fn from_attr(cx: &C, ity: attr::IntType) -> Integer; . fn from_int_ty(cx: &C, ity: ty::IntTy) -> Integer; . fn from_uint_ty(cx: &C, uty: ty::UintTy) -> Integer; -- line 39 ---------------------------------------- -- line 44 ---------------------------------------- . min: i128, . max: i128, . ) -> (Integer, bool); . } . . impl IntegerExt for Integer { . #[inline] . fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>, signed: bool) -> Ty<'tcx> { 230,555 ( 0.01%) match (*self, signed) { . (I8, false) => tcx.types.u8, . (I16, false) => tcx.types.u16, . (I32, false) => tcx.types.u32, . (I64, false) => tcx.types.u64, . (I128, false) => tcx.types.u128, . (I8, true) => tcx.types.i8, . (I16, true) => tcx.types.i16, . (I32, true) => tcx.types.i32, . (I64, true) => tcx.types.i64, . (I128, true) => tcx.types.i128, . } . } . . /// Gets the Integer type from an attr::IntType. 36 ( 0.00%) fn from_attr(cx: &C, ity: attr::IntType) -> Integer { . let dl = cx.data_layout(); . 90 ( 0.00%) match ity { . attr::SignedInt(ast::IntTy::I8) | attr::UnsignedInt(ast::UintTy::U8) => I8, . attr::SignedInt(ast::IntTy::I16) | attr::UnsignedInt(ast::UintTy::U16) => I16, . attr::SignedInt(ast::IntTy::I32) | attr::UnsignedInt(ast::UintTy::U32) => I32, . attr::SignedInt(ast::IntTy::I64) | attr::UnsignedInt(ast::UintTy::U64) => I64, . attr::SignedInt(ast::IntTy::I128) | attr::UnsignedInt(ast::UintTy::U128) => I128, . attr::SignedInt(ast::IntTy::Isize) | attr::UnsignedInt(ast::UintTy::Usize) => { 18 ( 0.00%) dl.ptr_sized_integer() . } . } 36 ( 0.00%) } . . fn from_int_ty(cx: &C, ity: ty::IntTy) -> Integer { . match ity { . ty::IntTy::I8 => I8, . ty::IntTy::I16 => I16, . ty::IntTy::I32 => I32, . ty::IntTy::I64 => I64, . ty::IntTy::I128 => I128, 125,076 ( 0.01%) ty::IntTy::Isize => cx.data_layout().ptr_sized_integer(), . } . } . fn from_uint_ty(cx: &C, ity: ty::UintTy) -> Integer { . match ity { . ty::UintTy::U8 => I8, . ty::UintTy::U16 => I16, . ty::UintTy::U32 => I32, . ty::UintTy::U64 => I64, . ty::UintTy::U128 => I128, 1 ( 0.00%) ty::UintTy::Usize => cx.data_layout().ptr_sized_integer(), . } . } . . /// Finds the appropriate Integer type and signedness for the given . /// signed discriminant range and `#[repr]` attribute. . /// N.B.: `u128` values above `i128::MAX` will be treated as signed, but . /// that shouldn't affect anything, other than maybe debuginfo. 27 ( 0.00%) fn repr_discr<'tcx>( . tcx: TyCtxt<'tcx>, . ty: Ty<'tcx>, . repr: &ReprOptions, . min: i128, . max: i128, . ) -> (Integer, bool) { . // Theoretically, negative values could be larger in unsigned representation . // than the unsigned representation of the signed minimum. However, if there . // are any negative values, the only valid unsigned representation is u128 . // which can fit all i128 values, so the result remains unaffected. . let unsigned_fit = Integer::fit_unsigned(cmp::max(min as u128, max as u128)); . let signed_fit = cmp::max(Integer::fit_signed(min), Integer::fit_signed(max)); . 27 ( 0.00%) if let Some(ity) = repr.int { . let discr = Integer::from_attr(&tcx, ity); . let fit = if ity.is_signed() { signed_fit } else { unsigned_fit }; . if discr < fit { . bug!( . "Integer::repr_discr: `#[repr]` hint too small for \ . discriminant range of enum `{}", . ty . ) . } . return (discr, ity.is_signed()); . } . 18 ( 0.00%) let at_least = if repr.c() { . // This is usually I32, however it can be different on some platforms, . // notably hexagon and arm-none/thumb-none . tcx.data_layout().c_enum_min_size . } else { . // repr(Rust) enums try to be as small as possible . I8 . }; . . // If there are no negative values, we can use the unsigned fit. 81 ( 0.00%) if min >= 0 { . (cmp::max(unsigned_fit, at_least), false) . } else { . (cmp::max(signed_fit, at_least), true) . } 54 ( 0.00%) } . } . . pub trait PrimitiveExt { . fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx>; . fn to_int_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx>; . } . . impl PrimitiveExt for Primitive { . #[inline] . fn to_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { 193,668 ( 0.01%) match *self { . Int(i, signed) => i.to_ty(tcx, signed), . F32 => tcx.types.f32, . F64 => tcx.types.f64, . Pointer => tcx.mk_mut_ptr(tcx.mk_unit()), . } . } . . /// Return an *integer* type matching this primitive. . /// Useful in particular when dealing with enum discriminants. . #[inline] . fn to_int_ty<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { 110,664 ( 0.01%) match *self { 55,332 ( 0.00%) Int(i, signed) => i.to_ty(tcx, signed), . Pointer => tcx.types.usize, . F32 | F64 => bug!("floats do not have an int type"), . } . } . } . . /// The first half of a fat pointer. . /// -- line 181 ---------------------------------------- -- line 215 ---------------------------------------- . "unable to determine layout for `{}` because `{}` cannot be normalized", . t, . e.get_type_for_failure() . ), . } . } . } . 1,088 ( 0.00%) #[instrument(skip(tcx, query), level = "debug")] . fn layout_of<'tcx>( . tcx: TyCtxt<'tcx>, . query: ty::ParamEnvAnd<'tcx, Ty<'tcx>>, . ) -> Result, LayoutError<'tcx>> { . ty::tls::with_related_context(tcx, move |icx| { 68 ( 0.00%) let (param_env, ty) = query.into_parts(); . debug!(?ty); . 272 ( 0.00%) if !tcx.recursion_limit().value_within_limit(icx.layout_depth) { . tcx.sess.fatal(&format!("overflow representing the type `{}`", ty)); . } . . // Update the ImplicitCtxt to increase the layout_depth 612 ( 0.00%) let icx = ty::tls::ImplicitCtxt { layout_depth: icx.layout_depth + 1, ..icx.clone() }; . . ty::tls::enter_context(&icx, |_| { 204 ( 0.00%) let param_env = param_env.with_reveal_all_normalized(tcx); . let unnormalized_ty = ty; . . // FIXME: We might want to have two different versions of `layout_of`: . // One that can be called after typecheck has completed and can use . // `normalize_erasing_regions` here and another one that can be called . // before typecheck has completed and uses `try_normalize_erasing_regions`. . let ty = match tcx.try_normalize_erasing_regions(param_env, ty) { . Ok(t) => t, . Err(normalization_error) => { . return Err(LayoutError::NormalizationFailure(ty, normalization_error)); . } . }; . 68 ( 0.00%) if ty != unnormalized_ty { . // Ensure this layout is also cached for the normalized type. . return tcx.layout_of(param_env.and(ty)); . } . 236 ( 0.00%) let cx = LayoutCx { tcx, param_env }; . 177 ( 0.00%) let layout = cx.layout_of_uncached(ty)?; . let layout = TyAndLayout { ty, layout }; . . cx.record_layout_for_printing(layout); . . // Type-level uninhabitedness should always imply ABI uninhabitedness. 59 ( 0.00%) if tcx.conservative_is_privately_uninhabited(param_env.and(ty)) { . assert!(layout.abi.is_uninhabited()); . } . 177 ( 0.00%) Ok(layout) . }) . }) . } . . pub struct LayoutCx<'tcx, C> { . pub tcx: C, . pub param_env: ty::ParamEnv<'tcx>, . } -- line 279 ---------------------------------------- -- line 291 ---------------------------------------- . // Invert a bijective mapping, i.e. `invert(map)[y] = x` if `map[x] = y`. . // This is used to go between `memory_index` (source field order to memory order) . // and `inverse_memory_index` (memory order to source field order). . // See also `FieldsShape::Arbitrary::memory_index` for more details. . // FIXME(eddyb) build a better abstraction for permutations, if possible. . fn invert_mapping(map: &[u32]) -> Vec { . let mut inverse = vec![0; map.len()]; . for i in 0..map.len() { 100 ( 0.00%) inverse[map[i] as usize] = i as u32; . } . inverse . } . . impl<'tcx> LayoutCx<'tcx, TyCtxt<'tcx>> { 135 ( 0.00%) fn scalar_pair(&self, a: Scalar, b: Scalar) -> Layout { . let dl = self.data_layout(); 105 ( 0.00%) let b_align = b.value.align(dl); 120 ( 0.00%) let align = a.value.align(dl).max(b_align).max(dl.aggregate_align); . let b_offset = a.value.size(dl).align_to(b_align.abi); . let size = (b_offset + b.value.size(dl)).align_to(align.abi); . . // HACK(nox): We iter on `b` and then `a` because `max_by_key` . // returns the last maximum. 180 ( 0.00%) let largest_niche = Niche::from_scalar(dl, b_offset, b) . .into_iter() 150 ( 0.00%) .chain(Niche::from_scalar(dl, Size::ZERO, a)) . .max_by_key(|niche| niche.available(dl)); . 285 ( 0.00%) Layout { . variants: Variants::Single { index: VariantIdx::new(0) }, . fields: FieldsShape::Arbitrary { 30 ( 0.00%) offsets: vec![Size::ZERO, b_offset], 30 ( 0.00%) memory_index: vec![0, 1], . }, 195 ( 0.00%) abi: Abi::ScalarPair(a, b), 150 ( 0.00%) largest_niche, . align, . size, . } 120 ( 0.00%) } . 1,500 ( 0.00%) fn univariant_uninterned( . &self, . ty: Ty<'tcx>, . fields: &[TyAndLayout<'_>], . repr: &ReprOptions, . kind: StructKind, . ) -> Result> { . let dl = self.data_layout(); 500 ( 0.00%) let pack = repr.pack; 125 ( 0.00%) if pack.is_some() && repr.align.is_some() { . self.tcx.sess.delay_span_bug(DUMMY_SP, "struct cannot be packed and aligned"); . return Err(LayoutError::Unknown(ty)); . } . 500 ( 0.00%) let mut align = if pack.is_some() { dl.i8_align } else { dl.aggregate_align }; . . let mut inverse_memory_index: Vec = (0..fields.len() as u32).collect(); . . let optimize = !repr.inhibit_struct_field_reordering_opt(); 125 ( 0.00%) if optimize { . let end = 875 ( 0.00%) if let StructKind::MaybeUnsized = kind { fields.len() - 1 } else { fields.len() }; . let optimizing = &mut inverse_memory_index[..end]; 125 ( 0.00%) let field_align = |f: &TyAndLayout<'_>| { 32 ( 0.00%) if let Some(pack) = pack { f.align.abi.min(pack) } else { f.align.abi } . }; . . // If `-Z randomize-layout` was enabled for the type definition we can shuffle . // the field ordering to try and catch some code making assumptions about layouts . // we don't guarantee . if repr.can_randomize_type_layout() { . // `ReprOptions.layout_seed` is a deterministic seed that we can use to . // randomize field ordering with . let mut rng = Xoshiro128StarStar::seed_from_u64(repr.field_shuffle_seed); . . // Shuffle the ordering of the fields . optimizing.shuffle(&mut rng); . . // Otherwise we just leave things alone and actually optimize the type's fields . } else { 250 ( 0.00%) match kind { . StructKind::AlwaysSized | StructKind::MaybeUnsized => { 45 ( 0.00%) optimizing.sort_by_key(|&x| { . // Place ZSTs first to avoid "interesting offsets", . // especially with only one or two non-ZST fields. 28 ( 0.00%) let f = &fields[x as usize]; 4 ( 0.00%) (!f.is_zst(), cmp::Reverse(field_align(f))) . }); . } . . StructKind::Prefixed(..) => { . // Sort in ascending alignment so that the layout stays optimal . // regardless of the prefix 580 ( 0.00%) optimizing.sort_by_key(|&x| field_align(&fields[x as usize])); . } . } . . // FIXME(Kixiron): We can always shuffle fields within a given alignment class . // regardless of the status of `-Z randomize-layout` . } . } . -- line 393 ---------------------------------------- -- line 399 ---------------------------------------- . // produce `memory_index` (see `invert_mapping`). . . let mut sized = true; . let mut offsets = vec![Size::ZERO; fields.len()]; . let mut offset = Size::ZERO; . let mut largest_niche = None; . let mut largest_niche_available = 0; . 375 ( 0.00%) if let StructKind::Prefixed(prefix_size, prefix_align) = kind { . let prefix_align = 812 ( 0.00%) if let Some(pack) = pack { prefix_align.min(pack) } else { prefix_align }; . align = align.max(AbiAndPrefAlign::new(prefix_align)); . offset = prefix_size.align_to(prefix_align); . } . 25 ( 0.00%) for &i in &inverse_memory_index { 315 ( 0.00%) let field = fields[i as usize]; 50 ( 0.00%) if !sized { . self.tcx.sess.delay_span_bug( . DUMMY_SP, . &format!( . "univariant: field #{} of `{}` comes after unsized field", . offsets.len(), . ty . ), . ); . } . 125 ( 0.00%) if field.is_unsized() { . sized = false; . } . . // Invariant: offset < dl.obj_size_bound() <= 1<<61 50 ( 0.00%) let field_align = if let Some(pack) = pack { . field.align.min(AbiAndPrefAlign::new(pack)) . } else { 75 ( 0.00%) field.align . }; . offset = offset.align_to(field_align.abi); . align = align.max(field_align); . . debug!("univariant offset: {:?} field: {:#?}", offset, field); 50 ( 0.00%) offsets[i as usize] = offset; . 25 ( 0.00%) if !repr.hide_niche() { 361 ( 0.00%) if let Some(mut niche) = field.largest_niche { . let available = niche.available(dl); 88 ( 0.00%) if available > largest_niche_available { . largest_niche_available = available; . niche.offset += offset; 224 ( 0.00%) largest_niche = Some(niche); . } . } . } . 25 ( 0.00%) offset = offset.checked_add(field.size, dl).ok_or(LayoutError::SizeOverflow(ty))?; . } . 265 ( 0.00%) if let Some(repr_align) = repr.align { . align = align.max(AbiAndPrefAlign::new(repr_align)); . } . . debug!("univariant min_size: {:?}", offset); . let min_size = offset; . . // As stated above, inverse_memory_index holds field indices by increasing offset. . // This makes it an already-sorted view of the offsets vec. . // To invert it, consider: . // If field 5 has offset 0, offsets[0] is 5, and memory_index[5] should be 0. . // Field 5 would be the first element, so memory_index is i: . // Note: if we didn't optimize, it's already right. . . let memory_index = 250 ( 0.00%) if optimize { invert_mapping(&inverse_memory_index) } else { inverse_memory_index }; . . let size = min_size.align_to(align.abi); 250 ( 0.00%) let mut abi = Abi::Aggregate { sized }; . . // Unpack newtype ABIs and find scalar pairs. 500 ( 0.00%) if sized && size.bytes() > 0 { . // All other fields must be ZSTs. . let mut non_zst_fields = fields.iter().enumerate().filter(|&(_, f)| !f.is_zst()); . 24 ( 0.00%) match (non_zst_fields.next(), non_zst_fields.next(), non_zst_fields.next()) { . // We have exactly one non-ZST field. . (Some((i, field)), None, None) => { . // Field fills the struct and it has a scalar or scalar pair ABI. 24 ( 0.00%) if offsets[i].bytes() == 0 && align.abi == field.align.abi && size == field.size . { . match field.abi { . // For plain scalars, or vectors of them, we can't unpack . // newtypes for `#[repr(C)]`, as that affects C ABIs. . Abi::Scalar(_) | Abi::Vector { .. } if optimize => { . abi = field.abi; . } . // But scalar pairs are Rust-specific and get -- line 494 ---------------------------------------- -- line 503 ---------------------------------------- . . // Two non-ZST fields, and they're both scalars. . ( . Some((i, &TyAndLayout { layout: &Layout { abi: Abi::Scalar(a), .. }, .. })), . Some((j, &TyAndLayout { layout: &Layout { abi: Abi::Scalar(b), .. }, .. })), . None, . ) => { . // Order by the memory placement, not source order. 18 ( 0.00%) let ((i, a), (j, b)) = 14 ( 0.00%) if offsets[i] < offsets[j] { ((i, a), (j, b)) } else { ((j, b), (i, a)) }; 22 ( 0.00%) let pair = self.scalar_pair(a, b); 4 ( 0.00%) let pair_offsets = match pair.fields { 4 ( 0.00%) FieldsShape::Arbitrary { ref offsets, ref memory_index } => { 2 ( 0.00%) assert_eq!(memory_index, &[0, 1]); . offsets . } . _ => bug!(), . }; 18 ( 0.00%) if offsets[i] == pair_offsets[0] 2 ( 0.00%) && offsets[j] == pair_offsets[1] . && align == pair.align . && size == pair.size . { . // We can use `ScalarPair` only when it matches our . // already computed layout (including `#[repr(C)]`). 28 ( 0.00%) abi = pair.abi; . } 2 ( 0.00%) } . . _ => {} . } . } . 25 ( 0.00%) if fields.iter().any(|f| f.abi.is_uninhabited()) { . abi = Abi::Uninhabited; . } . 4,000 ( 0.00%) Ok(Layout { . variants: Variants::Single { index: VariantIdx::new(0) }, 1,250 ( 0.00%) fields: FieldsShape::Arbitrary { offsets, memory_index }, . abi, 1,375 ( 0.00%) largest_niche, . align, . size, . }) 1,250 ( 0.00%) } . 590 ( 0.00%) fn layout_of_uncached(&self, ty: Ty<'tcx>) -> Result<&'tcx Layout, LayoutError<'tcx>> { 118 ( 0.00%) let tcx = self.tcx; 59 ( 0.00%) let param_env = self.param_env; . let dl = self.data_layout(); 85 ( 0.00%) let scalar_unit = |value: Primitive| { . let size = value.size(dl); 76 ( 0.00%) assert!(size.bits() <= 128); 91 ( 0.00%) Scalar { value, valid_range: WrappingRange { start: 0, end: size.unsigned_int_max() } } 26 ( 0.00%) }; . let scalar = |value: Primitive| tcx.intern_layout(Layout::scalar(self, scalar_unit(value))); . . let univariant = |fields: &[TyAndLayout<'_>], repr: &ReprOptions, kind| { 126 ( 0.00%) Ok(tcx.intern_layout(self.univariant_uninterned(ty, fields, repr, kind)?)) . }; . debug_assert!(!ty.has_infer_types_or_consts()); . 454 ( 0.00%) Ok(match *ty.kind() { . // Basic scalars. . ty::Bool => tcx.intern_layout(Layout::scalar( . self, 6 ( 0.00%) Scalar { value: Int(I8, false), valid_range: WrappingRange { start: 0, end: 1 } }, . )), . ty::Char => tcx.intern_layout(Layout::scalar( . self, 12 ( 0.00%) Scalar { . value: Int(I32, false), . valid_range: WrappingRange { start: 0, end: 0x10FFFF }, . }, . )), 5 ( 0.00%) ty::Int(ity) => scalar(Int(Integer::from_int_ty(dl, ity), true)), 25 ( 0.00%) ty::Uint(ity) => scalar(Int(Integer::from_uint_ty(dl, ity), false)), . ty::Float(fty) => scalar(match fty { . ty::FloatTy::F32 => F32, . ty::FloatTy::F64 => F64, . }), . ty::FnPtr(_) => { . let mut ptr = scalar_unit(Pointer); . ptr.valid_range = ptr.valid_range.with_start(1); . tcx.intern_layout(Layout::scalar(self, ptr)) -- line 588 ---------------------------------------- -- line 594 ---------------------------------------- . fields: FieldsShape::Primitive, . abi: Abi::Uninhabited, . largest_niche: None, . align: dl.i8_align, . size: Size::ZERO, . }), . . // Potentially-wide pointers. 19 ( 0.00%) ty::Ref(_, pointee, _) | ty::RawPtr(ty::TypeAndMut { ty: pointee, .. }) => { . let mut data_ptr = scalar_unit(Pointer); . if !ty.is_unsafe_ptr() { . data_ptr.valid_range = data_ptr.valid_range.with_start(1); . } . . let pointee = tcx.normalize_erasing_regions(param_env, pointee); 152 ( 0.00%) if pointee.is_sized(tcx.at(DUMMY_SP), param_env) { 102 ( 0.00%) return Ok(tcx.intern_layout(Layout::scalar(self, data_ptr))); . } . 52 ( 0.00%) let unsized_part = tcx.struct_tail_erasing_lifetimes(pointee, param_env); 52 ( 0.00%) let metadata = match unsized_part.kind() { . ty::Foreign(..) => { . return Ok(tcx.intern_layout(Layout::scalar(self, data_ptr))); . } 104 ( 0.00%) ty::Slice(_) | ty::Str => scalar_unit(Int(dl.ptr_sized_integer(), false)), . ty::Dynamic(..) => { . let mut vtable = scalar_unit(Pointer); . vtable.valid_range = vtable.valid_range.with_start(1); . vtable . } . _ => return Err(LayoutError::Unknown(unsized_part)), . }; . . // Effectively a (ptr, meta) tuple. 273 ( 0.00%) tcx.intern_layout(self.scalar_pair(data_ptr, metadata)) . } . . // Arrays and slices. 18 ( 0.00%) ty::Array(element, mut count) => { 6 ( 0.00%) if count.has_projections() { . count = tcx.normalize_erasing_regions(param_env, count); . if count.has_projections() { . return Err(LayoutError::Unknown(ty)); . } . } . 24 ( 0.00%) let count = count.try_eval_usize(tcx, param_env).ok_or(LayoutError::Unknown(ty))?; 30 ( 0.00%) let element = self.layout_of(element)?; . let size = 30 ( 0.00%) element.size.checked_mul(count, dl).ok_or(LayoutError::SizeOverflow(ty))?; . . let abi = 48 ( 0.00%) if count != 0 && tcx.conservative_is_privately_uninhabited(param_env.and(ty)) { . Abi::Uninhabited . } else { . Abi::Aggregate { sized: true } . }; . 66 ( 0.00%) let largest_niche = if count != 0 { element.largest_niche } else { None }; . 132 ( 0.00%) tcx.intern_layout(Layout { . variants: Variants::Single { index: VariantIdx::new(0) }, 6 ( 0.00%) fields: FieldsShape::Array { stride: element.size, count }, . abi, . largest_niche, 6 ( 0.00%) align: element.align, . size, . }) . } 12 ( 0.00%) ty::Slice(element) => { 18 ( 0.00%) let element = self.layout_of(element)?; 66 ( 0.00%) tcx.intern_layout(Layout { . variants: Variants::Single { index: VariantIdx::new(0) }, 6 ( 0.00%) fields: FieldsShape::Array { stride: element.size, count: 0 }, . abi: Abi::Aggregate { sized: false }, . largest_niche: None, 6 ( 0.00%) align: element.align, . size: Size::ZERO, . }) . } 6 ( 0.00%) ty::Str => tcx.intern_layout(Layout { . variants: Variants::Single { index: VariantIdx::new(0) }, . fields: FieldsShape::Array { stride: Size::from_bytes(1), count: 0 }, . abi: Abi::Aggregate { sized: false }, . largest_niche: None, 1 ( 0.00%) align: dl.i8_align, . size: Size::ZERO, . }), . . // Odd unit types. . ty::FnDef(..) => univariant(&[], &ReprOptions::default(), StructKind::AlwaysSized)?, . ty::Dynamic(..) | ty::Foreign(..) => { . let mut unit = self.univariant_uninterned( . ty, -- line 687 ---------------------------------------- -- line 702 ---------------------------------------- . let tys = substs.as_closure().upvar_tys(); . univariant( . &tys.map(|ty| self.layout_of(ty)).collect::, _>>()?, . &ReprOptions::default(), . StructKind::AlwaysSized, . )? . } . 6 ( 0.00%) ty::Tuple(tys) => { . let kind = 18 ( 0.00%) if tys.len() == 0 { StructKind::AlwaysSized } else { StructKind::MaybeUnsized }; . 6 ( 0.00%) univariant( 12 ( 0.00%) &tys.iter() . .map(|k| self.layout_of(k.expect_ty())) . .collect::, _>>()?, 12 ( 0.00%) &ReprOptions::default(), . kind, . )? . } . . // SIMD vector types. 24 ( 0.00%) ty::Adt(def, substs) if def.repr.simd() => { . if !def.is_struct() { . // Should have yielded E0517 by now. . tcx.sess.delay_span_bug( . DUMMY_SP, . "#[repr(simd)] was applied to an ADT that is not a struct", . ); . return Err(LayoutError::Unknown(ty)); . } -- line 732 ---------------------------------------- -- line 833 ---------------------------------------- . abi: Abi::Vector { element: e_abi, count: e_len }, . largest_niche: e_ly.largest_niche, . size, . align, . }) . } . . // ADTs. 24 ( 0.00%) ty::Adt(def, substs) => { . // Cache the field layouts. 24 ( 0.00%) let variants = def . .variants . .iter() . .map(|v| { . v.fields . .iter() 100 ( 0.00%) .map(|field| self.layout_of(field.ty(tcx, substs))) . .collect::, _>>() . }) . .collect::, _>>()?; . 12 ( 0.00%) if def.is_union() { . if def.repr.pack.is_some() && def.repr.align.is_some() { . self.tcx.sess.delay_span_bug( . tcx.def_span(def.did), . "union cannot be packed and aligned", . ); . return Err(LayoutError::Unknown(ty)); . } . -- line 862 ---------------------------------------- -- line 921 ---------------------------------------- . } . . // A variant is absent if it's uninhabited and only has ZST fields. . // Present uninhabited variants only require space for their fields, . // but *not* an encoding of the discriminant (e.g., a tag value). . // See issue #49298 for more details on the need to leave space . // for non-ZST uninhabited data (mostly partial initialization). . let absent = |fields: &[TyAndLayout<'_>]| { 19 ( 0.00%) let uninhabited = fields.iter().any(|f| f.abi.is_uninhabited()); . let is_zst = fields.iter().all(|f| f.is_zst()); 116 ( 0.00%) uninhabited && is_zst 116 ( 0.00%) }; . let (present_first, present_second) = { . let mut present_variants = variants . .iter_enumerated() 84 ( 0.00%) .filter_map(|(i, v)| if absent(v) { None } else { Some(i) }); . (present_variants.next(), present_variants.next()) . }; 24 ( 0.00%) let present_first = match present_first { . Some(present_first) => present_first, . // Uninhabited because it has no variants, or only absent ones. . None if def.is_enum() => { . return Ok(tcx.layout_of(param_env.and(tcx.types.never))?.layout); . } . // If it's a struct, still compute a layout so that we can still compute the . // field offsets. . None => VariantIdx::new(0), . }; . 12 ( 0.00%) let is_struct = !def.is_enum() || . // Only one variant is present. 9 ( 0.00%) (present_second.is_none() && . // Representation optimizations are allowed. . !def.repr.inhibit_enum_layout_opt()); . if is_struct { . // Struct, or univariant enum equivalent to a struct. . // (Typechecking will reject discriminant-sizing attrs.) . . let v = present_first; 3 ( 0.00%) let kind = if def.is_enum() || variants[v].is_empty() { . StructKind::AlwaysSized . } else { 9 ( 0.00%) let param_env = tcx.param_env(def.did); 3 ( 0.00%) let last_field = def.variants[v].fields.last().unwrap(); . let always_sized = 18 ( 0.00%) tcx.type_of(last_field.did).is_sized(tcx.at(DUMMY_SP), param_env); 6 ( 0.00%) if !always_sized { . StructKind::MaybeUnsized . } else { . StructKind::AlwaysSized . } . }; . 39 ( 0.00%) let mut st = self.univariant_uninterned(ty, &variants[v], &def.repr, kind)?; 15 ( 0.00%) st.variants = Variants::Single { index: v }; 21 ( 0.00%) let (start, end) = self.tcx.layout_scalar_valid_range(def.did); 12 ( 0.00%) match st.abi { . Abi::Scalar(ref mut scalar) | Abi::ScalarPair(ref mut scalar, _) => { . // the asserts ensure that we are not using the . // `#[rustc_layout_scalar_valid_range(n)]` . // attribute to widen the range of anything as that would probably . // result in UB somewhere . // FIXME(eddyb) the asserts are probably not needed, . // as larger validity ranges would result in missed . // optimizations, *not* wrongly assuming the inner . // value is valid. e.g. unions enlarge validity ranges, . // because the values may be uninitialized. 6 ( 0.00%) if let Bound::Included(start) = start { . // FIXME(eddyb) this might be incorrect - it doesn't . // account for wrap-around (end < start) ranges. . assert!(scalar.valid_range.start <= start); . scalar.valid_range.start = start; . } 4 ( 0.00%) if let Bound::Included(end) = end { . // FIXME(eddyb) this might be incorrect - it doesn't . // account for wrap-around (end < start) ranges. . assert!(scalar.valid_range.end >= end); . scalar.valid_range.end = end; . } . . // Update `largest_niche` if we have introduced a larger niche. 6 ( 0.00%) let niche = if def.repr.hide_niche() { . None . } else { 20 ( 0.00%) Niche::from_scalar(dl, Size::ZERO, *scalar) . }; 14 ( 0.00%) if let Some(niche) = niche { 4 ( 0.00%) match st.largest_niche { 14 ( 0.00%) Some(largest_niche) => { . // Replace the existing niche even if they're equal, . // because this one is at a lower offset. 10 ( 0.00%) if largest_niche.available(dl) <= niche.available(dl) { 14 ( 0.00%) st.largest_niche = Some(niche); . } . } . None => st.largest_niche = Some(niche), . } . } . } . _ => assert!( 3 ( 0.00%) start == Bound::Unbounded && end == Bound::Unbounded, . "nonscalar layout for layout_scalar_valid_range type {:?}: {:#?}", . def, . st, . ), . } . 27 ( 0.00%) return Ok(tcx.intern_layout(st)); . } . . // At this point, we have handled all unions and . // structs. (We have also handled univariant enums . // that allow representation optimization.) . assert!(def.is_enum()); . . // The current code for niche-filling relies on variant indices . // instead of actual discriminants, so dataful enums with . // explicit discriminants (RFC #2363) would misbehave. . let no_explicit_discriminants = def . .variants . .iter_enumerated() . .all(|(i, v)| v.discr == ty::VariantDiscr::Relative(i.as_u32())); . 18 ( 0.00%) let mut niche_filling_layout = None; . . // Niche-filling enum optimization. 18 ( 0.00%) if !def.repr.inhibit_enum_layout_opt() && no_explicit_discriminants { . let mut dataful_variant = None; . let mut niche_variants = VariantIdx::MAX..=VariantIdx::new(0); . . // Find one non-ZST variant. 682 ( 0.00%) 'variants: for (v, fields) in variants.iter_enumerated() { 348 ( 0.00%) if absent(fields) { . continue 'variants; . } 232 ( 0.00%) for f in fields { . if !f.is_zst() { . if dataful_variant.is_none() { . dataful_variant = Some(v); . continue 'variants; . } else { . dataful_variant = None; . break 'variants; . } . } . } 440 ( 0.00%) niche_variants = *niche_variants.start().min(&v)..=v; . } . 18 ( 0.00%) if niche_variants.start() > niche_variants.end() { . dataful_variant = None; . } . . if let Some(i) = dataful_variant { . let count = (niche_variants.end().as_u32() . - niche_variants.start().as_u32() . + 1) as u128; . -- line 1078 ---------------------------------------- -- line 1151 ---------------------------------------- . largest_niche, . size, . align, . }); . } . } . } . 45 ( 0.00%) let (mut min, mut max) = (i128::MAX, i128::MIN); 116 ( 0.00%) let discr_type = def.repr.discr_type(); 27 ( 0.00%) let bits = Integer::from_attr(self, discr_type).size().bits(); 215 ( 0.00%) for (i, discr) in def.discriminants(tcx) { 6 ( 0.00%) if variants[i].iter().any(|f| f.abi.is_uninhabited()) { . continue; . } . let mut x = discr.val as i128; 116 ( 0.00%) if discr_type.is_signed() { . // sign extend the raw representation to be an i128 2,204 ( 0.00%) x = (x << (128 - bits)) >> (128 - bits); . } 464 ( 0.00%) if x < min { 36 ( 0.00%) min = x; . } 464 ( 0.00%) if x > max { 348 ( 0.00%) max = x; . } . } . // We might have no inhabited variants, so pretend there's at least one. 9 ( 0.00%) if (min, max) == (i128::MAX, i128::MIN) { . min = 0; . max = 0; . } 45 ( 0.00%) assert!(min <= max, "discriminant range is {}...{}", min, max); 81 ( 0.00%) let (min_ity, signed) = Integer::repr_discr(tcx, ty, &def.repr, min, max); . 18 ( 0.00%) let mut align = dl.aggregate_align; 9 ( 0.00%) let mut size = Size::ZERO; . . // We're interested in the smallest alignment, so start large. 18 ( 0.00%) let mut start_align = Align::from_bytes(256).unwrap(); 45 ( 0.00%) assert_eq!(Integer::for_align(dl, start_align), None); . . // repr(C) on an enum tells us to make a (tag, union) layout, . // so we need to grow the prefix alignment to be at least . // the alignment of the union. (This value is used both for . // determining the alignment of the overall enum, and the . // determining the alignment of the payload after the tag.) 117 ( 0.00%) let mut prefix_align = min_ity.align(dl).abi; 9 ( 0.00%) if def.repr.c() { . for fields in &variants { . for field in fields { . prefix_align = prefix_align.max(field.align.abi); . } . } . } . . // Create the set of structs that represent each variant. 18 ( 0.00%) let mut layout_variants = variants . .iter_enumerated() . .map(|(i, field_layouts)| { 2,204 ( 0.00%) let mut st = self.univariant_uninterned( 116 ( 0.00%) ty, . &field_layouts, 232 ( 0.00%) &def.repr, 464 ( 0.00%) StructKind::Prefixed(min_ity.size(), prefix_align), . )?; 348 ( 0.00%) st.variants = Variants::Single { index: i }; . // Find the first field we can't move later . // to make room for a larger discriminant. . for field in 1,520 ( 0.00%) st.fields.index_by_increasing_offset().map(|j| field_layouts[j]) . { . if !field.is_zst() || field.align.abi.bytes() != 1 { 12 ( 0.00%) start_align = start_align.min(field.align.abi); . break; . } . } 464 ( 0.00%) size = cmp::max(size, st.size); 348 ( 0.00%) align = align.max(st.align); 696 ( 0.00%) Ok(st) . }) . .collect::, _>>()?; . . // Align the maximum variant size to the largest alignment. 45 ( 0.00%) size = size.align_to(align.abi); . 36 ( 0.00%) if size.bytes() >= dl.obj_size_bound() { . return Err(LayoutError::SizeOverflow(ty)); . } . 36 ( 0.00%) let typeck_ity = Integer::from_attr(dl, def.repr.discr_type()); 27 ( 0.00%) if typeck_ity < min_ity { . // It is a bug if Layout decided on a greater discriminant size than typeck for . // some reason at this point (based on values discriminant can take on). Mostly . // because this discriminant will be loaded, and then stored into variable of . // type calculated by typeck. Consider such case (a bug): typeck decided on . // byte-sized discriminant, but layout thinks we need a 16-bit to store all . // discriminant values. That would be a bug, because then, in codegen, in order . // to store this 16-bit discriminant into 8-bit sized temporary some of the . // space necessary to represent would have to be discarded (or layout is wrong -- line 1250 ---------------------------------------- -- line 1263 ---------------------------------------- . // as the alignment of the first field of each variant. . // We increase the size of the discriminant to avoid LLVM copying . // padding when it doesn't need to. This normally causes unaligned . // load/stores and excessive memcpy/memset operations. By using a . // bigger integer size, LLVM can be sure about its contents and . // won't be so conservative. . . // Use the initial field alignment 27 ( 0.00%) let mut ity = if def.repr.c() || def.repr.int.is_some() { . min_ity . } else { 27 ( 0.00%) Integer::for_align(dl, start_align).unwrap_or(min_ity) . }; . . // If the alignment is not larger than the chosen discriminant size, . // don't use the alignment as the final size. 9 ( 0.00%) if ity <= min_ity { . ity = min_ity; . } else { . // Patch up the variants' first few fields. 6 ( 0.00%) let old_ity_size = min_ity.size(); . let new_ity_size = ity.size(); . for variant in &mut layout_variants { 12 ( 0.00%) match variant.fields { . FieldsShape::Arbitrary { ref mut offsets, .. } => { . for i in offsets { 18 ( 0.00%) if *i <= old_ity_size { . assert_eq!(*i, old_ity_size); . *i = new_ity_size; . } . } . // We might be making the struct larger. 6 ( 0.00%) if variant.size <= old_ity_size { . variant.size = new_ity_size; . } . } . _ => bug!(), . } . } . } . 9 ( 0.00%) let tag_mask = ity.size().unsigned_int_max(); . let tag = Scalar { . value: Int(ity, signed), . valid_range: WrappingRange { 45 ( 0.00%) start: (min as u128 & tag_mask), 36 ( 0.00%) end: (max as u128 & tag_mask), . }, . }; . let mut abi = Abi::Aggregate { sized: true }; 54 ( 0.00%) if tag.value.size(dl) == size { . abi = Abi::Scalar(tag); . } else { . // Try to use a ScalarPair for all tagged enums. . let mut common_prim = None; . for (field_layouts, layout_variant) in iter::zip(&variants, &layout_variants) { 6 ( 0.00%) let offsets = match layout_variant.fields { . FieldsShape::Arbitrary { ref offsets, .. } => offsets, . _ => bug!(), . }; . let mut fields = . iter::zip(field_layouts, offsets).filter(|p| !p.0.is_zst()); 30 ( 0.00%) let (field, offset) = match (fields.next(), fields.next()) { . (None, None) => continue, . (Some(pair), None) => pair, . _ => { . common_prim = None; . break; . } . }; 9 ( 0.00%) let prim = match field.abi { . Abi::Scalar(scalar) => scalar.value, . _ => { . common_prim = None; . break; . } . }; . if let Some(pair) = common_prim { . // This is pretty conservative. We could go fancier -- line 1341 ---------------------------------------- -- line 1370 ---------------------------------------- . } . } . } . . if layout_variants.iter().all(|v| v.abi.is_uninhabited()) { . abi = Abi::Uninhabited; . } . 144 ( 0.00%) let largest_niche = Niche::from_scalar(dl, Size::ZERO, tag); . . let tagged_layout = Layout { . variants: Variants::Multiple { . tag, . tag_encoding: TagEncoding::Direct, . tag_field: 0, . variants: layout_variants, . }, . fields: FieldsShape::Arbitrary { 45 ( 0.00%) offsets: vec![Size::ZERO], 36 ( 0.00%) memory_index: vec![0], . }, . largest_niche, . abi, 18 ( 0.00%) align, 9 ( 0.00%) size, . }; . 27 ( 0.00%) let best_layout = match (tagged_layout, niche_filling_layout) { . (tagged_layout, Some(niche_filling_layout)) => { . // Pick the smaller layout; otherwise, . // pick the layout with the larger niche; otherwise, . // pick tagged as it has simpler codegen. . cmp::min_by_key(tagged_layout, niche_filling_layout, |layout| { . let niche_size = layout.largest_niche.map_or(0, |n| n.available(dl)); . (layout.size, cmp::Reverse(niche_size)) . }) . } 549 ( 0.00%) (tagged_layout, None) => tagged_layout, . }; . 81 ( 0.00%) tcx.intern_layout(best_layout) 24 ( 0.00%) } . . // Types with no meaningful known layout. . ty::Projection(_) | ty::Opaque(..) => { . // NOTE(eddyb) `layout_of` query should've normalized these away, . // if that was possible, so there's no reason to try again here. . return Err(LayoutError::Unknown(ty)); . } . -- line 1419 ---------------------------------------- -- line 1420 ---------------------------------------- . ty::Placeholder(..) | ty::GeneratorWitness(..) | ty::Infer(_) => { . bug!("Layout::compute: unexpected type `{}`", ty) . } . . ty::Bound(..) | ty::Param(_) | ty::Error(_) => { . return Err(LayoutError::Unknown(ty)); . } . }) 472 ( 0.00%) } . } . . /// Overlap eligibility and variant assignment for each GeneratorSavedLocal. . #[derive(Clone, Debug, PartialEq)] . enum SavedLocalEligibility { . Unassigned, . Assigned(VariantIdx), . // FIXME: Use newtype_index so we aren't wasting bytes -- line 1436 ---------------------------------------- -- line 1755 ---------------------------------------- . } . . /// This is invoked by the `layout_of` query to record the final . /// layout of each type. . #[inline(always)] . fn record_layout_for_printing(&self, layout: TyAndLayout<'tcx>) { . // If we are running with `-Zprint-type-sizes`, maybe record layouts . // for dumping later. 295 ( 0.00%) if self.tcx.sess.opts.debugging_opts.print_type_sizes { . self.record_layout_for_printing_outlined(layout) . } . } . . fn record_layout_for_printing_outlined(&self, layout: TyAndLayout<'tcx>) { . // Ignore layouts that are done with non-empty environments or . // non-monomorphic layouts, as the user only wants to see the stuff . // resulting from the final codegen session. -- line 1771 ---------------------------------------- -- line 2041 ---------------------------------------- . . pub trait HasParamEnv<'tcx> { . fn param_env(&self) -> ty::ParamEnv<'tcx>; . } . . impl<'tcx> HasDataLayout for TyCtxt<'tcx> { . #[inline] . fn data_layout(&self) -> &TargetDataLayout { 417,577 ( 0.02%) &self.data_layout . } . } . . impl<'tcx> HasTargetSpec for TyCtxt<'tcx> { . fn target_spec(&self) -> &Target { . &self.sess.target . } . } -- line 2057 ---------------------------------------- -- line 2080 ---------------------------------------- . #[inline] . fn tcx(&self) -> TyCtxt<'tcx> { . **self . } . } . . impl<'tcx, C> HasParamEnv<'tcx> for LayoutCx<'tcx, C> { . fn param_env(&self) -> ty::ParamEnv<'tcx> { 25 ( 0.00%) self.param_env . } . } . . impl<'tcx, T: HasDataLayout> HasDataLayout for LayoutCx<'tcx, T> { . fn data_layout(&self) -> &TargetDataLayout { . self.tcx.data_layout() . } . } -- line 2096 ---------------------------------------- -- line 2098 ---------------------------------------- . impl<'tcx, T: HasTargetSpec> HasTargetSpec for LayoutCx<'tcx, T> { . fn target_spec(&self) -> &Target { . self.tcx.target_spec() . } . } . . impl<'tcx, T: HasTyCtxt<'tcx>> HasTyCtxt<'tcx> for LayoutCx<'tcx, T> { . fn tcx(&self) -> TyCtxt<'tcx> { 25 ( 0.00%) self.tcx.tcx() . } . } . . pub trait MaybeResult { . type Error; . . fn from(x: Result) -> Self; . fn to_result(self) -> Result; -- line 2114 ---------------------------------------- -- line 2124 ---------------------------------------- . Ok(self) . } . } . . impl MaybeResult for Result { . type Error = E; . . fn from(x: Result) -> Self { 124,910 ( 0.01%) x . } . fn to_result(self) -> Result { . self . } . } . . pub type TyAndLayout<'tcx> = rustc_target::abi::TyAndLayout<'tcx, Ty<'tcx>>; . -- line 2140 ---------------------------------------- -- line 2167 ---------------------------------------- . ) -> >>::Error; . } . . /// Blanket extension trait for contexts that can compute layouts of types. . pub trait LayoutOf<'tcx>: LayoutOfHelpers<'tcx> { . /// Computes the layout of a type. Note that this implicitly . /// executes in "reveal all" mode, and will normalize the input type. . #[inline] 332,258 ( 0.02%) fn layout_of(&self, ty: Ty<'tcx>) -> Self::LayoutOfResult { . self.spanned_layout_of(ty, DUMMY_SP) 332,240 ( 0.02%) } . . /// Computes the layout of a type, at `span`. Note that this implicitly . /// executes in "reveal all" mode, and will normalize the input type. . // FIXME(eddyb) avoid passing information like this, and instead add more . // `TyCtxt::at`-like APIs to be able to do e.g. `cx.at(span).layout_of(ty)`. . #[inline] . fn spanned_layout_of(&self, ty: Ty<'tcx>, span: Span) -> Self::LayoutOfResult { . let span = if !span.is_dummy() { span } else { self.layout_tcx_at_span() }; -- line 2185 ---------------------------------------- -- line 2216 ---------------------------------------- . err . } . } . . impl<'tcx, C> TyAbiInterface<'tcx, C> for Ty<'tcx> . where . C: HasTyCtxt<'tcx> + HasParamEnv<'tcx>, . { 184,480 ( 0.01%) fn ty_and_layout_for_variant( . this: TyAndLayout<'tcx>, . cx: &C, . variant_index: VariantIdx, . ) -> TyAndLayout<'tcx> { 36,896 ( 0.00%) let layout = match this.variants { . Variants::Single { index } . // If all variants but one are uninhabited, the variant layout is the enum layout. . if index == variant_index && . // Don't confuse variants of uninhabited enums with the enum itself. . // For more details see https://github.com/rust-lang/rust/issues/69763. . this.fields != FieldsShape::Primitive => . { . this.layout -- line 2237 ---------------------------------------- -- line 2263 ---------------------------------------- . align: tcx.data_layout.i8_align, . size: Size::ZERO, . }) . } . . Variants::Multiple { ref variants, .. } => &variants[variant_index], . }; . 147,584 ( 0.01%) assert_eq!(layout.variants, Variants::Single { index: variant_index }); . . TyAndLayout { ty: this.ty, layout } 184,480 ( 0.01%) } . 1,646,985 ( 0.08%) fn ty_and_layout_field(this: TyAndLayout<'tcx>, cx: &C, i: usize) -> TyAndLayout<'tcx> { . enum TyMaybeWithLayout<'tcx> { . Ty(Ty<'tcx>), . TyAndLayout(TyAndLayout<'tcx>), . } . 1,317,588 ( 0.06%) fn field_ty_or_layout<'tcx>( . this: TyAndLayout<'tcx>, . cx: &(impl HasTyCtxt<'tcx> + HasParamEnv<'tcx>), . i: usize, . ) -> TyMaybeWithLayout<'tcx> { . let tcx = cx.tcx(); . let tag_layout = |tag: Scalar| -> TyAndLayout<'tcx> { 516,448 ( 0.02%) let layout = Layout::scalar(cx, tag); 419,614 ( 0.02%) TyAndLayout { layout: tcx.intern_layout(layout), ty: tag.value.to_ty(tcx) } . }; . 329,397 ( 0.02%) match *this.ty.kind() { . ty::Bool . | ty::Char . | ty::Int(_) . | ty::Uint(_) . | ty::Float(_) . | ty::FnPtr(_) . | ty::Never . | ty::FnDef(..) -- line 2301 ---------------------------------------- -- line 2350 ---------------------------------------- . */ . } . _ => bug!("TyAndLayout::field({:?}): not applicable", this), . } . } . . // Arrays and slices. . ty::Array(element, _) | ty::Slice(element) => TyMaybeWithLayout::Ty(element), 12 ( 0.00%) ty::Str => TyMaybeWithLayout::Ty(tcx.types.u8), . . // Tuples, generators and closures. . ty::Closure(_, ref substs) => field_ty_or_layout( . TyAndLayout { ty: substs.as_closure().tupled_upvars_ty(), ..this }, . cx, . i, . ), . -- line 2366 ---------------------------------------- -- line 2377 ---------------------------------------- . Variants::Multiple { tag, tag_field, .. } => { . if i == tag_field { . return TyMaybeWithLayout::TyAndLayout(tag_layout(tag)); . } . TyMaybeWithLayout::Ty(substs.as_generator().prefix_tys().nth(i).unwrap()) . } . }, . 145,728 ( 0.01%) ty::Tuple(tys) => TyMaybeWithLayout::Ty(tys[i].expect_ty()), . . // ADTs. 36,450 ( 0.00%) ty::Adt(def, substs) => { 137,456 ( 0.01%) match this.variants { 36,450 ( 0.00%) Variants::Single { index } => { 145,800 ( 0.01%) TyMaybeWithLayout::Ty(def.variants[index].fields[i].ty(tcx, substs)) . } . . // Discriminant field for enums (where applicable). . Variants::Multiple { tag, .. } => { 64,556 ( 0.00%) assert_eq!(i, 0); . return TyMaybeWithLayout::TyAndLayout(tag_layout(tag)); . } . } . } . . ty::Projection(_) . | ty::Bound(..) . | ty::Placeholder(..) . | ty::Opaque(..) . | ty::Param(_) . | ty::Infer(_) . | ty::Error(_) => bug!("TyAndLayout::field: unexpected type `{}`", this.ty), . } 988,191 ( 0.05%) } . 439,196 ( 0.02%) match field_ty_or_layout(this, cx, i) { 155,042 ( 0.01%) TyMaybeWithLayout::Ty(field_ty) => { . cx.tcx().layout_of(cx.param_env().and(field_ty)).unwrap_or_else(|e| { . bug!( . "failed to get layout for `{}`: {},\n\ . despite it being a field (#{}) of an existing layout: {:#?}", . field_ty, . e, . i, . this . ) . }) . } 96,834 ( 0.00%) TyMaybeWithLayout::TyAndLayout(field_layout) => field_layout, . } 878,392 ( 0.04%) } . . fn ty_and_layout_pointee_info_at( . this: TyAndLayout<'tcx>, . cx: &C, . offset: Size, . ) -> Option { . let tcx = cx.tcx(); . let param_env = cx.param_env(); -- line 2435 ---------------------------------------- 366,617 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/mod.rs -------------------------------------------------------------------------------- Ir -- line 141 ---------------------------------------- . /// ``` . /// let a = [1, 2, 3]; . /// assert!(!a.is_empty()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_slice_is_empty", since = "1.39.0")] . #[inline] . pub const fn is_empty(&self) -> bool { 831,799 ( 0.04%) self.len() == 0 . } . . /// Returns the first element of the slice, or `None` if it is empty. . /// . /// # Examples . /// . /// ``` . /// let v = [10, 40, 30]; -- line 157 ---------------------------------------- -- line 159 ---------------------------------------- . /// . /// let w: &[i32] = &[]; . /// assert_eq!(None, w.first()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")] . #[inline] . pub const fn first(&self) -> Option<&T> { 5,217 ( 0.00%) if let [first, ..] = self { Some(first) } else { None } . } . . /// Returns a mutable pointer to the first element of the slice, or `None` if it is empty. . /// . /// # Examples . /// . /// ``` . /// let x = &mut [0, 1, 2]; -- line 175 ---------------------------------------- -- line 178 ---------------------------------------- . /// *first = 5; . /// } . /// assert_eq!(x, &[5, 1, 2]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")] . #[inline] . pub const fn first_mut(&mut self) -> Option<&mut T> { 1,320 ( 0.00%) if let [first, ..] = self { Some(first) } else { None } . } . . /// Returns the first and all the rest of the elements of the slice, or `None` if it is empty. . /// . /// # Examples . /// . /// ``` . /// let x = &[0, 1, 2]; -- line 194 ---------------------------------------- -- line 237 ---------------------------------------- . /// assert_eq!(last, &2); . /// assert_eq!(elements, &[0, 1]); . /// } . /// ``` . #[stable(feature = "slice_splits", since = "1.5.0")] . #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")] . #[inline] . pub const fn split_last(&self) -> Option<(&T, &[T])> { 15,571 ( 0.00%) if let [init @ .., last] = self { Some((last, init)) } else { None } . } . . /// Returns the last and all the rest of the elements of the slice, or `None` if it is empty. . /// . /// # Examples . /// . /// ``` . /// let x = &mut [0, 1, 2]; -- line 253 ---------------------------------------- -- line 276 ---------------------------------------- . /// . /// let w: &[i32] = &[]; . /// assert_eq!(None, w.last()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_slice_first_last_not_mut", since = "1.56.0")] . #[inline] . pub const fn last(&self) -> Option<&T> { 721,228 ( 0.03%) if let [.., last] = self { Some(last) } else { None } . } . . /// Returns a mutable pointer to the last item in the slice. . /// . /// # Examples . /// . /// ``` . /// let x = &mut [0, 1, 2]; -- line 292 ---------------------------------------- -- line 295 ---------------------------------------- . /// *last = 10; . /// } . /// assert_eq!(x, &[0, 1, 10]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_slice_first_last", issue = "83570")] . #[inline] . pub const fn last_mut(&mut self) -> Option<&mut T> { 293,588 ( 0.01%) if let [.., last] = self { Some(last) } else { None } . } . . /// Returns a reference to an element or subslice depending on the type of . /// index. . /// . /// - If given a position, returns a reference to the element at that . /// position or `None` if out of bounds. . /// - If given a range, returns the subslice corresponding to that range, -- line 311 ---------------------------------------- -- line 448 ---------------------------------------- . /// } . /// ``` . /// . /// [`as_mut_ptr`]: slice::as_mut_ptr . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_slice_as_ptr", since = "1.32.0")] . #[inline] . pub const fn as_ptr(&self) -> *const T { 516,909 ( 0.02%) self as *const [T] as *const T . } . . /// Returns an unsafe mutable pointer to the slice's buffer. . /// . /// The caller must ensure that the slice outlives the pointer this . /// function returns, or else it will end up pointing to garbage. . /// . /// Modifying the container referenced by this slice may cause its buffer -- line 464 ---------------------------------------- -- line 476 ---------------------------------------- . /// } . /// } . /// assert_eq!(x, &[3, 4, 6]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")] . #[inline] . pub const fn as_mut_ptr(&mut self) -> *mut T { 10 ( 0.00%) self as *mut [T] as *mut T . } . . /// Returns the two raw pointers spanning the slice. . /// . /// The returned range is half-open, which means that the end pointer . /// points *one past* the last element of the slice. This way, an empty . /// slice is represented by two equal pointers, and the difference between . /// the two pointers represents the size of the slice. -- line 492 ---------------------------------------- -- line 582 ---------------------------------------- . /// v.swap(2, 4); . /// assert!(v == ["a", "b", "e", "d", "c"]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_swap", issue = "83163")] . #[inline] . #[track_caller] . pub const fn swap(&mut self, a: usize, b: usize) { 28,252 ( 0.00%) let _ = &self[a]; 30,977 ( 0.00%) let _ = &self[b]; . . // SAFETY: we just checked that both `a` and `b` are in bounds . unsafe { self.swap_unchecked(a, b) } . } . . /// Swaps two elements in the slice, without doing bounds checking. . /// . /// For a safe alternative see [`swap`]. -- line 599 ---------------------------------------- -- line 677 ---------------------------------------- . . // Because this function is first compiled in isolation, . // this check tells LLVM that the indexing below is . // in-bounds. Then after inlining -- once the actual . // lengths of the slices are known -- it's removed. . let (a, b) = (&mut a[..n], &mut b[..n]); . . for i in 0..n { 142 ( 0.00%) mem::swap(&mut a[i], &mut b[n - 1 - i]); . } . } . } . . /// Returns an iterator over the slice. . /// . /// # Examples . /// -- line 693 ---------------------------------------- -- line 1499 ---------------------------------------- . /// assert_eq!(left, [1, 2, 3, 4, 5, 6]); . /// assert_eq!(right, []); . /// } . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . #[track_caller] . pub fn split_at(&self, mid: usize) -> (&[T], &[T]) { 18 ( 0.00%) assert!(mid <= self.len()); . // SAFETY: `[ptr; mid]` and `[mid; len]` are inside `self`, which . // fulfills the requirements of `from_raw_parts_mut`. . unsafe { self.split_at_unchecked(mid) } . } . . /// Divides one mutable slice into two at an index. . /// . /// The first will contain all indices from `[0, mid)` (excluding -- line 1515 ---------------------------------------- -- line 1530 ---------------------------------------- . /// left[1] = 2; . /// right[1] = 4; . /// assert_eq!(v, [1, 2, 3, 4, 5, 6]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . #[track_caller] . pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) { 13,676 ( 0.00%) assert!(mid <= self.len()); . // SAFETY: `[ptr; mid]` and `[mid; len]` are inside `self`, which . // fulfills the requirements of `from_raw_parts_mut`. . unsafe { self.split_at_mut_unchecked(mid) } . } . . /// Divides one slice into two at an index, without doing bounds checking. . /// . /// The first will contain all indices from `[0, mid)` (excluding -- line 1546 ---------------------------------------- -- line 1628 ---------------------------------------- . pub unsafe fn split_at_mut_unchecked(&mut self, mid: usize) -> (&mut [T], &mut [T]) { . let len = self.len(); . let ptr = self.as_mut_ptr(); . . // SAFETY: Caller has to check that `0 <= mid <= self.len()`. . // . // `[ptr; mid]` and `[mid; len]` are not overlapping, so returning a mutable reference . // is fine. 1,862 ( 0.00%) unsafe { (from_raw_parts_mut(ptr, mid), from_raw_parts_mut(ptr.add(mid), len - mid)) } . } . . /// Divides one slice into an array and a remainder slice at an index. . /// . /// The array will contain all indices from `[0, N)` (excluding . /// the index `N` itself) and the slice will contain all . /// indices from `[N, len)` (excluding the index `len` itself). . /// -- line 1644 ---------------------------------------- -- line 2113 ---------------------------------------- . /// assert!(!v.iter().any(|e| e == "hi")); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . pub fn contains(&self, x: &T) -> bool . where . T: PartialEq, . { 360 ( 0.00%) cmp::SliceContains::slice_contains(x, self) . } . . /// Returns `true` if `needle` is a prefix of the slice. . /// . /// # Examples . /// . /// ``` . /// let v = [10, 40, 30]; -- line 2129 ---------------------------------------- -- line 2142 ---------------------------------------- . /// assert!(v.starts_with(&[])); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn starts_with(&self, needle: &[T]) -> bool . where . T: PartialEq, . { . let n = needle.len(); 1,331 ( 0.00%) self.len() >= n && needle == &self[..n] . } . . /// Returns `true` if `needle` is a suffix of the slice. . /// . /// # Examples . /// . /// ``` . /// let v = [10, 40, 30]; -- line 2158 ---------------------------------------- -- line 2171 ---------------------------------------- . /// assert!(v.ends_with(&[])); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn ends_with(&self, needle: &[T]) -> bool . where . T: PartialEq, . { . let (m, n) = (self.len(), needle.len()); 706 ( 0.00%) m >= n && needle == &self[m - n..] . } . . /// Returns a subslice with the prefix removed. . /// . /// If the slice starts with `prefix`, returns the subslice after the prefix, wrapped in `Some`. . /// If `prefix` is empty, simply returns the original slice. . /// . /// If the slice does not start with `prefix`, returns `None`. -- line 2187 ---------------------------------------- -- line 2293 ---------------------------------------- . /// s.insert(idx, num); . /// assert_eq!(s, [0, 1, 1, 1, 1, 2, 3, 5, 8, 13, 21, 34, 42, 55]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn binary_search(&self, x: &T) -> Result . where . T: Ord, . { 3 ( 0.00%) self.binary_search_by(|p| p.cmp(x)) . } . . /// Binary searches this sorted slice with a comparator function. . /// . /// The comparator function should implement an order consistent . /// with the sort order of the underlying slice, returning an . /// order code that indicates whether its argument is `Less`, . /// `Equal` or `Greater` the desired target. -- line 2309 ---------------------------------------- -- line 2345 ---------------------------------------- . #[inline] . pub fn binary_search_by<'a, F>(&'a self, mut f: F) -> Result . where . F: FnMut(&'a T) -> Ordering, . { . let mut size = self.len(); . let mut left = 0; . let mut right = size; 3,912,146 ( 0.18%) while left < right { 5,152,691 ( 0.24%) let mid = left + size / 2; . . // SAFETY: the call is made safe by the following invariants: . // - `mid >= 0` . // - `mid < size`: `mid` is limited by `[left; right)` bound. 907,134 ( 0.04%) let cmp = f(unsafe { self.get_unchecked(mid) }); . . // The reason why we use if/else control flow rather than match . // is because match reorders comparison operations, which is perf sensitive. . // This is x86 asm for u8: https://rust.godbolt.org/z/8Y8Pra. 1,315,575 ( 0.06%) if cmp == Less { 4,390,800 ( 0.21%) left = mid + 1; 396,794 ( 0.02%) } else if cmp == Greater { . right = mid; . } else { . // SAFETY: same as the `get_unchecked` above . unsafe { crate::intrinsics::assume(mid < self.len()) }; . return Ok(mid); . } . 3,861,773 ( 0.18%) size = right - left; . } . Err(left) . } . . /// Binary searches this sorted slice with a key extraction function. . /// . /// Assumes that the slice is sorted by the key, for instance with . /// [`sort_by_key`] using the same key extraction function. -- line 2382 ---------------------------------------- -- line 3203 ---------------------------------------- . #[track_caller] . fn len_mismatch_fail(dst_len: usize, src_len: usize) -> ! { . panic!( . "source slice length ({}) does not match destination slice length ({})", . src_len, dst_len, . ); . } . 23,100 ( 0.00%) if self.len() != src.len() { . len_mismatch_fail(self.len(), src.len()); . } . . // SAFETY: `self` is valid for `self.len()` elements by definition, and `src` was . // checked to have the same length. The slices cannot overlap because . // mutable references are exclusive. . unsafe { . ptr::copy_nonoverlapping(src.as_ptr(), self.as_mut_ptr(), self.len()); -- line 3219 ---------------------------------------- -- line 3382 ---------------------------------------- . } . let gcd: usize = gcd(mem::size_of::(), mem::size_of::()); . let ts: usize = mem::size_of::() / gcd; . let us: usize = mem::size_of::() / gcd; . . // Armed with this knowledge, we can find how many `U`s we can fit! . let us_len = self.len() / ts * us; . // And how many `T`s will be in the trailing slice! 906 ( 0.00%) let ts_len = self.len() % ts; . (us_len, ts_len) . } . . /// Transmute the slice to a slice of another type, ensuring alignment of the types is . /// maintained. . /// . /// This method splits the slice into three distinct slices: prefix, correctly aligned middle . /// slice of a new type, and the suffix slice. The method may make the middle slice the greatest -- line 3398 ---------------------------------------- -- line 3429 ---------------------------------------- . return (self, &[], &[]); . } . . // First, find at what point do we split between the first and 2nd slice. Easy with . // ptr.align_offset. . let ptr = self.as_ptr(); . // SAFETY: See the `align_to_mut` method for the detailed safety comment. . let offset = unsafe { crate::ptr::align_offset(ptr, mem::align_of::()) }; 906 ( 0.00%) if offset > self.len() { . (self, &[], &[]) . } else { . let (left, rest) = self.split_at(offset); . let (us_len, ts_len) = rest.align_to_offsets::(); . // SAFETY: now `rest` is definitely aligned, so `from_raw_parts` below is okay, . // since the caller guarantees that we can transmute `T` to `U` safely. . unsafe { . ( . left, . from_raw_parts(rest.as_ptr() as *const U, us_len), 906 ( 0.00%) from_raw_parts(rest.as_ptr().add(rest.len() - ts_len), ts_len), . ) . } . } . } . . /// Transmute the slice to a slice of another type, ensuring alignment of the types is . /// maintained. . /// -- line 3456 ---------------------------------------- 2,611,323 ( 0.12%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/mbe/macro_parser.rs -------------------------------------------------------------------------------- Ir -- line 90 ---------------------------------------- . use std::collections::hash_map::Entry::{Occupied, Vacant}; . use std::mem; . use std::ops::{Deref, DerefMut}; . . // To avoid costly uniqueness checks, we require that `MatchSeq` always has a nonempty body. . . /// Either a sequence of token trees or a single one. This is used as the representation of the . /// sequence of tokens that make up a matcher. 11,818 ( 0.00%) #[derive(Clone)] . enum TokenTreeOrTokenTreeSlice<'tt> { . Tt(TokenTree), 1,774 ( 0.00%) TtSeq(&'tt [TokenTree]), . } . . impl<'tt> TokenTreeOrTokenTreeSlice<'tt> { . /// Returns the number of constituent top-level token trees of `self` (top-level in that it . /// will not recursively descend into subtrees). . fn len(&self) -> usize { 174,236 ( 0.01%) match *self { 55,522 ( 0.00%) TtSeq(ref v) => v.len(), . Tt(ref tt) => tt.len(), . } . } . . /// The `index`-th token tree of `self`. . fn get_tt(&self, index: usize) -> TokenTree { 33,617 ( 0.00%) match *self { 146,976 ( 0.01%) TtSeq(ref v) => v[index].clone(), 20,202 ( 0.00%) Tt(ref tt) => tt.get_tt(index), . } . } . } . . /// An unzipping of `TokenTree`s... see the `stack` field of `MatcherPos`. . /// . /// This is used by `inner_parse_loop` to keep track of delimited submatchers that we have . /// descended into. 1,008 ( 0.00%) #[derive(Clone)] . struct MatcherTtFrame<'tt> { . /// The "parent" matcher that we are descending into. . elts: TokenTreeOrTokenTreeSlice<'tt>, . /// The position of the "dot" in `elts` at the time we descended. 504 ( 0.00%) idx: usize, . } . . type NamedMatchVec = SmallVec<[NamedMatch; 4]>; . . /// Represents a single "position" (aka "matcher position", aka "item"), as . /// described in the module documentation. . /// . /// Here: -- line 140 ---------------------------------------- -- line 147 ---------------------------------------- . /// position refers to. . /// . /// It is important to distinguish these two lifetimes because we have a . /// `SmallVec>` below, and the destructor of . /// that is considered to possibly access the data from its elements (it lacks . /// a `#[may_dangle]` attribute). As a result, the compiler needs to know that . /// all the elements in that `SmallVec` strictly outlive the root stack slot . /// lifetime. By separating `'tt` from `'root`, we can show that. 56,964 ( 0.00%) #[derive(Clone)] . struct MatcherPos<'root, 'tt> { . /// The token or sequence of tokens that make up the matcher . top_elts: TokenTreeOrTokenTreeSlice<'tt>, . . /// The position of the "dot" in this matcher 1,212 ( 0.00%) idx: usize, . . /// For each named metavar in the matcher, we keep track of token trees matched against the . /// metavar by the black box parser. In particular, there may be more than one match per . /// metavar if we are in a repetition (each repetition matches each of the variables). . /// Moreover, matchers and repetitions can be nested; the `matches` field is shared (hence the . /// `Rc`) among all "nested" matchers. `match_lo`, `match_cur`, and `match_hi` keep track of . /// the current position of the `self` matcher position in the shared `matches` list. . /// . /// Also, note that while we are descending into a sequence, matchers are given their own . /// `matches` vector. Only once we reach the end of a full repetition of the sequence do we add . /// all bound matches from the submatcher into the shared top-level `matches` vector. If `sep` . /// and `up` are `Some`, then `matches` is _not_ the shared top-level list. Instead, if one . /// wants the shared `matches`, one should use `up.matches`. 4,848 ( 0.00%) matches: Box<[Lrc]>, . /// The position in `matches` corresponding to the first metavar in this matcher's sequence of . /// token trees. In other words, the first metavar in the first token of `top_elts` corresponds . /// to `matches[match_lo]`. 1,212 ( 0.00%) match_lo: usize, . /// The position in `matches` corresponding to the metavar we are currently trying to match . /// against the source token stream. `match_lo <= match_cur <= match_hi`. . match_cur: usize, . /// Similar to `match_lo` except `match_hi` is the position in `matches` of the _last_ metavar . /// in this matcher. 1,212 ( 0.00%) match_hi: usize, . . // The following fields are used if we are matching a repetition. If we aren't, they should be . // `None`. . /// The KleeneOp of this sequence if we are in a repetition. 1,212 ( 0.00%) seq_op: Option, . . /// The separator if we are in a repetition. . sep: Option, . . /// The "parent" matcher position if we are in a repetition. That is, the matcher position just . /// before we enter the sequence. 2,424 ( 0.00%) up: Option>, . . /// Specifically used to "unzip" token trees. By "unzip", we mean to unwrap the delimiters from . /// a delimited token tree (e.g., something wrapped in `(` `)`) or to get the contents of a doc . /// comment... . /// . /// When matching against matchers with nested delimited submatchers (e.g., `pat ( pat ( .. ) . /// pat ) pat`), we need to keep track of the matchers we are descending into. This stack does . /// that where the bottom of the stack is the outermost matcher. . /// Also, throughout the comments, this "descent" is often referred to as "unzipping"... . stack: SmallVec<[MatcherTtFrame<'tt>; 1]>, . } . . impl<'root, 'tt> MatcherPos<'root, 'tt> { . /// Adds `m` as a named match for the `idx`-th metavar. . fn push_match(&mut self, idx: usize, m: NamedMatch) { 62,944 ( 0.00%) let matches = Lrc::make_mut(&mut self.matches[idx]); . matches.push(m); . } . } . . // Lots of MatcherPos instances are created at runtime. Allocating them on the . // heap is slow. Furthermore, using SmallVec to allocate them all . // on the stack is also slow, because MatcherPos is quite a large type and . // instances get moved around a lot between vectors, which requires lots of -- line 221 ---------------------------------------- -- line 226 ---------------------------------------- . // and this type is used to encapsulate both cases. . enum MatcherPosHandle<'root, 'tt> { . Ref(&'root mut MatcherPos<'root, 'tt>), . Box(Box>), . } . . impl<'root, 'tt> Clone for MatcherPosHandle<'root, 'tt> { . // This always produces a new Box. 4,848 ( 0.00%) fn clone(&self) -> Self { 2,424 ( 0.00%) MatcherPosHandle::Box(match *self { 543 ( 0.00%) MatcherPosHandle::Ref(ref r) => Box::new((**r).clone()), . MatcherPosHandle::Box(ref b) => b.clone(), . }) 7,272 ( 0.00%) } . } . . impl<'root, 'tt> Deref for MatcherPosHandle<'root, 'tt> { . type Target = MatcherPos<'root, 'tt>; . fn deref(&self) -> &Self::Target { . match *self { . MatcherPosHandle::Ref(ref r) => r, . MatcherPosHandle::Box(ref b) => b, -- line 247 ---------------------------------------- -- line 272 ---------------------------------------- . . /// A `ParseResult` where the `Success` variant contains a mapping of . /// `MacroRulesNormalizedIdent`s to `NamedMatch`es. This represents the mapping . /// of metavars to the token trees they bind to. . crate type NamedParseResult = ParseResult>; . . /// Count how many metavars are named in the given matcher `ms`. . pub(super) fn count_names(ms: &[TokenTree]) -> usize { 113,288 ( 0.01%) ms.iter().fold(0, |count, elt| { 56,644 ( 0.00%) count 169,932 ( 0.01%) + match *elt { 200 ( 0.00%) TokenTree::Sequence(_, ref seq) => seq.num_captures, 59 ( 0.00%) TokenTree::Delimited(_, ref delim) => count_names(&delim.tts), . TokenTree::MetaVar(..) => 0, . TokenTree::MetaVarDecl(..) => 1, . TokenTree::Token(..) => 0, . } 141,610 ( 0.01%) }) . } . . /// `len` `Vec`s (initially shared and empty) that will store matches of metavars. . fn create_matches(len: usize) -> Box<[Lrc]> { 27,728 ( 0.00%) if len == 0 { . vec![] . } else { . let empty_matches = Lrc::new(SmallVec::new()); . vec![empty_matches; len] . } . .into_boxed_slice() . } . . /// Generates the top-level matcher position in which the "dot" is before the first token of the . /// matcher `ms`. . fn initial_matcher_pos<'root, 'tt>(ms: &'tt [TokenTree]) -> MatcherPos<'root, 'tt> { . let match_idx_hi = count_names(ms); . let matches = create_matches(match_idx_hi); 137,400 ( 0.01%) MatcherPos { . // Start with the top level matcher given to us . top_elts: TtSeq(ms), // "elts" is an abbr. for "elements" . // The "dot" is before the first token of the matcher . idx: 0, . . // Initialize `matches` to a bunch of empty `Vec`s -- one for each metavar in `top_elts`. . // `match_lo` for `top_elts` is 0 and `match_hi` is `matches.len()`. `match_cur` is 0 since . // we haven't actually matched anything yet. -- line 316 ---------------------------------------- -- line 340 ---------------------------------------- . /// particular token tree. . /// . /// The width of each `MatchedSeq` in the `NamedMatch`, and the identity of . /// the `MatchedNonterminal`s, will depend on the token tree it was applied . /// to: each `MatchedSeq` corresponds to a single `TTSeq` in the originating . /// token tree. The depth of the `NamedMatch` structure will therefore depend . /// only on the nesting depth of `ast::TTSeq`s in the originating . /// token tree it was derived from. 7,782 ( 0.00%) #[derive(Debug, Clone)] . crate enum NamedMatch { . MatchedSeq(Lrc), . MatchedNonterminal(Lrc), . } . . /// Takes a sequence of token trees `ms` representing a matcher which successfully matched input . /// and an iterator of items that matched input and produces a `NamedParseResult`. . fn nameize>( -- line 356 ---------------------------------------- -- line 357 ---------------------------------------- . sess: &ParseSess, . ms: &[TokenTree], . mut res: I, . ) -> NamedParseResult { . // Recursively descend into each type of matcher (e.g., sequences, delimited, metavars) and make . // sure that each metavar has _exactly one_ binding. If a metavar does not have exactly one . // binding, then there is an error. If it does, then we insert the binding into the . // `NamedParseResult`. 153,978 ( 0.01%) fn n_rec>( . sess: &ParseSess, . m: &TokenTree, . res: &mut I, . ret_val: &mut FxHashMap, . ) -> Result<(), (rustc_span::Span, String)> { 88,396 ( 0.00%) match *m { . TokenTree::Sequence(_, ref seq) => { 44 ( 0.00%) for next_m in &seq.tts { 582 ( 0.00%) n_rec(sess, next_m, res.by_ref(), ret_val)? . } . } . TokenTree::Delimited(_, ref delim) => { 18 ( 0.00%) for next_m in &delim.tts { 522 ( 0.00%) n_rec(sess, next_m, res.by_ref(), ret_val)?; . } . } . TokenTree::MetaVarDecl(span, _, None) => { . if sess.missing_fragment_specifiers.borrow_mut().remove(&span).is_some() { . return Err((span, "missing fragment specifier".to_string())); . } . } 55,218 ( 0.00%) TokenTree::MetaVarDecl(sp, bind_name, _) => match ret_val 36,812 ( 0.00%) .entry(MacroRulesNormalizedIdent::new(bind_name)) . { . Vacant(spot) => { . spot.insert(res.next().unwrap()); . } . Occupied(..) => return Err((sp, format!("duplicated bind name: {}", bind_name))), . }, . TokenTree::MetaVar(..) | TokenTree::Token(..) => (), . } . 13,998 ( 0.00%) Ok(()) 111,984 ( 0.01%) } . . let mut ret_val = FxHashMap::default(); . for m in ms { 133,407 ( 0.01%) match n_rec(sess, m, res.by_ref(), &mut ret_val) { . Ok(_) => {} . Err((sp, msg)) => return Error(sp, msg), . } . } . 41,211 ( 0.00%) Success(ret_val) . } . . /// Performs a token equality check, ignoring syntax context (that is, an unhygienic comparison) . fn token_name_eq(t1: &Token, t2: &Token) -> bool { 60,330 ( 0.00%) if let (Some((ident1, is_raw1)), Some((ident2, is_raw2))) = (t1.ident(), t2.ident()) { 756 ( 0.00%) ident1.name == ident2.name && is_raw1 == is_raw2 80,262 ( 0.00%) } else if let (Some(ident1), Some(ident2)) = (t1.lifetime(), t2.lifetime()) { . ident1.name == ident2.name . } else { 34,378 ( 0.00%) t1.kind == t2.kind . } . } . . /// Process the matcher positions of `cur_items` until it is empty. In the process, this will . /// produce more items in `next_items`, `eof_items`, and `bb_items`. . /// . /// For more info about the how this happens, see the module-level doc comments and the inline . /// comments of this function. -- line 427 ---------------------------------------- -- line 443 ---------------------------------------- . sess: &ParseSess, . cur_items: &mut SmallVec<[MatcherPosHandle<'root, 'tt>; 1]>, . next_items: &mut Vec>, . eof_items: &mut SmallVec<[MatcherPosHandle<'root, 'tt>; 1]>, . bb_items: &mut SmallVec<[MatcherPosHandle<'root, 'tt>; 1]>, . token: &Token, . ) -> ParseResult<()> { . // Pop items from `cur_items` until it is empty. 131,080 ( 0.01%) while let Some(mut item) = cur_items.pop() { . // When unzipped trees end, remove them. This corresponds to backtracking out of a . // delimited submatcher into which we already descended. In backtracking out again, we need . // to advance the "dot" past the delimiters in the outer matcher. 398,611 ( 0.02%) while item.idx >= item.top_elts.len() { 1,030 ( 0.00%) match item.stack.pop() { . Some(MatcherTtFrame { elts, idx }) => { 4,635 ( 0.00%) item.top_elts = elts; 2,060 ( 0.00%) item.idx = idx + 1; . } . None => break, . } . } . . // Get the current position of the "dot" (`idx`) in `item` and the number of token trees in . // the matcher (`len`). . let idx = item.idx; . let len = item.top_elts.len(); . . // If `idx >= len`, then we are at or past the end of the matcher of `item`. 89,260 ( 0.00%) if idx >= len { . // We are repeating iff there is a parent. If the matcher is inside of a repetition, . // then we could be at the end of a sequence or at the beginning of the next . // repetition. 5,377 ( 0.00%) if item.up.is_some() { . // At this point, regardless of whether there is a separator, we should add all . // matches from the complete repetition of the sequence to the shared, top-level . // `matches` list (actually, `up.matches`, which could itself not be the top-level, . // but anyway...). Moreover, we add another item to `cur_items` in which the "dot" . // is at the end of the `up` matcher. This ensures that the "dot" in the `up` . // matcher is also advanced sufficiently. . // . // NOTE: removing the condition `idx == len` allows trailing separators. 1,336 ( 0.00%) if idx == len { . // Get the `up` matcher . let mut new_pos = item.up.clone().unwrap(); . . // Add matches from this repetition to the `matches` of `up` 1,310 ( 0.00%) for idx in item.match_lo..item.match_hi { 4,960 ( 0.00%) let sub = item.matches[idx].clone(); 2,976 ( 0.00%) new_pos.push_match(idx, MatchedSeq(sub)); . } . . // Move the "dot" past the repetition in `up` 1,297 ( 0.00%) new_pos.match_cur = item.match_hi; 3,930 ( 0.00%) new_pos.idx += 1; . cur_items.push(new_pos); . } . . // Check if we need a separator. 655 ( 0.00%) if idx == len && item.sep.is_some() { . // We have a separator, and it is the current token. We can advance past the . // separator token. 40 ( 0.00%) if item.sep.as_ref().map_or(false, |sep| token_name_eq(token, sep)) { 91 ( 0.00%) item.idx += 1; . next_items.push(item); . } . } . // We don't need a separator. Move the "dot" back to the beginning of the matcher . // and try to match again UNLESS we are only allowed to have _one_ repetition. 648 ( 0.00%) else if item.seq_op != Some(mbe::KleeneOp::ZeroOrOne) { 1,296 ( 0.00%) item.match_cur = item.match_lo; 2,592 ( 0.00%) item.idx = 0; . cur_items.push(item); . } . } . // If we are not in a repetition, then being at the end of a matcher means that we have . // reached the potential end of the input. . else { . eof_items.push(item); . } . } . // We are in the middle of a matcher. . else { . // Look at what token in the matcher we are trying to match the current token (`token`) . // against. Depending on that, we may generate new items. 89,582 ( 0.00%) match item.top_elts.get_tt(idx) { . // Need to descend into a sequence 557 ( 0.00%) TokenTree::Sequence(sp, seq) => { . // Examine the case where there are 0 matches of this sequence. We are . // implicitly disallowing OneOrMore from having 0 matches here. Thus, that will . // result in a "no rules expected token" error by virtue of this matcher not . // working. 248 ( 0.00%) if seq.kleene.op == mbe::KleeneOp::ZeroOrMore . || seq.kleene.op == mbe::KleeneOp::ZeroOrOne . { 222 ( 0.00%) let mut new_item = item.clone(); 444 ( 0.00%) new_item.match_cur += seq.num_captures; 555 ( 0.00%) new_item.idx += 1; 666 ( 0.00%) for idx in item.match_cur..item.match_cur + seq.num_captures { 318 ( 0.00%) new_item.push_match(idx, MatchedSeq(Lrc::new(smallvec![]))); . } . cur_items.push(new_item); . } . 124 ( 0.00%) let matches = create_matches(item.matches.len()); 1,488 ( 0.00%) cur_items.push(MatcherPosHandle::Box(Box::new(MatcherPos { 124 ( 0.00%) stack: smallvec![], . sep: seq.separator.clone(), 124 ( 0.00%) seq_op: Some(seq.kleene.op), . idx: 0, 620 ( 0.00%) matches, 248 ( 0.00%) match_lo: item.match_cur, . match_cur: item.match_cur, 248 ( 0.00%) match_hi: item.match_cur + seq.num_captures, . up: Some(item), 868 ( 0.00%) top_elts: Tt(TokenTree::Sequence(sp, seq)), . }))); . } . . // We need to match a metavar (but the identifier is invalid)... this is an error . TokenTree::MetaVarDecl(span, _, None) => { . if sess.missing_fragment_specifiers.borrow_mut().remove(&span).is_some() { . return Error(span, "missing fragment specifier".to_string()); . } -- line 565 ---------------------------------------- -- line 568 ---------------------------------------- . // We need to match a metavar with a valid ident... call out to the black-box . // parser by adding an item to `bb_items`. . TokenTree::MetaVarDecl(_, _, Some(kind)) => { . // Built-in nonterminals never start with these tokens, so we can eliminate . // them from consideration. . // . // We use the span of the metavariable declaration to determine any . // edition-specific matching behavior for non-terminals. 75,190 ( 0.00%) if Parser::nonterminal_may_begin_with(kind, token) { . bb_items.push(item); . } . } . . // We need to descend into a delimited submatcher or a doc comment. To do this, we . // push the current matcher onto a stack and push a new item containing the . // submatcher onto `cur_items`. . // . // At the beginning of the loop, if we reach the end of the delimited submatcher, . // we pop the stack to backtrack out of the descent. 2,575 ( 0.00%) seq @ (TokenTree::Delimited(..) . | TokenTree::Token(Token { kind: DocComment(..), .. })) => { . let lower_elts = mem::replace(&mut item.top_elts, Tt(seq)); 515 ( 0.00%) let idx = item.idx; 3,605 ( 0.00%) item.stack.push(MatcherTtFrame { elts: lower_elts, idx }); 2,060 ( 0.00%) item.idx = 0; . cur_items.push(item); . } . . // We just matched a normal token. We can just advance the parser. 57,422 ( 0.00%) TokenTree::Token(t) if token_name_eq(&t, token) => { 48,342 ( 0.00%) item.idx += 1; . next_items.push(item); . } . . // There was another token that was not `token`... This means we can't add any . // rules. NOTE that this is not necessarily an error unless _all_ items in . // `cur_items` end up doing this. There may still be some other matchers that do . // end up working out. . TokenTree::Token(..) | TokenTree::MetaVar(..) => {} . } 146,106 ( 0.01%) } 53,756 ( 0.00%) } . . // Yay a successful parse (so far)! . Success(()) . } . . /// Use the given sequence of token trees (`ms`) as a matcher. Match the token . /// stream from the given `parser` against it and return the match. 91,600 ( 0.00%) pub(super) fn parse_tt( . parser: &mut Cow<'_, Parser<'_>>, . ms: &[TokenTree], . macro_name: Ident, . ) -> NamedParseResult { . // A queue of possible matcher positions. We initialize it with the matcher position in which . // the "dot" is before the first token of the first token tree in `ms`. `inner_parse_loop` then . // processes all of these possible matcher positions and produces possible next positions into . // `next_items`. After some post-processing, the contents of `next_items` replenish `cur_items` . // and we start over again. . // . // This MatcherPos instance is allocated on the stack. All others -- and . // there are frequently *no* others! -- are allocated on the heap. . let mut initial = initial_matcher_pos(ms); 45,800 ( 0.00%) let mut cur_items = smallvec![MatcherPosHandle::Ref(&mut initial)]; . let mut next_items = Vec::new(); . . loop { . // Matcher positions black-box parsed by parser.rs (`parser`) . let mut bb_items = SmallVec::new(); . . // Matcher positions that would be valid if the macro invocation was over now . let mut eof_items = SmallVec::new(); 30,704 ( 0.00%) assert!(next_items.is_empty()); . . // Process `cur_items` until either we have finished the input or we need to get some . // parsing from the black-box parser done. The result is that `next_items` will contain a . // bunch of possible next matcher positions in `next_items`. . match inner_parse_loop( . parser.sess, . &mut cur_items, . &mut next_items, -- line 648 ---------------------------------------- -- line 652 ---------------------------------------- . ) { . Success(_) => {} . Failure(token, msg) => return Failure(token, msg), . Error(sp, msg) => return Error(sp, msg), . ErrorReported => return ErrorReported, . } . . // inner parse loop handled all cur_items, so it's empty 30,704 ( 0.00%) assert!(cur_items.is_empty()); . . // We need to do some post processing after the `inner_parser_loop`. . // . // Error messages here could be improved with links to original rules. . . // If we reached the EOF, check that there is EXACTLY ONE possible matcher. Otherwise, . // either the parse is ambiguous (which should never happen) or there is a syntax error. 153,520 ( 0.01%) if parser.token == token::Eof { 18,316 ( 0.00%) if eof_items.len() == 1 { . let matches = 18,361 ( 0.00%) eof_items[0].matches.iter_mut().map(|dv| Lrc::make_mut(dv).pop().unwrap()); 13,737 ( 0.00%) return nameize(parser.sess, ms, matches); . } else if eof_items.len() > 1 { . return Error( . parser.token.span, . "ambiguity: multiple successful parses".to_string(), . ); . } else { . return Failure( . Token::new( -- line 680 ---------------------------------------- -- line 687 ---------------------------------------- . ), . "missing tokens in macro arguments", . ); . } . } . // Performance hack: eof_items may share matchers via Rc with other things that we want . // to modify. Dropping eof_items now may drop these refcounts to 1, preventing an . // unnecessary implicit clone later in Rc::make_mut. 104,500 ( 0.00%) drop(eof_items); . . // If there are no possible next positions AND we aren't waiting for the black-box parser, . // then there is a syntax error. 89,862 ( 0.00%) if bb_items.is_empty() && next_items.is_empty() { 59,553 ( 0.00%) return Failure(parser.token.clone(), "no rules expected this token in macro call"); . } . // Another possibility is that we need to call out to parse some rust nonterminal . // (black-box) parser. However, if there is not EXACTLY ONE of these, something is wrong. 58,552 ( 0.00%) else if (!bb_items.is_empty() && !next_items.is_empty()) || bb_items.len() > 1 { . let nts = bb_items . .iter() . .map(|item| match item.top_elts.get_tt(item.idx) { . TokenTree::MetaVarDecl(_, bind, Some(kind)) => format!("{} ('{}')", kind, bind), . _ => panic!(), . }) . .collect::>() . .join(" or "); -- line 712 ---------------------------------------- -- line 721 ---------------------------------------- . n => format!("built-in NTs {} or {} other options.", nts, n), . } . ), . ); . } . // Dump all possible `next_items` into `cur_items` for the next iteration. . else if !next_items.is_empty() { . // Now process the next token 20,718 ( 0.00%) cur_items.extend(next_items.drain(..)); 6,906 ( 0.00%) parser.to_mut().bump(); . } . // Finally, we have the case where we need to call the black-box parser to get some . // nonterminal. . else { . assert_eq!(bb_items.len(), 1); . 29,276 ( 0.00%) let mut item = bb_items.pop().unwrap(); 76,028 ( 0.00%) if let TokenTree::MetaVarDecl(span, _, Some(kind)) = item.top_elts.get_tt(item.idx) { 14,638 ( 0.00%) let match_cur = item.match_cur; . // We use the span of the metavariable declaration to determine any . // edition-specific matching behavior for non-terminals. 96,949 ( 0.00%) let nt = match parser.to_mut().parse_nonterminal(kind) { . Err(mut err) => { . err.span_label( . span, . format!("while parsing argument for this `{}` macro fragment", kind), . ) . .emit(); . return ErrorReported; . } 87,828 ( 0.00%) Ok(nt) => nt, . }; 58,552 ( 0.00%) item.push_match(match_cur, MatchedNonterminal(Lrc::new(nt))); 58,552 ( 0.00%) item.idx += 1; 87,828 ( 0.00%) item.match_cur += 1; . } else { . unreachable!() . } . cur_items.push(item); . } . 43,088 ( 0.00%) assert!(!cur_items.is_empty()); . } 82,440 ( 0.00%) } 674,773 ( 0.03%) -------------------------------------------------------------------------------- The following files chosen for auto-annotation could not be found: -------------------------------------------------------------------------------- ./elf/../sysdeps/x86_64/dl-machine.h ./elf/dl-lookup.c ./elf/do-rel.h ./malloc/malloc.c ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S -------------------------------------------------------------------------------- Ir -------------------------------------------------------------------------------- 919,593,574 (43.28%) events annotated